Repository navigation
fix(qqq): allocate the reduce scratch per call instead of caching it (#4621) - #4626
Merged
Merged
Conversation
…4621) `qqq_gemm` uses its `C` argument only as the INT32 global-reduce scratch of one call, and `global_reduce` writes each column slice before reading it, so nothing in `C` carries across calls. A zeroed and a garbage-filled buffer give bitwise-equal output. The per-device cache added for #4387 and its stream-keyed replacement for #4488 were never pruned: every stream that ran a QQQ forward kept a max-width buffer for the life of the process (32 pooled streams pinned 1.75 GiB on an 8B model), and `del model` released none of it. Allocate the scratch with `torch.empty` in the forward and let the caching allocator reuse the block. Each call owns its buffer, so cross-stream aliasing is impossible by construction, and the eager and compiled paths now share one implementation instead of a cache and a `torch.zeros` branch. Measured with a three-layer mixed-width 8B-shaped stack: live scratch after 8 streams went from 896.0 MiB to 0.0 MiB, and after `del model` from 1065.9 MiB to the harness baseline. Per-call cost was 0.0-0.3 us on the 4096x14336 shapes, where one kernel call is 13.9 us.
This was referenced Nov 17, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 17, 2026
…4717) `qqq_gemm.cu` spins on and resets the counters in its `workspace` argument, so one lock array per `QQQLinear` let two streams serving the same module increment and reset each other's counters; the kernel never completed and the device had to be reset. The per-call reduce scratch from #4626 covered only `C`, and the docs' "stream-safe by construction" claim did not hold for this second writable buffer. `QQQLinear._split_k_locks(device)` allocates a zeroed `ceil(out_features / 64) * max_par` INT32 array for each forward, matching EXL3's per-call locks (#4645). The registered `workspace` buffer stays only so existing checkpoints keep loading; the kernel no longer reads it. Tests: `tests/kernels/test_qqq_workspace.py::test_forward_allocates_a_fresh_lock_array_per_call` fails on unmodified main (both calls receive the same tensor) and asserts two distinct zeroed arrays of the kernel's size. QQQ suites: 280 passed, 65 skipped, 1 pre-existing `test_qqq_export_scale` tolerance failure also present on main. The CUDA concurrency repro needs two GPUs and is not runnable here.
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.
TL;DR
FIXS #4621
QQQ's INT32
qqq_gemmreduce scratch (C) is now allocated per kernel callrather than cached per
(device, stream). The cache from #4524 was neverpruned, so every stream that ever ran a QQQ forward pinned a max-width buffer
for the life of the process, and
del modelreleased none of it. Net diff:6 files, +308/-169;
qqq.pyloses the cache, its lock and itstorch.compilespecial case.
1. The problem
qqq_gemm.cuusesConly as a global-reduction buffer.global_reducewrites a column slice before reading it and
barrier_releasepublishes it, soCis call-local state. That was not modelled by the ownership: #4387 replacedone buffer per module (5.25 GiB on Llama-3-8B) with one lazily grown buffer per
device, and #4524 keyed that cache by
(device, stream handle)to fix across-stream race — but nothing ever removed an entry.
flowchart LR subgraph OLD["Old: process-wide cache keyed by device + stream handle"] L1["QQQLinear on stream s1"] -->|"get-or-grow"| R1["_REDUCE_SCRATCH[(cuda:0, s1)]<br/>int32[1024 * N]"] L2["QQQLinear on stream s2"] -->|"get-or-grow"| R2["_REDUCE_SCRATCH[(cuda:0, s2)]<br/>int32[1024 * N]"] R1 -.->|"never pruned"| LEAK["still allocated after del model<br/>32 streams x 56 MiB"] R2 -.-> LEAK end style LEAK fill:#f8d7da,stroke:#b02a37_REDUCE_SCRATCHprocess-wide dictgptqmodel/nn_modules/qlinear/qqq.py:50del modeldoes not clear it_REDUCE_SCRATCH_LOCKqqq.py:49_shared_reduce_scratch(..., stream=...)key lookupqqq.py:53-83torch.compiler.is_compiling()+torch.zerosbranchqqq.py:451-458_clear_reduce_scratch()qqq.py:86-90The reproduction from the report was re-measured before the fix on a 4096x14336
layer: 10 distinct streams retained 560 MiB in 11 cache entries and 616 MiB was
still allocated after
del modelplusempty_cache.2. The new flow
flowchart LR subgraph NEW["New: one allocation per kernel call"] L1["QQQLinear.forward"] -->|"_reduce_scratch(A.device)"| A1["_allocate_reduce_scratch<br/>torch.empty(16 * 64, out_features) int32"] A1 --> K1["qqq_gemm C on the current stream"] K1 -->|"forward returns"| FREE["block returned to the<br/>caching allocator"] S1["stream s1"] --> A1 S2["stream s2"] --> A2["independent allocation"] A2 --> K2["qqq_gemm C on s2"] end style FREE fill:#d1e7dd,stroke:#146c43QQQLinear._reduce_scratch()now calls_allocate_reduce_scratch, which returnsa fresh contiguous
(max_par * 64, out_features)INT32 tensor. There is no key,no lock and no entry to leak. Cross-stream aliasing is impossible by
construction: two calls cannot receive the same live block, and the caching
allocator only reuses a freed block on the stream that freed it, where stream
ordering provides the dependency.
QQQTorchLinearnever allocates it, as before,because the portable kernel does not take
C.(device, stream handle), never pruned1024 x N x 4bytes, live for one calltorch.zerostorch.empty3. Why per call is safe:
Cis write-before-readThis is the load-bearing property, so it is pinned by a test rather than
asserted in prose.
test_qqq_gemm_ignores_the_initial_contents_of_cfillsCwith
0,-1andINT32_MAXand checks bitwise-equal outputs across fourshapes, including the multi-slice global-reduce path and
max_parparallelproblems.
Cpar=164. Validation
Correctness and numerics, native kernel versus the portable Torch path, on
NVIDIA (
torch 2.15.0+cu132, SM89) and AMD (torch 2.16.0.dev+rocm7.16, gfx1201):tests/test_qqq_kernel_memory_4387.py,tests/test_qqq_kernel_memory_4621.pytests/kernels/test_qqq_workspace.pytests/kernels/test_inference_numeric_range.py,tests/test_qqq_jit.py,tests/test_qqq_config.py,tests/test_qqq_uncaptured_fallback_4468.py,tests/test_qqq_descact_oom_device_4538.py,tests/test_qqq_exl3_oom_fallback_4400.pytests/test_gsq_method_adapters.py::test_calibrated_fp8_*(FP8 bias dtype) also fail on unpatchedmaintorch.compileparity (fullgraph=False)torch.cuda.CUDAGraphcapture and replayMemory, three-layer mixed-width 8B-shaped stack (4096x14336, 4096x4096,
4096x28672), separate processes per cell. "Live" is
memory_allocatedabovethe post-warmup baseline:
del modeldel modelThe flat 57.9 MiB per-call residual is the harness's own allocation baseline, not
scratch; it does not vary with stream count. A single-layer probe that ran eight
streams returned to
allocated 0.0 MiB, reserved 0.0 MiBafter teardown.Cost, isolated
qqq_gemmcalls with a reused versus a per-callC:CCThe absolute delta is small because
torch.emptyon a warm allocator is apointer bump; it is noisier on the tiny 896x4864 shapes, where the allocator
call is a larger fraction of a 5-6 us kernel.
5. Failure and ambiguity contract
stateDiagram-v2 [*] --> Allocate: forward on stream s Allocate --> Running: qqq_gemm enqueued Running --> Released: forward returns, Python drops C Released --> Reused: allocator hands the block to stream s Released --> Returned: empty_cache / process teardown Allocate --> Error: out of memory Error --> [*]: raises to caller, nothing is cacheddel modelempty_cachereturns ittorch.compiletorch.zerospathtorch.emptypath6. Change inventory
gptqmodel/nn_modules/qlinear/qqq.py_allocate_reduce_scratchtests/test_qqq_kernel_memory_4387.pytests/test_qqq_kernel_memory_4621.pyCwrite-before-read and post-teardown releasedocs/kernel-scratch-lifecycle.mdREADME.mdpytorch_gil_0_compat.mdtorch.empty7. Reviewer notes
events,
record_streambookkeeping and a prune policy; per-call allocationneeds none of that and measured within 0.3 us on the shapes that matter.
Tensor.record_streamis still UNVERIFIED under GIL=0 in the ledger, andthis change avoids depending on it.
torch.emptyrather thantorch.zeros: the zero-fill was only there tomimic the old per-module buffer, and it costs 50-70 us per call on these
shapes.
empty_cache, exactly as any activation buffer would. It is not a live setand it is not retained by the library.