Skip to content

fix(cpu): keep activation gradients in compiled fused forwards (#5369) - #5499

Merged
Qubitium merged 4 commits into
mainfrom
fix/issue-5369-compiled-grad
Nov 19, 2026
Merged

Qubitium merged 4 commits into
mainfrom
fix/issue-5369-compiled-grad

Conversation

@ZX-ModelCloud

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

Copy link
Copy Markdown
Collaborator

Summary

torch.compile(fullgraph=True) on a warmed CPU int4pack GPTQ/AWQ layer took the inference branch and called the @torch.no_grad fused op, so a grad-requiring call returned a detached tensor. The eager path restored the checkpoint layout, but doing that inside a trace would mutate packed buffers.

This PR decodes the live runtime int4pack operands with the same affine identity the fused op uses and takes the dense matmul path for grad-requiring compiled calls. The decode is derived from the module's live buffers; no dense weight is stored or cached.

Fixes #5369

What Changed

  • gptqmodel/nn_modules/qlinear/_cpu_int4pack_layout.py: int4pack_to_codes accepts a verified block size; new runtime_int4pack_dense_weight(module) decodes the runtime layout to a temporary [in, out] weight.
  • gptqmodel/nn_modules/qlinear/_fused_train_state.py: cache the verified int4pack block size during the eager transform so dynamo never runs the layout probe (and its torch.Generator) inside a graph.
  • TorchFusedLinear, TorchAtenLinear, TorchFusedAwqLinear, TorchAtenAwqLinear: when compiling, take the runtime dense fallback only when fused_autograd_needs_dense is true on CPU; preserve the existing fused inference path and the eager restore path.
  • The GPTQ fallback gathers desc_act activations with ret_idx exactly like the fused op; biased layers reuse matmul_fp32_reduce.
  • Out of scope: non-CPU devices keep their existing behavior; no model definitions, aliases, AWQ grouping/search/replay/fold, or serialization changed.

Old compiled forward flow

flowchart TD
    A["compiled forward"] --> B["read linear_mode"]
    B --> C{"linear_mode == inference?"}
    C -->|yes| D["_fused_op_forward<br/>@torch.no_grad"]
    D --> E["detached output"]
    C -->|no| F["dequantize checkpoint layout<br/>matmul"]
Loading

New compiled forward flow

flowchart TD
    A["compiled forward"] --> B["read linear_mode"]
    B --> C{"grad needed on CPU<br/>and mode == inference?"}
    C -->|yes| D["runtime_int4pack_dense_weight<br/>decode live qweight/scales/qzeros"]
    D --> E["optional ret_idx gather<br/>matmul or matmul_fp32_reduce"]
    E --> F["differentiable output<br/>runtime buffers unchanged"]
    C -->|no| G{"linear_mode == inference?"}
    G -->|yes| H["_fused_op_forward<br/>@torch.no_grad"]
    G -->|no| I["dequantize checkpoint layout<br/>matmul"]
Loading

Before / after

Area Before After
Compiled grad call after an inference warmup Took the fused no-grad branch; the output had no grad_fn Takes the runtime dense fallback; the output keeps grad_fn
Runtime layout after the call n/a linear_mode and packed buffers are unchanged
Dense weight lifetime n/a Local to the call; released after the matmul
Eager grad call Restores the checkpoint layout (#5314, #5392) Unchanged
Non-CPU devices Existing fused inference branch Unchanged

File pointers:

  • gptqmodel/nn_modules/qlinear/torch_fused.py:661-725
  • gptqmodel/nn_modules/qlinear/torch_aten_kernel.py:495-573
  • gptqmodel/nn_modules/qlinear/torch_fused_awq.py:461-530
  • gptqmodel/nn_modules/qlinear/torch_aten_kernel_awq.py:382-447
  • gptqmodel/nn_modules/qlinear/_cpu_int4pack_layout.py:111-205
  • gptqmodel/nn_modules/qlinear/_fused_train_state.py:243-255

Tests

  • Unit tests have been executed and passed.
  • I added new simple/fast unit tests for this change.
python -m pytest tests/test_cpu_fused_compiled_grad_5369.py -q -rs
# 20 passed

python -m pytest tests/test_cpu_fused_compiled_grad_5369.py \
  tests/test_cpu_trainable_kernels_grad_after_inference_5314.py \
  tests/test_cpu_fused_eval_grad_latch_5392.py -q -rs
# 35 passed

python -m pytest \
  tests/kernels/test_awq_cpu_fused_post_init.py \
  tests/kernels/test_cpu_fp32_fused_numerics.py \
  tests/kernels/test_gptq_torch_cpu_bias_epilogue.py \
  tests/kernels/test_cpu_awq_int4_mmap_detach_4785.py \
  tests/kernels/test_cpu_int4_mmap_detach_4785.py \
  tests/kernels/test_kernel_compile_levels_cpu.py -q -rs
# 68 passed, 3 skipped

./format/check.sh
# ruff 0.14.2; All checks passed

Compile test files also pass individually: test_compiled_forward_no_retrace_5266.py (2), test_compile_fallback_no_replay_5119.py (5), test_compile_nested_suppression_5224.py (6), test_compile_lock_scope_5268.py (4), test_torch_compile_fallback.py (18), test_generation_compile_policy_4669.py (17).

Red evidence before the fix: the new regression failed at assert out.requires_grad for all four kernels, and the issue reproduction printed requires_grad: False. After the fix, the issue fixture returns the expected scalar gradient -8.0.

The three skips are environment/format limits, not this change: TorchFP8Linear is load-only, GGUFCppKernel has no CPU builder on this host, and the Paro biased layer is served by the AVX512-BF16 kernel.

Unrelated failures reproduced on unmodified origin/main: tests/test_cpu_int4_verify_cost_4884.py::test_transformed_state_dict_is_bounded_by_its_own_bytes[desc_act] (host timing bound) and tests/test_q4_torch_fused.py::TestsTorchFused::test_torch_fused (quantize_config applied to a quantized checkpoint).

Model Support / Module Plan

Not applicable: no new model type, alias, definition, module plan, or fusion eligibility changed.

AWQ onboarding safety

Not applicable: no new model/alias and no AWQ grouping, search, replay, or folding change. The AWQ kernel forward only gains the compiled gradient fallback.

Logic Flow Documentation

  • The old/new compiled-forward diagrams are included above and in docs/cpu-int4pack-compiled-grad.md.
  • New-flow Mermaid diagrams use shipped symbol names.
  • The removed/replaced mechanism is shown with file:line evidence.
  • Failure and ambiguity paths are marked.
  • The reference page is linked from README.md.

The fallback is selected only while torch.compiler.is_compiling() is true, the call needs an activation gradient, the device is CPU, and the module is already latched to the inference layout. The decoded weight is a local [in, out] temporary consumed by the matmul; it is not stored on the module, in a buffer, in a cache, or as a compiled graph constant.

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.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

  • Accuracy drift measured against an independent float32 checkpoint-layout oracle (dequantize_weight/dequantize_gemm), not the runtime decode under test.
  • Fusion support changes: not applicable.
  • Complete kernel inventory/device report: the affected CPU kernels already declare their compile levels; the three environment/format skips are listed above.

Measured maximum absolute gradient drift over five random trials: 7.3e-3 for GPTQ and 1.4e-2 for AWQ. The visible path is BF16 and the reference is float32, so the regression uses the same 2e-2 tolerance as the existing CPU fused gradient family. The issue fixture is exact: -8.0. An Inductor check (not only the eager compiler backend) also kept the gradient, with maximum drift 5.8e-3 (GPTQ) and 1.2e-2 (AWQ).

Notes

  • CPU-only scope. Non-CPU devices keep the existing behavior and are not claimed as validated by this PR.

The CPU int4pack compile branches read the warmed inference latch and
always called the @torch.no_grad fused op, so a grad-requiring
torch.compile(fullgraph=True) call returned a detached tensor. The eager
path restored the checkpoint layout, but doing that inside a traced graph
would mutate packed buffers.

Decode the live runtime int4pack operands with the same affine identity
the fused op uses and take the dense matmul path for grad-requiring
compiled calls. Cache the verified block size during the eager transform
so dynamo never re-enters the layout probe. Apply the same fallback to
TorchFusedLinear, TorchAtenLinear, TorchFusedAwqLinear and
TorchAtenAwqLinear, including desc_act activation gathers and bias
epilogues.

Regression: tests/test_cpu_fused_compiled_grad_5369.py compares compiled
and eager gradients, bias, desc_act and the issue fixture.
Cover the runtime layout staying intact after a compiled grad forward and
assert that no dense [in, out] weight is retained on the module.
Add the old/new compiled-forward diagrams, the before/after table, the
failure contract and the regression coverage. Link the mechanism page
from the CPU inference section.
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.

[BUG] Compiled CPU fused GPTQ and AWQ forwards drop activation gradients after warmup

2 participants