Skip to content

fix(looper): release subset capture hooks on cancel and failure - #4515

Merged
Qubitium merged 1 commit into
mainfrom
fix/issue-4470-cancel-hook-cleanup
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/issue-4470-cancel-hook-cleanup

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Fixes #4470. StageSubset installs a forward hook on every module of the subset and sets forward_hook_last on the final one, but the teardown ran only on the success path. A StopMainLoop returned from the forward_start callback (the documented cancellation hook), any forward exception, or a failing capture-context factory unwound past the cleanup and left the hooks installed:

  • the hook closures retained the processor/looper state for as long as the model lived;
  • the next ordinary forward raised StopForward, so a cancelled model could neither be used nor re-quantized.
qmodel.subset_callback = lambda **kw: StopMainLoop if kw["stage"] == "forward_start" else None
qmodel.quantize(calibration, ...)          # StopMainLoop
qmodel.model(...)                          # StopForward: Forwarding stopped

What Changed

  • gptqmodel/looper/stage_subset.py
    • New _release_capture_hooks(): detaches every registered handle, clears the handle list, and resets forward_hook/forward_hook_last on the subset's NamedModule wrappers. Idempotent, so every exit can call it.
    • Called from the forward_start callback, from the forward device-override step, from the forward itself (new except BaseException), and from the success path (replacing the inline teardown).
    • The capture-context factory now runs inside the guarded region instead of before it.
  • tests/test_subset_cancel_hook_cleanup_4470.py (new): cancellation via StopMainLoop, a callback raising RuntimeError, and a forward raising after the hooks are armed. Each asserts no leaked hook state and that a plain forward still works afterwards.

No API change.

Tests

CPU-only (GPTQ_BYPASS_SAFETY_CHECKS=1, CUDA_VISIBLE_DEVICES="", PYTHONPATH = worktree):

pytest tests/test_subset_cancel_hook_cleanup_4470.py -q
# 3 passed

pytest tests/test_subset_plan.py tests/test_stage_modules.py tests/test_stage_inputs_capture.py \
       tests/test_looper_helpers.py tests/test_module_looper_quant_log_4321.py \
       tests/test_subset_cancel_hook_cleanup_4470.py -q
# 106 passed

ruff check gptqmodel/looper/stage_subset.py tests/test_subset_cancel_hook_cleanup_4470.py
# All checks passed

All three new tests fail on unmodified main (4 leaked hooks, then StopForward) and pass with the fix.

Notes

  • The success path is behaviourally unchanged: the same teardown runs at the same point, now through the shared helper.
  • A partial failure inside _apply_forward_device_overrides still may leave device overrides applied (pre-existing); this PR only guarantees the capture hooks are released.

StageSubset installs a forward hook on every module of the subset and sets
forward_hook_last on the final one. The teardown ran only on the success path,
so a StopMainLoop from the forward_start callback, a forward exception, or a
failing capture-context factory unwound past it and left the hooks installed:

  * the closures retained the processor/looper state while the model lived;
  * the next ordinary forward raised StopForward, so a cancelled model could
    not be used or re-quantized.

Factor the teardown into _release_capture_hooks() (idempotent) and run it from
every exit: the forward_start callback, the forward device-override step, the
forward itself, and the success path.
@Qubitium
Qubitium merged commit ba6ed56 into main Nov 17, 2026
9 checks passed
@Qubitium
Qubitium deleted the fix/issue-4470-cancel-hook-cleanup branch November 17, 2026 00:27
Qubitium added a commit that referenced this pull request Nov 17, 2026
…4631)

The failure branch of ModuleLooper.loop() restored the model and deleted the
per-run offload directory while submodule finalizers already submitted to
DEVICE_THREAD_POOL were still running. Those finalizers re-created the run
directory that release_private_offload_root had just removed (one leaked
bundle set per failed run) and kept packing/replacing modules after
quantize() had raised to the caller. #4515 only fixed the capture-hook half
of #4470.

Drain the device pool, the finalizer watcher threads and the stream device
pool before any teardown, mirroring the success path. Each wait is
independent so one wedged pool cannot skip the others or mask the original
exception.

Issue #4595.
sLaffey pushed a commit to sLaffey/GPTQModel that referenced this pull request Nov 18, 2026
…lCloud#5009, ModelCloud#5012) (ModelCloud#5031)

* fix(looper): release a subset's capture hooks when the post-forward tail stops (ModelCloud#5009)

ModelCloud#4515 made the subset stage release its capture hooks on the forward-start
callback, the device override and the forward itself, so a cancelled run no
longer left a `StopForward` trap behind. The tail after the forward stayed
unguarded: `receive_layer_forward_context`, `receive_layer_inputs` and the
`forward_end` subset callback - the documented way to stop the loop - all ran
with this subset's hooks still installed, and a `StopMainLoop`, an exception or
Ctrl-C there unwound past the success-path `_release_capture_hooks()`.

The in-flight layer then kept `AutoNF12HookedLinear`/`HookedLinear` modules with
`forward_hook` set and `forward_hook_last=True` on the last member, so every
later forward of the in-session model raised `StopForward("Forwarding
stopped")`, and the failure cleanup never cleared it.

Wrap that tail in the same release guard, and clear the inline hook pair on the
in-flight layer in `ModuleLooper._restore_inflight_layer` as a safety net for the
windows the stage guard cannot see (the zero-route-recovery callbacks, a
KeyboardInterrupt inside a processor hook).

`tests/test_failed_run_model_state_5009.py` stops a real GPTQ quantize at
`forward_end` (both a returned `StopMainLoop` and a raised exception) and
asserts no module keeps a capture hook and that a later forward runs.

* fix(looper): repair tensor version counters on the failed-run path too (ModelCloud#5012)

model must be an ordinary tensor, and `ModuleLooper.loop()` /
`WeightOnlyLooper.loop()` enforce that with `ensure_version_counters(...)` - but
only on the success path. The failure branch restores devices (ModelCloud#4546),
materializes unreached layers (ModelCloud#4860), rehomes kernels (ModelCloud#4947) and keeps the
offload root (ModelCloud#4807), then re-raises without that repair.

So after any cancelled or failed run (a `StopMainLoop` from a callback, Ctrl-C,
an exception) the norms, biases and buffers `pre_quantize` materialized under
`inference_mode()` stayed inference tensors, and a plain grad-mode forward -
a loss computation, fine-tuning, an evaluation harness - raised
"RuntimeError: Inference tensors cannot be saved for backward". The same model
quantized to completion passed.

Run the repair on both failure branches. It is best-effort: a repair failure is
logged and never replaces the exception that failed the run, matching the rest
of that teardown.

`tests/test_failed_run_model_state_5009.py` stops GPTQ and AWQ at
`quant_complete` (with `offload_to_disk` on and off) and an RTN run through an
injected module failure, then asserts no inference tensor is left and that a
plain grad-mode forward succeeds.

* docs(looper): record the cancelled-run model-state contract (ModelCloud#5009, ModelCloud#5012)

A `quantize()` that stops mid-run leaves the in-session model alive, so it must
be left runnable. Draw the two exit windows that did not honour that - the
subset stage's post-forward tail and the loopers' failure branch - with the
release points that now cover them, plus a before/after table citing the pre-fix
revision.

New page `docs/cancelled-run-contract.md`, linked from `README.md` and the
`docs/` index next to the lifecycle contracts it extends.

* test(looper): only assert the weight-only forward when the layer was restored (ModelCloud#5012)

The weight-only looper still leaves the in-flight layer on the quant device when
a run fails (ModelCloud#5011), so on an accelerator host the post-failure model can be
mixed-device for a reason unrelated to the inference-tensor repair. Keep the
repair assertion unconditional and check the forward only when every parameter
shares one device (always true on a CPU run).

* test(looper): narrow the stop helper to Exception (ModelCloud#5009, ModelCloud#5012)

CodeQL flagged the helper's `except BaseException`. Both signals under test
(`StopMainLoop` and an ordinary stage error) are `Exception` subclasses, so the
helper can leave `KeyboardInterrupt`/`SystemExit` to the caller. The red-on-main
proof is unchanged (8 failed).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant