Skip to content

[BUG] Cancelled or failed quantize() leaves the in-flight layer on the GPU: next forward raises a device mismatch and the layer's VRAM stays pinned (#4515 incomplete off-CPU) #4546

Closed

Description

@Qubitium

Found on main @ 4b65923, AMD R9700 (ROCm 10.1, torch 2.16 dev, CPython 3.14t with PYTHON_GIL=0). The bug is in device-agnostic looper code, so it should also happen on CUDA.

What is wrong

#4515 (fix for #4470) releases the subset capture hooks when a run is cancelled or fails, so that "the model never keeps a capture closure ... or raises StopForward on the next ordinary forward". The test for it (tests/test_subset_cancel_hook_cleanup_4470.py) runs only with device="cpu". On an accelerator the cancelled model still can't run a forward, for a related reason: the in-flight layer is left on the GPU.

The looper moves each subset's modules to the quantize device before the forward and moves the layer back to CPU only on the success path. ModuleLooper.loop()'s except BaseException handler (gptqmodel/looper/module_looper.py:1905-1913) restores the offloaded base modules and releases the offload root, but it never moves the current layer back. After StopMainLoop from subset_callback (the supported cancellation path), a KeyboardInterrupt, or any exception mid-layer:

  • every parameter and buffer of the current layer stays on cuda:0, while the embeddings, the other layers and lm_head are on CPU;
  • the next ordinary forward of model.model raises Expected all tensors to be on the same device;
  • the layer's VRAM stays allocated while the model lives (27 MiB for one Qwen2.5-0.5B layer; one Llama-3.1-8B layer is about 0.4 GiB in fp16).

Repro

import gzip, json, torch
from gptqmodel import GPTQModel
from gptqmodel.quantization import GPTQConfig
from gptqmodel.looper.module_looper import StopMainLoop

calib = [json.loads(l)["text"][:1500] for _, l in zip(range(16), gzip.open(
    "c4-train.00000-of-01024.json.gz", "rt"))]
m = GPTQModel.load("Qwen/Qwen2.5-0.5B-Instruct",
                   GPTQConfig(bits=4, group_size=128, offload_to_disk=False), dtype=torch.float16)

def cancel(**kw):   # supported cancellation hook (#4470 / #4515)
    if kw["stage"] == "forward_start" and kw["layer_idx"] == 3:
        return StopMainLoop
m.subset_callback = cancel
try:
    m.quantize(calib, batch_size=4)
except StopMainLoop as e:
    print("cancelled:", e)

on_gpu = sorted({n.rsplit(".", 1)[0] for n, p in [*m.model.named_parameters(), *m.model.named_buffers()] if p.device.type != "cpu"})
print("params left on accelerator:", len(on_gpu), on_gpu[:3], "...")
print("memory_allocated MiB:", torch.cuda.memory_allocated() // 2**20)
try:
    with torch.no_grad(): m.model(m.tokenizer("Hello world", return_tensors="pt").input_ids)
    print("forward OK")
except RuntimeError as e:
    print("forward failed:", e)

Output:

cancelled: Subset callback requested stop at layer 3 subset 0
params left on accelerator: 9 ['model.layers.3.input_layernorm', 'model.layers.3.mlp.down_proj', 'model.layers.3.mlp.gate_proj'] ...
memory_allocated MiB: 27
forward failed: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

The same happens when an exception or a KeyboardInterrupt is raised from GPTQ.quantize (monkeypatched to raise on its 10th call). All 9 modules of model.layers.1 stay on cuda:0, 22-26 MiB stay allocated, and the forward fails the same way. With a layer_callback that returns StopMainLoop (handled as a clean stop at a layer boundary) and with an uncancelled run, nothing is left on the GPU and the forward works. So only the mid-layer exit paths are affected.

Also checked after each failure mode, and these were clean: no hooks or forward_hook attributes left (#4515 works), the BLAS, TF32, BF16x3, HF-init and threadpool-limit guard depths are back to 0, and the default dtype, torch.get_num_threads(), grad mode and the init functions are restored.

Suggested fix

In ModuleLooper.loop()'s failure handler (or in a try/except BaseException around the per-layer body in stage_layer.py), move the in-flight layer back to its pre-run home (CPU, or the offload/meta placement) before re-raising, using the same step that post_quantize runs on success. Then extend test_subset_cancel_hook_cleanup_4470.py so that it runs on cuda when one is available and checks that every parameter and buffer is back on the model's home device.

Which test should have caught it

tests/test_subset_cancel_hook_cleanup_4470.py::_assert_plain_forward_still_works checks exactly this, but the test only runs with device="cpu", where the layer is never moved.

Severity

Medium-low. A cancelled or failed quantize() leaves a model that can't run an in-session forward, which is the contract #4470/#4515 set out to restore, and it pins one layer of VRAM until the model is dropped.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Claimed by an AI agent. Will reproduce on CPU, fix, add a focused regression test, and open a PR.

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