Repository navigation
perf(cpu): drop the int4 qweight snapshot where the inverse is exact (#5013) - #5033
Merged
Merged
Conversation
…5013) #4918 (fix of #4873) removed the fused/Paro operands that pinned the safetensors mapping, but two CPU int4 layouts still kept a full checkpoint-layout copy of `qweight` (`_fused_train_state_qweight`) for the life of the model, even though a bitwise inverse exists. 1. GPTQ `desc_act` on `TorchAtenLinear`/`TorchFusedLinear`: `_can_rebuild_checkpoint_qweight` returned False for every non-identity `ret_idx`, on the grounds that the ATen transform reorders the input rows "without keeping the gather". The module does keep `ret_idx` (it is `argsort(g_idx)`, a permutation of `[0, in_features)`), so `index_copy_` with that index is the exact inverse of `weight.index_select(0, ret_idx)`. `AUTO` with `dtype=torch.float16` on CPU selects this kernel, so the duplicate was not opt-in. 2. `TorchCpuAvx512AwqLinear` declared `_FUSED_TRAIN_STATE_REBUILD = None` ("no verified inverse") for the extension's `pack_awq_int4`. That op is a pure nibble permutation: each runtime byte pairs output column `group * 32 + row` (low nibble) with `group * 32 + row + 16` (high nibble) for one input feature, reading the checkpoint word through the AWQ reverse order. `rebuild_avx512_awq_qweight` undoes it with the reverse read plus `pack_awq_columns(..., order=AWQ_ORDER)`, in pure Torch, so it needs neither the extension nor AVX512-BF16 at save time. `TorchCpuAvx512AwqLinear.transform_cpu` now ends with `finalize_fused_train_state`, like the other CPU int4 transforms. Both inverses are only trusted after `finalize_fused_train_state` compares the rebuilt words bitwise with the clone captured before the transform; a mismatch keeps the clone, so an unverified layout can never reach a saved checkpoint. Measured on Qwen2.5-0.5B-Instruct, 4-bit g128 `desc_act`, CPU fp16 (`TorchAtenLinear`, `AUTO`'s choice), unique tensor storages before/after one forward: | tree | snapshot buffers | after forward | snapshot bytes | | --- | ---: | ---: | ---: | | `origin/main` | 168 | 620.3 MiB | 172.0 MiB | | this branch | 0 | 449.6 MiB | 1.3 MiB | `state_dict()` still emits the checkpoint `qweight` bitwise unchanged.
This was referenced Nov 17, 2026
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.
Summary
Fixes #5013. #4918 (fix of #4873) removed the fused/Paro operands that pinned
the safetensors mapping, but two CPU int4 layouts still kept a full
checkpoint-layout copy of
qweight(_fused_train_state_qweight) for thelife of the model, even though a bitwise inverse exists:
desc_actonTorchAtenLinear/TorchFusedLinear._can_rebuild_checkpoint_qweightreturnedFalsefor every non-identityret_idx, on the grounds that "the ATen fused transform reorders the inputrows by
ret_idxwithout keeping the gather". The module does keepret_idx— it isargsort(g_idx), a permutation of[0, in_features)— soindex_copy_with that index is the exact inverse ofweight.index_select(0, ret_idx).AUTOwithdtype=torch.float16on CPUselects
TorchAtenLinear, so this duplicate was not opt-in.TorchCpuAvx512AwqLineardeclared_FUSED_TRAIN_STATE_REBUILD = None("no verified inverse") for the extension's
pack_awq_int4.What Changed
gptqmodel/nn_modules/qlinear/_cpu_int4pack_layout.pyrebuild_gptq_qweightscatters the unpacked codes back throughret_idxwhen the order is not the identity.
rebuild_avx512_awq_qweight: the inverse of the extension'spack_awq_int4. Each runtime byte pairs output columngroup * 32 + row(low nibble) withgroup * 32 + row + 16(high nibble)for one input feature, reading the checkpoint word through the AWQ reverse
order; undoing it is the reverse read plus
pack_awq_columns(..., order=AWQ_ORDER), in pure Torch, so it needsneither the extension nor AVX512-BF16 at save time.
gptqmodel/nn_modules/qlinear/__init__.py:_FUSED_TRAIN_STATE_REBUILDgains
"avx512_awq"; thekind == "gptq" and not identity()bail-out isremoved;
_rebuild_checkpoint_qweightdispatches the new kind.gptqmodel/nn_modules/qlinear/torch_cpu_avx512_awq.py:_FUSED_TRAIN_STATE_REBUILD = "avx512_awq", andtransform_cpunow endswith
finalize_fused_train_statelike the other CPU int4 transforms.gptqmodel/nn_modules/qlinear/_fused_train_state.py: the verified-layout keyfor
"avx512_awq"is layout-wide (that packer applies no channel reorder), soone proof covers every module of the layout ([PERF] Regression from #4845 (fix of #4783), also #4832: verify-by-full-rebuild of every CPU int4 qweight makes the AVX512 AUTO first forward 10x slower (8B: 1.97 -> 23.5 s) and every state_dict() 72x slower (0.32 -> 22.9 s) #4884 behaviour preserved).
docs/torch_fused_int4_transformations.md: new "Which layouts keep aresident
qweightclone" section with the per-kernel inverse table.tests/test_cpu_int4_snapshot_5013.py(new, 17 nodes) and the AWQ CPUunitCI suite now runs it (with the touched
qlinearfiles added to the workflowpath filter).
Both inverses are only trusted after
finalize_fused_train_statecompares therebuilt words bitwise with the clone captured before the transform; a
mismatch keeps the clone, so an unverified layout can never reach a saved
checkpoint. This is the existing fail-closed contract, now covering the two
layouts that previously opted out of it entirely.
Tests
On unmodified
origin/main(8fd8644a1, test file copied into a separateworktree): 17 failed — every node, because neither inverse exists and both
layouts keep the clone.
On this branch: 16 passed, 1 skipped. The skip is the cross-check against
the real extension
pack_awq_int4, which needs AVX512-BF16.test_gptq_rebuild_undoes_the_desc_act_row_reorder[4 shapes]ret_idxscatter, against an independent checkpoint-word oracle, for group sizes 32 and 128test_desc_act_layer_drops_the_qweight_snapshot[2 kernels × 2 shapes]desc_actTorchAtenLinear/TorchFusedLinearforward drops the clone andstate_dict()is bitwise unchangedtest_desc_act_layer_keeps_the_clone_when_the_inverse_disagreestest_avx512_awq_inverse_round_trips_every_checkpoint_bit[5 shapes]int4_qzero_group_scaled_pack.cpptest_avx512_awq_inverse_matches_the_extension_when_it_is_availabletest_avx512_awq_module_drops_the_qweight_snapshottransform_cpupath: capture → pack → finalize drops the clone,state_dict()bitwise unchangedtest_avx512_awq_module_keeps_the_clone_for_a_foreign_layoutNeighbouring suites (
test_cpu_int4_snapshot_dedup_4395.py,test_cpu_int4_verify_cost_4884.py,test_checkpoint_state_invariant.py,kernels/test_cpu_avx512_snapshot_rebuild_4783.py,test_torch_cpu_avx512.py,kernels/test_paro.py,test_docs_contract_refs.py): 138 passed, 53skipped, 4 failed — the 4 are the AVX512-only
torch_cpu_avx512invariantnodes, which fail identically on unmodified
mainon this host (the AVX512extension cannot load here).
test_ret_idx_group_order.pyandtest_checkpoint_modules.pyshow the same pre-existing failures on both trees.The full AWQ CPU
unitlist: 1006 passed, 96 skipped, 9 failed, where the9 are the known pre-existing
afmoe/flint/jambaAWQ group invariants andgranitemodule-tree nodes (identical on unmodifiedmain).Model Support / Module Plan
No model or module-plan change; only the CPU int4 serialization contract.
Logic Flow Documentation
docs/torch_fused_int4_transformations.mdgains the inverse table and the"drop only after a bitwise match" rule, next to the existing snapshot-restore
section.
Kernel Accuracy Requirements
No kernel math changes. The runtime layouts, forwards and dequantization are
untouched; only the checkpoint-side inverse and the moment the clone is
released changed, and the release is gated on bitwise equality with the bytes
the module actually loaded.
Measured
Qwen2.5-0.5B-Instruct, 4-bit g128
desc_act, CPU fp16,TorchAtenLinear(
AUTO's choice), unique tensor storages over params + buffers + tensorattributes, before/after one in-session forward:
_fused_train_state_qweightbuffersorigin/mainThe issue's 8B numbers (3354 MiB snapshot) could not be reproduced on this
host (no 8B GPTQ
desc_actcheckpoint cached); the 0.5B delta is the samemechanism at 1/16 the width. The residual 1.3 MiB is the
qzerossnapshot,which this change does not touch.
Notes
kernel cannot load and its forward cannot run here. The AWQ inverse is
verified against a line-by-line Python mirror of
gptqmodel_ext/int4_qzero_group_scaled_cpu/int4_qzero_group_scaled_pack.cpp(cross-checked against the real kernel automatically on a host that has it),
and the module-level test runs the real
transform_cpuwith that mirrorinstalled as the pack kernel. No claim of an AVX512 end-to-end run.
ParoLinearkeeps its own_can_rebuild_checkpoint_qweightoverride; itslayouts are unchanged.