Skip to content

[PERF] generate(cache_implementation="static") is 2-4x SLOWER than eager on every default CUDA kernel (HF auto-compile graph-breaks on each quantized linear: no fake impls, data_ptr/id() guards); model.optimize() compiles nothing that generate() runs #4669

Closed

Description

@Qubitium

Found on main @ 12c1273, RTX 4090 (torch 2.15, transformers 5.22, triton 3.9).

Summary

  1. generate(cache_implementation="static") is 2-4x slower than plain eager generation on every CUDA kernel that GPT-QModel selects by default. On the same GPU the dense model gets about 1.6x faster. Transformers auto-compiles the forward pass for a static cache (CompileConfig, mode="reduce-overhead"). The GPT-QModel kernels break that graph on every quantized linear, so CUDA-graph capture never covers a layer. Each decode step then pays for dozens of graph fragments, guard checks and recompiles. Output stays correct; the cost is speed. Nothing warns the user, and the static cache is the setting transformers recommends for fast decoding.
  2. model.optimize() has no effect on generate(). It replaces self.model with an OptimizedModule (models/base.py:3627). GPTQModel.generate calls self.model.generate, which OptimizedModule.__getattr__ resolves to the original module's generate. That method calls the original eager forward. During generate() after optimize(), dynamo compiles 0 frames.

Measurements

Llama-3.2-1B-Instruct, fp16, 4 left-padded prompts, 48 new tokens (min_new_tokens=48), greedy. Times are seconds for the whole generate() call, after warm-up; "static" is the steady-state second or third call, after compilation.

model / backend (kernel) dynamic cache (eager) static cache (auto-compile) static, disable_compile=True dynamo graphs
dense bf16 checkpoint (HF) 0.31 0.19-0.21 0.34 1
GPTQ g128, MARLIN (= AUTO) 0.33 0.98-1.05 0.35 25
GPTQ g128, GPTQ_EXLLAMA_V2 0.35 0.78-0.97 0.37 32
GPTQ g128, GPTQ_TRITON 0.65 1.52-2.26 0.70 147
GPTQ g128, GPTQ_TORCH 0.60 1.99-2.85 0.64 148
AWQ gemm, AWQ_GEMM 0.36 1.23-1.33 0.40 29
AWQ gemm, AUTO (Marlin) 0.34 0.78-0.94 0.38 25
AWQ gemm, AWQ_TORCH (pure torch, no custom op) 1.36 0.76 1.44 26

Qwen2.5-0.5B-Instruct-gptq-4bit (desc_act, g32) shows the same pattern: GPTQ_TORCH 0.95 s dynamic vs 2.3-4.0 s static (173 graphs); MARLIN 0.55 vs 1.76; GPTQ_EXLLAMA_V2 0.57 vs 2.15; GPTQ_TRITON 1.09 vs 6.19.

AWQ_TORCH is the only kernel with no custom op and no Python-side identity guards, and it is the only one that speeds up under compile. That points to the kernels, not to transformers.

Root causes (from TORCH_LOGS=graph_breaks,recompiles)

  • No fake/meta implementation for any GPT-QModel custom op. grep -rn "register_fake\|impl_abstract\|register_meta" gptqmodel gptqmodel_ext finds nothing. Every Marlin call breaks the graph:
    Operator does not support running with fake tensors ... unsupported operator: gptqmodel_marlin_fp16.gptq_marlin_gemm_fp16.default (29 breaks for a 16-layer model).
    The same applies to the gptqmodel_awq, gptqmodel_exllamav2, gptqmodel_allspark and QQQ ops. The Marlin schema also returns an alias of c (Tensor(a!)? c), so a plain register_fake is not enough. I tried it, and dynamo raises Found a custom (non-ATen) operator whose output has alias annotations. The op needs a functional torch.library.custom_op wrapper, with the scratch/workspace mutation declared in mutates_args, plus a fake.
  • ExLlamaV2: the handle cache check _q_fast_signature (nn_modules/qlinear/exllamav2.py:59, used at :268) compares tensor.data_ptr() on every forward. Dynamo cannot trace that: Data pointer comparison ... DataPtrVariable() __eq__ ConstantVariable(int: ...).
  • TorchLinear / TritonV2Linear: _gptq_gemm_uniform_group_for_current_g_idx (nn_modules/qlinear/torch.py:946-950) checks id(g_idx) == self._gptq_gemm_uniform_id and version == self._gptq_gemm_uniform_version on every forward. That causes a data-dependent graph break (Could not guard on data-dependent expression Eq(u0, 0)) and one recompile per linear module ([13/128] [__recompiles] ... id(g_idx) == self._gptq_gemm_uniform_id, 128 recompiles for 24 layers).

