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"""CSA2 parallel stages: bank exchange, Indexer dispatch and internal head SUM."""
16
17from __future__ import annotations
18
19from collections.abc import Callable
20from dataclasses import dataclass
21from functools import partial
22from typing import Any
23
24import torch
25import torch.distributed._functional_collectives as funcol
26
27from hyper_parallel.components.quantization.quantizers.csa2 import CSA2CacheQuantizer
28from hyper_parallel.components.quantization.tensor.csa2_cache_tensor import CSA2CacheTensor
29from hyper_parallel.core.activation_memory.api import checkpoint_exclude_wrapper
30from hyper_parallel.core.activation_memory.recompute_state import is_recomputing
31from hyper_parallel.core.utils.communication import differentiable_all_to_all_single
32from hyper_parallel.distributed.context_parallel.compressed_document import (
33 document_compression_plan, launch_compressed_bank,
34)
35from hyper_parallel.distributed.context_parallel.csa2_cache_transport import (
36 launch_packed_bank_gather, launch_packed_sequence_dispatch,
37)
38from hyper_parallel.distributed.context_parallel.indexer_balance import (
39 launch_indexer_inputs, resolve_indexer_balance_block_size, validate_indexer_hybrid_threshold,
40)
41from hyper_parallel.distributed.context_parallel.sequence_dispatch import (
42 async_sequence_dispatch, document_prefix_route, sliding_window_route,
43)
44from .compressed_sparse_attention2 import (
45 CSA2AttentionInputs, CSA2DocumentInputs,
46 SharedCompressedAttentionState, _apply_v41_rope,
47)
48from .compressor import CSA2Compressor
49from .document_layout import SharedCompressedPackedSequence
50from .indexer import CSA2Indexer, CSA2IndexerOutput
51from .quantize_compressed_sparse_attention2 import QuantizeCompressedSparseAttention2Module
52
53
54def _exchange_boundary(tensor: torch.Tensor, route: Any, context: Any) -> torch.Tensor:
55 """Complete projected boundary rows, including reverse participation for empty receives."""
56 if not route.needs_exchange:
57 return tensor
58 local = tensor.movedim(1, 0).contiguous()
59 parts = [local.narrow(0, offset, count)
60 for offset, count in zip(route.send_offsets, route.input_splits) if count]
61 send = torch.cat(parts, dim=0) if parts else local[:0]
62 received = differentiable_all_to_all_single(
63 send, list(route.input_splits), list(route.output_splits), group=context.mesh.get_group(),
64 )
65 return torch.cat((received, local), dim=0).movedim(0, 1).contiguous()
66
67
68class _CPCompressor(CSA2Compressor):
69 """Keep projection and boundary exchange inside the managed compressor call."""
70
71 cp_context = None
72
73 @classmethod
74 def from_module(cls, module: CSA2Compressor) -> _CPCompressor:
75 """Adopt children by identity without initializing another parameter tree."""
76 result = object.__new__(cls)
77 torch.nn.Module.__init__(result) # pylint: disable=unnecessary-dunder-call
78 for name, child in module.named_children():
79 result.add_module(name, child)
80 for name, parameter in module._parameters.items(): # pylint: disable=protected-access
81 result.register_parameter(name, parameter)
82 # PyTorch has no public getter for buffer persistence, including None buffers.
83 non_persistent_buffers = module._non_persistent_buffers_set # pylint: disable=protected-access
84 for name, buffer in module._buffers.items(): # pylint: disable=protected-access
85 result.register_buffer(name, buffer, persistent=name not in non_persistent_buffers)
86 result.compress_ratio = module.compress_ratio
87 result.apply_rope = module.apply_rope
88 result.training = module.training
89 return result
90
91 def exchange_blocks(self, projected: torch.Tensor, block_plan: Any) -> torch.Tensor:
92 """Exchange only the missing projected rows for locally owned compression blocks."""
93 return _exchange_boundary(projected, block_plan.route, self.cp_context)
94
95
96@dataclass
97class _MainAttentionWork:
98 """Main KV submission and query work executed after the Index K submission."""
99
100 query_residual: torch.Tensor
101 cos: torch.Tensor
102 sin: torch.Tensor
103 launch_main_bank: Callable[[], Any] | None
104 compressed_handle: Any = None
105 query: torch.Tensor | None = None
106
107
108@dataclass
109class _PendingAttention:
110 """Per-call communication receipts, never stored in cross-layer shared state."""
111
112 query: torch.Tensor
113 raw_handle: Any
114 compressed_handle: Any
115 indexer_output: Any
116 raw_offset: int
117 main_offset: int
118
119
120class _CPIndexer(CSA2Indexer):
121 """Schedule shared keys and no-grad qr/TopK while Indexer weights remain resident."""
122
123 cp_context = None
124 balance_mode = "none"
125 balance_block_size = None
126 zigzag_min_length = None
127 _input_region = None
128 _result_region = None
129 _wait_region = None
130
131 def prepare_key(self, latent: torch.Tensor | None, cos: torch.Tensor, sin: torch.Tensor,
132 index_key: torch.Tensor | None, block_plan: Any, key_position_embeddings: tuple | None) -> Any:
133 """Submit Full-layer K; Reindex reuses the already differentiable shared bank."""
134 key = self._project_index_key(latent, cos, sin, index_key, key_position_embeddings)
135 if not self.owns_key:
136 return key
137 if self._qk_policy is not None:
138 key = CSA2CacheQuantizer("indexer_k").quantize(key)
139 if isinstance(key, CSA2CacheTensor):
140 group = self.cp_context.mesh.get_group()
141 counts = None if block_plan is None else block_plan.counts
142 return launch_packed_bank_gather(key, counts, group, self.cp_context.size)
143 launch = self._launch_bank
144 return launch(key, 1) if block_plan is None else launch_compressed_bank(key, block_plan.counts, launch)
145
146 def _launch_bank(self, tensor: torch.Tensor, dim: int) -> Any:
147 """Borrow the framework's differentiable asynchronous sequence gather."""
148 return self.cp_context.launch_gather_sequence(tensor, dim=dim).collective
149
150 def exchange_key(self, prepared: Any) -> torch.Tensor:
151 """Wait only when the local/worker selection consumes Index K."""
152 return prepared if isinstance(prepared, torch.Tensor) else prepared.wait()
153
154 def forward(
155 self, hidden_states: torch.Tensor, query_residual: torch.Tensor, latent: torch.Tensor | None,
156 compress_position_embeddings: tuple[torch.Tensor, torch.Tensor], *,
157 index_key: torch.Tensor | None = None, candidate_blocks: torch.Tensor | None = None,
158 reduce_sum: Callable | None = None, query_offset: int = 0,
159 minimum_key_indices: torch.Tensor | None = None, query_segments: tuple | None = None,
160 document_lengths: tuple[int, ...] = (), prepare_attention: Callable | None = None,
161 block_plan: Any = None, key_position_embeddings: tuple | None = None,
162 causal_upper: torch.Tensor | None = None,
163 ) -> CSA2IndexerOutput:
164 """Reuse local math or dispatch only the discrete selection workload."""
165 if self.balance_mode == "none":
166 return super().forward(
167 hidden_states, query_residual, latent, compress_position_embeddings,
168 index_key=index_key, candidate_blocks=candidate_blocks, reduce_sum=reduce_sum,
169 query_offset=query_offset, minimum_key_indices=minimum_key_indices,
170 query_segments=query_segments, document_lengths=document_lengths,
171 prepare_attention=prepare_attention, block_plan=block_plan,
172 key_position_embeddings=key_position_embeddings, causal_upper=causal_upper,
173 )
174 if reduce_sum is not None or self.is_candidate_source or self.uses_candidates:
175 raise NotImplementedError("Indexer overlap requires ordinary causal selection and TP=1")
176 cos, sin = compress_position_embeddings
177 weights = self.weights_proj(hidden_states.detach())
178 weights = weights * (self.head_dim**-0.5 * self.global_num_heads**-0.5)
179 launch = self._launch_selection if self._input_region is None else self._input_region
180 wave = launch(query_residual, weights, (cos, sin), document_lengths)
181 prepared_key = self.prepare_key(latent, cos, sin, index_key, block_plan, key_position_embeddings)
182 if prepare_attention is not None:
183 prepare_attention()
184 prepared = self._prepare_dispatched(wave)
185 key = self.exchange_key(prepared_key)
186 # Recompute must preserve the first-pass cache for later consumers.
187 index_key_cache = None
188 if isinstance(key, CSA2CacheTensor):
189 index_key_cache = key
190 key = CSA2CacheQuantizer.dequantize(key)
191 select = self._select_dispatched if self._result_region is None else self._result_region
192 result = select(prepared, key)
193 del prepared
194 query = self._project_index_query(query_residual, cos, sin)
195 if weights.shape[-1] != query.shape[2]:
196 raise ValueError("Indexer query and merge weights must have matching head counts")
197 finish = self._finish_selection if self._wait_region is None else self._wait_region
198 return CSA2IndexerOutput(finish(result), key, None, query, weights, index_key_cache=index_key_cache)
199
200 def enable_selection_exclude(self) -> None:
201 """Reuse input/selection/result transfers instead of waiting on consumed handles."""
202 super().enable_selection_exclude()
203 object.__setattr__(self, "_input_region", checkpoint_exclude_wrapper(self._launch_selection))
204 object.__setattr__(self, "_result_region", checkpoint_exclude_wrapper(self._select_dispatched))
205 object.__setattr__(self, "_wait_region", checkpoint_exclude_wrapper(self._finish_selection))
206
207 @torch.no_grad()
208 def _launch_selection(self, qr: torch.Tensor, weights: torch.Tensor, embeddings: tuple, lengths: tuple) -> Any:
209 """Use the existing task planner and dtype-preserving input transport."""
210 return launch_indexer_inputs(qr, weights, embeddings, lengths, self.compress_ratio, self.balance_mode,
211 self.cp_context.mesh.get_group(), self.balance_block_size, self.zigzag_min_length)
212
213 @torch.no_grad()
214 def _prepare_dispatched(self, wave: Any) -> tuple | None:
215 """Expand received qr once; cached selection needs no worker Q during replay."""
216 if is_recomputing() and self._result_region is not None:
217 # The result and final IDs are checkpoint exclusions. Do not retain expanded
218 # worker Q or consume an already finished input receipt during recomputation.
219 return None
220 qr, weights, cos, sin = wave.wait()
221 query = self._project_worker_index_query(qr, cos, sin, wave.owner_queries)
222 return query, weights, wave
223
224 @torch.no_grad()
225 def _select_dispatched(self, prepared: tuple, key: torch.Tensor) -> Any:
226 """Consume worker Q once and launch the inverse ID transfer."""
227 query, weights, wave = prepared
228 selected = self._select_indices(query, key, weights, None, 0, None, None, wave.route.segments)[0]
229 return wave.launch_result(selected[0])
230
231 @staticmethod
232 @torch.no_grad()
233 def _finish_selection(result: Any) -> torch.Tensor:
234 """Cache completed IDs; replay never consumes an already finished handle."""
235 return result.wait().unsqueeze(0)
236
237
238def sum_head_scores(tensor: torch.Tensor, *, group: Any) -> torch.Tensor:
239 """Sum TP head contributions before Top-K selection and KL normalization."""
240 return funcol.all_reduce(tensor.contiguous(), "sum", group)
241
242
243class _TPCompressedSparseAttention2(QuantizeCompressedSparseAttention2Module):
244 """Only internal head SUM; framework boundaries own input/output TP and SP."""
245
246 _parallel_bound = False
247 _head_sum = None
248
249 def bind_parallel(self, binding: Any) -> None:
250 """Borrow the existing TP group without installing another TP executor."""
251 if self._parallel_bound:
252 raise ValueError("CSA2 parallel resources are already bound")
253 if getattr(binding.mesh_binding.mesh_context, "tp_size", 1) > 1:
254 mesh = binding.mesh_binding.axis_mesh("tp")
255 self._head_sum = partial(sum_head_scores, group=mesh.get_group())
256 self._parallel_bound = True
257
258 def head_reducer(self) -> Callable | None:
259 """Provide head SUM before TopK and KL normalization."""
260 return self._head_sum
261
262 def query_partition(self, sequence_length: int, position_ids: torch.Tensor) -> tuple[int, int]:
263 """Require binding for a selected parallel member before any model computation."""
264 if not self._parallel_bound:
265 raise RuntimeError("parallel CSA2 must be bound through the family mesh before forward")
266 return super().query_partition(sequence_length, position_ids)
267
268
269class CPCompressedSparseAttention2(_TPCompressedSparseAttention2):
270 """Own CP preparation/exchange stages while inheriting the complete local forward."""
271
272 cp_context = None
273
274 def __init__(self, module: torch.nn.Module | None = None, *, config: Any = None, layer_idx: int = 0,
275 replace_indexer: bool = True, use_fused_ops: bool = False,
276 indexer_load_balance: str = "none", main_kv_comm: str = "all_gather",
277 indexer_balance_block_size: int | None = None, indexer_zigzag_min_length: int | None = None,
278 low_precision: Any = None) -> None:
279 """Adopt mathematical children and choose CP stages without creating parameters."""
280 indexer_balance_block_size = resolve_indexer_balance_block_size(
281 indexer_load_balance, indexer_balance_block_size,
282 )
283 validate_indexer_hybrid_threshold(indexer_load_balance, indexer_zigzag_min_length)
284 if main_kv_comm not in ("all_gather", "all_to_all_v"):
285 raise ValueError("main_kv_comm must be 'all_gather' or 'all_to_all_v'")
286 super().__init__(module, config=config, layer_idx=layer_idx,
287 replace_indexer=replace_indexer, use_fused_ops=use_fused_ops,
288 low_precision=low_precision)
289 self.indexer_load_balance = indexer_load_balance
290 self.main_kv_comm = main_kv_comm
291 self.indexer_balance_block_size = indexer_balance_block_size
292 self.indexer_zigzag_min_length = indexer_zigzag_min_length
293 if self.is_index_source:
294 self.indexer = _CPIndexer(self.indexer, apply_rope=_apply_v41_rope)
295 self.indexer.balance_mode = indexer_load_balance
296 self.indexer.balance_block_size = indexer_balance_block_size
297 self.indexer.zigzag_min_length = indexer_zigzag_min_length
298 if self.is_kv_source and isinstance(getattr(self, "compressor", None), CSA2Compressor):
299 self.compressor = _CPCompressor.from_module(self.compressor)
300
301 def bind_parallel(self, binding: Any) -> None:
302 """Bind all stages to the framework-owned CP context and optional TP group."""
303 if (binding.cp_context is None or binding.cp_context.size <= 1
304 or not 0 <= binding.cp_context.rank < binding.cp_context.size):
305 raise ValueError("CP CSA2 requires an existing CP context with size > 1 and 0 <= rank < size")
306 super().bind_parallel(binding)
307 self.cp_context = binding.cp_context
308 if self.is_index_source:
309 self.indexer.cp_context = self.cp_context
310 if isinstance(getattr(self, "compressor", None), _CPCompressor):
311 self.compressor.cp_context = self.cp_context
312
313 def query_partition(self, sequence_length: int, position_ids: torch.Tensor) -> tuple[int, int]:
314 """Derive packed row addresses independently of RoPE position IDs."""
315 del position_ids # Position values are already encoded in the supplied RoPE embeddings.
316 if self.cp_context is None:
317 raise RuntimeError("CP CSA2 must be bound through the family mesh before forward")
318 offset = self.cp_context.rank * sequence_length
319 return offset, sequence_length * self.cp_context.size
320
321 def prepare_compression(self, document: CSA2DocumentInputs, embeddings: dict,
322 device: torch.device) -> tuple:
323 """Plan owner blocks and explicitly complete block-start position metadata."""
324 if not self.is_kv_source or self.compress_ratio <= 1:
325 return None, None
326 size, rank = self.cp_context.size, self.cp_context.rank
327 local_length = document.global_length // size
328 packed = document.packed
329 boundaries = (0, document.global_length) if packed is None else packed.document_boundaries()
330 if local_length % self.compress_ratio == 0 and all(value % self.compress_ratio == 0 for value in boundaries):
331 return None, None
332 if packed is None:
333 packed = SharedCompressedPackedSequence(torch.tensor(boundaries), rank * local_length,
334 local_length, document.global_length)
335 packed = packed.prepare(device, (self.compress_ratio,))
336 plan = document_compression_plan(boundaries, self.compress_ratio, local_length, size, rank)
337 source_positions = embeddings["compress"]
338 positions = packed.cached_compressed_positions(plan.ratio, source_positions)
339 if positions is None:
340 exchanged = _exchange_boundary(torch.cat(source_positions, dim=-1), plan.route, self.cp_context)
341 rows = plan.indices(device)[1]
342 positions = exchanged.index_select(1, rows).chunk(2, dim=-1)
343 packed.cache_compressed_positions(plan.ratio, source_positions, positions)
344 return plan, positions
345
346 def launch_bank(self, tensor: torch.Tensor, sequence_dim: int) -> Any:
347 """Launch a differentiable rank-ordered gather through CPContext."""
348 return self.cp_context.launch_gather_sequence(tensor, dim=sequence_dim).collective
349
350 def exchange_raw(self, tensor: torch.Tensor, sequence_dim: int, route: Any) -> Any:
351 """Launch the same-document raw SWA halo."""
352 if isinstance(tensor, CSA2CacheTensor):
353 return launch_packed_sequence_dispatch(tensor, sequence_dim, route,
354 self.cp_context.mesh.get_group())
355 return async_sequence_dispatch(tensor, sequence_dim, route, self.cp_context.mesh.get_group())
356
357 def exchange_main(self, tensor: torch.Tensor, sequence_dim: int, route: Any) -> Any:
358 """Launch the main compressed document prefix."""
359 if isinstance(tensor, CSA2CacheTensor):
360 return launch_packed_sequence_dispatch(tensor, sequence_dim, route,
361 self.cp_context.mesh.get_group())
362 return async_sequence_dispatch(tensor, sequence_dim, route, self.cp_context.mesh.get_group())
363
364 def _launch_compressed_bank(self, compressed: torch.Tensor, route: Any, plan: Any) -> Any:
365 """Respect the compressed bank's actual owner counts and physical layout."""
366 if isinstance(compressed, CSA2CacheTensor):
367 group = self.cp_context.mesh.get_group()
368 if route is not None:
369 return self.exchange_main(compressed, 1, route)
370 counts = None if plan is None else plan.counts
371 return launch_packed_bank_gather(compressed, counts, group, self.cp_context.size)
372 if route is not None:
373 return self.exchange_main(compressed, 1, route)
374 if plan is not None:
375 return launch_compressed_bank(compressed, plan.counts, self.launch_bank)
376 return self.launch_bank(compressed, 1)
377
378 def prepare_attention(self, work: _MainAttentionWork) -> None:
379 """Submit delayed main KV behind Index K, then compute the main query."""
380 if work.launch_main_bank is not None:
381 work.compressed_handle = work.launch_main_bank()
382 work.launch_main_bank = None
383 work.query = self._expand_query(work.query_residual, work.cos, work.sin)
384
385 def prepare_attention_inputs(self, hidden_states: torch.Tensor, embeddings: dict,
386 shared_state: SharedCompressedAttentionState,
387 document: CSA2DocumentInputs) -> _PendingAttention:
388 """Retain the original Full/Reindex launch order and owner/worker projection windows."""
389 plan, key_positions = self.prepare_compression(document, embeddings, hidden_states.device)
390 length = hidden_states.shape[1]
391 context = self.cp_context
392 boundaries = ((0, document.global_length) if document.packed is None
393 else document.packed.document_boundaries())
394 raw_route = sliding_window_route(boundaries, length, context.size, context.rank, self.sliding_window)
395 main_route = (document_prefix_route(boundaries, length, context.size, context.rank, self.compress_ratio)
396 if self.compress_ratio and self.main_kv_comm == "all_to_all_v" else None)
397 lengths = tuple(end - start for start, end in zip(boundaries, boundaries[1:]))
398 cos, sin = embeddings["compress" if self.compress_ratio else "main"]
399 raw = self._project_raw_kv(hidden_states, cos, sin)
400 raw_handle = self.exchange_raw(raw, 2, raw_route)
401 if self.is_index_source:
402 qr = self.q_a_norm(self.q_a_proj(hidden_states))
403 query = None
404 else:
405 qr, query = self._project_query(hidden_states, cos, sin)
406 latent, compressed = self.compress_key_value(hidden_states, embeddings, plan, key_positions)
407 if compressed is not None:
408 compressed = self._apply_main_kv_qat(compressed)
409 launch_main = (None if compressed is None
410 else partial(self._launch_compressed_bank, compressed, main_route, plan))
411 work = _MainAttentionWork(qr, cos, sin, launch_main) if self.is_index_source else None
412 compressed_handle = launch_main() if work is None and launch_main is not None else None
413 indexed = self._run_indexer(
414 hidden_states, qr, latent, embeddings, shared_state, document, lengths,
415 block_plan=plan, key_position_embeddings=key_positions,
416 prepare_attention=partial(self.prepare_attention, work) if work is not None else None,
417 )
418 if work is not None:
419 query, compressed_handle = work.query, work.compressed_handle
420 return _PendingAttention(query, raw_handle, compressed_handle, indexed, raw_route.global_start,
421 0 if main_route is None else main_route.global_start)
422
423 def exchange_attention(self, prepared: _PendingAttention,
424 shared_state: SharedCompressedAttentionState) -> CSA2AttentionInputs:
425 """Resolve banks only when the owner teacher and sparse attention can consume them."""
426 raw = prepared.raw_handle.wait()
427 if prepared.compressed_handle is not None:
428 compressed = prepared.compressed_handle.wait()
429 self._publish_compressed_kv(shared_state, compressed, prepared.main_offset)
430 return CSA2AttentionInputs(prepared.query, raw, prepared.indexer_output, prepared.raw_offset)