Skip to content

perf(cpu): verify the int4pack inverse once per layout instead of rebuilding every qweight (#4884) - #4965

Merged
Qubitium merged 1 commit into
mainfrom
root/cpu-verify-rebuild-4884
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
root/cpu-verify-rebuild-4884

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Fixes #4884, the CPU AUTO regression from #4845 (fix of #4783) and #4832. Dropping the checkpoint qweight clone is correct, but it made transform_cpu verify the pure-Torch inverse by rebuilding every module's full weight, and every later state_dict() rebuilds it again. On an 8B model that turned the first forward from 1.97 s into 23.5 s and state_dict() from 0.32 s into 22.95 s.

Two changes:

  1. The inverse itself is now one contiguous pass. The old codes.t().reshape(...) transpose plus eight strided shift/OR passes over an int32 expansion is replaced by building the checkpoint bytes (two nibbles per byte) and viewing four of them as one little-endian int32 word. unpack_hf_int4 also transposes only the 16 x half_in block per byte lane instead of walking the full 4-D view twice.
  2. The rebuild-vs-clone comparison is memoized once per (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_act channel order is applied at the checkpoint-byte level when the reorder keeps input pairs adjacent (the group-sorted g_idx case) 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: contiguous unpack_hf_int4; new avx512_checkpoint_bytes that emits the checkpoint byte layout directly.
  • gptqmodel/nn_modules/qlinear/_cpu_int4pack_layout.py: rebuild_avx512_qweight builds checkpoint bytes and views them as int32 words; avx512_checkpoint_byte_index selects the byte-level desc_act reorder with a code-level fallback.
  • gptqmodel/nn_modules/qlinear/_fused_train_state.py: process-wide _VERIFIED_REBUILD_LAYOUTS memo (lock-guarded for free-threaded builds) used by finalize_fused_train_state.
  • tests/test_cpu_int4_verify_cost_4884.py: cost guard for the inverse, cost guard for state_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++ unpack next to pack_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

export CUDA_HOME=/usr/local/cuda PATH=/usr/local/cuda/bin:$PATH TORCH_CUDA_ARCH_LIST=8.0 \
  TORCH_NO_COMPILER_WRAPPER=1 GPTQ_BYPASS_SAFETY_CHECKS=1 LOGBAR_ANIMATION=0 \
  CUDA_VISIBLE_DEVICES="" HF_HUB_OFFLINE=1 OMP_NUM_THREADS=8
cd /root/worktrees/root-4884
/root/venv-kernels/bin/python /tmp/root-rt.py \
  tests/kernels/test_cpu_avx512_snapshot_rebuild_4783.py \
  tests/test_cpu_int4_snapshot_dedup_4395.py \
  tests/kernels/test_paro.py \
  tests/test_cpu_int4pack_dispatch_contracts.py \
  tests/test_checkpoint_state_invariant.py \
  tests/test_cpu_int4_verify_cost_4884.py \
  -q -o addopts= -o log_cli=false -p no:cacheprovider
  • This branch: 4 failed, 98 passed, 26 skipped.
  • Unmodified origin/main: 4 failed, 91 passed, 26 skipped (delta: +7 passed, the new file).
  • The 4 failures are the pre-existing AVX512-BF16-only nodes in test_checkpoint_state_invariant.py (torch_cpu_avx512 / awq_torch_cpu_avx512); they fail identically on origin/main on this host.
  • New test alone: origin/main 4 failed, 3 passed -> this branch 7 passed.
  • Extra CPU/AVX512-adjacent coverage: 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 check on all four touched files: clean.

Red evidence from the same test file on unmodified origin/main:

E  AssertionError: rebuild_avx512_qweight costs 5.0x the forward pack of the same shape (188.3 ms vs 37.4 ms)
E  AssertionError: state_dict() took 24.49 ms for 4.2 MB of checkpoint bytes (373x a raw copy)
E  AssertionError: a later module of the same layout must not rebuild

Before / after

Same host, back-to-back runs, best of 5; synthetic 4096x14336 packed layout for the inverse and a transformed 1024x8192 TorchCpuAvx512Linear for state_dict():

measurement before after
pack_hf_int4 forward, 4096x14336 40.8 ms 36.1 ms
unpack_hf_int4 72.2 ms 23.9 ms
rebuild_avx512_qweight, identity 206.1 ms 38.3 ms
rebuild_avx512_qweight, desc_act 269.2 ms 59.1 ms
rebuild / forward pack (identity) 5.05x 1.06x
state_dict(), transformed 1024x8192 25.36 ms 5.29 ms
state_dict() / memcpy of its 4.2 MB qweight 264x 52x

Bitwise equality: the existing test_cpu_int4_snapshot_dedup_4395.py and test_cpu_avx512_snapshot_rebuild_4783.py still assert byte-identical checkpoint emission; the new file adds identity and desc_act transformed-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() is False and the real C++ pack_gptq_int4/GEMM kernels cannot be loaded. Consequences:

  • The AVX512-gated tests (tests/kernels/test_cpu_avx512_snapshot_rebuild_4783.py, the 4 test_checkpoint_state_invariant.py nodes) are skipped/fail here, exactly as on origin/main.
  • The C++ pack time and the issue's 8B model numbers were not re-measured. The inverse cost was measured directly on the pure-Torch rebuild_avx512_qweight/unpack_hf_int4 with the synthetic layout, and the module-level path was driven with the same pure-Torch packer stand-in pattern used by tests/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_state is replaced by a per-layout memo, and the inverse emits checkpoint bytes directly.

Removed/replaced mechanism:

before after
_fused_train_state.py::finalize_fused_train_state called _materialize_snapshot_entry (full _rebuild_checkpoint_qweight) for every module consults _VERIFIED_REBUILD_LAYOUTS; full rebuild only on the first module of a key
_cpu_int4pack_layout.py::rebuild_avx512_qheight did codes.t().reshape(-1, 8, out) plus 8 strided int32 shift/OR passes avx512_checkpoint_bytes emits [out, in // 2] bytes; 4 bytes are viewed as one little-endian int32 word
flowchart 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"]
Loading

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

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible (the only test stand-ins are the pure-Torch packer used by the existing CPU tests).
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions: the cache key includes the inverse and packer identities, the lock covers set mutation on free-threaded builds, and a mismatch still keeps the clone.

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 and desc_act orders.

Notes

The process-wide memo only removes repeated work. state_dict() still has to materialize the checkpoint qweight because 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.

…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.
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