Repository navigation
Description
Describe the bug
The public packing/repacking API has three backend-contract failures: split GPTQ initialization changes numerical results, AWQ repacking narrows checkpoint buffers, and AllSpark AWQ raw packing is rejected by the dispatcher. Grouped here so the common helper lifecycle can be validated across supported backends.
Priority: P2 — a supported configuration produces incorrect behavior. Specific triggers and validation boundaries are below.
Reviewed at 35987dfb7, within the merged-change window 2026-09-25 07:00 UTC–2026-11-13 07:00 UTC. The changes through 8ea76c395 were checked before filing; these causes remain.
GPU / software / model information
These are focused correctness reproductions using small generic fixtures and public model classes; no external model or dataset download is required. Each case states its execution environment and any hardware or mocking limitation. Accelerator execution is not claimed from a CPU dispatch test.
1. hf_post_init does not restore GPTQ runtime zero points after the default split packing lifecycle
A supported default-format GPTQ Torch layer silently computes wrong inference values when packing and initialization are separate. A zero-weight, no-bias 128x64 layer returns 128 in every output channel instead of zero, including eval mode.
Trigger
Pack TorchLinear(bits=4, group_size=32, sym=True, desc_act=False) with hf_pack_layer(..., post_init=False), the default, then call hf_post_init(layer) or hf_post_init(container). Default checkpoint_format='gptq' leaves stored zp-1 fields; Torch decoding needs logical zero points.
Introducing change
Introduced by PR #3481, merge 876575397bf83bc05b7453c9a1501e832a6f41e1 (2026-11-02). The same split-init probe produces zeros at parent 27f07edf9df9d15402e6cd5b51615cebf768e168 and 128 at this merge. Inline post_init=True has a correction that the standalone helper lacks.
Source evidence
Default checkpoint packing resets raw logical qzeros to format 2 and converts to checkpoint format 1:
GPTQModel/gptqmodel/utils/packing.py
Lines 635 to 666 in 35987df
| if isinstance(module, GPTQQuantLinear): | |
| # Every raw GPTQ packer writes logical zero points (the internal/v2 | |
| # qzero layout). A caller may reuse a module that was previously | |
| # converted to v1, so reset the metadata before deciding whether a | |
| # conversion is needed. Without this, a second pack can skip v2->v1 | |
| # or apply v1->v2 to freshly-written v2 words. | |
| module.qzero_format(format=2) | |
| requested_format = checkpoint_format | |
| if requested_format is None: | |
| requested_format = getattr(module, "format", None) or FORMAT.GPTQ | |
| requested_format = _normalize_format(requested_format) | |
| if requested_format in (FORMAT.GPTQ, FORMAT.GPTQ_V2): | |
| # The v1-checkpoint convention (stored zero point minus one) only | |
| # applies to kernels that require the v2 runtime layout; other | |
| # kernels keep the raw packer words for both checkpoint flavors, | |
| # matching `pack_module`. | |
| wanted_qzero_format = ( | |
| 1 | |
| if requested_format == FORMAT.GPTQ | |
| and getattr(module, "REQUIRES_FORMAT_V2", False) | |
| else 2 | |
| ) | |
| if module.qzero_format() != wanted_qzero_format: | |
| from .model import ( | |
| convert_gptq_v1_to_v2_format_module, | |
| convert_gptq_v2_to_v1_format_module, | |
| ) | |
| if wanted_qzero_format == 1: | |
| convert_gptq_v2_to_v1_format_module( | |
| module=module, | |
| quantize_config=QuantizeConfig(bits=module.bits), | |
| ) |
Inline post_init=True explicitly restores logical v2 words before post_init:
GPTQModel/gptqmodel/utils/packing.py
Lines 674 to 690 in 35987df
| if post_init: | |
| if ( | |
| isinstance(module, GPTQQuantLinear) | |
| and getattr(module, "REQUIRES_FORMAT_V2", False) | |
| and module.qzero_format() == 1 | |
| ): | |
| # A v1-checkpoint request left zp-1 words for export, but the v2 | |
| # runtime layout is what flag-blind decoders read; restore it before | |
| # the module becomes usable. | |
| from .model import convert_gptq_v1_to_v2_format_module | |
| convert_gptq_v1_to_v2_format_module( | |
| module=module, | |
| bits=module.bits, | |
| pack_dtype=getattr(module, "pack_dtype", torch.int32), | |
| ) | |
| module.post_init(**(post_init_kwargs or {})) |
GPTQModel/gptqmodel/utils/packing.py
Lines 694 to 727 in 35987df
| def hf_post_init(module: nn.Module, **post_init_kwargs) -> nn.Module: | |
| """Run the kernel post-load initialization for quantized layers. | |
| Stable API for external integrators (auto-round, optimum, ...). Calls | |
| ``post_init()`` on every :class:`BaseQuantLinear` found in ``module``: | |
| passing a single quantized layer initializes that layer, while passing a | |
| container initializes each quantized child in depth-first order. This is | |
| the layer-scoped counterpart of | |
| :func:`gptqmodel.utils.model.hf_gptqmodel_post_init`, which also performs | |
| model-level work such as activation-order and scratch-buffer setup. | |
| Args: | |
| module: A quantized layer or a container holding quantized layers. | |
| **post_init_kwargs: Keyword arguments forwarded to each layer's | |
| ``post_init()``; kernels such as ExllamaV2 require a scratch space. | |
| Returns: | |
| The same ``module``, initialized in place. | |
| Raises: | |
| TypeError: When ``module`` is not an ``nn.Module``. | |
| """ | |
| if not isinstance(module, nn.Module): | |
| raise TypeError(f"hf_post_init: `module` must be an nn.Module, got `{type(module).__name__}`.") | |
| if isinstance(module, BaseQuantLinear): | |
| module.post_init(**post_init_kwargs) | |
| return module | |
| for submodule in module.modules(): | |
| if isinstance(submodule, BaseQuantLinear): | |
| submodule.post_init(**post_init_kwargs) | |
| return module |
TorchLinear.post_init does not perform qzero conversion:
GPTQModel/gptqmodel/nn_modules/qlinear/torch.py
Lines 306 to 327 in 35987df
| def post_init(self): | |
| # if self.padded_infeatures != self.in_features: | |
| # self.qweight.resize_(self.padded_infeatures // self.pack_dtype_bits * self.bits, self.out_features) | |
| # self.qzeros.resize_( | |
| # math.ceil(self.padded_infeatures / self.group_size), | |
| # self.out_features // self.pack_dtype_bits * self.bits | |
| # ) | |
| # self.scales.resize_((math.ceil(self.padded_infeatures / self.group_size), self.out_features), ) | |
| # self.g_idx = torch.tensor([i // self.group_size for i in range(self.padded_infeatures)], dtype=torch.int32, | |
| # device=self.g_idx.device) | |
| super().post_init() | |
| validate_g_idx_bounds( | |
| self.g_idx, | |
| self.scales, | |
| layer_name=type(self).__name__, | |
| ) | |
| # torch benefits the most from torch.compile, enable it by default | |
| self.optimize() | |
| self.clear_weight_cache() |
GPTQModel/gptqmodel/nn_modules/qlinear/__init__.py
Lines 1340 to 1346 in 35987df
| if self.bits in [2, 4, 8]: | |
| zeros = _torch_right_shift( | |
| t.unsqueeze(self.qzeros, 2).expand(-1, -1, self.pack_factor), | |
| wf_zero, | |
| ).to(self.dequant_dtype) | |
| zeros = t.bitwise_and(zeros, self.maxq).reshape(self.qzeros.shape[0], -1) | |
| return zeros[:, :self.scales.shape[1]] |
GPTQModel/gptqmodel/nn_modules/qlinear/__init__.py
Lines 1403 to 1410 in 35987df
| def _dequantize_from_codes(self, weight: t.Tensor, zeros: t.Tensor, num_itr: int = 1): | |
| # Packed words may contain zero-filled tail codes when an embedding | |
| # vocabulary is not divisible by the packing width. The runtime | |
| # embedding contract remains the original vocabulary size. | |
| if weight.shape[0] > self.in_features: | |
| weight = weight[:self.in_features] | |
| if num_itr == 1: | |
| weights = self.scales[self.g_idx.long()] * (weight - zeros[self.g_idx.long()]) |
Existing standalone tests mock post_init and assert dispatch only:
GPTQModel/tests/test_hf_packing_api.py
Lines 451 to 468 in 35987df
| def test_hf_post_init_initializes_single_layer(monkeypatch): | |
| module = _make_gptq_module() | |
| calls = [] | |
| monkeypatch.setattr(TorchLinear, "post_init", lambda self: calls.append(self)) | |
| assert hf_post_init(module) is module | |
| assert calls == [module] | |
| def test_hf_post_init_initializes_container_children(monkeypatch): | |
| container = nn.Module() | |
| container.first = _make_gptq_module() | |
| container.second = _make_gptq_module() | |
| calls = [] | |
| monkeypatch.setattr(TorchLinear, "post_init", lambda self: calls.append(self)) | |
| assert hf_post_init(container) is container | |
| assert calls == [container.first, container.second] |
GPTQModel/tests/test_hf_packing_api.py
Lines 652 to 671 in 35987df
| def test_hf_pack_layer_post_init_restores_v2_runtime_layout(): | |
| """A `gptq` request leaves zp-1 words for export, but `post_init=True` | |
| means the caller wants a usable module: flag-blind torch decoding must see | |
| the restored v2 layout, or every weight decodes one scale too high.""" | |
| module = _make_gptq_module(bits=4, sym=True) | |
| linear = nn.Linear(128, 64, bias=False) | |
| with torch.no_grad(): | |
| linear.weight.zero_() | |
| g_idx = torch.arange(128, dtype=torch.int32) // 32 | |
| scales = torch.ones(64, 4, dtype=torch.float32) | |
| zeros = torch.full((64, 4), 8, dtype=torch.int32) | |
| hf_pack_layer(module, linear, scales, zeros, g_idx, post_init=True) | |
| assert module.qzero_format() == 2 | |
| x = torch.randn(2, 128) | |
| # Zero weights: codes equal the zero point, so output must be exactly 0; | |
| # decoding zp-1 words raw would return +scale instead. | |
| assert torch.equal(module(x), torch.zeros(2, 64)) |
To reproduce / expected behavior
From the repository root at 35987df with requirements installed; CPU is sufficient:
python - <<'PY'
import torch
from torch import nn
from gptqmodel.nn_modules.qlinear.torch import TorchLinear
from gptqmodel.utils.backend import BACKEND
from gptqmodel.utils.packing import hf_pack_layer, hf_post_init
torch.set_num_threads(1)
kw = dict(bits=4, group_size=32, desc_act=False, sym=True,
in_features=128, out_features=64, bias=False,
pack_dtype=torch.int32, backend=BACKEND.GPTQ_TORCH,
register_buffers=True, compile=False)
linear = nn.Linear(128, 64, bias=False)
linear.weight.data.zero_()
scales = torch.ones(64, 4)
zeros = torch.full((64, 4), 8, dtype=torch.int32)
g_idx = torch.arange(128, dtype=torch.int32) // 32
for container, fmt, inline in [(False, 'gptq', False),
(True, 'gptq', False),
(False, 'gptq', True),
(False, 'gptq_v2', False)]:
layer = TorchLinear(**kw)
hf_pack_layer(layer, linear, scales, zeros, g_idx,
pack_impl='original', post_init=inline,
checkpoint_format=fmt)
if not inline:
hf_post_init(nn.Sequential(layer) if container else layer)
layer.eval()
with torch.no_grad():
y = layer(torch.ones(1, 128))
print(container, fmt, inline, layer.qzero_format(), y[0, :4].tolist())
PYObserved result
Ignoring routine import logs:
False gptq False 1 [128.0, 128.0, 128.0, 128.0]
True gptq False 1 [128.0, 128.0, 128.0, 128.0]
False gptq True 2 [0.0, 0.0, 0.0, 0.0]
False gptq_v2 False 2 [0.0, 0.0, 0.0, 0.0]
Expected all four outputs to be exactly zero by the independent zero-weight oracle.
Validation limits
Actual shipped Python code, no mocks/AST extraction, CPU Torch 2.15.0+cpu, Python 3.12.16, Transformers 5.22.2. Eval and container variants executed. Historical introduction verified by running actual detached worktrees. No full-model or accelerator inference claim.
2. hf_repack_layer silently casts BF16 AWQ checkpoint buffers into FP16 target allocations
A valid AWQ layer loses checkpoint values immediately when copied to the CPU ATen backend, even when BF16 activation/output dtype is explicitly requested. A finite BF16 bias of 65536 becomes FP16 infinity, making outputs infinite. A separately tested 2^-30 scale becomes zero, erasing nonzero weights.
Trigger
Use hf_repack_layer(source, BACKEND.AWQ_TORCH_ATEN, device='cpu', dtype=torch.bfloat16) on a 4-bit GEMM AwqTorchLinear with group_size=32, 128 inputs, 64 outputs, and BF16/FP32 scales or bias outside FP16's range. Both kernels declare BF16 activation support; the API's dtype parameter describes activation/output dtype, not permission to narrow checkpoint storage.
Introducing change
Introduced by PR #3251, merge 5cef672b9df3e1fe846a574ccd80683e33d3e01d (2026-10-11). The BF16-source reproduction was also executed at that merge. PR #3800 later broadens exposure to FP32 source buffers; it did not introduce the original copy-path defect.
Source evidence
Source AwqTorchLinear.pack preserves source scales and bias dtypes:
GPTQModel/gptqmodel/nn_modules/qlinear/torch_awq.py
Lines 114 to 128 in 35987df
| def pack(self, linear: torch.nn.Module, scales: torch.Tensor, zeros: torch.Tensor, g_idx: torch.Tensor = None): | |
| del g_idx | |
| assert scales is not None and zeros is not None | |
| scales = scales.t().contiguous() | |
| zeros = zeros.t().contiguous() | |
| scale_zeros = zeros.float() * scales.float() | |
| # Torch AWQ converts scales for each forward, so packing need not | |
| # narrow a source scale before writing the checkpoint. | |
| self.register_buffer("scales", scales.clone()) | |
| if linear.bias is not None: | |
| # The bias is added after a wide reduction, so keep the source | |
| # precision even when AWQ scales are stored in half precision. | |
| self.register_buffer("bias", linear.bias.clone()) |
GPTQModel/gptqmodel/nn_modules/qlinear/torch_awq.py
Lines 89 to 94 in 35987df
| def post_init(self): | |
| # `scales` and `bias` keep the precision they were loaded with. The | |
| # activation dtype is applied to temporary operands inside `forward`, | |
| # never written back to the stored buffers. | |
| self.clear_weight_cache() | |
| super().post_init() |
Target declares BF16 support but allocates scales and bias unconditionally in FP16:
| SUPPORTS_DTYPES = [torch.float16, torch.bfloat16] |
GPTQModel/gptqmodel/nn_modules/qlinear/torch_aten_kernel_awq.py
Lines 115 to 123 in 35987df
| self.register_buffer( | |
| "scales", | |
| torch.zeros((group_rows, self.out_features), dtype=torch.float16), | |
| ) | |
| if bias: | |
| self.register_buffer("bias", torch.zeros(self.out_features, dtype=torch.float16)) | |
| else: | |
| self.bias = None |
_copy_packed_state calls ordinary load_state_dict, casting into those allocations:
GPTQModel/gptqmodel/utils/packing.py
Lines 764 to 791 in 35987df
| def _copy_packed_state(source: BaseQuantLinear, target: BaseQuantLinear) -> None: | |
| source_state = source.state_dict() | |
| target_state = target.state_dict() | |
| if not any(key in source_state for key in ("qweight", "qzeros")): | |
| raise ValueError( | |
| f"hf_repack_layer: `{type(source).__name__}` has no packed tensors; " | |
| "pack the layer before repacking." | |
| ) | |
| missing = [ | |
| key | |
| for key in _PACKED_STATE_KEYS | |
| if key in source_state and key not in target_state | |
| ] | |
| if missing: | |
| raise NotImplementedError( | |
| f"hf_repack_layer: `{type(target).__name__}` does not expose the packed buffers " | |
| f"{missing} required to copy a `{type(source).__name__}` layout." | |
| ) | |
| shared = {key: value for key, value in source_state.items() if key in target_state} | |
| target.load_state_dict(shared, strict=False) | |
| source_qzero_format = getattr(source, "qzero_format", None) | |
| target_qzero_format = getattr(target, "qzero_format", None) | |
| if callable(source_qzero_format) and callable(target_qzero_format): | |
| target_qzero_format(format=source_qzero_format()) |
The existing compatible-kernels test uses GPTQ tensors rather than BF16-range AWQ buffers:
GPTQModel/tests/test_hf_packing_api.py
Lines 484 to 509 in 35987df
| def test_hf_repack_layer_between_compatible_kernels(): | |
| if not _torch_aten_available(): | |
| pytest.skip("torch aten int4 CPU ops are unavailable in this build") | |
| linear, scales, zeros, g_idx = _make_inputs(4) | |
| source = _make_gptq_module() | |
| hf_pack_layer(source, linear, scales, zeros, g_idx, checkpoint_format=FORMAT.GPTQ_V2) | |
| # Model packing commonly exports a v1 GPTQ checkpoint after packing. | |
| convert_gptq_v2_to_v1_format_module(source, QuantizeConfig(bits=4)) | |
| target = hf_repack_layer(source, BACKEND.GPTQ_TORCH_ATEN) | |
| assert isinstance(target, TorchAtenLinear) | |
| for key in ("qweight", "scales", "g_idx"): | |
| assert torch.equal(getattr(source, key), getattr(target, key)) | |
| assert target.qzero_format() == 2 | |
| # Compare inference with an independently packed v2 reference, rather | |
| # than with the v1 checkpoint source itself. | |
| reference = _make_gptq_module() | |
| hf_pack_layer( | |
| reference, | |
| linear, | |
| scales, | |
| zeros, | |
| g_idx, |
To reproduce / expected behavior
From the pinned repository root with requirements installed; CPU is sufficient:
python - <<'PY'
import torch
from torch import nn
from gptqmodel.nn_modules.qlinear.torch_awq import AwqTorchLinear
from gptqmodel.utils.backend import BACKEND
from gptqmodel.utils.packing import hf_pack_layer, hf_repack_layer
torch.set_num_threads(1)
linear = nn.Linear(128, 64, bias=True, dtype=torch.bfloat16)
linear.weight.data.zero_()
linear.bias.data.fill_(65536)
source = AwqTorchLinear(bits=4, group_size=32, desc_act=False,
sym=False, in_features=128, out_features=64,
bias=True, backend=BACKEND.AWQ_TORCH)
hf_pack_layer(source, linear, torch.ones(64, 4, dtype=torch.bfloat16),
torch.full((64, 4), 8, dtype=torch.int32), post_init=True)
target = hf_repack_layer(source, BACKEND.AWQ_TORCH_ATEN,
device='cpu', dtype=torch.bfloat16)
x = torch.ones(1, 128, dtype=torch.bfloat16)
print('source', source.bias.dtype, source.bias[0].item(), source(x)[0, 0].item())
print('target', target.bias.dtype, target.bias[0].item(), target(x)[0, 0].item())
PYObserved result
source torch.bfloat16 65536.0 65536.0
target torch.float16 inf inf
Expected finite BF16 output exactly 65536 because weights are exactly zero. Independently repeated the original FP32-source fixture: source bias/output 65536, target inf, restoring source bias/scales gives 65536. Additional actual probe with all dense weights and scales 2^-30, zero bias: source output 1.1920928955078125e-07; copied target scale/output 0; preserving source buffers restores the exact source/oracle output.
Validation limits
Actual shipped public APIs and CPU ATen wrapper executed, no mocked kernels or AST extraction. Forward reproductions use default training=True, the supported portable path; optimized fused ATen eval arithmetic was not validated. Buffer corruption occurs immediately after repack independently of forward/training mode. BF16-source reproduction also executed at the introducing #3251 merge. No GPU or full-model claim.
3. hf_pack_layer misclassifies AllSparkAwqLinear as GPTQ and rejects its supported raw AWQ packer
The public stable packing helper cannot pack the supported AllSpark AWQ backend at all: it raises before invoking the class's working AWQ pack method. This blocks external integrators using the advertised common helper, although direct class.pack remains a workaround.
Trigger
Call hf_pack_layer on AllSparkAwqLinear(bits=8, group_size=-1, desc_act=False, sym=False, in_features=128, out_features=128, register_buffers=True), with valid per-channel scales/zeros and post_init=False for packing before accelerator placement. On supported accelerator systems the constructor's hardware admission succeeds.
Introducing change
Introduced when PR #3490, merge 8a6a03f614d0650f8e9fafdd9fe1140fac62eac0 (2026-11-03), added AllSparkAwqLinear with QUANT_TYPE="allspark" and pack(). The common helper's older AWQ-prefix test does not recognize that declared AWQ backend.
Source evidence
Class declares METHOD.AWQ, GEMM format, 8-bit/per-channel support, NVIDIA/AMD device families, but QUANT_TYPE='allspark':
GPTQModel/gptqmodel/nn_modules/qlinear/allspark_awq.py
Lines 64 to 91 in 35987df
| class AllSparkAwqLinear(AWQuantLinear): | |
| # AWQ sub-kernel of the shared AllSpark backend. ``BACKEND.ALLSPARK`` plus | |
| # the checkpoint method/format selects this class; no AWQ-specific backend | |
| # name is required. | |
| SUPPORTS_BACKENDS = [BACKEND.ALLSPARK] | |
| SUPPORTS_METHODS = [METHOD.AWQ] | |
| # 0 keeps the format registered but opts out of AUTO selection, like the | |
| # GPTQ module: the numbers come first, promotion to AUTO later. | |
| SUPPORTS_FORMATS = {FORMAT.GEMM: 0} | |
| SUPPORTS_BITS = [8] | |
| # Per-channel only: one scale/zero row covers all of K. | |
| SUPPORTS_GROUP_SIZE = [-1] | |
| SUPPORTS_DESC_ACT = [True, False] | |
| SUPPORTS_SYM = [True, False] | |
| SUPPORTS_SHARDS = False | |
| SUPPORTS_TRAINING = False | |
| SUPPORTS_AUTO_PADDING = False | |
| SUPPORTS_IN_FEATURES_DIVISIBLE_BY = [ALLSPARK_K_ALIGN] | |
| SUPPORTS_OUT_FEATURES_DIVISIBLE_BY = [ALLSPARK_N_ALIGN] | |
| SUPPORTS_DEVICES = [DEVICE.CUDA, DEVICE.ROCM] | |
| SUPPORTS_PLATFORM = [PLATFORM.LINUX] | |
| SUPPORTS_PACK_DTYPES = [torch.int32] | |
| SUPPORTS_ADAPTERS = [] | |
| SUPPORTS_DTYPES = [torch.float16, torch.bfloat16] | |
| REQUIRES_FORMAT_V2 = False | |
| QUANT_TYPE = "allspark" |
Public dispatcher recognizes AWQ only by QUANT_TYPE prefix 'awq_' or exact 'llm-awq', otherwise requires pack_original and raises:
GPTQModel/gptqmodel/utils/packing.py
Lines 573 to 588 in 35987df
| quant_type = getattr(type(module), "QUANT_TYPE", None) | |
| if quant_type == "qqq": | |
| module.pack(linear=linear, scales=scales, s_extra=scales_extra) | |
| elif quant_type is not None and (quant_type.startswith("awq_") or quant_type == "llm-awq"): | |
| module.pack( | |
| linear=linear, | |
| scales=scales, | |
| zeros=_resolve_zeros(module=module, scales=scales, zeros=zeros), | |
| g_idx=g_idx, | |
| ) | |
| else: | |
| if not hasattr(module, "pack_original"): | |
| raise ValueError( | |
| f"hf_pack_layer: `{type(module).__name__}` does not implement a supported packing path." | |
| ) |
The shipped pack method implements AWQ N-axis packing and checkpoint-buffer registration:
GPTQModel/gptqmodel/nn_modules/qlinear/allspark_awq.py
Lines 179 to 223 in 35987df
| def pack(self, linear: torch.nn.Module, scales: torch.Tensor, | |
| zeros: torch.Tensor, g_idx: torch.Tensor = None): | |
| """Quantise a dense weight into the AWQ 8-bit on-disk layout. | |
| Required because the inherited GPTQ packer packs along K; AWQ packs | |
| along N. Uses the shared ``pack_awq`` helper so a checkpoint written | |
| here is byte-compatible with the other AWQ backends. | |
| """ | |
| from ...quantization.awq.utils.packing_utils import pack_awq | |
| del g_idx | |
| assert scales is not None and zeros is not None | |
| if self.requested_group_size not in (-1, self.in_features): | |
| raise ValueError( | |
| "AWQ AllSpark supports group_size=-1 only, got " | |
| f"{self.requested_group_size}" | |
| ) | |
| scales = scales.t().contiguous() | |
| zeros = zeros.t().contiguous() | |
| scale_zeros = zeros * scales | |
| scale_dtype = self.scales.dtype if getattr(self, "scales", None) is not None else self.compute_dtype | |
| self.register_buffer("scales", scales.clone().to(scale_dtype)) | |
| if linear.bias is not None: | |
| # Keep the source width; an FP32 bias must stay FP32 through the | |
| # kernel's FP32 epilogue instead of narrowing to the activation | |
| # dtype first. | |
| self.register_buffer("bias", linear.bias.clone()) | |
| else: | |
| self.bias = None | |
| weight = linear.weight.data | |
| group_index = torch.arange(self.in_features, device=weight.device) // self.group_size | |
| intweight = torch.round( | |
| (weight.t() + scale_zeros.index_select(0, group_index)) | |
| / self.scales.index_select(0, group_index) | |
| ).clamp_(0, self.maxq).to(torch.int32).contiguous() | |
| qweight, qzeros = pack_awq(intweight, zeros.to(torch.int32), self.bits) | |
| self.register_buffer("qweight", qweight) | |
| self.register_buffer("qzeros", qzeros) | |
| # A re-pack replaces the checkpoint tensors, so any kernel layout built | |
| # from the previous ones is stale. | |
| self.clear_weight_cache() |
GPTQModel/gptqmodel/utils/importer.py
Lines 362 to 374 in 35987df
| def _supports_pack_api(cls: Type[BaseQuantLinear]) -> bool: | |
| # Some kernels expose a ``pack`` method only because they share the | |
| # runtime interface, but deliberately reject raw-weight packing and are | |
| # valid only as repack/load targets (for example TorchInt8). Do not | |
| # advertise those classes when ``select_quant_linear(..., pack=True)`` is | |
| # used by the public HF packing API. | |
| if getattr(cls, "SUPPORTS_RAW_PACKING", True) is False: | |
| return False | |
| return ( | |
| issubclass(cls, PackableQuantLinear) | |
| or (hasattr(cls, "pack") and callable(getattr(cls, "pack"))) | |
| or (hasattr(cls, "pack_block") and callable(getattr(cls, "pack_block"))) | |
| ) |
Existing supported-device AllSpark tests call mod.pack directly, bypassing hf_pack_layer:
GPTQModel/tests/test_allspark_awq_cuda.py
Lines 228 to 244 in 35987df
| @pytest.mark.parametrize("dtype", DTYPES) | |
| def test_awq_module_pack_boundaries_and_dtype_moves(dtype): | |
| from gptqmodel.nn_modules.qlinear.allspark_awq import AllSparkAwqLinear | |
| k, n = 80, 272 | |
| # Power-of-two scales make half-code ties and their neighbours exact. | |
| values = torch.tensor([-129., -128., -127.5, -0.5, 0., 0.5, 1.5, 126.5, 127., 128.], dtype=dtype) | |
| below = torch.nextafter(values, torch.full_like(values, -float("inf"))) | |
| above = torch.nextafter(values, torch.full_like(values, float("inf"))) | |
| weight = torch.cat([below, values, above]).repeat((k * n + 29) // 30)[:k*n].reshape(n, k).cuda() | |
| dense = torch.nn.Linear(k, n, bias=False, device="cuda", dtype=dtype) | |
| dense.weight.data.copy_(weight) | |
| mod = AllSparkAwqLinear(bits=8, group_size=-1, sym=False, desc_act=False, | |
| in_features=k, out_features=n, dtype=dtype, register_buffers=True).cuda() | |
| scales = torch.ones(n, 1, device="cuda", dtype=dtype) | |
| zeros = torch.full((n, 1), 128, device="cuda", dtype=torch.int32) | |
| mod.pack(dense, scales, zeros) |
To reproduce / expected behavior
CPU dispatch-only reproduction from pinned root with requirements installed; only hardware admission is mocked, no accelerator forward is called. On an admitted supported NVIDIA/AMD host, omit the patch wrapper and construct normally:
python - <<'PY'
from unittest.mock import patch
import torch
from torch import nn
from gptqmodel.nn_modules.qlinear.allspark_awq import AllSparkAwqLinear
from gptqmodel.utils.packing import hf_pack_layer
torch.set_num_threads(1)
with patch.object(AllSparkAwqLinear, 'cached_validate_once', return_value=(True, None)):
layer = AllSparkAwqLinear(bits=8, group_size=-1, desc_act=False,
sym=False, in_features=128, out_features=128,
bias=False, register_buffers=True)
linear = nn.Linear(128, 128, bias=False)
linear.weight.data.zero_()
scales = torch.ones(128, 1)
zeros = torch.full((128, 1), 128, dtype=torch.int32)
try:
hf_pack_layer(layer, linear, scales, zeros, post_init=False)
except Exception as exc:
print(type(exc).__name__, str(exc))
layer.pack(linear, scales, zeros)
print('direct pack succeeds', tuple(layer.qweight.shape), tuple(layer.qzeros.shape))
PYObserved result
ValueError hf_pack_layer: `AllSparkAwqLinear` does not implement a supported packing path.
direct pack succeeds (128, 32) (1, 32)
Expected the public helper to invoke the AWQ pack method, producing the same supported packed layout as the direct-call control.
Validation limits
Confirmed the public Python dispatch failure and direct shipped CPU packing control. Mocked cached_validate_once solely because this environment has no supported accelerator; constructor format/shape arguments are valid declared contracts. No claim of AllSpark CUDA/ROCm numerical correctness, native extension build, post_init, or supported-device execution.
Duplicate check
Independently searched gh issue list --repo ModelCloud/GPTQModel --state all with hf_post_init, hf_pack_layer, '"hf_" "packing"', '"packing" "zero"', '"post_init" "qzeros"', and '"zero point offset"'. No matching issue found. Viewed closed #726 (API request/old installation issue) and #2350 (ExLlamaV2 AWQ asymmetric zero-point packing, a different backend/algorithm). Also inspected merged PR #3481 and its related resolved inline-init review discussion: the shipped inline correction does not fix this standalone path.
Independently searched public open and closed issues with hf_repack_layer, '"repack" "AWQ"', '"repack" "bias"', '"repack precision"', '"AWQ" "bfloat16"', '"bias" "inf"', and '"scales" "precision"'. No matching report found. Viewed closed #2221 (checkpoint key compatibility with vLLM) and #1625 (native qweight dtype error), neither is this stable-API storage cast.
gh issue list --repo ModelCloud/GPTQModel --state all --search 'AllSpark' returned only closed #1359. Viewed its body: it requests general AllSpark/ExLlama kernel support and does not report this common-helper dispatch error. Searches for hf_pack_layer returned no issues. No matching existing issue found.
Activity