Skip to content

[PERF] #5321 (fix of #5314) incomplete: two eval-mode grad forwards latch CPU int4pack kernels to the dense TRAIN path for good - later inference 8-15x slower per layer, Llama-1B generate 0.49 s -> 43.8 s, eval() cannot recover #5392

Closed

Description

@Qubitium

Found on main @ 1405751, CPU (x86 AVX512, 8 threads), torch 2.15, transformers 5.23.0.

What is wrong

#5321 (fix of #5314) makes the CPU int4pack kernels restore the checkpoint layout when a grad forward arrives after the fused inference latch. The commit says "The next inference forward transforms again." That only holds when exactly one grad forward comes between two inference forwards.

The per-call branch in TorchFusedLinear.forward (gptqmodel/nn_modules/qlinear/torch_fused.py:670-697) works like this. The same code is in TorchFusedAwqLinear, TorchAtenLinear (and so TorchCpuAvx512Linear), TorchAtenAwqLinear and TorchCpuAvx512AwqLinear:

  1. Grad forward Add perplexity unit test to guard against regressions #1: linear_mode == INFERENCE, so force_dense=True and restore_fused_train_state() runs, which resets linear_mode to None.
  2. Grad forward Update readme table's style #2: linear_mode is None and force_dense=False. The transform condition fails because x.requires_grad, so it falls into elif not force_dense and self.linear_mode is None: self.linear_mode = LinearMode.TRAIN.

From then on the module is latched to the dense-dequant path for good. Later no_grad/inference_mode forwards dequantize the full weight on every call. The module is still in eval mode, so model.eval() returns early (mode == old_train) and the #4949 reset in train(False) never runs. The only way out is model.train(); model.eval().

Before #5321 these eval-mode grad forwards were silently detached (#5314). Now gradients are correct, but every eval-mode training/attribution loop of 2 or more steps permanently pins the model to the slow path. These are the scenarios #5314 lists: LoRA kept in eval() to disable dropout, saliency, soft-prompt optimization after a generate().

Measured

Model level: Llama-3.2-1B-Instruct GPTQ 4-bit g128, BACKEND.AUTO on CPU (TorchCpuAvx512Linear x112), bf16, generate of 16 tokens under inference_mode:

state kernels generate time
after warmup TorchCpuAvx512Linear:inference x112 0.49 s
after 2 eval-mode grad forwards (inputs_embeds.requires_grad) TorchCpuAvx512Linear:train x112 43.84 s (89.7x)
then model.eval() still train 57.88 s

Module level, 4096x4096 g128, bf16, M=1, no_grad, after two grad forwards:

kernel before after ratio
TorchFusedLinear 3.79 ms 53.50 ms 14.1x
TorchFusedAwqLinear 4.61 ms 34.87 ms 7.6x
TorchAtenLinear 3.49 ms 52.69 ms 15.1x

The gradients themselves are correct: inputs_embeds.grad is non-null with the same norm on both steps.

Repro

import time, torch
from gptqmodel import GPTQModel, BACKEND
m = GPTQModel.load("Llama-3.2-1B-Instruct GPTQ 4bit g128", backend=BACKEND.AUTO, device="cpu", dtype=torch.bfloat16)
ids = m.tokenizer("The quick brown fox jumps over the lazy dog. " * 4, return_tensors="pt").input_ids
def gen():
    with torch.inference_mode():
        t = time.perf_counter(); m.model.generate(ids[:, :8], max_new_tokens=16, min_new_tokens=16, do_sample=False)
        return time.perf_counter() - t
gen(); print("before", gen())
for _ in range(2):                                   # e.g. two eval-mode LoRA/attribution steps
    e = m.model.get_input_embeddings()(ids).detach().requires_grad_(True)
    m.model(inputs_embeds=e).logits.float().logsumexp(-1).sum().backward()
gen(); print("after", gen())
print({getattr(x, "linear_mode", None) for x in m.model.modules() if hasattr(x, "linear_mode")})
before 0.49
after 43.84
{'train'}

Suggested fix

A grad forward taken in eval mode should not latch TRAIN. In the else branch, set LinearMode.TRAIN only when self.training is true. In eval mode, leave linear_mode = None so the next no-grad forward transforms again, and take the dense path for this call only, as the force-dense call already does. If the restore/transform churn on every switch is a concern, keep the checkpoint snapshot and transformed layout side by side while in eval mode, so a switch does not rewrite the packed buffers.

Sibling not covered by #5321: GGUFCppKernel (GGUF AUTO on CPU, gguf_cpp.py:1725), which #5314 also listed, still returns a detached output for x.requires_grad=True on every call (y.requires_grad == False, grad_fn None, fp32 and bf16), while GGUFTorchLinear on the same bytes is differentiable. It declares SUPPORTS_TRAINING = False, so it should raise instead of silently dropping the gradient.

Test that should have caught it

tests/test_cpu_trainable_kernels_grad_after_inference_5314.py does a single grad forward after the inference forward. Extend it to: inference forward, then two grad forwards, then an inference forward, and assert linear_mode is back to the inference layout (or time it).

Severity

Medium (perf). There is no wrong output, but every eval-mode gradient loop silently pins CPU inference to dense dequant, which is 8-15x per layer and about 90x for end-to-end generate on a 1B model, and eval() cannot recover it.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 19, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-fb5145b84190 finished this issue.

    Pull request: #5447

    CPU fused int4pack kernels: an eval-mode grad forward must not latch LinearMode.TRAIN; keep linear_mode None so the next no-grad forward re-transforms. Extend the #5314 test to two grad forwards then inference.

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