Skip to content

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

[high risk]Speedup 2.5-6X moe tuning and pin ngram to cpu (#2303)

Wenhua Cheng678f8f5f2b85
diff --git a/auto_round/algorithms/quantization/sign_round/quantizer.py b/auto_round/algorithms/quantization/sign_round/quantizer.py
index 1df932c83..37bd72aeb 100644
--- a/auto_round/algorithms/quantization/sign_round/quantizer.py
+++ b/auto_round/algorithms/quantization/sign_round/quantizer.py
@@ -110,7 +110,12 @@ class SignRoundQuantizer(BaseQuantizer):
continue
add_hook_to_module(_mod, AlignDevicesHook(_mod.tuning_device, io_same_device=True), True)
else:
- block = block.to(device_manager.device)
+ from auto_round.utils.model import move_to_device_preserving_cpu_pinned, place_ngram_embeddings_for_tuning_
+
+ # Honor AR_NGRAM_DEVICE even on a single GPU (default keeps the table on CPU and
+ # logs a hint); this also surfaces the ngram size / placement info to the user.
+ place_ngram_embeddings_for_tuning_(block)
+ block = move_to_device_preserving_cpu_pinned(block, device_manager.device)
card_0_in_high_risk, loss_device = False, device_manager.device
self._card_0_in_high_risk = card_0_in_high_risk
diff --git a/auto_round/compressors/orchestrator.py b/auto_round/compressors/orchestrator.py
index 243492de4..cc2a9f7b5 100644
--- a/auto_round/compressors/orchestrator.py
+++ b/auto_round/compressors/orchestrator.py
@@ -1030,7 +1030,10 @@ class CompressionOrchestrator(BaseOrchestrator):
materialize_model_(block)
convert_module_to_hp_if_necessary(block, self.model_context.amp_dtype, device)
- block = block.to(device)
+ from auto_round.utils.model import move_to_device_preserving_cpu_pinned, pin_ngram_embeddings_on_cpu_
+
+ pin_ngram_embeddings_on_cpu_(block)
+ block = move_to_device_preserving_cpu_pinned(block, device)
ctx = BlockContext(
model=self.model,
@@ -1096,7 +1099,13 @@ class CompressionOrchestrator(BaseOrchestrator):
device,
)
else:
- block = block.to(device)
+ from auto_round.utils.model import (
+ move_to_device_preserving_cpu_pinned,
+ place_ngram_embeddings_for_tuning_,
+ )
+
+ place_ngram_embeddings_for_tuning_(block)
+ block = move_to_device_preserving_cpu_pinned(block, device)
card_0_in_high_risk, loss_device = False, device
else:
card_0_in_high_risk, loss_device = False, device
diff --git a/auto_round/context/model.py b/auto_round/context/model.py
index 0b399bf6d..63657b526 100644
--- a/auto_round/context/model.py
+++ b/auto_round/context/model.py
@@ -225,21 +225,6 @@ class ModelContext(BaseContext):
model_name=self.model, trust_remote_code=self.trust_remote_code
)
- if (
- not self.is_model_patched
- and config is not None
- and is_moe_model_via_config(config)
- and version.parse(transformers.__version__) >= version.parse("5.0.0")
- ):
- from auto_round.modeling.fused_moe.replace_modules import BUILTIN_MODULES
-
- model_type = getattr(config, "model_type", None)
- if model_type is not None and model_type not in BUILTIN_MODULES:
- logger.warning(
- "This MoE model has not been optimized by AutoRound yet, which may result in high RAM usage, "
- "Please consider submitting an issue to https://github.com/intel/auto-round/issues"
- )
-
# Reclaim temporary HTTP/config objects from model type detection
# and AutoConfig loading before the large model allocation. This
# reduces heap fragmentation especially on HPU where habana internal
@@ -346,7 +331,7 @@ class ModelContext(BaseContext):
self.disk_stream_model_dir = checkpoint_dir
logger.info(
"Fused-MoE checkpoint detected: building a meta skeleton and materializing weights per block "
- "(set AR_DISABLE_AUTO_META_LOAD=1 to load the whole model on CPU instead)."
+ "(set `AR_DISABLE_AUTO_META_LOAD=1` to load the whole model on CPU instead)."
)
return True
diff --git a/auto_round/envs.py b/auto_round/envs.py
index f62f6f308..d0d18da0a 100644
--- a/auto_round/envs.py
+++ b/auto_round/envs.py
@@ -142,6 +142,57 @@ environment_variables: dict[str, Callable[[], Any]] = {
# to rotate token assignments across all experts for calibration coverage.
"AR_FORCE_MOE_ROUTING_ALL_EXPERTS": lambda: os.getenv("AR_FORCE_MOE_ROUTING_ALL_EXPERTS", "0").lower()
in ("1", "true", "yes"),
+ # Experts forward used for AutoRound's unfused per-expert nn.Linear MoE layout:
+ # "auto" - (default) same as "linear_grouped"
+ # "linear_grouped" - sort the routed (token, expert) pairs once and run one
+ # grouped GEMM over the sorted batch, using torch's native
+ # ``grouped_mm`` kernel (one launch for all experts -- markedly
+ # faster for tuning fwd+bwd on many-expert MoEs, up to ~5x on a
+ # synthetic full Qwen3.5-MoE decoder layer, batch=8, A100, with the
+ # gain almost entirely in backward). Avoids the per-expert
+ # nonzero()/numel() device syncs of the loop backend. Transparently
+ # falls back to the sliced per-expert loop when the native kernel is
+ # unavailable/ineligible (non-CUDA, pre-sm80, unsupported dtype/torch,
+ # alignment) -- see modeling/fused_moe/grouped_experts.py.
+ # "linear_grouped_sliced" - same grouped backend, but force the sliced per-expert
+ # ``F.linear`` loop instead of the native ``grouped_mm`` kernel.
+ # Both grouped paths are numerically identical (gradients included,
+ # verified bit-exact on A100).
+ # "linear_loop" - legacy per-expert Python loop.
+ # The grouped backend validates the layer and transparently falls back to the loop
+ # when the layer is not eligible (Conv1D experts, forward hooks, static/per-tensor
+ # activation quantization, mixed devices, ...).
+ "AR_MOE_EXPERTS_IMPL": lambda: os.getenv("AR_MOE_EXPERTS_IMPL", "auto").lower(),
+ # How many experts the "linear_grouped" backend groups per fused op. This one knob
+ # governs BOTH the fake-quant fusion AND the native grouped_mm tiling (when the native
+ # kernel is active): the qdq of a chunk is one fused quant call, and that same chunk
+ # is one native grouped_mm launch, so the ``torch.stack`` (E, out, in) operand the kernel
+ # needs is bounded to ``chunk`` experts instead of all active experts.
+ # Accepted values:
+ # "auto" - (default) derive the group size from a fixed working-set budget and the
+ # weight shape (~16 on the shapes it was tuned on; more for small experts).
+ # Benchmarks (A100, W4G128 tuning fwd+bwd) show "auto" matches or beats a
+ # fixed 16 on every Qwen3-MoE preset (e.g. 35B-A3B: 108 ms vs 156 ms).
+ # <int > 0> - fixed group size. Fusing every active expert at once builds a working set
+ # that grows with the expert count; past a point that costs peak memory on
+ # GPU and cache locality on CPU (measured: fusing 64 experts halved CPU
+ # calibration throughput, and doubled the GPU calibration peak).
+ # 0 or <0 - disable chunking/tiling: "fuse everything" in one group (e.g. set -1 to turn it off).
+ # Results are identical for any value -- rows stay independent. A fixed count and "auto"
+ # are both torch.compile-friendly (constant fused shape -> no per-count recompile).
+ "AR_MOE_CHUNK": lambda: os.getenv("AR_MOE_CHUNK", "auto").lower(),
+ # Where to place huge, non-quantizable per-layer ngram/PLE embeddings (e.g. Qwen4-Exp's
+ # ~95 GiB table) during per-block tuning. They do not participate in tuning but must run to
+ # produce correct block outputs.
+ # "auto" - (default) keep the table pinned on CPU (memory-safe: no per-card OOM and no
+ # extra device RAM churn). A one-time hint suggests the faster on-GPU options.
+ # "across"/"shard"/"gpu" - row-shard the table across all available GPUs (fast on-device
+ # lookup, avoids card-0 OOM). Experimental.
+ # "cpu" - keep it pinned on CPU (same as the default).
+ # "cuda:N"/"xpu:N"/"<index>" - put the whole table on that specific card.
+ # NOTE: multi-GPU sharding ("across") is experimental and may have bugs; prefer "cpu"
+ # (default) or a specific card if you hit issues.
+ "AR_NGRAM_DEVICE": lambda: os.getenv("AR_NGRAM_DEVICE", "auto").strip().lower(),
# vLLM fused kernels require q/k/v and gate/up projections to use one
# weight global scale. Disable only for runtimes without that requirement.
"AR_NVFP4_FUSED_LAYER_GLOBAL_SCALE": lambda: os.getenv("AR_NVFP4_FUSED_LAYER_GLOBAL_SCALE", "1").lower()
diff --git a/auto_round/logger.py b/auto_round/logger.py
index afcce709d..e439d2cad 100644
--- a/auto_round/logger.py
+++ b/auto_round/logger.py
@@ -34,6 +34,18 @@ def warning_once(self, msg, *args):
logger.warning(msg, *args, stacklevel=2)
+@lru_cache(maxsize=None)
+def info_once(self, msg, *args):
+ """
+ Log an info message only once per unique message/arguments combination.
+
+ Args:
+ msg: The info message format string
+ *args: Variable positional arguments for message formatting
+ """
+ logger.info(msg, *args, stacklevel=2)
+
+
# Define a new logging level TRACE
TRACE_LEVEL = 5
logging.addLevelName(TRACE_LEVEL, "TRACE")
@@ -94,6 +106,7 @@ class AutoRoundFormatter(logging.Formatter):
logging.Logger.warning_once = warning_once
+logging.Logger.info_once = info_once
logger = logging.getLogger("autoround")
logger.setLevel(envs.AR_LOG_LEVEL)
logger.propagate = False
diff --git a/auto_round/modeling/fused_moe/__init__.py b/auto_round/modeling/fused_moe/__init__.py
index deacabb31..d29e61a91 100644
--- a/auto_round/modeling/fused_moe/__init__.py
+++ b/auto_round/modeling/fused_moe/__init__.py
@@ -18,11 +18,17 @@ from auto_round.modeling.fused_moe.replace_modules import (
materialize_model_,
release_original_module_,
)
+from auto_round.modeling.fused_moe.grouped_experts import (
+ GROUPED_LINEAR_IMPL,
+ grouped_linear_experts_forward,
+)
from auto_round.modeling.fused_moe.moe_experts_interface import (
+ LINEAR_LOOP_IMPL,
is_linear_loop_available,
linear_loop_experts_forward,
prepare_model_for_moe_quantization,
register_linear_loop_experts,
+ resolve_experts_implementation,
)
__all__ = [
@@ -32,7 +38,11 @@ __all__ = [
"release_original_module_",
# Transformers-native MOE integration (transformers 5.0+)
"linear_loop_experts_forward",
+ "grouped_linear_experts_forward",
"register_linear_loop_experts",
"prepare_model_for_moe_quantization",
+ "resolve_experts_implementation",
"is_linear_loop_available",
+ "LINEAR_LOOP_IMPL",
+ "GROUPED_LINEAR_IMPL",
]
diff --git a/auto_round/modeling/fused_moe/gpt_oss.py b/auto_round/modeling/fused_moe/gpt_oss.py
index 370d7ba0d..d8f4ee5f6 100644
--- a/auto_round/modeling/fused_moe/gpt_oss.py
+++ b/auto_round/modeling/fused_moe/gpt_oss.py
@@ -28,10 +28,34 @@ from transformers.models.gpt_oss.modeling_gpt_oss import GptOssMLP
from auto_round.modeling.fused_moe.fusion_spec import build_standard_moe_fusion_spec, register_moe_fusion_spec
from auto_round.modeling.fused_moe.replace_modules import ReplacementModuleBase
-from auto_round.modeling.fused_moe.utils import _update_parameter
+from auto_round.modeling.fused_moe.utils import _update_parameter, grouped_or_sequential_moe_forward
from auto_round.utils import clear_memory, unsupported_meta_device
+class GPTOssExperts(torch.nn.ModuleList):
+ """Per-expert ``GPTOssSingleExpert`` container with the GPT-OSS gating exposed for the
+ grouped experts forward.
+
+ GPT-OSS does not use the generic ``act_fn(gate) * up`` gate, so it provides ``_apply_gate``
+ (the hook the grouped path prefers): the ``[gate; up]`` clamp, the ``glu = gate * sigmoid(
+ gate * alpha)`` GLU, and the ``(up + 1) * glu`` scaling -- byte-for-byte what
+ ``GPTOssSingleExpert.forward`` does, so the grouped result matches the per-expert loop.
+ """
+
+ def __init__(self, experts: list[nn.Module], num_experts: int, alpha: float, limit: float):
+ super().__init__(experts)
+ self.num_experts = num_experts
+ self.alpha = alpha
+ self.limit = limit
+
+ def _apply_gate(self, gate_up_out: torch.Tensor) -> torch.Tensor:
+ gate, up = gate_up_out.chunk(2, dim=-1)
+ gate = gate.clamp(max=self.limit)
+ up = up.clamp(min=-self.limit, max=self.limit)
+ glu = gate * torch.sigmoid(gate * self.alpha)
+ return (up + 1) * glu
+
+
class GPTOssSingleExpert(nn.Module):
def __init__(self, hidden_size: int, intermediate_size: int, dtype: torch.dtype | None = None):
@@ -80,11 +104,11 @@ class SequentialGPTOSSMoE(ReplacementModuleBase):
self.num_experts = E
# Build per-expert MLPs
- self.experts = nn.ModuleList()
target_device = next(original.experts.parameters()).device
with no_init_weights(), torch.device("meta"):
- for _ in range(E):
- self.experts.append(GPTOssSingleExpert(hidden_size, intermediate_size, dtype=dtype))
+ expert_mlps = [GPTOssSingleExpert(hidden_size, intermediate_size, dtype=dtype) for _ in range(E)]
+ # Expose num_experts + the GPT-OSS gating so the grouped experts forward can run.
+ self.experts = GPTOssExperts(expert_mlps, num_experts=E, alpha=expert_mlps[0].alpha, limit=expert_mlps[0].limit)
register_moe_fusion_spec(
self.experts,
build_standard_moe_fusion_spec(
@@ -123,33 +147,16 @@ class SequentialGPTOSSMoE(ReplacementModuleBase):
else:
router_scores, router_indices = router_out
- final_hidden_states = self.shared_expert(x) if self.shared_expert is not None else torch.zeros_like(x)
- num_all_tokens, total_num_experts = x.size(0), self.num_experts
- mask_weights = torch.zeros((num_all_tokens, total_num_experts), dtype=x.dtype, device=x.device)
- topk_ids = router_indices.to(torch.int64)
-
- mask_weights.scatter_(-1, topk_ids, 1)
-
- # Build per-expert routing score matrix: shape (num_experts, num_tokens)
- # experts_mask[e, t] = router score of expert e for token t (0 if not selected)
- expert_score_matrix = torch.zeros_like(mask_weights)
- expert_score_matrix.scatter_(-1, topk_ids, router_scores)
- expert_score_matrix = expert_score_matrix.transpose(0, 1) # (num_experts, num_tokens)
-
- mask_weights = mask_weights[:num_all_tokens, :total_num_experts]
- mask_weights = mask_weights.transpose(0, 1)
-
- # Only process experts that actually received tokens (expert_hit pattern),
- # skipping experts with zero routing weight to save compute during calibration.
- with torch.no_grad():
- expert_hit = torch.greater(mask_weights.sum(dim=-1), 0).nonzero()
- for expert_idx in expert_hit:
- expert_idx = expert_idx[0]
- mask_weight = mask_weights[expert_idx].unsqueeze(1)
- current_state_static = x * mask_weight
- expert_output = self.experts[expert_idx](current_state_static)
- expert_output = expert_output * expert_score_matrix[expert_idx].unsqueeze(1)
- final_hidden_states += expert_output
+ shared = self.shared_expert(x) if self.shared_expert is not None else torch.zeros_like(x)
+
+ # ``router_indices``/``router_scores`` are the gathered (token, top_k) ids and weights
+ # (the original built its per-expert score matrix by scattering exactly these). Feeding
+ # them to the grouped experts forward reproduces the old ``sum_e expert(x) * score[e]``
+ # dense-mask loop -- routed pairs only, weighted then reduced over top_k.
+ expert_output = grouped_or_sequential_moe_forward(
+ x, router_indices, router_scores, self.experts, self.num_experts
+ )
+ final_hidden_states = shared + expert_output
return final_hidden_states.view(B, T, H), router_scores.view(B * T, -1)
diff --git a/auto_round/modeling/fused_moe/grouped_experts.py b/auto_round/modeling/fused_moe/grouped_experts.py
new file mode 100644
index 000000000..c9a755316
--- /dev/null
+++ b/auto_round/modeling/fused_moe/grouped_experts.py
@@ -0,0 +1,1250 @@
+# 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.
+
+"""Grouped experts forward for unfused (per-expert ``nn.Linear``) MoE modules.
+
+Motivation
+----------
+``linear_loop_experts_forward`` iterates ``range(num_experts)`` in Python. Only the
+experts that were actually routed to do any work -- the rest are skipped -- but *every*
+iteration still pays ``nonzero()`` + ``sample_idx.numel()``, and that ``.numel()`` on a
+data-dependent ``nonzero()`` result is a host<->device sync. For the experts that do have
+tokens it then runs an ``index_select`` gather, three small GEMMs, and -- the expensive
+part -- a separate ``weight_quant_func`` call, because each expert's ``WrapperLinear``
+fake-quantizes its own weight. Block-wise tuning pays all of that on every forward *and*
+backward of every calibration step.
+
+This module keeps the math identical but restructures the layer around two independent
+wins. Measured on A100 (sm80, bf16, W4G128, 2048x768 experts, 4096 routed pairs), speedup
+over ``linear_loop`` for 16/32/64/128/256 experts:
+
+ routing/GEMM only 1.09 1.09 1.21 1.10 1.12 (forward+backward)
+ + fused fake-quantization 4.36 4.70 5.32 5.14 5.24
+
+So the fused fake-quant is the dominant term. The routing rework looks small here only
+because the per-expert quant dominates the total: on plain fp weights, where nothing hides
+the GEMM, the same rework is worth 1.90-2.42x on its own.
+
+How it works:
+
+1. Flatten the ``(num_tokens, top_k)`` routing into ``S = num_tokens * top_k`` pairs.
+2. ``sort`` the pairs by expert id so every expert's tokens are one contiguous slice --
+ a plain view, so no ``nonzero`` and no gather kernel.
+3. Take a **single** sync (``unique_consecutive``) to learn which experts are hit and how
+ many rows each got, instead of one per expert. Experts with no tokens never appear.
+4. **Fuse the fake-quantization**: concatenate the active experts' weights *and* their
+ tuning tensors (``value``, ``min_scale``, ``max_scale``, ``weight_min``/``weight_max``,
+ SignRoundV2's ``init_scale``) into one big tensor and call ``weight_quant_func`` once
+ for the whole projection instead of once per expert. AutoRound's quantizers derive
+ their scales per row of the group-reshaped tensor, so rows stay independent and the
+ result is bit-identical; the backward likewise becomes a single big graph. See
+ ``_batched_qdq_weights``.
+5. Run the routed GEMM: by default torch's native ``grouped_mm`` kernel (one launch for all
+ experts); ``AR_MOE_EXPERTS_IMPL=linear_grouped_sliced`` forces one ``F.linear`` per
+ *active* expert over its contiguous slice instead (see the note above
+ ``_native_grouped_mm_available``).
+6. Scatter back and reduce over ``top_k``.
+
+Gradients flow through the fake-quantized weights exactly as in the loop version, so this
+is usable during tuning and not only for calibration/inference.
+
+Fallbacks
+---------
+The grouped path only kicks in when the layer really is a stack of plain ``nn.Linear`` /
+``WrapperLinear`` projections that all share one quantization scheme. Anything else
+transparently falls back to ``linear_loop_experts_forward``:
+
+* **mixed-bit MoE** — experts (or projections) quantized with different
+ bits/group_size/data_type/sym, a mix of quantized and left-in-16-bit experts, or a mix
+ of wrapper classes;
+* Conv1D / LinearAllreduce experts, which need their own forward;
+* forward hooks on the expert layers (e.g. online Hadamard rotation);
+* activation quantization that is not row-independent (static ranges, per-tensor groups,
+ per-expert tunable min/max, NVFP per-layer global scales);
+* experts spread over different devices.
+
+Step 4 has its own, narrower eligibility check on top of that. It covers plain group-wise
+quantization, per-tensor (``group_size == 0``), 2-D blocks whose grid does not straddle
+experts, NVFP ``global_scale`` and per-expert ``imatrix``; it steps aside (keeping only the
+grouped GEMM) for GGUF super-blocks that would span two experts and for wrappers that
+override ``_qdq_weight`` (GGUF double-quant search, AutoScheme scoring).
+See ``_supports_batched_qdq``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from math import ceil
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from auto_round import envs
+from auto_round.modeling.fused_moe.utils import build_forced_routing, force_all_experts_routing_enabled
+from auto_round.utils import logger
+
+# Expert implementation name registered into transformers' ``ALL_EXPERTS_FUNCTIONS``.
+GROUPED_LINEAR_IMPL = "linear_grouped"
+# Same grouped forward, but forcing the sliced per-expert GEMM loop instead of the native
+# ``grouped_mm`` kernel. Selected via ``AR_MOE_EXPERTS_IMPL=linear_grouped_sliced``.
+GROUPED_LINEAR_SLICED_IMPL = "linear_grouped_sliced"
+
+# Set once if the native grouped_mm kernel raises; afterwards we always use the sliced loop.
+_NATIVE_GROUPED_MM_DISABLED = False
+_LOGGED_FALLBACK_REASONS: set[str] = set()
+
+
+def _log_fallback_once(reason: str) -> None:
+ if reason not in _LOGGED_FALLBACK_REASONS:
+ _LOGGED_FALLBACK_REASONS.add(reason)
+ logger.debug(f"[MoE grouped] falling back to linear_loop: {reason}")
+
+
+# --------------------------------------------------------------------------------------
+# Layer introspection helpers
+# --------------------------------------------------------------------------------------
+
+
+_WRAPPER_LINEAR_CLS: type | None = None
+
+
+def _is_wrapper_linear(layer: nn.Module) -> bool:
+ """``isinstance(layer, WrapperLinear)`` without importing wrapper.py at module import.
+
+ The class is resolved once and cached: this runs a few times per expert per forward,
+ and a MoE layer can have hundreds of experts.
+ """
+ global _WRAPPER_LINEAR_CLS
+ if _WRAPPER_LINEAR_CLS is None:
+ try:
+ from auto_round.wrapper import WrapperLinear
+ except Exception: # pragma: no cover - defensive
+ return False
+ _WRAPPER_LINEAR_CLS = WrapperLinear
+ return isinstance(layer, _WRAPPER_LINEAR_CLS)
+
+
+def _act_signature(layer: nn.Module):
+ """Quantization signature of a wrapped layer's *activation* path.
+
+ Two projections may share one grouped activation-quantization call only when their
+ signatures match, because we quantize the whole sorted batch in a single shot.
+ """
+ orig = layer.orig_layer
+ return (
+ getattr(orig, "act_bits", 16),
+ getattr(orig, "act_group_size", -1),
+ getattr(orig, "act_sym", True),
+ getattr(orig, "act_data_type", None),
+ bool(getattr(orig, "act_dynamic", True)),
+ )
+
+
+def _quant_signature(layer: nn.Module):
+ """Quantization signature of one projection slot, or ``None`` if it is not quantized.
+
+ AutoRound supports mixed-bit MoE: individual experts (or even individual projections
+ inside one expert) can carry different schemes. Sharing one grouped GEMM across
+ experts whose weights were produced by different quant functions is not something we
+ want to reason about case by case, so experts must agree on this signature or the
+ layer falls back to the per-expert loop. The common case — one uniform scheme for the
+ whole experts module — is unaffected.
+
+ The wrapper *class* is part of the signature too: SignRoundV2's optimized wrapper,
+ the GGUF double-quant wrapper and the AutoScheme scoring wrappers all carry their own
+ tuning state and ``minmax_scale_bound``, so they must not be mixed inside one group.
+ """
+ if not _is_wrapper_linear(layer):
+ return None
+ orig = layer.orig_layer
+ enable_act_quant = bool(getattr(layer, "enable_act_quant", False))
+ return (
+ type(layer),
+ getattr(orig, "bits", 16),
+ getattr(orig, "group_size", -1),
+ bool(getattr(orig, "sym", True)),
+ getattr(orig, "data_type", None),
+ getattr(layer, "data_type", None), # resolved by get_quant_func, may differ from orig
+ getattr(orig, "super_bits", None),
+ getattr(orig, "super_group_size", None),
+ bool(getattr(layer, "disable_opt_rtn", True)),
+ enable_act_quant,
+ _act_signature(layer) if enable_act_quant else None,
+ )
+
+
+def _weight_layout(layer: nn.Module):
+ """``(shape, dtype)`` of the underlying weight; must match to be batched together."""
+ weight = layer.weight
+ return tuple(weight.shape), weight.dtype
+
+
+def _act_quant_is_row_independent(layer: nn.Module) -> bool:
+ """Whether activation quantization can be applied to the concatenated batch at once.
+
+ Quantizing ``x[a:b]`` per expert equals quantizing the full ``x`` only when each row
+ (or each group inside a row) gets its own scale and that scale is derived from the
+ data itself. Per-tensor (``group_size == 0``), 2-D groups, static ranges and tunable
+ per-expert min/max coefficients all couple rows of *different* experts together, so
+ they disqualify the grouped path.
+ """
+ orig = layer.orig_layer
+ if not getattr(orig, "act_dynamic", False):
+ return False # static: act_max is calibrated per expert
+ group_size = getattr(orig, "act_group_size", -1)
+ if isinstance(group_size, tuple) or group_size == 0:
+ return False # per-tensor / 2-D groups mix rows across experts
+ if getattr(layer, "input_global_scale", None) is not None:
+ return False # NVFP-style per-layer global scale
+ for name in ("act_max_scale", "act_min_scale"):
+ if isinstance(getattr(layer, name, None), nn.Parameter):
+ return False # tunable, and tuned independently per expert
+ return True
+
+
+def _projection_is_supported(layer: nn.Module) -> bool:
+ if type(layer) is nn.Linear:
+ # A plain Linear carrying forward (pre-)hooks must run its own forward so the hooks
+ # fire. This is how act_max is collected during calibration: the composer registers a
+ # forward hook on each expert Linear, and the grouped path -- which multiplies the
+ # weights directly and never calls ``Linear.forward`` -- would silently skip them,
+ # leaving every expert without ``act_max`` (breaking static-act export, e.g. NVFP4).
+ if layer._forward_pre_hooks or layer._forward_hooks:
+ return False
+ return True
+ if not _is_wrapper_linear(layer):
+ return False
+ orig = layer.orig_layer
+ if type(orig) is not nn.Linear:
+ return False # Conv1D / LinearAllreduce need their own forward
+ if orig._forward_pre_hooks or orig._forward_hooks:
+ return False # e.g. online Hadamard rotation must run per layer
+ if getattr(layer, "enable_act_quant", False) and not _act_quant_is_row_independent(layer):
+ return False
+ return True
+
+
+def _compute_device(layer: nn.Module) -> torch.device:
+ if _is_wrapper_linear(layer):
+ return torch.device(layer.device)
+ return layer.weight.device
+
+
+def _output_device(layer: nn.Module) -> torch.device:
+ if _is_wrapper_linear(layer):
+ return torch.device(layer.output_device)
+ return layer.weight.device
+
+
+def _effective_weight_and_bias(layer: nn.Module) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Return the weight the layer would actually multiply with, plus its bias.
+
+ For a ``WrapperLinear`` this is the fake-quantized weight produced by the current
+ tuning parameters, so autograd reaches ``value`` / ``min_scale`` / ``max_scale``.
+ """
+ if _is_wrapper_linear(layer):
+ weight, _, _ = layer._qdq_weight(layer.value, layer.min_scale, layer.max_scale)
+ return weight, _effective_bias(layer)
+ return layer.weight, layer.bias
+
+
+def _effective_bias(layer: nn.Module) -> torch.Tensor | None:
+ if not _is_wrapper_linear(layer):
+ return layer.bias
+ bias = layer.orig_layer.bias
+ if bias is not None and bias.device.type == "meta":
+ bias = layer.orig_layer.get_bias().to(layer.device)
+ if getattr(layer, "enable_norm_bias_tuning", False):
+ bias, _, _ = layer._qdq_bias(bias, layer.bias_v)
+ return bias
+
+
+# --------------------------------------------------------------------------------------
+# Batched fake-quantization
+# --------------------------------------------------------------------------------------
+#
+# The grouped GEMM alone removes the per-expert launches/syncs of the *matmul*, but with
+# ``WrapperLinear`` the dominant cost during tuning is the fake-quantization itself: one
+# ``weight_quant_func`` call per expert, each on a small ``(out, in)`` tensor, plus the
+# matching backward. With hundreds of experts that is hundreds of tiny elementwise graphs
+# (and, under ``enable_torch_compile``, hundreds of compiled-graph launches).
+#
+# AutoRound's weight quantizers derive their scales from *rows* of the group-reshaped
+# tensor (``reshape_pad_tensor_by_group_size``), so as long as the fused layout keeps each
+# expert on its own set of rows, quantizing ``cat([w_0, ..., w_{E-1}])`` is identical to
+# quantizing each ``w_i`` on its own. We then also concatenate the per-row tuning tensors
+# (``value``, ``min_scale``, ``max_scale``, ``weight_min``/``weight_max``, SignRoundV2's
+# ``init_scale``) and run a single quant call for the whole slot. Autograd routes each
+# row-block's gradient back to the owning expert's parameters, so tuning is unchanged.
+#
+# Group layouts, and how they fuse:
+# group_size > 0 / -1 ``cat(dim=0)`` -> ``(E * out, in)``; groups never straddle rows.
+# group_size == 0 per-tensor, i.e. ONE scale per expert. Reshaping each expert to a
+# single row and passing ``group_size=-1`` reproduces that exactly.
+# group_size == (M, N) 2-D blocks. ``cat(dim=0)`` is only equivalent when ``out % M == 0``
+# -- otherwise per-expert zero-padding of the last block row would
+# differ from the fused tensor's.
+#
+# Per-layer extras, and how they fuse:
+# NVFP ``global_scale`` a per-layer scalar that the quant func broadcasts against the
+# ``(rows, 1)`` per-group max, so an expanded ``(rows, 1)`` column
+# keeps every expert on its own scalar.
+# GGUF ``super_bits`` super-blocks group consecutive *rows*; GGUF requires
+# ``in % QK_K == 0``, so every expert's row count is already a
+# multiple of ``super_group_size`` and blocks cannot straddle
+# experts. Guarded explicitly all the same.
+# ``imatrix`` declared as one value per *input channel*, which the quantizers
+# broadcast across output rows with
+# ``imatrix.reshape(1, -1).expand(tensor.numel() // imatrix.numel(),
+# -1).reshape(tensor.shape)``. Handing them a *full-size* importance
+# tensor makes that expand a no-op and the reshape an exact
+# per-element mapping, so each expert keeps its own imatrix. The
+# row-wise zero fixup (``_imatrix_handle_zero``) is row-independent,
+# so the result stays bit-exact. When the experts happen to share one
+# imatrix we pass it through unexpanded and pay nothing.
+#
+# Wrappers that override ``_qdq_weight`` (GGUF double-quant search, AutoScheme scoring)
+# carry per-layer state and always keep the per-expert call. That also keeps the GGUF
+# "row pattern" imatrix consumers (``_imatrix_row_pattern``, only reached from the
+# double-quant search) out of the fused path.
+
+
+def _grouped_row_count(out_features: int, in_features: int, group_size: int) -> int:
+ """Rows of the group-reshaped weight, mirroring ``reshape_pad_tensor_by_group_size``."""
+ if group_size == -1 or in_features < group_size:
+ return out_features
+ return out_features * ceil(in_features / group_size)
+
+
+# Quant funcs that take ``global_scale`` and only ever broadcast it against per-row
+# quantities, so a per-row column vector keeps each expert on its own scalar. Variants that
+# recompute the scale from the tensor's global max (``*_with_static_gs``, ``nvfp4_v2*``,
+# ``opt_rtn_nv_fp4``) would collapse it across experts and are deliberately excluded.
+_PER_ROW_GLOBAL_SCALE_DTYPES = frozenset({"nv_fp4", "nv_fp4_rtn"})
+
+
+def _fusion_group_size(layer: nn.Module) -> int | tuple | None:
+ """``group_size`` to hand the fused quant call, or ``None`` if the slot cannot fuse."""
+ group_size = layer.orig_layer.group_size
+ out_features = layer.weight.shape[0]
+ if isinstance(group_size, tuple):
+ if len(group_size) != 2 or out_features % group_size[0] != 0:
+ return None # the block grid would straddle two experts
+ return group_size
+ if not isinstance(group_size, int) or isinstance(group_size, bool):
+ return None
+ if group_size == 0:
+ return -1 # per-tensor == one row per expert
+ return group_size
+
+
+def _supports_batched_qdq(layer: nn.Module) -> bool:
+ """Whether this projection's fake-quantization may be fused with its siblings'."""
+ if not _is_wrapper_linear(layer):
+ return False
+ if type(layer)._qdq_weight is not _WRAPPER_LINEAR_CLS._qdq_weight:
+ return False # custom qdq: GGUF double-quant search, AutoScheme scoring, ...
+ orig = layer.orig_layer
+ if getattr(orig, "bits", 16) >= 16:
+ return False # not quantized: the plain weight is used as-is
+ if hasattr(layer, "_extra_quant_kwargs"):
+ return False # unknown per-layer quant kwargs
+
+ fusion_group_size = _fusion_group_size(layer)
+ if fusion_group_size is None:
+ return False
+
+ if getattr(orig, "imatrix", None) is not None:
+ # The fused importance tensor is flattened once and padded as a whole, so it only
+ # lines up with the per-expert layout when no row-level padding is involved.
+ if not isinstance(fusion_group_size, int):
+ return False
+ in_features = layer.weight.shape[1]
+ if fusion_group_size > 0 and in_features % fusion_group_size != 0:
+ return False
+
+ if getattr(layer, "weight_global_scale", None) is not None:
+ if getattr(layer, "data_type", None) not in _PER_ROW_GLOBAL_SCALE_DTYPES:
+ return False
+ if isinstance(fusion_group_size, tuple):
+ return False # no per-row column to broadcast against
+
+ super_group_size = getattr(orig, "super_group_size", None)
+ if getattr(orig, "super_bits", None) is not None:
+ if not super_group_size or isinstance(fusion_group_size, tuple):
+ return False
+ out_features, in_features = layer.weight.shape
+ rows = _grouped_row_count(out_features, in_features, fusion_group_size)
+ if rows % super_group_size != 0:
+ return False # a super-block would span two experts
+
+ return True
+
+
+_UNBATCHABLE = object()
+
+
+def _cat_tuning_tensors(layers: list[nn.Module], name: str) -> torch.Tensor | None | object:
+ """Concatenate a per-row tuning tensor across experts, or pass a shared scalar through.
+
+ Returns ``_UNBATCHABLE`` when the attribute is inconsistent (some experts have it and
+ others do not), which disables the batched path for the slot.
+ """
+ values = [getattr(layer, name, None) for layer in layers]
+ first = values[0]
+ if first is None:
+ return None if all(v is None for v in values) else _UNBATCHABLE
+ if not isinstance(first, torch.Tensor):
+ return _UNBATCHABLE
+ if first.dim() == 0:
+ # Non-tunable constant (e.g. value=0.0 when round tuning is off): identical for
+ # every expert, and broadcast by the quant func.
+ if any(v is None or not isinstance(v, torch.Tensor) or v.dim() != 0 for v in values):
+ return _UNBATCHABLE
+ return first
+ if any(v is None or not isinstance(v, torch.Tensor) or v.dim() == 0 for v in values):
+ return _UNBATCHABLE
+ return torch.cat(values, dim=0)
+
+
+def _fused_global_scale(layers: list[nn.Module], rows_per_expert: int, device) -> torch.Tensor | None | object:
+ """Expand each expert's NVFP per-layer scalar into a ``(E * rows, 1)`` column."""
+ scales = [getattr(layer, "weight_global_scale", None) for layer in layers]
+ if all(scale is None for scale in scales):
+ return None
+ if any(scale is None or not isinstance(scale, torch.Tensor) or scale.numel() != 1 for scale in scales):
+ return _UNBATCHABLE
+ flat = torch.stack([scale.reshape(()) for scale in scales]).to(device=device, dtype=torch.float32)
+ return flat.repeat_interleave(rows_per_expert).unsqueeze(-1)
+
+
+def _shares_one_tensor(tensors: list[torch.Tensor]) -> bool:
+ """Cheap, sync-free "are these all the same tensor" test (identity or same storage)."""
+ first = tensors[0]
+ for other in tensors[1:]:
+ if other is first:
+ continue
+ if other.shape != first.shape or other.dtype != first.dtype or other.data_ptr() != first.data_ptr():
+ return False
+ return True
+
+
+def _fused_imatrix(layers: list[nn.Module], out_features: int, device) -> torch.Tensor | None | object:
+ """Build the importance matrix matching the fused weight layout.
+
+ The quantizers treat ``imatrix`` as one value per input channel and broadcast it over
+ the output rows with ``reshape(1, -1).expand(tensor.numel() // imatrix.numel(),
+ -1).reshape(tensor.shape)``. Passing a full-size ``(E * out, in)`` tensor turns that
+ expand into a no-op and the reshape into an exact per-element mapping, which is how
+ each expert keeps its own importance instead of inheriting the first one's.
+
+ When every expert already points at the same imatrix we hand that single vector over
+ untouched, so the common case costs nothing; otherwise the fused tensor is
+ materialized (roughly the size of the fused weight in fp32).
+ """
+ mats = [getattr(layer.orig_layer, "imatrix", None) for layer in layers]
+ if all(mat is None for mat in mats):
+ return None
+ if any(mat is None or not isinstance(mat, torch.Tensor) for mat in mats):
+ return _UNBATCHABLE
+
+ mats = [mat.to(device) for mat in mats]
+ if _shares_one_tensor(mats):
+ # The quant func's own row-repeat already produces the right thing.
+ return mats[0]
+
+ numel = mats[0].numel()
+ if any(mat.numel() != numel for mat in mats[1:]):
+ return _UNBATCHABLE
+ stacked = torch.stack([mat.reshape(-1) for mat in mats]) # (E, in)
+ return stacked.repeat_interleave(out_features, dim=0) # (E * out, in), expert-major
+
+
+def _batched_qdq_weights(
+ layers: list[nn.Module], *, allow_compiled: bool = True
+) -> tuple[torch.Tensor | None, list[torch.Tensor]] | None:
+ """Fake-quantize one projection of every expert in a single quant-func call.
+
+ Args:
+ layers: The projections to fuse, all from the same slot.
+ allow_compiled: Whether the group size is a constant, so the compiled quant
+ function can be used. Dynamo keys its cache on the traced code object, shared
+ by every ``WrapperLinear``, so a group whose size follows the router would add
+ a cache entry per distinct count.
+
+ Returns ``(stacked, per_expert_weights)`` where ``stacked`` is the ``(E, out, in)``
+ view of the fused result (free operand for the grouped-GEMM kernel, or ``None`` if the
+ result is not contiguous). Returns ``None`` when the slot turned out not to be
+ eligible and the caller must go per-expert.
+ """
+ ref = layers[0]
+ orig = ref.orig_layer
+ out_features, in_features = ref.weight.shape
+ num_experts = len(layers)
+
+ fusion_group_size = _fusion_group_size(ref)
+ if fusion_group_size is None: # pragma: no cover - already checked by the plan
+ return None
+ # Per-tensor slots fuse as one row per expert so each keeps its own single scale.
+ per_tensor = orig.group_size == 0
+
+ raw_weights = []
+ for layer in layers:
+ weight = layer.orig_layer.weight
+ if weight.device.type == "meta":
+ weight = layer.orig_layer.get_weight()
+ weight = weight.to(ref.device)
+ raw_weights.append(weight.reshape(1, -1) if per_tensor else weight)
+ fused_input = torch.cat(raw_weights, dim=0) # (E, out * in) or (E * out, in)
+
+ # WrapperLinear._qdq_weight clamps the *parameters* in place; do the same here so the
+ # optimizer sees identical state, then concatenate the clamped values.
+ min_bound, max_bound = type(ref).minmax_scale_bound
+ for layer in layers:
+ for name in ("min_scale", "max_scale"):
+ param = getattr(layer, name, None)
+ if isinstance(param, torch.Tensor) and param.dim() > 0:
+ param.data.clamp_(min_bound, max_bound)
+
+ fused: dict[str, object] = {
+ name: _cat_tuning_tensors(layers, name)
+ for name in ("value", "min_scale", "max_scale", "weight_min", "weight_max", "init_scale")
+ }
+ if isinstance(fusion_group_size, tuple):
+ # 2-D blocks never carry a per-layer global scale (checked by _supports_batched_qdq).
+ fused["global_scale"] = None
+ else:
+ rows_per_expert = 1 if per_tensor else _grouped_row_count(out_features, in_features, fusion_group_size)
+ fused["global_scale"] = _fused_global_scale(layers, rows_per_expert, ref.device)
+ fused["imatrix"] = _fused_imatrix(layers, out_features, ref.device)
+ if any(value is _UNBATCHABLE for value in fused.values()):
+ _log_fallback_once("inconsistent tuning tensors across experts; batched qdq disabled")
+ return None
+
+ quant_kwargs = {}
+ if getattr(orig, "super_bits", None) is not None:
+ quant_kwargs["super_bits"] = orig.super_bits
+ quant_kwargs["super_group_size"] = orig.super_group_size
+
+ # Normally the *compiled* quant function, same as the per-expert path uses: this call
+ # is reached from a function dynamo does not trace into (see ``_opaque_to_dynamo``), so
+ # it is an ordinary call into a compiled artifact and the fused shape is a constant.
+ # Only when the caller says the group size follows the router do we drop to eager,
+ # because dynamo keys its cache on the traced code object -- shared by every
+ # WrapperLinear -- and would gain an entry per distinct expert count.
+ quant_func = ref.weight_quant_func
+ if not allow_compiled:
+ quant_func = getattr(ref, "weight_quant_func_eager", None) or quant_func
+
+ weight_q, _, _ = quant_func(
+ fused_input,
+ bits=orig.bits,
+ group_size=fusion_group_size,
+ v=fused["value"],
+ min_scale=fused["min_scale"],
+ max_scale=fused["max_scale"],
+ scale_dtype=orig.scale_dtype,
+ tensor_min=fused["weight_min"],
+ tensor_max=fused["weight_max"],
+ data_type=ref.data_type,
+ q_scale_thresh=ref.q_scale_thresh,
+ imatrix=fused["imatrix"],
+ global_scale=fused["global_scale"],
+ init_scale=fused["init_scale"],
+ **quant_kwargs,
+ )
+ weight_q = weight_q.to(fused_input.dtype)
+
+ stacked = None
+ if weight_q.is_contiguous():
+ stacked = weight_q.view(num_experts, out_features, in_features)
+ weights = list(stacked.unbind(0))
+ elif per_tensor:
+ weights = [row.reshape(out_features, in_features) for row in weight_q]
+ else:
+ weights = list(torch.split(weight_q, out_features, dim=0))
+ return stacked, weights
+
+
+@dataclass
+class _SlotWeights:
+ """The weights/biases of one projection slot for every active expert."""
+
+ weights: list[torch.Tensor]
+ biases: list[torch.Tensor | None]
+ # (E, out, in) view of the fused qdq result, when available. Lets the native grouped_mm
+ # kernel get its 3D operand for free instead of a torch.stack copy.
+ stacked: torch.Tensor | None = None
+
+
+# Experts fake-quantized per fused call. Fusing *all* active experts at once maximizes
+# kernel size, but the working set it builds -- roughly
+# ``chunk * out * in * (weight_itemsize + 4)`` bytes, the concatenated weight plus its fp32
+# ``value`` -- grows with the expert count, and the quant func streams it several times
+# (min/max, scale, round_ste, clamp, mul). Past a point that costs peak memory on GPU and
+# cache locality on CPU.
+#
+# 16 comes from the chunk sweeps, not from taste:
+# CPU, 64x(512x256): fusing all 64 halved calibration throughput (0.50x vs the per-expert
+# loop); chunk=16 turned it into a win (1.28x calibration, 1.54x tuning).
+# A100, 128x(4096x1536): chunk=16 held the speed (1.58x tuning vs 1.63x for one fused
+# call) while cutting the calibration peak from 32.7 GB to 20.5 GB.
+#
+# ``AR_MOE_CHUNK`` overrides it; 0 or negative means "fuse everything".
+_DEFAULT_QDQ_CHUNK = 16
+
+# Target working set for one fused qdq call. The chunk is derived from this budget and the
+# per-expert weight size, instead of a flat count, so it adapts to the *shape* of the MoE:
+#
+# * On the large experts the flat 16 was tuned on (4096x1536, bf16 -> ~38 MB/expert) the
+# budget reproduces ~16, preserving those sweeps.
+# * On small experts (e.g. 512-wide MoE, ~6 MB/expert) it fuses far more per call, so the
+# compiled quant graph is launched a handful of times instead of ~16 -- which is what
+# makes the batched qdq pay off once the block forward is eager under torch.compile.
+#
+# The tail below is fused into a single eager call, so a larger chunk never inflates the
+# per-expert launch count; it only shifts work from many compiled calls to a few big ones.
+_QDQ_FUSED_WORKINGSET_BYTES = 512 * 1024 * 1024
+
+
+def _auto_qdq_chunk(layers: list[nn.Module]) -> int:
+ """Experts-per-fused-call derived from a fixed working-set budget and the weight shape.
+
+ Shape-derived (not routing-derived), so it stays constant across steps and does not
+ break :func:`_static_shapes_required`.
+ """
+ weight = layers[0].weight
+ # bytes streamed per expert: the concatenated weight plus its fp32 tuning ``value``.
+ per_expert = int(weight.shape[0]) * int(weight.shape[1]) * (weight.element_size() + 4)
+ if per_expert <= 0:
+ return _DEFAULT_QDQ_CHUNK
+ return max(_DEFAULT_QDQ_CHUNK, int(_QDQ_FUSED_WORKINGSET_BYTES // per_expert))
+
+
+def _qdq_chunk_size(layers: list[nn.Module]) -> int:
+ """Configured experts-per-fused-call. Not clamped to ``len(layers)``.
+
+ Clamping here would defeat :func:`_static_shapes_required`: when fewer experts than
+ the chunk are routed, the group would silently shrink to the active count and the
+ fused shape would follow the router again.
+ """
+ setting = envs.AR_MOE_CHUNK
+ if setting in ("", "auto"):
+ return _auto_qdq_chunk(layers)
+ try:
+ chunk = int(setting)
+ except ValueError:
+ logger.warning_once(f"Ignoring AR_MOE_CHUNK={setting!r}: expected 'auto' or an integer.")
+ return _auto_qdq_chunk(layers)
+ return chunk
+
+
+def _static_shapes_required(layer: nn.Module) -> bool:
+ """Whether the fused group size must stay constant across steps.
+
+ Only matters under ``torch.compile``: the fused call goes to the same compiled quant
+ function the per-expert path uses, and dynamo keys its cache on the traced code object
+ (shared by every ``WrapperLinear``). A group whose size followed the router would add
+ a cache entry per distinct active-expert count -- i.e. per calibration sample.
+ """
+ return bool(getattr(layer, "enable_torch_compile", False))
+
+
+def _plan_qdq_groups(layers: list[nn.Module]) -> tuple[list[list[nn.Module]], list[nn.Module], bool]:
+ """Split the active experts into fused groups, a remainder tail, and a "fixed size" flag.
+
+ Without ``torch.compile`` every expert can be fused, the last group simply being
+ smaller. With it, only whole ``chunk``-sized groups are fused so the fused shape is a
+ constant the compiled quant graph can cache; the router-sized remainder is returned as
+ the tail, which :func:`_slot_weights` fuses into a single *eager* call (its shape may
+ follow the router because eager needs no shape-keyed cache). The flag tells the caller
+ whether the compiled quant function may be used for the whole groups -- it may not when
+ an explicit ``AR_MOE_CHUNK=0`` asks to fuse everything, since that group's size
+ follows the router.
+ """
+ chunk = _qdq_chunk_size(layers)
+ total = len(layers)
+ if chunk <= 0: # explicit "fuse everything": one group, sized by the routing
+ return [layers], [], not _static_shapes_required(layers[0])
+ if not _static_shapes_required(layers[0]):
+ return [layers[i : i + chunk] for i in range(0, total, chunk)], [], True
+ num_full = (total // chunk) * chunk
+ groups = [layers[i : i + chunk] for i in range(0, num_full, chunk)]
+ return groups, layers[num_full:], True
+
+
+def _slot_weights(layers: list[nn.Module], batched: bool) -> _SlotWeights:
+ biases = [_effective_bias(layer) for layer in layers]
+ if batched:
+ groups, tail, allow_compiled = _plan_qdq_groups(layers)
+ if groups or tail:
+ weights: list[torch.Tensor] = []
+ stacked = None
+ ok = True
+ for group in groups:
+ result = _batched_qdq_weights(group, allow_compiled=allow_compiled)
+ if result is None:
+ ok = False
+ break
+ if len(groups) == 1 and not tail:
+ stacked = result[0] # free 3-D operand for the native kernel
+ weights.extend(result[1])
+ if ok and tail:
+ # Fuse the router-sized remainder in a SINGLE eager qdq call. Its shape
+ # follows the routing, so it must stay off the compiled quant graph
+ # (``allow_compiled=False``), but batching it collapses up to ``chunk - 1``
+ # per-expert launches into one -- the launches torch.compile would
+ # otherwise hide inside the per-expert loop it competes with.
+ tail_result = _batched_qdq_weights(tail, allow_compiled=False) if len(tail) > 1 else None
+ if tail_result is not None:
+ weights.extend(tail_result[1])
+ else:
+ weights.extend(_effective_weight_and_bias(layer)[0] for layer in tail)
+ if ok and weights:
+ return _SlotWeights(weights=weights, biases=biases, stacked=stacked)
+ weights = [_effective_weight_and_bias(layer)[0] for layer in layers]
+ return _SlotWeights(weights=weights, biases=biases)
+
+
+def _quantize_activation(layer: nn.Module, x: torch.Tensor) -> torch.Tensor:
+ """Apply the layer's activation fake-quantization to a whole grouped batch."""
+ if not _is_wrapper_linear(layer) or not getattr(layer, "enable_act_quant", False):
+ return x
+ act_max = getattr(layer.orig_layer, "act_max", None)
+ x, _, _ = layer._qdq_act(x, act_max_scale=layer.act_max_scale, act_min_scale=layer.act_min_scale, act_max=act_max)
+ return x
+
+
+# --------------------------------------------------------------------------------------
+# Plan
+# --------------------------------------------------------------------------------------
+
+
+@dataclass
+class _GroupedPlan:
+ """Everything needed to run one grouped forward, resolved for the *active* experts."""
+
+ experts: list[nn.Module]
+ has_gate: bool
+ device: torch.device
+ output_device: torch.device
+ # Per-slot: may the fake-quantization of all active experts be fused into one call?
+ batched_qdq: dict[str, bool]
+
+
+_SLOTS = ("gate_proj", "up_proj", "down_proj")
+
+
+def _build_plan(module: nn.Module, active_ids: list[int]) -> _GroupedPlan | None:
+ """Validate the active experts and gather them, or return ``None`` to fall back."""
+ experts: list[nn.Module] = []
+ has_gate: bool | None = None
+ device: torch.device | None = None
+ output_device: torch.device | None = None
+ # Per-slot reference signatures: every active expert must agree on them.
+ quant_signatures: dict[str, object] = {}
+ layouts: dict[str, object] = {}
+ batched_qdq: dict[str, bool] = {}
+
+ for expert_id in active_ids:
+ expert = getattr(module, str(expert_id), None)
+ if expert is None:
+ _log_fallback_once("expert container missing")
+ return None
+ if not hasattr(expert, "up_proj") or not hasattr(expert, "down_proj"):
+ _log_fallback_once("expert does not expose up_proj/down_proj")
+ return None
+
+ expert_has_gate = hasattr(expert, "gate_proj")
+ if has_gate is None:
+ has_gate = expert_has_gate
+ elif has_gate != expert_has_gate:
+ _log_fallback_once("experts disagree on gate_proj")
+ return None
+
+ slots = _SLOTS if expert_has_gate else ("up_proj", "down_proj")
+ for slot in slots:
+ projection = getattr(expert, slot)
+ if not _projection_is_supported(projection):
+ _log_fallback_once(f"unsupported projection type {type(projection).__name__}")
+ return None
+
+ proj_device = _compute_device(projection)
+ if device is None:
+ device = proj_device
+ output_device = _output_device(projection)
+ elif proj_device != device:
+ _log_fallback_once("experts live on different devices")
+ return None
+
+ # Mixed-bit MoE: bail out instead of batching differently-quantized experts.
+ signature = _quant_signature(projection)
+ if slot in quant_signatures:
+ if quant_signatures[slot] != signature:
+ _log_fallback_once(f"mixed quantization schemes across experts for '{slot}'")
+ return None
+ else:
+ quant_signatures[slot] = signature
+
+ layout = _weight_layout(projection)
+ if slot in layouts:
+ if layouts[slot] != layout:
+ _log_fallback_once(f"experts have different weight shape/dtype for '{slot}'")
+ return None
+ else:
+ layouts[slot] = layout
+
+ supports_batched = _supports_batched_qdq(projection)
+ batched_qdq[slot] = batched_qdq.get(slot, True) and supports_batched
+
+ # gate_proj and up_proj consume the *same* tensor, which the grouped path
+ # activation-quantizes once, so their activation settings must be identical.
+ if expert_has_gate:
+ gate_act = _act_signature(expert.gate_proj) if _is_wrapper_linear(expert.gate_proj) else None
+ up_act = _act_signature(expert.up_proj) if _is_wrapper_linear(expert.up_proj) else None
+ gate_enabled = bool(getattr(expert.gate_proj, "enable_act_quant", False))
+ up_enabled = bool(getattr(expert.up_proj, "enable_act_quant", False))
+ if gate_enabled != up_enabled or (gate_enabled and gate_act != up_act):
+ _log_fallback_once("gate_proj/up_proj activation quantization differ")
+ return None
+
+ experts.append(expert)
+
+ if not experts or device is None or output_device is None:
+ return None
+ return _GroupedPlan(
+ experts=experts,
+ has_gate=bool(has_gate),
+ device=device,
+ output_device=output_device,
+ batched_qdq=batched_qdq,
+ )
+
+
+# --------------------------------------------------------------------------------------
+# Grouped matmul
+# --------------------------------------------------------------------------------------
+#
+# Two ways to run the routed GEMM, plus one we deliberately avoid:
+#
+# sliced loop one ``F.linear`` per *active* expert over a contiguous slice.
+# Same kernels as transformers' ``grouped_mm_fallback``, but without its
+# extra ``offs.tolist()`` sync -- we already hold the counts on the host.
+# Enable with ``AR_MOE_EXPERTS_IMPL=linear_grouped_sliced``.
+# grouped_mm (default) ``torch.nn.functional.grouped_mm`` / ``torch._grouped_mm``: one
+# kernel for all experts, driven by ``offsets``. Differentiable, and
+# bit-identical to the loop (verified on A100). Disable with
+# ``AR_MOE_EXPERTS_IMPL=linear_grouped_sliced``.
+# batched_mm transformers' ``_batched_linear``/``torch.bmm`` path gathers
+# ``weight[expert_ids]`` into an ``(S, out, in)`` tensor -- one weight copy
+# per routed token. That is a decode-time trick (S == top_k); at tuning
+# shapes it is orders of magnitude slower (measured ~87x) and the gather
+# alone would be hundreds of GB. Never used here.
+#
+# Why grouped_mm is the default: the winner depends on the number of routed (token, expert)
+# pairs, i.e. on the calibration batch. At realistic tuning sizes (batch=8, seqlen=2048 ->
+# ~131k pairs) the sliced loop issues ~num_experts separate grad GEMMs in backward, whose
+# launch pressure dominates; the single fused grouped_mm backward then wins by a wide margin
+# -- up to ~5x on a synthetic full Qwen3.5-MoE decoder layer (A100, sm80, bf16), with the
+# gap almost entirely in backward.
+#
+# The earlier, small-batch microbench below (only 4096 routed pairs, 2048x768 experts) is
+# where the two looked equal and the loop was historically preferred -- it under-represented
+# the backward launch count. Speedup over ``linear_loop`` for 16/32/64/128/256 experts:
+#
+# forward+backward grouped_mm 3.89 4.36 5.11 4.84 5.05 | sliced 4.36 4.70 5.32 5.14 5.24
+# forward (wrapped) grouped_mm 2.57 2.99 3.21 3.30 3.28 | sliced 3.13 3.44 3.69 3.80 -
+# forward (plain fp) grouped_mm 2.07 2.53 2.76 2.99 2.93 | sliced 1.90 2.21 2.29 2.42 2.39
+#
+# grouped_mm needs a ``torch.stack`` copy when the qdq was not fused (higher peak memory)
+# and has dtype/alignment/compute-capability constraints, so it transparently falls back to
+# the sliced loop when the native kernel is not usable. torch's CPU ``grouped_mm`` loses, so
+# on CPU the loop still runs.
+#
+# Deciding whether the native kernel is *legal* is fiddly (torch version, device, compute
+# capability, dynamo, 16-byte alignment on CPU), so when it is requested we defer to
+# transformers' own ``_can_use_grouped_mm`` rather than re-deriving it.
+
+try: # transformers >= 5.0
+ from transformers.integrations.moe import _can_use_grouped_mm as _transformers_can_use_grouped_mm
+except Exception: # pragma: no cover - older/absent transformers
+ _transformers_can_use_grouped_mm = None
+
+
+def _sliced_grouped_mm_requested() -> bool:
+ """Whether the sliced per-expert GEMM loop was explicitly requested.
+
+ ``AR_MOE_EXPERTS_IMPL=linear_grouped_sliced`` forces the sliced loop; every other
+ grouped setting (``auto`` / ``linear_grouped``) prefers the native ``grouped_mm`` kernel.
+ """
+ return str(envs.AR_MOE_EXPERTS_IMPL).lower() == GROUPED_LINEAR_SLICED_IMPL
+
+
+def _native_grouped_mm_available() -> bool:
+ """Cheap pre-check that does not need the stacked 3-D operand."""
+ if _NATIVE_GROUPED_MM_DISABLED or _sliced_grouped_mm_requested():
+ return False
+ return hasattr(F, "grouped_mm") or hasattr(torch, "_grouped_mm")
+
+
+def _native_grouped_mm_preferred(device: torch.device) -> bool:
+ """Whether the native kernel is opted into. On by default; see the note above."""
+ return not _sliced_grouped_mm_requested()
+
+
+def _native_grouped_mm_usable(x: torch.Tensor, weight: torch.Tensor, offsets: torch.Tensor) -> bool:
+ """Whether ``grouped_mm`` can and should run this batch. ``weight`` is ``(E, in, out)``."""
+ if not _native_grouped_mm_available():
+ return False
+ if _transformers_can_use_grouped_mm is not None:
+ return _transformers_can_use_grouped_mm(x, weight, offsets)
+ # Backstop mirroring the parts of transformers' rules we can check on our own.
+ if weight.device.type == "cuda":
+ try:
+ return torch.cuda.get_device_capability(weight.device) >= (8, 0)
+ except Exception: # pragma: no cover - defensive
+ return False
+ return True
+
+
+def _native_grouped_mm(x: torch.Tensor, weight: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:
+ """``(S, in) @ grouped (E, in, out)`` -> ``(S, out)``."""
+ x = x.to(weight.dtype) # grouped_mm is not autocast-aware
+ if hasattr(F, "grouped_mm"):
+ return F.grouped_mm(x, weight, offs=offsets)
+ return torch._grouped_mm(x, weight, offs=offsets)
+
+
+def _sliced_linear(x: torch.Tensor, slot: _SlotWeights, counts: list[int]) -> torch.Tensor:
+ """Per-expert ``F.linear`` over contiguous slices — no gather, no sync, no 3D copy."""
+ outputs = []
+ start = 0
+ for weight, bias, count in zip(slot.weights, slot.biases, counts):
+ end = start + count
+ outputs.append(F.linear(x[start:end], weight, bias)) # pylint: disable=not-callable
+ start = end
+ return torch.cat(outputs, dim=0)
+
+
+def _stack_weights(slot: _SlotWeights) -> torch.Tensor:
+ """``(E, out, in)`` operand for the native kernel, as a view when the qdq was fused."""
+ if slot.stacked is not None:
+ return slot.stacked
+ return torch.stack(slot.weights, dim=0)
+
+
+def _stack_weights_range(slot: _SlotWeights, start: int, stop: int) -> torch.Tensor:
+ """``(E', out, in)`` operand for a slice of experts, as a view when the qdq was fused."""
+ if slot.stacked is not None:
+ return slot.stacked[start:stop]
+ return torch.stack(slot.weights[start:stop], dim=0)
+
+
+def _add_grouped_bias(out: torch.Tensor, slot: _SlotWeights, counts: list[int]) -> torch.Tensor:
+ """Add per-expert bias to a grouped output whose rows are in sorted-expert order."""
+ if slot.biases[0] is None:
+ return out
+ device = out.device
+ row_expert = torch.repeat_interleave(
+ torch.arange(len(counts), device=device),
+ torch.tensor(counts, device=device),
+ )
+ return out + torch.stack(slot.biases, dim=0)[row_expert]
+
+
+def _gemm_expert_chunk(num_experts: int, weight: torch.Tensor) -> int:
+ """Experts per native grouped_mm tile. ``num_experts`` (the full count) disables tiling.
+
+ Follows the single ``AR_MOE_CHUNK`` knob (same value as the qdq fusion), so a tile is
+ exactly one qdq chunk: the ``torch.stack`` ``(E, out, in)`` operand the native kernel needs
+ is bounded to ``chunk`` experts. ``auto`` derives the count from the working-set budget;
+ a fixed int is used as-is; ``0``/negative means "fuse everything" -> no tiling. Tiling only
+ actually runs when the qdq produced no free stacked view (see ``_grouped_linear``).
+ """
+ setting = envs.AR_MOE_CHUNK
+ if setting in ("", "auto"):
+ per_expert = int(weight.shape[0]) * int(weight.shape[1]) * weight.element_size()
+ if per_expert <= 0:
+ return num_experts
+ return max(_DEFAULT_QDQ_CHUNK, min(num_experts, int(_QDQ_FUSED_WORKINGSET_BYTES // per_expert)))
+ try:
+ chunk = int(setting)
+ except ValueError:
+ return num_experts
+ return num_experts if chunk <= 0 else min(chunk, num_experts)
+
+
+def _grouped_mm_tiled(x: torch.Tensor, slot: _SlotWeights, counts: list[int], chunk: int) -> torch.Tensor | None:
+ """Native grouped_mm tiled over experts, bounding the stacked weight to ``chunk`` experts.
+
+ ``x`` is sorted so each expert owns a contiguous row slice; a tile of ``chunk`` experts
+ owns the concatenation of their slices. Returns ``None`` (fall back to the sliced loop)
+ if any tile is not eligible for the native kernel. Bias is added by the caller.
+ """
+ num_experts = len(slot.weights)
+ outputs = []
+ row = 0
+ for start in range(0, num_experts, chunk):
+ stop = min(start + chunk, num_experts)
+ tile_counts = counts[start:stop]
+ rows = sum(tile_counts)
+ x_tile = x[row : row + rows]
+ row += rows
+ weight = _stack_weights_range(slot, start, stop).transpose(-2, -1) # (E', in, out)
+ sub_offsets = torch.tensor(tile_counts, device=x.device, dtype=torch.int32).cumsum(0).to(torch.int32)
+ if not _native_grouped_mm_usable(x_tile, weight, sub_offsets):
+ return None
+ outputs.append(_native_grouped_mm(x_tile, weight, sub_offsets))
+ return torch.cat(outputs, dim=0)
+
+
+def _grouped_linear(
+ x: torch.Tensor,
+ slot: _SlotWeights,
+ counts: list[int],
+ offsets: torch.Tensor,
+) -> torch.Tensor:
+ """Run one projection for all active experts at once."""
+ global _NATIVE_GROUPED_MM_DISABLED
+
+ if len(slot.weights) == 1:
+ # Single active expert: a plain GEMM beats every grouped path.
+ return F.linear(x, slot.weights[0], slot.biases[0]) # pylint: disable=not-callable
+
+ if _native_grouped_mm_available():
+ num_experts = len(slot.weights)
+ # Tile only when the qdq did not hand us a free stacked view: that is exactly the
+ # case where feeding all experts costs a full torch.stack copy.
+ chunk = num_experts if slot.stacked is not None else _gemm_expert_chunk(num_experts, slot.weights[0])
+ try:
+ if chunk >= num_experts:
+ weight = _stack_weights(slot).transpose(-2, -1) # (E, in, out)
+ if _native_grouped_mm_usable(x, weight, offsets):
+ out = _native_grouped_mm(x, weight, offsets)
+ return _add_grouped_bias(out, slot, counts)
+ else:
+ out = _grouped_mm_tiled(x, slot, counts, chunk)
+ if out is not None:
+ return _add_grouped_bias(out, slot, counts)
+ except Exception as err: # pragma: no cover - kernel/shape constraints vary
+ _NATIVE_GROUPED_MM_DISABLED = True
+ logger.warning_once(
+ f"torch grouped_mm failed ({err}); using the sliced per-expert GEMM loop for MoE tuning."
+ )
+
+ return _sliced_linear(x, slot, counts)
+
+
+# --------------------------------------------------------------------------------------
+# Forward
+# --------------------------------------------------------------------------------------
+
+
+def _run_routes(
+ module: nn.Module,
+ hidden_states: torch.Tensor,
+ route_indices: torch.Tensor,
+ route_weights: torch.Tensor,
+ num_experts: int,
+) -> torch.Tensor | None:
+ """Grouped expert forward for one routing table, or ``None`` if unsupported."""
+ device = hidden_states.device
+ num_tokens, hidden_dim = hidden_states.shape
+ num_top_k = route_indices.size(-1)
+
+ expert_ids = route_indices.reshape(-1) # (S,)
+ sample_weights = route_weights.reshape(-1).to(hidden_states.dtype) # (S,)
+ num_pairs = expert_ids.numel()
+
+ # Sort the token/expert pairs so each expert owns one contiguous slice.
+ expert_ids_sorted, perm = torch.sort(expert_ids)
+
+ # The only host<->device sync of the whole layer.
+ unique_ids, unique_counts = torch.unique_consecutive(expert_ids_sorted, return_counts=True)
+ active_ids = unique_ids.tolist()
+ active_counts = unique_counts.tolist()
+
+ # Expert-parallel sentinels (id >= num_experts) sort to the tail; drop them.
+ keep = [i for i, expert_id in enumerate(active_ids) if 0 <= expert_id < num_experts]
+ active_ids = [active_ids[i] for i in keep]
+ active_counts = [active_counts[i] for i in keep]
+ num_valid = sum(active_counts)
+ if num_valid == 0:
+ return torch.zeros_like(hidden_states)
+
+ plan = _build_plan(module, active_ids)
+ if plan is None:
+ return None
+
+ perm_valid = perm[:num_valid]
+ token_idx = torch.div(perm_valid, num_top_k, rounding_mode="floor")
+ x = hidden_states.index_select(0, token_idx).to(plan.device)
+
+ offsets = torch.tensor(active_counts, device=plan.device, dtype=torch.int32).cumsum(0).to(torch.int32)
+
+ # --- input projections (gate / up) -------------------------------------------------
+ x = _quantize_activation(plan.experts[0].up_proj, x)
+
+ up = _slot_weights([e.up_proj for e in plan.experts], plan.batched_qdq.get("up_proj", False))
+ up_out = _grouped_linear(x, up, active_counts, offsets)
+
+ if plan.has_gate:
+ gate = _slot_weights([e.gate_proj for e in plan.experts], plan.batched_qdq.get("gate_proj", False))
+ gate_out = _grouped_linear(x, gate, active_counts, offsets)
+ if hasattr(module, "_apply_gate"):
+ # Keep the module's own gating (clamping, alpha, ...) and its [gate; up] layout,
+ # exactly as linear_loop_experts_forward does.
+ hidden = module._apply_gate(torch.cat([gate_out, up_out], dim=-1))
+ else:
+ hidden = module.act_fn(gate_out) * up_out
+ else:
+ hidden = module.act_fn(up_out)
+
+ # --- down projection ---------------------------------------------------------------
+ hidden = _quantize_activation(plan.experts[0].down_proj, hidden)
+ down = _slot_weights([e.down_proj for e in plan.experts], plan.batched_qdq.get("down_proj", False))
+ out = _grouped_linear(hidden, down, active_counts, offsets)
+
+ out = out.to(plan.output_device)
+ # ``sample_weights``/``perm_valid`` live on the input device, which can differ from the
+ # experts' device in multi-GPU tuning (a whole layer's experts co-located on one card
+ # while the block input flows on another). Align to ``out`` before the multiply.
+ sample_weights_out = sample_weights.index_select(0, perm_valid).to(device=out.device, dtype=out.dtype)
+ out = out * sample_weights_out.unsqueeze(-1)
+
+ # Scatter back to the original (token, top_k) order and reduce over top_k.
+ out_per_sample = torch.zeros(num_pairs, hidden_dim, device=out.device, dtype=out.dtype)
+ out_per_sample = out_per_sample.index_copy(0, perm_valid.to(out.device), out)
+ return out_per_sample.view(num_tokens, num_top_k, hidden_dim).sum(dim=1).to(device)
+
+
+def _opaque_to_dynamo(fn):
+ """Stop ``torch.compile`` from tracing into this function.
+
+ ``block_runner`` compiles the whole block forward, and the experts forward below is
+ deliberately full of *Python-level* data-dependent control flow: the routed expert ids
+ come back through ``.tolist()``, the number of loop iterations and fused groups follows
+ them, and experts are looked up by name. Dynamo would retrace on every distinct routing
+ -- i.e. on every calibration sample -- which is exactly the "fused MoE with
+ shape-dependent control flow" case that already forces compile off for the DeepSeek and
+ GLM-5 families (see ``special_model_handler``).
+
+ ``linear_loop_experts_forward`` does not need this because its control flow is static
+ (``for expert_idx in range(num_experts)``); only the tensor values inside vary.
+
+ Making just this call opaque keeps the rest of the block compiled, and the quantization
+ functions it calls are compiled in their own right, so nothing of value is lost.
+ """
+ disable = getattr(torch.compiler, "disable", None)
+ if disable is None: # pragma: no cover - torch < 2.1
+ dynamo = getattr(torch, "_dynamo", None)
+ disable = getattr(dynamo, "disable", None) if dynamo is not None else None
+ return disable(fn) if disable is not None else fn
+
+
+# Config attributes various architectures store the expert count under. transformers' own
+# experts forwards (``grouped_mm_experts_forward`` / ``batched_mm_experts_forward``) read
+# ``self.num_experts`` directly, and every ``@use_experts_implementation`` module sets it in
+# ``__init__``; AutoRound's unfuse sets it too. These config keys are the ones those
+# ``__init__`` methods derive ``num_experts`` from (e.g. DeepSeek ``n_routed_experts``,
+# Mixtral ``num_local_experts``), used only as a fallback so a module that leaves the
+# attribute unset still resolves instead of silently dropping to the per-expert loop.
+_NUM_EXPERTS_CONFIG_KEYS = ("num_experts", "num_local_experts", "n_routed_experts")
+
+
+def _resolve_num_experts(module: nn.Module) -> int | None:
+ """Resolve the expert count, matching transformers' ``self.num_experts`` convention.
+
+ top_k is deliberately *not* resolved this way: transformers reads it per-call from
+ ``top_k_index.size(-1)`` rather than from an attribute, which is what the forward below
+ already does, so it stays correct even for models that never store a ``top_k`` field.
+ """
+ num_experts = getattr(module, "num_experts", None)
+ if isinstance(num_experts, int) and num_experts > 0:
+ return num_experts
+ config = getattr(module, "config", None)
+ if config is not None:
+ for key in _NUM_EXPERTS_CONFIG_KEYS:
+ value = getattr(config, key, None)
+ if isinstance(value, int) and value > 0:
+ return value
+ return None
+
+
+@_opaque_to_dynamo
+def grouped_linear_experts_forward(
+ self: nn.Module,
+ hidden_states: torch.Tensor,
+ top_k_index: torch.Tensor,
+ top_k_weights: torch.Tensor,
+) -> torch.Tensor:
+ """Experts forward that batches the routed token/expert pairs into grouped GEMMs.
+
+ Drop-in replacement for :func:`linear_loop_experts_forward` with the same module
+ layout (numbered ``_ExpertContainer`` children holding ``gate_proj``/``up_proj``/
+ ``down_proj``). Falls back to the loop implementation whenever the layer does not
+ satisfy the grouped path's requirements.
+
+ Args:
+ self: The experts module.
+ hidden_states: ``(num_tokens, hidden_dim)`` or ``(bs, seq_len, hidden_dim)``.
+ top_k_index: Selected expert indices, ``(..., top_k)``.
+ top_k_weights: Routing weights, ``(..., top_k)``.
+
+ Returns:
+ Output tensor with the same shape as ``hidden_states``.
+ """
+ from auto_round.modeling.fused_moe.moe_experts_interface import linear_loop_experts_forward
+
+ num_experts = _resolve_num_experts(self)
+ if num_experts is None:
+ _log_fallback_once("num_experts is unavailable")
+ return linear_loop_experts_forward(self, hidden_states, top_k_index, top_k_weights)
+
+ if hidden_states.dim() == 3:
+ batch_size, seq_len, hidden_dim = hidden_states.shape
+ flat_hidden_states = hidden_states.reshape(-1, hidden_dim)
+ flat_index = top_k_index.reshape(-1, top_k_index.size(-1))
+ flat_weights = top_k_weights.reshape(-1, top_k_weights.size(-1))
+ else:
+ batch_size, seq_len = None, None
+ hidden_dim = hidden_states.size(-1)
+ flat_hidden_states = hidden_states
+ flat_index = top_k_index
+ flat_weights = top_k_weights
+
+ final_hidden_states = _run_routes(self, flat_hidden_states, flat_index, flat_weights, num_experts)
+ if final_hidden_states is None:
+ return linear_loop_experts_forward(self, hidden_states, top_k_index, top_k_weights)
+
+ # Auxiliary coverage path: rotate the routing so every expert sees tokens (and its
+ # hooks/statistics fire), discarding the output so model semantics stay untouched.
+ if force_all_experts_routing_enabled():
+ forced_indices, forced_weights = build_forced_routing(
+ module=self,
+ routing_scores=None,
+ top_k=flat_index.size(-1),
+ num_experts=num_experts,
+ dtype=flat_hidden_states.dtype,
+ num_tokens=flat_hidden_states.size(0),
+ device=flat_hidden_states.device,
+ normalize=True,
+ )
+ with torch.no_grad():
+ _ = _run_routes(self, flat_hidden_states, forced_indices, forced_weights, num_experts)
+
+ if batch_size is not None:
+ final_hidden_states = final_hidden_states.view(batch_size, seq_len, hidden_dim)
+ return final_hidden_states
diff --git a/auto_round/modeling/fused_moe/llama4.py b/auto_round/modeling/fused_moe/llama4.py
index c6b2f0591..07c5500be 100644
--- a/auto_round/modeling/fused_moe/llama4.py
+++ b/auto_round/modeling/fused_moe/llama4.py
@@ -25,7 +25,7 @@ from transformers.models.llama4.modeling_llama4 import Llama4Config, Llama4TextM
from auto_round.modeling.fused_moe.fusion_spec import build_standard_moe_fusion_spec, register_moe_fusion_spec
from auto_round.modeling.fused_moe.replace_modules import ReplacementModuleBase
-from auto_round.modeling.fused_moe.utils import _update_parameter
+from auto_round.modeling.fused_moe.utils import _update_parameter, grouped_or_sequential_moe_forward
from auto_round.utils import clear_memory, unsupported_meta_device
@@ -34,6 +34,10 @@ class SequentialLlama4TextExperts(torch.nn.ModuleList):
self.num_experts = original.gate_up_proj.shape[0]
with no_init_weights(), torch.device("meta"):
super().__init__([Llama4TextMLP(config) for _ in range(self.num_experts)])
+ # Container-level activation so the grouped experts forward can apply gating.
+ # Store via ``object.__setattr__`` so a Module activation is NOT registered as a child
+ # of this ``ModuleList`` (it would otherwise appear as an extra expert in iteration/len).
+ object.__setattr__(self, "act_fn", getattr(self[0], "act_fn", None) or getattr(self[0], "activation_fn", None))
register_moe_fusion_spec(
self,
build_standard_moe_fusion_spec(
@@ -96,13 +100,15 @@ class SequentialLlama4TextMoe(ReplacementModuleBase):
out = self.shared_expert(hidden_states)
- # Only process experts that actually received tokens (expert_hit pattern),
- # skipping experts with zero routing weight to save compute during calibration.
- with torch.no_grad():
- expert_hit = torch.greater(router_scores.sum(dim=-1), 0).nonzero()
- for expert_idx in expert_hit:
- expert_idx = expert_idx[0]
- out += self.experts[expert_idx](hidden_states) * router_scores[expert_idx].reshape(-1, 1)
+ # ``router_scores`` is (num_experts, num_tokens), top-k-sparse (non-routed entries are
+ # 0). Recover the gathered (token, top_k) routing the grouped experts forward expects:
+ # topk over the expert axis returns exactly the routed experts and their weights, so
+ # ``sum_k weight * expert(x)`` reproduces the old ``sum_{hit e} score[e] * expert(x)``.
+ scores_te = router_scores.transpose(0, 1) # (num_tokens, num_experts)
+ top_k_weights, top_k_index = scores_te.topk(self.top_k, dim=-1)
+ out = out + grouped_or_sequential_moe_forward(
+ hidden_states, top_k_index, top_k_weights, self.experts, self.num_experts
+ )
return out, router_logits
diff --git a/auto_round/modeling/fused_moe/moe_experts_interface.py b/auto_round/modeling/fused_moe/moe_experts_interface.py
index 7d2dd065e..2a9bc7f1c 100644
--- a/auto_round/modeling/fused_moe/moe_experts_interface.py
+++ b/auto_round/modeling/fused_moe/moe_experts_interface.py
@@ -34,7 +34,13 @@ Usage:
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
@@ -50,6 +56,39 @@ except ImportError:
# 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}
@@ -287,7 +326,10 @@ def linear_loop_experts_forward(
def register_linear_loop_experts() -> bool:
- """Register the linear_loop experts implementation with transformers.
+ """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.
@@ -300,9 +342,11 @@ def register_linear_loop_experts() -> bool:
)
return False
- if LINEAR_LOOP_IMPL not in ALL_EXPERTS_FUNCTIONS._global_mapping:
- ALL_EXPERTS_FUNCTIONS._global_mapping[LINEAR_LOOP_IMPL] = linear_loop_experts_forward
- logger.debug(f"Registered '{LINEAR_LOOP_IMPL}' experts implementation")
+ 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
@@ -700,13 +744,13 @@ def _unfuse_experts_weights_inplace(
def prepare_model_for_moe_quantization(
model: nn.Module,
- implementation: str = LINEAR_LOOP_IMPL,
+ 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 the linear_loop experts implementation with transformers
+ 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
@@ -715,7 +759,8 @@ def prepare_model_for_moe_quantization(
Args:
model: The model to prepare
- implementation: The experts implementation to use (default: "linear_loop")
+ 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.
@@ -729,6 +774,9 @@ def prepare_model_for_moe_quantization(
"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():
@@ -745,10 +793,13 @@ def prepare_model_for_moe_quantization(
logger.info(f"[MoE Prep] Unfused {len(unfused_modules)} MOE experts modules")
clear_memory()
- # Set config for linear_loop forward
+ # 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 or implementation
+ 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}'")
@@ -763,6 +814,22 @@ def is_linear_loop_available() -> bool:
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.
diff --git a/auto_round/modeling/fused_moe/qwen3_5_moe.py b/auto_round/modeling/fused_moe/qwen3_5_moe.py
index e96c3224e..f5a18fc09 100644
--- a/auto_round/modeling/fused_moe/qwen3_5_moe.py
+++ b/auto_round/modeling/fused_moe/qwen3_5_moe.py
@@ -12,7 +12,7 @@ from auto_round.modeling.fused_moe.utils import (
_update_parameter,
build_forced_routing,
force_all_experts_routing_enabled,
- sequential_moe_forward,
+ grouped_or_sequential_moe_forward,
)
from auto_round.utils import clear_memory, unsupported_meta_device
@@ -42,7 +42,9 @@ class LinearQwen3_5MoeSparseMoeBlock(ReplacementModuleBase):
clear_memory()
def experts_forward(self, hidden_states, top_k_index, top_k_weights):
- return sequential_moe_forward(hidden_states, top_k_index, top_k_weights, self.experts, self.num_experts)
+ return grouped_or_sequential_moe_forward(
+ hidden_states, top_k_index, top_k_weights, self.experts, self.num_experts
+ )
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
batch_size, sequence_length, hidden_dim = hidden_states.shape
@@ -88,6 +90,14 @@ class SequentialQwen3_5MoeExperts(torch.nn.ModuleList):
with torch.device("meta"):
super().__init__([Qwen3_5MoeMLP(config, intermediate_size) for _ in range(self.num_experts)])
+ # The grouped experts forward applies gating at the container level, so it needs the
+ # activation here (all experts share the same stateless act_fn). Referencing the first
+ # expert's keeps it consistent with the per-expert MLPs.
+ # Store via ``object.__setattr__`` so the activation is NOT registered as a child module
+ # of this ``ModuleList``; otherwise it would appear as an extra expert (e.g. index 256)
+ # in iteration/len, breaking per-expert traversal, materialization and export.
+ object.__setattr__(self, "act_fn", self[0].act_fn)
+
register_moe_fusion_spec(
self,
build_standard_moe_fusion_spec(
diff --git a/auto_round/modeling/fused_moe/qwen3_omni.py b/auto_round/modeling/fused_moe/qwen3_omni.py
index 369e80a75..c8469ad32 100644
--- a/auto_round/modeling/fused_moe/qwen3_omni.py
+++ b/auto_round/modeling/fused_moe/qwen3_omni.py
@@ -13,7 +13,7 @@ import torch
from auto_round.modeling.fused_moe.fusion_spec import build_standard_moe_fusion_spec, register_moe_fusion_spec
from auto_round.modeling.fused_moe.replace_modules import ReplacementModuleBase
-from auto_round.modeling.fused_moe.utils import _update_parameter, sequential_moe_forward
+from auto_round.modeling.fused_moe.utils import _update_parameter, grouped_or_sequential_moe_forward
from auto_round.utils import clear_memory, unsupported_meta_device
# ---------------------------------------------------------------------------
@@ -50,7 +50,9 @@ class LinearQwen3OmniThinkerSparseMoeBlock(ReplacementModuleBase):
clear_memory()
def experts_forward(self, hidden_states, top_k_index, top_k_weights):
- return sequential_moe_forward(hidden_states, top_k_index, top_k_weights, self.experts, self.num_experts)
+ return grouped_or_sequential_moe_forward(
+ hidden_states, top_k_index, top_k_weights, self.experts, self.num_experts
+ )
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
batch_size, sequence_length, hidden_dim = hidden_states.shape
@@ -88,6 +90,10 @@ class SequentialQwen3OmniThinkerExperts(torch.nn.ModuleList):
with torch.device("meta"):
super().__init__([Qwen3OmniMoeThinkerTextMLP(config, intermediate_size) for _ in range(self.num_experts)])
+ # Container-level activation so the grouped experts forward can apply gating.
+ # Store via ``object.__setattr__`` so the activation is NOT registered as a child module
+ # of this ``ModuleList``; otherwise it would appear as an extra expert in iteration/len.
+ object.__setattr__(self, "act_fn", self[0].act_fn)
register_moe_fusion_spec(
self,
build_standard_moe_fusion_spec(
diff --git a/auto_round/modeling/fused_moe/qwen3_vl_moe.py b/auto_round/modeling/fused_moe/qwen3_vl_moe.py
index f1ddeedce..eb76cfc34 100644
--- a/auto_round/modeling/fused_moe/qwen3_vl_moe.py
+++ b/auto_round/modeling/fused_moe/qwen3_vl_moe.py
@@ -23,7 +23,7 @@ from auto_round.utils import clear_memory, unsupported_meta_device
transformers_version = version.parse(transformers.__version__)
from typing import TYPE_CHECKING
-from auto_round.modeling.fused_moe.utils import _update_parameter, sequential_moe_forward
+from auto_round.modeling.fused_moe.utils import _update_parameter, grouped_or_sequential_moe_forward
if TYPE_CHECKING:
from transformers import Qwen3VLMoeConfig, Qwen3VLMoeTextConfig
@@ -105,7 +105,7 @@ class LinearQwen3VLMoeTextSparseMoeBlock(ReplacementModuleBase):
weighted_output = expert_out * routing_weights[token_idx, idx, None]
next_states.index_add_(0, token_idx, weighted_output.to(hidden_states.dtype))
else:
- next_states = sequential_moe_forward(
+ next_states = grouped_or_sequential_moe_forward(
hidden_states, router_indices, routing_weights, self.experts, self.num_experts
)
next_states = next_states.reshape(batch_size, sequence_length, hidden_dim)
@@ -144,6 +144,10 @@ class SequentialQwen3VLMoeTextExperts(torch.nn.ModuleList):
with torch.device("meta"):
super().__init__([Qwen3VLMoeTextMLP(config, intermediate_size) for _ in range(self.num_experts)])
+ # Container-level activation so the grouped experts forward can apply gating.
+ # Store via ``object.__setattr__`` so the activation is NOT registered as a child module
+ # of this ``ModuleList``; otherwise it would appear as an extra expert in iteration/len.
+ object.__setattr__(self, "act_fn", self[0].act_fn)
register_moe_fusion_spec(
self,
build_standard_moe_fusion_spec(
diff --git a/auto_round/modeling/fused_moe/step3_5_moe.py b/auto_round/modeling/fused_moe/step3_5_moe.py
index ae6a47741..53cbf620a 100755
--- a/auto_round/modeling/fused_moe/step3_5_moe.py
+++ b/auto_round/modeling/fused_moe/step3_5_moe.py
@@ -21,7 +21,7 @@ from transformers.activations import ACT2FN
from auto_round.modeling.fused_moe.fusion_spec import build_standard_moe_fusion_spec, register_moe_fusion_spec
from auto_round.modeling.fused_moe.replace_modules import ReplacementModuleBase
-from auto_round.modeling.fused_moe.utils import _update_parameter, sequential_moe_forward
+from auto_round.modeling.fused_moe.utils import _update_parameter, grouped_or_sequential_moe_forward
from auto_round.utils import clear_memory, unsupported_meta_device
@@ -57,6 +57,13 @@ class SequentialStep3p5MoeExperts(torch.nn.ModuleList):
with torch.device("meta"):
super().__init__([Step3p5ExpertMLP(hidden_size, intermediate_size, limit) for _ in range(self.num_experts)])
+ # Container-level activation + limit so the grouped experts forward can reproduce the
+ # per-expert gating (silu + the optional gate/up clamp) via ``_apply_gate`` below.
+ # Store ``act_fn`` via ``object.__setattr__`` so it is NOT registered as a child module
+ # of this ``ModuleList``; otherwise iterating ``experts`` would also yield the activation
+ # module (breaking per-expert iteration / materialization).
+ object.__setattr__(self, "act_fn", self[0].act_fn)
+ self.limit = limit
register_moe_fusion_spec(
self,
build_standard_moe_fusion_spec(
@@ -88,6 +95,20 @@ class SequentialStep3p5MoeExperts(torch.nn.ModuleList):
original.down_proj.to_empty(device="meta")
clear_memory()
+ def _apply_gate(self, gate_up_out: torch.Tensor) -> torch.Tensor:
+ """Grouped-path gating that matches ``Step3p5ExpertMLP.forward``'s optional clamp.
+
+ The grouped experts forward concatenates ``[gate_out, up_out]`` and defers gating to
+ this hook, so the ``limit`` clamp (absent from the generic ``act_fn(gate) * up``) is
+ preserved -- keeping the grouped result numerically identical to the per-expert loop.
+ """
+ gate, up = gate_up_out.chunk(2, dim=-1)
+ gate = self.act_fn(gate)
+ if self.limit is not None:
+ gate = gate.clamp(max=self.limit)
+ up = up.clamp(min=-self.limit, max=self.limit)
+ return gate * up
+
class LinearStep3p5MoEMLP(ReplacementModuleBase):
"""Replacement for Step3p5MoEMLP that splits fused MoELinear into
@@ -157,7 +178,7 @@ class LinearStep3p5MoEMLP(ReplacementModuleBase):
routing_weights = routing_weights * self.routed_scaling_factor
- final_hidden_states = sequential_moe_forward(
+ final_hidden_states = grouped_or_sequential_moe_forward(
hidden_states, selected_experts, routing_weights, self.experts, self.num_experts
)
final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
diff --git a/auto_round/modeling/fused_moe/utils.py b/auto_round/modeling/fused_moe/utils.py
index d8b4f5c1f..cfc53da8b 100644
--- a/auto_round/modeling/fused_moe/utils.py
+++ b/auto_round/modeling/fused_moe/utils.py
@@ -102,6 +102,49 @@ def sequential_moe_forward(
return final_hidden_states
+def grouped_or_sequential_moe_forward(
+ hidden_states: torch.Tensor,
+ top_k_index: torch.Tensor,
+ top_k_weights: torch.Tensor,
+ experts,
+ num_experts: int,
+) -> torch.Tensor:
+ """Fast grouped-GEMM MoE forward on CUDA, single-sort sequential loop everywhere else.
+
+ Custom fused-MoE replacements (Qwen3.5, etc.) split the fused 3D experts into a
+ ``ModuleList`` of per-expert ``gate_proj``/``up_proj``/``down_proj`` linears -- exactly
+ the layout :func:`grouped_linear_experts_forward` consumes. Routing through it batches
+ the routed token/expert pairs into sorted grouped GEMMs (one launch for all experts,
+ with batched fake-quant), which is markedly faster for tuning fwd+bwd on many-expert
+ MoEs than the per-expert loop; it self-checks the layer and falls back to the loop when
+ a layer is ineligible.
+
+ Only taken on CUDA: the grouped/loop paths issue the per-expert gather kernels that
+ trigger a driver-level bug on some XPU builds, which :func:`sequential_moe_forward`
+ (a single sort, no per-expert gather) is written to avoid. It also requires the experts
+ container to expose ``act_fn`` / ``_apply_gate`` (the grouped path applies gating at the
+ container level), so containers without one keep the sequential path.
+
+ Gated by ``AR_MOE_EXPERTS_IMPL``: setting it to ``linear_loop`` forces the sequential
+ path even on CUDA; ``auto`` / ``linear_grouped`` / ``linear_grouped_sliced`` take grouped.
+ """
+ from auto_round.modeling.fused_moe.moe_experts_interface import (
+ LINEAR_LOOP_IMPL,
+ resolve_experts_implementation,
+ )
+
+ use_grouped = (
+ hidden_states.device.type == "cuda"
+ and (hasattr(experts, "act_fn") or hasattr(experts, "_apply_gate"))
+ and resolve_experts_implementation() != LINEAR_LOOP_IMPL
+ )
+ if use_grouped:
+ from auto_round.modeling.fused_moe.grouped_experts import grouped_linear_experts_forward
+
+ return grouped_linear_experts_forward(experts, hidden_states, top_k_index, top_k_weights)
+ return sequential_moe_forward(hidden_states, top_k_index, top_k_weights, experts, num_experts)
+
+
def get_num_experts(original: torch.nn.Module) -> int:
"""Get the number of experts from either fused or linearized layout."""
if is_fused_layout(original):
diff --git a/auto_round/utils/device.py b/auto_round/utils/device.py
index 7a7f5cfa5..fda2e7cf0 100644
--- a/auto_round/utils/device.py
+++ b/auto_round/utils/device.py
@@ -635,6 +635,92 @@ def set_non_auto_device_map(
logger.warning(f"{key} in `device_map` dose not match any modules, please have a check")
+def _resolve_moe_chunk() -> int:
+ """The configured experts-per-chunk (``AR_MOE_CHUNK``), for device co-allocation.
+
+ ``auto`` / invalid -> the default fixed chunk (16); ``<=0`` means "whole container"
+ (fuse everything -> a container is only ever placed as a single device-local unit).
+ """
+ from auto_round import envs
+
+ try:
+ return int(str(envs.AR_MOE_CHUNK))
+ except (TypeError, ValueError):
+ return 16
+
+
+def _preassign_moe_experts(
+ layer_memory_dict: dict, device_memory: dict, gpu_devices: list, mem_per_param: float
+) -> dict:
+ """Place a MoE experts container's experts chunk-locally so the grouped path stays on.
+
+ The grouped experts forward only needs the experts *of one fused chunk* to sit on the same
+ device (else that chunk falls back to the slow per-expert loop, which also churns
+ ``torch.compile`` recompiles). This pre-pass keeps each ``AR_MOE_CHUNK``-aligned group whole
+ on one device while spreading the groups across cards, so memory stays balanced across GPUs
+ instead of piling a whole (potentially hundreds of experts) container onto a single card.
+
+ * Per chunk -- place each ``AR_MOE_CHUNK``-aligned expert group whole on the device with
+ the most free memory that fits it, so grouped GEMM stays single-device within a chunk.
+ * Overflow -- groups that do not fit on any device are left unassigned here and fall
+ through to the general load balancer (grouped will loop-fallback for those layers).
+
+ Relies on the per-card memory budgets (``device_memory``) being set correctly by the caller
+ (symmetric transient reservation); otherwise best-fit repeatedly picks the same card and
+ piles experts there. Only placement is affected -- correctness is unchanged (the forward's
+ device checks and AlignDevicesHook handle whatever layout results). ``device_memory`` is
+ decremented in place for the layers this function assigns.
+
+ Returns a ``{layer_name: device}`` map for the experts it placed.
+ """
+ # Group expert projections by their container -> {expert_idx: [(name, mem_info), ...]}.
+ containers: dict[str, dict[int, list]] = {}
+ for name, info in layer_memory_dict.items():
+ if not info.get("is_moe_expert"):
+ continue
+ head, _, _slot = name.rpartition(".") # ".../<container>.<idx>.<slot>"
+ container, _, idx_str = head.rpartition(".")
+ try:
+ idx = int(idx_str)
+ except ValueError:
+ continue # unexpected naming; leave it to the general balancer
+ containers.setdefault(container, {}).setdefault(idx, []).append((name, info))
+
+ assigned: dict[str, str] = {}
+ if not containers:
+ return assigned
+
+ def mem_of(items) -> float:
+ return sum(mem_info["param_memory"] * mem_per_param for _, mem_info in items)
+
+ def best_fit(required: float):
+ candidates = [d for d in gpu_devices if device_memory[d] >= required]
+ return max(candidates, key=lambda d: device_memory[d]) if candidates else None
+
+ def place(items, device) -> None:
+ for layer_name, _ in items:
+ assigned[layer_name] = device
+
+ chunk = _resolve_moe_chunk()
+ for container, by_idx in containers.items():
+ idxs = sorted(by_idx)
+
+ # Spread chunk-aligned groups across cards: each group stays whole on one device (so a
+ # chunk's grouped GEMM is single-device) but different groups balance across GPUs.
+ # ``chunk <= 0`` ("fuse everything") keeps the whole container as one group.
+ step = len(idxs) if chunk <= 0 else chunk
+ for start in range(0, len(idxs), step):
+ group_items = [item for i in idxs[start : start + step] for item in by_idx[i]]
+ group_mem = mem_of(group_items)
+ group_device = best_fit(group_mem)
+ if group_device is None:
+ continue # Overflow: leave for the general balancer
+ place(group_items, group_device)
+ device_memory[group_device] -= group_mem
+
+ return assigned
+
+
def _allocate_layers_to_devices(
layer_memory_dict: dict, device_memory: dict, gpu_devices: list, mem_per_param: float
) -> tuple[dict, list]:
@@ -642,7 +728,10 @@ def _allocate_layers_to_devices(
Allocates layers to devices using a load-balancing strategy.
Strategy:
- 1. Sort layers by memory size (descending), preserve order for equal sizes
+ 0. MoE pre-pass: keep each ``AR_MOE_CHUNK``-aligned expert group whole on one device while
+ spreading the groups across cards, so a chunk's grouped GEMM stays single-device without
+ piling a whole experts container onto one card.
+ 1. Sort remaining layers by memory size (descending), preserve order for equal sizes
2. Assign largest N layers to higher-index devices (N = num_devices)
3. Remaining layers use memory availability + layer continuity scorings
@@ -654,32 +743,23 @@ def _allocate_layers_to_devices(
Returns:
tuple[dict, list]: (device_map, names)
-
- Example:
- Input:
- device_memory = {"cuda:0": 30.0, "cuda:1": 40.0, "cuda:2": 40.0}
- layer_memory_dict = {
- "q_proj": {"param_memory": 4.0}, "k_proj": {"param_memory": 1.0},
- "v_proj": {"param_memory": 1.0}, "o_proj": {"param_memory": 4.0},
- "gate_proj": {"param_memory": 11.0}, "up_proj": {"param_memory": 11.0},
- "down_proj": {"param_memory": 11.0}
- }
- mem_per_param = 2.0
-
- Result (allocation order by size):
- 1. gate_proj (22GB) -> cuda:2 (largest, prefer last device)
- 2. up_proj (22GB) -> cuda:1 (2nd largest, prefer 2nd last device)
- 3. down_proj (22GB) -> cuda:0 (3rd largest, cuda:0 has 30GB available)
- 4. q_proj (8GB) -> cuda:2 (neighbor of gate_proj, continuity bonus)
- 5. o_proj (8GB) -> cuda:2 (neighbor of q_proj, continuity bonus)
- 6. k_proj (2GB) -> cuda:1 (neighbor of q_proj via original order)
- 7. v_proj (2GB) -> cuda:1 (neighbor of k_proj, continuity bonus)
"""
device_map = {}
names = []
layer_names_in_order = list(layer_memory_dict.keys())
layer_order = {name: idx for idx, name in enumerate(layer_names_in_order)}
- sorted_layers = sorted(layer_memory_dict.items(), key=lambda x: (-x[1]["param_memory"], -layer_order[x[0]]))
+
+ # Phase 0: keep each MoE expert chunk device-local (grouped GEMM stays single-device, avoids
+ # the per-expert loop-fallback and its torch.compile recompiles) while spreading chunks across
+ # cards. Depends on the caller's symmetric per-card budgets so best-fit alternates cards
+ # instead of piling every chunk onto one card.
+ preassigned = _preassign_moe_experts(layer_memory_dict, device_memory, gpu_devices, mem_per_param)
+ device_map.update(preassigned)
+ names.extend(preassigned.keys())
+
+ # The general balancer handles everything the pre-pass did not place.
+ remaining = {name: layer_memory_dict[name] for name in layer_names_in_order if name not in preassigned}
+ sorted_layers = sorted(remaining.items(), key=lambda x: (-x[1]["param_memory"], -layer_order[x[0]]))
num_devices = len(gpu_devices)
def find_best_device(layer_name, estimated_memory, layer_idx):
@@ -717,7 +797,7 @@ def _allocate_layers_to_devices(
# Fallback: device with most available memory
return best_device or max(gpu_devices, key=lambda d: device_memory[d])
- # Allocate layers
+ # Allocate the remaining (non-preassigned) layers
for layer_idx, (layer_name, mem_info) in enumerate(sorted_layers):
names.append(layer_name)
estimated_memory = mem_info["param_memory"] * mem_per_param
@@ -957,6 +1037,20 @@ def set_auto_device_map_for_block_with_tuning(
This function is intended for internal use in device memory management and tuning.
"""
card_0_in_high_risk, loss_device = False, output_device
+ from auto_round.utils.model import (
+ _module_manages_own_device,
+ module_pinned_execution_device,
+ move_to_device_preserving_cpu_pinned,
+ place_ngram_embeddings_for_tuning_,
+ )
+
+ # Distribute huge, non-quantizable ngram embeddings before any block placement:
+ # row-shard them across the GPUs when >1 is available (on-device lookup, no card-0 OOM and
+ # far faster than a CPU-pinned table), otherwise keep them pinned on CPU. Must run first.
+ placed = place_ngram_embeddings_for_tuning_(block, list(device_list) if device_list else None)
+ if placed:
+ logger.debug(f"Placed {len(placed)} ngram embedding module(s) for tuning: {placed}")
+
dev_mgr = get_current_device_manager()
if dev_mgr.is_available() and dev_mgr.type != "cpu":
num_devices = dev_mgr.device_count()
@@ -965,7 +1059,7 @@ def set_auto_device_map_for_block_with_tuning(
return card_0_in_high_risk, loss_device
if len(device_list) <= 1: # Only 1 card is available or non-auto device map
- block = block.to(output_device)
+ move_to_device_preserving_cpu_pinned(block, output_device)
return card_0_in_high_risk, loss_device
if device_list:
@@ -1003,7 +1097,7 @@ def set_auto_device_map_for_block_with_tuning(
if not layer_memory_dict:
output_device = device_0 if output_device is None else output_device
- block.to(output_device)
+ move_to_device_preserving_cpu_pinned(block, output_device)
logger.debug(f"No layers require tuning; moved the block to {output_device}")
return card_0_in_high_risk, loss_device
@@ -1031,13 +1125,29 @@ def set_auto_device_map_for_block_with_tuning(
# Ensure all remaining modules with parameters/buffers are moved to expected device, by default device_0
output_device = device_0 if output_device is None else output_device
+
for name, module in block.named_modules():
- if name not in names: # This module wasn't assigned a device
- # Check if module has any parameters or buffers
- has_params = any(True for _ in module.parameters(recurse=False))
- has_buffers = any(True for _ in module.buffers(recurse=False))
- if has_params or has_buffers:
- module = module.to(output_device)
+ if name in names: # This module was already assigned a device
+ continue
+ if module_pinned_execution_device(module) is not None:
+ # Intentionally pinned to a fixed execution device (CPU, or a specific card for
+ # huge non-quantizable ngram embeddings); never relocate it or it could OOM / break
+ # the chosen placement.
+ continue
+ if _module_manages_own_device(module):
+ # Places its own (possibly multi-device) storage, e.g. a row-sharded ngram
+ # embedding split across GPUs; moving its buffers here would collapse the shards.
+ continue
+ # Move only this module's OWN tensors (recurse=False). Using module.to()
+ # would recurse and drag a CPU-pinned child (e.g. a nested ngram
+ # embedding) back onto the accelerator. Because named_modules() visits
+ # every module, each tensor is still covered exactly once here.
+ for _, param in module.named_parameters(recurse=False):
+ if param.device.type != "meta":
+ param.data = param.data.to(output_device)
+ for _, buf in module.named_buffers(recurse=False):
+ if buf.device.type != "meta":
+ buf.data = buf.data.to(output_device)
return card_0_in_high_risk, loss_device
diff --git a/auto_round/utils/disk_stream_util.py b/auto_round/utils/disk_stream_util.py
index 4751fac17..f8de6614d 100644
--- a/auto_round/utils/disk_stream_util.py
+++ b/auto_round/utils/disk_stream_util.py
@@ -188,6 +188,29 @@ _MODEL_PROJ_TO_FUSED = {
"down_proj": ("down_proj", 0),
}
+
+def _renamed_expert_candidates(index, full_name: str):
+ """Checkpoint-name candidates for an unfused per-expert parameter."""
+ match = _MODEL_SIDE_EXPERT_RE.match(full_name)
+ if match is None:
+ return
+
+ fused_position = _MODEL_PROJ_TO_FUSED.get(match["proj"])
+ if fused_position is None:
+ return
+ prefix, expert = match["prefix"], match["expert"]
+
+ for model_type in _index_model_types(index):
+ for key, suffix in _expert_projection_renames_for(model_type):
+ if key != fused_position:
+ continue
+ # "w1.weight" keeps the checkpoint's own attribute name; drop it for a bias.
+ suffix_attr = suffix.rsplit(".", 1)
+ if len(suffix_attr) == 2:
+ suffix = f"{suffix_attr[0]}.{match['attr']}"
+ yield f"{prefix}.{expert}.{suffix}"
+
+
# On-disk layout of fused expert tensors, keyed by checkpoint ``model_type``.
# Two axes vary between families:
# * ``checkpoint_transposed`` -- the per-expert 2-D slice is stored as
@@ -378,28 +401,6 @@ def _concat_converters_for(model_type):
return tuple(converters)
-def _renamed_expert_candidates(index, full_name: str):
- """Checkpoint-name candidates for an unfused per-expert parameter."""
- match = _MODEL_SIDE_EXPERT_RE.match(full_name)
- if match is None:
- return
-
- fused_position = _MODEL_PROJ_TO_FUSED.get(match["proj"])
- if fused_position is None:
- return
- prefix, expert = match["prefix"], match["expert"]
-
- for model_type in _index_model_types(index):
- for key, suffix in _expert_projection_renames_for(model_type):
- if key != fused_position:
- continue
- # "w1.weight" keeps the checkpoint's own attribute name; drop it for a bias.
- suffix_attr = suffix.rsplit(".", 1)
- if len(suffix_attr) == 2:
- suffix = f"{suffix_attr[0]}.{match['attr']}"
- yield f"{prefix}.{expert}.{suffix}"
-
-
def _resolve_checkpoint_name(index, full_name: str):
"""Map a model-side parameter name to its checkpoint-side tensor name."""
if index.has_tensor(full_name):
@@ -421,6 +422,290 @@ def _resolve_checkpoint_name(index, full_name: str):
return None
+def _dot_natural_key(name: str):
+ """Natural-sort key matching transformers' ``dot_natural_key``.
+
+ Falls back to a local reimplementation when the transformers symbol is
+ unavailable, so shards sort as ``shard_2`` < ``shard_11`` (numeric), exactly
+ like ``from_pretrained`` orders them before concatenating.
+ """
+ try:
+ from transformers.core_model_loading import dot_natural_key
+
+ return dot_natural_key(name)
+ except Exception: # pragma: no cover - transformers < 5 / API drift
+ parts: list = []
+ for part in name.split("."):
+ if part.isdigit():
+ parts.append((0, int(part)))
+ else:
+ text = part.rstrip("0123456789")
+ trailing = part[len(text) :]
+ parts.append((1, text, int(trailing)) if trailing else (1, text))
+ return parts
+
+
+@lru_cache(maxsize=None)
+def _wildcard_concat_converters_for(model_type):
+ """Wildcard shard-concat converters registered for one family.
+
+ Mirrors :func:`_concat_converters_for` but keeps the *wildcard* converters it
+ intentionally skips: a single-source ``source_patterns`` containing ``*`` whose
+ only operation is a ``Concatenate``. Qwen3-Next "Flash" (``qwen4_exp_text``) is
+ the motivating case -- its per-layer PLE n-gram embedding is stored as
+ ``...ngram_embedding.shard_<i>.weight`` and merged into a single
+ ``...ngram_embedding.weight`` via
+ ``Concatenate(dim=0, num_shards_attribute="split_ngram_parts")`` with
+ ``force_cpu=True`` (the assembled embedding is far too large to concatenate on
+ an accelerator).
+
+ Returns a tuple of ``(target_suffix, source_suffix, concat_dim, force_cpu)``
+ tuples; ``source_suffix`` still contains the ``*`` shard wildcard.
+ """
+ if not model_type:
+ return ()
+ try:
+ from transformers.conversion_mapping import get_checkpoint_conversion_mapping
+ from transformers.core_model_loading import Concatenate, WeightConverter
+ except ImportError: # pragma: no cover - transformers < 5
+ return ()
+
+ mapping = get_checkpoint_conversion_mapping(model_type)
+ if not mapping:
+ return ()
+
+ converters = []
+ for entry in mapping:
+ if not isinstance(entry, WeightConverter):
+ continue
+ if len(entry.source_patterns) != 1 or len(entry.target_patterns) != 1:
+ continue
+ # Only a single Concatenate op (no MergeModulelist -> that is expert fusion,
+ # no Chunk/Transpose/etc. -> not a plain shard merge).
+ if len(entry.operations) != 1 or not isinstance(entry.operations[0], Concatenate):
+ continue
+ source = entry.source_patterns[0].rstrip("$")
+ target = entry.target_patterns[0].rstrip("$")
+ if "*" not in source or "*" in target:
+ continue
+ converters.append((target, source, getattr(entry.operations[0], "dim", 0), getattr(entry, "force_cpu", False)))
+ return tuple(converters)
+
+
+def _assemble_sharded_tensor(index, full_name: str, device: str):
+ """Reconstruct a fused model-side param stored on disk as numbered shards.
+
+ Follows the transformers checkpoint converter for the checkpoint's family: it
+ finds a wildcard ``Concatenate`` converter whose target suffix matches
+ ``full_name``, expands the ``shard_*`` source glob against the checkpoint index,
+ orders the shards with transformers' natural-sort key, and concatenates them
+ along the converter's declared ``dim`` (honoring its ``force_cpu`` flag so a
+ huge embedding is never assembled on an accelerator).
+
+ Returns ``(tensor, dst_device)`` -- ``dst_device`` is ``"cpu"`` when the
+ converter sets ``force_cpu`` -- or ``None`` when no converter matches (the
+ caller then leaves the param on meta and surfaces an actionable error).
+ """
+ for model_type in _index_model_types(index):
+ for target_suffix, source_suffix, dim, force_cpu in _wildcard_concat_converters_for(model_type):
+ if not full_name.endswith(target_suffix):
+ continue
+ prefix = full_name[: -len(target_suffix)]
+ # Require a clean path boundary so a suffix does not match mid-token.
+ if prefix and not prefix.endswith("."):
+ continue
+ # Build the concrete ``shard_*`` glob for this parameter and match the index.
+ source_regex = re.compile("^" + re.escape(prefix + source_suffix).replace(r"\*", r"(.+)") + "$")
+ matched = [name for name in index.weight_map if source_regex.match(name)]
+ if not matched:
+ continue
+ matched.sort(key=_dot_natural_key)
+ read_device = "cpu" if force_cpu else device
+ read = index.read_tensors(matched, device=read_device)
+ assembled = torch.cat([read[name] for name in matched], dim=dim).contiguous()
+ return assembled, read_device
+ return None
+
+
+# ── General converter-driven materialization ─────────────────────────────────
+# The helpers above cover the common single-op cases explicitly (direct name,
+# reverse renaming, expert fusion, literal/wildcard concat). Some model families
+# -- especially the MoE ones we target on the meta path (Qwen3-Next "Flash",
+# GLM-5-next, DeepSeek-V4, ...) -- also carry *other* WeightConverters in their
+# transformers mapping: fused-qkv ``Chunk``, ``Interleave``/``Transpose`` gate-up,
+# ``PermuteForRope``, and multi-op chains. Rather than reimplement each op, the
+# fallback below reuses the real transformers ``WeightConverter`` objects: it
+# routes the checkpoint keys through ``rename_source_key`` exactly like
+# ``from_pretrained`` (all renamings, then one converter), feeds the collected
+# source tensors into a fresh converter instance, and runs ``convert`` -- the same
+# path transformers' own ``revert_weight_conversion`` uses. Output is accepted
+# only when its shape matches the destination parameter, so a bad route can never
+# silently corrupt a weight (it just falls back to leaving the param on meta).
+
+
+@lru_cache(maxsize=8)
+def _conversion_transforms_for_dir(checkpoint_dir: str):
+ """Collect ``(renamings, converters)`` from every model_type in the config.
+
+ Deduplicated by ``(source_patterns, target_patterns)`` so families that share
+ a base mapping (e.g. ``qwen3_5_moe_text`` embeds ``qwen2_moe``) do not route a
+ checkpoint key through the same converter twice (which would duplicate tensors
+ inside a concat/merge).
+ """
+ try:
+ from transformers.conversion_mapping import get_checkpoint_conversion_mapping
+ from transformers.core_model_loading import WeightConverter, WeightRenaming
+ except ImportError: # pragma: no cover - transformers < 5
+ return (), ()
+
+ renamings: list = []
+ converters: list = []
+ seen: set = set()
+ for model_type in _model_types_for_dir(checkpoint_dir):
+ mapping = get_checkpoint_conversion_mapping(model_type)
+ if not mapping:
+ continue
+ for entry in mapping:
+ if not isinstance(entry, (WeightConverter, WeightRenaming)):
+ continue
+ sig = (tuple(entry.source_patterns), tuple(entry.target_patterns))
+ if sig in seen:
+ continue
+ seen.add(sig)
+ (converters if isinstance(entry, WeightConverter) else renamings).append(entry)
+ return tuple(renamings), tuple(converters)
+
+
+@lru_cache(maxsize=8)
+def _converter_routing_table(checkpoint_dir: str):
+ """Map each converter-produced model-side name to its checkpoint sources.
+
+ Mirrors the ``from_pretrained`` routing loop: every checkpoint key is renamed
+ via ``rename_source_key`` (all ``WeightRenaming``s, then at most one
+ ``WeightConverter``). Returns ``(table, pattern_to_converter)`` where ``table``
+ maps ``renamed_full_name -> [(source_pattern, checkpoint_key), ...]``.
+ """
+ renamings, converters = _conversion_transforms_for_dir(checkpoint_dir)
+ if not converters:
+ return {}, {}
+ try:
+ from transformers.core_model_loading import rename_source_key
+ except ImportError: # pragma: no cover - transformers < 5
+ return {}, {}
+
+ index = get_safetensors_index(checkpoint_dir)
+ pattern_to_converter = {pattern: conv for conv in converters for pattern in conv.source_patterns}
+ renaming_list = list(renamings)
+ converter_list = list(converters)
+ table: dict = {}
+ for key in index.weight_map:
+ try:
+ renamed, source_pattern = rename_source_key(key, renaming_list, converter_list)
+ except Exception: # pragma: no cover - never fail the whole load on one key
+ continue
+ if source_pattern is None:
+ continue
+ table.setdefault(renamed, []).append((source_pattern, key))
+
+ # ``rename_source_key`` renames a 1->N converter (e.g. fused-QKV ``Chunk``) to its FIRST
+ # target only, so the table above holds just that one name. ``convert`` emits every target
+ # from the same source tensors, so register the sibling target names too (each pointing at
+ # the same collected sources); the caller passes whichever it needs and picks it out.
+ expanded: dict = {}
+ for renamed, entries in table.items():
+ converter = pattern_to_converter.get(entries[0][0])
+ targets = list(getattr(converter, "target_patterns", []) or [])
+ first = targets[0] if targets else None
+ if len(targets) <= 1 or first is None or first not in renamed:
+ expanded[renamed] = entries
+ continue
+ for target in targets:
+ expanded[renamed.replace(first, target, 1)] = entries
+ return expanded, pattern_to_converter
+
+
+@lru_cache(maxsize=8)
+def _auto_config_for_dir(checkpoint_dir: str):
+ """Best-effort model config for converter ops that need it (PermuteForRope, ...).
+
+ ``local_files_only=True`` keeps this fully offline -- the checkpoint is already a local
+ snapshot dir, and a hub round-trip here would stall the whole materialization.
+ """
+ try:
+ from transformers import AutoConfig
+
+ return AutoConfig.from_pretrained(checkpoint_dir, trust_remote_code=True, local_files_only=True)
+ except Exception as exc: # pragma: no cover - config-less ops still work
+ logger.debug("could not load config for converter ops from %s: %s", checkpoint_dir, exc)
+ return None
+
+
+def _convert_param_via_converters(index, full_name: str, target_shape, device: str):
+ """Materialize ``full_name`` by replaying its transformers ``WeightConverter``.
+
+ Returns ``(tensor, dst_device)`` when a converter produces a tensor whose shape
+ matches ``target_shape``; otherwise ``None`` (the caller then leaves the param
+ on meta). ``dst_device`` is ``"cpu"`` when the converter declares ``force_cpu``.
+ """
+ checkpoint_dir = str(getattr(index, "checkpoint_dir", "") or "")
+ if not checkpoint_dir:
+ return None
+ try:
+ table, pattern_to_converter = _converter_routing_table(checkpoint_dir)
+ except Exception: # pragma: no cover
+ return None
+ entries = table.get(full_name)
+ if not entries:
+ return None
+
+ try:
+ import copy as _copy
+ from types import SimpleNamespace
+
+ base_converter = pattern_to_converter.get(entries[0][0])
+ if base_converter is None:
+ return None
+ force_cpu = bool(getattr(base_converter, "force_cpu", False))
+ read_device = "cpu" if force_cpu else device
+
+ # Group checkpoint keys per source pattern; order within each group by the
+ # same natural key transformers uses, so shard/expert indices line up.
+ keys_by_pattern: dict = {}
+ for source_pattern, key in entries:
+ keys_by_pattern.setdefault(source_pattern, []).append(key)
+
+ converter = _copy.deepcopy(base_converter)
+ all_keys = [k for keys in keys_by_pattern.values() for k in keys]
+ read = index.read_tensors(all_keys, device=read_device)
+ for source_pattern in converter.source_patterns:
+ keys = keys_by_pattern.get(source_pattern)
+ if not keys:
+ continue
+ keys.sort(key=_dot_natural_key)
+ for key in keys:
+ converter.add_tensor(full_name, key, source_pattern, read[key])
+
+ config = _auto_config_for_dir(checkpoint_dir)
+ target_size = torch.Size(tuple(target_shape))
+ model_shim = SimpleNamespace(
+ config=config,
+ get_parameter=lambda _name, _s=target_size: SimpleNamespace(shape=_s),
+ )
+ result = converter.convert(full_name, model=model_shim, config=config)
+ except Exception as exc:
+ logger.debug("converter-driven materialization of %s failed: %s", full_name, exc)
+ return None
+
+ if not isinstance(result, dict):
+ return None
+ value = result.get(full_name)
+ if isinstance(value, list):
+ value = value[0] if value else None
+ if value is None or tuple(value.shape) != tuple(target_shape):
+ return None
+ return value.contiguous(), read_device
+
+
def materialize_module(module: nn.Module, module_name: str, index: SafetensorsIndex, device: str) -> None:
"""Populate `module`'s (currently meta) parameters/buffers with real data read
directly from the checkpoint, onto `device`. `module_name` is `module`'s dotted
@@ -524,6 +809,16 @@ def materialize_module(module: nn.Module, module_name: str, index: SafetensorsIn
if sliced is not None:
fused_targets.append((name, sliced))
continue
+ assembled = _assemble_sharded_tensor(index, full_name, device)
+ if assembled is not None:
+ value, dst_device = assembled
+ set_module_tensor_to_device(module, name, dst_device, value=value, dtype=value.dtype)
+ continue
+ converted = _convert_param_via_converters(index, full_name, tensor.shape, device)
+ if converted is not None:
+ value, dst_device = converted
+ set_module_tensor_to_device(module, name, dst_device, value=value, dtype=value.dtype)
+ continue
logger.warning("No checkpoint tensor found for %s, leaving on meta", full_name)
continue
targets.append((name, resolved_name, tensor.dtype))
@@ -723,6 +1018,16 @@ def materialize_non_block_params(
full_name = name.replace(".orig_layer.", ".")
resolved_name = _resolve_checkpoint_name(index, full_name)
if resolved_name is None:
+ assembled = _assemble_sharded_tensor(index, full_name, device)
+ if assembled is not None:
+ value, dst_device = assembled
+ set_module_tensor_to_device(model, name, dst_device, value=value, dtype=value.dtype)
+ continue
+ converted = _convert_param_via_converters(index, full_name, tensor.shape, device)
+ if converted is not None:
+ value, dst_device = converted
+ set_module_tensor_to_device(model, name, dst_device, value=value, dtype=value.dtype)
+ continue
if _is_tied(name):
deferred_tied.append(name)
else:
diff --git a/auto_round/utils/model.py b/auto_round/utils/model.py
index df4995cd6..c8f09f2a9 100644
--- a/auto_round/utils/model.py
+++ b/auto_round/utils/model.py
@@ -2558,23 +2558,438 @@ def rename_weights_files(path: str, prefix="diffusion_pytorch_model"):
os.remove(idx)
-def hook_ngram_embeddings_on_cpu(model):
- has_ngram_embeddings = hasattr(model, "model") and hasattr(model.model, "ngram_embeddings")
- if has_ngram_embeddings:
- raw_ngram_embeddings = model.model.ngram_embeddings
+def _pin_module_execution_on_device(module: torch.nn.Module, device) -> None:
+ """Attach an accelerate hook that runs ``module``'s forward on ``device``.
+
+ ``AlignDevicesHook(execution_device=device, io_same_device=True)`` aligns the module's
+ inputs to ``device`` before the forward and moves the output back to the caller's device,
+ so a huge, non-quantizable embedding can stay resident on a chosen device (CPU host RAM,
+ or a specific accelerator) instead of being dragged around by generic block relocation.
+ Params are expected to already live on ``device`` (the caller moves them for GPU targets).
+ """
+ from accelerate.hooks import AlignDevicesHook, add_hook_to_module
+
+ add_hook_to_module(module, AlignDevicesHook(io_same_device=True, execution_device=str(device)))
+
+
+def _pin_module_execution_on_cpu(module: torch.nn.Module) -> None:
+ """Attach an accelerate hook that keeps ``module``'s forward on CPU."""
+ _pin_module_execution_on_device(module, "cpu")
+
+
+def module_pinned_execution_device(module: torch.nn.Module) -> str | None:
+ """Return the execution-device string a module is pinned to, or ``None`` if not pinned.
+
+ Matches modules hooked by :func:`_pin_module_execution_on_device` (CPU or a specific
+ accelerator). Used by block relocation to leave intentionally-pinned modules in place.
+ """
+ hook = getattr(module, "_hf_hook", None)
+ if hook is None:
+ return None
+ hooks = getattr(hook, "hooks", (hook,)) # SequentialHook aggregates several
+ for h in hooks:
+ exec_device = getattr(h, "execution_device", None)
+ if exec_device is not None:
+ return str(exec_device)
+ return None
+
+
+def module_is_pinned_on_cpu(module: torch.nn.Module) -> bool:
+ """Return True if ``module`` carries a CPU-execution accelerate hook."""
+ return module_pinned_execution_device(module) == "cpu"
+
+
+def pin_ngram_embeddings_on_cpu_(module: torch.nn.Module) -> list:
+ """Pin every ngram embedding found under ``module`` on CPU, in place.
+
+ Works on any subtree (a whole model *or* a single decoder block), so it can
+ be applied right after a block is materialized and before it is dispatched
+ onto accelerators. Returns the list of pinned module names.
+ """
+ pinned = []
+ pinned_modules = []
+ for name, sub in module.named_modules():
+ leaf = name.rsplit(".", 1)[-1]
+ if leaf in ("ngram_embedding", "ngram_embeddings"):
+ if not module_is_pinned_on_cpu(sub):
+ _pin_module_execution_on_cpu(sub)
+ pinned.append(name)
+ pinned_modules.append(sub)
+ if pinned_modules:
+ _log_ngram_cpu_hint(pinned_modules)
+ return pinned
+
+
+def _log_ngram_cpu_hint(ngram_modules: list) -> None:
+ """Tell the user ngram embeddings are on CPU and how to move them (once per run).
+
+ Emits the total ngram size and, when ``AR_NGRAM_DEVICE`` is not explicitly set, points at
+ the faster on-GPU options -- noting that ``across`` (multi-GPU sharding) is experimental
+ and may have bugs.
+ """
+ from auto_round import envs
+
+ total_nbytes = sum(_module_storage_nbytes(sub) for sub in ngram_modules)
+ if envs.is_set("AR_NGRAM_DEVICE"):
+ logger.info_once(
+ "Found %d ngram embedding module(s) (total %s); AR_NGRAM_DEVICE=%s keeps them on CPU.",
+ len(ngram_modules),
+ _format_nbytes_gib(total_nbytes),
+ str(getattr(envs, "AR_NGRAM_DEVICE", "auto")),
+ )
+ else:
+ logger.info_once(
+ "Found %d ngram embedding module(s) (total %s). AR_NGRAM_DEVICE is not set, so they stay on "
+ "CPU by default (memory-safe, but adds host<->device copies each block forward). To speed up, "
+ "set AR_NGRAM_DEVICE=<cuda:N|xpu:N> to place the whole table on one card, or AR_NGRAM_DEVICE=across "
+ "to row-shard it across all GPUs (experimental, may have bugs).",
+ len(ngram_modules),
+ _format_nbytes_gib(total_nbytes),
+ )
+
+
+def move_to_device_preserving_cpu_pinned(module: torch.nn.Module, device) -> torch.nn.Module:
+ """Move ``module`` to ``device`` but leave pinned/self-managed subtrees in place.
+
+ ``nn.Module.to()`` recurses unconditionally and would drag a pinned child (e.g. a
+ multi-GiB ngram embedding pinned on CPU or on a specific accelerator) onto ``device``,
+ which is exactly what causes card-0 OOM on large ngram models. This walks the tree
+ manually and stops at any subtree pinned to an execution device
+ (:func:`_pin_module_execution_on_device`) or one that manages its own (possibly
+ multi-device) storage, e.g. a row-sharded :class:`_ShardedEmbedding`.
+ """
+ if module_pinned_execution_device(module) is not None or _module_manages_own_device(module):
+ return module
+ # Materialize the iterators before mutating: reassigning ``param.data`` can trigger
+ # changes to the module's internal ``_parameters``/``_buffers`` dicts (e.g. on HPU lazy
+ # mode), which would raise ``RuntimeError: dictionary keys changed during iteration``.
+ for _, param in list(module.named_parameters(recurse=False)):
+ if param.device.type != "meta":
+ param.data = param.data.to(device)
+ if param.grad is not None:
+ param.grad.data = param.grad.data.to(device)
+ for _, buf in list(module.named_buffers(recurse=False)):
+ if buf.device.type != "meta":
+ buf.data = buf.data.to(device)
+ for child in list(module.children()):
+ move_to_device_preserving_cpu_pinned(child, device)
+ return module
+
+
+class _ShardedEmbedding(torch.nn.Module):
+ """Row-sharded, multi-GPU drop-in replacement for a huge ``nn.Embedding``.
+
+ A single embedding table ``(num_embeddings, dim)`` that is too large to fit on one
+ accelerator (e.g. the ~95 GiB Qwen4-Exp per-layer ngram table) is split along dim 0 into
+ contiguous row ranges, one shard per device. ``forward(ids)`` reproduces
+ ``nn.Embedding(ids)`` bit-exactly by gathering each id from the shard that owns its row,
+ so the lookup runs on-GPU instead of being pinned (slowly) on CPU.
+
+ The module owns its (multi-device) storage: generic block-relocation helpers must skip it
+ (see :func:`_module_manages_own_device`), or the shards would be collapsed onto one device.
+ Shards are registered as non-persistent buffers so ``.to("cpu")`` based offload can still
+ reclaim their device memory after the block is done.
+ """
+
+ def __init__(self, embedding: "torch.nn.Embedding", devices: list) -> None:
+ super().__init__()
+ weight = embedding.weight.data
+ self.num_embeddings, self.embedding_dim = int(weight.shape[0]), int(weight.shape[1])
+ self.weight_dtype = weight.dtype
+ n = max(1, len(devices))
+ rows_per_shard = (self.num_embeddings + n - 1) // n
+ self._bounds: list[tuple[int, int]] = []
+ for i, device in enumerate(devices):
+ lo = i * rows_per_shard
+ hi = min(self.num_embeddings, lo + rows_per_shard)
+ if lo >= hi:
+ break
+ self.register_buffer(f"shard_{i}", weight[lo:hi].to(device), persistent=False)
+ self._bounds.append((lo, hi))
+
+ @property
+ def weight(self):
+ # Exposed so callers that read ``embedding.weight.device`` keep working (the forward
+ # re-routes ids to the correct shard regardless of which device they arrive on).
+ return getattr(self, "shard_0")
+
+ def forward(self, input_ids: "torch.Tensor") -> "torch.Tensor":
+ flat = input_ids.reshape(-1)
+ # Compile-friendly gather: no data-dependent control flow. Avoid ``mask.any()`` (a scalar
+ # sync -> dynamo graph break) and boolean-mask indexing (``flat[mask]`` -> data-dependent
+ # shapes -> recompiles). Instead, for every shard clamp ids into its local range, gather,
+ # and select the owning shard's rows with ``torch.where``. Each id lives in exactly one
+ # shard, so exactly one iteration writes it; the rest keep the running ``out``.
+ out = torch.zeros(flat.shape[0], self.embedding_dim, dtype=self.weight_dtype, device=flat.device)
+ for i, (lo, hi) in enumerate(self._bounds):
+ shard = getattr(self, f"shard_{i}")
+ mask = (flat >= lo) & (flat < hi)
+ local = torch.clamp(flat - lo, 0, hi - lo - 1).to(shard.device)
+ gathered = torch.nn.functional.embedding(local, shard).to(out.device)
+ out = torch.where(mask.unsqueeze(-1), gathered, out)
+ return out.reshape(*input_ids.shape, self.embedding_dim)
+
+
+def _module_manages_own_device(module: torch.nn.Module) -> bool:
+ """True for modules that place their own (possibly multi-device) storage.
+
+ Such modules (e.g. :class:`_ShardedEmbedding`) must be skipped by the generic block
+ relocation helpers so their shards are not collapsed onto a single device.
+ """
+ return isinstance(module, _ShardedEmbedding)
+
+
+def shard_ngram_embeddings_across_gpus_(module: torch.nn.Module, devices: list) -> list:
+ """Row-shard every plain ``nn.Embedding`` ngram table under ``module`` across ``devices``.
+
+ Requires >= 2 devices; only plain, already-materialized ``nn.Embedding`` tables are
+ sharded (anything else is left for the caller to CPU-pin). Returns the sharded names.
+ """
+ if not devices or len(devices) < 2:
+ return []
+ sharded = []
+ for name, sub in list(module.named_modules()):
+ leaf = name.rsplit(".", 1)[-1]
+ if leaf not in ("ngram_embedding", "ngram_embeddings"):
+ continue
+ if not isinstance(sub, torch.nn.Embedding) or isinstance(sub, _ShardedEmbedding):
+ continue
+ if sub.weight.device.type == "meta":
+ continue # not materialized yet; caller decides
+ parent = get_module(module, name.rsplit(".", 1)[0]) if "." in name else module
+ try:
+ replacement = _ShardedEmbedding(sub, devices)
+ except Exception as err: # OOM or device error -> leave for the caller to CPU-pin
+ logger.warning(f"Could not shard ngram embedding '{name}' across GPUs ({err}); keeping it on CPU.")
+ continue
+ setattr(parent, leaf, replacement)
+ sharded.append(name)
+ return sharded
- def hook_input_output_device_for_cpu_module(module):
- from accelerate.hooks import AlignDevicesHook, add_hook_to_module
- hook = AlignDevicesHook(
- io_same_device=True,
- execution_device="cpu",
+def _iter_ngram_modules(module: torch.nn.Module):
+ """Yield ``(name, submodule)`` for every ngram embedding leaf under ``module``."""
+ for name, sub in module.named_modules():
+ leaf = name.rsplit(".", 1)[-1]
+ # Keep exact matches first, but also accept common ngram leaf variants.
+ if leaf in ("ngram_embedding", "ngram_embeddings") or ("ngram_embedding" in leaf or leaf.startswith("ngram")):
+ yield name, sub
+
+
+def _module_storage_nbytes(module: torch.nn.Module) -> int:
+ """Return parameter+buffer storage bytes for one module (including its children)."""
+ total = 0
+ for param in module.parameters(recurse=True):
+ total += int(param.numel()) * int(param.element_size())
+ for buf in module.buffers(recurse=True):
+ total += int(buf.numel()) * int(buf.element_size())
+ return total
+
+
+def _format_nbytes_gib(nbytes: int) -> str:
+ """Format byte count in GiB for user-facing logs."""
+ gib = float(nbytes) / (1024.0**3)
+ return f"{gib:.2f} GiB"
+
+
+def _place_ngram_on_single_device_(sub: torch.nn.Module, device: str) -> None:
+ """Keep one ngram embedding resident on ``device`` (CPU or a specific accelerator).
+
+ For a GPU target the params are physically moved onto the card first (so the on-device
+ lookup is real); for CPU they stay in host RAM. An ``AlignDevicesHook`` then keeps the
+ module executing on ``device`` and re-aligns I/O to the caller, and marks it so the
+ generic block relocation leaves it in place.
+ """
+ if module_pinned_execution_device(sub) == str(device):
+ return
+ if not isinstance(sub, _ShardedEmbedding):
+ try:
+ tensors = list(sub.parameters(recurse=False)) + list(sub.buffers(recurse=False))
+ if any(t.device.type != "meta" for t in tensors):
+ sub.to(device)
+ except Exception as err: # OOM, invalid/unavailable device, ... -> safe CPU fallback
+ logger.warning(f"Could not place ngram embedding on {device} ({err}); keeping it on CPU.")
+ device = "cpu"
+ _pin_module_execution_on_device(sub, device)
+
+
+def _normalize_ngram_target_device(setting: str, devices: list) -> str | None:
+ """Resolve an ``AR_NGRAM_DEVICE`` value naming a single device to a concrete device string.
+
+ Accepts a full string (``cuda:1``/``xpu:0``/``cpu``) or a bare index (``1`` -> the second
+ entry of ``devices`` when present, else ``<accelerator>:1``). Returns ``None`` if the value
+ is not a single-device request.
+ """
+ if setting == "cpu":
+ return "cpu"
+ if ":" in setting:
+ return setting
+ if setting.isdigit():
+ idx = int(setting)
+ if devices and idx < len(devices):
+ return str(devices[idx])
+ try:
+ from auto_round.utils.device_manager import device_manager
+
+ return f"{device_manager.type}:{idx}"
+ except Exception: # pragma: no cover - device manager optional/unavailable
+ return f"cuda:{idx}"
+ return None
+
+
+def place_ngram_embeddings_for_tuning_(module: torch.nn.Module, gpu_devices: list | None = None) -> list:
+ """Place ngram embeddings for per-block tuning, honoring the ``AR_NGRAM_DEVICE`` env var.
+
+ ``AR_NGRAM_DEVICE`` values:
+
+ * ``auto`` (default): keep the table pinned on CPU (memory-safe; the table does not
+ participate in tuning). A one-time hint points users at the faster on-GPU options.
+ * ``across`` / ``shard`` / ``gpu``: force row-sharding across all available GPUs.
+ * ``cpu``: pin on CPU (same as the default).
+ * a device (``cuda:1``, ``xpu:0``, or a bare index like ``1``): put the whole table on
+ that specific card.
+
+ Multi-GPU sharding is experimental (see the warning below). Returns the handled names.
+ """
+ from auto_round import envs
+
+ setting = str(getattr(envs, "AR_NGRAM_DEVICE", "auto")).strip().lower()
+ ngram_device_explicitly_set = bool(envs.is_set("AR_NGRAM_DEVICE"))
+
+ devices = [str(d) for d in gpu_devices] if gpu_devices else []
+ if not devices:
+ try:
+ from auto_round.utils.device_manager import device_manager
+
+ if device_manager.is_available() and device_manager.type != "cpu":
+ devices = [str(d) for d in device_manager.device_list]
+ except Exception: # pragma: no cover - device manager optional/unavailable
+ devices = []
+
+ ngram_modules = list(_iter_ngram_modules(module))
+ if not ngram_modules:
+ fallback_ngram_names = [name for name, _ in module.named_modules() if "ngram" in name.lower()]
+ if fallback_ngram_names:
+ logger.info_once(
+ "AR_NGRAM_DEVICE=%s is set, but no ngram embedding leaf matched placement rules in this block. "
+ "Found %d ngram-like module name(s), e.g. %s",
+ setting or "auto",
+ len(fallback_ngram_names),
+ ", ".join(fallback_ngram_names[:3]),
)
+ else:
+ logger.info_once(
+ "AR_NGRAM_DEVICE=%s is set, but no ngram modules were found under this block.",
+ setting or "auto",
+ )
+ return []
+ total_ngram_nbytes = sum(_module_storage_nbytes(sub) for _, sub in ngram_modules)
+ logger.info_once(
+ "Detected %d ngram embedding module(s), total size %s (AR_NGRAM_DEVICE=%s).",
+ len(ngram_modules),
+ _format_nbytes_gib(total_ngram_nbytes),
+ setting or "auto",
+ )
- add_hook_to_module(module, hook)
+ # Resolve the requested mode.
+ single_target = _normalize_ngram_target_device(setting, devices)
+ if setting in ("across", "shard", "gpu"):
+ mode = "across"
+ elif setting in ("auto", ""):
+ # Default: keep the (huge, non-tunable) ngram table on CPU. It does not participate in
+ # tuning, so host residency is correct and memory-safe (no per-card OOM, no extra device
+ # RAM churn); the only cost is host<->device copies per forward. Point users at the
+ # faster on-GPU options once, so they can opt in when they have the headroom.
+ mode = "single"
+ single_target = "cpu"
+ if not ngram_device_explicitly_set:
+ logger.info_once(
+ "AR_NGRAM_DEVICE is not set, so ngram embeddings stay on CPU by default (total %s, memory-safe). "
+ "For faster lookup set AR_NGRAM_DEVICE=<cuda:N|xpu:N> (single GPU) or AR_NGRAM_DEVICE=across "
+ "(multi-GPU sharding, experimental and may have bugs).",
+ _format_nbytes_gib(total_ngram_nbytes),
+ )
+ else:
+ logger.info_once(
+ "AR_NGRAM_DEVICE=%s keeps ngram embeddings on CPU (total %s, memory-safe).",
+ setting,
+ _format_nbytes_gib(total_ngram_nbytes),
+ )
+ elif single_target is not None:
+ mode = "single"
+ else:
+ logger.warning(f"Unrecognized AR_NGRAM_DEVICE={setting!r}; falling back to CPU (safe default).")
+ mode = "single"
+ single_target = "cpu"
+
+ handled: list = []
+ if mode == "across":
+ if len(devices) >= 2:
+ logger.warning_once(
+ "Sharding ngram embeddings across multiple GPUs is experimental and may have bugs; "
+ "set AR_NGRAM_DEVICE=cpu (safe) or a specific card (e.g. AR_NGRAM_DEVICE=cuda:0) if you hit issues."
+ )
+ handled = list(shard_ngram_embeddings_across_gpus_(module, devices))
+ if handled:
+ logger.info(
+ "Placed %d ngram embedding module(s) across %d GPUs (total %s).",
+ len(handled),
+ len(devices),
+ _format_nbytes_gib(total_ngram_nbytes),
+ )
+ # Any ngram not sharded (single/no GPU, custom module, OOM) falls back to CPU pin below.
+ fallback = devices[0] if len(devices) == 1 else "cpu"
+ for name, sub in ngram_modules:
+ if name in handled or isinstance(sub, _ShardedEmbedding):
+ continue
+ _place_ngram_on_single_device_(sub, fallback)
+ handled.append(name)
+ if handled and len(devices) < 2:
+ logger.info(
+ "Placed %d ngram embedding module(s) on %s (total %s).",
+ len(handled),
+ fallback,
+ _format_nbytes_gib(total_ngram_nbytes),
+ )
+ return handled
+
+ # mode == "single": every ngram table on one chosen device (CPU or a specific card).
+ target = single_target if single_target is not None else "cpu"
+ for name, sub in ngram_modules:
+ _place_ngram_on_single_device_(sub, target)
+ handled.append(name)
+ if handled:
+ logger.info(
+ "Placed %d ngram embedding module(s) on %s (total %s).",
+ len(handled),
+ target,
+ _format_nbytes_gib(total_ngram_nbytes),
+ )
+ return handled
+
+
+def hook_ngram_embeddings_on_cpu(model):
+ """Pin ngram embeddings on CPU so they are never moved onto an accelerator.
- hook_input_output_device_for_cpu_module(raw_ngram_embeddings)
- return has_ngram_embeddings, raw_ngram_embeddings if has_ngram_embeddings else None
+ Handles two layouts:
+
+ * The top-level ``model.model.ngram_embeddings`` module (original behavior).
+ * Per-layer ngram embeddings nested anywhere in the tree, e.g.
+ ``model.language_model.layers.N.ple.ple_embedding.ngram_embedding`` used by
+ Qwen3-Next-Flash style checkpoints. These are single, very large lookup
+ tables (~tens of GiB) that do not participate in tuning, so keeping them on
+ CPU avoids GPU OOM during per-block dispatch.
+
+ Returns ``(has_top_level_ngram, raw_top_level_ngram_or_None)`` for backward
+ compatibility with the calibration dispatch restore logic.
+ """
+ # Per-layer / nested ngram embeddings (match any module attribute literally
+ # named ``ngram_embedding``, plus the pluralized top-level ``ngram_embeddings``).
+ pin_ngram_embeddings_on_cpu_(model)
+
+ has_ngram_embeddings = hasattr(model, "model") and hasattr(model.model, "ngram_embeddings")
+ raw_ngram_embeddings = model.model.ngram_embeddings if has_ngram_embeddings else None
+ return has_ngram_embeddings, raw_ngram_embeddings
def is_model_free_route(
diff --git a/test/unit/common/models/test_moe_experts_interface.py b/test/unit/common/models/test_moe_experts_interface.py
index f8c811985..49f0f9125 100644
--- a/test/unit/common/models/test_moe_experts_interface.py
+++ b/test/unit/common/models/test_moe_experts_interface.py
@@ -270,6 +270,7 @@ def test_prepare_model_for_moe_quantization():
"""Test the full prepare_model_for_moe_quantization flow."""
from auto_round.modeling.fused_moe.moe_experts_interface import (
prepare_model_for_moe_quantization,
+ resolve_experts_implementation,
)
_skip_if_no_linear_loop()
@@ -311,7 +312,7 @@ def test_prepare_model_for_moe_quantization():
unfused = prepare_model_for_moe_quantization(model)
# Verify
- assert model.config._experts_implementation == "linear_loop"
+ assert model.config._experts_implementation == resolve_experts_implementation()
assert len(unfused) == 1
experts = model.layer["experts"]
expert_0 = getattr(experts, "0")
diff --git a/test/unit/common/utils/test_model_utils.py b/test/unit/common/utils/test_model_utils.py
index 781ebe0cc..c561de4af 100644
--- a/test/unit/common/utils/test_model_utils.py
+++ b/test/unit/common/utils/test_model_utils.py
@@ -1521,6 +1521,88 @@ class TestHookNgramEmbeddingsOnCpu:
assert has_ngram is False
assert raw_ngram is None
+ def test_top_level_ngram_embeddings_pinned(self):
+ """Top-level ``model.model.ngram_embeddings`` is pinned and returned."""
+ import torch.nn as nn
+
+ from auto_round.utils.model import hook_ngram_embeddings_on_cpu, module_is_pinned_on_cpu
+
+ class Inner(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.ngram_embeddings = nn.Embedding(50, 8)
+
+ class Model(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.model = Inner()
+
+ model = Model()
+ has_ngram, raw_ngram = hook_ngram_embeddings_on_cpu(model)
+ assert has_ngram is True
+ assert raw_ngram is model.model.ngram_embeddings
+ assert module_is_pinned_on_cpu(model.model.ngram_embeddings)
+
+ def test_per_layer_ngram_embeddings_pinned(self):
+ """Nested per-layer ``...ple.ple_embedding.ngram_embedding`` are pinned.
+
+ Mirrors the Qwen3-Next-Flash layout where each decoder layer carries its
+ own large ngram lookup table that must stay resident on CPU.
+ """
+ import torch
+ import torch.nn as nn
+
+ from auto_round.utils.model import hook_ngram_embeddings_on_cpu, module_is_pinned_on_cpu
+
+ class PleEmb(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.register_buffer("layer_multipliers", torch.zeros(4))
+ self.ngram_embedding = nn.Embedding(100, 8)
+
+ class Ple(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.ple_embedding = PleEmb()
+ self.key_proj = nn.Linear(8, 8)
+
+ class Layer(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.ple = Ple()
+
+ class Inner(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.layers = nn.ModuleList([Layer(), Layer()])
+
+ class Model(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.model = Inner()
+
+ model = Model()
+ # No top-level ngram_embeddings here.
+ has_ngram, raw_ngram = hook_ngram_embeddings_on_cpu(model)
+ assert has_ngram is False
+ assert raw_ngram is None
+
+ pinned = [n for n, m in model.named_modules() if module_is_pinned_on_cpu(m)]
+ assert pinned == [
+ "model.layers.0.ple.ple_embedding.ngram_embedding",
+ "model.layers.1.ple.ple_embedding.ngram_embedding",
+ ]
+ # Sibling / regular projection layers are untouched.
+ assert not module_is_pinned_on_cpu(model.model.layers[0].ple.key_proj)
+
+ def test_module_is_pinned_on_cpu_false_for_plain_module(self):
+ """A module without a CPU-execution hook is not reported as pinned."""
+ import torch.nn as nn
+
+ from auto_round.utils.model import module_is_pinned_on_cpu
+
+ assert module_is_pinned_on_cpu(nn.Linear(4, 4)) is False
+
class TestMvModuleFromGpu:
"""Test mv_module_from_gpu function."""