Skip to content

fix: prevent silent NaN logits on MLX 0.31 (Qwen3.8 kernels switch Metal signatures with the window size) - #33

Closed
jasontitus wants to merge 1 commit into
ashhart:mainfrom
jasontitus:fix-kernel-signatures
Closed

jasontitus wants to merge 1 commit into
ashhart:mainfrom
jasontitus:fix-kernel-signatures

Conversation

@jasontitus

@jasontitus jasontitus commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Why: on MLX 0.31.2, TensorFold's Qwen3.8 kernels can silently produce NaN logits. It does not happen in today's serving loop, but only because of how rounds happen to be evaluated. It does happen during warm-up (harmlessly: those outputs are thrown away) and in tests. Any change that overlaps two rounds on the GPU would turn it into wrong output in serving. This PR removes the cause. It is a correctness fix only: output is byte-identical and speed is unchanged.

The bug: MLX 0.31.2 compiles a custom kernel differently depending on whether each input has fewer than 8 elements, but caches both versions under one name. Several of our kernel inputs are sized by the draft window (1 to 32 rows), so as windows change size a kernel flips between the two versions. Each flip throws away the compiled kernel and rebuilds it. That happened 585 times in one 18-request run on 0.3.0, too cheaply to show in the timings. If both versions are used within one batch of GPU work, the rebuild frees a pipeline that already-queued work still needs, and that work never runs: its outputs stay unwritten (NaN). We hit this while adding 3- and 2-bit weights (#34).

Why not just require MLX 0.32, which fixes it (ml-explore/mlx#3662)? TensorFold still allows 0.31.2, and its README recommends 0.31.2 on M5 because 0.32.2 breaks Nemotron's drafts there.

The fix: pad those window-sized inputs to at least 8 elements, so each kernel only ever has one version. The kernels never read the padding. This covers the M5 lane decoder and the M1-M4 row decoder. Five new tests record every kernel call's signature and fail without the fix.

How it happens

mx.fast.metal_kernel writes a kernel's Metal signature per call:

  • each input is declared constant when it has fewer than 8 elements, and device otherwise;
  • each input's dtype and scalar-ness, and the output dtypes, are written in too.

The compiled library is cached under the kernel's name plus its template only. MLX 0.31.2 is the pyproject floor and the version the README tests on the M5 Max (0.32.2 fails Nemotron's draft check there). In 0.31.2, when evaluating a call whose generated source differs from the cached one, eval_gpu runs Device::clear_library(name) and compiles the kernel again. Upstream fixed this in ml-explore/mlx#3662 (87c3cf9, first released in v0.32.0): kernel names now include each input's dtype, address space and scalar-ness, and the output dtypes.

The clear has two costs:

  • A recompile on the encoding thread, at every switch between the two signatures.
  • A lost dispatch when both signatures of one kernel are in the same graph. Clearing releases the pipeline that dispatches already encoded in the open command buffer still use: MLX's command buffers hold unretained references, and upstream calls it a use-after-free. In our runs those dispatches were lost and their outputs never written: NaN logits.

Several inputs of both Qwen3.8 dense decoders are sized by the window, so they cross 8 elements between calls:

Kernel Input Elements
attention tail and tree merge poA, pmA, plA 1 (a placeholder while no 64-key tile is committed) or the real partial state
attention tail depths W (window rows)
gated_delta_tree parents W
gated_delta_replay rows accepted rows
gdn_pre (lane_glue, lane_fuse, row_forward) windows W × 4
row decoder tree (row_forward) parents W
row_attention partial depth, path W, W × depth

In serving, each round's forward is evaluated before the next one is built (LaneEngine._step_tree, lane_prefill chunks). A round's commit runs lazily with the next forward, but the replay kernel is called once per graph. So every kernel sees one signature per graph, and main pays recompiles rather than lost dispatches: its replies are byte-identical to this change's in every launch. The row decoder (M1 to M4) changes width from round to round the same way.

On the 0.3.0 base, one server launch (Qwen3.8-27B 4-bit on the M5 lane decoder, 18 requests) had 585 signature changes, each a recompile, and 0 with this change (breakdown under Performance).

Both signatures meet in one graph in two places:

  • lane_fuse.warm runs rows 1, 17 and 33 in one mx.eval. The outputs lost there are discarded.
  • The lane decoder's tests, whose rounds evaluate once at the end, with pipeline_layers leaving layers lazy. There it produced all-NaN logits in test_models_of_other_widths_in_one_process (in the 3-bit PR: a 4-bit then a 3-bit model in one process, without pipelining).

Any future pipelining across rounds would hit it in serving.

Fix

kernels/metal_inputs.device_ints() pads a list of ints to MIN_DEVICE_ELEMENTS (8), at the end. It is used for:

  • The lane decoder (M5): tree parents, attention depths, and a padded copy of the replay rows (the unpadded rows still drives mx.take). _conv_windows pads its rows, lane_fuse.warm warms with them, and the attention placeholders take 8 elements.
  • The row decoder (M1 to M4, new in 0.3.3/0.3.4): its tree parents, and row_attention's depth and path. Its gdn_pre windows and replay rows go through the same lane_tree code.

No kernel reads the padding. Each reads only the first len(values) entries, or the rows below W on the grid, and none reads a padded input's shape. No kernel's arithmetic changes. The one edit to a kernel source removes a stale comment in _TAIL ("a placeholder is tiny: constant space"), which renames the tail kernel; kernel_version hashes the kernel folder, so prefix snapshots stored by an earlier version are not reused after upgrading.

Not covered: the same pattern elsewhere, for follow-ups

These are left out because they cannot be tested end to end here:

  • Flash Next (qwen4_exp) kernels:
    • q4_hc_norm_* INJ ([R, 4]) changes between 1 and 2+ rows.
    • The [R]-sized POS, IDS, NK, SPARSE, COMPLETE and ENDS change at 8 rows.
    • rows_match_serial evaluates 1-row and multi-row forwards in one graph.
  • engine/gpu_sampling: seeds and positions are sized by rows. Flash Next and Nemotron reach it through family_engine.
  • Nemotron add_norm_moe / add_norm_experts: WE ([R, top_k, +2 when folded]) changes when that width is under 8.
  • mlx_lm's gated_delta_step_mask in Qwen3.8's batched multi-stream rounds: the mask is [B, width].

Requiring MLX 0.32 removes the whole class, but it is not an option on M5 while 0.32.2 fails Nemotron's draft check there. A general alternative is a wrapper that keys kernel objects by signature, as upstream now does; it costs some Python time per call on a hot path.

Tests

  • tests/kernel_signatures.py: a recorder that wraps mx.fast.metal_kernel. Per (name, template) it records the parts of the signature MLX 0.31.2 varies per call: dtype, scalar-ness, constant or device, and output dtypes.
  • Lane decoder (test_lane_fuse.py::test_kernel_signatures_do_not_change_between_calls[fused=False|True]): the lane matmul's install and warm-ups, then rounds of a 40-row prompt, a 16-node tree keeping 7, a 20-row chain, single rows and a 3-row chain, with the committed keys crossing a 64-key tile.
  • Row decoder (test_row_forward.py::test_one_kernel_signature_for_every_window[row_qmv|simd_qmm]): a chunked prompt and windows of 7 rows kept 3, 2, 1 and full width, plus 12 rows kept 9 with the 16-row backend.
  • row_attention (test_row_attention.py::test_one_kernel_signature_for_every_window): windows of 1 to 15 rows, chains and a tree.
  • Each asserts one signature per kernel and finite outputs. All five fail without this change and pass with it. Full suite on 0.3.4.1: 376 passed, 1 skipped.

Performance vs main (measured on 0.3.4; rebased onto 0.3.4.1)

Setup: M5 Max 128 GB, Qwen3.8-27B 4-bit (Vontra) with the DFlash2 drafter. One server at a time, 4 launches per arm interleaved with main's. 512-token replies, thinking off, prompt cache and MLX buffer cache off, 16k context.

Mean over launches of each launch's median, tok/s (ms/round). Memory is the median launch's steady / peak phys_footprint.

Arm Code T1 Code T0 Prose T1 Prose T0 Tokens / round (code T0) Steady / peak GiB
0.3.4 138.9 (54.5) 143.8 (54.0) 75.2 (53.4) 72.5 (54.0) 7.53 19.43 / 20.97
this change 141.2 (54.0) 145.2 (53.5) 75.1 (53.2) 72.8 (53.7) 7.53 19.43 / 20.97

No measurable speed change (-0.1% to +1.6%). The recompiles it removes are not what limits a round. The change is for correctness.

Output:

  • Replies: byte-identical to 0.3.4 in every launch (text hashes per prompt and temperature).
  • Drafted vs serial: "draft": false replies match drafted ones in 10 of 10 cases.
  • Fresh server: the first request equals the second in every launch.
  • Signature changes while serving (measured on the 0.3.0 base, M5 lane decoder, one launch of 18 requests): 585 on main (replay rows 437, tree parents 46, attention placeholders and depths 86, gdn_pre windows 16); 0 with this change, with the same 69 first compiles.

How it was measured

  • Speed: a harness that starts each arm's server in turn, checks that the GPU is idle and that the machine is on AC power in High Power mode, then reads the server's own tok/s and round counts over 4 prompt/temperature cells. It samples memory at 1 Hz with footprint.
  • Signature changes: a separate launch with mx.fast.metal_kernel wrapped to log every signature change. It is kept separate because the wrapper adds Python time per call.

🤖 Generated with Claude Code

mx.fast.metal_kernel declares an input `constant` below 8 elements and
`device` from 8 up, but MLX 0.31.2 (the pyproject floor, and the version
the README tests on M5) caches the compiled kernel by name and template
only. A call with the other signature clears the library and recompiles;
with both signatures in one graph, dispatches already encoded lose their
pipeline and never run (NaN logits). Fixed upstream in ml-explore/mlx#3662
(v0.32.0).

The window-sized inputs of both Qwen3.8 dense decoders now keep at least 8
elements, padded at the end (kernels/metal_inputs.device_ints): the lane
decoder's tree parents, attention depths and placeholders, replay rows and
gdn_pre windows; and the row decoder's tree parents, gdn_pre windows and
replay rows (shared lane_tree code), and row_attention's depth and path.
No kernel reads the padding; bits are unchanged. On 0.3.0 (M5 Max), one
serving launch recompiled lane kernels 585 times; with this change, 0.

Tests: tests/kernel_signatures.py records each call's signature; the lane
decoder (install, warm-ups, rounds of several widths), the row decoder
with both matmul backends, and row_attention must keep one signature per
kernel. All five fail without this change.

Not covered: Qwen3.8 Flash Next's kernels and engine/gpu_sampling (inputs
sized by rows), and mlx_lm's masked gated_delta kernel in multi-stream
rounds (built inside mlx_lm).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@jasontitus jasontitus changed the title fix: keep each Qwen3.8 dense kernel's Metal signature fixed (MLX 0.31 recompiles, and can lose dispatches) fix: prevent silent NaN logits on MLX 0.31 (Qwen3.8 kernels switch Metal signatures with the window size) Sep 27, 2026
@ashhart

