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"""Complete local CSA2 math and shared forward stages."""
16
17from __future__ import annotations
18
19from collections.abc import Callable
20from dataclasses import dataclass, field
21from typing import Any
22
23import torch
24from torch import nn
25
26from hyper_parallel.components.losses.aux_loss import aux_loss_auto_scale
27from hyper_parallel.components.functional.sparse_flash_mla import (
28 supports_fused_attention_inputs, sparse_flash_mla,
29)
30from hyper_parallel.components.modules.common.rms_norm import RMSNorm
31from hyper_parallel.components.quantization.quantizers.csa2 import CSA2CacheQuantizer
32from hyper_parallel.components.quantization.tensor.csa2_cache_tensor import CSA2CacheTensor
33from hyper_parallel.core.activation_memory.recompute_state import is_recomputing
34from .compressor import CSA2Compressor
35from .document_layout import SharedCompressedPackedSequence
36from .indexer import CSA2Indexer
37from .indexer_kl_loss import shared_compressed_indexer_kl_loss
38
39
40def _rotate_half(tensor: torch.Tensor) -> torch.Tensor:
41 """Rotate adjacent real/imaginary pairs for V4 interleaved RoPE."""
42 first, second = tensor.unflatten(-1, (-1, 2)).unbind(-1)
43 return torch.stack((-second, first), dim=-1).flatten(-2)
44
45
46def _apply_v41_rope(
47 tensor: torch.Tensor,
48 cos: torch.Tensor,
49 sin: torch.Tensor,
50 unsqueeze_dim: int = 1,
51) -> torch.Tensor:
52 """Apply V4 interleaved RoPE to the trailing rotary channels."""
53 cos = cos.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
54 sin = sin.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
55 rope_dim = cos.shape[-1]
56 pass_through, rotary = tensor.split((tensor.shape[-1] - rope_dim, rope_dim), dim=-1)
57 rotary = ((rotary.float() * cos) + (_rotate_half(rotary).float() * sin)).to(tensor.dtype)
58 return torch.cat((pass_through, rotary), dim=-1) if pass_through.shape[-1] else rotary
59
60
61@dataclass
62class SharedCompressedAttentionState:
63 """Autograd-bearing CSA2 state scoped to one training forward.
64
65 State is addressed by the layer that produced it instead of using one
66 mutable "latest value" slot. This matters for the released V4.1 topology,
67 which has several Full/Reindex groups, and makes a consumer's dependency
68 explicit when activation recomputation revisits modules out of forward
69 order.
70
71 Publication returns False during replay without replacing an entry.
72 Validation observes actual publications through that result.
73
74 Nothing drops an entry early. The state travels into every layer as one of
75 the checkpoint region's inputs, so the graph keeps it alive from the forward
76 pass to the end of backward, and a layer whose forward is recomputed reads
77 its entries a second time there. A published entry therefore has to stay
78 readable until backward is done with every consumer, which is also why the
79 publishers skip their write while recomputing.
80 """
81
82 compressed_kv_by_source: dict[int, torch.Tensor] = field(default_factory=dict)
83 index_key_by_source: dict[int, torch.Tensor] = field(default_factory=dict)
84 topk_indices_by_source: dict[int, torch.Tensor] = field(default_factory=dict)
85 candidate_blocks_by_source: dict[int, torch.Tensor] = field(default_factory=dict)
86 compressed_kv_offsets: dict[int, int] = field(default_factory=dict)
87
88 @staticmethod
89 def _require(
90 values: dict[int, torch.Tensor],
91 source_layer: int | None,
92 value_name: str,
93 consumer_layer: int,
94 ) -> torch.Tensor:
95 """Return one published tensor or report the broken layer dependency."""
96 if source_layer is None or source_layer not in values:
97 raise RuntimeError(
98 f"layer {consumer_layer} requires {value_name} from source "
99 f"layer {source_layer}, but that source has not run in this forward"
100 )
101 return values[source_layer]
102
103 def publish_compressed_kv(self, source_layer: int, value: torch.Tensor, key_offset: int = 0) -> bool:
104 """Publish compressed K=V and its global origin, preserving the autograd graph."""
105 if is_recomputing():
106 return False
107 self.compressed_kv_by_source[source_layer] = value
108 self.compressed_kv_offsets[source_layer] = key_offset
109 return True
110
111 def require_compressed_kv(self, source_layer: int | None, consumer_layer: int) -> torch.Tensor:
112 """Read compressed K=V from the consumer's configured Full layer."""
113 return self._require(
114 self.compressed_kv_by_source,
115 source_layer,
116 "compressed K=V",
117 consumer_layer,
118 )
119
120 def publish_index_key(self, source_layer: int, value: torch.Tensor) -> bool:
121 """Publish the Full Indexer's shared key tensor."""
122 if is_recomputing():
123 return False
124 self.index_key_by_source[source_layer] = value
125 return True
126
127 def require_index_key(self, source_layer: int | None, consumer_layer: int) -> torch.Tensor:
128 """Read the Indexer key associated with a compressed-KV source."""
129 return self._require(
130 self.index_key_by_source,
131 source_layer,
132 "Indexer key",
133 consumer_layer,
134 )
135
136 def publish_topk_indices(self, source_layer: int, value: torch.Tensor) -> bool:
137 """Publish one Full/Reindex layer's token selection."""
138 if is_recomputing():
139 return False
140 self.topk_indices_by_source[source_layer] = value
141 return True
142
143 def require_topk_indices(self, source_layer: int | None, consumer_layer: int) -> torch.Tensor:
144 """Read the latest configured Full/Reindex selection."""
145 return self._require(
146 self.topk_indices_by_source,
147 source_layer,
148 "Top-K indices",
149 consumer_layer,
150 )
151
152 def publish_candidate_blocks(self, source_layer: int, value: torch.Tensor) -> bool:
153 """Publish hierarchical candidate blocks from the configured source."""
154 if is_recomputing():
155 return False
156 self.candidate_blocks_by_source[source_layer] = value
157 return True
158
159 def require_candidate_blocks(
160 self,
161 source_layer: int | None,
162 consumer_layer: int,
163 ) -> torch.Tensor:
164 """Read hierarchical candidates for a later Reindex layer."""
165 return self._require(
166 self.candidate_blocks_by_source,
167 source_layer,
168 "candidate blocks",
169 consumer_layer,
170 )
171
172
173@dataclass(frozen=True)
174class CSA2DocumentInputs:
175 """Ready document coordinates shared by reference and fused execution."""
176
177 packed: SharedCompressedPackedSequence | None
178 query_offset: int
179 global_length: int
180 segment_starts: torch.Tensor | None
181 minimum_key_indices: torch.Tensor | None
182 query_segments: tuple | None
183 causal_upper: torch.Tensor | None
184 raw_document_starts: tuple
185 global_key_length: int
186
187
188@dataclass
189class CSA2AttentionInputs:
190 """Ready operands at the shared attention consumer boundary."""
191
192 query: torch.Tensor
193 key_value: torch.Tensor
194 indexer_output: Any = None
195 raw_key_offset: int = 0
196
197
198def build_sliding_window_indices(
199 batch_size: int,
200 sequence_length: int,
201 window_size: int,
202 device: torch.device,
203 *,
204 query_offset: int = 0,
205 key_length: int | None = None,
206) -> torch.Tensor:
207 """Build fixed-width causal sliding-window indices."""
208 if key_length is None:
209 key_length = sequence_length
210 width = min(key_length, window_size)
211 query = torch.arange(
212 query_offset,
213 query_offset + sequence_length,
214 device=device,
215 ).unsqueeze(-1)
216 offsets = torch.arange(width - 1, -1, -1, device=device)
217 indices = query - offsets
218 indices = indices.masked_fill(indices < 0, -1)
219 return indices.unsqueeze(0).expand(batch_size, -1, -1)
220
221
222def reference_sparse_attention(
223 query: torch.Tensor,
224 key_value: torch.Tensor,
225 sparse_indices: torch.Tensor,
226 sinks: torch.Tensor,
227 scale: float,
228) -> torch.Tensor:
229 """Compute sink attention with eager Torch operations on any device.
230
231 Args:
232 query: Main queries [batch, heads, local queries, head dimension].
233 key_value: Shared K=V bank [batch, 1, keys, head dimension].
234 sparse_indices: Visible bank IDs [batch, local queries, selections];
235 negative entries are padding and repeated IDs count only once.
236 sinks: Learnable scalar sink logits [heads], with zero-valued output.
237 scale: Main attention logit scale.
238
239 Returns:
240 Attention values [batch, local queries, heads, head dimension].
241 Softmax uses FP32; matrix multiplications retain the input precision.
242
243 Note:
244 This reference materializes a dense query/key mask and scores. It is
245 intended for explicit unfused comparisons, not long-sequence efficiency.
246 """
247 batch_size, num_heads, sequence_length, _ = query.shape
248 key_length = key_value.shape[2]
249 valid = sparse_indices >= 0
250 safe_indices = sparse_indices.clamp_min(0).long()
251 allowed_counts = torch.zeros(
252 batch_size,
253 sequence_length,
254 key_length,
255 dtype=torch.int32,
256 device=query.device,
257 )
258 allowed_counts.scatter_add_(2, safe_indices, valid.to(torch.int32))
259 allowed = allowed_counts > 0
260 logits = torch.matmul(query, key_value.transpose(-1, -2)) * scale
261 logits = logits.masked_fill(~allowed.unsqueeze(1), float("-inf"))
262 sink_logits = sinks.view(1, num_heads, 1, 1).expand(batch_size, -1, sequence_length, -1)
263 probabilities = torch.cat((logits, sink_logits), dim=-1).softmax(dim=-1, dtype=torch.float32)
264 return torch.matmul(probabilities[..., :-1].to(key_value.dtype), key_value).transpose(1, 2)
265
266
267def _build_parameters(config: Any, layer_idx: int) -> nn.Module:
268 """Create the canonical V4.1 parameter tree without importing the model."""
269 # Transformers provides V4 parameter classes; CSA2 owns the V4.1 math below.
270 # Preserve their construction order so seeded initialization stays compatible.
271 # pylint: disable-next=import-outside-toplevel
272 from transformers.models.deepseek_v4.modeling_deepseek_v4 import DeepseekV4Attention
273
274 module = DeepseekV4Attention(config, layer_idx)
275 module.q_a_norm = RMSNorm(module=module.q_a_norm)
276 module.kv_norm = RMSNorm(module=module.kv_norm)
277 # DeepSeek-V4 applies this unweighted RMSNorm after q_b_proj. V4.1
278 # explicitly removes it: q_norm remains between wq_a and wq_b, while
279 # the projected query heads go directly into RoPE.
280 del module.q_b_norm
281 module.compress_ratio = int(config.v41_compress_ratios[layer_idx])
282 module.is_kv_source = layer_idx in config.v41_kv_source_layer_ids
283 module.is_index_source = layer_idx in config.v41_index_source_layer_ids
284 kv_sources = [source for source in config.v41_kv_source_layer_ids if source <= layer_idx]
285 index_sources = [source for source in config.v41_index_source_layer_ids if source <= layer_idx]
286 module.kv_source_layer_idx = max(kv_sources, default=None)
287 module.index_source_layer_idx = max(index_sources, default=None)
288 candidate_source = int(getattr(config, "v41_candidate_source_layer_id", -1))
289 module.candidate_source_layer_idx = (
290 candidate_source if 0 <= candidate_source <= layer_idx else None
291 )
292 if module.is_kv_source:
293 module.compressor = CSA2Compressor(config, module.compress_ratio, apply_rope=_apply_v41_rope)
294 if module.is_index_source:
295 module.indexer = CSA2Indexer(
296 config=config, compress_ratio=module.compress_ratio, layer_idx=layer_idx, apply_rope=_apply_v41_rope,
297 )
298
299 return module
300
301
302class CompressedSparseAttention2Module(nn.Module):
303 """Complete CSA2 algorithm with local preparation and identity exchange stages."""
304
305 def __init__(
306 self,
307 module: nn.Module | None = None,
308 *,
309 config: Any = None,
310 layer_idx: int = 0,
311 replace_indexer: bool = True,
312 use_fused_ops: bool = False,
313 ) -> None:
314 """Create from config or adopt a source module without replacing its parameters."""
315 if (module is None) == (config is None):
316 raise ValueError("CSA2 requires exactly one of config or module")
317 if not isinstance(use_fused_ops, bool):
318 raise ValueError("use_fused_ops must be a bool")
319 if module is None:
320 module = _build_parameters(config, layer_idx)
321 super().__init__()
322 for name, child in module._modules.items(): # pylint: disable=protected-access
323 self.add_module(name, child)
324 for name, parameter in module._parameters.items(): # pylint: disable=protected-access
325 self.register_parameter(name, parameter)
326 for name, buffer in module._buffers.items(): # pylint: disable=protected-access
327 self.register_buffer(name, buffer, persistent=name not in module._non_persistent_buffers_set)
328 indexer = getattr(self, "indexer", None)
329 if (
330 replace_indexer
331 and indexer is not None
332 and not isinstance(indexer, CSA2Indexer)
333 ):
334 self.indexer = CSA2Indexer(indexer, apply_rope=_apply_v41_rope)
335 self.config = module.config
336 self.layer_idx = module.layer_idx
337 self.num_heads = module.num_heads
338 self.num_key_value_groups = module.num_key_value_groups
339 self.num_groups = module.config.o_groups
340 self.compress_ratio = module.compress_ratio
341 self.is_kv_source = module.is_kv_source
342 self.is_index_source = module.is_index_source
343 self.kv_source_layer_idx = module.kv_source_layer_idx
344 self.index_source_layer_idx = module.index_source_layer_idx
345 self.candidate_source_layer_idx = module.candidate_source_layer_idx
346 self.head_dim = module.head_dim
347 self.rope_head_dim = module.config.qk_rope_head_dim
348 self.sliding_window = module.sliding_window
349 self.scaling = module.scaling
350 self.use_fused_ops = use_fused_ops
351 if self.is_index_source:
352 self.indexer.use_fused = use_fused_ops
353 # Children are adopted by identity; preserve their individual training modes.
354 self.training = module.training
355
356 def head_reducer(self) -> Callable | None:
357 """Keep local head sums; parallel members provide the complete-head reduction."""
358 return None
359
360 def query_partition(self, sequence_length: int, position_ids: torch.Tensor) -> tuple[int, int]:
361 """Return the complete local sequence coordinates."""
362 del position_ids
363 return 0, sequence_length
364
365 def _apply_swa_kv_qat(self, key_value: torch.Tensor) -> torch.Tensor:
366 """Return unquantized SWA KV for the base implementation."""
367 return key_value
368
369 def _apply_main_kv_qat(self, compressed: torch.Tensor) -> torch.Tensor:
370 """Return unquantized Main KV for the base implementation."""
371 return compressed
372
373 def _project_raw_kv(self, hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
374 """Project and rotate the local raw K=V rows."""
375 key_value = self.kv_norm(self.kv_proj(hidden_states)).unsqueeze(1)
376 return self._apply_swa_kv_qat(_apply_v41_rope(key_value, cos, sin))
377
378 def _project_query(
379 self,
380 hidden_states: torch.Tensor,
381 cos: torch.Tensor,
382 sin: torch.Tensor,
383 ) -> tuple[torch.Tensor, torch.Tensor]:
384 """Project and normalize the local query heads."""
385 query_residual = self.q_a_norm(self.q_a_proj(hidden_states))
386 return query_residual, self._expand_query(query_residual, cos, sin)
387
388 def _expand_query(self, query_residual: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
389 """Expand main heads after low-rank query inputs have been dispatched."""
390 query = self.q_b_proj(query_residual).view(*query_residual.shape[:2], -1, self.head_dim)
391 # Preserve sequence-major storage for sparse attention while keeping the head-major API.
392 return _apply_v41_rope(query, cos, sin, unsqueeze_dim=2).transpose(1, 2)
393
394 def _validate_forward_inputs(
395 self,
396 hidden_states: torch.Tensor,
397 attention_mask: torch.Tensor | None,
398 past_key_values: Any | None,
399 kwargs: dict[str, Any],
400 ) -> tuple[SharedCompressedAttentionState, SharedCompressedPackedSequence | None, int, int]:
401 """Pop and validate the shared-attention keyword arguments."""
402 if past_key_values is not None:
403 raise NotImplementedError("shared compressed DSA training does not support KV cache")
404 shared_state = kwargs.pop("shared_attention_state", None)
405 if not isinstance(shared_state, SharedCompressedAttentionState):
406 raise ValueError("shared_attention_state is required for shared compressed DSA")
407 if attention_mask is not None:
408 raise NotImplementedError(
409 "shared compressed DSA consumes compact packed_seq_params instead of a dense mask"
410 )
411 batch_size, sequence_length, _ = hidden_states.shape
412 packed_sequence = kwargs.pop("packed_seq_params", None)
413 if packed_sequence is not None and not isinstance(
414 packed_sequence, SharedCompressedPackedSequence
415 ):
416 raise TypeError(
417 "packed_seq_params must be SharedCompressedPackedSequence, "
418 f"got {type(packed_sequence).__name__}"
419 )
420 if "shared_attention_cp_context" in kwargs or "shared_attention_tp_context" in kwargs:
421 raise ValueError("CSA2 parallel resources must be bound through its family, not forward kwargs")
422 return shared_state, packed_sequence, batch_size, sequence_length
423
424 def _resolve_packed_segments(
425 self,
426 packed_sequence: "SharedCompressedPackedSequence | None",
427 batch_size: int,
428 sequence_length: int,
429 query_offset: int,
430 global_sequence_length: int,
431 device: torch.device,
432 ) -> tuple[torch.Tensor | None, torch.Tensor | None, tuple, torch.Tensor | None]:
433 """Validate packed document boundaries and derive local Q/K geometry.
434
435 Both execution modes consume the same per-token tensors: document
436 starts, per-query compressed-key minima and the packed causal upper
437 bound. Python ``query_segments`` stay available for the eager fused
438 kernels only; graph packing inputs never carry them.
439 """
440 segment_starts = None
441 minimum_key_indices = None
442 causal_upper = None
443 ratio = max(1, self.compress_ratio)
444 raw_end = query_offset + sequence_length
445 query_segments = ((0, sequence_length, 0, raw_end // ratio, raw_end % ratio),)
446 if packed_sequence is not None:
447 if batch_size != 1:
448 raise ValueError("V4.1 compact packed attention currently requires micro_batch_size=1")
449 if (
450 packed_sequence.local_query_start != query_offset
451 or packed_sequence.local_query_length != sequence_length
452 or packed_sequence.global_sequence_length != global_sequence_length
453 ):
454 packed_shard = (
455 packed_sequence.local_query_start,
456 packed_sequence.local_query_length,
457 packed_sequence.global_sequence_length,
458 )
459 raise ValueError(
460 "packed sequence geometry does not match the local CP shard: "
461 f"packed={packed_shard}, "
462 f"attention={(query_offset, sequence_length, global_sequence_length)}"
463 )
464 prepared = packed_sequence.prepare(device, (self.compress_ratio,))
465 segment_starts = prepared.local_segment_starts(device)
466 if self.compress_ratio:
467 minimum_key_indices = prepared.minimum_key_indices(device, self.compress_ratio)
468 causal_upper = prepared.causal_key_upper_bounds(device, self.compress_ratio)
469 if (self.candidate_source_layer_idx is not None
470 and not prepared.is_compression_aligned(ratio)):
471 raise ValueError("candidate-pool packed attention still requires compression-aligned documents")
472 query_segments = (
473 None if prepared._restored_from_packing_tensors # pylint: disable=protected-access
474 else prepared.indexer_segments(ratio)
475 )
476 return segment_starts, minimum_key_indices, query_segments, causal_upper
477
478 def prepare_document_inputs(self, hidden_states: torch.Tensor, position_ids: torch.Tensor,
479 packed: SharedCompressedPackedSequence | None) -> CSA2DocumentInputs:
480 """Prepare mathematical document bounds without launching communication."""
481 batch, length = hidden_states.shape[:2]
482 offset, global_length = self.query_partition(length, position_ids)
483 if packed is not None:
484 packed = packed.prepare(hidden_states.device, (self.compress_ratio,))
485 if self.use_fused_ops and packed._restored_from_packing_tensors: # pylint: disable=protected-access
486 raise NotImplementedError(
487 "fused DSA operators require Python document segments, not graph packing inputs"
488 )
489 starts, minima, segments, upper = self._resolve_packed_segments(
490 packed, batch, length, offset, global_length, hidden_states.device,
491 )
492 keys = (packed.compressed_key_length(self.compress_ratio) if packed is not None
493 else global_length // max(1, self.compress_ratio))
494 return CSA2DocumentInputs(packed, offset, global_length, starts, minima, segments, upper,
495 () if packed is None else packed.raw_document_starts(), keys)
496
497 def prepare_compression(self, document: CSA2DocumentInputs, embeddings: dict,
498 device: torch.device) -> tuple:
499 """Select complete local compression blocks and their original RoPE positions."""
500 if not self.is_kv_source or self.compress_ratio <= 1:
501 return None, None
502 packed = document.packed
503 if packed is None:
504 if document.global_length % self.compress_ratio == 0:
505 return None, None
506 packed = SharedCompressedPackedSequence(torch.tensor((0, document.global_length)),
507 0, document.global_length, document.global_length)
508 packed = packed.prepare(device, (self.compress_ratio,))
509 plan = packed.block_plan(self.compress_ratio)
510 positions = None if plan is None else packed.compressed_positions(plan, embeddings["compress"])
511 return plan, positions
512
513 def compress_key_value(self, hidden_states: torch.Tensor, embeddings: dict,
514 block_plan: Any, key_positions: tuple | None) -> tuple:
515 """Call the compressor through its managed module boundary."""
516 if not self.is_kv_source:
517 return None, None
518 if block_plan is None:
519 return self.compressor(hidden_states, embeddings["compress"])
520 return self.compressor(hidden_states, key_positions, block_plan)
521
522 def _publish_compressed_kv(
523 self, shared_state: SharedCompressedAttentionState, compressed: torch.Tensor,
524 main_offset: int = 0,
525 ) -> None:
526 """Publish Main KV once while retaining its first-pass autograd edge.
527
528 With low precision, CP producers pack before communication. Received
529 packed banks pass through the precision hook without another quantization.
530 Checkpoint replay retains the original shared bank until backward finishes.
531 """
532 if is_recomputing():
533 return
534 compressed = self._apply_main_kv_qat(compressed)
535 shared_state.publish_compressed_kv(self.layer_idx, compressed, main_offset)
536
537 def prepare_attention_inputs(self, hidden_states: torch.Tensor, embeddings: dict,
538 shared_state: SharedCompressedAttentionState,
539 document: CSA2DocumentInputs) -> CSA2AttentionInputs:
540 """Prepare ready local operands for the common attention forward."""
541 plan, key_positions = self.prepare_compression(document, embeddings, hidden_states.device)
542 cos, sin = embeddings["compress" if self.compress_ratio else "main"]
543 key_value = self._project_raw_kv(hidden_states, cos, sin)
544 qr, query = self._project_query(hidden_states, cos, sin)
545 latent, compressed = self.compress_key_value(hidden_states, embeddings, plan, key_positions)
546 if compressed is not None:
547 self._publish_compressed_kv(shared_state, compressed)
548 indexed = self._run_indexer(hidden_states, qr, latent, embeddings, shared_state, document,
549 block_plan=plan, key_position_embeddings=key_positions)
550 return CSA2AttentionInputs(query, key_value, indexed)
551
552 def exchange_attention(self, prepared: Any, shared_state: SharedCompressedAttentionState) -> CSA2AttentionInputs:
553 """Keep local ready operands; CP members wait at this consumer boundary."""
554 del shared_state
555 return prepared
556
557 def _run_indexer(
558 self,
559 hidden_states: torch.Tensor,
560 query_residual: torch.Tensor,
561 latent: torch.Tensor | None,
562 position_embeddings: dict[str, tuple[torch.Tensor, torch.Tensor]],
563 shared_state: "SharedCompressedAttentionState",
564 document: CSA2DocumentInputs,
565 document_lengths: tuple[int, ...] = (),
566 block_plan: Any = None,
567 key_position_embeddings: tuple | None = None,
568 prepare_attention: Callable[[], None] | None = None,
569 ) -> Any | None:
570 """Run the indexer on index-source layers and publish its forward outputs."""
571 if not self.is_index_source:
572 return None
573 index_key = (
574 None
575 if self.indexer.owns_key
576 else shared_state.require_index_key(self.kv_source_layer_idx, self.layer_idx)
577 )
578 candidate_blocks = (
579 shared_state.require_candidate_blocks(
580 self.candidate_source_layer_idx,
581 self.layer_idx,
582 )
583 if self.indexer.uses_candidates else None
584 )
585 indexer_output = self.indexer(
586 hidden_states,
587 query_residual,
588 latent,
589 position_embeddings["compress"],
590 prepare_attention=prepare_attention,
591 index_key=index_key,
592 candidate_blocks=candidate_blocks,
593 reduce_sum=self.head_reducer(),
594 query_offset=document.query_offset,
595 minimum_key_indices=document.minimum_key_indices,
596 query_segments=document.query_segments,
597 block_plan=block_plan,
598 key_position_embeddings=key_position_embeddings,
599 document_lengths=document_lengths,
600 causal_upper=document.causal_upper,
601 )
602 if self.indexer.owns_key:
603 shared_state.publish_index_key(
604 self.layer_idx,
605 indexer_output.index_key_cache if indexer_output.index_key_cache is not None
606 else indexer_output.index_key,
607 )
608 shared_state.publish_topk_indices(self.layer_idx, indexer_output.topk_indices)
609 if indexer_output.candidate_blocks is not None:
610 shared_state.publish_candidate_blocks(
611 self.layer_idx,
612 indexer_output.candidate_blocks,
613 )
614 return indexer_output
615
616 def _build_sparse_indices(
617 self,
618 key_value: torch.Tensor,
619 compressed_kv: torch.Tensor | None,
620 topk_indices: torch.Tensor | None,
621 sequence_length: int,
622 query_offset: int,
623 global_sequence_length: int,
624 segment_starts: torch.Tensor | None,
625 raw_key_offset: int = 0,
626 main_key_offset: int = 0,
627 ) -> tuple[torch.Tensor, torch.Tensor]:
628 """Assemble dense-reference banks only after reference dispatch is selected."""
629 window = build_sliding_window_indices(
630 key_value.shape[0], sequence_length, self.sliding_window, key_value.device,
631 query_offset=query_offset, key_length=global_sequence_length,
632 )
633 if segment_starts is not None:
634 window.masked_fill_(window < segment_starts.unsqueeze(-1), -1)
635 window = torch.where(window >= 0, window - raw_key_offset, -1)
636 if compressed_kv is None:
637 return key_value, window
638 combined_key_value = torch.cat((key_value, compressed_kv.unsqueeze(1)), dim=2)
639 compressed_indices = torch.where(
640 topk_indices >= 0, topk_indices.long() - main_key_offset + key_value.shape[2], -1,
641 )
642 return combined_key_value, torch.cat((window, compressed_indices), dim=-1)
643
644 def _apply_indexer_loss(
645 self,
646 indexer_output: Any | None,
647 query: torch.Tensor,
648 compressed_kv: torch.Tensor | None,
649 query_segments: tuple,
650 main_key_offset: int = 0,
651 ) -> torch.Tensor:
652 """Auto-scale the query by the indexer KL loss when configured."""
653 if (
654 indexer_output is not None
655 and self.training
656 and self.indexer.loss_coeff
657 and compressed_kv is not None
658 ):
659 # KL uses the original owner's queries. A view aligns its student K
660 # with the compact teacher bank while preserving global Index K gradients.
661 index_key = indexer_output.index_key
662 if main_key_offset or compressed_kv.shape[1] != index_key.shape[1]:
663 index_key = index_key[:, main_key_offset:main_key_offset+compressed_kv.shape[1]]
664 selected = indexer_output.topk_indices
665 if main_key_offset:
666 selected = torch.where(selected >= 0, selected - main_key_offset, -1)
667 query_segments = tuple((s, e, ks-main_key_offset, ke-main_key_offset, residual)
668 for s, e, ks, ke, residual in query_segments)
669 indexer_loss = shared_compressed_indexer_kl_loss(
670 indexer_output.index_query,
671 index_key,
672 indexer_output.merge_weight,
673 query,
674 compressed_kv,
675 selected,
676 self.sinks,
677 attention_scale=self.scaling,
678 loss_coeff=self.indexer.loss_coeff,
679 query_chunk_size=self.indexer.query_chunk_size,
680 reduce_sum=self.head_reducer(),
681 compress_ratio=self.compress_ratio,
682 query_segments=query_segments,
683 use_fused=self.use_fused_ops,
684 )
685 query = aux_loss_auto_scale(query, indexer_loss)
686 return query
687
688 def _run_sparse_attention(
689 self, query: torch.Tensor, key_value: torch.Tensor, compressed_kv: torch.Tensor | None,
690 topk_indices: torch.Tensor | None, query_offset: int, global_sequence_length: int,
691 segment_starts: torch.Tensor | None, query_segments: tuple, raw_key_offset: int = 0,
692 main_key_offset: int = 0, raw_document_starts: tuple = (), global_key_length: int | None = None,
693 ) -> torch.Tensor:
694 """Run the chosen implementation; unsupported explicit fusion always raises."""
695 if self.use_fused_ops:
696 expected_topk = min(512, global_key_length if global_key_length is not None
697 else global_sequence_length // max(1, self.compress_ratio))
698 if not (self.candidate_source_layer_idx is None
699 and (topk_indices is None or topk_indices.shape[-1] == expected_topk)
700 and supports_fused_attention_inputs(
701 query, self.compress_ratio, self.sliding_window,
702 0 if topk_indices is None else topk_indices.shape[-1])):
703 raise RuntimeError(
704 "V4.1 fused attention is required but this call is unsupported: "
705 f"layer={self.layer_idx}, device={query.device}, dtype={query.dtype}, Q={tuple(query.shape)}, "
706 f"ratio={self.compress_ratio}, window={self.sliding_window}. "
707 "Check the SMLA training extension and native input contract; no reference fallback was run."
708 )
709 # CP transfers packed storage; decode only after its communication wait.
710 # Both attention implementations retain their floating-bank kernel contracts.
711 key_value = CSA2CacheQuantizer.dequantize(key_value) if isinstance(key_value, CSA2CacheTensor) else key_value
712 compressed_kv = (CSA2CacheQuantizer.dequantize(compressed_kv) if isinstance(compressed_kv, CSA2CacheTensor)
713 else compressed_kv)
714 if self.use_fused_ops:
715 output = sparse_flash_mla(
716 query, key_value, compressed_kv, topk_indices, self.sinks, self.scaling,
717 self.compress_ratio, self.sliding_window, query_offset, query_segments, raw_key_offset, main_key_offset,
718 raw_document_starts,
719 )
720 if compressed_kv is not None and all(end == start for _, _, start, end, _ in query_segments):
721 # Empty-prefix ranks must still participate in the shared bank's collective backward.
722 output = output + compressed_kv[:, :0].sum().to(output.dtype)
723 return output
724 combined_key_value, sparse_indices = self._build_sparse_indices(
725 key_value, compressed_kv, topk_indices, query.shape[2], query_offset,
726 global_sequence_length, segment_starts, raw_key_offset, main_key_offset,
727 )
728 return reference_sparse_attention(query, combined_key_value, sparse_indices, self.sinks, self.scaling)
729
730 def _project_output(
731 self,
732 attention_output: torch.Tensor,
733 cos: torch.Tensor,
734 sin: torch.Tensor,
735 batch_size: int,
736 sequence_length: int,
737 ) -> torch.Tensor:
738 """Undo RoPE and apply the grouped low-rank output projection."""
739 attention_output = _apply_v41_rope(attention_output, cos, -sin, unsqueeze_dim=2)
740 num_groups = attention_output.shape[2] * self.head_dim // self.o_a_proj.weight.shape[1]
741 grouped = attention_output.reshape(batch_size, sequence_length, num_groups, -1)
742 hidden_per_group = grouped.shape[-1]
743 output_per_group = self.o_a_proj.weight.shape[0] // num_groups
744 projection = self.o_a_proj.weight.view(
745 num_groups, output_per_group, hidden_per_group
746 ).transpose(1, 2)
747 flattened = grouped.reshape(-1, num_groups, hidden_per_group).transpose(0, 1)
748 projected = torch.bmm(flattened, projection).transpose(0, 1)
749 projected = projected.reshape(batch_size, sequence_length, -1)
750 return self.o_b_proj(projected)
751
752 def forward(
753 self, hidden_states: torch.Tensor,
754 position_embeddings: dict[str, tuple[torch.Tensor, torch.Tensor]],
755 position_ids: torch.Tensor, attention_mask: torch.Tensor | None,
756 past_key_values: Any | None = None, **kwargs: Any,
757 ) -> tuple[torch.Tensor, None]:
758 """Run common math; the family/framework owns distributed port conversion."""
759 shared, packed, batch, length = self._validate_forward_inputs(
760 hidden_states, attention_mask, past_key_values, kwargs,
761 )
762 document = self.prepare_document_inputs(hidden_states, position_ids, packed)
763 prepared = self.prepare_attention_inputs(hidden_states, position_embeddings, shared, document)
764 inputs = self.exchange_attention(prepared, shared)
765 del prepared
766 compressed, selected, main_offset = None, None, 0
767 if self.compress_ratio:
768 compressed = shared.require_compressed_kv(self.kv_source_layer_idx, self.layer_idx)
769 selected = shared.require_topk_indices(self.index_source_layer_idx, self.layer_idx)
770 main_offset = shared.compressed_kv_offsets.get(self.kv_source_layer_idx, 0)
771 if self.use_fused_ops and isinstance(compressed, CSA2CacheTensor):
772 # Share this layer's decode; the KL teacher detaches its view.
773 compressed = CSA2CacheQuantizer.dequantize(compressed)
774 query = self._apply_indexer_loss(inputs.indexer_output, inputs.query, compressed,
775 document.query_segments, main_offset)
776 output = self._run_sparse_attention(
777 query, inputs.key_value, compressed, selected, document.query_offset, document.global_length,
778 document.segment_starts, document.query_segments, inputs.raw_key_offset, main_offset,
779 document.raw_document_starts, document.global_key_length,
780 )
781 del inputs
782 cos, sin = position_embeddings["compress" if self.compress_ratio else "main"]
783 return self._project_output(output, cos, sin, batch, length), None