Skip to content

fix(looper): leave a cancelled quantize() with a runnable model (#5009, #5012) - #5031

Merged
Qubitium merged 5 commits into
mainfrom
root/failed-run-model-state-5009
Nov 17, 2026
Merged

Qubitium merged 5 commits into
mainfrom
root/failed-run-model-state-5009

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

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.

What Changed

  • gptqmodel/looper/stage_subset.py: the post-forward tail (through the
    forward_end callback and the timing bookkeeping) is wrapped in
    try/except BaseException that calls _release_capture_hooks() before
    re-raising. The success path still releases exactly where it did; the helper is
    idempotent.
  • gptqmodel/looper/module_looper.py:
    • _restore_inflight_layer now 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).
    • the failure branch calls 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 CPU
    unit CI suite now runs it.
  • docs/cancelled-run-contract.md (new) records the contract with a state
    diagram and a before/after table; linked from README.md and docs/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:#b38600
Loading
Exit window Before (revision bfbb7a2b4) After
forward_end callback returns StopMainLoop (stage_subset.py:1470) unwound past the release at :1488; 3 HookedLinear modules kept forward_hook, later forwards raised StopForward tail guard releases both the inline hooks and the registered handles
receive_layer_* raises / Ctrl-C in the same window same leak same guard
zero-route-recovery callbacks or any other unwind failure branch never cleared forward_hook _restore_inflight_layer clears the layer's inline hook pair
any cancelled/failed run (module_looper.py:2154, weight_only_looper.py:1033) ensure_version_counters success-only; inference tensors left behind failure branch runs it too

The committed page docs/cancelled-run-contract.md keeps both diagrams.

Tests

# red on unmodified origin/main @ bfbb7a2b4 (test copied into a separate worktree)
GPTQ_BYPASS_SAFETY_CHECKS=1 CUDA_VISIBLE_DEVICES= HF_HUB_OFFLINE=1 \
  PYTHONPATH=/root/worktrees/root-5009-base \
  /root/venv-kernels/bin/python /tmp/root-rt.py \
  tests/test_failed_run_model_state_5009.py -q -o addopts= -o log_cli=false -p no:cacheprovider
# 8 failed

# green on this branch
... PYTHONPATH=/root/worktrees/root-5009 ... tests/test_failed_run_model_state_5009.py
# 8 passed   (5 consecutive runs, stable)

Red-on-main failure reasons (exactly the two mechanisms):

Node Main
test_forward_end_stop_releases_capture_hooks[return_stop], [raise] assert [('model.layers.0.self_attn.q_proj', 'HookedLinear'), ...] == [] - 3 modules keep forward_hook
test_failed_run_repairs_inference_tensors[True-gptq] 14 inference tensors (first: model.layers.0.input_layernorm.weight)
test_failed_run_repairs_inference_tensors[True-awq] 14
test_failed_run_repairs_inference_tensors[False-gptq] 38 (first: model.layers.1.self_attn.q_proj.weight)
test_failed_run_repairs_inference_tensors[False-awq] 28 (first: model.layers.0.self_attn.q_proj.qzeros_format)
test_failed_weight_only_run_repairs_inference_tensors[True], [False] RTN, same

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 fail
identically on unmodified origin/main (2 failed, 3 passed) and are unrelated to
this change.

tests/module_tree/test_subset.py, test_looper_concurrency.py and the five
test_quantize_* files: 84 passed, 2 skipped on both trees (identical).
tests/test_docs_contract_refs.py + the new file: 31 passed. ruff check
clean 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

  • Reviewed: three small, local guards; no new abstraction.
  • Matches existing structure: _release_capture_hooks and
    ensure_version_counters are the mechanisms the success path already uses.
  • No monkeypatching in product code; the test injects a failure through the
    documented subset_callback and a quantize_module wrapper.
  • Regression risk: the success path is unchanged (the release is idempotent
    and the repair is a no-op on an already-clean model).

Notes

…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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant