Skip to content

[MEM] #4871 (fix of #4847) incomplete: model.optimize() still leaves the whole model in a reference cycle (compiled bound forward stored on the instance); VRAM kept until gc.collect() #4937

Closed

Description

@Qubitium

Found on main @ 3867c82, RTX 4090, torch 2.15, transformers 5.22.

What is wrong

#4871 (fix of #4847) removed the reference cycles of a plain GPU load. TorchLinear.optimize() was rewritten so its compiled dequant no longer holds self. The model-level BaseQModel.optimize() still stores a compiled callable that wraps a bound method of the model on the model itself:

As a result, every model that a user calls optimize() on keeps all of its VRAM after the last reference is gone, until a full cyclic gc.collect() happens to run. This is the #4847 symptom, and it hits exactly the users who opt into the compiled path (optimize() is the documented opt-in for compiled generate(), see docs/generation-compile-policy.md).

Repro (Llama-3.2-1B-Instruct-GPTQ-4bits-gp128, gc disabled to make the cycle deterministic)

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

Output:

optimize=False: unreachable model still allocated 0.000 GiB -> after gc.collect() 0.000 GiB
optimize=True:  unreachable model still allocated 0.962 GiB -> after gc.collect() 0.000 GiB
backend no optimize optimize() (main) optimize() at 8bd9169^ (pre-#4912)
GPTQ_TRITON 0.000 0.962 GiB 0.962 GiB
MARLIN 0.000 0.957 GiB -
GPTQ_TORCH 0.000 0.963 GiB -

Isolation on main: calling only the per-kernel qlinear.optimize() releases cleanly (model weakref dead). Compiling only model.forward = torch_compile(model.forward) reproduces the full leak. gc.get_referrers(model) shows method <bound method LlamaForCausalLM.forward> and a closure cell holding the model.

Suggested fix

Do not store a callable that captures the bound method on the instance. Use the same approach #4871 used for TorchLinear.optimize: compile the unbound type(model).forward, and install an instance forward that reaches the module through a weakref (for example def forward(*a, **k): return compiled(ref(), *a, **k)). Keep the eager-fallback proxy in that weakref form too. A repeated optimize() should unwrap that proxy.

Test that should have caught it

tests/test_quant_linear_release_4847.py / tests/test_single_device_dispatch_4847.py cover only a plain load and TorchLinear.optimize() in isolation. Add a release check after BaseQModel.optimize() + generate() (gc disabled, weakref to model.model must be dead and memory_allocated back at baseline). tests/test_optimize_generate_4669.py would be a natural home.

Severity

Medium (memory): the same as #4847 for every optimize() user. A process that loads, optimizes, evaluates and then loads or quantizes the next model keeps the previous model resident (0.96 GiB for a 1B model, which scales with model size).

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Additional data on the same root cause (the compiled forward stored as an instance attribute by #4912), found on main @ 3867c82, RTX 5090 (sm_120): torch.save(model) regressed after optimize().

    Here the pickling side is a regression from #4912, not something carried over. Before #4912, self.model was an OptimizedModule, which pickles. Now model.__dict__["forward"] is the compile-fallback proxy of a bound method, and pickle refuses it:

    import io, copy, torch
    from gptqmodel import GPTQModel
    gm = GPTQModel.load("Qwen2.5-0.5B-Instruct-gptq-4bit", device="cuda:0")   # AUTO -> MarlinLinear
    torch.save(gm.model, io.BytesIO())        # OK
    gm.optimize(); gm.generate(...)
    torch.save(gm.model, io.BytesIO())
    before optimize() after optimize()
    main @ 3867c82 OK PicklingError: Can't pickle <function Qwen2ForCausalLM.forward at 0x...>: it's not the same object as transformers.models.qwen2.modeling_qwen2.Qwen2ForCausalLM.forward
    8bd91692e^ (pre-#4912) OK OK

    copy.deepcopy(gm.model) and gm.save() + reload still work after optimize().

    The kernels already honour this contract: BaseQuantLinear.__getstate__ -> compiled_module_getstate() drops compiled callables so that a model stays picklable after optimize() (#4070 item 5). The model-level forward is the one compiled callable it does not cover.

    Note on the suggested fix above: an instance forward closure that goes through a weakref fixes the cycle, but it is still a local function in __dict__, so pickle would still refuse it. The fix should also drop the instance forward when pickling. One way is a __reduce_ex__/__getstate__ hook installed on the model, or keeping the compiled callable outside __dict__, for example a class-level dispatch keyed by a weakref registry. tests/test_optimize_generate_4669.py should then also assert torch.save(model) after optimize().

    🤖 Generated with Claude Code

  2. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-53ba17eb4d83 finished this issue.

    Pull request: #4986

    Finish #4871 for the model level: BaseQModel.optimize() stores a compiled bound forward on the model, keeping the whole model in a reference cycle; compile an unbound/weak callable and add a no-gc VRAM release test.

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