Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/functional/npu_fusion_attention.py 100%  
hyper_parallel/components/functional/torch_attention.py 90.0% 28,42,46,108,117
hyper_parallel/components/modules/attention/compressed_sparse_attention2/compressed_sparse_attention2.py 76.0% 298-300,366,381,384
hyper_parallel/components/modules/attention/compressed_sparse_attention2/compressed_sparse_attention2_family.py 100%  
hyper_parallel/components/modules/attention/deepseek_sparse_attention/cp_deepseek_sparse_attention.py 100%  
hyper_parallel/components/modules/attention/deepseek_sparse_attention/deepseek_sparse_attention.py 100%  
hyper_parallel/components/modules/attention/deepseek_sparse_attention/deepseek_sparse_attention_family.py 100%  
hyper_parallel/components/modules/attention/gated_grouped_query_attention/cp_gated_grouped_query_attention.py 100%  
hyper_parallel/components/modules/attention/gated_grouped_query_attention/gated_grouped_query_attention.py 65.2% 120,142-145,153-155
hyper_parallel/components/modules/attention/gated_grouped_query_attention/gated_grouped_query_attention_family.py 100%  
hyper_parallel/components/modules/attention/gated_multi_latent_attention/cp_gated_multi_latent_attention.py 83.3% 60
hyper_parallel/components/modules/attention/gated_multi_latent_attention/gated_multi_latent_attention.py 36.8% 41-51,62
hyper_parallel/components/modules/attention/gated_multi_latent_attention/gated_multi_latent_attention_family.py 100%  
hyper_parallel/components/modules/attention/grouped_query_attention/cp_grouped_query_attention.py 84.6% 313,524
hyper_parallel/components/modules/attention/grouped_query_attention/grouped_query_attention.py 84.8% 244,246,248,282,284,295,312,315,319,324,373,375,572,583-585
hyper_parallel/components/modules/attention/grouped_query_attention/grouped_query_attention_family.py 80.0% 105
hyper_parallel/components/modules/attention/multi_latent_attention/cp_multi_latent_attention.py 70.8% 412,437,439,444,446,448,742
hyper_parallel/components/modules/attention/multi_latent_attention/multi_latent_attention.py 78.4% 82-84,170,183,189,195,204,206,208,210,212,277,286,288,297,410,412,433-439,494,559,741-743
hyper_parallel/components/modules/attention/multi_latent_attention/multi_latent_attention_family.py 91.7% 42,67
hyper_parallel/components/modules/common/rms_norm.py 100%  
hyper_parallel/distributed/context_parallel/wrappers.py 53.2% 1224,1259,1262,1299-1307,1309-1310,1325-1331,1333
hyper_parallel/components/functional/torch_attention.py
24
25
26
27
28
29
30
31
32
    mask = attention_mask
    if mask is not None and mask.ndim == 2:
        mask = mask.to(torch.bool)[:, None, None, :]
    elif mask is not None and mask.ndim == 3:
        mask = mask[:, None, :, :]
    return mask


