Skip to content

[BUG] #4515 (fix of #4470) incomplete: stopping quantize() at the forward_end subset stage (StopMainLoop, exception or Ctrl-C) leaves capture hooks with forward_hook_last=True; every later forward raises StopForward #5009

Closed

Description

@Qubitium

Found on main @ c2b0bf6, RTX 4090 (also reproduces with the model on CPU between layers; default offload_to_disk=True).

What is wrong

#4515 (fix of #4470) made the subset stage release its capture hooks on every exit path, so that "the model never keeps a capture closure that retains the processor state or raises StopForward on the next ordinary forward" (gptqmodel/looper/stage_subset.py, _release_capture_hooks docstring). It covers the forward_start callback (line ~1217), the device-override step (~1250) and the forward itself (~1335), but not the tail of the stage that runs after the forward and before the success-path release at line 1488:

# stage_subset.py, _run_single_subset_pass, after the guarded forward
    if execute_forward and capture_layer_forward_context:
        processor.receive_layer_forward_context(...)          # unguarded
    if execute_forward and plan.need_forward_outputs:
        processor.receive_layer_inputs(forward_outputs)       # unguarded
    if execute_forward and subset_event_cb:
        subset_event_cb(stage="forward_end", ...)             # unguarded  <- StopMainLoop / exception / Ctrl-C
    ...
    _release_capture_hooks()                                  # line 1488, never reached

When the forward_end subset callback stops the run (returns StopMainLoop, the documented way to abort the loop, or raises), or a KeyboardInterrupt / failure lands anywhere in that window, the in-flight layer keeps its capture hooks. ModuleLooper.loop()'s failure cleanup (#4546/#4860/#4947) restores devices and kernels but never clears forward_hook. The in-flight layer's projections are left as AutoNF12HookedLinear with forward_hook still set and forward_hook_last=True on the last subset member, so every later forward of the in-session model raises StopForward("Forwarding stopped"). A second quantize() on that model is not a way out either: it fails with layer module item self_attn.q_proj not found.

Repro (GPTQ shown; AWQ is the same)

import torch, gzip, json
from gptqmodel import GPTQModel
from gptqmodel.quantization import config as C
from gptqmodel.looper.module_looper import StopMainLoop

cal = [...]  # 16 C4 rows of 1500 chars
m = GPTQModel.load("Qwen2.5-0.5B-Instruct (num_hidden_layers=4)", C.GPTQConfig(bits=4, group_size=128), dtype=torch.float16)

def scb(**kw):
    if kw["stage"] == "forward_end" and kw["layer_idx"] == 1:
        return StopMainLoop          # same with: raise KeyboardInterrupt / raise RuntimeError
m.subset_callback = scb
try:
    m.quantize(C.CalibrationConfig(dataset=cal, batch_size=4))
except BaseException as e:
    print("ERR", type(e).__name__, e)

for n, x in m.model.named_modules():
    if getattr(x, "forward_hook", None) is not None:
        print(n, type(x).__name__, "forward_hook_last", x.forward_hook_last)
ids = m.tokenizer("Hello world", return_tensors="pt").input_ids
m.model(ids)

Output:

ERR StopMainLoop Subset callback requested stop at layer 1 subset 0
model.layers.1.self_attn.q_proj AutoNF12HookedLinear forward_hook_last False
model.layers.1.self_attn.k_proj AutoNF12HookedLinear forward_hook_last False
model.layers.1.self_attn.v_proj AutoNF12HookedLinear forward_hook_last True
...
gptqmodel.nn_modules.hooked_linear.StopForward: Forwarding stopped

Results by stop point (same script, layer 1):

stop at hooks left next forward
forward_start (StopMainLoop / KBI) 0 OK
quant_start, quant_complete (KBI) 0 OK
forward_end, StopMainLoop 3 StopForward
forward_end, RuntimeError 3 StopForward
forward_end, KeyboardInterrupt 3 StopForward (GPTQ and AWQ)

Suggested fix

Put the whole post-forward tail (receive_layer_forward_context, receive_layer_inputs, the forward_end callback, the region timer) in the same try/except BaseException: _release_capture_hooks(); raise as the other three exit points, or wrap the stage from hook install through line 1488 in one try/finally: _release_capture_hooks(). As a backstop, ModuleLooper.loop()'s failure branch could clear forward_hook/forward_hook_last on every module of the in-flight layer.

Test that should have caught it

tests/test_subset_cancel_hook_cleanup_4470.py stops only at forward_start. Parametrize it over every subset stage (forward_start, forward_end, quant_start, quant_complete) and over StopMainLoop, RuntimeError and KeyboardInterrupt, then assert no module has forward_hook set and that a plain forward succeeds.

Severity

Medium. Stopping the run at forward_end (StopMainLoop) is a supported way to abort, and an interrupt can land in this window. Either way the in-session model is unusable and the only way out is to reload it.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

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

  2. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent release: agent-root-5009 finished this issue. Fix: #5031, squash-merged as 8fd8644.

    The post-forward tail of _run_single_subset_pass (receive_layer_forward_context, receive_layer_inputs and the forward_end subset callback) now runs inside the same release guard as the forward itself, so a StopMainLoop/exception there still calls _release_capture_hooks(). ModuleLooper._restore_inflight_layer additionally clears the in-flight layer's inline forward_hook/forward_hook_last pair as a safety net for the windows the stage guard cannot see (zero-route-recovery callbacks, Ctrl-C inside a processor hook).

    Red on unmodified main @ bfbb7a2: tests/test_failed_run_model_state_5009.py::test_forward_end_stop_releases_capture_hooks[return_stop|raise] failed with assert [('model.layers.0.self_attn.q_proj', 'HookedLinear'), ...] == [] (3 modules kept forward_hook). Green with the fix (8 passed for the whole file). Contract recorded in docs/cancelled-run-contract.md.

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