Skip to content

CUDA: long-prompt prefill aborts (exit 134, invalid launch config) when a kernel grid dim exceeds 65535 #648

Closed

Description

@inureyes

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 gathered l dimension into <= 65535 slices across qmm_sm80 / qmm_naive / gather_qmv.
  • Output is token-exact vs the working <= 65535 path (qwen3-30b @8192 vs @8191-scale reference; mixtral-8x7b-4bit @32768).
  • The dense-model kernel (~3x seq grid, llama-3.1-8b-4bit failing at >= 24576) is pinned to an exact kernel/line and fixed with the same clamp/chunk approach.
  • scripts/bench_decode.sh surfaces the last captured stderr lines on FAIL:bench instead of discarding $raw.
  • The limitation is reported upstream to ml-explore/mlx.

Activity

  1. added
    type:bug
    status:ready
    priority:high
    area:inference
    area:benchmark
    on Jul 3, 2026
  2. inureyes commented on Jul 3, 2026

    @inureyes
    MemberAuthor

    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×seq characterization 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:80 sets grid.z = l = tokens × num_experts_per_tok. When tokens×top_k ≥ 65536 this exceeds the CUDA gridDim.z max 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 shows cu::qmv(m=23491, n=128256, k=4096, l=0); qmv.cu:276 then sets grid.z = l = 0, and a grid dim of 0 is invalid → cudaErrorInvalidValue. Root cause: int l = out.size() / (m * n) at qmv.cu:421 (and identically make_problem_shape at qmm_utils.h:12, and int B = out.size()/(M*N) in quantized.cpp). m*n is computed in int32; for the LM head tokens*vocab = 23491*128256 = 3.01e9 > 2^31, so it wraps negative and the size_t division 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×seq hypothesis in the issue body.

    Fixes (different per bug):

    • Bug 2: 64-bit arithmetic, matching what the Metal backend already does (out.size() / M / N): out.size() / (static_cast<size_t>(m) * n) at qmv.cu:421, qmm_utils.h:12, and the quantized.cpp B computations.
    • Bug 1: chunk the gathered batch l into ≤65535 slices per launch.

    Scope: CUDA-only, confirmed for both. The Metal backend uses int B = out.size() / M / N (sequential size_t division, no M*N int product) and MTLSize grid dims are not capped at 65535, so Apple silicon is affected by neither bug. No Metal fix required.

  3. inureyes commented on Jul 3, 2026

    @inureyes
    MemberAuthor

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

    • Helpers row_view/batch_view/flat_view build sub-array views via array::copy_shared_buffer(other, strides, flags, data_size, offset).
    • run_row_chunked (QuantizedMatmul): splits M into slices of cap = min(65535, INT32_MAX/N) so each launch keeps grid.y ≤ 65535 and per-slice m*n < 2^31 (fixes Bug 2, the qmv int-overflow l=0). Gated on single_batch = out.size() == size_t(M)*N (the LM-head output is 3D [1, tokens, vocab], so an ndim==2 gate would miss it).
    • run_batch_chunked (GatherQMM): splits the gathered batch B into ≤ 65535 slices so grid.z stays legal (fixes Bug 1, MoE tokens*top_k > 65535).
    • int B = out.size() / M / N (sequential 64-bit division) so the overflow no longer yields B=0 and misroutes dispatch.
    • Both helpers early-return to the original single call when no split is needed, so the common path is byte-identical.

    Validation (bench binary — what scripts/bench_longprompt.sh runs)

    Previously-FAIL:bench cells now pass, exit 0 with real throughput:

    Chunk correctness confirmed: mlxcel generate short/mid prompts produce coherent text, and a debug mlxcel generate @23491 completes cleanly — so the sub-array offsets/math are correct. Metal remains unaffected (uses out.size()/M/N and no 65535 cap).

    Remaining: a separate crash in mlxcel generate at long prompts

    Release 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 same cudaGraphAddKernelNode/cudaLaunchKernelExC ... invalid argument. It is release-build-specific (a debug build of generate runs to completion at @23491) and generate-command-specific (the bench binary works at @23491), even though both use the same CxxGenerator prefill. 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.

  4. inureyes commented on Jul 4, 2026

    @inureyes
    MemberAuthor

    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 generate long-prompt crash was a process error on my side, not a code bug. After the single_batch guard fix I had rebuilt only --bin mlxcel-bench-decode (and validated the bench/sweep path), but the mlxcel (generate) binary was never rebuilt, so it still carried the earlier ndim!=2 guard that skips chunking the 3D LM-head output [1, tokens, vocab] and thus still hit the overflow. A debug generate build (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.sh runs):

    • 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 output
    • qwen3-30b-a3b-4bit @~11k → completes, coherent output

    Patch application verified: the fix lives in the mlxcel overlay patches/mlx/backend/cuda/quantized/quantized.cpp; build.rs tracks patches/ (rerun-if-changed), and diff between 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.

  5. self-assigned this
    on Aug 31, 2026
  6. added
    status:done
    and removed
    status:ready
    on Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:benchmarkarea:inferencebugpriority:highstatus:donetype:bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions