Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/modules/moe/grouped_experts/__init__.py 63.6% 64,67-69
hyper_parallel/components/modules/moe/grouped_experts/low_precision_grouped_experts.py 79.2% 104-106,113,116-122,131,154,156,226-228,240,248,252,331,335,337,345,348,351,355,370,383-384,398,402,404-408,427,429,431,433,481-484,503-505,507-509,513,515-518,521,542-544,548-549,555,560,565,666-667,671-672,684,686,694,696,699,719,723-724
hyper_parallel/components/quantization/__init__.py 60.0% 117-120
hyper_parallel/components/quantization/modules/__init__.py 100%  
hyper_parallel/components/quantization/modules/replacement.py 100%  
hyper_parallel/components/modules/moe/grouped_experts/__init__.py
60
61
62
63
64
65
66
67
68
69
def __getattr__(name: str) -> Any:  # pylint: disable=invalid-name
    """Lazily load low-precision grouped-expert implementations."""
    if name not in _LAZY_LOW_PRECISION_EXPORTS:
        raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
    module = importlib.import_module(
        "hyper_parallel.components.modules.moe.grouped_experts.low_precision_grouped_experts"
    )
    value = getattr(module, name)
    globals()[name] = value
    return value
hyper_parallel/components/modules/moe/grouped_experts/low_precision_grouped_experts.py
100
101
102
103
104
105
106
107
108
109
110
        grouped_linear: GroupedLinear,
        fqn: str = "",
    ) -> None:
        """Create an unbound packed-expert module."""
        self._validate_grouped_linear(grouped_linear)
        super().__init__()
        self.gate_up_proj = nn.Parameter(
            torch.empty(
                num_experts,
                _GATE_UP_BRANCHES * intermediate_dim,
                hidden_dim,
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
                _GATE_UP_BRANCHES * intermediate_dim,
                hidden_dim,
            )
        )
        self.down_proj = nn.Parameter(
            torch.empty(num_experts, hidden_dim, intermediate_dim)
        )
        self.act_fn = nn.SiLU()
        self.num_experts = num_experts
        self.hidden_dim = hidden_dim
        self.intermediate_dim = intermediate_dim
        self.fqn = fqn
        self.grouped_linear = grouped_linear
        self.activation_limit = None

    @staticmethod
    def _validate_grouped_linear(grouped_linear: GroupedLinear) -> None:
        """Require a plain strategy so module registration stays unchanged."""
127
128
129
130
131
132
133
134
135
        if isinstance(grouped_linear, nn.Module) or not isinstance(
            grouped_linear,
            GroupedLinear,
        ):
            raise TypeError(
                "grouped_linear must be a non-Module GroupedLinear instance"
            )

    @classmethod
150
151
152
153
154
155
156
157
158
159
160
            )
        gate_up_proj = source._parameters["gate_up_proj"]  # pylint: disable=protected-access
        down_proj = source._parameters["down_proj"]  # pylint: disable=protected-access
        if gate_up_proj is None or down_proj is None:
            raise ValueError(f"{fqn!r} packed expert parameters cannot be None.")
        if gate_up_proj.ndim != GROUPED_NDIM or down_proj.ndim != GROUPED_NDIM:
            raise ValueError(
                f"{fqn!r} packed expert weights must be three-dimensional."
            )
        expected_down_shape = (
            gate_up_proj.shape[0],
222
223
224
225
226
227
228
229
230
231
232
                tokens_per_expert,
                self.grouped_linear,
                GROUP_LIST_COUNTS,
            )
        except (LowPrecisionCapabilityError, W4A8CapabilityError) as exc:
            target = self.fqn or "<unknown>"
            raise LowPrecisionCapabilityError(
                f"Low-precision grouped-expert target {target!r} cannot run: {exc}"
            ) from exc

    def forward(
236
237
238
239
240
241
242
243
244
        top_k_weights: torch.Tensor,
    ) -> torch.Tensor:
        """Sort routed tokens, execute grouped experts, and restore token order."""
        if hidden_states.ndim != MATRIX_NDIM:
            raise ValueError(
                "Grouped experts require two-dimensional hidden_states, "
                f"but got shape {tuple(hidden_states.shape)}."
            )
        if (
244
245
246
247
248
249
250
251
252
253
254
255
        if (
            top_k_index.shape != top_k_weights.shape
            or top_k_index.ndim != MATRIX_NDIM
        ):
            raise ValueError(
                "top_k_index and top_k_weights must have the same two-dimensional shape."
            )
        if top_k_index.shape[0] != hidden_states.shape[0]:
            raise ValueError(
                "The routed token count must match hidden_states: "
                f"routes={top_k_index.shape[0]}, tokens={hidden_states.shape[0]}."
            )
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
    def _source_parameters(module: nn.Module) -> tuple[nn.Parameter, nn.Parameter]:
        """Validate and return bias-free 3D packed expert weight parameters."""
        missing = [name for name in ("gate_up_proj", "down_proj") if not hasattr(module, name)]
        if missing:
            raise TypeError(f"GroupedExperts source module is missing: {missing}")
        source_gate_up = module.gate_up_proj
        source_down = module.down_proj
        if not isinstance(source_gate_up, nn.Parameter):
            raise TypeError("GroupedExperts requires gate_up_proj to be an nn.Parameter")
        if not isinstance(source_down, nn.Parameter):
            raise TypeError("GroupedExperts requires down_proj to be an nn.Parameter")
        return source_gate_up, source_down

    @staticmethod
    def _source_dimensions(module: nn.Module, config: Any) -> tuple[int, int, int]:
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
    def _source_dimensions(module: nn.Module, config: Any) -> tuple[int, int, int]:
        """Infer expert count and projection dimensions from the source module."""
        num_experts = getattr(module, "num_local_experts", getattr(module, "num_experts", None))
        if num_experts is None and config is not None:
            num_experts = getattr(config, "n_routed_experts", getattr(config, "num_experts", None))
        hidden_size = getattr(module, "hidden_size", getattr(module, "hidden_dim", None))
        if hidden_size is None and config is not None:
            hidden_size = getattr(config, "hidden_size", None)
        intermediate_size = getattr(module, "intermediate_size", getattr(module, "intermediate_dim", None))
        if intermediate_size is None and config is not None:
            intermediate_size = getattr(
                config, "moe_intermediate_size", getattr(config, "intermediate_size", None),
            )
        if num_experts is None or hidden_size is None or intermediate_size is None:
            raise ValueError("GroupedExperts requires expert count, hidden size, and intermediate size")
        return num_experts, hidden_size, intermediate_size

    @staticmethod
    def _activation(module: nn.Module, config: Any, gated_linear_unit: bool = True) -> Any:
366
367
368
369
370
371
372
373
374
            hidden_act = getattr(config, "mlp_hidden_act", None)
        activation_func = getattr(module, "act_fn", None)
        if activation_func is None:
            if hidden_act is None:
                hidden_act = "silu"
            activation_func = ACT2FN[hidden_act]
        source_apply_gate = getattr(module, "_apply_gate", None)
        source_apply_gate_func = getattr(source_apply_gate, "__func__", source_apply_gate)
        if (
379
380
381
382
383
384
385
386
387
388
        if hidden_act == "silu" and bool(getattr(config, "use_fused_swiglu", True)):
            return partial(npu_swiglu, dim=-1)

        def glu(x: torch.Tensor) -> torch.Tensor:
            gate, value = torch.chunk(x, 2, dim=-1)
            return activation_func(gate) * value

        return glu

    @staticmethod
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
    ) -> bool:
        """Return whether 3D source weights need transposition into ``[E, H, 2I]`` / ``[E, I, H]``."""
        if source_is_transposed is False:
            if source_shapes != transformers_shapes:
                raise ValueError("GroupedExperts source weights do not match their declared layout")
            return True
        if source_is_transposed is True:
            if source_shapes != npu_shapes:
                raise ValueError("GroupedExperts source weights do not match their declared layout")
            return False
        if source_shapes == transformers_shapes:
            return True
        if source_shapes == npu_shapes:
            return False
        raise ValueError("GroupedExperts source weight shapes are incompatible with the configured dimensions")

    def __init__(
        self,
        *,
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
        if bool(getattr(module, "has_bias", False)) or any(
            getattr(module, name, None) is not None
            for name in ("bias1", "bias2", "gate_up_proj_bias", "down_proj_bias")
        ):
            raise ValueError("GroupedExperts does not support source modules with bias")
        if not bool(getattr(module, "has_gate", getattr(config, "gated_linear_unit", True))):
            raise ValueError("GroupedExperts requires gated SwiGLU expert weights")
        if not bool(getattr(module, "is_concatenated", True)):
            raise ValueError("GroupedExperts requires concatenated gate/up expert weights")
        if not bool(getattr(module, "router_gating_in_fp32", True)):
            raise ValueError("GroupedExperts requires routing scores applied after GMM2")

        source_gate_up, source_down = self._source_parameters(module)
        num_experts, hidden_size, intermediate_size = self._source_dimensions(module, config)
        self.num_local_experts = num_experts
477
478
479
480
481
482
483
484
485
486
487
488
        self.train(module.training)

    def reset_parameters(self) -> None:
        """Initialize grouped weights with the source model's configured standard deviation."""
        if self.initializer_range is None:
            raise ValueError("GroupedExperts random initialization requires config.initializer_range")
        nn.init.normal_(self.gate_up_proj, mean=0.0, std=self.initializer_range)
        nn.init.normal_(self.down_proj, mean=0.0, std=self.initializer_range)

    def make_transforms(self) -> list[WeightConverter]:
        """Describe reversible source-checkpoint to transposed-layout conversion."""
        if not self._transpose_source_weights:
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
    def _grouped_gemm_expert_forward(
        self, gate_up_proj, down_proj, permuted, tokens_per_expert, permuted_probs,
    ):
        """Baseline GroupGemm expert computation (NPU-only)."""
        del permuted_probs
        self._tokens_per_expert_gmm = tokens_per_expert.to(device=permuted.device)
        self._group_list = self._tokens_per_expert_gmm.cumsum(dim=0)

        numel = permuted.nelement()
        if torch.compiler.is_compiling() or not isinstance(numel, int) or numel != 0:
            fc1_output = grouped_matmul(  # pylint: disable=not-callable
                permuted, gate_up_proj, bias=None, group_list=self._group_list, group_type=0, group_list_type=0,
            )
        else:
            fc1_output = torch.matmul(permuted, gate_up_proj.view(self.hidden_size, -1))

        fc1_output = self.activation_func(fc1_output)
        numel = fc1_output.nelement()
        if torch.compiler.is_compiling() or not isinstance(numel, int) or numel != 0:
            return grouped_matmul(  # pylint: disable=not-callable
                fc1_output, down_proj, bias=None, group_list=self._group_list, group_type=0, group_list_type=0,
            )
        return torch.matmul(fc1_output, down_proj.view(-1, self.hidden_size))

    def forward_expert_major(
        self,
        x: torch.Tensor,
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
        top_k_index: torch.Tensor,
        top_k_weights: torch.Tensor,
    ) -> torch.Tensor:
        """Run grouped experts with the Transformers Experts interface."""
        hidden_shape = hidden_states.shape
        hidden_states_flat = hidden_states.view(-1, hidden_states.shape[-1])
        permuted_tokens, sorted_indices = moe_token_permute(
            hidden_states_flat,
            top_k_index,
        )
        permuted_probs = top_k_weights.view(-1).index_select(0, sorted_indices)
        tokens_per_expert = torch.histc(
            top_k_index.view(-1).float(),
            bins=self.num_experts,
            min=0,
            max=self.num_experts,
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
            bins=self.num_experts,
            min=0,
            max=self.num_experts,
        ).long()
        expert_outputs = self.forward_expert_major(
            permuted_tokens,
            tokens_per_expert,
            permuted_probs,
        )
        output = moe_token_unpermute(
            expert_outputs,
            sorted_indices,
            top_k_weights,
        )
        return output.view(hidden_shape)


class LowPrecisionGroupedExperts(GroupedExperts):
    """Preserve transposed expert layout/routing and bind one QAT ``GroupedLinear`` strategy."""
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
        if any(context.get(axis) for axis in ("tp", "cp", "pp")):
            raise NotImplementedError(f"{prefix} requires TP=CP=PP=1")
        try:
            super().__init__(module=module, module_fqn=module_fqn, context=context)
        except (ValueError, TypeError, KeyError) as exc:
            raise ValueError(f"{prefix}: {exc}") from exc
        self._validate_source_contract(module, prefix)
        try:
            validate_npu_gmm_runtime()
        except RuntimeError as exc:
            raise RuntimeError(f"{prefix}: {exc}") from exc
        self.quantizer = MXFP8Quantizer()

    def _validate_source_contract(self, module: nn.Module, prefix: str) -> None:
        """Check the initial layout and activation before any device computation."""
680
681
682
683
684
685
686
687
688
689
690
        source_activation = getattr(module, "act_fn", None)
        if (hidden_act not in ("silu", "swiglu")
                or (source_activation is not None
                    and not isinstance(source_activation, (nn.SiLU, type(ACT2FN["silu"]))))):
            raise ValueError(f"{prefix} requires standard bias-free SwiGLU")
        if self.hidden_size % 32 or self.intermediate_size % 32:
            raise ValueError(f"{prefix} requires H and I divisible by 32")

    def _grouped_gemm_expert_forward(self, gate_up_proj, down_proj, permuted,
                                     tokens_per_expert, permuted_probs):
        """Validate expert groups and dispatch local math without applying scores."""
690
691
692
693
694
695
696
697
698
699
700
701
702
703
        """Validate expert groups and dispatch local math without applying scores."""
        del permuted_probs
        counts = tokens_per_expert.to(device=permuted.device)
        if counts.ndim != 1 or counts.shape[0] != gate_up_proj.shape[0]:
            raise ValueError(f"{self.module_fqn}: counts must contain one count per local expert")
        if counts.dtype not in (torch.int32, torch.int64):
            raise ValueError(f"{self.module_fqn}: counts must be integers")
        if tokens_per_expert.device.type == "cpu":
            if bool((tokens_per_expert < 0).any()) or int(tokens_per_expert.sum()) != permuted.shape[0]:
                raise ValueError(f"{self.module_fqn}: counts must be non-negative and sum to token count")
        return self._local_compute(permuted, gate_up_proj, down_proj, counts)

    def _local_compute(self, permuted, gate_up_proj, down_proj, counts):
        """Run the non-fused local chain after common protocol validation."""
715
716
717
718
719
720
721
722
723
724
725
726
727
728
                 context: Mapping[str, Any] | None = None) -> None:
        """Validate both fused kernels during construction, with module diagnostics."""
        self.clamp_limit = float(module.limit) if isinstance(module, DeepseekV4Experts) else None
        if self.clamp_limit is not None and (not math.isfinite(self.clamp_limit) or self.clamp_limit <= 0):
            raise ValueError(f"{module_fqn or '<root>'}: clipped MXFP8 fusion requires a positive finite limit")
        super().__init__(module=module, module_fqn=module_fqn, context=context)
        try:
            validate_npu_swiglu_runtime(clamp_limit=self.clamp_limit)
        except RuntimeError as exc:
            raise RuntimeError(f"{module_fqn or '<root>'}: {exc}") from exc

    @classmethod
    def _activation(cls, module: nn.Module, config: Any, gated_linear_unit: bool = True) -> Any:
        """Accept DeepSeek V4/V4.1 clipped experts while keeping the custom-gate guard for others."""
hyper_parallel/components/quantization/__init__.py
113
114
115
116
117
118
119
120
def __getattr__(name: str) -> Any:  # pylint: disable=invalid-name
    """Lazily resolve module exports to avoid cycles with ``hyper_parallel.models``."""
    if name not in _LAZY_MODULE_EXPORTS:
        raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
    modules_pkg = importlib.import_module("hyper_parallel.components.quantization.modules")
    value = getattr(modules_pkg, name)
    globals()[name] = value
    return value