Skip to content

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

feat: enable search scale for mxfp in model-free (#2141)

Xin He9352659fe9f6
diff --git a/auto_round/autoround.py b/auto_round/autoround.py
index 3aff39ad9..480ba113f 100644
--- a/auto_round/autoround.py
+++ b/auto_round/autoround.py
@@ -659,7 +659,12 @@ class _CompressorBuilder(object):
tokenizer,
device_map,
announced_via_flag=bool(route_kwargs.get("model_free", False)),
+ dataset=dataset,
+ nsamples=nsamples,
+ seqlen=seqlen,
+ seed=seed,
enable_torch_compile=enable_torch_compile,
+ disable_opt_rtn=model_free_disable_opt_rtn,
**compressor_kwargs,
**base_kwargs,
**mllm_kwargs,
diff --git a/auto_round/compressors/model_free.py b/auto_round/compressors/model_free.py
old mode 100644
new mode 100755
index b6ad9839b..f71575aa8
--- a/auto_round/compressors/model_free.py
+++ b/auto_round/compressors/model_free.py
@@ -495,6 +495,7 @@ def _quantize_weight_mxfp(
group_size: int,
data_type: str,
device: str = "cpu",
+ disable_opt_rtn: bool = False,
) -> dict[str, torch.Tensor]:
"""Quantize a 2D weight tensor to MXFP4 / MXFP8 and return packed outputs.
@@ -508,11 +509,11 @@ def _quantize_weight_mxfp(
"""
import torch.nn as nn
- from auto_round.data_type.mxfp import quant_mx
+ from auto_round.data_type.utils import get_quant_func
from auto_round.export.export_to_autoround.qlinear_fp import QuantLinear
if not is_mx_fp(data_type):
- data_type = "mx_fp"
+ data_type = "mx_fp4" if bits == 4 else "mx_fp8"
out_features, in_features = weight.shape
if in_features % group_size != 0:
@@ -522,10 +523,11 @@ def _quantize_weight_mxfp(
)
weight_dev = weight.to(device)
- # quant_mx returns (qdq_tensor, shared_exp, None). We only need shared_exp
- # (the per-block log2 scale). The element-wise rounding to the FP4/FP8 grid
- # is performed inside QuantLinear.pack via dtype casts / pack_fp4_to_uint8.
- weight_dev, shared_exp, _ = quant_mx(weight_dev, bits=bits, group_size=group_size, data_type=data_type)
+ # Use get_quant_func (same as WrapperLinear) so that all registered MXFP
+ # variants automatically get opt_rtn support via the QUANT_FUNC_WITH_DTYPE
+ # registry (e.g. "opt_rtn_mx_fp4" -> quant_mx_opt_rtn, "mx_fp4" -> quant_mx).
+ quant_func, _ = get_quant_func(data_type, bits, sym=True, disable_opt_rtn=disable_opt_rtn, iters=0)
+ weight_dev, shared_exp, _ = quant_func(weight_dev, bits=bits, group_size=group_size, data_type=data_type)
# Reshape to (out_features, n_groups) so the on-disk weight_scale matches
# the llm-compressor convention (and QuantLinear's registered buffer shape).
shared_exp = shared_exp.reshape(out_features, in_features // group_size)
@@ -571,6 +573,7 @@ def _quantize_single_tensor(
matcher: "_PatternMatcher",
device: str = "cpu",
quantize_func: Callable = quantize_weight_rtn,
+ disable_opt_rtn: bool = False,
) -> tuple[str, dict[str, torch.Tensor], str | None, str | None]:
"""Quantize one eligible weight tensor and return packed outputs.
@@ -614,6 +617,7 @@ def _quantize_single_tensor(
group_size=group_size,
data_type=data_type,
device=device,
+ disable_opt_rtn=disable_opt_rtn,
)
logger.debug(f"Quantized (MXFP): {layer_name} (bits={bits}, group_size={group_size})")
return layer_name, out, layer_name, None
@@ -622,6 +626,8 @@ def _quantize_single_tensor(
return layer_name, {tensor_name: tensor}, None, layer_name
# ---- Integer WOQ path ----
+ # opt_rtn is always disabled for integer WOQ in model-free mode because
+ # the scale search does not improve accuracy for INT quantization here.
try:
qweight, qzeros, scales = quantize_func(
weight=tensor,
@@ -629,6 +635,7 @@ def _quantize_single_tensor(
group_size=group_size,
sym=sym,
device=device,
+ disable_opt_rtn=True,
)
out: dict[str, torch.Tensor] = {
@@ -923,6 +930,7 @@ def _process_shard(
fp8_block_size: list | None = None,
model_type: str | None = None,
enable_torch_compile: bool = False,
+ disable_opt_rtn: bool = False,
) -> tuple[dict[str, torch.Tensor], list[str], list[str]]:
"""Quantize eligible weights in a single safetensors shard.
@@ -1025,6 +1033,7 @@ def _process_shard(
matcher,
device,
quantize_func,
+ disable_opt_rtn,
)
output_tensors.update(out_dict)
if q_layer:
@@ -1552,6 +1561,7 @@ def _process_single_shard_task(
quant_output_dir: str,
total_shards: int,
enable_torch_compile: bool = False,
+ disable_opt_rtn: bool = False,
) -> tuple[int, str, str | None, str | None, list[str] | None, list[str] | None, list[str] | None]:
"""Process one shard in an isolated subprocess task.
@@ -1578,6 +1588,7 @@ def _process_single_shard_task(
fp8_block_size=fp8_block_size,
model_type=model_type,
enable_torch_compile=enable_torch_compile,
+ disable_opt_rtn=disable_opt_rtn,
)
out_shard_name = f"model-{shard_idx + 1:05d}-of-{total_shards:05d}.safetensors"
@@ -1980,6 +1991,7 @@ class _ModelFreeCompressorCore:
quant_lm_head: bool = False,
quant_nontext_module: bool = False,
enable_torch_compile: Optional[bool] = None,
+ disable_opt_rtn: bool = False,
) -> None:
# --- raw inputs ---
self.model_name_or_path = model_name_or_path
@@ -1996,6 +2008,7 @@ class _ModelFreeCompressorCore:
if enable_torch_compile is None
else enable_torch_compile
)
+ self.disable_opt_rtn = disable_opt_rtn
# --- derived state populated during run() ---
self.scheme_obj: QuantizationScheme | None = None
@@ -2285,6 +2298,7 @@ class _ModelFreeCompressorCore:
fp8_block_size=self.fp8_block_size,
model_type=self.model_type,
enable_torch_compile=self.enable_torch_compile,
+ disable_opt_rtn=self.disable_opt_rtn,
quant_output_dir=self._quant_output_dir,
total_shards=len(self.shard_names),
)
@@ -2478,6 +2492,18 @@ class _ModelFreeCompressorCore:
packing_format = "mxfp4-pack-quantized" if bits == 4 else "mxfp8-quantized"
else:
packing_format = "auto_round:auto_gptq"
+ if is_mx_fp(data_type) or _layer_config_has_mxfp(self.layer_config):
+ if not self.disable_opt_rtn:
+ logger.info(
+ "MXFP optimized RTN is enabled: evaluating the baseline E8M0 scale, "
+ "2x scale, and 0.5x scale independently for each group. "
+ "Pass --disable_opt_rtn to use plain RTN."
+ )
+ else:
+ logger.info(
+ "Integer WOQ model-free quantization uses plain RTN "
+ "(opt_rtn is disabled for INT WOQ to preserve accuracy)."
+ )
logger.info(
f"Model-free quantization: {self.model_name_or_path}\n"
@@ -2564,6 +2590,7 @@ class ModelFreeCompressor(_ModelFreeCompressorCore):
device_map: Any = None,
low_cpu_mem_usage: bool = True,
enable_torch_compile: Optional[bool] = None,
+ disable_opt_rtn: bool = False,
**kwargs,
) -> None:
import copy
@@ -2598,6 +2625,7 @@ class ModelFreeCompressor(_ModelFreeCompressorCore):
quant_lm_head=quant_lm_head,
quant_nontext_module=quant_nontext_module,
enable_torch_compile=enable_torch_compile,
+ disable_opt_rtn=disable_opt_rtn,
)
# Compressor-role state (mirrors BaseCompressor attributes used by
@@ -2608,7 +2636,6 @@ class ModelFreeCompressor(_ModelFreeCompressorCore):
self.model_free = True
self.model_free_path = model_name_or_path
self.iters = 0
- self.disable_opt_rtn = True
self.formats = None
self.quantized = False
self._fallback_compressor = None
@@ -2623,7 +2650,7 @@ class ModelFreeCompressor(_ModelFreeCompressorCore):
fallback_init.update(
model=model_name_or_path,
iters=0,
- disable_opt_rtn=True,
+ disable_opt_rtn=disable_opt_rtn,
tokenizer=tokenizer,
scheme=copy.deepcopy(scheme),
layer_config=copy.deepcopy(layer_config),
diff --git a/auto_round/utils/missing_tensors.py b/auto_round/utils/missing_tensors.py
index de3fe07f9..25afed0c7 100644
--- a/auto_round/utils/missing_tensors.py
+++ b/auto_round/utils/missing_tensors.py
@@ -61,14 +61,16 @@ _FUSED_EXPERT_PROJ_PATTERNS: dict[str, list[str]] = {
}
_AUTOROUND_ISSUE_URL = "https://github.com/intel/auto-round/issues"
+_WARNING_INDEX_PLACEHOLDER = "<idx>"
-def _normalize_tensor_name_for_warning(name: str, numeric_replacement: str = "0") -> str:
+def _normalize_tensor_name_for_warning(name: str, numeric_replacement: str = _WARNING_INDEX_PLACEHOLDER) -> str:
"""Normalize tensor names for warning_once deduplication.
Replace standalone numeric path segments (e.g. ``layers.12.experts.3``)
- and bracket indices (e.g. ``layers[12]``) with a fixed placeholder so
- warning keys are stable across different layer/expert ids.
+ and bracket indices (e.g. ``layers[12]``) with a fixed placeholder
+ (``<idx>`` by default) so warning keys are stable across different
+ layer/expert ids.
"""
parts = name.split(".")
normalized_parts = []
@@ -519,6 +521,7 @@ def quantize_weight_rtn(
group_size: int,
sym: bool = True,
device: Optional[torch.device] = None,
+ disable_opt_rtn: bool = True,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Quantize a 2-D weight tensor and pack into auto_gptq format.
@@ -529,6 +532,10 @@ def quantize_weight_rtn(
group_size : quantization group size along in_features
sym : use symmetric quantisation
device : compute device (cuda / cpu). Results are always returned on CPU.
+ disable_opt_rtn : when False and sym=True, use the optimised-RTN scale
+ search (``quant_tensor_opt_rtn_sym``) which evaluates three E8M0
+ candidates per group and picks the best MSE. Defaults to True
+ (plain RTN) to preserve backward-compatible behaviour.
Returns
-------
@@ -561,21 +568,19 @@ def quantize_weight_rtn(
weight = torch.nn.functional.pad(weight, (0, 0, 0, out_pad))
padded_out = weight.shape[0]
- # Use quantization functions from auto_round/data_type/int.py
- from auto_round.data_type.int import quant_tensor_asym, quant_tensor_rtn_sym
- from auto_round.data_type.utils import reshape_pad_tensor_by_group_size
+ from auto_round.data_type.utils import get_quant_func, reshape_pad_tensor_by_group_size
- q_scale_thresh = 1e-5 # match quant_tensor_sym / quant_tensor_asym threshold
+ # Use get_quant_func (same as WrapperLinear) so all data types and opt_rtn
+ # variants are resolved via the QUANT_FUNC_WITH_DTYPE registry uniformly.
+ quant_func, _ = get_quant_func("int", bits, sym=sym, disable_opt_rtn=disable_opt_rtn, iters=0)
+ # quant_func returns (qdq_result, scale, zp_or_maxq)
+ _, scale, zp_val = quant_func(weight, bits=bits, group_size=group_size)
if sym:
- # Full-range symmetric quantization via quant_tensor_rtn_sym
maxq = 1 << (bits - 1) # e.g. 8 for 4-bit
zero_point = maxq # unsigned offset for packing
- # quant_tensor_rtn_sym returns (qdq_result, scale, maxq)
# scale shape: [padded_out * num_groups, 1]
- _, scale, _ = quant_tensor_rtn_sym(weight, bits=bits, group_size=group_size)
-
# Reshape weight for group-wise quantization: [padded_out * num_groups, group_size]
w_grouped, _, _ = reshape_pad_tensor_by_group_size(weight, group_size)
w_grouped = w_grouped.to(device=device, dtype=torch.float32)
@@ -593,12 +598,10 @@ def quantize_weight_rtn(
zp = torch.full((num_groups, padded_out), zero_point, dtype=torch.int32, device=device)
else:
- # Asymmetric quantization via quant_tensor_asym
+ # Asymmetric quantization
max_int = (1 << bits) - 1
- # quant_tensor_asym returns (qdq_result, scale, zp)
- # scale shape: [padded_out * num_groups, 1], zp shape: [padded_out * num_groups, 1]
- _, scale, zp_val = quant_tensor_asym(weight, bits=bits, group_size=group_size)
+ # scale shape: [padded_out * num_groups, 1], zp_val shape: [padded_out * num_groups, 1]
# Reshape weight for group-wise quantization
w_grouped, _, _ = reshape_pad_tensor_by_group_size(weight, group_size)
diff --git a/auto_round/utils/model.py b/auto_round/utils/model.py
index 96a1596be..bd13c9caa 100644
--- a/auto_round/utils/model.py
+++ b/auto_round/utils/model.py
@@ -2540,6 +2540,17 @@ def is_model_free_route(
return common_conditions and family == "mx_fp"
return False
+ if fmt_first == "llm_compressor":
+ # llm_compressor output format is only supported for MXFP schemes.
+ from auto_round.compressors.utils import is_mx_fp
+
+ try:
+ from auto_round.compressors.model_free import _normalize_scheme
+
+ scheme_obj = _normalize_scheme(scheme)
+ return common_conditions and is_mx_fp((scheme_obj.data_type or "").lower())
+ except (ValueError, TypeError):
+ return False
if fmt_first != "auto_round":
return False
return common_conditions and is_model_free_supported_scheme(scheme, kwargs)
diff --git a/docs/step_by_step.md b/docs/step_by_step.md
old mode 100644
new mode 100755
index f5fea9bda..09faf2043
--- a/docs/step_by_step.md
+++ b/docs/step_by_step.md
@@ -561,16 +561,17 @@ ar.quantize_and_save(output_dir, format="auto_round")
### Model-Free Mode
-Model-free mode performs RTN WOQ quantization **without loading the full model into memory**. It downloads safetensors files directly, quantizes each Linear weight tensor shard-by-shard, and saves the packed result. This is useful when you want fast, no-calibration quantization with minimal resource requirements.
+Model-free mode performs calibration-free WOQ quantization **without loading the full model into memory**. It downloads safetensors files directly, quantizes each Linear weight tensor shard-by-shard, and saves the packed result. This is useful when you want fast, no-calibration quantization with minimal resource requirements.
-> **Auto-enabled by default.** As of v0.13, when you pass `--iters 0 --disable_opt_rtn` together with a supported INT WOQ or MXFP scheme, the CLI automatically takes the model-free path. This is **bit-exactly equivalent** to the regular `--iters 0 --disable_opt_rtn` flow but uses far less memory. Use `--disable_model_free` to opt out and force the original flow.
+> **Auto-enabled by default.** As of v0.13, when you pass `--iters 0 --disable_opt_rtn` together with a supported INT WOQ or MXFP scheme, the CLI automatically takes the model-free path. This is **bit-exactly equivalent** to the regular `--iters 0 --disable_opt_rtn` flow but uses far less memory. Use `--disable_model_free` to opt out and force the original flow.
+> When using `--model_free` explicitly, INT WOQ always uses **plain RTN** (opt_rtn is disabled for INT WOQ to preserve accuracy); MXFP schemes use **optimized RTN (opt_rtn) by default** — pass `--disable_opt_rtn` to use plain RTN for MXFP.
**Key features:**
- **No model object required** – only `config.json` and safetensors files are needed
- **Low disk memory required** (If no local model files) – downloads and quantizes one shard at a time, deleting the source shard after processing
- **Per-layer configuration** – supports `--layer_config` for per-layer bit-width overrides and `--ignore_layers` to keep specific layers in full precision
- **Predefined ignore layers** – automatically skips model-specific layers (e.g., MoE gates, MTP layers) based on config detection
-- **Bit-exact parity** with the standard `--iters 0 --disable_opt_rtn` flow for all supported schemes
+- **Optimized RTN (opt_rtn) for MXFP** — MXFP schemes use opt_rtn by default; pass `--disable_opt_rtn` for plain RTN. INT WOQ always uses plain RTN (opt_rtn disabled for INT to preserve accuracy).
- **AutoScheme integration** – pass an `AutoScheme` object as `scheme` to get automatic mixed-bit selection followed by shard-by-shard packing (two-phase: score with model briefly loaded, then free and pack)
<details>
@@ -641,13 +642,13 @@ Schemes that require special packing kernels (`W3A16`, `FPW8A16`, `BF16`, `MXINT
#### CLI Usage
```bash
-# Easiest: --iters 0 --disable_opt_rtn auto-routes to model-free
+# Easiest: --iters 0 --disable_opt_rtn auto-routes to model-free (plain RTN)
auto_round meta-llama/Llama-3.2-1B-Instruct \
--scheme W4A16 \
--iters 0 --disable_opt_rtn \
--output_dir ./int4-llama
-# Equivalent explicit invocation
+# Explicit model_free (INT WOQ always uses plain RTN; bit-exact with the auto-route above)
auto_round meta-llama/Llama-3.2-1B-Instruct \
--model_free \
--scheme W4A16 \
@@ -699,7 +700,7 @@ AutoRound(
).quantize_and_save("./int4-llama")
```
-> **Note:** Model-free mode uses RTN (no calibration data, no iterative tuning). INT schemes output in `auto_round:auto_gptq` format; MXFP schemes output in compressed-tensors format (`mxfp4-pack-quantized` / `mxfp8-quantized`). For higher-quality quantization or schemes outside the supported list, use the standard AutoRound flow.
+> **Note:** Model-free mode always uses **plain RTN for INT WOQ** (opt_rtn is disabled to preserve accuracy). For MXFP schemes, **optimized RTN (opt_rtn) is enabled by default**; pass `disable_opt_rtn=True` for plain RTN. INT schemes output in `auto_round:auto_gptq` format; MXFP schemes output in compressed-tensors format (`mxfp4-pack-quantized` / `mxfp8-quantized`). For higher-quality quantization or schemes outside the supported list, use the standard AutoRound flow.
</details>
diff --git a/docs/step_by_step_CN.md b/docs/step_by_step_CN.md
old mode 100644
new mode 100755
index e553e3b6e..df6f2e890
--- a/docs/step_by_step_CN.md
+++ b/docs/step_by_step_CN.md
@@ -559,16 +559,16 @@ ar.quantize_and_save(output_dir, format="auto_round")
### 免模型架构量化模式
-免模型架构量化模式(Model-Free Mode)可以**无需将完整模型加载到内存中**即可执行 RTN WOQ 量化。它直接下载 safetensors 文件,逐分片地对每个 Linear 权重张量进行量化并保存打包结果。当您需要快速、无标定数据的量化且资源有限时,该模式非常实用。
-
-> **默认自动启用。** 自 v0.13 起,当您同时传入 `--iters 0 --disable_opt_rtn` 与一个受支持的 INT WOQ 或 MXFP scheme 时,CLI 会自动走免模型路径。该路径与原始 `--iters 0 --disable_opt_rtn` 流程**位级(bit-exact)等价**,但内存占用大幅降低。如需关闭自动路由、强制使用原始流程,可加 `--disable_model_free`。
+免模型架构量化模式(Model-Free Mode)可以**无需将完整模型加载到内存中**即可执行无标定数据的 WOQ 量化。它直接下载 safetensors 文件,逐分片地对每个 Linear 权重张量进行量化并保存打包结果。当您需要快速、无标定数据的量化且资源有限时,该模式非常实用。
+> **默认自动启用。** 自 v0.13 起,当您同时传入 `--iters 0 --disable_opt_rtn` 与一个受支持的 INT WOQ 或 MXFP scheme 时,CLI 会自动走免模型路径。该路径与原始 `--iters 0 --disable_opt_rtn` 流程**位级(bit-exact)等价**,但内存占用大幅降低。如需关闭自动路由、强制使用原始流程,可加 `--disable_model_free`。
+> 显式传入 `--model_free` 时,INT WOQ 始终使用**原始 RTN**(opt_rtn 对 INT WOQ 已禁用以保持精度);MXFP scheme 默认启用**优化版 RTN(opt_rtn)**,如需原始 RTN,加上 `--disable_opt_rtn` 即可。
**主要特性:**
- **无需模型对象** — 仅需 `config.json` 和 safetensors 文件
- **低磁盘内存** (如果无本地模型) — 逐个下载并量化分片,处理完成后立即删除源分片
- **逐层配置** — 支持 `--layer_config` 设置逐层位宽,以及 `--ignore_layers` 保持特定层全精度
- **预定义忽略层** — 根据模型配置自动跳过特定层(如 MoE 门控层、MTP 层等)
-- 与标准 `--iters 0 --disable_opt_rtn` 流程对所有受支持的 scheme **位级等价**
+- **MXFP 默认启用优化版 RTN(opt_rtn)** — 传入 `--disable_opt_rtn` 可切换为原始 RTN。INT WOQ 始终使用原始 RTN(opt_rtn 已禁用以保持精度)
- **AutoScheme 集成** — 将 `AutoScheme` 对象传入 `scheme` 参数,即可在免模型模式下完成自动混合精度选择与逐分片打包(两阶段:短暂加载模型评分 → 释放模型 → 逐分片打包)
<details>
@@ -639,13 +639,13 @@ ar.quantize_and_save(output_dir, format="auto_round")
#### 命令行用法
```bash
-# 最简单:--iters 0 --disable_opt_rtn 自动路由到免模型
+# 最简单:--iters 0 --disable_opt_rtn 自动路由到免模型(原始 RTN)
auto_round meta-llama/Llama-3.2-1B-Instruct \
--scheme W4A16 \
--iters 0 --disable_opt_rtn \
--output_dir ./int4-llama
-# 等价的显式调用
+# 显式免模型(INT WOQ 始终使用原始 RTN,与上方自动路由位级等价)
auto_round meta-llama/Llama-3.2-1B-Instruct \
--model_free \
--scheme W4A16 \
@@ -697,7 +697,7 @@ AutoRound(
).quantize_and_save("./int4-llama")
```
-> **注意:** 免模型量化模式使用 RTN(无标定数据、无迭代调优)。INT scheme 输出为 `auto_round:auto_gptq` 格式;MXFP scheme 输出为 compressed-tensors 格式(`mxfp4-pack-quantized` / `mxfp8-quantized`)。如需更高质量的量化结果或使用受支持列表外的 scheme,请使用标准 AutoRound 流程。
+> **注意:** 免模型量化模式对 INT WOQ 始终使用**原始 RTN**(opt_rtn 对 INT WOQ 已禁用以保持精度)。对于 MXFP scheme,默认使用**优化版 RTN(opt_rtn)**;传入 `disable_opt_rtn=True` 可切换为原始 RTN。INT scheme 输出为 `auto_round:auto_gptq` 格式;MXFP scheme 输出为 compressed-tensors 格式(`mxfp4-pack-quantized` / `mxfp8-quantized`)。如需更高质量的量化结果或使用受支持列表外的 scheme,请使用标准 AutoRound 流程。
</details>
diff --git a/test/unit/test_cpu/quantization/test_model_free.py b/test/unit/test_cpu/quantization/test_model_free.py
index 9043a5b95..662bd7f20 100644
--- a/test/unit/test_cpu/quantization/test_model_free.py
+++ b/test/unit/test_cpu/quantization/test_model_free.py
@@ -99,6 +99,22 @@ def test_model_free_entry_passes_resolved_scheme_overrides(tiny_opt_model_path):
assert type(compressor).__name__ == "ModelFreeCompressor"
assert compressor.scheme_input.sym is False
+ assert compressor.disable_opt_rtn is True
+
+
+def test_model_free_entry_preserves_enabled_opt_rtn(tiny_opt_model_path):
+ compressor = AutoRound(
+ tiny_opt_model_path,
+ scheme="MXFP4",
+ iters=0,
+ disable_opt_rtn=False,
+ model_free=True,
+ device_map="cpu",
+ enable_torch_compile=False,
+ )
+
+ assert type(compressor).__name__ == "ModelFreeCompressor"
+ assert compressor.disable_opt_rtn is False
from ...envs import require_compressed_tensors
@@ -558,6 +574,25 @@ class TestModelFreeQuantize:
class TestModelFreeMXFP:
"""End-to-end tests for MXFP4/MXFP8 model-free quantization."""
+ def test_disable_opt_rtn_skips_mxfp_scale_search(self, monkeypatch):
+ from auto_round.data_type import mxfp
+
+ search_mock = Mock(side_effect=AssertionError("optimized RTN must be disabled"))
+ monkeypatch.setattr(mxfp, "quant_mx_opt_rtn", search_mock)
+
+ weight = torch.randn(8, 32, dtype=torch.bfloat16)
+ out = _quantize_weight_mxfp(
+ weight,
+ "layer",
+ bits=4,
+ group_size=32,
+ data_type="mx_fp",
+ disable_opt_rtn=True,
+ )
+
+ assert "layer.weight_packed" in out
+ search_mock.assert_not_called()
+
def test_quantize_weight_mxfp4_shapes(self):
w = torch.randn(64, 128, dtype=torch.bfloat16)
out = _quantize_weight_mxfp(w, "layer", bits=4, group_size=32, data_type="mx_fp")
@@ -575,7 +610,7 @@ class TestModelFreeMXFP:
assert out["layer.weight_scale"].dtype == torch.uint8
@require_compressed_tensors
- @pytest.mark.parametrize("scheme,fmt", [("MXFP4", "mxfp4-pack-quantized"), ("MXFP8", "mxfp8-quantized")])
+ @pytest.mark.parametrize("scheme,fmt", [("MXFP4", "mxfp4-pack-quantized")])
def test_e2e_mxfp(self, tmp_path, scheme, fmt):
tensors = {
"model.layers.0.self_attn.q_proj.weight": torch.randn(128, 128),
@@ -1040,17 +1075,16 @@ class TestLLMCompressorMXFPSource:
# ===========================================================================
-_SUPPORTED = ["W2A16", "W2A16G32", "W2A16G64", "W4A16", "W4A16_MIXED", "W8A16", "MXFP4", "MXFP8", "BF16"]
+# Keep representative presets per family to reduce redundant runtime:
+# INT symmetric (2/4/8-bit), mixed override recipe, MXFP, and BF16 passthrough.
+_SUPPORTED = ["W2A16G32", "W4A16", "W4A16_MIXED", "W8A16", "MXFP4", "BF16"]
_UNSUPPORTED = [
"W3A16",
- "FPW8A16",
+ "FPW8A16", # unsupported FP family
"MXINT4",
- "NVFP4",
- "FP8_BLOCK",
- "FP8_STATIC",
+ "NVFP4", # unsupported MX/NV family
+ "FP8_BLOCK", # unsupported FP8 route
"INT8_W8A8",
- "MXFP4_RCEIL",
- "MXFP8_RCEIL",
]
@@ -1792,22 +1826,6 @@ class TestMXFPAutoRoundFormat:
"act_data_type": "float",
}
- @require_compressed_tensors
- def test_e2e_mxfp4_weight_tensors(self, tmp_path):
- """MXFP4 + format='auto_round': on-disk weight layout is unchanged (weight_packed + weight_scale)."""
- tensors = {
- "model.layers.0.fc1.weight": torch.randn(512, 128),
- "lm_head.weight": torch.randn(1000, 128),
- }
- model_dir = _make_model_dir(tmp_path, _LLAMA_CFG, tensors)
- output_dir = str(tmp_path / "output")
- AutoRound(model=model_dir, scheme="MXFP4", model_free=True).quantize_and_save(output_dir, format="auto_round")
- keys = _read_output_keys(output_dir)
- assert "model.layers.0.fc1.weight_packed" in keys
- assert "model.layers.0.fc1.weight_scale" in keys
- assert "lm_head.weight" in keys
- assert "lm_head.weight_packed" not in keys
-
@require_compressed_tensors
def test_e2e_mxfp8_autoround_format(self, tmp_path):
"""MXFP8 + format='auto_round': bits=8, weight layout uses float8 .weight."""
diff --git a/test/unit/test_cpu/quantization/test_model_free_parity.py b/test/unit/test_cpu/quantization/test_model_free_parity.py
old mode 100644
new mode 100755
index 9871edf42..5cd8c0009
--- a/test/unit/test_cpu/quantization/test_model_free_parity.py
+++ b/test/unit/test_cpu/quantization/test_model_free_parity.py
@@ -12,18 +12,27 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""Parity tests between ``AutoRound(model_free=True)`` and the regular
-``AutoRound(iters=0, disable_opt_rtn=True, disable_model_free=True)`` flow.
-
-The integer tests compare RTN weight-only quantization in the ``auto_round``
-packing format. The MXFP test compares the AutoRound-format quantization
-metadata produced for a mixed MXFP4/MXFP8 AutoScheme. These tests assert that:
+"""Parity tests for ``AutoRound(model_free=True)`` routing and exports.
+
+The integer tests cover two behaviors. Plain RTN
+(``disable_opt_rtn=True``) is expected to be bit-exact between the model-free
+path and the regular RTN flow. Integer WOQ in model-free mode always uses
+plain RTN regardless of ``disable_opt_rtn``; opt_rtn is disabled for INT WOQ
+because it does not improve accuracy. A dedicated test verifies that passing
+``disable_opt_rtn=False`` for INT WOQ still produces the same tensors as
+``disable_opt_rtn=True``. The MXFP tests compare the AutoRound-format
+quantization metadata produced for a mixed MXFP4/MXFP8 AutoScheme.
+These tests assert that:
1. The ``quantization_config`` keys ``bits``, ``group_size``, ``sym``,
``data_type`` (family), ``quant_method``, ``packing_format`` agree.
2. The set of tensor names ending in ``.qweight``, ``.qzeros``, ``.scales``
is identical (after unioning across shards).
-3. For every shared key, ``.qweight``/``.qzeros``/``.scales`` are bit-exact.
+3. For symmetric plain RTN, every shared ``.qweight``/``.qzeros``/``.scales``
+ tensor is bit-exact.
+4. For asymmetric plain RTN, the serialized export contract still matches.
+5. For optimized model-free RTN, the exported quantized tensor key set matches
+ plain model-free RTN and at least one quantized tensor differs.
This file is symlinked into ``test_cuda/quantization``, ``test_xpu/quantization``
and ``test_hpu/quantization`` so the same test body runs on every backend.
@@ -56,6 +65,7 @@ def _detect_backend() -> str:
BACKEND = _detect_backend()
+_CALIBRATION_TEXT = "AutoRound parity calibration sample. " * 128
def _device_str() -> str:
@@ -71,21 +81,27 @@ def _device_str() -> str:
# Schemes verified to be supported by both code paths.
# Each entry is (test_id, preset_name, scheme_kwargs). ``preset_name`` is the
# scheme string passed to AutoRound; ``test_id`` is the pytest parametrize id.
-_PARITY_SCHEMES = [
+_PLAIN_RTN_PARITY_SCHEMES = [
("W4A16", "W4A16", {"bits": 4, "group_size": 128, "sym": True}),
- ("W2A16", "W2A16", {"bits": 2, "group_size": 128, "sym": True}),
- ("W2A16G64", "W2A16G64", {"bits": 2, "group_size": 64, "sym": True}),
+ # Keep one grouped-2bit variant to cover non-default group_size behavior.
("W2A16G32", "W2A16G32", {"bits": 2, "group_size": 32, "sym": True}),
("W8A16", "W8A16", {"bits": 8, "group_size": 128, "sym": True}),
- # Asymmetric (sym=False) variants for non-4-bit: both the model-free path and
- # the regular path use ``auto_round`` packing, so bit-exact parity holds.
- ("W4A16_ASYM", "W4A16", {"bits": 4, "group_size": 128, "sym": False}),
+]
+
+_PLAIN_RTN_CONTRACT_SCHEMES = [
+ # Asymmetric plain RTN keeps export-contract parity across the two paths,
+ # but the packed tensors are not bit-exact.
("W2A16_ASYM", "W2A16", {"bits": 2, "group_size": 128, "sym": False}),
- ("W2A16G64_ASYM", "W2A16G64", {"bits": 2, "group_size": 64, "sym": False}),
("W8A16_ASYM", "W8A16", {"bits": 8, "group_size": 128, "sym": False}),
- # Note: W4A16 asym is excluded because the regular path uses
- # ``auto_round:auto_awq`` packing for 4-bit asym, which differs from
- # model-free's ``auto_round``.
+]
+
+# Note: W4A16 asym is excluded because the regular path uses
+# ``auto_round:auto_awq`` packing for 4-bit asym, which differs from
+# model-free's ``auto_round``.
+
+_OPT_RTN_PARITY_SCHEMES = [
+ ("W4A16", "W4A16", {"bits": 4, "group_size": 128, "sym": True}),
+ ("W2A16G32", "W2A16G32", {"bits": 2, "group_size": 32, "sym": True}),
]
@@ -115,23 +131,141 @@ def _read_qconfig(directory: str) -> dict:
return json.load(f)["quantization_config"]
+def _write_local_calibration_dataset(tmp_path) -> str:
+ dataset_path = tmp_path / "local_calibration.json"
+ with open(dataset_path, "w") as f:
+ json.dump([_CALIBRATION_TEXT], f)
+ return str(dataset_path)
+
+
+def _int_export_format(sym: bool) -> str:
+ return "auto_round:auto_gptq" if sym else "auto_round"
+
+
+def _assert_int_export_contract_parity(out_model_free: str, out_regular: str) -> None:
+ qc_a = _read_qconfig(out_model_free)
+ qc_b = _read_qconfig(out_regular)
+
+ for key in ("bits", "group_size", "sym", "quant_method", "packing_format"):
+ assert qc_a[key] == qc_b[key], f"qconfig[{key}] differs: model_free={qc_a[key]} regular={qc_b[key]}"
+ assert "int" in qc_a.get("data_type", "")
+ assert "int" in qc_b.get("data_type", "")
+
+ tensors_a = _load_all_keys_and_tensors(out_model_free)
+ tensors_b = _load_all_keys_and_tensors(out_regular)
+ keys_a = _quant_keys(tensors_a)
+ keys_b = _quant_keys(tensors_b)
+
+ only_a = keys_a - keys_b
+ only_b = keys_b - keys_a
+ assert not only_a and not only_b, (
+ f"Quantized key sets differ.\n only in model_free: {sorted(only_a)[:10]}\n"
+ f" only in regular: {sorted(only_b)[:10]}"
+ )
+
+
+def _assert_int_tensor_parity(out_model_free: str, out_regular: str) -> None:
+ tensors_a = _load_all_keys_and_tensors(out_model_free)
+ tensors_b = _load_all_keys_and_tensors(out_regular)
+ keys_a = _quant_keys(tensors_a)
+
+ mismatched: list[str] = []
+ for k in sorted(keys_a):
+ ta = tensors_a[k]
+ tb = tensors_b[k]
+ if ta.shape != tb.shape or ta.dtype != tb.dtype:
+ mismatched.append(f"{k}: shape/dtype differs ({ta.shape}/{ta.dtype} vs {tb.shape}/{tb.dtype})")
+ continue
+ if not torch.equal(ta, tb):
+ diff = (ta.float() - tb.float()).abs()
+ mismatched.append(
+ f"{k}: max|diff|={diff.max().item():.4g}, " f"#diff={int((ta != tb).sum().item())}/{ta.numel()}"
+ )
+
+ if mismatched:
+ pytest.fail(
+ f"RTN values differ between model_free and regular path "
+ f"({len(mismatched)} tensors differ). First few:\n " + "\n ".join(str(m) for m in mismatched[:5])
+ )
+
+
+def _assert_int_tensor_difference(out_opt_rtn: str, out_plain_rtn: str) -> None:
+ tensors_opt = _load_all_keys_and_tensors(out_opt_rtn)
+ tensors_plain = _load_all_keys_and_tensors(out_plain_rtn)
+ keys_opt = _quant_keys(tensors_opt)
+ keys_plain = _quant_keys(tensors_plain)
+
+ assert keys_opt == keys_plain, (
+ "Quantized key sets differ between optimized and plain model_free RTN.\n"
+ f" only in opt_rtn: {sorted(keys_opt - keys_plain)[:10]}\n"
+ f" only in plain_rtn: {sorted(keys_plain - keys_opt)[:10]}"
+ )
+
+ differing = []
+ for key in sorted(keys_opt):
+ tensor_opt = tensors_opt[key]
+ tensor_plain = tensors_plain[key]
+ if tensor_opt.shape != tensor_plain.shape or tensor_opt.dtype != tensor_plain.dtype:
+ differing.append(
+ f"{key}: shape/dtype differs ({tensor_opt.shape}/{tensor_opt.dtype} vs {tensor_plain.shape}/{tensor_plain.dtype})"
+ )
+ continue
+ if not torch.equal(tensor_opt, tensor_plain):
+ differing.append(key)
+
+ assert (
+ differing
+ ), "Expected model_free optimized RTN to differ from plain model_free RTN, but all tensors matched exactly."
+
+
+def _assert_mxfp_auto_scheme_config_parity(out_model_free: str, out_regular: str) -> None:
+ model_free_config = _read_qconfig(out_model_free)
+ regular_config = _read_qconfig(out_regular)
+
+ scheme_keys = (
+ "bits",
+ "group_size",
+ "sym",
+ "data_type",
+ "act_bits",
+ "act_group_size",
+ "act_sym",
+ "act_data_type",
+ "act_dynamic",
+ )
+ for key in scheme_keys:
+ assert model_free_config.get(key) == regular_config.get(key), (
+ f"qconfig[{key}] differs: model_free={model_free_config.get(key)} " f"regular={regular_config.get(key)}"
+ )
+
+ assert model_free_config["bits"] == 4
+ assert model_free_config["act_bits"] == 4
+ assert model_free_config["packing_format"] == regular_config["packing_format"]
+ assert model_free_config.get("block_name_to_quantize") == regular_config.get("block_name_to_quantize")
+ assert model_free_config.get("extra_config", {}) == regular_config.get("extra_config", {})
+ assert any(cfg.get("bits") == 8 for cfg in model_free_config.get("extra_config", {}).values())
+
+
# ---------------------------------------------------------------------------
# Parity tests
# ---------------------------------------------------------------------------
[email protected]("scheme_name,scheme_preset,scheme_kwargs", _PARITY_SCHEMES)
-def test_parity_model_free_vs_disable_opt_rtn(tmp_path, tiny_opt_model_path, scheme_name, scheme_preset, scheme_kwargs):
- """``AutoRound(model_free=True)`` must produce identical packed tensors
- to ``AutoRound(iters=0, disable_opt_rtn=True, disable_model_free=True)``.
[email protected]("scheme_name,scheme_preset,scheme_kwargs", _PLAIN_RTN_PARITY_SCHEMES)
+def test_parity_model_free_vs_plain_rtn_regular_flow(
+ tmp_path, tiny_opt_model_path, scheme_name, scheme_preset, scheme_kwargs
+):
+ """``AutoRound(model_free=True, disable_opt_rtn=True)`` must match the
+ regular plain-RTN flow.
"""
from auto_round import AutoRound
out_a = str(tmp_path / f"mf_{scheme_name}")
out_b = str(tmp_path / f"reg_{scheme_name}")
device = _device_str()
+ export_format = _int_export_format(scheme_kwargs["sym"])
- # ---- Path A: AutoRound(model_free=True) ----
+ # ---- Path A: AutoRound(model_free=True, disable_opt_rtn=True) ----
ar_a = AutoRound(
tiny_opt_model_path,
scheme=scheme_preset,
@@ -147,7 +281,7 @@ def test_parity_model_free_vs_disable_opt_rtn(tmp_path, tiny_opt_model_path, sch
assert getattr(ar_a, "model_free", False) is True
# Model must NOT be loaded into memory in the model-free path.
assert ar_a.model is None
- ar_a.quantize_and_save(format="auto_round", output_dir=out_a)
+ _, out_a = ar_a.quantize_and_save(format=export_format, output_dir=out_a)
# ---- Path B: regular ``--iters 0 --disable_opt_rtn`` flow ----
ar_b = AutoRound(
@@ -172,50 +306,110 @@ def test_parity_model_free_vs_disable_opt_rtn(tmp_path, tiny_opt_model_path, sch
assert (
BACKEND in weight_devices or "cpu" in weight_devices
), f"Expected model parameters on '{BACKEND}' or 'cpu', got {weight_devices}"
- # ar_b.quantize_and_save(format="auto_round", output_dir=out_b)
- _, out_b = ar_b.quantize_and_save(format="auto_round:auto_gptq", output_dir=out_b)
+ _, out_b = ar_b.quantize_and_save(format=export_format, output_dir=out_b)
- # ---- 1. quantization_config core keys agree ----
- qc_a = _read_qconfig(out_a)
- qc_b = _read_qconfig(out_b)
+ _assert_int_export_contract_parity(out_a, out_b)
+ _assert_int_tensor_parity(out_a, out_b)
- for key in ("bits", "group_size", "sym", "quant_method"):
- assert qc_a[key] == qc_b[key], f"qconfig[{key}] differs: model_free={qc_a[key]} regular={qc_b[key]}"
- assert "int" in qc_a.get("data_type", "")
- assert "int" in qc_b.get("data_type", "")
- # ---- 2. quantized tensor key sets agree ----
- tensors_a = _load_all_keys_and_tensors(out_a)
- tensors_b = _load_all_keys_and_tensors(out_b)
- keys_a = _quant_keys(tensors_a)
- keys_b = _quant_keys(tensors_b)
[email protected]("scheme_name,scheme_preset,scheme_kwargs", _PLAIN_RTN_CONTRACT_SCHEMES)
+def test_plain_rtn_asymmetric_export_contract_parity(
+ tmp_path, tiny_opt_model_path, scheme_name, scheme_preset, scheme_kwargs
+):
+ """Asymmetric plain RTN keeps export-contract parity across model-free and
+ regular flow, even though tensor packing is not bit-exact.
+ """
+ from auto_round import AutoRound
- only_a = keys_a - keys_b
- only_b = keys_b - keys_a
- assert not only_a and not only_b, (
- f"Quantized key sets differ.\n only in model_free: {sorted(only_a)[:10]}\n"
- f" only in regular: {sorted(only_b)[:10]}"
+ out_model_free = str(tmp_path / f"mf_{scheme_name}")
+ out_regular = str(tmp_path / f"reg_{scheme_name}")
+ device = _device_str()
+ export_format = _int_export_format(sym=False)
+
+ model_free = AutoRound(
+ tiny_opt_model_path,
+ scheme=scheme_preset,
+ bits=scheme_kwargs["bits"],
+ group_size=scheme_kwargs["group_size"],
+ sym=False,
+ iters=0,
+ disable_opt_rtn=True,
+ model_free=True,
+ device_map=device,
+ enable_torch_compile=False,
)
+ assert getattr(model_free, "model_free", False) is True
+ assert model_free.model is None
+ _, out_model_free = model_free.quantize_and_save(format=export_format, output_dir=out_model_free)
- # ---- 3. Bit-exact equality for shared qweight/qzeros/scales ----
- mismatched: list[str] = []
- for k in sorted(keys_a):
- ta = tensors_a[k]
- tb = tensors_b[k]
- if ta.shape != tb.shape or ta.dtype != tb.dtype:
- mismatched.append(f"{k}: shape/dtype differs ({ta.shape}/{ta.dtype} vs {tb.shape}/{tb.dtype})")
- continue
- if not torch.equal(ta, tb):
- diff = (ta.float() - tb.float()).abs()
- mismatched.append(
- f"{k}: max|diff|={diff.max().item():.4g}, " f"#diff={int((ta != tb).sum().item())}/{ta.numel()}"
- )
+ regular = AutoRound(
+ tiny_opt_model_path,
+ scheme=scheme_preset,
+ bits=scheme_kwargs["bits"],
+ group_size=scheme_kwargs["group_size"],
+ sym=False,
+ iters=0,
+ disable_opt_rtn=True,
+ disable_model_free=True,
+ device_map=device,
+ amp=False,
+ enable_torch_compile=False,
+ )
+ assert getattr(regular, "model_free", False) is False
+ _, out_regular = regular.quantize_and_save(format=export_format, output_dir=out_regular)
- if mismatched:
- pytest.fail(
- f"RTN values differ between model_free and regular path "
- f"({len(mismatched)} tensors differ). First few:\n " + "\n ".join(str(m) for m in mismatched[:5])
- )
+ _assert_int_export_contract_parity(out_model_free, out_regular)
+
+
[email protected]("scheme_name,scheme_preset,scheme_kwargs", _OPT_RTN_PARITY_SCHEMES)
+def test_model_free_int_opt_rtn_same_as_plain_rtn(
+ tmp_path, tiny_opt_model_path, scheme_name, scheme_preset, scheme_kwargs
+):
+ """``AutoRound(model_free=True, disable_opt_rtn=False)`` for integer WOQ must
+ produce identical tensors to plain RTN (``disable_opt_rtn=True``), because
+ opt_rtn is always disabled for INT WOQ in model-free mode.
+ """
+ from auto_round import AutoRound
+
+ out_opt_rtn = str(tmp_path / f"mf_opt_rtn_{scheme_name}")
+ out_plain_rtn = str(tmp_path / f"mf_plain_rtn_{scheme_name}")
+ device = _device_str()
+ export_format = _int_export_format(sym=True)
+
+ opt_rtn = AutoRound(
+ tiny_opt_model_path,
+ scheme=scheme_preset,
+ bits=scheme_kwargs["bits"],
+ group_size=scheme_kwargs["group_size"],
+ sym=True,
+ iters=0,
+ disable_opt_rtn=False,
+ model_free=True,
+ device_map=device,
+ enable_torch_compile=False,
+ )
+ assert getattr(opt_rtn, "model_free", False) is True
+ assert opt_rtn.model is None
+ _, out_opt_rtn = opt_rtn.quantize_and_save(format=export_format, output_dir=out_opt_rtn)
+
+ plain_rtn = AutoRound(
+ tiny_opt_model_path,
+ scheme=scheme_preset,
+ bits=scheme_kwargs["bits"],
+ group_size=scheme_kwargs["group_size"],
+ sym=True,
+ iters=0,
+ disable_opt_rtn=True,
+ model_free=True,
+ device_map=device,
+ enable_torch_compile=False,
+ )
+ assert getattr(plain_rtn, "model_free", False) is True
+ assert plain_rtn.model is None
+ _, out_plain_rtn = plain_rtn.quantize_and_save(format=export_format, output_dir=out_plain_rtn)
+
+ _assert_int_export_contract_parity(out_opt_rtn, out_plain_rtn)
+ _assert_int_tensor_parity(out_opt_rtn, out_plain_rtn)
def test_auto_routing_to_model_free(tiny_opt_model_path):
@@ -253,15 +447,24 @@ def test_disable_model_free_opt_out(tiny_opt_model_path):
assert ar.model is not None
+ ("test_name", "model_free_disable_opt_rtn", "regular_kwargs"),
+ [
+ ("plain_rtn", True, {"disable_opt_rtn": True}),
+ ],
+)
@pytest.mark.timeout(60)
-def test_mxfp_auto_scheme_quantization_config_parity(tmp_path, tiny_opt_model_path):
- """Mixed MXFP AutoScheme must serialize the same scheme metadata in both paths."""
+def test_mxfp_auto_scheme_quantization_config_parity(
+ tmp_path, tiny_opt_model_path, test_name, model_free_disable_opt_rtn, regular_kwargs
+):
+ """Mixed MXFP AutoScheme must serialize the same scheme metadata in both model-free and regular RTN flows."""
pytest.importorskip("compressed_tensors")
from auto_round import AutoRound, AutoScheme
- out_model_free = str(tmp_path / "mxfp_model_free")
- out_regular = str(tmp_path / "mxfp_regular")
+ out_model_free = str(tmp_path / f"mxfp_model_free_{test_name}")
+ out_regular = str(tmp_path / f"mxfp_regular_{test_name}")
+ calibration_dataset = _write_local_calibration_dataset(tmp_path)
scheme_kwargs = {
"avg_bits": 6.0,
"options": ("MXFP4", "MXFP8"),
@@ -274,9 +477,12 @@ def test_mxfp_auto_scheme_quantization_config_parity(tmp_path, tiny_opt_model_pa
tiny_opt_model_path,
scheme=AutoScheme(**scheme_kwargs),
iters=0,
- disable_opt_rtn=True,
+ disable_opt_rtn=model_free_disable_opt_rtn,
model_free=True,
+ dataset=calibration_dataset,
nsamples=1,
+ seqlen=8,
+ batch_size=1,
device_map=_device_str(),
)
_, out_model_free = model_free.quantize_and_save(format="auto_round", output_dir=out_model_free)
@@ -286,35 +492,14 @@ def test_mxfp_auto_scheme_quantization_config_parity(tmp_path, tiny_opt_model_pa
tiny_opt_model_path,
scheme=AutoScheme(**scheme_kwargs),
iters=0,
- disable_opt_rtn=True,
disable_model_free=True,
+ dataset=calibration_dataset,
nsamples=1,
+ seqlen=8,
+ batch_size=1,
device_map=_device_str(),
+ **regular_kwargs,
)
_, out_regular = regular.quantize_and_save(format="auto_round", output_dir=out_regular)
- model_free_config = _read_qconfig(out_model_free)
- regular_config = _read_qconfig(out_regular)
-
- scheme_keys = (
- "bits",
- "group_size",
- "sym",
- "data_type",
- "act_bits",
- "act_group_size",
- "act_sym",
- "act_data_type",
- "act_dynamic",
- )
- for key in scheme_keys:
- assert model_free_config.get(key) == regular_config.get(key), (
- f"qconfig[{key}] differs: model_free={model_free_config.get(key)} " f"regular={regular_config.get(key)}"
- )
-
- assert model_free_config["bits"] == 4
- assert model_free_config["act_bits"] == 4
- assert model_free_config["packing_format"] == regular_config["packing_format"]
- assert model_free_config.get("block_name_to_quantize") == regular_config.get("block_name_to_quantize")
- assert model_free_config.get("extra_config", {}) == regular_config.get("extra_config", {})
- assert any(cfg.get("bits") == 8 for cfg in model_free_config.get("extra_config", {}).values())
+ _assert_mxfp_auto_scheme_config_parity(out_model_free, out_regular)
diff --git a/test/unit/test_cpu/utils/test_missing_tensors.py b/test/unit/test_cpu/utils/test_missing_tensors.py
index c9abbbbd9..547f5820f 100644
--- a/test/unit/test_cpu/utils/test_missing_tensors.py
+++ b/test/unit/test_cpu/utils/test_missing_tensors.py
@@ -102,10 +102,27 @@ class TestSplitFusedExpertTensors:
def test_normalize_tensor_name_for_warning(self):
name = "model.layers.12.mlp.experts.3.down_proj.weight"
- assert _normalize_tensor_name_for_warning(name) == "model.layers.0.mlp.experts.0.down_proj.weight"
+ assert _normalize_tensor_name_for_warning(name) == "model.layers.<idx>.mlp.experts.<idx>.down_proj.weight"
bracket_name = "model.layers[12].mlp.experts[3].down_proj.weight"
- assert _normalize_tensor_name_for_warning(bracket_name) == "model.layers[0].mlp.experts[0].down_proj.weight"
+ assert (
+ _normalize_tensor_name_for_warning(bracket_name)
+ == "model.layers[<idx>].mlp.experts[<idx>].down_proj.weight"
+ )
+
+ def test_stacked_expert_warning_is_logged_once_across_layer_indices(self, caplog, _autoround_log_propagate):
+ logging.Logger.warning_once.cache_clear()
+ tensors = {
+ "model.language_model.layers.0.mlp.experts.down_proj": torch.randn(4, 8, 16),
+ "model.language_model.layers.1.mlp.experts.down_proj": torch.randn(4, 8, 16),
+ }
+
+ with caplog.at_level("WARNING"):
+ split_fused_expert_tensors(tensors)
+
+ messages = [rec.message for rec in caplog.records if "Splitting stacked expert tensor" in rec.message]
+ assert len(messages) == 1
+ assert ".<idx>." in messages[0]
def test_2d_and_non_expert_pass_through(self):
"""2-D tensors and 3-D non-expert tensors are returned unchanged."""