Skip to content

perf(dequant): vectorise and device-preserve qzeros pack/unpack (#3985) - #3991

Merged
Qubitium merged 6 commits into
mainfrom
fix/issue-3985
Nov 14, 2026
Merged

Qubitium merged 6 commits into
mainfrom
fix/issue-3985

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #3985

Root cause

gptqmodel/utils/model_dequant.py unpack_cols, pack_cols and
unpack_rows allocated torch.empty(...) without a device and then ran a
Python loop of pack_factor strided writes. These helpers back
_shift_gptq_qzeros (_correct_gptq_v1_qzeros /
_revert_gptq_v1_qzeros_correction), which run on load for GPTQ v1 -> v2
(loader.py:2526 -> utils/model.py:930) and inside pack_module for
v2 -> v1 (utils/model.py:1049).

Two consequences:

  1. Correctness. dequantize_model(..., device="cuda") died with
    RuntimeError: indices should be either on cpu or on the same device as the indexed tensor (cpu) at model_dequant.py:1657
    (zeros.to(torch.float32)[g_idx]): the unpacked zeros were host-resident
    while g_idx came from the CUDA shard.
  2. Load time. Every GPU-resident qzeros tensor went GPU -> host loop -> GPU.

Fix

Decode/encode all packed fields in one broadcast shift, on the input's device:

shifts = torch.arange(pack_factor, device=packed.device, dtype=compute_dtype) * bits
fields = (packed.to(compute_dtype).unsqueeze(-1) >> shifts) & mask      # unpack_cols
words  = (values.to(compute_dtype) & mask).reshape(r, c // pf, pf) << shifts
packed = reduce(operator.or_, words.unbind(-1)).to(pack_dtype)         # pack_cols

unpack_rows is the same with unsqueeze(1). Field bits are unchanged:
an arithmetic right shift of the sign-extended word keeps the low bits of
every field identical to the unsigned decode, so 32-bit lanes are enough for
every packed width the helpers accept (int8/int16/int32 words; int64
lanes are kept for >32-bit words). OR (not sum) keeps the packed bit pattern
exact even when a 2-bit field lands in the sign bit. Result dtype (int32 for
unpack, pack_dtype for pack) and shapes are unchanged.

Scope: item 1 of the issue. Items 2 (zero-filled qweight host RAM), 3
(re-save rebuild + self.model replacement) and 4 (dense-shard dequant) are
not in this PR; see "Not in this PR" below.

Logic flow

flowchart TD
    A["GPTQModel.load of a v1 checkpoint"] --> B["convert_gptq_v1_to_v2_format_module"]
    C["pack_module v2 to v1"] --> D["_revert_gptq_v1_qzeros_correction"]
    B --> E["_correct_gptq_v1_qzeros"]
    D --> F["_shift_gptq_qzeros"]
    E --> F
    F --> G["unpack_cols"]
    G --> H["pack_cols"]
    H --> I{"result follows the input device"}
    I -- "before: no, host result" --> K["dequantize_model device cuda raises RuntimeError at the zeros g_idx gather"]
    I -- "after: yes" --> L["bitwise-equal packed qzeros on the shard device"]
    L --> M["convert_gptq_file unpacks qweight rows and qzeros columns, then gathers g_idx"]
Loading

The same diagram is committed with file:line references in
docs/gptq-qzero-device-conversion.md.

Bitwise-equality proof

tests/test_qzero_pack_device.py (new) pins the vectorised helpers to an
independent loop oracle (the pre-fix implementation) and asserts
torch.equal + identical device for:

  • cpu and cuda
  • bits 2 / 4 / 8
  • int8, int16, int32 packed words
  • unpack_cols, pack_cols (round trip == input bytes) and unpack_rows

plus the two end-to-end regressions:

  • test_unpacked_qzeros_stay_on_device_for_g_idx_gather - the exact
    zeros[g_idx] expression that crashed;
  • test_gptq_dequant_cuda_shard_is_bitwise_equal_to_cpu - a real safetensors
    GPTQ shard (qweight/qzeros/scales/g_idx/bias) converted with
    device="cpu" and device="cuda"; every output tensor must be
    torch.equal and CPU-resident.

Before (origin/main 1a30538)

$ python -m pytest tests/test_qzero_pack_device.py -q
12 failed, 9 passed
E  RuntimeError: indices should be either on cpu or on the same device as the indexed tensor (cpu)
   gptqmodel/utils/model_dequant.py:1657

After

$ python -m pytest tests/test_qzero_pack_device.py -q
21 passed
$ python -m pytest tests/test_qzero_offsets.py tests/test_planar_bits_567.py tests/test_hf_packing_api.py -q
98 passed, 3 skipped

Measured before/after

Host: one RTX 4090 (UUID GPU-50a20676..., sm_89), Python 3.14.10t,
torch 2.16.0.dev20261102+cu130, Triton 3.9.0. Load average ~10 on 16 cores
(shared box), so CPU numbers are pessimistic. Timing: CUDA events through
triton.testing.do_bench (L2 flush, best-of-N) for device work; best-of-30
perf_counter for host work. "Before" is the pre-fix loop implementation run
in the same process on the same inputs (asserted torch.equal first).

case before after
_correct_gptq_v1_qzeros, CUDA int32 [32, 1376] 352.8 ms 39.1 us
_correct_gptq_v1_qzeros, CUDA int32 [64, 3584] 10.76 ms 75.7 us
_correct_gptq_v1_qzeros, CUDA int32 [128, 128] 694.7 us 31.8 us
56 x [32, 3584] v1->v2 conversion, CPU 156.9 ms 74.6 ms (2.1x)

The CUDA numbers collapse because the device -> host -> device round trip and
the Python loop are gone; the CPU number improves because one vectorised pass
replaces 8 strided write kernels.

Not in this PR (limitations)

  • Item 2 (t.zeros -> t.empty for qweight) is not included. It needs a
    load-path contract threaded from make_quant(..., from_quantized=True)
    through the per-backend buffer registration; an empty buffer that a path
    forgets to fill fails silently with garbage instead of loudly, and this PR
    does not add that guarantee.
  • Item 3 (re-save rebuilds the model from disk and replaces self.model) and
    item 4 (dense-shard dequant) are unaddressed: both need the streaming
    TensorSource save plan, which is a separate redesign.

Docs

docs/gptq-qzero-device-conversion.md (new, linked from README.md) carries the
Mermaid conversion flow with the failing path marked and a before/after table
with file:line references.

Risk

Low. Same arithmetic, same dtypes, same output bytes; the only behaviour change
is that the result follows the input device instead of being forced to the host.
ruff check gptqmodel docs/eora tests setup.py is green (the branch is merged
up to origin/main d18e2ba).

gptq-perf and others added 6 commits November 14, 2026 12:35
unpack_cols/pack_cols/unpack_rows allocated their result on the host and
filled it with a Python loop of pack_factor strided writes.  Every qzeros
conversion therefore moved the tensor GPU -> host loop -> GPU, and on
device="cuda" the unpacked zeros landed on the CPU while g_idx stayed on
the GPU, so dequantize_model crashed with

  RuntimeError: indices should be either on cpu or on the same device
  as the indexed tensor (cpu)

Decode/encode all packed fields with one broadcast shift on the input's
device (int32 lanes; arithmetic shifts keep the low field bits identical
for every accepted packed width).  Output dtype, shape and bits are
unchanged, so the conversion is bitwise equal to the loop implementation.

Test: tests/test_qzero_pack_device.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant