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"""Exchange packed CSA2 cache rows across context-parallel ranks.
16
17SWA halo rows use all-to-all. Main KV uses all-to-all or all-gather, and
18Indexer K uses all-gather. Forward moves packed bytes. Backward sums
19floating-point gradients on the ranks that own the original rows.
20"""
21
22from __future__ import annotations
23
24from dataclasses import dataclass
25from types import SimpleNamespace
26from typing import Any
27
28import torch
29import torch.distributed as dist
30from torch import Tensor
31
32from hyper_parallel.components.quantization.tensor.csa2_cache_tensor import CSA2CacheTensor
33from hyper_parallel.distributed.context_parallel.compressed_document import _bank_slots
34from hyper_parallel.distributed.context_parallel.sequence_dispatch import _SequenceDispatchWait
35
36
37def packed_rewrap(packed: Tensor, template: CSA2CacheTensor) -> CSA2CacheTensor:
38 """Wrap received rows with the producer's logical width, dtype, and cache format."""
39 return CSA2CacheTensor(
40 packed, (*packed.shape[:-1], template.shape[-1]), template.dtype,
41 template.cache_format, template.scale_format, template.requires_grad,
42 )
43
44
45class _PackedSequenceDispatch(torch.autograd.Function):
46 """Connect a packed row exchange to the producer's autograd graph."""
47
48 @staticmethod
49 def forward(ctx: Any, cache: CSA2CacheTensor, local: Tensor, received: Tensor | None,
50 handle: Any, route: Any, group: Any, sequence_dim: int) -> CSA2CacheTensor:
51 """Wait for remote rows and insert the local shard in owner order."""
52 ctx.route = route
53 ctx.group = group
54 ctx.sequence_dim = sequence_dim
55 ctx.exchanged = handle is not None
56 if handle is not None:
57 handle.wait()
58 if received is not None and received.shape[0]:
59 before = route.local_output_start
60 assembled = torch.cat((received[:before], local, received[before:]), dim=0)
61 else:
62 assembled = local
63 assembled = assembled.movedim(0, sequence_dim).contiguous()
64 return packed_rewrap(assembled, cache)
65
66 @staticmethod
67 def backward(ctx: Any, grad: Tensor) -> tuple[Tensor | None, ...]:
68 """Reverse the exchange and sum consumer gradients on each owner."""
69 route, group, sequence_dim = ctx.route, ctx.group, ctx.sequence_dim
70 grad_seq = grad.movedim(sequence_dim, 0)
71 if ctx.exchanged:
72 local_seq = _SequenceDispatchWait.backward(
73 SimpleNamespace(route=route, group=group), grad_seq,
74 )[0]
75 else:
76 local_seq = grad_seq
77 return local_seq.movedim(0, sequence_dim), None, None, None, None, None, None
78
79
80@dataclass
81class _AsyncPackedSequenceDispatch:
82 """Keep send and receive buffers alive until the exchange completes."""
83
84 cache: CSA2CacheTensor
85 local: Tensor
86 send: Tensor | None
87 received: Tensor | None
88 handle: Any
89 route: Any
90 group: Any
91 sequence_dim: int
92 waited: bool = False
93
94 def wait(self) -> CSA2CacheTensor:
95 """Wait once and return the assembled cache in its original axis order."""
96 if self.waited:
97 raise RuntimeError("a packed sequence dispatch handle cannot be waited twice")
98 self.waited = True
99 output = _PackedSequenceDispatch.apply(
100 self.cache, self.local, self.received, self.handle, self.route, self.group, self.sequence_dim,
101 )
102 self.send = None
103 self.received = None
104 return output
105
106
107def launch_packed_sequence_dispatch(cache: CSA2CacheTensor, sequence_dim: int,
108 route: Any, group: Any) -> _AsyncPackedSequenceDispatch:
109 """Exchange variable numbers of packed rows across a context-parallel group.
110
111 Args:
112 cache: Producer's packed cache.
113 sequence_dim: Axis containing the rows to exchange.
114 route: Per-peer row ranges and splits for this batch.
115 group: Process group in sequence-shard order.
116 """
117 if not -cache.ndim <= sequence_dim < cache.ndim:
118 raise ValueError("sequence dispatch dimension is outside the input tensor dimensions")
119 sequence_dim %= cache.ndim
120 if cache.packed.shape[sequence_dim] != route.local_length:
121 raise ValueError("sequence dispatch owner length does not match the bank's physical layout")
122 # Materialize only the rows sent to peers; local rows can remain a view.
123 local = cache.packed.movedim(sequence_dim, 0)
124 if not route.needs_exchange:
125 return _AsyncPackedSequenceDispatch(cache, local, None, None, None, route, group, sequence_dim)
126 parts = [local.detach().narrow(0, offset, count)
127 for offset, count in route.owner_ranges() if count]
128 send = torch.cat(parts, dim=0) if parts else local.detach()[:0]
129 received = local.new_empty((sum(route.output_splits), *local.shape[1:]))
130 handle = dist.all_to_all_single(
131 received, send, output_split_sizes=list(route.output_splits),
132 input_split_sizes=list(route.input_splits), group=group, async_op=True,
133 )
134 return _AsyncPackedSequenceDispatch(cache, local, send, received, handle, route, group, sequence_dim)
135
136
137class _PackedBankGather(torch.autograd.Function):
138 """Connect a packed all-gather to the producer's autograd graph."""
139
140 @staticmethod
141 def forward(ctx: Any, cache: CSA2CacheTensor, work: Any, output: Tensor,
142 slots: Tensor | None, group: Any, world_size: int,
143 gather_dim: int, original_rows: int) -> CSA2CacheTensor:
144 """Wait for all ranks and discard padding when row counts differ."""
145 ctx.group = group
146 ctx.world_size = world_size
147 ctx.gather_dim = gather_dim
148 ctx.slots = slots
149 ctx.original_rows = original_rows
150 ctx.padded_total = output.shape[0]
151 work.wait()
152 gathered = output.movedim(0, gather_dim)
153 if slots is not None:
154 gathered = gathered.index_select(gather_dim, slots)
155 return packed_rewrap(gathered.contiguous(), cache)
156
157 @staticmethod
158 def backward(ctx: Any, grad: Tensor) -> tuple[Tensor | None, ...]:
159 """Restore rank padding and reduce-scatter gradients to the row owners."""
160 gather_dim = ctx.gather_dim
161 if ctx.slots is not None:
162 padded_shape = (*grad.shape[:gather_dim], ctx.padded_total, *grad.shape[gather_dim + 1:])
163 padded = grad.new_zeros(padded_shape)
164 padded.index_add_(gather_dim, ctx.slots.long(), grad)
165 else:
166 padded = grad
167 send = padded.movedim(gather_dim, 0).contiguous()
168 received = grad.new_empty((ctx.padded_total // ctx.world_size, *send.shape[1:]))
169 work = dist.reduce_scatter_tensor(
170 received, send, op=dist.ReduceOp.SUM, group=ctx.group, async_op=True,
171 )
172 work.wait()
173 local = received.movedim(0, gather_dim).contiguous()
174 local = local.narrow(gather_dim, 0, ctx.original_rows)
175 return local, None, None, None, None, None, None, None, None
176
177
178@dataclass
179class _AsyncPackedBankGather:
180 """Keep the receive buffer alive until the all-gather completes."""
181
182 cache: CSA2CacheTensor
183 work: Any
184 output: Tensor
185 group: Any
186 world_size: int
187 slots: Tensor | None
188 gather_dim: int
189 original_rows: int
190 waited: bool = False
191
192 def wait(self) -> CSA2CacheTensor:
193 """Wait once and return the compacted cache in rank order."""
194 if self.waited:
195 raise RuntimeError("a packed bank gather handle cannot be waited twice")
196 self.waited = True
197 return _PackedBankGather.apply(
198 self.cache, self.work, self.output, self.slots, self.group,
199 self.world_size, self.gather_dim, self.original_rows,
200 )
201
202
203def launch_packed_bank_gather(cache: CSA2CacheTensor, counts: tuple[int, ...] | None,
204 group: Any, world_size: int, gather_dim: int = 1) -> _AsyncPackedBankGather:
205 """Gather packed cache rows in rank order, padding uneven shards for transport.
206
207 Args:
208 cache: Producer's packed cache.
209 counts: Row count per rank, or None for equally sized shards.
210 group: Process group in sequence-shard order.
211 world_size: Number of ranks in the group.
212 gather_dim: Axis containing the rows to gather.
213 """
214 if counts is not None and len(counts) != world_size:
215 raise ValueError("packed bank gather owner counts must cover the CP group")
216 original_rows = cache.packed.shape[gather_dim]
217 send = cache.packed.movedim(gather_dim, 0).contiguous()
218 if counts is not None:
219 capacity = max(counts)
220 if send.shape[0] != capacity:
221 send = torch.cat((send, send.new_zeros((capacity - send.shape[0], *send.shape[1:]))), dim=0)
222 else:
223 capacity = original_rows
224 output = send.new_empty((capacity * world_size, *send.shape[1:]))
225 work = dist.all_gather_into_tensor(output, send, group=group, async_op=True)
226 slots = _bank_slots(counts, cache.device) if counts is not None else None
227 return _AsyncPackedBankGather(cache, work, output, group, world_size, slots, gather_dim, original_rows)
228
229
230__all__ = ["launch_packed_sequence_dispatch", "launch_packed_bank_gather"]