Skip to content

fix(qqq): build the CPU packed cache outside inference mode (#5197) - #5238

Merged
Qubitium merged 1 commit into
mainfrom
fix/5197-qqq-cpu-cache
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5197-qqq-cpu-cache

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #5197.

Fix #5197: QQQ CPU packed cache must not be built out of inference tensors

Root cause (one line)

QQQTorchLinear._packed_weight_for_cpu() builds _torch_packed_cache = (packed, s_group, s_channel) inside whatever mode the first forward runs in;
when that is torch.inference_mode() (every generate() / eval loop) the
cached s_channel is an inference tensor, so the next grad-mode forward raises
RuntimeError: Inference tensors cannot be saved for backward at
accum = accum * s_channel (qqq.py forward).

Mechanism

  1. First forward after load/quantize runs inside torch.inference_mode()
    (GPTQModel.generate() wraps generate in inference_mode; eval loops do
    the same). _packed_cpu_matmul() calls _packed_weight_for_cpu().
  2. pack_hf_int4(codes), _unpermute_scales(...), .to(...), .contiguous()
    all inherit the current inference flag, so the tuple stored on
    self._torch_packed_cache is made of inference tensors.
  3. _maybe_drop_checkpoint_tensors() then proves the cache can rebuild
    B/s_group/s_channel and drops those buffers ([MEM] QQQ on CPU (AUTO QQQTorchLinear) keeps a second packed copy of every weight in _torch_packed_cache next to the unused checkpoint B: QQQ-Llama-3-8B +3.5 GiB host RAM (5.4 -> 9.0 GiB tensors, RSS 4.2 -> 11.2 GB) after the first forward #4805), so the cache is
    now the only resident weight and it outlives the inference_mode block.
  4. A later grad-mode forward (training/finetune step, or any requires_grad
    activation) multiplies the INT32 accumulator by the cached s_channel.
    Autograd must save that operand for the backward of mul, and PyTorch
    rejects inference tensors there.
  5. Grad-first then inference works, because the cache is then built outside
    inference mode and stays normal.

Before / after

sequenceDiagram
    participant U as user
    participant F as forward()
    participant B as _packed_weight_for_cpu()
    participant C as _torch_packed_cache

    rect rgb(255, 235, 235)
    Note over U,C: BEFORE (bug)
    U->>F: inference_mode() forward (generate)
    F->>B: cold cache
    B->>C: store (packed, s_group, s_channel) = inference tensors
    B->>B: drop B/s_group/s_channel buffers (#4805)
    U->>F: grad-mode forward (requires_grad=True)
    F->>C: read s_channel
    F--xF: RuntimeError: Inference tensors cannot be saved for backward
    end

    rect rgb(230, 245, 230)
    Note over U,C: AFTER (fix)
    U->>F: inference_mode() forward (generate)
    F->>B: cold cache
    B->>B: @inference_mode(False) + @no_grad
    B->>C: store normal tensors (no grad graph)
    B->>B: drop checkpoint buffers (#4805, unchanged)
    U->>F: grad-mode forward
    F->>C: read normal s_channel
    F-->>U: same values, backward OK
    end
Loading

Fix

@torch.inference_mode(False)
@torch.no_grad()
def _packed_weight_for_cpu(self):
    ...
  • inference_mode(False) makes the cached operands normal tensors, so a
    grad-mode forward can save s_channel for backward.
  • no_grad() is required as well: on this torch (2.15.0) a nested
    inference_mode(False) re-enables the enclosing grad mode, and the builder
    (which also rebuilds/compares the checkpoint tensors) must not record a
    graph.
  • Correct for both orderings (inference-first, grad-first) and for a module
    packed inside the quantization loop's inference_mode.

Sibling audit

Same probe for every CPU kernel: inference-mode forward first, then a
grad-mode forward with requires_grad=True, then backward().

kernel lazy CPU cache forward grad-safe?
QQQTorchLinear _torch_packed_cache tuple, built in first forward NO pre-fix / yes post-fix
TorchLinear _zeros_cache, _g_idx_long_cache (metadata only; g_idx already normalised in post_init) yes
TorchFusedLinear / TorchAtenLinear / TorchCpuAvx512Linear buffer layout rewrite (transform_cpu / int4pack), forward is @torch.no_grad yes
TorchFusedAwqLinear / TorchAtenAwqLinear / TorchCpuAvx512AwqLinear same int4pack layout rewrite yes
ParoLinear _ensure_cpu_layout buffer rewrite, forward no-grad yes
QQQ generic fallback (_int8_weight_for_forward) none (re-derived per forward, advanced-index copy) yes (not reachable on AVX512 hosts)

Only QQQ keeps a tensor tuple that is read by an autograd-tracked op.

Evidence

All CPU-only (CUDA_VISIBLE_DEVICES=""), PYTHONPATH=/root/work/issue-5197,
HF_HUB_OFFLINE=1, /root/venv/bin/python (torch 2.15.0+cu132).

run command result
red pytest tests/kernels/test_qqq_cpu_cache_inference_5197.py -q (fix stashed) 2 failed, 1 passed
green same, with fix 3 passed
red .scratch/repro.py (fix stashed) RuntimeError: Inference tensors cannot be saved for backward at qqq.py:1252
green .scratch/repro.py both orders ok, `max
sibling audit .scratch/audit_siblings.py only QQQTorchLinear red
family (fixed) pytest tests/test_qqq*.py tests/kernels/test_qqq*.py tests/test_awq_qqq_pack_shape_4567.py tests/test_gsq_qqq_activation_contract.py -q -m "not cuda and not gpu and not model and not slow" -k "not test_quant_and_inference" 261 passed, 61 skipped, 9 pre-existing env failures
family (pristine) same command in /tmp/issue5197-red 259 passed, 61 skipped, 11 failed (the 2 extra are this PR's red tests)
CPU subset 12 CPU QQQ files 101 passed, 19 skipped
compile probe pytest tests/kernels/test_kernel_compile_levels_cpu.py -k QQQ 2 passed
lint uvx [email protected] check gptqmodel docs/eora tests setup.py All checks passed!

Tests

New file tests/kernels/test_qqq_cpu_cache_inference_5197.py:

  • test_inference_forward_then_grad_forward_matches — the reported order:
    one inference_mode() forward (cold cache, checkpoint dropped), then a
    grad-mode forward + backward; both outputs must be bit-identical. Red
    pre-fix with the exact RuntimeError.
  • test_inference_built_cache_holds_normal_tensors — builds the cache
    directly inside inference_mode() and asserts no cached operand
    is_inference(). Red pre-fix on every host, including ones without AVX512.
  • test_grad_forward_after_in_session_quantize_matches — packs the module
    inside inference_mode() (as QQQ.quantize does), then grad forward +
    backward, then inference forward; outputs must match.

Family failures are environment-only and identical in both trees:
tests/test_qqq.py::TestGroupSize::test_load_group_128 and the 8
tests/kernels/test_qqq_workspace.py cases build the CUDA QQQLinear kernel
and raise ImportError: QQQ: CUDA is not available under
CUDA_VISIBLE_DEVICES=""; they pass in isolation on a CUDA host. diff of the
FAILED lists shows the only delta is the two new red tests.

What could not be verified

  • Real end-to-end generate() -> training on a quantized checkpoint (no GPU
    and no cached model for this task); the unit-level ordering is covered.
  • Non-x86 hosts: the packed AVX512 path is not built there; the generic
    fallback was audited by reading the code, not executed.
  • torch.compile re-measurement of QQQ CPU levels after adding the decorators
    (the builder is never traced — _packed_cpu_matmul returns early when
    compiling — but no fresh inductor run was made).

`QQQTorchLinear._packed_weight_for_cpu()` cached
`(packed, s_group, s_channel)` in whatever mode the first forward ran in.
Every `generate()`/eval loop runs that first forward inside
`torch.inference_mode()`, so the cache held inference tensors and the
checkpoint buffers were then dropped (#4805), leaving them as the only
resident weight. A later grad-mode forward raised
`RuntimeError: Inference tensors cannot be saved for backward` at
`accum = accum * s_channel`.

Build the cache under `torch.inference_mode(False)` + `torch.no_grad()`:
the cached operands are normal tensors for inference-first, grad-first and
for a module packed inside the quantization loop's `inference_mode`. The
plain `no_grad` is needed because a nested `inference_mode(False)`
restores the enclosing grad mode.

Audited the sibling CPU kernels (TorchLinear metadata caches, the
int4pack/AVX512/aten/fused/Paro buffer layouts): all are read by
`@torch.no_grad` forwards or only feed a non-grad weight, so QQQ was the
only affected kernel.

New `tests/kernels/test_qqq_cpu_cache_inference_5197.py` is red on
`main` (2 failed, 1 passed) and green with the fix (3 passed).
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