Skip to content

[BUG] CPU trainable kernels (TorchCpuAvx512/TorchFused/TorchAten, GPTQ+AWQ; AUTO and AUTO_TRAINABLE) latch the @no_grad int4pack path after one eval forward: later eval-mode grad forwards are silently detached (LoRA: 96/144 params get no grad, rest rel err 1.6) #5314

Closed

Description

@Qubitium

Found on main @ c03416c, CPU (x86 AVX512), Qwen2.5-0.5B-Instruct GPTQ/AWQ 4-bit g128, bf16.

What is wrong

The trainable CPU kernels pick their path once, on the first forward, and then keep it ("latch"):

  • TorchFusedLinear.forward (nn_modules/qlinear/torch_fused.py:668-683, also used by TorchFusedAwqLinear)
  • TorchAtenLinear.forward (torch_aten_kernel.py:503-525, also TorchAtenAwqLinear)
  • TorchCpuAvx512Linear / TorchCpuAvx512AwqLinear (torch_cpu_avx512.py, linear_mode reset only in train() at :254)
if not self.training and not x.requires_grad and self.linear_mode is None ...:
    self.transform(...); self.linear_mode = LinearMode.INFERENCE      # latched
...
if linear_mode == LinearMode.INFERENCE:
    out = self._fused_op_forward(x)        # @torch.no_grad -> output has no grad_fn

The first forward in eval mode under no_grad / inference_mode (a generate(), a sanity check, a validation pass) latches INFERENCE. Every later forward in eval mode then takes the @torch.no_grad int4pack path, even when grad is enabled and x.requires_grad. The layer's output is silently detached. No error is raised, and the only thing that clears the latch is a train(True) toggle.

All of these declare SUPPORTS_TRAINING = True, and AUTO / AUTO_TRAINABLE select TorchCpuAvx512Linear on CPU. TorchLinear (GPTQ_TORCH) does not latch and gives correct gradients in the same scenario.

#4072 item 4 relied on "the GPTQ fused gate falls back when x.requires_grad". It does, but only on the module's first call. The #5197/#5238 audit concluded these kernels were safe because they "are read by @torch.no_grad forwards". That no_grad is exactly what drops the gradient.

Failure scenario

Any gradient taken in eval mode after one no-grad forward:

  • LoRA/PEFT in a custom loop that never calls .train() (GPTQModel.load returns an eval model, and get_peft_model does not switch modes), or that keeps eval() to disable dropout, after a quick generate() check.
  • Input attribution or saliency, adversarial or soft-prompt optimization on inputs_embeds after a generate().

Repro

import torch
from gptqmodel import GPTQModel, BACKEND
from peft import LoraConfig, get_peft_model

m = GPTQModel.load(GPTQ_CKPT, backend=BACKEND.AUTO_TRAINABLE, device="cpu", dtype=torch.bfloat16)
ids = m.tokenizer("The quick brown fox jumps over the lazy dog. " * 8, return_tensors="pt").input_ids
pm = get_peft_model(m.model, LoraConfig(r=8, lora_alpha=16, target_modules=["q_proj", "v_proj", "down_proj"]))
pm.eval()
with torch.inference_mode():
    pm(input_ids=ids)                        # any eval/generate pass
pm(input_ids=ids, labels=ids).loss.backward()
print(sum(p.grad is not None for n, p in pm.named_parameters() if "lora" in n), "of 144 LoRA params got a grad")

I compared against a dense reference: the same model with every quant linear replaced by an nn.Linear holding its dequantized weight, the same LoRA init and the same eval-mode flow.

backend (kernel) LoRA params with grad max rel. grad error vs dense ref
GPTQ_TORCH (TorchLinear) 144 / 144 0.196 (bf16 noise; same as train mode)
AUTO (TorchCpuAvx512Linear) 48 / 144 1.64
AUTO_TRAINABLE (TorchCpuAvx512Linear) 48 / 144 1.64
GPTQ_TORCH_FUSED (TorchFusedLinear) 48 / 144 1.67
AWQ AUTO (TorchCpuAvx512AwqLinear) 48 / 144 1.22

Every q_proj/v_proj LoRA parameter gets grad=None, because o_proj's output is detached. The down_proj LoRA gradients are wrong because the residual gradient no longer includes the path through any later quant layer. The loss still drops, so nothing looks broken.

Module level, after one inference_mode forward, x = randn(..., requires_grad=True): y = layer(x) has y.requires_grad == False for GPTQ_TORCH_FUSED, GPTQ_TORCH_CPU_AVX512, GPTQ_TORCH_ATEN, AWQ_TORCH_FUSED, AWQ_TORCH_CPU_AVX512, AWQ_TORCH_ATEN and GGUF AUTO (GGUFCppKernel). For GPTQ_TORCH, AWQ_TORCH, GGUF_TORCH, Paro, BnB and FP8_TORCH, dx matches gy @ W_deq. Whole-model inputs_embeds.grad norm: 4.6 (fused/AVX512/ATen) vs 986 (GPTQ_TORCH).

In train mode all of these kernels match the reference (144/144, max rel 0.19-0.26), so only the eval-mode latch is affected.

Suggested fix

Decide per call, not per module. When torch.is_grad_enabled() and x.requires_grad (or any parameter needs grad), take the differentiable dense-dequant path even if INFERENCE is latched. That means restoring the train layout via restore_fused_train_state, or keeping a differentiable dequant of the packed layout. Otherwise raise instead of detaching. Apply the same per-call check to GGUFCppKernel and any other @torch.no_grad fast path (see #4072 item 4 for bnb/GGUF Triton).

Test that should have caught it

The kernel training tests run in train() mode only. Add a test per SUPPORTS_TRAINING=True kernel: in eval mode, run one inference_mode forward, then a grad-mode forward with x.requires_grad, and assert y.grad_fn is not None and dx ≈ gy @ dequant(W).

Severity

High for training and attribution users. Gradients are silently wrong or missing, with no error and a plausible decreasing loss. The default CPU kernels (AUTO and even AUTO_TRAINABLE) are affected.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 19, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-root-5314-cpu-grad-latch finished this issue.

    Pull request: #5321

    claiming: decide the CPU fused-vs-dense path per call so a latched no_grad inference forward cannot detach later grad-mode forwards, with per-kernel eval-after-inference regressions

  2. Qubitium commented on Nov 19, 2026

    @Qubitium
    CollaboratorAuthor

    Implemented in draft PR #5321. Each CPU fused forward now checks torch.is_grad_enabled() and x.requires_grad per call; if the fused inference layout is latched, it restores the checkpoint layout and takes the differentiable dequant path for that call. New per-kernel regressions (GPTQ/AWQ x fused/ATen/AVX512) fail on the parent commit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions