Repository navigation
fix(compile): keep nested torch_compile wrappers trace-clean (#5224) - #5240
Merged
Merged
Conversation
`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
marked this pull request as ready for review
November 18, 2026 13:09
This was referenced Nov 18, 2026
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #5224.
Root cause
_call_with_dynamo_suppression()(#5163) writestorch._dynamo.config.suppress_errors— aContextVar— inside the callabletorch_compile()installs.VPTQLinear.optimize()runs at post-init andinstalls exactly such a callable as
self.dequantize. Since #5171 setsVPTQLinear.SUPPORTS_COMPILE = True, transformers auto-compiles a static-cachegenerate(); the outer trace walks into the wrapper, cannot traceContextVar('suppress_errors').set(), and graph-breaks per VPTQ layer(
Unsupported: ContextVar mutation not supported). With the cudagraphreduce-overheadstatic cache those fragments hand out tensors the nextpartition overwrites, so the first
generate()dies withaccessing tensor output of CUDAGraphs that has been overwritten.One line: #5163's per-call
suppress_errorsContextVar write is untraceablewhen the wrapper is entered from inside another
torch.compiletrace, so everyVPTQ layer breaks out of #5171's static-cache graph.
torch.compileis lazy, so patchingsuppress_errorsaround thetorch.compile(...)creation cannot cover the later trace; the flag is readwhen the first call traces. The nesting-aware short-circuit below is the
compile-time-correct equivalent.
Fix
gptqmodel/utils/torch.py: adddynamo_is_compiling()(
torch.compiler.is_compiling, safe fallback). Both fallback wrappers(
_install_callable_compile_fallback.call,_install_module_compile_fallback.forward) return the eageroriginalwhenan outer trace is already active: no dynamo-config write, no load lock, and
the body is inlined into the outer graph.
_call_with_dynamo_suppressionalso short-circuits when nested, as defence in depth.
Top-level non-
fullgraphcalls still enablesuppress_errorsfor the calland 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_garbageskips
gc.collect()while an outer trace is active.gc.collectisuntraceable, so the
finallywas a second, once-per-model-call graph breakon 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"]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 --> OKEvidence (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".Unsupported: ContextVar mutation not supportedtests/test_compile_nested_suppression_5224.pyoptimize()optimize()x3tests/test_*vptq*(4 files)tests/test_*compile*(6 files)tests/kernels/test_*compile*(11 files)tests/test_optimize_dynamo_release_5020.pyuvx [email protected] check gptqmodel docs/eora tests setup.pyRed log:
.scratch/red_full.log; green log:.scratch/green_full.log.Not verified
fix are device-independent (dynamo tracing + ContextVar), and the CPU
minimal repro covers the same path.
tests/test_optimize_dynamo_release_5020.pyneeded the localHuggingFaceTB/SmolLM2-135Mcache ref recreated (missingrefs/main); therepo is untouched.
VPTQCudaLinearkernel is not built here, so its tests skip.