Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / context_parallel / ring_transport.py: 19%
128 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Bounded Ring transport with document-limited routes and explicit stream ownership."""
17from __future__ import annotations
19from functools import lru_cache
20from math import gcd
21from typing import Any
23# Native Torch is required; the legacy lint rule predates the Torch-only migration.
24import torch # pylint: disable=forbidden-backend-import
25import torch.distributed as dist # pylint: disable=forbidden-backend-import
28@lru_cache(maxsize=16)
29def _communication_stream(device, gradient):
30 """Return a cached communication stream keyed separately for KV and dKV."""
31 del gradient # The argument distinguishes forward and gradient stream cache entries.
32 return torch.npu.Stream(device=device)
35class _Packet:
36 """Protect a receive slot until its producer, readers and outstanding send finish."""
38 def __init__(self, storage: torch.Tensor, owner: int, heads: int, dimension: int,
39 counts: tuple[int, ...]) -> None:
40 """Bind a flat transport allocation to an owner and its active shape."""
41 self.storage = storage
42 self.owner = owner
43 self.heads = heads
44 self.dimension = dimension
45 self.counts = counts
46 self.receive = None
47 self.send = None
48 self.consumed = None
49 self.produced = None
50 self.producer_stream = None
51 self._views = {}
52 self._recorded_streams = set()
54 def ready(self) -> None:
55 """Wait for the latest producer, which already includes any preceding receive."""
56 if self.produced is not None:
57 stream = torch.npu.current_stream()
58 if stream != self.producer_stream:
59 self.produced.wait(stream)
60 elif self.receive is not None:
61 self.receive.wait()
63 def _active_views(self):
64 count = self.counts[self.owner]
65 if count not in self._views:
66 width = count * self.heads * self.dimension
67 payload = self.storage[:2 * width]
68 self._views[count] = (payload, payload[:width].view(count, self.heads, self.dimension),
69 payload[width:].view(count, self.heads, self.dimension))
70 return self._views[count]
72 def payload(self) -> torch.Tensor:
73 """Reuse the active flat send/receive view for this owner size."""
74 return self._active_views()[0]
76 def tensors(self) -> tuple[torch.Tensor, torch.Tensor]:
77 """Reuse K/V views without reconstructing slices at every consumer."""
78 return self._active_views()[1:]
80 def record_stream(self, stream: Any) -> None:
81 """Register each allocator stream once for this storage's lifetime.
83 Args:
84 stream: Device stream that may retain access to this storage.
85 """
86 if stream not in self._recorded_streams:
87 self.storage.record_stream(stream)
88 self._recorded_streams.add(stream)
90 def consumed_now(self) -> None:
91 """Protect every read already enqueued on the current compute stream."""
92 self.consumed = torch.npu.Event()
93 self.consumed.record()
95 def produced_now(self) -> None:
96 """One event covers both gradient production and the final accumulation read."""
97 self.producer_stream = torch.npu.current_stream()
98 self.produced = torch.npu.Event()
99 self.produced.record(self.producer_stream)
100 self.consumed = self.produced
103class _PackedRingExchange:
104 """Double-buffer neighbor traffic, stopping each owner at its last consumer."""
106 def __init__(self, initial: torch.Tensor, plan: Any, ring: Any, stream: Any) -> None:
107 """Allocate bounded receive slots and order their first write after allocation."""
108 self.ring, self.stream, self.plan = ring, stream, plan
109 heads, dimension = initial.shape[1:]
110 self.buffers = tuple(_Packet(initial.new_empty(2 * plan.capacity * heads * dimension),
111 ring.rank, heads, dimension, plan.counts) for _ in range(2))
112 self.slot = 0
113 for packet in self.buffers:
114 packet.record_stream(stream)
115 stream.wait_stream(torch.npu.current_stream())
117 def launch(self, source: _Packet, step: int) -> _Packet:
118 """Post the matching subset of neighbor sends and receives for this round.
120 Args:
121 source: Current owner packet whose data may be forwarded.
122 step: Zero-based Ring hop used to enforce route horizons.
123 """
124 target = self.buffers[self.slot]
125 self.slot = 1 - self.slot
126 with torch.npu.stream(self.stream):
127 if target.send is not None:
128 target.send.wait()
129 if target.consumed is not None:
130 target.consumed.wait()
131 target.owner = (source.owner - 1) % self.ring.size
132 target.produced, target.producer_stream, target.consumed, target.send = None, None, None, None
133 target.receive = None
134 send = self.plan.counts[source.owner] and step < self.plan.hops[source.owner]
135 receive = self.plan.counts[target.owner] and step < self.plan.hops[target.owner]
136 requests = (("send", send), ("recv", receive))
137 for kind, active in requests if self.ring.rank % 2 == 0 else reversed(requests):
138 if not active:
139 continue
140 if kind == "send":
141 source.ready()
142 source.record_stream(self.stream)
143 source.send = dist.isend(source.payload(), self.ring.next_rank, group=self.ring.group)
144 else:
145 target.receive = dist.irecv(target.payload(), self.ring.previous_rank, group=self.ring.group)
146 return target
148 def finish(self, initial: _Packet) -> None:
149 """Join outstanding transport before local storage references are released.
151 Args:
152 initial: Original locally produced packet to join with the receive slots.
153 """
154 for packet in (initial, *self.buffers):
155 packet.ready()
156 if packet.send is not None:
157 packet.send.wait()
158 torch.npu.current_stream().wait_stream(self.stream)
161def _receive_first(rank, size, distance):
162 # Alternate within each shifted cycle, including non-coprime return distances.
163 divisor = gcd(size, distance)
164 cycle = size // divisor
165 position = (rank // divisor * pow(distance // divisor, -1, cycle)) % cycle
166 return position % 2 != 0
169def _return_ring_gradient(source, initial, plan, ring, stream, step):
170 """Send the final dKV contribution directly back to its original owner."""
171 if not step:
172 return
173 send = plan.counts[source.owner] and step == plan.hops[source.owner]
174 receive = plan.counts[ring.rank] and step == plan.hops[ring.rank]
175 if not send and not receive:
176 return
177 requests = (("send", send), ("recv", receive))
178 with torch.npu.stream(stream):
179 for kind, active in reversed(requests) if _receive_first(ring.rank, ring.size, step) else requests:
180 if not active:
181 continue
182 if kind == "send":
183 source.ready()
184 source.record_stream(stream)
185 peer = dist.get_global_rank(ring.group, source.owner)
186 source.send = dist.isend(source.payload(), peer, group=ring.group)
187 else:
188 # The owner reuses its initial send allocation only after that send completes.
189 initial.send.wait()
190 initial.produced, initial.producer_stream = None, None
191 peer = dist.get_global_rank(ring.group, (ring.rank + step) % ring.size)
192 initial.receive = dist.irecv(initial.payload(), peer, group=ring.group)
195def _pack_ring_kv(tensors, spans, ring, counts, out=None):
196 pieces = [tensor[start:end] for tensor in tensors for start, end in spans[ring.rank]]
197 if out is None:
198 storage = torch.cat(pieces, dim=0).reshape(-1) if pieces else tensors[0].new_empty(0)
199 out = _Packet(storage, ring.rank, tensors[0].shape[1], tensors[0].shape[-1], counts)
200 elif pieces:
201 target = out.payload().view(-1, out.heads, out.dimension)
202 torch.cat(pieces, dim=0, out=target)
203 out.produced_now()
204 return out