Skip to content

fix(optimize): release dynamo's trace cycles so a compiled model frees its VRAM (#5020) - #5064

Merged
Qubitium merged 1 commit into
mainfrom
root/optimize-dynamo-release-5020
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
root/optimize-dynamo-release-5020

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Fixes #5020. #4986 (the fix for #4937) removed the
model -> forward -> model cycle from optimize() by compiling the unbound
type(model).forward behind a weak reference. The model was still pinned
afterwards: torch.compile's own trace state holds it. Every frame dynamo traces
builds VariableTracker objects, and a graph break leaves an
UnspecializedNNModuleVariable -> SideEffectsProxyDict -> DunderDictVariable
cycle 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 user
reference 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() between
backends, GiB allocated after the model was dropped):

backend before this PR after this PR
GPTQ_TRITON 0.432 0.000
GPTQ_TORCH 0.432 0.000
MARLIN 0.431 0.000

(no optimize() is 0.000 for all three, before and after: the leak is the
compiled path only.)

What Changed

  • gptqmodel/utils/torch.py
    • dynamo_traced_frames(): the number of frames torch.compile has traced
      (counters["frames"]["total"]), read through sys.modules so dynamo is
      never imported for a model that was not compiled.
    • release_compile_trace_garbage(): one gc.collect(), documented as
      reclaiming only the unreachable trace cycles.
  • gptqmodel/models/base.py
    • _CompiledModelForward samples dynamo_traced_frames() when it is
      installed and, after each compiled call, collects only when that call
      traced a new frame (try/finally, so a failing call releases too). A call
      that reuses dynamo's cache adds no frames and does nothing.
    • optimize() now sets the compiled flag its docstring promises; it was
      only 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:

run releases time
cold generate(8) (first compile) 3 1.34 s total (~450 ms each) out of 65-70 s
first dynamic-shape recompile (generate #2) 1 ~450 ms out of 30 s
warm generate(48) (cache hit) 0 13.8 ms/token

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.py on unmodified origin/main
(d6b4934ea, test copied into a separate worktree): 4 failed.

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 (with
gc.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 both
origin/main and this branch (identical node sets). tests/test_docs_contract_refs.py:
23 passed. ruff check clean on all changed Python files.

Notes

  • A full gc.collect() on this process costs ~450-800 ms because the trace
    leaves ~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.py still passes unchanged: the
    weakref proxy is untouched, only the trace garbage is now released.

…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.
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