Skip to content

[BUG] #4572 repair skipped on the failure path: after a cancelled/failed quantize() the in-session model keeps inference-mode norms/buffers; a plain (grad-mode) forward raises 'Inference tensors cannot be saved for backward' #5012

Closed

Description

@Qubitium

Found on main @ c2b0bf6, RTX 4090, torch 2.15. Reproduces with offload_to_disk=True (the default) and offload_to_disk=False, for GPTQ and AWQ.

What is wrong

#4572 established that when quantize() returns, every tensor in the in-session model must be an ordinary tensor. ModuleLooper.loop() does that repair with ensure_version_counters(self.gptq_model.model) (gptqmodel/looper/module_looper.py:2154; the weight-only looper does the same at weight_only_looper.py:1033), but only on the success path. The failure branch above it (except BaseException: at about line 2087) 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 (StopMainLoop from a callback, Ctrl-C, an exception), the norms, biases and buffers that pre_quantize materialized under torch.inference_mode() stay inference tensors. That covers the finished layers, the in-flight layer, model.norm and rotary_emb.inv_freq. Forwards under inference_mode() or no_grad() and generate() still work, but a plain forward in default grad mode, as a loss computation or any fine-tuning or evaluation code would run, fails:

RuntimeError: Inference tensors cannot be saved for backward. Please do not use Tensors created in inference mode in computation tracked by autograd.

The same model, quantized to completion, passes all of these checks.

Repro

import torch
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)
m.subset_callback = lambda **kw: StopMainLoop if (kw["stage"] == "quant_complete" and kw["layer_idx"] == 2) else None
try:
    m.quantize(C.CalibrationConfig(dataset=cal, batch_size=4))
except StopMainLoop:
    pass
print({n for n, t in list(m.model.named_parameters()) + list(m.model.named_buffers()) if t.device.type != "meta" and t.is_inference()})
ids = m.tokenizer("The capital of France is a city that", return_tensors="pt").input_ids
with torch.no_grad(): m.model(ids)    # ok
m.model(ids)                           # RuntimeError

Measured (q05 = Qwen2.5-0.5B-Instruct truncated to 4 layers):

run inference tensors left (per module) inference_mode / no_grad / generate plain forward
GPTQ, completed none ok ok
GPTQ, stopped at layer 2 quant_complete, offload on layers.0: 2, layers.1: 2, layers.2: 20, model.norm: 1, rotary_emb: 2 ok RuntimeError
GPTQ, same stop, offload_to_disk=False layers.0: 40, layers.1: 40, layers.2: 20 ok RuntimeError
GPTQ, stopped at layer 1 forward_start layers.0: 2, layers.1: 26, model.norm: 1, rotary_emb: 2 ok RuntimeError
AWQ, stopped at layer 1 forward_start, offload on / off layers.0: 2 / 33, layers.1: 26 / 26, ... ok RuntimeError
RTN, completed none ok ok

Suggested fix

Call ensure_version_counters(self.gptq_model.model) in the failure branch of ModuleLooper.loop() and of WeightOnlyLooper, after _materialize_unreached_meta_modules() and rehome_failed_run_kernels(), best effort and never masking the original exception, like the other cleanup steps there.

Test that should have caught it

The cancel/failure tests (tests/test_cancelled_quantize_kernel_rehome_4947.py and tests/test_subset_cancel_hook_cleanup_4470.py) only run forwards under inference_mode. Add the #4572 assertion they already use for the success path: no parameter or buffer is_inference(), and a plain grad-mode forward runs.

Severity

Low to medium. The in-session model is usable only under no_grad/inference_mode. Any grad-mode use after a cancelled run fails with an error that says nothing about the cancellation.

🤖 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.

    ModuleLooper.loop() and WeightOnlyLooper.loop() now call ensure_version_counters(self.gptq_model.model) on the failure branch too, after _materialize_unreached_meta_modules() / rehome_failed_run_kernels() — so a cancelled or failed run returns the same ordinary (non-inference) tensors a completed run does. The repair is best-effort and never replaces the exception that failed the run.

    Red on unmodified main @ bfbb7a2, tests/test_failed_run_model_state_5009.py: GPTQ/AWQ stopped at quant_complete left 14 (offload on) / 38 and 28 (offload off) inference tensors, and RTN through an injected module failure left 31/35; a plain grad-mode forward then raised Inference tensors cannot be saved for backward. Green with the fix: 8 passed (5 consecutive runs). Contract recorded in docs/cancelled-run-contract.md.

  3. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Fixed by #5031, squash-merged as 8fd8644a1: both loopers run ensure_version_counters on the failure branch, so a cancelled/failed run no longer leaves inference tensors behind. (The PR body said "Fixes #5009 and #5012"; GitHub only auto-closed the first reference.)

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