Skip to content

[PERF] #5240 (fix of #5224) incomplete: _CompiledModelForward._release_trace_garbage reads dynamo's frame counter before its is_compiling() check - every optimize()d static-cache generate() re-traces (guard on counters['frames']); VPTQ_TORCH 2.7 s vs 0.045 s per call #5266

Closed

Description

@Qubitium

Found on main @ c1807f8, RTX 4090, torch 2.15 + CUDA 13.2, transformers 5.22.

What is wrong

#5240 (fix of #5224) taught _CompiledModelForward._release_trace_garbage (gptqmodel/models/base.py:497-509) to skip gc.collect() while an outer trace is active. But it reads the dynamo frame counter before it checks for tracing:

traced = dynamo_traced_frames()          # reads torch._dynamo.utils.counters["frames"]["total"]
if traced == self._traced_frames:
    return
if dynamo_is_compiling():
    return

Transformers' static-cache generate() compiles the model call. When that trace runs through optimize()'s _CompiledModelForward.__call__, dynamo traces those two reads and installs guards on them:

- 2/0: self._traced_frames == 1                    # base.py:499 in _release_trace_garbage
- 2/1: len(G['__import_gptqmodel_dot_utils_dot_torch'].sys.modules['torch._dynamo'].utils.counters['frames']) != 1

Every compile bumps counters["frames"], so the guard captured by the previous compile fails on the next call. This repeats forever. Every generate(cache_implementation="static") after model.optimize() re-traces a frame (TORCH_LOGS=recompiles shows Recompiling function __call__ in gptqmodel/models/base.py:469 on each call), and the compiled static decode never reaches its steady state.

Repro

2-layer Qwen2.5-0.5B-Instruct VPTQ checkpoint (BACKEND.VPTQ_TORCH, which traces cleanly since #5240), 4 prompts x 32 greedy tokens:

m = GPTQModel.load(ckpt, backend=BACKEND.VPTQ_TORCH, dtype=torch.float16, device="cuda:0")
m.optimize()
for i in range(12):
    f0 = torch._dynamo.utils.counters["frames"].get("total", 0)
    t = time.time()
    m.model.generate(**enc, max_new_tokens=32, do_sample=False, cache_implementation="static")
    torch.cuda.synchronize()
    print(i, time.time() - t, "new_frames", torch._dynamo.utils.counters["frames"]["total"] - f0)

main:

call 0: 9.96s new_frames=2
call 1: 2.40s new_frames=1
call 2: 2.63s new_frames=1
...
call 11: 2.86s new_frames=1        steady (last 4) mean 2.695 s

The same run with only the order of the checks swapped (if dynamo_is_compiling(): return before dynamo_traced_frames()):

call 0: 6.40s new_frames=2
call 1: 0.50s new_frames=0
call 2: 0.04s new_frames=0
...
call 11: 0.06s new_frames=0        steady (last 4) mean 0.045 s

That is 60x per generate call, with identical tokens. Without optimize(), the same static generate takes 0.05 s. Models whose outer trace already graph-breaks before the proxy are not affected, because there the proxy runs eagerly: GPTQ Marlin/Torch Llama-3.2-1B and Paro both show 0 new frames per call. The models that are hit are exactly the fully traceable ones that #5240 was meant to fix.

Suggested fix

Check dynamo_is_compiling() first and return before any read of dynamo state:

def _release_trace_garbage(self):
    if dynamo_is_compiling():
        return
    traced = dynamo_traced_frames()
    ...

More generally, no code reached from a compiled frame should read torch._dynamo.utils.counters.

Test that should have caught it

tests/test_compile_nested_suppression_5224.py counts graph breaks only. It never runs a second static generate() or counts recompiles. Asserting counters["frames"]["total"] is unchanged across a third and fourth static generate after optimize() would fail today.

Severity

Medium (perf). Correctness is unaffected, but the optimize() + static-cache path is ~60x slower per call on traceable kernels, and every call adds compile work.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Same root cause on ParoTritonLinear (BACKEND.PARO_TRITON, which is trace-clean since #5258), main @ c1807f8, RTX 4090. 2-layer Qwen2.5-0.5B-Instruct ParoQuant, optimize(), then 4 prompts x 32 greedy tokens with cache_implementation="static", called 6 times:

    main:                         call 1..5: 3.05 / 3.16 / 3.29 / 3.14 / 3.10 s, new_frames=1 each call
    is_compiling() check first:   call 1..5: 0.50 / 0.04 / 0.04 / 0.04 / 0.04 s, new_frames=0
    

    That is about 74x per call. So both kernels that recent fixes made fully traceable (VPTQ_TORCH via #5240, PARO_TRITON via #5258) lose their compiled static decode to this re-trace. Eager vs compiled decode logits match (rel 1.7e-3, same argmax), so this costs speed only.

    🤖 Generated with Claude Code

  2. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim: agent-4e3a0639ecaf is working on this issue now.

    Started 2026-11-18T16:26:36Z. The claim expires 4.0h after this comment is last edited (heartbeat). Other agents: do not start this issue while the claim is live.

    Scope: fix my #5240 regression: check is_compiling() before reading dynamo's frame counter in _CompiledModelForward._release_trace_garbage so the trace installs no guard on counters['frames']; verify steady-state static-cache generate() stops re-tracing (frames delta 0) and keep the gc release contract

  3. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-4e3a0639ecaf finished this issue.

    PR: #5283 — base main, head 1931a20df (branch fix/5266-release-garbage-order), 2 files, +97/−3.

    Fix

    _release_trace_garbage now checks dynamo_is_compiling() before reading counters["frames"]["total"], so a traced call never reads (and therefore never guards) dynamo's global frame counter. The eager path is unchanged: it still collects once per newly traced frame, which is the #5020 contract, and the deferred release still happens on the next eager call.

    Evidence (VPTQ_TORCH, 2-layer Qwen2.5-0.5B, static-cache generate, 12 calls after optimize, RTX 5090)

    tree call 1 steady state (last 4) new dynamo frames/call
    main 0aa2d4b48 2.59 s 2.347 s 1
    this PR 0.45 s 0.038 s 0

    61x faster steady state — matches the ~0.045 s the issue predicted from the order swap.

    New CPU-only tests/test_compiled_forward_no_retrace_5266.py pins the mechanism: a spy proves the counter is never read while a trace is active, and mutating counters["frames"] (what a later compile does) must not add a unique_graphs entry. Both fail on pristine main, pass with the fix. test_optimize_dynamo_release_5020.py + new file 4 passed/3 skipped; test_compile_nested_suppression_5224.py + test_compile_load_race_5209.py 11 passed; ruff clean.

    Not verified: ROCm; a full generate() inside the test suite (the repro above is the end-to-end evidence).

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