Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/modules/attention/__init__.py 100%  
hyper_parallel/components/modules/attention/deepseek_sparse_attention/__init__.py 100%  
hyper_parallel/components/modules/attention/deepseek_sparse_attention/cp_deepseek_sparse_attention.py 80.8% 58,114,131,188-189,199,203,220,223,227-232,238,240,253-258
hyper_parallel/components/modules/attention/deepseek_sparse_attention/deepseek_sparse_attention.py 57.3% 72,91,95-97,113,117-123,153-156,179,202-206,208,215-217,221-225,231-232,242-243,246-249,253,256,262-264,267,271,277-278,305,313,324,326,348,350,357-359,366,400-402,410-412,416-429,434,469,483,491,497-499,504,508-510,528-529,545,554-558,569-579,583-584,651-653,657,660,666,670,679-681,704,707,711,718-719,722,725,728,731-732,735,743,753-754,758,761-762,765-766
hyper_parallel/components/modules/attention/deepseek_sparse_attention/deepseek_sparse_attention_family.py 41.7% 41,43,46,51-56,60-61,66,70-83,92-98,103-104
hyper_parallel/components/modules/attention/deepseek_sparse_attention/cp_deepseek_sparse_attention.py
54
55
56
57
58
59
60
61
62
            if begin >= end:
                continue
            prefix_end = key_end - (query_end - end)
            if prefix_end <= key_start:
                raise ValueError(f"Sparse attention has an empty packed KV segment on CP rank {rank}")
            query_total += end - begin
            key_total += prefix_end - key_start
            query_ends.append(query_total)
            key_ends.append(key_total)
110
111
112
113
114
115
116
117
118
    queries, keys = resolve_packed_sequence_lengths(packed, total, total)
    if queries is None:
        queries = keys = [(row + 1) * global_length for row in range(batch_size)]
    if len(queries) != len(keys):
        raise ValueError("Sparse attention requires the same number of packed Q and KV documents")
    cross_row = cp_size > 1 and any(
        begin // global_length != (end - 1) // global_length
        for boundaries in (queries, keys)
        for begin, end in zip((0, *boundaries[:-1]), boundaries)
127
128
129
130
131
132
133
134
135
        )
        if any(end == previous for previous, end in zip((0, *query[:-1]), query)):
            raise ValueError(f"Sparse attention does not support zero-query packed documents on CP rank {rank}")
        if any(end == previous for previous, end in zip((0, *key[:-1]), key)):
            raise ValueError(f"Sparse attention has an empty packed KV document on CP rank {rank}")
        key_ranges = ()
        if cross_row:
            # A rank's cross-row queries are not a contiguous document suffix.
            # CANN's right-aligned causal mask needs one segment per intersection.
184
185
186
187
188
189
190
191
192
193

    @staticmethod
    def parallel_module_spec() -> ParallelModuleSpec:
        """Declare operand exchange while the local algorithm owns mathematical dispatch."""
        local_spec = sparse_attention_parallel_spec(module=None, member=None)
        return ParallelModuleSpec(
            "attention.deepseek_sparse_attention.cp", binding_kind="cp",
            stages=local_spec.stages,
            validate=validate_sparse_attention_layout,
        )
195
196
197
198
199
200
201
202
203
204
205
206
207
    def bind_parallel(self, binding: ParallelBinding) -> None:
        """Borrow an existing CPContext before FSDP installs projection hooks."""
        context = binding.cp_context
        if context is None or context.size <= 1:
            raise ValueError("DeepSeek sparse-attention CP member requires an active CPContext")
        if self.kv_cp_size != context.size:
            raise ValueError("kv_cp_size must equal the bound CPContext size")
        if self._cp_context is not None and self._cp_context.mesh is not context.mesh:
            raise ValueError("DeepSeek sparse-attention CP member already belongs to another mesh")
        self._cp_context = context

    def prepare_key_bank(
        self, index_states: tuple[torch.Tensor, ...], attention_states: tuple[torch.Tensor, ...],
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
        return _gather_key_banks(self._cp_context, self.cp_comm_overlap, index_states, attention_states, metadata)

    def exchange_attention(self, inputs: SparseAttentionInputs) -> SparseAttentionInputs:
        """Return ready key banks without taking ownership of the attention algorithm."""
        index_states, attention_states = self.prepare_key_bank(
            inputs.index_states, inputs.attention_states, inputs.metadata,
        )
        return SparseAttentionInputs(index_states, attention_states, inputs.metadata, inputs.use_dense)

    def _validate_attention_mask(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None) -> None:
        """Accept existing causal-mask carriers without reading their device contents."""
        if attention_mask is None:
            return
        batch_size, local_length = hidden_states.shape[:2]
        global_length = local_length * self._cp_context.size
        prefix_length = local_length * (self._cp_context.rank + 1)
        shapes = {
            (local_length, local_length), (local_length, global_length),
            (global_length, global_length), (local_length, prefix_length),
        }
        # TextParallelBatch constructs a global square mask after slicing token fields.
234
235
236
237
238
239
240
241
242
243
244
            (global_length, global_length), (local_length, prefix_length),
        }
        # TextParallelBatch constructs a global square mask after slicing token fields.
        # Packed endpoints, rather than mask values, remain the CANN causality contract.
        if (attention_mask.ndim != 4 or attention_mask.shape[0] not in (1, batch_size)
                or attention_mask.shape[1] != 1 or tuple(attention_mask.shape[-2:]) not in shapes):
            raise ValueError(
                "DeepSeek sparse attention CP requires a standard 4D causal mask "
                "with local/global sequence dimensions; "
                "padding and custom masks are not supported"
            )
249
250
251
252
253
254
255
256
257
258
259
260
261
262
        actual_seq_len: torch.Tensor | Sequence[int] | None,
        kwargs: dict[str, Any], *, use_dense: bool,
    ) -> SparseAttentionSequenceMetadata:
        """Validate every rank's packed geometry before any operand collective."""
        del use_dense
        if self._cp_context is None:
            raise ValueError("DeepSeek sparse-attention CP member must be bound before execution")
        self._validate_forward_inputs(hidden_states, None, past_key_values, position_ids, kwargs)
        self._validate_attention_mask(hidden_states, attention_mask)
        return build_cp_sequence_metadata(
            batch_size=hidden_states.shape[0], local_seq_len=hidden_states.shape[1],
            device=hidden_states.device, cp_size=self._cp_context.size, cp_rank=self._cp_context.rank,
            actual_seq_len=actual_seq_len, kwargs=kwargs,
        )
