Repository navigation
Description
Summary
On the CUDA backend (verified on NVIDIA GB10, sm_121), long-prompt prefill of 4-bit models aborts with SIGABRT (exit 134) once a CUDA kernel's grid dimension exceeds the hardware limit of 65535 for gridDim.y/gridDim.z. It is NOT out-of-memory (peak was ~20 GB of 122 GB) and NOT a timeout. It surfaces in the long-prompt prefill benchmark (scripts/bench_longprompt.sh, epic #623/#624) as FAIL:bench cells.
Error
terminate called after throwing an instance of 'std::runtime_error'
what(): cuLaunchKernelEx(&config, func, params, nullptr) failed: invalid argument
(with CUDA graphs enabled it is the same error from cudaGraphAddKernelNode/cuGraphAddKernelNode.) MLX_USE_CUDA_GRAPHS=0 does NOT fix it: both the direct-launch and graph-capture paths reject the identical launch config, so it is not graph-specific. It is an uncaught exception from CHECK_CUDA_ERROR, hence std::terminate/abort (exit 134).
Reproduction (models under ./models, release bench binary)
./target/release/mlxcel-bench-decode -m ./models/qwen3-30b-a3b-4bit -p "Hi" -n 4 --warmup-tokens 2 --prompt-tokens 8192 # ABORTS (exit 134)
./target/release/mlxcel-bench-decode -m ./models/qwen3-30b-a3b-4bit -p "Hi" -n 4 --warmup-tokens 2 --prompt-tokens 8191 # SUCCEEDS (exit 0)
Root cause (MoE case, confirmed)
The 4-bit MoE path dispatches GatherQMM::eval_gpu (mlxcel overlay src/lib/mlx-cpp/patches/mlx/backend/cuda/quantized/quantized.cpp:163) into qmm_sm80 (upstream MLX mlx/backend/cuda/quantized/qmm/qmm_sm80.cu). At qmm_sm80.cu:77-80 the launch grid is built as:
dim3 num_blocks{
uint32_t(cute::ceil_div(m, cute::size<0>(cta_tiler))), // grid.x
uint32_t(cute::ceil_div(n, cute::size<1>(cta_tiler))), // grid.y
uint32_t(l)}; // grid.z = l (unclamped)where l = out.size()/(m*n) (qmm_utils.h:12) is the gathered-batch count. For MoE prefill the gathered output is [tokens, top_k, 1, N], so l = tokens * num_experts_per_tok. When l >= 65536 (i.e. tokens * top_k >= 65536), grid.z exceeds the CUDA gridDim.z max of 65535 and the launch is rejected with CUDA_ERROR_INVALID_VALUE. Unlike MLX's get_launch_args_general (kernel_utils.cu:53-62, which spills grid.y/z overflow into another dim at the 65535 boundary), qmm_sm80 (and its siblings qmm_naive, qmv) build the grid manually with no such clamp.
Evidence that it is exactly tokens * top_k > 65535 (rules out "8192 is a special power of two")
The failure threshold scales inversely with num_experts_per_tok:
- qwen3-30b-a3b-4bit (top_k=8): fails at 8192 (81928 = 65536), succeeds at 8191 (81918 = 65528). Peak memory at 8191 was only ~20 GB / 122 GB, so not OOM.
- mixtral-8x7b-4bit (top_k=2): succeeds at 8192, fails at 32768 (32768*2 = 65536).
Second, distinct instance (dense models)
Dense llama-3.1-8b-4bit also aborts with the same error, but via a DIFFERENT (non-qmm) kernel: dense QuantizedMatmul has l = 1, so it does not use the grid.z = l path. Bisection: @8192 ok, @16384 ok, @24576 FAIL, @32768 FAIL, consistent with a grid dimension ~= 3 * seq_len (crossing 65536 near seq around 21846). The exact kernel/line is not yet pinned (needs a symbolized build). This shows the 65535-unclamped-grid problem is not unique to qmm_sm80: other CUDA kernels build grid.y/z from sequence length without clamping.
Scope
CUDA-specific. The 65535 cap is a CUDA hardware limit on gridDim.y/gridDim.z (gridDim.x allows 2^31). The Metal backend uses the same grid_dims(M, (N+bn-1)/bn, B) batch-in-depth pattern but MTLSize grid dims are not capped at 65535, so Apple silicon is not expected to hit this at these sizes (not reproducible on the CUDA host; conclusion from source plus the hardware nature of the limit).
Harness note
scripts/bench_decode.sh (around lines 455-463) classifies these as FAIL:bench and prints only benchmark failed (exit N), discarding the captured stderr ($raw), so the sweep CSV/log never shows the actual CUDA error. Consider surfacing the last stderr lines on FAIL:bench to make future triage faster.
Proposed fix
In the mlxcel CUDA overlay, chunk the gathered/batched dimension l into slices of <= 65535 per launch (loop qmm_sm80 / qmm_naive / gather_qmv, offsetting the batch base pointers: for the gather path, offset lhs_indices/rhs_indices and out by the chunk start; x/w are addressed via the global index values). Validate token-exact output vs the working <= 65535 path (e.g. qwen3-30b @8192 vs @8191-scale reference, mixtral @32768). Separately pin and fix the dense-model kernel (~3x seq grid). This is fundamentally an upstream MLX CUDA-backend limitation worth reporting to ml-explore/mlx as well.
Acceptance Criteria
- MoE 4-bit prefill (qwen3-30b-a3b-4bit) completes at
--prompt-tokens 8192(and beyond) without abort, via chunking the gatheredldimension into<= 65535slices acrossqmm_sm80/qmm_naive/gather_qmv. - Output is token-exact vs the working
<= 65535path (qwen3-30b @8192 vs @8191-scale reference; mixtral-8x7b-4bit @32768). - The dense-model kernel (~3x seq grid,
llama-3.1-8b-4bitfailing at >= 24576) is pinned to an exact kernel/line and fixed with the same clamp/chunk approach. -
scripts/bench_decode.shsurfaces the last captured stderr lines onFAIL:benchinstead of discarding$raw. - The limitation is reported upstream to ml-explore/mlx.
Activity
inureyes commentedon Jul 3, 2026
Correction + refinement after further investigation
The dense-model case in the original report is a separate, distinct bug from the MoE case, and my initial
~3×seqcharacterization of it was wrong. Pinned via a symbolized backtrace. There are two distinct bugs, both aborting with the same...KernelNode ... invalid argument:Bug 1 — MoE (
qmm_sm80), grid.z too large. As described in the issue body:GatherQMM→qmm_sm80.cu:80setsgrid.z = l = tokens × num_experts_per_tok. Whentokens×top_k ≥ 65536this exceeds the CUDAgridDim.zmax of 65535. Genuine large batch. (qwen3-30b top_k=8 @8192; mixtral top_k=2 @32768.)Bug 2 — dense LM head (
qmv), grid.z == 0 from int32 overflow.QuantizedMatmul::eval_gpu→qmv. Backtrace showscu::qmv(m=23491, n=128256, k=4096, l=0);qmv.cu:276then setsgrid.z = l = 0, and a grid dim of 0 is invalid →cudaErrorInvalidValue. Root cause:int l = out.size() / (m * n)atqmv.cu:421(and identicallymake_problem_shapeatqmm_utils.h:12, andint B = out.size()/(M*N)inquantized.cpp).m*nis computed in int32; for the LM headtokens*vocab = 23491*128256 = 3.01e9 > 2^31, so it wraps negative and thesize_tdivision yields 0. Threshold:tokens × vocab ≥ 2^31(llama-3.1 vocab 128256 → ~16744 tokens). Confirmed razor-sharp: llama-3.1-8b-4bit @16384 ok, @17000 FAIL, @24576 FAIL — refuting the~3×seqhypothesis in the issue body.Fixes (different per bug):
out.size() / M / N):out.size() / (static_cast<size_t>(m) * n)atqmv.cu:421,qmm_utils.h:12, and thequantized.cppBcomputations.linto ≤65535 slices per launch.Scope: CUDA-only, confirmed for both. The Metal backend uses
int B = out.size() / M / N(sequential size_t division, noM*Nint product) and MTLSize grid dims are not capped at 65535, so Apple silicon is affected by neither bug. No Metal fix required.inureyes commentedon Jul 3, 2026
Fix implemented + validated (for the bench/sweep path)
Both grid-limit bugs are fixed in the mlxcel-owned CUDA overlay
src/lib/mlx-cpp/patches/mlx/backend/cuda/quantized/quantized.cpp(no new overlay files, no CMake reconfigure):row_view/batch_view/flat_viewbuild sub-array views viaarray::copy_shared_buffer(other, strides, flags, data_size, offset).run_row_chunked(QuantizedMatmul): splitsMinto slices ofcap = min(65535, INT32_MAX/N)so each launch keeps grid.y ≤ 65535 and per-slicem*n < 2^31(fixes Bug 2, theqmvint-overflowl=0). Gated onsingle_batch = out.size() == size_t(M)*N(the LM-head output is 3D[1, tokens, vocab], so anndim==2gate would miss it).run_batch_chunked(GatherQMM): splits the gathered batchBinto ≤ 65535 slices so grid.z stays legal (fixes Bug 1, MoEtokens*top_k > 65535).int B = out.size() / M / N(sequential 64-bit division) so the overflow no longer yieldsB=0and misroutes dispatch.Validation (bench binary — what
scripts/bench_longprompt.shruns)Previously-
FAIL:benchcells now pass, exit 0 with real throughput:llama-3.1-8b-4bit@17000 (1663 tok/s prefill), @23491 (1605), @32768 (1544)qwen3-30b-a3b-4bit@8192 (326)Chunk correctness confirmed:
mlxcel generateshort/mid prompts produce coherent text, and a debugmlxcel generate@23491 completes cleanly — so the sub-array offsets/math are correct. Metal remains unaffected (usesout.size()/M/Nand no 65535 cap).Remaining: a separate crash in
mlxcel generateat long promptsRelease
mlxcel generate(the interactive/server command, not the bench binary) still aborts at long prompts (threshold ~13k-19.5k tokens) during the prefill eval, with the samecudaGraphAddKernelNode/cudaLaunchKernelExC ... invalid argument. It is release-build-specific (a debug build ofgenerateruns to completion at @23491) and generate-command-specific (the bench binary works at @23491), even though both use the sameCxxGeneratorprefill. This is a distinct third kernel/path, not yet root-caused; pinning it needs a RelWithDebInfo build for a symbolized backtrace (the debug build is crash-clean, the release build is stripped). Tracking as remaining work under this issue.inureyes commentedon Jul 4, 2026
Correction: the "remaining" generate crash was a stale binary, not a third bug. Fix is complete.
The earlier note about a separate release-only
mlxcel generatelong-prompt crash was a process error on my side, not a code bug. After thesingle_batchguard fix I had rebuilt only--bin mlxcel-bench-decode(and validated the bench/sweep path), but themlxcel(generate) binary was never rebuilt, so it still carried the earlierndim!=2guard that skips chunking the 3D LM-head output[1, tokens, vocab]and thus still hit the overflow. A debuggeneratebuild (built after the fix) and the release bench binary both worked, which made it look release/generate-specific.After rebuilding both binaries from the same committed patch, the fix works everywhere. Final validation on GB10 (fresh binaries, default settings):
Bench (what
scripts/bench_longprompt.shruns):llama-3.1-8b-4bit@17000 (1629 tok/s), @32768 (1492 tok/s)qwen3-30b-a3b-4bit@8192 (328 tok/s)Interactive
mlxcel generate(previously "crashing"):llama-3.1-8b-4bit@23491 → completes, coherent outputqwen3-30b-a3b-4bit@~11k → completes, coherent outputPatch application verified: the fix lives in the mlxcel overlay
patches/mlx/backend/cuda/quantized/quantized.cpp;build.rstrackspatches/(rerun-if-changed), anddiffbetween the patch and the overlay-applied fetched source is empty, so it applies identically to the other overlay patches. There is no third kernel; the fix is complete.fix(cuda/quantized): chunk long-prompt qmm launches to avoid gridDim>…
fix(cuda/attention): bound long-prompt prefill memory for flash-ineli…
fix(cuda/quantized): chunk long-prompt qmm launches to avoid gridDim>…
fix(cuda/attention): bound long-prompt prefill memory for flash-ineli…