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 Indexer projections, causal selection and candidate-pool reference math."""
16
17from __future__ import annotations
18
19from collections.abc import Callable
20from dataclasses import dataclass
21from types import SimpleNamespace
22from typing import Any, TYPE_CHECKING
23
24import torch
25from torch import nn
26
27from hyper_parallel.components.functional.lightning_indexer import (
28 lightning_indexer, sort_key_indices, validate_indexer_tensors,
29)
30from hyper_parallel.components.modules.common.rms_norm import NativeRMSNormModule, 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.api import checkpoint_exclude_wrapper
34
35if TYPE_CHECKING:
36 # Policies are injected; importing the binding layer at runtime would cycle.
37 from .quantize_compressed_sparse_attention2 import IndexerQATPolicy
38
39
40@dataclass
41class CSA2IndexerOutput:
42 """Tensors produced by one Full or Reindex Indexer invocation.
43
44 index_key is differentiable; index_key_cache retains shared packed bytes.
45 """
46
47 topk_indices: torch.Tensor
48 index_key: torch.Tensor
49 candidate_blocks: torch.Tensor | None
50 index_query: torch.Tensor
51 merge_weight: torch.Tensor
52 index_key_cache: torch.Tensor | None = None
53
54
55def _run_lightning_indexer(
56 query: torch.Tensor, key: torch.Tensor, merge_weight: torch.Tensor,
57 top_k: int, compress_ratio: int, query_offset: int,
58 reduce_sum: Callable[[torch.Tensor], torch.Tensor] | None,
59 minimum_key_indices: torch.Tensor | None, query_segments: tuple | None,
60) -> torch.Tensor:
61 """Run LI V2 with explicit adapter errors and native capability validation."""
62 if reduce_sum is not None:
63 raise NotImplementedError("Fused LightningIndexer does not support TP score reduction before TopK")
64 if minimum_key_indices is not None and query_segments is None:
65 raise ValueError("Fused LightningIndexer requires query_segments when minimum_key_indices is set")
66 validate_indexer_tensors(query, key, merge_weight)
67 if query.device.type != "npu":
68 raise RuntimeError(f"Fused LightningIndexer requires NPU inputs; got device={query.device}")
69 if query_segments is None:
70 length = query.shape[1]
71 raw_end = query_offset + length
72 query_segments = ((0, length, 0, raw_end // compress_ratio, raw_end % compress_ratio),)
73 return lightning_indexer(query, key, merge_weight, compress_ratio, top_k, query_segments)
74
75
76def _causal_key_bounds(
77 query: torch.Tensor, ratio: int, query_offset: int,
78 minimum_key_indices: torch.Tensor | None, segments: tuple | None,
79 causal_upper: torch.Tensor | None = None,
80) -> tuple[torch.Tensor, torch.Tensor | None]:
81 """Derive visibility from original query positions within each independently compressed document.
82
83 The returned upper bound always has shape ``[1, queries]`` (shared across
84 the batch), so chunked consumers slice it along the sequence dimension.
85 ``causal_upper`` is the packed per-query exclusive bound shared by eager and
86 graph execution; Python ``segments`` remain available for eager callers and
87 the fused native kernels.
88 """
89 batch_size, length = query.shape[:2]
90 if causal_upper is not None:
91 return causal_upper, minimum_key_indices
92 if segments is None:
93 positions = torch.arange(query_offset, query_offset + length, device=query.device)
94 return ((positions + 1) // ratio).unsqueeze(0), minimum_key_indices
95 upper = torch.empty(length, device=query.device, dtype=torch.long)
96 lower = torch.empty_like(upper)
97 for begin, end, key_start, key_end, residual in segments:
98 first = ratio * key_end + residual - (end - begin)
99 positions = torch.arange(first, first + end - begin, device=query.device)
100 upper[begin:end] = (positions + 1) // ratio
101 lower[begin:end] = key_start
102 return upper.unsqueeze(0), lower.unsqueeze(0).expand(batch_size, -1)
103
104
105@torch.no_grad()
106def compressed_causal_topk(
107 query: torch.Tensor,
108 key: torch.Tensor,
109 merge_weight: torch.Tensor,
110 *,
111 compress_ratio: int,
112 sparse_count: int,
113 query_offset: int = 0,
114 query_chunk_size: int = 256,
115 reduce_sum: Callable[[torch.Tensor], torch.Tensor] | None = None,
116 minimum_key_indices: torch.Tensor | None = None,
117 query_segments: tuple[tuple[int, int, int, int, int], ...] | None = None,
118 causal_upper: torch.Tensor | None = None,
119 use_fused: bool = False,
120) -> torch.Tensor:
121 """Select compressed positions with V4.1's ratio-aware causal rule.
122
123 CSA2 keys represent closed groups of ``compress_ratio`` source tokens.
124 Both LI V2 and the batched reference preserve the source rule
125 ``key < floor((query + 1) / ratio)``. The optional native path requires
126 document-local K prefixes; the reference retains TP score reductions.
127
128 Args:
129 query_segments: Local Q intersections and global compressed K prefixes.
130 causal_upper: Packed per-query exclusive causal bound shared by eager
131 and graph execution; supersedes ``query_segments`` for reference
132 selection when provided.
133 use_fused: Select LI V2 and raise if a nonempty call is unsupported.
134 False explicitly selects the numerical reference.
135 """
136 if compress_ratio <= 0:
137 raise ValueError(f"compress_ratio must be positive, got {compress_ratio}")
138 if query_chunk_size <= 0:
139 raise ValueError(f"query_chunk_size must be positive, got {query_chunk_size}")
140 if query.ndim != 4:
141 raise ValueError(f"Indexer query must have shape [B, Q, H, D], got {tuple(query.shape)}")
142 batch_size, sequence_length, _, head_dim = query.shape
143 if key.ndim != 3 or key.shape[::2] != (batch_size, head_dim):
144 raise ValueError(
145 "compressed index key must have shape [batch, compressed_sequence, head_dim]"
146 )
147 if merge_weight.shape != query.shape[:3]:
148 raise ValueError(
149 f"merge_weight must have shape {tuple(query.shape[:3])}, got {tuple(merge_weight.shape)}"
150 )
151 compressed_length = key.shape[1]
152 if minimum_key_indices is not None and minimum_key_indices.shape != query.shape[:2]:
153 raise ValueError("minimum_key_indices must have shape [batch, query]")
154 top_k = min(sparse_count, compressed_length)
155 if top_k <= 0 or sequence_length == 0:
156 return torch.empty(
157 batch_size,
158 sequence_length,
159 max(top_k, 0),
160 dtype=torch.int32,
161 device=query.device,
162 )
163
164 if use_fused:
165 return _run_lightning_indexer(
166 query, key, merge_weight, top_k, compress_ratio, query_offset,
167 reduce_sum, minimum_key_indices, query_segments,
168 )
169
170 visible_keys, minimum_key_indices = _causal_key_bounds(
171 query, compress_ratio, query_offset, minimum_key_indices, query_segments, causal_upper,
172 )
173 key_fp32 = key.float().transpose(1, 2).unsqueeze(1)
174 key_positions = torch.arange(compressed_length, device=query.device).view(1, 1, -1)
175 selected_chunks = []
176 for start in range(0, sequence_length, query_chunk_size):
177 end = min(start + query_chunk_size, sequence_length)
178 # SAC may retain the matmul result; do not mutate its cached tensor.
179 scores = torch.matmul(query[:, start:end].float(), key_fp32).relu()
180 scores = (scores * merge_weight[:, start:end].float().unsqueeze(-1)).sum(dim=2)
181 if reduce_sum is not None:
182 scores = reduce_sum(scores)
183 # Bounds are [1, S]; slice the query axis so the mask covers this chunk.
184 visible = visible_keys[:, start:end].unsqueeze(-1)
185 scores.masked_fill_(key_positions >= visible, float("-inf"))
186 if minimum_key_indices is not None:
187 minimum = minimum_key_indices[:, start:end].unsqueeze(-1)
188 scores.masked_fill_(key_positions < minimum, float("-inf"))
189 top = scores.topk(top_k, dim=-1, sorted=False)
190 indices = top.indices.masked_fill(~torch.isfinite(top.values), compressed_length)
191 indices = sort_key_indices(indices, compressed_length)
192 indices = indices.masked_fill(indices == compressed_length, -1)
193 selected_chunks.append(indices.to(torch.int32))
194 return torch.cat(selected_chunks, dim=1)
195
196
197def select_candidate_blocks(
198 logits: torch.Tensor,
199 compress_lens: torch.Tensor | int,
200 topk_blocks: int,
201 block_size: int,
202) -> torch.Tensor:
203 """Select the official block-max hierarchical candidate pool.
204
205 The newest reachable partial block is pinned into the candidate set, then
206 the remaining blocks compete by their maximum position score. ``logits``
207 must already contain ``-inf`` at causally unreachable positions.
208 """
209 if topk_blocks <= 0:
210 raise ValueError(f"topk_blocks must be positive, got {topk_blocks}")
211 if block_size <= 0:
212 raise ValueError(f"block_size must be positive, got {block_size}")
213 width = logits.shape[-1]
214 if width == 0:
215 return torch.zeros_like(logits, dtype=torch.bool)
216 padding = -width % block_size
217 scores = torch.nn.functional.pad(logits, (0, padding), value=float("-inf"))
218 scores = scores.unflatten(-1, (-1, block_size)).amax(dim=-1)
219 num_blocks = scores.shape[-1]
220 if isinstance(compress_lens, torch.Tensor):
221 last = (compress_lens.to(device=logits.device) - 1) // block_size
222 else:
223 last = (compress_lens - 1) // block_size
224 block_positions = torch.arange(num_blocks, device=logits.device)
225 scores = scores.masked_fill(block_positions == last, float("inf"))
226 top = scores.topk(min(topk_blocks, num_blocks), dim=-1)
227 keep = torch.zeros_like(scores, dtype=torch.bool)
228 keep.scatter_(-1, top.indices, top.values > float("-inf"))
229 return keep.repeat_interleave(block_size, dim=-1)[..., :width]
230
231
232def select_candidate_block_indices(
233 logits: torch.Tensor,
234 compress_lens: torch.Tensor | int,
235 topk_blocks: int,
236 block_size: int,
237) -> torch.Tensor:
238 """Return compact block ids for the official hierarchical candidates.
239
240 Storing block ids uses ``block_size`` times less cross-layer state than
241 expanded position ids and avoids the full ``[batch, query, key]`` boolean
242 mask used by the released inference reference. Invalid slots are ``-1``.
243 """
244 if topk_blocks <= 0:
245 raise ValueError(f"topk_blocks must be positive, got {topk_blocks}")
246 if block_size <= 0:
247 raise ValueError(f"block_size must be positive, got {block_size}")
248 width = logits.shape[-1]
249 if width == 0:
250 return torch.empty(*logits.shape[:-1], 0, dtype=torch.int32, device=logits.device)
251 padding = -width % block_size
252 scores = torch.nn.functional.pad(logits, (0, padding), value=float("-inf"))
253 scores = scores.unflatten(-1, (-1, block_size)).amax(dim=-1)
254 num_blocks = scores.shape[-1]
255 if isinstance(compress_lens, torch.Tensor):
256 last = (compress_lens.to(device=logits.device) - 1) // block_size
257 else:
258 last = (compress_lens - 1) // block_size
259 block_positions = torch.arange(num_blocks, device=logits.device)
260 scores = scores.masked_fill(block_positions == last, float("inf"))
261 top = scores.topk(min(topk_blocks, num_blocks), dim=-1, sorted=False)
262 return top.indices.masked_fill(top.values == float("-inf"), -1).to(torch.int32)
263
264
265def compressed_causal_candidates(
266 query: torch.Tensor,
267 key: torch.Tensor,
268 merge_weight: torch.Tensor,
269 *,
270 compress_ratio: int,
271 topk_blocks: int,
272 block_size: int,
273 query_offset: int = 0,
274 query_chunk_size: int = 256,
275 reduce_sum: Callable[[torch.Tensor], torch.Tensor] | None = None,
276 minimum_key_indices: torch.Tensor | None = None,
277) -> torch.Tensor:
278 """Build compact blockwise candidate ids in bounded query chunks."""
279 _, sequence_length, _, _ = query.shape
280 compressed_length = key.shape[1]
281 if minimum_key_indices is not None and minimum_key_indices.shape != query.shape[:2]:
282 raise ValueError("minimum_key_indices must have shape [batch, query]")
283 key_fp32 = key.float().transpose(1, 2).unsqueeze(1)
284 key_positions = torch.arange(compressed_length, device=query.device).view(1, 1, -1)
285 candidate_chunks = []
286 for start in range(0, sequence_length, query_chunk_size):
287 end = min(start + query_chunk_size, sequence_length)
288 scores = torch.matmul(query[:, start:end].float(), key_fp32).relu()
289 scores = (scores * merge_weight[:, start:end].float().unsqueeze(-1)).sum(dim=2)
290 if reduce_sum is not None:
291 scores = reduce_sum(scores)
292 visible = (
293 torch.arange(query_offset + start, query_offset + end, device=query.device) + 1
294 ) // compress_ratio
295 scores.masked_fill_(key_positions >= visible.view(1, -1, 1), float("-inf"))
296 if minimum_key_indices is not None:
297 minimum = minimum_key_indices[:, start:end].unsqueeze(-1)
298 scores.masked_fill_(key_positions < minimum, float("-inf"))
299 candidate_chunks.append(
300 select_candidate_block_indices(
301 scores,
302 visible.view(1, -1, 1),
303 topk_blocks,
304 block_size,
305 )
306 )
307 return torch.cat(candidate_chunks, dim=1)
308
309
310def compressed_causal_topk_and_candidates(
311 query: torch.Tensor,
312 key: torch.Tensor,
313 merge_weight: torch.Tensor,
314 *,
315 compress_ratio: int,
316 sparse_count: int,
317 topk_blocks: int,
318 block_size: int,
319 query_offset: int = 0,
320 query_chunk_size: int = 256,
321 reduce_sum: Callable[[torch.Tensor], torch.Tensor] | None = None,
322 minimum_key_indices: torch.Tensor | None = None,
323 causal_upper: torch.Tensor | None = None,
324) -> tuple[torch.Tensor, torch.Tensor]:
325 """Select Full-layer Top-K and candidate blocks from one score pass.
326
327 ``causal_upper`` supplies the packed per-query causal bound for eager and
328 graph execution; it must be compression-aligned packed input when given.
329 """
330 if compress_ratio <= 0:
331 raise ValueError(f"compress_ratio must be positive, got {compress_ratio}")
332 if query_chunk_size <= 0:
333 raise ValueError(f"query_chunk_size must be positive, got {query_chunk_size}")
334 batch_size, sequence_length, _, head_dim = query.shape
335 if key.ndim != 3 or key.shape[::2] != (batch_size, head_dim):
336 raise ValueError(
337 "compressed index key must have shape [batch, compressed_sequence, head_dim]"
338 )
339 if merge_weight.shape != query.shape[:3]:
340 raise ValueError(
341 f"merge_weight must have shape {tuple(query.shape[:3])}, got {tuple(merge_weight.shape)}"
342 )
343 compressed_length = key.shape[1]
344 if minimum_key_indices is not None and minimum_key_indices.shape != query.shape[:2]:
345 raise ValueError("minimum_key_indices must have shape [batch, query]")
346 top_k = min(sparse_count, compressed_length)
347 if top_k <= 0:
348 empty_topk = torch.empty(
349 batch_size,
350 sequence_length,
351 0,
352 dtype=torch.int32,
353 device=query.device,
354 )
355 return empty_topk, empty_topk
356
357 key_fp32 = key.float().transpose(1, 2).unsqueeze(1)
358 key_positions = torch.arange(compressed_length, device=query.device).view(1, 1, -1)
359 selected_chunks = []
360 candidate_chunks = []
361 for start in range(0, sequence_length, query_chunk_size):
362 end = min(start + query_chunk_size, sequence_length)
363 scores = torch.matmul(query[:, start:end].float(), key_fp32).relu()
364 scores = (scores * merge_weight[:, start:end].float().unsqueeze(-1)).sum(dim=2)
365 if reduce_sum is not None:
366 scores = reduce_sum(scores)
367 visible = (
368 causal_upper[:, start:end] if causal_upper is not None else
369 (torch.arange(query_offset + start, query_offset + end, device=query.device) + 1) // compress_ratio
370 )
371 scores.masked_fill_(key_positions >= visible.view(1, -1, 1), float("-inf"))
372 if minimum_key_indices is not None:
373 minimum = minimum_key_indices[:, start:end].unsqueeze(-1)
374 scores.masked_fill_(key_positions < minimum, float("-inf"))
375 top = scores.topk(top_k, dim=-1, sorted=False)
376 indices = top.indices.masked_fill(~torch.isfinite(top.values), compressed_length)
377 indices = indices.sort(dim=-1).values
378 selected_chunks.append(indices.masked_fill(indices == compressed_length, -1).to(torch.int32))
379 candidate_chunks.append(
380 select_candidate_block_indices(
381 scores,
382 visible.view(1, -1, 1),
383 topk_blocks,
384 block_size,
385 )
386 )
387 return torch.cat(selected_chunks, dim=1), torch.cat(candidate_chunks, dim=1)
388
389
390def compressed_candidate_topk(
391 query: torch.Tensor,
392 key: torch.Tensor,
393 merge_weight: torch.Tensor,
394 candidate_blocks: torch.Tensor,
395 *,
396 compress_ratio: int,
397 sparse_count: int,
398 block_size: int,
399 query_offset: int = 0,
400 query_chunk_size: int = 256,
401 reduce_sum: Callable[[torch.Tensor], torch.Tensor] | None = None,
402 minimum_key_indices: torch.Tensor | None = None,
403 causal_upper: torch.Tensor | None = None,
404) -> torch.Tensor:
405 """Score only hierarchical candidate blocks and return global key ids.
406
407 ``causal_upper`` supplies the packed per-query causal bound for eager and
408 graph execution; it must be compression-aligned packed input when given.
409 """
410 if compress_ratio <= 0:
411 raise ValueError(f"compress_ratio must be positive, got {compress_ratio}")
412 if block_size <= 0:
413 raise ValueError(f"block_size must be positive, got {block_size}")
414 if query_chunk_size <= 0:
415 raise ValueError(f"query_chunk_size must be positive, got {query_chunk_size}")
416 batch_size, sequence_length, _, head_dim = query.shape
417 if key.ndim != 3 or key.shape[::2] != (batch_size, head_dim):
418 raise ValueError(
419 "compressed index key must have shape [batch, compressed_sequence, head_dim]"
420 )
421 if merge_weight.shape != query.shape[:3]:
422 raise ValueError(
423 f"merge_weight must have shape {tuple(query.shape[:3])}, got {tuple(merge_weight.shape)}"
424 )
425 if candidate_blocks.ndim != 3 or candidate_blocks.shape[:2] != query.shape[:2]:
426 raise ValueError(
427 "candidate_blocks must have shape [batch, query, candidate_blocks], "
428 f"got {tuple(candidate_blocks.shape)}"
429 )
430 if minimum_key_indices is not None and minimum_key_indices.shape != query.shape[:2]:
431 raise ValueError("minimum_key_indices must have shape [batch, query]")
432
433 compressed_length = key.shape[1]
434 candidate_width = candidate_blocks.shape[-1] * block_size
435 top_k = min(sparse_count, candidate_width)
436 if top_k <= 0:
437 return torch.empty(
438 batch_size,
439 sequence_length,
440 0,
441 dtype=torch.int32,
442 device=query.device,
443 )
444
445 block_offsets = torch.arange(block_size, device=query.device)
446 batch_indices = torch.arange(batch_size, device=query.device).view(-1, 1, 1)
447 selected_chunks = []
448 for start in range(0, sequence_length, query_chunk_size):
449 end = min(start + query_chunk_size, sequence_length)
450 blocks = candidate_blocks[:, start:end].long()
451 block_positions = blocks.unsqueeze(-1) * block_size + block_offsets
452 positions = block_positions.flatten(-2)
453 visible = (
454 causal_upper[:, start:end] if causal_upper is not None else
455 (torch.arange(query_offset + start, query_offset + end, device=query.device) + 1) // compress_ratio
456 )
457 valid = (blocks.unsqueeze(-1) >= 0).expand_as(block_positions).flatten(-2)
458 valid = valid & (positions < compressed_length) & (positions < visible.view(1, -1, 1))
459 if minimum_key_indices is not None:
460 valid = valid & (positions >= minimum_key_indices[:, start:end].unsqueeze(-1))
461 safe_positions = positions.clamp(min=0, max=max(compressed_length - 1, 0))
462 selected_key = key[batch_indices, safe_positions].float()
463 dots = torch.einsum(
464 "bchd,bckd->bchk",
465 query[:, start:end].float(),
466 selected_key,
467 ).relu()
468 scores = (dots * merge_weight[:, start:end].float().unsqueeze(-1)).sum(dim=2)
469 if reduce_sum is not None:
470 scores = reduce_sum(scores)
471 scores.masked_fill_(~valid, float("-inf"))
472 top = scores.topk(top_k, dim=-1, sorted=False)
473 selected = positions.gather(-1, top.indices)
474 selected.masked_fill_(~torch.isfinite(top.values), compressed_length)
475 selected = selected.sort(dim=-1).values
476 selected.masked_fill_(selected == compressed_length, -1)
477 selected_chunks.append(selected.to(torch.int32))
478 return torch.cat(selected_chunks, dim=1)
479
480
481class _IndexerParameters(nn.Module):
482 """Construct the released Full or Reindex Lightning Indexer state."""
483
484 def __init__(self, config: Any, compress_ratio: int, layer_idx: int) -> None:
485 """Create layer-local queries and Full-only shared-key projections."""
486
487 super().__init__()
488 self.compress_ratio = compress_ratio
489 self.num_heads = config.index_n_heads
490 self.head_dim = config.index_head_dim
491 self.index_topk = config.index_topk
492 # Query rows processed per indexer scoring pass. Larger chunks cut the
493 # Python-loop launch count but enlarge the transient fp32 score
494 # buffer; 256 is the released default, ~1024 measured fastest at 32K.
495 self.query_chunk_size = int(getattr(config, "v41_indexer_query_chunk_size", 256) or 256)
496 self.owns_key = layer_idx in config.v41_kv_source_layer_ids
497 candidate_source = int(getattr(config, "v41_candidate_source_layer_id", -1))
498 self.is_candidate_source = layer_idx == candidate_source
499 self.uses_candidates = 0 <= candidate_source < layer_idx
500 self.candidate_topk_blocks = int(getattr(config, "v41_candidate_topk_blocks", 0))
501 self.candidate_block_size = int(getattr(config, "v41_candidate_block_size", 1))
502 self.loss_coeff = float(getattr(config, "v41_indexer_loss_coeff", 0.0))
503 self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
504 self.weights_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
505 if self.owns_key:
506 self.wk = nn.Linear(config.head_dim, self.head_dim, bias=False)
507 # Keep this source subtree eligible for enclosing CSA2 replacement.
508 norm = NativeRMSNormModule(
509 config=SimpleNamespace(hidden_size=self.head_dim, eps=config.rms_norm_eps),
510 cast_order="before_weight",
511 )
512 self.k_norm = RMSNorm(module=norm)
513
514
515class CSA2Indexer(nn.Module):
516 """Local Indexer math with overridable key preparation and selection stages."""
517
518 _selection_region: Callable[..., Any] | None = None
519
520 def __init__(self, module: nn.Module | None = None, *, config: Any = None,
521 compress_ratio: int = 1, layer_idx: int = 0, apply_rope: Callable | None = None) -> None:
522 """Create or adopt projections without changing checkpoint names."""
523 if (module is None) == (config is None):
524 raise ValueError("CSA2 Indexer requires exactly one of config or module")
525 if module is None:
526 module = _IndexerParameters(config, compress_ratio, layer_idx)
527 super().__init__()
528 required = ("q_b_proj", "weights_proj")
529 missing = [name for name in required if not hasattr(module, name)]
530 if missing:
531 raise TypeError(f"shared compressed DSA indexer is missing: {missing}")
532 for name, child in module._modules.items(): # pylint: disable=protected-access
533 self.add_module(name, child)
534 for name, parameter in module._parameters.items(): # pylint: disable=protected-access
535 self.register_parameter(name, parameter)
536 for name, buffer in module._buffers.items(): # pylint: disable=protected-access
537 self.register_buffer(name, buffer, persistent=name not in module._non_persistent_buffers_set)
538 self.apply_rope = apply_rope if apply_rope is not None else getattr(module, "apply_rope", None)
539 if self.apply_rope is None:
540 raise ValueError("CSA2 Indexer requires the enclosing attention's rotary function")
541 self.use_fused = getattr(module, "use_fused", False)
542 self.compress_ratio = module.compress_ratio
543 self.global_num_heads = getattr(module, "global_num_heads", getattr(module, "num_heads", None))
544 self.head_dim = module.head_dim
545 self.index_topk = module.index_topk
546 self.owns_key = module.owns_key
547 self.is_candidate_source = module.is_candidate_source
548 self.uses_candidates = module.uses_candidates
549 self.candidate_topk_blocks = module.candidate_topk_blocks
550 self.candidate_block_size = module.candidate_block_size
551 self.loss_coeff = module.loss_coeff
552 self.query_chunk_size = int(getattr(module, "query_chunk_size", 256))
553 self._qk_policy: IndexerQATPolicy | None = getattr(module, "_qk_policy", None)
554 # Children are adopted by identity; preserve their individual training modes.
555 self.training = module.training
556
557 def set_qk_policy(self, policy: IndexerQATPolicy) -> None:
558 """Bind the query QDQ and Full-key packing policy."""
559 self._qk_policy = policy
560
561 def _project_index_query(
562 self, query_residual: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
563 *, sequence_major: bool = False,
564 ) -> torch.Tensor:
565 """Project queries with their original rotary positions, including moved tasks."""
566 query = self.q_b_proj(query_residual.detach())
567 if query.shape[-1] % self.head_dim:
568 raise ValueError(
569 f"Indexer query width {query.shape[-1]} is not divisible by head_dim {self.head_dim}"
570 )
571 query = query.view(*query_residual.shape[:2], -1, self.head_dim)
572 if sequence_major:
573 query = self.apply_rope(query, cos, sin, unsqueeze_dim=2)
574 else:
575 query = self.apply_rope(query.transpose(1, 2), cos, sin).transpose(1, 2)
576 # Selection and KL must observe the same quantized queries.
577 return self._qk_policy.quantize_query(query) if self._qk_policy is not None else query
578
579 @torch.no_grad()
580 def _project_worker_index_query(
581 self, query_residual: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
582 owner_query_length: int,
583 ) -> torch.Tensor:
584 """Preserve the owner's projection row shape for discrete worker selection.
585
586 BF16 GEMM rounding can depend on its row count. Match the original
587 owner's GEMM shape so task redistribution does not perturb TopK inputs.
588 Padding is confined to the no-grad projection and never reaches LI.
589
590 Args:
591 query_residual: Low-rank query rows assigned to this worker.
592 cos: Original-position cosine rows for the worker queries.
593 sin: Original-position sine rows for the worker queries.
594 owner_query_length: Query count in the original owner projection.
595
596 Returns:
597 Worker Index Q in sequence-major layout, excluding padded rows.
598 """
599 if owner_query_length <= 0:
600 raise ValueError("Indexer owner query length must be positive")
601 batch, length = query_residual.shape[:2]
602 if length == owner_query_length:
603 return self._project_index_query(query_residual, cos, sin, sequence_major=True)
604 if not length:
605 query = self.q_b_proj(query_residual.detach())
606 return query.view(batch, 0, query.shape[-1] // self.head_dim, self.head_dim)
607
608 query = None
609 for start in range(0, length, owner_query_length):
610 end = min(start + owner_query_length, length)
611 chunk = query_residual[:, start:end].detach()
612 if end - start < owner_query_length:
613 chunk = torch.nn.functional.pad(chunk, (0, 0, 0, owner_query_length - (end - start)))
614 projected = self.q_b_proj(chunk)
615 if query is None:
616 query = projected.new_empty((batch, length, projected.shape[-1]))
617 query[:, start:end].copy_(projected[:, :end - start])
618 del projected, chunk
619 query = query.view(batch, length, query.shape[-1] // self.head_dim, self.head_dim)
620 # Redispatched worker rows must retain the owner's QDQ tail.
621 query = self.apply_rope(query, cos, sin, unsqueeze_dim=2)
622 return self._qk_policy.quantize_query(query) if self._qk_policy is not None else query
623
624 def _project_index_key(
625 self,
626 latent: torch.Tensor | None,
627 cos: torch.Tensor,
628 sin: torch.Tensor,
629 index_key: torch.Tensor | None,
630 key_position_embeddings: tuple | None = None,
631 ) -> torch.Tensor:
632 """Project or adopt the index key without communicating."""
633 if self.owns_key:
634 if latent is None:
635 raise RuntimeError("a Full Indexer requires the compressor latent")
636 key = self.k_norm(self.wk(latent.detach()))
637 compressed_length = key.shape[1]
638 if key_position_embeddings is None:
639 key_cos = cos[:, :compressed_length * self.compress_ratio:self.compress_ratio]
640 key_sin = sin[:, :compressed_length * self.compress_ratio:self.compress_ratio]
641 else:
642 key_cos, key_sin = key_position_embeddings
643 key = self.apply_rope(key.unsqueeze(1), key_cos, key_sin).squeeze(1)
644 return key
645 if index_key is None:
646 raise RuntimeError("a Reindex layer requires index K from the preceding Full layer")
647 return index_key
648
649 def prepare_key(self, latent: torch.Tensor | None, cos: torch.Tensor, sin: torch.Tensor,
650 index_key: torch.Tensor | None, block_plan: Any, key_position_embeddings: tuple | None) -> Any:
651 """Prepare a local ready bank; parallel members may return a pending transfer."""
652 del block_plan
653 return self._project_index_key(latent, cos, sin, index_key, key_position_embeddings)
654
655 def exchange_key(self, prepared: Any) -> torch.Tensor:
656 """Keep the local bank unchanged."""
657 return prepared
658
659 def forward(
660 self, hidden_states: torch.Tensor, query_residual: torch.Tensor, latent: torch.Tensor | None,
661 compress_position_embeddings: tuple[torch.Tensor, torch.Tensor], *,
662 index_key: torch.Tensor | None = None, candidate_blocks: torch.Tensor | None = None,
663 reduce_sum: Callable | None = None, query_offset: int = 0,
664 minimum_key_indices: torch.Tensor | None = None, query_segments: tuple | None = None,
665 document_lengths: tuple[int, ...] = (), prepare_attention: Callable | None = None,
666 block_plan: Any = None, key_position_embeddings: tuple | None = None,
667 causal_upper: torch.Tensor | None = None,
668 ) -> CSA2IndexerOutput:
669 """Project owner queries and select keys; exclusion fixes TopK during replay."""
670 del document_lengths
671 cos, sin = compress_position_embeddings
672 prepared_key = self.prepare_key(latent, cos, sin, index_key, block_plan, key_position_embeddings)
673 if prepare_attention is not None:
674 prepare_attention()
675 query = self._project_index_query(query_residual, cos, sin)
676 weights = self.weights_proj(hidden_states.detach())
677 if weights.shape[-1] != query.shape[2]:
678 raise ValueError("Indexer query and merge weights must have matching head counts")
679 weights = weights * (self.head_dim**-0.5 * self.global_num_heads**-0.5)
680 key = self.exchange_key(prepared_key)
681 index_key_cache = None
682 if isinstance(key, CSA2CacheTensor):
683 # Preserve producer bytes while decoding the differentiable scoring key.
684 index_key_cache = key
685 key = CSA2CacheQuantizer.dequantize(key)
686 elif self.owns_key and self._qk_policy is not None:
687 # Local owners share one quantization between scoring and publication.
688 key, index_key_cache = self._qk_policy.pack_owned_key(key)
689 selected, candidates = self._run_selection(
690 query, key, weights, candidate_blocks, query_offset, reduce_sum,
691 minimum_key_indices, query_segments, causal_upper,
692 )
693 return CSA2IndexerOutput(
694 selected, key, candidates, query, weights, index_key_cache=index_key_cache
695 )
696
697 def enable_selection_exclude(self) -> None:
698 """Reuse the discrete selection during activation recomputation."""
699 object.__setattr__(self, "_selection_region", checkpoint_exclude_wrapper(self._select_tokens))
700
701 def _run_selection(self, *args: Any, **kwargs: Any) -> tuple[torch.Tensor, torch.Tensor | None]:
702 """Select directly, or reuse the result retained by the checkpoint region."""
703 selection = self._select_tokens if self._selection_region is None else self._selection_region
704 return selection(*args, **kwargs)
705
706 def _select_tokens(self, *args: Any, **kwargs: Any) -> tuple:
707 """Run only selection inside the checkpoint exclusion region."""
708 return self._select_indices(*args, **kwargs)
709
710 def _select_indices(
711 self, query: torch.Tensor, key: torch.Tensor, merge_weight: torch.Tensor,
712 candidate_blocks: torch.Tensor | None, query_offset: int,
713 reduce_sum: Callable[[torch.Tensor], torch.Tensor] | None,
714 minimum_key_indices: torch.Tensor | None, query_segments: tuple | None,
715 causal_upper: torch.Tensor | None = None,
716 ) -> tuple[torch.Tensor, torch.Tensor | None]:
717 """Select the requested implementation without changing candidate policies."""
718 if self.use_fused and (self.is_candidate_source or self.uses_candidates):
719 raise NotImplementedError("V4.1 fused Indexer does not support candidate-pool selection")
720 if self.is_candidate_source:
721 topk_indices, candidate_blocks = compressed_causal_topk_and_candidates(
722 query,
723 key,
724 merge_weight,
725 compress_ratio=self.compress_ratio,
726 sparse_count=self.index_topk,
727 topk_blocks=self.candidate_topk_blocks,
728 block_size=self.candidate_block_size,
729 query_offset=query_offset,
730 query_chunk_size=self.query_chunk_size,
731 reduce_sum=reduce_sum,
732 minimum_key_indices=minimum_key_indices,
733 causal_upper=causal_upper,
734 )
735 elif self.uses_candidates:
736 if candidate_blocks is None:
737 raise RuntimeError("a hierarchical Reindex layer requires candidate block ids")
738 topk_indices = compressed_candidate_topk(
739 query,
740 key,
741 merge_weight,
742 candidate_blocks,
743 compress_ratio=self.compress_ratio,
744 sparse_count=self.index_topk,
745 block_size=self.candidate_block_size,
746 query_offset=query_offset,
747 query_chunk_size=self.query_chunk_size,
748 reduce_sum=reduce_sum,
749 minimum_key_indices=minimum_key_indices,
750 causal_upper=causal_upper,
751 )
752 else:
753 candidate_blocks = None
754 topk_indices = compressed_causal_topk(
755 query,
756 key,
757 merge_weight,
758 compress_ratio=self.compress_ratio,
759 sparse_count=self.index_topk,
760 query_offset=query_offset,
761 query_chunk_size=self.query_chunk_size,
762 reduce_sum=reduce_sum,
763 minimum_key_indices=minimum_key_indices,
764 query_segments=query_segments,
765 causal_upper=causal_upper,
766 use_fused=self.use_fused,
767 )
768 return topk_indices, candidate_blocks