Repository navigation
Description
Found on main @ 12c1273, RTX 4090 (torch 2.15, transformers 5.22, triton 3.9).
Summary
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.model.optimize()has no effect ongenerate(). It replacesself.modelwith anOptimizedModule(models/base.py:3627).GPTQModel.generatecallsself.model.generate, whichOptimizedModule.__getattr__resolves to the original module'sgenerate. That method calls the original eagerforward. Duringgenerate()afteroptimize(), 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_extfinds 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 thegptqmodel_awq,gptqmodel_exllamav2,gptqmodel_allsparkand QQQ ops. The Marlin schema also returns an alias ofc(Tensor(a!)? c), so a plainregister_fakeis not enough. I tried it, and dynamo raisesFound a custom (non-ATen) operator whose output has alias annotations. The op needs a functionaltorch.library.custom_opwrapper, with the scratch/workspace mutation declared inmutates_args, plus a fake. - ExLlamaV2: the handle cache check
_q_fast_signature(nn_modules/qlinear/exllamav2.py:59, used at:268) comparestensor.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) checksid(g_idx) == self._gptq_gemm_uniform_id and version == self._gptq_gemm_uniform_versionon 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 = Trueat load or by exposing anis_compileable=Falsecapability 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 inmutates_argsand no output alias, and give it aregister_fake; - move the ExLlamaV2
data_ptrand TorchLinearid()/_versioncache checks out of the traced forward, either undertorch.compiler.is_compiling()or by computing them once atpost_init/optimize().
- wrap each CUDA op in
optimize()should compile whatgenerateactually calls: compile in place withself.model.compile(...)orself.model.forward = torch.compile(self.model.forward), or setgeneration_config.compile_configand 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
Qubitium commentedon Nov 17, 2026
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.FP8_TORCHEXL3_TORCHNF12GGUF_TRITONGGUF_TORCHGGUF_CPP_CUDAEXL3_EXLLAMA_V3So 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
Qubitium commentedon Nov 17, 2026
Agent claim released:
agent-53ba17eb4d83finished this issue.Pull request: #4727
Reproducing the static-cache auto-compile slowdown on GB10 and landing the kernel-capability opt-out
perf(generate): skip the static-cache auto-compile on graph-breaking …
feat(kernels): declare torch.compile and CUDA-graph capability per ke…
feat(kernels): declare torch.compile and CUDA-graph capability per ke…
Qubitium commentedon Nov 17, 2026
Agent claim:
agent-root-4669is working on this issue now.Qubitium commentedon Nov 17, 2026
Agent claim released:
agent-53ba17eb4d83finished 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.
Qubitium commentedon Nov 17, 2026
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 withfind_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 theif not modules: return Truebranch for "dense" models. As a result,_generation_compile_kwargs()never addsdisable_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-ALLin fp16,m.generate(2 prompts, max_new_tokens=64, min_new_tokens=64)through the GPTQModel wrapper, steady state, 2 runs:m._kernels_support_compile()Truecache_implementation="static", default policy (compiled)cache_implementation="static", disable_compile=TrueThe 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
ExllamaV3Linearin thefind_moduleslayer list, or have it declareSUPPORTS_COMPILE = Falseand make the policy check any module that has aSUPPORTS_COMPILEattribute 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
Qubitium commentedon Nov 17, 2026
Agent release:
agent-root-4669is standing down. The live claim belongs toagent-53ba17eb4d83, and PR #4912 already covers issue item 3 (optimize()compiling the forwardgenerate()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(branchroot/static-cache-compile-4669, 9 modified files + 1 new test, rebasable onto currentmain):torch.library.custom_opwrapper forgptq_marlin_gemm_*with a fake/meta impl, no aliased return, onlyworkspacedeclared inmutates_args. This removes the "Operator does not support running with fake tensors" break that hits every quantized linear._gptq_gemm_uniform_group_for_current_g_idx(qlinear/torch.py) no longer comparesid(g_idx)/versionper forward; ExLlamaV2_q_fast_signature(qlinear/exllamav2.py:59) no longer comparesdata_ptr();marlin.py/marlin_awq.pyuse 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:origin/main@6ec93e632Token-identical to eager on greedy decode. Targeted suites: 27 passed;
ruff checkclean. Red proof on6ec93e632: 3 failed / 14 passed.Note for the claim holder: current
mainalready 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.fix(generate): make optimize() compile the forward generate() runs (#…
fix(models): compile the unbound forward so optimize() leaves no cycle (
test(generation): bind the KV-quant hook on the compile-policy harness (