Repository navigation
perf(cpu): verify the int4pack inverse once per layout instead of rebuilding every qweight (#4884) - #4965
Merged
Conversation
…uilding every qweight (#4884) #4845 dropped the checkpoint `qweight` clone of `TorchCpuAvx512Linear` and verified the pure-Torch inverse against that clone inside `transform_cpu`. With the clone gone, every `state_dict()` rebuilt every weight too, and the inverse itself was a `codes.t()` transpose plus eight strided shift/OR passes over an int32 expansion. - Build the checkpoint bytes in one pass over the packed tensor and view four of them as one little-endian int32 word, replacing the transpose plus eight passes. `unpack_hf_int4` transposes the 16 x half_in block per byte lane instead of walking the full 4-D view twice. - Verify the inverse once per (module class, inverse, packer, shape, layout) in the process; later modules of the same layout only check the captured shape/dtype. The key carries the inverse and packer identities, so a monkeypatched or overridden inverse re-verifies. - A `desc_act` channel order is applied at the checkpoint-byte level when the reorder keeps input pairs adjacent, and at the code level otherwise; both emit the same bytes. The emitted checkpoint stays bitwise identical. On a synthetic 4096x14336 module `rebuild_avx512_qweight` drops from 184 ms to 40 ms (identity) and 235 ms to 75 ms (desc_act); a transformed 1024x8192 module's `state_dict()` drops from 22.4 ms to 4.6 ms.
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 #4884, the CPU AUTO regression from #4845 (fix of #4783) and #4832. Dropping the checkpoint
qweightclone is correct, but it madetransform_cpuverify the pure-Torch inverse by rebuilding every module's full weight, and every laterstate_dict()rebuilds it again. On an 8B model that turned the first forward from 1.97 s into 23.5 s andstate_dict()from 0.32 s into 22.95 s.Two changes:
codes.t().reshape(...)transpose plus eight strided shift/OR passes over anint32expansion is replaced by building the checkpoint bytes (two nibbles per byte) and viewing four of them as one little-endianint32word.unpack_hf_int4also transposes only the 16 xhalf_inblock per byte lane instead of walking the full 4-D view twice.(module class, inverse, forward packer, shape, bits/group_size/pack_factor, ret_idx mode)in the process. Later modules of the same layout only check the captured shape/dtype before dropping their clone. The key carries the inverse and packer identities, so a monkeypatched/overridden inverse or a different packer re-verifies instead of inheriting an unrelated proof.A
desc_actchannel order is applied at the checkpoint-byte level when the reorder keeps input pairs adjacent (the group-sortedg_idxcase) and at the code level otherwise. Both paths emit identical bytes.The emitted checkpoint is bitwise identical, the clone is still dropped (the #4783 memory win is unchanged), and an unverified inverse still keeps the clone.
What Changed
gptqmodel/nn_modules/qlinear/torch_cpu_avx512.py: contiguousunpack_hf_int4; newavx512_checkpoint_bytesthat emits the checkpoint byte layout directly.gptqmodel/nn_modules/qlinear/_cpu_int4pack_layout.py:rebuild_avx512_qweightbuilds checkpoint bytes and views them asint32words;avx512_checkpoint_byte_indexselects the byte-leveldesc_actreorder with a code-level fallback.gptqmodel/nn_modules/qlinear/_fused_train_state.py: process-wide_VERIFIED_REBUILD_LAYOUTSmemo (lock-guarded for free-threaded builds) used byfinalize_fused_train_state.tests/test_cpu_int4_verify_cost_4884.py: cost guard for the inverse, cost guard forstate_dict()on a transformed module, once-per-layout guard, and two corruption guards.API/behavior changes: none. No checkpoint bytes, tensor shapes, dtypes, or user-facing entry points change.
Follow-up intentionally out of scope: adding a native C++
unpacknext topack_gptq_int4. The pure-Torch path is now about as fast as the pure-Torch forward pack, and the C++ kernel cannot be built or loaded on this host (no AVX512-BF16), so it cannot be validated here.Tests
origin/main: 4 failed, 91 passed, 26 skipped (delta: +7 passed, the new file).test_checkpoint_state_invariant.py(torch_cpu_avx512/awq_torch_cpu_avx512); they fail identically onorigin/mainon this host.origin/main4 failed, 3 passed -> this branch 7 passed.tests/kernels/test_paro_cpu_lock_concurrency_4885.py tests/test_qqq_cpu.py tests/test_torch_cpu_avx512.py tests/test_torch_cpu_avx512_awq.py-> 22 passed, 116 skipped.ruff checkon all four touched files: clean.Red evidence from the same test file on unmodified
origin/main:Before / after
Same host, back-to-back runs, best of 5; synthetic 4096x14336 packed layout for the inverse and a transformed 1024x8192
TorchCpuAvx512Linearforstate_dict():pack_hf_int4forward, 4096x14336unpack_hf_int4rebuild_avx512_qweight, identityrebuild_avx512_qweight,desc_actstate_dict(), transformed 1024x8192state_dict()/ memcpy of its 4.2 MB qweightBitwise equality: the existing
test_cpu_int4_snapshot_dedup_4395.pyandtest_cpu_avx512_snapshot_rebuild_4783.pystill assert byte-identical checkpoint emission; the new file adds identity anddesc_acttransformed-module round trips, plus a corrupted-runtime-words case that must keep the clone authoritative.What could not be measured on this host
This EPYC has no AVX512-BF16, so
TorchCpuAvx512Linear.cached_validate_once()isFalseand the real C++pack_gptq_int4/GEMM kernels cannot be loaded. Consequences:tests/kernels/test_cpu_avx512_snapshot_rebuild_4783.py, the 4test_checkpoint_state_invariant.pynodes) are skipped/fail here, exactly as onorigin/main.rebuild_avx512_qweight/unpack_hf_int4with the synthetic layout, and the module-level path was driven with the same pure-Torch packer stand-in pattern used bytests/kernels/test_paro.py.Model Support / Module Plan
Not applicable: no
MODEL_MAP, model definition, or module-plan change.Logic Flow Documentation
The mechanism changes: the per-module unconditional rebuild-compare in
finalize_fused_train_stateis replaced by a per-layout memo, and the inverse emits checkpoint bytes directly.Removed/replaced mechanism:
_fused_train_state.py::finalize_fused_train_statecalled_materialize_snapshot_entry(full_rebuild_checkpoint_qweight) for every module_VERIFIED_REBUILD_LAYOUTS; full rebuild only on the first module of a key_cpu_int4pack_layout.py::rebuild_avx512_qheightdidcodes.t().reshape(-1, 8, out)plus 8 stridedint32shift/OR passesavx512_checkpoint_bytesemits[out, in // 2]bytes; 4 bytes are viewed as one little-endianint32wordflowchart TD A["capture_fused_train_state(module)<br/>clone qweight as RebuildCandidate"] --> B["transform_cpu<br/>pack_gptq_int4_kernel -> runtime qweight"] B --> C["finalize_fused_train_state(module)"] C --> D{"key = _rebuild_layout_key(module, inverse)<br/>key in _VERIFIED_REBUILD_LAYOUTS?"} D -- "yes" --> E["drop _fused_train_state_qweight<br/>snapshot[name] = RebuiltCheckpointTensor"] D -- "no" --> F["_materialize_snapshot_entry<br/>_rebuild_checkpoint_qweight(module)"] F --> G{"torch.equal(rebuilt, expected)?"} G -- "no" --> H["keep the clone<br/>(fail closed: unverified inverse)"] G -- "yes" --> I["_VERIFIED_REBUILD_LAYOUTS.add(key)"] --> E E --> J["state_dict()<br/>rebuild checkpoint bytes on demand"] H --> K["state_dict()<br/>emit the resident clone"]A reference page under
docs/is not added: this is an internal memoization of a pure function, the checkpoint contract and emitted bytes are unchanged, and the mechanism is documented in the touched module docstrings. This matches the documentation scope of the predecessor #4845.Review Requirements
Kernel Accuracy Requirements
Not applicable: no kernel arithmetic, layout, or dtype change. The pure-Torch inverse is still the documented inverse of
pack_hf_int4, and the tests assert bitwise-identical checkpoint bytes for identity anddesc_actorders.Notes
The process-wide memo only removes repeated work.
state_dict()still has to materialize the checkpointqweightbecause the clone is gone; that is why the inverse itself is made cheap. Keeping a resident checkpoint copy would restore the 63% memory regression from #4783.