Repository navigation
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
Closed
jasontitus wants to merge 1 commit into
jasontitus wants to merge 1 commit into
Conversation
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]>
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.
Owner
|
Thanks @jasontitus! This landed in 0.3.5 as 9ef3c7d, authored by you, and ships in https://github.com/ashhart/TensorFold/releases/tag/v0.3.5. |
This was referenced Oct 19, 2026
7 of 12 tasks
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.
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_kernelwrites a kernel's Metal signature per call:constantwhen it has fewer than 8 elements, anddeviceotherwise;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_gpurunsDevice::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:
Several inputs of both Qwen3.8 dense decoders are sized by the window, so they cross 8 elements between calls:
poA,pmA,plAdepthsgated_delta_treeparentsgated_delta_replayrowsgdn_pre(lane_glue, lane_fuse, row_forward)windowsparentsrow_attentionpartialdepth,pathIn serving, each round's forward is evaluated before the next one is built (
LaneEngine._step_tree,lane_prefillchunks). 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.warmruns rows 1, 17 and 33 in onemx.eval. The outputs lost there are discarded.pipeline_layersleaving layers lazy. There it produced all-NaN logits intest_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 toMIN_DEVICE_ELEMENTS(8), at the end. It is used for:parents, attentiondepths, and a padded copy of the replayrows(the unpaddedrowsstill drivesmx.take)._conv_windowspads its rows,lane_fuse.warmwarms with them, and the attention placeholders take 8 elements.parents, androw_attention'sdepthandpath. Itsgdn_prewindows and replay rows go through the samelane_treecode.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_versionhashes 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:
qwen4_exp) kernels:q4_hc_norm_*INJ([R, 4]) changes between 1 and 2+ rows.POS,IDS,NK,SPARSE,COMPLETEandENDSchange at 8 rows.rows_match_serialevaluates 1-row and multi-row forwards in one graph.engine/gpu_sampling:seedsandpositionsare sized by rows. Flash Next and Nemotron reach it throughfamily_engine.add_norm_moe/add_norm_experts:WE([R, top_k, +2 when folded]) changes when that width is under 8.gated_delta_step_maskin 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 wrapsmx.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.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.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.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.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:
"draft": falsereplies match drafted ones in 10 of 10 cases.gdn_prewindows 16); 0 with this change, with the same 69 first compiles.How it was measured
footprint.mx.fast.metal_kernelwrapped to log every signature change. It is kept separate because the wrapper adds Python time per call.🤖 Generated with Claude Code