ashhart commented Sep 27, 2026

Copy link
Copy Markdown
Owner

Thanks @jasontitus for tracing the MLX 0.31 kernel-signature problem and adding the regression checks. The fix is in final testing for 0.3.5, which ships tonight, as a commit authored by you. This PR closes when the release is published.

ashhart pushed a commit that referenced this pull request Sep 27, 2026
MLX 0.31.2 compiles a custom kernel's input as `constant` below 8 elements
and `device` from 8 up, but caches both under one name; a call with the
other signature rebuilds the library and can drop queued work (NaN
outputs). tests/kernel_signatures.py records each mx.fast.metal_kernel
call's signature (input dtypes, scalars, constant or device, output
dtypes) per kernel name and template, and the tests below require one
signature per kernel.

From jasontitus's pull request #33. release-0.3.5 already pads every
window-sized input of these kernels (kernels/inputs.py and
lane_tree.kernel_ints, from its own fix of the same bug), so this port
brings the tests and no source change.

Adapted by the maintainer to release-0.3.5's decoders: the lane-decoder
test drives lane_multi over stream_attention and stream_gdn, through the
PR's one-stream rounds plus shared rounds of 1 to 9 streams (two launch
groups past 8); the row-decoder test uses the simd_qmm backend (the only
one here) with a window of WINDOW_ROWS instead of the backend's row limit,
and adds a draft tree through row_attention and shared rounds through
row_streams. With the padding switched off, all four tests fail.
@ashhart

ashhart commented Sep 27, 2026

Copy link
Copy Markdown
Owner

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants