Skip to content

fix(cpu): keep packed buffers when clearing fused caches - #3773

Merged
Qubitium merged 4 commits into
mainfrom
fix/clear-weight-cache-restore
Nov 11, 2026
Merged

Qubitium merged 4 commits into
mainfrom
fix/clear-weight-cache-restore

Conversation

@ZX-ModelCloud

@ZX-ModelCloud ZX-ModelCloud commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR

clear_weight_cache() no longer restores the _fused_train_state checkpoint
snapshot. It only drops derived state and rebuilds it from the live packed
buffers. Checkpoint restore now happens only on an explicit checkpoint load,
checkpoint export, training resume, or a move that invalidates the runtime
layout (a low-precision dtype move or a cross-device move). Net: 12 files,
+472/-57.

1. The problem

A CPU inference forward rewrites qweight/qzeros/scales into the kernel's
int4pack layout in place. capture_fused_train_state() keeps the checkpoint
layout in _fused_train_state. clear_weight_cache() was also the restore
hook, so every clear put the checkpoint layout back:

flowchart TD
    A["eval forward"] --> B["capture_fused_train_state"]
    B --> C["transform_cpu: live qweight becomes int4pack uint8"]
    C --> D["linear_mode = INFERENCE"]
    E["clear_weight_cache / _apply move"] --> F["restore_fused_train_state"]
    F --> G["qweight back to int32 checkpoint shape"]
    F --> H["snapshot scales overwrite live scales"]
    G --> I["packed-storage assertion fails"]
    H --> J["fused output uses stale metadata"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class I,J failure;
Loading

Measured on origin/main at bc2ab2079: after scales.mul_(2) and then
clear_weight_cache(), the fused output was max_abs 1.390625 against an
expected 2.78125 (0.5x). Without the scale edit, clear was numerically
neutral. The packed qweight also reverted from int4pack uint8 (64, 64) to
int32 (16, 64), failing module.qweight is packed.

Mechanism Before After
Explicit clear / same-device move clear_weight_cache() restored the snapshot (gptqmodel/nn_modules/qlinear/torch_fused.py:145-148, gptqmodel/nn_modules/qlinear/torch_aten_kernel.py:172-176 before this PR). It drops derived state and rebuilds from the live packed buffers (torch_fused.py:133-160, torch_aten_kernel.py:165-185).
Checkpoint load Relied on the cache clear to restore before the copy (gptqmodel/nn_modules/qlinear/__init__.py:357-366 before this PR). Calls restore_fused_train_state() explicitly before the copy (qlinear/__init__.py:319-390).
Checkpoint export Relied on the cache clear to restore (gptqmodel/utils/model.py:2369-2375 before this PR). Calls restore_fused_train_state() explicitly per transformed module (gptqmodel/utils/model.py:2357-2377).
Training resume Restored in train() (gptqmodel/nn_modules/qlinear/torch_fused.py:212-216). Unchanged.
Low-precision dtype move Kept the runtime layout and narrowed scales/qzeros in place, pairing new scales with offsets built at the old precision; _cpu_transform_dtype still named the old activation dtype. Restores the snapshot and re-transforms (_fused_train_state.py:105-135, torch_aten_kernel.py:187-214).
Cross-device move Kept the runtime layout, handing one backend's packing to another. Restores the snapshot because the CPU int4pack packing is not the XPU packing (_fused_train_state.py:105-135).

2. The new flow

flowchart TD
    A["checkpoint layout<br/>qweight int32, snapshot present"] -->|"first eval forward<br/>capture_fused_train_state + transform"| B["runtime layout<br/>qweight int4pack uint8"]
    B -->|"clear_weight_cache<br/>explicit clear or same-device move"| B
    B -->|"low-precision dtype move<br/>restore_fused_train_state"| A
    B -->|"cross-device move<br/>restore_fused_train_state"| A
    B -->|"train / checkpoint load / export<br/>restore_fused_train_state"| A
    A -->|"clear_weight_cache<br/>invalidate derived state"| A
    B -. "modified runtime state" .-> X["export / invalidating move raises RuntimeError"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class X failure;
Loading

restore_fused_train_state() now also resets the runtime-layout state
(linear_mode, torch_fused_op, scales_and_zeros, _cpu_transformed,
_cpu_transform_dtype, _fused_state_key) because the restored tensors no
longer match that layout. The cache clear itself keeps those live.

The same contract is applied to the fused/ATen AWQ clear hooks. The fused AWQ
hook previously only restored the snapshot; it now rebuilds its packed op from
the live buffers like the GPTQ fused hook.

3. Failure and ambiguity paths

  • A modified runtime state has no valid checkpoint layout to re-finalize from,
    so restore_fused_train_state() raises instead of writing stale weights.
    This covers export, training resume, and an invalidating move.
  • A same-device move to FP32 keeps the live layout because it only widens the
    offsets. A move to FP16/BF16, or to another device, restores and
    re-transforms; it does not narrow the offsets in place.
  • A module without a snapshot (never transformed, or a non-CPU backend) is
    untouched by clear, export, and move handling.

4. Tests

  • tests/kernels/test_ret_idx_cache_invalidation.py — the reported 10
    failures now pass, including the packed-storage and clear/move lifecycle
    cases.
  • tests/test_torch_fused_asym_qzeros.py — clear keeps the packed layout and
    a later train() still restores the checkpoint.
  • tests/test_kernel_audit_regressions.py — checkpoint load/export and
    runtime self-round-trip cases still pass; the low-precision move test now
    covers all four CPU fused/ATen classes, and a device-move test asserts the
    checkpoint layout is restored.
  • Fusion and weight-storage suites still pass.

5. Validation

Suite Result
tests/test_kernel_audit_regressions.py, tests/kernels/test_ret_idx_cache_invalidation.py, tests/test_torch_fused_asym_qzeros.py, tests/test_torch_weight_storage.py 354 passed
tests/kernels/test_awq_torch_fused.py, tests/test_torch_cpu_avx512_awq.py, tests/kernels/test_awq_cpu_fused_post_init.py 51 passed, 1 skipped
tests/module_tree/test_fusion_kernel_backends.py 156 passed, 34 skipped
tests/module_tree/test_llama_fusion.py 78 passed
Same focused suites in the ROCm runtime 403 passed, 1 skipped, 2 unrelated failures
Fusion suites in the ROCm runtime 154 passed, 114 skipped

The two ROCm-only failures in test_kernel_audit_regressions.py
(test_awq_gemm_validation_... and test_machete_validation_...) reproduce on
untouched origin/main.

6. Reference

docs/torch_fused_int4_transformations.md now documents the cache-invalidation
versus checkpoint-restore lifecycle, the measured 0.5x regression, and the
cross-device layout rule. The page is already linked from README.md.

7. Reviewer notes

  • The clear hook is also used by nn.Module._apply; keeping the snapshot out
    of it is what makes explicit clears and same-device moves preserve
    uncommitted metadata.
  • restore_fused_train_state() remains the single explicit restore entry
    point, so export still raises for a modified runtime state.
  • No dense or expanded weight cache is introduced; only packed tensors and
    derived metadata are retained.

The helper gained a fourth return value in #3771, but three audit call sites still unpacked three. Unpack the checkpoint slot so the CPU fused regressions collect and run.
clear_weight_cache() unconditionally called restore_fused_train_state().
That hook also runs for nn.Module._apply moves and explicit cache clears,
so clearing after an in-place metadata edit replaced the live scales and
zero points with the checkpoint snapshot and put the checkpoint layout
back into the inference kernel. With scales.mul_(2) followed by clear,
the fused output was 0.5x the expected value (max_abs 1.390625 against
2.78125), and qweight reverted from int4pack uint8 (64, 64) to int32
(16, 64).

Make clear_weight_cache() only drop derived state (ret_idx,
scales_and_zeros, torch_fused_op, transform flags) and rebuild it from
the live packed buffers. Restore the checkpoint snapshot only on an
explicit checkpoint load, export, or training resume.
restore_fused_train_state() now also resets the runtime-layout state that
its restored tensors invalidate.

Apply the same contract to the fused/ATen AWQ clear hooks and document
the cache-invalidation versus checkpoint-restore lifecycle.
@ZX-ModelCloud
ZX-ModelCloud marked this pull request as ready for review November 11, 2026 12:28
@ZX-ModelCloud
ZX-ModelCloud marked this pull request as draft November 11, 2026 12:29
Keeping the runtime layout across an FP16/BF16 move paired the narrowed scales with affine offsets built from the old precision, silently changing the decoded weights (measured max_abs 0.03125 on a 10x-scale fixture). TorchAtenLinear also rejected its own moved model because _cpu_transform_dtype still named the pre-move activation dtype.

Restore the checkpoint snapshot after a low-precision dtype move and let the next forward re-transform. Device moves and moves to FP32 keep the live packed layout, as does an explicit clear. Add regression coverage that compares the moved layer with a checkpoint-layout copy moved before its first transform, using non-symmetric zero codes and non-power-of-two scales.

@ZX-ModelCloud ZX-ModelCloud left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed and pushed d63aee1e7 to fix two blocking regressions in the move path.

  • Low-precision moves corrupted the affine pair. _apply kept the runtime layout and narrowed scales/qzeros in place, but qzeros holds offsets computed from the pre-move scale dtype. A BF16 move therefore paired the new scales with stale offsets and changed the decoded weights (measured max_abs=0.03125 on an asymmetric-zero fixture with 10x scales). TorchAtenLinear/TorchAtenAwqLinear also rejected their own moved model because _cpu_transform_dtype still named the old activation dtype.

  • Fix: a move to FP16/BF16 now restores the checkpoint snapshot and lets the next forward re-transform. Device moves and moves to FP32 keep the live packed layout, as does an explicit clear_weight_cache(); the original cache-invalidation fix is unchanged. Regression tests compare the moved layer with a checkpoint-layout copy moved before its first transform, using non-symmetric zero codes and non-power-of-two scales.

Validation: tests/test_kernel_audit_regressions.py, tests/kernels/test_ret_idx_cache_invalidation.py, tests/test_torch_fused_asym_qzeros.py, tests/test_torch_weight_storage.py, and the AWQ/AVX512 suites: 397 passed, 1 skipped. Fusion: 234 passed, 34 skipped.

One follow-up for the description: the committed docs page now distinguishes a device move (keep the live layout) from a low-precision dtype move (restore + re-transform). The PR body's flow diagram and table still describe both moves as keeping the live layout and should be refreshed to match.

The runtime int4pack layout is device-specific: the CPU
_convert_weight_to_int4pack_for_cpu packing is not the XPU packing, so a
cross-device move that kept the live buffers handed the CPU kernel an
int32 XPU tensor (RuntimeError: _weight_int4pack_mm_cpu : expect B to be
uint8 tensor). Restore the checkpoint snapshot on any device change and
let the next forward re-transform; a same-device move to FP32 still keeps
the live layout because it only widens the offsets.

- Share one decision helper for the four CPU fused/ATen classes instead of
  four copies of the dtype-only check.
- Report the finalized activation dtype, not the widened scales dtype, in
  the ATen fused dtype-mismatch error.
- Cover all four classes in the low-precision move test and add a
  device-move test; refresh the docs page flow.

@ZX-ModelCloud ZX-ModelCloud left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 745aa4468. One blocking issue remained in the move path, now fixed:

  • Cross-device moves reinterpreted the runtime layout. _apply only re-finalized on a low-precision dtype change, but the int4pack qweight is device-specific: the CPU _convert_weight_to_int4pack_for_cpu packing is not the XPU packing. A transformed layer moved between devices kept the live buffers, so the next CPU forward received an int32 XPU tensor and raised _weight_int4pack_mm_cpu : expect B to be uint8 tensor. A move now restores the checkpoint snapshot whenever the device changes; a same-device FP32 move still keeps the live layout because it only widens the offsets.

Also folded the four copies of the move decision into one helper, fixed the ATen dtype-mismatch error to report the finalized activation dtype instead of the widened scales dtype, and extended the move tests to all four CPU fused/ATen classes plus a device-move case. The docs page and the PR description now match the shipped flow.

Validation: 405 passed / 1 skipped (focused CPU + AWQ suites), 234 passed / 34 skipped (fusion). The same suites pass in the ROCm runtime; the two pre-existing test_awq_gemm_validation_* / test_machete_validation_* ROCm failures reproduce on untouched origin/main.

@Qubitium
Qubitium marked this pull request as ready for review November 11, 2026 14:29
@Qubitium
Qubitium merged commit 1283671 into main Nov 11, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/clear-weight-cache-restore branch November 11, 2026 14:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants