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"""Shared state exchange for the Ascend C KDA and GDN drivers.
16
17Local preparation and backward math stay in the algorithm-specific drivers.
18This module owns document-bounded state traffic and invocation-local buffer
19lifetimes for the native FP32 128-by-128 map format. AllGather metadata is also
20reused by the Triton KDA protocol without importing either kernel backend.
21"""
22from __future__ import annotations
23from bisect import bisect_left
24from collections import deque
25from typing import Any
26
27import torch
28import torch.distributed as dist
29
30from hyper_parallel.core.activation_memory.recompute_state import get_recompute_state
31
32
33_ENTRY_CACHE_KEY = object()
34_NATIVE_MERGE_MAX_HEADS = 256
35
36
37class _CPEntryCache:
38 """Store actual entries in checkpoint-call order, independently of autograd saves."""
39
40 def __init__(self) -> None:
41 self.entries = deque()
42
43 def save(self, signature: tuple, entry: torch.Tensor | None) -> None:
44 """Own a snapshot rather than a view of a receive or packed-state buffer."""
45 self.entries.append((signature, None if entry is None else entry.detach().clone()))
46
47 def pop(self, signature: tuple) -> torch.Tensor | None:
48 """Reject missing or reordered replay before issuing any state communication."""
49 if not self.entries:
50 raise RuntimeError(
51 "CP entry cache is missing for checkpoint replay; repeated replay after "
52 "resource cleanup is unsupported.")
53 expected, entry = self.entries.popleft()
54 if expected != signature:
55 raise RuntimeError("CP checkpoint replay changed the layer, state group, shape, or document layout.")
56 return entry
57
58 def clear(self) -> None:
59 """Release consumed and unused entries on replay exit or an exception."""
60 self.entries.clear()
61
62
63def _apply_state(state, transition, initial):
64 """Keep the established FP32 matmul/add order outside model autocast."""
65 if initial is None:
66 return state
67 with torch.autocast(device_type=state.device.type, enabled=False):
68 return torch.matmul(transition.float(), initial.float()) + state
69
70
71class NativeStateAllGather:
72 """Precreated communication metadata; gathered maps belong to each invocation."""
73
74 def __init__(self, group: Any, rank: int, size: int) -> None:
75 """Borrow one precreated group; do not retain gathered tensors."""
76 if not isinstance(size, int) or isinstance(size, bool) or size < 1 or not 0 <= rank < size:
77 raise ValueError("AllGather requires a positive size and valid local rank.")
78 self.group, self.rank, self.size = group, rank, size
79
80 def gather_packed(self, packed: torch.Tensor) -> torch.Tensor:
81 """Gather [B,H,128,256] maps while preserving the independent sample axis."""
82 output = packed.new_empty((self.size * packed.shape[0], *packed.shape[1:]))
83 dist.all_gather_into_tensor(output, packed, group=self.group)
84 return output.reshape(self.size, *packed.shape)
85
86
87def native_state_intervals(info: Any, tokens: int, rank: int, size: int) -> tuple:
88 """Return tail/head windows and document-bounded exclusive scan lengths."""
89 if info is None:
90 return (0, tokens), (0, tokens), rank, size - rank - 1
91 first_rank = (info.start - info.preceding_sample_tokens) // tokens
92 last_rank = (info.global_offsets[bisect_left(info.global_offsets, info.end)] - 1) // tokens
93 return ((info.tail.start, info.tail.stop), (info.head.start, info.head.stop),
94 rank - first_rank if info.continues_previous else 0,
95 last_rank - rank if info.continues_next else 0)
96
97
98class NativeStateSends:
99 """Drain every packet while the caller retains the corresponding payloads."""
100
101 def __init__(self, handles: list[Any]) -> None:
102 """Own all outstanding handles for one communication direction."""
103 self.handles = handles
104
105 def wait(self) -> None:
106 """Finish all sends before releasing this invocation's payload storage."""
107 for handle in self.handles:
108 handle.wait()
109
110
111class NativeStateExchange:
112 """Bind one invocation's sequence plan to precreated communication groups.
113
114 Only metadata survives forward. Receive buffers and send handles are owned
115 by the active direction and drained before that invocation returns.
116 """
117
118 def __init__(self, mesh: Any, executor: Any, info: Any, local_length: int, heads: int,
119 p2p_head_chunks: int = 1, *, reuse_cp_state_on_recompute: bool = False,
120 cache_key: object = None, algorithm: str = "", batch_size: int = 1) -> None:
121 """Copy communication metadata and retain only this call's sequence plan."""
122 self.executor, self.info, self.heads = executor, info, heads
123 self.batch_size = batch_size
124 self.reuse_cp_state_on_recompute = reuse_cp_state_on_recompute
125 self.cache_key, self.algorithm, self.local_length = cache_key, algorithm, local_length
126 self._entry_cache = self._cache_signature = self._replay_entry = None
127 self.rank = mesh.get_local_rank()
128 self.size = mesh.size()
129 self.ranks = tuple(mesh.rank_list)
130 self.group = mesh.get_group()
131 self.width = getattr(executor, "width", self.size) if executor is not None else 1
132 self.block, self.local = divmod(self.rank, self.width)
133 self.owner = self.block * self.width + self.width - 1
134 self.is_rd = getattr(executor, "protocol", None) == "recursive_doubling"
135 if (isinstance(p2p_head_chunks, bool) or not isinstance(p2p_head_chunks, int)
136 or not 1 <= p2p_head_chunks <= heads):
137 raise ValueError("p2p_head_chunks must be a positive integer no larger than local heads.")
138 if p2p_head_chunks > 1 and (self.width != 1 or self.is_rd):
139 raise ValueError("p2p_head_chunks applies only to ordinary state P2P.")
140 self.head_ranges = tuple((index * heads // p2p_head_chunks, (index + 1) * heads // p2p_head_chunks)
141 for index in range(p2p_head_chunks))
142 self.sparse = None
143 if getattr(executor, "protocol", None) == "alltoallv" and info is not None:
144 self.sparse = executor.bind_sequence(info, state_shape=(batch_size, heads, 128, 128))
145 if reuse_cp_state_on_recompute and (self.is_rd or self.sparse is not None or self.width not in (1, self.size)):
146 raise NotImplementedError("Checkpoint entry caching currently supports native P2P and AllGather.")
147 self.plans = (tuple(executor.directional_plan(info, local_length, reverse=reverse) for reverse in (False, True))
148 if self.is_rd else ())
149
150 def peer(self, forward: bool, receiving: bool) -> int | None:
151 """Return a chronological peer, pruning disconnected ordinary P2P edges.
152
153 Args:
154 forward: Whether to use forward state traffic rather than backward gradient traffic.
155 receiving: Whether to select the incoming peer rather than the outgoing peer.
156 """
157 direction = 1 if forward else -1
158 peer = self.owner + (-direction if receiving else direction) * self.width
159 if not 0 <= peer < self.size:
160 return None
161 if self.width == 1 and self.info is not None:
162 needs_previous = forward == receiving
163 connected = self.info.continues_previous if needs_previous else self.info.continues_next
164 if not connected:
165 return None
166 return peer
167
168 def needs_summary(self, forward: bool) -> bool:
169 """Avoid producing a summary without an exit consumer.
170
171 Args:
172 forward: Select the forward S/M or backward G/N direction.
173 """
174 if forward and self._replay_entry is not None:
175 return False
176 if self.is_rd:
177 plan = self.plans[not forward]
178 return plan.shift_peers(plan.local_rank)[0] is not None
179 return self.width > 1 or self.peer(forward, receiving=False) is not None
180
181 def receive(self, reference: torch.Tensor, forward: bool) -> tuple[torch.Tensor | None, Any]:
182 """Post reception before native prepare, independently of summary production.
183
184 Args:
185 reference: Local input supplying the device.
186 forward: Select the chronological communication direction.
187
188 Returns:
189 Full input state and the pending packet's buffer/handle, if any.
190 """
191 if forward and self._bind_checkpoint_entry(reference):
192 return None, None
193 if self.is_rd or self.width == self.size:
194 return None, None
195 incoming = reference.new_zeros((self.batch_size, self.heads, 128, 128), dtype=torch.float32)
196 peer = self.peer(forward, receiving=True)
197 pending = None
198 if self.rank == self.owner and peer is not None:
199 end = self.head_ranges[0][1] if self.width == 1 else self.heads
200 pending = self._post_receive(incoming[:, :end], peer)
201 return incoming, pending
202
203 def _post_receive(self, target, peer):
204 """HCCL needs a contiguous packet when slicing heads across several batches."""
205 buffer = target if target.is_contiguous() else target.new_empty(target.shape)
206 return buffer, dist.irecv(buffer, src=self.ranks[peer], group=self.group)
207
208 @staticmethod
209 def _finish_receive(target, pending):
210 """Own staging storage until reception completes, then restore the batch/head view."""
211 if pending is not None:
212 buffer, handle = pending
213 handle.wait()
214 if not target.is_contiguous():
215 target.copy_(buffer)
216
217 def _bind_checkpoint_entry(self, reference: torch.Tensor) -> bool:
218 """Bind this direction to an invocation cache, never a shared module tensor."""
219 state = get_recompute_state() if self.reuse_cp_state_on_recompute else None
220 if state is None:
221 return False
222 sequence = None if self.info is None else (
223 self.info.global_offsets, self.info.start, self.info.end)
224 signature = (self.cache_key, self.algorithm, self.group, self.ranks, self.rank,
225 self.batch_size, self.heads, self.local_length, self.width, self.head_ranges,
226 sequence, reference.device, reference.dtype)
227 cache = state.get_resource(_ENTRY_CACHE_KEY, _CPEntryCache)
228 if state.is_recomputing:
229 self._replay_entry = (cache.pop(signature),)
230 return True
231 self._entry_cache, self._cache_signature = cache, signature
232 return False
233
234 @staticmethod
235 def apply(packed: torch.Tensor, incoming: torch.Tensor | None) -> torch.Tensor:
236 """Apply forward M or native backward N directly, without transposing N.
237
238 Args:
239 packed: Packed state and transition tensors for the scan.
240 incoming: State entering this rank or group.
241 """
242 return _apply_state(packed[..., :128], packed[..., 128:], incoming)
243
244 def exchange(self, ops: Any, packed: torch.Tensor | None,
245 reception: tuple[torch.Tensor | None, Any], forward: bool,
246 count: int) -> tuple[torch.Tensor, Any, torch.Tensor | list[torch.Tensor] | None]:
247 """Produce the local input state and retain an asynchronous outgoing payload.
248
249 Args:
250 ops: Native summary-merge operations for AllGather.
251 packed: Local S/M or G/N, absent when no exit consumes it.
252 reception: Input state and a previously posted packet with its receive handle.
253 forward: Select the chronological communication direction.
254 count: Number of maps in the relevant AllGather prefix or suffix.
255 """
256 if forward and self._replay_entry is not None:
257 entry, = self._replay_entry
258 self._replay_entry = None
259 return entry, None, None
260 result = self._exchange_uncached(ops, packed, reception, forward, count)
261 if forward and self._entry_cache is not None:
262 self._entry_cache.save(self._cache_signature, result[0])
263 # The backward context must not keep the entire invocation registry alive.
264 self._entry_cache = self._cache_signature = None
265 return result
266
267 def _exchange_uncached(self, ops, packed, reception, forward, count):
268 """Execute the existing state protocol, including every ordinary backward."""
269 if self.is_rd:
270 state_shape = (self.batch_size, self.heads, 128, 128)
271 maps = None if packed is None else packed.reshape(self.batch_size, self.heads, 128, 256)
272 result = self.executor.scan_affine(maps, self.plans[not forward], state_shape, reverse=not forward)
273 return result, None, None
274 if self.sparse is not None:
275 maps, rank = self.sparse.exchange_maps(packed.reshape(self.batch_size, self.heads, 128, 256), forward)
276 maps = maps.squeeze(1)
277 incoming = maps.new_zeros((self.heads, 128, 128))
278 count = maps.shape[0] - 1
279 if count:
280 self._merge(ops, incoming, maps, count, rank, forward)
281 return incoming.unsqueeze(0), None, None
282 if self.width == self.size:
283 maps = self.executor.gather_packed(packed.reshape(self.batch_size, self.heads, 128, 256))
284 incoming = maps.new_zeros((self.batch_size, self.heads, 128, 128))
285 if count:
286 # The native merge has no sample axis. Each call scans ranks for
287 # one sample, without converting independent samples into heads.
288 for sample in range(self.batch_size):
289 self._merge(ops, incoming[sample], maps[:, sample], count, self.rank, forward)
290 return incoming, None, None
291 incoming, pending = reception
292 if self.width > 1:
293 return self._grouped_exchange(packed, incoming, pending, forward)
294 return self._p2p_exchange(packed, incoming, pending, forward)
295
296 @staticmethod
297 def _merge(ops, incoming, maps, count, rank, forward):
298 """Tile independent heads to respect the native merge's 256-head ABI limit."""
299 for begin in range(0, incoming.shape[0], _NATIVE_MERGE_MAX_HEADS):
300 end = begin + _NATIVE_MERGE_MAX_HEADS
301 ops.merge_fwd_bwd_kernel(incoming[begin:end], maps[:, begin:end].contiguous(),
302 count, rank, forward=forward)
303
304 def _p2p_exchange(self, packed, incoming, pending, forward):
305 """Relay each head packet before queuing the next receive on the HCCL stream."""
306 source = self.peer(forward, receiving=True)
307 destination = self.peer(forward, receiving=False)
308 transfer = self.info is None or self.info.num_sequences == 1
309 states = matrices = None
310 if packed is not None:
311 # Packed S/M columns require copies for Torch matmul/add. Move those
312 # copies before the state dependency, preserving FP32 arithmetic.
313 states = packed[..., :128].reshape(self.batch_size, self.heads, 128, 128).contiguous()
314 if transfer and source is not None:
315 matrices = packed[..., 128:].reshape(self.batch_size, self.heads, 128, 128).contiguous()
316 handles, payloads = [], []
317 for index, (begin, end) in enumerate(self.head_ranges):
318 if transfer:
319 self._finish_receive(incoming[:, begin:end], pending)
320 pending = None
321 if destination is not None:
322 outgoing = _apply_state(
323 states[:, begin:end], None if matrices is None else matrices[:, begin:end],
324 incoming[:, begin:end] if matrices is not None else None).contiguous()
325 payloads.append(outgoing)
326 handles.append(dist.isend(outgoing, dst=self.ranks[destination], group=self.group))
327 self._finish_receive(incoming[:, begin:end], pending)
328 # Posting every receive first can serialize send_i behind recv_i+1
329 # on the same communication stream, defeating packet relay.
330 if source is not None and index + 1 < len(self.head_ranges):
331 next_begin, next_end = self.head_ranges[index + 1]
332 pending = self._post_receive(incoming[:, next_begin:next_end], source)
333 return incoming, NativeStateSends(handles) if handles else None, payloads
334
335 def _grouped_exchange(self, packed, incoming, pending, forward):
336 """Gather native maps within a group and relay only its exit state."""
337 if self.info is not None:
338 if not self.info.transfer_active or not self.info.continues_next:
339 packed[..., 128:].zero_()
340 connected = self.info.continues_next if forward else self.info.continues_previous
341 if not connected:
342 packed[..., :128].zero_()
343 packed = packed.reshape(self.batch_size, self.heads, 128, 256)
344 maps = packed.new_empty((self.width * self.batch_size, self.heads, 128, 256))
345 dist.all_gather_into_tensor(maps, packed, group=self.executor.intra)
346 maps = maps.reshape(self.width, self.batch_size, self.heads, 128, 256)
347 send_handle, outgoing, result = None, None, None
348 indices = range(self.width) if forward else range(self.width - 1, -1, -1)
349 prefix_count = self.local if forward else self.width - self.local - 1
350 if self.rank == self.owner:
351 self._finish_receive(incoming, pending)
352 peer = self.peer(forward, receiving=False)
353 if peer is not None:
354 outgoing, result = self._scan(maps, incoming, indices, prefix_count)
355 send_handle = dist.isend(outgoing, dst=self.ranks[peer], group=self.group)
356 if self.peer(forward, receiving=True) is not None:
357 dist.broadcast(incoming, src=self.ranks[self.owner], group=self.executor.intra)
358 if result is None:
359 local_indices = range(self.local) if forward else range(self.width - 1, self.local, -1)
360 result, _ = self._scan(maps, incoming, local_indices)
361 return result, send_handle, outgoing
362
363 @staticmethod
364 def _scan(maps, incoming, indices, prefix_count=None):
365 """Keep native M/N orientation while applying a nonzero group entry."""
366 state = incoming
367 prefix = incoming if prefix_count == 0 else None
368 for step, index in enumerate(indices, start=1):
369 state = NativeStateExchange.apply(maps[index], state)
370 if step == prefix_count:
371 prefix = state
372 return state, prefix