Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/auto_parallel/_npu_contracts.py 100%  
hyper_parallel/components/modules/attention/compressed_sparse_attention2/__init__.py 100%  
hyper_parallel/components/modules/attention/compressed_sparse_attention2/compressed_sparse_attention2.py 88.0% 95,121,152-155,163,207,314,316,393,396,398,406,411,438,444,449,457-458,461,476,496,498-501,510,578,581,632-638,640,656
hyper_parallel/components/modules/attention/compressed_sparse_attention2/compressed_sparse_attention2_family.py 86.1% 52,55,60,63,78,85,93,105,107-109
hyper_parallel/components/modules/attention/compressed_sparse_attention2/compressor.py 90.4% 36,79-82
hyper_parallel/components/modules/attention/compressed_sparse_attention2/cp_compressed_sparse_attention2.py 67.2% 60-63,65-66,69,80-85,87-93,97,141-142,168-187,199,205,208-211,216-218,224,238-239,248-250,268,281,287,293,314-315,317-326,334,338,343,345,351-352
hyper_parallel/components/modules/attention/compressed_sparse_attention2/document_layout.py 92.7% 93,216,229,251,275,278,280,295,311,334,336,348,354,362,386,392
hyper_parallel/components/modules/attention/compressed_sparse_attention2/indexer.py 46.6% 59-63,125,127,129,132,136,141,144,170,196-208,210-216,230-242,244-248,264-277,280-284,292,314-320,323-324,327-332,339,341-351,355-363,371,393-401,404-405,408-409,413-414,416-420,428-436,440-446,451-461,506,513,517,519,522,545,550,573-580,582-594,606-612,614-616,618,650,683,698-700
hyper_parallel/components/modules/attention/compressed_sparse_attention2/indexer_kl_loss.py 89.7% 75,91,177,182,185,188,190,192
hyper_parallel/distributed/context_parallel/compressed_document.py 16.7% 213-216,219
hyper_parallel/tools/model_integration/integration_validator.py 100%  
hyper_parallel/components/modules/attention/compressed_sparse_attention2/compressed_sparse_attention2.py
91
92
93
94
95
96
97
98
99
            consumer_layer: int,
    ) -> torch.Tensor:
        """Return one published tensor or report the broken layer dependency."""
        if source_layer is None or source_layer not in values:
            raise RuntimeError(
                f"layer {consumer_layer} requires {value_name} from source "
                f"layer {source_layer}, but that source has not run in this forward"
            )
        return values[source_layer]
117
118
119
120
121
122
123
124
125

    def publish_index_key(self, source_layer: int, value: torch.Tensor) -> bool:
        """Publish the Full Indexer's shared key tensor."""
        if is_recomputing():
            return False
        self.index_key_by_source[source_layer] = value
        return True

    def require_index_key(self, source_layer: int | None, consumer_layer: int) -> torch.Tensor:
148
149
150
151
152
153
154
155
156
157
158
159
        )

    def publish_candidate_blocks(self, source_layer: int, value: torch.Tensor) -> bool:
        """Publish hierarchical candidate blocks from the configured source."""
        if is_recomputing():
            return False
        self.candidate_blocks_by_source[source_layer] = value
        return True

    def require_candidate_blocks(
            self,
            source_layer: int | None,
159
160
161
162
163
164
165
166
167
            source_layer: int | None,
            consumer_layer: int,
    ) -> torch.Tensor:
        """Read hierarchical candidates for a later Reindex layer."""
        return self._require(
            self.candidate_blocks_by_source,
            source_layer,
            "candidate blocks",
            consumer_layer,
203
204
205
206
207
208
209
210
211
        key_length: int | None = None,
) -> torch.Tensor:
    """Build fixed-width causal sliding-window indices."""
    if key_length is None:
        key_length = sequence_length
    width = min(key_length, window_size)
    query = torch.arange(
        query_offset,
        query_offset + sequence_length,
310
311
312
313
314
315
316
317
318
319
320
            use_fused_ops: bool = False,
    ) -> None:
        """Create from config or adopt a source module without replacing its parameters."""
        if (module is None) == (config is None):
            raise ValueError("CSA2 requires exactly one of config or module")
        if not isinstance(use_fused_ops, bool):
            raise ValueError("use_fused_ops must be a bool")
        if module is None:
            module = _build_parameters(config, layer_idx)
        super().__init__()
        for name, child in module._modules.items():  # pylint: disable=protected-access
389
390
391
392
393
394
395
396
397
398
399
400
401
402
            kwargs: dict[str, Any],
    ) -> tuple[SharedCompressedAttentionState, SharedCompressedPackedSequence | None, int, int]:
        """Pop and validate the shared-attention keyword arguments."""
        if past_key_values is not None:
            raise NotImplementedError("shared compressed DSA training does not support KV cache")
        shared_state = kwargs.pop("shared_attention_state", None)
        if not isinstance(shared_state, SharedCompressedAttentionState):
            raise ValueError("shared_attention_state is required for shared compressed DSA")
        if attention_mask is not None:
            raise NotImplementedError(
                "shared compressed DSA consumes compact packed_seq_params instead of a dense mask"
            )
        batch_size, sequence_length, _ = hidden_states.shape
        packed_sequence = kwargs.pop("packed_seq_params", None)
