From ab7585d9538dc5dcdaf16c5216f8dc930ebaa256 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:00:20 +0100 Subject: [PATCH 1/2] metal: MiniMax-M3's, Spark2.5's and Llama's NaN-aware bf16 argmax from one source (#2251) --- zig/kernels/metal/core/bf16_argmax.metal | 41 +++++++++++++++++++++++ zig/kernels/metal/llama/glue.metal | 37 ++------------------ zig/kernels/metal/minimax_m3/glue.metal | 37 ++------------------ zig/kernels/metal/sources.zig | 6 ++-- zig/kernels/metal/spark25/glue.metal | 37 ++------------------ zig/tests/contract/metal_minimax_glue.zig | 2 +- 6 files changed, 51 insertions(+), 109 deletions(-) create mode 100644 zig/kernels/metal/core/bf16_argmax.metal diff --git a/zig/kernels/metal/core/bf16_argmax.metal b/zig/kernels/metal/core/bf16_argmax.metal new file mode 100644 index 00000000000..83cc0b90570 --- /dev/null +++ b/zig/kernels/metal/core/bf16_argmax.metal @@ -0,0 +1,41 @@ +// The greedy draw for decode glue: a bf16 logits row's argmax, NaN first, ties to the lower id (MLX argmax). +#include +using namespace metal; + +// The better of two (value, id) candidates: NaN first (lower id among NaNs), then the larger value, then the lower id. +inline bool tf_bf16_argmax_better(float a, uint ia, float b, uint ib) { + if (isnan(a)) return !isnan(b) || ia < ib; + if (isnan(b)) return false; + return a > b || (a == b && ia < ib); +} + +// Kernel NAME: logits [vocab] bf16 to its argmax in ids[0], one threadgroup of 1024. +#define TF_BF16_ARGMAX(NAME) \ + [[kernel]] void NAME(const device bfloat* logits [[buffer(0)]], device uint* ids [[buffer(1)]], \ + constant uint& vocab [[buffer(2)]], uint t [[thread_position_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { \ + threadgroup float vals[32]; \ + threadgroup uint idxs[32]; \ + float best = -INFINITY; \ + uint at = 0xffffffffu; \ + for (uint i = t; i < vocab; i += 1024) { \ + const float v = float(logits[i]); \ + if (tf_bf16_argmax_better(v, i, best, at)) { best = v; at = i; } \ + } \ + for (ushort d = 16; d > 0; d >>= 1) { \ + const float ov = simd_shuffle_xor(best, d); \ + const uint oi = simd_shuffle_xor(at, d); \ + if (tf_bf16_argmax_better(ov, oi, best, at)) { best = ov; at = oi; } \ + } \ + if (lane == 0) { vals[sg] = best; idxs[sg] = at; } \ + threadgroup_barrier(mem_flags::mem_threadgroup); \ + if (sg != 0) return; \ + best = vals[lane]; \ + at = idxs[lane]; \ + for (ushort d = 16; d > 0; d >>= 1) { \ + const float ov = simd_shuffle_xor(best, d); \ + const uint oi = simd_shuffle_xor(at, d); \ + if (tf_bf16_argmax_better(ov, oi, best, at)) { best = ov; at = oi; } \ + } \ + if (lane == 0) ids[0] = at; \ + } diff --git a/zig/kernels/metal/llama/glue.metal b/zig/kernels/metal/llama/glue.metal index 33311408352..55a8bac131e 100644 --- a/zig/kernels/metal/llama/glue.metal +++ b/zig/kernels/metal/llama/glue.metal @@ -230,41 +230,8 @@ struct ll_vec_args { uint rows, pos, heads, groups, blocks, chunk, first; float for (uint j = 0; j < PER; ++j) O[(row * a.heads + head) * DH + PER * sg + j] = bfloat(acc[j]); } -inline bool ll_better(float a, uint ia, float b, uint ib) { - if (isnan(a)) return !isnan(b) || ia < ib; - if (isnan(b)) return false; - return a > b || (a == b && ia < ib); -} - -// The greedy draw (nemotron_glue's tf_argmax_bf16): a bf16 logits row's argmax, ties to the lower id, into ids[0]. -[[kernel]] void ll_argmax(const device bfloat* logits [[buffer(0)]], device uint* ids [[buffer(1)]], - constant uint& vocab [[buffer(2)]], uint t [[thread_position_in_threadgroup]], - uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { - threadgroup float vals[32]; - threadgroup uint idxs[32]; - float best = -INFINITY; - uint at = 0xffffffffu; - for (uint i = t; i < vocab; i += 1024) { - const float v = float(logits[i]); - if (ll_better(v, i, best, at)) { best = v; at = i; } - } - for (ushort d = 16; d > 0; d >>= 1) { - const float ov = simd_shuffle_xor(best, d); - const uint oi = simd_shuffle_xor(at, d); - if (ll_better(ov, oi, best, at)) { best = ov; at = oi; } - } - if (lane == 0) { vals[sg] = best; idxs[sg] = at; } - threadgroup_barrier(mem_flags::mem_threadgroup); - if (sg != 0) return; - best = vals[lane]; - at = idxs[lane]; - for (ushort d = 16; d > 0; d >>= 1) { - const float ov = simd_shuffle_xor(best, d); - const uint oi = simd_shuffle_xor(at, d); - if (ll_better(ov, oi, best, at)) { best = ov; at = oi; } - } - if (lane == 0) ids[0] = at; -} +// The greedy draw: a bf16 logits row's argmax into ids[0] (core/bf16_argmax.metal). +TF_BF16_ARGMAX(ll_argmax) // The bf16 linear rows ll_matvec_1 to ll_matvec_32 (core/bf16_matvec.metal). TF_BF16_MATVECS(ll) diff --git a/zig/kernels/metal/minimax_m3/glue.metal b/zig/kernels/metal/minimax_m3/glue.metal index ccdd1bd8594..0b798224edd 100644 --- a/zig/kernels/metal/minimax_m3/glue.metal +++ b/zig/kernels/metal/minimax_m3/glue.metal @@ -528,41 +528,8 @@ struct mm_vec_args { uint rows, pos, heads, groups, topk; float scale; uint sel, *(device bfloat4*)(O + (row * a.heads + head) * 128 + 4 * lane) = bfloat4(acc); } -inline bool mm_better(float a, uint ia, float b, uint ib) { - if (isnan(a)) return !isnan(b) || ia < ib; - if (isnan(b)) return false; - return a > b || (a == b && ia < ib); -} - -// The greedy draw: a bf16 logits row's argmax, ties to the lower id, into ids[0]. -[[kernel]] void mm_argmax(const device bfloat* logits [[buffer(0)]], device uint* ids [[buffer(1)]], - constant uint& vocab [[buffer(2)]], uint t [[thread_position_in_threadgroup]], - uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { - threadgroup float vals[32]; - threadgroup uint idxs[32]; - float best = -INFINITY; - uint at = 0xffffffffu; - for (uint i = t; i < vocab; i += 1024) { - const float v = float(logits[i]); - if (mm_better(v, i, best, at)) { best = v; at = i; } - } - for (ushort d = 16; d > 0; d >>= 1) { - const float ov = simd_shuffle_xor(best, d); - const uint oi = simd_shuffle_xor(at, d); - if (mm_better(ov, oi, best, at)) { best = ov; at = oi; } - } - if (lane == 0) { vals[sg] = best; idxs[sg] = at; } - threadgroup_barrier(mem_flags::mem_threadgroup); - if (sg != 0) return; - best = vals[lane]; - at = idxs[lane]; - for (ushort d = 16; d > 0; d >>= 1) { - const float ov = simd_shuffle_xor(best, d); - const uint oi = simd_shuffle_xor(at, d); - if (mm_better(ov, oi, best, at)) { best = ov; at = oi; } - } - if (lane == 0) ids[0] = at; -} +// The greedy draw: a bf16 logits row's argmax into ids[0] (core/bf16_argmax.metal). +TF_BF16_ARGMAX(mm_argmax) // bf16 rows into fp32 ones (n values): an image's rows over their placeholders' embeddings, the tower's pre-norm out. diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index 5c28fc732fc..90556bce078 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -188,7 +188,7 @@ pub const core_simd_qmm_bits = @embedFile("core/simd_qmm_bits.metal"); /// Step-5's glue at StepFun's rounding points: embed, norms, q/k rotation, gate, SwiGLU, residual adds. pub const step5_glue = @embedFile("step5/glue.metal"); /// MiniMax-M3's glue at transformers' rounding points: norms, rotation, SwiGLU-OAI, router, indexer, decode attention. -pub const minimax_m3_glue = @embedFile("minimax_m3/glue.metal"); +pub const minimax_m3_glue = @embedFile("core/bf16_argmax.metal") ++ @embedFile("minimax_m3/glue.metal"); /// MiniMax-M3's prompt attention on the tensor units over each row's kept index blocks. pub const minimax_m3_attention_nax = @embedFile("minimax_m3/attention_nax.metal"); /// MiniMax-M3's DSpark drafter (norms, q/k into its context rings, block attention, the Markov chain) and the taps. @@ -210,13 +210,13 @@ pub const step5_attend_nax = @embedFile("step5/attend_nax.metal"); /// Step-5's image tower (perception encoder, downsampler convs, projector) on gemm_nax's tensor-unit GEMMs. pub const step5_vision = vision_glue ++ @embedFile("step5/vision.metal"); /// Spark2.5's glue at its PyTorch rounding points: embed, fp32 residual adds and norms, rope, head gate, exact GELU. -pub const spark25_glue = @embedFile("core/bf16_matvec.metal") ++ @embedFile("spark25/glue.metal"); +pub const spark25_glue = @embedFile("core/bf16_matvec.metal") ++ @embedFile("core/bf16_argmax.metal") ++ @embedFile("spark25/glue.metal"); /// Spark2.5's prompt attention on the tensor units (gemma4's prompt kernel; nax.h inlined at load). pub const spark25_attention_nax = @embedFile("spark25/attention_nax.metal"); /// Spark2.5's bf16 prompt projections on gemm_nax's tensor-unit GEMM (nax.h inlined at load). pub const spark25_gemm = gemm_nax ++ @embedFile("spark25/gemm.metal"); /// Llama's glue at HF's rounding points: embed, a bf16 residual and its norm, rope with bf16 cos and sin, SiLU. -pub const llama_glue = @embedFile("core/bf16_matvec.metal") ++ @embedFile("llama/glue.metal"); +pub const llama_glue = @embedFile("core/bf16_matvec.metal") ++ @embedFile("core/bf16_argmax.metal") ++ @embedFile("llama/glue.metal"); /// Llama's prompt attention on the tensor units (gemma4's prompt kernel, every key; nax.h inlined at load). pub const llama_attention_nax = @embedFile("llama/attention_nax.metal"); /// Llama's bf16 prompt projections on gemm_nax's tensor-unit GEMM (nax.h inlined at load). diff --git a/zig/kernels/metal/spark25/glue.metal b/zig/kernels/metal/spark25/glue.metal index 9508cbb7b57..ecc49dc0f60 100644 --- a/zig/kernels/metal/spark25/glue.metal +++ b/zig/kernels/metal/spark25/glue.metal @@ -232,41 +232,8 @@ struct sp_vec_args { uint rows, pos, heads, groups, ring, window, blocks, chunk, for (uint j = 0; j < PER; ++j) O[(row * a.heads + head) * DH + PER * sg + j] = bfloat(acc[j]); } -inline bool sp_better(float a, uint ia, float b, uint ib) { - if (isnan(a)) return !isnan(b) || ia < ib; - if (isnan(b)) return false; - return a > b || (a == b && ia < ib); -} - -// The greedy draw (nemotron_glue's tf_argmax_bf16): a bf16 logits row's argmax, ties to the lower id, into ids[0]. -[[kernel]] void sp_argmax(const device bfloat* logits [[buffer(0)]], device uint* ids [[buffer(1)]], - constant uint& vocab [[buffer(2)]], uint t [[thread_position_in_threadgroup]], - uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { - threadgroup float vals[32]; - threadgroup uint idxs[32]; - float best = -INFINITY; - uint at = 0xffffffffu; - for (uint i = t; i < vocab; i += 1024) { - const float v = float(logits[i]); - if (sp_better(v, i, best, at)) { best = v; at = i; } - } - for (ushort d = 16; d > 0; d >>= 1) { - const float ov = simd_shuffle_xor(best, d); - const uint oi = simd_shuffle_xor(at, d); - if (sp_better(ov, oi, best, at)) { best = ov; at = oi; } - } - if (lane == 0) { vals[sg] = best; idxs[sg] = at; } - threadgroup_barrier(mem_flags::mem_threadgroup); - if (sg != 0) return; - best = vals[lane]; - at = idxs[lane]; - for (ushort d = 16; d > 0; d >>= 1) { - const float ov = simd_shuffle_xor(best, d); - const uint oi = simd_shuffle_xor(at, d); - if (sp_better(ov, oi, best, at)) { best = ov; at = oi; } - } - if (lane == 0) ids[0] = at; -} +// The greedy draw: a bf16 logits row's argmax into ids[0] (core/bf16_argmax.metal). +TF_BF16_ARGMAX(sp_argmax) // Row r of residual R = bf16 embedding row ids[r] (the release's table, [vocab, width]), held in fp32. [[kernel]] void sp_embed_bf16(const device uint* ids [[buffer(0)]], const device bfloat* E [[buffer(1)]], diff --git a/zig/tests/contract/metal_minimax_glue.zig b/zig/tests/contract/metal_minimax_glue.zig index 9ffc8165abd..1ea2b1f6b3c 100644 --- a/zig/tests/contract/metal_minimax_glue.zig +++ b/zig/tests/contract/metal_minimax_glue.zig @@ -422,7 +422,7 @@ pub const Copy = struct { // --- mm_argmax: the greedy draw over a bf16 logits row, ties to the lower id --------------------------------------- -/// mm_better: NaN beats any number (the lower id among NaNs), else the larger value, ties to the lower id. +/// tf_bf16_argmax_better (core/bf16_argmax.metal): NaN first (lower id among NaNs), then larger, ties to the lower id. fn better(v: f32, i: usize, best: f32, at: usize) bool { if (std.math.isNan(v)) return !std.math.isNan(best) or i < at; if (std.math.isNan(best)) return false; From 1716a73ce02f6752bb48893830d6bbbe7e651db7 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:42:18 +0000 Subject: [PATCH 2/2] changelog: #2949 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d785a94f97b..3a81c13ac54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Metal: MiniMax-M3, Spark2.5 and Llama take their NaN-aware bf16 argmax from one shared source; the compiled code is unchanged (#2949, part of #2251). Thanks to @jschmied. + - Metal: the image towers of GLM, Step-5, Gemma 4 and Qwen share one source for bf16 rounding, threadgroup sum and max, row softmax and LayerNorm statistics; the compiled code is unchanged (#2948, part of #2251). Thanks to @jschmied. - Tests: the dashboard page's test runs on every OS, so Linux CI covers it, and no longer expects a paged prefix cache tile the page never had; `zig build test` passes on Macs again (#2946).