Repro

import time, torch
from gptqmodel import GPTQModel, BACKEND
from torch._dynamo.utils import counters

m = GPTQModel.load("Llama-3.2-1B-Instruct-GPTQ-4bits-gp128", backend=BACKEND.MARLIN, dtype=torch.float16, device="cuda:0")
tok = m.tokenizer; tok.padding_side = "left"
enc = tok(["The capital of France is", "def fibonacci(n):", "Hello",
           "In 1905, Albert Einstein published four papers"], return_tensors="pt", padding=True).to("cuda:0")

def run(**kw):
    counters.clear(); torch.cuda.synchronize(); t = time.time()
    m.generate(**enc, max_new_tokens=48, min_new_tokens=48, do_sample=False, **kw)
    torch.cuda.synchronize(); return round(time.time() - t, 3), dict(counters["stats"])

run(); print("dynamic", run())
for i in range(3): print("static", run(cache_implementation="static"))
print("static no-compile", run(cache_implementation="static", disable_compile=True))

# item 2
m.optimize(); counters.clear(); run(); print("frames compiled in generate after optimize():", dict(counters["stats"]))

Output:

dynamic (0.324, {})
static (8.684, {'calls_captured': 384, 'unique_graphs': 25})
static (1.121, {})
static (1.108, {})
static no-compile (0.353, {})
frames compiled in generate after optimize(): {}

For item 2, Qwen2.5-0.5B-Instruct-gptq-4bit gives GPTQ_TORCH 1.06 s before and 1.08 s after optimize(), and MARLIN 0.66 s vs 0.64 s, with 0 frames compiled during generate(). A direct m.model(**enc) does go through the compiled wrapper (174 graphs on GPTQ_TORCH, 44 on MARLIN). Tokens and save/reload after optimize() are fine.

Suggested fix

  • Short term: until the selected kernels are compile-clean, have GPT-QModel opt out of transformers' auto-compile, either by setting generation_config.disable_compile = True at load or by exposing an is_compileable=False capability per kernel. A static cache without compile runs at eager speed (table above) instead of 3x slower.
  • Make the kernels traceable:
    • wrap each CUDA op in torch.library.custom_op, with the mutated workspace in mutates_args and no output alias, and give it a register_fake;
    • move the ExLlamaV2 data_ptr and TorchLinear id()/_version cache checks out of the traced forward, either under torch.compiler.is_compiling() or by computing them once at post_init/optimize().
  • optimize() should compile what generate actually calls: compile in place with self.model.compile(...) or self.model.forward = torch.compile(self.model.forward), or set generation_config.compile_config and use a static cache. With the current kernels that would still be slower (in-place compile with a dynamic cache on Marlin: 1.12 s vs 0.75 s eager, 46 graph breaks), so it depends on the item above.

Tests that should catch it

A CUDA test that runs generate(cache_implementation="static") with the AUTO kernel on a small GPTQ/AWQ checkpoint and asserts (a) counters["graph_break"] is empty and (b) the steady-state time is not slower than the dynamic cache. Today the tests only check that static-cache tokens match.

Severity: medium (perf). It is silent, it hits every default CUDA kernel, and it inverts the expected speed-up of the recommended fast-decode setting. optimize() is a documented API that currently does nothing for generate().

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    More data, same main @ 12c1273, RTX 4090. This time on the other formats: Qwen2.5-0.5B-Instruct quantized on main, fp16, 4 left-padded prompts, 48 new tokens. Times are seconds per generate() call, measured after warm-up.

    backend (kernel) dynamic cache (eager) static cache (auto-compile), steady state dynamo graphs static tokens == dynamic
    FP8_TORCH 0.77 0.175 (compiles clean) 1 yes
    EXL3_TORCH 7.16 1.33 (but the first static call takes 591 s to compile: 74,471 captured calls, trellis decode unrolled per module) 1 yes (1 row near-tie at token 13)
    NF12 0.78 2.75 38 yes
    GGUF_TRITON 0.95 3.84 42 yes
    GGUF_TORCH 2.08 4.68 37 yes
    GGUF_CPP_CUDA 2.05 8.57 42 1 row near-tie
    EXL3_EXLLAMA_V3 0.66 4.50 32 yes

    So the slowdown is not limited to GPTQ/AWQ. NF12, GGUF (all three CUDA paths) and EXL3 native also run 2.8x to 6.8x slower than eager under the static cache. The kernels that are pure torch (FP8_TORCH, AWQ_TORCH, EXL3_TORCH) are the ones that gain. EXL3_TORCH's first compile, at almost 10 minutes on a 0.5B model, is a usability problem of its own.

    🤖 Generated with Claude Code

  2. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-53ba17eb4d83 finished this issue.

    Pull request: #4727

    Reproducing the static-cache auto-compile slowdown on GB10 and landing the kernel-capability opt-out

  3. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim: agent-root-4669 is working on this issue now.

  4. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-53ba17eb4d83 finished this issue.

    Pull request: #4912

    Profile generate(cache_implementation='static') on GB10 sm_121 vs eager; identify the graph breaks on quantized linears and whether fake impls/guards can be added; fix and measure.

  5. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    One concrete gap in the current policy, main @ 5cded90 on an RTX 4090: native EXL3 models are still auto-compiled under the static cache.

    BaseQModel._kernels_support_compile() (gptqmodel/models/base.py:3262-3290) collects kernels with find_modules(model, layers=[BaseQuantLinear, ExllamaV3TorchLinear]). ExllamaV3Linear, the AUTO EXL3 kernel on CUDA, subclasses neither, so an EXL3 model has no matched modules. The method then takes the if not modules: return True branch for "dense" models. As a result, _generation_compile_kwargs() never adds disable_compile=True, and transformers compiles a model whose native custom ops graph-break on every layer.

    Measured with Llama-3.2-1B-Instruct-EXL3-W4-ALL in fp16, m.generate(2 prompts, max_new_tokens=64, min_new_tokens=64) through the GPTQModel wrapper, steady state, 2 runs:

    seconds
    m._kernels_support_compile() True
    dynamic cache 0.50 / 0.60
    cache_implementation="static", default policy (compiled) 1.48 / 1.51
    cache_implementation="static", disable_compile=True 0.60 / 0.72

    The default static-cache path is about 2.5x slower than the same call with compile disabled. bf16 shows the same pattern: static default 2.89 s against 1.55 s with disable_compile=True.

    Fix: include ExllamaV3Linear in the find_modules layer list, or have it declare SUPPORTS_COMPILE = False and make the policy check any module that has a SUPPORTS_COMPILE attribute instead of a class list. Add a policy test that loads one checkpoint per AUTO kernel family, including native EXL3, and asserts _kernels_support_compile() matches that kernel's declared capability.

    🤖 Generated with Claude Code

  6. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent release: agent-root-4669 is standing down. The live claim belongs to agent-53ba17eb4d83, and PR #4912 already covers issue item 3 (optimize() compiling the forward generate() runs). Item 1/2 work is preserved in the shared container for whoever holds the claim to fold in — nothing was pushed and no competing PR was opened.

    What is sitting in /root/worktrees/root-4669 (branch root/static-cache-compile-4669, 9 modified files + 1 new test, rebasable onto current main):

    • Marlin functional custom op — torch.library.custom_op wrapper for gptq_marlin_gemm_* with a fake/meta impl, no aliased return, only workspace declared in mutates_args. This removes the "Operator does not support running with fake tensors" break that hits every quantized linear.
    • Dynamo-safe guards — _gptq_gemm_uniform_group_for_current_g_idx (qlinear/torch.py) no longer compares id(g_idx)/version per forward; ExLlamaV2 _q_fast_signature (qlinear/exllamav2.py:59) no longer compares data_ptr(); marlin.py/marlin_awq.py use the per-stream workspace from fix(marlin): give each CUDA stream its own lock workspace (#4683) #4859 inside the functional wrapper.

    Measured on this sm_80 host, Llama-3.2-1B GPTQ fp16, 4 left-padded prompts, 48 new tokens, BACKEND.MARLIN:

    static cache (steady state) dynamo graphs graph breaks
    origin/main @ 6ec93e632 0.238 s 20 23
    with the local diff 0.065 s 1 0
    eager 0.147 s - -

    Token-identical to eager on greedy decode. Targeted suites: 27 passed; ruff check clean. Red proof on 6ec93e632: 3 failed / 14 passed.

    Note for the claim holder: current main already contains #4727 (ROCm gate) and #4739 (FP8 static cache), so a rebase is needed; the Marlin custom op is the part that is still missing and is what takes the graph count from 20 to 1.

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