Repository navigation
fix(looper): leave a cancelled quantize() with a runnable model (#5009, #5012) - #5031
Merged
Merged
Conversation
…ail stops (#5009) #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.
#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 (#4546), materializes unreached layers (#4860), rehomes kernels (#4947) and keeps the offload root (#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.
…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.
…restored (#5012) The weight-only looper still leaves the in-flight layer on the quant device when a run fails (#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).
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).
This was referenced Nov 17, 2026
This was referenced Nov 18, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #5009 and #5012. Both are "the run was cancelled, and the in-session model
is now unusable" holes left by earlier fixes that only covered the success path.
_run_single_subset_passguarded the forward itself but not thetail after it:
receive_layer_forward_context,receive_layer_inputsand theforward_endsubset callback (the documented way to stop the loop) ran withthe subset's capture hooks still installed. A
StopMainLoop, an exception orCtrl-C there unwound past the success-path
_release_capture_hooks(), so thein-flight layer kept
HookedLinear.forward_hookset andforward_hook_last=Trueon the last member. Every later forward of that modelthen raised
StopForward("Forwarding stopped"), and the failure cleanup(
ModuleLooper._restore_inflight_layer) never cleared it.ModuleLooper.loop()/WeightOnlyLooper.loop()callensure_version_counters()only on the success path. After any cancelled orfailed run, the norms, biases and buffers
pre_quantizematerialized underinference_mode()stayed inference tensors, so a plain grad-mode forward (aloss computation, fine-tuning, an eval harness) raised
RuntimeError: Inference tensors cannot be saved for backward. The same modelquantized to completion passed.
What Changed
gptqmodel/looper/stage_subset.py: the post-forward tail (through theforward_endcallback and the timing bookkeeping) is wrapped intry/except BaseExceptionthat calls_release_capture_hooks()beforere-raising. The success path still releases exactly where it did; the helper is
idempotent.
gptqmodel/looper/module_looper.py:_restore_inflight_layernow calls a new_clear_layer_capture_hooks(module)before rehoming the layer, as a safety net for windows the stage guard cannot
see (the zero-route-recovery callbacks, a Ctrl-C inside a processor hook).
ensure_version_counters(self.gptq_model.model)after
_materialize_unreached_meta_modules()/rehome_failed_run_kernels(),matching the success path. Best-effort: a repair failure is logged and never
replaces the exception that failed the run.
gptqmodel/looper/weight_only_looper.py: the same failure-branch repair.tests/test_failed_run_model_state_5009.py(new, 8 nodes) and the AWQ CPUunitCI suite now runs it.docs/cancelled-run-contract.md(new) records the contract with a statediagram and a before/after table; linked from
README.mdanddocs/README.md.No API change. Nothing on the success path changes behaviour: the repair and the
hook release already ran there.
Logic Flow
flowchart TD A["_run_single_subset_pass: hooks installed"] --> B["forward_start cb, device override, forward"] B -->|"StopMainLoop / exception"| R1["_release_capture_hooks()"] B --> C["post-forward tail: receive_layer_forward_context, receive_layer_inputs, forward_end cb"] C -->|"StopMainLoop / exception"| R1 C --> D["_release_capture_hooks() (success path)"] B -->|"other unwind"| E["ModuleLooper.loop failure branch"] C -->|"other unwind"| E D --> F["ensure_version_counters(model) (success path)"] E --> G["_fence_run_work, _restore_inflight_layer"] G --> H["_clear_layer_capture_hooks(layer)"] H --> I["ensure_version_counters(model)"] F --> J["model is runnable"] I --> J R1 --> J style R1 fill:#d7f0d7,stroke:#2f7d32 style H fill:#d7f0d7,stroke:#2f7d32 style I fill:#d7f0d7,stroke:#2f7d32 style E fill:#ffe9b3,stroke:#b38600bfbb7a2b4)forward_endcallback returnsStopMainLoop(stage_subset.py:1470):1488; 3HookedLinearmodules keptforward_hook, later forwards raisedStopForwardreceive_layer_*raises / Ctrl-C in the same windowforward_hook_restore_inflight_layerclears the layer's inline hook pairmodule_looper.py:2154,weight_only_looper.py:1033)ensure_version_counterssuccess-only; inference tensors left behindThe committed page
docs/cancelled-run-contract.mdkeeps both diagrams.Tests
Red-on-main failure reasons (exactly the two mechanisms):
test_forward_end_stop_releases_capture_hooks[return_stop],[raise]assert [('model.layers.0.self_attn.q_proj', 'HookedLinear'), ...] == []- 3 modules keepforward_hooktest_failed_run_repairs_inference_tensors[True-gptq]model.layers.0.input_layernorm.weight)test_failed_run_repairs_inference_tensors[True-awq]test_failed_run_repairs_inference_tensors[False-gptq]model.layers.1.self_attn.q_proj.weight)test_failed_run_repairs_inference_tensors[False-awq]model.layers.0.self_attn.q_proj.qzeros_format)test_failed_weight_only_run_repairs_inference_tensors[True],[False]Neighbouring suites on the branch (new file + 19 cancel/looper/subset/quantize
files): 148 passed, 12 skipped, 2 failed. The two failures are
tests/test_pre_looper_failure_cleanup_4862.py::test_calibration_rejected_before_the_looper_leaves_no_smi_threads[empty](
AssertionError: Regex pattern did not match ... Expected 'must not be empty', actual 'Quantize: calibration dataset is empty.') and::test_later_processor_failure_releases_the_processors_already_built; they failidentically on unmodified
origin/main(2 failed, 3 passed) and are unrelated tothis change.
tests/module_tree/test_subset.py,test_looper_concurrency.pyand the fivetest_quantize_*files: 84 passed, 2 skipped on both trees (identical).tests/test_docs_contract_refs.py+ the new file: 31 passed.ruff checkclean on all changed Python files.
Model Support / Module Plan
Not applicable: no model definition, registry entry or module-plan change.
AWQ onboarding safety
Not applicable: no AWQ grouping, search, replay or fold change. The AWQ
parametrisation in the new test only exercises the cancelled-run path.
Kernel Accuracy Requirements
Not applicable: no kernel change.
Review Requirements
_release_capture_hooksandensure_version_countersare the mechanisms the success path already uses.documented
subset_callbackand aquantize_modulewrapper.and the repair is a no-op on an already-clean model).
Notes
replace the exception that failed the run, matching
_fence_run_workand_release_failed_run_processorsnext to it.quantize()on a stopped model is not part of this contract (thedocumented recovery is to reload the checkpoint). It happens to work on the
tiny fixture after this change, but that is not asserted.
([BUG] #4580 (fix of #4546) incomplete with default offload_to_disk=True: a cancelled/failed quantize() leaves every completed layer on meta and deletes their offload bundles -> next forward FileNotFoundError, in-session model unrecoverable #4807); the repair does not materialize them.