Skip to content

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

fix model_free saving with single shard and MXFP fake format evaluation (#2391)

Xin Hef4d2c1629b03
diff --git a/auto_round/cli/main.py b/auto_round/cli/main.py
index 5d5d3524d..05be1767c 100644
--- a/auto_round/cli/main.py
+++ b/auto_round/cli/main.py
@@ -255,6 +255,8 @@ def start(recipe="default", argv=None):
for key, value in recipe_defaults.items():
if getattr(args, key, None) is None:
setattr(args, key, value)
+ if args.model_free:
+ args.iters = 0
tune(args)
diff --git a/auto_round/compressors/model_free.py b/auto_round/compressors/model_free.py
index e28829530..478bd29e0 100644
--- a/auto_round/compressors/model_free.py
+++ b/auto_round/compressors/model_free.py
@@ -58,7 +58,7 @@ Output formats
``quant_method="compressed-tensors"``, compatible with vLLM / llm-compressor.
* **NVFP4_E5M3** → AutoRound format with packed ``.weight_packed`` and
``.weight_scale`` tensors; use ``format="fake"`` explicitly for high-precision
- QDQ ``.weight`` tensors.
+ QDQ ``.weight`` tensors with metadata that restores runtime activation QDQ.
Usage (CLI)
-----------
@@ -1516,7 +1516,7 @@ class _ModelFreeCompressorCore:
self._remove_stale_quantization_config_files()
_remove_quantization_configs(self.config)
- if self.format == "fake":
+ if self.format == "fake" and quantization_config.get("packing_format") != "auto_round:fake":
with open(os.path.join(self._quant_output_dir, "config.json"), "w") as f:
json.dump(self.config, f, indent=2)
return
@@ -1641,6 +1641,13 @@ class _ModelFreeCompressorCore:
packing_format = "fake" if self.format == "fake" else "auto_round:llm_compressor_nvfp4_e5m3"
else:
packing_format = "fake" if self.format == "fake" else "auto_round:auto_gptq"
+ supports_opt_rtn = (
+ is_mx_fp(data_type)
+ or data_type == _NVFP4_E5M3_DATA_TYPE
+ or _layer_config_has_mxfp(self.layer_config)
+ or _layer_config_has_nvfp4(self.layer_config)
+ )
+ opt_rtn_enabled = supports_opt_rtn and not self.disable_opt_rtn
if is_mx_fp(data_type) or _layer_config_has_mxfp(self.layer_config):
if not self.disable_opt_rtn:
logger.info(
@@ -1648,7 +1655,7 @@ class _ModelFreeCompressorCore:
"2x scale, and 0.5x scale independently for each group. "
"Pass --disable_opt_rtn to use plain RTN."
)
- else:
+ elif not supports_opt_rtn:
logger.info(
"Integer WOQ model-free quantization uses plain RTN "
"(opt_rtn is disabled for INT WOQ to preserve accuracy)."
@@ -1658,6 +1665,7 @@ class _ModelFreeCompressorCore:
f"Model-free quantization: {self.model_name_or_path}\n"
f" Scheme: {self.scheme_obj}\n"
f" Packing format: {packing_format}\n"
+ f" Optimized RTN: {'enabled' if opt_rtn_enabled else 'disabled'}\n"
f" Output: {self.output_dir}\n"
f" Shards: {len(self.shard_names)}\n"
f" Shard parallelism: {self.shard_parallelism} ({shard_parallelism_source}, "
diff --git a/auto_round/data_type/nvfp.py b/auto_round/data_type/nvfp.py
index 1b3414422..eed0c05fe 100644
--- a/auto_round/data_type/nvfp.py
+++ b/auto_round/data_type/nvfp.py
@@ -316,13 +316,15 @@ def ref_nvfp4_quant_inplace(
return out.reshape(m, n), scale
-def search_nvfp4_scale(tensor, bits=4, qw=None):
+def search_nvfp4_scale(tensor, bits=4, qw=None, quant_func=None, group_size=16):
tensor_fp32 = tensor.float()
+ baseline_func = nv_fp4 if quant_func is None else quant_func
+ candidate_func = nv_fp4_rtn if quant_func is None else quant_func
- qdq_t, scale, _ = nv_fp4(
+ qdq_t, scale, _ = baseline_func(
tensor_fp32,
bits=bits,
- group_size=16,
+ group_size=group_size,
v=0,
max_scale=1.0,
)
@@ -352,13 +354,14 @@ def search_nvfp4_scale(tensor, bits=4, qw=None):
continue
test_scale.fill_(tmp_scale)
+ candidate_scale = test_scale.squeeze(-1) if quant_func is nvfp4_v2 else test_scale
- tmp_qdq, _, _ = nv_fp4_rtn(
+ tmp_qdq, _, _ = candidate_func(
tensor_fp32,
bits=bits,
- group_size=16,
+ group_size=group_size,
v=0,
- max_scale=test_scale,
+ max_scale=candidate_scale,
)
diff.copy_(tmp_qdq)
@@ -376,6 +379,10 @@ def search_nvfp4_scale(tensor, bits=4, qw=None):
return best_scale
+def search_nvfp4_v2_scale(tensor, bits=4, qw=None):
+ return search_nvfp4_scale(tensor, bits, qw, quant_func=nvfp4_v2, group_size=tensor.shape[-1]).squeeze(-1)
+
+
@register_dtype("opt_rtn_nv_fp4")
def opt_rtn_fast_nvfp4(
tensor,
@@ -531,13 +538,24 @@ class _NVFPV2WeightQuantizer:
def create_state(self, weight, *, imatrix=None, mode, tune_rounding, tune_minmax):
grouped, _, _ = reshape_pad_tensor_by_group_size(weight, self.spec.group_size)
tunables = {}
- if tune_rounding:
+ optimized_rtn = mode == "optimized_rtn"
+ if tune_rounding and not optimized_rtn:
tunables["value"] = torch.nn.Parameter(torch.zeros_like(grouped, dtype=torch.float32))
- if tune_minmax:
+ if tune_minmax and not optimized_rtn:
tunables["max_scale"] = torch.nn.Parameter(
torch.ones(grouped.shape[:-1], device=weight.device, dtype=torch.float32)
)
- return _NVFPState(tunables, None, None)
+ optimized_scale = None
+ if optimized_rtn:
+ if isinstance(imatrix, torch.Tensor):
+ imatrix = imatrix.reshape(1, -1)
+ imatrix = reshape_pad_tensor_by_group_size(imatrix, self.spec.group_size, val=1e-5)[0].view(1, -1)
+ imatrix = imatrix.expand(grouped.numel() // imatrix.numel(), -1).reshape(grouped.shape)
+ qw = _imatrix_handle_zero(imatrix, grouped, self.spec.bits, self.spec.group_size)
+ else:
+ qw = 1.0
+ optimized_scale = search_nvfp4_v2_scale(grouped, self.spec.bits, qw)
+ return _NVFPState(tunables, None, optimized_scale)
def qdq(self, weight, state, *, tunables, materialize=False):
quantized, scale, zero_point = nvfp4_v2(
@@ -545,7 +563,7 @@ class _NVFPV2WeightQuantizer:
bits=self.spec.bits,
group_size=self.spec.group_size,
v=tunables.get("value", 0),
- max_scale=tunables.get("max_scale", 1.0),
+ max_scale=tunables.get("max_scale", state.optimized_init if state.optimized_init is not None else 1.0),
)
from auto_round.data_type.base import WeightQuantizationResult
diff --git a/auto_round/eval/evaluation.py b/auto_round/eval/evaluation.py
index 9bc850be2..ab4638ede 100644
--- a/auto_round/eval/evaluation.py
+++ b/auto_round/eval/evaluation.py
@@ -516,20 +516,39 @@ def run_model_evaluation(model, tokenizer, autoround, folders, formats, args):
if model is None:
return
else:
- if model is None:
- # Model-free mode: load model from the saved output directory
+ # Evaluate the exported artifact for both regular and model-free flows.
+ # The in-memory regular model still contains quantization wrappers,
+ # while fake-format loading materializes FakeActQuantLinear modules.
+ if model is not None:
+ model_context = getattr(autoround, "model_context", None)
+ if model_context is not None and getattr(model_context, "model", None) is model:
+ model_context.model = None
+ model = None
+ from auto_round.utils import clear_memory
+
+ clear_memory()
+
+ eval_model_dtype = get_model_dtype(args.eval_model_dtype, "auto")
+ if getattr(autoround, "mllm", False):
+ from auto_round.utils.model import mllm_load_model
+
+ model, _, loaded_tokenizer, _ = mllm_load_model(
+ eval_folder,
+ device=device_str,
+ torch_dtype=eval_model_dtype,
+ trust_remote_code=not args.disable_trust_remote_code,
+ )
+ if tokenizer is None:
+ tokenizer = loaded_tokenizer
+ else:
from transformers import AutoModelForCausalLM, AutoTokenizer
- eval_model_dtype = get_model_dtype(args.eval_model_dtype, "auto")
model = AutoModelForCausalLM.from_pretrained(
- eval_folder, device_map=args.device_map, torch_dtype=eval_model_dtype
+ eval_folder, device_map=device_str, torch_dtype=eval_model_dtype
)
model.eval()
if tokenizer is None:
tokenizer = AutoTokenizer.from_pretrained(eval_folder)
- else:
- eval_model_dtype = get_model_dtype(args.eval_model_dtype, "auto")
- model = prepare_model_for_eval(model, args.device_map, eval_model_dtype)
# Evaluate with model instance
evaluate_with_model_instance(model, tokenizer, device_str, args)
diff --git a/auto_round/utils/model_free_utils.py b/auto_round/utils/model_free_utils.py
index c872c9e0e..239234ac6 100644
--- a/auto_round/utils/model_free_utils.py
+++ b/auto_round/utils/model_free_utils.py
@@ -1224,9 +1224,10 @@ def _quantize_weight_nvfp4_e5m3(
layer_name: str,
group_size: int = 16,
device: str = "cpu",
+ disable_opt_rtn: bool = False,
) -> dict[str, torch.Tensor]:
"""Fake-quantize a 2D weight tensor to NVFP4 E5M3 and return its high-precision QDQ weight."""
- from auto_round.data_type.nvfp import nvfp4_v2
+ from auto_round.data_type.base import create_quantizer
out_features, in_features = weight.shape
if group_size != 16:
@@ -1238,7 +1239,13 @@ def _quantize_weight_nvfp4_e5m3(
)
weight_dev = weight.to(device)
- qdq_weight, _, _ = nvfp4_v2(weight_dev, bits=4, group_size=group_size)
+ quantizer = create_quantizer(
+ {"data_type": "nvfp4_v2", "bits": 4, "group_size": group_size, "sym": True, "scale_dtype": torch.float32},
+ iters=0,
+ disable_opt_rtn=disable_opt_rtn,
+ )
+ quantizer.initialize(weight_dev)
+ qdq_weight = quantizer.quantize(weight_dev)
return {f"{layer_name}.weight": qdq_weight.to(dtype=weight.dtype, device="cpu")}
@@ -1270,9 +1277,10 @@ def _pack_weight_nvfp4_e5m3(
layer_name: str,
group_size: int = 16,
device: str = "cpu",
+ disable_opt_rtn: bool = False,
) -> dict[str, torch.Tensor]:
"""Pack FP4 E2M1 weights with unsigned E5M3 block scales."""
- from auto_round.data_type.nvfp import nvfp4_v2
+ from auto_round.data_type.base import create_quantizer
from auto_round.export.export_to_autoround.qlinear_fp import QuantLinear
out_features, in_features = weight.shape
@@ -1281,7 +1289,13 @@ def _pack_weight_nvfp4_e5m3(
f"NVFP4_E5M3 requires in_features divisible by group_size=16, got {in_features} for '{layer_name}'."
)
weight_dev = weight.to(device)
- _, scale, _ = nvfp4_v2(weight_dev, bits=4, group_size=group_size)
+ quantizer = create_quantizer(
+ {"data_type": "nvfp4_v2", "bits": 4, "group_size": group_size, "sym": True, "scale_dtype": torch.float32},
+ iters=0,
+ disable_opt_rtn=disable_opt_rtn,
+ )
+ quantizer.initialize(weight_dev)
+ scale = quantizer.qdq(weight_dev, materialize=True).scale
# nvfp4_v2 may return a flattened per-group scale layout (e.g. [N, 1]);
# normalize to [out_features, in_features // group_size] before packing
# so serialized .weight_scale keeps the expected 2D shape.
@@ -1391,6 +1405,7 @@ def _quantize_single_tensor(
layer_name=layer_name,
group_size=group_size,
device=device,
+ disable_opt_rtn=disable_opt_rtn,
)
logger.debug(f"Quantized (NVFP4_E5M3): {layer_name} (bits=4, group_size={group_size})")
return layer_name, out, layer_name, None
@@ -3054,12 +3069,18 @@ def _derive_dominant_int_scheme(
return None
(bits, group_size, sym, data_type), _ = counter.most_common(1)[0]
- return {
+ dominant = {
"bits": bits,
"group_size": group_size,
"sym": sym,
"data_type": data_type,
}
+ if data_type == _NVFP4_E5M3_DATA_TYPE:
+ for act_key in ("act_bits", "act_data_type", "act_group_size", "act_sym", "act_dynamic"):
+ value = scheme.get(act_key)
+ if value is not None:
+ dominant[act_key] = value
+ return dominant
def _build_quantization_config(
@@ -3144,6 +3165,7 @@ def _build_quantization_config(
dominant = _derive_dominant_int_scheme(quantized_layers, layer_config, default_scheme)
if dominant is not None:
default_scheme = dominant
+ data_type = (default_scheme.get("data_type") or "int").lower()
from auto_round.version import __version__
diff --git a/test/unit/common/advanced/test_evaluation_functions.py b/test/unit/common/advanced/test_evaluation_functions.py
index e195ada39..570e66a3b 100644
--- a/test/unit/common/advanced/test_evaluation_functions.py
+++ b/test/unit/common/advanced/test_evaluation_functions.py
@@ -206,6 +206,55 @@ def _fake_lm_eval_modules(simple_evaluate_impl):
class TestEvalArgumentForwarding:
+ def test_run_model_evaluation_fake_reloads_exported_artifact(self, tmp_path):
+ from auto_round.eval.evaluation import run_model_evaluation
+
+ args = _make_eval_args()
+ in_memory_model = MagicMock()
+ loaded_model = MagicMock()
+ tokenizer = MagicMock()
+ model_context = SimpleNamespace(model=in_memory_model)
+ autoround = SimpleNamespace(model_context=model_context)
+
+ with patch("auto_round.utils.model.detect_model_type", return_value="llm"), patch(
+ "auto_round.utils.device_manager.get_device_and_parallelism", return_value=("cpu", False)
+ ), patch("auto_round.utils.get_library_version", return_value="test"), patch(
+ "auto_round.utils.clear_memory"
+ ) as mock_clear_memory, patch(
+ "transformers.AutoModelForCausalLM.from_pretrained", return_value=loaded_model
+ ) as mock_from_pretrained, patch(
+ "auto_round.eval.evaluation.evaluate_with_model_instance"
+ ) as mock_evaluate:
+ run_model_evaluation(in_memory_model, tokenizer, autoround, str(tmp_path), ["fake"], args)
+
+ mock_from_pretrained.assert_called_once_with(str(tmp_path), device_map="cpu", torch_dtype="auto")
+ mock_clear_memory.assert_called_once()
+ assert model_context.model is None
+ mock_evaluate.assert_called_once_with(loaded_model, tokenizer, "cpu", args)
+
+ def test_run_model_evaluation_fake_reloads_mllm_artifact(self, tmp_path):
+ from auto_round.eval.evaluation import run_model_evaluation
+
+ args = _make_eval_args(mllm=True, disable_trust_remote_code=True)
+ in_memory_model = MagicMock()
+ loaded_model = MagicMock()
+ loaded_tokenizer = MagicMock()
+ autoround = SimpleNamespace(mllm=True, model_context=SimpleNamespace(model=in_memory_model))
+
+ with patch("auto_round.utils.model.detect_model_type", return_value="mllm"), patch(
+ "auto_round.utils.device_manager.get_device_and_parallelism", return_value=("cpu", False)
+ ), patch("auto_round.utils.get_library_version", return_value="test"), patch(
+ "auto_round.utils.clear_memory"
+ ), patch(
+ "auto_round.utils.model.mllm_load_model", return_value=(loaded_model, None, loaded_tokenizer, None)
+ ) as mock_load, patch(
+ "auto_round.eval.evaluation.evaluate_with_model_instance"
+ ) as mock_evaluate:
+ run_model_evaluation(in_memory_model, None, autoround, str(tmp_path), ["fake"], args)
+
+ mock_load.assert_called_once_with(str(tmp_path), device="cpu", torch_dtype="auto", trust_remote_code=False)
+ mock_evaluate.assert_called_once_with(loaded_model, loaded_tokenizer, "cpu", args)
+
def test_run_eval_task_by_task_forwards_eval_generation_arguments(self):
from auto_round.cli.main import run_eval
diff --git a/test/unit/common/data_type/test_nvfp.py b/test/unit/common/data_type/test_nvfp.py
index ac9576eae..0db81a493 100644
--- a/test/unit/common/data_type/test_nvfp.py
+++ b/test/unit/common/data_type/test_nvfp.py
@@ -38,6 +38,7 @@ from auto_round.data_type.nvfp import (
ref_fp4_quant,
ref_nvfp4_quant,
search_nvfp4_scale,
+ search_nvfp4_v2_scale,
)
from auto_round.data_type.utils import update_fused_layer_global_scales
@@ -306,6 +307,24 @@ class TestSearchNvfp4Scale:
search_nvfp4_scale(tensor, qw=None)
+class TestSearchNvfp4V2Scale:
+ def test_search_does_not_increase_weighted_mse(self):
+ torch.manual_seed(1)
+ tensor = torch.randn(8, 16, dtype=torch.float32)
+ qw = torch.rand_like(tensor) + 0.1
+
+ scales = search_nvfp4_v2_scale(tensor, qw=qw)
+ baseline, _, _ = nvfp4_v2(tensor, group_size=16)
+ optimized, _, _ = nvfp4_v2(tensor, group_size=16, max_scale=scales)
+
+ baseline_loss = ((baseline - tensor).square() * qw).sum()
+ optimized_loss = ((optimized - tensor).square() * qw).sum()
+ assert scales.shape == (tensor.shape[0],)
+ assert torch.all(scales >= 0.5)
+ assert torch.all(scales <= 1.51)
+ assert optimized_loss <= baseline_loss
+
+
# ---------------------------------------------------------------------------
# nv_fp4
# ---------------------------------------------------------------------------
diff --git a/test/unit/common/utils/test_cli_usage.py b/test/unit/common/utils/test_cli_usage.py
index 4675d2bc8..5ae47a08b 100644
--- a/test/unit/common/utils/test_cli_usage.py
+++ b/test/unit/common/utils/test_cli_usage.py
@@ -334,6 +334,43 @@ def test_run_opt_rtn_uses_recipe(monkeypatch):
assert args.nsamples == 128
+def test_model_free_cli_disable_opt_rtn(monkeypatch):
+ from auto_round import AutoRound
+ from auto_round.cli import main as cli_main
+ from auto_round.cli.algorithms import AlgorithmHandler
+
+ captured = {}
+ monkeypatch.setattr(cli_main, "tune", lambda args: captured.setdefault("args", args))
+
+ cli_main.start(
+ argv=[
+ "dummy-model",
+ "--scheme",
+ "NVFP4_E5M3",
+ "--model_free",
+ "--disable_opt_rtn",
+ ]
+ )
+
+ args = captured["args"]
+ configs = AlgorithmHandler.build_configs(args, cli_main._extract_common_quantization_kwargs(args))
+ compressor = AutoRound(
+ args.model,
+ scheme=args.scheme,
+ alg_configs=configs[-1],
+ model_free=args.model_free,
+ device_map="cpu",
+ enable_torch_compile=False,
+ )
+
+ assert args.model_free is True
+ assert args.iters == 0
+ assert args.disable_opt_rtn is True
+ assert configs[-1].disable_opt_rtn is True
+ assert type(compressor).__name__ == "ModelFreeCompressor"
+ assert compressor.disable_opt_rtn is True
+
+
def test_unknown_algorithm_help_exits_with_suggestion(monkeypatch):
from auto_round.cli import main as cli_main
diff --git a/test/unit/test_cpu/quantization/test_model_free.py b/test/unit/test_cpu/quantization/test_model_free.py
index a4fd6308a..63ad51a9d 100644
--- a/test/unit/test_cpu/quantization/test_model_free.py
+++ b/test/unit/test_cpu/quantization/test_model_free.py
@@ -499,6 +499,62 @@ def test_int_model_free_fake_export_has_no_quantization_config(tmp_path):
assert "quantization_config" not in json.load(f)
+def test_nvfp4_e5m3_model_free_fake_export_preserves_activation_config(tmp_path):
+ tensors = {"model.layers.0.self_attn.q_proj.weight": torch.randn(32, 32)}
+ model_dir = _make_model_dir(tmp_path, _LLAMA_CFG, tensors)
+ output_dir = str(tmp_path / "output")
+ compressor = _ModelFreeCompressorCore(
+ model_name_or_path=model_dir, output_dir=output_dir, scheme="NVFP4_E5M3", format="fake"
+ )
+ compressor.run()
+
+ assert "model.layers.0.self_attn.q_proj.weight" in _read_output_keys(output_dir)
+ quantization_config = _read_qconfig(output_dir)
+ assert quantization_config["packing_format"] == "auto_round:fake"
+ assert quantization_config["act_bits"] == 4
+ assert quantization_config["act_data_type"] == "nvfp4_v2"
+ with open(os.path.join(output_dir, "config.json")) as config_file:
+ assert json.load(config_file)["quantization_config"] == quantization_config
+
+ from types import SimpleNamespace
+
+ from transformers import LlamaConfig, LlamaForCausalLM
+
+ from auto_round.experimental.qmodules.fake import FakeActQuantLinear
+ from auto_round.inference.convert_model import convert_hf_model
+
+ config = LlamaConfig(
+ hidden_size=32, intermediate_size=64, num_hidden_layers=1, num_attention_heads=2, vocab_size=64
+ )
+ model = LlamaForCausalLM(config)
+ model.config.quantization_config = SimpleNamespace(**quantization_config)
+ model, used_backends = convert_hf_model(model, target_device="cpu")
+ layer = model.model.layers[0].self_attn.q_proj
+ assert used_backends == ["auto_round:fake"]
+ assert isinstance(layer, FakeActQuantLinear)
+ activation = torch.randn(2, 32)
+ assert not torch.equal(layer.qdq_input(activation), activation)
+
+
+def test_mixed_nvfp4_e5m3_fake_export_preserves_activation_config(tmp_path):
+ tensors = {"model.layers.0.self_attn.q_proj.weight": torch.randn(32, 32)}
+ model_dir = _make_model_dir(tmp_path, _LLAMA_CFG, tensors)
+ output_dir = str(tmp_path / "output")
+ compressor = _ModelFreeCompressorCore(
+ model_name_or_path=model_dir,
+ output_dir=output_dir,
+ scheme="BF16",
+ layer_config={"model.layers.0.self_attn.q_proj": {"scheme": "NVFP4_E5M3"}},
+ format="fake",
+ )
+ compressor.run()
+
+ quantization_config = _read_qconfig(output_dir)
+ assert quantization_config["packing_format"] == "auto_round:fake"
+ assert quantization_config["act_bits"] == 4
+ assert quantization_config["act_data_type"] == "nvfp4_v2"
+
+
def test_nvfp4_e5m3_model_free_end_to_end(tmp_path):
tensors = {
"model.layers.0.self_attn.q_proj.weight": torch.randn(32, 32),
@@ -690,6 +746,39 @@ def test_model_free_legacy_nvfp4_is_normalized_and_passthrough(tmp_path):
class TestModelFreeQuantize:
+ @pytest.mark.parametrize(
+ "disable_opt_rtn,expected_status",
+ [(False, "enabled"), (True, "disabled")],
+ )
+ def test_nvfp4_e5m3_startup_summary_reports_opt_rtn_status(
+ self, tmp_path, monkeypatch, disable_opt_rtn, expected_status
+ ):
+ tensors = {"model.decoder.layers.0.self_attn.q_proj.weight": torch.randn(4, 16)}
+ model_dir = _make_model_dir(tmp_path, _SIMPLE_CONFIG, tensors)
+ output_dir = str(tmp_path / "output")
+ info_mock = Mock()
+ monkeypatch.setattr("auto_round.compressors.model_free.logger.info", info_mock)
+ core = _ModelFreeCompressorCore(
+ model_name_or_path=model_dir,
+ output_dir=output_dir,
+ scheme="NVFP4_E5M3",
+ format="fake",
+ disable_opt_rtn=disable_opt_rtn,
+ device="cpu",
+ enable_torch_compile=False,
+ )
+ monkeypatch.setattr(core, "_process_all_shards", Mock(side_effect=RuntimeError("stop after summary")))
+
+ with pytest.raises(RuntimeError, match="stop after summary"):
+ core.run()
+
+ startup_summary = next(
+ call.args[0]
+ for call in info_mock.call_args_list
+ if call.args and isinstance(call.args[0], str) and call.args[0].startswith("Model-free quantization:")
+ )
+ assert f"Optimized RTN: {expected_status}" in startup_summary
+
def test_basic(self, tmp_path):
model_dir = _make_model_dir(tmp_path, _SIMPLE_CONFIG, _SIMPLE_TENSORS)
output_dir = str(tmp_path / "output")
diff --git a/test/unit/test_cpu/utils/test_model_free_utils.py b/test/unit/test_cpu/utils/test_model_free_utils.py
index f4e36613a..142b9a776 100644
--- a/test/unit/test_cpu/utils/test_model_free_utils.py
+++ b/test/unit/test_cpu/utils/test_model_free_utils.py
@@ -685,6 +685,35 @@ class TestQuantizeWeightMXFP:
assert out["layer.weight_scale"].dtype == torch.uint8
+# ===========================================================================
+# NVFP4 E5M3 optimized RTN
+# ===========================================================================
+
+
+def test_nvfp4_e5m3_model_free_honors_opt_rtn_toggle(monkeypatch):
+ from auto_round.data_type import nvfp
+
+ search_mock = Mock(wraps=nvfp.search_nvfp4_v2_scale)
+ monkeypatch.setattr(nvfp, "search_nvfp4_v2_scale", search_mock)
+ matcher = _matcher(
+ default={
+ "bits": 4,
+ "group_size": 16,
+ "sym": True,
+ "data_type": "nvfp4_v2",
+ "_output_format": "fake",
+ }
+ )
+ weight = torch.randn(4, 32, dtype=torch.bfloat16)
+
+ _quantize_single_tensor("layer.weight", weight, matcher, disable_opt_rtn=False)
+ search_mock.assert_called_once()
+
+ search_mock.reset_mock()
+ _quantize_single_tensor("layer.weight", weight, matcher, disable_opt_rtn=True)
+ search_mock.assert_not_called()
+
+
# ===========================================================================
# _build_mxfp_quantization_config (non-MoE, structural tests)
# ===========================================================================