Skip to content

fix(cpu): keep gradients on a grad forward after a fused eval forward (#5314) - #5321

Merged
Qubitium merged 1 commit into
mainfrom
fix/cpu-trainable-grad-latch-5314
Nov 19, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/cpu-trainable-grad-latch-5314

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Fixes #5314.

The CPU int4pack kernels chose fused-vs-dense once, on the first forward, and
latched linear_mode=inference after any no_grad/inference_mode call. Every
later eval-mode forward then took the @torch.no_grad fused op, even when grad
was enabled and x.requires_grad was true. The output was silently detached:
LoRA params behind a quantized o_proj/down_proj got grad=None, and the
rest had wrong gradients, with no error.

The decision is now per call: if the fused inference layout is latched and the
call needs a gradient, the module restores the checkpoint layout with
restore_fused_train_state() and takes the differentiable dequant path. The
next inference forward transforms again.

Affected GPTQ kernels: TorchFusedLinear, TorchAtenLinear,
TorchCpuAvx512Linear (inherits the ATen forward).
Affected AWQ kernels: TorchFusedAwqLinear, TorchAtenAwqLinear,
TorchCpuAvx512AwqLinear.

What Changed

  • gptqmodel/nn_modules/qlinear/_fused_train_state.py: new
    fused_autograd_needs_dense(module, x) helper. True only when grad is enabled,
    x.requires_grad, and linear_mode is the fused inference state.
  • Each affected forward: compute force_dense under the existing transform
    lock, restore the checkpoint layout before the dense call, and skip the
    one-time inference latch for that call. If the checkpoint layout cannot be
    restored (no snapshot / suspended export), raise instead of returning a
    detached tensor.
  • tests/test_cpu_trainable_kernels_grad_after_inference_5314.py: for each
    kernel, run one inference_mode forward (which latches the fused path), then
    a grad-mode forward with requires_grad=True. Assert the output has a
    grad_fn, x.grad is not None, and x.grad == grad_out @ W.T from the
    dequantized weight. Also assert a later inference forward still works.

GGUFCppKernel is unchanged: it declares SUPPORTS_TRAINING = False, so it
does not promise gradients.

Tests

PYTHONPATH=$PWD GPTQ_BYPASS_SAFETY_CHECKS=1 \
  /root/gptqmodel-test-venv/bin/python -m pytest \
  tests/test_cpu_trainable_kernels_grad_after_inference_5314.py -q
# 4 passed, 2 skipped (AVX512 requires x86 AVX512-BF16; this host is aarch64)

PYTHONPATH=$PWD GPTQ_BYPASS_SAFETY_CHECKS=1 \
  /root/gptqmodel-test-venv/bin/python -m pytest \
  tests/test_torch_cpu_avx512.py tests/test_torch_fused_asym_qzeros.py \
  tests/test_cpu_kernel_optimize.py tests/test_torch_cpu_avx512_awq.py \
  tests/test_ret_idx_group_order.py -q
# 47 passed, 70 skipped
# 2 pre-existing failures in test_cpu_feature_detection_requires_{vbmi,xsave}
# (`cpu_features` function has no cache_clear); they fail identically on the
# parent commit.

ruff check <changed files>
# All checks passed!

The four runnable kernel cases fail on the parent commit (out.requires_grad
is false); they pass with the fix. The AVX512 cases skip here and will run on
the x86 CI runner.

Model Support / Module Plan

Not applicable: no model, alias, or module-plan change.

Logic Flow Documentation

The change adds one decision inside each existing forward:

flowchart TD
    A[forward x] --> B{fused inference latched?}
    B -- no --> C[existing first-call selection]
    B -- yes --> D{grad enabled and x.requires_grad?}
    D -- no --> E[fused no_grad op]
    D -- yes --> F[restore_fused_train_state]
    F --> G[dense dequant matmul]
    G --> H[next inference forward re-transforms]
Loading

No public control flow or ownership changes.

Kernel Accuracy Requirements

Not applicable: the fused kernel math is unchanged. The new test compares the
dense-path gradient with grad_out @ W.T from the dequantized weight.

Notes

Restoring and re-transforming when a process alternates inference and gradient
calls costs one pack/unpack per switch. A pure training loop stays on the dense
path after the first restore; a pure inference loop keeps the fused path.

…#5314)

The CPU int4pack kernels latch linear_mode=inference on the first no_grad forward and then keep using the @torch.no_grad fused op, so later eval-mode grad forwards returned detached outputs. Check torch.is_grad_enabled() and x.requires_grad per call; when the fused layout is latched, restore the checkpoint layout and use the differentiable dequant path for that call. The next inference forward transforms again.
@Qubitium
Qubitium marked this pull request as ready for review November 19, 2026 01:18
@Qubitium
Qubitium merged commit 35d97a7 into main Nov 19, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/cpu-trainable-grad-latch-5314 branch November 19, 2026 01:19
Qubitium added a commit that referenced this pull request Nov 19, 2026
… dense (#5392) (#5447)

The CPU int4pack kernels (`TorchFusedLinear`/`TorchFusedAwqLinear`,
`TorchAtenLinear`/`TorchAtenAwqLinear`, `TorchCpuAvx512Linear`/
`TorchCpuAvx512AwqLinear`) latch `linear_mode="train"` when a forward runs with
`linear_mode is None`. After #5321, the first eval-mode grad forward restores
the checkpoint layout and leaves `linear_mode=None`; the second grad forward
then took that branch and pinned the module to the dense-dequant path for good.
`model.eval()` returns early (`mode == old_train`), so only `train(); eval()`
recovered, and later inference dequantized the whole weight on every call
(measured 8-15x per layer, ~90x end to end).

Only latch the dense path in training mode. An eval-mode grad forward takes the
dense path for that call only, so the next no-grad forward transforms again.

Also fix the GGUF CPU sibling the issue lists: `GGUFCppKernel` returned a
detached tensor for `x.requires_grad` because the native ggml matmul has no
autograd support. A grad-mode forward now takes the exact torch path for that
call (same math as `GGUFTorchLinear`); inference forwards keep the native
kernel.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant