Skip to content

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

[fix] XPU crash due to circle call of nonzero() and index_select() (#2117)

Xin He28003697d743
diff --git a/.claude/skills/adapt-new-llm/SKILL.md b/.claude/skills/adapt-new-llm/SKILL.md
index 3c9de24e6..782771158 100644
--- a/.claude/skills/adapt-new-llm/SKILL.md
+++ b/.claude/skills/adapt-new-llm/SKILL.md
@@ -152,7 +152,6 @@ BUILTIN_MODULES["your_model_type"] = LazyImport("auto_round.modeling.fused_moe.y
|------------|------|---------|
| `llama4` | `fused_moe/llama4.py` | Custom replacement for no `use_experts_implementation` |
| `deepseek_v2` | `fused_moe/deepseek_v2.py` | q_scale calibration for Gaudi |
-| `qwen3_5_moe` | `fused_moe/qwen3_5_moe.py` | Transformers >= 5.0 support |
| `step3p5` | `fused_moe/step3_5_moe.py` | Splits fused MoELinear |
| `qwen3_omni_moe` | `fused_moe/qwen3_omni.py` | Thinker + talker MoE |
diff --git a/auto_round/modeling/fused_moe/moe_experts_interface.py b/auto_round/modeling/fused_moe/moe_experts_interface.py
index 61d34da42..3cf25784e 100644
--- a/auto_round/modeling/fused_moe/moe_experts_interface.py
+++ b/auto_round/modeling/fused_moe/moe_experts_interface.py
@@ -226,17 +226,35 @@ def linear_loop_experts_forward(
# Get current hidden states for selected samples
selected_hidden_states = hidden_states[token_idx] # (S, hidden_dim)
- # Allocate output tensor
- out_per_sample = torch.zeros(token_idx.size(0), hidden_dim, device=device, dtype=hidden_states.dtype)
-
- # Process each expert
- for expert_idx in range(num_experts):
- # Find samples routed to this expert
- mask = expert_ids == expert_idx
- if not mask.any():
+ # Group token-expert pairs by expert using a single sort, then run each
+ # expert on a contiguous *static* slice, instead of doing a per-expert
+ # nonzero()/boolean-mask lookup inside the Python loop.
+ #
+ # Why: repeatedly issuing dynamic-shape gather kernels (nonzero(),
+ # index_select() or boolean-mask indexing) once per expert in a loop
+ # reliably triggers a driver-level bug on some XPU builds - either a
+ # "vectorized gather kernel index out of bounds" device-side assertion or
+ # a hard UR_RESULT_ERROR_DEVICE_LOST - even when every index is valid.
+ # This was confirmed with minimal PyTorch-only reproductions unrelated to
+ # this model/library, so working around it in application code is the
+ # practical fix. Sorting once needs only two dynamic gather/scatter calls
+ # in total (regardless of num_experts): one index_select to group tokens
+ # by expert, and one index_copy_ to scatter results back to their
+ # original positions. Each expert's slice `permuted[start:end]` is a
+ # plain view (no gather kernel involved), so this is also efficient.
+ sort_order = torch.argsort(expert_ids)
+ permuted_hidden_states = selected_hidden_states.index_select(0, sort_order) # (S, hidden_dim)
+
+ # Per-expert token counts, computed once on host to drive static slicing.
+ counts = torch.bincount(expert_ids, minlength=num_experts).tolist()
+
+ out_permuted = torch.zeros_like(permuted_hidden_states)
+ start = 0
+ for expert_idx, count in enumerate(counts):
+ if count == 0:
continue
-
- expert_input = selected_hidden_states[mask] # (num_samples_for_expert, hidden_dim)
+ end = start + count
+ expert_input = permuted_hidden_states[start:end] # static slice/view, no gather kernel
# Get this expert's container with its projection layers
expert = getattr(self, str(expert_idx))
@@ -253,8 +271,12 @@ def linear_loop_experts_forward(
# Down projection
expert_out = expert.down_proj(gated_out) # (num_samples, hidden_dim)
- # Store results
- out_per_sample[mask] = expert_out.to(out_per_sample.dtype)
+ out_permuted[start:end] = expert_out.to(out_permuted.dtype)
+ start = end
+
+ # Scatter results back to their original (pre-sort) token-expert order.
+ out_per_sample = torch.empty_like(out_permuted)
+ out_per_sample.index_copy_(0, sort_order, out_permuted)
# Apply routing weights
out_per_sample = out_per_sample * sample_weights.unsqueeze(-1) # (S, hidden_dim)
diff --git a/auto_round/modeling/fused_moe/qwen3_5_moe.py b/auto_round/modeling/fused_moe/qwen3_5_moe.py
index 1e15a102e..eb0a2eea3 100644
--- a/auto_round/modeling/fused_moe/qwen3_5_moe.py
+++ b/auto_round/modeling/fused_moe/qwen3_5_moe.py
@@ -1,5 +1,5 @@
-# # Copyright (C) 2026 Intel Corporation
-# # SPDX-License-Identifier: Apache-2.0
+# Copyright (c) 2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
import torch
import torch.nn.functional as F
@@ -8,12 +8,11 @@ from transformers.utils.versions import require_version
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.utils import clear_memory, unsupported_meta_device
require_version("transformers>=5.2.0")
-from auto_round.modeling.fused_moe.utils import _update_parameter
-
class LinearQwen3_5MoeSparseMoeBlock(ReplacementModuleBase):
supports_gguf_fused_moe = True
@@ -30,7 +29,6 @@ class LinearQwen3_5MoeSparseMoeBlock(ReplacementModuleBase):
@classmethod
def original_module_class(cls) -> str:
- """Return the class name of the module this replaces."""
return "Qwen3_5MoeSparseMoeBlock"
def _materialize_weights(self) -> None:
@@ -38,32 +36,8 @@ class LinearQwen3_5MoeSparseMoeBlock(ReplacementModuleBase):
self.experts._materialize_weights(original.experts)
clear_memory()
- def experts_forward(
- self,
- hidden_states: torch.Tensor,
- top_k_index: torch.Tensor,
- top_k_weights: torch.Tensor,
- ) -> torch.Tensor:
- final_hidden_states = torch.zeros_like(hidden_states)
- with torch.no_grad():
- expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
- expert_mask = expert_mask.permute(2, 1, 0)
- expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
-
- for expert_idx in expert_hit:
- expert_idx = expert_idx[0]
- if expert_idx == self.num_experts:
- continue
- top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
- current_state = hidden_states[token_idx]
- # gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
- # current_hidden_states = self.act_fn(gate) * up
- # current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
- current_hidden_states = self.experts[expert_idx](current_state)
- current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
- final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
-
- return final_hidden_states
+ 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)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
batch_size, sequence_length, hidden_dim = hidden_states.shape
@@ -73,19 +47,11 @@ class LinearQwen3_5MoeSparseMoeBlock(ReplacementModuleBase):
expert_output = self.experts_forward(hidden_states_reshaped, selected_experts, routing_weights)
shared_expert_output = F.sigmoid(self.shared_expert_gate(hidden_states_reshaped)) * shared_expert_output
-
expert_output += shared_expert_output
- expert_output = expert_output.reshape(batch_size, sequence_length, hidden_dim)
- return expert_output
+ return expert_output.reshape(batch_size, sequence_length, hidden_dim)
@classmethod
- def from_original(
- cls,
- original,
- config,
- **kwargs,
- ):
- """Create an instance from the original module."""
+ def from_original(cls, original, config, **kwargs):
return cls(original, config)
@@ -114,16 +80,16 @@ class SequentialQwen3_5MoeExperts(torch.nn.ModuleList):
def _materialize_weights(self, original) -> None:
intermediate_size = original.down_proj.shape[-1]
if not unsupported_meta_device(original):
- for i in range(self.num_experts):
- gate_up = original.gate_up_proj[i]
- down = original.down_proj[i]
+ for expert_idx in range(self.num_experts):
+ gate_up = original.gate_up_proj[expert_idx]
+ down = original.down_proj[expert_idx]
gate_proj = gate_up[:intermediate_size, :]
up_proj = gate_up[intermediate_size:, :]
- _update_parameter(self[i].gate_proj, "weight", gate_proj.contiguous())
- _update_parameter(self[i].up_proj, "weight", up_proj.contiguous())
- _update_parameter(self[i].down_proj, "weight", down.contiguous())
+ _update_parameter(self[expert_idx].gate_proj, "weight", gate_proj.contiguous())
+ _update_parameter(self[expert_idx].up_proj, "weight", up_proj.contiguous())
+ _update_parameter(self[expert_idx].down_proj, "weight", down.contiguous())
del gate_up, down, gate_proj, up_proj
- original.to_empty(device="meta") # release original experts parameters
+ original.to_empty(device="meta")
clear_memory()
diff --git a/auto_round/modeling/fused_moe/qwen3_omni.py b/auto_round/modeling/fused_moe/qwen3_omni.py
index 17d3f493d..369e80a75 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
+from auto_round.modeling.fused_moe.utils import _update_parameter, sequential_moe_forward
from auto_round.utils import clear_memory, unsupported_meta_device
# ---------------------------------------------------------------------------
@@ -50,23 +50,7 @@ class LinearQwen3OmniThinkerSparseMoeBlock(ReplacementModuleBase):
clear_memory()
def experts_forward(self, hidden_states, top_k_index, top_k_weights):
- final_hidden_states = torch.zeros_like(hidden_states)
- with torch.no_grad():
- expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
- expert_mask = expert_mask.permute(2, 1, 0)
- expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
-
- for expert_idx in expert_hit:
- expert_idx = expert_idx[0]
- if expert_idx == self.num_experts:
- continue
- top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
- current_state = hidden_states[token_idx]
- current_hidden_states = self.experts[expert_idx](current_state)
- current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
- final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
-
- return final_hidden_states
+ return 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
diff --git a/auto_round/modeling/fused_moe/qwen3_vl_moe.py b/auto_round/modeling/fused_moe/qwen3_vl_moe.py
index 87024dfb8..f1ddeedce 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
+from auto_round.modeling.fused_moe.utils import _update_parameter, sequential_moe_forward
if TYPE_CHECKING:
from transformers import Qwen3VLMoeConfig, Qwen3VLMoeTextConfig
@@ -105,15 +105,9 @@ 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:
- expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
- for expert_idx in expert_hit:
- expert_idx = expert_idx[0]
- if expert_idx == self.num_experts:
- continue
- idx, token_idx = torch.where(expert_mask[expert_idx])
- expert_out = self.experts[expert_idx](hidden_states[token_idx])
- weighted_output = expert_out * routing_weights[token_idx, idx, None]
- next_states.index_add_(0, token_idx, weighted_output.to(hidden_states.dtype))
+ next_states = 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)
if transformers_version < version.parse("5.0"):
diff --git a/auto_round/modeling/fused_moe/replace_modules.py b/auto_round/modeling/fused_moe/replace_modules.py
index d6813f9ac..1276b89e5 100644
--- a/auto_round/modeling/fused_moe/replace_modules.py
+++ b/auto_round/modeling/fused_moe/replace_modules.py
@@ -35,7 +35,7 @@ BUILTIN_MODULES = {
"llama4": LazyImport("auto_round.modeling.fused_moe.llama4"),
# DeepseekV2Attention enables q_scale calibration for deepseek v2 on Gaudi (#1299)
"deepseek_v2": LazyImport("auto_round.modeling.fused_moe.deepseek_v2"),
- # supports transformers >= 5.0.0
+ # Qwen3.5 MoE uses block-local materialization to avoid eagerly unfusing the full model.
"qwen3_5_moe": LazyImport("auto_round.modeling.fused_moe.qwen3_5_moe"),
"qwen3_5_moe_text": LazyImport("auto_round.modeling.fused_moe.qwen3_5_moe"),
# Step 3.5 MoE: splits fused MoELinear into per-expert nn.Linear
diff --git a/auto_round/modeling/fused_moe/step3_5_moe.py b/auto_round/modeling/fused_moe/step3_5_moe.py
index f39cd3897..ae6a47741 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
+from auto_round.modeling.fused_moe.utils import _update_parameter, sequential_moe_forward
from auto_round.utils import clear_memory, unsupported_meta_device
@@ -157,19 +157,9 @@ class LinearStep3p5MoEMLP(ReplacementModuleBase):
routing_weights = routing_weights * self.routed_scaling_factor
- final_hidden_states = torch.zeros(
- (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
+ final_hidden_states = sequential_moe_forward(
+ hidden_states, selected_experts, routing_weights, self.experts, self.num_experts
)
-
- expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
-
- for expert_idx in range(self.num_experts):
- idx, top_x = torch.where(expert_mask[expert_idx])
-
- current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
- current_hidden_states = self.experts[expert_idx](current_state) * routing_weights[top_x, idx, None]
-
- final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
return final_hidden_states
diff --git a/auto_round/modeling/fused_moe/utils.py b/auto_round/modeling/fused_moe/utils.py
index 260cf3cec..05b1ad3d6 100644
--- a/auto_round/modeling/fused_moe/utils.py
+++ b/auto_round/modeling/fused_moe/utils.py
@@ -39,6 +39,78 @@ def is_linearized_layout(original: torch.nn.Module) -> bool:
return all(hasattr(first_expert, attr) for attr in ("gate_proj", "up_proj", "down_proj"))
+def sequential_moe_forward(
+ hidden_states: torch.Tensor,
+ top_k_index: torch.Tensor,
+ top_k_weights: torch.Tensor,
+ experts,
+ num_experts: int,
+) -> torch.Tensor:
+ """Sequential per-expert MoE forward using a single sort to group tokens by expert.
+
+ Repeatedly issuing dynamic-shape gather kernels (``nonzero()``,
+ ``index_select()`` or boolean-mask indexing) once per expert in a Python
+ loop reliably triggers a driver-level bug on some XPU builds - either a
+ "vectorized gather kernel index out of bounds" device-side assertion or a
+ hard ``UR_RESULT_ERROR_DEVICE_LOST`` - even when every index is valid.
+ Sorting once needs only two dynamic gather/scatter calls in total
+ (regardless of ``num_experts``): one ``index_select`` to group tokens by
+ expert, and one ``index_copy_`` to scatter results back to their original
+ positions. Each expert's slice ``permuted[start:end]`` is a plain view (no
+ gather kernel involved), so this is also efficient.
+
+ Args:
+ hidden_states: (num_tokens, hidden_dim) input tensor.
+ top_k_index: (num_tokens, top_k) selected expert indices.
+ top_k_weights: (num_tokens, top_k) routing weights.
+ experts: Indexable collection of per-expert callables (e.g. nn.ModuleList),
+ each taking (num_samples, hidden_dim) and returning (num_samples, hidden_dim).
+ num_experts: Total number of experts.
+
+ Returns:
+ final_hidden_states: (num_tokens, hidden_dim) output tensor.
+ """
+ hidden_dim = hidden_states.size(-1)
+ num_tokens = hidden_states.size(0)
+ top_k = top_k_index.size(-1)
+ device = hidden_states.device
+
+ token_idx = torch.arange(num_tokens, device=device).unsqueeze(1).expand(-1, top_k).reshape(-1) # (S,)
+ sample_weights = top_k_weights.reshape(-1).to(hidden_states.dtype) # (S,)
+ expert_ids = top_k_index.reshape(-1) # (S,)
+
+ selected_hidden_states = hidden_states[token_idx] # (S, hidden_dim)
+
+ sort_order = torch.argsort(expert_ids)
+ permuted_hidden_states = selected_hidden_states.index_select(0, sort_order) # (S, hidden_dim)
+
+ # Per-expert token counts, computed once on host to drive static slicing.
+ counts = torch.bincount(expert_ids, minlength=num_experts).tolist()
+
+ out_permuted = torch.zeros_like(permuted_hidden_states)
+ start = 0
+ for expert_idx, count in enumerate(counts):
+ if count == 0:
+ continue
+ end = start + count
+ expert_input = permuted_hidden_states[start:end] # static slice/view, no gather kernel
+ out_permuted[start:end] = experts[expert_idx](expert_input).to(out_permuted.dtype)
+ start = end
+
+ # Scatter results back to their original (pre-sort) token-expert order.
+ out_per_sample = torch.empty_like(out_permuted)
+ out_per_sample.index_copy_(0, sort_order, out_permuted)
+
+ # Apply routing weights
+ out_per_sample = out_per_sample * sample_weights.unsqueeze(-1) # (S, hidden_dim)
+
+ # Accumulate results using deterministic reshape+sum instead of index_add_
+ # (index_add_ with duplicate indices is non-deterministic on CUDA due to atomicAdd)
+ final_hidden_states = out_per_sample.view(num_tokens, top_k, hidden_dim).sum(dim=1)
+
+ return final_hidden_states
+
+
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/modeling/unfused_moe/deepseek_v3.py b/auto_round/modeling/unfused_moe/deepseek_v3.py
index 749e075b4..80939e620 100644
--- a/auto_round/modeling/unfused_moe/deepseek_v3.py
+++ b/auto_round/modeling/unfused_moe/deepseek_v3.py
@@ -15,6 +15,8 @@
import torch
import torch.nn as nn
+from auto_round.modeling.fused_moe.utils import sequential_moe_forward
+
class LinearDeepseekV3MoE(nn.Module):
"""
@@ -47,27 +49,7 @@ class LinearDeepseekV3MoE(nn.Module):
top_k_index: torch.Tensor,
top_k_weights: torch.Tensor,
) -> torch.Tensor:
- final_hidden_states = torch.zeros_like(hidden_states)
- with torch.no_grad():
- expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
- expert_mask = expert_mask.permute(2, 1, 0)
- expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
-
- for expert_idx in expert_hit:
- expert_idx = expert_idx[0]
- if expert_idx == self.num_experts:
- continue
- top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
- current_state = hidden_states[token_idx]
- # gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
- # current_hidden_states = self.act_fn(gate) * up
- # current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
- expert_layer = self.experts[expert_idx]
- current_hidden_states = expert_layer(current_state)
- current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
- final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
-
- return final_hidden_states
+ return sequential_moe_forward(hidden_states, top_k_index, top_k_weights, self.experts, self.num_experts)
def route_tokens_to_experts(self, router_logits):
router_logits = router_logits.sigmoid()
diff --git a/auto_round/modeling/unfused_moe/ernie4_5_moe.py b/auto_round/modeling/unfused_moe/ernie4_5_moe.py
index 6fc4d9f4c..6f9a638ee 100644
--- a/auto_round/modeling/unfused_moe/ernie4_5_moe.py
+++ b/auto_round/modeling/unfused_moe/ernie4_5_moe.py
@@ -15,6 +15,8 @@
import torch
import torch.nn as nn
+from auto_round.modeling.fused_moe.utils import sequential_moe_forward
+
class LinearErnie4_5_MoeSparseMoeBlock(nn.Module):
def __init__(self, config):
@@ -39,27 +41,7 @@ class LinearErnie4_5_MoeSparseMoeBlock(nn.Module):
top_k_index: torch.Tensor,
top_k_weights: torch.Tensor,
) -> torch.Tensor:
- final_hidden_states = torch.zeros_like(hidden_states)
- with torch.no_grad():
- expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
- expert_mask = expert_mask.permute(2, 1, 0)
- expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
-
- for expert_idx in expert_hit:
- expert_idx = expert_idx[0]
- if expert_idx == self.num_experts:
- continue
- top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
- current_state = hidden_states[token_idx]
- # gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
- # current_hidden_states = self.act_fn(gate) * up
- # current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
- expert_layer = self.experts[expert_idx]
- current_hidden_states = expert_layer(current_state)
- current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
- final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
-
- return final_hidden_states
+ return 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_states.shape
diff --git a/auto_round/modeling/unfused_moe/glm_moe.py b/auto_round/modeling/unfused_moe/glm_moe.py
index 5ef9fcc2c..82267f334 100644
--- a/auto_round/modeling/unfused_moe/glm_moe.py
+++ b/auto_round/modeling/unfused_moe/glm_moe.py
@@ -15,6 +15,8 @@
import torch
import torch.nn as nn
+from auto_round.modeling.fused_moe.utils import sequential_moe_forward
+
class LinearGlm4MoeMoE(nn.Module):
"""
@@ -47,27 +49,7 @@ class LinearGlm4MoeMoE(nn.Module):
top_k_index: torch.Tensor,
top_k_weights: torch.Tensor,
) -> torch.Tensor:
- final_hidden_states = torch.zeros_like(hidden_states)
- with torch.no_grad():
- expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
- expert_mask = expert_mask.permute(2, 1, 0)
- expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
-
- for expert_idx in expert_hit:
- expert_idx = expert_idx[0]
- if expert_idx == self.num_experts:
- continue
- top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
- current_state = hidden_states[token_idx]
- # gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
- # current_hidden_states = self.act_fn(gate) * up
- # current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
- expert_layer = self.experts[expert_idx]
- current_hidden_states = expert_layer(current_state)
- current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
- final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
-
- return final_hidden_states
+ return sequential_moe_forward(hidden_states, top_k_index, top_k_weights, self.experts, self.num_experts)
def route_tokens_to_experts(self, router_logits):
router_logits = router_logits.sigmoid()
diff --git a/auto_round/modeling/unfused_moe/glm_moe_dsa.py b/auto_round/modeling/unfused_moe/glm_moe_dsa.py
index 3a108a8cb..61636fdaa 100644
--- a/auto_round/modeling/unfused_moe/glm_moe_dsa.py
+++ b/auto_round/modeling/unfused_moe/glm_moe_dsa.py
@@ -4,6 +4,8 @@
import torch
import torch.nn as nn
+from auto_round.modeling.fused_moe.utils import sequential_moe_forward
+
class LinearGlmMoeDsaMoE(nn.Module):
"""
@@ -37,27 +39,7 @@ class LinearGlmMoeDsaMoE(nn.Module):
top_k_index: torch.Tensor,
top_k_weights: torch.Tensor,
) -> torch.Tensor:
- final_hidden_states = torch.zeros_like(hidden_states)
- with torch.no_grad():
- expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
- expert_mask = expert_mask.permute(2, 1, 0)
- expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
-
- for expert_idx in expert_hit:
- expert_idx = expert_idx[0]
- if expert_idx == self.num_experts:
- continue
- top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
- current_state = hidden_states[token_idx]
- # gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
- # current_hidden_states = self.act_fn(gate) * up
- # current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
- expert_layer = self.experts[expert_idx]
- current_hidden_states = expert_layer(current_state)
- current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
- final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
-
- return final_hidden_states
+ return sequential_moe_forward(hidden_states, top_k_index, top_k_weights, self.experts, self.num_experts)
def route_tokens_to_experts(self, router_logits):
router_logits = router_logits.sigmoid()
diff --git a/auto_round/modeling/unfused_moe/glm_moe_light.py b/auto_round/modeling/unfused_moe/glm_moe_light.py
index 03814650f..c16b52b56 100644
--- a/auto_round/modeling/unfused_moe/glm_moe_light.py
+++ b/auto_round/modeling/unfused_moe/glm_moe_light.py
@@ -15,6 +15,8 @@
import torch
import torch.nn as nn
+from auto_round.modeling.fused_moe.utils import sequential_moe_forward
+
class LinearGlm4MoeLiteMoE(nn.Module):
"""
@@ -49,27 +51,7 @@ class LinearGlm4MoeLiteMoE(nn.Module):
top_k_weights: torch.Tensor,
) -> torch.Tensor:
""" """
- final_hidden_states = torch.zeros_like(hidden_states)
- with torch.no_grad():
- expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
- expert_mask = expert_mask.permute(2, 1, 0)
- expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
-
- for expert_idx in expert_hit:
- expert_idx = expert_idx[0]
- if expert_idx == self.num_experts:
- continue
- top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
- current_state = hidden_states[token_idx]
- expert_layer = self.experts[expert_idx]
- current_hidden_states = expert_layer(current_state)
- # gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
- # current_hidden_states = self.act_fn(gate) * up
- # current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
- current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
- final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
-
- return final_hidden_states
+ return sequential_moe_forward(hidden_states, top_k_index, top_k_weights, self.experts, self.num_experts)
def route_tokens_to_experts(self, router_logits):
router_logits = router_logits.sigmoid()
diff --git a/auto_round/modeling/unfused_moe/qwen3_moe.py b/auto_round/modeling/unfused_moe/qwen3_moe.py
index e8b9ec673..d1e9d7a39 100644
--- a/auto_round/modeling/unfused_moe/qwen3_moe.py
+++ b/auto_round/modeling/unfused_moe/qwen3_moe.py
@@ -16,6 +16,8 @@ import torch
import torch.nn as nn
from torch.nn import functional as F
+from auto_round.modeling.fused_moe.utils import sequential_moe_forward
+
class LinearQwen3MoeSparseMoeBlock(nn.Module):
def __init__(self, config):
@@ -46,31 +48,8 @@ class LinearQwen3MoeSparseMoeBlock(nn.Module):
# we cast back to the input dtype
routing_weights = routing_weights.to(hidden_states.dtype)
- final_hidden_states = torch.zeros(
- (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
+ final_hidden_states = sequential_moe_forward(
+ hidden_states, selected_experts, routing_weights, self.experts, self.num_experts
)
-
- # One hot encode the selected experts to create an expert mask
- # this will be used to easily index which expert is going to be solicited
- with torch.no_grad():
- expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
-
- # Loop over all available experts in the model and perform the computation on each expert
- expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
- for expert_idx in expert_hit:
- if expert_idx == self.num_experts:
- continue
- expert_layer = self.experts[expert_idx]
- idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
-
- # Index the correct hidden states and compute the expert hidden state for
- # the current expert. We need to make sure to multiply the output hidden
- # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
- current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
- current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
-
- # However `index_add_` only support torch tensors for indexing so we'll use
- # the `top_x` tensor here.
- final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
return final_hidden_states
diff --git a/auto_round/modeling/unfused_moe/qwen3_next.py b/auto_round/modeling/unfused_moe/qwen3_next.py
index dfbda11d7..df0f7a960 100644
--- a/auto_round/modeling/unfused_moe/qwen3_next.py
+++ b/auto_round/modeling/unfused_moe/qwen3_next.py
@@ -16,6 +16,8 @@ import torch
import torch.nn as nn
from torch.nn import functional as F
+from auto_round.modeling.fused_moe.utils import sequential_moe_forward
+
class LinearQwen3NextSparseMoeBlock(nn.Module):
def __init__(self, config):
@@ -49,31 +51,10 @@ class LinearQwen3NextSparseMoeBlock(nn.Module):
# we cast back to the input dtype
routing_weights = routing_weights.to(hidden_states.dtype)
- final_hidden_states = torch.zeros(
- (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
+ final_hidden_states = sequential_moe_forward(
+ hidden_states, selected_experts, routing_weights, self.experts, self.num_experts
)
- # One hot encode the selected experts to create an expert mask
- # this will be used to easily index which expert is going to be sollicitated
- with torch.no_grad():
- expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
-
- # Loop over all available experts in the model and perform the computation on each expert
- expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
- for expert_idx in expert_hit:
- expert_layer = self.experts[expert_idx]
- idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
-
- # Index the correct hidden states and compute the expert hidden state for
- # the current expert. We need to make sure to multiply the output hidden
- # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
- current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
- current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
-
- # However `index_add_` only support torch tensors for indexing so we'll use
- # the `top_x` tensor here.
- final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
-
shared_expert_output = self.shared_expert(hidden_states)
shared_expert_output = F.sigmoid(self.shared_expert_gate(hidden_states)) * shared_expert_output
diff --git a/auto_round/utils/missing_tensors.py b/auto_round/utils/missing_tensors.py
index a25ca10cc..de3fe07f9 100644
--- a/auto_round/utils/missing_tensors.py
+++ b/auto_round/utils/missing_tensors.py
@@ -39,6 +39,7 @@
import json
import os
+import re
from typing import Optional, Tuple
import torch
@@ -62,6 +63,23 @@ _FUSED_EXPERT_PROJ_PATTERNS: dict[str, list[str]] = {
_AUTOROUND_ISSUE_URL = "https://github.com/intel/auto-round/issues"
+def _normalize_tensor_name_for_warning(name: str, numeric_replacement: str = "0") -> str:
+ """Normalize tensor names for warning_once deduplication.
+
+ Replace standalone numeric path segments (e.g. ``layers.12.experts.3``)
+ and bracket indices (e.g. ``layers[12]``) with a fixed placeholder so
+ warning keys are stable across different layer/expert ids.
+ """
+ parts = name.split(".")
+ normalized_parts = []
+ for part in parts:
+ if part.isdigit():
+ normalized_parts.append(numeric_replacement)
+ continue
+ normalized_parts.append(re.sub(r"\[(\d+)\]", f"[{numeric_replacement}]", part))
+ return ".".join(normalized_parts)
+
+
def split_fused_expert_tensors(
tensors_dict: dict[str, torch.Tensor],
) -> dict[str, torch.Tensor]:
@@ -104,6 +122,8 @@ def split_fused_expert_tensors(
result[tensor_name] = tensor
continue
+ warning_tensor_name = _normalize_tensor_name_for_warning(tensor_name)
+
# Strip optional .weight suffix for pattern matching
stripped = tensor_name
stripped = stripped.removesuffix(".weight") # len(".weight") == 7
@@ -123,12 +143,11 @@ def split_fused_expert_tensors(
# The immediate parent must be "experts" or "moe"
if not is_experts_parent and not is_moe_parent:
- logger.warning(
- "Found 3-D tensor '%s' with unsupported parent '%s' while splitting expert tensors; "
+ logger.warning_once(
+ "Found 3-D tensor '%s' while splitting expert tensors; "
"it will be kept unchanged. If this is an MoE/expert weight that should be split/quantized, "
"please open an issue at %s.",
- tensor_name,
- parent,
+ warning_tensor_name,
_AUTOROUND_ISSUE_URL,
)
result[tensor_name] = tensor
@@ -140,8 +159,8 @@ def split_fused_expert_tensors(
if proj_name in _FUSED_EXPERT_PROJ_PATTERNS:
split_names = _FUSED_EXPERT_PROJ_PATTERNS[proj_name]
- logger.info(
- f"Splitting fused expert tensor '{tensor_name}' "
+ logger.warning_once(
+ f"Splitting fused expert tensor '{warning_tensor_name}' "
f"(shape={list(tensor.shape)}, num_experts={num_experts}) "
f"into {split_names}"
)
@@ -152,8 +171,8 @@ def split_fused_expert_tensors(
out_key = f"{target_prefix}.{i}.{split_name}.weight"
result[out_key] = chunk.contiguous()
else:
- logger.info(
- f"Splitting stacked expert tensor '{tensor_name}' "
+ logger.warning_once(
+ f"Splitting stacked expert tensor '{warning_tensor_name}' "
f"(shape={list(tensor.shape)}, num_experts={num_experts})"
)
for i in range(num_experts):
@@ -163,12 +182,6 @@ def split_fused_expert_tensors(
split_count += 1
- if split_count:
- logger.info(
- f"Split {split_count} fused expert tensor(s) into "
- f"{len(result) - (len(tensors_dict) - split_count)} per-expert tensors."
- )
-
return result
diff --git a/test/test_cpu/utils/test_missing_tensors.py b/test/test_cpu/utils/test_missing_tensors.py
index 1528c7e30..8fb371122 100644
--- a/test/test_cpu/utils/test_missing_tensors.py
+++ b/test/test_cpu/utils/test_missing_tensors.py
@@ -21,6 +21,7 @@ import torch
from auto_round.utils.missing_tensors import (
_get_woq_config_from_dir,
+ _normalize_tensor_name_for_warning,
copy_missing_tensors_from_source,
quantize_weight_rtn,
split_fused_expert_tensors,
@@ -77,6 +78,13 @@ def _make_auto_round_config(bits=4, group_size=128, sym=True, block_name_to_quan
class TestSplitFusedExpertTensors:
+ def test_normalize_tensor_name_for_warning(self):
+ name = "model.layers.12.mlp.experts.3.down_proj.weight"
+ assert _normalize_tensor_name_for_warning(name) == "model.layers.0.mlp.experts.0.down_proj.weight"
+
+ bracket_name = "model.layers[12].mlp.experts[3].down_proj.weight"
+ assert _normalize_tensor_name_for_warning(bracket_name) == "model.layers[0].mlp.experts[0].down_proj.weight"
+
def test_2d_and_non_expert_pass_through(self):
"""2-D tensors and 3-D non-expert tensors are returned unchanged."""
tensors = {
@@ -98,7 +106,9 @@ class TestSplitFusedExpertTensors:
result = split_fused_expert_tensors(tensors)
assert set(result.keys()) == set(tensors.keys())
- assert any("unsupported parent" in rec.message and "open an issue" in rec.message for rec in caplog.records)
+ assert any(
+ "while splitting expert tensors" in rec.message and "open an issue" in rec.message for rec in caplog.records
+ )
def test_empty_dict_returns_empty(self):
assert split_fused_expert_tensors({}) == {}