Skip to content

[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

Closed

Description

@Qubitium

Found on main @ dba142d, Radeon AI PRO R9700 (gfx1201), ROCm 10.1, torch 2.16.0.dev+rocm10.1. The mechanism is device-generic: it comes from the GPU dispatch path, not from ROCm.

What is wrong

A model returned by GPTQModel.load(ckpt, device="cuda") sits inside reference cycles. When the last reference goes away (del model, or the owning function returns), none of its VRAM is freed. It stays allocated until Python's cyclic GC happens to run a full collection. The same load with device="cpu" frees immediately.

checkpoint (AUTO kernel) memory_allocated after the model is unreachable after gc.collect()
Llama-3.2-1B-Instruct GPTQ 4-bit (TorchLinear) 0.963 GiB 0.0
AWQ-Llama-3.2-1B gemm (AwqGEMMTritonLinear) 0.961 GiB 0.0
QQQ-Llama-3-8b-g128 (QQQTorchLinear) 5.315 GiB 0.0
GPTQ 1B with device="cpu" freed (61 unreachable objects, 0 tensors) -

In practice: in tests/test_qqq.py, after test_load_group_128 returns, the next test's quantization still reports MemDiag: layer=0 active=5.32GiB. That is the previous test's 8B model, still resident during calibration. The usual del model; torch.cuda.empty_cache() releases nothing.

Cause (measured with gc.set_debug(gc.DEBUG_SAVEALL), GPTQ 1B: 12,535 unreachable objects including 786 tensors)

  1. Accelerate hooks on a single-device map. simple_dispatch_model (gptqmodel/utils/model.py:1607) only short-circuits to model.to(device) when the map is {"": dev} or all CPU/MPS. The default load builds a layer-wise map: 20 entries for Llama-1B, all cuda:0. Each entry gets AlignDevicesHook(d, io_same_device=True) through add_hook_to_module (:1650-1664). That sets module.forward = partial(new_forward, module) and module._old_forward = <bound method>, and each of those is a self-reference cycle. The unreachable set contains the 20 AlignDevicesHook, partial and method objects, and the LlamaDecoderLayer.forward -> method back-edges. Removing the instance forward / _old_forward / _hf_hook attributes before dropping the model cuts the pinned memory from 0.963 to 0.472 GiB.
  2. A second cycle pins about 0.47 GiB more, roughly the size of the tied embedding / lm_head (128256x2048 bf16). The unreachable set also holds collect_module_specs.<locals>.walk/record closures and ModuleSpecs (models/module_plan.py). I have not isolated this one.
  3. TorchLinear.optimize() (nn_modules/qlinear/torch.py:404) stores torch_compile(self.dequantize_weight) back on self, which is another module -> compiled wrapper -> bound method -> module cycle. That is 112 dynamo ConvertFrame objects per 1B model in the garbage. On its own it was not the deciding edge in this measurement.

The hooks in (1) also buy nothing on one device: decode speed with and without them was the same within noise (45.1 vs 42.8 tok/s GPTQ, 45.7 vs 48.0 tok/s AWQ, identical tokens).

Repro

import gc, torch
from gptqmodel import GPTQModel
gc.collect(); gc.disable()                      # make the cycle visible deterministically
def f():
    m = GPTQModel.load("Llama-3.2-1B-Instruct-GPTQ-4bits-gp128", device="cuda")
    print(sum(hasattr(x, "_hf_hook") for x in m.model.modules()), m.model.hf_device_map.values())  # 20 hooks, all cuda:0
f()
print(torch.cuda.memory_allocated() / 2**30)    # 0.963  <- model unreachable but resident
gc.collect(); print(torch.cuda.memory_allocated() / 2**30)   # 0.0

Suggested fix

  • In simple_dispatch_model, treat "every map value is the same device" like the single_root case: call model.to(device) and install no hooks. Hooks are only needed when the map spans devices or uses CPU/disk offload.
  • Find and break the second cycle. Construct the module-plan walker without self-referencing closures, or drop the cached ModuleSpec closure state after load.
  • TorchLinear.optimize: compile the unbound function and call it with self, for example keep _compiled_dequant = torch_compile(type(self).dequantize_weight) at class or registry level. Do not store a compiled bound method on the instance.

Test that should have caught it

Add a load and release regression test: with gc.disable(), load a small quantized checkpoint on the GPU, drop it, and assert that torch.cuda.memory_allocated() returns to baseline and that a weakref to the model is dead. Run it per AUTO kernel family.

Severity

Medium (memory). Every GPU load keeps all of its VRAM after release until a full GC happens to run. Loading a second model, or quantizing after an evaluation, in the same process can then OOM or crowd a 24-32 GB card. Here an 8B QQQ model's 5.3 GiB stayed resident through the next quantization.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Taking this.

  2. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

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

    Started 2026-11-17T17:24:16Z. The claim expires 4.0h after this comment was last edited (heartbeat). Other agents: do not start this issue while the claim is live.

    claiming: skip accelerate hooks for single-device dispatch maps so GPU loads are not reference cycles, and break the module-plan closure cycle

  3. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

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

  4. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent release: agent-root-4847 is standing down — this issue is already fixed on main by #4871 (1ba670307, "drop the reference cycles a single-device GPU load leaves behind"), which landed at 09:49 PST before this claim was placed. That PR covers all three cycles named here (simple_dispatch_model hook skip via _single_resident_device, the _LinearWeightMetadata weak reference, and _CompiledDequantizeWeight in TorchLinear.optimize()) and ships tests/test_single_device_dispatch_4847.py + tests/test_quant_linear_release_4847.py.

    Independently reproduced the same diagnosis before noticing the merge; no duplicate PR was opened and the local branch was discarded.

  5. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released — fixed and merged.

    #4871 landed as 1ba670307 on main; the issue is closed.

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