def _causal_mask(query: torch.Tensor, key: torch.Tensor, mask: torch.Tensor | None,
38
39
40
41
42
43
44
45
46
47
48
49
50
    visible = key_positions[None, :] <= query_positions[:, None]
    if sliding_window is not None:
        visible &= key_positions[None, :] > query_positions[:, None] - sliding_window
    if mask is None:
        mask = visible
    elif mask.dtype == torch.bool:
        mask = mask & visible
    else:
        mask = mask.masked_fill(~visible, float("-inf"))
    return mask


def _eager_attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
104
105
106
107
108
109
110
111
112
    """
    if sliding_window is not None and (
        isinstance(sliding_window, bool) or not isinstance(sliding_window, int) or sliding_window < 1
    ):
        raise ValueError("sliding_window must be a positive integer or None")
    mask = _padding_mask(attention_mask)
    implicit_causal = (is_causal and mask is None and sliding_window is None
                       and query.shape[-2] == key.shape[-2] and implementation == "sdpa")
    if is_causal and not implicit_causal:
113
114
115
116
117
118
119
120
121
        mask = _causal_mask(query, key, mask, sliding_window)
    if implementation == "eager":
        return _eager_attention(query, key, value, mask, scaling, dropout)
    if implementation != "sdpa":
        raise ValueError("Portable attention implements only eager or sdpa")
    output = F.scaled_dot_product_attention(  # pylint: disable=not-callable
        query, key, value, attn_mask=mask, dropout_p=dropout, scale=scaling,
        is_causal=implicit_causal, enable_gqa=query.shape[1] != key.shape[1]
    )
hyper_parallel/components/modules/attention/compressed_sparse_attention2/compressed_sparse_attention2.py
294
295
296
297
298
299
300
301
302
303
304
            config=config, compress_ratio=module.compress_ratio, layer_idx=layer_idx, apply_rope=_apply_v41_rope,
        )

    if norm_cast_order is not None:
        for child in module.modules():
            if isinstance(child, RMSNormModule):
                child.rms_norm_cast_order = norm_cast_order
    return module


class CompressedSparseAttention2Module(nn.Module):
362
363
364
365
366
367
368
369
370
                or (type(child).__name__ == "DeepseekV4RMSNorm"
                    and type(child).__module__.startswith("transformers.models.deepseek_v4.")
                    and norm_cast_order != "after_weight")
                for child in module.modules()):
            raise ValueError("Changing CSA2 source norm policy requires config construction and state loading")

    def _adopt_indexer(self, replace_indexer: bool, use_fused_ops: bool) -> None:
        """Adopt the source Indexer while preserving its fusion and parallel-selection policy."""
        indexer = getattr(self, "indexer", None)
377
378
379
380
381
382
383
384
385
386
387
388
                and (not isinstance(indexer, CSA2Indexer) or indexer.use_fused != use_fused_ops)
        ):
            # Reject parallel Indexer subclasses whose policy is outside this source contract.
            if isinstance(indexer, CSA2Indexer) and type(indexer) is not CSA2Indexer:  # pylint: disable=unidiomatic-typecheck
                raise ValueError("CSA2 cannot change the fusion policy of a parallel Indexer source")
            self.indexer = CSA2Indexer(indexer, apply_rope=_apply_v41_rope)
            if getattr(indexer, "_selection_region", None) is not None:
                self.indexer.enable_selection_exclude()

    def head_reducer(self) -> Callable | None:
        """Keep local head sums; parallel members provide the complete-head reduction."""
        return None
hyper_parallel/components/modules/attention/gated_grouped_query_attention/gated_grouped_query_attention.py
116
117
118
119
120
121
122
123
124
        del source_qkv
        if self.fuse_qkv:
            self._initialize_projection(module)
        else:
            self._initialize_separate_projections(module)

    def make_transforms(self) -> list[WeightConverter]:
        """Describe reversible gated-query and grouped-QKV conversion."""
        if self._config_initialization or not self.fuse_qkv:
138
139
140
141
142
143
144
145
146
147
148
149
    def split_projection(self, hidden_states: torch.Tensor) -> tuple:
        """Keep the fused per-KV-head Q/K/V/gate checkpoint row ordering."""
        shape = hidden_states.shape[:-1]
        if not self.fuse_qkv:
            query, gate = self.q_proj(hidden_states).view(*shape, self.num_heads, 2 * self.qk_head_dim).chunk(2, dim=-1)
            key = self.k_proj(hidden_states).view(*shape, self.num_key_value_heads, self.qk_head_dim)
            value = self.v_proj(hidden_states).view(*shape, self.num_key_value_heads, self.v_head_dim)
            return query, key, value, gate.reshape(*shape, -1)
        projected = self.linear_qkv(hidden_states).view(*shape, self.num_key_value_heads, self.gated_qkv_group_width)
        query, key, value, gate = projected.split(
            (*self.qkv_split_sizes, self.num_key_value_groups * self.qk_head_dim), dim=-1)
        return query.reshape(*shape, self.num_heads, self.qk_head_dim), key, value, gate.reshape(*shape, -1)
149
150
151
152
153
154
155
156
157
158
159
        return query.reshape(*shape, self.num_heads, self.qk_head_dim), key, value, gate.reshape(*shape, -1)

    def project_query_state(self, hidden_states: torch.Tensor, positions: Any) -> tuple[torch.Tensor, torch.Tensor]:
        """Keep the per-query gate local while CP submits independent Q/K/V transfers."""
        shape = hidden_states.shape[:-1]
        query, gate = self.q_proj(hidden_states).view(*shape, self.num_heads, 2 * self.qk_head_dim).chunk(2, dim=-1)
        return self.normalize_position(query, self.q_norm, positions), gate.reshape(*shape, -1)

    def project_output(self, attention_output: torch.Tensor, output_state: torch.Tensor) -> torch.Tensor:
        """Apply the mandatory gate before the output projection."""
        return self.o_proj(attention_output.flatten(-2).contiguous() * torch.sigmoid(output_state))
hyper_parallel/components/modules/attention/gated_multi_latent_attention/cp_gated_multi_latent_attention.py
56
57
58
59
60
61
62
63
64
        super().__init__(module=module, config=config, module_fqn=module_fqn, context=context,
                         strategy=strategy, overlap=overlap, ulysses_degree=ulysses_degree, kv_exchange=kv_exchange,
                         rotary_fn=rotary_fn, attention_interface=attention_interface, fuse_latent_qkv=fuse_latent_qkv)
        if source_contract not in ("tuple", "tensor"):
            raise ValueError("Gated MLA source_contract must be tuple or tensor")
        self.source_contract = source_contract

    def prepare_output_projection(self) -> None:
        """Install the existing gated output derivative inside its managed Linear."""
hyper_parallel/components/modules/attention/gated_multi_latent_attention/gated_multi_latent_attention.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    source_extra_children = ("g_proj",)

    def forward(self, hidden_states: torch.Tensor, *args: Any, **kwargs: Any) -> Any:
        """Consume the selected source's positional arguments inside the complete family."""
        if self.source_contract == "tensor":
            names = ("attention_mask", "position_ids", "past_key_values")
            if len(args) > len(names):
                raise TypeError("NoPE source attention accepts at most three arguments after hidden_states")
            for name, value in zip(names, args):
                if name in kwargs:
                    raise TypeError(f"Multiple values for attention argument {name}")
                kwargs[name] = value
            kwargs.pop("position_ids", None)
            return super().forward(hidden_states, **kwargs)
        return super().forward(hidden_states, *args, **kwargs)

    def __init__(self, *, module: nn.Module | None = None, config: Any = None,
                 fuse_latent_qkv: bool = True, source_contract: str = "tuple") -> None:
        """Construct mandatory-gate NoPE MLA with the ordinary MLA parameter layout.
58
59
60
61
62
63
64
65
66
            module: Optional NoPE source with an enabled plain Linear output gate.
            config: Direct construction dimensions, exclusive with module; NoPE is intrinsic to this class.
        """
        if source_contract not in ("tuple", "tensor"):
            raise ValueError("Gated MLA source_contract must be tuple or tensor")
        self.source_contract = source_contract
        if module is None:
            super().__init__(config=config, fuse_latent_qkv=fuse_latent_qkv)
            self.use_nope = True
hyper_parallel/components/modules/attention/grouped_query_attention/cp_grouped_query_attention.py
309
310
311
312
313
314
315
316
317
        self.ring_context, self.kv_context, self.ulysses_context = (
            CPContext(mesh[name]) for name in names
        )
        if self.num_heads % self.ulysses_cp_size:
            raise ValueError("GQA ulysses_cp_size must divide TP-local Q heads")
        self.kv_head_repeats = self.ulysses_cp_size // math.gcd(self.ulysses_cp_size, self.num_key_value_heads)

    def _repeat_kv_heads(self, tensor: torch.Tensor) -> torch.Tensor:
        """Preserve contiguous query groups while expanding only to lcm(KV heads, U)."""
520
521
522
523
524
525
526
527
528
        causal = _validate_ring_options(self, attention_mask, options)
        lengths = _ring_document_lengths(cumulative_lengths, options)
        query, key, value, projection_state = self.project_qkv(hidden_states, positions)
        if self.ulysses_cp_size > 1:
            key, value = (self._repeat_kv_heads(tensor) for tensor in (key, value))
            if self.cp_comm_overlap:
                pending = tuple(self.ulysses_context.launch_sequence_to_head(tensor)
                                for tensor in (query, key, value))
                query, key, value = (transfer.wait() for transfer in pending)
hyper_parallel/components/modules/attention/grouped_query_attention/grouped_query_attention.py
240
241
242
243
244
245
246
247
248
249
250
251
252
        if not isinstance(fuse_qkv, bool):
            raise TypeError("GQA fuse_qkv must be boolean")
        self.fuse_qkv = fuse_qkv
        if not isinstance(use_fused_ops, bool):
            raise TypeError("GQA use_fused_ops must be boolean")
        if qk_norm_cast_order not in (None, "before_weight", "after_weight"):
            raise ValueError("qk_norm_cast_order must be before_weight, after_weight or None")
        if qk_norm_scale_kind not in (None, "scale", "offset"):
            raise ValueError("qk_norm_scale_kind must be scale, offset or None")
        self.use_fused_ops = use_fused_ops
        self.qk_norm_cast_order = qk_norm_cast_order
        self.qk_norm_scale_kind = qk_norm_scale_kind
        if (config is None) == (module is None):
278
279
280
281
282
283
284
285
286
287
288
        """Preserve parameter identity and source math when topology selects another family member."""
        if self.fuse_qkv != module.fuse_qkv:
            raise ValueError("GQA promotion cannot change the fused/split parameter representation")
        if self.use_fused_ops != module.use_fused_ops:
            raise ValueError("GQA promotion cannot change the Norm/RoPE kernel policy")
        if hasattr(self, "gated_qkv_group_width") != hasattr(module, "gated_qkv_group_width"):
            raise ValueError("GQA promotion cannot add or remove query gate parameters")
        self._inherit_norm_policy(module)
        # Promotion happens before sharding: retain weights, FQNs and conversion provenance.
        for name in ("_source_is_fused", "_source_projection_names"):
            setattr(self, name, getattr(module, name, None))
291
292
293
294
295
296
297
298
299
            if name and "." not in name:
                self.add_module(name, child)
        for name in ("q_norm", "k_norm"):
            if not hasattr(self, name):
                setattr(self, name, getattr(module, name, None))
        self._initialize_attention_options(module)
        self.training = module.training

    def _initialize_source_norms(self, module: nn.Module) -> None:
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    def _adopt_source_norm(self, norm: nn.Module, explicit: bool) -> nn.Module:
        """Select the public Norm without reinterpreting a declared offset as direct scale."""
        if not (hasattr(norm, "variance_epsilon") or hasattr(norm, "rms_norm_scale_kind")):
            if explicit:
                raise ValueError("explicit Q/K Norm policy requires a supported RMSNorm source")
            return norm
        if set(dict(norm.named_parameters())) != {"weight"}:
            raise ValueError("GQA RMSNorm requires only a weight parameter")
        declared = getattr(norm, "rms_norm_scale_kind", None)
        hf_kind = _hf_scale_kind(norm)
        if declared is None and hf_kind is not None:
            declared = "offset" if hf_kind == "offset" else "scale"
        if self.qk_norm_scale_kind is not None and declared not in (None, self.qk_norm_scale_kind):
            raise ValueError("qk_norm_scale_kind conflicts with source RMSNorm representation")
        scale_kind = self.qk_norm_scale_kind or declared or "scale"
        if scale_kind not in ("scale", "offset"):
            raise ValueError("source rms_norm_scale_kind must be scale or offset")
        norm_family = OffsetRMSNorm if scale_kind == "offset" else RMSNorm
        return norm_family(module=norm, use_fused_ops=self.use_fused_ops, cast_order=self.qk_norm_cast_order)

    def _inherit_norm_policy(self, module: nn.Module) -> None:
369
370
371
372
373
374
375
376
377
378
379
        self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, config.hidden_size, bias=output_bias, dtype=dtype)
        self.qk_norm_cast_order = self.qk_norm_cast_order or getattr(config, "qk_norm_cast_order", "after_weight")
        self.qk_norm_scale_kind = self.qk_norm_scale_kind or getattr(config, "qk_norm_scale_kind", "scale")
        if self.qk_norm_cast_order not in ("before_weight", "after_weight"):
            raise ValueError("qk_norm_cast_order must be before_weight or after_weight")
        if self.qk_norm_scale_kind not in ("scale", "offset"):
            raise ValueError("qk_norm_scale_kind must be scale or offset")
        norm_family = OffsetRMSNorm if self.qk_norm_scale_kind == "offset" else RMSNorm
        self.q_norm = (
            norm_family(config=SimpleNamespace(hidden_size=self.qk_head_dim, eps=eps),
                        use_fused_ops=self.use_fused_ops, cast_order=self.qk_norm_cast_order).to(dtype=dtype)
568
569
570
571
572
573
574
575
        options.setdefault("sliding_window", self.sliding_window)
        if self.torch_attention_implementation == "eager" and (
            self.attention_interface is npu_fusion_attention_forward
        ):
            return self._run_torch_attention(inputs, options), None
        return self.attention_interface(
            self, inputs.query, inputs.key, inputs.value, inputs.attention_mask,
            dropout=self.attention_dropout if self.training else 0.0, scaling=self.scaling, **options)
579
580
581
582
583
584
585
586
587
588
589

        Packed document boundaries require a dedicated implementation; rejecting
        them prevents accidental cross-document attention in the dense reference.
        """
        if any(options.get(name) is not None for name in PACKED_SEQUENCE_ARGUMENTS):
            raise ValueError("Torch GQA attention does not support packed document metadata")
        return torch_attention(inputs.query, inputs.key, inputs.value, inputs.attention_mask,
                               is_causal=options.get(
                                   "is_causal", self.is_causal and (inputs.attention_mask is None
                                                                   or inputs.attention_mask.ndim == 2)
                               ), scaling=self.scaling,
hyper_parallel/components/modules/attention/grouped_query_attention/grouped_query_attention_family.py
101
102
103
104
105
106
107
108
109
        raise ValueError("GQA head counts must be positive integers")
    if not isinstance(member.arguments.get("fuse_qkv", True), bool):
        raise TypeError("GQA fuse_qkv must be boolean")
    if not isinstance(member.arguments.get("use_fused_ops", True), bool):
        raise TypeError("GQA use_fused_ops must be boolean")
    options = _gqa_cp_options(config)
    if options["ulysses_cp_size"] * options["kv_cp_size"] * options["ring_cp_size"] != member.axis_sizes["cp"]:
        raise ValueError(
            "GQA CP factors must multiply to accelerator.cp_size: "
hyper_parallel/components/modules/attention/multi_latent_attention/cp_multi_latent_attention.py
408
409
410
411
412
413
414
415
416
            self.attention_interface = attention_interface
        if self.attention_dropout != 0 or self.sliding_window is not None:
            raise ValueError("MLA CP requires zero dropout and no implicit sliding window")
        if self.q_b_proj is None and (overlap or (context or {}).get("tp_size", 1) > 1):
            raise NotImplementedError("Direct-query MLA CP requires TP1 and overlap=False")
        if self.q_b_proj is not None and type(self.q_b_proj) is not nn.Linear:  # pylint: disable=unidiomatic-typecheck
            raise ValueError("MLA CP requires a plain Linear query up-projection")
        dimensions = MLADimensions(self.config.num_attention_heads, self._q_latent_output_size, self.kv_lora_rank,
                                   self.qk_nope_head_dim, self.qk_rope_head_dim, self.v_head_dim)
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
    def _source_math_options(use_fused_norm, use_fused_rotary_pos_emb, key_expansion_layout, use_nope,
                             norm_cast_order):
        """Forward explicit math choices without injecting options into the gated NoPE member."""
        if not isinstance(use_fused_rotary_pos_emb, bool):
            raise TypeError("use_fused_rotary_pos_emb must be bool")
        if key_expansion_layout not in ("bsnd", "bnsd"):
            raise ValueError("key_expansion_layout must be bsnd or bnsd")
        norm_options = {} if use_fused_norm is None else {"use_fused_norm": use_fused_norm}
        if norm_cast_order is not None:
            norm_options["norm_cast_order"] = norm_cast_order
        if key_expansion_layout != "bsnd":
            norm_options["key_expansion_layout"] = key_expansion_layout
        if use_nope is not None:
            norm_options["use_nope"] = use_nope
        if not use_fused_rotary_pos_emb:
            norm_options["use_fused_rotary_pos_emb"] = False
        return norm_options

    def parallel_module_spec(self) -> ParallelModuleSpec:
        """Declare operand/output stages; framework TP still owns its outer ports."""
738
739
740
741
742
743
744
745
746
        # Keep K assembly inside V's communication window.
        key_nope = launch_input_a2a(
            value, key_nope, input_a2a.value, overlap_backward=overlap_input_backward,
        )
        key = self.assemble_key(key_nope, key_rope, layout=self.key_expansion_layout)
        # K is complete; Q projection and its model-defined rotation can cover it.
        query_latent = launch_input_a2a(
            key, state.query_latent, input_a2a.key, overlap_backward=overlap_input_backward,
        )
hyper_parallel/components/modules/attention/multi_latent_attention/multi_latent_attention.py
78
79
80
81
82
83
84
85
86
87
88
    """
    if position_embeddings is None:
        return tensor
    if isinstance(position_embeddings, torch.Tensor) and position_embeddings.is_complex():
        pairs = torch.view_as_complex(tensor.float().reshape(*tensor.shape[:-1], -1, 2))
        rotated = pairs * position_embeddings.to(tensor.device).unsqueeze(2)
        return torch.view_as_real(rotated).flatten(-2).to(tensor.dtype)
    cos, sin = (part.to(tensor.dtype) for part in position_embeddings)
    if cos.ndim == 2:
        cos, sin = cos.unsqueeze(0), sin.unsqueeze(0)
    if interleaved:
166
167
168
169
170
171
172
173
174
        super().__init__()
        self._validate_math_options(fuse_latent_qkv, use_fused_norm, use_fused_rotary_pos_emb,
                                    key_expansion_layout, use_nope)
        if norm_cast_order not in (None, "before_weight", "after_weight"):
            raise ValueError("norm_cast_order must be before_weight, after_weight or None")
        self.norm_cast_order = norm_cast_order
        self.key_expansion_layout = key_expansion_layout
        self.use_fused_rotary_pos_emb = use_fused_rotary_pos_emb
        self.use_fused_norm = use_fused_norm
179
180
181
182
183
184
185
186
187
            if config is None:
                raise ValueError("MLA construction requires config or a source module")
            self._initialize_config(config)
            if use_nope is not None:
                self.use_nope = use_nope
            return
        if config is not None:
            raise ValueError("MLA construction accepts config or module, not both")
        self._initialize_source(module)
185
186
187
188
189
190
191
192
193
        if config is not None:
            raise ValueError("MLA construction accepts config or module, not both")
        self._initialize_source(module)
        if use_nope is not None:
            self.use_nope = use_nope
        for name in ("q_a_layernorm", "kv_a_layernorm"):
            norm = getattr(self, name, None)
            if norm is None:
                continue
191
192
193
194
195
196
197
198
199
            norm = getattr(self, name, None)
            if norm is None:
                continue
            if use_fused_norm is not None:
                setattr(self, name, RMSNorm(module=norm, use_fused_ops=use_fused_norm, cast_order=norm_cast_order))
            elif norm_cast_order is not None and getattr(norm, "rms_norm_cast_order", None) != norm_cast_order:
                raise ValueError("changing a retained source Norm requires explicit use_fused_norm")

    @staticmethod
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
    def _validate_math_options(fuse_latent_qkv, use_fused_norm, use_fused_rotary_pos_emb,
                               key_expansion_layout, use_nope):
        """Validate source-math selectors before creating or adopting parameters."""
        if not isinstance(fuse_latent_qkv, bool):
            raise TypeError("fuse_latent_qkv must be boolean")
        if use_fused_norm is not None and not isinstance(use_fused_norm, bool):
            raise TypeError("use_fused_norm must be a bool or None")
        if not isinstance(use_fused_rotary_pos_emb, bool):
            raise TypeError("use_fused_rotary_pos_emb must be bool")
        if key_expansion_layout not in ("bsnd", "bnsd"):
            raise ValueError("key_expansion_layout must be bsnd or bnsd")
        if use_nope is not None and not isinstance(use_nope, bool):
            raise TypeError("use_nope must be bool or None")

    def _initialize_source(self, module: nn.Module) -> None:
        """Read source math options and reuse its managed projection children."""
        self._read_projection_contract(module)
273
274
275
276
277
278
279
280
                if not name or "." in name:
                    continue
                if (name not in children and child is not None
                        and name not in getattr(self, "source_extra_children", ())):
                    raise ValueError(f"MLA source contains an unsupported child {name!r}")
                self.add_module(name, children.get(name, child))

        self.training = module.training
282
283
284
285
286
287
288
289
290
291
292
    def _read_projection_contract(self, module: nn.Module) -> None:
        """Validate the source latent projection representation before adopting its state."""
        self._source_is_fused = hasattr(module, "linear_qkv")
        if isinstance(module, MultiLatentAttentionModule) and module.fuse_latent_qkv != self.fuse_latent_qkv:
            raise ValueError("MLA promotion cannot change the latent projection representation")
        if self._source_is_fused and not self.fuse_latent_qkv:
            raise ValueError("Separate latent projections require a separate source representation")
        self.query_projection_name = "q_proj" if module.config.q_lora_rank is None else "q_a_proj"
        required = ("kv_a_layernorm", "kv_b_proj", "o_proj")
        if module.config.q_lora_rank is not None:
            required += ("q_a_layernorm", "q_b_proj")
293
294
295
296
297
298
299
300
301
        required += (("linear_qkv",) if self._source_is_fused else
                     (self.query_projection_name, "kv_a_proj_with_mqa"))
        missing = [name for name in required if not hasattr(module, name)]
        if missing:
            raise TypeError(f"MultiLatentAttention source module is missing: {missing}")

    def _initialize_latent_projection(self, module: nn.Module) -> None:
        """Fuse compatible down projections or retain an already-fused source."""
        self._q_latent_output_size = (self.q_lora_rank if self.q_lora_rank is not None
406
407
408
409
410
411
412
413
414
415
            "v_head_dim": config.v_head_dim,
        }
        if any(not isinstance(value, int) or isinstance(value, bool) or value <= 0
               for key, value in dimensions.items() if key != "q_lora_rank" or value is not None):
            raise ValueError("MLA dimensions must be positive integers; q_lora_rank may be None for direct queries")
        if dimensions["qk_rope_head_dim"] % 2:
            raise ValueError("MLA rotary dimension must be even")
        for name, value in dimensions.items():
            setattr(self, name, value)

429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
        # HF initialization already visits converted Linear/Norm children. The replacement
        # framework also invokes this method after it, so source conversions must not reset them again.
        if not self._config_initialization:
            return
        names = ("linear_qkv",) if self.fuse_latent_qkv else (self.query_projection_name, "kv_a_proj_with_mqa")
        for name in (*names, "q_b_proj", "kv_b_proj", "o_proj"):
            child = getattr(self, name)
            if child is not None:
                child.reset_parameters()
        if self.q_a_layernorm is not None:
            nn.init.ones_(self.q_a_layernorm.weight)
        nn.init.ones_(self.kv_a_layernorm.weight)

    def make_transforms(self) -> list[WeightConverter]:
        """Describe reversible source-checkpoint to high-performance conversion."""
490
491
492
493
494
495
496
497
498
        Returns:
            BSND features in the MLA key/query feature order.
        """
        if self.use_nope:
            return tensor
        return apply_mla_rope(
            tensor, position_embeddings,
            interleaved=self.rotary_interleaved if interleaved is None else interleaved,
            use_fused_rotary_pos_emb=self.use_fused_rotary_pos_emb,
555
556
557
558
559
560
561
562
563
        """
        if layout == "bsnd":
            return torch.cat((content, shared_key.unsqueeze(2).expand(-1, -1, content.shape[2], -1)), dim=-1)
        if layout != "bnsd":
            raise ValueError("key expansion layout must be bsnd or bnsd")
        # Keep the source BNSD expansion axis: BF16 head-gradient reductions
        # can round differently after an otherwise equivalent BSND expansion.
        native_content = content.transpose(1, 2)
        native_shared = shared_key.unsqueeze(1).expand(-1, content.shape[2], -1, -1)
737
738
739
740
741
742
743
744
745
746
747
        # Newer Transformers decoders use `cache`; keep one cache input for both
        # source signatures. CP validation still rejects any actual KV cache.
        cache = kwargs.pop("cache", None)
        if cache is not None:
            if past_key_values is not None and cache is not past_key_values:
                raise ValueError("MLA received different cache and past_key_values objects")
            past_key_values = cache
        self.validate_inputs(past_key_values)
        positions = self.prepare_positions(position_embeddings)
        state, output_state = self.prepare_attention_inputs(hidden_states)
        inputs = self.exchange_attention(
hyper_parallel/components/modules/attention/multi_latent_attention/multi_latent_attention_family.py
38
39
40
41
42
43
44
45
46
    if config is None:
        raise ValueError("MLA requires source configuration")
    if (member.family.name == "multi_latent_attention"
            and (getattr(module, "use_output_gate", False) or isinstance(getattr(module, "g_proj", None), nn.Module))):
        raise ValueError("Output-gated MLA sources require the gated MLA family")
    options = member.arguments
    exchange = _validate_mla_selectors(options)
    cp, tp = member.axis_sizes["cp"], member.axis_sizes["tp"]
    _validate_direct_query(config, cp, tp, options.get("overlap", False))
63
64
65
66
67
68
69
70
71

def _validate_mla_selectors(options):
    """Validate algorithm/communication choices independently of job topology."""
    if options.get("key_expansion_layout", "bsnd") not in ("bsnd", "bnsd"):
        raise ValueError("key_expansion_layout must be bsnd or bnsd")
    if not isinstance(options.get("overlap", False), bool):
        raise TypeError("MLA overlap must be boolean")
    if options.get("strategy", "expanded_ulysses") not in ("expanded_ulysses", "latent_kv_head"):
        raise ValueError("Unknown MLA CP strategy")
hyper_parallel/distributed/context_parallel/wrappers.py
1220
1221
1222
1223
1224
1225
1226
1227
1228
    block_type = getattr(target_module, "block_type", getattr(target_module, "layer_type", None))
    if block_type != "linear_attention" or any(
        not hasattr(target_module, name) for name in required
    ):
        raise TypeError("Packed decoder wrapper requires a Qwen3.5 linear-attention decoder.")
    original_forward = target_module.forward

    @functools.wraps(original_forward)
    def packed_forward(
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
                past_key_values=past_key_values,
                **kwargs,
            )
        if past_key_values is not None or kwargs.get("use_cache", False):
            raise NotImplementedError("Packed linear attention supports training without recurrent cache.")
        family = get_family_build_info(target_module.linear_attn)
        if family is None or family.resolved.family.name != "gated_delta_net":
            raise RuntimeError(
                "Select the GDN module family before installing packed decoder metadata forwarding.")
        residual = hidden_states
        hidden_states = target_module.input_layernorm(hidden_states)
        hidden_states = target_module.linear_attn(
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314

    Returns:
        Forward rewrite that delegates causal masking to the attention families.
    """
    del mesh, tp_mesh, cp_mesh, ep_mesh
    if not hasattr(target_module, "layers") or not hasattr(target_module, "rotary_emb"):
        raise TypeError("Packed model wrapper requires a Qwen3.5 text decoder model.")
    for layer in target_module.layers:
        attention = getattr(layer, "linear_attn", getattr(layer, "self_attn", None))
        family = get_family_build_info(attention) if attention is not None else None
        if family is None or family.resolved.family.name not in ("gated_delta_net", "gated_grouped_query_attention"):
            raise RuntimeError("Packed Qwen requires packed-capable GDN and GQA module families in every decoder.")
    original_forward = target_module.forward

    @functools.wraps(original_forward)
    def packed_forward(
        input_ids: torch.Tensor | None = None,
        attention_mask: Any = None,
        **kwargs: Any,
    ) -> Any:
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333

        Returns:
            Unmodified output from the source text-model forward.
        """
        if kwargs.get("packed_sequence_info") is not None:
            if attention_mask is not None:
                raise ValueError("Packed Qwen attention cannot also receive an explicit attention mask.")
            if kwargs.get("past_key_values") is not None or kwargs.get("use_cache", False):
                raise NotImplementedError("Packed Qwen attention requires training without recurrent cache.")
            attention_mask = {"full_attention": None, "linear_attention": None}
        return original_forward(input_ids=input_ids, attention_mask=attention_mask, **kwargs)

    return _ForwardRewriteRequest(target_module, packed_forward)