Repository navigation
fix(cpu): keep activation gradients in compiled fused forwards (#5369) - #5499
Merged
Merged
Conversation
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.
ZX-ModelCloud
force-pushed
the
fix/issue-5369-compiled-grad
branch
from
November 19, 2026 08:27
ac759c2 to
909f563
Compare
ZX-ModelCloud
marked this pull request as ready for review
November 19, 2026 08:28
This was referenced Nov 19, 2026
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
torch.compile(fullgraph=True)on a warmed CPU int4pack GPTQ/AWQ layer took the inference branch and called the@torch.no_gradfused 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_codesaccepts a verified block size; newruntime_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 itstorch.Generator) inside a graph.TorchFusedLinear,TorchAtenLinear,TorchFusedAwqLinear,TorchAtenAwqLinear: when compiling, take the runtime dense fallback only whenfused_autograd_needs_denseis true on CPU; preserve the existing fused inference path and the eager restore path.desc_actactivations withret_idxexactly like the fused op; biased layers reusematmul_fp32_reduce.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"]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"]Before / after
grad_fngrad_fnlinear_modeand packed buffers are unchangedFile pointers:
gptqmodel/nn_modules/qlinear/torch_fused.py:661-725gptqmodel/nn_modules/qlinear/torch_aten_kernel.py:495-573gptqmodel/nn_modules/qlinear/torch_fused_awq.py:461-530gptqmodel/nn_modules/qlinear/torch_aten_kernel_awq.py:382-447gptqmodel/nn_modules/qlinear/_cpu_int4pack_layout.py:111-205gptqmodel/nn_modules/qlinear/_fused_train_state.py:243-255Tests
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_gradfor all four kernels, and the issue reproduction printedrequires_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:
TorchFP8Linearis load-only,GGUFCppKernelhas 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) andtests/test_q4_torch_fused.py::TestsTorchFused::test_torch_fused(quantize_configapplied 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
docs/cpu-int4pack-compiled-grad.md.file:lineevidence.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
Kernel Accuracy Requirements
dequantize_weight/dequantize_gemm), not the runtime decode under test.Measured maximum absolute gradient drift over five random trials:
7.3e-3for GPTQ and1.4e-2for AWQ. The visible path is BF16 and the reference is float32, so the regression uses the same2e-2tolerance 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 drift5.8e-3(GPTQ) and1.2e-2(AWQ).Notes