PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
Support general MOE replacement for MOE models (Transformers 5.0 compatible) (#1374)
Liang Lv28839a9a6b1c
diff --git a/auto_round/experimental/qmodules/nvfp4.py b/auto_round/experimental/qmodules/nvfp4.pyindex 88ea577e2..81aea8b54 100644--- a/auto_round/experimental/qmodules/nvfp4.py+++ b/auto_round/experimental/qmodules/nvfp4.py@@ -71,6 +71,7 @@ class NVFP4QuantLinear(QModuleBase):self.config = configself.dtype = dtypeself.pre_dequantized = False+ self._cached_weight = None# Validate dtypeassert (@@ -165,6 +166,12 @@ class NVFP4QuantLinear(QModuleBase):dq_weight = self._dequant_nvfp4_tensor(self.weight_packed, self.weight_scale)return dq_weight+ @property+ def weight(self) -> torch.Tensor:+ if not hasattr(self, "_cached_weight") or self._cached_weight is None:+ self._cached_weight = self.dequant_weight_online()+ return self._cached_weight+def qdq_input(self, activation: torch.Tensor):original_dtype = activation.dtypetemp_qdq_act = _nvfp4_qdq(activation.to(torch.float32), self.config, self.input_global_scale)diff --git a/auto_round/export/export_to_autoround/export_to_nvfp_mxfp.py b/auto_round/export/export_to_autoround/export_to_nvfp_mxfp.pyindex 1320846dc..186eea053 100644--- a/auto_round/export/export_to_autoround/export_to_nvfp_mxfp.py+++ b/auto_round/export/export_to_autoround/export_to_nvfp_mxfp.py@@ -175,6 +175,12 @@ def save_quantized_as_fp(set_module(model, n, orig_layer)if is_nv_fp(act_data_type) and "static_gs" in str(act_data_type).lower():+ # Ensure all MOE layers have act_max set (needed after deep copy or for uncalibrated layers)+ from auto_round.utils.model import is_moe_model, set_amax_for_all_moe_layers++ if is_moe_model(model):+ set_amax_for_all_moe_layers(model)+# generate static input_global_scalefor n, m in model.named_modules():if type(m) in SUPPORTED_LAYER_TYPES:diff --git a/auto_round/export/utils.py b/auto_round/export/utils.pyindex 6f9490dad..42e6b4f9e 100644--- a/auto_round/export/utils.py+++ b/auto_round/export/utils.py@@ -19,6 +19,59 @@ import torch.nn as nnfrom auto_round.utils import copy_python_files_from_model_cache, logger, unsupported_meta_device+def _has_unfused_moe_experts(model: nn.Module) -> bool:+ """Check if model has unfused MOE experts (nn.ModuleList instead of 3D Parameter).++ This is used to detect if we need to bypass transformers' weight conversion+ during save_pretrained.+ """+ for module in model.modules():+ if hasattr(module, "gate_up_proj") and isinstance(module.gate_up_proj, nn.ModuleList):+ if hasattr(module, "down_proj") and isinstance(module.down_proj, nn.ModuleList):+ return True+ return False+++def _save_model_state_dict(+ model: nn.Module,+ save_dir: str,+ max_shard_size: str = "5GB",+ safe_serialization: bool = True,+):+ """Save model using state_dict directly, bypassing transformers' weight conversion.++ This is needed for models with unfused MOE experts where transformers'+ revert_weight_conversion expects 3D tensor format but we have ModuleList.+ """+ import torch+ from safetensors.torch import save_file++ os.makedirs(save_dir, exist_ok=True)++ # Save config+ if hasattr(model, "config") and model.config is not None:+ model.config.save_pretrained(save_dir)++ if hasattr(model, "generation_config") and model.generation_config is not None:+ try:+ model.generation_config.save_pretrained(save_dir)+ except Exception:+ pass # generation_config save can fail for some models++ # Get state dict+ state_dict = model.state_dict()++ # Save weights+ if safe_serialization:+ # Save as safetensors+ weights_file = os.path.join(save_dir, "model.safetensors")+ save_file(state_dict, weights_file)+ else:+ # Save as pytorch bin+ weights_file = os.path.join(save_dir, "pytorch_model.bin")+ torch.save(state_dict, weights_file)++def save_model(model: nn.Module,save_dir: str,@@ -47,12 +100,22 @@ def save_model(Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`)."""os.makedirs(save_dir, exist_ok=True)++ # Check if model has unfused MOE experts - if so, we need to bypass transformers'+ # weight conversion which expects original 3D tensor format+ has_unfused_experts = _has_unfused_moe_experts(model)+if unsupported_meta_device(model):if hasattr(model, "config") and model.config is not None:model.config.save_pretrained(save_dir)if hasattr(model, "generation_config") and model.generation_config is not None:model.generation_config.save_pretrained(save_dir)+ elif has_unfused_experts:+ # For models with unfused MOE experts, save state_dict directly to avoid+ # transformers' revert_weight_conversion which expects 3D tensor format+ logger.info("Saving model with unfused MOE experts using state_dict (bypassing weight conversion)")+ _save_model_state_dict(model, save_dir, max_shard_size, safe_serialization)else:try:model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)@@ -68,6 +131,7 @@ def save_model(data["torch_dtype"] = str(dtype).split(".")[-1]with open(config_path, "w") as file:json.dump(data, file, indent=2)+config_file = "quantization_config.json"if hasattr(model, "config") and hasattr(model.config, "quantization_config"):with open(os.path.join(save_dir, config_file), "w", encoding="utf-8") as f:diff --git a/auto_round/modeling/fused_moe/__init__.py b/auto_round/modeling/fused_moe/__init__.pyindex 14a492441..deacabb31 100644--- a/auto_round/modeling/fused_moe/__init__.py+++ b/auto_round/modeling/fused_moe/__init__.py@@ -11,3 +11,28 @@# 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.++from auto_round.modeling.fused_moe.replace_modules import (+ ReplacementModuleBase,+ apply_replacements,+ materialize_model_,+ release_original_module_,+)+from auto_round.modeling.fused_moe.moe_experts_interface import (+ is_linear_loop_available,+ linear_loop_experts_forward,+ prepare_model_for_moe_quantization,+ register_linear_loop_experts,+)++__all__ = [+ "ReplacementModuleBase",+ "apply_replacements",+ "materialize_model_",+ "release_original_module_",+ # Transformers-native MOE integration (transformers 5.0+)+ "linear_loop_experts_forward",+ "register_linear_loop_experts",+ "prepare_model_for_moe_quantization",+ "is_linear_loop_available",+]diff --git a/auto_round/modeling/fused_moe/moe_experts_interface.py b/auto_round/modeling/fused_moe/moe_experts_interface.pynew file mode 100644index 000000000..aaef9ab8b--- /dev/null+++ b/auto_round/modeling/fused_moe/moe_experts_interface.py@@ -0,0 +1,447 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""+Custom experts implementation for transformers' MOE integration.++This module provides a `linear_loop` experts implementation that uses+individual nn.Linear layers per expert instead of fused 3D Parameters.+This enables proper quantization of MOE expert weights.++The implementation integrates with transformers' `use_experts_implementation`+decorator and `ALL_EXPERTS_FUNCTIONS` registry.++Usage:++ from auto_round.modeling.fused_moe.moe_experts_interface import prepare_model_for_moe_quantization+ # Before quantization+ prepare_model_for_moe_quantization(model)++ # Now the model uses linear_loop forward which supports quantized nn.Linear layers+"""++import torch+from torch import nn++from auto_round.utils import clear_memory, logger++try:+ from transformers.integrations.moe import ALL_EXPERTS_FUNCTIONS++ HAS_EXPERTS_INTERFACE = True+except ImportError:+ HAS_EXPERTS_INTERFACE = False+ ALL_EXPERTS_FUNCTIONS = None++# Expert implementation name - change this if transformers want to use a different name+LINEAR_LOOP_IMPL = "linear_loop"++# Known expert projection patterns for reference+# These are used as hints when auto-detection needs to infer projection properties+# Format: proj_name -> {"is_input_proj": bool, "output_multiplier": int}+# is_input_proj: True if takes hidden_dim as input, False if takes intermediate_dim+# output_multiplier: output dimension multiplier (e.g., 2 for fused gate+up projection)+KNOWN_PROJECTION_PATTERNS = {+ # Transformers 5.0+ standard (Qwen3-MoE, etc.)+ "gate_up_proj": {"is_input_proj": True, "output_multiplier": 2}, # hidden -> 2*intermediate+ "down_proj": {"is_input_proj": False, "output_multiplier": 1}, # intermediate -> hidden+ # Mixtral-style+ "w1": {"is_input_proj": True, "output_multiplier": 1}, # gate: hidden -> intermediate+ "w2": {"is_input_proj": False, "output_multiplier": 1}, # down: intermediate -> hidden+ "w3": {"is_input_proj": True, "output_multiplier": 1}, # up: hidden -> intermediate+ # DBRX-style+ "v1": {"is_input_proj": True, "output_multiplier": 1},+ "w1_proj": {"is_input_proj": True, "output_multiplier": 1},+ "w2_proj": {"is_input_proj": False, "output_multiplier": 1},+}+++def linear_loop_experts_forward(+ self: nn.Module,+ hidden_states: torch.Tensor,+ top_k_index: torch.Tensor,+ top_k_weights: torch.Tensor,+) -> torch.Tensor:+ """Forward using individual nn.Linear layers per expert.++ This implementation loops over experts and uses self.gate_up_proj[i] and+ self.down_proj[i] as nn.Linear layers (or quantized equivalents), enabling+ proper quantization support.++ Expected module attributes:+ - gate_up_proj: nn.ModuleList of nn.Linear (in_features=hidden_dim, out_features=2*intermediate_dim)+ - down_proj: nn.ModuleList of nn.Linear (in_features=intermediate_dim, out_features=hidden_dim)+ - act_fn: activation function+ - num_experts: number of experts+ - _apply_gate: optional custom gating function++ Args:+ self: The experts module+ hidden_states: Input tensor of shape (num_tokens, hidden_dim)+ top_k_index: Selected expert indices of shape (num_tokens, top_k)+ top_k_weights: Expert weights of shape (num_tokens, top_k)++ Returns:+ final_hidden_states: Output tensor of shape (num_tokens, hidden_dim)+ """+ logger.debug(f"Using {LINEAR_LOOP_IMPL} experts forward for {self.__class__.__name__}")++ # Handle [batch_size, seq_len, hidden_dim] input format+ if hidden_states.dim() == 3:+ batch_size, seq_len, hidden_dim = hidden_states.shape+ hidden_states = hidden_states.view(-1, hidden_dim) # [bs * seq_len, hidden_dim]+ top_k_index = top_k_index.view(-1, top_k_index.size(-1)) # [bs * seq_len, top_k]+ top_k_weights = top_k_weights.view(-1, top_k_weights.size(-1)) # [bs * seq_len, top_k]+ else:+ batch_size, seq_len = None, None+ hidden_dim = hidden_states.size(-1)++ device = hidden_states.device+ num_top_k = top_k_index.size(-1)+ num_tokens = hidden_states.size(0)+ num_experts = self.num_experts++ # Reshape for easier indexing+ # S is the number of selected token-expert pairs (S = num_tokens * num_top_k)+ token_idx = torch.arange(num_tokens, device=device).unsqueeze(1).expand(-1, num_top_k).reshape(-1) # (S,)+ sample_weights = top_k_weights.reshape(-1).to(hidden_states.dtype) # (S,)+ expert_ids = top_k_index.reshape(-1) # (S,)++ # 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():+ continue++ expert_input = selected_hidden_states[mask] # (num_samples_for_expert, hidden_dim)++ # Use nn.Linear layers for this expert+ gate_up_out = self.gate_up_proj[expert_idx](expert_input) # (num_samples, 2*intermediate_dim)++ # Apply gating+ if hasattr(self, "_apply_gate"):+ gated_out = self._apply_gate(gate_up_out) # (num_samples, intermediate_dim)+ else:+ gate, up = gate_up_out.chunk(2, dim=-1)+ gated_out = self.act_fn(gate) * up++ # Down projection+ expert_out = self.down_proj[expert_idx](gated_out) # (num_samples, hidden_dim)++ # Store results+ out_per_sample[mask] = expert_out.to(out_per_sample.dtype)++ # Apply routing weights+ out_per_sample = out_per_sample * sample_weights.unsqueeze(-1) # (S, hidden_dim)++ # Accumulate results using deterministic reshape+sum instead of index_add_+ # (index_add_ with duplicate indices is non-deterministic on CUDA due to atomicAdd)+ final_hidden_states = out_per_sample.view(num_tokens, num_top_k, hidden_dim).sum(dim=1)++ # Reshape back to original format if input was [batch_size, seq_len, hidden_dim]+ if batch_size is not None:+ final_hidden_states = final_hidden_states.view(batch_size, seq_len, hidden_dim)++ return final_hidden_states+++def register_linear_loop_experts() -> bool:+ """Register the linear_loop experts implementation with transformers.++ Returns:+ True if registration was successful, False otherwise.+ """+ if not HAS_EXPERTS_INTERFACE:+ logger.warning(+ "transformers.integrations.moe.ALL_EXPERTS_FUNCTIONS not available. "+ "linear_loop experts implementation not registered. "+ "Requires transformers >= 5.0.0"+ )+ return False++ 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")++ return True+++def _experts_supports_decorator(module: nn.Module) -> bool:+ """Check if experts module supports @use_experts_implementation decorator.++ Only experts classes decorated with @use_experts_implementation will use+ our linear_loop forward. Others need full module replacement.+ """+ forward_method = getattr(module.__class__, "forward", None)+ if forward_method is None:+ return False+ # @use_experts_implementation sets __wrapped__ on the decorated method+ return hasattr(forward_method, "__wrapped__")+++def _detect_expert_projections(module: nn.Module) -> dict[str, dict]:+ """Detect which expert projections exist in the module.++ This function scans the module for any 3D nn.Parameter attributes.+ It first checks known projection names, then discovers any unknown 3D parameters.++ Returns:+ Dict mapping projection names to their config, only for projections that exist+ as 3D nn.Parameter in the module.+ """+ detected = {}++ # First, check known projection patterns+ for proj_name, config in KNOWN_PROJECTION_PATTERNS.items():+ param = getattr(module, proj_name, None)+ if param is not None and isinstance(param, nn.Parameter) and param.dim() == 3:+ detected[proj_name] = config++ # If no known patterns found, scan for any 3D Parameter (future-proofing)+ if not detected:+ for attr_name in dir(module):+ if attr_name.startswith("_"):+ continue+ param = getattr(module, attr_name, None)+ if param is not None and isinstance(param, nn.Parameter) and param.dim() == 3:+ # Use default config for unknown projections+ logger.debug(f"Discovered unknown 3D projection: {attr_name}")+ detected[attr_name] = {"is_input_proj": True, "output_multiplier": 1}++ return detected+++def _infer_dimensions(param: nn.Parameter, config: dict, is_transposed: bool) -> tuple[int, int]:+ """Infer input and output dimensions for a projection.++ Args:+ param: The 3D parameter (num_experts, dim1, dim2)+ config: Projection config with is_input_proj and output_multiplier+ is_transposed: Whether weights are stored transposed++ Returns:+ (in_features, out_features) for the Linear layer+ """+ dim1, dim2 = param.shape[1], param.shape[2]+ multiplier = config.get("output_multiplier", 1)++ if is_transposed:+ # transposed: (num_experts, in_features, out_features)+ in_features, out_features = dim1, dim2+ else:+ # not transposed: (num_experts, out_features, in_features)+ out_features, in_features = dim1, dim2++ # Adjust for multiplier (e.g., gate_up has 2x intermediate)+ if multiplier > 1:+ out_features = out_features // multiplier * multiplier # ensure divisible++ return in_features, out_features+++def _unfuse_single_projection(+ module: nn.Module,+ proj_name: str,+ num_experts: int,+ is_transposed: bool,+ dtype: torch.dtype,+ target_device: torch.device,+) -> nn.ModuleList | None:+ """Unfuse a single projection from 3D Parameter to ModuleList of Linear layers.++ Args:+ module: The experts module+ proj_name: Name of the projection attribute+ num_experts: Number of experts+ is_transposed: Whether weights are stored transposed+ dtype: Data type for the Linear layers+ target_device: Device for the Linear layers++ Returns:+ ModuleList of Linear layers, or None if projection doesn't exist+ """+ param = getattr(module, proj_name, None)+ if param is None or not isinstance(param, nn.Parameter) or param.dim() != 3:+ return None++ # Get projection config+ config = KNOWN_PROJECTION_PATTERNS.get(proj_name, {"is_input_proj": True, "output_multiplier": 1})++ # Infer dimensions+ in_features, out_features = _infer_dimensions(param, config, is_transposed)++ # Check for bias+ bias_name = f"{proj_name}_bias"+ bias_param = getattr(module, bias_name, None)+ has_bias = bias_param is not None++ # Create ModuleList+ linears = nn.ModuleList()+ source_device = param.device++ for i in range(num_experts):+ linear = nn.Linear(in_features, out_features, bias=has_bias, dtype=dtype, device=target_device)++ # Copy weights if not on meta device+ if source_device.type != "meta":+ if is_transposed:+ linear.weight.data.copy_(param[i].t())+ else:+ linear.weight.data.copy_(param[i])++ if has_bias:+ linear.bias.data.copy_(bias_param[i])++ linears.append(linear)++ # Release original parameter memory using to_empty+ if source_device.type != "meta":+ try:+ param.data = param.data.to_empty(device="meta")+ logger.debug(f"Released memory for {proj_name} using to_empty(device='meta')")+ except Exception:+ # Fallback: just delete+ pass++ return linears+++def _unfuse_experts_weights_inplace(+ module: nn.Module,+ check_decorator: bool = True,+ projection_names: list[str] | None = None,+) -> bool:+ """Convert fused 3D expert weights to nn.ModuleList of nn.Linear layers.++ This function modifies the module in-place, replacing fused 3D Parameters+ with nn.ModuleList[nn.Linear] for each detected projection.++ Args:+ module: The experts module to unfuse+ check_decorator: If True, only unfuse if the module supports+ @use_experts_implementation decorator. Default is True.+ projection_names: Optional list of projection names to unfuse.+ If None, auto-detects from KNOWN_PROJECTION_PATTERNS.++ Returns:+ True if unfusing was successful, False if module doesn't match pattern+ """+ # Detect available projections+ if projection_names:+ detected_projections = {+ name: config for name, config in KNOWN_PROJECTION_PATTERNS.items() if name in projection_names+ }+ else:+ detected_projections = _detect_expert_projections(module)++ if not detected_projections:+ return False++ # Only unfuse if the module supports the decorator (unless check_decorator is False)+ if check_decorator and not _experts_supports_decorator(module):+ logger.debug(f"Skipping unfuse for {module.__class__.__name__}: does not support @use_experts_implementation")+ return False++ # Get first projection to determine num_experts and layout+ first_proj_name = next(iter(detected_projections))+ first_param = getattr(module, first_proj_name)+ num_experts = first_param.shape[0]++ # Detect if transposed+ is_transposed = getattr(module, "is_transposed", None)+ if is_transposed is None:+ # Infer from shape: typically hidden_dim < intermediate_dim+ dim1, dim2 = first_param.shape[1], first_param.shape[2]+ is_transposed = dim1 < dim2++ dtype = first_param.dtype+ target_device = first_param.device if first_param.device.type != "meta" else "cpu"++ # Unfuse each projection+ unfused_count = 0+ for proj_name in detected_projections:+ linears = _unfuse_single_projection(module, proj_name, num_experts, is_transposed, dtype, target_device)+ if linears is not None:+ # Delete original parameter and set new ModuleList+ delattr(module, proj_name)+ setattr(module, proj_name, linears)+ unfused_count += 1+ logger.debug(f"Unfused {proj_name}: {num_experts} experts")++ # Ensure num_experts is set+ if not hasattr(module, "num_experts"):+ module.num_experts = num_experts++ return unfused_count > 0+++def prepare_model_for_moe_quantization(model: nn.Module, implementation: str = LINEAR_LOOP_IMPL) -> list[str]:+ """Prepare a model for MOE quantization using transformers' experts interface.++ This function:+ 1. Registers the linear_loop experts implementation with transformers+ 2. Sets model.config._experts_implementation = implementation+ 3. Unfuses all fused MOE expert weights into nn.ModuleList[nn.Linear]++ After calling this function, the model's forward pass will use individual+ nn.Linear layers per expert, which can be quantized normally.++ Args:+ model: The model to prepare+ implementation: The experts implementation to use (default: "linear_loop")++ Returns:+ List of module names that were unfused+ """+ # Register our custom implementation+ if not register_linear_loop_experts():+ raise RuntimeError(+ "Failed to register linear_loop experts implementation. "+ "This requires transformers >= 5.0.0 with MOE integration support."+ )++ # Unfuse all fused experts modules (only those supporting @use_experts_implementation)+ unfused_modules = []+ for name, module in model.named_modules():+ if _unfuse_experts_weights_inplace(module):+ unfused_modules.append(name)+ logger.debug(f"Unfused expert weights in: {name}")++ # Only set config if we actually unfused something+ # Models that don't support the decorator (like Llama4) won't have anything unfused+ # and should use full module replacement instead+ if unfused_modules:+ logger.info(f"Unfused {len(unfused_modules)} MOE experts modules for quantization")+ clear_memory()++ # Set config for linear_loop forward+ if hasattr(model, "config"):+ saved_impl = getattr(model.config, "experts_implementation", None)+ impl_to_set = saved_impl if saved_impl else implementation+ model.config._experts_implementation = impl_to_set+ logger.debug(f"Set model.config._experts_implementation = '{impl_to_set}'")++ return unfused_modules+++def is_linear_loop_available() -> bool:+ """Check if linear_loop experts implementation is available."""+ return HAS_EXPERTS_INTERFACEdiff --git a/auto_round/modeling/fused_moe/replace_modules.py b/auto_round/modeling/fused_moe/replace_modules.pyindex 66222f414..06845e93c 100644--- a/auto_round/modeling/fused_moe/replace_modules.py+++ b/auto_round/modeling/fused_moe/replace_modules.py@@ -20,6 +20,8 @@ import torchfrom tqdm import tqdmfrom transformers import PreTrainedModel+# Import constant for expert implementation name+from auto_round.modeling.fused_moe.moe_experts_interface import LINEAR_LOOP_IMPLfrom auto_round.utils import LazyImport, dump_mem_usage, dump_memory_usage_ctx, global_state, loggerBUILTIN_MODULES = {@@ -30,6 +32,55 @@ BUILTIN_MODULES = {}+def _has_custom_replacement_only(model: torch.nn.Module) -> bool:+ """Check if all MOE-like modules in model have custom replacements registered.++ If all MOE modules are covered by BUILTIN_MODULES, we can skip the linear_loop path entirely.+ """+ for _, module in model.named_modules():+ class_name = module.__class__.__name__+ # Check if this looks like an MOE experts module (has fused 3D weights)+ if (+ hasattr(module, "gate_up_proj")+ and isinstance(module.gate_up_proj, torch.nn.Parameter)+ and module.gate_up_proj.dim() == 3+ ):+ # This is a fused experts module - check if it has a custom replacement+ if class_name not in BUILTIN_MODULES and not ReplacementModuleBase.is_registered(class_name):+ # Found a fused experts module without custom replacement - need linear_loop+ return False+ return True+++def _handle_moe_modules(model: torch.nn.Module) -> list[str]:+ """Handle fused MOE modules using transformers' linear_loop backend.++ Args:+ model: The model to process++ Returns:+ List of module names that were processed+ """+ from auto_round.modeling.fused_moe.moe_experts_interface import (+ is_linear_loop_available,+ prepare_model_for_moe_quantization,+ )++ if not is_linear_loop_available():+ logger.warning(+ "transformers' linear_loop experts interface not available (requires transformers 5.0+). "+ "MOE modules with @use_experts_implementation decorator will fall back to custom replacements "+ "if registered."+ )+ return []++ # Use transformers' experts interface+ unfused = prepare_model_for_moe_quantization(model)+ if unfused:+ logger.info(f"Prepared {len(unfused)} MOE modules for quantization")+ return unfused++def _import_required_replacements(model: torch.nn.Module) -> None:"""Scan model and trigger lazy imports for registered replacement modules."""imported = set()@@ -44,6 +95,33 @@ def _import_required_replacements(model: torch.nn.Module) -> None:logger.debug(f"Loaded replacement module for {class_name}")+def _should_skip_moe_replacement(module: torch.nn.Module, model: torch.nn.Module) -> bool:+ """Skip MOE replacement if linear_loop experts are already unfused.++ This is only true when:+ 1. model.config._experts_implementation == "linear_loop" (set by prepare_model_for_moe_quantization)+ 2. The experts' gate_up_proj and down_proj are already nn.ModuleList++ Note: _experts_implementation is only set when the experts class supports+ @use_experts_implementation decorator, so we don't need to check that again here.+ """+ if not hasattr(model, "config"):+ return False+ if getattr(model.config, "_experts_implementation", None) != LINEAR_LOOP_IMPL:+ return False+ experts = getattr(module, "experts", None)+ if experts is None:+ return False+ gate_up = getattr(experts, "gate_up_proj", None)+ down = getattr(experts, "down_proj", None)+ result = isinstance(gate_up, torch.nn.ModuleList) and isinstance(down, torch.nn.ModuleList)+ logger.debug(+ f"_should_skip_moe_replacement for {module.__class__.__name__}: "+ f"gate_up type={type(gate_up).__name__}, down type={type(down).__name__}, skip={result}"+ )+ return result++@dump_mem_usage("Materializing model", log_level="debug")def materialize_model_(model: torch.nn.Module) -> None:def _materialize_module(module: torch.nn.Module) -> None:@@ -219,6 +297,7 @@ class ReplacementModuleBase(ABC, torch.nn.Module):def apply_replacements(model: torch.nn.Module,+ auto_detect_moe: bool = True,) -> torch.nn.Module:"""Function to apply module replacements to a model.@@ -230,11 +309,19 @@ def apply_replacements(Args:model: The model to apply module replacement to (modified in-place).+ auto_detect_moe: If True, automatically detect and handle fused MOE modules+ (transformers 5.0+ pattern). Default is True.Returns:The model with modules replaced."""_import_required_replacements(model)++ # Auto-detect and handle fused MOE modules if enabled+ # Skip if all MOE modules already have custom replacements registered+ if auto_detect_moe and not _has_custom_replacement_only(model):+ _handle_moe_modules(model)+replaced = []# Step 1: Collect all modules that need replacement@@ -245,6 +332,9 @@ def apply_replacements(if isinstance(module, ReplacementModuleBase):continueclass_name = module.__class__.__name__+ if class_name in BUILTIN_MODULES and _should_skip_moe_replacement(module, model):+ logger.debug(f"Skipping replacement for {name}: linear_loop experts already unfused")+ continueif ReplacementModuleBase.is_registered(class_name) and ReplacementModuleBase.get_replacement_class(class_name).is_to_be_replaced(module):@@ -255,8 +345,18 @@ def apply_replacements(logger.info(f"Found {len(modules_to_replace)} modules to replace")for name, module, class_name in tqdm(modules_to_replace, desc="Replacing modules"):module = model.get_submodule(name)+ # The module might have been replaced earlier in the loop (parent-first replacement).+ # Skip if the class has changed or it no longer matches replacement criteria.+ if module.__class__.__name__ != class_name:+ logger.debug(+ f"Skipping replacement for {name}: class changed from {class_name} to {module.__class__.__name__}"+ )+ continuewith dump_memory_usage_ctx(f"Replacing module {name}", log_level="debug"):replacement_cls = ReplacementModuleBase.get_replacement_class(class_name)+ if not replacement_cls.is_to_be_replaced(module):+ logger.debug(f"Skipping replacement for {name}: no longer matches replacement criteria")+ continuereplacement = replacement_cls.from_original(module,model.config,diff --git a/auto_round/utils/model.py b/auto_round/utils/model.pyindex 513d23e68..7ce80a5cd 100644--- a/auto_round/utils/model.py+++ b/auto_round/utils/model.py@@ -1122,34 +1122,65 @@ def set_amax_for_uncalibrated_experts(uncalibrated_experts: a list of uncalibrated experts"""uncalibrated_experts = []++ def _get_attr(module, name):+ """Get attribute from module or its orig_layer."""+ if hasattr(module, name):+ return getattr(module, name)+ if hasattr(module, "orig_layer") and hasattr(module.orig_layer, name):+ return getattr(module.orig_layer, name)+ return None++ def _get_amax_value(module):+ value = get_nested_attr(module, attr_name)+ if value is None and hasattr(module, "orig_layer"):+ value = get_nested_attr(module.orig_layer, attr_name)+ return value+# get the max amax value from all expertsif set_amax_value is None:- amax_values = [- get_nested_attr(module, attr_name) for module in experts if get_nested_attr(module, attr_name) is not None- ]+ amax_values = [_get_amax_value(m) for m in experts if _get_amax_value(m) is not None]if len(amax_values) == 0:+ # Check if any expert actually needs act_max (act_bits < 8, not dynamic, not already quantized)+ sample = next((m for m in experts if m is not None), None)+ if sample is not None:+ act_bits = _get_attr(sample, "act_bits")+ act_dynamic = _get_attr(sample, "act_dynamic")+ is_quantized = "Quant" in sample.__class__.__name__ or hasattr(sample, "is_mx")+ needs_warning = (+ not is_quantized and isinstance(act_bits, (int, float)) and act_bits < 8 and not act_dynamic+ )+ if needs_warning:+ logger.warning_once(+ f"All {len(experts)} expert layers are missing '{attr_name}' values. "+ f"This may indicate calibration hooks were not attached to expert layers."+ )return uncalibrated_experts- # Flatten all tensors to 1D before concatenation- flat_values = [t.reshape(-1) for t in amax_values]- all_values = torch.cat(flat_values)- set_amax_value = torch.max(all_values)+ else:+ # Flatten all tensors to 1D before concatenation+ flat_values = [t.reshape(-1) for t in amax_values]+ all_values = torch.cat(flat_values)+ set_amax_value = torch.max(all_values)for module in experts:- current_amax = get_nested_attr(module, attr_name)+ current_amax = _get_amax_value(module)# Set amax if it's None (uncalibrated) OR if unify_all is Trueif current_amax is None or unify_all:- if current_amax is None:- logger.warning_once(- "Missing amax value of expert layers."- "This typically occurs in MoE models when certain experts are not activated during calibration. "- "Consider increasing your calibration dataset size to ensure all experts are exercised."- )# Use float32 dtype explicitly to ensure we create a floating point tensorif not isinstance(set_amax_value, torch.Tensor):set_amax_value = torch.tensor(set_amax_value, dtype=torch.float32)- set_nested_attr(module, attr_name, set_amax_value)- # uncalibrated_experts.append(module)+ set_nested_attr(module, attr_name, set_amax_value.clone())+ if current_amax is None:+ uncalibrated_experts.append(module)++ if uncalibrated_experts:+ logger.info_once(+ f"Found {len(uncalibrated_experts)} uncalibrated expert layers. "+ "Using max amax from calibrated experts to fill missing values. "+ )++ return uncalibrated_experts# Please refer to: https://github.com/NVIDIA/TensorRT-Model-Optimizer/blob/@@ -1166,13 +1197,31 @@ def set_amax_for_all_moe_layers(model: torch.nn.Module, layer_name=None, attr_nafor name, sub_module in model.named_modules():if not (is_moe_layer(sub_module) and hasattr(sub_module, "experts")):continue++ # Handle router (gate) layer - it's a Linear layer used for token routing+ # It needs act_max for quantization but may not be calibrated if it wasn't exercised+ _set_amax_for_moe_auxiliary_layers(sub_module, attr_name=attr_name)+expert_linear_names = get_expert_linear_names(sub_module)# Get input projection names for FP8 dispatch unificationexpert_input_proj_names = get_expert_input_proj_names(sub_module)- for linear_name in expert_linear_names:- if isinstance(sub_module.experts, collections.abc.Iterable):- # For other MoE models (like Mixtral) with iterable experts+ # Check experts structure and handle accordingly+ if _is_unfused_experts_module(sub_module.experts):+ # Unfused experts: gate_up_proj/down_proj are nn.ModuleList+ _set_amax_for_unfused_experts(sub_module.experts, attr_name=attr_name)+ elif _is_fused_experts_module(sub_module.experts):+ # Fused experts: 3D Parameters (e.g., DeepseekV2Experts)+ # For fused experts, act_max is set on the parent MOE module, not individual experts+ # Skip processing here as they don't have individual Linear layers to calibrate+ logger.debug(+ f"Skipping act_max setting for fused experts module '{name}': "+ f"fused experts use parent module's act_max"+ )+ continue+ elif isinstance(sub_module.experts, collections.abc.Iterable):+ # Iterable experts: list of expert modules (e.g., Mixtral)+ for linear_name in expert_linear_names:try:# Determine if this is an input projection that needs scale unificationunify_scale = linear_name in expert_input_proj_names and envs.AR_ENABLE_UNIFY_MOE_INPUT_SCALE@@ -1194,12 +1243,153 @@ def set_amax_for_all_moe_layers(model: torch.nn.Module, layer_name=None, attr_naf"to be updated for this model architecture. "f"Original error: {e}") from e- else:- # Unsupported MoE model structure- raise NotImplementedError(- f"MoE model with experts type '{type(sub_module.experts).__name__}' is not supported in export."- f"Please file an issue or add support for this model architecture."- )+ else:+ # Unknown experts structure+ logger.warning(+ f"Unknown experts structure in '{name}': type={type(sub_module.experts).__name__}. "+ f"Skipping act_max setting. This may cause issues during export."+ )+++def _is_unfused_experts_module(module: torch.nn.Module) -> bool:+ """Check if the module is an unfused experts module (has ModuleList gate_up_proj/down_proj)."""+ if not hasattr(module, "gate_up_proj") or not hasattr(module, "down_proj"):+ return False+ return isinstance(module.gate_up_proj, torch.nn.ModuleList) and isinstance(module.down_proj, torch.nn.ModuleList)+++def _is_fused_experts_module(module: torch.nn.Module) -> bool:+ """Check if the module is a fused experts module (has 3D Parameter gate_up_proj/down_proj)."""+ if not hasattr(module, "gate_up_proj") or not hasattr(module, "down_proj"):+ return False+ return (+ isinstance(module.gate_up_proj, torch.nn.Parameter)+ and isinstance(module.down_proj, torch.nn.Parameter)+ and module.gate_up_proj.dim() == 3+ and module.down_proj.dim() == 3+ )+++def _set_amax_for_unfused_experts(experts_module: torch.nn.Module, attr_name: str = "act_max"):+ """Set amax for unfused experts module with ModuleList attributes.++ This handles experts modules that have been unfused to have:+ - gate_up_proj: nn.ModuleList of nn.Linear (input projections, unified scale)+ - down_proj: nn.ModuleList of nn.Linear (output projections)+ """+ if hasattr(experts_module, "gate_up_proj") and isinstance(experts_module.gate_up_proj, torch.nn.ModuleList):+ unify_scale = envs.AR_ENABLE_UNIFY_MOE_INPUT_SCALE+ set_amax_for_uncalibrated_experts(+ list(experts_module.gate_up_proj),+ attr_name=attr_name,+ unify_all=unify_scale,+ )++ if hasattr(experts_module, "down_proj") and isinstance(experts_module.down_proj, torch.nn.ModuleList):+ set_amax_for_uncalibrated_experts(+ list(experts_module.down_proj),+ attr_name=attr_name,+ unify_all=False,+ )+++def _set_amax_for_moe_auxiliary_layers(moe_module: torch.nn.Module, attr_name: str = "act_max"):+ """Set amax for auxiliary layers in MOE modules (gate/router, shared_experts).++ These layers are not part of the experts structure but are siblings in the MOE module.+ They need act_max for quantization but may be missing if not all paths were exercised+ during calibration.++ Args:+ moe_module: The MOE module (e.g., DeepseekV2MoE)+ attr_name: The attribute name for amax (default: "act_max")+ """+ # Collect all Linear layers that have act_bits set but missing act_max+ layers_needing_amax = []++ # Check gate (router) layer - it's typically a Linear layer for token routing+ if hasattr(moe_module, "gate") and isinstance(moe_module.gate, torch.nn.Linear):+ gate = moe_module.gate+ if hasattr(gate, "act_bits") and gate.act_bits < 8:+ if get_nested_attr(gate, attr_name) is None:+ layers_needing_amax.append(gate)++ # Check shared_experts - may have Linear layers that need act_max+ if hasattr(moe_module, "shared_experts"):+ shared_experts = moe_module.shared_experts+ if shared_experts is not None:+ for child_name, child in shared_experts.named_modules():+ if isinstance(child, torch.nn.Linear):+ if hasattr(child, "act_bits") and child.act_bits < 8:+ if get_nested_attr(child, attr_name) is None:+ layers_needing_amax.append(child)++ if not layers_needing_amax:+ return++ # Try to get reference amax from calibrated experts+ reference_amax = _get_reference_amax_from_experts(moe_module, attr_name)++ if reference_amax is not None:+ for layer in layers_needing_amax:+ if not isinstance(reference_amax, torch.Tensor):+ reference_amax = torch.tensor(reference_amax, dtype=torch.float32)+ set_nested_attr(layer, attr_name, reference_amax.clone())+ logger.info_once(+ f"Set act_max for {len(layers_needing_amax)} MOE auxiliary layers (gate/shared_experts) "+ f"using reference value from calibrated experts."+ )+ else:+ logger.warning_once(+ f"Cannot set act_max for {len(layers_needing_amax)} MOE auxiliary layers: "+ f"no calibrated experts found to use as reference."+ )+++def _get_reference_amax_from_experts(moe_module: torch.nn.Module, attr_name: str = "act_max"):+ """Get a reference amax value from calibrated expert layers.++ Args:+ moe_module: The MOE module containing experts+ attr_name: The attribute name for amax++ Returns:+ A reference amax tensor, or None if no calibrated experts found+ """+ amax_values = []++ if not hasattr(moe_module, "experts"):+ return None++ experts = moe_module.experts++ # Handle unfused experts (ModuleList)+ if _is_unfused_experts_module(experts):+ for proj_list in [getattr(experts, "gate_up_proj", None), getattr(experts, "down_proj", None)]:+ if proj_list is not None and isinstance(proj_list, torch.nn.ModuleList):+ for layer in proj_list:+ amax = get_nested_attr(layer, attr_name)+ if amax is not None:+ amax_values.append(amax)++ # Handle iterable experts (list of modules)+ elif isinstance(experts, collections.abc.Iterable):+ expert_linear_names = get_expert_linear_names(moe_module)+ for expert in experts:+ for linear_name in expert_linear_names:+ layer = getattr(expert, linear_name, None)+ if layer is not None:+ amax = get_nested_attr(layer, attr_name)+ if amax is not None:+ amax_values.append(amax)++ if not amax_values:+ return None++ # Return max of all amax values+ flat_values = [t.reshape(-1) for t in amax_values]+ all_values = torch.cat(flat_values)+ return torch.max(all_values)# Adapted from https://github.com/vllm-project/llm-compressor/blob/diff --git a/auto_round/wrapper.py b/auto_round/wrapper.pyindex 24836d85b..89f903827 100644--- a/auto_round/wrapper.py+++ b/auto_round/wrapper.py@@ -141,6 +141,14 @@ class WrapperLinear(torch.nn.Module):else:self.orig_forward = self.linear_forward if type(self.orig_layer) == torch.nn.Linear else self.conv1d_forward+ @property+ def weight(self):+ return self.orig_layer.weight++ @property+ def bias(self):+ return self.orig_layer.bias+def _init_tuning_params_and_quant_func(self):"""Initializes tuning parameters and quantization functions.@@ -502,6 +510,16 @@ class WrapperWALayer(torch.nn.Module):self.act_quant_func = compile_func(self.act_quant_func, self.device)self.extra_repr_org = orig_layer.extra_repr+ @property+ def weight(self):+ """Exposes the weight of the wrapped layer for external access."""+ return self.orig_layer.weight++ @property+ def bias(self):+ """Exposes the bias of the wrapped layer for external access."""+ return self.orig_layer.bias+def forward(self, x):act_max = self.orig_layer.act_max if hasattr(self.orig_layer, "act_max") else Nonex, _, _ = self.orig_layer.act_quant_func(diff --git a/test/test_cpu/quantization/test_mxfp_nvfp.py b/test/test_cpu/quantization/test_mxfp_nvfp.pyindex 3c2e9bcce..37b8a8a4d 100644--- a/test/test_cpu/quantization/test_mxfp_nvfp.py+++ b/test/test_cpu/quantization/test_mxfp_nvfp.py@@ -1,3 +1,4 @@+import collectionsimport osimport shutil@@ -32,9 +33,6 @@ class TestAutoRoundFP:shutil.rmtree("./saved", ignore_errors=True)shutil.rmtree("runs", ignore_errors=True)- @pytest.mark.skipif(- transformers_version >= version.parse("5.0.0"), reason="transformers v5 MOE model has breaking changes"- )def test_nvfp4_moe_actmax_rtn(self, tiny_deepseek_v2_model_path, dataloader):model_name = tiny_deepseek_v2_model_pathlayer_config = {@@ -55,16 +53,47 @@ class TestAutoRoundFP:layer_config=layer_config,)compressed_model, _ = autoround.quantize()- assert hasattr(compressed_model.model.layers[1].mlp.experts[0].gate_proj.orig_layer, "act_max")+ moe = compressed_model.model.layers[1].mlp+ experts = moe.experts++ def _has_act_max(layer):+ if layer is None:+ return False+ if hasattr(layer, "orig_layer"):+ layer = layer.orig_layer+ return hasattr(layer, "act_max")++ found_act_max = False+ if hasattr(experts, "gate_up_proj") and isinstance(experts.gate_up_proj, torch.nn.ModuleList):+ if len(experts.gate_up_proj) > 0:+ found_act_max = _has_act_max(experts.gate_up_proj[0])+ elif isinstance(experts, collections.abc.Iterable):+ first_expert = next(iter(experts), None)+ if first_expert is not None:+ for linear_name in [+ "gate_proj",+ "up_proj",+ "down_proj",+ "linear_fc1",+ "linear_fc2",+ "w1",+ "w2",+ "w3",+ ]:+ if hasattr(first_expert, linear_name):+ found_act_max = _has_act_max(getattr(first_expert, linear_name))+ if found_act_max:+ break+ elif hasattr(moe, "act_max"):+ found_act_max = True++ assert found_act_max, "Missing act_max on MOE expert layers"lm_head = compressed_model.lm_headassert hasattr(lm_head, "orig_layer") and hasattr(lm_head.orig_layer, "act_max"), "Illegal NVFP4 quantization for lm_head layer"shutil.rmtree(self.save_dir, ignore_errors=True)- @pytest.mark.skipif(- transformers_version >= version.parse("5.0.0"), reason="transformers v5 MOE model has breaking changes"- )def test_nvfp4_moe_actmax_ar(self, tiny_deepseek_v2_model_path, dataloader):model_name = tiny_deepseek_v2_model_pathlayer_config = {@@ -97,9 +126,6 @@ class TestAutoRoundFP:assert is_model_outputs_similar(model_name, quantized_model_path)shutil.rmtree(self.save_dir, ignore_errors=True)- @pytest.mark.skipif(- transformers_version >= version.parse("5.0.0"), reason="transformers v5 MOE model has breaking changes"- )def test_mxfp4_moe_ar(self, tiny_deepseek_v2_model_path, dataloader):model_name = tiny_deepseek_v2_model_pathlayer_config = {@@ -333,9 +359,6 @@ class TestAutoRoundFP:), "Illegal NVFP4 packing name or data_type or shape"shutil.rmtree(quantized_model_path, ignore_errors=True)- @pytest.mark.skipif(- transformers_version >= version.parse("5.0.0"), reason="transformers v5 MOE model has breaking changes"- )def test_qwen_moe_quant_infer(self, tiny_qwen_moe_model_path, dataloader):model_name = tiny_qwen_moe_model_pathlayer_config = {diff --git a/test/test_cuda/models/test_moe_experts_interface.py b/test/test_cuda/models/test_moe_experts_interface.pynew file mode 100644index 000000000..a292d4294--- /dev/null+++ b/test/test_cuda/models/test_moe_experts_interface.py@@ -0,0 +1,239 @@+# 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.++"""+Test script for moe_experts_interface.py - linear_loop experts implementation.++This verifies that:+1. linear_loop is registered with transformers 'ALL_EXPERTS_FUNCTIONS'+2. Fused expert weights are correctly unfused to nn.Linear layers+3. The forward pass produces correct results+"""++import pytest+import torch+from torch import nn+++def _skip_if_no_linear_loop():+ from auto_round.modeling.fused_moe.moe_experts_interface import is_linear_loop_available++ if not is_linear_loop_available():+ pytest.skip("transformers MOE integration not available")+++def test_linear_loop_registration():+ """Test that linear_loop is registered with transformers."""+ from auto_round.modeling.fused_moe.moe_experts_interface import (+ register_linear_loop_experts,+ )++ _skip_if_no_linear_loop()+ success = register_linear_loop_experts()+ assert success, "Failed to register linear_loop"++ from transformers.integrations.moe import ALL_EXPERTS_FUNCTIONS++ assert "linear_loop" in ALL_EXPERTS_FUNCTIONS._global_mapping+++def test_unfuse_experts_weights():+ """Test unfusing fused expert weights to nn.Linear layers."""+ from auto_round.modeling.fused_moe.moe_experts_interface import _unfuse_experts_weights_inplace++ # Create a mock fused experts module (Mixtral style - not transposed)+ num_experts = 4+ hidden_dim = 64+ intermediate_dim = 128++ class MockFusedExperts(nn.Module):+ def __init__(self):+ super().__init__()+ # Not transposed: (num_experts, 2*intermediate, hidden)+ self.gate_up_proj = nn.Parameter(torch.randn(num_experts, 2 * intermediate_dim, hidden_dim))+ # (num_experts, hidden, intermediate)+ self.down_proj = nn.Parameter(torch.randn(num_experts, hidden_dim, intermediate_dim))+ self.act_fn = nn.SiLU()+ self.num_experts = num_experts+ self.has_bias = False+ self.is_transposed = False++ module = MockFusedExperts()++ # Store original weights for comparison+ original_gate_up = module.gate_up_proj.data.clone()+ original_down = module.down_proj.data.clone()++ # Unfuse (check_decorator=False since mock module doesn't have the decorator)+ success = _unfuse_experts_weights_inplace(module, check_decorator=False)+ assert success, "Failed to unfuse weights"++ # Verify structure+ assert isinstance(module.gate_up_proj, nn.ModuleList)+ assert isinstance(module.down_proj, nn.ModuleList)+ assert len(module.gate_up_proj) == num_experts+ assert len(module.down_proj) == num_experts++ # Verify weights are preserved+ for i in range(num_experts):+ # gate_up: original (2*intermediate, hidden), linear.weight should be same+ assert torch.allclose(+ module.gate_up_proj[i].weight.data, original_gate_up[i], atol=1e-6+ ), f"gate_up weight mismatch for expert {i}"++ # down: original (hidden, intermediate), linear.weight should be same+ assert torch.allclose(+ module.down_proj[i].weight.data, original_down[i], atol=1e-6+ ), f"down weight mismatch for expert {i}"+++def test_unfuse_experts_weights_transposed():+ """Test unfusing transposed expert weights (Llama4/GptOss style)."""+ from auto_round.modeling.fused_moe.moe_experts_interface import _unfuse_experts_weights_inplace++ num_experts = 4+ hidden_dim = 64+ intermediate_dim = 128++ class MockFusedExpertsTransposed(nn.Module):+ def __init__(self):+ super().__init__()+ # Transposed: (num_experts, hidden, 2*intermediate)+ self.gate_up_proj = nn.Parameter(torch.randn(num_experts, hidden_dim, 2 * intermediate_dim))+ # Transposed: (num_experts, intermediate, hidden)+ self.down_proj = nn.Parameter(torch.randn(num_experts, intermediate_dim, hidden_dim))+ self.act_fn = nn.SiLU()+ self.num_experts = num_experts+ self.is_transposed = True+ self.has_bias = False++ module = MockFusedExpertsTransposed()++ # Store original weights for comparison+ original_gate_up = module.gate_up_proj.data.clone()+ original_down = module.down_proj.data.clone()++ # Unfuse (check_decorator=False since mock module doesn't have the decorator)+ success = _unfuse_experts_weights_inplace(module, check_decorator=False)+ assert success, "Failed to unfuse transposed weights"++ # Verify structure+ assert isinstance(module.gate_up_proj, nn.ModuleList)+ assert isinstance(module.down_proj, nn.ModuleList)++ # Verify weights are correctly transposed+ for i in range(num_experts):+ # gate_up: original (hidden, 2*intermediate), should be transposed to (2*intermediate, hidden)+ assert torch.allclose(+ module.gate_up_proj[i].weight.data, original_gate_up[i].t(), atol=1e-6+ ), f"gate_up weight mismatch for expert {i}"++ # down: original (intermediate, hidden), should be transposed to (hidden, intermediate)+ assert torch.allclose(+ module.down_proj[i].weight.data, original_down[i].t(), atol=1e-6+ ), f"down weight mismatch for expert {i}"+++def test_linear_loop_forward():+ """Test that linear_loop forward produces correct results."""+ from auto_round.modeling.fused_moe.moe_experts_interface import (+ _unfuse_experts_weights_inplace,+ linear_loop_experts_forward,+ )++ num_experts = 4+ hidden_dim = 64+ intermediate_dim = 128+ num_tokens = 10+ top_k = 2++ # Create module with unfused weights+ class MockExperts(nn.Module):+ def __init__(self):+ super().__init__()+ self.gate_up_proj = nn.Parameter(torch.randn(num_experts, 2 * intermediate_dim, hidden_dim))+ self.down_proj = nn.Parameter(torch.randn(num_experts, hidden_dim, intermediate_dim))+ self.act_fn = nn.SiLU()+ self.num_experts = num_experts+ self.has_bias = False+ self.is_transposed = False++ module = MockExperts()++ # Unfuse weights (check_decorator=False since mock module doesn't have the decorator)+ _unfuse_experts_weights_inplace(module, check_decorator=False)++ # Create inputs+ hidden_states = torch.randn(num_tokens, hidden_dim)+ top_k_index = torch.randint(0, num_experts, (num_tokens, top_k))+ top_k_weights = torch.softmax(torch.randn(num_tokens, top_k), dim=-1)++ # Run forward+ output = linear_loop_experts_forward(module, hidden_states, top_k_index, top_k_weights)++ # Verify output shape+ assert output.shape == hidden_states.shape, f"Output shape mismatch: {output.shape} vs {hidden_states.shape}"++ # Verify output is not all zeros (sanity check)+ assert not torch.allclose(output, torch.zeros_like(output)), "Output is all zeros"+++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,+ )++ _skip_if_no_linear_loop()++ num_experts = 4+ hidden_dim = 64+ intermediate_dim = 128++ # Create a mock model with fused experts+ class MockConfig:+ def __init__(self):+ self._experts_implementation = "eager"++ class MockExpertsModule(nn.Module):+ def __init__(self):+ super().__init__()+ self.gate_up_proj = nn.Parameter(torch.randn(num_experts, 2 * intermediate_dim, hidden_dim))+ self.down_proj = nn.Parameter(torch.randn(num_experts, hidden_dim, intermediate_dim))+ self.act_fn = nn.SiLU()+ self.num_experts = num_experts+ self.has_bias = False+ self.is_transposed = False++ def forward(self, x):+ pass++ # Add __wrapped__ to simulate @use_experts_implementation decorator+ MockExpertsModule.forward.__wrapped__ = True++ class MockModel(nn.Module):+ def __init__(self):+ super().__init__()+ self.config = MockConfig()+ self.layer = nn.ModuleDict({"experts": MockExpertsModule()})++ model = MockModel()++ # Prepare for quantization+ unfused = prepare_model_for_moe_quantization(model)++ # Verify+ assert model.config._experts_implementation == "linear_loop"+ assert len(unfused) == 1+ assert isinstance(model.layer["experts"].gate_up_proj, nn.ModuleList)