Repository navigation
fix(optimize): release dynamo's trace cycles so a compiled model frees its VRAM (#5020) - #5064
Merged
Merged
Conversation
…s its VRAM (#5020) `optimize()` compiles the unbound `type(model).forward` and reaches the model through a weak reference, so the proxy itself no longer closes a `model -> forward -> model` cycle (#4937). Torch.compile still pins the model: every frame dynamo traces builds `VariableTracker` objects, and a graph break leaves an `UnspecializedNNModuleVariable` -> `SideEffectsProxyDict` -> `DunderDictVariable` cycle that keeps the traced module reachable. Reference counting cannot reclaim those cycles, so after `optimize()` + `generate()` the quantized model and all of its VRAM survived the last user reference until a full cyclic `gc.collect()` - the whole 0.43 GiB model on Qwen2.5-0.5B, for GPTQ_TRITON, GPTQ_TORCH and MARLIN alike. `_CompiledModelForward` now compares `dynamo_traced_frames()` across a compiled call and, when that call traced a new frame, runs `release_compile_trace_garbage()`: a plain `gc.collect()` that reclaims the unreachable cycles while the caller still owns the model. Only those cycles are collected; dynamo's compiled-frame cache is untouched, so the next call still takes the compiled path. A call that reuses the cache adds no frames and costs nothing: a warm 48-token generate fired zero releases at 13.8 ms/token, against 12.5-14.0 ms/token for the same run with the release disabled on this shared GPU. `optimize()` also sets the `compiled` flag its docstring promises; the flag was only ever written as `False`. The new helpers shift `torch_sync` in `utils/torch.py` past the line its `docs/multi_gpu_quantization.md` citation pinned, so that citation moves to the symbol form (`torch.py::torch_sync`) the docs-contract guard recommends for files that keep growing.
This was referenced Nov 18, 2026
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.
Summary
Fixes #5020. #4986 (the fix for #4937) removed the
model -> forward -> modelcycle fromoptimize()by compiling the unboundtype(model).forwardbehind a weak reference. The model was still pinnedafterwards: torch.compile's own trace state holds it. Every frame dynamo traces
builds
VariableTrackerobjects, and a graph break leaves anUnspecializedNNModuleVariable->SideEffectsProxyDict->DunderDictVariablecycle that keeps the traced module reachable. Those cycles are unreachable
garbage, but reference counting cannot reclaim them, so after
optimize()+generate()the quantized model - and all of its VRAM - survived the last userreference until a full cyclic
gc.collect().Measured on this host (PG506 sm_80, Qwen2.5-0.5B GPTQ 4-bit g128, 8 new
tokens,
gc.disable()before the run,torch._dynamo.reset()betweenbackends, GiB allocated after the model was dropped):
GPTQ_TRITONGPTQ_TORCHMARLIN(
no optimize()is 0.000 for all three, before and after: the leak is thecompiled path only.)
What Changed
gptqmodel/utils/torch.pydynamo_traced_frames(): the number of framestorch.compilehas traced(
counters["frames"]["total"]), read throughsys.modulesso dynamo isnever imported for a model that was not compiled.
release_compile_trace_garbage(): onegc.collect(), documented asreclaiming only the unreachable trace cycles.
gptqmodel/models/base.py_CompiledModelForwardsamplesdynamo_traced_frames()when it isinstalled and, after each compiled call, collects only when that call
traced a new frame (
try/finally, so a failing call releases too). A callthat reuses dynamo's cache adds no frames and does nothing.
optimize()now sets thecompiledflag its docstring promises; it wasonly ever written as
False(initialisation and the no-compile branches).docs/generation-compile-policy.md: new "Releasing the compiled model"section with the mechanism and the measured numbers.
tests/test_optimize_dynamo_release_5020.py(new, 4 nodes).Dynamo's compiled-frame cache is deliberately not reset:
torch._dynamo.reset()would force a full recompile (65-95 s for this model) on the next call, which
would make a server that generates with varying prompt lengths recompile
forever. Collecting the unreachable cycles leaves the cache intact, and the
next call still takes the compiled path.
Perf check
The release fires once per newly traced frame, not per token:
generate(8)(first compile)generate#2)generate(48)(cache hit)Same run with the release disabled: 12.5-14.0 ms/token, i.e. within this shared
GPU's run-to-run spread. The second-generate recompile itself is dynamo's
normal dynamic-shape recompile: it happens identically with the release
disabled (30.3 s vs 30.3 s) and the third generate is 0.17 s vs 0.11 s.
Tests
tests/test_optimize_dynamo_release_5020.pyon unmodifiedorigin/main(
d6b4934ea, test copied into a separate worktree): 4 failed.test_optimize_reports_the_compiled_forward- thecompiledflag is neverwritten on the success path.
test_optimize_generate_does_not_pin_the_model[gptq_triton]and[gptq_torch]- "the compiled model survived its last reference with cyclicGC disabled: optimize() + generate() left dynamo trace cycles holding the
model ([MEM] #4986 (fix of #4937) incomplete: after optimize() + generate(), GPTQ_TRITON/GPTQ_TORCH models still keep 0.96/0.47 GiB VRAM until gc.collect() (dynamo graph-break trace state cycles); PR test is an 8x8 CPU Linear #5020)".
test_repeated_generate_does_not_accumulate- the model stays alive after asecond generate that re-traces decode frames for a new prompt length.
On this branch: 4 passed. The GPU nodes use a 4-layer SmolLM2-135M
quantized to GPTQ 4-bit on the CPU in a module-scoped fixture, assert a
weakref to the HF model is dead after the call frame returns, and also bound
the residual
memory_allocated()to 25% of the model's resident size (withgc.disable()for the whole window).Neighbouring suites (
test_optimize_no_reference_cycle_4937.py,test_optimize_generate_4669.py,test_quant_linear_release_4847.py,test_cpu_kernel_optimize.py,test_generate_attention_mask.py,kernels/test_compile_policy_levels_4984.py,kernels/test_kernel_compile_protocol.py): 64 passed, 169 skipped on bothorigin/mainand this branch (identical node sets).tests/test_docs_contract_refs.py:23 passed.
ruff checkclean on all changed Python files.Notes
gc.collect()on this process costs ~450-800 ms because the traceleaves ~320k objects in gen0. Generational collects are not cheaper (gen0:
696-789 ms, gen1: 578-596 ms, gen2: 626-818 ms) and all three free the model,
so the release uses the full collect, which also covers cycles promoted to
older generations.
test_optimize_no_reference_cycle_4937.pystill passes unchanged: theweakref proxy is untouched, only the trace garbage is now released.