Skip to content

[BUG] Failed quantization retains capture hooks and releases offload storage before finalizers finish #4470

Closed

Description

@devin-ai-integration

Describe the bug

At 0b94d79c67, the cases below violate the stated supported contract. The validation scope for each case is explicit; source/dispatch proofs are not device numerical qualification.

Subset cancellation leaves active capture hooks and an early-stop flag on the model

Severity: P2

Contract and impact

A subset capture scope must release all hook handles, HookedLinear.forward_hook assignments and forward_hook_last flags on every exit, including supported StopMainLoop cancellation.

After a supported callback stop, the otherwise valid model cannot perform an ordinary forward: a stale last-projection hook raises StopForward. The installed hook closures also retain processor/looper state while the model is retained.

To reproduce / evidence

Set qmodel.subset_callback to return StopMainLoop at stage="forward_start", then call quantize() and catch the stop. The same success-only cleanup gap applies to a real forward exception before cleanup.

Actual public quantize() path; local random one-layer 32-hidden Llama, eight tokens, offload enabled, AUTO dtype conversion disabled. No model download. Save the following as reproduce_hooks.py and run PYTHONPATH= python reproduce_hooks.py. Python 3.14.6 free-threaded, Torch 2.15.0+cpu, Transformers 5.23.0; no CUDA/ROCm/MLX hardware.

"""Exercise actual tiny CPU quantize callback cancellation."""
from pathlib import Path
import tempfile, threading, time
import torch
from tokenizers import Tokenizer, models
from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
from gptqmodel import BACKEND, DEVICE_THREAD_POOL
from gptqmodel.models.definitions.llama import LlamaQModel
from gptqmodel.quantization import QuantizeConfig
from gptqmodel.quantization.config import AutoDtypeCast
from gptqmodel.looper.gptq_processor import GPTQProcessor

torch.set_num_threads(1)
work = Path(tempfile.mkdtemp(prefix='audit-finalizers-'))
source = work / 'source'
config = LlamaConfig(vocab_size=32, hidden_size=32, intermediate_size=64,
    num_hidden_layers=1, num_attention_heads=4, num_key_value_heads=4,
    max_position_embeddings=32, bos_token_id=1, eos_token_id=2, pad_token_id=0)
config._attn_implementation = 'eager'
model = LlamaForCausalLM(config).eval()
model.save_pretrained(source)
tok = Tokenizer(models.WordLevel({'[PAD]':0, '[UNK]':1, 'a':2}, unk_token='[UNK]'))
tokenizer = PreTrainedTokenizerFast(tokenizer_object=tok, pad_token='[PAD]', unk_token='[UNK]')
qmodel = LlamaQModel(model=model, quantized=False, tokenizer=tokenizer,
    quantize_config=QuantizeConfig(bits=4, group_size=32, desc_act=False,
        device='cpu', offload_to_disk=True, offload_to_disk_path=str(work/'offload'),
        auto_dtype_cast=AutoDtypeCast.OFF), model_local_path=str(source))

from gptqmodel.looper.module_looper import StopMainLoop
def cancel(**kwargs):
    if kwargs['stage'] == 'forward_start':
        return StopMainLoop
qmodel.subset_callback = cancel
try:
    qmodel.quantize([{'input_ids':[1,3,5,7,9,11,13,15], 'attention_mask':[1]*8}],
        batch_size=1, backend=BACKEND.GPTQ_TORCH, calibration_data_min_length=1)
except Exception as exc:
    print('QUANTIZE_EXCEPTION', type(exc).__name__, str(exc), flush=True)
for name, module in qmodel.model.named_modules():
    if callable(getattr(module, 'forward_hook', None)):
        print('STALE_HOOK', name, 'stop_flag', module.forward_hook_last, flush=True)
try:
    qmodel.model(input_ids=torch.tensor([[1,3,5,7]]))
    print('POST_CANCEL_FORWARD_OK', flush=True)
