Skip to content

fix(looper): publish a quant kernel only after packing returns (#5089) - #5152

Merged
Qubitium merged 2 commits into
mainfrom
fix/5089-atomic-pack
Nov 18, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/5089-atomic-pack

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Summary

GPTQModel.quantize() promises the in-session model stays runnable after a cancelled or failed run (docs/cancelled-run-contract.md). A Ctrl-C or exception inside pack_module broke that promise: finalization installed the kernel class in the tree first and packed it second, so an interrupt left a TorchLinear owning no packed buffers and every later forward raised AttributeError: 'TorchLinear' object has no attribute 'qzeros' (or 'g_idx'). Packing dominates RTN/GPTQ wall time, so the window is wide.

Fixes #5089

What Changed

  • gptqmodel/utils/model.py: create_quant_module(..., install=False) returns the built module without touching the tree, and install_quant_module() publishes it with a single assignment. install=True keeps the historical behavior for every other caller (loader, HF bridge, make_quant).
  • gptqmodel/looper/{gptq,weight_only,awq,qqq,paro,vptq,macaq}_processor.py: build and pack the kernel off-tree, then install it after packing returns, under the same parent_module_lock the create/pack calls use. The float weight is dropped only after the tree no longer references it. Configs that resolve to an excluded module still return early.
  • gptqmodel/looper/inflight_layer.py, run_exit_recovery.py, both loopers: recovery unwraps the failed run's remaining float HookedLinear projections into plain linears. HookedLinear.forward always runs under inference_mode(), so the partially quantized layer a cancelled run leaves behind mixed inference-mode outputs with packed siblings; a plain grad-mode forward then raised RuntimeError: Inference tensors cannot be saved for backward. The unwrap runs as its own best-effort step so it can never replace the run's error.
  • gptqmodel/nn_modules/hooked_linear.py: restore_linear_from_hooked() / unwrap_hooked_linears() own that conversion; Paro's layer-scope wrapper stripping now uses them.
  • docs/cancelled-run-contract.md: new "Atomic kernel publication ([BUG] #5031/#5066 cancelled-run contract: a Ctrl-C during pack_module leaves a half-built TorchLinear (no qweight/qzeros) in the model; every later forward raises AttributeError 'qzeros' #5089)" section with a sequence diagram, the before/after table row, and the test map.

Behavior notes: no API removal; create_quant_module gains an optional keyword with a backward-compatible default. Excluded-module handling in each processor is unchanged. Out of scope: re-quantizing a partially processed model (already excluded by the contract) and concurrent in-place writes to a module the tree still owns.

Tests

New regression, run from tests/:

  • test_run_exit_recovery_contract_5060.py::test_pack_fault_leaves_no_half_built_kernel[gptq|rtn × offload|no-offload] injects a KeyboardInterrupt inside pack_module, then asserts (a) the trigger fired, (b) no installed kernel is missing qweight/qzeros/scales/g_idx, (c) no capture hook or non-CPU tensor remains, and (d) an ordinary default-grad forward runs.
  • test_finalize_module_lookup.py::test_finalize_looks_up_only_the_module_being_packed[...] (existing suite) now also pins that the tree still holds the float projection while packing runs, and that the packed module is installed afterwards.

Red evidence on 8585be2c8 (parent of this branch) with the new tests:

$ python -m pytest tests/test_run_exit_recovery_contract_5060.py tests/test_finalize_module_lookup.py -q -o addopts=''
11 failed, 18 passed
FAILED ...::test_pack_fault_leaves_no_half_built_kernel[gptq-offload]
FAILED ...::test_pack_fault_leaves_no_half_built_kernel[gptq-no-offload]
FAILED ...::test_pack_fault_leaves_no_half_built_kernel[rtn-offload]
FAILED ...::test_pack_fault_leaves_no_half_built_kernel[rtn-no-offload]
   E AssertionError: a cancelled run left a quant kernel installed without its packed buffers
   assert ["model.layers.0.mlp.down_proj (TorchLinear): ['qweight', 'qzeros', 'scales', 'g_idx']"] == []
FAILED ...::test_finalize_looks_up_only_the_module_being_packed[gptq|gptq-embedding|rtn|rtn-embedding|qqq|awq|paro]
   E AssertionError: assert TorchLinear() is Linear(in_features=128, out_features=128, bias=False)

The four pack_fault nodes fail on the intended behavioral assertion (a half-built kernel in the tree), not on imports or skips.

Green on this branch (rebased onto 8585be2c8):

# new + shared cancelled-run conformance matrix
python -m pytest tests/test_run_exit_recovery_contract_5060.py tests/test_failed_run_model_state_5009.py \
  tests/test_weight_only_failed_run_device_5011.py tests/test_cancelled_quantize_default_offload_4860.py \
  tests/test_cancelled_quantize_layer_cleanup_4546.py tests/test_cancelled_quantize_disk_offload_4807.py \
  tests/test_cancelled_quantize_kernel_rehome_4947.py tests/test_finalize_module_lookup.py \
  tests/test_stage_modules.py tests/test_host_memory_trim_4990.py \
  tests/test_quantization_lifecycle_contracts.py tests/test_processor_finalize_4747.py \
  -q -o addopts=''
138 passed

# packing / finalize / MACaQ families
python -m pytest tests/test_pack_tails.py tests/test_pack_gpu_alignment.py tests/test_awq_qqq_pack_shape_4567.py \
  tests/test_awq_per_module_bits.py tests/test_quant_module_device.py tests/test_exl3_projection_resume.py \
  tests/test_docs_contract_refs.py tests/test_macaq.py tests/test_macaq_single_output_4472.py \
  tests/test_macaq_forward_dtype_4217.py -q -o addopts=''
387 passed (packing families) / 166 passed (MACaQ set)

# strict lint
ruff check gptqmodel tests   ->  All checks passed!

Device runs of the same fault, CUDA pack path (pack_impl="gpu", NVIDIA) and the ROCm path, on a tiny Llama: interrupted inside packing, half-built kernels: [], forward OK with finite logits. The same script on the parent commit leaves model.layers.0.self_attn.q_proj (TorchLinear) in the tree and fails the forward with AttributeError: 'TorchLinear' object has no attribute 'g_idx'.

Random-timer sweeps after the fix: RTN (disk offload) and GPTQ (disk offload), 24 cancel points total, 0 unusable models / 0 half-built kernels.

Skips and limits:

  • The regression matrix uses a tiny 3-layer Llama fixture on CPU with device="cpu"; the device runs above are the manual CUDA/ROCm evidence, not pytest nodes.
  • tests/test_cancelled_quantize_kernel_rehome_4947.py needs ninja on PATH for the AWQ/QQQ JIT extension; it fails identically on the parent commit without it.
  • tests/test_torch.py::test_forward_observes_weight_mutation_and_state_load_clears_metadata and ::test_cached_dequant_offloads_g_idx_to_cpu_on_cuda fail identically on the parent commit in this environment (unrelated to this change).
  • GPTQ no-offload at the very first pack occasionally left an HookedLinear in the in-flight layer on the pre-fix code path; the fix makes the trigger deterministic by construction and the nodes are stable in repeated runs.

Model Support / Module Plan

Not applicable: no MODEL_MAP, definition, alias, or module-plan change.

Logic Flow Documentation

This changes tensor-lifecycle/ownership and adds a fail-closed publication step, so the required diagrams are included in docs/cancelled-run-contract.md (linked from the cancelled-run section of the README):

Removed mechanism: create_quant_module(..., register_buffers=False) inserted the kernel into the tree (gptq_processor.py:1113, weight_only_processor.py:251) before pack_module (:1153, :330), so the window between them published an unpacked module.

flowchart TD
    A["submodule_finalize"] --> B["create_quant_module<br/>register_buffers=False"]
    B --> C["setattr: empty kernel in tree"]
    C --> D["pack_module"]
    D -->|"returns"| E["tree holds packed kernel"]
    D -->|"Ctrl-C / exception"| F["tree holds kernel with no<br/>qweight / qzeros / scales / g_idx"]
    F --> G["later forward:<br/>AttributeError qzeros"]
    style F fill:#ffd6d6,stroke:#b00020
    style G fill:#ffd6d6,stroke:#b00020
    style E fill:#d7f0d7,stroke:#2f7d32
Loading

New flow, shipped symbol names:

sequenceDiagram
    participant P as processor.submodule_finalize
    participant B as create_quant_module
    participant K as pack_module
    participant T as model tree
    P->>B: install=False, off-tree kernel
    B-->>P: quant module
    P->>K: pack(quant module, float layer)
    alt packing returns
        K-->>P: packed
        P->>T: install_quant_module (one assignment)
    else stop / exception / Ctrl-C
        K-->>P: raises
        Note over T: float projection stayed installed
        T->>T: RunExitRecovery: unwrap HookedLinear
    end
    style T fill:#ffe9b3,stroke:#b38600
Loading

Diagram summary: build/pack off-tree, publish once, unwrap leftover float projections on abort.

Review Requirements

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

Not applicable: no kernel math, packer layout, or dispatch change. Publication order only; packed tensor contents are produced by the same unchanged packers.

Notes

  • create_quant_module keeps install=True by default, so checkpoint load, the HF bridge and make_quant are byte-for-byte unchanged.
  • The ExLlamaV3 path already published atomically (create_exllamav3_module builds from tensors and assigns once); it was not modified.
  • A later PR could make the same guarantee explicit at the API by returning the module and letting callers publish, but that would touch shared call sites and is out of scope here.

Finalization swapped the float projection for its kernel class with
`create_quant_module(..., register_buffers=False)` and only then called
`pack_module`. A Ctrl-C or exception inside packing therefore left a
`TorchLinear` in the tree that owned no `qweight`/`qzeros`/`scales`/`g_idx`,
and every later forward raised
`AttributeError: 'TorchLinear' object has no attribute 'qzeros'` (or
`'g_idx'`). Packing dominates RTN/GPTQ wall time, so the window is wide; the
reported timer sweep left 12 of 40 cancelled runs unusable.

- `create_quant_module` gains `install=False` and `install_quant_module`
  publishes a packed module with one assignment. Every processor that packed
  in-tree (GPTQ, weight-only, AWQ, QQQ, Paro, VPTQ, MACaQ) now builds and
  packs off-tree and installs last, so the tree holds either a complete module
  or the untouched float one.
- Run-exit recovery also unwraps the run's remaining float `HookedLinear`
  projections into plain linears. Their forward always runs under
  `inference_mode`, so the partially quantized layer a cancelled run leaves
  behind otherwise mixed inference outputs with packed siblings and a plain
  grad-mode forward raised "Inference tensors cannot be saved for backward".
- `tests/test_run_exit_recovery_contract_5060.py` gains
  `test_pack_fault_leaves_no_half_built_kernel` (GPTQ and RTN, disk offload on
  and off) and `tests/test_finalize_module_lookup.py` now pins that the tree
  still holds the float projection while packing runs.

Fixes #5089
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants