Skip to content

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

fix: skip layers the AWQ GEMM kernel cannot serve in AWQ export (#2456)

losewayy7a660e16d391
diff --git a/auto_round/compressors/layer_config_resolver.py b/auto_round/compressors/layer_config_resolver.py
index 1be0d2912..8d281adf5 100644
--- a/auto_round/compressors/layer_config_resolver.py
+++ b/auto_round/compressors/layer_config_resolver.py
@@ -48,6 +48,7 @@ def apply_layer_config_special_cases(
quant_block_list,
quant_lm_head,
gguf_name,
+ export_to_awq=False,
) -> tuple[dict, bool, str | None, bool]:
"""Apply lm-head, shape-divisibility, and block-membership layer rules."""
from auto_round.utils.model import get_lm_head_name
@@ -73,6 +74,14 @@ def apply_layer_config_special_cases(
layer_config.setdefault(n, copy.deepcopy(default_dict))
layer_config[n].update({"bits": 16, "data_type": "fp", "fixed_by_user": True})
+ if export_to_awq and not gguf_name:
+ # Re-mark after regex/partial layer_config entries are expanded: the same
+ # marking already ran at format-resolution time, but raw user entries can
+ # overwrite it during expansion.
+ from auto_round.export.formats.backends.auto_awq import mark_awq_unservable_layers
+
+ layer_config = mark_awq_unservable_layers(model, layer_config, default_dict)
+
if (is_nv_fp(default_dict["data_type"]) or is_mx_fp(default_dict["data_type"])) and not gguf_name:
skipped_layers = []
for n, m in model.named_modules():
@@ -465,6 +474,7 @@ def resolve_layer_config(
quant_block_list,
quant_lm_head,
gguf_name,
+ export_to_awq="awq" in (format or ""),
)
if gguf_name:
from auto_round.export.formats.backends.gguf import apply_gguf_layer_defaults
diff --git a/auto_round/export/export_to_autoround/export.py b/auto_round/export/export_to_autoround/export.py
index 8dbdbff16..b2f2cf979 100644
--- a/auto_round/export/export_to_autoround/export.py
+++ b/auto_round/export/export_to_autoround/export.py
@@ -201,6 +201,20 @@ def pack_layer(layer_name, model, backend, device=None):
elif type(layer) == transformers.pytorch_utils.Conv1D:
in_features = layer.weight.shape[0]
out_features = layer.weight.shape[1]
+
+ if "awq" in backend:
+ # The AWQ GEMM kernel rejects shapes that violate its divisibility
+ # constraints (e.g. out_features < group_size in Gated-DeltaNet
+ # projections); keep such layers in full precision unless the user
+ # explicitly configured them for quantization (fixed_by_user).
+ from auto_round.export.export_to_awq.utils import awq_gemm_kernel_supported, awq_layer_user_forced
+
+ if not awq_gemm_kernel_supported(in_features, out_features, bits, group_size) and not awq_layer_user_forced(
+ layer
+ ):
+ logger.warning_once(f"skipping {layer_name}: its shape cannot be served by the AWQ GEMM kernel")
+ return
+
bias = layer.bias is not None
new_layer = QuantLinear( ##pylint: disable=E1123
diff --git a/auto_round/export/export_to_awq/export.py b/auto_round/export/export_to_awq/export.py
index 306ed4c87..011724d94 100644
--- a/auto_round/export/export_to_awq/export.py
+++ b/auto_round/export/export_to_awq/export.py
@@ -29,7 +29,11 @@ import torch
import torch.nn as nn
from tqdm import tqdm
-from auto_round.export.export_to_awq.utils import WQLinear_GEMM
+from auto_round.export.export_to_awq.utils import (
+ WQLinear_GEMM,
+ awq_gemm_kernel_supported,
+ awq_layer_user_forced,
+)
from auto_round.export.utils import (
filter_quantization_config,
is_immediate_saving_mode,
@@ -42,6 +46,7 @@ from auto_round.utils import (
INNER_SUPPORTED_LAYER_TYPES,
SUPPORTED_LAYER_TYPES,
check_to_quantized,
+ compress_layer_names,
copy_python_files_from_model_cache,
extract_block_names_to_str,
get_block_names,
@@ -117,12 +122,29 @@ def pack_layer(name, model, backend, device=None):
if type(layer) not in SUPPORTED_LAYER_TYPES: ##already packed
return
- bits = layer.bits
-
- if bits > 8:
+ bits = getattr(layer, "bits", None)
+ if bits is None or bits > 8:
return
- group_size = layer.group_size
+ group_size = getattr(layer, "group_size", None)
+ in_features = getattr(layer, "in_features", None)
+ out_features = getattr(layer, "out_features", None)
+ if group_size is None or in_features is None or out_features is None:
+ # Layers missing AWQ packing attributes (e.g. Conv1D) stay in full precision.
+ logger.warning_once(f"skipping {name}: its shape cannot be served by the AWQ GEMM kernel")
+ return
+ if not awq_gemm_kernel_supported(in_features, out_features, bits, group_size):
+ if awq_layer_user_forced(layer):
+ # The user explicitly configured this layer for quantization;
+ # honor it and pack anyway.
+ logger.warning_once(
+ f"{name}: quantized per explicit `layer_config` but its shape "
+ "cannot be served by the AWQ GEMM kernel; packing as configured"
+ )
+ else:
+ # The GEMM kernel cannot serve this shape; keep it in full precision.
+ logger.warning_once(f"skipping {name}: its shape cannot be served by the AWQ GEMM kernel")
+ return
sym = layer.sym
linear_layer = get_module(model, name)
scale, zp = linear_layer.scale, linear_layer.zp
@@ -182,9 +204,52 @@ def save_quantized_as_autoawq(
names = list(layer_config.keys())
+ # Layers the AWQ GEMM kernel cannot serve (e.g. out_features not divisible by
+ # group_size, as in Gated-DeltaNet in_proj_ba) must stay in full precision;
+ # packing them crashes serving stacks such as vLLM. They are reported via
+ # modules_to_not_convert below. Layers the user explicitly configured for
+ # quantization in layer_config are exempt: their setting is honored and they
+ # are packed as requested. This also covers the split
+ # quantize() -> save_quantized(format="auto_awq") flow, where format
+ # resolution (and the fp16 downgrade in check_and_reset_format) happens only
+ # after the layer has already been quantized.
+ unservable_layers = set()
+ meta_device = unsupported_meta_device(model)
+ if not meta_device:
+ for name in names:
+ layer = get_module(compressed_model, name)
+ if (
+ type(layer) not in SUPPORTED_LAYER_TYPES
+ or not hasattr(layer, "in_features")
+ or not hasattr(layer, "out_features")
+ ):
+ continue
+ cfg = layer_config.get(name, {})
+ cfg_get = cfg.get if hasattr(cfg, "get") else (lambda *a, **k: None)
+ bits = getattr(layer, "bits", None)
+ if bits is None:
+ bits = cfg_get("bits") or serialization_dict.get("bits")
+ if not isinstance(bits, int) or bits > 8:
+ continue
+ group_size = getattr(layer, "group_size", None)
+ if group_size is None:
+ group_size = cfg_get("group_size") or serialization_dict.get("group_size")
+ if not awq_gemm_kernel_supported(layer.in_features, layer.out_features, bits, group_size):
+ if not awq_layer_user_forced(layer, cfg):
+ unservable_layers.add(name)
+ if unservable_layers:
+ logger.warning_once(
+ f"{len(unservable_layers)} layer(s) cannot be served by the AWQ GEMM kernel "
+ "(in/out features not divisible by group_size or out_features not divisible by 64) "
+ "and are kept in full precision: "
+ f"{compress_layer_names(sorted(unservable_layers))}"
+ )
+
backend = None
- if not unsupported_meta_device(model):
+ if not meta_device:
for name in tqdm(names, desc="packing", leave=True):
+ if name in unservable_layers:
+ continue
pack_layer(name, compressed_model, backend, device)
if output_dir is None:
return model
@@ -207,6 +272,8 @@ def save_quantized_as_autoawq(
quantization_config["quant_method"] = "awq"
quantization_config["zero_point"] = not quantization_config["sym"]
quantization_config["version"] = "gemm"
+ if unservable_layers:
+ modules_to_not_convert = sorted(set(modules_to_not_convert) | unservable_layers)
quantization_config["modules_to_not_convert"] = modules_to_not_convert
##check module quantized in block, this may have bug for mixed precision quantization
filter_quantization_config(quantization_config)
diff --git a/auto_round/export/export_to_awq/utils.py b/auto_round/export/export_to_awq/utils.py
index ddf59ac0d..be75ce997 100644
--- a/auto_round/export/export_to_awq/utils.py
+++ b/auto_round/export/export_to_awq/utils.py
@@ -54,6 +54,58 @@ from auto_round.utils.bit_packing import (
SUPPORTED_AWQ_BITS = (4, 5, 6, 7)
+def awq_gemm_kernel_supported(in_features: int, out_features: int, bits: int, group_size: int) -> bool:
+ """Whether the AWQ GEMM kernel can serve a layer of the given shape.
+
+ The kernel requires ``in_features`` and ``out_features`` to be multiples of
+ ``group_size`` (``IC/OC is not multiple of Group size``) and ``out_features``
+ to be a multiple of the 64-wide CTA tile. Bit widths outside
+ ``SUPPORTED_AWQ_BITS`` have no servable packing layout. A non-positive
+ ``group_size`` (per-channel quantization) is treated as servable here;
+ per-channel compatibility is validated elsewhere.
+ """
+ if bits not in SUPPORTED_AWQ_BITS:
+ return False
+ if not isinstance(group_size, int) or group_size <= 0:
+ return True
+ return in_features % group_size == 0 and out_features % group_size == 0 and out_features % 64 == 0
+
+
+def awq_user_forced_quantization(cfg) -> bool:
+ """Whether a ``layer_config`` entry explicitly keeps this layer quantized.
+
+ User-supplied entries (exact names or expanded regex matches) carry
+ ``fixed_by_user=True`` once normalized; entries AutoRound filled in from
+ the default scheme carry ``fixed_by_user=False``. At format-resolution
+ time user entries can still be raw (a dict missing the flag, a preset
+ string, or a QuantizationScheme), so any present entry counts as user
+ intent unless it explicitly says ``fixed_by_user=False``.
+
+ After ``apply_plan_to_model`` the same flag is also available on the
+ module itself as ``layer.fixed_by_user``; see ``awq_layer_user_forced``.
+ """
+ if not cfg:
+ return False
+ if not hasattr(cfg, "get"):
+ return True
+ return cfg.get("fixed_by_user", True) is not False
+
+
+def awq_layer_user_forced(layer, cfg=None) -> bool:
+ """Whether a quantized module explicitly keeps an AWQ-unservable shape quantized.
+
+ Reads ``layer.fixed_by_user`` written by ``apply_plan_to_model``. A module
+ without the flag falls back to its ``layer_config`` entry when given, and
+ otherwise follows the same rule as ``awq_user_forced_quantization`` for a
+ plan entry missing the key (e.g. lm_head added via ``quant_lm_head``), so
+ the marking step and the packers agree.
+ """
+ flag = getattr(layer, "fixed_by_user", None)
+ if flag is not None:
+ return bool(flag)
+ return cfg is None or awq_user_forced_quantization(cfg)
+
+
def unpack_awq(qweight: torch.Tensor, qzeros: torch.Tensor, bits: int):
shifts = torch.arange(0, 32, bits, device=qzeros.device)
diff --git a/auto_round/export/formats/backends/auto_awq.py b/auto_round/export/formats/backends/auto_awq.py
index f7f8c4388..2b35b3d4c 100644
--- a/auto_round/export/formats/backends/auto_awq.py
+++ b/auto_round/export/formats/backends/auto_awq.py
@@ -12,8 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import copy
import re
-from collections.abc import Callable
+from collections.abc import Callable, Mapping
+from dataclasses import asdict
import torch
import transformers
@@ -21,6 +23,91 @@ import transformers
from auto_round.export.formats.base import OutputFormat, _check_divisible_by_32
from auto_round.logger import logger
from auto_round.schemes import QuantizationScheme
+from auto_round.utils import INNER_SUPPORTED_LAYER_TYPES, SUPPORTED_LAYER_TYPES, compress_layer_names
+
+
+def mark_awq_unservable_layers(model, layer_config: dict, default_dict: dict) -> dict:
+ """Exclude layers the AWQ GEMM kernel cannot serve by marking them fp16.
+
+ Serving stacks such as vLLM crash on shapes violating the kernel's
+ divisibility constraints ("OC is not multiple of Group size"), e.g. the
+ small ``in_proj_ba`` projections in Gated-DeltaNet hybrids. Marking such
+ layers fp16 keeps them out of quantization and packing and lands them in
+ ``modules_to_not_convert`` in the saved config.
+
+ ``layer_config`` may hold raw user entries at format-resolution time
+ (partial dicts, preset strings, not-yet-expanded regex keys) or fully
+ resolved per-layer dicts at plan time; both are tolerated.
+
+ Layers the user explicitly configured for quantization (exact name or
+ expanded regex entry, ``fixed_by_user != False``) are honored: they keep
+ their configuration, the packers pick the flag up from
+ ``layer.fixed_by_user`` (written by ``apply_plan_to_model``, see
+ ``awq_layer_user_forced``), and only a warning is logged that the shape
+ may fail on the AWQ GEMM path.
+ """
+ if model is None or default_dict["data_type"] != "int":
+ return layer_config
+ from auto_round.export.export_to_awq.utils import (
+ awq_gemm_kernel_supported,
+ awq_user_forced_quantization,
+ )
+
+ scheme_bits, scheme_group_size = default_dict["bits"], default_dict["group_size"]
+ skipped_layers = []
+ user_forced_layers = []
+ for name, module in model.named_modules():
+ if not (type(module) in SUPPORTED_LAYER_TYPES or module.__class__.__name__ in INNER_SUPPORTED_LAYER_TYPES):
+ continue
+ if not hasattr(module, "in_features") or not hasattr(module, "out_features"):
+ continue
+ cfg = layer_config.get(name) if layer_config else None
+ if hasattr(cfg, "get"):
+ bits = cfg.get("bits") or scheme_bits
+ group_size = cfg.get("group_size") or scheme_group_size
+ else:
+ bits, group_size = scheme_bits, scheme_group_size
+ if not isinstance(bits, int) or bits > 8:
+ continue # already excluded from quantization or exotic config
+ if not isinstance(group_size, int) or group_size <= 0:
+ continue
+ if awq_gemm_kernel_supported(module.in_features, module.out_features, bits, group_size):
+ continue
+ if awq_user_forced_quantization(cfg):
+ # The user explicitly configured this layer for quantization;
+ # keep the configuration. fixed_by_user is applied to the module
+ # by apply_plan_to_model, which the packers consult.
+ user_forced_layers.append(name)
+ continue
+ if layer_config is None:
+ layer_config = {}
+ # Build a fresh entry rather than updating in place: regex expansion
+ # shares one dict object across all matched layer names, so an in-place
+ # update would leak the fp16 mark to sibling layers.
+ new_cfg = copy.deepcopy(default_dict)
+ if isinstance(cfg, Mapping):
+ new_cfg.update(cfg)
+ new_cfg.update({"bits": 16, "data_type": "fp", "fixed_by_user": True})
+ layer_config[name] = new_cfg
+ skipped_layers.append(name)
+ compressed_skipped_layers = compress_layer_names(skipped_layers)
+ if compressed_skipped_layers:
+ logger.warning_once(
+ "some layers are skipped quantization (in/out features not divisible by the AWQ "
+ f"group_size {scheme_group_size} or out_features not divisible by 64, "
+ "which the AWQ GEMM kernel cannot serve); they are exported in fp16 and listed "
+ f"in `modules_to_not_convert`: {compressed_skipped_layers}"
+ )
+ compressed_user_forced = compress_layer_names(user_forced_layers)
+ if compressed_user_forced:
+ logger.warning_once(
+ "some layers are quantized per their explicit `layer_config` entry but their "
+ "shapes cannot be served by the AWQ GEMM kernel (in/out features not divisible "
+ "by group_size or out_features not divisible by 64); they are packed as "
+ "configured and may fail on the AWQ GEMM path in serving stacks such as vLLM: "
+ f"{compressed_user_forced}"
+ )
+ return layer_config
@OutputFormat.register("auto_awq")
@@ -53,35 +140,44 @@ class AutoAWQFormat(OutputFormat):
@staticmethod
def check_awq_gemm_compatibility(model, bits, group_size, sym, layer_configs=None):
"""Check whether a model is compatible with the AutoAWQ GEMM kernel."""
- from auto_round.utils.bit_packing import requires_generic_bit_packing
+ from auto_round.export.export_to_awq.utils import SUPPORTED_AWQ_BITS, awq_gemm_kernel_supported
from auto_round.utils.model import get_layer_names_in_block, get_module
- if bits not in (4, 5, 6, 7):
- return False, "AutoAWQ GEMM kernel only supports 4 bits"
+ if bits not in SUPPORTED_AWQ_BITS:
+ return False, f"AutoAWQ GEMM kernel only supports bits in {SUPPORTED_AWQ_BITS}"
for _, module in model.named_modules():
if type(module) == transformers.pytorch_utils.Conv1D:
return False, "AutoAWQ GEMM kernel does not support conv1d"
- # 5/6/7-bit packs a contiguous bit-stream over blocks of 32 values.
- out_align = 32 if requires_generic_bit_packing(bits) else 32 // bits
layer_names = get_layer_names_in_block(model)
for layer_name in layer_names:
- if (
- layer_configs is not None
- and layer_name in layer_configs.keys()
- and layer_configs[layer_name].get("bits", bits) > 8
- ):
+ layer_cfg = layer_configs.get(layer_name) if layer_configs else None
+ if hasattr(layer_cfg, "get") and (layer_cfg.get("bits") or bits) > 8:
continue
layer = get_module(model, layer_name)
- if layer.in_features % group_size != 0:
- return False, f"Layer {layer_name} in_features is not multiple of group_size {group_size}"
- if layer.out_features % out_align != 0:
- return False, f"Layer {layer_name} out_features is not multiple of {out_align}"
+ layer_bits = layer_cfg.get("bits") if hasattr(layer_cfg, "get") else None
+ layer_group_size = layer_cfg.get("group_size") if hasattr(layer_cfg, "get") else None
+ if not awq_gemm_kernel_supported(
+ layer.in_features,
+ layer.out_features,
+ layer_bits or bits,
+ layer_group_size or group_size,
+ ):
+ return False, (
+ f"Layer {layer_name} (in_features={layer.in_features}, "
+ f"out_features={layer.out_features}, group_size={layer_group_size or group_size}) "
+ "cannot be served by the AWQ GEMM kernel"
+ )
return True, ""
def check_and_reset_format(self, scheme: QuantizationScheme, ctx):
+ if self.backend is None:
+ ctx.layer_config = _check_divisible_by_32(scheme, ctx.model, ctx.layer_config)
+ # Also re-applied after layer-config resolution (regex/partial user
+ # entries are expanded then) via apply_layer_config_special_cases.
+ ctx.layer_config = mark_awq_unservable_layers(ctx.model, ctx.layer_config, asdict(scheme))
awq_supported, info = self.check_awq_gemm_compatibility(
ctx.model, scheme.bits, scheme.group_size, scheme.sym, ctx.layer_config
)
@@ -99,9 +195,6 @@ class AutoAWQFormat(OutputFormat):
f"but got bits={scheme.bits}, please have a check."
)
- if self.backend is None:
- ctx.layer_config = _check_divisible_by_32(scheme, ctx.model, ctx.layer_config)
-
return super().check_and_reset_format(scheme, ctx)
def pack_layer(self, layer_name, model, device=None, **kwargs):
diff --git a/test/unit/test_cpu/export/test_export.py b/test/unit/test_cpu/export/test_export.py
index 0d4abe728..abf6e2a44 100644
--- a/test/unit/test_cpu/export/test_export.py
+++ b/test/unit/test_cpu/export/test_export.py
@@ -815,3 +815,341 @@ def test_save_model_writes_diffusers_config(tmp_path):
config = json.load(f)
assert config["_class_name"] == "SD3Transformer2DModel"
assert config["quantization_config"] == {"quant_method": "auto-round", "bits": 4}
+
+
+def test_awq_gemm_kernel_supported():
+ """AWQ GEMM kernel divisibility contract (IC/OC % group_size, OC % 64)."""
+ from auto_round.export.export_to_awq.utils import awq_gemm_kernel_supported
+
+ # Canonical servable shapes
+ assert awq_gemm_kernel_supported(2048, 2048, 4, 128)
+ assert awq_gemm_kernel_supported(256, 128, 4, 128)
+ # out_features < group_size, e.g. DeltaNet in_proj_ba (OC=32/64, gs=128)
+ assert not awq_gemm_kernel_supported(256, 64, 4, 128)
+ assert not awq_gemm_kernel_supported(256, 32, 4, 128)
+ # in_features not a multiple of group_size
+ assert not awq_gemm_kernel_supported(96, 256, 4, 128)
+ # OC % 64 (cta_N tile) still binds when group_size is small
+ assert not awq_gemm_kernel_supported(64, 96, 4, 32)
+ assert awq_gemm_kernel_supported(64, 192, 4, 32)
+ # Bit widths without a servable packing layout are rejected
+ assert not awq_gemm_kernel_supported(256, 256, 8, 128)
+ assert not awq_gemm_kernel_supported(256, 256, None, 128)
+ # Per-channel group_size is left to the caller
+ assert awq_gemm_kernel_supported(256, 256, 4, -1)
+ assert awq_gemm_kernel_supported(256, 64, 4, -1)
+
+
+def test_awq_format_excludes_unservable_layers():
+ """Layers the AWQ GEMM kernel cannot serve are marked fp16 during format resolution."""
+ from types import SimpleNamespace
+
+ import torch.nn as nn
+
+ from auto_round.export.formats.backends.auto_awq import AutoAWQFormat
+ from auto_round.schemes import preset_name_to_scheme
+
+ class ToyModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = nn.Linear(256, 256)
+ self.in_proj_ba = nn.Linear(256, 64) # OC=64 < group_size -> unservable
+ self.in_proj_b = nn.Linear(96, 256) # IC=96 % 128 != 0 -> unservable
+ self.mlp_up = nn.Linear(256, 96) # OC=96 % 64 != 0 -> unservable
+
+ model = ToyModel()
+ scheme = preset_name_to_scheme("W4A16")
+ # Fields normally filled by scheme resolution
+ scheme.act_data_type = scheme.act_data_type or "fp16"
+ scheme.act_dynamic = False if scheme.act_dynamic is None else scheme.act_dynamic
+ ctx = SimpleNamespace(
+ model=model,
+ layer_config={},
+ mllm=False,
+ quant_block_list=None,
+ )
+ output_format = AutoAWQFormat("auto_awq", scheme, ctx)
+ output_format.check_and_reset_format(scheme, ctx)
+
+ # None of the shapes are caught by _check_divisible_by_32 (all % 32 == 0),
+ # so any fp16 mark comes from the AWQ kernel constraint check.
+ assert ctx.layer_config["in_proj_ba"]["bits"] == 16
+ assert ctx.layer_config["in_proj_ba"]["data_type"] == "fp"
+ assert ctx.layer_config["in_proj_b"]["bits"] == 16
+ assert ctx.layer_config["mlp_up"]["bits"] == 16
+ assert "q_proj" not in ctx.layer_config
+
+
+def test_awq_format_honors_explicit_layer_config():
+ """At format-resolution time a raw user entry (no fixed_by_user flag yet)
+ counts as explicit configuration: the unservable layer is not marked fp16."""
+ from types import SimpleNamespace
+
+ import torch.nn as nn
+
+ from auto_round.export.formats.backends.auto_awq import AutoAWQFormat
+ from auto_round.schemes import preset_name_to_scheme
+
+ class ToyModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.in_proj_ba = nn.Linear(256, 64) # OC=64 < group_size -> unservable
+ self.mlp_bad = nn.Linear(96, 256) # IC=96 % 128 != 0 -> unservable, no user entry
+
+ model = ToyModel()
+ scheme = preset_name_to_scheme("W4A16")
+ scheme.act_data_type = scheme.act_data_type or "fp16"
+ scheme.act_dynamic = False if scheme.act_dynamic is None else scheme.act_dynamic
+ ctx = SimpleNamespace(
+ model=model,
+ layer_config={"in_proj_ba": {"bits": 4}},
+ mllm=False,
+ quant_block_list=None,
+ )
+ output_format = AutoAWQFormat("auto_awq", scheme, ctx)
+ output_format.check_and_reset_format(scheme, ctx)
+
+ # The explicit entry is honored
+ assert ctx.layer_config["in_proj_ba"]["bits"] == 4
+ # The layer without a user entry is still marked fp16
+ assert ctx.layer_config["mlp_bad"]["bits"] == 16
+
+
+def test_awq_pack_layer_skips_unservable_layer():
+ """pack_layer must not AWQ-pack a layer whose shape the GEMM kernel cannot serve."""
+ import torch.nn as nn
+
+ from auto_round.export.export_to_awq.export import pack_layer
+ from auto_round.utils import get_module
+
+ class ToyModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.in_proj_ba = nn.Linear(256, 64)
+
+ model = ToyModel()
+ layer = get_module(model, "in_proj_ba")
+ # Simulate a layer that went through quantization (attrs set by the quantizer)
+ layer.bits = 4
+ layer.group_size = 128
+ layer.sym = True
+ layer.scale = torch.ones(2, 64)
+ layer.zp = torch.zeros(2, 64)
+ # apply_plan_to_model writes fixed_by_user=False for default-filled layers
+ layer.fixed_by_user = False
+
+ pack_layer("in_proj_ba", model, backend="auto_awq")
+
+ assert type(get_module(model, "in_proj_ba")) is nn.Linear
+
+
+def test_awq_export_lists_unservable_layers(tmp_path):
+ """Layers the AWQ GEMM kernel cannot serve land in modules_to_not_convert.
+
+ Covers the split quantize() -> save_quantized(format="auto_awq") flow where
+ the layer was already quantized before the format check ran.
+ """
+ import torch.nn as nn
+
+ from auto_round.export.export_to_awq.export import save_quantized_as_autoawq
+ from auto_round.utils import get_module
+
+ class ToyModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.in_proj_ba = nn.Linear(256, 64) # OC=64 < group_size -> unservable
+ self.q_proj = nn.Linear(256, 256)
+ self.dtype = torch.float32
+
+ def save_pretrained(self, save_dir, **kwargs):
+ os.makedirs(save_dir, exist_ok=True)
+
+ model = ToyModel()
+ # Simulate a layer that already went through quantization
+ layer = get_module(model, "in_proj_ba")
+ layer.bits = 4
+ layer.group_size = 128
+ layer.sym = True
+ # fixed_by_user=False mirrors what resolve_layer_config writes for
+ # default-filled entries (a user entry would carry True).
+ layer_config = {
+ "in_proj_ba": {"bits": 4, "group_size": 128, "sym": True, "data_type": "int", "fixed_by_user": False}
+ }
+ serialization_dict = {"bits": 4, "group_size": 128, "sym": True}
+
+ save_quantized_as_autoawq(
+ str(tmp_path),
+ model=model,
+ layer_config=layer_config,
+ inplace=True,
+ serialization_dict=serialization_dict,
+ )
+
+ assert "in_proj_ba" in serialization_dict["modules_to_not_convert"]
+ # Not packed into an AWQ layer
+ assert type(get_module(model, "in_proj_ba")) is nn.Linear
+ # Export reads fixed_by_user but never writes it onto modules
+ assert not hasattr(get_module(model, "in_proj_ba"), "fixed_by_user")
+
+
+def test_awq_export_packs_user_forced_layer(tmp_path):
+ """A layer_config entry the user explicitly set for quantization is honored:
+ the unservable layer is packed anyway and does not land in
+ modules_to_not_convert."""
+ import torch.nn as nn
+
+ from auto_round.export.export_to_awq.export import save_quantized_as_autoawq
+ from auto_round.export.export_to_awq.utils import WQLinear_GEMM
+ from auto_round.utils import get_module
+
+ class ToyModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.in_proj_ba = nn.Linear(256, 64) # OC=64 < group_size -> unservable
+ self.q_proj = nn.Linear(256, 256)
+ self.dtype = torch.float32
+
+ def save_pretrained(self, save_dir, **kwargs):
+ os.makedirs(save_dir, exist_ok=True)
+
+ model = ToyModel()
+ layer = get_module(model, "in_proj_ba")
+ layer.bits = 4
+ layer.group_size = 128
+ layer.sym = True
+ # The quantizer stores scale/zp as (out_features, num_groups); pack_layer
+ # transposes them before handing them to the packer.
+ layer.scale = torch.ones(64, 2)
+ layer.zp = torch.zeros(64, 2)
+ layer_config = {
+ "in_proj_ba": {"bits": 4, "group_size": 128, "sym": True, "data_type": "int", "fixed_by_user": True}
+ }
+ serialization_dict = {"bits": 4, "group_size": 128, "sym": True}
+
+ save_quantized_as_autoawq(
+ str(tmp_path),
+ model=model,
+ layer_config=layer_config,
+ inplace=True,
+ serialization_dict=serialization_dict,
+ )
+
+ assert "in_proj_ba" not in serialization_dict["modules_to_not_convert"]
+ assert isinstance(get_module(model, "in_proj_ba"), WQLinear_GEMM)
+
+
+def test_awq_unservable_lm_head_via_quant_lm_head_is_packed():
+ """quant_lm_head=True adds lm_head from the default scheme without a
+ fixed_by_user key, so the marking step keeps it quantized and no flag is
+ applied to the module. pack_layer must follow the same rule and pack it,
+ otherwise it would be neither packed nor listed in modules_to_not_convert
+ on paths that call pack_layer without the export prescan."""
+ import torch.nn as nn
+
+ from auto_round.compressors.config_resolution import ResolvedScheme
+ from auto_round.compressors.layer_config_resolver import resolve_layer_config
+ from auto_round.export.export_to_awq.export import pack_layer
+ from auto_round.export.export_to_awq.utils import WQLinear_GEMM
+ from auto_round.schemes import preset_name_to_scheme
+ from auto_round.utils import get_module
+
+ class Block(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = nn.Linear(256, 256)
+
+ class ToyModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.layers = nn.ModuleList([Block()])
+ self.lm_head = nn.Linear(256, 96) # 96 % 32 == 0 but 96 % 64 != 0 -> AWQ-unservable only
+
+ model = ToyModel()
+ resolved = resolve_layer_config(
+ model=model,
+ scheme=ResolvedScheme.from_scheme(preset_name_to_scheme("W4A16")),
+ layer_config={},
+ quant_block_list=[["layers.0"]],
+ quant_lm_head=True,
+ format="auto_awq",
+ )
+ assert resolved["lm_head"]["bits"] == 4
+ assert "fixed_by_user" not in resolved["lm_head"]
+
+ layer = get_module(model, "lm_head")
+ layer.bits = 4
+ layer.group_size = 128
+ layer.sym = True
+ layer.scale = torch.ones(96, 2)
+ layer.zp = torch.zeros(96, 2)
+
+ pack_layer("lm_head", model, backend="auto_awq")
+
+ assert isinstance(get_module(model, "lm_head"), WQLinear_GEMM)
+
+
+def test_awq_explicit_layer_config_overrides_unservable_mark():
+ """Explicit layer_config entries keep unservable layers quantized.
+
+ A user-supplied entry (exact name or expanded regex) counts as user
+ intent: the AWQ unservable marking must leave it untouched instead of
+ forcing fp16. Layers without a user entry are still marked fp16."""
+ import torch.nn as nn
+
+ from auto_round.compressors.config_resolution import ResolvedScheme
+ from auto_round.compressors.layer_config_resolver import resolve_layer_config
+ from auto_round.schemes import preset_name_to_scheme
+
+ class ToyModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = nn.Linear(256, 256) # servable
+ self.in_proj_ba = nn.Linear(256, 64) # OC=64 < group_size -> unservable
+ self.mlp_bad = nn.Linear(96, 256) # IC=96 % 128 != 0 -> unservable, not user-configured
+
+ model = ToyModel()
+ scheme = ResolvedScheme.from_scheme(preset_name_to_scheme("W4A16"))
+ resolved = resolve_layer_config(
+ model=model,
+ scheme=scheme,
+ layer_config={"proj": {"bits": 4}}, # regex matches q_proj and in_proj_ba
+ format="auto_awq",
+ )
+ # The user-configured unservable layer keeps its quantized setting
+ assert resolved["in_proj_ba"]["bits"] == 4
+ # The regex-matched sibling is servable and untouched as before
+ assert resolved["q_proj"]["bits"] == 4
+ # The unservable layer without a user entry is still marked fp16
+ assert resolved["mlp_bad"]["bits"] == 16
+ assert resolved["mlp_bad"]["data_type"] == "fp"
+
+
+def test_awq_pack_layer_packs_user_forced_layer():
+ """pack_layer must AWQ-pack an unservable layer the user explicitly
+ configured for quantization (fixed_by_user, applied to the module by
+ apply_plan_to_model)."""
+ import torch.nn as nn
+
+ from auto_round.export.export_to_awq.export import pack_layer
+ from auto_round.export.export_to_awq.utils import WQLinear_GEMM
+ from auto_round.utils import get_module
+
+ class ToyModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.in_proj_ba = nn.Linear(256, 64)
+
+ model = ToyModel()
+ layer = get_module(model, "in_proj_ba")
+ # Simulate a layer that went through quantization (attrs set by the
+ # quantizer); scale/zp are stored as (out_features, num_groups).
+ layer.bits = 4
+ layer.group_size = 128
+ layer.sym = True
+ layer.scale = torch.ones(64, 2)
+ layer.zp = torch.zeros(64, 2)
+ layer.fixed_by_user = True
+
+ pack_layer("in_proj_ba", model, backend="auto_awq")
+
+ assert isinstance(get_module(model, "in_proj_ba"), WQLinear_GEMM)