Skip to content

[BUG] #4470 only half fixed by #4515: failed quantize() returns while finalizers still run; they recreate the deleted offload run dir (orphaned bundles) and mutate the model after the exception #4595

Closed

Description

@Qubitium

Found on main @ 4b65923, AMD R9700 (ROCm 10.1, CPython 3.14t, PYTHON_GIL=0), and also on CPU.

What is wrong

#4470 reported two defects. #4515 closed it but fixes only the first one (subset capture hooks). The second one is still present on main: a failed quantize() returns while already-submitted submodule finalizers keep running in DEVICE_THREAD_POOL.

ModuleLooper.loop()'s except BaseException handler (gptqmodel/looper/module_looper.py:1905-1913) calls release_private_offload_root(), and its finally calls _release_run_workspace(). Neither of them first drains the pool or calls wait_dangling_threads(), which the success path does at :2196-2204. The finalizers then:

  • recreate the per-run offload directory that was just deleted and write that layer's packed bundles into it. model._private_offload_run_root and the weakref finalizer were already cleared, so nothing ever removes the directory, and every failed or cancelled run leaks one;
  • keep mutating the model (packing and module replacement) after quantize() has already raised to the caller, so caller code that runs right after the exception (retry, save, inspection) races with them.

Repro (real model, no injected delays)

import gzip, json, os, time, torch, shutil
from pathlib import Path
from gptqmodel import GPTQModel, DEVICE_THREAD_POOL
from gptqmodel.quantization import GPTQConfig
off = Path("offload_real"); shutil.rmtree(off, ignore_errors=True)
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=True, offload_to_disk_path=str(off)), dtype=torch.float16)
def cb(*, layer_idx, submodule_finalized):
    if layer_idx == 3 and not submodule_finalized:
        raise RuntimeError("user layer callback error")
m.layer_callback = cb
try:
    m.quantize(calib, batch_size=4)
except RuntimeError as e:
    print("quantize raised:", e)
def snap(tag):
    print(tag, "offload dir entries:", sorted(p.name for p in off.glob("*")) if off.exists() else "absent",
          "| index.json files:", len(list(off.rglob("index.json"))) if off.exists() else 0)
snap("at return  ")
time.sleep(10)
snap("after 10 s ")
DEVICE_THREAD_POOL.wait()
snap("after drain")

Output (2/2 runs):

quantize raised: user layer callback error
at return   offload dir entries: [] | index.json files: 0
after 10 s  offload dir entries: ['run-fa90275a29d24131'] | index.json files: 7
after drain offload dir entries: ['run-fa90275a29d24131'] | index.json files: 7

The original #4470 CPU repro (one-layer tiny Llama, finalizer delayed with an Event) still prints the same as in that report on this commit: ROOT_AT_EXCEPTION ... exists False, MODEL_ROOT_ATTRIBUTE None, then ROOT_AFTER_WORKERS exists True, INDEXES_AFTER_WORKERS 7, PRIVATE_FINALIZER None.

Suggested fix

In the failure branch of ModuleLooper.loop(), fence the run's outstanding work before tearing anything down: DEVICE_THREAD_POOL.wait() (or a run-scoped wait), self.wait_dangling_threads(), and STREAM_DEVICE_POOL.wait(), each in a try/finally so the original exception is still re-raised. Only then call release_private_offload_root() and _release_run_workspace(). Alternatively, have finalizers check a run-cancelled flag, and skip publishing and directory creation once the run has failed.

Which test should have caught it

tests/test_subset_cancel_hook_cleanup_4470.py only covers the hook half of #4470. The #4470 finalizer repro above could be added to it almost unchanged.

Severity

Medium-low. Disk leak of one layer's bundles per failed or cancelled run (unbounded across retries in a long-lived process), plus background mutation of the model after quantize() has raised.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Claimed. This issue is now owned by a dedicated worker; a fix PR referencing it will follow.

  2. added a commit that references this issue on Nov 22, 2026
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