Skip to content

fix(cpu): keep fused AVX512 layers on concatenated int4pack operands - #3762

Merged
Qubitium merged 1 commit into
mainfrom
fix/cpu-avx512-fused-int4pack
Nov 11, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/cpu-avx512-fused-int4pack

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Fixes a CPU-only failure in the fused int4pack executor. Fusing two or more
TorchCpuAvx512Linear projections raised

RuntimeError: split_with_sizes expects split_sizes to sum exactly to 64
(input tensor's size at dimension 0), but got split_sizes=[1024, 1024]

before the layer ever ran a forward. This reproduces on clean main at
be3852b for the gate_up, qkv_mha and qkv_gqa CPU profiles.

No CUDA, ROCm, XPU or NPU code path is touched.

What Changed

  • gptqmodel/models/fusion_kernels.py: combine() now discards the inherited
    _fused_train_state for cpu_avx512, and only concatenates
    scales_and_zeros for the layouts that actually own that operand.
  • gptqmodel/models/fusion.py: _share_operands() extends the existing
    suppress_restore flag to cpu_avx512.
  • tests/module_tree/test_fusion_kernel_backends.py: adds
    test_avx512_fusion_does_not_restore_source_checkpoint_state.

Out of scope: no change to how snapshots are captured, to the training-restore
contract, or to any non-CPU layout.

Root cause

FusionKernelSpec.combine() builds the fused shell with copy.copy(first), so
it inherits the sources' _fused_train_state snapshot. That snapshot is the
pre-transform GPTQ-v2 state:

Operand Snapshot (GPTQ-v2) Live int4pack
qweight (in_features / 8, out_features) → (64, 1024) (out_features, in_features / 2) → (1024, 256)
qzeros (groups, out_features) → (4, 1024) (groups, out_features) → (4, 1024)

combine() correctly concatenates the live int4pack tensors, then calls
clear_weight_cache() → restore_fused_train_state(), which consumes the
inherited snapshot and writes the stale GPTQ-v2 tensors back
over them.
_share_operands() then tried to split a 64-row fused weight into two
1024-row views.

Both existing guards — discard_fused_train_state(fused) and
suppress_restore — listed cpu_aten and cpu_legacy but omitted
cpu_avx512, even though that layout captures its snapshot from the same
TorchAtenLinear base.

A second, latent defect sat behind the first: the concatenation block assumed
scales_and_zeros exists. cpu_avx512 has no such operand — it passes separate
zeros and scales matrices into gemm_int4_qzero_group_scaled_cpu_kernel, and
FusionKernelSpec.extra_tensors records no such name. Widening the layout test
without guarding it would have raised AttributeError instead.

flowchart TD
    A["combine(): copy.copy(first)"] --> B["inherits _fused_train_state<br/>GPTQ-v2 (64, 1024)"]
    B --> C["torch.cat live int4pack<br/>(2048, 256) — correct"]
    C --> D["clear_weight_cache()"]
    D --> E["restore_fused_train_state()"]
    E -->|before| F["stale (64, 1024) restored"]:::fail
    E -->|after| G["snapshot discarded,<br/>int4pack preserved"]:::ok
    F --> H["_share_operands split<br/>1024 + 1024 != 64"]:::fail
    G --> I["split into (1024, 256) views"]:::ok
    classDef fail fill:#fee2e2,stroke:#b91c1c,color:#7f1d1d;
    classDef ok fill:#dcfce7,stroke:#15803d,color:#14532d;
Loading

Tests

  • Unit tests have been executed and passed.
  • Added a new focused regression test.

Exact command and result:

python -m pytest -q tests/module_tree/test_fusion_kernel_backends.py
# 55 passed, 127 skipped in 58.39s

The new test asserts that the fused layer owns the combined int4pack
allocations, that no _fused_train_state is inherited, and that every source
operand aliases the fused storage (untyped_storage().data_ptr()). It fails
without the fix and passes with it
— verified by stashing the two source
changes and re-running.

Baseline against clean be3852b: the three CPU cases below fail, and pass with
the fix.

python -m pytest -q \
  "tests/module_tree/test_fusion_kernel_backends.py::test_native_fusion_shapes_oracle_ownership_and_invalidation[gate_up-cpu-TorchCpuAvx512Linear-torch.bfloat16]" \
  "tests/module_tree/test_fusion_kernel_backends.py::test_native_fusion_shapes_oracle_ownership_and_invalidation[qkv_mha-cpu-TorchCpuAvx512Linear-torch.bfloat16]" \
  "tests/module_tree/test_fusion_kernel_backends.py::test_native_fusion_shapes_oracle_ownership_and_invalidation[qkv_gqa-cpu-TorchCpuAvx512Linear-torch.bfloat16]"
# before: 3 failed | after: 3 passed

Wider module-tree sweep, to show other layouts are unaffected:

python -m pytest -q tests/module_tree -k "fusion or train"
# 240 passed, 633 skipped, 1291 deselected
ruff check gptqmodel/models/fusion.py gptqmodel/models/fusion_kernels.py \
  tests/module_tree/test_fusion_kernel_backends.py
# All checks passed!
git diff --check
# clean

Skips are optional-dependency and non-CPU architecture exclusions, not
validation of this path.

Model Support / Module Plan

Not applicable: no model definition, MODEL_MAP entry, alias, or module-plan
consumer changes.

Logic Flow Documentation

  • This change alters the tensor-restore lifecycle for the cpu_avx512
    fusion layout.
  • The Mermaid diagram above uses the shipped symbol names
    (combine, clear_weight_cache, restore_fused_train_state,
    _share_operands).
  • The replaced mechanism is tabulated with the stale/live operand shapes.
  • The failure path is visually distinct from the success path.
  • No separate docs/ reference page: this restores an intended invariant
    rather than introducing a new mechanism, and the contract is documented in
    the _fused_train_state module docstring and in the new test.

Review Requirements

  • Reviewed this PR.
  • Matches existing project structure, APIs, and conventions — reuses the
    existing discard_fused_train_state and suppress_restore mechanisms.
  • Avoided monkeypatching; no new extension point.
  • Minimized the diff: 3 changed lines plus one test.
  • Considered regressions: full kernel matrix re-run, other layouts unchanged.

Kernel Accuracy Requirements

  • Accuracy drift measured against an independent Torch oracle — the
    existing test compares the fused output to torch.cat([m(x) for m in modules], -1)
    and to a separate FP32 dequantize/matmul oracle at rtol=atol=2e-3. It
    now passes instead of aborting.
  • No fusion backend or dtype support added, so the FP16/BF16 addition
    checklist does not apply.
  • No skips were counted as validation of this path.

Notes

Found while validating an unrelated Tenstorrent backend branch; split out at
request so it can land on its own. This defect exists on main and is not
introduced by any pending PR.

`FusionKernelSpec.combine()` builds the fused shell with `copy.copy(first)`, so
it inherits the sources' `_fused_train_state` snapshot. That snapshot holds the
pre-transform GPTQ-v2 `qweight` `(in_features / 8, out_features)` and `qzeros`
`(groups, out_features)` tensors that `transform_cpu()` replaced with int4pack
storage.

`clear_weight_cache()` calls `restore_fused_train_state()`, which consumes the
snapshot and writes those stale shapes back over the correctly concatenated
int4pack tensors. `_share_operands()` then saw a `(64, 1024)` fused weight where
the sources expected `(1024, 256)` slices and raised

    RuntimeError: split_with_sizes expects split_sizes to sum exactly to 64
    (input tensor's size at dimension 0), but got split_sizes=[1024, 1024]

The `discard_fused_train_state()` guard and the `suppress_restore` flag both
covered `cpu_aten` and `cpu_legacy` but omitted `cpu_avx512`, even though that
layout captures its snapshot from the same `TorchAtenLinear` base. Add it to
both.

`cpu_avx512` has no `scales_and_zeros` operand of its own: it hands separate
`zeros` and `scales` matrices to `gemm_int4_qzero_group_scaled_cpu_kernel`, and
`extra_tensors` records no such name. Guard the concatenation accordingly so
the wider `layout` test cannot build a missing tensor.

Reproduced on clean base be3852b: gate_up, qkv_mha and qkv_gqa CPU cases all
fail. With the fix the focused suite is 55 passed / 127 skipped, and the rest
of the matrix (cpu_aten, rdisp, exllamav2, marlin, AWQ, int8, allspark) is
unchanged.
@Qubitium
Qubitium merged commit f2b14e4 into main Nov 11, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/cpu-avx512-fused-int4pack branch November 11, 2026 01:33
Qubitium added a commit that referenced this pull request Nov 11, 2026
…on (#3765)

* fix(cpu): keep checkpoint layout across inference transforms and fusion

A CPU W4A16 inference forward rewrites `qweight`/`qzeros`/`scales` in place
into the kernel's int4pack runtime layout, and the AVX512 pair also widen
`bias` to FP32. The checkpoint values survived only in the
`_fused_train_state` snapshot, so every save path serialized runtime shapes
under checkpoint keys. The written file could not be loaded into a fresh
model, and `load_state_dict()` into an already-transformed model failed with
a size mismatch. A plain forward triggered it even with fusion disabled, and
`torch_cpu_avx512_awq` never captured a snapshot at all, so its layout was
unrecoverable after one forward. Reproduced on clean base be3852b, so this
predates #3762/#3763.

- `capture_fused_train_state()` now takes an explicit operand list and clones
  outside `inference_mode`; an inference-mode clone cannot be restored as a
  buffer that `load_state_dict` later copies into.
- `_load_from_state_dict()` restores the snapshot first, but only when the
  incoming tensors match the checkpoint shapes; a model's own runtime
  `state_dict()` keeps round-tripping unchanged.
- `get_state_dict_for_save()` restores every transformed module before it
  collects tensors, which covers `save()` and the writer paths.
- `TorchCpuAvx512AwqLinear` captures and restores its snapshot, and both
  AVX512 classes include the widened `bias` in the captured set.
- `FusionKernelSpec.prepare()` captures the snapshot before it finalizes a
  source for a fused group. Fusion had bypassed the forward-time capture, so
  a fused model exported int4pack shapes and `fuse(False)` had nothing to
  restore.
- `_FusionGroup.remove()` skips a CPU runtime rebind once an export restored
  checkpoint operands; rebuilding `scales_and_zeros` from GPTQ codes produced
  mismatched shapes and infinities.

Snapshot buffers are non-persistent and never appear in `state_dict()`.

Verified on AVX512-BF16 CPU with torch 2.15.0: the 6-layout checkpoint matrix
and the 6-class fused round trip (save -> fresh strict load -> forward) all
match pristine shapes and baseline numerics; the 12-layout fusion sweep stays
exact at err=0. New regression tests cover both paths. Suites:
tests/test_kernel_audit_regressions.py + tests/test_qqq_cpu.py 79 passed;
AVX512/AWQ/INT8/writer/offload 243 passed, 3 skipped; module_tree fusion,
fusable and module_plan 728 passed, 633 skipped.

* docs(kernels): document checkpoint-layout restoration on save and load

* docs(fusion): note the CPU checkpoint snapshot taken before finalizing
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.

1 participant