Repository navigation
perf(dequant): vectorise and device-preserve qzeros pack/unpack (#3985) - #3991
Merged
Merged
Conversation
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
# Conflicts: # README.md
# Conflicts: # README.md
# Conflicts: # README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #3985
Root cause
gptqmodel/utils/model_dequant.pyunpack_cols,pack_colsandunpack_rowsallocatedtorch.empty(...)without adeviceand then ran aPython loop of
pack_factorstrided 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 insidepack_moduleforv2 -> v1 (
utils/model.py:1049).Two consequences:
dequantize_model(..., device="cuda")died withRuntimeError: indices should be either on cpu or on the same device as the indexed tensor (cpu)atmodel_dequant.py:1657(
zeros.to(torch.float32)[g_idx]): the unpacked zeros were host-residentwhile
g_idxcame from the CUDA shard.Fix
Decode/encode all packed fields in one broadcast shift, on the input's device:
unpack_rowsis the same withunsqueeze(1). Field bits are unchanged:an arithmetic right shift of the sign-extended word keeps the low
bitsofevery field identical to the unsigned decode, so 32-bit lanes are enough for
every packed width the helpers accept (
int8/int16/int32words;int64lanes 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 (
int32forunpack,
pack_dtypefor pack) and shapes are unchanged.Scope: item 1 of the issue. Items 2 (zero-filled
qweighthost RAM), 3(re-save rebuild +
self.modelreplacement) and 4 (dense-shard dequant) arenot 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"]The same diagram is committed with
file:linereferences indocs/gptq-qzero-device-conversion.md.Bitwise-equality proof
tests/test_qzero_pack_device.py(new) pins the vectorised helpers to anindependent loop oracle (the pre-fix implementation) and asserts
torch.equal+ identical device for:int8,int16,int32packed wordsunpack_cols,pack_cols(round trip == input bytes) andunpack_rowsplus the two end-to-end regressions:
test_unpacked_qzeros_stay_on_device_for_g_idx_gather- the exactzeros[g_idx]expression that crashed;test_gptq_dequant_cuda_shard_is_bitwise_equal_to_cpu- a real safetensorsGPTQ shard (qweight/qzeros/scales/g_idx/bias) converted with
device="cpu"anddevice="cuda"; every output tensor must betorch.equaland CPU-resident.Before (origin/main 1a30538)
After
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-30perf_counterfor host work. "Before" is the pre-fix loop implementation runin the same process on the same inputs (asserted
torch.equalfirst)._correct_gptq_v1_qzeros, CUDAint32[32, 1376]_correct_gptq_v1_qzeros, CUDAint32[64, 3584]_correct_gptq_v1_qzeros, CUDAint32[128, 128]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)
t.zeros->t.emptyforqweight) is not included. It needs aload-path contract threaded from
make_quant(..., from_quantized=True)through the per-backend buffer registration; an
emptybuffer that a pathforgets to fill fails silently with garbage instead of loudly, and this PR
does not add that guarantee.
self.model) anditem 4 (dense-shard dequant) are unaddressed: both need the streaming
TensorSourcesave plan, which is a separate redesign.Docs
docs/gptq-qzero-device-conversion.md(new, linked fromREADME.md) carries theMermaid conversion flow with the failing path marked and a before/after table
with
file:linereferences.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.pyis green (the branch is mergedup to
origin/maind18e2ba).