Repository navigation
Description
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:
gptqmodel/models/base.py:3847-3854(added by fix(generate): make optimize() compile the forward generate() runs (#4669) #4912 for [PERF] generate(cache_implementation="static") is 2-4x SLOWER than eager on every default CUDA kernel (HF auto-compile graph-breaks on each quantized linear: no fake impls, data_ptr/id() guards); model.optimize() compiles nothing that generate() runs #4669):eager_forward = model.forward(bound method -> model). Thenmodel.forward = torch_compile(eager_forward), which is an instance attribute that wraps the bound method. The result is a cycle: model ->__dict__['forward']-> compiled wrapper / fallback closure -> bound method -> model.- Before fix(generate): make optimize() compile the forward generate() runs (#4669) #4912,
self.model = torch_compile(self.model)(_install_module_compile_fallback,utils/torch.py:458) leaked the same amount through theOptimizedModulepath. That makes this an incomplete [MEM] GPU-loaded models are reference cycles: VRAM is not released on del/scope exit until a full gc.collect() (1B: 0.96 GiB, 8B QQQ: 5.3 GiB); single-device loads install AlignDevicesHook on every layer #4847 fix, not a new regression from fix(generate): make optimize() compile the forward generate() runs (#4669) #4912. fix(generate): make optimize() compile the forward generate() runs (#4669) #4912 only changed which edge forms the cycle.
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
Qubitium commentedon Nov 17, 2026
Additional data on the same root cause (the compiled
forwardstored as an instance attribute by #4912), found onmain@ 3867c82, RTX 5090 (sm_120):torch.save(model)regressed afteroptimize().Here the pickling side is a regression from #4912, not something carried over. Before #4912,
self.modelwas anOptimizedModule, which pickles. Nowmodel.__dict__["forward"]is the compile-fallback proxy of a bound method, and pickle refuses it:optimize()optimize()main@ 3867c82PicklingError: Can't pickle <function Qwen2ForCausalLM.forward at 0x...>: it's not the same object as transformers.models.qwen2.modeling_qwen2.Qwen2ForCausalLM.forward8bd91692e^(pre-#4912)copy.deepcopy(gm.model)andgm.save()+ reload still work afteroptimize().The kernels already honour this contract:
BaseQuantLinear.__getstate__->compiled_module_getstate()drops compiled callables so that a model stays picklable afteroptimize()(#4070 item 5). The model-level forward is the one compiled callable it does not cover.Note on the suggested fix above: an instance
forwardclosure that goes through aweakreffixes the cycle, but it is still a local function in__dict__, so pickle would still refuse it. The fix should also drop the instanceforwardwhen 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.pyshould then also asserttorch.save(model)afteroptimize().🤖 Generated with Claude Code
Qubitium commentedon Nov 17, 2026
Agent claim released:
agent-53ba17eb4d83finished 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.
fix(models): compile the unbound forward so optimize() leaves no cycle (
fix(optimize): release dynamo's trace cycles so a compiled model free…