Skip to content

[MEM] MACaQ default compile_flip leaves each Linear's flip working set in a frame cycle: 0.4-1.4 GiB still on GPU after quantize() until cyclic GC, +1.25 GiB peak on Llama-8B (sibling of #4747 that #4757 does not cover) #4801

Description

@Qubitium

Found on main @ d2060d4, RTX 4090 (sm_89, CUDA 13.2, torch 2.15, Python 3.14).

What is wrong

#4757 (fix for #4747) made every processor finalize() release its captured state, so GPTAQ/FOEM/AWQ now return from quantize() with ~0 MiB still allocated. MACaQ is the sibling that still does not. The leak is not in MacaqProcessor.finalize(). It comes from the default compile_flip=True path.

flip_refine_levels() (gptqmodel/quantization/macaq.py:452-505) calls _compiled_flip_sweep() (:432, torch.compile(_flip_sweep, dynamic=True)). Each compiled call leaves its whole Python stack in a reference cycle:

  • the Dynamo resume frames (torch_dynamo_resume_in__flip_sweep_at_402/412);
  • _flip_sweep, flip_refine_levels, macaq_quantize_weight, MacaqProcessor.quantize (:884).

Those frames hold the per-weight working set as CUDA tensors: signed_index (int64), hessian_weight_target/current, scale_element, the rotated_weight (fp32), and others. Python's cyclic GC frees them eventually, but nothing collects them deterministically. They therefore pile up during quantize(), which raises the peak, and some are still allocated when quantize() returns. This is the contract #4747 cites from docs/quantization-memory.md: memory should be released "without waiting for Python's cyclic garbage collector".

Referrer chain of a leftover tensor after quantize() (Qwen2.5-0.5B, [4864, 896] int64, found through gc.get_objects() / gc.get_referrers):

tensor <- tuple <- frame no_grad (torch/utils/_contextlib.py:157)
       <- frame flip_refine_levels (quantization/macaq.py:504)
       <- frame _compiled_flip_sweep (quantization/macaq.py:436)
       <- frame compile_wrapper (torch/_dynamo/eval_frame.py:1328)
       <- frame _flip_sweep (quantization/macaq.py:402)
       <- frame torch_dynamo_resume_in__flip_sweep_at_402 (quantization/macaq.py:412) ...

Removing the data-dependent early return at macaq.py:401-402, which is the visible graph break, does not stop it (896 -> 3233 MiB in the repro below), so the cycle comes from somewhere else in the compiled call.

Measured

memory_allocated() right after quantize() (no gc.collect(); the in-session model is on CPU), default MacaqConfig(), 32 C4 rows, bf16:

model after quantize() after gc.collect() max_memory_allocated during quantize
Qwen2.5-0.5B-Instruct, 3 layers 223-237 MiB 0
Llama-3.1-8B-Instruct, 2 layers (default) 358-1409 MiB (depends on when gen-2 GC last ran) 0 13398 MiB
same, gc.collect() after each flip_refine_levels call (monkeypatch) 0 0 12123 MiB (-1.25 GiB, -9.5%)
same, MacaqConfig(compile_flip=False) 0 0 16538 MiB (eager sweep is a different path)

For comparison, after #4757 the other processors measure as follows (Qwen 3-layer, same harness): GPTAQ 26.0 -> 0.0 MiB and AWQ 8.3 -> 0.004 MiB. GPTQ, FOEM, QQQ, Paro and GGUF all read 0.

Minimal repro (no model needed)

import gc, torch
from gptqmodel.quantization.macaq import flip_refine_levels

def one(out_f, in_f, compile_flip):
    g = torch.Generator(device="cuda").manual_seed(0)
    x = torch.randn(4 * in_f, in_f, device="cuda", generator=g)
    H = x.T @ x / x.shape[0] + 1e-2 * torch.eye(in_f, device="cuda")
    w = torch.randn(out_f, in_f, device="cuda", generator=g) * 0.02
    scale = torch.full((out_f, in_f), 0.01, device="cuda")
    idx = torch.randint(0, 15, (out_f, in_f), device="cuda", generator=g)
    flip_refine_levels(idx, scale, w, H, n_iters=4, fast=True, compile_flip=compile_flip)

for shape in [(4096, 4096), (14336, 4096), (4096, 14336)]:
    one(*shape, compile_flip=True); torch.cuda.synchronize()
    print(shape, torch.cuda.memory_allocated() / 2**20)   # every input is out of scope here
gc.collect(); print("gc", torch.cuda.memory_allocated() / 2**20)

Output:

compile_flip=True  fast=True : (4096,4096) 1040.2 MiB   (14336,4096) 2840.9 MiB   (4096,14336) 2840.9 MiB   after gc.collect(): 0.0
compile_flip=True  fast=False: (4096,4096)  912.1 MiB   ...
compile_flip=False (either)  : 0.0 MiB after every call

Suggested fix

  • Find and break the cycle inside the compiled call. For example, check whether a Dynamo/Inductor guard-failure or recompile exception keeps __traceback__ alive, or whether the compiled wrapper stores frames.
  • Until then, run one gc.collect() after each flip_refine_levels(..., compile_flip=True) in macaq_quantize_weight (macaq.py:611-614). One collection per Linear costs little next to 256 flip sweeps. On Llama-8B 2 layers it made the run faster (46 s vs 67 s), removed the post-quantize residue, and lowered the peak by 1.25 GiB.
  • Also consider gc.collect() in MacaqProcessor.finalize(). That would make the after-quantize() contract hold regardless of the cause.

Test that should have caught it

tests/test_processor_finalize_4747.py is CPU-only and structural (it checks that finalize() overrides chain to the base), so it cannot see this. A CUDA test should run the repro above, or a tiny MACaQ quantize(), and assert that torch.cuda.memory_allocated() returns to its baseline without gc.collect().

Severity

Low-medium (MEM). It costs 0.4-1.4 GiB of GPU memory held after every default MACaQ quantize() until cyclic GC, and +1.25 GiB (+10%) quantize peak on a Llama-8B layer. The amount scales with the largest Linear (about 2.8 GiB already after one 14336x4096 weight). Output is not affected.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

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

    Pull request: #4854

    Fixing: MACaQ compiled flip leaves frame cycles; release working set deterministically after each compiled sweep.

  2. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Claiming. Will collect the compiled sweep's frame cycle once per Linear at the call site in macaq_quantize_weight (the frames are still alive inside flip_refine_levels, so the collection cannot live there), plus a finalize() backstop, with a CPU-only test that pins the collection.

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