Repository navigation
fix(cpu): keep fused AVX512 layers on concatenated int4pack operands - #3762
Merged
Merged
Conversation
`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.
This was referenced Nov 10, 2026
This was referenced Nov 11, 2026
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
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 a CPU-only failure in the fused int4pack executor. Fusing two or more
TorchCpuAvx512Linearprojections raisedbefore the layer ever ran a forward. This reproduces on clean
mainatbe3852bfor 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_stateforcpu_avx512, and only concatenatesscales_and_zerosfor the layouts that actually own that operand.gptqmodel/models/fusion.py:_share_operands()extends the existingsuppress_restoreflag tocpu_avx512.tests/module_tree/test_fusion_kernel_backends.py: addstest_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 withcopy.copy(first), soit inherits the sources'
_fused_train_statesnapshot. That snapshot is thepre-transform GPTQ-v2 state:
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 callsclear_weight_cache()→restore_fused_train_state(), which consumes theinherited snapshot and writes the stale GPTQ-v2 tensors back over them.
_share_operands()then tried to split a 64-row fused weight into two1024-row views.
Both existing guards —
discard_fused_train_state(fused)andsuppress_restore— listedcpu_atenandcpu_legacybut omittedcpu_avx512, even though that layout captures its snapshot from the sameTorchAtenLinearbase.A second, latent defect sat behind the first: the concatenation block assumed
scales_and_zerosexists.cpu_avx512has no such operand — it passes separatezerosandscalesmatrices intogemm_int4_qzero_group_scaled_cpu_kernel, andFusionKernelSpec.extra_tensorsrecords no such name. Widening the layout testwithout guarding it would have raised
AttributeErrorinstead.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;Tests
Exact command and result:
python -m pytest -q tests/module_tree/test_fusion_kernel_backends.py # 55 passed, 127 skipped in 58.39sThe new test asserts that the fused layer owns the combined int4pack
allocations, that no
_fused_train_stateis inherited, and that every sourceoperand aliases the fused storage (
untyped_storage().data_ptr()). It failswithout 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 withthe fix.
Wider module-tree sweep, to show other layouts are unaffected:
Skips are optional-dependency and non-CPU architecture exclusions, not
validation of this path.
Model Support / Module Plan
Not applicable: no model definition,
MODEL_MAPentry, alias, or module-planconsumer changes.
Logic Flow Documentation
cpu_avx512fusion layout.
(
combine,clear_weight_cache,restore_fused_train_state,_share_operands).docs/reference page: this restores an intended invariantrather than introducing a new mechanism, and the contract is documented in
the
_fused_train_statemodule docstring and in the new test.Review Requirements
existing
discard_fused_train_stateandsuppress_restoremechanisms.Kernel Accuracy Requirements
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. Itnow passes instead of aborting.
checklist does not apply.
Notes
Found while validating an unrelated Tenstorrent backend branch; split out at
request so it can land on its own. This defect exists on
mainand is notintroduced by any pending PR.