except Exception as exc:
    print('POST_CANCEL_FORWARD_EXCEPTION', type(exc).__name__, str(exc), flush=True)

Observed and expected behavior

Observed QUANTIZE_EXCEPTION StopMainLoop; q_proj/k_proj/v_proj retain callable forward_hook, v_proj.forward_hook_last=True; qmodel.model(input_ids=[[1,3,5,7]]) raises StopForward("Forwarding stopped"). Expected no capture hooks/stop flags remain after scope exit, and ordinary inference runs.

Public source and history

Hook installation and stop flag:

if execute_forward:
for idx, name in enumerate(subset_names):
m = subset[name]
# Register the forward hook that captures activations for quantization.
# The final module optionally flips a flag so processors can trigger
# once-per-subset logic after the forward pass.
is_last = idx == subset_size - 1
hook_source = getattr(m, "full_name", None)
if hook_source is None:
hook_source = getattr(m, "name", name)
if hook_source is None:
hook_source = str(name)
# Determine if this module is part of MoE block (needs pre-hook to avoid StopForward)
is_moe_module = moe_block_name and name.startswith(moe_block_name + ".")
if hasattr(subset[name], "forward_hook"):
original_hook = processor.pre_process_fwd_hook(name)
# Use pre-hook for MoE modules to fire before StopForward
if is_moe_module:
subset[name].forward_hook = looper._masked_pre_hook_wrapper(
processor, original_hook, hook_source
)
else:
subset[name].forward_hook = looper._masked_hook_wrapper(
processor, original_hook, hook_source
)
enable_stop = (
forward.replay_after_process
or forward.subset_early_stop
)
if is_last and enable_stop:
subset[name].forward_hook_last = True
else:
original_hook = processor.pre_process_fwd_hook(name)
# Use pre-hook registration for MoE modules
if is_moe_module:
handle.append(
subset[name].register_forward_hook(
looper._masked_pre_hook_wrapper(
processor, original_hook, hook_source
)
)
)
else:
handle.append(
subset[name].register_forward_hook(
looper._masked_hook_wrapper(
processor, original_hook, hook_source
)
)
; callback before the forward cleanup scope:
if execute_forward:
if subset_event_cb:
subset_event_cb(
stage="forward_start",
layer_idx=layer_index,
subset_index=subset_index,
subset_total=subset_total,
module_names=subset_names,
processor=getattr(processor, "name", type(processor).__name__),
)
fwd_start = time.perf_counter()
reuse_kv = bool(getattr(module, "reuse_kv", False))
; success-only removal:
for h in handle:
# Detach temporary hooks to avoid leaking state into future passes.
h.remove()
if execute_forward:
for name in subset_names:
# Reset inline hook attributes on NamedModule wrappers so future passes
# do not reuse state from this subset run.
if hasattr(subset[name], "forward_hook"):
subset[name].forward_hook = None
subset[name].forward_hook_last = False
; public callback resolution and StopMainLoop return handling:
def _resolve_subset_callback(self):
"""Resolve the active subset callback from looper or model state."""
for candidate in (
getattr(self, "_subset_callback", None),
getattr(self, "subset_callback", None),
getattr(self.gptq_model, "subset_callback", None),
):
if candidate is not None:
return candidate
return None
def callbackup(self, layer_idx: int, submodule_finalized: bool):
"""Invoke the layer callback and normalize stop-loop responses."""
callback = self._resolve_layer_callback()
if callback is None:
return None
handler = getattr(callback, "layer_complete", None)
if handler is None and callable(callback):
handler = callback
if handler is None:
return None
try:
result = handler(layer_idx=layer_idx, submodule_finalized=submodule_finalized)
except StopMainLoop:
raise
if result is StopMainLoop:
raise StopMainLoop(f"Layer callback requested stop at layer {layer_idx}")
if isinstance(result, StopMainLoop):
raise result
return result
def _subset_event_dispatch(
self,
*,
stage: str,
layer_idx: int,
subset_index: int,
subset_total: int,
module_names: List[str],
processor: str,
) -> None:
"""Emit a subset event immediately and surface callback failures."""
self._emit_subset_event(
stage=stage,
layer_idx=layer_idx,
subset_index=subset_index,
subset_total=subset_total,
module_names=module_names,
processor=processor,
raise_in_place=True,
)
def _request_loop_stop(self, exc: Optional[BaseException]) -> None:
"""Record the first stop reason and signal loop shutdown."""
with self.lock:
if self._loop_stop_exc is None and exc is not None:
self._loop_stop_exc = exc
self._loop_stop_event.set()
def _check_loop_stop(self) -> bool:
"""Drain outstanding work and re-raise any recorded stop signal."""
if not self._loop_stop_event.is_set():
return False
if not self._loop_stop_waited:
DEVICE_THREAD_POOL.wait()
self._loop_stop_waited = True
if self._loop_stop_exc is not None:
raise self._loop_stop_exc
return True
def _emit_subset_event(
self,
*,
stage: str,
layer_idx: int,
subset_index: int,
subset_total: int,
module_names: List[str],
processor: str,
raise_in_place: bool,
) -> None:
"""Forward a subset lifecycle event to the configured callback."""
callback = self._resolve_subset_callback()
if callback is None:
return
handler = getattr(callback, "subset_event", None)
if handler is None and callable(callback):
handler = callback
if handler is None:
return
try:
result = handler(
stage=stage,
layer_idx=layer_idx,
subset_index=subset_index,
subset_total=subset_total,
module_names=module_names,
processor=processor,
)
except StopMainLoop as exc:
self._request_loop_stop(exc)
if raise_in_place:
raise
return
except BaseException as exc:
# Only the swallowed path needs a record: when the caller asked for
# in-place propagation the exception reaches it unchanged, so logging
# here would double-report it and would mislabel a user Ctrl-C as a
# callback bug. Note `_emit_layer_complete` does not latch a stop on
# this path, so this is stricter than its sibling, not identical.
if raise_in_place:
self._request_loop_stop(exc)
raise
log.warning(
"Subset callback raised (stage=%s, layer=%s, subset=%s/%s)",
stage,
layer_idx,
subset_index,
subset_total,
exc_info=True,
)
self._request_loop_stop(exc)
return
if result is StopMainLoop:
exc = StopMainLoop(f"Subset callback requested stop at layer {layer_idx} subset {subset_index}")
self._request_loop_stop(exc)
if raise_in_place:
raise exc
return
if isinstance(result, StopMainLoop):
self._request_loop_stop(result)
if raise_in_place:
raise result
return
; outer failure cleanup never clears subset hooks:
def loop(self, fallback=None, **kwargs):
"""Run the quantization loop under the TF32 guard."""
with tf32_high_precision_guard():
try:
result = self._loop_impl(fallback=fallback, **kwargs)
except BaseException:
# A failed run must not leave the base modules stranded on meta.
try:
self._restore_offloaded_base_modules(strict=False)
finally:
# A failed run cannot be saved, so its per-run offload
# bundles are no longer reachable (issue #4368).
release_private_offload_root(self.gptq_model)
raise
finally:
# Process-wide scratch (e.g. EXL3's per-stream tile buffers)
# outlives the model unless the run releases it, and a failed
# run must release it too.
self._release_run_workspace()

The public subset-callback trigger was added in ee9a956 (PR #2172, 2025-11-04). The underlying success-only hook cleanup is already visible in 6f1fbc5 (PR #2123, 2025-10-27). This is an old latent defect, present at both audit baseline and previous audit HEAD. 771b1e0 (#3600) reformats an existing forward_start callback; it did not introduce that callback.

Existing reports

Searched public OPEN and CLOSED hook/subset/cancellation reports. No exact duplicate established. #4078 is related cleanup work for StopForward tracebacks and worker references; it does not fix installed subset hooks.

Software / device info and validation limits

Executed real CPU quantize(), not AST-extracted numerical code or a model mock. Cancellation is exercised before the first subset forward. No GPU quality, memory-scale or accelerator-numerics claim.

Failed quantization releases the offload root before queued finalizers finish and recreate it

Severity: P2

Contract and impact

No run-owned directory or scratch may be released until every already-submitted finalizer using it is quiescent; a failed run must not leave an ownerless recreated root.

A layer callback failure leaves run-uuid directories containing finalized model bundles after quantize() has returned. The model root attribute and weakref cleanup owner were already cleared, so the directory is no longer reclaimed by normal model teardown. A concurrent deletion can also race a finalizer reading/writing the same root; only the orphan-directory outcome is directly reproduced.

To reproduce / evidence

GPTQ quantize with offload_to_disk=True and a layer_callback that raises an ordinary RuntimeError at submodule_finalized=False, after finalizers are submitted and before their watcher/drain is established. The no-checkpoint path is sufficient.

Real quantize() and real GPTQProcessor.submodule_finalize; only worker scheduling is delayed by threading.Event. Save as reproduce_finalizers.py and run PYTHONPATH= python reproduce_finalizers.py. Python 3.14.6 free-threaded, Torch 2.15.0+cpu, Transformers 5.23.0; no CUDA/ROCm/MLX hardware.

"""Exercise actual tiny quantize with a delayed real CPU finalizer."""
from pathlib import Path
import tempfile, threading, time
import torch
from tokenizers import Tokenizer, models
from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
from gptqmodel import BACKEND, DEVICE_THREAD_POOL
from gptqmodel.models.definitions.llama import LlamaQModel
from gptqmodel.quantization import QuantizeConfig
from gptqmodel.quantization.config import AutoDtypeCast
from gptqmodel.looper.gptq_processor import GPTQProcessor

torch.set_num_threads(1)
work = Path(tempfile.mkdtemp(prefix='audit-finalizers-'))
source = work / 'source'
config = LlamaConfig(vocab_size=32, hidden_size=32, intermediate_size=64,
    num_hidden_layers=1, num_attention_heads=4, num_key_value_heads=4,
    max_position_embeddings=32, bos_token_id=1, eos_token_id=2, pad_token_id=0)
config._attn_implementation = 'eager'
model = LlamaForCausalLM(config).eval()
model.save_pretrained(source)
tok = Tokenizer(models.WordLevel({'[PAD]':0, '[UNK]':1, 'a':2}, unk_token='[UNK]'))
tokenizer = PreTrainedTokenizerFast(tokenizer_object=tok, pad_token='[PAD]', unk_token='[UNK]')
qmodel = LlamaQModel(model=model, quantized=False, tokenizer=tokenizer,
    quantize_config=QuantizeConfig(bits=4, group_size=32, desc_act=False,
        device='cpu', offload_to_disk=True, offload_to_disk_path=str(work/'offload'),
        auto_dtype_cast=AutoDtypeCast.OFF), model_local_path=str(source))
entered, release = threading.Event(), threading.Event()
original_finalize = GPTQProcessor.submodule_finalize
def delayed_finalize(self, module, model, **kwargs):
    entered.set()
    assert release.wait(30), 'finalizer release timeout'
    return original_finalize(self, module, model, **kwargs)
GPTQProcessor.submodule_finalize = delayed_finalize
def callback(*, layer_idx, submodule_finalized):
    if not submodule_finalized:
        assert entered.wait(10), 'no finalizer started'
        print('CALLBACK_FINALIZER_PENDING', flush=True)
        raise RuntimeError('audit layer callback error')
qmodel.layer_callback = callback
run_root = None
try:
    qmodel.quantize([{'input_ids':[1,3,5,7,9,11,13,15], 'attention_mask':[1]*8}],
        batch_size=1, backend=BACKEND.GPTQ_TORCH, calibration_data_min_length=1)
except Exception as exc:
    print('QUANTIZE_EXCEPTION', type(exc).__name__, str(exc), flush=True)
    run_root = Path(qmodel.quantize_config.offload_to_disk_path)
    print('ROOT_AT_EXCEPTION', run_root, 'exists', run_root.exists(), flush=True)
    print('MODEL_ROOT_ATTRIBUTE', getattr(qmodel, '_private_offload_run_root', None), flush=True)
finally:
    release.set()
    DEVICE_THREAD_POOL.wait()
    GPTQProcessor.submodule_finalize = original_finalize
if run_root is not None:
    print('ROOT_AFTER_WORKERS', 'exists', run_root.exists(), flush=True)
    print('INDEXES_AFTER_WORKERS', len(list(run_root.rglob('index.json'))), flush=True)
    print('PRIVATE_FINALIZER', getattr(qmodel, '_private_offload_run_finalizer', None), flush=True)

Observed and expected behavior

Observed CALLBACK_FINALIZER_PENDING, then RuntimeError. At exception: run root exists=False and model._private_offload_run_root=None. Release the worker event and call DEVICE_THREAD_POOL.wait(): root exists=True with seven index.json bundles, while _private_offload_run_finalizer=None. Expected quantize() error handling first drains submitted work, then deletes the root; once quantize() returns the root must stay absent.

Public source and history

Finalizers submitted before raise-in-place callback:

for index, (process, module, module_label, target_dev, layer_idx) in enumerate(finalize_tasks, start=1):
# Schedule finalize work on the device thread pool so CPU
# bound tasks do not stall the main orchestration loop.
future = DEVICE_THREAD_POOL.submit(
target_dev,
_finalize_on_worker,
process,
module,
index,
finalize_count,
module_label,
layer_idx,
)
finalize_futures.append((future, index, module_label, process, layer_idx))
boundary_futures.append(future)
finalize_futures_snapshot = list(finalize_futures)
looper._emit_layer_complete(
layer_idx=layer_index,
submodule_finalized=False,
raise_in_place=True,
)
; worker writes disk_path captured before teardown:
if key is not None:
looper._module_device_map[key] = CPU
target_dev = CPU
module_label = getattr(module, "full_name", getattr(module, "name", ""))
layer_idx = getattr(module, "layer_index", None)
finalize_tasks.append((reverse_p, module, module_label, target_dev, layer_idx))
finalize_count = len(finalize_tasks)
finalize_futures = []
finalize_pb = log.pb(range(finalize_count)).manual().set(show_left_steps=False)
@torch.inference_mode()
def _finalize_on_worker(process, module, idx, total, module_label, layer_idx):
"""Runs processor finalization and optional disk offload for one module."""
resolved_label = module_label or getattr(module, "full_name", getattr(module, "name", ""))
start = time.perf_counter() if region_timer is not None else None
try:
with log_time_block(
"submodule_finalize",
logger=log,
module_name=resolved_label,
):
process.submodule_finalize(module, looper.gptq_model)
# Disk offload (lifecycle TODO note preserved)
if isinstance(process, (GPTQProcessor, QQQProcessor, AWQProcessor, ParoQuantProcessor)):
quant_config = getattr(looper.gptq_model, "quantize_config", None)
if quant_config and getattr(quant_config, "offload_to_disk", False):
offload_path = getattr(quant_config, "offload_to_disk_path", None)
if offload_path:
module_full_name = getattr(module, "full_name", None)
if module_full_name not in requant_endpoint_names:
target_module = (
looper.gptq_model.model.get_submodule(module_full_name)
if module_full_name
else module
)
offload_start = time.perf_counter() if region_timer is not None else None
with log_time_block(
"disk_offload",
logger=log,
module_name=resolved_label,
):
offload_to_disk(
model=looper.gptq_model.model,
module=target_module,
disk_path=offload_path,
# The on-disk bundle is the only record a
# resumed run can restore from, so never
# skip it for small modules.
force=True,
)
if region_timer is not None and offload_start is not None:
region_timer.record(
"submodule_finalize_offload",
time.perf_counter() - offload_start,
source=resolved_label,
)
else:
log.warning(
"Skipping disk offload for %s: no offload path configured",
; outer error path deletes root and releases scratch without a drain:
def loop(self, fallback=None, **kwargs):
"""Run the quantization loop under the TF32 guard."""
with tf32_high_precision_guard():
try:
result = self._loop_impl(fallback=fallback, **kwargs)
except BaseException:
# A failed run must not leave the base modules stranded on meta.
try:
self._restore_offloaded_base_modules(strict=False)
finally:
# A failed run cannot be saved, so its per-run offload
# bundles are no longer reachable (issue #4368).
release_private_offload_root(self.gptq_model)
raise
finally:
# Process-wide scratch (e.g. EXL3's per-stream tile buffers)
# outlives the model unless the run releases it, and a failed
# run must release it too.
self._release_run_workspace()
; normal-path drains:
self._check_loop_stop()
# Ensure ANY remaining tasks the looper submitted have drained
DEVICE_THREAD_POOL.wait() # same as wait('all')
# Drain any watcher threads tracking submodule finalization progress.
self.wait_dangling_threads()
# Ensure any background stream sync tasks complete before returning.
from ..utils.stream import STREAM_DEVICE_POOL
STREAM_DEVICE_POOL.wait()
self._check_loop_stop()
; exceptional outer drain is conditional on checkpoint extensions:
# Keep the run lease until every worker has stopped accessing
# the attempt directory, including exceptional/stop exits.
if extension is not None:
try:
DEVICE_THREAD_POOL.wait()
module_looper.wait_dangling_threads()
finally:
self.model.config.use_cache = use_cache
def _quantize_weight_only(
self,
*,
checkpoint=None,
calibration,
; release detaches owner and clears root:
def release_private_offload_root(model: nn.Module) -> Optional[str]:
"""Remove the private offload directory bound to ``model``, if any.
The directory is only deleted after the caller has finished reading its
bundles (save) or after the run failed. Keeping the explicit path's parent
intact means other runs and the caller's own files are untouched.
"""
finalizer = getattr(model, "_private_offload_run_finalizer", None)
if finalizer is not None:
try:
finalizer.detach()
except Exception: # pragma: no cover - defensive
pass
try:
model._private_offload_run_finalizer = None
except Exception: # pragma: no cover - defensive
pass
run_root = getattr(model, "_private_offload_run_root", None)
if not run_root:
return None
try:
model._private_offload_run_root = None
except Exception: # pragma: no cover - defensive
pass
_remove_private_offload_root(run_root)
log.debug("Offload: released private run directory `%s`.", run_root)

a427804 (PR #4409, 2026-11-16T13:06:38Z) added root deletion to ModuleLooper.loop() error handling without fencing pending workers. The finalizer/callback ordering predates that change. f14d189 later adds release_run_workspace() to the same unfenced finally; this is an additional affected resource, not a separately measured scratch failure.

Existing reports

Related closed #4368 requested run-directory cleanup. Its helper/synchronous failure tests do not cover pending real finalizers. #4182 and #4242 (comment) establish drain-before-reraise in other worker loops, so this is a remaining caller gap rather than that fix being removed. No exact published race duplicate established.

Software / device info and validation limits

Real one-layer hidden_size=32 CPU Llama quantization, eight tokens, seven real finalizers; threading.Event delays scheduling only. Event timeouts bound a failed probe. No accelerator behavior, workspace corruption or large-model disk-growth measurement claimed.

Model / datasets

The evidence uses tiny synthetic tensors or local fixtures derived from the public tests; no private model or dataset is required. Device execution that remains untested is stated above.

Activity

  1. added
    bug
    on Nov 16, 2026
  2. Qubitium commented on Nov 17, 2026

    @Qubitium
    Collaborator

    Taking this. I'll investigate against current main, add a targeted regression test, and open a PR. Will report back here if the claim turns out to be invalid or already fixed.

  3. Qubitium commented on Nov 17, 2026

    @Qubitium
    Collaborator

    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

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions