Skip to content

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

Delay materializing the replaced model weights until quantization (#1307)

Yi Liud9d20a125c73
diff --git a/auto_round/compressors/base.py b/auto_round/compressors/base.py
index e226fe742..3232c4470 100644
--- a/auto_round/compressors/base.py
+++ b/auto_round/compressors/base.py
@@ -55,6 +55,7 @@ from auto_round.data_type.utils import reshape_pad_tensor_by_group_size
from auto_round.export.export_to_gguf.config import GGUF_INNER_CONFIG, ModelType
from auto_round.formats import OutputFormat, get_formats
from auto_round.logger import logger
+from auto_round.modelling.replace_modules import materialize_model_, safe_to_cpu_
from auto_round.schemes import (
QuantizationScheme,
_handle_special_schemes,
@@ -84,6 +85,7 @@ from auto_round.utils import (
get_layer_names_in_block,
get_lm_head_name,
get_module,
+ global_state,
htcore,
is_auto_device_mapping,
is_debug_mode,
@@ -1070,7 +1072,7 @@ class BaseCompressor(object):
import accelerate
accelerate.hooks.remove_hook_from_submodules(model)
- model = model.to("cpu")
+ safe_to_cpu_(model)
clear_memory(device_list=self.device_list)
self._quantize_via_rtn_blockwise(all_to_quantized_module_names)
except torch.OutOfMemoryError:
@@ -1082,7 +1084,7 @@ class BaseCompressor(object):
"Fallback to CPU. "
"Consider enabling `low_gpu_mem_usage` or using more GPUs via `--device 0,1,2,3`."
)
- model = model.to("cpu")
+ safe_to_cpu_(model)
clear_memory(device_list=self.device_list)
if hasattr(model, "hf_device_map") and len(model.hf_device_map) > 1:
import accelerate
@@ -1218,6 +1220,10 @@ class BaseCompressor(object):
all_to_quantized_module_names: list[str] = [n for n, m in self.model.named_modules() if check_to_quantized(m)]
self.all_to_quantized_module_names = all_to_quantized_module_names
if is_nv_fp(self.data_type):
+ # FIXME: (yiliu30) change it to block-wise after we refactor the quantization code and
+ # https://github.com/intel/auto-round/issues/1331
+ materialize_model_(self.model)
+ self.model.to("cpu")
from auto_round.data_type.nvfp import calculate_gparam
from auto_round.data_type.utils import update_fused_layer_global_scales
@@ -1239,7 +1245,6 @@ class BaseCompressor(object):
if not (any(fmt.is_gguf() for fmt in getattr(self, "formats", [])) or self.super_bits is not None):
self._quantize_embedding_layer() # leave to gguf itself to handle
- self.model.to("cpu")
# Release memory
clear_memory(device_list=self.device_list)
@@ -1280,7 +1285,8 @@ class BaseCompressor(object):
for handle in hook_handles:
handle.remove()
else:
- use_blockwise_quantization = False
+ # By default, we go with layer-wise way if no replacement happened
+ use_blockwise_quantization = global_state.replaced_module_count > 0
tied_weights_keys = getattr(self.model, "_tied_weights_keys", [])
if tied_weights_keys is None:
tied_weights_keys = []
@@ -1304,6 +1310,7 @@ class BaseCompressor(object):
for block_name in block_names:
pbar.set_description(f"Quantizing {block_name}")
block = get_module(self.model, block_name)
+ materialize_model_(block)
for name, m in block.named_modules():
if hasattr(m, "global_name") and m.global_name in all_to_quantized_module_names:
self._quantize_layer_via_rtn(m.global_name, to_cpu=self.low_gpu_mem_usage)
@@ -1329,6 +1336,8 @@ class BaseCompressor(object):
clear_memory(device_list=self.device_list)
memory_monitor.log_summary()
else:
+ materialize_model_(self.model)
+ self.model.to("cpu")
block_names_cnt = len(flatten_list(get_block_names(self.model, True)))
clear_mem_freq = len(all_to_quantized_module_names) // block_names_cnt
cnt = 0
@@ -1421,6 +1430,8 @@ class BaseCompressor(object):
for block_name in block_names:
pbar.set_description(f"Quantizing {block_name}")
block = get_module(self.model, block_name)
+ materialize_model_(block)
+ block.to("cpu")
if is_fp8_model(self.model):
convert_fp8_module_to_16b(block, dtype=self.amp_dtype, device=self.device)
@@ -1594,7 +1605,9 @@ class BaseCompressor(object):
formats = self.formats if hasattr(self, "formats") else None
# It is best to modify the model structure in the quantize function and check the format,
# because it may cause the gguf format to not be exported normally.
- self.model = update_module(self.model, formats=formats, trust_remote_code=self.trust_remote_code)
+ self.model = update_module(
+ self.model, formats=formats, trust_remote_code=self.trust_remote_code, cleanup_original=False
+ )
# Temporary names must be assigned after handle_moe_model;
# placing them earlier would cause them to be removed when the module is replaced.
@@ -2133,6 +2146,7 @@ class BaseCompressor(object):
)
try:
+ materialize_model_(self.model)
self.model = dispatch_model(self.model, device_map=device_map)
except ValueError as e:
if "offload_dir" in e.__str__():
@@ -2728,6 +2742,7 @@ class BaseCompressor(object):
Returns:
Tuple: (q_outputs, output) if self.enable_quanted_input is True, else (None, output)
"""
+ materialize_model_(block)
if is_fp8_model(self.model):
for n, m in block.named_modules():
if is_fp8_linear(m):
diff --git a/auto_round/inference/convert_model.py b/auto_round/inference/convert_model.py
index 1041d2a49..3daa3c822 100644
--- a/auto_round/inference/convert_model.py
+++ b/auto_round/inference/convert_model.py
@@ -593,7 +593,7 @@ def convert_hf_model(model: nn.Module, target_device: str = "cpu") -> tuple[nn.M
packing_format = "auto_round:auto_gptq"
# Preprocess model before replace layers
- model = update_module(model)
+ model = update_module(model, cleanup_original=True)
# Replace layers with quantized versions
layer_configs = get_layer_config(model, quantization_config)
diff --git a/auto_round/modelling/deepseek_v2.py b/auto_round/modelling/deepseek_v2.py
index 6b47a2866..7caff2696 100644
--- a/auto_round/modelling/deepseek_v2.py
+++ b/auto_round/modelling/deepseek_v2.py
@@ -144,7 +144,7 @@ def attn_forward(
class DeepseekV2RotaryEmbedding(ReplacementModuleBase):
def __init__(self, original, config):
- super().__init__()
+ super().__init__(original)
@classmethod
def original_module_class(cls) -> str:
@@ -174,10 +174,13 @@ class DeepseekV2RotaryEmbedding(ReplacementModuleBase):
and inspect.getfile(original.__class__) == inspect.getfile(eager_attention_forward)
)
+ def release_original_module(self) -> None:
+ pass
+
class DeepseekV2Attention(ReplacementModuleBase):
def __init__(self, original, config):
- super().__init__()
+ super().__init__(original)
@classmethod
def original_module_class(cls) -> str:
@@ -206,3 +209,6 @@ class DeepseekV2Attention(ReplacementModuleBase):
and is_hpex_available()
and inspect.getfile(original.__class__) == inspect.getfile(eager_attention_forward)
)
+
+ def release_original_module(self) -> None:
+ pass
diff --git a/auto_round/modelling/gpt_oss.py b/auto_round/modelling/gpt_oss.py
index 7514b77b2..83d980d42 100644
--- a/auto_round/modelling/gpt_oss.py
+++ b/auto_round/modelling/gpt_oss.py
@@ -20,18 +20,10 @@ from transformers.models.gpt_oss.configuration_gpt_oss import GptOssConfig
from transformers.models.gpt_oss.modeling_gpt_oss import GptOssMLP
from auto_round.modelling.replace_modules import ReplacementModuleBase
+from auto_round.modelling.utils import _update_parameter
from auto_round.utils import LazyImport, clear_memory, logger, unsupported_meta_device
-def _update_parameter(
- module: torch.nn.Module,
- name: str,
- data: torch.Tensor,
-) -> None:
- param = getattr(module, name)
- param.data.copy_(data)
-
-
class GPTOssSingleExpert(nn.Module):
def __init__(self, hidden_size: int, intermediate_size: int, dtype: torch.dtype | None = None):
super().__init__()
@@ -60,7 +52,7 @@ class SequentialGPTOSSMoE(ReplacementModuleBase):
"""
def __init__(self, original: GptOssMLP, config: GptOssConfig):
- super().__init__()
+ super().__init__(original)
hidden_size = config.hidden_size
intermediate_size = config.intermediate_size
dtype_str = getattr(config, "torch_dtype", None) or getattr(config, "dtype", None)
@@ -79,10 +71,12 @@ class SequentialGPTOSSMoE(ReplacementModuleBase):
# Build per-expert MLPs
self.experts = nn.ModuleList()
target_device = next(original.experts.parameters()).device
- with skip_weights_initialize(), torch.device(target_device):
+ with skip_weights_initialize(), torch.device("meta"):
for _ in range(E):
self.experts.append(GPTOssSingleExpert(hidden_size, intermediate_size, dtype=dtype))
+ def _materialize_weights(self) -> None:
+ original = self._get_original_module()
if not unsupported_meta_device(original):
for i, mlp in enumerate(self.experts):
_update_parameter(mlp.gate_proj, "weight", original.experts.gate_up_proj[i, :, ::2].T)
diff --git a/auto_round/modelling/llama4.py b/auto_round/modelling/llama4.py
index ddca377b8..795431554 100644
--- a/auto_round/modelling/llama4.py
+++ b/auto_round/modelling/llama4.py
@@ -17,6 +17,7 @@ from transformers.modeling_utils import no_init_weights
from transformers.models.llama4.modeling_llama4 import Llama4Config, Llama4TextMLP, Llama4TextMoe
from auto_round.modelling.replace_modules import ReplacementModuleBase
+from auto_round.modelling.utils import _update_parameter
from auto_round.utils import clear_memory, unsupported_meta_device
@@ -24,9 +25,10 @@ class SequentialLlama4TextExperts(torch.nn.ModuleList):
def __init__(self, config, original):
self.num_experts = original.gate_up_proj.shape[0]
target_device = next(original.parameters()).device
- with no_init_weights(), torch.device(target_device):
+ with no_init_weights(), torch.device("meta"):
super().__init__([Llama4TextMLP(config) for _ in range(self.num_experts)])
+ def _materialize_weights(self, original) -> None:
if not unsupported_meta_device(original):
intermediate_size = original.down_proj.shape[1]
@@ -35,22 +37,23 @@ class SequentialLlama4TextExperts(torch.nn.ModuleList):
down = original.down_proj[i]
gate_proj = gate_up[:, :intermediate_size]
up_proj = gate_up[:, intermediate_size:]
-
- self[i].gate_proj.weight.data.copy_(gate_proj.t())
- self[i].up_proj.weight.data.copy_(up_proj.t())
- self[i].down_proj.weight.data.copy_(down.t())
+ _update_parameter(self[i].gate_proj, "weight", gate_proj.t().contiguous())
+ _update_parameter(self[i].up_proj, "weight", up_proj.t().contiguous())
+ _update_parameter(self[i].down_proj, "weight", down.t().contiguous())
del gate_up, down, gate_proj, up_proj
original.to_empty(device="meta") # release original experts parameters
class SequentialLlama4TextMoe(ReplacementModuleBase):
def __init__(self, original, config):
- super().__init__()
+ super().__init__(original)
config = config.text_config
self.top_k = config.num_experts_per_tok
self.hidden_dim = config.hidden_size
self.num_experts = config.num_local_experts
- self.experts = SequentialLlama4TextExperts(config, original.experts)
+ with torch.device("meta"):
+ self.experts = SequentialLlama4TextExperts(config, original.experts)
+
self.router = original.router
self.shared_expert = original.shared_expert
@@ -91,3 +94,8 @@ class SequentialLlama4TextMoe(ReplacementModuleBase):
) -> "SequentialLlama4TextMoe":
"""Create an instance from the original module."""
return cls(original, config)
+
+ def _materialize_weights(self) -> None:
+ original = self._get_original_module()
+ self.experts._materialize_weights(original.experts)
+ clear_memory()
diff --git a/auto_round/modelling/qwen3_vl_moe.py b/auto_round/modelling/qwen3_vl_moe.py
index 345855fa2..609b1df74 100644
--- a/auto_round/modelling/qwen3_vl_moe.py
+++ b/auto_round/modelling/qwen3_vl_moe.py
@@ -22,9 +22,10 @@ from auto_round.modelling.replace_modules import ReplacementModuleBase
from auto_round.utils import clear_memory, logger, unsupported_meta_device
transformers_version = version.parse(transformers.__version__)
-
from typing import TYPE_CHECKING
+from auto_round.modelling.utils import _update_parameter
+
if TYPE_CHECKING:
from transformers import Qwen3VLMoeConfig, Qwen3VLMoeTextConfig
from transformers.models.qwen3_vl_moe.modeling_qwen3_vl_moe import (
@@ -32,15 +33,6 @@ if TYPE_CHECKING:
)
-def _update_parameter(
- module: torch.nn.Module,
- name: str,
- data: torch.Tensor,
-) -> None:
- param = getattr(module, name)
- param.data.copy_(data)
-
-
# Adapted from https://github.com/vllm-project/llm-compressor/blob/main/src/llmcompressor/modeling/qwen3_vl_moe.py
class LinearQwen3VLMoeTextSparseMoeBlock(ReplacementModuleBase):
"""
@@ -56,7 +48,7 @@ class LinearQwen3VLMoeTextSparseMoeBlock(ReplacementModuleBase):
config: "Qwen3VLMoeConfig",
calibrate_all_experts: bool = False,
):
- super().__init__()
+ super().__init__(original)
text_config: "Qwen3VLMoeTextConfig" = config.get_text_config()
self.hidden_size = text_config.hidden_size
@@ -66,7 +58,8 @@ class LinearQwen3VLMoeTextSparseMoeBlock(ReplacementModuleBase):
# https://github.com/JJJYmmm/transformers/commit/f5dea1c694af8c994c769170813a8702332119ee
self.gate = original.gate
self.calibrate_all_experts = calibrate_all_experts
- self.experts = SequentialQwen3VLMoeTextExperts(text_config, original.experts)
+ with torch.device("meta"):
+ self.experts = SequentialQwen3VLMoeTextExperts(text_config, original.experts)
if not transformers_version < version.parse(
"5.0"
): # remove conversion_mapping for qwen3_vl_moe when transformers>=5.0
@@ -74,6 +67,11 @@ class LinearQwen3VLMoeTextSparseMoeBlock(ReplacementModuleBase):
register_checkpoint_conversion_mapping(config.model_type, [], overwrite=True)
+ def _materialize_weights(self) -> None:
+ original = self._get_original_module()
+ self.experts._materialize_weights(original.experts)
+ clear_memory()
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
batch_size, sequence_length, hidden_dim = hidden_states.shape
hidden_states = hidden_states.reshape(-1, hidden_dim)
@@ -144,9 +142,12 @@ class SequentialQwen3VLMoeTextExperts(torch.nn.ModuleList):
)
target_device = next(original.parameters()).device
- with torch.device(target_device):
+
+ with torch.device("meta"):
super().__init__([Qwen3VLMoeTextMLP(config, intermediate_size) for _ in range(self.num_experts)])
+ 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]
diff --git a/auto_round/modelling/replace_modules.py b/auto_round/modelling/replace_modules.py
index 591ed891d..d77ffca2d 100644
--- a/auto_round/modelling/replace_modules.py
+++ b/auto_round/modelling/replace_modules.py
@@ -13,13 +13,14 @@
# limitations under the License.
from abc import ABC, abstractmethod
+from dataclasses import dataclass
from typing import Dict, Type
import torch
from tqdm import tqdm
from transformers import PreTrainedModel
-from auto_round.utils import LazyImport, logger
+from auto_round.utils import LazyImport, dump_mem_usage, dump_memory_usage_ctx, global_state, logger
BUILTIN_MODULES = {
"Llama4TextMoe": LazyImport("auto_round.modelling.llama4"),
@@ -43,6 +44,57 @@ def _import_required_replacements(model: torch.nn.Module) -> None:
logger.debug(f"Loaded replacement module for {class_name}")
+@dump_mem_usage("Materializing model", log_level="debug")
+def materialize_model_(model: torch.nn.Module) -> None:
+ def _materialize_module(module: torch.nn.Module) -> None:
+ if isinstance(module, ReplacementModuleBase):
+ module.materialize_weights()
+
+ model.apply(_materialize_module)
+ # check if any module on meta device remains
+ found_meta = False
+ for name, param in model.named_parameters():
+ if param.device.type == "meta":
+ logger.warning(f"Parameter {name} is still on meta device after materialization.")
+ found_meta = True
+ for name, buffer in model.named_buffers():
+ if buffer.device.type == "meta":
+ logger.warning(f"Buffer {name} is still on meta device after materialization.")
+ found_meta = True
+ if not found_meta:
+ logger.debug("All parameters and buffers have been materialized from meta device.")
+ release_original_module_(model)
+
+
+def release_original_module_(model: torch.nn.Module) -> None:
+ def _clear_source_module(module: torch.nn.Module) -> None:
+ if isinstance(module, ReplacementModuleBase):
+ module.release_original_module()
+
+ model.apply(_clear_source_module)
+
+
+def _has_meta_params_or_buffers(model: PreTrainedModel) -> bool:
+ for _, param in model.named_parameters():
+ if param.device.type == "meta":
+ return True
+ for _, buffer in model.named_buffers():
+ if buffer.device.type == "meta":
+ return True
+ return False
+
+
+def safe_to_cpu_(model: torch.nn.Module) -> None:
+ # If no replacement happened, move model to CPU directly
+ if global_state.replaced_module_count == 0:
+ model.to("cpu")
+ return
+ else:
+ # TODO: (yiliu30) there might be some edge cases where some modules are replaced
+ # and we need to move them to CPU safely.
+ pass
+
+
class ReplacementModuleBase(ABC, torch.nn.Module):
"""
Abstract base class for module replacement during calibration phase.
@@ -81,6 +133,15 @@ class ReplacementModuleBase(ABC, torch.nn.Module):
cls._replacement_registry[cls.original_module_class()] = cls
logger.trace(f"Registered {cls.__name__} for replacing {cls.original_module_class()}")
+ def __init__(self, original: torch.nn.Module):
+ super().__init__()
+ _global_tracker.register_replacement(
+ name=str(id(self)),
+ original=original,
+ replacement=self,
+ )
+ self._materialized = False
+
@classmethod
def get_replacement_class(cls, module_class_name: str) -> Type["ReplacementModuleBase"]:
"""Get replacement class for a given module class name."""
@@ -123,6 +184,34 @@ class ReplacementModuleBase(ABC, torch.nn.Module):
"""Create replacement module from original module."""
pass
+ def materialize_weights(self):
+ """Materialize weights if needed."""
+ if not self._materialized:
+ self._materialize_weights()
+ self.post_process_materialization()
+
+ def _materialize_weights(self) -> None:
+ """Materialize weights from the original module.
+
+ Subclasses should override this method to implement
+ weight materialization logic.
+ """
+ pass
+
+ def release_original_module(self) -> None:
+ """Release reference to the original module to free memory."""
+ # Release from global tracker
+ _global_tracker.release_original(self)
+
+ def _get_original_module(self) -> torch.nn.Module:
+ """Get the original module associated with this replacement."""
+ return _global_tracker.get_original(self)
+
+ def post_process_materialization(self) -> None:
+ """Mark the replacement module as materialized."""
+ self._materialized = True
+ self.release_original_module()
+
# Note: adapted from llm-compressor
# https://github.com/vllm-project/llm-compressor/blob/main/src/llmcompressor/modeling/moe_context.py
@@ -146,7 +235,7 @@ def apply_replacements(
The model with modules replaced.
"""
_import_required_replacements(model)
- replaced = {}
+ replaced = []
# Step 1: Collect all modules that need replacement
logger.debug("Scanning for modules to replace")
@@ -165,18 +254,101 @@ def apply_replacements(
if modules_to_replace:
logger.info(f"Found {len(modules_to_replace)} modules to replace")
for name, module, class_name in tqdm(modules_to_replace, desc="Replacing modules"):
- replacement_cls = ReplacementModuleBase.get_replacement_class(class_name)
- replacement = replacement_cls.from_original(
- module,
- model.config,
- )
- model.set_submodule(name, replacement)
- replaced[name] = (module, replacement)
+ module = model.get_submodule(name)
+ with dump_memory_usage_ctx(f"Replacing module {name}", log_level="debug"):
+ replacement_cls = ReplacementModuleBase.get_replacement_class(class_name)
+ replacement = replacement_cls.from_original(
+ module,
+ model.config,
+ )
+ model.set_submodule(name, replacement)
+ replaced.append((name, replacement_cls))
else:
logger.debug("No modules found for replacement")
# Log what was replaced
if replaced:
+ global_state.replaced_module_count = len(replaced)
logger.info(f"Replaced {len(replaced)} modules")
return model
+
+
+@dataclass
+class ReplacedModuleInfo:
+ original_module: torch.nn.Module
+ replacement_module: ReplacementModuleBase
+
+
+class ModuleReplacementTracker:
+ """Tracker to maintain mapping between replacement modules and their original modules.
+
+ This is a singleton class - only one instance can exist.
+ """
+
+ _instance = None
+ _initialized = False
+
+ def __new__(cls):
+ if cls._instance is None:
+ cls._instance = super(ModuleReplacementTracker, cls).__new__(cls)
+ return cls._instance
+
+ def __init__(self):
+ # Only initialize once
+ if ModuleReplacementTracker._initialized:
+ return
+
+ # Map from replacement module id to original module
+ self._replacement_to_original: Dict[int, torch.nn.Module] = {}
+ # Map from module name to ReplacedModuleInfo
+ self._name_to_info: Dict[str, ReplacedModuleInfo] = {}
+
+ ModuleReplacementTracker._initialized = True
+
+ @classmethod
+ def get_instance(cls) -> "ModuleReplacementTracker":
+ """Get the singleton instance of the tracker."""
+ if cls._instance is None:
+ cls._instance = cls()
+ return cls._instance
+
+ def register_replacement(self, name: str, original: torch.nn.Module, replacement: ReplacementModuleBase) -> None:
+ """Register a module replacement."""
+ self._replacement_to_original[id(replacement)] = original
+ self._name_to_info[name] = ReplacedModuleInfo(original_module=original, replacement_module=replacement)
+ logger.trace(f"Registered replacement for module: {name}")
+
+ def get_original(self, replacement: ReplacementModuleBase) -> torch.nn.Module:
+ """Get the original module for a given replacement module."""
+ return self._replacement_to_original.get(id(replacement))
+
+ def get_info_by_name(self, name: str) -> ReplacedModuleInfo:
+ """Get replacement info by module name."""
+ return self._name_to_info.get(name)
+
+ def release_original(self, replacement: ReplacementModuleBase) -> None:
+ """Release the original module associated with a replacement module."""
+ replacement_id = id(replacement)
+ if replacement_id in self._replacement_to_original:
+ original = self._replacement_to_original[replacement_id]
+ # Delete the original module to free memory
+ del original
+ del self._replacement_to_original[replacement_id]
+ logger.trace(f"Released original module for replacement {replacement_id}")
+
+ def release_all_originals(self) -> None:
+ """Release all tracked original modules."""
+ count = len(self._replacement_to_original)
+ if count > 0:
+ self._replacement_to_original.clear()
+ logger.debug(f"Released {count} original modules from tracker")
+
+ def clear(self) -> None:
+ """Clear all tracked information."""
+ self._replacement_to_original.clear()
+ self._name_to_info.clear()
+ logger.debug("Cleared module replacement tracker")
+
+
+_global_tracker = ModuleReplacementTracker()
diff --git a/auto_round/modelling/utils.py b/auto_round/modelling/utils.py
new file mode 100644
index 000000000..015dccf5c
--- /dev/null
+++ b/auto_round/modelling/utils.py
@@ -0,0 +1,26 @@
+# 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.
+
+import torch
+import torch.nn as nn
+
+
+def _update_parameter(
+ module: torch.nn.Module,
+ name: str,
+ data: torch.Tensor,
+) -> None:
+ old_param = getattr(module, name)
+ new_param = nn.Parameter(data, requires_grad=old_param.requires_grad)
+ setattr(module, name, new_param)
diff --git a/auto_round/special_model_handler.py b/auto_round/special_model_handler.py
index 4c2b4bcbc..f3621f913 100644
--- a/auto_round/special_model_handler.py
+++ b/auto_round/special_model_handler.py
@@ -19,7 +19,7 @@ import torch
import auto_round.modelling as auto_round_modelling
from auto_round.formats import OutputFormat
-from auto_round.modelling.replace_modules import apply_replacements
+from auto_round.modelling.replace_modules import apply_replacements, materialize_model_, release_original_module_
from auto_round.utils import LazyImport, logger, unsupported_meta_device
mllms_with_limited_bs = ("llava", "qwen2_vl", "phi3_v", "mllama") # Limitations on batch_size
@@ -56,11 +56,18 @@ def _handle_special_model(model):
return model
-def update_module(model, formats: list[OutputFormat] = None, trust_remote_code: bool = True):
+def update_module(
+ model, formats: list[OutputFormat] = None, trust_remote_code: bool = True, cleanup_original: bool = True
+):
if formats is not None and any([format_.is_gguf() for format_ in formats]):
return model
- return apply_replacements(model)
+ model = apply_replacements(model)
+
+ if cleanup_original:
+ release_original_module_(model)
+
+ return model
def _get_deepseek_vl2_multimodal_block(model, quant_vision=False):
diff --git a/auto_round/utils/common.py b/auto_round/utils/common.py
index a99409a7a..045f76936 100644
--- a/auto_round/utils/common.py
+++ b/auto_round/utils/common.py
@@ -17,6 +17,7 @@ import importlib
import os
import re
import sys
+from dataclasses import dataclass
from functools import lru_cache, wraps
from typing import Any
@@ -376,3 +377,11 @@ def get_reciprocal(tensor):
recip[mask] = 0.0
return recip
+
+
+@dataclass
+class GlobalState:
+ replaced_module_count = 0
+
+
+global_state = GlobalState()
diff --git a/auto_round/utils/device.py b/auto_round/utils/device.py
index fc98eda31..55e64565c 100644
--- a/auto_round/utils/device.py
+++ b/auto_round/utils/device.py
@@ -11,9 +11,11 @@
# 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.
+import functools
import gc
import os
import re
+from contextlib import contextmanager
from functools import lru_cache
from itertools import combinations
from threading import Lock
@@ -1448,13 +1450,46 @@ class MemoryMonitor:
summary += f", 'peak_vram': {{{items_str}}}"
return summary
- def log_summary(self):
+ def log_summary(self, msg: str = "", level: str = "info"):
"""Log memory usage summary."""
summary = self.get_summary()
- logger.info(summary)
+ logger_method = getattr(logger, level.lower(), logger.info)
+ logger_method(f"{msg} {summary}")
return summary
# Global singleton instance
memory_monitor = MemoryMonitor()
+
+
+@contextmanager
+def dump_memory_usage_ctx(msg: str = "", log_level: str = "info"):
+ """Context manager to dump memory usage before and after a code block."""
+ memory_monitor.update_cpu()
+ logger_method = getattr(logger, log_level.lower(), logger.info)
+ logger_method(f"[Memory Monitor] Before {msg}: {memory_monitor.get_summary()}")
+ try:
+ yield
+ finally:
+ memory_monitor.update_cpu()
+ logger_method(f"[Memory Monitor] After {msg}: {memory_monitor.get_summary()}")
+
+
+def dump_mem_usage(msg: str = "", log_level: str = "info"):
+ """Decorator to dump memory usage before and after a function call."""
+
+ def decorator(func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ memory_monitor.update_cpu()
+ logger_method = getattr(logger, log_level.lower(), logger.info)
+ logger_method(f"[Memory Monitor] Before {msg}: {memory_monitor.get_summary()}")
+ result = func(*args, **kwargs)
+ memory_monitor.update_cpu()
+ logger_method(f"[Memory Monitor] After {msg}: {memory_monitor.get_summary()}")
+ return result
+
+ return wrapper
+
+ return decorator
diff --git a/test/test_cuda/models/test_moe_model.py b/test/test_cuda/models/test_moe_model.py
index 78c5c07cf..66b0dc827 100644
--- a/test/test_cuda/models/test_moe_model.py
+++ b/test/test_cuda/models/test_moe_model.py
@@ -128,7 +128,7 @@ def test_llama4(setup_llama4):
class NewQwen3MLP(ReplacementModuleBase):
def __init__(self, original: Qwen3MLP, config: Qwen3Config):
- super().__init__()
+ super().__init__(original)
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size