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"""Cached eager recursive doubling using public batched point-to-point transport."""
16from __future__ import annotations
17
18
19from bisect import bisect_left
20from dataclasses import dataclass
21from functools import lru_cache
22import importlib
23from typing import Any
24
25import torch
26import torch.distributed as dist
27from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import PackedDocumentInfo
28
29
30class _RoundExchange:
31 """Keep immutable payload alive until send completion; outputs belong to the call."""
32
33 def __init__(self, group: Any, rank: int, ranks: tuple[int, ...]) -> None:
34 """Resolve ordered peers and the process group's protocol device."""
35 if not ranks or len(set(ranks)) != len(ranks) or not 0 <= rank < len(ranks):
36 raise ValueError("RD requires unique global peers and a valid local rank")
37 if tuple(dist.get_process_group_ranks(group)) != ranks:
38 raise ValueError("RD mesh sequence order must match its communication group order")
39 self.group, self.rank, self.size, self.peers = group, rank, len(ranks), ranks
40 if dist.get_backend(group) != "hccl":
41 raise ValueError("KDA recursive doubling requires an HCCL process group")
42 # Receive-only TND ranks have no local summary to infer a device from.
43 # Load the optional extension here and bind buffers to the caller's NPU.
44 torch_npu = importlib.import_module("torch_npu")
45 self.device = torch.device("npu", torch_npu.npu.current_device())
46
47 def __call__(
48 self, payload: torch.Tensor | None, destination: int | None, source: int | None,
49 receive_shape: tuple[int, ...] | None = None,
50 ) -> torch.Tensor | None:
51 """Exchange peers, allocating only a live receive independently of the send.
52
53 Args:
54 payload: Immutable send tensor; may be absent when there is no destination.
55 destination: Group-local send peer, or None.
56 source: Group-local receive peer, or None.
57 receive_shape: Explicit receive shape, required for a receive without a payload.
58 """
59 output = self._prepare_receive(payload, destination, source, receive_shape)
60 if source is None and destination is None:
61 return output
62 operations = []
63 if source is not None:
64 operations.append(dist.P2POp(dist.irecv, output, self.peers[source], self.group))
65 if destination is not None:
66 operations.append(dist.P2POp(dist.isend, payload, self.peers[destination], self.group))
67 for handle in dist.batch_isend_irecv(operations):
68 handle.wait()
69 return output
70
71 def _prepare_receive(
72 self, payload: torch.Tensor | None, destination: int | None, source: int | None,
73 receive_shape: tuple[int, ...] | None,
74 ) -> torch.Tensor | None:
75 """Validate one exchange and allocate only its live receive buffer."""
76 if payload is None:
77 if destination is not None:
78 raise ValueError('RD send requires a payload')
79 if source is not None and receive_shape is None:
80 raise ValueError('RD receive without a payload requires a shape')
81 elif payload.device != self.device or not payload.is_contiguous():
82 raise ValueError('RD payload must be contiguous on the protocol device')
83 if any(peer is not None and not 0 <= peer < self.size for peer in (source, destination)):
84 raise ValueError('RD peer is outside the process group')
85 output = None
86 if source is not None:
87 output = (torch.empty_like(payload) if receive_shape is None else torch.empty(
88 receive_shape, dtype=torch.float32 if payload is None else payload.dtype, device=self.device))
89 return output
90
91
92@dataclass(frozen=True)
93class RDScanRound:
94 """One immutable exchange and its subsequent transfer-matrix consumer."""
95
96 stage: int
97 destination: int | None
98 source: int | None
99 save_matrix: bool
100
101
102def build_scan_rounds(
103 rank: int, size: int, distances: tuple[int, ...],
104) -> tuple[RDScanRound, ...]:
105 """Precompute dense inclusive-scan peers and transfer consumers for one rank.
106
107 Args:
108 rank: Rank in the state process group.
109 size: Number of chronological ranks in the state process group.
110 distances: Increasing powers of two used by the inclusive scan.
111 """
112 # Dense execution retains the final rank's inclusive output. Use size as
113 # an exclusive scan bound, instead of pruning a document's final rank.
114 return _interval_rounds(rank, distances, _RankInterval(0, size, rank > 0))
115
116
117@dataclass(frozen=True)
118class _RankInterval:
119 """Rank span of the tail document and independent head continuation."""
120
121 first: int
122 last: int
123 continues_previous: bool
124
125 def peers(self, rank: int, distance: int) -> tuple[int | None, int | None]:
126 """Return the exact live scan edge at one doubling distance.
127
128 A document's last rank has no exit-state consumer. Earlier ranks reach
129 a predecessor precisely when that predecessor belongs to this document.
130
131 Args:
132 rank: Rank index in sequence order.
133 distance: Rank distance of this doubling round.
134 """
135 destination = rank + distance if rank + distance < self.last else None
136 source = rank - distance if rank < self.last and rank - distance >= self.first else None
137 return destination, source
138
139 def cache_count(self, rank: int) -> int:
140 """Count powers of two that reach a preceding rank of this document.
141
142 Args:
143 rank: Rank index in sequence order.
144 """
145 return (rank - self.first).bit_length() if rank < self.last else 0
146
147
148def _rank_interval(offsets: tuple[int, ...], local_length: int, rank: int) -> _RankInterval:
149 """Find the tail document without treating a rank cut as a reset."""
150 tail = bisect_left(offsets, (rank + 1) * local_length) - 1
151 start = rank * local_length
152 head = bisect_left(offsets, start)
153 return _RankInterval(offsets[tail] // local_length, (offsets[tail + 1] - 1) // local_length,
154 offsets[head] != start)
155
156
157def _interval_rounds(
158 rank: int, distances: tuple[int, ...], interval: _RankInterval,
159) -> tuple[RDScanRound, ...]:
160 """Keep stage order and transfer lifetimes from the inclusive scan.
161
162 Each effective receive caches the matrix used by its adjoint. Retain its
163 composed output only when a subsequent receive consumes that output.
164 """
165 last_receive = interval.cache_count(rank) - 1
166 rounds = []
167 for stage, distance in enumerate(distances):
168 destination, source = interval.peers(rank, distance)
169 if destination is not None or source is not None:
170 save_matrix = stage < last_receive
171 rounds.append(RDScanRound(stage, destination, source, save_matrix))
172 return tuple(rounds)
173
174
175@dataclass(frozen=True)
176class RDResetPlan:
177 """An immutable local schedule derived from true document boundaries.
178
179 Cached-adjoint backward transposes the same plan; fresh reverse maps use
180 a mirrored plan. Matrices are never inspected on device: only true document
181 boundaries can remove an edge. Binding one rank
182 retains its tail interval and rounds, without building the all-rank graph.
183 """
184
185 size: int
186 distances: tuple[int, ...]
187 offsets: tuple[int, ...]
188 local_length: int
189 local_rank: int | None
190 local_rounds: tuple[RDScanRound, ...]
191 _local_interval: _RankInterval | None
192
193 def _interval(self, rank: int) -> _RankInterval:
194 """Reuse local bounds or locate another rank for an audit query."""
195 if rank == self.local_rank and self._local_interval is not None:
196 return self._local_interval
197 if not 0 <= rank < self.size:
198 raise ValueError("RD execution-plan rank is outside the state process group")
199 return _rank_interval(self.offsets, self.local_length, rank)
200
201 def peers(self, stage: int, rank: int) -> tuple[int | None, int | None]:
202 """Return forward destination/source, both in process-group order.
203
204 Args:
205 stage: Index of the planned doubling round.
206 rank: Rank index in sequence order.
207 """
208 return self._interval(rank).peers(rank, self.distances[stage])
209
210 def shift_peers(self, rank: int) -> tuple[int | None, int | None]:
211 """Return the tail's consumer and the head's producer independently.
212
213 Args:
214 rank: Rank index in sequence order.
215 """
216 interval = self._interval(rank)
217 return (rank + 1 if rank < interval.last else None,
218 rank - 1 if interval.continues_previous else None)
219
220 def is_transfer_active(self, rank: int) -> bool:
221 """Whether a rank's entry can reach its exit without a document reset.
222
223 Args:
224 rank: Rank index in sequence order.
225 """
226 return rank > self._interval(rank).first
227
228 def execution_rounds(self, rank: int) -> tuple[RDScanRound, ...]:
229 """Reuse the caller's plan without materializing schedules for every peer.
230
231 Args:
232 rank: Rank index in sequence order.
233 """
234 if rank == self.local_rank:
235 return self.local_rounds
236 return _interval_rounds(rank, self.distances, self._interval(rank))
237
238 def cache_count(self, rank: int) -> int:
239 """Count invocation-owned pre-round transfers on one rank.
240
241 Args:
242 rank: Rank index in sequence order.
243 """
244 return self._interval(rank).cache_count(rank)
245
246
247@lru_cache(maxsize=32)
248def _validate_intervals(offsets: tuple[int, ...], local_length: int, size: int) -> None:
249 """Share document validation across rank-specific plans with bounded storage."""
250 if (size < 1 or local_length < 1 or len(offsets) < 2 or offsets[0] != 0
251 or offsets[-1] != size * local_length
252 or any(left >= right for left, right in zip(offsets, offsets[1:]))):
253 raise ValueError("RD reset planning requires ordered documents covering equal state-rank intervals")
254
255
256@lru_cache(maxsize=32)
257def _reverse_documents(offsets: tuple[int, ...] | PackedDocumentInfo) -> PackedDocumentInfo:
258 """Cache the reversed immutable snapshot across layers of the same batch."""
259 values = offsets.offsets if isinstance(offsets, PackedDocumentInfo) else offsets
260 return PackedDocumentInfo(tuple(values[-1] - value for value in reversed(values)))
261
262
263@lru_cache(maxsize=32)
264def build_reset_plan(
265 offsets: tuple[int, ...] | PackedDocumentInfo, local_length: int, size: int, rank: int | None = None,
266 *, reverse: bool = False,
267) -> RDResetPlan:
268 """Derive one rank's exact live edges from its tail document interval.
269
270 Args:
271 offsets: Global document offsets, or a batch's already validated snapshot.
272 Reusing the snapshot avoids full-offset validation and hashing.
273 local_length: Equal token interval length after any Ulysses exchange.
274 size: Number of chronological state ranks, independent of global rank IDs.
275 rank: Optional physical group rank whose execution schedule should be cached.
276 reverse: Plan a fresh reverse-map scan in mirrored token/rank order.
277 The executor maps logical peers back to the unchanged process group.
278
279 Returns:
280 An immutable CPU plan reusable across layers with identical metadata.
281 Omitting rank retains only metadata for subsequent diagnostic queries.
282 """
283 if rank is not None and not 0 <= rank < size:
284 raise ValueError("RD execution-plan rank is outside the state process group")
285 if reverse:
286 if not isinstance(offsets, PackedDocumentInfo):
287 _validate_intervals(offsets, local_length, size)
288 offsets = _reverse_documents(offsets)
289 rank = None if rank is None else size - rank - 1
290 if isinstance(offsets, PackedDocumentInfo):
291 offsets = offsets.offsets
292 if size < 1 or local_length < 1 or offsets[-1] != size * local_length:
293 raise ValueError("RD reset planning requires ordered documents covering equal state-rank intervals")
294 else:
295 _validate_intervals(offsets, local_length, size)
296 distances = tuple(1 << level for level in range((size - 1).bit_length()))
297 interval = None if rank is None else _rank_interval(offsets, local_length, rank)
298 rounds = () if rank is None else _interval_rounds(rank, distances, interval)
299 return RDResetPlan(size, distances, offsets, local_length, rank, rounds, interval)
300
301
302_RD_EPILOGUE_BLOCK_ROWS = 64
303
304
305@lru_cache(maxsize=1)
306def _rd_kernels() -> Any:
307 """Load optional Ascend kernels only when an NPU epilogue is executed."""
308 return importlib.import_module(
309 "hyper_parallel.components.functional._triton.kimi_delta_attention.rd_pointwise"
310 )
311
312
313def _finish_round(product: torch.Tensor, previous: torch.Tensor, save_m: bool = True) -> torch.Tensor | None:
314 """Add the previous S and copy the next M in one launch, without fusing GEMM.
315
316 Inputs must be distinct contiguous FP32 [B,H,128,256] buffers. Only the
317 newly computed product's S half is modified; input summaries are immutable.
318 The validated scan inputs and fresh matrix product establish this layout.
319
320 Args:
321 product: Fresh contiguous FP32 packed matrix product [B, H, 128, 256].
322 previous: Previous immutable packed S/M tensor with the same layout.
323 save_m: Whether a future round consumes the new contiguous M.
324 """
325 state_width, packed_width = product.shape[-2:]
326 matrix = (torch.empty((*product.shape[:-1], state_width), dtype=product.dtype, device=product.device)
327 if save_m else None)
328 kernels = _rd_kernels()
329
330 rows = product.numel() // packed_width
331 block_rows = _RD_EPILOGUE_BLOCK_ROWS
332 kernels.kda_rd_finish_round_kernel[((rows + block_rows - 1) // block_rows,)](
333 product, previous, matrix if save_m else product,
334 row_count=rows, state_width=state_width, packed_width=packed_width,
335 block_rows=block_rows, save_matrix=save_m, num_warps=4)
336 return matrix
337
338
339def _finish_to_state(
340 product: torch.Tensor, previous: torch.Tensor, save_m: bool,
341) -> tuple[torch.Tensor | None, torch.Tensor]:
342 """Emit contiguous final-stage S alongside the unchanged packed epilogue.
343
344 Args:
345 product: Fresh contiguous FP32 packed matrix product [B, H, 128, 256].
346 previous: Previous immutable packed S/M tensor with the same layout.
347 save_m: Whether a future round consumes the new contiguous M.
348 """
349 state_width, packed_width = product.shape[-2:]
350 state = torch.empty((*product.shape[:-1], state_width), dtype=product.dtype, device=product.device)
351 matrix = torch.empty_like(state) if save_m else None
352 kernels = _rd_kernels()
353
354 rows = product.numel() // packed_width
355 block_rows = _RD_EPILOGUE_BLOCK_ROWS
356 kernels.kda_rd_finish_to_state_kernel[((rows + block_rows - 1) // block_rows,)](
357 product, previous, matrix if save_m else product, state,
358 row_count=rows, state_width=state_width, packed_width=packed_width,
359 block_rows=block_rows, save_matrix=save_m, num_warps=4)
360 return matrix, state
361
362
363def _validate_summary(
364 tensor: torch.Tensor, device: torch.device, state_shape: tuple[int, ...] | None = None,
365) -> None:
366 """Validate caller-owned S/M/G and cached transfers before any peer exchange."""
367 if (not isinstance(tensor, torch.Tensor) or tensor.ndim != 4
368 or tensor.shape[-2:] != (128, 128) or tensor.dtype != torch.float32
369 or tensor.device != device or not tensor.is_contiguous()):
370 raise ValueError("RD requires contiguous FP32 B/H/K128/V128 summaries on the protocol device")
371 if state_shape is not None and tensor.shape != state_shape:
372 raise ValueError("RD summary shape differs from the invocation")
373
374
375def _validate_backward_summary(
376 gradient: torch.Tensor | None, cache: tuple, expected: int,
377 device: torch.device, state_shape: tuple[int, ...] | None = None,
378) -> None:
379 """Reject incompatible invocation cache layouts before any peer exchange."""
380 if gradient is None:
381 if state_shape is None:
382 raise ValueError("RD gradient may be absent only with invocation shape metadata")
383 else:
384 _validate_summary(gradient, device, state_shape)
385 state_shape = gradient.shape
386 if not isinstance(cache, tuple) or len(cache) != expected:
387 raise ValueError("RD received an incompatible invocation cache")
388 for matrix in cache:
389 _validate_summary(matrix, device, state_shape)
390
391
392def _compact_transfer(matrix: torch.Tensor) -> torch.Tensor:
393 """Keep a contiguous M view from retaining a larger producer allocation."""
394 if matrix.untyped_storage().nbytes() != matrix.numel() * matrix.element_size():
395 return matrix.clone()
396 return matrix
397
398
399class KDAStateRecursiveDoubling:
400 """Exclusive forward scan and its cached adjoint, preserving the established rounding.
401
402 Caller creates/warm-ups the HCCL group collectively. Inputs are immutable,
403 contiguous FP32 B/H/K128/V128 summaries. Keep the returned invocation cache
404 with its own autograd context. No shared graph buffers or mutable layer state.
405 """
406
407 protocol = "recursive_doubling"
408
409 requires_contiguous_summaries = True
410
411 def __init__(self, group: Any, rank: int, ranks: tuple[int, ...]) -> None:
412 """Prepare communication metadata and logarithmic scan distances."""
413 self.exchange = _RoundExchange(group, rank, ranks)
414 self.rank, self.size = self.exchange.rank, self.exchange.size
415 self.device = self.exchange.device
416 self.distances = tuple(1 << level for level in range((self.size - 1).bit_length()))
417 self.rounds = build_scan_rounds(self.rank, self.size, self.distances)
418
419 def bind_sequence(
420 self, sequence_info: Any, state_shape: tuple[int, ...] | None = None,
421 ) -> _ResetRDInvocation:
422 """Bind immutable packed metadata, optionally allowing absent dead summaries.
423
424 Args:
425 sequence_info: This call's packed document offsets and local interval.
426 state_shape: B/H/K/V dimensions, without retaining a tensor allocation.
427 """
428 if sequence_info.start != self.rank * sequence_info.length:
429 raise ValueError("RD packed interval must follow the state process-group order")
430 if state_shape is not None:
431 state_shape = tuple(state_shape)
432 if (len(state_shape) != 4 or state_shape[-2:] != (128, 128)
433 or any(not isinstance(dim, int) or dim < 1 for dim in state_shape)):
434 raise ValueError("RD invocation shape requires positive B/H and K=V128")
435 plan = build_reset_plan(sequence_info.documents, sequence_info.length, self.size, self.rank)
436 return _ResetRDInvocation(self, plan, state_shape)
437
438 def directional_plan(self, sequence_info: Any, local_length: int, reverse: bool = False) -> RDResetPlan:
439 """Reuse reset planning for independent forward or reverse affine maps.
440
441 Args:
442 sequence_info: Packed metadata, or None for one continuous document.
443 local_length: Equal token interval length in this state group.
444 reverse: Whether to scan fresh G/N in reverse chronological order.
445 """
446 if sequence_info is not None and sequence_info.start != self.rank * local_length:
447 raise ValueError("RD packed interval must follow the state process-group order")
448 documents = (0, self.size * local_length) if sequence_info is None else sequence_info.documents
449 return build_reset_plan(documents, local_length, self.size, self.rank, reverse=reverse)
450
451 def scan_affine(
452 self, packed: torch.Tensor | None, plan: RDResetPlan,
453 state_shape: tuple[int, ...], reverse: bool = False,
454 ) -> torch.Tensor | None:
455 """Scan independently supplied affine maps without a forward-adjoint cache.
456
457 Args:
458 packed: Immutable FP32 [B,H,128,256] S/M or G/N; absent for a dead tail.
459 plan: Directional reset plan from this invocation's metadata.
460 state_shape: B/H/K/V dimensions for receive-only fragments.
461 reverse: Map mirrored logical ranks onto the original process group.
462
463 Returns:
464 Exclusive input state, or None at a real document boundary.
465 N is already a reverse transfer and is never transposed here.
466 """
467 rank = self.size - self.rank - 1 if reverse else self.rank
468 if plan.size != self.size or plan.local_rank != rank:
469 raise ValueError("RD affine scan received another rank's directional plan")
470 rounds = plan.execution_rounds(rank)
471 destination, source = plan.shift_peers(rank)
472 if packed is None:
473 if rounds or destination is not None:
474 raise ValueError("RD affine map may be absent only without an exit consumer")
475 state = None
476 else:
477 if (packed.shape != (*state_shape[:-1], 256) or packed.dtype != torch.float32
478 or packed.device != self.device or not packed.is_contiguous()):
479 raise ValueError("RD affine maps must be contiguous FP32 [B,H,128,256] on the protocol device")
480 with torch.autocast(device_type=packed.device.type, enabled=False):
481 state = self._scan_independent_maps(packed, plan, rounds, reverse)
482 return self._exchange_direction(state, destination, source, reverse, state_shape)
483
484 def _exchange_direction(self, payload, destination, source, reverse, receive_shape=None):
485 """Reverse only logical peers; retain the original communicator and global ranks."""
486 if reverse:
487 destination = None if destination is None else self.size - destination - 1
488 source = None if source is None else self.size - source - 1
489 return self.exchange(payload, destination, source, receive_shape=receive_shape)
490
491 def _scan_independent_maps(self, packed, plan, rounds, reverse):
492 """Use FP32 Torch GEMM/add while sharing RD transport and pruning plans."""
493 state = packed[..., :128]
494 matrix = packed[..., 128:].contiguous() if rounds else None
495 for step in rounds:
496 final = step.stage == len(plan.distances) - 1
497 payload = state.contiguous() if final else packed
498 received = self._exchange_direction(payload, step.destination, step.source, reverse)
499 if received is None:
500 continue
501 if final:
502 state = matrix @ received + state
503 else:
504 updated = matrix @ received
505 updated[..., :128].add_(state)
506 packed, state = updated, updated[..., :128]
507 matrix = updated[..., 128:].contiguous() if step.save_matrix else None
508 return state.contiguous()
509
510 def _shift_peers(self, plan: RDResetPlan | None) -> tuple[int | None, int | None]:
511 """Only continued documents consume the preceding rank's exit."""
512 if plan is not None:
513 return plan.shift_peers(self.rank)
514 return (self.rank + 1 if self.rank + 1 < self.size else None,
515 self.rank - 1 if self.rank else None)
516
517 def _compose_packed_round(self, step, matrix, received, previous):
518 """Keep packed arithmetic, materializing a transfer only for a later receive."""
519 aggregate = matrix @ received
520 if 2 * self.distances[step.stage] == self.distances[-1]:
521 next_matrix, state = _finish_to_state(aggregate, previous, step.save_matrix)
522 else:
523 next_matrix = _finish_round(aggregate, previous, save_m=step.save_matrix)
524 state = None
525 return aggregate, next_matrix, state
526
527 def forward(
528 self, state: torch.Tensor | None, matrix: torch.Tensor | None,
529 plan: RDResetPlan | None = None, state_shape: tuple[int, ...] | None = None,
530 ) -> tuple[torch.Tensor | None, tuple[torch.Tensor, ...]]:
531 """Return the exclusive incoming state and immutable pre-round transfer cache.
532
533 Args:
534 state: Local summary S tensor or kernel output.
535 matrix: Contiguous FP32 local transfer M.
536 plan: Internal immutable plan supplied by the packed invocation wrapper.
537 state_shape: Optional per-call dimensions enabling absent dead summaries.
538 """
539 rounds = self.rounds if plan is None else plan.execution_rounds(self.rank)
540 destination, source = self._shift_peers(plan)
541 if state_shape is not None and plan is None:
542 raise ValueError("RD optional summaries require a packed invocation plan")
543 if state is None:
544 if state_shape is None or matrix is not None or rounds or destination is not None:
545 raise ValueError("RD state may be absent only when no exit-state consumer exists")
546 return self.exchange(None, None, source, receive_shape=state_shape), ()
547 _validate_summary(state, self.device, state_shape)
548 _validate_summary(matrix, self.device, state.shape)
549 # Autocast would round the composed maps before they enter communication
550 # and the backward cache, despite the validated FP32 inputs.
551 with torch.autocast(device_type=self.device.type, enabled=False):
552 narrow_state, cache = self._scan_forward(state, matrix, rounds)
553 received = self.exchange(narrow_state, destination, source)
554 if received is None and state_shape is None:
555 received = torch.zeros_like(state)
556 return received, cache
557
558 def _scan_forward(
559 self, state: torch.Tensor, matrix: torch.Tensor, rounds: tuple,
560 ) -> tuple[torch.Tensor, tuple[torch.Tensor, ...]]:
561 """Compose live inclusive-scan rounds, preserving per-round adjoint inputs."""
562 matrix = _compact_transfer(matrix) if rounds else matrix
563 # Reset-only shifts never consume a packed S/M payload.
564 packed = (torch.cat((state, matrix), dim=-1)
565 if any(step.stage < len(self.distances) - 1 for step in rounds) else None)
566 before_m, narrow_state = matrix, state
567 cache = []
568 for step in rounds:
569 final = step.stage == len(self.distances) - 1
570 if final and narrow_state is None:
571 narrow_state = packed[..., :128].contiguous()
572 destination, source = step.destination, step.source
573 received = self.exchange(narrow_state if final else packed, destination, source)
574 if source is not None:
575 cache.append(before_m)
576 if final:
577 narrow_state = before_m @ received + narrow_state
578 else:
579 packed, before_m, narrow_state = self._compose_packed_round(
580 step, before_m, received, packed)
581 if narrow_state is None:
582 narrow_state = packed[..., :128].contiguous()
583 return narrow_state, tuple(cache)
584
585 def backward(
586 self, gradient: torch.Tensor | None, cache: tuple[torch.Tensor, ...],
587 plan: RDResetPlan | None = None, state_shape: tuple[int, ...] | None = None,
588 ) -> torch.Tensor | None:
589 """Transpose the exact recorded forward composition order.
590
591 Args:
592 gradient: Contiguous FP32 local state-gradient summary G.
593 cache: Invocation-owned transfers returned by this protocol forward.
594 plan: The same internal plan used by this invocation's forward.
595 state_shape: The same optional per-call shape used by forward.
596 """
597 expected = (sum(self.rank >= distance for distance in self.distances)
598 if plan is None else plan.cache_count(self.rank))
599 source, destination = self._shift_peers(plan)
600 if state_shape is not None and plan is None:
601 raise ValueError("RD optional summaries require a packed invocation plan")
602 if gradient is None and destination is not None:
603 raise ValueError("RD gradient may be absent only when no head-gradient consumer exists")
604 _validate_backward_summary(gradient, cache, expected, self.device, state_shape)
605 received = (self.exchange(gradient, destination, source) if gradient is not None
606 else self.exchange(None, destination, source, receive_shape=state_shape))
607 if received is None and state_shape is not None:
608 # A tail without a consumer has no live scan rounds in a reset plan.
609 return None
610 adjoint = torch.zeros_like(gradient) if received is None else received
611 index = len(cache)
612 rounds = self.rounds if plan is None else plan.execution_rounds(self.rank)
613 # Backward may be called inside autocast too; keep its transmitted
614 # adjoints in the same precision as the recorded forward maps.
615 with torch.autocast(device_type=self.device.type, enabled=False):
616 for step in reversed(rounds):
617 source, destination = step.destination, step.source
618 payload = adjoint
619 if destination is not None:
620 index -= 1
621 payload = cache[index].transpose(-2, -1) @ adjoint
622 received = self.exchange(payload, destination, source)
623 if received is not None:
624 # Adjoint is invocation-owned and every send has completed.
625 adjoint.add_(received)
626 return adjoint
627
628
629@dataclass(frozen=True)
630class _ResetRDInvocation:
631 """Share static transport while keeping the exact plan with one autograd call."""
632
633 requires_contiguous_summaries = True
634
635 protocol: KDAStateRecursiveDoubling
636 plan: RDResetPlan
637 state_shape: tuple[int, ...] | None = None
638
639 @property
640 def allows_absent_summaries(self) -> bool:
641 """Whether shape metadata replaces unused full-size placeholders."""
642 return self.state_shape is not None
643
644 @property
645 def needs_state_summary(self) -> bool:
646 """Only a continuing tail document has an exit-state consumer."""
647 return self.plan.shift_peers(self.protocol.rank)[0] is not None
648
649 @property
650 def needs_transition_summary(self) -> bool:
651 """Produce M only when a consumed exit depends on this rank's entry."""
652 return self.needs_state_summary and self.plan.is_transfer_active(self.protocol.rank)
653
654 def forward(
655 self, state: torch.Tensor | None, matrix: torch.Tensor | None,
656 ) -> tuple[torch.Tensor | None, tuple[torch.Tensor, ...]]:
657 """Execute the pruned graph and return its tensor-only cache.
658
659 Args:
660 state: State tensor at the invocation boundary, or None for zero input.
661 matrix: Local recurrent-state transition matrix.
662 """
663 return self.protocol.forward(state, matrix, self.plan, self.state_shape)
664
665 def backward(self, gradient: torch.Tensor | None, cache: tuple[torch.Tensor, ...]) -> torch.Tensor | None:
666 """Transpose this invocation's graph, independent of later forwards.
667
668 Args:
669 gradient: Gradient arriving from the following sequence interval.
670 cache: Forward-owned transition cache for this invocation.
671 """
672 return self.protocol.backward(gradient, cache, self.plan, self.state_shape)