Skip to content

fix(cuda): keep small masked verify blocks off cuDNN SDPA (#1799) - #1817

Merged
inureyes merged 9 commits into
mainfrom
fix/issue-1799-laguna-verify-cost
Sep 11, 2026
Merged

inureyes merged 9 commits into
mainfrom
fix/issue-1799-laguna-verify-cost

Conversation

@inureyes

@inureyes inureyes commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Summary

The Laguna DFlash verify round's fixed floor on GB10 was host time, not GPU work: a multi-row masked SDPA with head_dim 128 is cuDNN-eligible, MLX caches the cuDNN execution plan by the exact key length and mask shape, and a verify round's key length is new every round, so three shape classes (target full layers, target sliding layers with sinks, drafter layers) rebuilt a plan on the host each round at about 22 ms each: 67 to 76 ms per round by nsys NVTX ranges against 2.8 ms per classic token. The same LRU's lifetime miss counter aborted every block-2 generation past about 170 rounds. The per-row term is the routed experts reading each selected expert per row, inherent to a MoE verify. Full attribution, including the graph-side candidates ruled out with bounds and two corrected premises (this checkpoint's attention projections are bf16, and the experts take qmm_sm80 at every width), is in docs/benchmark_results/laguna-dflash-verify-cost-gb10-2026-09-11.md; the report pair is TECHNICAL_REPORTS/1799-laguna-dflash-verify-cost-cuda-20260911.{en,ko}.md.

  • A patched supports_sdpa_cudnn (the pinned 81ba1c6a file plus one gate) keeps a masked call with 2 to 32 query rows over a longer key sequence off cuDNN, so it takes MLX's own ops fallback with no per-shape build; the one-row decode step and prefill are untouched. MLXCEL_SDPA_FALLBACK_MAX_QUERIES=0 restores upstream dispatch without a rebuild.
  • MLX_CUDA_SDPA_CACHE_SIZE defaults to 2000 on CUDA builds (hardware::apply_cuda_sdpa_cache_default, the fix(server): speculative serving aborts the whole process via MLX CUDA graph-cache "Cache thrashing" throw (lifetime miss counter vs default capacity 400) #818 sibling, wired from all four binaries), because prefill prompt-length diversity alone crosses the 512-miss abort on a long-lived server.
  • materializing_sdpa_query_chunk mirrors the new gate (cuda_sdpa_small_query_fallback) so the score-matrix chunk budget still applies to the calls the gate diverts (review finding; inert below the 1 GiB budget).

Measured

Same binary, kill-switch A/B on an idle host (load1 gated and recorded, ps checked), n = 3 with ranges, tree 2deae307 for the baseline and the rebuilt tree for the after arm (the rebase onto bec64748 changed no file of this PR): Laguna DFlash goes from a best of 0.72x to 1.33x at block 4 and 1.32x at block 6 (1.13x at 2, 1.12x at 8, crossover between 10 and 12, checkpoint default 16 still 0.83x); the kill switch reproduces the baseline within 2%; the device sync fit moves from 71.6 + 3.79/row to 36.0 + 3.6/row ms; the after profile has no ScaledDotProductAttention host range at all and the round is GPU-bound. Qwen 3.5 through the #1782 server harness on the same binary: 1.26x and 1.35x (#1782: 1.24x, 1.32x), greedy text byte-identical to classic at both widths; its head_dim 256 never enters cuDNN, so that number shows the rebuild changed nothing else.

Blast radius

Measured: Laguna, and Qwen 3.5 as the cross-family control. Sharing the new path without a number: every other CUDA model whose masked SDPA calls with 2 to 32 query rows and prior context reach scaled_dot_product_attention.cpp on Ampere or later, which is the speculative verify of any head_dim-128-or-less pairing (Muse Glimmer DFlash, LFM2 and LFM2.5 DSpark, Inkling MTP; none re-probed here, and a flipped exactness probe declines speculation rather than corrupting output), a short incremental prefill over a reused prefix-cache prefix, and the trailing short chunk of a chunked prefill. The fallback's cost grows with the key length while the plan build it replaces is constant (about 10 ms more GPU per round at block 2 with 350 keys; the crossover is in the tens of thousands of keys at block 16, unmeasured). Metal and CPU are unaffected. The Laguna exactness gate is not touched. The general fix, bucketing the key length so the cuDNN plan cache can hit and keep the flash kernel, is deliberately not attempted here and is being filed as its own issue. Also recorded for #1798: GB10's default graph budgets make capture a net loss on this MoE classic arm (graphs off +12%, both budgets raised +16%), opposite sign to Qwen 3.5.

Test plan

  • Baseline, zero-code controls, nsys at 2, 8 and 16 rows, cuDNN-off control, after-fix A/B and the Qwen 3.5 check on GB10, all in the record with n and ranges
  • cargo fmt --all -- --check
  • cargo test --profile test-fast --features cuda -p mlxcel-core -- hardware:: small_query_fallback materializing_sdpa chunked_query_attention (35 passed, on the rebased tree)
  • cargo clippy --profile test-fast --features cuda --lib --bins --tests -- -D warnings (clean, on the rebased tree)
  • metal,accelerate gate: not runnable on this Linux/CUDA host, unrun; the patched file compiles only into the CUDA backend and the cache default is None without the cuda feature

Closes #1799

@inureyes inureyes added status:review Under review type:performance Performance improvements priority:high High priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:linux Linux (CUDA / packaging) specific labels Sep 11, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Reviewed against the #1799 deliverables. The attribution, the kill-switch A/B, the blast-radius statement, the record and the bilingual report are all present, and the gate itself is sound: every call it refuses reaches either sdpa_vector (2 or 3 unmasked rows, whose i <= kL - qL + q_seq_idx is the same bottom-right alignment as cuDNN's set_causal_mask_bottom_right) or the mlx/fast.cpp ops fallback (array mask or 4 to 32 rows), which honors array and bool masks, GQA repeats, sinks and a k_len - q_len causal offset. One-row decode never reaches the gate, backward never consults supports_sdpa_cudnn, and use_fallback and eval_gpu evaluate the gate on identical shapes so they cannot desync. The patch file is pinned upstream 81ba1c6a plus exactly two hunks.

Fixed and pushed as 38f2bb57

  • HIGH apply_cuda_sdpa_cache_default was wired into three binaries but not src/bin/speculative_bench.rs, the fourth that raises the graph-cache sibling and the one its own comment calls the canonical workload for that abort. Now wired, with the SAFETY note naming all four callers.
  • HIGH Both TECHNICAL_REPORTS/1799-*.{en,ko}.md shipped a literal VERIFICATION_PLACEHOLDER as their verification section. Filled in with the patch provenance, the dispatch paths, the measurement protocol and the gates; the entry-point count in both goes from three to four.

Left open

  • MEDIUM The blast-radius examples (PR body, both reports, docs/environment-variables.md) name only the trailing chunk of a chunked prefill. With the prefix cache adopting the longest common prefix, a short new turn over a long reused prefix is also 2 to 32 rows over a much longer k_len, and that regime is unmeasured here (every arm used a 152-token prompt). Narrowing the gate without a measurement would defeat the point, so this is a follow-up.
  • MEDIUM docs/upstream/mlx-cuda-graph-cache-lifetime-miss-abort.md, the chore(deps): report the MLX CUDA graph-cache lifetime-miss abort upstream and track dropping our local default #821 upstream draft, says the graph cache "is the only one whose key space grows with the shape of the host's op stream" and that the SDPA caches are keyed by "a comparatively fixed set of layer configurations". This PR is the counterexample and the draft should be corrected before it is filed.
  • LOW The two new helpers sit after the ── Detection ── divider in hardware.rs, away from the sibling they mirror.
  • LOW MLX resolves the variable with atoi, so an unparseable MLXCEL_SDPA_FALLBACK_MAX_QUERIES silently disables the gate; the docs row promises "non-negative integer". Consistent with the file's existing switches.
  • LOW The record gives block 6's baseline round wall as 126.7 ms in one table and 126.6 ms in another.

cargo fmt --all -- --check is clean after the push. Cargo test and clippy were in flight when the review started and the push lands after them, so both need a re-run; speculative_bench is covered by the --bins selector.

@inureyes

Copy link
Copy Markdown
Member Author

Follow-up: second-opinion review, adjudicated

A second reviewer raised three items. One is a real bug and is now fixed, one is half right, one duplicates a fix already pushed.

Fixed as 473e2d7a (HIGH). cuda_sdpa_materializes_scores in src/lib/mlxcel-core/src/layers.rs states in its own doc comment that it mirrors supports_sdpa_cudnn, and this PR changed that function without updating the mirror. The guard therefore still classified a masked 2-to-32-row call as flash-eligible and skipped chunking, so MLX's now-forced ops fallback allocated the whole [B, heads, q_len, k_len] score matrix with no budget check. materializing_sdpa_query_chunk now takes whether the call is masked or causal and consults a cuda_sdpa_small_query_fallback mirror that reads MLXCEL_SDPA_FALLBACK_MAX_QUERIES with MLX's atoi semantics. Below the 1 GiB budget query_chunk_len still returns None, so no configuration measured for #1799 changes; only calls over the budget begin to chunk. This also bounds what happens if an operator raises the variable, which previously widened the unguarded range without limit. A unit test pins the mirror to the gate.

Half right, left open (MEDIUM). The claim that the DFlash drafter is maskless is false for Laguna: LagunaDFlashAttention::forward passes an explicit sliding-window causal mask, which is why the record shows its host build dropping from 30 ms to 9 to 11 ms. It is true for the generic DFlashAttention::forward, which calls fast_scaled_dot_product_attention with a null mask and no causal flag, so a non-Laguna DFlash pairing with head_dim 128 or less still rebuilds one plan per round. That is outside this PR's measured workload and extending the gate to maskless shapes is a dispatch change no measurement here covers, so it belongs in a follow-up.

Already fixed. The speculative_bench wiring gap was pushed as 38f2bb57.

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review of the SDPA gate. No CRITICAL or HIGH findings, so nothing was auto-fixed and the branch is untouched. cargo fmt --all -- --check is clean, the patched file differs from the pinned upstream in exactly the header comment and the gate, and no commit or the PR body carries AI attribution. Two MEDIUM items for the author to decide on.

MEDIUM, performance: the gate bounds query rows but not key length. The cuDNN plan build it replaces is a constant (about 22 ms times three shape classes), while the ops fallback's cost grows linearly in k_len. Every arm in the record ran at k_len under about 350 (152-token prompt, 200 generated), and the record itself notes the fallback is slower than cuDNN's flash kernels on long prompts. Scaling the recorded "about 10 ms more GPU time per round at block 2" by the ten full-attention layers times 48 heads puts the crossover in the tens of thousands of key tokens at block 16, inside the pairing's usable context. Consider a score-element or k_len bound in the gate, or record the unmeasured regime in the report and in docs/environment-variables.md.

MEDIUM, memory: materializing_sdpa_query_chunk is reached only from layers::attention (src/lib/mlxcel-core/src/layers.rs:4349) and causal_attention (src/lib/mlxcel-core/src/lib.rs:3386). The four in-tree sinks call sites call fast_scaled_dot_product_attention_with_sinks directly and never consult it: src/models/laguna_layers.rs:183 (the target sliding layers, one of the three diverted shape classes), src/models/gpt_oss.rs:764, src/models/deepseek_v4_attention.rs:346, src/models/falcon_ocr.rs:435. On those paths the newly diverted call materializes [B, heads, q_len, k_len] with no budget at all. Laguna's own exposure stays bounded because its sinks layers are window-rotating, but gpt_oss carries sinks on its full-attention layers too, so a 2 to 32 row masked call over a long cache materializes there unguarded. The doc comment on cuda_sdpa_small_query_fallback describes protection those call sites do not have.

First increment of #1799 phase 0. The #1771 sweep ran with another session's build at load 2.6 to 3.9; this re-measures the Laguna NVFP4 DFlash pairing on an otherwise idle host (start gated on load1 under 0.6, load1 recorded per run, ps shows only the process under test), same binary on every arm, widths 2 to 16 interleaved, n = 3 with min and max, tree 2deae30.

The idle host does not rescue the pairing: classic 34.2 ms per step, device sync per round 71.6 ms plus 3.79 ms per row by least squares, and the round's three serial links (drafter host build, verify host build, device sync) add up to the measured round wall to within 0.1 ms. Also records that the classic arm itself is not run-to-run deterministic on this host, a fact for the separate exactness issue.

Refs #1799
…round

Zero-code controls on the idle host, n = 3 each, same binary: MLX_MAX_MB_PER_BUFFER=400, MLX_MAX_OPS_PER_BUFFER=100, both raised, and MLX_USE_CUDA_GRAPHS=0, on the classic arm and at 2, 8 and 16 rows. None moves the 2-row device sync by more than 3% (80.4 to 78.1 ms) or the round by more than 4%, and capture off leaves block 8 faster than capture on, so byte budget, op budget and capture itself are ruled out as owners of the 72 ms floor.

Also records the classic-arm result for #1798: with GB10's default 20-op and 25 "MB" budgets, capture is a net loss on this MoE model (graphs off +12%, both budgets raised +16%), the two knobs interact because every 256-expert nvfp4 stack exceeds the byte cap on its own, and the sign is opposite to Qwen 3.5 in #1782, so no single default generalizes across model shapes.

Refs #1799, #1798
On CUDA a multi-row speculative verify (a masked block of 2 to 16 query rows appended to a KV cache) is cuDNN-eligible whenever head_dim is 128 or less, and MLX caches the cuDNN execution plan by the exact q/k/v/mask shapes and strides. The key length changes every round, so every round of every layer class missed the cache and rebuilt a plan on the host: about 22 ms per build on GB10, 67 to 76 ms per round on the Laguna DFlash pairing measured by nsys NVTX ranges against 2.8 ms per classic token, which is the whole fixed floor that kept that pairing below classic at every width. The plan cache's lifetime miss counter then aborted a 400-token block-2 run with MLX's Cache thrashing throw.

The patched supports_sdpa_cudnn refuses a masked call with 2 to MLXCEL_SDPA_FALLBACK_MAX_QUERIES (default 32) query rows over a longer key sequence, so it takes MLX's own ops fallback with no per-shape build; the one-row decode step (vector kernel) and prefill (k_len equals q_len, or more rows than the bound) are untouched. 0 restores upstream dispatch without a rebuild and is the kill switch for the A/B. Alongside it, MLX_CUDA_SDPA_CACHE_SIZE defaults to 2000 on CUDA builds the way MLX_CUDA_GRAPH_CACHE_SIZE does (#818), because prefill prompt-length diversity alone crosses the 512-miss abort on a long-lived server.

Blast radius: every CUDA masked SDPA call with 2 to 32 query rows and prior context, which is the speculative verify shape on every family with head_dim 128 or less and the last short chunk of a chunked prefill; those calls now run MLX's fallback arithmetic instead of cuDNN's. Metal and CPU are unaffected. Measurement record in docs/benchmark_results/laguna-dflash-verify-cost-gb10-2026-09-11.md.

Refs #1799
…n builds

nsys tables per round (400 minus 200 token differencing so load, prefill and the exactness probe cancel), the NVTX host split, and the cuDNN-off control. The fixed term is 67 to 76 ms of host time per round in ScaledDotProductAttention::eval_gpu against 2.8 ms per classic token: MLX caches cuDNN SDPA plans by exact shape, a verify round's key length is new every round, so three shape classes rebuild a plan each round at about 22 ms; the same LRU's lifetime miss counter aborted every block-2 profile past about 170 rounds. The per-row term is GPU work in the routed experts (2.5 ms per row, near the read-each-selected-expert floor). Also corrects two premises: this checkpoint's attention projections are bf16, not NVFP4, and the experts take qmm_sm80 at every width.

Refs #1799
Same binary, kill-switch A/B on a quiet host, n = 3: Laguna DFlash goes from a best of 0.72x to 1.33x at block 4 and 1.32x at block 6 (block 2 1.13x, block 8 1.12x, crossover between 10 and 12 rows, checkpoint default 16 still 0.83x); the kill switch reproduces the baseline within 2%; the device sync fit moves from 71.6 + 3.79/row to 36.0 + 3.6/row ms. The after profile has no ScaledDotProductAttention host range at all and the round is GPU-bound. Qwen 3.5 through the #1782 server harness is unchanged (1.26x, 1.35x) and byte-identical to classic. Fills the report pair's after table.

Refs #1799
`speculative_bench` was the one binary that raised `MLX_CUDA_GRAPH_CACHE_SIZE` (#818) without also raising `MLX_CUDA_SDPA_CACHE_SIZE`, so a long sweep on it could still die on the cuDNN plan cache's lifetime-miss abort, the same defect in the same `lru_cache.h`, in the workload its own comment calls the canonical one for that class of crash. It now calls `apply_cuda_sdpa_cache_default` beside the graph-cache sibling, and that function's SAFETY note names all four callers the way the sibling's does.

The #1799 report pair shipped with a literal `VERIFICATION_PLACEHOLDER` where its verification section belongs. Filled in with the patch provenance against MLX pin `81ba1c6a`, the path every refused call takes (the ops fallback for an array mask or 4 to 32 rows, `sdpa_vector` for 2 or 3 unmasked rows with the same bottom-right causal alignment, one-row decode never reaching the gate), the measurement protocol, and the gates. The entry-point count in both reports goes from three to four.

Refs #1799.
`cuda_sdpa_materializes_scores` documents itself as mirroring `supports_sdpa_cudnn`, and the #1799 gate changed that function without updating the mirror. A masked or causal call with 2 to 32 query rows over a longer key sequence now takes MLX's materializing ops fallback, but the guard still read it as flash-eligible and skipped chunking, so the `[B, heads, q_len, k_len]` score matrix was allocated whole with no budget check. The hole is bounded by the default row cap and widens without bound if an operator raises `MLXCEL_SDPA_FALLBACK_MAX_QUERIES`.

`materializing_sdpa_query_chunk` now takes whether the call carries a mask or is causal and consults `cuda_sdpa_small_query_fallback`, which reads that variable with MLX's `atoi` semantics so an unparseable value is 0 on both sides. Below the 1 GiB chunk budget `query_chunk_len` still returns `None`, so every configuration measured for #1799 is unchanged and only calls whose score matrix exceeds the budget begin to chunk. The key rank is now checked before indexing, which the previous code did only for the query.

Refs #1799.
@inureyes
inureyes force-pushed the fix/issue-1799-laguna-verify-cost branch from 473e2d7 to 5f415d6 Compare September 11, 2026 15:16
…A gate

Review and security follow-ups for #1799, all text. The record and both reports now separate what was measured (Laguna, and Qwen 3.5 as the cross-family control) from what merely shares the new path without a number (every head_dim 128 or less speculative verify on CUDA, short incremental prefill over a reused prefix-cache prefix, the trailing chunk of a chunked prefill), note that the fallback's cost grows with the key length while the plan build it replaces is constant, that the four direct sinks paths bypass the chunk budget as before, that the cache-size default is per MLX eval thread with no measured memory figure, and point at the general fix this change deliberately does not attempt (bucketing the key length so the cuDNN plan cache can hit), with the LRU lifetime-miss abort as the evidence that the miss path is terminal. The layers.rs comment states exactly where the Rust mirror and MLX's atoi diverge, the patch header and the env-var rows name the trailing-chunk case, the upstream cache note no longer claims the SDPA cache has a fixed key set, and one rounding inconsistency (126.7 against 126.6) is fixed.

Refs #1799
@inureyes inureyes added status:done Completed and removed status:review Under review labels Sep 11, 2026
@inureyes
inureyes merged commit 23a6a26 into main Sep 11, 2026
14 checks passed
@inureyes
inureyes deleted the fix/issue-1799-laguna-verify-cost branch September 14, 2026 11:59
inureyes added a commit that referenced this pull request Sep 17, 2026
Measured on GB10 against main (`60341873`, which carries #1817). What the record establishes: the three shape classes and exactly which key fields move round over round, measured per call rather than inferred; three plan builds per verify round becoming zero after warm-up (82 builds to 11 in a 25-round generation); byte-identical token ids between bucketed and exact-shape cuDNN on both binaries; a non-speculative head_dim-128 model that does not enter the new path at all; and a plan-cache growth bound of shape classes times query widths times buckets crossed rather than rounds.

What it does not establish: that bucketing beats #1817's ops fallback. On the 152-token prompt they are a wash at widths 2 and 4 and bucketing is 3 to 6% behind at 6, 8 and 16, so the roughly 10 ms per round #1799 attributed to the fallback is not recovered at those key lengths. The long-context sweep that would have tested #1799's prediction (the fallback's score matrix grows with the key length, cuDNN's flash does not) was stopped partway when a second session loaded a model on the same GPU and the host's NVRM failure count went from 0 to 356 in two minutes. Those 10 rows are kept in `laguna_long_cli.jsonl` and marked unusable rather than quietly reported; the clean sweep finished before the foreign process existed.

Refs #1820
inureyes added a commit that referenced this pull request Sep 17, 2026
Bucketing the cuDNN SDPA plan-cache key works and should not ship. Against the bar that a default-on change must not lose on any measured workload, it fails on the workload it was built for: at a 152-token prompt it is behind #1799's ops fallback at three of five block widths with non-overlapping ranges (0.943x, 0.953x, 0.915x at widths 2, 8 and 16), and at 2634 tokens it is a wash on both throughput and per-round verify time. There is no measured context length at which it wins, so the roughly 10 ms per round #1799 attributed to the fallback is not recovered anywhere it was measured. `MLXCEL_SDPA_FALLBACK_MAX_QUERIES` therefore stays exactly as #1817 shipped it, and the implementation stays on the branch behind its own kill switch rather than being removed.

What bucketing does achieve is recorded rather than dismissed: 12 plan builds in a generation instead of 82, zero per verify round after warm-up, and greedy token ids byte-identical to the exact-shape cuDNN path on both binaries across three repeats. The mechanism is sound; it is the throughput that does not justify a default.

The crossover question is recorded as unmeasured on this host rather than absent, with the mechanism that motivates it: only 10 of the pairing's 45 attention calls scale with prompt length, since the target's 30 sliding layers and all 5 drafter layers are capped at a 512 window, so bucketing's cost is flat in context while the fallback's score matrix grows linearly. Answering it would produce a context-gated ship, not an unconditional one, and would then need the short-context loss re-confirmed before a gate could be designed.

Two host findings are recorded as first-class results. A 16k-token run costs about 38 `NVRM: NV_ERR_NO_MEMORY` allocation failures against near-zero at 2634, which projected the deciding 13-run rung to roughly 678 cumulative against a 400 budget and is why it could not be run; a follow-up needs a fresh boot. And `peak_rss_kib` reports 1.9 GiB for a run whose weights alone are 20.97 GiB, because CUDA unified allocations on GB10 do not enter the resident set, so that field is marked as not a valid footprint proxy rather than left as a plausible number someone trusts later.

The 2026-09-12 record is marked superseded in place: its mechanism findings hold, its throughput table does not.

Refs #1820
inureyes added a commit that referenced this pull request Sep 19, 2026
…1906)

* perf(cuda): bucket the cuDNN SDPA plan-cache key

MLX keys its cuDNN SDPA execution-plan cache on the exact shapes and strides of q, k, v and the mask, and a speculative verify round appends keys every round, so every round of every attention-layer class missed that cache and rebuilt a plan on the host: about 22 ms per build on GB10, 67 to 76 ms per round on the Laguna DFlash pairing, and a fatal `Cache thrashing` abort once lifetime misses passed twice the capacity. #1799 routed those calls off cuDNN entirely; this makes the key reusable so they can stay on it.

Measured on the pairing #1799 attributed the defect on (GB10, block 4, 25 verify rounds, `MLXCEL_SDPA_PLAN_DEBUG=1`): three shape classes, three plan builds per round, 82 in the process. Only three key fields move round over round, the k/v sequence length and the mask's column count and row stride; the k/v strides and the mask's two leading strides (0, from the broadcast `fast::scaled_dot_product_attention` builds) do not. With bucketing each class builds one plan for the whole run, 11 in the process, and the round's accept counts are unchanged.

The canonicalization is MLX's own one-row decode path extended to a small array-masked multi-row call: k and v are widened to a bucket, the mask is widened to the same width with the new columns set to `-inf`, and the true lengths reach cuDNN through `set_padding_mask` with `set_seq_len_q` / `set_seq_len_kv`, which is what keeps the widened region out of the result. k and v reach the bucket by unslicing when they are a leading slice of one cache buffer with room to spare (the target's dense and speculative-buffered caches), and by a zero-padded copy when they are not, which is the third class: the drafter concatenates its proposal keys onto the cache window, so its k and v are freshly built arrays. The copy is bounded by `MLXCEL_SDPA_PLAN_BUCKET_MAX_MB` (64 per tensor); above it the call keeps its exact shape.

`MLXCEL_SDPA_PLAN_BUCKET_MAX_QUERIES` (default 32, 0 disables) is the kill switch, and it narrows #1799's gate rather than leaving both mechanisms in place: `MLXCEL_SDPA_FALLBACK_MAX_QUERIES` no longer claims a call whose key can be bucketed, so what it still covers is a causal-mode block with no array mask, where there is no mask to widen. `MLXCEL_SDPA_PLAN_DEBUG=1` traces the key fields and plan builds per call. A cuDNN that cannot plan the widened shape degrades to per-length plans instead of aborting, per sinks setting so one refusal cannot disable the other shape.

Refs #1820

* docs(benchmark): record the #1820 plan-cache bucketing measurements

Measured on GB10 against main (`60341873`, which carries #1817). What the record establishes: the three shape classes and exactly which key fields move round over round, measured per call rather than inferred; three plan builds per verify round becoming zero after warm-up (82 builds to 11 in a 25-round generation); byte-identical token ids between bucketed and exact-shape cuDNN on both binaries; a non-speculative head_dim-128 model that does not enter the new path at all; and a plan-cache growth bound of shape classes times query widths times buckets crossed rather than rounds.

What it does not establish: that bucketing beats #1817's ops fallback. On the 152-token prompt they are a wash at widths 2 and 4 and bucketing is 3 to 6% behind at 6, 8 and 16, so the roughly 10 ms per round #1799 attributed to the fallback is not recovered at those key lengths. The long-context sweep that would have tested #1799's prediction (the fallback's score matrix grows with the key length, cuDNN's flash does not) was stopped partway when a second session loaded a model on the same GPU and the host's NVRM failure count went from 0 to 356 in two minutes. Those 10 rows are kept in `laguna_long_cli.jsonl` and marked unusable rather than quietly reported; the clean sweep finished before the foreign process existed.

Refs #1820

* docs(benchmark): preserve the partial #1820 context-ladder sweep

The long-context ladder sweep stopped at 31 rows on 2026-09-12 14:35 when its session ended, and the host was later rebooted, so these results were at risk of being lost uncommitted. This commit preserves them verbatim along with the harness changes that produced them: the 8k, 16k and 32k code prompts, the ladder driver, and the host-gate and CLI harness edits.

The data is committed as raw evidence only. Completeness per configuration and whether each row ran on a clean host have not been reviewed yet, and nothing here is cited as a result until that review is done.

Refs #1820

* fix(cuda): separate the causal and array-mask axes in the SDPA gate

An audit of the #1820 overlay against its Rust mirror found that the mirror had collapsed two axes the C++ gate keeps apart. `cuda_sdpa_plan_bucket_eligible` took a single `masked` flag, and the maskless causal call site in `fast_scaled_dot_product_attention_causal_windowed` passes `true` for it. That was correct before #1820, when the #1799 gate fired for `has_arr_mask || do_causal` alike, and wrong after: bucketing needs an array mask to widen, so C++ rejects a causal block at `do_causal` and still routes it to MLX's materializing ops fallback, while the mirror now claimed it stayed on cuDNN. The score-matrix query chunking was therefore switched off for exactly the calls that still materialize a `[B, heads, q_len, k_len]` matrix, and `cuda_sdpa_small_query_fallback` had become dead code on CUDA builds. Both predicates now take `arr_masked` and `do_causal` separately, both call sites pass what they mean, and the unit tests assert the causal axis rather than re-asserting the array-mask one.

Four fixes in the overlay itself, all found by the same audit:

`kv_cache_slice_extent` now requires `offset() == 0`. Its element-count identity proves the widened view is the same size as the allocation, not that it starts at it, so a mid-buffer window slice passed every test and `unslice_kv` would then subtract a non-zero byte offset from the base pointer. No mlxcel producer hands SDPA such a slice today, so this guards a future one.

The bucket try/catch no longer wraps `sdpa_cache().emplace`. The LRU's lifetime-miss "Cache thrashing" throw is the exact abort this bucketing exists to prevent, and catching it as a cuDNN refusal would have disabled bucketing permanently and then hit the abort again, uncaught, on the exact-shape retry.

A shape-eligible call whose layout declines bucketing now warns once. `supports_sdpa_cudnn` narrows #1799's fallback on the shape alone because it must answer identically during graph building and at eval, so a call that then declines on layout (the by-copy size cap, a mask that is not the broadcast plane) gets neither fix and rebuilds a plan every round. That hole is real and was silent.

The unslice arm now takes `k_extent >= k_len` rather than `>`, so an exactly-full cache unslices as a no-op view instead of copying onto a buffer of identical size.

`docs/environment-variables.md` said a `RotatingKVCache` multi-row append is not bucketed. The by-copy arm does bucket it; corrected, and `MLXCEL_SDPA_PLAN_BUCKET_MAX_MB` now has a row of its own.

Refs #1820

* docs(benchmark): re-baseline the #1820 short-context sweep after the rebase

The branch was rebased onto `0ef0a1a4`, 30 commits of main, which in that window gained f32 attention work touching the attention path, so the short-context table the branch already carried had to be re-measured rather than assumed to survive. It does not fully survive, and this records the new run rather than editing the old one.

Every arm is 2 to 7% below the committed table, on both sides, and the fallback arm moves as much as the bucketed one, so most of that is a session offset: load1 ran 1.00 to 3.14 against 0.72 to 2.29 before, another session held `rustc` and `cargo-clippy` on the box throughout, and six runs had a CI job alive. The comparison itself also moved. Bucketing was a wash at widths 2 and 4 and 3 to 6% behind at 6, 8 and 16; it is now 0.94x at width 2 with disjoint ranges, 1.03x at 4, and 0.92x to 0.95x at 6, 8 and 16. So the conclusion the committed table drew is unchanged and slightly stronger: at a 152-token prompt bucketing does not beat #1799's ops fallback.

One term did not move with the session. The fallback arm's drafter host build is flat against the committed run (7.4 to 7.6, 9.1 to 9.2, 10.1 to 10.3 ms per round at widths 2, 4 and 16), while the bucketed arm's rose about 3 ms at every width (7.3 to 10.5, 9.4 to 13.4, 13.0 to 16.2). That term is host kernel enqueues, which is what the widening adds and what CPU contention hits hardest, so contention and a real change are not separable from this run alone. It is recorded as unattributed rather than explained away.

The 10 rows of a first attempt at this sweep are not included: the harness was killed partway when the host ran low on memory, and they were taken while that pressure was building.

Refs #1820

* docs(benchmark): record the #1820 ladder 2634-token rung

First rung of the rebased context ladder, committed as it completes rather than at the end of the sweep, so a driver spike on a later rung cannot take the earlier evidence with it.

At 2634 prompt tokens the two fixes are a wash, which is what the pre-rebase run found: bucketed against #1799's ops fallback is 1.017x at width 4 and 1.011x at width 8 on throughput, with per-round verify time overlapping in both. n = 3 per arm, no foreign model process on the host, no CI job, load1 1.24 to 3.81.

The table carries two metrics because only one of them is a kernel measurement. The arms run different kernels, and #1799 already recorded that the ops fallback shifts the greedy path at ties, so they generate different text and need a different number of verify rounds to reach the same 150 tokens (64 against 66 at width 4). Throughput therefore mixes kernel speed with acceptance luck; verify ms per round divides that out and is the number to read for a crossover.

Refs #1820

* docs(benchmark): preserve the halted #1820 8k rung as raw evidence

The context ladder was halted partway through its 8k rung when the driver trip wire fired: 107 `NVRM: NV_ERR_NO_MEMORY` errors in a five-minute window against a pre-run baseline of 2 that had been stable for three days. Only this unit's own processes were on the GPU, checked by process cwd rather than ancestry, so the errors are this workload's own, not a foreign session's.

These six non-warmup rows are committed as raw evidence and are cited for nothing. They are incomplete (n = 1 to 2 per configuration against the n = 3 the record requires) and partly contaminated: the second `b8` row reports a drafter host build of 24.8 ms per round against about 12 ms in every other row here, which is the signature of the allocation storm rather than of the arm under test. Both `b8` rows sit well under the 27.63 tok/s the pre-rebase run measured for that configuration.

What the kernel log shows about the burst is worth keeping, because it changes how the halt should be read. The 107 errors are not a climb: 96 of them land inside one second at 16:12:02, on top of 6 at 16:11:56 and 4 at 16:11:25, and the count returns to zero for the minute after. The earlier burst has the same shape, 27 errors inside one second at 15:38:21. So this is a discrete allocation storm repeating at intervals, not the compounding accumulation that preceded the 2026-07-06 hard freezes, and it is an order of magnitude below the 2026-09-12 halt (234 errors in two minutes).

The 2634-token rung completed at n = 3 and is already committed. 16k and 32k are unrun.

Refs #1820

* test(bench): gate the #1820 harness on the driver, memory and CI

Three preconditions added to the measurement gate, each because a run was actually lost to the thing it now refuses, on a shared self-hosted host where peer sessions and CI compete for the same box.

Driver. `NV_ERR_NO_MEMORY` is now checked before every run rather than by eye between rungs, on two independent limits: at least 50 in the trailing five minutes, or 400 cumulative since boot. Cumulative is the primary gauge and is deliberately not waitable, because it never decays, so a run that trips it stops rather than waits. That asymmetry is the lesson from the 2026-09-17 halt, where a per-second burst shape was read as reassurance while the total went 2 to 77 to 184; the instantaneous rate says nothing about the documented freeze precursor, which is cumulative over hours. Each row now carries `nvrm_window_before`, `nvrm_total_before` and `nvrm_total_after`, so a row's driver conditions are auditable from the file instead of reconstructed from whoever was watching.

Memory. Three concurrent foreign builds drove `MemAvailable` to zero and the supervisor killed background tasks three times; a model run started in that state dies mid-row, which is worse than a bad number because a bad number at least shows up in the spread. The floor is 32 GiB. It is derived rather than measured and is commented as such: 20.97 GiB of weights measured on disk (GB10 memory is unified, so weights count against system RAM) plus 0.69 GiB of KV at 16k computed from `config.json`, about 21.7 GiB resident, plus headroom for prefill-chunk activations and cuDNN workspace. Rows now record `peak_rss_kib` sampled from `VmHWM` so the floor can be replaced with the measured figure.

Sustained quiet, and CI. Two samples five seconds apart was not enough: a lull between two queued CI runs clears a ten-second check, and the timed run that starts in it is overrun when the next job ramps. Quiet is now a minute of continuous quiet, and an active `Runner.Worker` gates rather than merely being recorded, because a CI job between compiler invocations is not an idle host, it is a host about to compile again.

No measurement policy changed: same binary per arm, same warmup, same round-robin, same repeat count. These only decide when a run is allowed to start.

Refs #1820

* test(bench): count the node toolchain as host-busy in the #1820 gate

The gate watched for compilers and read a frontend build as silence. A Tauri build bundles a node toolchain on top of its Rust link step, and a CI job's own artifact step can be pure node, and both saturate this box exactly as `rustc` does. On 2026-09-17 a compiler-only predicate reported the host clear while a `WebUI installed artifact` step was still running and the `cargo-clippy` job it was gating on had not even started.

This is the same failure the sustained-quiet change fixed one commit earlier, in a different costume: there the check was too short, here it was too narrow. Both let a timed run start next to work that invalidates it.

`node`, `npm`, `npx`, `yarn`, `pnpm`, `bun`, `tsc`, `esbuild`, `vite`, `rollup` and `webpack` now gate alongside the compilers. A node process was live on the host when this was written, so the gap was load-bearing rather than theoretical.

Refs #1820

* docs(benchmark): quarantine the unusable #1820 ladder rows

The 8k and 16k rows sat in the same file as the clean 2634 rung with clean `foreign_models_*` fields, so every filter the summarizer had would have passed them through and averaged them in. They are now in `laguna_ladder_excluded.jsonl`, each carrying an `excluded_reason` naming what is wrong with it, and `summarize_ladder.py` drops any row carrying that field ahead of every other signal. Structural rather than annotative: the clean file yields only the 2634 rung, and the excluded file refuses its own contents.

The 8k rung was halted mid-run under a driver allocation storm, and is contaminated as well as sparse: one b8 row reports a 24.8 ms per round drafter host build against about 12 ms in its siblings, which is the storm and not the arm under test.

The 16k rung was stopped after two runs. Each 16k run cost about 38 `NVRM: NV_ERR_NO_MEMORY` allocation failures against near-zero at 2634, so the 13-run rung projected to roughly 678 cumulative against a 400 budget and could not fit. That step change with prompt length is a measured property of this host and is reported as a result rather than as an incident.

Two more guards while the summarizer was open. A row whose run moved the cumulative driver count by more than 20 is surfaced as suspect but kept, since that threshold is judgement rather than fact. Any configuration under n = 3 is labelled UNDERPOWERED in the table itself, so a sparse arm cannot read as a measured one at a glance.

Refs #1820

* docs(benchmark): record the #1820 decision against shipping bucketing

Bucketing the cuDNN SDPA plan-cache key works and should not ship. Against the bar that a default-on change must not lose on any measured workload, it fails on the workload it was built for: at a 152-token prompt it is behind #1799's ops fallback at three of five block widths with non-overlapping ranges (0.943x, 0.953x, 0.915x at widths 2, 8 and 16), and at 2634 tokens it is a wash on both throughput and per-round verify time. There is no measured context length at which it wins, so the roughly 10 ms per round #1799 attributed to the fallback is not recovered anywhere it was measured. `MLXCEL_SDPA_FALLBACK_MAX_QUERIES` therefore stays exactly as #1817 shipped it, and the implementation stays on the branch behind its own kill switch rather than being removed.

What bucketing does achieve is recorded rather than dismissed: 12 plan builds in a generation instead of 82, zero per verify round after warm-up, and greedy token ids byte-identical to the exact-shape cuDNN path on both binaries across three repeats. The mechanism is sound; it is the throughput that does not justify a default.

The crossover question is recorded as unmeasured on this host rather than absent, with the mechanism that motivates it: only 10 of the pairing's 45 attention calls scale with prompt length, since the target's 30 sliding layers and all 5 drafter layers are capped at a 512 window, so bucketing's cost is flat in context while the fallback's score matrix grows linearly. Answering it would produce a context-gated ship, not an unconditional one, and would then need the short-context loss re-confirmed before a gate could be designed.

Two host findings are recorded as first-class results. A 16k-token run costs about 38 `NVRM: NV_ERR_NO_MEMORY` allocation failures against near-zero at 2634, which projected the deciding 13-run rung to roughly 678 cumulative against a 400 budget and is why it could not be run; a follow-up needs a fresh boot. And `peak_rss_kib` reports 1.9 GiB for a run whose weights alone are 20.97 GiB, because CUDA unified allocations on GB10 do not enter the resident set, so that field is marked as not a valid footprint proxy rather than left as a plausible number someone trusts later.

The 2026-09-12 record is marked superseded in place: its mechanism findings hold, its throughput table does not.

Refs #1820

* perf(cuda): default the SDPA plan-cache bucketing off

#1820 built this path and then measured it losing. At a 152-token prompt it is behind #1799's ops fallback at three of five block widths with non-overlapping ranges (0.943x, 0.953x and 0.915x at widths 2, 8 and 16), and at 2634 tokens it is a wash on both throughput and per-round verify time. Against the bar that a default-on change must not lose on any measured workload, that disqualifies it, so `MLXCEL_SDPA_PLAN_BUCKET_MAX_QUERIES` now defaults to `0` on both sides of the bridge and the shipped dispatch is #1799's alone.

With the bound at 0 nothing is bucket-eligible, so the #1799 gate reclaims every array-masked verify block it claimed before this branch existed: the default reproduces main's dispatch exactly. `plan_bucketing_is_off_by_default_so_1799_dispatch_ships` pins that, so a future default change cannot alter shipped dispatch silently.

The code stays rather than being deleted, and the C++ comment says why so it is read as neither dead code nor a soft endorsement: the mechanism is sound (12 plan builds per generation instead of 82, greedy token ids byte-identical to exact-shape cuDNN across three repeats), and a crossover above 2634 keys is plausible and unmeasured, because this path's cost is flat in context while the fallback materializes a score matrix that grows with the key length. A long-context re-measurement on a freshly booted host should be a flag flip, not a reimplementation.

The eligibility predicate is split into `plan_bucket_eligible_with`, which takes the bound as an argument. The old test asserted bucketing was eligible, which held only while the default was on, and a `OnceLock` read of the environment cannot be varied per test.

`docs/environment-variables.md` is corrected on both rows. The `MLXCEL_SDPA_FALLBACK_MAX_QUERIES` row claimed #1820 had narrowed it; that is true only when bucketing is enabled, and the shipped default leaves that gate's behaviour unchanged.

Refs #1820

* docs(benchmark): extract the #1820 traces and cite the quarantine file

Two cleanups on the data directory, which was 1.7 MB against 336 KB for the merged #1798 precedent at the same file count.

The three raw traces were 1.2 MB of it and 88 to 97 percent redundant (the non-speculative control is 3444 lines with 125 distinct). They are replaced by frequency extracts: one row per distinct line as the count, a tab, then the line. `sort -u` would have been wrong here, because the call totals the records cite are exactly those occurrence counts. What survives is every count, distinct-value count and maximum; what does not is per-call ordering, and no figure in either record depends on it. `harness/extract_trace.py` generates them and `summarize_trace.py` now reads either format and reports which it was given, using `max(plans)` rather than the last record for the resident plan count, which is equivalent because that counter is monotonic within a run.

Every number the records cite was re-derived from the extracts rather than assumed to survive: 82 plan builds upstream against 12 rebased (and 11 pre-rebase); the three shape classes at 25, 25 and 24 builds over 25 rounds, which is the three-per-round figure, against 12 in the whole rebased run; 1204 non-speculative calls with zero bucketed and three builds; cache extents 256 and 768 with `copy=0` on both target arms and `copy=1` on the drafter; and prefill chunks of 2048 and 586 query rows.

Doing that surfaced a gap this commit also closes. The 2026-09-17 record cited 12 plan builds and 1204 non-speculative calls from rebased runs that had never been committed; the committed traces were the pre-rebase ones, at 11 and 3444. Extracts of both rebased runs are added, so that record's own numbers now have evidence in the tree.

Second, `laguna_ladder_excluded.jsonl` was referenced by nothing. That is the defect rather than an oversight: the quarantined rows have clean foreign-process fields, so every automatic filter passes them, and an uncited file beside the clean data cannot be told from a stray one. Both records and both reports now name it, say it holds the halted 8k rung and the two 16k rows, say why each is disqualified, and say it is retained as raw evidence and cited for nothing.

Directory is 1.7 MB to 692 KB.

Refs #1820
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:linux Linux (CUDA / packaging) specific priority:high High priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(speculative): attribute the Laguna DFlash verify round's fixed and per-row cost on GB10

1 participant