Skip to content

fix(awq): keep FP32 affine operands across CPU AVX512 dtype moves - #3763

Merged
Qubitium merged 2 commits into
mainfrom
fix/awq-avx512-fused-affine-abi
Nov 11, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/awq-avx512-fused-affine-abi

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Problem

TorchCpuAvx512AwqLinear.transform_cpu() packs the weight once and promotes scales/bias to FP32, because the shared AVX512-BF16 kernel (gemm_int4_qzero_group_scaled_cpu_kernel) requires an FP32 absmax and accumulates in FP32.

Both are registered buffers, so nn.Module._apply() casts them too. A plain model.float(), .half() or .to(dtype) therefore left a non-FP32 absmax and the next forward raised:

RuntimeError: absmax must be float32

The class also had no clear_weight_cache at all — the only CPU quantization kernel in the tree without one — so _load_from_state_dict and _apply had no hook to call.

Why restoring the dtype is not enough

BF16 keeps 8 explicit mantissa bits against the checkpoint's 10, so casting scales through BF16 during _apply discards precision permanently. Restoring the dtype afterwards still drifted the output by 0.0625 against the pre-move result. The exact tensors have to survive the move.

Fix

  • Override _apply() to hold the exact FP32 scales/bias across super()._apply() and reinstall them at the resulting device. Packed integer codes are untouched and never repacked.
  • Add clear_weight_cache() for the load / explicit-clear paths that bypass _apply.

Scales and zero points are quantization metadata rather than an expanded weight, so retaining them is within the repo's persistent-storage rule.

This matters more since fusion began installing on cpu_avx512 AWQ layers: the fused shell runs the same kernel, so a dtype move broke fused models too.

Scope

Both defects predate this change and reproduce on base be3852b with no fusion involved. This is independent of #3762 (that PR correctly keeps cpu_avx512 fused layers on concatenated int4pack operands); this one is the affine-dtype ABI underneath it.

Tests

New test_fused_layer_keeps_fp32_affine_abi_across_dtype_moves (parameterized over to(dtype) / .float() / .half()):

  • compares each post-move forward against an independent affine oracle and against the pre-move baseline
  • asserts the packed codes are not repacked (_cpu_transformed stays set)
  • fails 3/3 against the pre-fix source (verified by stashing only the source change) and passes after it

Suites: 87 passed across tests/test_torch_cpu_avx512{,_awq}.py; 55 passed, 127 skipped in tests/module_tree/test_fusion_kernel_backends.py; ruff and git diff --check clean.

I also swept every CPU fusion layout (cpu_aten, cpu_avx512, cpu_legacy, int8) under dtype moves and train-mode toggles: all now match the pre-move baseline exactly (0.0 max abs drift).

`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.
`TorchCpuAvx512AwqLinear.transform_cpu()` packs the weight once and promotes
`scales`/`bias` to FP32 because the shared AVX512 kernel requires an FP32
`absmax` operand and accumulates in FP32. Both values are registered buffers,
so `nn.Module._apply()` applied the requested cast to them as well: a plain
`model.float()`, `.half()` or `.to(dtype)` rounded the affine metadata through
BF16 and then the next forward raised

    RuntimeError: absmax must be float32

Adding the missing hook alone was not enough. BF16 keeps 8 explicit mantissa
bits against the checkpoint's 10, so the round trip discarded scale precision
permanently: restoring the dtype after `_apply` still drifted the output by
0.0625 against the pre-move result. The class had no `clear_weight_cache` at
all, making it the only CPU quantization kernel in the tree without one, so
`_load_from_state_dict` and `_apply` had nothing to call.

Hold the exact FP32 tensors across `super()._apply()` and reinstall them at the
resulting device, keeping the packed integer codes untouched (nothing is
repacked, and scales/zero points are quantization metadata rather than an
expanded weight). Add `clear_weight_cache()` for the load and explicit-clear
paths that bypass `_apply`. This matters more since fusion began installing on
`cpu_avx512` AWQ layers: the fused shell runs the same kernel, so a dtype move
broke fused models as well.

Both defects predate this change and reproduce on base be3852b, where the AWQ
path raised the same error with no fusion involved.

Tests: new `test_fused_layer_keeps_fp32_affine_abi_across_dtype_moves` fails
three-of-three against the pre-fix source (measured by stashing only the
source change) and passes after it; it compares each post-move forward against
an independent affine oracle and against the pre-move baseline, and asserts the
packed codes are not repacked. 87 passed across
tests/test_torch_cpu_avx512{,_awq}.py, 55 passed / 127 skipped in
tests/module_tree/test_fusion_kernel_backends.py, ruff clean.
@Qubitium
Qubitium merged commit d38f892 into main Nov 11, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/awq-avx512-fused-affine-abi 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