402
403
404
405
406
407
408
409
410
411
412
413
414
415
        packed_sequence = kwargs.pop("packed_seq_params", None)
        if packed_sequence is not None and not isinstance(
                packed_sequence, SharedCompressedPackedSequence
        ):
            raise TypeError(
                "packed_seq_params must be SharedCompressedPackedSequence, "
                f"got {type(packed_sequence).__name__}"
            )
        if "shared_attention_cp_context" in kwargs or "shared_attention_tp_context" in kwargs:
            raise ValueError("CSA2 parallel resources must be bound through its family, not forward kwargs")
        return shared_state, packed_sequence, batch_size, sequence_length

    def _resolve_packed_segments(
            self,
434
435
436
437
438
439
440
441
442
        raw_end = query_offset + sequence_length
        query_segments = ((0, sequence_length, 0, raw_end // ratio, raw_end % ratio),)
        if packed_sequence is not None:
            if batch_size != 1:
                raise ValueError("V4.1 compact packed attention currently requires micro_batch_size=1")
            if (
                    packed_sequence.local_query_start != query_offset
                    or packed_sequence.local_query_length != sequence_length
                    or packed_sequence.global_sequence_length != global_sequence_length
440
441
442
443
444
445
446
447
448
449
450
451
452
453
                    packed_sequence.local_query_start != query_offset
                    or packed_sequence.local_query_length != sequence_length
                    or packed_sequence.global_sequence_length != global_sequence_length
            ):
                packed_shard = (
                    packed_sequence.local_query_start,
                    packed_sequence.local_query_length,
                    packed_sequence.global_sequence_length,
                )
                raise ValueError(
                    "packed sequence geometry does not match the local CP shard: "
                    f"packed={packed_shard}, "
                    f"attention={(query_offset, sequence_length, global_sequence_length)}"
                )
453
454
455
456
457
458
459
460
461
462
463
464
465
                )
            prepared = packed_sequence.prepare(device, (self.compress_ratio,))
            segment_starts = prepared.local_segment_starts(device)
            if self.compress_ratio:
                minimum_key_indices = prepared.minimum_key_indices(device, self.compress_ratio)
                causal_upper = prepared.causal_key_upper_bounds(device, self.compress_ratio)
            if (self.candidate_source_layer_idx is not None
                    and not prepared.is_compression_aligned(ratio)):
                raise ValueError("candidate-pool packed attention still requires compression-aligned documents")
            query_segments = (
                None if prepared._restored_from_packing_tensors  # pylint: disable=protected-access
                else prepared.indexer_segments(ratio)
            )
472
473
474
475
476
477
478
479
480
        offset, global_length = self.query_partition(length, position_ids)
        if packed is not None:
            packed = packed.prepare(hidden_states.device, (self.compress_ratio,))
            if self.use_fused_ops and packed._restored_from_packing_tensors:  # pylint: disable=protected-access
                raise NotImplementedError(
                    "fused DSA operators require Python document segments, not graph packing inputs"
                )
        starts, minima, segments, upper = self._resolve_packed_segments(
            packed, batch, length, offset, global_length, hidden_states.device,
492
493
494
495
496
497
498
499
500
501
502
503
504
505
        packed = document.packed
        if packed is None:
            if document.global_length % self.compress_ratio == 0:
                return None, None
            packed = SharedCompressedPackedSequence(torch.tensor((0, document.global_length)),
                                                     0, document.global_length, document.global_length)
        packed = packed.prepare(device, (self.compress_ratio,))
        plan = packed.block_plan(self.compress_ratio)
        positions = None if plan is None else packed.compressed_positions(plan, embeddings["compress"])
        return plan, positions

    def compress_key_value(self, hidden_states: torch.Tensor, embeddings: dict,
                           block_plan: Any, key_positions: tuple | None) -> tuple:
        """Call the compressor through its managed module boundary."""
506
507
508
509
510
511
512
513
514
        if not self.is_kv_source:
            return None, None
        if block_plan is None:
            return self.compressor(hidden_states, embeddings["compress"])
        return self.compressor(hidden_states, key_positions, block_plan)

    def prepare_attention_inputs(self, hidden_states: torch.Tensor, embeddings: dict,
                                 shared_state: SharedCompressedAttentionState,
                                 document: CSA2DocumentInputs) -> CSA2AttentionInputs:
574
575
576
577
578
579
580
581
582
583
584
585
            document_lengths=document_lengths,
            causal_upper=document.causal_upper,
        )
        if self.indexer.owns_key:
            shared_state.publish_index_key(self.layer_idx, indexer_output.index_key)
        shared_state.publish_topk_indices(self.layer_idx, indexer_output.topk_indices)
        if indexer_output.candidate_blocks is not None:
            shared_state.publish_candidate_blocks(
                self.layer_idx,
                indexer_output.candidate_blocks,
            )
        return indexer_output
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
                and compressed_kv is not None
        ):
            # KL uses the original owner's queries. A view aligns its student K
            # with the compact teacher bank while preserving global Index K gradients.
            index_key = indexer_output.index_key
            if main_key_offset or compressed_kv.shape[1] != index_key.shape[1]:
                index_key = index_key[:, main_key_offset:main_key_offset+compressed_kv.shape[1]]
            selected = indexer_output.topk_indices
            if main_key_offset:
                selected = torch.where(selected >= 0, selected - main_key_offset, -1)
                query_segments = tuple((s, e, ks-main_key_offset, ke-main_key_offset, residual)
                                       for s, e, ks, ke, residual in query_segments)
            indexer_loss = shared_compressed_indexer_kl_loss(
                indexer_output.index_query,
                index_key,
                indexer_output.merge_weight,
                query,
652
653
654
655
656
657
658
659
660
                compress_ratio=self.compress_ratio,
                query_segments=query_segments,
                use_fused=self.use_fused_ops,
            )
            query = aux_loss_auto_scale(query, indexer_loss)
        return query

    def _run_sparse_attention(
            self, query: torch.Tensor, key_value: torch.Tensor, compressed_kv: torch.Tensor | None,
hyper_parallel/components/modules/attention/compressed_sparse_attention2/compressed_sparse_attention2_family.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
    roles.update({"sinks": Shard(0), "o_b_proj.weight": Shard(1), "o_b_proj.bias": Replicate()})
    params = {}
    for name, _ in module.named_parameters():
        if name not in roles:
            raise ValueError(f"CSA2 parameter {name!r} has no declared sharding role")
        params[name] = dict(axes)
        if context.axis_sizes["tp"] > 1:
            params[name]["tp"] = roles[name]
    tokens = dict(axes)
    if context.axis_sizes["cp"] > 1:
        tokens["cp"] = Shard(1)
    if context.axis_sizes["tp"] > 1 and context.sequence_parallel:
        tokens["tp"] = Shard(1)
    compute_input, compute_output = dict(tokens), dict(tokens)
    if context.axis_sizes["tp"] > 1:
        compute_input["tp"], compute_output["tp"] = Replicate(), Partial()
    return ModuleShardingSpec(
        params=params, in_src={"hidden_states": dict(tokens)}, in_dst={"hidden_states": compute_input},
        out_src={"output": compute_output}, out_dst={"output": dict(tokens)},
        out_names=("output", "attention_weights"), is_boundary=True,
74
75
76
77
78
79
80
81
82
    validate_tp_boundary(sharding, expected, name="CSA2")
    tp_size = context.axis_sizes["tp"]
    if (module.config.o_groups % tp_size or module.num_heads % tp_size
            or (module.is_index_source and module.indexer.global_num_heads % tp_size)):
        raise ValueError("CSA2 main heads, Indexer heads and output groups must be divisible by TP")


def _parallel_spec(*, module: nn.Module, member: Any) -> ParallelModuleSpec:
    """Bind resources only to parallel members; standalone math has no mesh dependency."""
81
82
83
84
85
86
87
88
89
def _parallel_spec(*, module: nn.Module, member: Any) -> ParallelModuleSpec:
    """Bind resources only to parallel members; standalone math has no mesh dependency."""
    del member
    if isinstance(module, CPCompressedSparseAttention2):
        return ParallelModuleSpec(
            "attention.csa2.cp", "cp",
            {"query_partition": ("sequence_length", "position_ids"),
             "prepare_attention_inputs": ("hidden_states", "embeddings", "shared_state", "document"),
             "exchange_attention": ("prepared", "shared_state"),
89
90
91
92
93
94
95
96
97
             "exchange_attention": ("prepared", "shared_state"),
             "launch_bank": ("tensor", "sequence_dim")}, validate=_validate_layout,
        )
    if isinstance(module, _TPCompressedSparseAttention2):
        return ParallelModuleSpec(
            "attention.csa2.tp", "mesh", {"head_reducer": (),
                                          "query_partition": ("sequence_length", "position_ids")},
            validate=_validate_layout,
        )
101
102
103
104
105
106
107
108
109
110
111
112
113
def _validate(*, config: Any, module: nn.Module | None, context: Any, member: Any) -> None:
    """Validate the source contract and supported fusion, balance and communication options."""
    del context
    if module is not None and not isinstance(module, CompressedSparseAttention2Module):
        raise TypeError("CSA2 source conversion requires the shared V4.1 attention parameter contract")
    if module is None:
        required = ("v41_compress_ratios", "v41_kv_source_layer_ids", "v41_index_source_layer_ids")
        if any(not hasattr(config, name) for name in required):
            raise ValueError("CSA2 config must include compression ratios and Full/Reindex source layers")
    arguments = member.arguments
    mode = arguments.get("indexer_load_balance", "none")
    resolve_indexer_balance_block_size(mode, arguments.get("indexer_balance_block_size"))
    validate_indexer_hybrid_threshold(mode, arguments.get("indexer_zigzag_min_length"))
hyper_parallel/components/modules/attention/compressed_sparse_attention2/compressor.py
32
33
34
35
36
37
38
39
40
    def __init__(self, config: Any, compress_ratio: int, *, apply_rope: Callable) -> None:
        """Create the learned KV pooling projections."""
        super().__init__()
        if compress_ratio < 1:
            raise ValueError(f"compress_ratio must be positive, got {compress_ratio}")
        self.compress_ratio = compress_ratio
        self.apply_rope = apply_rope
        self.wkv = nn.Linear(config.hidden_size, config.head_dim, bias=False)
        if compress_ratio > 1:
75
76
77
78
79
80
81
82
83
84
85
86
            block_plan: Optional document-local grouping and cross-rank boundary plan.
        """
        batch_size, sequence_length, _ = hidden_states.shape
        if self.compress_ratio == 1:
            latent = self.norm(self.wkv(hidden_states))
            cos, sin = compress_position_embeddings
            rotated = self.apply_rope(latent.unsqueeze(1), cos, sin).squeeze(1)
            return latent, rotated

        if block_plan is not None:
            projected = torch.cat((self.wkv(hidden_states), self.wgate(hidden_states)), dim=-1)
            projected = self.exchange_blocks(projected, block_plan)
hyper_parallel/components/modules/attention/compressed_sparse_attention2/cp_compressed_sparse_attention2.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73


def _exchange_boundary(tensor: torch.Tensor, route: Any, context: Any) -> torch.Tensor:
    """Complete projected boundary rows, including reverse participation for empty receives."""
    if not route.needs_exchange:
        return tensor
    local = tensor.movedim(1, 0).contiguous()
    parts = [local.narrow(0, offset, count)
             for offset, count in zip(route.send_offsets, route.input_splits) if count]
    send = torch.cat(parts, dim=0) if parts else local[:0]
    received = differentiable_all_to_all_single(
        send, list(route.input_splits), list(route.output_splits), group=context.mesh.get_group(),
    )
    return torch.cat((received, local), dim=0).movedim(0, 1).contiguous()


class _CPCompressor(CSA2Compressor):
    """Keep projection and boundary exchange inside the managed compressor call."""
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101

    @classmethod
    def from_module(cls, module: CSA2Compressor) -> _CPCompressor:
        """Adopt children by identity without initializing another parameter tree."""
        result = object.__new__(cls)
        torch.nn.Module.__init__(result)  # pylint: disable=unnecessary-dunder-call
        for name, child in module.named_children():
            result.add_module(name, child)
        for name, parameter in module._parameters.items():  # pylint: disable=protected-access
            result.register_parameter(name, parameter)
        # PyTorch has no public getter for buffer persistence, including None buffers.
        non_persistent_buffers = module._non_persistent_buffers_set  # pylint: disable=protected-access
        for name, buffer in module._buffers.items():  # pylint: disable=protected-access
            result.register_buffer(name, buffer, persistent=name not in non_persistent_buffers)
        result.compress_ratio = module.compress_ratio
        result.apply_rope = module.apply_rope
        result.training = module.training
        return result

    def exchange_blocks(self, projected: torch.Tensor, block_plan: Any) -> torch.Tensor:
        """Exchange only the missing projected rows for locally owned compression blocks."""
        return _exchange_boundary(projected, block_plan.route, self.cp_context)


@dataclass
class _MainAttentionWork:
137
138
139
140
141
142
143
144
145
146
        """Submit Full-layer K; Reindex reuses the already differentiable shared bank."""
        key = self._project_index_key(latent, cos, sin, index_key, key_position_embeddings)
        if not self.owns_key:
            return key
        launch = partial(_launch_bank, context=self.cp_context)
        return launch(key, 1) if block_plan is None else launch_compressed_bank(key, block_plan.counts, launch)

    def exchange_key(self, prepared: Any) -> torch.Tensor:
        """Wait only when the local/worker selection consumes Index K."""
        return prepared if isinstance(prepared, torch.Tensor) else prepared.wait()
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
                query_segments=query_segments, document_lengths=document_lengths,
                prepare_attention=prepare_attention, block_plan=block_plan,
                key_position_embeddings=key_position_embeddings, causal_upper=causal_upper,
            )
        if reduce_sum is not None or self.is_candidate_source or self.uses_candidates:
            raise NotImplementedError("Indexer overlap requires ordinary causal selection and TP=1")
        cos, sin = compress_position_embeddings
        weights = self.weights_proj(hidden_states.detach())
        weights = weights * (self.head_dim**-0.5 * self.global_num_heads**-0.5)
        launch = self._launch_selection if self._input_region is None else self._input_region
        wave = launch(query_residual, weights, (cos, sin), document_lengths)
        prepared_key = self.prepare_key(latent, cos, sin, index_key, block_plan, key_position_embeddings)
        if prepare_attention is not None:
            prepare_attention()
        prepared = self._prepare_dispatched(wave)
        key = self.exchange_key(prepared_key)
        select = self._select_dispatched if self._result_region is None else self._result_region
        result = select(prepared, key)
        del prepared
        query = self._project_index_query(query_residual, cos, sin)
        if weights.shape[-1] != query.shape[2]:
            raise ValueError("Indexer query and merge weights must have matching head counts")
        finish = self._finish_selection if self._wait_region is None else self._wait_region
        return CSA2IndexerOutput(finish(result), key, None, query, weights)

    def enable_selection_exclude(self) -> None:
        """Reuse input/selection/result transfers instead of waiting on consumed handles."""
        super().enable_selection_exclude()
195
196
197
198
199
200
201
202
203

    @torch.no_grad()
    def _launch_selection(self, qr: torch.Tensor, weights: torch.Tensor, embeddings: tuple, lengths: tuple) -> Any:
        """Use the existing task planner and dtype-preserving input transport."""
        return launch_indexer_inputs(qr, weights, embeddings, lengths, self.compress_ratio, self.balance_mode,
                                     self.cp_context.mesh.get_group(), self.balance_block_size, self.zigzag_min_length)

    @torch.no_grad()
    def _prepare_dispatched(self, wave: Any) -> tuple | None:
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222

    @torch.no_grad()
    def _prepare_dispatched(self, wave: Any) -> tuple | None:
        """Expand received qr once; cached selection needs no worker Q during replay."""
        if is_recomputing() and self._result_region is not None:
            # The result and final IDs are checkpoint exclusions. Do not retain expanded
            # worker Q or consume an already finished input receipt during recomputation.
            return None
        qr, weights, cos, sin = wave.wait()
        query = self._project_worker_index_query(qr, cos, sin, wave.owner_queries)
        return query, weights, wave

    @torch.no_grad()
    def _select_dispatched(self, prepared: tuple, key: torch.Tensor) -> Any:
        """Consume worker Q once and launch the inverse ID transfer."""
        query, weights, wave = prepared
        selected = self._select_indices(query, key, weights, None, 0, None, None, wave.route.segments)[0]
        return wave.launch_result(selected[0])

    @staticmethod
    @torch.no_grad()
    def _finish_selection(result: Any) -> torch.Tensor:
220
221
222
223
224
225
226
227
228
    @staticmethod
    @torch.no_grad()
    def _finish_selection(result: Any) -> torch.Tensor:
        """Cache completed IDs; replay never consumes an already finished handle."""
        return result.wait().unsqueeze(0)


class _TPCompressedSparseAttention2(CompressedSparseAttention2Module):
    """Only internal head SUM; framework boundaries own input/output TP and SP."""
234
235
236
237
238
239
240
241
242
243
        """Borrow the existing TP group without installing another TP executor."""
        if self._parallel_bound:
            raise ValueError("CSA2 parallel resources are already bound")
        if getattr(binding.mesh_binding.mesh_context, "tp_size", 1) > 1:
            mesh = binding.mesh_binding.axis_mesh("tp")
            self._head_sum = partial(_reduce_scores, group=mesh.get_group())
        self._parallel_bound = True

    def head_reducer(self) -> Callable | None:
        """Provide head SUM before TopK and KL normalization."""
244
245
246
247
248
249
250
251
252
253
254
        return self._head_sum

    def query_partition(self, sequence_length: int, position_ids: torch.Tensor) -> tuple[int, int]:
        """Require binding for a selected parallel member before any model computation."""
        if not self._parallel_bound:
            raise RuntimeError("parallel CSA2 must be bound through the family mesh before forward")
        return super().query_partition(sequence_length, position_ids)


class CPCompressedSparseAttention2(_TPCompressedSparseAttention2):
    """Own CP preparation/exchange stages while inheriting the complete local forward."""
264
265
266
267
268
269
270
271
272
            indexer_load_balance, indexer_balance_block_size,
        )
        validate_indexer_hybrid_threshold(indexer_load_balance, indexer_zigzag_min_length)
        if main_kv_comm not in ("all_gather", "all_to_all_v"):
            raise ValueError("main_kv_comm must be 'all_gather' or 'all_to_all_v'")
        super().__init__(module, config=config, layer_idx=layer_idx,
                         replace_indexer=replace_indexer, use_fused_ops=use_fused_ops)
        self.indexer_load_balance = indexer_load_balance
        self.main_kv_comm = main_kv_comm
277
278
279
280
281
282
283
284
285
            self.indexer.balance_mode = indexer_load_balance
            self.indexer.balance_block_size = indexer_balance_block_size
            self.indexer.zigzag_min_length = indexer_zigzag_min_length
        if self.is_kv_source and isinstance(getattr(self, "compressor", None), CSA2Compressor):
            self.compressor = _CPCompressor.from_module(self.compressor)

    def bind_parallel(self, binding: Any) -> None:
        """Bind all stages to the framework-owned CP context and optional TP group."""
        if (binding.cp_context is None or binding.cp_context.size <= 1
283
284
285
286
287
288
289
290
291
    def bind_parallel(self, binding: Any) -> None:
        """Bind all stages to the framework-owned CP context and optional TP group."""
        if (binding.cp_context is None or binding.cp_context.size <= 1
                or not 0 <= binding.cp_context.rank < binding.cp_context.size):
            raise ValueError("CP CSA2 requires an existing CP context with size > 1 and 0 <= rank < size")
        super().bind_parallel(binding)
        self.cp_context = binding.cp_context
        if self.is_index_source:
            self.indexer.cp_context = self.cp_context
289
290
291
292
293
294
295
296
297
        self.cp_context = binding.cp_context
        if self.is_index_source:
            self.indexer.cp_context = self.cp_context
        if isinstance(getattr(self, "compressor", None), _CPCompressor):
            self.compressor.cp_context = self.cp_context

    def query_partition(self, sequence_length: int, position_ids: torch.Tensor) -> tuple[int, int]:
        """Derive packed row addresses independently of RoPE position IDs."""
        del position_ids  # Position values are already encoded in the supplied RoPE embeddings.
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
        packed = document.packed
        boundaries = (0, document.global_length) if packed is None else packed.document_boundaries()
        if local_length % self.compress_ratio == 0 and all(value % self.compress_ratio == 0 for value in boundaries):
            return None, None
        if packed is None:
            packed = SharedCompressedPackedSequence(torch.tensor(boundaries), rank * local_length,
                                                     local_length, document.global_length)
        packed = packed.prepare(device, (self.compress_ratio,))
        plan = document_compression_plan(boundaries, self.compress_ratio, local_length, size, rank)
        source_positions = embeddings["compress"]
        positions = packed.cached_compressed_positions(plan.ratio, source_positions)
        if positions is None:
            exchanged = _exchange_boundary(torch.cat(source_positions, dim=-1), plan.route, self.cp_context)
            rows = plan.indices(device)[1]
            positions = exchanged.index_select(1, rows).chunk(2, dim=-1)
            packed.cache_compressed_positions(plan.ratio, source_positions, positions)
        return plan, positions

    def launch_bank(self, tensor: torch.Tensor, sequence_dim: int) -> Any:
        """Launch a differentiable rank-ordered gather through CPContext."""
        return _launch_bank(tensor, sequence_dim, self.cp_context)
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
        return _launch_bank(tensor, sequence_dim, self.cp_context)

    def exchange_raw(self, tensor: torch.Tensor, sequence_dim: int, route: Any) -> Any:
        """Launch the same-document raw SWA halo."""
        return async_sequence_dispatch(tensor, sequence_dim, route, self.cp_context.mesh.get_group())

    def exchange_main(self, tensor: torch.Tensor, sequence_dim: int, route: Any) -> Any:
        """Launch the main compressed document prefix."""
        return async_sequence_dispatch(tensor, sequence_dim, route, self.cp_context.mesh.get_group())

    def _launch_compressed_bank(self, compressed: torch.Tensor, route: Any, plan: Any) -> Any:
        """Respect the compressed bank's actual owner counts and physical layout."""
        if route is not None:
            return self.exchange_main(compressed, 1, route)
        if plan is not None:
            return launch_compressed_bank(compressed, plan.counts, self.launch_bank)
        return self.launch_bank(compressed, 1)

    def prepare_attention(self, work: _MainAttentionWork) -> None:
        """Submit delayed main KV behind Index K, then compute the main query."""
347
348
349
350
351
352
353
354
355
356

    def prepare_attention(self, work: _MainAttentionWork) -> None:
        """Submit delayed main KV behind Index K, then compute the main query."""
        if work.launch_main_bank is not None:
            work.compressed_handle = work.launch_main_bank()
            work.launch_main_bank = None
        work.query = self._expand_query(work.query_residual, work.cos, work.sin)

    def prepare_attention_inputs(self, hidden_states: torch.Tensor, embeddings: dict,
                                 shared_state: SharedCompressedAttentionState,
hyper_parallel/components/modules/attention/compressed_sparse_attention2/document_layout.py
89
90
91
92
93
94
95
96
97
        The runtime calls this before capture. Eager retains its real boundaries;
        graph inputs carry token-shaped metadata, not a variable document list.
        """
        if self.local_query_start != 0 or self.local_query_length != self.global_sequence_length:
            return
        self.segment_start_mask(device)
        object.__setattr__(self, "_use_prepared_packing_inputs", True)

    def router_metadata(self, device: torch.device) -> tuple[torch.Tensor, int]:
212
213
214
215
216
217
218
219
220
            compress_ratio: Compression ratio of the consuming layer.
            segment_starts: Optional precomputed global sample starts for local queries.
        """
        if compress_ratio <= 0:
            raise ValueError("minimum_key_indices requires a positive compression ratio")
        cached = self._prepared_minima.get((torch.device(device), compress_ratio))
        if cached is not None:
            return cached
        self.validate_compression_ratio(compress_ratio)
225
226
227
228
229
230
231
232
233
        # exclusive cumsum as the document's global compressed-key base.
        boundaries = self.cu_seq_lens.to(device=device, dtype=torch.long)
        documents = self._prepared_sequences.get(device)
        if documents is None:
            documents = torch.bucketize(
                self.local_positions(device).squeeze(0), boundaries[1:], right=True,
            ).unsqueeze(0)
        counts = (boundaries[1:] - boundaries[:-1]) // compress_ratio
        offsets = torch.cat((counts.new_zeros(1), counts.cumsum(dim=0)[:-1]))
247
248
249
250
251
252
253
254
255
            device: Device on which tensors and prepared geometry are consumed.
            compress_ratio: Compression ratio of the consuming layer.
        """
        if compress_ratio <= 0:
            raise ValueError("causal_key_upper_bounds requires a positive compression ratio")
        key = (torch.device(device), compress_ratio)
        cached = self._prepared_bounds.get(key)
        if cached is None:
            device = torch.device(device)
271
272
273
274
275
276
277
278
279
280
281
282
283
284
            return cached
        if self.local_query_start < 0 or self.local_query_length < 0 or (
                self.local_query_start + self.local_query_length > self.global_sequence_length
        ):
            raise ValueError("packed local query interval must lie within the global sequence")
        boundaries = self.cu_seq_lens.to(dtype=torch.long)
        if boundaries.ndim != 1 or boundaries.numel() < 2 or int(boundaries[0]) != 0:
            raise ValueError("packed cu_seq_lens must be one-dimensional and start with zero")
        if int(boundaries[-1]) != self.global_sequence_length:
            raise ValueError(
                "packed cu_seq_lens must cover global_sequence_length: "
                f"{int(boundaries[-1])} versus {self.global_sequence_length}"
            )
        if torch.any(boundaries[1:] <= boundaries[:-1]):
291
292
293
294
295
296
297
298
    @staticmethod
    def validate_compression_ratio(compress_ratio: int) -> None:
        """Validate the ratio; complete block planning handles natural document lengths."""
        if compress_ratio < 0:
            raise ValueError("compression ratio must be nonnegative")

    def is_compression_aligned(self, compress_ratio: int) -> bool:
        """Report whether every document boundary lies on a complete-block edge.
307
308
309
310
311
312
313
314
        if compress_ratio <= 1:
            return True
        if self._restored_from_packing_tensors:
            return 0 < self._packing_alignment and self._packing_alignment % compress_ratio == 0
        return not any(boundary % compress_ratio for boundary in self.document_boundaries())

    def compressed_key_length(self, compress_ratio: int) -> int:
        """Return the total number of complete compressed keys in the batch.
330
331
332
333
334
335
336
337
338
339
        if self._restored_from_packing_tensors or ratio <= 1:
            return None
        boundaries = self.document_boundaries()
        if self.local_query_length % ratio == 0 and all(value % ratio == 0 for value in boundaries):
            return None
        if self.local_query_start or self.local_query_length != self.global_sequence_length:
            raise ValueError("local document block planning requires the complete local sequence")
        blocks = tuple((start, (end - start) // ratio) for start, end in zip(boundaries, boundaries[1:])
                       if (end - start) // ratio)
        return DocumentBlockPlan(ratio, blocks)
344
345
346
347
348
349
350
351
352
        versions = tuple(None if value.is_inference() else value._version for value in embeddings)  # pylint: disable=protected-access
        cached = self._compression_rope.get(ratio)
        if (cached is not None and cached[0] is cos and cached[1] is sin and cached[2] == versions
                and None not in versions and not cos.requires_grad and not sin.requires_grad):
            return cached[3]
        return None

    def cache_compressed_positions(self, ratio: int, embeddings: tuple, positions: tuple) -> None:
        """Retain only non-differentiable position metadata for the same source tensors."""
350
351
352
353
354
355
356
357
358

    def cache_compressed_positions(self, ratio: int, embeddings: tuple, positions: tuple) -> None:
        """Retain only non-differentiable position metadata for the same source tensors."""
        if any(value.requires_grad for value in embeddings):
            return
        versions = tuple(None if value.is_inference() else value._version for value in embeddings)  # pylint: disable=protected-access
        self._compression_rope[ratio] = (*embeddings, versions, positions)

    def compressed_positions(self, plan: Any, embeddings: tuple) -> tuple:
358
359
360
361
362
363
364
365
366
    def compressed_positions(self, plan: Any, embeddings: tuple) -> tuple:
        """Select local block-start positions without any tensor exchange."""
        cached = self.cached_compressed_positions(plan.ratio, embeddings)
        if cached is not None:
            return cached
        rows = plan.indices(embeddings[0].device)[1]
        positions = tuple(value.index_select(1, rows) for value in embeddings)
        self.cache_compressed_positions(plan.ratio, embeddings, positions)
        return positions
382
383
384
385
386
387
388
389
390
        if self._use_prepared_packing_inputs:
            return [self._prepared_starts, self._prepared_positions,
                    self._prepared_masks, self._prepared_sequences,
                    self._prepared_minima], ("packing", self._packing_alignment)
        return [self.cu_seq_lens], (self.local_query_start, self.local_query_length, self.global_sequence_length)

    @classmethod
    def pytree_unflatten(cls, children: Any, context: tuple) -> SharedCompressedPackedSequence:
        """Restore prepared metadata without reading boundary values during capture."""
388
389
390
391
392
393
394
395
396
    @classmethod
    def pytree_unflatten(cls, children: Any, context: tuple) -> SharedCompressedPackedSequence:
        """Restore prepared metadata without reading boundary values during capture."""
        if context[0] != "packing":
            return cls(children[0], *context)
        starts, positions, masks, sequences, minima = children
        reference = next(iter(starts.values()))
        length = reference.shape[-1]
        packed = cls(reference.new_empty(0), 0, length, length)
hyper_parallel/components/modules/attention/compressed_sparse_attention2/indexer.py
55
56
57
58
59
60
61
62
63
64
65
66
67
        raise ValueError("Fused LightningIndexer requires query_segments when minimum_key_indices is set")
    validate_indexer_tensors(query, key, merge_weight)
    if query.device.type != "npu":
        raise RuntimeError(f"Fused LightningIndexer requires NPU inputs; got device={query.device}")
    if query_segments is None:
        length = query.shape[1]
        raw_end = query_offset + length
        query_segments = ((0, length, 0, raw_end // compress_ratio, raw_end % compress_ratio),)
    return lightning_indexer(query, key, merge_weight, compress_ratio, top_k, query_segments)

def _causal_key_bounds(
        query: torch.Tensor, ratio: int, query_offset: int,
        minimum_key_indices: torch.Tensor | None, segments: tuple | None,
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
        use_fused: Select LI V2 and raise if a nonempty call is unsupported.
            False explicitly selects the numerical reference.
    """
    if compress_ratio <= 0:
        raise ValueError(f"compress_ratio must be positive, got {compress_ratio}")
    if query_chunk_size <= 0:
        raise ValueError(f"query_chunk_size must be positive, got {query_chunk_size}")
    if query.ndim != 4:
        raise ValueError(f"Indexer query must have shape [B, Q, H, D], got {tuple(query.shape)}")
    batch_size, sequence_length, _, head_dim = query.shape
    if key.ndim != 3 or key.shape[::2] != (batch_size, head_dim):
        raise ValueError(
            "compressed index key must have shape [batch, compressed_sequence, head_dim]"
        )
    if merge_weight.shape != query.shape[:3]:
        raise ValueError(
            f"merge_weight must have shape {tuple(query.shape[:3])}, got {tuple(merge_weight.shape)}"
        )
    compressed_length = key.shape[1]
    if minimum_key_indices is not None and minimum_key_indices.shape != query.shape[:2]:
        raise ValueError("minimum_key_indices must have shape [batch, query]")
    top_k = min(sparse_count, compressed_length)
    if top_k <= 0 or sequence_length == 0:
        return torch.empty(
            batch_size,
            sequence_length,
            max(top_k, 0),
            dtype=torch.int32,
166
167
168
169
170
171
172
173
174
        # SAC may retain the matmul result; do not mutate its cached tensor.
        scores = torch.matmul(query[:, start:end].float(), key_fp32).relu()
        scores = (scores * merge_weight[:, start:end].float().unsqueeze(-1)).sum(dim=2)
        if reduce_sum is not None:
            scores = reduce_sum(scores)
        # Bounds are [1, S]; slice the query axis so the mask covers this chunk.
        visible = visible_keys[:, start:end].unsqueeze(-1)
        scores.masked_fill_(key_positions >= visible, float("-inf"))
        if minimum_key_indices is not None:
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
    The newest reachable partial block is pinned into the candidate set, then
    the remaining blocks compete by their maximum position score. ``logits``
    must already contain ``-inf`` at causally unreachable positions.
    """
    if topk_blocks <= 0:
        raise ValueError(f"topk_blocks must be positive, got {topk_blocks}")
    if block_size <= 0:
        raise ValueError(f"block_size must be positive, got {block_size}")
    width = logits.shape[-1]
    if width == 0:
        return torch.zeros_like(logits, dtype=torch.bool)
    padding = -width % block_size
    scores = torch.nn.functional.pad(logits, (0, padding), value=float("-inf"))
    scores = scores.unflatten(-1, (-1, block_size)).amax(dim=-1)
    num_blocks = scores.shape[-1]
    if isinstance(compress_lens, torch.Tensor):
        last = (compress_lens.to(device=logits.device) - 1) // block_size
    else:
        last = (compress_lens - 1) // block_size
    block_positions = torch.arange(num_blocks, device=logits.device)
    scores = scores.masked_fill(block_positions == last, float("inf"))
    top = scores.topk(min(topk_blocks, num_blocks), dim=-1)
    keep = torch.zeros_like(scores, dtype=torch.bool)
    keep.scatter_(-1, top.indices, top.values > float("-inf"))
    return keep.repeat_interleave(block_size, dim=-1)[..., :width]

def select_candidate_block_indices(
        logits: torch.Tensor,
        compress_lens: torch.Tensor | int,
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
    Storing block ids uses ``block_size`` times less cross-layer state than
    expanded position ids and avoids the full ``[batch, query, key]`` boolean
    mask used by the released inference reference. Invalid slots are ``-1``.
    """
    if topk_blocks <= 0:
        raise ValueError(f"topk_blocks must be positive, got {topk_blocks}")
    if block_size <= 0:
        raise ValueError(f"block_size must be positive, got {block_size}")
    width = logits.shape[-1]
    if width == 0:
        return torch.empty(*logits.shape[:-1], 0, dtype=torch.int32, device=logits.device)
    padding = -width % block_size
    scores = torch.nn.functional.pad(logits, (0, padding), value=float("-inf"))
    scores = scores.unflatten(-1, (-1, block_size)).amax(dim=-1)
    num_blocks = scores.shape[-1]
    if isinstance(compress_lens, torch.Tensor):
        last = (compress_lens.to(device=logits.device) - 1) // block_size
    else:
        last = (compress_lens - 1) // block_size
    block_positions = torch.arange(num_blocks, device=logits.device)
    scores = scores.masked_fill(block_positions == last, float("inf"))
    top = scores.topk(min(topk_blocks, num_blocks), dim=-1, sorted=False)
    return top.indices.masked_fill(top.values == float("-inf"), -1).to(torch.int32)

def compressed_causal_candidates(
        query: torch.Tensor,
        key: torch.Tensor,
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
        reduce_sum: Callable[[torch.Tensor], torch.Tensor] | None = None,
        minimum_key_indices: torch.Tensor | None = None,
) -> torch.Tensor:
    """Build compact blockwise candidate ids in bounded query chunks."""
    _, sequence_length, _, _ = query.shape
    compressed_length = key.shape[1]
    if minimum_key_indices is not None and minimum_key_indices.shape != query.shape[:2]:
        raise ValueError("minimum_key_indices must have shape [batch, query]")
    key_fp32 = key.float().transpose(1, 2).unsqueeze(1)
    key_positions = torch.arange(compressed_length, device=query.device).view(1, 1, -1)
    candidate_chunks = []
    for start in range(0, sequence_length, query_chunk_size):
        end = min(start + query_chunk_size, sequence_length)
        scores = torch.matmul(query[:, start:end].float(), key_fp32).relu()
        scores = (scores * merge_weight[:, start:end].float().unsqueeze(-1)).sum(dim=2)
        if reduce_sum is not None:
            scores = reduce_sum(scores)
        visible = (
            torch.arange(query_offset + start, query_offset + end, device=query.device) + 1
        ) // compress_ratio
        scores.masked_fill_(key_positions >= visible.view(1, -1, 1), float("-inf"))
        if minimum_key_indices is not None:
            minimum = minimum_key_indices[:, start:end].unsqueeze(-1)
            scores.masked_fill_(key_positions < minimum, float("-inf"))
        candidate_chunks.append(
            select_candidate_block_indices(
                scores,
                visible.view(1, -1, 1),
                topk_blocks,
288
289
290
291
292
293
294
295
296
                topk_blocks,
                block_size,
            )
        )
    return torch.cat(candidate_chunks, dim=1)

def compressed_causal_topk_and_candidates(
        query: torch.Tensor,
        key: torch.Tensor,
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336

    ``causal_upper`` supplies the packed per-query causal bound for eager and
    graph execution; it must be compression-aligned packed input when given.
    """
    if compress_ratio <= 0:
        raise ValueError(f"compress_ratio must be positive, got {compress_ratio}")
    if query_chunk_size <= 0:
        raise ValueError(f"query_chunk_size must be positive, got {query_chunk_size}")
    batch_size, sequence_length, _, head_dim = query.shape
    if key.ndim != 3 or key.shape[::2] != (batch_size, head_dim):
        raise ValueError(
            "compressed index key must have shape [batch, compressed_sequence, head_dim]"
        )
    if merge_weight.shape != query.shape[:3]:
        raise ValueError(
            f"merge_weight must have shape {tuple(query.shape[:3])}, got {tuple(merge_weight.shape)}"
        )
    compressed_length = key.shape[1]
    if minimum_key_indices is not None and minimum_key_indices.shape != query.shape[:2]:
        raise ValueError("minimum_key_indices must have shape [batch, query]")
    top_k = min(sparse_count, compressed_length)
    if top_k <= 0:
        empty_topk = torch.empty(
            batch_size,
            sequence_length,
            0,
            dtype=torch.int32,
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
            0,
            dtype=torch.int32,
            device=query.device,
        )
        return empty_topk, empty_topk

    key_fp32 = key.float().transpose(1, 2).unsqueeze(1)
    key_positions = torch.arange(compressed_length, device=query.device).view(1, 1, -1)
    selected_chunks = []
    candidate_chunks = []
    for start in range(0, sequence_length, query_chunk_size):
        end = min(start + query_chunk_size, sequence_length)
        scores = torch.matmul(query[:, start:end].float(), key_fp32).relu()
        scores = (scores * merge_weight[:, start:end].float().unsqueeze(-1)).sum(dim=2)
        if reduce_sum is not None:
            scores = reduce_sum(scores)
        visible = (
            causal_upper[:, start:end] if causal_upper is not None else
            (torch.arange(query_offset + start, query_offset + end, device=query.device) + 1) // compress_ratio
        )
        scores.masked_fill_(key_positions >= visible.view(1, -1, 1), float("-inf"))
        if minimum_key_indices is not None:
            minimum = minimum_key_indices[:, start:end].unsqueeze(-1)
            scores.masked_fill_(key_positions < minimum, float("-inf"))
        top = scores.topk(top_k, dim=-1, sorted=False)
        indices = top.indices.masked_fill(~torch.isfinite(top.values), compressed_length)
        indices = indices.sort(dim=-1).values
        selected_chunks.append(indices.masked_fill(indices == compressed_length, -1).to(torch.int32))
        candidate_chunks.append(
            select_candidate_block_indices(
                scores,
                visible.view(1, -1, 1),
                topk_blocks,
367
368
369
370
371
372
373
374
375
                topk_blocks,
                block_size,
            )
        )
    return torch.cat(selected_chunks, dim=1), torch.cat(candidate_chunks, dim=1)

def compressed_candidate_topk(
        query: torch.Tensor,
        key: torch.Tensor,
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424

    ``causal_upper`` supplies the packed per-query causal bound for eager and
    graph execution; it must be compression-aligned packed input when given.
    """
    if compress_ratio <= 0:
        raise ValueError(f"compress_ratio must be positive, got {compress_ratio}")
    if block_size <= 0:
        raise ValueError(f"block_size must be positive, got {block_size}")
    if query_chunk_size <= 0:
        raise ValueError(f"query_chunk_size must be positive, got {query_chunk_size}")
    batch_size, sequence_length, _, head_dim = query.shape
    if key.ndim != 3 or key.shape[::2] != (batch_size, head_dim):
        raise ValueError(
            "compressed index key must have shape [batch, compressed_sequence, head_dim]"
        )
    if merge_weight.shape != query.shape[:3]:
        raise ValueError(
            f"merge_weight must have shape {tuple(query.shape[:3])}, got {tuple(merge_weight.shape)}"
        )
    if candidate_blocks.ndim != 3 or candidate_blocks.shape[:2] != query.shape[:2]:
        raise ValueError(
            "candidate_blocks must have shape [batch, query, candidate_blocks], "
            f"got {tuple(candidate_blocks.shape)}"
        )
    if minimum_key_indices is not None and minimum_key_indices.shape != query.shape[:2]:
        raise ValueError("minimum_key_indices must have shape [batch, query]")

    compressed_length = key.shape[1]
    candidate_width = candidate_blocks.shape[-1] * block_size
    top_k = min(sparse_count, candidate_width)
    if top_k <= 0:
        return torch.empty(
            batch_size,
            sequence_length,
            0,
            dtype=torch.int32,
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
            dtype=torch.int32,
            device=query.device,
        )

    block_offsets = torch.arange(block_size, device=query.device)
    batch_indices = torch.arange(batch_size, device=query.device).view(-1, 1, 1)
    selected_chunks = []
    for start in range(0, sequence_length, query_chunk_size):
        end = min(start + query_chunk_size, sequence_length)
        blocks = candidate_blocks[:, start:end].long()
        block_positions = blocks.unsqueeze(-1) * block_size + block_offsets
        positions = block_positions.flatten(-2)
        visible = (
            causal_upper[:, start:end] if causal_upper is not None else
            (torch.arange(query_offset + start, query_offset + end, device=query.device) + 1) // compress_ratio
        )
        valid = (blocks.unsqueeze(-1) >= 0).expand_as(block_positions).flatten(-2)
        valid = valid & (positions < compressed_length) & (positions < visible.view(1, -1, 1))
        if minimum_key_indices is not None:
            valid = valid & (positions >= minimum_key_indices[:, start:end].unsqueeze(-1))
        safe_positions = positions.clamp(min=0, max=max(compressed_length - 1, 0))
        selected_key = key[batch_indices, safe_positions].float()
        dots = torch.einsum(
            "bchd,bckd->bchk",
            query[:, start:end].float(),
            selected_key,
        ).relu()
        scores = (dots * merge_weight[:, start:end].float().unsqueeze(-1)).sum(dim=2)
        if reduce_sum is not None:
            scores = reduce_sum(scores)
        scores.masked_fill_(~valid, float("-inf"))
        top = scores.topk(top_k, dim=-1, sorted=False)
        selected = positions.gather(-1, top.indices)
        selected.masked_fill_(~torch.isfinite(top.values), compressed_length)
        selected = selected.sort(dim=-1).values
        selected.masked_fill_(selected == compressed_length, -1)
        selected_chunks.append(selected.to(torch.int32))
    return torch.cat(selected_chunks, dim=1)

class _IndexerParameters(nn.Module):
    """Construct the released Full or Reindex Lightning Indexer state."""
502
503
504
505
506
507
508
509
510
    def __init__(self, module: nn.Module | None = None, *, config: Any = None,
                 compress_ratio: int = 1, layer_idx: int = 0, apply_rope: Callable | None = None) -> None:
        """Create or adopt projections without changing checkpoint names."""
        if (module is None) == (config is None):
            raise ValueError("CSA2 Indexer requires exactly one of config or module")
        if module is None:
            module = _IndexerParameters(config, compress_ratio, layer_idx)
        super().__init__()
        required = ("q_b_proj", "weights_proj")
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
        super().__init__()
        required = ("q_b_proj", "weights_proj")
        missing = [name for name in required if not hasattr(module, name)]
        if missing:
            raise TypeError(f"shared compressed DSA indexer is missing: {missing}")
        for name, child in module._modules.items():  # pylint: disable=protected-access
            self.add_module(name, child)
        for name, parameter in module._parameters.items():  # pylint: disable=protected-access
            self.register_parameter(name, parameter)
        for name, buffer in module._buffers.items():  # pylint: disable=protected-access
            self.register_buffer(name, buffer, persistent=name not in module._non_persistent_buffers_set)
        self.apply_rope = apply_rope if apply_rope is not None else getattr(module, "apply_rope", None)
        if self.apply_rope is None:
            raise ValueError("CSA2 Indexer requires the enclosing attention's rotary function")
        self.use_fused = getattr(module, "use_fused", False)
        self.compress_ratio = module.compress_ratio
        self.global_num_heads = getattr(module, "global_num_heads", getattr(module, "num_heads", None))
        self.head_dim = module.head_dim
541
542
543
544
545
546
547
548
549
550
551
552
553
554
    ) -> torch.Tensor:
        """Project queries with their original rotary positions, including moved tasks."""
        query = self.q_b_proj(query_residual.detach())
        if query.shape[-1] % self.head_dim:
            raise ValueError(
                f"Indexer query width {query.shape[-1]} is not divisible by head_dim {self.head_dim}"
            )
        query = query.view(*query_residual.shape[:2], -1, self.head_dim)
        if sequence_major:
            return self.apply_rope(query, cos, sin, unsqueeze_dim=2)
        return self.apply_rope(query.transpose(1, 2), cos, sin).transpose(1, 2)

    @torch.no_grad()
    def _project_worker_index_query(
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598

        Returns:
            Worker Index Q in sequence-major layout, excluding padded rows.
        """
        if owner_query_length <= 0:
            raise ValueError("Indexer owner query length must be positive")
        batch, length = query_residual.shape[:2]
        if length == owner_query_length:
            return self._project_index_query(query_residual, cos, sin, sequence_major=True)
        if not length:
            query = self.q_b_proj(query_residual.detach())
            return query.view(batch, 0, query.shape[-1] // self.head_dim, self.head_dim)

        query = None
        for start in range(0, length, owner_query_length):
            end = min(start + owner_query_length, length)
            chunk = query_residual[:, start:end].detach()
            if end - start < owner_query_length:
                chunk = torch.nn.functional.pad(chunk, (0, 0, 0, owner_query_length - (end - start)))
            projected = self.q_b_proj(chunk)
            if query is None:
                query = projected.new_empty((batch, length, projected.shape[-1]))
            query[:, start:end].copy_(projected[:, :end - start])
            del projected, chunk
        query = query.view(batch, length, query.shape[-1] // self.head_dim, self.head_dim)
        return self.apply_rope(query, cos, sin, unsqueeze_dim=2)

    def _project_index_key(
            self,
            latent: torch.Tensor | None,
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
            key_position_embeddings: tuple | None = None,
    ) -> torch.Tensor:
        """Project or adopt the index key without communicating."""
        if self.owns_key:
            if latent is None:
                raise RuntimeError("a Full Indexer requires the compressor latent")
            key = self.k_norm(self.wk(latent.detach()))
            compressed_length = key.shape[1]
            if key_position_embeddings is None:
                key_cos = cos[:, :compressed_length * self.compress_ratio:self.compress_ratio]
                key_sin = sin[:, :compressed_length * self.compress_ratio:self.compress_ratio]
            else:
                key_cos, key_sin = key_position_embeddings
            key = self.apply_rope(key.unsqueeze(1), key_cos, key_sin).squeeze(1)
            return key
        if index_key is None:
            raise RuntimeError("a Reindex layer requires index K from the preceding Full layer")
        return index_key

    def prepare_key(self, latent: torch.Tensor | None, cos: torch.Tensor, sin: torch.Tensor,
                    index_key: torch.Tensor | None, block_plan: Any, key_position_embeddings: tuple | None) -> Any:
646
647
648
649
650
651
652
653
654
            prepare_attention()
        query = self._project_index_query(query_residual, cos, sin)
        weights = self.weights_proj(hidden_states.detach())
        if weights.shape[-1] != query.shape[2]:
            raise ValueError("Indexer query and merge weights must have matching head counts")
        weights = weights * (self.head_dim**-0.5 * self.global_num_heads**-0.5)
        key = self.exchange_key(prepared_key)
        selected, candidates = self._run_selection(
            query, key, weights, candidate_blocks, query_offset, reduce_sum,
679
680
681
682
683
684
685
686
687
        """Select the requested implementation without changing candidate policies."""
        if self.use_fused and (self.is_candidate_source or self.uses_candidates):
            raise NotImplementedError("V4.1 fused Indexer does not support candidate-pool selection")
        if self.is_candidate_source:
            topk_indices, candidate_blocks = compressed_causal_topk_and_candidates(
                query,
                key,
                merge_weight,
                compress_ratio=self.compress_ratio,
694
695
696
697
698
699
700
701
702
703
704
                minimum_key_indices=minimum_key_indices,
                causal_upper=causal_upper,
            )
        elif self.uses_candidates:
            if candidate_blocks is None:
                raise RuntimeError("a hierarchical Reindex layer requires candidate block ids")
            topk_indices = compressed_candidate_topk(
                query,
                key,
                merge_weight,
                candidate_blocks,
hyper_parallel/components/modules/attention/compressed_sparse_attention2/indexer_kl_loss.py
71
72
73
74
75
76
77
78
79
                )
                index_relu = index_dots.relu()
                index_scores = (index_relu * weight_chunk.unsqueeze(-1)).sum(dim=2)
                if reduce_sum is not None:
                    index_scores = reduce_sum(index_scores)
                index_scores.masked_fill_(~valid, -1.0e9)

                selected_attention_key = gather_selected_keys(compressed_key, safe_indices).float()
                attention_scores = torch.einsum(
87
88
89
90
91
92
93
94
                )
                target = torch.cat((attention_scores, sink_logits), dim=-1).softmax(dim=-1)
                target = target[..., :-1].masked_fill(~valid.unsqueeze(1), 0.0).sum(dim=1)
                if reduce_sum is not None:
                    target = reduce_sum(target)
                target = target / target.sum(dim=-1, keepdim=True).clamp_min(
                    torch.finfo(torch.float32).tiny
                )
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
    ``use_fused=True`` raises for unsupported calls when ``loss_coeff != 0``;
    False explicitly selects the numerical reference. Native errors propagate.
    """
    if query_chunk_size <= 0:
        raise ValueError(f"query_chunk_size must be positive, got {query_chunk_size}")
    if not loss_coeff:
        return index_query.sum(dtype=torch.float32) * 0.0
    if index_key.shape[1] == 0:
        # Keep zero gradients connected even when no document contains a complete block.
        return (index_query[..., :0].sum(dtype=torch.float32) + index_key.sum(dtype=torch.float32)
                + merge_weight[..., :0].sum(dtype=torch.float32)) * 0.0
    if topk_indices.shape[:2] != index_query.shape[:2]:
        raise ValueError("topk_indices and index_query must share batch/query dimensions")
    if use_fused:
        if reduce_sum is not None:
            raise NotImplementedError("Fused KL does not support TP score/teacher reduction")
        if query_segments is None:
            raise ValueError("Fused KL requires document-local causal query_segments")
        validate_fused_kl_inputs(index_query, index_key, merge_weight, topk_indices)
        return sparse_lightning_indexer_kl_loss(
            index_query, index_key, merge_weight, attention_query.detach(), compressed_key.detach(),
            topk_indices, sinks.detach(), attention_scale, loss_coeff, query_chunk_size,
            compress_ratio, query_segments,
        )
hyper_parallel/distributed/context_parallel/compressed_document.py
209
210
211
212
213
214
215
216
217
218
219
        tensor: Locally owned bank [batch, keys, features].
        counts: Number of complete keys owned by each CP rank.
        launch: Existing differentiable sequence-gather launcher, taking tensor and dimension.
    """
    capacity = max(counts)
    if not capacity:
        return CompactBankGather(None, tensor, None)
    padded = tensor if tensor.shape[1] == capacity else functional.pad(
        tensor, (0, 0, 0, capacity - tensor.shape[1]),
    )
    return CompactBankGather(launch(padded, 1), tensor, _bank_slots(counts, tensor.device))