Repository navigation
fix(qqq): build the CPU packed cache outside inference mode (#5197) - #5238
Merged
Merged
Conversation
`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).
Qubitium
marked this pull request as ready for review
November 18, 2026 13:08
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.
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()(everygenerate()/ eval loop) thecached
s_channelis an inference tensor, so the next grad-mode forward raisesRuntimeError: Inference tensors cannot be saved for backwardataccum = accum * s_channel(qqq.pyforward).Mechanism
torch.inference_mode()(
GPTQModel.generate()wrapsgenerateininference_mode; eval loops dothe same).
_packed_cpu_matmul()calls_packed_weight_for_cpu().pack_hf_int4(codes),_unpermute_scales(...),.to(...),.contiguous()all inherit the current inference flag, so the tuple stored on
self._torch_packed_cacheis made of inference tensors._maybe_drop_checkpoint_tensors()then proves the cache can rebuildB/s_group/s_channeland 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 isnow the only resident weight and it outlives the
inference_modeblock.requires_gradactivation) multiplies the INT32 accumulator by the cached
s_channel.Autograd must save that operand for the backward of
mul, and PyTorchrejects inference tensors there.
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 endFix
inference_mode(False)makes the cached operands normal tensors, so agrad-mode forward can save
s_channelfor backward.no_grad()is required as well: on this torch (2.15.0) a nestedinference_mode(False)re-enables the enclosing grad mode, and the builder(which also rebuilds/compares the checkpoint tensors) must not record a
graph.
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, thenbackward().QQQTorchLinear_torch_packed_cachetuple, built in first forwardTorchLinear_zeros_cache,_g_idx_long_cache(metadata only;g_idxalready normalised inpost_init)TorchFusedLinear/TorchAtenLinear/TorchCpuAvx512Lineartransform_cpu/ int4pack), forward is@torch.no_gradTorchFusedAwqLinear/TorchAtenAwqLinear/TorchCpuAvx512AwqLinearParoLinear_ensure_cpu_layoutbuffer rewrite, forward no-grad_int8_weight_for_forward)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).pytest tests/kernels/test_qqq_cpu_cache_inference_5197.py -q(fix stashed).scratch/repro.py(fix stashed)RuntimeError: Inference tensors cannot be saved for backwardatqqq.py:1252.scratch/repro.py.scratch/audit_siblings.pyQQQTorchLinearredpytest 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"/tmp/issue5197-redpytest tests/kernels/test_kernel_compile_levels_cpu.py -k QQQuvx [email protected] check gptqmodel docs/eora tests setup.pyTests
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 agrad-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 cachedirectly inside
inference_mode()and asserts no cached operandis_inference(). Red pre-fix on every host, including ones without AVX512.test_grad_forward_after_in_session_quantize_matches— packs the moduleinside
inference_mode()(asQQQ.quantizedoes), 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_128and the 8tests/kernels/test_qqq_workspace.pycases build the CUDAQQQLinearkerneland raise
ImportError: QQQ: CUDA is not availableunderCUDA_VISIBLE_DEVICES=""; they pass in isolation on a CUDA host.diffof theFAILED lists shows the only delta is the two new red tests.
What could not be verified
generate()-> training on a quantized checkpoint (no GPUand no cached model for this task); the unit-level ordering is covered.
fallback was audited by reading the code, not executed.
torch.compilere-measurement of QQQ CPU levels after adding the decorators(the builder is never traced —
_packed_cpu_matmulreturns early whencompiling — but no fresh inductor run was made).