Repository navigation
fix(exl3): own kernel scratch per call instead of per device (#4619) - #4645
Merged
Merged
Conversation
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
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.
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 == 1Hadamard input per
(device, shape, dtype). Two forwards on different streamstherefore 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 endcudaMallocedMAX_TILES_CINT32 array per device, handed to every launchgptqmodel_ext/exllamav3/quant/exl3_devctx.cu:65DevCtx::get_locks,quant/exl3_gemm.cu:91,quant/exl3_gemm_inner.cuh:370-372,519cudaMallocper device installed on the caller's handle withcublasSetWorkspacegptqmodel_ext/exllamav3/hgemm.cu:56-57,quant/exl3_devctx.cu:52DevCtx::get_wsbsz == 1Hadamard input (xh)(device, (1, in_features), dtype)ing_tensor_cache, shared by q/k/v/gate/up of the same widthgptqmodel/exllamav3/modules/quant/exl3.py:80-89,gptqmodel_ext/exllamav3/libtorch/linear.cpp:30The lock array is not a cache, it is a barrier.
exl3_gemmis launchedcooperatively and its CTAs spin in
barrier_acquire/barrier_releaseonlocks[slice_m * blocks_n + slice2_n]. When two launches are co-resident (akernel 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
xhbuffer is worse than per-device: it was keyed by shape, so twodifferent 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 enddevicefor locks and workspacetiles_m x (size_n / 16) x 4bytes of locks, 4 MiB workspace, live for one callxhshared by shapexhallocated inbc_linear_exl3_run3. Per-subsystem detail
Lock array —
exl3_gemmnow allocatesat::zeros({tiles_m * (size_n / 16)}, int32)after kernel selection. The kernel indexeslocks[slice_m * blocks_n + slice2_n]withblocks_n = size_n / 16;tiles_mis
ceil(size_m / 16), andEXL3_GEMM_TILESIZE_Mis now a single constantshared by the four shape macros and the host sizing so the two cannot drift.
The old array was
MAX_TILES_C = 1024 * 1024ints (4 MiB) for a bound that issize_n / 16(896 ints for N=14336). Zeroing is required by the barrierprotocol; 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 —
hgemmallocatesat::empty({WORKSPACE_SIZE}, kByte),calls
cublasSetWorkspaceon the per-thread handle, and a scope guard resetsthe handle to its default (
cublasSetWorkspace(handle, nullptr, 0), verifiedto return
CUBLAS_STATUS_SUCCESS) before the tensor is released. That is thesame discipline ATen's
CUDABlasHandleWithWorkspaceguard 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_runallocatesat::empty_like(x)forevery batch size (the
M > 1branch already did).BC_LinearEXL3no longertakes an
xhargument, the torch.ops schema loses it, andLinearEXL3stopsreserving the
g_tensor_cacheentry.LinearEXL3.unload()therefore has noshared 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
bc.runlauncheshgemmon stream s2 while s1 runsM == 1xhxhxhand workspacebc.rununavailable; hgemm workspace was also device-globalbc.runstill NVIDIA-only5. Change inventory
gptqmodel_ext/exllamav3/quant/exl3_gemm.cugptqmodel_ext/exllamav3/quant/exl3_kernel_map.cuhEXL3_GEMM_TILESIZE_Mshared by shapes and hostgptqmodel_ext/exllamav3/quant/exl3_devctx.cu,.cuhget_locks/get_ws,MAX_TILES_C; keep read-only attrsgptqmodel_ext/exllamav3/hgemm.cuxhlibtorch/linear.cpp,linear.h,linear_bc.h,bindings.cppxh, allocate per callgptqmodel/exllamav3/ext.py,modules/quant/exl3.pyxhplumbing andg_tensor_cachereservationtests/test_exl3_dispatch_concurrency.py,tests/test_exllamav3_jit.pydocs/kernel-scratch-lifecycle.md,README.md6. Tests / guarantees
test_exl3_linears_do_not_share_a_writable_kernel_buffer(in_features, out_features)pass no common tensor to the kernel and leaveg_tensor_cacheempty; host-only, no extension neededtest_concurrent_streams_do_not_share_exl3_kernel_scratchM in {1, 4, 8, 256}, bitwise equal to the serial reference; child-process watchdog turns a deadlock into a failuretest_exllamav3_bc_linear_wrapper_uses_jit_opM == 1covers thebsz == 1Hadamard buffer,M == 4/8the lock array,M == 256hgemm and its workspace. Two modules with four threads means twothreads 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):
bsz == 1xh)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 stashof the fix;the pre-fix JIT build was already cached):
After the fix:
The two skips are
test_exllamav3_torch_rocm_forward_runs_and_matches_oracle("ROCm GPU required") on the CUDA host.
ROCm:
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:
Performance spot check on a 4096x14336 prefill shape (median of 100 forwards,
two runs each):
M=256346–347 us before, 348–349 us after;M=1024720–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
EXL3 checkpoint. The random-trellis snippet reaches the same three kernels
and reproduces the defect, and the numeric results above are from that
snippet.
threads on
M=256/K=8192/N=4096(fp16),M=256/K=4096/N=2048(fp32) andM=1024/K=4096/N=14336gave 0 mismatches both before and after. The fix isapplied 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 (noxhargument). It is internal tothis package; the only caller is
_BCLinearEXL3.GPTQMODEL_*switch is added. The 4 MiB hgemm workspace is still 4 MiB,now per call instead of per device.