Skip to content

[BUG] optimize() compile fallback re-runs a partially executed forward: a compiler failure in a resume frame replays KV-cache updates; first generate() after optimize() always crashes on GGUF Triton (AUTO) models #5119

Closed

Description

@Qubitium

Found on main @ 7b8f127, RTX 5090 (sm_120), torch 2.15 + CUDA 13.2, triton 3.9, transformers 5.22.

What is wrong

model.optimize() installs torch_compile(type(model).forward) with the eager-retry wrapper _install_callable_compile_fallback (gptqmodel/utils/torch.py:430-443). If the first compiled call raises a compiler failure, the wrapper latches fallback and runs original(*args, **kwargs) again from the beginning, in the same call.

With fullgraph=False (the optimize() default), dynamo runs the forward as compiled fragments plus resume frames. A compiler failure can therefore come from a resume frame deep in the model, after earlier fragments have already run their side effects. The retry runs those side effects a second time. In generate() the side effect is DynamicCache.update(): the layers that ran before the failure now hold their keys/values twice. The eager re-run then fails on the mask/KV length mismatch.

The _is_compiler_failure docstring already says why user errors are not retried ("retrying eagerly would run that code twice"). A compiler failure after a graph break has exactly the same problem.

Concrete trigger: the CUDA AUTO GGUF kernel. GGUFTritonKernel (honestly declared SUPPORTS_COMPILE_LEVEL = EAGER) launches a raw Triton kernel through custom_autotune.run -> _bench -> triton.testing.do_bench (gguf_triton.py:2439 -> 2272 -> 1222 -> 1008). Dynamo fails inside it with InternalTorchDynamoError: AttributeError: 'SymNodeVariable' object has no attribute 'value'. That happens in layer 0's MLP, after layer 0's attention has already appended 19 positions to the cache. So on a freshly loaded GGUF model, the first generate() after optimize() always raises:

WARN  `Qwen2ForCausalLM.forward` torch.compile failed at first use; staying on eager execution: InternalTorchDynamoError: AttributeError: 'SymNodeVariable' object has no attribute 'value'
RuntimeError: The expanded size of the tensor (19) must match the existing size (38) at non-singleton dimension 3.  Target sizes: [1, 14, 19, 19].  Tensor sizes: [1, 1, 19, 38]

After the failed call the cache holds [38, 19, ...] positions for layers 0 and 1 (prompt = 19 tokens), so layer 0 was written twice. The second generate() works, because the wrapper is now latched to eager. If the model ran one eager forward before optimize(), the autotune is already cached and the failure point moves; in that order the first generate happened to succeed. On a fresh load it fails every time (3/3 runs).

The same replay also hits any other in-place state a forward mutates before the failing frame: Mamba/linear-attention conv and SSM states, offload hooks, kernel caches. Those cases need not raise; they can silently return wrong results.

Repro

import torch
from transformers import DynamicCache
from gptqmodel import GPTQModel, BACKEND
m = GPTQModel.load("<GGUF q4_k_m Qwen2.5-0.5B-Instruct, quantized with GPTQModel>", backend=BACKEND.AUTO, dtype=torch.float16, device="cuda:0")  # GGUFTritonKernel
ids = m.tokenizer("In 1905, Albert Einstein published four papers that changed physics. The first one", return_tensors="pt").input_ids.cuda()
m.optimize()
m.generate(input_ids=ids, max_new_tokens=8, do_sample=False)   # RuntimeError ... (19) must match ... (38)
# direct form: the cache is written twice
# c = DynamicCache(); m.model(input_ids=ids, past_key_values=c, use_cache=True)  -> same RuntimeError, [l.keys.shape[-2] for l in c.layers][:2] == [38, 19]

Output (this box): generate 1 raised RuntimeError The expanded size of the tensor (19) must match the existing size (38) ..., then generate 2: was "On the electrodynamics of (correct, eager).

Suggested fix

  • Do not re-run a partially executed forward. For the model-level optimize() proxy, either:
    • let dynamo handle the failure per frame (for example torch._dynamo.config.suppress_errors scoped to this compiled callable, which falls back for the failing frame only and runs nothing twice), or
    • latch the fallback and re-raise for this call with a clear "compile failed, the next call runs eagerly" error, instead of silently replaying.
  • Independently, keep dynamo out of the GGUF Triton launch/autotune path (wrap the launch in a torch.library custom op, or apply torch.compiler.disable on _launch/autotune) so optimize() graph-breaks cleanly instead of hitting a dynamo internal error.

Test that should have caught it

tests/test_silent_exception_handling.py covers the fallback only with callables whose failure happens before any user code runs. It needs a case where the failure comes from a resume frame after a side effect (append to a list or cache, then fail in a later frame), asserting the side effect happened once. An optimize() + generate() smoke test per AUTO kernel on a fresh load (no eager warm-up) would also have caught the GGUF crash.

Severity

Medium: the documented optimize() + generate() flow crashes on the first call for the CUDA AUTO GGUF kernel. The replay is a silent-corruption risk for stateful models.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-fb5145b84190 finished this issue.

    Pull request: #5163

    Reproducing the compile-fallback replay of a partially executed forward and fixing the fallback to not re-run user code

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