Skip to content

[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

Closed

Description

@Qubitium

Found on main @ c2b0bf6, RTX 4090 (torch 2.15 + CUDA 13.2, transformers 5.22).

What is wrong

#4986 (fix of #4937) compiles the unbound type(model).forward and reaches the model through a weakref (_CompiledModelForward, gptqmodel/models/base.py). That removed the bound-method cycle. But the #4937 symptom is still there for two of the three backends from the issue's table: after optimize() + generate(), the whole quantized model and its VRAM survive the last user reference until a full cyclic gc.collect().

The remaining holder is torch.compile's own trace state, not the forward attribute. gc.get_referrers(hf_model) after del shows only dynamo UnspecializedNNModuleVariable -> SideEffectsProxyDict -> DunderDictVariable objects in cycles. Dynamo leaves these behind when a compiled frame graph-breaks. The GPTQ Triton and Torch kernels graph-break, and Marlin does not, which matches the table below.

Repro (#4937's script, unchanged)

import gc, torch
from gptqmodel import GPTQModel, BACKEND
gc.collect(); gc.disable()
def f(be, opt):
    m = GPTQModel.load("Llama-3.2-1B-Instruct-GPTQ-4bits-gp128", device="cuda:0", backend=be)
    if opt: m.optimize()
    m.generate(torch.tensor([[128000, 791, 6864, 315, 9822, 374]], device="cuda:0"), max_new_tokens=8, do_sample=False)
for be in (BACKEND.GPTQ_TRITON, BACKEND.MARLIN, BACKEND.GPTQ_TORCH):
    f(be, False); a0 = torch.cuda.memory_allocated() / 2**30
    f(be, True);  a1 = torch.cuda.memory_allocated() / 2**30
    gc.collect(); a2 = torch.cuda.memory_allocated() / 2**30
    print(be, a0, a1, a2); torch._dynamo.reset()

GiB still allocated after the function returns:

backend no optimize optimize() on main (after #4986) after gc.collect() #4937 report (before #4986)
GPTQ_TRITON 0.000 0.963 0.000 0.962
MARLIN 0.000 0.000 0.000 0.957
GPTQ_TORCH 0.000 0.473 0.000 0.963

Tokens match eager in all cases.

Control with a dense HF model: Llama-3.2-1B-Instruct fp16, m.forward = _CompiledModelForward(torch.compile(type(m).forward), type(m).forward, m), one generate:

  • No graph break: the model object dies, but 1.81 GiB stays allocated until gc.collect().
  • One torch._dynamo.graph_break() in a layer hook: the model itself stays alive, with 2.30 GiB allocated, until gc.collect().

Why the PR test passes

tests/test_optimize_no_reference_cycle_4937.py uses an 8x8 nn.Linear on CPU with no quantized kernel and no graph break. That exercises only the bound-method cycle, not the real GPU path that #4937 reported.

Suggested fix

The leftover cycles live in dynamo, so the weakref proxy alone cannot free them. Options:

  • Make release explicit. For example, have BaseQModel expose a teardown that drops the compiled forward, calls torch._dynamo.reset(), and runs one gc.collect(). Alternatively, run gc.collect() once after the first compiled call, since dynamo's garbage exists from then on.
  • At minimum, document in optimize() that VRAM is only released after gc.collect().
  • Either way, the regression test should load a real GPTQ checkpoint on CUDA with a graph-breaking kernel (GPTQ_TRITON) and assert memory_allocated() returns to baseline with GC disabled.

Severity: medium. Serving code that swaps models after optimize() keeps the full previous model in VRAM until the next cyclic GC (0.96 GiB on 1B, proportionally more on large models).

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim: agent-root-5020 is working on this issue now.

  2. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-53ba17eb4d83 is no longer working on this issue.

    The issue is free to claim.

    duplicate: agent-root-5020 claimed first

  3. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent release: agent-root-5020 finished this issue. Fix: #5064, squash-merged as e3ec24309.

    _CompiledModelForward now samples dynamo_traced_frames() when it is installed and, after each compiled call, runs release_compile_trace_garbage() (one gc.collect()) only when that call traced a new frame. That reclaims dynamo's unreachable VariableTracker cycles while the caller still owns the model, so dropping the model frees its weights immediately with cyclic GC disabled. Dynamo's compiled-frame cache is deliberately left intact (torch._dynamo.reset() would force a full recompile), so the next call still takes the compiled path. optimize() also sets the compiled flag it documents; it was only ever written as False.

    Measured (PG506 sm_80, Qwen2.5-0.5B GPTQ 4-bit g128, 8 new tokens, gc.disable(), GiB allocated after the model was dropped): GPTQ_TRITON 0.432 -> 0.000, GPTQ_TORCH 0.432 -> 0.000, MARLIN 0.431 -> 0.000.

    Cost: one collect per newly traced frame (~450-800 ms), 3 on the first generate and 1 on dynamo's normal dynamic-shape recompile, i.e. ~1.8 s against 65-95 s of compile; a warm 48-token generate fires zero releases (13.8 ms/token, vs 12.5-14.0 ms/token with the release disabled on this shared GPU).

    New tests/test_optimize_dynamo_release_5020.py (4 nodes): red on unmodified main (4 failed - the model survives its last reference, and the compiled flag is never set on the success path), green after the fix. Neighbouring suites (test_optimize_no_reference_cycle_4937, test_optimize_generate_4669, test_quant_linear_release_4847, test_cpu_kernel_optimize, test_generate_attention_mask, kernels/test_compile_policy_levels_4984, kernels/test_kernel_compile_protocol): 64 passed / 169 skipped on both trees. test_docs_contract_refs: 23 passed (the torch_sync citation moved to the symbol form). Docs: docs/generation-compile-policy.md gained a "Releasing the compiled model" section.

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