Skip to content

fix(qqq): allocate the reduce scratch per call instead of caching it (#4621) - #4626

Merged
Qubitium merged 1 commit into
mainfrom
fix/4621-qqq-scratch
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/4621-qqq-scratch

Conversation

@ZX-ModelCloud

@ZX-ModelCloud ZX-ModelCloud commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR

FIXS #4621

QQQ's INT32 qqq_gemm reduce scratch (C) is now allocated per kernel call
rather than cached per (device, stream). The cache from #4524 was never
pruned, so every stream that ever ran a QQQ forward pinned a max-width buffer
for the life of the process, and del model released none of it. Net diff:
6 files, +308/-169; qqq.py loses the cache, its lock and its torch.compile
special case.

1. The problem

qqq_gemm.cu uses C only as a global-reduction buffer. global_reduce
writes a column slice before reading it and barrier_release publishes it, so
C is call-local state. That was not modelled by the ownership: #4387 replaced
one 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 a
cross-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
Loading
Mechanism being removed Where it lived Why it was wrong
_REDUCE_SCRATCH process-wide dict gptqmodel/nn_modules/qlinear/qqq.py:50 Entries are never pruned; del model does not clear it
_REDUCE_SCRATCH_LOCK qqq.py:49 Only guarded allocation, never a use lease (#4488)
_shared_reduce_scratch(..., stream=...) key lookup qqq.py:53-83 Bounded at ~64 buffers per device for pool streams, unbounded for raw handles
torch.compiler.is_compiling() + torch.zeros branch qqq.py:451-458 A second path existed only because the cache could not be a graph constant
_clear_reduce_scratch() qqq.py:86-90 Teardown hook that only tests called

The 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 model plus empty_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:#146c43
Loading

QQQLinear._reduce_scratch() now calls _allocate_reduce_scratch, which returns
a 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. QQQTorchLinear never allocates it, as before,
because the portable kernel does not take C.

Before After
Cache key (device, stream handle), never pruned No cache; one allocation per call
One max-width buffer per stream, 56 MiB on 8B 1024 x N x 4 bytes, live for one call
Stream exclusivity enforced by the key Exclusivity by construction
Eager uses the cache, compiled uses torch.zeros Both use torch.empty

3. Why per call is safe: C is write-before-read

This 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_c fills C
with 0, -1 and INT32_MAX and checks bitwise-equal outputs across four
shapes, including the multi-slice global-reduce path and max_par parallel
problems.

Shape Slices in C Output equality across fills
896x4864, M=1 1 bitwise equal
1024x4096, M=16 4 bitwise equal
4096x14336, M=16 16 bitwise equal
4096x14336, M=64 16, par=16 bitwise equal

4. 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):

Check Result
tests/test_qqq_kernel_memory_4387.py, tests/test_qqq_kernel_memory_4621.py 16 passed (CUDA), 17 passed / 6 skipped (ROCm; native-kernel tests skip by design)
tests/kernels/test_qqq_workspace.py 7 passed
tests/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.py 388 passed
Pre-existing failures unrelated to this change tests/test_gsq_method_adapters.py::test_calibrated_fp8_* (FP8 bias dtype) also fail on unpatched main
torch.compile parity (fullgraph=False) bitwise equal, max diff 0.0
torch.cuda.CUDAGraph capture and replay capture OK, bitwise equal
M in 1, 2, 15, 16, 17, 63, 64, 65, 129 repeated forwards bitwise equal

Memory, three-layer mixed-width 8B-shaped stack (4096x14336, 4096x4096,
4096x28672), separate processes per cell. "Live" is memory_allocated above
the post-warmup baseline:

Streams seen Cached design: live / after del model Per call: live / after del model
1 112.0 MiB / 281.9 MiB 0.0 MiB / 57.9 MiB
8 896.0 MiB / 1065.9 MiB 0.0 MiB / 57.9 MiB
32 3584.0 MiB / 3753.9 MiB 0.0 MiB / 57.9 MiB

The 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 MiB after teardown.

Cost, isolated qqq_gemm calls with a reused versus a per-call C:

Shape Reused C Per-call C Delta
K=128, N=128, M=1 6.18 us 7.30 us +1.11 us
K=896, N=4864, M=1 5.02 us 6.27 us +1.25 us
K=896, N=4864, M=16 6.11 us 7.16 us +1.04 us
K=4096, N=14336, M=1 13.89 us 13.90 us +0.00 us
K=4096, N=14336, M=16 13.60 us 13.90 us +0.30 us

The absolute delta is small because torch.empty on a warm allocator is a
pointer 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 cached
Loading
Situation Before After
del model Cache keeps every stream's buffer No reference remains; empty_cache returns it
Concurrent streams Independent entries, kept forever Independent blocks per call
torch.compile Separate torch.zeros path Same torch.empty path
Allocation failure Grew/kept cache entries Raises; no state is left behind

6. Change inventory

Area File +/- Purpose
Kernel scratch gptqmodel/nn_modules/qlinear/qqq.py +40/-56 Remove cache/lock/compiled branch, add _allocate_reduce_scratch
Tests tests/test_qqq_kernel_memory_4387.py +69/-67 Replace cache-identity assertions with per-call contracts
Tests tests/test_qqq_kernel_memory_4621.py +144 C write-before-read and post-teardown release
Docs docs/kernel-scratch-lifecycle.md +67/-30 History table, new flow, measured numbers
Docs README.md +1/-1 Link wording
GIL=0 ledger pytorch_gil_0_compat.md +1/-1 Record the per-call allocation under torch.empty

7. Reviewer notes

  • The alternative "keep the cache but drop entries with idle streams" needs
    events, record_stream bookkeeping and a prune policy; per-call allocation
    needs none of that and measured within 0.3 us on the shapes that matter.
    Tensor.record_stream is still UNVERIFIED under GIL=0 in the ledger, and
    this change avoids depending on it.
  • torch.empty rather than torch.zeros: the zero-fill was only there to
    mimic the old per-module buffer, and it costs 50-70 us per call on these
    shapes.
  • The allocator's reservation does grow with concurrent streams before
    empty_cache, exactly as any activation buffer would. It is not a live set
    and it is not retained by the library.

…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.
@Qubitium
Qubitium merged commit 9ef7da0 into main Nov 17, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/4621-qqq-scratch branch November 17, 2026 05:43
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants