Skip to content

fix(compile): keep nested torch_compile wrappers trace-clean (#5224) - #5240

Merged
Qubitium merged 1 commit into
mainfrom
fix/5224-vptq-static-cache
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5224-vptq-static-cache

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #5224.

Root cause

_call_with_dynamo_suppression() (#5163) writes
torch._dynamo.config.suppress_errors — a ContextVar — inside the callable
torch_compile() installs. VPTQLinear.optimize() runs at post-init and
installs exactly such a callable as self.dequantize. Since #5171 sets
VPTQLinear.SUPPORTS_COMPILE = True, transformers auto-compiles a static-cache
generate(); the outer trace walks into the wrapper, cannot trace
ContextVar('suppress_errors').set(), and graph-breaks per VPTQ layer
(Unsupported: ContextVar mutation not supported). With the cudagraph
reduce-overhead static cache those fragments hand out tensors the next
partition overwrites, so the first generate() dies with
accessing tensor output of CUDAGraphs that has been overwritten.

One line: #5163's per-call suppress_errors ContextVar write is untraceable
when the wrapper is entered from inside another torch.compile trace, so every
VPTQ layer breaks out of #5171's static-cache graph.

torch.compile is lazy, so patching suppress_errors around the
torch.compile(...) creation cannot cover the later trace; the flag is read
when the first call traces. The nesting-aware short-circuit below is the
compile-time-correct equivalent.

Fix

  • gptqmodel/utils/torch.py: add dynamo_is_compiling()
    (torch.compiler.is_compiling, safe fallback). Both fallback wrappers
    (_install_callable_compile_fallback.call,
    _install_module_compile_fallback.forward) return the eager original when
    an outer trace is already active: no dynamo-config write, no load lock, and
    the body is inlined into the outer graph. _call_with_dynamo_suppression
    also short-circuits when nested, as defence in depth.
    Top-level non-fullgraph calls still enable suppress_errors for the call
    and restore it afterwards, so fix(compile): let dynamo fall back per frame instead of replaying the forward (#5119) #5163's resume-frame fallback is unchanged.
  • gptqmodel/models/base.py: _CompiledModelForward._release_trace_garbage
    skips gc.collect() while an outer trace is active. gc.collect is
    untraceable, so the finally was a second, once-per-model-call graph break
    on the perf(qqq,vptq): opt portable torch kernels into compiled generation (#5102) #5171 path; the release is deferred to the next eager call.
  • tests/test_compile_nested_suppression_5224.py: pins the nested callable,
    nested module, VPTQ optimize() + outer trace, _CompiledModelForward,
    top-level suppression, and flag-restoration contracts.

Before / after

Before:

flowchart TD
    G["static-cache generate()"] --> C["transformers torch.compile(model.__call__)"]
    C --> W["VPTQLinear.dequantize wrapper (torch_compile)"]
    W -->|"suppress_errors = True (ContextVar write)"| B["Unsupported: ContextVar mutation not supported"]
    B --> P["graph break per VPTQ layer (32 breaks / 32 graphs)"]
    P --> S["cudagraph partitions hand out overwritten outputs"]
    S --> X["RuntimeError: accessing tensor output of CUDAGraphs that has been overwritten"]
Loading

After:

flowchart TD
    G["static-cache generate()"] --> C["transformers torch.compile(model.__call__)"]
    C --> Q{"torch.compiler.is_compiling()?"}
    Q -->|yes| E["inline eager dequantize body (no config write, no lock)"]
    Q -->|no| T["set suppress_errors for the call, restore in finally (#5163)"]
    E --> OK["0 graph breaks, 2 graphs, tokens == eager"]
    T --> OK
Loading

Evidence (GPU 2, RTX 5090 sm_120, torch 2.15.0+cu132, transformers 5.22.1)

Checkpoint: 2-layer Qwen2.5-0.5B-Instruct quantized with VPTQConfig
(VPTQ_TORCH, fp16), 4 prompts x 32 greedy tokens, cache_implementation="static".

Check Pre-fix (upstream/main b54abcb) Post-fix
CPU minimal nested compile repro Unsupported: ContextVar mutation not supported 0 breaks, 2 graphs, same value
tests/test_compile_nested_suppression_5224.py 4 failed, 2 passed 6 passed
GPU2 static cache, no optimize() RuntimeError: accessing tensor output of CUDAGraphs that has been overwritten 0 breaks, tokens == eager
GPU2 static cache, after optimize() x3 not reached (crashed before) 0 breaks, 2 graphs each run, tokens == eager
tests/test_*vptq* (4 files) — 338 passed
tests/test_*compile* (6 files) — 51 passed, 1 skipped
tests/kernels/test_*compile* (11 files) — 170 passed, 179 skipped
VPTQ kernel probes (#4984/#5102) red per issue report 2 passed
tests/test_optimize_dynamo_release_5020.py — 5 passed
uvx [email protected] check gptqmodel docs/eora tests setup.py — clean

Red log: .scratch/red_full.log; green log: .scratch/green_full.log.

Not verified

  • ROCm/gfx1201 (the reporter's hardware): no ROCm host here. The mechanism and
    fix are device-independent (dynamo tracing + ContextVar), and the CPU
    minimal repro covers the same path.
  • tests/test_optimize_dynamo_release_5020.py needed the local
    HuggingFaceTB/SmolLM2-135M cache ref recreated (missing refs/main); the
    repo is untouched.
  • The fused VPTQCudaLinear kernel is not built here, so its tests skip.

`torch_compile` installs lazy wrappers, so they can be entered from inside
another `torch.compile` trace: transformers compiles a static-cache
`generate()` forward, and `VPTQLinear.optimize()` installs one of these
wrappers on `dequantize` at post-init.

Since #5163 that wrapper wrote `torch._dynamo.config.suppress_errors` for the
call. Dynamo config overrides are ContextVars, so the write is an
`Unsupported: ContextVar mutation not supported` graph break in the outer
trace. Every VPTQ layer then breaks out of the compiled forward, and the
cudagraph static-cache decode returns outputs a later partition overwrote
(`accessing tensor output of CUDAGraphs that has been overwritten`).

Nested calls now stay read-only: when dynamo is already tracing, the wrapper
returns the eager callable/module body so it is inlined into the outer graph,
mutating no config and taking no `model_global_state_lock`. Top-level
non-fullgraph behaviour is unchanged (#5163 still enables suppression for the
call and restores it in `finally`); `_call_with_dynamo_suppression` carries the
same guard as defence in depth.

`_CompiledModelForward._release_trace_garbage` also skipped its `gc.collect()`
while dynamo is tracing: `gc.collect` is untraceable, so it was one more graph
break per model call on the #5171 path. The frame count is left unchanged so
the next eager call does the release.

Repro (Qwen2.5-0.5B-Instruct 2-layer VPTQ_TORCH fp16, 4 prompts x 32 greedy,
static cache, RTX 5090): before the fix the first no-optimize static generate
raised the CUDAGraph overwrite error; after it, no-optimize and three
post-`optimize()` runs report 0 graph breaks, 2 unique graphs each, and tokens
equal to eager.

Tests: tests/test_compile_nested_suppression_5224.py (6 cases; 4 fail without
the fix). Existing VPTQ/compile suites unchanged and green.
@Qubitium
Qubitium marked this pull request as ready for review November 18, 2026 13:09
@Qubitium
Qubitium merged commit 70a6b20 into main Nov 18, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/5224-vptq-static-cache branch November 18, 2026 13:12
Qubitium added a commit that referenced this pull request Nov 18, 2026
… counter (#5266) (#5283)

#5240 made `_CompiledModelForward._release_trace_garbage` skip `gc.collect()`
while an outer `torch.compile` traces the call, but it read
`counters["frames"]["total"]` first. Dynamo traced that read and installed a
guard on the counter mapping; every later compile mutates the mapping, so the
guard failed on the next call and every static-cache `generate()` after
`optimize()` re-traced a frame forever.

Check `dynamo_is_compiling()` first, so a traced call never reads the counter
and never guards it. The eager path is unchanged: it still collects once per
newly traced frame, which is the #5020 contract.

VPTQ_TORCH, 2-layer Qwen2.5-0.5B, static-cache generate(), 12 calls after
optimize(): steady state 2.347 s -> 0.038 s per call (61x), new dynamo frames
per call 1 -> 0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant