diff --git a/CHANGELOG.md b/CHANGELOG.md index c2012b61671..d336a2861c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,12 +4,12 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Inkling 2 Mini on Metal: decode's routed-expert dots, router, dynamic convolution, logits and loop gates read their weights and activations in 16-byte loads and the router picks its top 8 in parallel, about twice as fast on an M4 Pro (9.3 to 20.9 tok/s, one stream), with every output bit and every sum order unchanged (#4919). + - Inkling 2 on Metal: the DSpark drafter's kernels are reworked, with transposed phi and RNN weights, one online-softmax attention kernel without score scratch, batched multi-stream drafting, softmax chances and a two-pass GPU top-k; plain and drafted output bits are unchanged (#4699). Thanks @gilby. - Flash Next on CUDA prefill: `TF_FLASHNEXT_PREFILL_MTP_LEAN=1` runs only the cache-writing part of the MTP step during prefill, skipping proposal and query work whose outputs prefill never reads; off by default (#4529). - - - Tests: `test-metal-residency-owners-host` builds and passes again; its Qwen27 fixture no longer reads an unset draft-backend field (#4987). - DeepSeek-V4.1 on Metal: if the BF16 `mv_mma` pipeline fails to load, the F32 pipeline created before it is released instead of leaked (#5015). Thanks @cwschroeder. diff --git a/zig/kernels/metal/inkling2/experts.metal b/zig/kernels/metal/inkling2/experts.metal index 72d8cba9029..e86e780383a 100644 --- a/zig/kernels/metal/inkling2/experts.metal +++ b/zig/kernels/metal/inkling2/experts.metal @@ -37,19 +37,84 @@ inline float ink2_mx_weight(uchar value, uchar scale) { return float(bfloat(w)); } +inline float2 ink2_bf2(uint pair) { + return float2(as_type(pair << 16u), as_type(pair & 0xffff0000u)); +} + +// A byte of two E2M1 codes as two FP16 values scaled by 2^-14, low nibble first; the byte must stand alone. +inline float2 ink2_e2m1_pair(uint code) { + return float2(as_type(((code * 0x00200200u) & 0x0e000e00u) | ((code * 0x01001000u) & 0x80008000u))); +} + +// ink2_e4m3(code) * 2^14 from the FP16 bits of the same layout; 0x7f and 0xff stay NaN. +inline float ink2_e4m3_scale(uint code) { + const float v = float(as_type(ushort(((code & 0x7fu) << 7u) | ((code & 0x80u) << 8u)))) * 4194304.0f; + return (code & 0x7fu) == 0x7fu ? as_type(((code & 0x80u) << 24u) | 0x7fc00000u) : v; +} + +// ink2_nv_weight twice: (e2m1 * 2^-14) * (e4m3 * 2^14) is the same exact product, then phi and one BF16 round. +inline float ink2_nv_byte(float sum, uint code, float scale, float phi, float2 x) { + const float2 m = ink2_e2m1_pair(code); + sum += float(bfloat((m.x * scale) * phi)) * x.x; + return sum + float(bfloat((m.y * scale) * phi)) * x.y; +} + +// Columns in order, 16 to a scale block; k is a multiple of 16 and w, x are 16-byte aligned. inline float ink2_dot_nv(device const uchar* w, device const uchar* scales, device const bfloat* x, float phi, uint k) { float sum = 0.0f; - for (uint c = 0; c < k; ++c) - sum += ink2_nv_weight(w[c / 2u], c, scales[c / 16u], phi) * float(x[c]); + for (uint b = 0; b < k / 16u; ++b) { + const uint2 codes = *(device const uint2*)(w + 8u * b); + const float scale = ink2_e4m3_scale(scales[b]); + const uint4 xa = *(device const uint4*)(x + 16u * b), xb = *(device const uint4*)(x + 16u * b + 8u); + sum = ink2_nv_byte(sum, codes.x & 255u, scale, phi, ink2_bf2(xa.x)); + sum = ink2_nv_byte(sum, (codes.x >> 8u) & 255u, scale, phi, ink2_bf2(xa.y)); + sum = ink2_nv_byte(sum, (codes.x >> 16u) & 255u, scale, phi, ink2_bf2(xa.z)); + sum = ink2_nv_byte(sum, codes.x >> 24u, scale, phi, ink2_bf2(xa.w)); + sum = ink2_nv_byte(sum, codes.y & 255u, scale, phi, ink2_bf2(xb.x)); + sum = ink2_nv_byte(sum, (codes.y >> 8u) & 255u, scale, phi, ink2_bf2(xb.y)); + sum = ink2_nv_byte(sum, (codes.y >> 16u) & 255u, scale, phi, ink2_bf2(xb.z)); + sum = ink2_nv_byte(sum, codes.y >> 24u, scale, phi, ink2_bf2(xb.w)); + } return sum; } -inline float ink2_dot_mx(device const uchar* w, device const uchar* scales, - device const bfloat* x, uint k) { +// Four E4M3 bytes, columns 4i to 4i + 3, added in order; the FP16 route gives e4m3 / 256, 2^(scale - 119) restores it. +inline float ink2_mx_word(float sum, uint word, float factor, float2 x01, float2 x23) { + const uint even = word & 0x00ff00ffu, odd = (word >> 8u) & 0x00ff00ffu; + const float2 w02 = float2(as_type(((even << 7u) & 0x3f803f80u) | ((even << 8u) & 0x80008000u))); + const float2 w13 = float2(as_type(((odd << 7u) & 0x3f803f80u) | ((odd << 8u) & 0x80008000u))); + sum += (w02.x * factor) * x01.x; + sum += (w13.x * factor) * x01.y; + sum += (w02.y * factor) * x23.x; + return sum + (w13.y * factor) * x23.y; +} + +// A block of 32 columns: scales 24 to 230 with no NaN code take the word route, the rest decode as ink2_mx_weight. +inline float ink2_mx_block(float sum, device const uchar* w, uint scale, device const bfloat* x) { + const uint4 q0 = *(device const uint4*)w, q1 = *(device const uint4*)(w + 16); + uint nan = 0u; + for (uint i = 0; i < 4u; ++i) nan |= ((q0[i] & 0x7f7f7f7fu) + 0x01010101u) | ((q1[i] & 0x7f7f7f7fu) + 0x01010101u); + if (scale - 24u > 206u || (nan & 0x80808080u) != 0u) { + for (uint j = 0; j < 32u; ++j) sum += ink2_mx_weight(w[j], uchar(scale)) * float(x[j]); + return sum; + } + const float factor = as_type((scale + 8u) << 23u); + const uint4 xa = *(device const uint4*)x, xb = *(device const uint4*)(x + 8), xc = *(device const uint4*)(x + 16); + const uint4 xd = *(device const uint4*)(x + 24); + sum = ink2_mx_word(sum, q0.x, factor, ink2_bf2(xa.x), ink2_bf2(xa.y)); + sum = ink2_mx_word(sum, q0.y, factor, ink2_bf2(xa.z), ink2_bf2(xa.w)); + sum = ink2_mx_word(sum, q0.z, factor, ink2_bf2(xb.x), ink2_bf2(xb.y)); + sum = ink2_mx_word(sum, q0.w, factor, ink2_bf2(xb.z), ink2_bf2(xb.w)); + sum = ink2_mx_word(sum, q1.x, factor, ink2_bf2(xc.x), ink2_bf2(xc.y)); + sum = ink2_mx_word(sum, q1.y, factor, ink2_bf2(xc.z), ink2_bf2(xc.w)); + sum = ink2_mx_word(sum, q1.z, factor, ink2_bf2(xd.x), ink2_bf2(xd.y)); + return ink2_mx_word(sum, q1.w, factor, ink2_bf2(xd.z), ink2_bf2(xd.w)); +} + +inline float ink2_dot_mx(device const uchar* w, device const uchar* scales, device const bfloat* x, uint k) { float sum = 0.0f; - for (uint c = 0; c < k; ++c) - sum += ink2_mx_weight(w[c], scales[c / 32u]) * float(x[c]); + for (uint b = 0; b < k / 32u; ++b) sum = ink2_mx_block(sum, w + 32u * b, scales[b], x + 32u * b); return sum; } diff --git a/zig/kernels/metal/inkling2/glue.metal b/zig/kernels/metal/inkling2/glue.metal index 81c7d2e2bd5..55ed7d1543b 100644 --- a/zig/kernels/metal/inkling2/glue.metal +++ b/zig/kernels/metal/inkling2/glue.metal @@ -18,6 +18,30 @@ inline float ink_value(const device bfloat* blocks, const device float* partial, return source + 1 == sources ? partial[d] : float(blocks[size_t(source) * 2304 + d]); } +// Two BF16 pairs of w and x multiplied and added to sum in column order. +inline float ink_pair(float sum, uint w, uint x) { + sum += as_type(w << 16u) * as_type(x << 16u); + return sum + as_type(w & 0xffff0000u) * as_type(x & 0xffff0000u); +} +// One thread's dot over k columns, k a multiple of 32 and both rows 16-byte aligned: the serial chain, loads batched. +inline float ink_chain(const device bfloat* w, const device bfloat* x, uint k) { + float sum = 0.0f; + for (uint d = 0; d < k; d += 32) { + uint4 a[4], b[4]; + for (uint i = 0; i < 4; ++i) { + a[i] = *(const device uint4*)(w + d + 8 * i); + b[i] = *(const device uint4*)(x + d + 8 * i); + } + for (uint i = 0; i < 4; ++i) { + sum = ink_pair(sum, a[i].x, b[i].x); + sum = ink_pair(sum, a[i].y, b[i].y); + sum = ink_pair(sum, a[i].z, b[i].z); + sum = ink_pair(sum, a[i].w, b[i].w); + } + } + return sum; +} + struct InkEmbedArgs { uint rows; }; [[max_total_threads_per_threadgroup(256)]] kernel void tf_inkling2_embed_norm( @@ -128,10 +152,7 @@ kernel void tf_inkling2_conv_dynamic( if (r >= a.rows) return; threadgroup float projected[32]; if (t < 32) { - float dot = 0.0f; - for (uint d = 0; d < 2304; ++d) - dot += float(projection[size_t(t) * 2304 + d]) * float(input[size_t(r) * 2304 + d]); - projected[t] = float(bfloat(dot)); + projected[t] = float(bfloat(ink_chain(projection + size_t(t) * 2304, input + size_t(r) * 2304, 2304))); } threadgroup_barrier(mem_flags::mem_threadgroup); for (uint c = t; c < a.channels; c += 256) { @@ -152,36 +173,55 @@ kernel void tf_inkling2_router( device float* weights [[buffer(4)]], constant InkRouteArgs& a [[buffer(5)]], uint t [[thread_position_in_threadgroup]], uint row [[threadgroup_position_in_grid]]) { if (row >= a.rows) return; - threadgroup float scores[128], chosen[8]; - threadgroup uint picked[8]; + threadgroup float scores[128], key[128], chosen[8]; + threadgroup uint picked[8], selected[128], any_nan; if (t < 128) { - float dot = 0.0f; - for (uint d = 0; d < 2304; ++d) - dot += float(weight[size_t(t) * 2304 + d]) * float(x[size_t(row) * 2304 + d]); - scores[t] = ink_sigmoid(dot); + scores[t] = ink_sigmoid(ink_chain(weight + size_t(t) * 2304, x + size_t(row) * 2304, 2304)); + key[t] = scores[t] + bias[t]; } threadgroup_barrier(mem_flags::mem_threadgroup); - if (t == 0) { - bool used[128] = {}; - for (uint j = 0; j < 8; ++j) { - uint best = 128; - for (uint e = 0; e < 128; ++e) if (!used[e]) { - if (best == 128 || scores[e] + bias[e] > scores[best] + bias[best]) best = e; + // Ranks 0 to 7 by (key descending, index ascending) are the serial scan's picks; a NaN key runs the scan. + if (t < 128) { + uint rank = 0; + bool nan = false; + for (uint f = 0; f < 128; ++f) { + nan = nan || isnan(key[f]); + rank += (key[f] > key[t] || (key[f] == key[t] && f < t)) ? 1u : 0u; + } + selected[t] = rank < 8 ? 1u : 0u; + // Every thread scanned all 128 keys; thread 0 alone stores the flag, so the barrier publishes one write. + if (t == 0) any_nan = nan ? 1u : 0u; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (any_nan != 0) { + if (t == 0) { + bool used[128] = {}; + for (uint j = 0; j < 8; ++j) { + uint best = 128; + for (uint e = 0; e < 128; ++e) if (!used[e]) { + if (best == 128 || key[e] > key[best]) best = e; + } + used[best] = true; picked[j] = best; chosen[j] = scores[best]; + } + // Combining, including the denominator, is in ascending expert index. + for (uint j = 1; j < 8; ++j) { + uint id = picked[j]; float score = chosen[j]; uint k = j; + while (k > 0 && picked[k - 1] > id) { picked[k] = picked[k - 1]; chosen[k] = chosen[k - 1]; --k; } + picked[k] = id; chosen[k] = score; } - used[best] = true; picked[j] = best; chosen[j] = scores[best]; } + } else if (t < 128 && selected[t] != 0) { // Combining, including the denominator, is in ascending expert index. - for (uint j = 1; j < 8; ++j) { - uint id = picked[j]; float score = chosen[j]; uint k = j; - while (k > 0 && picked[k - 1] > id) { picked[k] = picked[k - 1]; chosen[k] = chosen[k - 1]; --k; } - picked[k] = id; chosen[k] = score; - } + uint at = 0; + for (uint f = 0; f < t; ++f) at += selected[f]; + picked[at] = t; chosen[at] = scores[t]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < 8) { float den = 1e-20f; for (uint j = 0; j < 8; ++j) den += chosen[j]; - for (uint j = 0; j < 8; ++j) { - ids[row * 8 + j] = picked[j]; - weights[row * 8 + j] = precise::divide(chosen[j], den) * 8.0f; - } + ids[row * 8 + t] = picked[t]; + weights[row * 8 + t] = precise::divide(chosen[t], den) * 8.0f; } } @@ -205,9 +245,7 @@ kernel void tf_inkling2_logits( uint2 at [[thread_position_in_grid]]) { const uint v = at.x, r = at.y; if (v >= a.vocab || r >= a.rows) return; - float dot = 0.0f; - for (uint d = 0; d < 2304; ++d) - dot += float(unembed[size_t(v) * 2304 + d]) * float(h[size_t(r) * 2304 + d]); + const float dot = ink_chain(unembed + size_t(v) * 2304, h + size_t(r) * 2304, 2304); // A9(a): unembedding rounds to bf16 before it widens for softcap30. out[size_t(r) * a.vocab + v] = ink_cap(float(bfloat(dot)), 30.0f); } diff --git a/zig/kernels/metal/inkling2/loop.metal b/zig/kernels/metal/inkling2/loop.metal index 041738acb24..8142d0ba584 100644 --- a/zig/kernels/metal/inkling2/loop.metal +++ b/zig/kernels/metal/inkling2/loop.metal @@ -11,6 +11,17 @@ constant uint INKLING_LOOP_MESSAGES = 48; struct InkLoopArgs { uint rows; }; +// Two BF16 pairs of w and x multiplied and added to sum in column order. +inline float ink_loop_pair(float sum, uint w, uint x) { + sum += as_type(w << 16u) * as_type(x << 16u); + return sum + as_type(w & 0xffff0000u) * as_type(x & 0xffff0000u); +} +// A BF16 pair of w times two FP32 values, added to sum in column order. +inline float ink_loop_zpair(float sum, uint w, float z0, float z1) { + sum += as_type(w << 16u) * z0; + return sum + as_type(w & 0xffff0000u) * z1; +} + [[max_total_threads_per_threadgroup(256)]] kernel void tf_inkling2_loop_messages( const device bfloat* bank0 [[buffer(0)]], const device bfloat* bank1 [[buffer(1)]], @@ -91,8 +102,11 @@ kernel void tf_inkling2_loop_gates( if (row >= a.rows) return; const device float* inputs[2] = { h + size_t(row) * INKLING_LOOP_H, m + size_t(row) * INKLING_LOOP_H }; - threadgroup float sums[2 * 8], inverse[2], zeta[INKLING_LOOP_RANK]; - threadgroup bfloat normalized[2 * INKLING_LOOP_H]; + threadgroup float sums[2 * 8], inverse[2]; + threadgroup float4 zeta4[INKLING_LOOP_RANK / 4]; + threadgroup uint4 normalized_words[2 * INKLING_LOOP_H / 8]; + threadgroup float* zeta = (threadgroup float*)zeta4; + threadgroup bfloat* normalized = (threadgroup bfloat*)normalized_words; for (uint s = 0; s < 2; ++s) { float ss = 0.0f; for (uint d = t; d < INKLING_LOOP_H; d += 256) { @@ -115,17 +129,43 @@ kernel void tf_inkling2_loop_gates( } threadgroup_barrier(mem_flags::mem_threadgroup); if (t < INKLING_LOOP_RANK) { + // One thread a rank: the serial chain over the 4,608 normalized values, 64 BF16 loaded ahead of each step. + const device uint4* w = (const device uint4*)(down + size_t(t) * (2 * INKLING_LOOP_H)); float dot = 0.0f; - for (uint d = 0; d < 2 * INKLING_LOOP_H; ++d) - dot += float(down[size_t(t) * (2 * INKLING_LOOP_H) + d]) * float(normalized[d]); + for (uint j = 0; j < 2 * INKLING_LOOP_H / 8; j += 8) { + uint4 wv[8]; + for (uint i = 0; i < 8; ++i) wv[i] = w[j + i]; + for (uint i = 0; i < 8; ++i) { + const uint4 xv = normalized_words[j + i]; + dot = ink_loop_pair(dot, wv[i].x, xv.x); + dot = ink_loop_pair(dot, wv[i].y, xv.y); + dot = ink_loop_pair(dot, wv[i].z, xv.z); + dot = ink_loop_pair(dot, wv[i].w, xv.w); + } + } zeta[t] = float(bfloat(dot)); } threadgroup_barrier(mem_flags::mem_threadgroup); for (uint d = t; d < INKLING_LOOP_H; d += 256) { + // The forget and gain dots over zeta in rank order, each row loaded whole ahead of its chain. + const device uint4* fw = (const device uint4*)(forget + size_t(d) * INKLING_LOOP_RANK); + const device uint4* gw = (const device uint4*)(gain + size_t(d) * INKLING_LOOP_RANK); + uint4 fv[8], gv[8]; + for (uint j = 0; j < 8; ++j) { + fv[j] = fw[j]; + gv[j] = gw[j]; + } float fdot = 0.0f, gdot = 0.0f; - for (uint r = 0; r < INKLING_LOOP_RANK; ++r) { - fdot += float(forget[size_t(d) * INKLING_LOOP_RANK + r]) * zeta[r]; - gdot += float(gain[size_t(d) * INKLING_LOOP_RANK + r]) * zeta[r]; + for (uint j = 0; j < 8; ++j) { + const float4 z0 = zeta4[2 * j], z1 = zeta4[2 * j + 1]; + fdot = ink_loop_zpair(fdot, fv[j].x, z0.x, z0.y); + fdot = ink_loop_zpair(fdot, fv[j].y, z0.z, z0.w); + fdot = ink_loop_zpair(fdot, fv[j].z, z1.x, z1.y); + fdot = ink_loop_zpair(fdot, fv[j].w, z1.z, z1.w); + gdot = ink_loop_zpair(gdot, gv[j].x, z0.x, z0.y); + gdot = ink_loop_zpair(gdot, gv[j].y, z0.z, z0.w); + gdot = ink_loop_zpair(gdot, gv[j].z, z1.x, z1.y); + gdot = ink_loop_zpair(gdot, gv[j].w, z1.z, z1.w); } const float f = precise::tanh(fdot); const float g = precise::tanh(gdot); diff --git a/zig/src/core/contract/inkling2_glue_metal_records.zig b/zig/src/core/contract/inkling2_glue_metal_records.zig index a57ea0f4d5d..e0c481274a7 100644 --- a/zig/src/core/contract/inkling2_glue_metal_records.zig +++ b/zig/src/core/contract/inkling2_glue_metal_records.zig @@ -5,7 +5,7 @@ pub const records = [_]M{ .{ .name = "metal inkling2 glue ar tf_inkling2_ar", .threads = 256, .tg_memory = 368, .reserved = 256 }, .{ .name = "metal inkling2 glue conv_static tf_inkling2_conv_static", .threads = 32, .tg_memory = 0, .reserved = 32 }, .{ .name = "metal inkling2 glue conv_dynamic tf_inkling2_conv_dynamic", .threads = 256, .tg_memory = 128, .reserved = 256 }, - .{ .name = "metal inkling2 glue router tf_inkling2_router", .threads = 256, .tg_memory = 576, .reserved = 256 }, + .{ .name = "metal inkling2 glue router tf_inkling2_router", .threads = 256, .tg_memory = 1616, .reserved = 256 }, .{ .name = "metal inkling2 glue swiglu tf_inkling2_swiglu", .threads = 32, .tg_memory = 0, .reserved = 32 }, .{ .name = "metal inkling2 glue logits tf_inkling2_logits", .threads = 32, .tg_memory = 0, .reserved = 32 }, .{ .name = "metal inkling2 glue expert_pick tf_inkling2_expert_pick", .threads = 32, .tg_memory = 0, .reserved = 32 }, diff --git a/zig/src/families/inkling2/metal/experts.zig b/zig/src/families/inkling2/metal/experts.zig index 0a63d4a08fd..f5a4c568626 100644 --- a/zig/src/families/inkling2/metal/experts.zig +++ b/zig/src/families/inkling2/metal/experts.zig @@ -97,8 +97,9 @@ fn launch(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, groups: u32 e.dispatchGroups(mtl.Size.of(groups, 1, 1), mtl.Size.of(32, 1, 1)); } -/// The products and the combine: threadgroups along the outputs (x) by route pairs or tokens (y). -fn launchGrid(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, g: plan.Geometry) void { +/// Products and combine: groups along outputs (x) by route pairs or tokens (y); 16-byte words need 16-byte offsets. +fn launchGrid(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, g: plan.Geometry, words: []const Ref) !void { + for (words) |r| if (r.off % 16 != 0) return error.ExpertAlignment; e.setPipeline(p.get(op)); e.dispatchGroups(mtl.Size.of(g.blocks, g.groups, 1), mtl.Size.of(g.threads, 1, 1)); } @@ -109,7 +110,7 @@ pub fn nvfp4Gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scale try plan.check(c); for ([_]Ref{ x, w, scales, amax, denominator, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(args(c), 7); - launchGrid(p, e, .nvfp4_gu, plan.geometry(c)); + try launchGrid(p, e, .nvfp4_gu, plan.geometry(c), &.{ x, w }); } /// Packed MXFP8 GU with UE8M0 scales per row/block32. @@ -118,7 +119,7 @@ pub fn mxfp8Gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scale try plan.check(c); for ([_]Ref{ x, w, scales, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(args(c), 5); - launchGrid(p, e, .mxfp8_gu, plan.geometry(c)); + try launchGrid(p, e, .mxfp8_gu, plan.geometry(c), &.{ x, w }); } pub fn nvfp4Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, amax: Ref, denominator: Ref, ids: Ref, out: Ref, c: Call) !void { @@ -126,7 +127,7 @@ pub fn nvfp4Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, s try plan.check(c); for ([_]Ref{ act, w, scales, amax, denominator, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(args(c), 7); - launchGrid(p, e, .nvfp4_down, plan.geometry(c)); + try launchGrid(p, e, .nvfp4_down, plan.geometry(c), &.{ act, w }); } pub fn mxfp8Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, ids: Ref, out: Ref, c: Call) !void { @@ -134,7 +135,7 @@ pub fn mxfp8Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, s try plan.check(c); for ([_]Ref{ act, w, scales, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(args(c), 5); - launchGrid(p, e, .mxfp8_down, plan.geometry(c)); + try launchGrid(p, e, .mxfp8_down, plan.geometry(c), &.{ act, w }); } /// Decode one expert matrix to BF16, not an activation quantization operation. @@ -160,7 +161,7 @@ pub fn combine(p: *const Pipelines, e: mtl.ComputeEncoder, down: Ref, ids: Ref, for ([_]Ref{ down, ids, weights, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(args(c), 4); // Combine's rows are tokens, rather than route pairs. - launchGrid(p, e, .combine, plan.combineGeometry(c)); + try launchGrid(p, e, .combine, plan.combineGeometry(c), &.{}); } pub fn gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, nv_globals: ?struct { amax: Ref, denominator: Ref }, ids: Ref, out: Ref, c: Call) !void { diff --git a/zig/tests/contract/metal_inkling2_experts_controls.zig b/zig/tests/contract/metal_inkling2_experts_controls.zig index fefd5d873ce..0edffa327c3 100644 --- a/zig/tests/contract/metal_inkling2_experts_controls.zig +++ b/zig/tests/contract/metal_inkling2_experts_controls.zig @@ -99,7 +99,8 @@ test "inkling2 experts: one thread an output, and each dot stays the serial chai try std.testing.expectEqual(@as(usize, 5), std.mem.count(u8, text, "const uint n = tg.x * 32u + lane")); try std.testing.expectEqual(@as(usize, 5), std.mem.count(u8, text, "if (n >= a.n) return;")); // the two dots: one FP32 chain from column 0 up, products rounded before each add, no lane reduction - try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, text, "for (uint c = 0; c < k; ++c)")); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "for (uint b = 0; b < k / 16u; ++b)")); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "for (uint b = 0; b < k / 32u; ++b)")); try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "#pragma METAL fp contract(off)")); try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, text, "simd_sum")); } diff --git a/zig/tests/contract/metal_inkling2_glue.zig b/zig/tests/contract/metal_inkling2_glue.zig index f8c90a6cf5f..2a3d0c78e5d 100644 --- a/zig/tests/contract/metal_inkling2_glue.zig +++ b/zig/tests/contract/metal_inkling2_glue.zig @@ -63,6 +63,7 @@ pub const Probe = struct { /// The split router against main's tf_inkling2_router: 1, 33 and 64 rows, two select blocks at 64. split: bool = false, scores: rig_.Ref = undefined, + nan_keys_run: bool = false, pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind) !Probe { return initSource(a, device, queue, kind, sources.glue); @@ -374,6 +375,59 @@ pub const Probe = struct { if (@abs(got - want[row * 8 + j]) > 1e-5 * @max(1, @abs(want[row * 8 + j]))) return "router weight differs"; } } + if (!self.split and !self.nan_keys_run) { + self.nan_keys_run = true; + return self.nanKeys(); + } + return null; + } + /// Six rows with NaN keys (inf times a zero weight) at varied experts, 50 launches, each the serial scan's IDs. + fn nanKeys(self: *Probe) !?[]const u8 { + const sets = [_][]const u8{ &.{0}, &.{5}, &.{63}, &.{127}, &.{ 7, 90 }, &.{ 1, 2, 3, 126 } }; + const r = sets.len; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + var prng = std.Random.DefaultPrng.init(0x4919); + const rng = prng.random(); + const x = try self.floats(r * p.hidden, rng); + const w = try self.floats(p.expert_count * p.hidden, rng); + const bias = try self.arena.allocator().alloc(f32, p.expert_count); + for (bias, 0..) |*b, e| b.* = @as(f32, @floatFromInt(e * 37 % 128)) / 1024 - 0.0625; + round(x); + round(w); + for (sets, 0..) |set, row| { + x[row * p.hidden + row] = std.math.inf(f32); + for (0..p.expert_count) |e| if (w[e * p.hidden + row] == 0) { + w[e * p.hidden + row] = 0.125; + }; + for (set) |e| w[@as(usize, e) * p.hidden + row] = 0; + } + const xs = try self.input(x, true); + const ws = try self.input(w, true); + const bs = try self.input(bias, false); + const ids = try self.rig.scratch(r * 8 * 4); + const weights = try self.rig.scratch(r * 8 * 4); + var first: [r * 8 * 4]u8 = undefined; + for (0..50) |launch| { + const pass = self.rig.begin(); + host.router(&self.pipes, pass.e, at(xs), at(ws), at(bs), at(ids), at(weights), r); + try self.rig.finish(pass); + const got_ids = std.mem.bytesAsSlice(u32, self.rig.bytes(ids, r * 8 * 4)); + const got = self.rig.bytes(weights, r * 8 * 4); + for (0..r) |row| { + const route = p.route(x[row * p.hidden ..][0..p.hidden], w, bias); + for (0..8) |j| { + if (got_ids[row * 8 + j] != route.ids[j]) return "NaN-key selected IDs differ from the serial scan"; + const v = c.read(.f32, got, row * 8 + j); + const want = route.weights[j]; + if (std.math.isNan(v) != std.math.isNan(want)) return "NaN-key weight class differs from the serial scan"; + if (!std.math.isNan(want) and @abs(v - want) > 1e-5 * @max(1, @abs(want))) return "NaN-key router weight differs"; + } + } + if (launch == 0) { + @memcpy(&first, got); + } else if (!std.mem.eql(u8, &first, got)) return "a repeated NaN-key launch differs from the first"; + } return null; } }; @@ -407,6 +461,22 @@ pub const Suite = struct { try s.kernels.append(s.a, k); } + fn addNanControl(s: *Suite, control: controls.NanControl, only: ?[]const u8) !void { + const name = controls.nanName(control); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + const text = try controls.nanSource(s.a, sources.glue, control); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, .router, text); + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + k.spec.name = name; + k.control = .shapes; + try s.kernels.append(s.a, k); + } + fn addSplit(s: *Suite, control: ?split_controls.Control, only: ?[]const u8) !void { const name = if (control) |x| split_controls.name(x) else split_label; if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; @@ -431,6 +501,7 @@ pub const Suite = struct { try s.add(kind, true, only); } try s.addSplit(null, only); + for (std.enums.values(controls.NanControl)) |control| try s.addNanControl(control, only); try s.addSplit(.route_strided, only); try s.addSplit(.route_index, only); } diff --git a/zig/tests/contract/metal_inkling2_glue_controls.zig b/zig/tests/contract/metal_inkling2_glue_controls.zig index aba23199f09..18fbf8bc0ae 100644 --- a/zig/tests/contract/metal_inkling2_glue_controls.zig +++ b/zig/tests/contract/metal_inkling2_glue_controls.zig @@ -9,7 +9,7 @@ fn edit(kind: p.Kind) Edit { .ar => .{ .from = "weights[s] = dot * INKLING_AR_SCALE;", .to = "weights[s] = dot;" }, .conv_static => .{ .from = "weight[c * 4 + tap]", .to = "weight[c * 4 + 3 - tap]" }, .conv_dynamic => .{ .from = "static_w[lag * a.channels + c]", .to = "static_w[(3 - lag) * a.channels + c]" }, - .router => .{ .from = "scores[e] + bias[e] > scores[best] + bias[best]", .to = "scores[e] > scores[best]" }, + .router => .{ .from = "key[t] = scores[t] + bias[t];", .to = "key[t] = scores[t];" }, .swiglu => .{ .from = "ink_cap(u, 25.0f)", .to = "ink_cap(g, 25.0f)" }, .logits => .{ .from = "ink_cap(float(bfloat(dot)), 30.0f)", .to = "ink_cap(dot, 30.0f)" }, .expert_pick => .{ .from = "ids[r * 8 + j]", .to = "ids[r * 8 + 7 - j]" }, @@ -37,6 +37,40 @@ pub fn name(kind: p.Kind) []const u8 { }; } +/// The router's NaN-key fallback planted out: the rank picks run on every row, or the flag reads expert 0's key alone. +pub const NanControl = enum { no_fallback, key0_flag }; + +fn nanEdit(c: NanControl) Edit { + return switch (c) { + .no_fallback => .{ .from = " if (any_nan != 0) {", .to = " if (false) {" }, + .key0_flag => .{ .from = "if (t == 0) any_nan = nan ? 1u : 0u;", .to = "if (t == 0) any_nan = isnan(key[0]) ? 1u : 0u;" }, + }; +} + +pub fn nanSource(a: std.mem.Allocator, production: []const u8, c: NanControl) ![]u8 { + const e = nanEdit(c); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +pub fn nanName(c: NanControl) []const u8 { + return switch (c) { + .no_fallback => "control: metal inkling2 glue router tf_inkling2_router, NaN keys without the serial fallback", + .key0_flag => "control: metal inkling2 glue router tf_inkling2_router, the NaN flag from expert 0's key only", + }; +} + +test "every router NaN-key control applies once" { + const production = @import("inkling2_metal").glue; + const a = std.testing.allocator; + for (std.enums.values(NanControl)) |c| { + const changed = try nanSource(a, production, c); + defer a.free(changed); + try std.testing.expectEqual(production.len - nanEdit(c).from.len + nanEdit(c).to.len, changed.len); + try std.testing.expectError(error.ControlEditMissing, nanSource(a, changed, c)); + } +} + test "every glue control applies once and changes only its arithmetic anchor" { const production = @import("inkling2_metal").glue; const a = std.testing.allocator;