hyper_parallel/components/modules/attention/deepseek_sparse_attention/deepseek_sparse_attention.py
68
69
70
71
72
73
74
75
76
        queries, keys = resolve_packed_sequence_lengths(packed, total, total)
        if queries is None:
            queries = keys = [(row + 1) * local_seq_len for row in range(batch_size)]
        if len(queries) != len(keys):
            raise ValueError("Sparse attention requires the same number of packed Q and KV documents")
        return cls(
            local_seq_len,
            torch.tensor(queries, dtype=torch.int32, device=device),
            torch.tensor(keys, dtype=torch.int32, device=device),
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
    """Apply the configured RoPE convention to an attention query/key pair."""
    if position_embeddings is None:
        return query, key
    # The rotary backend imports torch_npu; defer it until positional math is requested.
    from hyper_parallel.components.functional import (  # pylint: disable=import-outside-toplevel
        apply_rotary_pos_emb, apply_rotary_pos_emb_interleave,
    )

    cos, sin = position_embeddings
    rotary_op = apply_rotary_pos_emb_interleave if interleaved else apply_rotary_pos_emb
    return rotary_op(query, key, cos, sin, unsqueeze_dim=2)


def _apply_index_rope(
    query: torch.Tensor,
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
    """Apply RoPE to the rotary portion of an indexer query/key pair."""
    if position_embeddings is None:
        return query, key
    # The rotary backend is optional for construction and CPU metadata/projection tests.
    from hyper_parallel.components.functional import (  # pylint: disable=import-outside-toplevel
        apply_rotary_pos_emb, apply_rotary_pos_emb_interleave,
    )

    cos, sin = position_embeddings
    split_sizes = (rope_head_dim, index_head_dim - rope_head_dim)
    query_rot, query_pass = torch.split(query, split_sizes, dim=-1)
    key_rot, key_pass = torch.split(key, split_sizes, dim=-1)
    rotary_op = apply_rotary_pos_emb_interleave if interleaved else apply_rotary_pos_emb
    query_rot, key_rot = rotary_op(query_rot, key_rot, cos, sin, unsqueeze_dim=2)
    return torch.cat((query_rot, query_pass), dim=-1), torch.cat((key_rot, key_pass), dim=-1)


def _absorb_query_projection(
    query: torch.Tensor,
149
150
151
152
153
154
155
156
157
158
159
    kv_lora_rank: int,
    value_head_dim: int,
) -> torch.Tensor:
    """Apply the absorbed value up-projection and restore the hidden layout."""
    output = output[..., :kv_lora_rank]
    output = output.permute(2, 0, 1, 3).reshape(num_heads, batch_size * seq_length, kv_lora_rank)
    output = torch.bmm(output, value_up_weight)
    return output.view(num_heads, batch_size, seq_length, value_head_dim).permute(1, 2, 0, 3).reshape(
        batch_size, seq_length, -1
    )

175
176
177
178
179
180
181
182
183

    Returns:
        Detached Q, K, Q-rope, K-rope, maximum and sum for the existing KL kernel.
    """
    return tuple(tensor.detach() for tensor in (query, key, query_rope, key_rope, maximum, total))


@dataclass(frozen=True)
class SparseAttentionInputs:
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
    *,
    need_stats: bool,
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
    """Run one TND FA and return dense-indexer statistics."""
    query_ends, key_ends = (lengths.tolist() for lengths in sequence_lengths)
    q_flat, k_flat, v_flat = (tensor.flatten(0, 1) for tensor in (query, key, value))
    num_heads = q_flat.shape[1]
    causal_mask = torch.ones((2048, 2048), dtype=torch.bool, device=query.device).triu(diagonal=1)
    import torch_npu  # pylint: disable=import-outside-toplevel

    result = torch_npu.npu_fusion_attention(
        q_flat.contiguous(), k_flat.contiguous(), v_flat.contiguous(), num_heads, "TND",
        pse=None, padding_mask=None, atten_mask=causal_mask, scale=module.scaling,
        pre_tockens=getattr(module, "pre_tockens", 1048576),
        next_tockens=getattr(module, "next_tockens", 0), keep_prob=1.0, inner_precise=0,
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
        pre_tockens=getattr(module, "pre_tockens", 1048576),
        next_tockens=getattr(module, "next_tockens", 0), keep_prob=1.0, inner_precise=0,
        actual_seq_qlen=query_ends, actual_seq_kvlen=key_ends, sparse_mode=3,
    )
    output = result[0].reshape(*query.shape[:3], value.shape[-1])
    if not need_stats:
        return output, None, None

    # TND FA stores each packed segment as [head, token, 8], while exposing a
    # physical [token, head, 8] shape. Dense KL consumes [head, token, 1].
    statistics = []
    starts = [0, *query_ends[:-1]]
    for statistic in result[1:3]:
        rows = statistic.reshape(-1, statistic.shape[-1])
        segments = [
            rows[start * num_heads : end * num_heads].reshape(
                num_heads, end - start, statistic.shape[-1]
            )[..., :1]
            for start, end in zip(starts, query_ends)
227
228
229
230
231
232
233
234
235
236
                num_heads, end - start, statistic.shape[-1]
            )[..., :1]
            for start, end in zip(starts, query_ends)
        ]
        statistics.append(torch.cat(segments, dim=1).detach())
    return output, statistics[0], statistics[1]


def _deepseek_v32_dense_attention(
    module: nn.Module,
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
    attention_states: tuple[torch.Tensor, ...],
    sequence_lengths: tuple[torch.Tensor, torch.Tensor],
) -> torch.Tensor:
    """Run unabsorbed MLA FA and the fused dense indexer KL on local states."""
    query, compressed_kv, query_rope, key_rope = attention_states
    projected_kv = module.kv_b_proj(compressed_kv.squeeze(2)).view(
        *compressed_kv.shape[:2], query.shape[2], module.qk_nope_head_dim + module.v_head_dim,
    )
    key, value = projected_kv.split((module.qk_nope_head_dim, module.v_head_dim), dim=-1)
    key_rope = key_rope.expand(-1, -1, query.shape[2], -1)
    need_stats = bool(module.training and not module.freeze_dsa and module.dsa_loss_coeff)
    output, maximum, total = _dense_flash_attention(
        module, torch.cat((query, query_rope), dim=-1), torch.cat((key, key_rope), dim=-1),
        value, sequence_lengths, need_stats=need_stats,
    )
    if need_stats:
        # Dense CANN operators are optional for sparse and Omni execution.
        # pylint: disable=import-outside-toplevel
        from hyper_parallel.components.functional.dsa_dense import (
            dsa_dense_indexer_kl_loss,
            dsa_dense_indexer_lse,
        )
        # pylint: enable=import-outside-toplevel
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
            dsa_dense_indexer_lse,
        )
        # pylint: enable=import-outside-toplevel

        query_lengths, key_lengths = sequence_lengths
        index_query, index_key, weights = (tensor.flatten(0, 1) for tensor in index_states)
        indexer_stats = dsa_dense_indexer_lse(
            index_query, index_key, weights, query_lengths=query_lengths, key_lengths=key_lengths,
        )
        teacher_query, teacher_key, teacher_qrope, teacher_krope, maximum, total = prepare_indexer_teacher(
            query.flatten(0, 1), key.flatten(0, 1),
            query_rope.flatten(0, 1), key_rope.flatten(0, 1), maximum, total,
        )
        loss = dsa_dense_indexer_kl_loss(
            index_query, index_key, weights, teacher_query, teacher_key,
            maximum, total, indexer_stats, scale=module.scaling,
            query_rope=teacher_qrope, key_rope=teacher_krope,
            query_lengths=query_lengths, key_lengths=key_lengths, loss_coefficient=module.dsa_loss_coeff,
273
274
275
276
277
278
279
280
281
282
            maximum, total, indexer_stats, scale=module.scaling,
            query_rope=teacher_qrope, key_rope=teacher_krope,
            query_lengths=query_lengths, key_lengths=key_lengths, loss_coefficient=module.dsa_loss_coeff,
        )
        output = aux_loss_auto_scale(output, loss)
    return output


class DeepseekSparseAttentionModule(nn.Module):
    """DeepSeek-V3.2 sparse attention with native configuration and source-module construction.
301
302
303
304
305
306
307
308
309
        self.qk_nope_head_dim = getattr(module, "qk_nope_head_dim", config.qk_nope_head_dim)
        self.v_head_dim = getattr(module, "v_head_dim", config.v_head_dim)
        self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
        if self.q_lora_rank is None:
            raise ValueError("DeepseekSparseAttention requires the Q-LoRA projection path")
        self.index_head_dim = getattr(indexer, "head_dim", config.index_head_dim)
        self.num_index_heads = getattr(
            indexer,
            "n_heads",
309
310
311
312
313
314
315
316
317
            "n_heads",
            getattr(config, "index_n_heads", getattr(config, "index_num_attention_heads", None)),
        )
        if self.num_index_heads is None:
            raise ValueError("DeepseekSparseAttention requires the number of indexer heads")
        self.index_topk = getattr(indexer, "index_topk", config.index_topk)

    def _initialize_options(self, module: nn.Module | None) -> None:
        """Read sparse attention options while preserving source scaling and RoPE conventions."""
320
321
322
323
324
325
326
327
328
329
330
        if self.scaling is None:
            self.scaling = self._config_scaling(config)
        attention_dropout = getattr(module, "attention_dropout", getattr(config, "attention_dropout", 0.0))
        if isinstance(attention_dropout, nn.Dropout):
            attention_dropout = attention_dropout.p
        if attention_dropout != 0.0:
            raise ValueError(
                "DeepseekSparseAttention requires attention_dropout=0 because "
                "the sparse-attention operator does not apply dropout"
            )
        source_rotary_interleaved = getattr(module, "rotary_interleaved", getattr(config, "rotary_interleaved", None))
344
345
346
347
348
349
350
351
352
353
354
        self.dsa_dense_warm_up = bool(
            getattr(module, "dsa_dense_warm_up", getattr(config, "dsa_dense_warm_up", False))
        )
        if getattr(module, "param_sink_number", getattr(config, "param_sink_number", 0)) > 0:
            raise ValueError("DeepseekSparseAttention does not support the parameter-sink path")
        if getattr(module, "use_mome", getattr(config, "use_mome", False)):
            raise ValueError("DeepseekSparseAttention does not support the MOME path")

    def _config_scaling(self, config: Any) -> float:
        """Apply the source-compatible YaRN factor for native construction."""
        scaling = self.qk_head_dim**-0.5
353
354
355
356
357
358
359
360
361
362
363
        """Apply the source-compatible YaRN factor for native construction."""
        scaling = self.qk_head_dim**-0.5
        rope = getattr(config, "rope_parameters", None) or getattr(config, "rope_scaling", None) or {}
        if rope.get("rope_type", rope.get("type", "default")) != "default" and rope.get("mscale_all_dim", 0):
            factor = rope["factor"]
            mscale = 1.0 if factor <= 1 else 1.0 + 0.1 * rope["mscale_all_dim"] * math.log(factor)
            scaling *= mscale * mscale
        return getattr(config, "scaling", scaling)

    def _initialize_config_layers(self, config: Any) -> None:
        """Allocate the native parameter tree without constructing a Transformers model."""
362
363
364
365
366
367
368
369
370
    def _initialize_config_layers(self, config: Any) -> None:
        """Allocate the native parameter tree without constructing a Transformers model."""
        dtype = getattr(config, "dtype", None)
        if isinstance(dtype, str):
            dtype = getattr(torch, dtype.removeprefix("torch."))
        factory_kwargs = {"device": getattr(config, "device", None), "dtype": dtype}
        bias = getattr(config, "attention_bias", False)
        self._q_latent_output_size = self.q_lora_rank
        self._kv_latent_output_size = self.kv_lora_rank + self.qk_rope_head_dim
396
397
398
399
400
401
402
403
404
405
406
        self.indexer.weights_proj = nn.Linear(config.hidden_size, self.num_index_heads, bias=False, **factory_kwargs)

    def _initialize_source_layers(self, module: nn.Module) -> None:
        """Fuse loaded down-projection values and retain the remaining Parameters."""
        q_a, kv_a = module.q_a_proj, module.kv_a_proj_with_mqa
        self._q_latent_output_size, self._kv_latent_output_size = q_a.out_features, kv_a.out_features
        can_fuse = (
            q_a.in_features == kv_a.in_features
            and q_a.weight.requires_grad == kv_a.weight.requires_grad
            and q_a.weight.device == kv_a.weight.device
            and q_a.weight.dtype == kv_a.weight.dtype
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
            and q_a.weight.dtype == kv_a.weight.dtype
            and (q_a.bias is None) == (kv_a.bias is None)
            and (q_a.bias is None or q_a.bias.requires_grad == kv_a.bias.requires_grad)
        )
        if not can_fuse:
            raise ValueError("Q and KV latent projections cannot be represented by one fused projection")
        self.linear_qkv = nn.Linear(
            q_a.in_features, q_a.out_features + kv_a.out_features, bias=q_a.bias is not None,
            device=q_a.weight.device, dtype=q_a.weight.dtype,
        )
        self.linear_qkv.weight.requires_grad_(q_a.weight.requires_grad)
        if self.linear_qkv.bias is not None:
            self.linear_qkv.bias.requires_grad_(q_a.bias.requires_grad)
        if not q_a.weight.is_meta:
            with torch.no_grad():
                self.linear_qkv.weight.copy_(torch.cat((q_a.weight, kv_a.weight), dim=0))
                if self.linear_qkv.bias is not None:
                    self.linear_qkv.bias.copy_(torch.cat((q_a.bias, kv_a.bias), dim=0))
        for name in ("q_a_layernorm", "kv_a_layernorm", "q_b_proj"):
            setattr(self, name, getattr(module, name))
        if module.kv_b_proj.bias is not None:
            raise ValueError("Absorbed KV projection requires a bias-free Linear")
        self.kv_b_proj = module.kv_b_proj
        self.o_proj, self.indexer = module.o_proj, module.indexer

    def _reuse_local_member(self, module: DeepseekSparseAttentionModule) -> None:
        """Promote a loaded unbound member without re-fusing or reinitializing values."""
        if getattr(module, "_hp_parallel_binding", None) is not None:
            raise ValueError("DeepSeek-V3.2 promotion must precede parallel binding and FSDP")
        fields = (
            "config", "layer_idx", "num_heads", "q_lora_rank", "kv_lora_rank",
            "qk_rope_head_dim", "qk_nope_head_dim", "v_head_dim", "qk_head_dim", "index_head_dim",
            "num_index_heads", "index_topk", "scaling", "rotary_interleaved", "index_rotary_interleaved",
465
466
467
468
469
470
471
472
473
        """
        super().__init__()
        del module_fqn, context
        if (config is None) == (module is None):
            raise ValueError("DeepSeek-V3.2 sparse attention requires exactly one of config or module")
        if not isinstance(kv_cp_size, int) or isinstance(kv_cp_size, bool) or kv_cp_size < 1:
            raise ValueError("kv_cp_size must be a positive integer")
        if kv_cp_strategy != "allgather":
            raise ValueError("DeepSeek sparse attention supports only kv_cp_strategy='allgather'")
479
480
481
482
483
484
485
486
487
            self._reuse_local_member(module)
        else:
            self.config = config if module is None else module.config
            if hasattr(self.config, "indexer_types"):
                raise TypeError(
                    "DeepSeek-V3.2 sparse attention does not support shared-indexer or three-value output contracts"
                )
            self._initialize_dimensions(module)
            self._initialize_options(module)
487
488
489
490
491
492
493
494
495
            self._initialize_options(module)
            if module is None:
                self._initialize_config_layers(config)
            else:
                self._initialize_source_layers(module)
        if module is not None:
            self.train(module.training)

    def reset_parameters(self) -> None:
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
            self.train(module.training)

    def reset_parameters(self) -> None:
        """Initialize native/meta parameters without resetting converted source weights."""
        if not self._config_initialization:
            return
        for child in (
            self.linear_qkv, self.q_a_layernorm, self.kv_a_layernorm, self.q_b_proj,
            self.kv_b_proj, self.o_proj, self.indexer.wq_b, self.indexer.wk,
            self.indexer.k_norm, self.indexer.weights_proj,
        ):
            child.reset_parameters()

    def make_transforms(self) -> list[WeightConverter]:
        """Describe reversible source-checkpoint to high-performance conversion."""
        if self._config_initialization:
            return []
        transforms: list[WeightConverter] = [
            WeightConverter(
                source_patterns=[
                    "q_a_proj.weight",
                    "kv_a_proj_with_mqa.weight",
524
525
526
527
528
529
530
531
532
533
                    )
                ],
            ),
        ]
        if self.linear_qkv.bias is not None:
            transforms.insert(
                1,
                WeightConverter(
                    source_patterns=["q_a_proj.bias", "kv_a_proj_with_mqa.bias"],
                    target_patterns="linear_qkv.bias",
541
542
543
544
545
546
547
548
549
                        )
                    ],
                ),
            )
        return transforms

    @staticmethod
    def _invalid_position_ids(
        position_ids: torch.Tensor | None,
550
551
552
553
554
555
556
557
558
559
560
561
562
        batch_size: int,
        seq_length: int,
    ) -> bool:
        """Return whether position IDs violate the supported dense layout."""
        if position_ids is None:
            return False
        if position_ids.ndim != 2:
            return True
        return position_ids.shape[0] not in (1, batch_size) or position_ids.shape[1] != seq_length

    @staticmethod
    def _validate_forward_inputs(
        hidden_states: torch.Tensor,
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
        position_ids: torch.Tensor | None,
        kwargs: dict[str, Any],
    ) -> None:
        """Validate inputs supported by the DeepSeek sparse-attention path."""
        if hidden_states.ndim != 3:
            raise ValueError("DeepSeek-V3.2 hidden_states must have shape [batch, sequence, hidden]")
        batch_size, seq_length = hidden_states.shape[:-1]
        if past_key_values is not None:
            raise NotImplementedError("DeepseekSparseAttention does not support KV cache")
        if DeepseekSparseAttentionModule._invalid_position_ids(position_ids, batch_size, seq_length):
            raise ValueError("position_ids must have shape [1 or batch_size, sequence_length]")
        if attention_mask is not None:
            expected_shape = (batch_size, 1, seq_length, seq_length)
            if tuple(attention_mask.shape) != expected_shape:
                raise ValueError(
                    "DeepseekSparseAttention supports only a Transformers 4D causal mask; "
                    "padding and custom masks are not supported"
                )
        if kwargs.pop("output_attentions", False):
            raise NotImplementedError("DeepseekSparseAttention does not expose attention weights")

    def _project_attention_states(
        self, hidden_states: torch.Tensor, *, use_dense: bool = False,
    ) -> tuple[torch.Tensor, tuple[torch.Tensor, ...]]:
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
        actual_q_len: torch.Tensor,
        actual_kv_len: torch.Tensor,
    ) -> torch.Tensor:
        """Attach the sparse attention KL auxiliary loss when training enables it."""
        if not (self.training and not self.freeze_dsa and self.dsa_loss_coeff):
            return attn_output
        query_tnd, key_tnd, q_rot_tnd, k_rot_tnd = (
            tensor.reshape(-1, tensor.shape[2], tensor.shape[3])
            for tensor in attention_states
        )
        query_tnd, key_tnd, q_rot_tnd, k_rot_tnd, maximum, total = prepare_indexer_teacher(
            query_tnd, key_tnd, q_rot_tnd, k_rot_tnd, *softmax_stats,
        )
        aux_loss = dsa_kl_loss(
            *index_states, query_tnd, key_tnd,
            topk_indices, maximum, total, q_rot_tnd, k_rot_tnd,
            actual_q_len, actual_kv_len, self.scaling, self.dsa_loss_coeff,
            backend="cann",
662
663
664
665
666
667
668
669
670
671
672
673
674
            topk_indices, maximum, total, q_rot_tnd, k_rot_tnd,
            actual_q_len, actual_kv_len, self.scaling, self.dsa_loss_coeff,
            backend="cann",
        )
        return aux_loss_auto_scale(attn_output, aux_loss)

    def use_dense_attention(self) -> bool:
        """Read the current training stage unless an explicit override pins it."""
        return self.dsa_dense_warm_up if self._dense_warmup_override is None else self._dense_warmup_override

    def preflight_attention(
        self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None,
        past_key_values: Any | None, position_ids: torch.Tensor | None,
675
676
677
678
679
680
681
682
683
684
        actual_seq_len: torch.Tensor | Sequence[int] | None,
        kwargs: dict[str, Any], *, use_dense: bool,
    ) -> SparseAttentionSequenceMetadata:
        """Validate local inputs and construct packed geometry before projection."""
        del use_dense
        self._validate_forward_inputs(hidden_states, attention_mask, past_key_values, position_ids, kwargs)
        return SparseAttentionSequenceMetadata.build(
            batch_size=hidden_states.shape[0], local_seq_len=hidden_states.shape[1],
            device=hidden_states.device, actual_seq_len=actual_seq_len, kwargs=kwargs,
        )
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
        self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
        metadata: SparseAttentionSequenceMetadata, *, use_dense: bool,
    ) -> SparseAttentionInputs:
        """Prepare local operands while retaining one invocation's resolved mode."""
        index_states, attention_states = self.prepare_attention(
            hidden_states, position_embeddings, use_dense=use_dense,
        )
        return SparseAttentionInputs(index_states, attention_states, metadata, use_dense)

    def exchange_attention(self, inputs: SparseAttentionInputs) -> SparseAttentionInputs:
        """Return ready operands; local attention needs no sequence exchange."""
        return inputs

    def run_attention(
        self, index_states: tuple[torch.Tensor, ...], attention_states: tuple[torch.Tensor, ...],
        sequence_lengths: tuple[torch.Tensor, torch.Tensor], *, use_dense: bool,
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
        self, index_states: tuple[torch.Tensor, ...], attention_states: tuple[torch.Tensor, ...],
        sequence_lengths: tuple[torch.Tensor, torch.Tensor], *, use_dense: bool,
    ) -> torch.Tensor:
        """Execute the shared dense/sparse kernel and restore local-head output."""
        if use_dense:
            return _deepseek_v32_dense_attention(
                self, index_states, attention_states, sequence_lengths,
            ).flatten(2)
        topk, *flattened = dsa_indexer(
            *index_states, *sequence_lengths, self.index_topk, backend="cann",
        )
        output, maximum, total = dsa_sparse_attention(
            *attention_states, topk, self.scaling, *sequence_lengths, backend="cann",
        )
        output = self._apply_auxiliary_loss(
            output, tuple(flattened), attention_states, topk, (maximum, total), *sequence_lengths,
        )
        heads = output.shape[2]
        weight = self.kv_b_proj.weight.view(
            heads, self.qk_nope_head_dim + self.v_head_dim, self.kv_lora_rank,
        )
        return _restore_attention_projection(
            output, weight[:, self.qk_nope_head_dim:].transpose(1, 2), num_heads=heads,
            batch_size=output.shape[0], seq_length=output.shape[1],
            kv_lora_rank=self.kv_lora_rank, value_head_dim=self.v_head_dim,
        )
739
740
741
742
743
744
745
746
747
        )

    def project_output(self, output: torch.Tensor) -> torch.Tensor:
        """Run the output Linear before the shared TP boundary."""
        return self.o_proj(output)

    def forward(
        self, hidden_states: torch.Tensor,
        position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
        position_ids: torch.Tensor | None = None,
        actual_seq_len: torch.Tensor | Sequence[int] | None = None, **kwargs: Any,
    ) -> tuple[torch.Tensor, None]:
        """Run causal or packed sparse attention while retaining the Transformers output ABI."""
        use_dense = self.use_dense_attention()
        metadata = self.preflight_attention(
            hidden_states, attention_mask, past_key_values, position_ids, actual_seq_len, kwargs,
            use_dense=use_dense,
        )
        inputs = self.prepare_attention_inputs(
            hidden_states, position_embeddings, metadata, use_dense=use_dense,
        )
        inputs = self.exchange_attention(inputs)
        output = self.run_attention(
            inputs.index_states, inputs.attention_states, inputs.metadata.sequence_lengths, use_dense=inputs.use_dense,
        )
        del inputs
        return self.project_output(output), None
hyper_parallel/components/modules/attention/deepseek_sparse_attention/deepseek_sparse_attention_family.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    if cp_size is not None and member.arguments.get("kv_cp_size", 1) != cp_size:
        raise ValueError("kv_cp_size must equal the job cp_size")
    config = config if module is None else module.config
    if context.get("sequence_parallel", False):
        raise ValueError("DeepSeek sparse attention does not support sequence parallelism")
    if member.axis_sizes["pp"] > 1:
        raise ValueError("DeepSeek sparse attention does not support pipeline parallelism")
    heads = getattr(module, "num_heads", getattr(config, "num_attention_heads", None))
    if heads % member.axis_sizes["tp"]:
        raise ValueError("Sparse-attention heads must be divisible by TP degree")


def sparse_attention_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec:
    """Declare every owned parameter and external token port without name fallbacks."""
    del module_fqn, member
    if context.sequence_parallel:
        raise ValueError("DeepSeek sparse attention does not support sequence parallelism")
    placements = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes}
    column_names = ("q_b_proj", "kv_b_proj")
    replica_names = (
        "linear_qkv", "q_a_layernorm", "kv_a_layernorm",
        "indexer.wq_b", "indexer.wk", "indexer.k_norm", "indexer.weights_proj",
    )
    columns = {f"{name}.{suffix}" for name in column_names for suffix in ("weight", "bias")}
    replicas = {
        f"{name}.{suffix}"
        for name in replica_names
        for suffix in ("weight", "bias")
    }
    roles = {
        **dict.fromkeys(columns, Shard(0)), **dict.fromkeys(replicas, Replicate()),
        "o_proj.weight": Shard(1), "o_proj.bias": Replicate(),
    }
    params = {}
    for name, _ in module.named_parameters(remove_duplicate=False):
        if name not in roles:
            raise ValueError(f"Sparse-attention parameter {name!r} has no declared sharding role")
        params[name] = dict(placements)
        if context.axis_sizes["tp"] > 1:
            params[name]["tp"] = roles[name]
    tokens = dict(placements)
    if context.axis_sizes["cp"] > 1:
        tokens["cp"] = Shard(1)
    output = dict(tokens)
    if context.axis_sizes["tp"] > 1:
        output["tp"] = Partial()
    return ModuleShardingSpec(
        params=params, in_src={"hidden_states": dict(tokens)}, in_dst={"hidden_states": dict(tokens)},
        out_src={"output": output}, out_dst={"output": dict(tokens)},
        out_names=("output", "attention_weights"), is_boundary=True,
    )
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108


def validate_sparse_attention_layout(*, module: nn.Module, sharding: Any, context: Any) -> None:
    """Validate the final overridden contract, including the unsupported SP boundary."""
    expected = sparse_attention_sharding(module=module, module_fqn="", member=None, context=context)
    validate_tp_boundary(sharding, expected, name="DeepSeek sparse attention")
    for field, port in (("in_src", "hidden_states"), ("out_dst", "output")):
        if getattr(sharding, field)[port].get("tp", Replicate()) != Replicate():
            raise ValueError("DeepSeek sparse attention does not support SP token-port overrides")
    if tuple(sharding.out_names or ()) != tuple(expected.out_names):
        raise ValueError("Sparse-attention output names must preserve the declared return contract")


def sparse_attention_parallel_spec(*, module: nn.Module, member: Any) -> ParallelModuleSpec:
    """Declare shared algorithm stages and validate layouts outside local computation."""
    del module, member
    return ParallelModuleSpec(
        "attention.deepseek_sparse_attention.local",
        stages={
            "preflight_attention": (
                "hidden_states", "attention_mask", "past_key_values", "position_ids",