Skip to content

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

fix issue of step3p7 and CI failure (#1929)

Xin He1c4baa034561
diff --git a/auto_round/compressors/model_free.py b/auto_round/compressors/model_free.py
index 96af475be..b94a81fab 100644
--- a/auto_round/compressors/model_free.py
+++ b/auto_round/compressors/model_free.py
@@ -253,9 +253,9 @@ def _list_weight_shards(source_dir: str) -> list[str]:
if fname.endswith(".safetensors.index.json"):
return _shards_from_index(os.path.join(source_dir, fname))
- # --- safetensors: any single .safetensors file ---
+ # --- safetensors: single file or index-less multi-file shards ---
st_files = sorted(f for f in os.listdir(source_dir) if f.endswith(".safetensors"))
- if len(st_files) == 1:
+ if len(st_files) >= 1:
return st_files
# --- pytorch .bin: standard index ---
@@ -275,12 +275,9 @@ def _list_weight_shards(source_dir: str) -> list[str]:
# --- pytorch .bin: any single .bin file ---
bin_files = sorted(f for f in os.listdir(source_dir) if f.endswith(".bin"))
- if len(bin_files) == 1:
+ if len(bin_files) >= 1:
return bin_files
- # --- safetensors: single file ---
- return ["model.safetensors"]
-
def _is_eligible_weight(tensor_name: str, tensor: torch.Tensor) -> bool:
"""Check if a tensor is eligible for quantization (2D Linear weight)."""
@@ -574,6 +571,8 @@ def _quantize_single_tensor(
layer_name = tensor_name.rsplit(".", 1)[0]
if not _is_eligible_weight(tensor_name, tensor):
+ if tensor_name.endswith(".weight"):
+ return layer_name, {tensor_name: tensor}, None, layer_name
return layer_name, {tensor_name: tensor}, None, None
if matcher.should_ignore(tensor_name):
@@ -845,6 +844,13 @@ def _process_shard(
Returns:
(output_tensors, quantized_layer_names, ignored_layer_names)
+
+ ``ignored_layer_names`` is derived by comparing the set of input ``.weight``
+ layer names (collected after fused-expert splitting) with the final set of
+ quantized layer names. Any layer that had a ``.weight`` tensor in the input
+ but was NOT quantized is reported as ignored — this correctly captures
+ user-ignored layers, predefined-skipped layers, non-eligible weights, and
+ any other pass-through case without separate per-tensor tracking.
"""
if matcher is None:
matcher = _PatternMatcher(
@@ -855,7 +861,6 @@ def _process_shard(
output_tensors: dict[str, torch.Tensor] = {}
quantized_layers: list[str] = []
- ignored_layers: list[str] = []
if shard_path.endswith(".bin"):
# PyTorch pickle checkpoint — load with weights_only where supported.
@@ -875,6 +880,12 @@ def _process_shard(
raw_tensors = split_fused_expert_tensors(raw_tensors)
+ # Snapshot eligible weight layer names *before* any preprocessing so that
+ # the ignored-layer list can be derived by dict comparison at the end.
+ input_weight_layers: list[str] = list(
+ dict.fromkeys(k.rsplit(".", 1)[0] for k in raw_tensors if k.endswith(".weight"))
+ )
+
# Preserve original tensors for ignored/skipped layers so that already-
# quantized weights (FP8, FP4-packed, etc.) are NOT dequantized.
# Check both ".weight" and ".weight_packed" so that layers whose primary
@@ -911,7 +922,7 @@ def _process_shard(
for tensor_name in list(raw_tensors.keys()):
tensor = raw_tensors.pop(tensor_name)
- _layer_name, out_dict, q_layer, ig_layer = _quantize_single_tensor(
+ _layer_name, out_dict, q_layer, _ig_layer = _quantize_single_tensor(
tensor_name,
tensor,
matcher,
@@ -920,8 +931,10 @@ def _process_shard(
output_tensors.update(out_dict)
if q_layer:
quantized_layers.append(q_layer)
- if ig_layer:
- ignored_layers.append(ig_layer)
+
+ # Derive ignored layers by comparing input weight layers with quantized set.
+ quantized_set = set(quantized_layers)
+ ignored_layers: list[str] = [l for l in input_weight_layers if l not in quantized_set]
return output_tensors, quantized_layers, ignored_layers
@@ -1394,7 +1407,14 @@ class _ModelFreeCompressorCore:
)
def _parse_scheme(self) -> None:
- self.scheme_obj = _normalize_scheme(self.scheme_input)
+ scheme_in = self.scheme_input
+ if isinstance(scheme_in, str) and scheme_in.upper() == "W4A16_MIXED":
+ # Match regular-flow mixed recipe behavior in model-free mode:
+ # default non-expert linear layers use 8-bit; expert overrides are
+ # injected in _parse_layer_config.
+ self.scheme_obj = _normalize_scheme("W8A16")
+ else:
+ self.scheme_obj = _normalize_scheme(scheme_in)
_validate_supported_scheme(self.scheme_obj, self.scheme_input)
ds = asdict(self.scheme_obj)
self.default_scheme = {k: v for k, v in ds.items() if v is not None}
@@ -1402,6 +1422,15 @@ class _ModelFreeCompressorCore:
def _parse_layer_config(self) -> None:
lc = copy.deepcopy(self.layer_config_input) if self.layer_config_input else {}
+ if isinstance(self.scheme_input, str) and self.scheme_input.upper() == "W4A16_MIXED":
+ # Keep shared experts at 8-bit while routing experts to 4-bit.
+ # User-provided layer_config entries (if any) still take priority.
+ if "shared_expert" not in lc:
+ lc[".shared_expert."] = {"bits": 8, "data_type": "int"}
+ if "expert" not in lc:
+ lc[".experts."] = {"bits": 4, "data_type": "int"}
+ lc[".moe."] = {"bits": 4, "data_type": "int"}
+
# Append '.' only for keys ending with ".<digits>" to avoid partial
# numeric matches (e.g. layer.1 should not match layer.10).
# Keep plain names like "fc2" untouched.
@@ -1648,6 +1677,15 @@ class _ModelFreeCompressorCore:
if len(self.shard_names) > 1:
logger.info(f"Memory usage: {memory_monitor.get_summary()}")
+ # Log per-shard summary
+ compressed_quantized = compress_layer_names(quantized)
+ compressed_ignored = compress_layer_names(ignored)
+ logger.info(
+ f"Shard {shard_idx + 1}/{len(self.shard_names)} ({shard_name}):\n"
+ f" Quantized layers ({len(quantized)}): {compressed_quantized}\n"
+ f" Ignored layers ({len(ignored)}): {compressed_ignored}"
+ )
+
self.all_quantized_layers.extend(quantized)
self.all_ignored_layers.extend(ignored)
diff --git a/auto_round/utils/missing_tensors.py b/auto_round/utils/missing_tensors.py
index 7f2dc922f..a25ca10cc 100644
--- a/auto_round/utils/missing_tensors.py
+++ b/auto_round/utils/missing_tensors.py
@@ -56,8 +56,11 @@ from auto_round.utils.weight_handler import _dequant_fp8_linear_weight
# slice to produce one tensor per split name per expert.
_FUSED_EXPERT_PROJ_PATTERNS: dict[str, list[str]] = {
"gate_up_proj": ["gate_proj", "up_proj"],
+ "w13": ["w1", "w3"],
}
+_AUTOROUND_ISSUE_URL = "https://github.com/intel/auto-round/issues"
+
def split_fused_expert_tensors(
tensors_dict: dict[str, torch.Tensor],
@@ -65,7 +68,8 @@ def split_fused_expert_tensors(
"""Split 3-D fused expert tensors into per-expert 2-D tensors.
Many MoE checkpoints store expert weights as fused 3-D parameters
- under ``*.experts.<proj_name>`` (for example ``gate_up_proj`` with shape
+ under either ``*.experts.<proj_name>`` or ``*.moe.<proj_name>``
+ (for example ``gate_up_proj`` with shape
``[num_experts, 2*intermediate, hidden]``, or ``down_proj`` with shape
``[num_experts, out, in]``). After unfusing, each expert gets its own
2-D weight tensor, e.g.
@@ -73,12 +77,16 @@ def split_fused_expert_tensors(
Splitting rules:
- * **gate_up_proj** ``[N, 2*inter, hidden]`` →
+ * **gate_up_proj** ``[N, 2*inter, hidden]`` →
``experts.{i}.gate_proj.weight`` + ``experts.{i}.up_proj.weight``
* **up_gate_proj** ``[N, 2*inter, hidden]`` →
``experts.{i}.up_proj.weight`` + ``experts.{i}.gate_proj.weight``
- * **Other** stacked projections (e.g. ``down_proj``) ``[N, out, in]`` →
- ``experts.{i}.<proj>.weight``
+ * **Other** stacked projections (e.g. ``down_proj``) ``[N, out, in]`` →
+ ``experts.{i}.<proj>.weight``
+
+ For ``*.moe.<proj_name>`` tensors, outputs use
+ ``*.moe.experts.{i}.<proj>.weight`` so they align with the sequential
+ expert module layout used by quantized MoE replacements.
Non-3-D or non-expert tensors pass through unchanged.
@@ -109,11 +117,25 @@ def split_fused_expert_tensors(
parent = stripped[:dot_idx]
proj_name = stripped[dot_idx + 1 :]
- # The immediate parent must be "experts"
- if not parent.endswith("experts") and parent.split(".")[-1] != "experts":
+ parent_last = parent.split(".")[-1]
+ is_experts_parent = parent.endswith("experts") or parent_last == "experts"
+ is_moe_parent = parent.endswith("moe") or parent_last == "moe"
+
+ # The immediate parent must be "experts" or "moe"
+ if not is_experts_parent and not is_moe_parent:
+ logger.warning(
+ "Found 3-D tensor '%s' with unsupported parent '%s' while splitting expert tensors; "
+ "it will be kept unchanged. If this is an MoE/expert weight that should be split/quantized, "
+ "please open an issue at %s.",
+ tensor_name,
+ parent,
+ _AUTOROUND_ISSUE_URL,
+ )
result[tensor_name] = tensor
continue
+ target_prefix = parent if is_experts_parent else f"{parent}.experts"
+
num_experts = tensor.shape[0]
if proj_name in _FUSED_EXPERT_PROJ_PATTERNS:
@@ -127,7 +149,7 @@ def split_fused_expert_tensors(
expert_2d = tensor[i] # [fused_out, in_features]
chunks = expert_2d.chunk(len(split_names), dim=0)
for split_name, chunk in zip(split_names, chunks):
- out_key = f"{parent}.{i}.{split_name}.weight"
+ out_key = f"{target_prefix}.{i}.{split_name}.weight"
result[out_key] = chunk.contiguous()
else:
logger.info(
@@ -136,7 +158,7 @@ def split_fused_expert_tensors(
)
for i in range(num_experts):
expert_2d = tensor[i] # [out, in]
- out_key = f"{parent}.{i}.{proj_name}.weight"
+ out_key = f"{target_prefix}.{i}.{proj_name}.weight"
result[out_key] = expert_2d.contiguous()
split_count += 1
diff --git a/test/helpers.py b/test/helpers.py
index 532bede10..5a1975bfe 100644
--- a/test/helpers.py
+++ b/test/helpers.py
@@ -49,14 +49,14 @@ def generate_prompt(model_obj_or_str, tokenizer=None, text="The capital of Franc
if not (hasattr(model, "hf_device_map") and len(model.hf_device_map) > 1):
model = model.to(device)
inputs = tokenizer(text, return_tensors="pt").to(model.device)
- generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens)[0]
+ generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)[0]
output = tokenizer.decode(generated_ids)
print(output)
return output
def eval_generated_prompt(
- model, tokenizer=None, prompt_text="The United States of", target_text="America", max_new_tokens=10, device=None
+ model, tokenizer=None, prompt_text="United States of", target_text="America", max_new_tokens=10, device=None
):
generated_text = generate_prompt(model, tokenizer, prompt_text, max_new_tokens=max_new_tokens, device=device)
assert target_text in generated_text, f"Expected {target_text} in generated text: {generated_text}"
diff --git a/test/test_cpu/quantization/test_model_free.py b/test/test_cpu/quantization/test_model_free.py
index 5ce07255c..df73b9363 100644
--- a/test/test_cpu/quantization/test_model_free.py
+++ b/test/test_cpu/quantization/test_model_free.py
@@ -131,6 +131,7 @@ class TestPatternMatcher:
m = _matcher()
assert m.should_skip("model.layers.0.shared_expert_gate.weight") is True
assert m.should_skip("model.layers.0.mlp.gate.weight") is True
+ assert m.should_skip("model.layers.0.mlp.gate_proj.weight") is False
assert m.should_skip("model.embed_tokens.weight") is True
assert m.should_skip("model.layers.0.mlp.fc1.weight") is False
@@ -164,11 +165,11 @@ class TestPatternMatcher:
class TestParseLayerConfig:
@staticmethod
- def _make_core(layer_config_input):
+ def _make_core(layer_config_input, scheme="W4A16"):
core = _ModelFreeCompressorCore(
model_name_or_path="dummy",
output_dir="dummy_out",
- scheme="W4A16",
+ scheme=scheme,
)
core.layer_config_input = layer_config_input
core._parse_scheme()
@@ -198,6 +199,13 @@ class TestParseLayerConfig:
cfg = next(v for k, v in core.layer_config.items() if "ffn.experts" in k)
assert cfg["bits"] == 2 and cfg["group_size"] == 64
+ def test_w4a16_mixed_recipe_in_model_free(self):
+ core = self._make_core({}, scheme="W4A16_MIXED")
+ assert core.default_scheme["bits"] == 8
+ assert core.layer_config[".experts."]["bits"] == 4
+ assert core.layer_config[".moe."]["bits"] == 4
+ assert core.layer_config[".shared_expert."]["bits"] == 8
+
# ===========================================================================
# _process_shard
@@ -238,6 +246,45 @@ class TestProcessShard:
base = f"model.layers.0.mlp.experts.{i}.{proj}"
assert base in quantized and f"{base}.qweight" in output
+ def test_moe_stacked_weights_are_split_and_quantized(self, tmp_path):
+ shard_path = str(tmp_path / "shard.safetensors")
+ n_experts, hidden, intermediate = 3, 64, 32
+ save_file(
+ {
+ "model.layers.3.moe.down_proj.weight": torch.randn(n_experts, hidden, intermediate),
+ "model.layers.3.moe.gate_proj.weight": torch.randn(n_experts, intermediate, hidden),
+ "model.layers.3.moe.up_proj.weight": torch.randn(n_experts, intermediate, hidden),
+ "model.layers.3.moe.gate.weight": torch.randn(n_experts, hidden),
+ "model.layers.3.moe.router_bias": torch.randn(n_experts),
+ },
+ shard_path,
+ )
+
+ output, quantized, ignored = _process_shard(shard_path, _DEFAULT_SCHEME, {}, [])
+
+ for i in range(n_experts):
+ for proj in ["down_proj", "gate_proj", "up_proj"]:
+ base = f"model.layers.3.moe.experts.{i}.{proj}"
+ assert base in quantized
+ assert f"{base}.qweight" in output
+
+ # Router gate stays in full precision by predefined skip rules.
+ assert "model.layers.3.moe.gate" in ignored
+ assert "model.layers.3.moe.gate.weight" in output
+ # router_bias is not a 2D linear weight and remains unchanged.
+ assert "model.layers.3.moe.router_bias" in output
+
+ def test_3d_weight_in_ignored_layers(self, tmp_path):
+ """A non-eligible 3D .weight tensor must appear in ignored_layers."""
+ shard_path = str(tmp_path / "shard.safetensors")
+ save_file({"model.layers.0.mlp.branch.weight": torch.randn(4, 8, 16)}, shard_path)
+
+ output, quantized, ignored = _process_shard(shard_path, _DEFAULT_SCHEME, {}, [])
+
+ assert "model.layers.0.mlp.branch.weight" in output
+ assert quantized == []
+ assert "model.layers.0.mlp.branch" in ignored
+
# ===========================================================================
# FP8 source model
diff --git a/test/test_cpu/utils/test_missing_tensors.py b/test/test_cpu/utils/test_missing_tensors.py
index ae7ad83cc..1528c7e30 100644
--- a/test/test_cpu/utils/test_missing_tensors.py
+++ b/test/test_cpu/utils/test_missing_tensors.py
@@ -89,6 +89,17 @@ class TestSplitFusedExpertTensors:
for k in tensors:
assert torch.equal(result[k], tensors[k])
+ def test_warns_on_3d_tensor_with_unsupported_parent(self, caplog):
+ tensors = {
+ "model.layers.0.mlp.branch.down_proj.weight": torch.randn(4, 8, 16),
+ }
+
+ with caplog.at_level("WARNING"):
+ result = split_fused_expert_tensors(tensors)
+
+ assert set(result.keys()) == set(tensors.keys())
+ assert any("unsupported parent" in rec.message and "open an issue" in rec.message for rec in caplog.records)
+
def test_empty_dict_returns_empty(self):
assert split_fused_expert_tensors({}) == {}
@@ -128,6 +139,18 @@ class TestSplitFusedExpertTensors:
assert result[key].shape == (O, I)
assert torch.equal(result[key], stacked[i])
+ def test_moe_container_stacked_proj(self):
+ """moe.down_proj [N,O,I] → moe.experts.{i}.down_proj.weight."""
+ N, O, I = 3, 32, 16
+ stacked = torch.randn(N, O, I)
+ result = split_fused_expert_tensors({"model.layers.3.moe.down_proj.weight": stacked})
+ assert "model.layers.3.moe.down_proj.weight" not in result
+ assert len(result) == N
+ for i in range(N):
+ key = f"model.layers.3.moe.experts.{i}.down_proj.weight"
+ assert result[key].shape == (O, I)
+ assert torch.equal(result[key], stacked[i])
+
def test_mixed_fused_and_normal(self):
N, I, H = 2, 32, 16
tensors = {
diff --git a/test/test_cuda/integrations/test_vllm.py b/test/test_cuda/integrations/test_vllm.py
index bc1b65ac2..b58254c5e 100644
--- a/test/test_cuda/integrations/test_vllm.py
+++ b/test/test_cuda/integrations/test_vllm.py
@@ -64,7 +64,7 @@ def test_auto_round(model):
"The future of AI is",
]
# Create a sampling params object.
- sampling_params = SamplingParams(temperature=0.8, top_p=0.95)
+ sampling_params = SamplingParams(temperature=0, max_tokens=32)
# Create an LLM.
QUANTIZATION = "auto-round"
llm = LLM(