Skip to content

fix(exl3): own kernel scratch per call instead of per device (#4619) - #4645

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4619-exl3-scratch-streams
Nov 17, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4619-exl3-scratch-streams

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4619

TL;DR

EXL3 kept three writable kernel buffers as process-wide state — the split-K
lock array and the hgemm cuBLAS workspace per device, and the bsz == 1
Hadamard input per (device, shape, dtype). Two forwards on different streams
therefore wrote the same memory: wrong output (max rel err 1.68 measured) or a
GPU deadlock. All three are now allocated per call from the caching allocator,
so each launch owns its scratch and nothing is cached. Net: 15 files,
+358/−94, no new configuration, no environment switch.

1. The problem

flowchart LR
    subgraph OLD["Old: writable scratch shared per device or per shape"]
        L1["LinearEXL3 on stream s1"] -->|"bc.run"| K1["exl3_gemm"]
        L2["LinearEXL3 on stream s2"] -->|"bc.run"| K1
        K1 --> LK["DevCtx::get_locks(device)<br/>int[MAX_TILES_C], 4 MiB<br/>one array per device"]
        H1["hgemm on s1"] --> WS["DevCtx::get_ws(device)<br/>4 MiB, one buffer per device"]
        H2["hgemm on s2"] --> WS
        X1["bsz == 1 module A"] --> XH["g_tensor_cache<br/>device, shape (1, in_features), dtype"]
        X2["bsz == 1 module B"] --> XH
    end
Loading
Scratch Old owner Evidence (pre-fix)
Split-K lock array one cudaMalloced MAX_TILES_C INT32 array per device, handed to every launch gptqmodel_ext/exllamav3/quant/exl3_devctx.cu:65 DevCtx::get_locks, quant/exl3_gemm.cu:91, quant/exl3_gemm_inner.cuh:370-372,519
hgemm cuBLAS workspace one 4 MiB cudaMalloc per device installed on the caller's handle with cublasSetWorkspace gptqmodel_ext/exllamav3/hgemm.cu:56-57, quant/exl3_devctx.cu:52 DevCtx::get_ws
bsz == 1 Hadamard input (xh) one buffer per (device, (1, in_features), dtype) in g_tensor_cache, shared by q/k/v/gate/up of the same width gptqmodel/exllamav3/modules/quant/exl3.py:80-89, gptqmodel_ext/exllamav3/libtorch/linear.cpp:30

The lock array is not a cache, it is a barrier. exl3_gemm is launched
cooperatively and its CTAs spin in barrier_acquire/barrier_release on
locks[slice_m * blocks_n + slice2_n]. When two launches are co-resident (a
kernel that does not fill the SMs — narrow N, for example the k/v projections
of a GQA model) they increment and reset the same counters: a CTA either reads
a stage that never happened (wrong output) or waits for a release that another
kernel already consumed (deadlock).

The hgemm workspace is state on the cuBLAS handle while the GEMM runs
asynchronously. The handle is per thread, but one thread can drive several
streams, so a second forward replaced the handle's pointer and wrote into the
4 MiB buffer while the first GEMM was still reading it.

The xh buffer is worse than per-device: it was keyed by shape, so two
different modules of the same width shared it, and the same module called
from two streams shared it with itself.

2. The new flow

flowchart LR
    subgraph NEW["New: one allocation per kernel call"]
        L1["LinearEXL3 on stream s1"] -->|"bc.run"| A1["at::zeros<br/>tiles_m x (size_n / 16) int32"]
        L2["LinearEXL3 on stream s2"] -->|"bc.run"| A2["independent at::zeros"]
        A1 --> K1["exl3_gemm on s1"]
        A2 --> K2["exl3_gemm on s2"]
        H1["hgemm on s1"] --> W1["at::empty 4 MiB<br/>cublasSetWorkspace"]
        H2["hgemm on s2"] --> W2["independent at::empty"]
        B1["bc_linear_exl3_run"] --> X1["at::empty_like(x)"]
        K1 -->|"launch enqueued"| FREE1["block returned to the<br/>caching allocator"]
        W1 -->|"launch enqueued"| FREE1
    end
Loading
Before After
Cache key device for locks and workspace No cache; one allocation per call
Entries kept for the life of the process Freed when the launch is enqueued
4 MiB lock array per device, 4 MiB workspace per device tiles_m x (size_n / 16) x 4 bytes of locks, 4 MiB workspace, live for one call
Stream exclusivity needed a key Exclusivity by construction
xh shared by shape xh allocated in bc_linear_exl3_run

3. Per-subsystem detail

Lock array — exl3_gemm now allocates at::zeros({tiles_m * (size_n / 16)}, int32) after kernel selection. The kernel indexes
locks[slice_m * blocks_n + slice2_n] with blocks_n = size_n / 16; tiles_m
is ceil(size_m / 16), and EXL3_GEMM_TILESIZE_M is now a single constant
shared by the four shape macros and the host sizing so the two cannot drift.
The old array was MAX_TILES_C = 1024 * 1024 ints (4 MiB) for a bound that is
size_n / 16 (896 ints for N=14336). Zeroing is required by the barrier
protocol; the kernel leaves the array zeroed, but that reset is no longer
load-bearing because the next call does not see this allocation.

hgemm workspace — hgemm allocates at::empty({WORKSPACE_SIZE}, kByte),
calls cublasSetWorkspace on the per-thread handle, and a scope guard resets
the handle to its default (cublasSetWorkspace(handle, nullptr, 0), verified
to return CUBLAS_STATUS_SUCCESS) before the tensor is released. That is the
same discipline ATen's CUDABlasHandleWithWorkspace guard documents
("restores the default before releasing it"). Restoring matters: leaving the
handle pointing at a freed block would let a later Torch BLAS call on the same
thread use a released pointer. The enqueued kernel already holds the pointer it
was launched with, so the host-side reset cannot affect it.

Hadamard input — bc_linear_exl3_run allocates at::empty_like(x) for
every batch size (the M > 1 branch already did). BC_LinearEXL3 no longer
takes an xh argument, the torch.ops schema loses it, and LinearEXL3 stops
reserving the g_tensor_cache entry. LinearEXL3.unload() therefore has no
shared buffer to drop.

Lifetime argument for all three: the allocation is made and released on the
stream that runs the kernel, so the caching allocator only reuses a freed block
for ordered work on that stream. A later kernel on the same stream is ordered
after this one; a kernel on another stream never receives the block.

4. Failure and ambiguity contract

Situation Before After
Two co-resident bc.run launches shared counters → wrong output or deadlock independent counters
hgemm on stream s2 while s1 runs s2 overwrites s1's workspace independent workspaces
Two modules of the same width at M == 1 shared xh independent xh
Same module called from two streams shared xh and workspace independent
Allocation fails — normal Torch OOM propagates; no partial cache state to unwind
ROCm bc.run unavailable; hgemm workspace was also device-global hgemm workspace per call; bc.run still NVIDIA-only

5. Change inventory

Area File ± Purpose
lock scratch gptqmodel_ext/exllamav3/quant/exl3_gemm.cu +19/−2 per-call zeroed lock array
lock sizing gptqmodel_ext/exllamav3/quant/exl3_kernel_map.cuh +13/−4 EXL3_GEMM_TILESIZE_M shared by shapes and host
device ctx gptqmodel_ext/exllamav3/quant/exl3_devctx.cu, .cuh +14/−50 remove get_locks/get_ws, MAX_TILES_C; keep read-only attrs
hgemm gptqmodel_ext/exllamav3/hgemm.cu +27/−3 per-call workspace + default restore
xh libtorch/linear.cpp, linear.h, linear_bc.h, bindings.cpp +39/−26 drop caller-supplied xh, allocate per call
Python gptqmodel/exllamav3/ext.py, modules/quant/exl3.py +12/−6 drop xh plumbing and g_tensor_cache reservation
tests tests/test_exl3_dispatch_concurrency.py, tests/test_exllamav3_jit.py +196/−6 new regressions; wrapper test follows the new signature
docs docs/kernel-scratch-lifecycle.md, README.md +88/−2 EXL3 scratch section + link text

6. Tests / guarantees

Test Invariant
test_exl3_linears_do_not_share_a_writable_kernel_buffer two EXL3 layers with the same (in_features, out_features) pass no common tensor to the kernel and leave g_tensor_cache empty; host-only, no extension needed
test_concurrent_streams_do_not_share_exl3_kernel_scratch four threads over two modules, each on its own stream, M in {1, 4, 8, 256}, bitwise equal to the serial reference; child-process watchdog turns a deadlock into a failure
test_exllamav3_bc_linear_wrapper_uses_jit_op wrapper passes the new 8-argument schema

M == 1 covers the bsz == 1 Hadamard buffer, M == 4/8 the lock array,
M == 256 hgemm and its workspace. Two modules with four threads means two
threads share a module, which a per-module buffer would still corrupt.

7. Validation

Hardware: RTX 4090 (SM89), CUDA_VISIBLE_DEVICES=GPU-1892aea4-cc09-827c-b9a5-93d4eef7f5ae,
Python 3.14t, torch 2.16.0.dev20261102+cu130. ROCm: R9700 (gfx1201),
HIP_VISIBLE_DEVICES=0, torch 2.16.0.dev20261025+rocm10.1.
All runs exported OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 NUMEXPR_NUM_THREADS=4.

Issue snippet (random trellis, 2000 calls per thread, bitwise compare with the
serial output; each case in a fresh process):

Case (M, N, K) Before After
8, 512, 2048 (locks) GPU deadlock, process killed (one run); another run gave 0 mismatches 0 mismatches, rel err 0.000
4, 512, 2048 (locks) 329–881 mismatches of 2000, rel err 0.549 (one run); another run gave 0 0 mismatches, rel err 0.000
1, 8192, 2048 (bsz == 1 xh) 1–25 mismatches of 2000, rel err 1.204 0 mismatches, rel err 0.000
256, 512, 2048 (hgemm) 387–788 mismatches of 2000, rel err 1.683 0 mismatches, rel err 0.000
serial control, M=1/8/256 0 mismatches 0 mismatches

The lock-array failure is nondeterministic (it depends on whether the first
launch already filled the SMs), which is why the regression test uses a
watchdog and several M.

Red/green for the new tests (pre-fix tree obtained with git stash of the fix;
the pre-fix JIT build was already cached):

$ pytest tests/test_exl3_dispatch_concurrency.py -q -k "writable_kernel_buffer or concurrent_streams"
FAILED test_exl3_linears_do_not_share_a_writable_kernel_buffer
  AssertionError: two EXL3 layers alias a kernel buffer
FAILED test_concurrent_streams_do_not_share_exl3_kernel_scratch
  HANG [1, 1, 1, 2, 2, 1, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0] ... assert 3 == 0
2 failed, 2 deselected in 97.78s

After the fix:

$ pytest tests/test_exl3_dispatch_concurrency.py tests/test_exllamav3_jit.py \
    tests/test_exllamav3.py tests/test_exl3_buffer_dtype.py tests/test_exl3_wide_input.py \
    tests/test_exllamav3_torch_padding.py tests/test_exl3_generic_geometry.py \
    tests/test_exllamav3_cpu.py tests/test_exl3_native_half_rounding.py -q -p no:cacheprovider
245 passed, 2 skipped in 24.81s

The two skips are test_exllamav3_torch_rocm_forward_runs_and_matches_oracle
("ROCm GPU required") on the CUDA host.

ROCm:

$ HIP_VISIBLE_DEVICES=0 pytest tests/test_exllamav3_jit.py \
    tests/test_exl3_dispatch_concurrency.py tests/test_exllamav3.py -q -p no:cacheprovider
25 passed, 3 skipped in 5.53s

The EXL3 JIT extension rebuilds on ROCm (30 s) and the hgemm path runs; the
three skips are the NVIDIA-only tensor-core tests.

Lint:

$ ruff check gptqmodel docs/eora tests setup.py
All checks passed!

Performance spot check on a 4096x14336 prefill shape (median of 100 forwards,
two runs each): M=256 346–347 us before, 348–349 us after; M=1024
720–724 us before, 724 us after. The per-call allocations come from the caching
allocator; the difference is within run-to-run variance (~2 us, <1%). The
device was also hosting another process, so treat these as approximate.

8. Reviewer notes / limitations

  • The real-checkpoint repro from the issue was not repeated: this host has no
    EXL3 checkpoint. The random-trellis snippet reaches the same three kernels
    and reproduces the defect, and the numeric results above are from that
    snippet.
  • The ROCm hgemm race did not reproduce here: with the pre-fix build, four
    threads on M=256/K=8192/N=4096 (fp16), M=256/K=4096/N=2048 (fp32) and
    M=1024/K=4096/N=14336 gave 0 mismatches both before and after. The fix is
    applied to the shared code path and the ROCm build is green, but I am not
    claiming a measured ROCm numerical regression.
  • bc_linear_exl3_run's schema changes (no xh argument). It is internal to
    this package; the only caller is _BCLinearEXL3.
  • No GPTQMODEL_* switch is added. The 4 MiB hgemm workspace is still 4 MiB,
    now per call instead of per device.

The EXL3 CUDA inference path kept three writable scratch buffers as
process-wide state: the split-K lock array and the 4 MiB hgemm cuBLAS
workspace were one allocation per device, and the bsz == 1 Hadamard input
(`xh`) was one buffer per `(device, shape, dtype)` shared by every module
with the same in_features. Two forwards on different streams therefore
wrote the same memory. The lock array is a barrier: two co-resident
launches read each other's stages, which gave silently wrong output or a
GPU deadlock. Concurrent hgemm calls overwrote the handle's workspace
while the other GEMM still read it, and the shared `xh` corrupted decode.

All three are now owned by exactly one call:

- `exl3_gemm` allocates zeroed `tiles_m * (size_n / 16)` INT32 locks from
  the caching allocator. The kernel indexes `locks[slice_m * blocks_n +
  slice2_n]`, so that product is the bound; `EXL3_GEMM_TILESIZE_M` keeps
  the host sizing tied to the kernel's m tile. The array is per launch,
  and the kernel's own reset is no longer load-bearing.
- `hgemm` allocates its 4 MiB workspace per call, installs it on the
  per-thread cuBLAS handle, and restores the handle's default before the
  allocation is released, like ATen's scoped workspace guard.
- `bc_linear_exl3_run` allocates `at::empty_like(x)` for the Hadamard
  input at every batch size, and `BC_LinearEXL3` no longer takes a caller
  buffer. `LinearEXL3` stops reserving the `g_tensor_cache` entry.

Each allocation is made and released on the stream that runs the kernel,
so the caching allocator only reuses it for ordered work on that stream.
Nothing is cached per device, per stream, or per module, so there is no
cleanup story to add. The redundant `DevCtx::get_ws`/`get_locks` per-device
buffers and `MAX_TILES_C` are removed; `DevCtx` keeps the read-only device
attributes.

Regression: `tests/test_exl3_dispatch_concurrency.py` gains a host-side
ownership test (two layers must not share a tensor and must leave no
process-wide bsz-1 buffer) and a real concurrent-stream test at M in
{1, 4, 8, 256}, four threads over two modules, with a hang watchdog.
Both fail on the pre-fix code; the concurrent test deadlocks it.
@Qubitium
Qubitium merged commit 355ef40 into main Nov 17, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4619-exl3-scratch-streams branch November 17, 2026 06:36
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

1 participant