Skip to content

PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度

40.6 KB
Raw Blame
# Copyright (c) 2026 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Custom experts implementation for transformers' MOE integration.

This module provides a `linear_loop` experts implementation that uses
individual nn.Linear layers per expert instead of fused 3D Parameters.
This enables proper quantization of MOE expert weights.

The implementation integrates with transformers' `use_experts_implementation`
decorator and `ALL_EXPERTS_FUNCTIONS` registry.

Usage:

    from auto_round.modeling.fused_moe.moe_experts_interface import prepare_model_for_moe_quantization
    # Before quantization
    prepare_model_for_moe_quantization(model)

    # Now the model uses linear_loop forward which supports quantized nn.Linear layers
"""

import torch
from torch import nn

from auto_round import envs
from auto_round.modeling.fused_moe.fusion_spec import build_standard_moe_fusion_spec, register_moe_fusion_spec
from auto_round.modeling.fused_moe.grouped_experts import (
    GROUPED_LINEAR_IMPL,
    GROUPED_LINEAR_SLICED_IMPL,
    grouped_linear_experts_forward,
)
from auto_round.modeling.fused_moe.utils import build_forced_routing, force_all_experts_routing_enabled
from auto_round.utils import clear_memory, logger
from auto_round.utils.device import memory_monitor

try:
    from transformers.integrations.moe import ALL_EXPERTS_FUNCTIONS

    HAS_EXPERTS_INTERFACE = True
except ImportError:
    HAS_EXPERTS_INTERFACE = False
    ALL_EXPERTS_FUNCTIONS = None

# Expert implementation name - change this if transformers want to use a different name
LINEAR_LOOP_IMPL = "linear_loop"

# Implementations AutoRound registers for its per-expert nn.Linear layout.
AUTO_ROUND_EXPERTS_IMPLS = {
    LINEAR_LOOP_IMPL: None,  # filled in below (avoids a forward reference to the function)
    GROUPED_LINEAR_IMPL: grouped_linear_experts_forward,
}


def resolve_experts_implementation() -> str:
    """Pick the experts forward used for AutoRound's unfused per-expert layout.

    ``AR_MOE_EXPERTS_IMPL`` accepts ``auto`` (default), ``linear_grouped``,
    ``linear_grouped_sliced`` or ``linear_loop``. ``auto``/``linear_grouped`` select the
    grouped-GEMM backend with torch's native ``grouped_mm`` kernel, which batches the routed
    token/expert pairs into a single sorted GEMM instead of looping (and syncing) over every
    expert; it self-checks the layer and falls back to the loop when the layer is not
    eligible. ``linear_grouped_sliced`` is the same grouped backend but forces the sliced
    per-expert GEMM loop instead of the native kernel.
    """
    requested = str(envs.AR_MOE_EXPERTS_IMPL).lower()
    if requested in ("", "auto", GROUPED_LINEAR_IMPL, GROUPED_LINEAR_SLICED_IMPL):
        # Both grouped variants use the same forward; native vs sliced is decided inside it
        # from AR_MOE_EXPERTS_IMPL (see grouped_experts._sliced_grouped_mm_requested).
        return GROUPED_LINEAR_IMPL
    if requested == LINEAR_LOOP_IMPL:
        return LINEAR_LOOP_IMPL
    logger.warning(
        f"Unknown AR_MOE_EXPERTS_IMPL='{requested}', expected one of "
        f"{['auto', GROUPED_LINEAR_IMPL, GROUPED_LINEAR_SLICED_IMPL, LINEAR_LOOP_IMPL]}. "
        f"Falling back to '{LINEAR_LOOP_IMPL}'."
    )
    return LINEAR_LOOP_IMPL


# Known expert projection patterns for reference
# These are used as hints when auto-detection needs to infer projection properties
# Format: proj_name -> {"is_input_proj": bool, "output_multiplier": int}
#   is_input_proj: True if takes hidden_dim as input, False if takes intermediate_dim
#   output_multiplier: output dimension multiplier (e.g., 2 for fused gate+up projection)
KNOWN_PROJECTION_PATTERNS = {
    # Transformers 5.0+ standard (Qwen3-MoE, etc.)
    # gate_up_proj is auto-split into gate_proj + up_proj during unfusing
    "gate_up_proj": {"is_input_proj": True, "output_multiplier": 2, "split_into": ["gate_proj", "up_proj"]},
    "gate_proj": {"is_input_proj": True, "output_multiplier": 1},  # hidden -> intermediate (gate)
    "up_proj": {"is_input_proj": True, "output_multiplier": 1},  # hidden -> intermediate (up)
    "down_proj": {"is_input_proj": False, "output_multiplier": 1},  # intermediate -> hidden
    # Mixtral-style
    "w1": {"is_input_proj": True, "output_multiplier": 1},  # gate: hidden -> intermediate
    "w2": {"is_input_proj": False, "output_multiplier": 1},  # down: intermediate -> hidden
    "w3": {"is_input_proj": True, "output_multiplier": 1},  # up: hidden -> intermediate
    # DBRX-style
    "v1": {"is_input_proj": True, "output_multiplier": 1},
    "w1_proj": {"is_input_proj": True, "output_multiplier": 1},
    "w2_proj": {"is_input_proj": False, "output_multiplier": 1},
}


class _ExpertContainer(nn.Module):
    """Lightweight container for a single expert's projection layers.

    Each expert has its projections (e.g., gate_proj, up_proj, down_proj)
    as direct attributes. When attached as numbered children of the experts
    module (e.g., module.add_module("0", container)), PyTorch naturally
    produces state_dict keys like: {prefix}0.gate_proj.weight
    which matches the standard checkpoint format without any hooks.
    """


def _install_compact_expert_repr(module: nn.Module) -> None:
    """Install compact __repr__ on the module's class.

    Collapses identical _ExpertContainer children into a range display,
    similar to nn.ModuleList::

        GptOssExperts(
          (0-63): 64 x _ExpertContainer(
            (gate_proj): Linear(...)
            (up_proj): Linear(...)
            (down_proj): Linear(...)
          )
        )
    """
    cls = module.__class__
    if "_compact_expert_repr_installed" in cls.__dict__:
        return

    _original_repr = cls.__repr__

    def _compact_repr(self):
        from torch.nn.modules.module import _addindent

        # Separate expert containers from other children
        expert_items = []
        other_items = []
        for key, child in self._modules.items():
            if isinstance(child, _ExpertContainer):
                expert_items.append((key, child))
            else:
                other_items.append((key, child))

        if not expert_items:
            return _original_repr(self)

        lines = []
        extra_repr = self.extra_repr()
        if extra_repr:
            lines.extend(extra_repr.split("\n"))

        # Print non-expert children normally
        for key, child in other_items:
            mod_str = repr(child)
            mod_str = _addindent(mod_str, 2)
            lines.append(f"({key}): {mod_str}")

        # Collapse expert containers into a single range line
        first_key = expert_items[0][0]
        last_key = expert_items[-1][0]
        sample_repr = repr(expert_items[0][1])
        n = len(expert_items)
        sample_repr = _addindent(sample_repr, 2)
        if n > 1:
            lines.append(f"({first_key}-{last_key}): {n} x {sample_repr}")
        else:
            lines.append(f"({first_key}): {sample_repr}")

        main_str = self._get_name() + "("
        if lines:
            main_str += "\n  " + "\n  ".join(lines) + "\n"
        main_str += ")"
        return main_str

    cls.__repr__ = _compact_repr
    cls._compact_expert_repr_installed = True

    # Make the module subscriptable and iterable: module[0], module[1], len(module), for e in module
    if not hasattr(cls, "__getitem__") or "__getitem__" not in cls.__dict__:

        def _getitem(self, idx):
            return getattr(self, str(idx))

        def _len(self):
            return self.num_experts

        def _iter(self):
            for i in range(self.num_experts):
                yield getattr(self, str(i))

        cls.__getitem__ = _getitem
        cls.__len__ = _len
        cls.__iter__ = _iter


def linear_loop_experts_forward(
    self: nn.Module,
    hidden_states: torch.Tensor,
    top_k_index: torch.Tensor,
    top_k_weights: torch.Tensor,
) -> torch.Tensor:
    """Forward using individual nn.Linear layers per expert.

    This implementation loops over experts and accesses per-expert containers
    (self._modules["0"], self._modules["1"], ...) each with gate_proj,
    up_proj, and down_proj as nn.Linear layers (or quantized equivalents),
    enabling proper quantization support.

    Expected module structure:
        - Numbered children (0, 1, ..., num_experts-1), each an _ExpertContainer with:
            - gate_proj: nn.Linear (in_features=hidden_dim, out_features=intermediate_dim)
            - up_proj: nn.Linear (in_features=hidden_dim, out_features=intermediate_dim)
            - down_proj: nn.Linear (in_features=intermediate_dim, out_features=hidden_dim)
        - act_fn: activation function
        - num_experts: number of experts
        - _apply_gate: optional custom gating function

    Args:
        self: The experts module
        hidden_states: Input tensor of shape (num_tokens, hidden_dim)
        top_k_index: Selected expert indices of shape (num_tokens, top_k)
        top_k_weights: Expert weights of shape (num_tokens, top_k)

    Returns:
        final_hidden_states: Output tensor of shape (num_tokens, hidden_dim)
    """
    logger.debug(f"Using {LINEAR_LOOP_IMPL} experts forward for {self.__class__.__name__}")

    # Handle [batch_size, seq_len, hidden_dim] input format
    if hidden_states.dim() == 3:
        batch_size, seq_len, hidden_dim = hidden_states.shape
        hidden_states = hidden_states.view(-1, hidden_dim)  # [bs * seq_len, hidden_dim]
        top_k_index = top_k_index.view(-1, top_k_index.size(-1))  # [bs * seq_len, top_k]
        top_k_weights = top_k_weights.view(-1, top_k_weights.size(-1))  # [bs * seq_len, top_k]
    else:
        batch_size, seq_len = None, None
        hidden_dim = hidden_states.size(-1)

    device = hidden_states.device
    num_top_k = top_k_index.size(-1)
    num_tokens = hidden_states.size(0)
    num_experts = self.num_experts

    def _run_experts_with_routes(route_indices: torch.Tensor, route_weights: torch.Tensor) -> torch.Tensor:
        # Reshape for easier indexing
        # S is the number of selected token-expert pairs (S = num_tokens * num_top_k)
        token_idx = torch.arange(num_tokens, device=device).unsqueeze(1).expand(-1, num_top_k).reshape(-1)  # (S,)
        sample_weights = route_weights.reshape(-1).to(hidden_states.dtype)  # (S,)
        expert_ids = route_indices.reshape(-1)  # (S,)

        # Get current hidden states for selected samples
        selected_hidden_states = hidden_states[token_idx]  # (S, hidden_dim)

        out_per_sample = torch.zeros_like(selected_hidden_states)
        for expert_idx in range(num_experts):
            sample_idx = torch.nonzero(expert_ids == expert_idx, as_tuple=False).squeeze(-1)
            if sample_idx.numel() == 0:
                continue
            expert_input = selected_hidden_states.index_select(0, sample_idx)

            # Get this expert's container with its projection layers
            expert = getattr(self, str(expert_idx))
            up_out = expert.up_proj(expert_input)  # (num_samples, intermediate_dim)

            # Non-gated MLP experts (e.g. NemotronH's @use_experts_implementation(has_gate=False))
            # expose only up_proj/down_proj: out = down_proj(act_fn(up_proj(x))). Gated experts
            # (Mixtral/Qwen3-MoE/...) additionally own gate_proj. Mirror the grouped path
            # (grouped_linear_experts_forward) which keys the same branch off gate_proj presence.
            if hasattr(expert, "gate_proj"):
                gate_out = expert.gate_proj(expert_input)  # (num_samples, intermediate_dim)
                # Apply gating
                if hasattr(self, "_apply_gate"):
                    gate_up_out = torch.cat([gate_out, up_out], dim=-1)
                    gated_out = self._apply_gate(gate_up_out)  # (num_samples, intermediate_dim)
                else:
                    gated_out = self.act_fn(gate_out) * up_out  # (num_samples, intermediate_dim)
            else:
                gated_out = self.act_fn(up_out)  # (num_samples, intermediate_dim)

            # Down projection
            expert_out = expert.down_proj(gated_out)  # (num_samples, hidden_dim)

            out_per_sample.index_copy_(0, sample_idx, expert_out.to(out_per_sample.dtype))

        # Apply routing weights
        out_per_sample = out_per_sample * sample_weights.unsqueeze(-1)  # (S, hidden_dim)

        # Accumulate results using deterministic reshape+sum instead of index_add_
        # (index_add_ with duplicate indices is non-deterministic on CUDA due to atomicAdd)
        return out_per_sample.view(num_tokens, num_top_k, hidden_dim).sum(dim=1)

    # Main output path: always preserve original router selection.
    final_hidden_states = _run_experts_with_routes(top_k_index, top_k_weights)

    # Auxiliary coverage path: when enabled, run forced-routing once to trigger
    # expert hooks/stat collection, but discard this output to avoid changing
    # model semantics.
    if force_all_experts_routing_enabled():
        forced_indices, forced_weights = build_forced_routing(
            module=self,
            routing_scores=None,
            top_k=num_top_k,
            num_experts=num_experts,
            dtype=hidden_states.dtype,
            num_tokens=num_tokens,
            device=device,
            normalize=True,
        )
        with torch.no_grad():
            _ = _run_experts_with_routes(forced_indices, forced_weights)

    # Reshape back to original format if input was [batch_size, seq_len, hidden_dim]
    if batch_size is not None:
        final_hidden_states = final_hidden_states.view(batch_size, seq_len, hidden_dim)

    return final_hidden_states


def register_linear_loop_experts() -> bool:
    """Register AutoRound's experts implementations with transformers.

    Registers both ``linear_loop`` (per-expert Python loop) and ``linear_grouped``
    (sorted grouped-GEMM over the routed token/expert pairs).

    Returns:
        True if registration was successful, False otherwise.
    """
    if not HAS_EXPERTS_INTERFACE:
        logger.warning(
            "transformers.integrations.moe.ALL_EXPERTS_FUNCTIONS not available. "
            "linear_loop experts implementation not registered. "
            "Requires transformers >= 5.0.0"
        )
        return False

    AUTO_ROUND_EXPERTS_IMPLS[LINEAR_LOOP_IMPL] = linear_loop_experts_forward
    for impl_name, impl_fn in AUTO_ROUND_EXPERTS_IMPLS.items():
        if impl_name not in ALL_EXPERTS_FUNCTIONS._global_mapping:
            ALL_EXPERTS_FUNCTIONS._global_mapping[impl_name] = impl_fn
            logger.debug(f"Registered '{impl_name}' experts implementation")

    return True


def _experts_supports_decorator(module: nn.Module) -> bool:
    """Check if experts module supports @use_experts_implementation decorator.

    Only experts classes decorated with @use_experts_implementation will use
    our linear_loop forward. Others need full module replacement.
    """
    forward_method = getattr(module.__class__, "forward", None)
    if forward_method is None:
        return False
    # @use_experts_implementation sets __wrapped__ on the decorated method
    return hasattr(forward_method, "__wrapped__")


def _module_name_is_experts_container(module_name: str) -> bool:
    """True when ``module_name`` names a fused-MoE experts container.

    Fused expert weights always live on a module whose path carries an experts/MoE
    token (e.g. ``model.layers.0.mlp.experts``, ``...block_sparse_moe.experts``,
    ``...ffn.experts``). A vision/positional embedder such as gemma-4 unified's
    ``model.embed_vision`` (which owns a 3D ``pos_embedding`` table) does not, so it
    must never be mistaken for an experts module.
    """
    tokens = module_name.lower().split(".")
    return any(("expert" in token) or token == "moe" for token in tokens)


def _detect_expert_projections(module: nn.Module, module_name: str = "") -> dict[str, dict]:
    """Detect which expert projections exist in the module.

    This function scans the module for any 3D nn.Parameter attributes.
    It first checks known projection names, then discovers any unknown 3D parameters.

    Reads ``module._parameters`` directly instead of ``getattr``/``dir()``. This runs once
    per module in the model, and after unfusing a large MoE that is tens of thousands of
    modules: ``dir()`` on an ``nn.Module`` is expensive, and every miss goes through
    ``nn.Module.__getattr__``, which searches three dicts before raising. A parameter is
    always registered in ``_parameters``, so the cheap membership test is equivalent.

    Args:
        module: The candidate experts module.
        module_name: The module's qualified path in the model tree (e.g.
            ``model.layers.0.mlp.experts``). Used to gate the *unknown* 3D-parameter
            fallback so only genuine experts/MoE containers are unfused. When empty
            (name unavailable), the fallback stays permissive for backward compatibility.

    Returns:
        Dict mapping projection names to their config, only for projections that exist
        as 3D nn.Parameter in the module.
    """
    parameters = getattr(module, "_parameters", None)
    if not parameters:
        return {}

    # Fast reject: an experts module owns at least one 3D parameter. Almost every module
    # in the model (Linear, norms, containers) fails here in a single dict scan.
    three_dim = {
        name: param
        for name, param in parameters.items()
        if param is not None and not name.startswith("_") and param.dim() == 3
    }
    if not three_dim:
        return {}

    detected = {}

    # First, check known projection patterns
    for proj_name, config in KNOWN_PROJECTION_PATTERNS.items():
        if proj_name in three_dim:
            detected[proj_name] = config

    # Known 3D parameters that are *never* fused expert GEMMs and must never be split,
    # regardless of the module path (e.g. ``scale_shift_table`` on WanTransformer3DModel).
    _NON_EXPERT_3D_PARAMS = frozenset(["scale_shift_table"])

    # If no known pattern matched, fall back to treating an unknown 3D parameter as a
    # future expert projection -- but ONLY when this module is actually a fused-MoE
    # experts container (by path). This is the stable signal: an expert projection
    # always lives on a ``*.experts``/``*.moe`` module. Without it, legitimate 3D
    # parameters on non-expert modules get misclassified and split into bogus experts,
    # e.g. gemma-4 unified's ``model.embed_vision.pos_embedding``
    # ``(mm_posemb_size, 2, mm_embed_dim)`` -> ``embed_vision.{i}.pos_embedding.weight``.
    # When ``module_name`` is unavailable we cannot verify the container, so stay
    # permissive to preserve the previous behaviour -- but still honour the explicit
    # non-expert denylist in both cases.
    if not detected and (not module_name or _module_name_is_experts_container(module_name)):
        for name in three_dim:
            if name in _NON_EXPERT_3D_PARAMS:
                logger.debug(f"Skipping known non-expert 3D parameter: {name}")
                continue
            logger.debug(f"Discovered unknown 3D projection: {name}")
            detected[name] = {"is_input_proj": True, "output_multiplier": 1}
    elif not detected:
        logger.debug(f"Skipping 3D parameter(s) on non-experts module '{module_name}': {list(three_dim)}")

    return detected


def _infer_dimensions(param: nn.Parameter, config: dict, is_transposed: bool) -> tuple[int, int]:
    """Infer input and output dimensions for a projection.

    Args:
        param: The 3D parameter (num_experts, dim1, dim2)
        config: Projection config with is_input_proj and output_multiplier
        is_transposed: Whether weights are stored transposed

    Returns:
        (in_features, out_features) for the Linear layer
    """
    dim1, dim2 = param.shape[1], param.shape[2]
    multiplier = config.get("output_multiplier", 1)

    if is_transposed:
        # transposed: (num_experts, in_features, out_features)
        in_features, out_features = dim1, dim2
    else:
        # not transposed: (num_experts, out_features, in_features)
        out_features, in_features = dim1, dim2

    # Adjust for multiplier (e.g., gate_up has 2x intermediate)
    if multiplier > 1:
        out_features = out_features // multiplier * multiplier  # ensure divisible

    return in_features, out_features


def _new_meta_linear(in_features: int, out_features: int, has_bias: bool, dtype: torch.dtype) -> nn.Linear:
    """Build an ``nn.Linear`` shell on meta without running its initializer.

    ``nn.Linear.__init__`` calls ``reset_parameters`` -> ``kaiming_uniform_``, whose result
    is always discarded here: the weight is either left on meta for the checkpoint loader
    to fill, or replaced with a checkpoint slice on the very next line. With hundreds of
    experts per layer (256 x 3 projections x 40 layers for Qwen3.5-MoE) that initializer
    dominates the unfuse, so construct the module directly instead.
    """
    linear = nn.Linear.__new__(nn.Linear)
    nn.Module.__init__(linear)
    linear.in_features = in_features
    linear.out_features = out_features
    linear.weight = nn.Parameter(torch.empty((out_features, in_features), dtype=dtype, device="meta"))
    if has_bias:
        linear.bias = nn.Parameter(torch.empty(out_features, dtype=dtype, device="meta"))
    else:
        linear.register_parameter("bias", None)
    return linear


def _unfuse_single_projection(
    module: nn.Module,
    proj_name: str,
    num_experts: int,
    is_transposed: bool,
    dtype: torch.dtype,
    target_device: torch.device,
) -> list | None:
    """Unfuse a single projection from 3D Parameter to a list of Linear layers.

    Optimized to minimize device allocations and copies:
    - Moves the full 3D tensor to CPU in a single transfer
    - Performs batch transpose on CPU if needed
    - Creates Linear shells on meta device (no allocation)
    - Directly assigns weight slices as Parameters (zero-copy on CPU)

    Args:
        module: The experts module
        proj_name: Name of the projection attribute
        num_experts: Number of experts
        is_transposed: Whether weights are stored transposed
        dtype: Data type for the Linear layers
        target_device: Device for the Linear layers

    Returns:
        List of Linear layers, or None if projection doesn't exist
    """
    param = getattr(module, proj_name, None)
    if param is None or not isinstance(param, nn.Parameter) or param.dim() != 3:
        return None

    # Get projection config
    config = KNOWN_PROJECTION_PATTERNS.get(proj_name, {"is_input_proj": True, "output_multiplier": 1})

    # Infer dimensions
    in_features, out_features = _infer_dimensions(param, config, is_transposed)

    # Check for bias
    bias_name = f"{proj_name}_bias"
    bias_param = getattr(module, bias_name, None)
    has_bias = bias_param is not None

    source_device = param.device
    is_meta = source_device.type == "meta"

    # Prepare weight slices on CPU in batch (single D2H transfer + batch transpose)
    if not is_meta:
        # Single transfer: GPU -> CPU (or no-op if already on CPU)
        weights_cpu = param.data.cpu()  # (num_experts, dim1, dim2)
        if is_transposed:
            # Batch transpose: (num_experts, in, out) -> (num_experts, out, in)
            weights_cpu = weights_cpu.transpose(1, 2)
        # Ensure contiguous layout so unbind produces contiguous 2D slices.
        # This is needed when the param comes from a chunk split (Phase 1)
        # which produces non-contiguous views even on CPU.
        if not weights_cpu.is_contiguous():
            weights_cpu = weights_cpu.contiguous()
        # Unbind into a tuple of 2D tensors (zero-copy views since contiguous)
        weight_slices = weights_cpu.unbind(0)

        if has_bias:
            bias_cpu = bias_param.data.cpu()
            # Ensure contiguous — bias may come from a chunk split (Phase 1)
            if not bias_cpu.is_contiguous():
                bias_cpu = bias_cpu.contiguous()
            bias_slices = bias_cpu.unbind(0)

    # Create Linear shells on meta device (no memory allocation)
    linears = []
    for i in range(num_experts):
        # meta device: creates the module structure without allocating weight storage
        linear = _new_meta_linear(in_features, out_features, has_bias, dtype)

        if not is_meta:
            # Direct parameter assignment — no copy, just references the CPU tensor slice
            linear.weight = nn.Parameter(weight_slices[i])
            if has_bias:
                linear.bias = nn.Parameter(bias_slices[i])

        linears.append(linear)

    # Release original parameter memory
    if not is_meta:
        try:
            param.data = param.data.to_empty(device="meta")
            if has_bias:
                bias_param.data = bias_param.data.to_empty(device="meta")
            logger.debug(f"Released memory for {proj_name} using to_empty(device='meta')")
        except Exception:
            pass

    return linears


_logged_memory_before_replacement = False  # To ensure we only log memory once before replacements


def _warn_if_unfusing_allocates(module: nn.Module, detected_projections: dict[str, dict]) -> None:
    """Warn when the fused expert weights are not on meta.

    Unfusing is free on meta. On a real device the fused tensor and the per-expert copies
    must coexist for the duration of the split, so the peak is inherently ~2x one experts
    module on top of an already resident model.
    """
    params = [
        param
        for param in (getattr(module, name, None) for name in detected_projections)
        if isinstance(param, nn.Parameter) and param.device.type != "meta"
    ]
    if not params:
        return

    total_bytes = sum(param.numel() * param.element_size() for param in params)
    logger.warning(
        "[MoE Prep] unfusing '%s' (%.2f GB on %s) in memory needs ~2x that peak. "
        "For large MoE, enable AutoRound's disk-stream path (AR_DISK_STREAM_MODEL=1, "
        "needs a local checkpoint + transformers>=5) to unfuse on meta instead.",
        module.__class__.__name__,
        total_bytes / 1024**3,
        params[0].device.type,
    )


def _unfuse_experts_weights_inplace(
    module: nn.Module,
    check_decorator: bool = True,
    projection_names: list[str] | None = None,
    module_name: str = "",
) -> bool:
    """Convert fused 3D expert weights to per-expert containers of nn.Linear layers.

    This function modifies the module in-place, replacing fused 3D Parameters
    with numbered _ExpertContainer children, each holding nn.Linear projections.

    Args:
        module: The experts module to unfuse
        check_decorator: If True, only unfuse if the module supports
            @use_experts_implementation decorator. Default is True.
        projection_names: Optional list of projection names to unfuse.
            If None, auto-detects from KNOWN_PROJECTION_PATTERNS.
        module_name: The module's qualified path in the model tree. Forwarded to
            :func:`_detect_expert_projections` so the unknown-3D-parameter fallback
            only fires on genuine experts/MoE containers.

    Returns:
        True if unfusing was successful, False if module doesn't match pattern
    """
    # Detect available projections
    if projection_names:
        detected_projections = {
            name: config for name, config in KNOWN_PROJECTION_PATTERNS.items() if name in projection_names
        }
    else:
        detected_projections = _detect_expert_projections(module, module_name=module_name)

    if not detected_projections:
        return False

    # Only unfuse if the module supports the decorator (unless check_decorator is False)
    if check_decorator and not _experts_supports_decorator(module):
        logger.debug(f"Skipping unfuse for {module.__class__.__name__}: does not support @use_experts_implementation")
        return False

    global _logged_memory_before_replacement
    if not _logged_memory_before_replacement:
        _logged_memory_before_replacement = True
        _warn_if_unfusing_allocates(module, detected_projections)
        memory_monitor.update()
        memory_monitor.log_summary("Before applying custom replacements")

    # Get first projection to determine num_experts and layout
    first_proj_name = next(iter(detected_projections))
    first_param = getattr(module, first_proj_name)
    num_experts = first_param.shape[0]

    # Detect if transposed
    is_transposed = getattr(module, "is_transposed", None)
    if is_transposed is None:
        # Infer from shape: typically hidden_dim < intermediate_dim
        dim1, dim2 = first_param.shape[1], first_param.shape[2]
        is_transposed = dim1 < dim2

    fusion_spec = build_standard_moe_fusion_spec(
        detected_projections={name: config.copy() for name, config in detected_projections.items()},
        num_experts=num_experts,
        checkpoint_transposed=is_transposed,
        module=module,
    )

    dtype = first_param.dtype
    target_device = first_param.device if first_param.device.type != "meta" else "cpu"

    # Phase 1: Split fused projections (e.g., gate_up_proj -> gate_proj + up_proj) into separate 3D params
    extra_projections = {}
    fused_to_remove = []
    for proj_name, config in detected_projections.items():
        split_into = config.get("split_into")
        if not split_into:
            continue
        param = getattr(module, proj_name, None)
        if param is None or not isinstance(param, nn.Parameter) or param.dim() != 3:
            continue
        # Split along output dimension
        split_dim = 2 if is_transposed else 1
        split_params = param.chunk(len(split_into), dim=split_dim)

        # Also split bias if present (e.g., gate_up_proj_bias -> gate_proj_bias + up_proj_bias)
        bias_name = f"{proj_name}_bias"
        bias_param = getattr(module, bias_name, None)
        bias_splits = None
        if bias_param is not None and isinstance(bias_param, nn.Parameter) and bias_param.dim() == 2:
            bias_splits = bias_param.chunk(len(split_into), dim=1)

        for i, (split_name, split_param) in enumerate(zip(split_into, split_params)):
            # Avoid .contiguous() here — _unfuse_single_projection will handle it
            # during batch transpose/unbind, saving a full-tensor copy
            setattr(module, split_name, nn.Parameter(split_param))
            if bias_splits is not None:
                setattr(module, f"{split_name}_bias", nn.Parameter(bias_splits[i]))
            extra_projections[split_name] = KNOWN_PROJECTION_PATTERNS.get(
                split_name, {"is_input_proj": True, "output_multiplier": 1}
            )
        delattr(module, proj_name)
        if bias_param is not None:
            delattr(module, bias_name)
        fused_to_remove.append(proj_name)
        logger.debug(f"Split {proj_name} -> {split_into}: {num_experts} experts")

    # Remove fused entries and add split entries
    for name in fused_to_remove:
        del detected_projections[name]
    detected_projections.update(extra_projections)

    # Phase 2: Unfuse all 3D params into per-expert Linear layers
    proj_linears = {}  # proj_name -> [Linear_expert0, Linear_expert1, ...]
    for proj_name in detected_projections:
        linears = _unfuse_single_projection(module, proj_name, num_experts, is_transposed, dtype, target_device)
        if linears is not None:
            delattr(module, proj_name)
            # Also remove the bias parameter if it exists (already absorbed into Linear.bias)
            bias_name = f"{proj_name}_bias"
            if hasattr(module, bias_name):
                delattr(module, bias_name)
            proj_linears[proj_name] = linears

    if not proj_linears:
        return False

    # Phase 3: Assemble per-expert containers as direct numbered children.
    # This produces state_dict keys like: {prefix}0.gate_proj.weight
    # which naturally matches the standard checkpoint format — no hooks needed.
    for expert_idx in range(num_experts):
        container = _ExpertContainer()
        for proj_name, linears in proj_linears.items():
            setattr(container, proj_name, linears[expert_idx])
        module.add_module(str(expert_idx), container)

    # Ensure num_experts is set
    if not hasattr(module, "num_experts"):
        module.num_experts = num_experts

    register_moe_fusion_spec(module, fusion_spec)

    # Mark as unfused for detection during save
    module._unfused_experts = True

    # Mark all unfused modules as already initialized so transformers'
    # _initialize_weights skips them. Without this, the model's _init_weights
    # tries to access the original fused attributes (e.g., gate_up_proj) which
    # no longer exist after unfusing.
    module._is_hf_initialized = True
    for child in module.modules():
        child._is_hf_initialized = True

    # Install compact repr to collapse identical expert containers in print output
    _install_compact_expert_repr(module)

    return True


def prepare_model_for_moe_quantization(
    model: nn.Module,
    implementation: str | None = None,
    skip_prefixes: list[str] | None = None,
) -> list[str]:
    """Prepare a model for MOE quantization using transformers' experts interface.

    This function:
    1. Registers AutoRound's experts implementations with transformers
    2. Sets model.config._experts_implementation = implementation
    3. Unfuses all fused MOE expert weights into per-expert containers of nn.Linear

    After calling this function, the model's forward pass will use individual
    nn.Linear layers per expert, which can be quantized normally.

    Args:
        model: The model to prepare
        implementation: The experts implementation to use. Defaults to the one selected by
            ``AR_MOE_EXPERTS_IMPL`` (``linear_grouped`` unless overridden).
        skip_prefixes: Module name prefixes to skip (e.g. ["talker."]).
            Modules under these prefixes stay in their original fused 3D format.
            ShardWriter handles the fused→per-expert conversion at save time.

    Returns:
        List of module names that were unfused
    """
    if not register_linear_loop_experts():
        raise RuntimeError(
            "Failed to register linear_loop experts implementation. "
            "This requires transformers >= 5.0.0 with MOE integration support."
        )

    if implementation is None:
        implementation = resolve_experts_implementation()

    # Unfuse all fused experts modules (only those supporting @use_experts_implementation)
    unfused_modules = []
    for name, module in model.named_modules():
        if skip_prefixes and any(name.startswith(p) for p in skip_prefixes):
            continue
        if _unfuse_experts_weights_inplace(module, module_name=name):
            unfused_modules.append(name)
            logger.debug(f"[MoE Prep] Unfused '{name}'")

    # Only set config if we actually unfused something
    # Models that don't support the decorator (like Llama4) won't have anything unfused
    # and should use full module replacement instead
    if unfused_modules:
        logger.info(f"[MoE Prep] Unfused {len(unfused_modules)} MOE experts modules")
        clear_memory()

        # Set config for the per-expert nn.Linear forward. A user-provided
        # ``experts_implementation`` is only honored when it is one of ours: the fused
        # backends (grouped_mm/batched_mm/...) index 3D parameters that no longer exist
        # after unfusing.
        if hasattr(model, "config"):
            saved_impl = getattr(model.config, "experts_implementation", None)
            impl_to_set = saved_impl if saved_impl in AUTO_ROUND_EXPERTS_IMPLS else implementation
            model.config._experts_implementation = impl_to_set
            logger.debug(f"Set model.config._experts_implementation = '{impl_to_set}'")
            # Experts dispatch on their own ``self.config``; in a multimodal wrapper that is the
            # nested text config (e.g. Nemotron-H Omni's ``llm_config``), not ``model.config``.
            for name in unfused_modules:
                expert_config = getattr(model.get_submodule(name), "config", None)
                if expert_config is not None and expert_config is not model.config:
                    expert_config._experts_implementation = impl_to_set

        memory_monitor.update()
        memory_monitor.log_summary("After applying custom replacements")

    return unfused_modules


def is_linear_loop_available() -> bool:
    """Check if linear_loop experts implementation is available."""
    return HAS_EXPERTS_INTERFACE


def is_grouped_experts_forward_active(model: nn.Module | None) -> bool:
    """Whether this model will run the grouped-GEMM experts forward during tuning.

    The grouped experts forward (:func:`grouped_linear_experts_forward`) is deliberately
    opaque to dynamo -- its routing is data-dependent Python control flow, so it runs
    eager. Compiling the *block* forward around it therefore buys nothing over the experts
    region and only pays dynamo's routing recompiles, while the per-layer qdq
    (``weight_quant_func``) stays compiled in its own right. Callers use this to keep the
    block forward eager for grouped MoE while leaving qdq compilation on.
    """
    config = getattr(model, "config", None)
    if config is None:
        return False
    return getattr(config, "_experts_implementation", None) == GROUPED_LINEAR_IMPL


def _config_model_types(config) -> list[str]:
    """Collect ``model_type`` from a config and every nested sub-config.

    A VLM keeps the MoE rules on the text sub-config
    (``text_config.model_type == 'qwen3_5_moe_text'``), so the top-level type alone is
    not enough. Uses ``sub_configs``/``get_text_config`` when available (the supported
    transformers API) and falls back to scanning ``__dict__`` for config-like values.
    """
    found: list[str] = []
    seen: set[int] = set()

    def _walk(node) -> None:
        if node is None or id(node) in seen:
            return
        seen.add(id(node))

        model_type = getattr(node, "model_type", None)
        if isinstance(model_type, str) and model_type not in found:
            found.append(model_type)

        children = []
        # Preferred: the declared sub-config names (transformers >= 4.4x).
        for name in getattr(type(node), "sub_configs", None) or ():
            children.append(getattr(node, name, None))
        get_text_config = getattr(node, "get_text_config", None)
        if callable(get_text_config):
            try:
                children.append(get_text_config())
            except Exception:  # pragma: no cover - defensive
                pass
        # Fallback for plain/duck-typed configs.
        for value in (vars(node).values() if hasattr(node, "__dict__") else ()):
            if getattr(value, "model_type", None) is not None:
                children.append(value)

        for child in children:
            if child is not None and child is not node:
                _walk(child)

    _walk(config)
    return found


def config_has_fused_moe_experts(config) -> bool:
    """Whether loading this config would build fused 3D expert parameters.

    ``transformers>=5`` describes such models with a ``WeightConverter`` that stacks the
    checkpoint's per-expert 2D tensors into one fused parameter (``MergeModulelist``).
    That converter is exactly the signal we care about: its presence means
    ``from_pretrained`` would produce a fused ``nn.Parameter`` that AutoRound then has to
    split back into per-expert ``nn.Linear`` -- the expensive case worth building on meta
    for. MoE models that already ship as ``ModuleList`` of ``Linear`` have no such
    converter and are deliberately left on the ordinary load path.
    """
    try:
        from transformers.conversion_mapping import get_checkpoint_conversion_mapping
        from transformers.core_model_loading import MergeModulelist, WeightConverter
    except ImportError:  # pragma: no cover - transformers < 5
        return False

    for model_type in _config_model_types(config):
        mapping = get_checkpoint_conversion_mapping(model_type)
        if not mapping:
            continue
        for entry in mapping:
            if not isinstance(entry, WeightConverter):
                continue
            if not any(isinstance(op, MergeModulelist) for op in entry.operations):
                continue
            if any("experts" in pattern for pattern in entry.source_patterns):
                logger.debug(
                    "[MoE Prep] '%s' merges per-expert checkpoint tensors into a fused parameter (%s)",
                    model_type,
                    entry.target_patterns,
                )
                return True
    return False