diff --git a/zig/kernels/metal/inkling2/dense_mma.metal b/zig/kernels/metal/inkling2/dense_mma.metal new file mode 100644 index 00000000000..7e294d805e6 --- /dev/null +++ b/zig/kernels/metal/inkling2/dense_mma.metal @@ -0,0 +1,87 @@ +// Prompt projections on simdgroup matrices for GPUs without tensor units: sp_matvec's sums, bit for bit. +#include +using namespace metal; + +struct Ink2DenseMmaArgs { + uint rows, n, k, ldy; +}; + +using ink2_dense_frag = simdgroup_matrix; + +// Row tiles ROWS and column tiles COLS of the 16 by 16 tile that hold outputs; simdgroup g keeps lanes 8g .. 8g + 7. +template +inline void ink2_dense_mma(const device bfloat* X, const device bfloat* W, constant Ink2DenseMmaArgs& a, + device bfloat* Y, uint2 tg, uint g, uint lane, threadgroup float (&part)[4][2][2][8][8]) { + const uint r0 = tg.y * 16u, n0 = tg.x * 16u; + const uint qid = lane >> 2u; + const uint fm = (qid & 4u) + ((lane >> 1u) & 3u); + const uint fn = (qid & 2u) * 2u + (lane & 1u) * 2u; + // The first four columns of an octet go through one MMA and the last four through another. + const bool low = fn < 4u; + // A matvec lane adds, per 256 columns, its first four products to its next four, then to its running sum. + ink2_dense_frag acc[ROWS][COLS][8]; + _Pragma("clang loop unroll(full)") for (uint i = 0u; i < ROWS; ++i) + _Pragma("clang loop unroll(full)") for (uint j = 0u; j < COLS; ++j) + _Pragma("clang loop unroll(full)") for (uint c = 0u; c < 8u; ++c) acc[i][j][c] = ink2_dense_frag(0.0f); + const device bfloat* x = X + ulong(r0) * a.k + 64u * g; + const device bfloat* w = W + ulong(n0) * a.k + 64u * g; + for (uint col = 0u; col < a.k; col += 256u) { + _Pragma("clang loop unroll(full)") for (uint c = 0u; c < 8u; ++c) { + simdgroup_matrix fa[ROWS][2], fb[COLS]; + _Pragma("clang loop unroll(full)") for (uint i = 0u; i < ROWS; ++i) { + simdgroup_matrix v; + simdgroup_load(v, x + ulong(8u * i) * a.k + col + 8u * c, a.k); + const bfloat z = bfloat(0.0f); + fa[i][0].thread_elements()[0] = low ? v.thread_elements()[0] : z; + fa[i][0].thread_elements()[1] = low ? v.thread_elements()[1] : z; + fa[i][1].thread_elements()[0] = low ? z : v.thread_elements()[0]; + fa[i][1].thread_elements()[1] = low ? z : v.thread_elements()[1]; + } + _Pragma("clang loop unroll(full)") for (uint j = 0u; j < COLS; ++j) + simdgroup_load(fb[j], w + ulong(8u * j) * a.k + col + 8u * c, a.k, ulong2(0, 0), true); + _Pragma("clang loop unroll(full)") for (uint i = 0u; i < ROWS; ++i) + _Pragma("clang loop unroll(full)") for (uint j = 0u; j < COLS; ++j) { + ink2_dense_frag d0(0.0f), d1(0.0f); + simdgroup_multiply_accumulate(d0, fa[i][0], fb[j], d0); + simdgroup_multiply_accumulate(d1, fa[i][1], fb[j], d1); + acc[i][j][c].thread_elements()[0] += d0.thread_elements()[0] + d1.thread_elements()[0]; + acc[i][j][c].thread_elements()[1] += d0.thread_elements()[1] + d1.thread_elements()[1]; + } + } + } + // The eight chains of the group add adjacent first, as simd_sum's first three levels do. + _Pragma("clang loop unroll(full)") for (uint i = 0u; i < ROWS; ++i) + _Pragma("clang loop unroll(full)") for (uint j = 0u; j < COLS; ++j) + _Pragma("clang loop unroll(full)") for (uint e = 0u; e < 2u; ++e) { + float v[8]; + _Pragma("clang loop unroll(full)") for (uint c = 0u; c < 8u; ++c) v[c] = acc[i][j][c].thread_elements()[e]; + _Pragma("clang loop unroll(full)") for (uint s = 1u; s < 8u; s <<= 1u) + _Pragma("clang loop unroll(full)") for (uint c = 0u; c < 8u; c += 2u * s) v[c] = v[c] + v[c + s]; + part[g][i][j][fm][fn + e] = v[0]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // Then the four groups: (0 + 1) + (2 + 3). + for (uint o = g * 32u + lane; o < ROWS * COLS * 64u; o += 128u) { + const uint i = o >> (COLS == 2u ? 7u : 6u), j = COLS == 2u ? (o >> 6u) & 1u : 0u, m = (o >> 3u) & 7u, n = o & 7u; + const float t = (part[0][i][j][m][n] + part[1][i][j][m][n]) + (part[2][i][j][m][n] + part[3][i][j][m][n]); + const uint row = r0 + i * 8u + m, col = n0 + j * 8u + n; + if (row < a.rows) Y[ulong(row) * a.ldy + col] = bfloat(t); + } +} + +// Threadgroup (x, y): outputs 16x .. 16x + 15 of rows 16y .. 16y + 15; n is a multiple of 8, k of 256. +[[kernel, max_total_threads_per_threadgroup(128)]] void tf_ink2_dense_mma( + const device bfloat* X [[buffer(0)]], const device bfloat* W [[buffer(1)]], + constant Ink2DenseMmaArgs& a [[buffer(2)]], device bfloat* Y [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint g [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4][2][2][8][8]; + const bool two_rows = a.rows - tg.y * 16u > 8u, two_cols = a.n - tg.x * 16u > 8u; + if (two_rows) { + if (two_cols) ink2_dense_mma<2u, 2u>(X, W, a, Y, tg, g, lane, part); + else ink2_dense_mma<2u, 1u>(X, W, a, Y, tg, g, lane, part); + } else { + if (two_cols) ink2_dense_mma<1u, 2u>(X, W, a, Y, tg, g, lane, part); + else ink2_dense_mma<1u, 1u>(X, W, a, Y, tg, g, lane, part); + } +} diff --git a/zig/kernels/metal/inkling2/dense_sources.zig b/zig/kernels/metal/inkling2/dense_sources.zig new file mode 100644 index 00000000000..61c9884c86d --- /dev/null +++ b/zig/kernels/metal/inkling2/dense_sources.zig @@ -0,0 +1,2 @@ +//! Inkling 2 Mini's prompt projections on simdgroup matrices, for GPUs without tensor units. +pub const dense_mma = @embedFile("dense_mma.metal"); diff --git a/zig/kernels/metal/inkling2/experts.metal b/zig/kernels/metal/inkling2/experts.metal index b1ba70059cf..46cb111f91f 100644 --- a/zig/kernels/metal/inkling2/experts.metal +++ b/zig/kernels/metal/inkling2/experts.metal @@ -37,20 +37,55 @@ inline float ink2_mx_weight(uchar value, uchar scale) { return float(bfloat(w)); } +// Four packed bytes as one word, at any byte offset. +inline uint ink2_word(device const uchar* p) { + return as_type(uchar4(*(device const packed_uchar4*)p)); +} + +// E2M1 times two is 0, 1, 2, 3, 4, 6, 8 or 12: one nibble of this word a code. +inline float ink2_e2m1_twice(uint code) { + const float v = float((0xC8643210u >> (4u * (code & 7u))) & 15u); + return (code & 8u) ? -v : v; +} + +// ink2_e4m3 with its finite values built from their bits. +inline float ink2_e4m3_bits(uint code) { + const uint exp = (code >> 3u) & 15u, mant = code & 7u; + const float v = exp ? as_type(((exp + 120u) << 23u) | (mant << 20u)) : float(mant) * (1.0f / 512.0f); + const float s = (code & 0x80u) ? -v : v; + return (exp == 15u && mant == 7u) ? NAN : s; +} + +// One simdgroup a dot: lane l sums blocks l, l + 32, ... in column order, then the 32 lanes are summed. inline float ink2_dot_nv(device const uchar* w, device const uchar* scales, - device const bfloat* x, float phi, uint k) { + device const bfloat* x, float phi, uint k, uint lane) { 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]); - return sum; + for (uint b = lane; b < k / 16u; b += 32u) { + // ink2_nv_weight's inner product, exact in fp32 either way: (2 * e2m1) * (e4m3 / 2). + const float half_scale = 0.5f * ink2_e4m3(scales[b]); + const uint lo = ink2_word(w + 8u * b), hi = ink2_word(w + 8u * b + 4u); + for (uint j = 0; j < 16u; ++j) { + const uint code = ((j < 8u ? lo : hi) >> (4u * (j & 7u))) & 15u; + const float weight = float(bfloat(ink2_e2m1_twice(code) * half_scale * phi)); + sum += weight * float(x[16u * b + j]); + } + } + return simd_sum(sum); } +// As ink2_dot_nv over 32-column MXFP8 blocks. inline float ink2_dot_mx(device const uchar* w, device const uchar* scales, - device const bfloat* x, uint k) { + device const bfloat* x, uint k, uint lane) { float sum = 0.0f; - for (uint c = 0; c < k; ++c) - sum += ink2_mx_weight(w[c], scales[c / 32u]) * float(x[c]); - return sum; + for (uint b = lane; b < k / 32u; b += 32u) { + const int shift = int(scales[b]) - 127; + for (uint j = 0; j < 32u; ++j) { + const uint c = 32u * b + j; + const float weight = float(bfloat(ldexp(ink2_e4m3_bits(w[c]), shift))); + sum += weight * float(x[c]); + } + } + return simd_sum(sum); } inline float ink2_cap(float x, float cap) { @@ -64,70 +99,280 @@ inline bfloat ink2_act(float gate_dot, float up_dot) { return bfloat(left * ink2_cap(up, 25.0f)); } -[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_gu( +// The four products: threadgroup (x, y) is outputs 8x to 8x + 7 of route pair y, one simdgroup an output. +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_gu( device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], device const float* denominator [[buffer(4)]], device const int* ids [[buffer(5)]], device bfloat* Y [[buffer(6)]], constant Ink2MatrixArgs& a [[buffer(7)]], - uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, group = tg.y; + if (n >= a.n) return; const uint token = group / a.topk, expert = uint(ids[group]); const ulong expert_w = ulong(expert) * 2u * a.n * (a.k / 2u); const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 16u); const float phi = ink2_phi(amax, denominator, expert); - for (uint n = lane; n < a.n; n += 32u) { - const uint gr = 2u * n, ur = gr + 1u; - const float g = ink2_dot_nv(W + expert_w + ulong(gr) * (a.k / 2u), - S + expert_s + ulong(gr) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k); - const float u = ink2_dot_nv(W + expert_w + ulong(ur) * (a.k / 2u), - S + expert_s + ulong(ur) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k); - Y[group * a.n + n] = ink2_act(g, u); - } + const uint gr = 2u * n, ur = gr + 1u; + const float g = ink2_dot_nv(W + expert_w + ulong(gr) * (a.k / 2u), + S + expert_s + ulong(gr) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k, lane); + const float u = ink2_dot_nv(W + expert_w + ulong(ur) * (a.k / 2u), + S + expert_s + ulong(ur) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k, lane); + if (lane == 0u) Y[ulong(group) * a.n + n] = ink2_act(g, u); } -[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_gu( +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_gu( device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], device const uchar* S [[buffer(2)]], device const int* ids [[buffer(3)]], device bfloat* Y [[buffer(4)]], constant Ink2MatrixArgs& a [[buffer(5)]], - uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, group = tg.y; + if (n >= a.n) return; const uint token = group / a.topk, expert = uint(ids[group]); const ulong expert_w = ulong(expert) * 2u * a.n * a.k; const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 32u); - for (uint n = lane; n < a.n; n += 32u) { - const uint gr = 2u * n, ur = gr + 1u; - const float g = ink2_dot_mx(W + expert_w + ulong(gr) * a.k, - S + expert_s + ulong(gr) * (a.k / 32u), X + ulong(token) * a.k, a.k); - const float u = ink2_dot_mx(W + expert_w + ulong(ur) * a.k, - S + expert_s + ulong(ur) * (a.k / 32u), X + ulong(token) * a.k, a.k); - Y[group * a.n + n] = ink2_act(g, u); - } + const uint gr = 2u * n, ur = gr + 1u; + const float g = ink2_dot_mx(W + expert_w + ulong(gr) * a.k, + S + expert_s + ulong(gr) * (a.k / 32u), X + ulong(token) * a.k, a.k, lane); + const float u = ink2_dot_mx(W + expert_w + ulong(ur) * a.k, + S + expert_s + ulong(ur) * (a.k / 32u), X + ulong(token) * a.k, a.k, lane); + if (lane == 0u) Y[ulong(group) * a.n + n] = ink2_act(g, u); } -[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_down( +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_down( device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], device const float* denominator [[buffer(4)]], device const int* ids [[buffer(5)]], device bfloat* Y [[buffer(6)]], constant Ink2MatrixArgs& a [[buffer(7)]], - uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, group = tg.y; + if (n >= a.n) return; const uint expert = uint(ids[group]); const ulong expert_w = ulong(expert) * a.n * (a.k / 2u); const ulong expert_s = ulong(expert) * a.n * (a.k / 16u); const float phi = ink2_phi(amax, denominator, expert); - for (uint n = lane; n < a.n; n += 32u) - Y[group * a.n + n] = bfloat(ink2_dot_nv(W + expert_w + ulong(n) * (a.k / 2u), - S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, phi, a.k)); + const float d = ink2_dot_nv(W + expert_w + ulong(n) * (a.k / 2u), + S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, phi, a.k, lane); + if (lane == 0u) Y[ulong(group) * a.n + n] = bfloat(d); } -[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_down( +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_down( device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], device const uchar* S [[buffer(2)]], device const int* ids [[buffer(3)]], device bfloat* Y [[buffer(4)]], constant Ink2MatrixArgs& a [[buffer(5)]], - uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, group = tg.y; + if (n >= a.n) return; const uint expert = uint(ids[group]); const ulong expert_w = ulong(expert) * a.n * a.k; const ulong expert_s = ulong(expert) * a.n * (a.k / 32u); - for (uint n = lane; n < a.n; n += 32u) - Y[group * a.n + n] = bfloat(ink2_dot_mx(W + expert_w + ulong(n) * a.k, - S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k)); + const float d = ink2_dot_mx(W + expert_w + ulong(n) * a.k, + S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k, lane); + if (lane == 0u) Y[ulong(group) * a.n + n] = bfloat(d); +} + +// ---- Grouped by expert: the same sums a row as the kernels above, with each weight block decoded once a pass. ---- +struct Ink2GroupArgs { uint pairs, experts, cap; }; +struct Ink2GroupedArgs { uint k, n, topk, cap; }; +#define INK2_PASS 4u + +// Expert e's route pairs in pair order: counts[e], then members[e][0 .. counts[e]). +kernel void tf_ink2_group( + device const int* ids [[buffer(0)]], device uint* counts [[buffer(1)]], + device uint* members [[buffer(2)]], constant Ink2GroupArgs& a [[buffer(3)]], + uint e [[thread_position_in_grid]]) { + if (e >= a.experts) return; + uint n = 0u; + for (uint p = 0u; p < a.pairs; ++p) + if (uint(ids[p]) == e) { + if (n < a.cap) members[e * a.cap + n] = p; + ++n; + } + counts[e] = min(n, a.cap); +} + +// Block b of a packed NVFP4 row as its 16 BF16 weights, each as ink2_dot_nv decodes it. +inline void ink2_nv_block(device const uchar* w, device const uchar* scales, float phi, uint b, thread float* out) { + const float half_scale = 0.5f * ink2_e4m3(scales[b]); + const uint lo = ink2_word(w + 8u * b), hi = ink2_word(w + 8u * b + 4u); + for (uint j = 0; j < 16u; ++j) { + const uint code = ((j < 8u ? lo : hi) >> (4u * (j & 7u))) & 15u; + out[j] = float(bfloat(ink2_e2m1_twice(code) * half_scale * phi)); + } +} + +// Block b of an MXFP8 row as its 32 BF16 weights, each as ink2_dot_mx decodes it. +inline void ink2_mx_block(device const uchar* w, device const uchar* scales, uint b, thread float* out) { + const int shift = int(scales[b]) - 127; + for (uint j = 0; j < 32u; ++j) out[j] = float(bfloat(ldexp(ink2_e4m3_bits(w[32u * b + j]), shift))); +} + +// Threadgroup (x, e): outputs 8x to 8x + 7 of expert e for each of its route pairs, four pairs a pass. +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_gu_grouped( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2GroupedArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, expert = tg.y; + if (n >= a.n) return; + const uint count = counts[expert]; + if (count == 0u) return; + const ulong expert_w = ulong(expert) * 2u * a.n * (a.k / 2u); + const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 16u); + const float phi = precise::divide(float(bfloat(amax[expert])), float(bfloat(denominator[0]))); + device const uchar* gate_w = W + expert_w + ulong(2u * n) * (a.k / 2u); + device const uchar* gate_s = S + expert_s + ulong(2u * n) * (a.k / 16u); + device const uchar* up_w = gate_w + (a.k / 2u); + device const uchar* up_s = gate_s + (a.k / 16u); + for (uint first = 0u; first < count; first += INK2_PASS) { + uint pair[INK2_PASS]; + device const bfloat* x[INK2_PASS]; + float g[INK2_PASS], u[INK2_PASS]; + for (uint j = 0u; j < INK2_PASS; ++j) { + pair[j] = members[expert * a.cap + min(first + j, count - 1u)]; + x[j] = X + ulong(pair[j] / a.topk) * a.k; + g[j] = 0.0f; + u[j] = 0.0f; + } + for (uint b = lane; b < a.k / 16u; b += 32u) { + float gate[16], up[16]; + ink2_nv_block(gate_w, gate_s, phi, b, gate); + ink2_nv_block(up_w, up_s, phi, b, up); + for (uint j = 0u; j < INK2_PASS; ++j) + for (uint i = 0u; i < 16u; ++i) { + const float v = float(x[j][16u * b + i]); + g[j] += gate[i] * v; + u[j] += up[i] * v; + } + } + for (uint j = 0u; j < INK2_PASS; ++j) { + const float gs = simd_sum(g[j]), us = simd_sum(u[j]); + if (lane == 0u && first + j < count) Y[ulong(pair[j]) * a.n + n] = ink2_act(gs, us); + } + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_gu_grouped( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2GroupedArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, expert = tg.y; + if (n >= a.n) return; + const uint count = counts[expert]; + if (count == 0u) return; + const ulong expert_w = ulong(expert) * 2u * a.n * a.k; + const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 32u); + device const uchar* gate_w = W + expert_w + ulong(2u * n) * a.k; + device const uchar* gate_s = S + expert_s + ulong(2u * n) * (a.k / 32u); + device const uchar* up_w = gate_w + a.k; + device const uchar* up_s = gate_s + (a.k / 32u); + for (uint first = 0u; first < count; first += INK2_PASS) { + uint pair[INK2_PASS]; + device const bfloat* x[INK2_PASS]; + float g[INK2_PASS], u[INK2_PASS]; + for (uint j = 0u; j < INK2_PASS; ++j) { + pair[j] = members[expert * a.cap + min(first + j, count - 1u)]; + x[j] = X + ulong(pair[j] / a.topk) * a.k; + g[j] = 0.0f; + u[j] = 0.0f; + } + for (uint b = lane; b < a.k / 32u; b += 32u) { + float gate[32], up[32]; + ink2_mx_block(gate_w, gate_s, b, gate); + ink2_mx_block(up_w, up_s, b, up); + for (uint j = 0u; j < INK2_PASS; ++j) + for (uint i = 0u; i < 32u; ++i) { + const float v = float(x[j][32u * b + i]); + g[j] += gate[i] * v; + u[j] += up[i] * v; + } + } + for (uint j = 0u; j < INK2_PASS; ++j) { + const float gs = simd_sum(g[j]), us = simd_sum(u[j]); + if (lane == 0u && first + j < count) Y[ulong(pair[j]) * a.n + n] = ink2_act(gs, us); + } + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_down_grouped( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2GroupedArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, expert = tg.y; + if (n >= a.n) return; + const uint count = counts[expert]; + if (count == 0u) return; + const float phi = precise::divide(float(bfloat(amax[expert])), float(bfloat(denominator[0]))); + device const uchar* row_w = W + ulong(expert) * a.n * (a.k / 2u) + ulong(n) * (a.k / 2u); + device const uchar* row_s = S + ulong(expert) * a.n * (a.k / 16u) + ulong(n) * (a.k / 16u); + for (uint first = 0u; first < count; first += INK2_PASS) { + uint pair[INK2_PASS]; + device const bfloat* x[INK2_PASS]; + float d[INK2_PASS]; + for (uint j = 0u; j < INK2_PASS; ++j) { + pair[j] = members[expert * a.cap + min(first + j, count - 1u)]; + x[j] = X + ulong(pair[j]) * a.k; + d[j] = 0.0f; + } + for (uint b = lane; b < a.k / 16u; b += 32u) { + float weight[16]; + ink2_nv_block(row_w, row_s, phi, b, weight); + for (uint j = 0u; j < INK2_PASS; ++j) + for (uint i = 0u; i < 16u; ++i) d[j] += weight[i] * float(x[j][16u * b + i]); + } + for (uint j = 0u; j < INK2_PASS; ++j) { + const float ds = simd_sum(d[j]); + if (lane == 0u && first + j < count) Y[ulong(pair[j]) * a.n + n] = bfloat(ds); + } + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_down_grouped( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2GroupedArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, expert = tg.y; + if (n >= a.n) return; + const uint count = counts[expert]; + if (count == 0u) return; + device const uchar* row_w = W + ulong(expert) * a.n * a.k + ulong(n) * a.k; + device const uchar* row_s = S + ulong(expert) * a.n * (a.k / 32u) + ulong(n) * (a.k / 32u); + for (uint first = 0u; first < count; first += INK2_PASS) { + uint pair[INK2_PASS]; + device const bfloat* x[INK2_PASS]; + float d[INK2_PASS]; + for (uint j = 0u; j < INK2_PASS; ++j) { + pair[j] = members[expert * a.cap + min(first + j, count - 1u)]; + x[j] = X + ulong(pair[j]) * a.k; + d[j] = 0.0f; + } + for (uint b = lane; b < a.k / 32u; b += 32u) { + float weight[32]; + ink2_mx_block(row_w, row_s, b, weight); + for (uint j = 0u; j < INK2_PASS; ++j) + for (uint i = 0u; i < 32u; ++i) d[j] += weight[i] * float(x[j][32u * b + i]); + } + for (uint j = 0u; j < INK2_PASS; ++j) { + const float ds = simd_sum(d[j]); + if (lane == 0u && first + j < count) Y[ulong(pair[j]) * a.n + n] = bfloat(ds); + } + } } // Weight decode helpers unpack checkpoint bytes and never quantize an activation. @@ -154,18 +399,29 @@ inline bfloat ink2_act(float gate_dot, float up_dot) { Y[at] = bfloat(ink2_mx_weight(W[at], S[row * (a.k / 32u) + col / 32u])); } -[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_combine( +// Threadgroup (x, y) is outputs 256x to 256x + 255 of token y, a thread an output; the first topk order the routes. +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_combine( device const bfloat* down [[buffer(0)]], device const int* ids [[buffer(1)]], device const float* weights [[buffer(2)]], device bfloat* Y [[buffer(3)]], - constant Ink2MatrixArgs& a [[buffer(4)]], uint group [[threadgroup_position_in_grid]], - uint lane [[thread_index_in_threadgroup]]) { - // Outer expert order, not route-slot order, fixes the reference's accumulation order. - for (uint n = lane; n < a.n; n += 32u) { - float sum = 0.0f; - for (uint expert = 0; expert < a.experts; ++expert) - for (uint slot = 0; slot < a.topk; ++slot) - if (uint(ids[group * a.topk + slot]) == expert) - sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]); - Y[group * a.n + n] = bfloat(sum); + constant Ink2MatrixArgs& a [[buffer(4)]], uint2 tg [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]]) { + const uint n = tg.x * 256u + t, group = tg.y; + const uint base = group * a.topk; + threadgroup uint order[32]; + if (a.topk > 32u) return; + if (t < a.topk) { + // A route's rank among the token's routes by expert, an equal expert by slot: the reference's accumulation order. + const int id = ids[base + t]; + uint rank = 0; + for (uint o = 0; o < a.topk; ++o) rank += (ids[base + o] < id || (ids[base + o] == id && o < t)) ? 1u : 0u; + order[rank] = t; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (n >= a.n) return; + float sum = 0.0f; + for (uint r = 0; r < a.topk; ++r) { + const uint slot = order[r]; + if (uint(ids[base + slot]) < a.experts) sum += weights[base + slot] * float(down[ulong(base + slot) * a.n + n]); } + Y[ulong(group) * a.n + n] = bfloat(sum); } diff --git a/zig/kernels/metal/inkling2/experts_mma.metal b/zig/kernels/metal/inkling2/experts_mma.metal new file mode 100644 index 00000000000..02b3e2b89e4 --- /dev/null +++ b/zig/kernels/metal/inkling2/experts_mma.metal @@ -0,0 +1,276 @@ +// Routed experts on simdgroup matrices for GPUs without tensor units: the sums of the grouped kernels, bit for bit. +#define INK2_MMA_THREADS 256u +// A threadgroup's tile: 64 weight rows (one simdgroup 8) by a band of 32 of an expert's pairs. +#define INK2_MMA_ROWS 64u +#define INK2_MMA_PAIRS 32u +// A stage puts STEPS K octets of both through threadgroup memory: two blocks of a row. +#define INK2_MMA_STEPS(nv) ((nv) ? 4u : 8u) +// The 32 lane chains run in NP passes of NC adjacent chains; stage s of a round takes blocks 2s and 2s + 1 of them. +#define INK2_MMA_NP 8u +#define INK2_MMA_NC 4u +#define INK2_MMA_PT (INK2_MMA_PAIRS / 8u) +#define INK2_MMA_WORDS(nv) (2u * INK2_MMA_STEPS(nv) * INK2_MMA_ROWS * 4u) +#define INK2_MMA_XWORDS(nv) (2u * INK2_MMA_STEPS(nv) * INK2_MMA_PAIRS * 4u) +// Decode units (two K octets of one row) and staged activation octets of a stage, per thread. +#define INK2_MMA_UNITS(nv) (INK2_MMA_ROWS * (INK2_MMA_STEPS(nv) / 2u)) +#define INK2_MMA_DU(nv) ((INK2_MMA_UNITS(nv) + INK2_MMA_THREADS - 1u) / INK2_MMA_THREADS) +#define INK2_MMA_XU(nv) ((INK2_MMA_PAIRS * INK2_MMA_STEPS(nv) + INK2_MMA_THREADS - 1u) / INK2_MMA_THREADS) + +using ink2_frag = simdgroup_matrix; + +// E4M3FN as FP16 bits (same layout, bias 15) times 2^8; the sign sits in bit 15, and 0x7f / 0xff stay NaN. +inline float ink2_mma_e4m3(uint b) { + const float v = float(as_type(ushort(((b & 0x7fu) << 7) | ((b & 0x80u) << 8)))) * 256.0f; + return (b & 0x7fu) == 0x7fu ? as_type(((b & 0x80u) << 24) | 0x7fc00000u) : v; +} + +// Two E2M1 codes of one byte as FP16 bit pairs; the product's 2^14 is carried by the NVFP4 block scale. +inline float2 ink2_mma_e2m1_pair(uint code) { + return float2(as_type(((code * 0x00200200u) & 0x0e000e00u) | ((code * 0x01001000u) & 0x80008000u))); +} + +// What one thread decodes of a unit: a scale code and sixteen packed weights (NVFP4 one block, MXFP8 half of one). +struct Ink2MmaRaw { + uint code; + uint4 q; +}; + +// Unit index `i` of a stage: eight consecutive lanes take eight rows of one unit. +template +inline uint ink2_mma_row(uint i) { + return (i & 7u) | ((i / (8u * (INK2_MMA_STEPS(NV) / 2u))) << 3u); +} +template +inline uint ink2_mma_unit(uint i) { + return (i >> 3u) % (INK2_MMA_STEPS(NV) / 2u); +} + +// Block `bi` (0 or 1) of stage `stage` for the chains of `pass`: chain 4 * pass + m takes blocks m, m + 32, ... +inline uint ink2_mma_block(uint pass, uint stage, uint bi) { + return 32u * (stage >> 1u) + 4u * pass + 2u * (stage & 1u) + bi; +} + +template +inline Ink2MmaRaw ink2_mma_load(const device uchar* wp, const device uchar* sp, uint pitch, uint blocks, uint pass, + uint stage, uint i) { + Ink2MmaRaw raw = {0u, uint4(0u)}; + if (i >= INK2_MMA_UNITS(NV)) return raw; + const uint row = ink2_mma_row(i), u = ink2_mma_unit(i); + const uint block = ink2_mma_block(pass, stage, NV ? u : (u >> 1u)); + if (block >= blocks) return raw; + raw.code = sp[row * blocks + block]; + if (NV) { + const device uint* p = (const device uint*)(wp + row * pitch + block * 8u); + raw.q = uint4(p[0], p[1], 0u, 0u); + } else { + raw.q = *(const device uint4*)(wp + row * pitch + block * 32u + (u & 1u) * 16u); + } + return raw; +} + +// One K octet (eight weights, four BF16 pairs) per uint4, each weight rounded as ink2_nv_block and ink2_mx_block do. +template +inline void ink2_mma_decode(Ink2MmaRaw raw, float phi, uint i, threadgroup uint* tgw) { + if (i >= INK2_MMA_UNITS(NV)) return; + const uint row = ink2_mma_row(i), u = ink2_mma_unit(i); + threadgroup uint* dst = tgw + (2u * u * INK2_MMA_ROWS + row) * 4u; + uint words[8]; + if (NV) { + const float sc = ink2_mma_e4m3(raw.code) * 16384.0f; + for (uint w = 0u; w < 2u; ++w) { + for (uint b = 0u; b < 4u; ++b) { + const float2 e = ink2_mma_e2m1_pair((raw.q[w] >> (8u * b)) & 255u); + const uint lo = as_type(bfloat((e.x * sc) * phi)); + const uint hi = as_type(bfloat((e.y * sc) * phi)); + words[4u * w + b] = lo | (hi << 16u); + } + } + } else { + // 2^(s - 127) as the grouped kernel's ldexp gives it; the code 0 scale halves 2^-126. + const float sc = as_type(max(raw.code, 1u) << 23u), mant = select(1.0f, 0.5f, raw.code == 0u); + for (uint w = 0u; w < 4u; ++w) { + const uint word = raw.q[w]; + const uint v0 = as_type(bfloat((ink2_mma_e4m3(word & 255u) * mant) * sc)); + const uint v1 = as_type(bfloat((ink2_mma_e4m3((word >> 8u) & 255u) * mant) * sc)); + const uint v2 = as_type(bfloat((ink2_mma_e4m3((word >> 16u) & 255u) * mant) * sc)); + const uint v3 = as_type(bfloat((ink2_mma_e4m3(word >> 24u) * mant) * sc)); + words[2u * w] = v0 | (v1 << 16u); + words[2u * w + 1u] = v2 | (v3 << 16u); + } + } + *(threadgroup uint4*)dst = uint4(words[0], words[1], words[2], words[3]); + *(threadgroup uint4*)(dst + INK2_MMA_ROWS * 4u) = uint4(words[4], words[5], words[6], words[7]); +} + +// Activations stay row-major per pair, [step][pair tile][pair][k]; the loads run a stage ahead of the stores. +template +inline void ink2_mma_load_x(const device uint4* xrow, bool live, uint pass, uint stage, uint blocks, uint t, + thread uint4 (&q)[INK2_MMA_XU(NV)]) { + constexpr uint gpb = NV ? 2u : 4u; + _Pragma("clang loop unroll(full)") for (uint h = 0u; h < INK2_MMA_XU(NV); ++h) { + const uint ss = t / INK2_MMA_PAIRS + (INK2_MMA_THREADS / INK2_MMA_PAIRS) * h; + const uint block = ink2_mma_block(pass, stage, ss / gpb); + q[h] = live && ss < INK2_MMA_STEPS(NV) && block < blocks ? xrow[block * gpb + ss % gpb] : uint4(0u); + } +} + +template +inline void ink2_mma_store_x(const thread uint4 (&q)[INK2_MMA_XU(NV)], uint t, threadgroup uint* tgx) { + const uint pair = t % INK2_MMA_PAIRS; + _Pragma("clang loop unroll(full)") for (uint h = 0u; h < INK2_MMA_XU(NV); ++h) { + const uint ss = t / INK2_MMA_PAIRS + (INK2_MMA_THREADS / INK2_MMA_PAIRS) * h; + if (ss < INK2_MMA_STEPS(NV)) + *(threadgroup uint4*)(tgx + (((ss * (INK2_MMA_PAIRS / 8u) + (pair >> 3u)) * 8u + (pair & 7u)) * 4u)) = q[h]; + } +} + +// One staged stage on the MMAs: each block's K octets add into its lane chain's fragment, in order. +template +inline void ink2_mma_stage(const threadgroup uint* aw, const threadgroup uint* bx, + thread ink2_frag (&acc)[INK2_MMA_PT][INK2_MMA_NC], uint si, uint ot, uint blocks, + uint pass, uint stage) { + constexpr uint bsteps = NV ? 2u : 4u; + _Pragma("clang loop unroll(full)") for (uint i = 0u; i < 2u; ++i) { + if (CHECK && ink2_mma_block(pass, stage, i) >= blocks) break; + _Pragma("clang loop unroll(full)") for (uint s = 0u; s < bsteps; ++s) { + const uint ss = i * bsteps + s; + simdgroup_matrix fa, fb; + simdgroup_load(fa, (const threadgroup bfloat*)(aw + (ss * INK2_MMA_ROWS + ot * 8u) * 4u), 8); + _Pragma("clang loop unroll(full)") for (uint j = 0u; j < PT; ++j) { + simdgroup_load(fb, (const threadgroup bfloat*)(bx + (ss * (INK2_MMA_PAIRS / 8u) + j) * 32u), 8, ulong2(0, 0), + true); + simdgroup_multiply_accumulate(acc[j][si * 2u + i], fa, fb, acc[j][si * 2u + i]); + } + } + } +} + +// The pair tiles a band holds, 1 to 4, are fixed for it: skip the dead ones with a uniform switch. +template +inline void ink2_mma_run(uint active, const threadgroup uint* aw, const threadgroup uint* bx, + thread ink2_frag (&acc)[INK2_MMA_PT][INK2_MMA_NC], uint si, uint ot, uint blocks, uint pass, + uint stage) { + switch (active) { + case 1u: ink2_mma_stage(aw, bx, acc, si, ot, blocks, pass, stage); break; + case 2u: ink2_mma_stage(aw, bx, acc, si, ot, blocks, pass, stage); break; + case 3u: ink2_mma_stage(aw, bx, acc, si, ot, blocks, pass, stage); break; + default: ink2_mma_stage(aw, bx, acc, si, ot, blocks, pass, stage); break; + } +} + +// Threadgroup (x, e): rows 64x .. 64x + 63 of expert e for each band of 32 of its pairs; GU is X by row, else by pair. +template +inline void ink2_mma(device const bfloat* X, device const uchar* W, device const uchar* S, float phi, + device const uint* counts, device const uint* members, device bfloat* Y, + constant Ink2GroupedArgs& a, uint2 tg, uint t, threadgroup uint* tgw, threadgroup uint* tgx) { + // A BF16 product is exact in FP32 and an MMA adds its eight into C in order: a lane's chain is one fragment. + const uint expert = tg.y, count = counts[expert]; + if (count == 0u) return; + constexpr uint cols = GU ? INK2_MMA_ROWS / 2u : INK2_MMA_ROWS, per_round = INK2_MMA_NC / 2u; + const uint lane = t & 31u, ot = t >> 5u; + const uint rows_w = GU ? 2u * a.n : a.n, pitch = NV ? a.k / 2u : a.k, blocks = a.k / (NV ? 16u : 32u); + const ulong w_row = ulong(expert) * rows_w + ulong(tg.x) * INK2_MMA_ROWS; + device const uchar* wp = W + w_row * pitch; + device const uchar* sp = S + w_row * blocks; + const uint xp = t % INK2_MMA_PAIRS; + const uint qid = lane >> 2u; + const uint fm = (qid & 4u) + ((lane >> 1u) & 3u); + const uint fn = (qid & 2u) * 2u + (lane & 1u) * 2u; + uint buf = 0u; + for (uint band = 0u; band < count; band += INK2_MMA_PAIRS) { + const uint live = min(INK2_MMA_PAIRS, count - band); + const uint pair = members[expert * a.cap + band + min(xp, live - 1u)]; + const device uint4* xrow = (const device uint4*)(X + ulong(GU ? pair / a.topk : pair) * a.k); + const bool xlive = xp < live; + const uint active = min(INK2_MMA_PT, (live + 7u) / 8u); + float2 sums[INK2_MMA_PT][INK2_MMA_NP]; + for (uint pass = 0u; pass < INK2_MMA_NP; ++pass) { + ink2_frag acc[INK2_MMA_PT][INK2_MMA_NC]; + _Pragma("clang loop unroll(full)") for (uint j = 0u; j < INK2_MMA_PT; ++j) + _Pragma("clang loop unroll(full)") for (uint m = 0u; m < INK2_MMA_NC; ++m) acc[j][m] = ink2_frag(0.0f); + // Chain 4 * pass + m has a block in round r while 32 r + 4 pass + m < blocks. + const uint rounds = blocks > 4u * pass ? (blocks - 4u * pass + 31u) / 32u : 0u; + Ink2MmaRaw raw[INK2_MMA_DU(NV)]; + _Pragma("clang loop unroll(full)") for (uint h = 0u; h < INK2_MMA_DU(NV); ++h) + raw[h] = ink2_mma_load(wp, sp, pitch, blocks, pass, 0u, t + INK2_MMA_THREADS * h); + uint4 xq[INK2_MMA_XU(NV)]; + ink2_mma_load_x(xrow, xlive, pass, 0u, blocks, t, xq); + for (uint round = 0u; round < rounds; ++round) { + _Pragma("clang loop unroll(full)") for (uint si = 0u; si < per_round; ++si) { + const uint stage = round * per_round + si; + _Pragma("clang loop unroll(full)") for (uint h = 0u; h < INK2_MMA_DU(NV); ++h) + ink2_mma_decode(raw[h], phi, t + INK2_MMA_THREADS * h, tgw + buf * (INK2_MMA_STEPS(NV) * INK2_MMA_ROWS * 4u)); + ink2_mma_store_x(xq, t, tgx + buf * (INK2_MMA_STEPS(NV) * INK2_MMA_PAIRS * 4u)); + threadgroup_barrier(mem_flags::mem_threadgroup); + _Pragma("clang loop unroll(full)") for (uint h = 0u; h < INK2_MMA_DU(NV); ++h) + raw[h] = ink2_mma_load(wp, sp, pitch, blocks, pass, stage + 1u, t + INK2_MMA_THREADS * h); + ink2_mma_load_x(xrow, xlive, pass, stage + 1u, blocks, t, xq); + const threadgroup uint* aw = tgw + buf * (INK2_MMA_STEPS(NV) * INK2_MMA_ROWS * 4u); + const threadgroup uint* bx = tgx + buf * (INK2_MMA_STEPS(NV) * INK2_MMA_PAIRS * 4u); + buf ^= 1u; + // Only the last round of a pass can run past the blocks of K. + if (ink2_mma_block(pass, stage, 1u) < blocks) + ink2_mma_run(active, aw, bx, acc, si, ot, blocks, pass, stage); + else + ink2_mma_run(active, aw, bx, acc, si, ot, blocks, pass, stage); + } + } + // The pass's four chains add as simd_sum's first two levels do: (0 + 1) + (2 + 3). + _Pragma("clang loop unroll(full)") for (uint j = 0u; j < INK2_MMA_PT; ++j) { + const float2 c0 = float2(acc[j][0].thread_elements()[0], acc[j][0].thread_elements()[1]); + const float2 c1 = float2(acc[j][1].thread_elements()[0], acc[j][1].thread_elements()[1]); + const float2 c2 = float2(acc[j][2].thread_elements()[0], acc[j][2].thread_elements()[1]); + const float2 c3 = float2(acc[j][3].thread_elements()[0], acc[j][3].thread_elements()[1]); + sums[j][pass] = (c0 + c1) + (c2 + c3); + } + } + _Pragma("clang loop unroll(full)") for (uint j = 0u; j < INK2_MMA_PT; ++j) { + if (j >= active) break; + // Then the passes, adjacent first: (0 + 1) + (2 + 3) and (4 + 5) + (6 + 7), then the two. + _Pragma("clang loop unroll(full)") for (uint s = 1u; s < INK2_MMA_NP; s <<= 1u) + _Pragma("clang loop unroll(full)") for (uint p = 0u; p < INK2_MMA_NP; p += 2u * s) sums[j][p] += sums[j][p + s]; + const float2 total = sums[j][0]; + const uint p0 = j * 8u + fn; + if (GU) { + // A row's gate and up rows are neighbours: the lane with the odd row shares its sums. + const float up0 = simd_shuffle_xor(total.x, 2u), up1 = simd_shuffle_xor(total.y, 2u); + if (lane & 2u) continue; + const uint col = tg.x * cols + ot * 4u + (fm >> 1u); + if (p0 < live) Y[ulong(members[expert * a.cap + band + p0]) * a.n + col] = ink2_act(total.x, up0); + if (p0 + 1u < live) Y[ulong(members[expert * a.cap + band + p0 + 1u]) * a.n + col] = ink2_act(total.y, up1); + } else { + const uint col = tg.x * cols + ot * 8u + fm; + if (p0 < live) Y[ulong(members[expert * a.cap + band + p0]) * a.n + col] = bfloat(total.x); + if (p0 + 1u < live) Y[ulong(members[expert * a.cap + band + p0 + 1u]) * a.n + col] = bfloat(total.y); + } + } + } +} + +#define INK2_MMA_NVFP4(symbol, gu) \ + [[kernel, max_total_threads_per_threadgroup(INK2_MMA_THREADS)]] void symbol( \ + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], device const uchar* S [[buffer(2)]], \ + device const float* amax [[buffer(3)]], device const float* denominator [[buffer(4)]], \ + device const uint* counts [[buffer(5)]], device const uint* members [[buffer(6)]], \ + device bfloat* Y [[buffer(7)]], constant Ink2GroupedArgs& a [[buffer(8)]], \ + uint2 tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { \ + threadgroup uint tgw[INK2_MMA_WORDS(true)]; \ + threadgroup uint tgx[INK2_MMA_XWORDS(true)]; \ + ink2_mma(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, t, tgw, tgx); \ + } + +#define INK2_MMA_MXFP8(symbol, gu) \ + [[kernel, max_total_threads_per_threadgroup(INK2_MMA_THREADS)]] void symbol( \ + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], device const uchar* S [[buffer(2)]], \ + device const uint* counts [[buffer(3)]], device const uint* members [[buffer(4)]], \ + device bfloat* Y [[buffer(5)]], constant Ink2GroupedArgs& a [[buffer(6)]], \ + uint2 tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { \ + threadgroup uint tgw[INK2_MMA_WORDS(false)]; \ + threadgroup uint tgx[INK2_MMA_XWORDS(false)]; \ + ink2_mma(X, W, S, 1.0f, counts, members, Y, a, tg, t, tgw, tgx); \ + } + +INK2_MMA_NVFP4(tf_ink2_nvfp4_gu_mma, true) +INK2_MMA_NVFP4(tf_ink2_nvfp4_down_mma, false) +INK2_MMA_MXFP8(tf_ink2_mxfp8_gu_mma, true) +INK2_MMA_MXFP8(tf_ink2_mxfp8_down_mma, false) diff --git a/zig/kernels/metal/inkling2/experts_sources.zig b/zig/kernels/metal/inkling2/experts_sources.zig index 56ae6e1c0db..e262a5e6985 100644 --- a/zig/kernels/metal/inkling2/experts_sources.zig +++ b/zig/kernels/metal/inkling2/experts_sources.zig @@ -1,2 +1,6 @@ //! Inkling 2 Mini's M3 packed-weight expert kernels; activations stay BF16 throughout. pub const experts = @embedFile("experts.metal"); +/// The same products on the tensor units, after nax.h, the decode helpers above and the shared op. +pub const experts_units = @embedFile("../nax.h") ++ experts ++ @embedFile("units.metal") ++ @embedFile("experts_units.metal"); +/// The same products on simdgroup matrices, for GPUs without tensor units: after the decode helpers above. +pub const experts_mma = experts ++ @embedFile("experts_mma.metal"); diff --git a/zig/kernels/metal/inkling2/experts_units.metal b/zig/kernels/metal/inkling2/experts_units.metal new file mode 100644 index 00000000000..c2f7cb3b5c6 --- /dev/null +++ b/zig/kernels/metal/inkling2/experts_units.metal @@ -0,0 +1,335 @@ +// Inkling 2 Mini's routed experts on the tensor units, after nax.h, experts.metal and units.metal. + +// The columns of a gate-up row and of a down row: constants, since a loop of constant length runs faster here. +#define INK2_GU_K 2304u +#define INK2_DOWN_K 1152u + +// Columns c .. c + 3 of two rows of X (zeros for a row past the expert's pairs) as a left fragment's eight values. +inline tfp::frag ink2_units_x(device const bfloat* x0, device const bfloat* x1, bool live0, bool live1, uint c) { + const bfloat z1 = bfloat(0.0f); + const bfloat4 z = bfloat4(z1, z1, z1, z1); + return tfp::frag(live0 ? *(device const bfloat4*)(x0 + c) : z, live1 ? *(device const bfloat4*)(x1 + c) : z); +} + +// Columns 16b + hx .. + 3 of a packed NVFP4 row as BF16 weights, each as ink2_nv_block decodes it. +inline bfloat4 ink2_nv_quad(device const uchar* w, device const uchar* scales, float phi, uint b, uint hx) { + const float half_scale = 0.5f * ink2_e4m3(scales[b]); + const uint word = ink2_word(w + 8u * b + (hx & 8u) / 2u) >> (4u * (hx & 4u)); + float4 v; + for (uint j = 0; j < 4u; ++j) v[j] = ink2_e2m1_twice((word >> (4u * j)) & 15u) * half_scale * phi; + return bfloat4(bfloat(v[0]), bfloat(v[1]), bfloat(v[2]), bfloat(v[3])); +} + +// Columns 16b + hx .. + 3 of an MXFP8 row as BF16 weights, each as ink2_mx_block decodes it. +inline bfloat4 ink2_mx_quad(device const uchar* w, device const uchar* scales, uint b, uint hx) { + const int shift = int(scales[b / 2u]) - 127; + const uint word = ink2_word(w + 16u * b + hx); + float4 v; + for (uint j = 0; j < 4u; ++j) v[j] = ldexp(ink2_e4m3_bits((word >> (8u * j)) & 255u), shift); + return bfloat4(bfloat(v[0]), bfloat(v[1]), bfloat(v[2]), bfloat(v[3])); +} + +// Threadgroup (x, e): weight rows 32x .. 32x + 31 of expert e by its pairs, 16 a band; FP8 is MXFP8, else NVFP4. +template +inline void ink2_units(device const bfloat* X, device const uchar* W, device const uchar* S, float phi, + device const uint* counts, device const uint* members, device bfloat* Y, + constant Ink2GroupedArgs& a, uint2 tg, uint sg, uint lane, threadgroup float* part) { + // GU: X is by row and the 2n interleaved gate and up rows give Y[pair][n]; else X is by pair. 32 divides the rows. + const uint K = GU ? INK2_GU_K : INK2_DOWN_K, rows_w = GU ? 2u * a.n : a.n, steps = K / 128u; + const uint expert = tg.y, w0 = 32u * tg.x; + const uint count = counts[expert]; + if (count == 0u) return; + const uint wb = FP8 ? K : K / 2u, sb = FP8 ? K / 32u : K / 16u; + const short2 home = tfp::frag_home(ushort(lane)); + const uint hx = uint(home.x), hy = uint(home.y); + device const uchar* w = W + ulong(expert) * rows_w * wb + ulong(w0 + hy) * wb; + device const uchar* s = S + ulong(expert) * rows_w * sb + ulong(w0 + hy) * sb; + for (uint band = 0u; band < count; band += 16u) { + const uint m0 = band + hy, m1 = band + hy + 8u; + const bool live0 = m0 < count, live1 = m1 < count; + const uint p0 = members[expert * a.cap + min(m0, count - 1u)], p1 = members[expert * a.cap + min(m1, count - 1u)]; + device const bfloat* x0 = X + ulong(GU ? p0 / a.topk : p0) * K + hx; + device const bfloat* x1 = X + ulong(GU ? p1 / a.topk : p1) * K + hx; + tfp::frag lo = tfp::frag(0.0f), hi = tfp::frag(0.0f); + // Simdgroup s sums the columns of eighth s from zero, 16 an op; the eight partial sums are then added in order. + for (uint b = sg * steps; b < (sg + 1u) * steps; ++b) { + const tfp::frag fa = ink2_units_x(x0, x1, live0, live1, 16u * b); + tfp::frag b0, b1; + if (FP8) { + b0 = tfp::frag(ink2_mx_quad(w, s, b, hx), ink2_mx_quad(w + 8u * wb, s + 8u * sb, b, hx)); + b1 = tfp::frag(ink2_mx_quad(w + 16u * wb, s + 16u * sb, b, hx), ink2_mx_quad(w + 24u * wb, s + 24u * sb, b, hx)); + } else { + b0 = tfp::frag(ink2_nv_quad(w, s, phi, b, hx), ink2_nv_quad(w + 8u * wb, s + 8u * sb, phi, b, hx)); + b1 = tfp::frag(ink2_nv_quad(w + 16u * wb, s + 16u * sb, phi, b, hx), ink2_nv_quad(w + 24u * wb, s + 24u * sb, phi, b, hx)); + } + ink2_mma(lo, hi, fa, b0, b1); + } + ink2_part_put(part, lo, hi, sg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0u) { + ink2_part_sum(part, lo, hi, lane); + // Element e of lo is pair row hy + 8 (e >> 2), weight row w0 + hx + (e & 3); hi is 16 weight rows on. + for (uint q = 0u; q < 2u; ++q) { + if (!(q == 0u ? live0 : live1)) continue; + const ulong pair = q == 0u ? p0 : p1; + for (uint side = 0u; side < 2u; ++side) { + const uint col = w0 + 16u * side + hx; + const float4 v = side == 0u ? float4(lo[4u * q], lo[4u * q + 1u], lo[4u * q + 2u], lo[4u * q + 3u]) + : float4(hi[4u * q], hi[4u * q + 1u], hi[4u * q + 2u], hi[4u * q + 3u]); + if (GU) { + Y[pair * a.n + col / 2u] = ink2_act(v[0], v[1]); + Y[pair * a.n + col / 2u + 1u] = ink2_act(v[2], v[3]); + } else { + for (uint j = 0u; j < 4u; ++j) Y[pair * a.n + col + j] = bfloat(v[j]); + } + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_gu_units( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2GroupedArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_down_units( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2GroupedArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_gu_units( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2GroupedArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_down_units( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2GroupedArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); +} + +// Threadgroup (x, e): 16 weight rows of expert e by its pairs, 32 a band: ink2_units' tile turned, for wide chunks. +template +inline void ink2_units_t(device const bfloat* X, device const uchar* W, device const uchar* S, float phi, + device const uint* counts, device const uint* members, device bfloat* Y, + constant Ink2GroupedArgs& a, uint2 tg, uint sg, uint lane, threadgroup float* part) { + const uint K = GU ? INK2_GU_K : INK2_DOWN_K, rows_w = GU ? 2u * a.n : a.n, steps = K / 128u; + const uint expert = tg.y, count = counts[expert]; + if (count == 0u) return; + const uint wb = FP8 ? K : K / 2u, sb = FP8 ? K / 32u : K / 16u; + const short2 home = tfp::frag_home(ushort(lane)); + const uint hx = uint(home.x), hy = uint(home.y); + // A lane's two weight rows: the gate and up rows of output 8x + hy, or rows 16x + hy and 8 on. + const uint row0 = GU ? 2u * (8u * tg.x + hy) : 16u * tg.x + hy, row1 = GU ? row0 + 1u : row0 + 8u; + device const uchar* w0 = W + ulong(expert) * rows_w * wb + ulong(row0) * wb; + device const uchar* w1 = W + ulong(expert) * rows_w * wb + ulong(row1) * wb; + device const uchar* s0 = S + ulong(expert) * rows_w * sb + ulong(row0) * sb; + device const uchar* s1 = S + ulong(expert) * rows_w * sb + ulong(row1) * sb; + for (uint band = 0u; band < count; band += 32u) { + const uint m0 = band + hy, m1 = m0 + 8u, m2 = m0 + 16u, m3 = m0 + 24u; + const bool live0 = m0 < count, live1 = m1 < count, live2 = m2 < count, live3 = m3 < count; + const uint p0 = members[expert * a.cap + min(m0, count - 1u)], p1 = members[expert * a.cap + min(m1, count - 1u)]; + const uint p2 = members[expert * a.cap + min(m2, count - 1u)], p3 = members[expert * a.cap + min(m3, count - 1u)]; + device const bfloat* x0 = X + ulong(GU ? p0 / a.topk : p0) * K + hx; + device const bfloat* x1 = X + ulong(GU ? p1 / a.topk : p1) * K + hx; + device const bfloat* x2 = X + ulong(GU ? p2 / a.topk : p2) * K + hx; + device const bfloat* x3 = X + ulong(GU ? p3 / a.topk : p3) * K + hx; + tfp::frag lo = tfp::frag(0.0f), hi = tfp::frag(0.0f); + for (uint b = sg * steps; b < (sg + 1u) * steps; ++b) { + tfp::frag fa; + if (FP8) fa = tfp::frag(ink2_mx_quad(w0, s0, b, hx), ink2_mx_quad(w1, s1, b, hx)); + else fa = tfp::frag(ink2_nv_quad(w0, s0, phi, b, hx), ink2_nv_quad(w1, s1, phi, b, hx)); + const tfp::frag b0 = ink2_units_x(x0, x1, live0, live1, 16u * b); + const tfp::frag b1 = ink2_units_x(x2, x3, live2, live3, 16u * b); + ink2_mma(lo, hi, fa, b0, b1); + } + ink2_part_put(part, lo, hi, sg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0u) { + ink2_part_sum(part, lo, hi, lane); + // Element e of lo is weight row (e >> 2 ? row1 : row0), pair band + hx + (e & 3); hi is 16 pairs on. + for (uint side = 0u; side < 2u; ++side) + for (uint j = 0u; j < 4u; ++j) { + const uint m = band + 16u * side + hx + j; + if (m >= count) continue; + const ulong pair = members[expert * a.cap + m]; + const float v0 = side == 0u ? lo[j] : hi[j], v1 = side == 0u ? lo[4u + j] : hi[4u + j]; + if (GU) { + Y[pair * a.n + 8u * tg.x + hy] = ink2_act(v0, v1); + } else { + Y[pair * a.n + row0] = bfloat(v0); + Y[pair * a.n + row1] = bfloat(v1); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_gu_units_t( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2GroupedArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units_t(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_down_units_t( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2GroupedArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units_t(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_gu_units_t( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2GroupedArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units_t(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_down_units_t( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2GroupedArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units_t(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); +} + +struct Ink2LogitArgs { uint rows, vocab; }; + +// Threadgroup (x, y): vocabulary rows 32x .. + 31 by rows 16y .. + 15 of h, summed as the expert products are. +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_logits_units( + device const bfloat* X [[buffer(0)]], device const bfloat* W [[buffer(1)]], + device float* Y [[buffer(2)]], constant Ink2LogitArgs& a [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + const uint n0 = 32u * tg.x, r0 = 16u * tg.y, K = INK2_GU_K; + const short2 home = tfp::frag_home(ushort(lane)); + const uint hx = uint(home.x), hy = uint(home.y); + const bool live0 = r0 + hy < a.rows, live1 = r0 + hy + 8u < a.rows; + device const bfloat* x0 = X + ulong(r0 + hy) * K + hx; + // A vocabulary row past the end reads the last one: its sums are not stored. + const uint last = a.vocab - 1u; + device const bfloat* w0 = W + ulong(min(n0 + hy, last)) * K + hx; + device const bfloat* w1 = W + ulong(min(n0 + hy + 8u, last)) * K + hx; + device const bfloat* w2 = W + ulong(min(n0 + hy + 16u, last)) * K + hx; + device const bfloat* w3 = W + ulong(min(n0 + hy + 24u, last)) * K + hx; + tfp::frag lo = tfp::frag(0.0f), hi = tfp::frag(0.0f); + for (uint b = sg * (K / 128u); b < (sg + 1u) * (K / 128u); ++b) { + const tfp::frag fa = ink2_units_x(x0, x0 + 8u * K, live0, live1, 16u * b); + const tfp::frag b0 = tfp::frag(*(device const bfloat4*)(w0 + 16u * b), *(device const bfloat4*)(w1 + 16u * b)); + const tfp::frag b1 = tfp::frag(*(device const bfloat4*)(w2 + 16u * b), *(device const bfloat4*)(w3 + 16u * b)); + ink2_mma(lo, hi, fa, b0, b1); + } + ink2_part_put(part, lo, hi, sg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0u) return; + ink2_part_sum(part, lo, hi, lane); + // Element e of lo is row r0 + hy + 8 (e >> 2), vocabulary row n0 + hx + (e & 3); hi is 16 vocabulary rows on. + for (uint q = 0u; q < 2u; ++q) { + if (!(q == 0u ? live0 : live1)) continue; + const ulong row = r0 + hy + 8u * q; + for (uint side = 0u; side < 2u; ++side) + for (uint j = 0u; j < 4u; ++j) { + const uint v = n0 + 16u * side + hx + j; + const float dot = side == 0u ? lo[4u * q + j] : hi[4u * q + j]; + if (v < a.vocab) Y[row * a.vocab + v] = 30.0f * precise::tanh(precise::divide(float(bfloat(dot)), 30.0f)); + } + } +} + +struct Ink2DenseArgs { uint rows, n, k; }; + +// Threadgroup (x, y): outputs 32x .. 32x + 31 of rows 16y .. 16y + 15, summed as the expert products are; KC is k. +template +inline void ink2_dense(device const bfloat* X, device const bfloat* W, device bfloat* Y, constant Ink2DenseArgs& a, + uint2 tg, uint sg, uint lane, threadgroup float* part) { + const uint n0 = 32u * tg.x, r0 = 16u * tg.y, K = KC; + const short2 home = tfp::frag_home(ushort(lane)); + const uint hx = uint(home.x), hy = uint(home.y); + const bool live0 = r0 + hy < a.rows, live1 = r0 + hy + 8u < a.rows; + device const bfloat* x0 = X + ulong(r0 + hy) * K + hx; + // An output past the end reads the last one's weights: its sums are not stored. + const uint last = a.n - 1u; + device const bfloat* w0 = W + ulong(min(n0 + hy, last)) * K + hx; + device const bfloat* w1 = W + ulong(min(n0 + hy + 8u, last)) * K + hx; + device const bfloat* w2 = W + ulong(min(n0 + hy + 16u, last)) * K + hx; + device const bfloat* w3 = W + ulong(min(n0 + hy + 24u, last)) * K + hx; + tfp::frag lo = tfp::frag(0.0f), hi = tfp::frag(0.0f); + for (uint b = sg * (K / 128u); b < (sg + 1u) * (K / 128u); ++b) { + const tfp::frag fa = ink2_units_x(x0, x0 + 8u * K, live0, live1, 16u * b); + const tfp::frag b0 = tfp::frag(*(device const bfloat4*)(w0 + 16u * b), *(device const bfloat4*)(w1 + 16u * b)); + const tfp::frag b1 = tfp::frag(*(device const bfloat4*)(w2 + 16u * b), *(device const bfloat4*)(w3 + 16u * b)); + ink2_mma(lo, hi, fa, b0, b1); + } + ink2_part_put(part, lo, hi, sg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0u) return; + ink2_part_sum(part, lo, hi, lane); + // Element e of lo is row r0 + hy + 8 (e >> 2), output n0 + hx + (e & 3); hi is 16 outputs on. + for (uint q = 0u; q < 2u; ++q) { + if (!(q == 0u ? live0 : live1)) continue; + const ulong row = r0 + hy + 8u * q; + for (uint side = 0u; side < 2u; ++side) + for (uint j = 0u; j < 4u; ++j) { + const uint v = n0 + 16u * side + hx + j; + const float dot = side == 0u ? lo[4u * q + j] : hi[4u * q + j]; + if (v < a.n) Y[row * a.n + v] = bfloat(dot); + } + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_dense_units( + device const bfloat* X [[buffer(0)]], device const bfloat* W [[buffer(1)]], + device bfloat* Y [[buffer(2)]], constant Ink2DenseArgs& a [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + if (a.k == 2304u) ink2_dense<2304u>(X, W, Y, a, tg, sg, lane, part); + else ink2_dense<3072u>(X, W, Y, a, tg, sg, lane, part); +} diff --git a/zig/kernels/metal/inkling2/glue.metal b/zig/kernels/metal/inkling2/glue.metal index 79e3a71a743..d9fd0e30913 100644 --- a/zig/kernels/metal/inkling2/glue.metal +++ b/zig/kernels/metal/inkling2/glue.metal @@ -43,61 +43,57 @@ kernel void tf_inkling2_embed_norm( out[size_t(row) * 2304 + d] = bfloat(float(weight[d]) * (float(x[d]) * inverse)); } -struct InkARArgs { uint sources, queries; }; -[[max_total_threads_per_threadgroup(256)]] +struct InkARArgs { uint sources, queries, rows; }; +// Four consecutive values of a source: a completed block's BF16, or the running partial's FP32 for the last source. +inline float4 ink_values(const device bfloat* blocks, const device float* partial, uint source, uint sources, uint d) { + if (source + 1 == sources) return *(const device float4*)(partial + d); + return float4(*(const device bfloat4*)(blocks + size_t(source) * 2304 + d)); +} + +// Threadgroup (q, row): row's sources mixed by query q into out[q * rows + row], four values a thread. +[[max_total_threads_per_threadgroup(576)]] kernel void tf_inkling2_ar( - const device bfloat* blocks [[buffer(0)]], const device float* partial [[buffer(1)]], - const device float* queries [[buffer(2)]], device float* out [[buffer(3)]], - constant InkARArgs& a [[buffer(4)]], uint t [[thread_position_in_threadgroup]], - uint q [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { - if (q >= a.queries || a.sources == 0 || a.sources > 5) return; - threadgroup float red[2 * 5 * 8], means[5], weights[5]; - for (uint s = 0; s < a.sources; ++s) { - float ss = 0.0f; - for (uint d = t; d < 2304; d += 256) { - const float x = ink_value(blocks, partial, s, a.sources, d); - ss += x * x; - } - const float reduced = simd_sum(ss); - if (lane == 0) red[s * 8 + t / 32] = reduced; + const device bfloat* all_blocks [[buffer(0)]], const device float* all_partial [[buffer(1)]], + const device float* queries [[buffer(2)]], device float* all_out [[buffer(3)]], + constant InkARArgs& a [[buffer(4)]], uint t [[thread_index_in_threadgroup]], + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + const uint q = tg.x, row = tg.y, d = 4u * t; + if (q >= a.queries || row >= a.rows || a.sources == 0 || a.sources > 5) return; + const device bfloat* blocks = all_blocks + size_t(row) * 4 * 2304; + const device float* partial = all_partial + size_t(row) * 2304; + device float* out = all_out + (size_t(q) * a.rows + row) * 2304; + // Each of the 18 simdgroups folds the partial sums itself, so no thread waits on another's result. + threadgroup float red[5 * 18], dots[5 * 18]; + float4 x[5]; + for (uint s = 0; s < 5; ++s) { + x[s] = s < a.sources ? ink_values(blocks, partial, s, a.sources, d) : float4(0.0f); + const float4 sq = x[s] * x[s]; + const float reduced = simd_sum((sq.x + sq.y) + (sq.z + sq.w)); + if (lane == 0) red[s * 18 + sg] = reduced; } threadgroup_barrier(mem_flags::mem_threadgroup); - if (t == 0) for (uint s = 0; s < a.sources; ++s) { - float ss = 0.0f; - for (uint j = 0; j < 8; ++j) ss += red[s * 8 + j]; + const float4 query = *(const device float4*)(queries + size_t(q) * 2304 + d); + float means[5]; + for (uint s = 0; s < 5; ++s) { + const float ss = simd_sum(lane < 18u ? red[s * 18 + lane] : 0.0f); means[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_EPS); + const float4 z = query * (x[s] * means[s]); + const float reduced = simd_sum((z.x + z.y) + (z.z + z.w)); + if (lane == 0) dots[s * 18 + sg] = reduced; } threadgroup_barrier(mem_flags::mem_threadgroup); - threadgroup float* dots = red + 40; - for (uint s = 0; s < a.sources; ++s) { - float dot = 0.0f; - for (uint d = t; d < 2304; d += 256) { - const float z = ink_value(blocks, partial, s, a.sources, d) * means[s]; - dot += queries[size_t(q) * 2304 + d] * z; - } - const float reduced = simd_sum(dot); - if (lane == 0) dots[s * 8 + t / 32] = reduced; - } - threadgroup_barrier(mem_flags::mem_threadgroup); - if (t == 0) { - float peak = -INFINITY; - for (uint s = 0; s < a.sources; ++s) { - float dot = 0.0f; - for (uint j = 0; j < 8; ++j) dot += dots[s * 8 + j]; - weights[s] = dot * INKLING_AR_SCALE; - peak = max(peak, weights[s]); - } - float den = 0.0f; - for (uint s = 0; s < a.sources; ++s) { weights[s] = precise::exp(weights[s] - peak); den += weights[s]; } - for (uint s = 0; s < a.sources; ++s) weights[s] = precise::divide(weights[s], den); - } - threadgroup_barrier(mem_flags::mem_threadgroup); - for (uint d = t; d < 2304; d += 256) { - float acc = 0.0f; - for (uint s = 0; s < a.sources; ++s) - acc += weights[s] * (ink_value(blocks, partial, s, a.sources, d) * means[s]); - out[size_t(q) * 2304 + d] = acc; + float weights[5], peak = -INFINITY; + for (uint s = 0; s < 5; ++s) { + const float dot = simd_sum(lane < 18u ? dots[s * 18 + lane] : 0.0f); + weights[s] = dot * INKLING_AR_SCALE; + if (s < a.sources) peak = max(peak, weights[s]); } + float den = 0.0f; + for (uint s = 0; s < a.sources; ++s) { weights[s] = precise::exp(weights[s] - peak); den += weights[s]; } + float4 acc = float4(0.0f); + for (uint s = 0; s < a.sources; ++s) acc += precise::divide(weights[s], den) * (x[s] * means[s]); + *(device float4*)(out + d) = acc; } struct InkConvArgs { uint rows, channels; }; @@ -138,35 +134,75 @@ kernel void tf_inkling2_conv_dynamic( } struct InkRouteArgs { uint rows; }; -kernel void tf_inkling2_router( +// The router's first launch: fp32 dots[row][e] = weight[e] . x[row], a simdgroup an expert, 8 columns a lane a step. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_inkling2_route_scores( const device bfloat* x [[buffer(0)]], const device bfloat* weight [[buffer(1)]], - const device float* bias [[buffer(2)]], device uint* ids [[buffer(3)]], - device float* weights [[buffer(4)]], constant InkRouteArgs& a [[buffer(5)]], + device float* dots [[buffer(2)]], constant InkRouteArgs& a [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint e = tg.x * 8 + sg, row = tg.y; + if (e >= 128 || row >= a.rows) return; + const device bfloat* w = weight + size_t(e) * 2304; + const device bfloat* v = x + size_t(row) * 2304; + float acc = 0.0f; + for (uint i = 8 * lane; i < 2304; i += 256) { + const float4 w0 = float4(*(const device bfloat4*)(w + i)), w1 = float4(*(const device bfloat4*)(w + i + 4)); + const float4 v0 = float4(*(const device bfloat4*)(v + i)), v1 = float4(*(const device bfloat4*)(v + i + 4)); + acc += dot(w0, v0) + dot(w1, v1); + } + const float sum = simd_sum(acc); + if (lane == 0) dots[row * 128 + e] = sum; +} + +// The second: the eight greatest score + bias, the lowest expert on a tie, written in ascending expert order. +kernel void tf_inkling2_router( + const device float* dots [[buffer(0)]], const device float* bias [[buffer(1)]], + device uint* ids [[buffer(2)]], device float* weights [[buffer(3)]], + constant InkRouteArgs& a [[buffer(4)]], 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], keys[128], chosen[8]; + threadgroup uint ranks[128], picked[8]; 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(dots[row * 128 + t]); + keys[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; - } - used[best] = true; picked[j] = best; chosen[j] = scores[best]; + // Among ordered keys the scan in the last branch takes the greatest first: an expert's rank says the same. + bool unordered = false; + if (t < 128) { + uint rank = 0; + for (uint e = 0; e < 128; ++e) { + unordered = unordered || isnan(keys[e]); + rank += (keys[e] > keys[t] || (keys[e] == keys[t] && e < t)) ? 1u : 0u; } + ranks[t] = rank; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < 128 && !unordered && ranks[t] < 8) { // 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 slot = 0; + for (uint e = 0; e < t; ++e) slot += ranks[e] < 8 ? 1u : 0u; + picked[slot] = t; chosen[slot] = scores[t]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + if (unordered) { + // A NaN key neither wins nor loses a comparison, so the picks follow this scan's order. + 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 || keys[e] > keys[best]) best = e; + } + used[best] = true; picked[j] = best; chosen[j] = scores[best]; + } + 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; + } } float den = 1e-20f; for (uint j = 0; j < 8; ++j) den += chosen[j]; @@ -193,13 +229,27 @@ kernel void tf_inkling2_logits( const device bfloat* h [[buffer(0)]], const device bfloat* unembed [[buffer(1)]], device float* out [[buffer(2)]], constant InkLogitArgs& a [[buffer(3)]], 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]); - // 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); + // A thread takes vocabulary row v for up to eight rows of h, so a window reads the row once; a dot adds in d order. + const uint v = at.x, r0 = 8u * at.y; + if (v >= a.vocab || r0 >= a.rows) return; + const uint n = min(8u, a.rows - r0); + const device bfloat* w = unembed + size_t(v) * 2304; + const device bfloat* x = h + size_t(r0) * 2304; + float acc[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + for (uint d = 0; d < 2304; d += 4) { + const float4 wv = float4(*(const device bfloat4*)(w + d)); + for (uint r = 0; r < n; ++r) { + const float4 xv = float4(*(const device bfloat4*)(x + size_t(r) * 2304 + d)); + float sum = acc[r]; + sum += wv.x * xv.x; sum += wv.y * xv.y; sum += wv.z * xv.z; sum += wv.w * xv.w; + acc[r] = sum; + } + } + for (uint r = 0; r < n; ++r) { + const float dot = acc[r]; + // A9(a): unembedding rounds to bf16 before it widens for softcap30. + out[size_t(r0 + r) * a.vocab + v] = ink_cap(float(bfloat(dot)), 30.0f); + } } struct InkExpertArgs { uint rows, channels; }; diff --git a/zig/kernels/metal/inkling2/loop.metal b/zig/kernels/metal/inkling2/loop.metal index fce6e866f6b..e82ee231ff8 100644 --- a/zig/kernels/metal/inkling2/loop.metal +++ b/zig/kernels/metal/inkling2/loop.metal @@ -9,7 +9,8 @@ constant uint INKLING_LOOP_H = 2304; constant uint INKLING_LOOP_RANK = 64; constant uint INKLING_LOOP_MESSAGES = 48; -struct InkLoopArgs { uint rows; }; +// stride: floats from one row's m to the next (the messages interleave 48 entries a row). +struct InkLoopArgs { uint rows, stride; }; kernel void tf_inkling2_loop_messages( const device bfloat* bank0 [[buffer(0)]], const device bfloat* bank1 [[buffer(1)]], @@ -80,17 +81,16 @@ kernel void tf_inkling2_loop_messages( } } +// The gates' first launch: h and m each to unit RMS and BF16, as normalized[row][h | m]. kernel void tf_inkling2_loop_gates( const device float* h [[buffer(0)]], const device float* m [[buffer(1)]], - const device bfloat* down [[buffer(2)]], const device bfloat* forget [[buffer(3)]], - const device bfloat* gain [[buffer(4)]], device float* out [[buffer(5)]], - constant InkLoopArgs& a [[buffer(6)]], uint t [[thread_position_in_threadgroup]], + device bfloat* normalized [[buffer(2)]], constant InkLoopArgs& a [[buffer(3)]], + uint t [[thread_position_in_threadgroup]], uint row [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { 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]; + m + size_t(row) * a.stride }; + threadgroup float sums[2 * 8], inverse[2]; for (uint s = 0; s < 2; ++s) { float ss = 0.0f; for (uint d = t; d < INKLING_LOOP_H; d += 256) { @@ -107,30 +107,55 @@ kernel void tf_inkling2_loop_gates( inverse[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_LOOP_EPS); } threadgroup_barrier(mem_flags::mem_threadgroup); + device bfloat* y = normalized + size_t(row) * (2 * INKLING_LOOP_H); for (uint d = t; d < INKLING_LOOP_H; d += 256) { - normalized[d] = bfloat(h[size_t(row) * INKLING_LOOP_H + d] * inverse[0]); - normalized[INKLING_LOOP_H + d] = bfloat(m[size_t(row) * INKLING_LOOP_H + d] * inverse[1]); + y[d] = bfloat(inputs[0][d] * inverse[0]); + y[INKLING_LOOP_H + d] = bfloat(inputs[1][d] * inverse[1]); } - threadgroup_barrier(mem_flags::mem_threadgroup); - if (t < INKLING_LOOP_RANK) { - 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]); - zeta[t] = float(bfloat(dot)); +} + +// The second: zeta[row][r] = bf16(down[r] . normalized[row]) in fp32, a simdgroup a rank, eight columns a lane a step. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_inkling2_loop_zeta( + const device bfloat* normalized [[buffer(0)]], const device bfloat* down [[buffer(1)]], + device bfloat* zeta [[buffer(2)]], constant InkLoopArgs& a [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint r = tg.x * 8 + sg, row = tg.y; + if (r >= INKLING_LOOP_RANK || row >= a.rows) return; + const device bfloat* w = down + size_t(r) * (2 * INKLING_LOOP_H); + const device bfloat* x = normalized + size_t(row) * (2 * INKLING_LOOP_H); + float acc = 0.0f; + for (uint i = 8 * lane; i < 2 * INKLING_LOOP_H; i += 256) { + const float4 w0 = float4(*(const device bfloat4*)(w + i)), w1 = float4(*(const device bfloat4*)(w + i + 4)); + const float4 x0 = float4(*(const device bfloat4*)(x + i)), x1 = float4(*(const device bfloat4*)(x + i + 4)); + acc += dot(w0, x0) + dot(w1, x1); } - threadgroup_barrier(mem_flags::mem_threadgroup); - for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float sum = simd_sum(acc); + if (lane == 0) zeta[row * INKLING_LOOP_RANK + r] = bfloat(sum); +} + +// The third: each output's forget and gain dots over zeta in rank order, then the four-step blend. +kernel void tf_inkling2_loop_blend( + const device float* h [[buffer(0)]], const device float* m [[buffer(1)]], + const device bfloat* zeta [[buffer(2)]], const device bfloat* forget [[buffer(3)]], + const device bfloat* gain [[buffer(4)]], device float* out [[buffer(5)]], + constant InkLoopArgs& a [[buffer(6)]], uint2 at [[thread_position_in_grid]]) { + const uint d = at.x, row = at.y; + if (d >= INKLING_LOOP_H || row >= a.rows) return; + { 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]; + const float z = float(zeta[row * INKLING_LOOP_RANK + r]); + fdot += float(forget[size_t(d) * INKLING_LOOP_RANK + r]) * z; + gdot += float(gain[size_t(d) * INKLING_LOOP_RANK + r]) * z; } const float f = precise::tanh(fdot); const float g = precise::tanh(gdot); // Four separately rounded binary32 steps; do not fold these into one expression. const float keep = 1.0f - f; const float left = keep * h[size_t(row) * INKLING_LOOP_H + d]; - const float right = g * m[size_t(row) * INKLING_LOOP_H + d]; + const float right = g * m[size_t(row) * a.stride + d]; out[size_t(row) * INKLING_LOOP_H + d] = left + right; } } diff --git a/zig/kernels/metal/inkling2/loop_mma.metal b/zig/kernels/metal/inkling2/loop_mma.metal new file mode 100644 index 00000000000..0b089ce912b --- /dev/null +++ b/zig/kernels/metal/inkling2/loop_mma.metal @@ -0,0 +1,47 @@ +// The loop blend on simdgroup matrices, for GPUs without tensor units: the scalar blend's bytes. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_loop_blend_mma( + const device float* h [[buffer(0)]], const device float* m [[buffer(1)]], + const device bfloat* zeta [[buffer(2)]], const device bfloat* forget [[buffer(3)]], + const device bfloat* gain [[buffer(4)]], device float* out [[buffer(5)]], + constant InkLoopArgs& a [[buffer(6)]], uint2 tg [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + // Threadgroup (x, y): outputs 16x .. 16x + 15 of rows 16y .. 16y + 15; forget and gain chain over the ranks. + const uint r0 = tg.y * 16u, d0 = tg.x * 16u; + simdgroup_matrix dotf[2][2], dotg[2][2]; + _Pragma("clang loop unroll(full)") for (uint i = 0u; i < 2u; ++i) + _Pragma("clang loop unroll(full)") for (uint j = 0u; j < 2u; ++j) { + dotf[i][j] = simdgroup_matrix(0.0f); + dotg[i][j] = simdgroup_matrix(0.0f); + } + // The ranks go in order, eight to an MMA, and an MMA adds its eight into C in order. + _Pragma("clang loop unroll(full)") for (uint o = 0u; o < INKLING_LOOP_RANK / 8u; ++o) { + simdgroup_matrix z[2], wf[2], wg[2]; + _Pragma("clang loop unroll(full)") for (uint i = 0u; i < 2u; ++i) + simdgroup_load(z[i], zeta + size_t(r0 + 8u * i) * INKLING_LOOP_RANK + 8u * o, INKLING_LOOP_RANK); + _Pragma("clang loop unroll(full)") for (uint j = 0u; j < 2u; ++j) { + simdgroup_load(wf[j], forget + size_t(d0 + 8u * j) * INKLING_LOOP_RANK + 8u * o, INKLING_LOOP_RANK, ulong2(0, 0), true); + simdgroup_load(wg[j], gain + size_t(d0 + 8u * j) * INKLING_LOOP_RANK + 8u * o, INKLING_LOOP_RANK, ulong2(0, 0), true); + } + _Pragma("clang loop unroll(full)") for (uint i = 0u; i < 2u; ++i) + _Pragma("clang loop unroll(full)") for (uint j = 0u; j < 2u; ++j) { + simdgroup_multiply_accumulate(dotf[i][j], z[i], wf[j], dotf[i][j]); + simdgroup_multiply_accumulate(dotg[i][j], z[i], wg[j], dotg[i][j]); + } + } + const uint qid = lane >> 2u; + const uint fm = (qid & 4u) + ((lane >> 1u) & 3u); + const uint fn = (qid & 2u) * 2u + (lane & 1u) * 2u; + _Pragma("clang loop unroll(full)") for (uint i = 0u; i < 2u; ++i) + _Pragma("clang loop unroll(full)") for (uint j = 0u; j < 2u; ++j) + _Pragma("clang loop unroll(full)") for (uint e = 0u; e < 2u; ++e) { + const uint row = r0 + 8u * i + fm, d = d0 + 8u * j + fn + e; + if (row >= a.rows) continue; + const float f = precise::tanh(dotf[i][j].thread_elements()[e]); + const float g = precise::tanh(dotg[i][j].thread_elements()[e]); + // Four separately rounded binary32 steps, as the scalar kernel does. + const float keep = 1.0f - f; + const float left = keep * h[size_t(row) * INKLING_LOOP_H + d]; + const float right = g * m[size_t(row) * a.stride + d]; + out[size_t(row) * INKLING_LOOP_H + d] = left + right; + } +} diff --git a/zig/kernels/metal/inkling2/loop_sources.zig b/zig/kernels/metal/inkling2/loop_sources.zig index 3e1345c1a82..1c25ab3c8f1 100644 --- a/zig/kernels/metal/inkling2/loop_sources.zig +++ b/zig/kernels/metal/inkling2/loop_sources.zig @@ -1,2 +1,4 @@ //! Inkling 2 Mini's cross-pass message and rank-64 gate shaders. pub const loop = @embedFile("loop.metal"); +/// The blend on simdgroup matrices, for GPUs without tensor units: after the loop kernels, whose constants it uses. +pub const loop_mma = loop ++ @embedFile("loop_mma.metal"); diff --git a/zig/kernels/metal/inkling2/prompt_attention.metal b/zig/kernels/metal/inkling2/prompt_attention.metal index 06f4459bd7e..6d6af9841b8 100644 --- a/zig/kernels/metal/inkling2/prompt_attention.metal +++ b/zig/kernels/metal/inkling2/prompt_attention.metal @@ -6,12 +6,37 @@ using namespace metal; constant constexpr uint D = 128, EXTENT = 1024, KEYS = 64, PAIRS = 128; constant constexpr float LOG2E = 1.4426950408889634f; struct InkPromptSeg { int row0, n, p0, pad; long off; }; -struct InkPromptArgs { uint heads, kv_heads, ring, chunk, c0, chunks; float scale; }; +struct InkPromptArgs { uint heads, kv_heads, ring, chunk, c0, chunks; float scale; uint window; }; inline size_t ink_prompt_rh(const InkPromptSeg& s, uint heads, uint group, uint kvh, uint pair) { return (size_t(s.row0) + pair / group) * heads + kvh * group + pair % group; } +// The first chunk a row at `pos` reads, which holds its partial slot 0: its window's on a sliding layer, else c0. +inline uint ink_prompt_first(constant InkPromptArgs& a, uint pos) { + return a.window ? (pos + 1 > a.window ? pos + 1 - a.window : 0u) / a.chunk : a.c0; +} + +#ifndef TF_SIMD_FRAGS +// The 16x16 block at key row r, column c of a tile in the cache, two loads a lane; a key from `keys` on reads as zero. +inline void ink_tile_get(thread tfp::frag& f, const device bfloat* tile, int r, int c, short2 home, int keys) { + const device bfloat* q = tile + (r + home.y) * int(D) + (c + home.x); + const bfloat none = bfloat(0); + const bfloat4 zero = bfloat4(none, none, none, none); + f = tfp::frag(r + home.y < keys ? bfloat4(*(const device bfloat4*)q) : zero, + r + home.y + 8 < keys ? bfloat4(*(const device bfloat4*)(q + 8 * int(D))) : zero); +} +#endif + +#ifndef TF_SIMD_FRAGS +// Columns c .. c + 3 of two query rows as a left fragment's eight values; a row that is no pair reads as zero. +inline void ink_rows_get(thread tfp::frag& f, const device bfloat* r0, const device bfloat* r1, int c, bool lo, bool hi) { + const bfloat none = bfloat(0); + const bfloat4 zero = bfloat4(none, none, none, none); + f = tfp::frag(lo ? bfloat4(*(const device bfloat4*)(r0 + c)) : zero, hi ? bfloat4(*(const device bfloat4*)(r1 + c)) : zero); +} +#endif + inline void ink_fold(float& mm, float& ll, float m, float l, float& a, float& b) { const float mn = max(mm, m); a = precise::exp2(mm - mn); @@ -39,13 +64,18 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi const device InkPromptSeg* segs [[buffer(4)]], device float* part_o [[buffer(5)]], device float2* part_ml [[buffer(6)]], constant InkPromptArgs& a [[buffer(7)]], uint3 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint t [[thread_index_in_threadgroup]]) { +#ifdef TF_SIMD_FRAGS threadgroup bfloat ks[KEYS * D], vs[KEYS * D]; +#endif const InkPromptSeg s = segs[0]; const uint group = a.heads / a.kv_heads, total = uint(s.n) * group, m0 = tg.x * PAIRS; if (m0 >= total) return; const uint kvh = tg.y, c = a.c0 + tg.z, b_lo = c * a.chunk; const uint tile_hi = uint(s.p0) + min(m0 + PAIRS - 1, total - 1) / group; if (b_lo > tile_hi) return; + // A sliding layer's block starts at its first pair's window: a chunk wholly before it has no key for the block. + const uint first_pos = uint(s.p0) + m0 / group; + if (a.window && first_pos + 1 > a.window && b_lo + a.chunk <= first_pos + 1 - a.window) return; const uint k_hi = min(b_lo + a.chunk - 1, tile_hi), m = m0 + 16 * sg; const short2 home = tfp::frag_home(ushort(lane)); const uint row_a = m + uint(home.y), row_b = row_a + 8; @@ -53,12 +83,23 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi const device bfloat* qb0 = q + ink_prompt_rh(s, a.heads, group, kvh, pair_a) * D; const device bfloat* qb1 = q + ink_prompt_rh(s, a.heads, group, kvh, pair_b) * D; const size_t hb = s.off + size_t(kvh) * a.ring * D; - tfp::frag acc[8], out[8]; - for (uint d = 0; d < 8; ++d) { acc[d] = tfp::frag(0); out[d] = tfp::frag(0); } + tfp::frag acc[8]; + for (uint d = 0; d < 8; ++d) acc[d] = tfp::frag(0); + // Where each of the lane's two rows keeps this chunk's folded sums, and whether it has a slot in this chunk at all. + size_t slot[2]; + bool stored[2]; + for (uint h = 0; h < 2; ++h) { + const uint row = min(m + uint(home.y) + 8 * h, total - 1), pos = uint(s.p0) + row / group, first = ink_prompt_first(a, pos); + stored[h] = m + uint(home.y) + 8 * h < total && b_lo <= pos && c >= first; + slot[h] = (ink_prompt_rh(s, a.heads, group, kvh, row) * a.chunks + c - (stored[h] ? first : c)) * D + uint(home.x); + } + // The earlier of the lane's two rows: a tile wholly EXTENT or more before it is live and unbiased for both. + const uint far_pos = uint(s.p0) + min(row_a, total - 1) / group; float top[2] = {-INFINITY, -INFINITY}, mass[2] = {0.0f, 0.0f}; float upper[2] = {-INFINITY, -INFINITY}, whole[2] = {0.0f, 0.0f}; for (uint kt = b_lo; kt <= k_hi; kt += KEYS) { const uint tile_end = min(kt + KEYS, k_hi + 1); +#ifdef TF_SIMD_FRAGS for (uint e = t; e < KEYS * D; e += 256) { const uint key = e / D, col = e % D, kp = kt + key; const bool live = kp < tile_end; @@ -67,6 +108,12 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi vs[e] = live ? vc[at] : bfloat(0); } threadgroup_barrier(mem_flags::mem_threadgroup); +#else + // A tile is 64 keys from a multiple of 64 and a ring is a multiple of 64 rows, so a tile never wraps its ring. + const device bfloat* tile_k = kc + hb + size_t(kt % a.ring) * D; + const device bfloat* tile_v = vc + hb + size_t(kt % a.ring) * D; + const int keys = int(tile_end - kt); +#endif if ((kt - b_lo) % 1024 == 0) { for (uint d = 0; d < 8; ++d) acc[d] = tfp::frag(0); top[0] = top[1] = -INFINITY; mass[0] = mass[1] = 0.0f; @@ -75,21 +122,32 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi if (m < total && kt <= uint(s.p0) + min(m + 15, total - 1) / group) { for (uint d = 0; d < 8; ++d) { tfp::frag qa, kb0, kb1, kb2, kb3; +#ifdef TF_SIMD_FRAGS tfp::frag_get_rows(qa, qb0, qb1, 16 * d, home, row_a < total, row_b < total); tfp::frag_get_t(kb0, ks, D, 0, 16 * d, home); tfp::frag_get_t(kb1, ks, D, 16, 16 * d, home); tfp::frag_get_t(kb2, ks, D, 32, 16 * d, home); tfp::frag_get_t(kb3, ks, D, 48, 16 * d, home); +#else + ink_rows_get(qa, qb0, qb1, 16 * d + home.x, row_a < total, row_b < total); + ink_tile_get(kb0, tile_k, 0, 16 * d, home, keys); + ink_tile_get(kb1, tile_k, 16, 16 * d, home, keys); + ink_tile_get(kb2, tile_k, 32, 16 * d, home, keys); + ink_tile_get(kb3, tile_k, 48, 16 * d, home, keys); +#endif tfp::mma_16x32(score[0], score[1], qa, kb0, kb1); tfp::mma_16x32(score[2], score[3], qa, kb2, kb3); } float peak[2] = {top[0], top[1]}; const uint sub_lo = b_lo + ((kt - b_lo) / 1024) * 1024, sub_hi = sub_lo + 1023; - for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) { + if (a.window == 0u && kt + KEYS - 1 + EXTENT <= far_pos) { + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) + score[f][e] = (e >> 2 ? row_b : row_a) < total ? (score[f][e] * a.scale + 0.0f) * LOG2E : -INFINITY; + } else for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) { const uint row = m + uint(home.y) + (e >> 2) * 8, col = uint(home.x) + TF_COL(e), kp = kt + 16 * f + col; const uint lr = row < total ? row / group : 0, pos = uint(s.p0) + lr; const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); - const bool live = row < total && kp <= pos && kp >= sub_lo && kp <= sub_hi; + const bool live = row < total && kp <= pos && kp >= sub_lo && kp <= sub_hi && (a.window == 0u || kp + a.window > pos); const uint distance = live ? pos - kp : 0; const float bias = live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f; score[f][e] = live ? (score[f][e] * a.scale + bias) * LOG2E : -INFINITY; @@ -113,33 +171,42 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi for (uint d = 0; d < 8; ++d) for (uint e = 0; e < 8; ++e) acc[d][e] *= keep[e >> 2]; for (uint f = 0; f < 4; ++f) for (uint d = 0; d < 8; d += 2) { tfp::frag v0, v1; +#ifdef TF_SIMD_FRAGS tfp::frag_get(v0, vs, D, 16 * f, 16 * d, home); tfp::frag_get(v1, vs, D, 16 * f, 16 * d + 16, home); +#else + ink_tile_get(v0, tile_v, 16 * f, 16 * d, home, keys); + ink_tile_get(v1, tile_v, 16 * f, 16 * d + 16, home, keys); +#endif tfp::mma_16x32(acc[d], acc[d + 1], p[f], v0, v1); } } const bool fold_now = (kt - b_lo) % 1024 == 960 || kt + KEYS > k_hi; + // The chunk's first fold stores, a later one folds into what is stored; a row with no key yet stores zeros. + const bool opening = kt - b_lo < 1024; if (fold_now && m < total) for (uint h = 0; h < 2; ++h) { - if (top[h] == -INFINITY) continue; - float x, y; - ink_fold(upper[h], whole[h], top[h], mass[h], x, y); - for (uint d = 0; d < 8; ++d) for (uint e = 4 * h; e < 4 * h + 4; ++e) out[d][e] = out[d][e] * x + acc[d][e] * y; + const bool some = top[h] != -INFINITY; + if (!some && !opening) continue; + float x = 0.0f, y = 0.0f; + if (some) ink_fold(upper[h], whole[h], top[h], mass[h], x, y); + if (!stored[h]) continue; + for (uint d = 0; d < 8; ++d) for (uint e = 4 * h; e < 4 * h + 4; ++e) { + device float* o = part_o + slot[h] + 16 * d + TF_COL(e); + const float before = opening ? 0.0f : *o; + *o = some ? before * x + acc[d][e] * y : before; + } } +#ifdef TF_SIMD_FRAGS threadgroup_barrier(mem_flags::mem_threadgroup); // no simdgroup reads ks/vs when the next tile overwrites them +#endif } if (m >= total) return; - for (uint d = 0; d < 8; ++d) for (uint e = 0; e < 8; ++e) { - const uint row = m + uint(home.y) + (e >> 2) * 8, col = uint(home.x) + TF_COL(e); - if (row >= total) continue; - const uint pos = uint(s.p0) + row / group; - if (b_lo > pos) continue; - const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); - part_o[(prow * a.chunks + c - a.c0) * D + 16 * d + col] = out[d][e]; - } if (home.x == 0) for (uint h = 0; h < 2; ++h) { const uint row = m + uint(home.y) + 8 * h; if (row >= total || b_lo > uint(s.p0) + row / group) continue; + const uint first = ink_prompt_first(a, uint(s.p0) + row / group); + if (c < first) continue; const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); - part_ml[prow * a.chunks + c - a.c0] = float2(upper[h], whole[h]); + part_ml[prow * a.chunks + c - first] = float2(upper[h], whole[h]); } } diff --git a/zig/kernels/metal/inkling2/units.metal b/zig/kernels/metal/inkling2/units.metal new file mode 100644 index 00000000000..7075e8e9e6f --- /dev/null +++ b/zig/kernels/metal/inkling2/units.metal @@ -0,0 +1,43 @@ +// The tensor-unit op Inkling 2 Mini's expert products are built on, after nax.h: FP32 sums of BF16 products. +using namespace metal; + +// (lo | hi) += a (b0 | b1)^T, b's blocks as stored, [output][column]: nax.h's 16x32x16 op without relaxed precision. +inline void ink2_mma(thread tfp::frag& lo, thread tfp::frag& hi, thread const tfp::frag& a, + thread const tfp::frag& b0, thread const tfp::frag& b1) { + using namespace mpp::tensor_ops; + constexpr auto shape = matmul2d_descriptor(16, 32, 16, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d op; + auto left = op.template get_left_input_cooperative_tensor(); + auto right = op.template get_right_input_cooperative_tensor(); + auto acc = op.template get_destination_cooperative_tensor, + metal::remove_addrspace_t, float>(); + TF_UNROLL + for (short e = 0; e < 8; e++) { + left[e] = a[e]; + right[e] = b0[e]; + right[8 + e] = b1[e]; + acc[e] = lo[e]; + acc[8 + e] = hi[e]; + } + op.run(left, right, acc); + TF_UNROLL + for (short e = 0; e < 8; e++) { + lo[e] = acc[e]; + hi[e] = acc[8 + e]; + } +} + +// A simdgroup's partial sums into the threadgroup's block, and the eight simdgroups' partials added in order. +inline void ink2_part_put(threadgroup float* part, thread const tfp::frag& lo, thread const tfp::frag& hi, uint sg, uint lane) { + for (uint e = 0u; e < 8u; ++e) { + part[(sg * 16u + e) * 32u + lane] = lo[e]; + part[(sg * 16u + 8u + e) * 32u + lane] = hi[e]; + } +} +inline void ink2_part_sum(threadgroup float* part, thread tfp::frag& lo, thread tfp::frag& hi, uint lane) { + for (uint e = 0u; e < 8u; ++e) + for (uint o = 1u; o < 8u; ++o) { + lo[e] += part[(o * 16u + e) * 32u + lane]; + hi[e] += part[(o * 16u + 8u + e) * 32u + lane]; + } +} diff --git a/zig/kernels/metal/inkling2_sources.zig b/zig/kernels/metal/inkling2_sources.zig index f105ac0f3a2..9c1d0f6ec2b 100644 --- a/zig/kernels/metal/inkling2_sources.zig +++ b/zig/kernels/metal/inkling2_sources.zig @@ -5,6 +5,10 @@ pub const prompt_attention = @import("inkling2/attention_sources.zig").prompt_at pub const prompt_attention_pre_m5 = @import("inkling2/attention_sources.zig").prompt_attention_pre_m5; pub const glue = @import("inkling2/glue_sources.zig").glue; pub const experts = @import("inkling2/experts_sources.zig").experts; +pub const experts_units = @import("inkling2/experts_sources.zig").experts_units; +pub const experts_mma = @import("inkling2/experts_sources.zig").experts_mma; pub const loop = @import("inkling2/loop_sources.zig").loop; +pub const loop_mma = @import("inkling2/loop_sources.zig").loop_mma; +pub const dense_mma = @import("inkling2/dense_sources.zig").dense_mma; pub const runtime = @import("inkling2/runtime_sources.zig").runtime; pub const inkling2_dspark = @import("inkling2/dspark_sources.zig").dspark; diff --git a/zig/src/core/contract/inkling2_experts_metal_records.zig b/zig/src/core/contract/inkling2_experts_metal_records.zig index 357a1ca88b0..b7fd6d01929 100644 --- a/zig/src/core/contract/inkling2_experts_metal_records.zig +++ b/zig/src/core/contract/inkling2_experts_metal_records.zig @@ -1,15 +1,15 @@ -//! Inkling 2 Mini M3 scalar Metal launches; 32 reserved threads avoid unmeasured M1/M2 receipts. +//! Inkling 2 Mini M3 Metal launches; every thread count is reserved by its kernel, so no M1/M2 receipt is needed. const std = @import("std"); const M = @import("limits.zig").MetalLaunch; pub const records = [_]M{ - .{ .name = "metal inkling2 experts tf_ink2_nvfp4_gu", .threads = 32, .tg_memory = 0, .reserved = 32 }, - .{ .name = "metal inkling2 experts tf_ink2_nvfp4_down", .threads = 32, .tg_memory = 0, .reserved = 32 }, - .{ .name = "metal inkling2 experts tf_ink2_mxfp8_gu", .threads = 32, .tg_memory = 0, .reserved = 32 }, - .{ .name = "metal inkling2 experts tf_ink2_mxfp8_down", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_nvfp4_gu", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 experts tf_ink2_nvfp4_down", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 experts tf_ink2_mxfp8_gu", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 experts tf_ink2_mxfp8_down", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "metal inkling2 experts tf_ink2_nvfp4_quantize", .threads = 32, .tg_memory = 0, .reserved = 32 }, .{ .name = "metal inkling2 experts tf_ink2_mxfp8_quantize", .threads = 32, .tg_memory = 0, .reserved = 32 }, - .{ .name = "metal inkling2 experts tf_ink2_combine", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_combine", .threads = 256, .tg_memory = 128, .reserved = 256 }, }; test "Inkling2 expert launches carry no fabricated M1/M2 compile receipts" { diff --git a/zig/src/core/contract/inkling2_glue_metal_records.zig b/zig/src/core/contract/inkling2_glue_metal_records.zig index e0013f02bae..5256ba3cf5e 100644 --- a/zig/src/core/contract/inkling2_glue_metal_records.zig +++ b/zig/src/core/contract/inkling2_glue_metal_records.zig @@ -2,10 +2,10 @@ const M = @import("limits.zig").MetalLaunch; pub const records = [_]M{ .{ .name = "metal inkling2 glue embed_norm tf_inkling2_embed_norm", .threads = 256, .tg_memory = 48, .reserved = 256 }, - .{ .name = "metal inkling2 glue ar tf_inkling2_ar", .threads = 256, .tg_memory = 368, .reserved = 256 }, + .{ .name = "metal inkling2 glue ar tf_inkling2_ar", .threads = 576, .tg_memory = 720, .reserved = 576 }, .{ .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 = 1600, .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/core/contract/inkling2_loop_metal_records.zig b/zig/src/core/contract/inkling2_loop_metal_records.zig index 8f32f1a7ab5..1a11442bb46 100644 --- a/zig/src/core/contract/inkling2_loop_metal_records.zig +++ b/zig/src/core/contract/inkling2_loop_metal_records.zig @@ -2,5 +2,5 @@ const M = @import("limits.zig").MetalLaunch; pub const records = [_]M{ .{ .name = "metal inkling2 loop messages tf_inkling2_loop_messages", .threads = 256, .tg_memory = 144, .reserved = 256 }, - .{ .name = "metal inkling2 loop gates tf_inkling2_loop_gates", .threads = 256, .tg_memory = 9552, .reserved = 256 }, + .{ .name = "metal inkling2 loop gates tf_inkling2_loop_gates", .threads = 256, .tg_memory = 80, .reserved = 256 }, }; diff --git a/zig/src/core/contract/inkling2_mma_metal_records.zig b/zig/src/core/contract/inkling2_mma_metal_records.zig new file mode 100644 index 00000000000..e2c9c916e43 --- /dev/null +++ b/zig/src/core/contract/inkling2_mma_metal_records.zig @@ -0,0 +1,21 @@ +//! Inkling 2 Mini's simdgroup-matrix launches: every thread count is reserved by its kernel, so no M1/M2 receipt. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +pub const records = [_]M{ + .{ .name = "metal inkling2 mma tf_ink2_nvfp4_gu_mma", .threads = 256, .tg_memory = 12288, .reserved = 256 }, + .{ .name = "metal inkling2 mma tf_ink2_nvfp4_down_mma", .threads = 256, .tg_memory = 12288, .reserved = 256 }, + .{ .name = "metal inkling2 mma tf_ink2_mxfp8_gu_mma", .threads = 256, .tg_memory = 24576, .reserved = 256 }, + .{ .name = "metal inkling2 mma tf_ink2_mxfp8_down_mma", .threads = 256, .tg_memory = 24576, .reserved = 256 }, + .{ .name = "metal inkling2 mma tf_ink2_dense_mma", .threads = 128, .tg_memory = 4096, .reserved = 128 }, + .{ .name = "metal inkling2 mma tf_ink2_loop_blend_mma", .threads = 32, .tg_memory = 0, .reserved = 32 }, +}; + +test "Inkling2 simdgroup-matrix launches reserve their threads and carry no M1/M2 compile receipts" { + for (records) |record| { + try std.testing.expectEqual(@as(u32, 0), record.m1); + try std.testing.expectEqual(@as(u32, 0), record.m2); + try std.testing.expectEqual(record.threads, record.reserved); + try std.testing.expect(std.mem.startsWith(u8, record.name, "metal inkling2 mma ")); + } +} diff --git a/zig/src/core/contract/inkling2_units_metal_records.zig b/zig/src/core/contract/inkling2_units_metal_records.zig new file mode 100644 index 00000000000..dcfdbb217c3 --- /dev/null +++ b/zig/src/core/contract/inkling2_units_metal_records.zig @@ -0,0 +1,26 @@ +//! Inkling 2 Mini's tensor-unit launches: tensor-op kernels, so no M1/M2 compile and 256 reserved threads. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +pub const records = [_]M{ + .{ .name = "metal inkling2 units tf_ink2_nvfp4_gu_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_nvfp4_down_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_mxfp8_gu_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_mxfp8_down_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_nvfp4_gu_units_t", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_nvfp4_down_units_t", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_mxfp8_gu_units_t", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_mxfp8_down_units_t", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_logits_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_dense_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, +}; + +test "Inkling2 units launches reserve their threads and carry no M1/M2 compile receipts" { + for (records) |record| { + try std.testing.expectEqual(@as(u32, 0), record.m1); + try std.testing.expectEqual(@as(u32, 0), record.m2); + try std.testing.expectEqual(record.threads, record.reserved); + try std.testing.expect(!record.offline); + try std.testing.expect(std.mem.startsWith(u8, record.name, "metal inkling2 units ")); + } +} diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index d1a0b824589..31cfcaa5fc2 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -96,6 +96,8 @@ pub const all_metal = @import("lane_q8_records.zig").records ++ @import("inkling2_attention_metal_records.zig").records ++ @import("inkling2_glue_metal_records.zig").records ++ @import("inkling2_experts_metal_records.zig").records ++ + @import("inkling2_units_metal_records.zig").records ++ + @import("inkling2_mma_metal_records.zig").records ++ @import("inkling2_loop_metal_records.zig").records ++ @import("inkling2_runtime_metal_records.zig").records ++ @import("inkling2_dspark_metal_records.zig").records ++ @@ -145,6 +147,8 @@ test { _ = @import("inkling2_attention_metal_records.zig"); _ = @import("inkling2_glue_metal_records.zig"); _ = @import("inkling2_experts_metal_records.zig"); + _ = @import("inkling2_units_metal_records.zig"); + _ = @import("inkling2_mma_metal_records.zig"); _ = @import("inkling2_loop_metal_records.zig"); _ = @import("inkling2_runtime_metal_records.zig"); _ = @import("inkling2_dspark_metal_records.zig"); diff --git a/zig/src/families/inkling2/metal/attention.zig b/zig/src/families/inkling2/metal/attention.zig index 8b5b4c8f39b..9fe310d564f 100644 --- a/zig/src/families/inkling2/metal/attention.zig +++ b/zig/src/families/inkling2/metal/attention.zig @@ -67,7 +67,8 @@ pub fn relTable(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, rel: e.dispatchGroups(mtl.Size.of(r.rows * r.heads, 1, 1), mtl.Size.of(256, 1, 1)); } -pub fn attend(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, tab: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) !void { +/// The partial sums of every row and head: `merge` reads them after a barrier. +pub fn partials(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, tab: Ref, part_o: Ref, part_ml: Ref) !void { const launch = try planning.attend(r, l, stride, slots); const scale: f32 = 1.0 / @sqrt(@as(f32, planning.head_dim)); if (launch.path == .decode) { @@ -77,16 +78,26 @@ pub fn attend(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: pla } else { e.setPipeline(k.prompt); bind(e, &.{ q, kv.k, kv.v, tab, meta.segs, part_o, part_ml }, 0); - e.setValue(planning.PromptArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale }, 7); + e.setValue(planning.PromptArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .chunk = l.chunk, .c0 = launch.c0, .chunks = launch.partials_rh, .scale = scale, .window = l.window }, 7); } e.dispatchGroups(mtl.Size.of(launch.grid[0], launch.grid[1], launch.grid[2]), mtl.Size.of(launch.threads, 1, 1)); - e.barrier(); +} + +/// The partials of `partials` merged, with the sink and gate, into each row's attention output. +pub fn merge(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) !void { + const launch = try planning.attend(r, l, stride, slots); e.setPipeline(k.merge); bind(e, &.{ part_o, part_ml, sink, gate, meta.pos, out }, 0); e.setValue(planning.MergeArgs{ .heads = r.heads, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .subs = launch.subs }, 6); e.dispatchGroups(mtl.Size.of(launch.merge_grid[0], 1, 1), mtl.Size.of(planning.merge_threads, 1, 1)); } +pub fn attend(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, tab: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) !void { + try partials(k, e, r, l, stride, slots, meta, q, kv, tab, part_o, part_ml); + e.barrier(); + try merge(k, e, r, l, stride, slots, meta, part_o, part_ml, sink, gate, out); +} + test { _ = @import("attention_plan.zig"); } diff --git a/zig/src/families/inkling2/metal/attention_plan.zig b/zig/src/families/inkling2/metal/attention_plan.zig index 6688dc8d7a0..7647210f26b 100644 --- a/zig/src/families/inkling2/metal/attention_plan.zig +++ b/zig/src/families/inkling2/metal/attention_plan.zig @@ -5,7 +5,7 @@ pub const head_dim = 128; pub const d_rel = 16; pub const extent = 1024; pub const tile_keys = 64; -pub const sliding_chunk = 256; +pub const sliding_chunk = 32; pub const global_chunk = 16384; pub const global_sub = 1024; pub const subs = global_chunk / global_sub; @@ -29,10 +29,10 @@ pub const PrepArgs = extern struct { }; pub const AttnArgs = extern struct { heads: u32, kv_heads: u32, ring: u32, window: u32, chunk: u32, c0: u32, chunks: u32, scale: f32 }; pub const MergeArgs = extern struct { heads: u32, window: u32, chunk: u32, c0: u32, chunks: u32, subs: u32 = 1 }; -pub const PromptArgs = extern struct { heads: u32, kv_heads: u32, ring: u32, chunk: u32, c0: u32, chunks: u32, scale: f32 }; +pub const PromptArgs = extern struct { heads: u32, kv_heads: u32, ring: u32, chunk: u32, c0: u32, chunks: u32, scale: f32, window: u32 = 0 }; comptime { if (@sizeOf(Seg) != 24 or @sizeOf(PrepArgs) != 36 or @sizeOf(AttnArgs) != 32) @compileError("Inkling attention ABI drift"); - if (@sizeOf(MergeArgs) != 24 or @sizeOf(PromptArgs) != 28) @compileError("Inkling prompt ABI drift"); + if (@sizeOf(MergeArgs) != 24 or @sizeOf(PromptArgs) != 32) @compileError("Inkling prompt ABI drift"); } pub const Layer = struct { @@ -44,14 +44,22 @@ pub const Layer = struct { return .{ .window = window, .ring = ringFor(window, rows), .chunk = sliding_chunk, .tau = false }; } pub fn global(capacity: u32) Layer { - return .{ .window = 0, .ring = @intCast(std.mem.alignForward(usize, capacity, tile_keys)), .chunk = global_chunk, .tau = true }; + return .{ .window = 0, .ring = @intCast(std.mem.alignForward(usize, capacity, tile_keys)), .chunk = globalChunk(capacity), .tau = true }; } pub fn cacheBytes(l: Layer, kv: usize) usize { return @as(usize, l.ring) * kv * head_dim * 2; } }; pub const Prep = struct { qk_clip: f32 = 22.627416997969522, rel_clip: f32 = 8, floor: f32 = 8192, alpha: f32 = 0.1, eps: f32 = 1e-6 }; -pub const Rows = struct { rows: u32, heads: u32 = 24, kv_heads: u32 = 8, last_pos: u32, streams: u32 = 1 }; +/// `prompt`: a prompt's rows, whose sliding layers take the prompt kernel too. +pub const Rows = struct { rows: u32, heads: u32 = 24, kv_heads: u32 = 8, last_pos: u32, streams: u32 = 1, prompt: bool = false }; + +/// The fewest keys a slot that fit `capacity` in 64 slots; any whole number of 1,024-key folds gives the same bits. +pub fn globalChunk(capacity: u32) u32 { + var chunk: u32 = global_sub; + while (@as(u64, chunk) * 64 < capacity and chunk < global_chunk) chunk *= 2; + return chunk; +} pub fn ringFor(window: u32, rows: u32) u32 { return @intCast(std.mem.alignForward(usize, @as(usize, window) + rows - 1, tile_keys)); @@ -67,7 +75,8 @@ pub fn split(r: Rows, stride: u32, slots: usize) bool { return r.rows <= split_rows and @as(usize, r.rows) * r.heads * stride * subs <= slots; } pub fn usePrompt(r: Rows, l: Layer, stride: u32, slots: usize) bool { - return l.window == 0 and r.streams == 1 and !split(r, stride, slots); + if (l.window > 0) return r.prompt and r.streams == 1; + return r.streams == 1 and !split(r, stride, slots); } pub fn partialSlot(l: Layer, c: usize, pos: usize) ?usize { const lo = if (l.window > 0) (pos + 1) -| l.window else 0; @@ -82,12 +91,18 @@ pub fn partialBytes(rows: usize, heads: u32, n_chunks: u32) usize { } pub const Path = enum { decode, prompt }; -pub const Launch = struct { path: Path, grid: [3]u32, threads: u32, merge_grid: [3]u32, partials_rh: u32, subs: u32 = 1 }; +pub const Launch = struct { path: Path, grid: [3]u32, threads: u32, merge_grid: [3]u32, partials_rh: u32, subs: u32 = 1, c0: u32 = 0 }; pub fn attend(r: Rows, l: Layer, stride: u32, slots: usize) error{Inkling2Partials}!Launch { if (slotsFor(l, @as(usize, r.last_pos) + 1) > stride) return error.Inkling2Partials; const merge_grid = [3]u32{ r.rows * r.heads, 1, 1 }; if (usePrompt(r, l, stride, slots)) { const blocks = std.math.divCeil(u32, r.rows * (r.heads / r.kv_heads), prompt_pairs) catch unreachable; + if (l.window > 0) { + // A sliding layer's chunks run from the first row's window to the last row. + const first_pos = r.last_pos + 1 - r.rows; + const c0 = ((first_pos + 1) -| l.window) / l.chunk; + return .{ .path = .prompt, .grid = .{ blocks, r.kv_heads, r.last_pos / l.chunk - c0 + 1 }, .threads = prompt_threads, .merge_grid = merge_grid, .partials_rh = stride, .c0 = c0 }; + } return .{ .path = .prompt, .grid = .{ blocks, r.kv_heads, stride }, .threads = prompt_threads, .merge_grid = merge_grid, .partials_rh = stride }; } return .{ .path = .decode, .grid = .{ r.rows * r.heads, stride, 1 }, .threads = decode_threads, .merge_grid = merge_grid, .partials_rh = stride }; diff --git a/zig/src/families/inkling2/metal/attention_test.zig b/zig/src/families/inkling2/metal/attention_test.zig index 3a8e73a3deb..885fb201d17 100644 --- a/zig/src/families/inkling2/metal/attention_test.zig +++ b/zig/src/families/inkling2/metal/attention_test.zig @@ -11,7 +11,7 @@ test "inkling2 metal ABI matches the shaders" { try t.expectEqual(@as(usize, 24), @sizeOf(p.Seg)); try t.expectEqual(@as(usize, 36), @sizeOf(p.PrepArgs)); try t.expectEqual(@as(usize, 24), @sizeOf(p.MergeArgs)); - try t.expectEqual(@as(usize, 28), @sizeOf(p.PromptArgs)); + try t.expectEqual(@as(usize, 32), @sizeOf(p.PromptArgs)); try t.expectEqual(@as(u32, 24), (p.Rows{ .rows = 1, .last_pos = 0 }).heads); try t.expectEqual(@as(u32, 8), (p.Rows{ .rows = 1, .last_pos = 0 }).kv_heads); try t.expectEqual(@as(f32, 8192), (p.Prep{}).floor); @@ -22,11 +22,11 @@ test "inkling2 metal Mini ring and window boundaries" { try t.expectEqual(@as(u32, 1088), p.ringFor(1024, 2)); try t.expectEqual(@as(u32, 3072), p.Layer.sliding(1024, 2048).ring); const l = p.Layer.sliding(1024, 1); - try t.expectEqual(@as(u32, 5), p.slotsFor(l, 1048576)); - try t.expectEqual(@as(?usize, 3), p.partialSlot(l, 3, 1023)); - try t.expectEqual(@as(?usize, null), p.partialSlot(l, 4, 1023)); - try t.expectEqual(@as(?usize, 4), p.partialSlot(l, 4, 1024)); - try t.expectEqual(@as(?usize, 3), p.partialSlot(l, 7, 2047)); + try t.expectEqual(@as(u32, 33), p.slotsFor(l, 1048576)); + try t.expectEqual(@as(?usize, 31), p.partialSlot(l, 31, 1023)); + try t.expectEqual(@as(?usize, null), p.partialSlot(l, 32, 1023)); + try t.expectEqual(@as(?usize, 32), p.partialSlot(l, 32, 1024)); + try t.expectEqual(@as(?usize, 31), p.partialSlot(l, 63, 2047)); try t.expectEqual(@as(usize, 1023), @as(usize, 8191) % 1024); try t.expectEqual(@as(usize, 0), @as(usize, 8192) % 8192); } @@ -41,12 +41,15 @@ test "inkling2 metal tau starts strictly above its 8192 floor" { test "inkling2 metal decode and prompt dispatch geometry" { const sl = p.Layer.sliding(1024, 8); const sr = p.Rows{ .rows = 8, .last_pos = 4095, .streams = 2 }; - const sd = try p.attend(sr, sl, 5, 8 * 24 * 5); + const sd = try p.attend(sr, sl, 33, 8 * 24 * 33); try t.expectEqual(p.Path.decode, sd.path); - try t.expectEqual([3]u32{ 192, 5, 1 }, sd.grid); + try t.expectEqual([3]u32{ 192, 33, 1 }, sd.grid); try t.expectEqual([3]u32{ 192, 1, 1 }, sd.merge_grid); try t.expectEqual(@as(u32, 32), sd.threads); const gl = p.Layer.global(1048576); + try t.expectEqual(@as(u32, 16384), gl.chunk); + try t.expectEqual(@as(u32, 1024), p.Layer.global(65536).chunk); + try t.expectEqual(@as(u32, 4096), p.Layer.global(262144).chunk); const one = p.Rows{ .rows = 1, .last_pos = 1048575 }; const gd = try p.attend(one, gl, 64, 24 * 64 * p.subs - 1); try t.expectEqual(p.Path.prompt, gd.path); diff --git a/zig/src/families/inkling2/metal/backend.zig b/zig/src/families/inkling2/metal/backend.zig index 8b7bc6e2c2c..d251561ada5 100644 --- a/zig/src/families/inkling2/metal/backend.zig +++ b/zig/src/families/inkling2/metal/backend.zig @@ -96,9 +96,13 @@ pub const Metal = struct { const self = cast(ptr); try validateTaps(&self.model.config, taps); if (!self.prepared) return error.UnpreparedInkling2Taps; - const tp = (try self.cacheOf(stream)).tap; + const cache = try self.cacheOf(stream); + var tp = cache.tap; + const off = st.featureOffset(tp, start, count, self.tap_gen) catch |err| blk: { + tp = cache.fill_tap; + break :blk st.featureOffset(tp, start, count, self.tap_gen) catch return err; + }; const buf = tp.buf orelse return error.Inkling2TapsNotHeld; - const off = try st.featureOffset(tp, start, count, self.tap_gen); return .{ .buffer = @intFromPtr(buf.id), .offset = off, .rows = count, .row_bytes = @intCast(st.feature_row_bytes), .space = .device, .dtype = .bf16 }; } @@ -117,7 +121,7 @@ pub const Metal = struct { } pub fn backend(self: *Metal) be.Backend { - return .{ .keep_full_lone = true, .ptr = self, .vtable = &.{ .prefill = prefillFn, .prepare_features = prepareFn, .features = featuresFn, .prefill_features = prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; + return .{ .keep_full_lone = true, .chunk_invariant = self.model.experts.units != null, .ptr = self, .vtable = &.{ .prefill = prefillFn, .prefill_step = prefillStepFn, .reports_fill = true, .prepare_features = prepareFn, .features = featuresFn, .prefill_features = prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; } fn cast(ptr: *anyopaque) *Metal { @@ -138,6 +142,7 @@ pub const Metal = struct { fn draw(self: *Metal, l: []const f32, sampling: ?lanes.Sampling, position: u64, mask: []const u32) !u32 { const t = sampled(sampling) orelse { + if (mask.len == 0 and l.len > 0) return firstGreatest(l); var best: ?usize = null; for (l, 0..) |w, id| { if (mask.len > 0 and !lanes.grammar.allows(mask, id)) continue; @@ -152,6 +157,31 @@ pub const Metal = struct { return lanes.gpu_full.draw(self.gpa, values, t, @intCast(position), null); } + /// The first index of the greatest logit, as draw's scan picks it: a NaN is picked only at index 0. + fn firstGreatest(l: []const f32) u32 { + if (l[0] != l[0]) return 0; + const V = @Vector(16, f32); + const least: V = @splat(-std.math.inf(f32)); + var top = least; + var i: usize = 0; + while (i + 16 <= l.len) : (i += 16) { + const v: V = l[i..][0..16].*; + top = @max(top, @select(f32, v != v, least, v)); + } + var best = @reduce(.Max, top); + for (l[i..]) |w| if (w > best) { + best = w; + }; + const want: V = @splat(best); + i = 0; + while (i + 16 <= l.len) : (i += 16) { + const v: V = l[i..][0..16].*; + if (@reduce(.Or, v == want)) break; + } + for (l[i..], i..) |w, id| if (w == best) return @intCast(id); + return 0; + } + fn sampled(sampling: ?lanes.Sampling) ?lanes.Sampling { const t = sampling orelse return null; return if (t.temperature > 0) t else null; @@ -170,53 +200,60 @@ pub const Metal = struct { } fn feed(self: *Metal, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream) !void { - const base = cache.len; var at: usize = 0; - while (at < ids.len) { - var end = @min(ids.len, at + st.prompt_rows); - if (stream) |sm| { - if (sm.isCancelled()) return error.Cancelled; - for (sm.chunks) |x| if (x > base + at and x < base + end) { - end = x - base; - }; - for (sm.reuse.marks) |x| if (x > base + at and x < base + end) { - end = x - base; - }; + while (at < ids.len) at += try self.feedChunk(cache, ids[at..], stream, 0); + } + + /// One chunk of `ids` from the cache's length, of at most `cap` rows when set, cut at planned chunks and marks. + fn feedChunk(self: *Metal, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream, cap: u32) !usize { + const base = cache.len; + var end: usize = @min(ids.len, if (cap > 0) @min(st.prompt_rows, cap) else st.prompt_rows); + if (stream) |sm| { + if (sm.isCancelled()) return error.Cancelled; + for (sm.chunks) |x| if (x > base and x < base + end) { + end = x - base; + }; + for (sm.reuse.marks) |x| if (x > base and x < base + end) { + end = x - base; + }; + } + const s = if (end > st.batch_rows) &self.prompt else &self.scratch; + const capture = self.prepared and stream != null; + if (capture) _ = self.nextTapGeneration(); + const taps: ?st.Ref = if (capture) .{ .buf = s.taps.? } else null; + try fwd.run(self.model, s, cache, ids[0..end], .{ .taps = taps, .prompt = true }); + if (capture) { + if (self.sink) |k| try k.take(k.ptr, stream.?, .{ + .buffer = @intFromPtr(s.taps.?.id), + .offset = 0, + .rows = @intCast(end), + .row_bytes = @intCast(st.feature_row_bytes), + .space = .device, + .dtype = .bf16, + }, @intCast(base)) else { + cache.fill_tap = .{ .buf = s.taps, .start = @intCast(base), .rows = end, .gen = self.tap_gen }; } - const s = if (end - at > st.batch_rows) &self.prompt else &self.scratch; - const capture = self.prepared and stream != null; - if (capture) _ = self.nextTapGeneration(); - const taps: ?st.Ref = if (capture) .{ .buf = s.taps.? } else null; - try fwd.run(self.model, s, cache, ids[at..end], .{ .taps = taps }); - if (capture) { - const rows = end - at; - if (self.sink) |k| try k.take(k.ptr, stream.?, .{ - .buffer = @intFromPtr(s.taps.?.id), - .offset = 0, - .rows = @intCast(rows), - .row_bytes = @intCast(st.feature_row_bytes), - .space = .device, - .dtype = .bf16, - }, @intCast(cache.len)); - if (base + end == stream.?.prompt().len) { - if (cache.last_tap == null) { - cache.last_tap = try self.model.device.buffer(st.feature_row_bytes, mtl.ResourceOptions.shared); - if (cache.follow) |f| f.join(f.ctx, cache.last_tap.?); - } - const bytes = s.taps.?.slice(u8, rows * st.feature_row_bytes); - @memcpy(cache.last_tap.?.slice(u8, st.feature_row_bytes), bytes[(rows - 1) * st.feature_row_bytes ..][0..st.feature_row_bytes]); - cache.tap = .{ .buf = cache.last_tap, .start = @intCast(cache.len + rows - 1), .rows = 1 }; + if (base + end == stream.?.prompt().len) { + if (cache.last_tap == null) { + cache.last_tap = try self.model.device.buffer(st.feature_row_bytes, mtl.ResourceOptions.shared); + if (cache.follow) |f| f.join(f.ctx, cache.last_tap.?); } + const bytes = s.taps.?.slice(u8, end * st.feature_row_bytes); + @memcpy(cache.last_tap.?.slice(u8, st.feature_row_bytes), bytes[(end - 1) * st.feature_row_bytes ..][0..st.feature_row_bytes]); + cache.tap = .{ .buf = cache.last_tap, .start = @intCast(base + end - 1), .rows = 1 }; } - cache.len += end - at; - if (stream) |sm| lanes.prefill_widths.completed(self.gpa, sm, end - at); - at = end; - if (stream) |sm| if (std.mem.indexOfScalar(u32, sm.reuse.marks, @intCast(cache.len)) != null) if (sm.reuse.hook) |k| k.at(k.ptr, sm, @intCast(cache.len)); } + cache.len += end; + if (stream) |sm| { + lanes.prefill_widths.completed(self.gpa, sm, end); + sm.fill_at.store(@intCast(cache.len), .monotonic); + if (std.mem.indexOfScalar(u32, sm.reuse.marks, @intCast(cache.len)) != null) if (sm.reuse.hook) |k| k.at(k.ptr, sm, @intCast(cache.len)); + } + return end; } - fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { - const self = cast(ptr); + /// The stream's cache made and a kept prefix restored: the pass goes on from the cache's length. + fn opening(self: *Metal, stream: *lanes.Stream) !*st.Cache { const ids = stream.prompt(); if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidInklingPrompt; if (stream.images.len > 0) return error.InklingHasNoImageTower; @@ -240,7 +277,35 @@ pub const Metal = struct { if (snapshot.restore(cache, self.model.queue, snap)) stream.cached = @intCast(snap.at) else |_| stream.reuse_failed = true; } else stream.reuse_failed = true; } - try self.feed(cache, ids[cache.len..], stream); + return cache; + } + + /// A pass that failed: its cache goes, as the whole pass's error leaves it. + fn drop(self: *Metal, stream: *lanes.Stream) void { + const entry = self.caches.fetchRemove(stream) orelse return; + self.held -= st.cacheBytes(entry.value.capacity); + entry.value.deinit(); + self.gpa.destroy(entry.value); + } + + fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { + const self = cast(ptr); + const cache = try self.opening(stream); + errdefer self.drop(stream); + try self.feed(cache, stream.prompt()[cache.len..], stream); + } + + /// One chunk a call, other streams' rounds between; the host's `max_rows` caps a chunk while replies decode. + fn prefillStepFn(ptr: *anyopaque, stream: *lanes.Stream, max_rows: u32) !bool { + const self = cast(ptr); + const cache = self.caches.get(stream) orelse try self.opening(stream); + errdefer self.drop(stream); + const ids = stream.prompt(); + // Beside other streams a chunk is at most `busy_rows`, so their rounds wait no longer than a short chunk. + const busy: u32 = if (self.caches.count() > 1) busy_rows else 0; + const cap = if (max_rows > 0 and busy > 0) @min(max_rows, busy) else @max(max_rows, busy); + _ = try self.feedChunk(cache, ids[cache.len..], stream, cap); + return cache.len == ids.len; } pub fn warm(self: *Metal) !void { @@ -401,6 +466,9 @@ pub const Metal = struct { } }; +/// A stepped prompt chunk's rows while another stream holds state. +const busy_rows: u32 = 256; + fn gib(bytes: u64) f64 { return @as(f64, @floatFromInt(bytes)) / (1 << 30); } @@ -434,6 +502,35 @@ fn logprobRow(l: []const f32, pick: u32, count: u8) lanes.LogprobRow { return r; } +test "a greedy pick is the scan's: the first of equal maxima, and a NaN only at index 0" { + const scan = struct { + fn pick(l: []const f32) u32 { + var best: usize = 0; + for (l, 0..) |w, id| if (w > l[best]) { + best = id; + }; + return @intCast(best); + } + }.pick; + var l: [203]f32 = undefined; + for (0..64) |round| { + for (&l, 0..) |*v, i| v.* = @floatFromInt(@as(i32, @intCast((i * 37 + round * 11) % 101)) - 50); + // Equal maxima, NaNs, both infinities and zeros of both signs, at places that move with the round. + l[(round * 7) % l.len] = 60; + l[(round * 13 + 5) % l.len] = 60; + if (round % 3 == 0) l[(round * 5 + 1) % l.len] = std.math.nan(f32); + if (round % 4 == 0) l[(round * 17 + 2) % l.len] = std.math.inf(f32); + if (round % 5 == 0) l[(round * 3) % l.len] = -std.math.inf(f32); + if (round % 7 == 0) l[0] = std.math.nan(f32); + try std.testing.expectEqual(scan(&l), Metal.firstGreatest(&l)); + try std.testing.expectEqual(scan(l[0..17]), Metal.firstGreatest(l[0..17])); + } + var z = [_]f32{ -0.0, 0.0, -std.math.inf(f32) }; + try std.testing.expectEqual(@as(u32, 0), Metal.firstGreatest(&z)); + z = .{ -std.math.inf(f32), std.math.nan(f32), -std.math.inf(f32) }; + try std.testing.expectEqual(@as(u32, 0), Metal.firstGreatest(&z)); +} + test "sampled first-token logprob uses the last written handle, not argmax" { const logits = [_]f32{ 0, -1, -2, -3 }; var tokens: [ring]u32 = @splat(0); diff --git a/zig/src/families/inkling2/metal/dense.zig b/zig/src/families/inkling2/metal/dense.zig new file mode 100644 index 00000000000..2a6253d182b --- /dev/null +++ b/zig/src/families/inkling2/metal/dense.zig @@ -0,0 +1,55 @@ +//! Prompt projections on simdgroup matrices, for GPUs without tensor units: the bf16 matvec's sums, bit for bit. +const std = @import("std"); +const mtl = @import("metal"); +const src = @import("inkling2_metal"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; + +/// Rows of x [rows][k] against a bf16 weight [n][k] into y [rows][ldy]; n is a multiple of 8 and k of 256. +pub const Call = struct { rows: u32, n: u32, k: u32, ldy: u32 }; + +/// Under this many rows a launch reads the weights for too few of them: the matvec kernels are as fast. +pub const min_rows: u32 = 16; + +const tile = 16; +const threads = 128; + +pub const Mma = struct { + pipe: mtl.Pipeline, + + /// Null where the GPU has tensor units, which take a prompt's projections themselves. + pub fn load(device: mtl.Device) !?Mma { + if (device.tensorUnits()) return null; + return try loadSource(device, src.dense_mma); + } + + /// The kernel from `text`; the contract's controls pass an edited one. + pub fn loadSource(device: mtl.Device, text: []const u8) !Mma { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + return .{ .pipe = try mtl.Pipeline.init(device, lib, "tf_ink2_dense_mma", false) }; + } + + pub fn deinit(m: Mma) void { + m.pipe.deinit(); + } + + /// A call the kernel takes. + pub fn valid(c: Call) bool { + return c.rows != 0 and c.n != 0 and c.n % 8 == 0 and c.k != 0 and c.k % 256 == 0 and c.ldy >= c.n; + } + + /// A call worth the kernel: the matvec kernels serve fewer rows than `min_rows`. + pub fn serves(c: Call) bool { + return c.rows >= min_rows and valid(c); + } + + pub fn launch(m: Mma, e: mtl.ComputeEncoder, x: Ref, w: Ref, out: Ref, c: Call) void { + std.debug.assert(valid(c)); + for ([_]Ref{ x, w }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(c, 2); + e.setBuffer(out.buf, out.off, 3); + e.setPipeline(m.pipe); + e.dispatchGroups(mtl.Size.of((c.n + tile - 1) / tile, (c.rows + tile - 1) / tile, 1), mtl.Size.of(threads, 1, 1)); + } +}; diff --git a/zig/src/families/inkling2/metal/experts.zig b/zig/src/families/inkling2/metal/experts.zig index 268ca0398ea..178e6f367ff 100644 --- a/zig/src/families/inkling2/metal/experts.zig +++ b/zig/src/families/inkling2/metal/experts.zig @@ -7,7 +7,7 @@ const plan = @import("experts_plan.zig"); pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; pub const Format = plan.Format; pub const Call = plan.Call; -pub const Operation = enum { nvfp4_gu, nvfp4_down, mxfp8_gu, mxfp8_down, nvfp4_quantize, mxfp8_quantize, combine }; +pub const Operation = enum { nvfp4_gu, nvfp4_down, mxfp8_gu, mxfp8_down, nvfp4_quantize, mxfp8_quantize, combine, group, nvfp4_gu_grouped, nvfp4_down_grouped, mxfp8_gu_grouped, mxfp8_down_grouped }; pub const function_names = [_][:0]const u8{ "tf_ink2_nvfp4_gu", @@ -17,13 +17,70 @@ pub const function_names = [_][:0]const u8{ "tf_ink2_nvfp4_quantize", "tf_ink2_mxfp8_quantize", "tf_ink2_combine", + "tf_ink2_group", + "tf_ink2_nvfp4_gu_grouped", + "tf_ink2_nvfp4_down_grouped", + "tf_ink2_mxfp8_gu_grouped", + "tf_ink2_mxfp8_down_grouped", }; +/// The columns the units kernels read a row: experts_units.metal's INK2_GU_K and INK2_DOWN_K. +const units_gu_k = 2304; +const units_down_k = 1152; +const units_names = [_][:0]const u8{ "tf_ink2_nvfp4_gu_units", "tf_ink2_nvfp4_down_units", "tf_ink2_mxfp8_gu_units", "tf_ink2_mxfp8_down_units", "tf_ink2_logits_units", "tf_ink2_dense_units", "tf_ink2_nvfp4_gu_units_t", "tf_ink2_nvfp4_down_units_t", "tf_ink2_mxfp8_gu_units_t", "tf_ink2_mxfp8_down_units_t" }; +/// The grouped products on simdgroup matrices, for GPUs without tensor units: their sums are the grouped kernels'. +const mma_names = [_][:0]const u8{ "tf_ink2_nvfp4_gu_mma", "tf_ink2_nvfp4_down_mma", "tf_ink2_mxfp8_gu_mma", "tf_ink2_mxfp8_down_mma" }; +/// The weight rows a simdgroup-matrix threadgroup takes. +const mma_tile_rows = 64; +/// A chunk of more rows than this gives an expert enough pairs for the turned tiles, 32 pairs a band. +const turned_rows: u32 = 512; + +/// A chunk of at least this many rows runs grouped by expert; a row's sums are the same either way. +pub const grouped_rows: u32 = 8; +/// A chunk of at least this many rows fills a band of an expert's pairs often enough for the simdgroup matrices. +pub const mma_rows: u32 = 32; +const group_cap: u32 = 1024; + +/// How a chunk's grouped products run; every path gives a row the same sums where it exists. +pub const Path = enum { scalar, mma, units }; + pub const Pipelines = struct { entries: [function_names.len]mtl.Pipeline, + /// Each expert's count, then its route pairs: launches in one encoder run in order, so they share it. + groups: mtl.Buffer, + /// The gate-up and down products on the tensor units (NVFP4 then MXFP8), where the GPU has them. + units: ?[units_names.len]mtl.Pipeline = null, + /// The grouped products on simdgroup matrices, where the GPU has no tensor units. + mma: ?[mma_names.len]mtl.Pipeline = null, pub fn load(device: mtl.Device) !Pipelines { - return loadSource(device, src.experts); + var out = try loadSource(device, src.experts); + errdefer out.deinit(); + if (device.tensorUnits()) try out.loadUnits(device, src.experts_units) else try out.loadMma(device, src.experts_mma); + return out; + } + + /// The tensor-unit kernels from `text`; the contract's controls pass an edited one. The GPU must have the units. + pub fn loadUnits(p: *Pipelines, device: mtl.Device, text: []const u8) !void { + p.units = try compile(&units_names, device, text); + } + + /// The simdgroup-matrix kernels from `text`; the contract's controls pass an edited one. + pub fn loadMma(p: *Pipelines, device: mtl.Device, text: []const u8) !void { + p.mma = try compile(&mma_names, device, text); + } + + fn compile(comptime names: []const [:0]const u8, device: mtl.Device, text: []const u8) ![names.len]mtl.Pipeline { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var pipes: [names.len]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (pipes[0..made]) |pipe| pipe.deinit(); + for (names, &pipes) |name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + } + return pipes; } pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { @@ -35,12 +92,19 @@ pub const Pipelines = struct { for (function_names, 0..) |name, i| { out.entries[i] = try mtl.Pipeline.init(device, lib, name, false); made += 1; - if (out.entries[i].maxThreads() < 32) return error.ExpertThreads; + const scalar = std.mem.endsWith(u8, name, "quantize") or std.mem.endsWith(u8, name, "group"); + if (out.entries[i].maxThreads() < @as(usize, if (scalar) 32 else 256)) return error.ExpertThreads; } + out.groups = try device.buffer((plan.expert_count + plan.expert_count * group_cap) * @sizeOf(u32), mtl.ResourceOptions.shared); + out.units = null; + out.mma = null; return out; } pub fn deinit(p: *Pipelines) void { + if (p.units) |pipes| for (pipes) |pipe| pipe.deinit(); + if (p.mma) |pipes| for (pipes) |pipe| pipe.deinit(); + p.groups.deinit(); for (p.entries) |pipe| pipe.deinit(); } @@ -58,13 +122,18 @@ 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)); } +fn launchGrid(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, g: plan.Geometry) void { + e.setPipeline(p.get(op)); + e.dispatchGroups(mtl.Size.of(g.outputs, g.pairs, 1), mtl.Size.of(g.threads, 1, 1)); +} + /// Packed NVFP4 GU: X [rows,k], ids [rows,topk], Y [rows*topk,n]. pub fn nvfp4Gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, amax: Ref, denominator: Ref, ids: Ref, out: Ref, c: Call) !void { if (c.format != .nvfp4) return error.WrongExpertFormat; 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); - launch(p, e, .nvfp4_gu, plan.geometry(c).groups); + launchGrid(p, e, .nvfp4_gu, plan.geometry(c)); } /// Packed MXFP8 GU with UE8M0 scales per row/block32. @@ -73,7 +142,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); - launch(p, e, .mxfp8_gu, plan.geometry(c).groups); + launchGrid(p, e, .mxfp8_gu, plan.geometry(c)); } 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 { @@ -81,7 +150,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); - launch(p, e, .nvfp4_down, plan.geometry(c).groups); + launchGrid(p, e, .nvfp4_down, plan.geometry(c)); } pub fn mxfp8Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, ids: Ref, out: Ref, c: Call) !void { @@ -89,7 +158,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); - launch(p, e, .mxfp8_down, plan.geometry(c).groups); + launchGrid(p, e, .mxfp8_down, plan.geometry(c)); } /// Decode one expert matrix to BF16, not an activation quantization operation. @@ -112,11 +181,162 @@ pub fn combine(p: *const Pipelines, e: mtl.ComputeEncoder, down: Ref, ids: Ref, try plan.check(c); for ([_]Ref{ down, ids, weights, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(args(c), 4); - // Combine has one group per token, rather than one per route pair. - launch(p, e, .combine, c.rows); + launchGrid(p, e, .combine, plan.combineGeometry(c)); +} + +const GroupArgs = extern struct { pairs: u32, experts: u32, cap: u32 }; +const GroupedArgs = extern struct { k: u32, n: u32, topk: u32, cap: u32 }; + +fn groupedArgs(c: Call) GroupedArgs { + return .{ .k = c.k, .n = c.n, .topk = c.topk, .cap = group_cap }; +} + +fn counts(p: *const Pipelines) Ref { + return .{ .buf = p.groups }; +} + +fn members(p: *const Pipelines) Ref { + return .{ .buf = p.groups, .off = plan.expert_count * @sizeOf(u32) }; +} + +fn launchGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, c: Call) void { + e.setPipeline(p.get(op)); + e.dispatchGroups(mtl.Size.of((c.n + 7) / 8, c.experts, 1), mtl.Size.of(256, 1, 1)); +} + +/// Each expert's route pairs for the grouped launches that follow; at most 1,024 rows. +pub fn group(p: *const Pipelines, e: mtl.ComputeEncoder, ids: Ref, c: Call) !void { + try plan.check(c); + if (c.rows > group_cap or c.experts != plan.expert_count) return error.BadExpertShape; + for ([_]Ref{ ids, counts(p), members(p) }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(GroupArgs{ .pairs = c.rows * c.topk, .experts = c.experts, .cap = group_cap }, 3); + e.setPipeline(p.get(.group)); + e.dispatchThreads(mtl.Size.of(c.experts, 1, 1), mtl.Size.of(32, 1, 1)); +} + +/// gu after group: the same outputs, each expert's weight blocks decoded once a pass of four rows. +pub fn guGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + try plan.check(c); + switch (c.format) { + .nvfp4 => { + const g = nv_globals orelse return error.MissingNvfp4Globals; + for ([_]Ref{ x, w, scales, g.amax, g.denominator, counts(p), members(p), out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(groupedArgs(c), 8); + launchGrouped(p, e, .nvfp4_gu_grouped, c); + }, + .mxfp8 => { + for ([_]Ref{ x, w, scales, counts(p), members(p), out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(groupedArgs(c), 6); + launchGrouped(p, e, .mxfp8_gu_grouped, c); + }, + } +} + +pub const Globals = struct { amax: Ref, denominator: Ref }; + +/// gu, or the down products (`down`), after group on the tensor units: an op is 16 of an expert's pairs by 32 rows. +pub fn units(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + return launchUnits(p, e, down, c.rows > turned_rows, x, w, scales, nv_globals, out, c); +} + +/// The same products on the turned tiles, 16 rows by 32 of an expert's pairs an op: the same sums, for wide chunks. +pub fn unitsTurned(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + return launchUnits(p, e, down, true, x, w, scales, nv_globals, out, c); +} + +fn launchUnits(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, turned: bool, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + const pipes = p.units orelse return error.NoTensorUnits; + // Gate and up rows interleave, so gu has two weight rows an output; the kernels fix the columns of each product. + const weight_rows = if (down) c.n else 2 * c.n; + if (c.k != @as(u32, if (down) units_down_k else units_gu_k) or weight_rows % 32 != 0) return error.BadExpertShape; + try bindGrouped(p, e, x, w, scales, nv_globals, out, c); + const first: usize = if (turned) 6 else 0; + e.setPipeline(pipes[first + (if (c.format == .nvfp4) @as(usize, 0) else 2) + @intFromBool(down)]); + e.dispatchGroups(mtl.Size.of(if (turned) weight_rows / 16 else (weight_rows + 31) / 32, c.experts, 1), mtl.Size.of(256, 1, 1)); +} + +/// gu, or the down products (`down`), after group on simdgroup matrices: 64 weight rows by bands of 32 pairs a group. +pub fn mma(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + const pipes = p.mma orelse return error.NoSimdgroupMatrices; + const weight_rows = if (down) c.n else 2 * c.n; + if (weight_rows % mma_tile_rows != 0 or c.k % 32 != 0) return error.BadExpertShape; + try bindGrouped(p, e, x, w, scales, nv_globals, out, c); + e.setPipeline(pipes[(if (c.format == .nvfp4) @as(usize, 0) else 2) + @intFromBool(down)]); + e.dispatchGroups(mtl.Size.of(weight_rows / mma_tile_rows, c.experts, 1), mtl.Size.of(256, 1, 1)); +} + +/// The path a chunk of `rows` rows takes after group, or null for the one-pair kernels. +pub fn pathFor(p: *const Pipelines, rows: u32) ?Path { + if (p.units != null) return .units; + if (p.mma != null and rows >= mma_rows) return .mma; + return if (rows >= grouped_rows) .scalar else null; +} + +/// The gate-up (or `down`) products of a chunk on `path`, after group. +pub fn products(p: *const Pipelines, e: mtl.ComputeEncoder, path: Path, down: bool, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + switch (path) { + .units => try units(p, e, down, x, w, scales, nv_globals, out, c), + .mma => try mma(p, e, down, x, w, scales, nv_globals, out, c), + .scalar => if (down) try downGrouped(p, e, x, w, scales, nv_globals, out, c) else try guGrouped(p, e, x, w, scales, nv_globals, out, c), + } +} + +/// The buffers and arguments the grouped kernels of every path share, after group. +fn bindGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + try plan.check(c); + switch (c.format) { + .nvfp4 => { + const g = nv_globals orelse return error.MissingNvfp4Globals; + for ([_]Ref{ x, w, scales, g.amax, g.denominator, counts(p), members(p), out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(groupedArgs(c), 8); + }, + .mxfp8 => { + for ([_]Ref{ x, w, scales, counts(p), members(p), out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(groupedArgs(c), 6); + }, + } +} + +const LogitArgs = extern struct { rows: u32, vocab: u32 }; +/// Rows of h against the vocabulary on the tensor units: fp32 out[row][v], bf16-rounded and capped as the glue's. +pub fn logitsUnits(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, unembed: Ref, out: Ref, rows: u32, vocab: u32) !void { + const pipes = p.units orelse return error.NoTensorUnits; + for ([_]Ref{ h, unembed, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(LogitArgs{ .rows = rows, .vocab = vocab }, 3); + e.setPipeline(pipes[4]); + e.dispatchGroups(mtl.Size.of((vocab + 31) / 32, (rows + 15) / 16, 1), mtl.Size.of(256, 1, 1)); +} + +const DenseArgs = extern struct { rows: u32, n: u32, k: u32 }; +/// A prompt's rows of x [rows][k] against a bf16 weight [n][k] on the tensor units; k is 2,304 or 3,072. +pub fn denseUnits(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, out: Ref, rows: u32, n: u32, k: u32) !void { + const pipes = p.units orelse return error.NoTensorUnits; + if ((k != 2304 and k != 3072) or rows == 0 or n == 0) return error.BadExpertShape; + for ([_]Ref{ x, w, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(DenseArgs{ .rows = rows, .n = n, .k = k }, 3); + e.setPipeline(pipes[5]); + e.dispatchGroups(mtl.Size.of((n + 31) / 32, (rows + 15) / 16, 1), mtl.Size.of(256, 1, 1)); +} + +/// The down products after group, as guGrouped. +pub fn downGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + try plan.check(c); + switch (c.format) { + .nvfp4 => { + const g = nv_globals orelse return error.MissingNvfp4Globals; + for ([_]Ref{ act, w, scales, g.amax, g.denominator, counts(p), members(p), out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(groupedArgs(c), 8); + launchGrouped(p, e, .nvfp4_down_grouped, c); + }, + .mxfp8 => { + for ([_]Ref{ act, w, scales, counts(p), members(p), out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(groupedArgs(c), 6); + launchGrouped(p, e, .mxfp8_down_grouped, 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 { +pub fn gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, ids: Ref, out: Ref, c: Call) !void { switch (c.format) { .nvfp4 => if (nv_globals) |g| return nvfp4Gu(p, e, x, w, scales, g.amax, g.denominator, ids, out, c) else return error.MissingNvfp4Globals, .mxfp8 => return mxfp8Gu(p, e, x, w, scales, ids, out, c), diff --git a/zig/src/families/inkling2/metal/experts_plan.zig b/zig/src/families/inkling2/metal/experts_plan.zig index 6b98f9fe18a..c493e848da3 100644 --- a/zig/src/families/inkling2/metal/experts_plan.zig +++ b/zig/src/families/inkling2/metal/experts_plan.zig @@ -28,12 +28,19 @@ pub const Call = struct { }; pub const Geometry = struct { - groups: u32, - threads: u32 = 32, + outputs: u32, + pairs: u32, + threads: u32 = 256, }; +/// A product's grid: eight outputs a threadgroup (one simdgroup each) by one route pair. pub fn geometry(c: Call) Geometry { - return .{ .groups = c.rows * c.topk }; + return .{ .outputs = (c.n + 7) / 8, .pairs = c.rows * c.topk }; +} + +/// The combine's grid: 256 outputs a threadgroup (one thread each) by one token. +pub fn combineGeometry(c: Call) Geometry { + return .{ .outputs = (c.n + 255) / 256, .pairs = c.rows }; } pub fn check(c: Call) !void { diff --git a/zig/src/families/inkling2/metal/experts_test.zig b/zig/src/families/inkling2/metal/experts_test.zig index 4ae2612b76f..1be0e3d54e2 100644 --- a/zig/src/families/inkling2/metal/experts_test.zig +++ b/zig/src/families/inkling2/metal/experts_test.zig @@ -124,11 +124,14 @@ test "eight-term combine stress separates FP32 and BF16 in every contract order" try std.testing.expect(9.0 / exact_allowance >= 100); } -test "launch geometry is 32 scalar threads and validates block/layout edges" { +test "launch geometry is a simdgroup an output by route pair and validates block/layout edges" { const nv = p.Call{ .rows = 3, .k = 2304, .n = 1152, .format = .nvfp4 }; try p.check(nv); - try std.testing.expectEqual(@as(u32, 24), p.geometry(nv).groups); - try std.testing.expectEqual(@as(u32, 32), p.geometry(nv).threads); + try std.testing.expectEqual(@as(u32, 144), p.geometry(nv).outputs); + try std.testing.expectEqual(@as(u32, 24), p.geometry(nv).pairs); + try std.testing.expectEqual(@as(u32, 256), p.geometry(nv).threads); + try std.testing.expectEqual(@as(u32, 5), p.combineGeometry(nv).outputs); + try std.testing.expectEqual(@as(u32, 3), p.combineGeometry(nv).pairs); const mx = p.Call{ .rows = 1, .k = 1152, .n = 2304, .format = .mxfp8 }; try p.check(mx); var bad = nv; diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index e75b57a089e..ef505bbcecd 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -8,6 +8,7 @@ const attention = @import("attention.zig"); const glue = @import("glue.zig"); const experts = @import("experts.zig"); const loop = @import("loop.zig"); +const dense_mma = @import("dense.zig"); const state = @import("state.zig"); const model_file = @import("model.zig"); const Model = model_file.Model; @@ -19,6 +20,8 @@ pub const Options = struct { ids: ?Ref = null, flight: ?*mtl.CommandBuffer = null, taps: ?state.Ref = null, + /// A prompt's rows: its projections run on the tensor units where the GPU has them. + prompt: bool = false, }; pub const FinalPlan = struct { work_rows: usize, logits_rows: usize, logits_row: usize, capture_rows: usize }; @@ -83,8 +86,10 @@ fn widen(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, count: usiz fn norm(m: *const Model, e: mtl.ComputeEncoder, input: Ref, weight: ck.Tensor, out: Ref, rows: usize) void { e.setPipeline(m.norm); - inline for (.{ input, r(weight), out }, 0..) |v, i| e.setBuffer(v.buf, v.off, i); - e.setValue(NormArgs{ .rows = @intCast(rows), .width = state.hidden, .eps = 1e-6 }, 3); + e.setBuffer(input.buf, input.off, 0); + e.setBuffer(weight.buffer, weight.offset, 1); + e.setValue(NormArgs{ .rows = @intCast(rows), .width = state.hidden, .eps = 1e-6 }, 2); + e.setBuffer(out.buf, out.off, 3); e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); } @@ -95,16 +100,9 @@ pub fn dense(m: *const Model, e: mtl.ComputeEncoder, weight: ck.Tensor, input: R var base: usize = 0; while (base < rows) { const left = rows - base; - const take: usize = if (left >= 32) 32 else if (left >= 16) 16 else if (left >= 8) 8 else if (left >= 4) 4 else if (left >= 2) 2 else 1; - const variant: usize = switch (take) { - 1 => 0, - 2 => 1, - 4 => 2, - 8 => 3, - 16 => 4, - 32 => 5, - else => unreachable, - }; + // One launch of the next size up: the kernel stores only `take` rows, and reads one pass of the weights. + const take: usize = @min(left, 32); + const variant: usize = if (take > 16) 5 else if (take > 8) 4 else if (take > 4) 3 else if (take > 2) 2 else if (take > 1) 1 else 0; e.setPipeline(m.dense[variant]); e.setBuffer(input.buf, input.off + base * k * 2, 0); e.setBuffer(weight.buffer, weight.offset, 1); @@ -115,22 +113,39 @@ pub fn dense(m: *const Model, e: mtl.ComputeEncoder, weight: ck.Tensor, input: R } } +/// A visit's projection: a prompt's rows on the tensor units or the simdgroup matrices, a round's rows as `dense`. +fn project(m: *const Model, e: mtl.ComputeEncoder, prompt: bool, weight: ck.Tensor, input: Ref, out: Ref, rows: usize) !void { + const k = weight.shape[weight.rank - 1]; + const n = weight.shape[weight.rank - 2]; + if (prompt and m.experts.units != null and (k == 2304 or k == 3072)) + return experts.denseUnits(&m.experts, e, x(input), x(.{ .buf = weight.buffer, .off = weight.offset }), x(out), @intCast(rows), @intCast(n), @intCast(k)); + if (prompt) if (m.dense_mma) |mma| { + const call = dense_mma.Call{ .rows = @intCast(rows), .n = @intCast(n), .k = @intCast(k), .ldy = @intCast(n) }; + if (dense_mma.Mma.serves(call)) return mma.launch(e, .{ .buf = input.buf, .off = input.off }, .{ .buf = weight.buffer, .off = weight.offset }, .{ .buf = out.buf, .off = out.off }, call); + }; + return dense(m, e, weight, input, out, rows); +} + /// One row because M2's AR ABI is [sources,H] -> [queries,H]. Batch composition never mixes rows. fn residual(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, queries: ck.Tensor, sources: usize, rows: usize) void { - for (0..rows) |i| glue.ar(&m.glue, e, at(s.blocks, i * state.block_slots * state.hidden * 2), row(s.partial, i, state.hidden * 4), r(queries), row(s.mlp_ar, i, state.hidden * 4), @intCast(sources), 1); + glue.arRows(&m.glue, e, at(s.blocks, 0), at(s.partial, 0), r(queries), at(s.mlp_ar, 0), @intCast(sources), 1, @intCast(rows)); } +/// Ends with a barrier: the cross-pass messages and the restored p are written. fn bankAndReset(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, rows: usize) void { for (0..rows) |i| { // The second completed block of the previous pass is B12; its final p is P18. copyBf16(m, e, at(s.blocks, (i * state.block_slots + 2) * state.hidden * 2), row(s.bank0, i, state.hidden * 2), state.hidden); } copyBf16(m, e, at(s.p, 0), at(s.bank1, 0), rows * state.hidden); + e.barrier(); loop.crossPassMessageAttention(&m.loop, e, l(at(s.bank0, 0)), l(at(s.bank1, 0)), l(r(m.weights.cross_queries)), l(r(m.weights.cross_kv_queries)), l(at(s.messages, 0)), @intCast(rows)); // The prelude p is restored, but every visit's KV and convolution state remains live. copyBf16(m, e, at(s.prelude, 0), at(s.p, 0), rows * state.hidden); + e.barrier(); } +/// Ends with a barrier: the norms are written. fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, rows: usize) void { const lp = m.weight_plan.at(v.layer); const w = &m.weights.layers[v.layer]; @@ -138,21 +153,22 @@ fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scra widen(m, e, at(s.p, 0), at(s.ar, 0), rows * state.hidden); } else { const q = m.weights.attn_queries[v.layer - 1]; - for (0..lp.attn_queries) |role| { - const query = at(q.buffer, q.offset + role * state.hidden * 4); - for (0..rows) |i| glue.ar(&m.glue, e, at(s.blocks, i * state.block_slots * state.hidden * 2), row(s.partial, i, state.hidden * 4), query, arRow(s, role, rows, i, false), lp.attn_sources, 1); - } + glue.arRows(&m.glue, e, at(s.blocks, 0), at(s.partial, 0), r(q), at(s.ar, 0), lp.attn_sources, @intCast(lp.attn_queries), @intCast(rows)); } - if (v.hasMessages()) { + e.barrier(); + const gated = v.hasMessages(); + if (gated) { const controllers = w.controllers.?; const core = v.layer - 6; - for (0..3) |role| for (0..rows) |i| { + var roles: [3]loop.Gate = undefined; + for (&roles, 0..) |*g, role| { const c = controllers[role]; const source_role = if (lp.kind == .local) 0 else role; - loop.gates(&m.loop, e, l(arRow(s, source_role, rows, i, false)), l(messageRow(s, core, role, i)), l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(arRow(s, role, rows, i, true)), 1); - }; + g.* = .{ .h = l(arRow(s, source_role, rows, 0, false)), .m = l(messageRow(s, core, role, 0)), .down = l(r(c.down)), .forget = l(r(c.forget)), .gain = l(r(c.gain)), .out = l(arRow(s, role, rows, 0, true)) }; + } + loop.gatesEach(&m.loop, e, &roles, @intCast(rows), state.message_entries * state.hidden); + e.barrier(); } - const gated = v.hasMessages(); // An ungated local visit has exactly one AR result and one norm result; Q/K/V alias. if (!gated and lp.kind == .local) { norm(m, e, arRow(s, 0, rows, 0, false), w.attn.q_norm, at(s.q_norm, 0), rows); @@ -161,56 +177,124 @@ fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scra norm(m, e, arRow(s, 1, rows, 0, gated), w.attn.k_norm, at(s.k_norm, 0), rows); norm(m, e, arRow(s, 2, rows, 0, gated), w.attn.v_norm, at(s.v_norm, 0), rows); } + e.barrier(); } -fn staticPostConv(m: *const Model, e: mtl.ComputeEncoder, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, weight: ck.Tensor, out: Ref, base: usize, rows: usize) void { +/// A stream's staged taps: a chunk wider than a window stages in the scratch, which then holds that stream alone. +fn staged(s: *const state.Scratch, cache: *const state.Cache, rows: usize, slot: usize, conv_state: usize, rows_before: usize) Ref { + return if (rows > state.window_rows) s.staged(slot, conv_state, rows_before) else cache.staged(slot, conv_state, rows_before); +} + +fn stagePostConv(m: *const Model, e: mtl.ComputeEncoder, s: *const state.Scratch, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, base: usize, rows: usize) void { const channels = state.convWidth(conv_state); - const taps = cache.staged(slot, conv_state, 0); - copyBf16(m, e, cache.history(slot, conv_state), taps, 3 * channels); - copyBf16(m, e, at(raw.buf, raw.off + base * channels * 2), cache.staged(slot, conv_state, 3), rows * channels); - glue.convStatic(&m.glue, e, taps, r(weight), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels)); + copyBf16(m, e, cache.history(slot, conv_state), staged(s, cache, rows, slot, conv_state, 0), 3 * channels); + copyBf16(m, e, at(raw.buf, raw.off + base * channels * 2), staged(s, cache, rows, slot, conv_state, 3), rows * channels); } -fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: []const Segment) !void { +/// Every stream's static convolution of `raw` into `out`: the taps staged, a barrier, the convolutions, a barrier. +fn postConv(m: *const Model, e: mtl.ComputeEncoder, s: *const state.Scratch, segments: []const Segment, slot: usize, conv_state: usize, raw: Ref, weight: ck.Tensor, out: Ref) void { + const channels = state.convWidth(conv_state); var base: usize = 0; - for (segments, 0..) |seg, si| { - const rows = seg.rows; + for (segments) |seg| { + stagePostConv(m, e, s, seg.cache, slot, conv_state, raw, base, seg.rows); + base += seg.rows; + } + e.barrier(); + base = 0; + for (segments) |seg| { + glue.convStatic(&m.glue, e, staged(s, seg.cache, seg.rows, slot, conv_state, 0), r(weight), at(out.buf, out.off + base * channels * 2), @intCast(seg.rows), @intCast(channels)); + base += seg.rows; + } + e.barrier(); +} + +/// One stream's rows of a visit's attention. +const Attend = struct { + cache: *state.Cache, + base: usize, + rows: usize, + rr: ap.Rows, + layer: ap.Layer, + meta: attention.RowMeta, + kv: attention.Cache, +}; + +/// Every stream's attention a step at a time: a step's launches run side by side, and a barrier ends each step. +fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: []const Segment, prompt: bool) !void { + const w = &m.weights.layers[v.layer]; + const prep = ap.Prep{ .qk_clip = m.config.text.qk_clip, .rel_clip = m.config.text.rel_clip, .floor = @floatFromInt(m.config.text.log_floor), .alpha = m.config.text.log_alpha, .eps = m.config.text.eps }; + var items: [state.max_segments]Attend = undefined; + var base: usize = 0; + for (segments, items[0..segments.len], 0..) |seg, *it, si| { const cache = seg.cache; - const layer0 = cache.attentionLayer(&m.weight_plan, v.cache_slot, rows); - const layer = ap.Layer{ .window = layer0.window, .ring = @intCast(cache.ring(v.cache_slot)), .chunk = layer0.chunk, .tau = layer0.tau }; - const start = cache.len; - const rr = ap.Rows{ .rows = @intCast(rows), .heads = 24, .kv_heads = 8, .last_pos = @intCast(start + rows - 1), .streams = 1 }; - const prep = ap.Prep{ .qk_clip = m.config.text.qk_clip, .rel_clip = m.config.text.rel_clip, .floor = @floatFromInt(m.config.text.log_floor), .alpha = m.config.text.log_alpha, .eps = m.config.text.eps }; - const meta = attention.RowMeta{ - .pos = a(at(s.pos, base * 4)), - .seg_of = a(at(s.seg_of, base * 4)), - .segs = a(at(s.segs, si * @sizeOf(ap.Seg))), + const layer0 = cache.attentionLayer(&m.weight_plan, v.cache_slot, seg.rows); + it.* = .{ + .cache = cache, + .base = base, + .rows = seg.rows, + // A prompt's rows on a sliding layer: the prompt kernel, a tile of keys a chunk. + .rr = .{ .rows = @intCast(seg.rows), .heads = 24, .kv_heads = 8, .last_pos = @intCast(cache.len + seg.rows - 1), .streams = 1, .prompt = prompt and m.attention.units and layer0.window > 0 }, + .layer = .{ .window = layer0.window, .ring = @intCast(cache.ring(v.cache_slot)), .chunk = if (prompt and m.attention.units and layer0.window > 0) ap.tile_keys else layer0.chunk, .tau = layer0.tau }, + .meta = .{ .pos = a(at(s.pos, base * 4)), .seg_of = a(at(s.seg_of, base * 4)), .segs = a(at(s.segs, si * @sizeOf(ap.Seg))) }, + .kv = .{ .k = a(cache.keys(v.cache_slot)), .v = a(cache.values(v.cache_slot)) }, }; - const kv = attention.Cache{ .k = a(cache.keys(v.cache_slot)), .v = a(cache.values(v.cache_slot)) }; - try convInputForAttention(m, e, s, cache, v, base, rows, true); - try convInputForAttention(m, e, s, cache, v, base, rows, false); - attention.prep(&m.attention, e, rr, layer, prep, meta, .{ a(at(s.q_raw, base * state.query_width * 2)), a(at(s.k_conv, base * state.kv_width * 2)), a(at(s.v_conv, base * state.kv_width * 2)), a(at(s.rel_raw, base * state.rel_width * 2)) }, .{ a(r(m.weights.layers[v.layer].attn.q_scale)), a(r(m.weights.layers[v.layer].attn.rel_scale)) }, a(at(s.q_prep, base * state.query_width * 2)), a(at(s.rel_prep, base * 24 * ap.extent * 2)), kv); - attention.relTable(&m.attention, e, rr, a(at(s.rel_prep, base * 24 * ap.extent * 2)), a(r(m.weights.layers[v.layer].attn.rel_projection)), a(at(s.rel_tab, base * 24 * ap.extent * 2))); - try attention.attend(&m.attention, e, rr, layer, state.max_attention_stride, 0, meta, a(at(s.q_prep, base * state.query_width * 2)), kv, a(at(s.rel_tab, base * 24 * ap.extent * 2)), a(at(s.part_o, base * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, base * 24 * state.max_attention_stride * 8)), a(at(s.sink, base * 24 * 2)), a(at(s.gate, base * state.query_width * 2)), a(at(s.att, base * state.query_width * 2))); - base += rows; + base += seg.rows; + } + const all = items[0..segments.len]; + for (all) |it| for ([_]bool{ true, false }) |key| stageConvInput(m, e, s, it.cache, v, it.base, key, it.rows); + e.barrier(); + for (all) |it| for ([_]bool{ true, false }) |key| convInputForAttention(m, e, s, it.cache, v, it.base, it.rows, key); + e.barrier(); + for (all) |it| { + const b = it.base; + attention.prep(&m.attention, e, it.rr, it.layer, prep, it.meta, .{ a(at(s.q_raw, b * state.query_width * 2)), a(at(s.k_conv, b * state.kv_width * 2)), a(at(s.v_conv, b * state.kv_width * 2)), a(at(s.rel_raw, b * state.rel_width * 2)) }, .{ a(r(w.attn.q_scale)), a(r(w.attn.rel_scale)) }, a(at(s.q_prep, b * state.query_width * 2)), a(at(s.rel_prep, b * state.rel_width * 2)), it.kv); + } + e.barrier(); + for (all) |it| attention.relTable(&m.attention, e, it.rr, a(at(s.rel_prep, it.base * state.rel_width * 2)), a(r(w.attn.rel_projection)), a(at(s.rel_tab, it.base * 24 * ap.extent * 2))); + e.barrier(); + for (all) |it| { + const b = it.base; + try attention.partials(&m.attention, e, it.rr, it.layer, state.max_attention_stride, 0, it.meta, a(at(s.q_prep, b * state.query_width * 2)), it.kv, a(at(s.rel_tab, b * 24 * ap.extent * 2)), a(at(s.part_o, b * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, b * 24 * state.max_attention_stride * 8))); + } + e.barrier(); + for (all) |it| { + const b = it.base; + try attention.merge(&m.attention, e, it.rr, it.layer, state.max_attention_stride, 0, it.meta, a(at(s.part_o, b * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, b * 24 * state.max_attention_stride * 8)), a(at(s.sink, b * 24 * 2)), a(at(s.gate, b * state.query_width * 2)), a(at(s.att, b * state.query_width * 2))); } + e.barrier(); } -fn convInputForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, key: bool) !void { - const lp = m.weight_plan.at(v.layer); +const ConvInput = struct { raw: Ref, projected: Ref, normalized: Ref, taps: Ref, state: usize }; + +fn convInput(s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, local_ungated: bool, base: usize, key: bool, rows: usize) ConvInput { + const cs: usize = if (key) 0 else 1; + const normalized = if (key) at(s.k_norm, 0) else if (local_ungated) at(s.q_norm, 0) else at(s.v_norm, 0); + return .{ + .raw = if (key) at(s.k_conv, base * state.kv_width * 2) else at(s.v_conv, base * state.kv_width * 2), + .projected = if (key) at(s.k_raw, base * state.kv_width * 2) else at(s.v_raw, base * state.kv_width * 2), + .normalized = at(normalized.buf, normalized.off + base * state.hidden * 2), + .taps = staged(s, cache, rows, v.cache_slot, cs, 0), + .state = cs, + }; +} + +/// A convolution's three old rows and its new rows staged: `convInputForAttention` reads them after a barrier. +fn stageConvInput(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, key: bool, rows: usize) void { + const c = convInput(s, cache, v, !v.hasMessages() and m.weight_plan.at(v.layer).kind != .global, base, key, rows); + copyBf16(m, e, cache.history(v.cache_slot, c.state), c.taps, 3 * state.kv_width); + copyBf16(m, e, c.projected, staged(s, cache, rows, v.cache_slot, c.state, 3), rows * state.kv_width); +} + +fn convInputForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, key: bool) void { const w = &m.weights.layers[v.layer]; - const raw = if (key) at(s.k_conv, base * state.kv_width * 2) else at(s.v_conv, base * state.kv_width * 2); - const projected = if (key) at(s.k_raw, base * state.kv_width * 2) else at(s.v_raw, base * state.kv_width * 2); - const normalized = if (key) at(s.k_norm, 0) else if (v.hasMessages() or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); - const taps = cache.staged(v.cache_slot, if (key) 0 else 1, 0); - copyBf16(m, e, cache.history(v.cache_slot, if (key) 0 else 1), taps, 3 * state.kv_width); - copyBf16(m, e, projected, cache.staged(v.cache_slot, if (key) 0 else 1, 3), rows * state.kv_width); + const c = convInput(s, cache, v, !v.hasMessages() and m.weight_plan.at(v.layer).kind != .global, base, key, rows); switch (if (key) w.attn.k_conv else w.attn.v_conv) { - .static => |weight| glue.convStatic(&m.glue, e, taps, r(weight), raw, @intCast(rows), state.kv_width), - .dynamic => |d| glue.convDynamic(&m.glue, e, taps, at(normalized.buf, normalized.off + base * state.hidden * 2), r(d.static_w), r(d.projection), raw, @intCast(rows), state.kv_width), + .static => |weight| glue.convStatic(&m.glue, e, c.taps, r(weight), c.raw, @intCast(rows), state.kv_width), + .dynamic => |d| glue.convDynamic(&m.glue, e, c.taps, c.normalized, r(d.static_w), r(d.projection), c.raw, @intCast(rows), state.kv_width), } } +/// The combine's output is written by the last launch: the caller's barrier follows. fn routedExperts(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, layer: usize, rows: usize) !void { const w = &m.weights.layers[layer]; const precision: experts.Format = switch (m.weight_plan.at(@intCast(layer)).precision) { @@ -219,19 +303,36 @@ fn routedExperts(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, laye }; const gu_call = experts.Call{ .rows = @intCast(rows), .k = state.hidden, .n = state.intermediate, .format = precision }; const down_call = experts.Call{ .rows = @intCast(rows), .k = state.intermediate, .n = state.hidden, .format = precision }; + if (experts.pathFor(&m.experts, @intCast(rows))) |path| { + // A row's sums are the same on every path its GPU has, so a chunk or window takes the path that fits its width. + const nv = precision == .nvfp4; + const gu_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) } else null; + const down_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.down.amax.?)), .denominator = x(r(w.down.denominator.?)) } else null; + try experts.group(&m.experts, e, x(at(s.route_ids, 0)), gu_call); + e.barrier(); + try experts.products(&m.experts, e, path, false, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), gu_globals, x(at(s.gu, 0)), gu_call); + e.barrier(); + try experts.products(&m.experts, e, path, true, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), down_globals, x(at(s.down, 0)), down_call); + e.barrier(); + return experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); + } if (precision == .nvfp4) { try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) }, x(at(s.route_ids, 0)), x(at(s.gu, 0)), gu_call); + e.barrier(); } else { try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), null, x(at(s.route_ids, 0)), x(at(s.gu, 0)), gu_call); + e.barrier(); } switch (precision) { .nvfp4 => try experts.nvfp4Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(r(w.down.amax.?)), x(r(w.down.denominator.?)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), .mxfp8 => try experts.mxfp8Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), } + e.barrier(); try experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); } -fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: []const Segment, rows: usize, taps: ?state.Ref) !void { +/// A visit's launches in dependency order; a barrier follows every step a later launch reads. +fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: []const Segment, rows: usize, taps: ?state.Ref, prompt: bool) !void { const lp = m.weight_plan.at(v.layer); const gated = v.hasMessages(); if (taps) |to| { @@ -247,45 +348,46 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la const w = &m.weights.layers[v.layer]; // The running BF16 p is the partial AR source before attention replaces it with t. widen(m, e, at(s.p, 0), at(s.partial, 0), rows * state.hidden); + e.barrier(); prepareAttentionInputs(m, e, s, v, rows); const knorm = if (gated or lp.kind == .global) at(s.k_norm, 0) else at(s.q_norm, 0); const vnorm = if (gated or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); - dense(m, e, w.attn.wq, at(s.q_norm, 0), at(s.q_raw, 0), rows); - dense(m, e, w.attn.wk, knorm, at(s.k_raw, 0), rows); - dense(m, e, w.attn.wv, vnorm, at(s.v_raw, 0), rows); - dense(m, e, w.attn.wr, at(s.q_norm, 0), at(s.rel_raw, 0), rows); - dense(m, e, w.attn.sink, at(s.q_norm, 0), at(s.sink, 0), rows); - dense(m, e, w.attn.gate, at(s.q_norm, 0), at(s.gate, 0), rows); - try attendSegments(m, e, s, v, segments); - dense(m, e, w.attn.wo, at(s.att, 0), at(s.attn_dense, 0), rows); - var base: usize = 0; - for (segments) |seg| { - staticPostConv(m, e, seg.cache, v.cache_slot, 2, at(s.attn_dense, 0), w.attn_conv, at(s.attn_conv, 0), base, seg.rows); - base += seg.rows; - } + try project(m, e, prompt, w.attn.wq, at(s.q_norm, 0), at(s.q_raw, 0), rows); + try project(m, e, prompt, w.attn.wk, knorm, at(s.k_raw, 0), rows); + try project(m, e, prompt, w.attn.wv, vnorm, at(s.v_raw, 0), rows); + try project(m, e, prompt, w.attn.wr, at(s.q_norm, 0), at(s.rel_raw, 0), rows); + try project(m, e, prompt, w.attn.sink, at(s.q_norm, 0), at(s.sink, 0), rows); + try project(m, e, prompt, w.attn.gate, at(s.q_norm, 0), at(s.gate, 0), rows); + e.barrier(); + try attendSegments(m, e, s, v, segments, prompt); + try project(m, e, prompt, w.attn.wo, at(s.att, 0), at(s.attn_dense, 0), rows); + e.barrier(); + postConv(m, e, s, segments, v.cache_slot, 2, at(s.attn_dense, 0), w.attn_conv, at(s.attn_conv, 0)); runtime(m, e, .attention_partial, &.{ at(s.p, 0), at(s.attn_conv, 0), at(s.blocks, 0), at(s.partial, 0) }, rows * state.hidden, if (lp.boundary) lp.blocks_in + 1 else 0); + e.barrier(); residual(m, e, s, m.weights.mlp_queries[v.layer], lp.mlp_sources, rows); + e.barrier(); if (gated) { const c = w.controllers.?[3]; const core = v.layer - 6; - for (0..rows) |i| loop.gates(&m.loop, e, l(row(s.mlp_ar, i, state.hidden * 4)), l(messageRow(s, core, 3, i)), l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(row(s.mlp_gated, i, state.hidden * 4)), 1); + loop.gatesStrided(&m.loop, e, l(at(s.mlp_ar, 0)), l(messageRow(s, core, 3, 0)), l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(at(s.mlp_gated, 0)), @intCast(rows), state.message_entries * state.hidden); + e.barrier(); norm(m, e, at(s.mlp_gated, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); } else norm(m, e, at(s.mlp_ar, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); + e.barrier(); glue.router(&m.glue, e, at(s.mlp_normed, 0), r(w.router_weight), r(w.router_bias), at(s.route_ids, 0), at(s.route_weights, 0), @intCast(rows)); + e.barrier(); try routedExperts(m, e, s, v.layer, rows); - base = 0; - for (segments) |seg| { - staticPostConv(m, e, seg.cache, v.cache_slot, 3, at(s.mlp_out, 0), w.mlp_conv, at(s.mlp_conv, 0), base, seg.rows); - base += seg.rows; - } + e.barrier(); + postConv(m, e, s, segments, v.cache_slot, 3, at(s.mlp_out, 0), w.mlp_conv, at(s.mlp_conv, 0)); runtime(m, e, .mlp_partial, &.{ at(s.partial, 0), at(s.mlp_conv, 0), at(s.p, 0) }, rows * state.hidden, 0); + e.barrier(); if (v.cache_slot == 5) copyBf16(m, e, at(s.p, 0), at(s.prelude, 0), rows * state.hidden); } fn commitFullHistories(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: []const Segment) void { - _ = s; for (segments) |seg| for (0..state.visit_slots) |slot| for (0..state.conv_states) |cs| { - copyBf16(m, e, seg.cache.staged(slot, cs, seg.rows), seg.cache.history(slot, cs), 3 * state.convWidth(cs)); + copyBf16(m, e, staged(s, seg.cache, seg.rows, slot, cs, seg.rows), seg.cache.history(slot, cs), 3 * state.convWidth(cs)); }; } @@ -317,20 +419,42 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, } const pool = mtl.objc.Pool.push(); defer pool.pop(); - const cb = m.queue.commandBuffer(); - const e = cb.compute(.serial); + var cb = m.queue.commandBuffer(); + var e = cb.compute(.concurrent); + // Earlier parts of this forward, already committed: the GPU runs them while the host encodes the next. + var parts: [cuts.len]mtl.CommandBuffer = undefined; + var n_parts: usize = 0; + defer for (parts[0..n_parts]) |part| part.release(); + errdefer if (n_parts > 0) parts[n_parts - 1].wait(); glue.embedNorm(&m.glue, e, options.ids orelse at(s.ids, 0), r(m.weights.embed), r(m.weights.embed_norm), at(s.p, 0), @intCast(rows)); - for (m.weight_plan.visits[0..m.weight_plan.n_visits]) |*v| try visit(m, e, s, v, segments, rows, options.taps); + e.barrier(); + for (m.weight_plan.visits[0..m.weight_plan.n_visits], 0..) |*v, vi| { + try visit(m, e, s, v, segments, rows, options.taps, options.prompt); + if (n_parts < cuts.len and vi + 1 == cuts[n_parts]) { + e.end(); + cb.commit(); + parts[n_parts] = cb.retain(); + n_parts += 1; + cb = m.queue.commandBuffer(); + e = cb.compute(.concurrent); + } + } widen(m, e, at(s.p, 0), at(s.partial, 0), rows * state.hidden); + e.barrier(); const final = finalPlan(rows, options.all, options.taps != null); - for (0..final.work_rows) |j| { - const i = if (final.work_rows == rows) j else rows - 1; - glue.ar(&m.glue, e, at(s.blocks, i * state.block_slots * state.hidden * 2), row(s.partial, i, state.hidden * 4), r(m.weights.output_query), row(s.mlp_ar, j, state.hidden * 4), m.weight_plan.final_sources, 1); + if (final.work_rows == rows) { + glue.arRows(&m.glue, e, at(s.blocks, 0), at(s.partial, 0), r(m.weights.output_query), at(s.mlp_ar, 0), m.weight_plan.final_sources, 1, @intCast(rows)); + } else { + const i = rows - 1; + glue.ar(&m.glue, e, at(s.blocks, i * state.block_slots * state.hidden * 2), row(s.partial, i, state.hidden * 4), r(m.weights.output_query), at(s.mlp_ar, 0), m.weight_plan.final_sources, 1); } + e.barrier(); norm(m, e, at(s.mlp_ar, 0), m.weights.norm, at(s.mlp_normed, 0), final.work_rows); + e.barrier(); if (options.taps) |to| captureTap(m, e, at(s.mlp_normed, 0), to, final.capture_rows, 3); + if (options.all and rows > state.batch_rows) return error.Inkling2RowsExceeded; const logits = if (options.all) at(s.logits_all, 0) else at(segments[0].cache.logits, 0); - glue.logits(&m.glue, e, at(s.mlp_normed, final.logits_row * state.hidden * 2), r(m.weights.unembed), logits, @intCast(final.logits_rows), m.config.text.unpadded_vocab); + if (m.experts.units != null) try experts.logitsUnits(&m.experts, e, x(at(s.mlp_normed, final.logits_row * state.hidden * 2)), x(r(m.weights.unembed)), x(logits), @intCast(final.logits_rows), m.config.text.unpadded_vocab) else glue.logits(&m.glue, e, at(s.mlp_normed, final.logits_row * state.hidden * 2), r(m.weights.unembed), logits, @intCast(final.logits_rows), m.config.text.unpadded_vocab); commitFullHistories(m, e, s, segments); e.end(); cb.commit(); @@ -339,8 +463,15 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, return; } cb.wait(); + for (parts[0..n_parts]) |part| if (part.failure()) |msg| { + std.log.err("inkling2_loop forward: {s}", .{msg}); + return error.GpuFailed; + }; if (cb.failure()) |msg| { std.log.err("inkling2_loop forward: {s}", .{msg}); return error.GpuFailed; } } + +/// Visits after which a forward's command buffer is committed and the next begun. +const cuts = [_]usize{ 2, 12, 24, 36 }; diff --git a/zig/src/families/inkling2/metal/glue.zig b/zig/src/families/inkling2/metal/glue.zig index dd74a1735a5..aed35b3a910 100644 --- a/zig/src/families/inkling2/metal/glue.zig +++ b/zig/src/families/inkling2/metal/glue.zig @@ -21,6 +21,9 @@ pub const Pipelines = struct { logits: mtl.Pipeline, expert_pick: mtl.Pipeline, expert_combine: mtl.Pipeline, + route_scores: mtl.Pipeline, + /// The router's dots for up to 1,024 rows; launches in one encoder run in order, so they share it. + route_dots: mtl.Buffer, pub fn load(device: mtl.Device) !Pipelines { return loadSource(device, sources.glue); @@ -28,7 +31,7 @@ pub const Pipelines = struct { pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); defer lib.deinit(); - var pipes: [9]mtl.Pipeline = undefined; + var pipes: [10]mtl.Pipeline = undefined; var made: usize = 0; errdefer for (pipes[0..made]) |pipe| pipe.deinit(); for ([_][]const u8{ @@ -41,6 +44,7 @@ pub const Pipelines = struct { "tf_inkling2_logits", "tf_inkling2_expert_pick", "tf_inkling2_expert_combine", + "tf_inkling2_route_scores", }, &pipes) |name, *pipe| { pipe.* = try mtl.Pipeline.init(device, lib, name, false); made += 1; @@ -55,6 +59,8 @@ pub const Pipelines = struct { .logits = pipes[6], .expert_pick = pipes[7], .expert_combine = pipes[8], + .route_scores = pipes[9], + .route_dots = try device.buffer(1024 * experts * @sizeOf(f32), mtl.ResourceOptions.shared), }; } pub fn deinit(p: *Pipelines) void { @@ -71,16 +77,23 @@ pub fn embedNorm(p: *const Pipelines, e: mtl.ComputeEncoder, ids: Ref, table: Re e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); } -const ARArgs = extern struct { sources: u32, queries: u32 }; +const ARArgs = extern struct { sources: u32, queries: u32, rows: u32 }; /// sources = completed BF16 blocks plus one unrounded F32 partial; output is one FP32 row per query. pub fn ar(p: *const Pipelines, e: mtl.ComputeEncoder, blocks: Ref, partial: Ref, queries: Ref, out: Ref, sources_: u32, queries_: u32) void { - std.debug.assert(sources_ > 0 and sources_ <= 5 and queries_ > 0 and queries_ <= 3); + arRows(p, e, blocks, partial, queries, out, sources_, queries_, 1); +} + +/// As ar for `rows` rows in one launch: blocks [row][4][H], partial [row][H], output [query][row][H]. +pub fn arRows(p: *const Pipelines, e: mtl.ComputeEncoder, blocks: Ref, partial: Ref, queries: Ref, out: Ref, sources_: u32, queries_: u32, rows: u32) void { + std.debug.assert(sources_ > 0 and sources_ <= 5 and queries_ > 0 and queries_ <= 3 and rows > 0); e.setPipeline(p.ar); inline for (.{ blocks, partial, queries, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); - e.setValue(ARArgs{ .sources = sources_, .queries = queries_ }, 4); - e.dispatchGroups(mtl.Size.of(queries_, 1, 1), mtl.Size.of(256, 1, 1)); + e.setValue(ARArgs{ .sources = sources_, .queries = queries_, .rows = rows }, 4); + e.dispatchGroups(mtl.Size.of(queries_, rows, 1), mtl.Size.of(ar_threads, 1, 1)); } +/// The depth mix's threads a threadgroup: a row's 2,304 values, four a thread. +const ar_threads = 576; const ConvArgs = extern struct { rows: u32, channels: u32 }; /// taps contains three old rows followed by `rows` current BF16 inputs. pub fn convStatic(p: *const Pipelines, e: mtl.ComputeEncoder, taps: Ref, weight: Ref, out: Ref, rows: u32, channels: u32) void { @@ -104,9 +117,17 @@ const RouteArgs = extern struct { rows: u32 }; /// Router IDs and weights are sorted by ascending expert index for the deterministic expert sum. pub fn router(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, weight: Ref, bias: Ref, ids: Ref, weights: Ref, rows: u32) void { std.debug.assert(rows > 0); + std.debug.assert(rows <= 1024); + e.setPipeline(p.route_scores); + inline for (.{ x, weight }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(p.route_dots, 0, 2); + e.setValue(RouteArgs{ .rows = rows }, 3); + e.dispatchGroups(mtl.Size.of(experts / 8, rows, 1), mtl.Size.of(256, 1, 1)); + e.barrier(); e.setPipeline(p.router); - inline for (.{ x, weight, bias, ids, weights }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); - e.setValue(RouteArgs{ .rows = rows }, 5); + e.setBuffer(p.route_dots, 0, 0); + inline for (.{ bias, ids, weights }, 1..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(RouteArgs{ .rows = rows }, 4); e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); } @@ -125,7 +146,8 @@ pub fn logits(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, unembed: Ref, e.setPipeline(p.logits); inline for (.{ h, unembed, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); e.setValue(LogitArgs{ .rows = rows, .vocab = vocab }, 3); - e.dispatchThreads(mtl.Size.of(vocab, rows, 1), unit); + // A thread takes a vocabulary row for eight rows of h. + e.dispatchThreads(mtl.Size.of(vocab, (rows + 7) / 8, 1), unit); } const ExpertArgs = extern struct { rows: u32, channels: u32 }; diff --git a/zig/src/families/inkling2/metal/glue_plan.zig b/zig/src/families/inkling2/metal/glue_plan.zig index 9cebaffe0ca..f100405d77e 100644 --- a/zig/src/families/inkling2/metal/glue_plan.zig +++ b/zig/src/families/inkling2/metal/glue_plan.zig @@ -50,7 +50,7 @@ pub const Call = struct { rows: usize, n: usize, k: usize }; pub fn valid(kind: Kind, c: Call) bool { const key_depth: usize = if (kind == .expert_combine) top_k else 4; const max_width: usize = if (kind == .conv_dynamic) 1024 else hidden; - if (c.rows == 0 or c.rows > 64) return false; + if (c.rows == 0 or c.rows > 1024) return false; return switch (kind) { .embed_norm => c.k == hidden and c.n == hidden, .router => c.k == hidden and c.n == top_k, diff --git a/zig/src/families/inkling2/metal/loop.zig b/zig/src/families/inkling2/metal/loop.zig index ebd3588eedf..2efdd42af6e 100644 --- a/zig/src/families/inkling2/metal/loop.zig +++ b/zig/src/families/inkling2/metal/loop.zig @@ -2,6 +2,7 @@ const std = @import("std"); const mtl = @import("metal"); const sources = @import("inkling2_metal"); +const dense = @import("dense.zig"); pub const plan = @import("inkling2_loop_plan"); pub const hidden: u32 = plan.hidden; @@ -10,12 +11,35 @@ pub const message_entries: u32 = plan.message_entries; pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; pub const RowsArgs = plan.RowsArgs; +/// Bytes of gate scratch a row: normalized [h | m] in BF16, then zeta's 64 BF16. +const gate_row_bytes: usize = (2 * hidden + rank) * 2; + pub const Pipelines = struct { messages: mtl.Pipeline, gates: mtl.Pipeline, + zeta: mtl.Pipeline, + blend: mtl.Pipeline, + /// The down projection on simdgroup matrices, where the GPU has no tensor units: zeta's sums. + zeta_mma: ?dense.Mma = null, + /// The blend on simdgroup matrices, where the GPU has no tensor units. + blend_mma: ?mtl.Pipeline = null, + /// The gates' intermediates for up to 1,024 rows of each of `max_gates` tuples. + scratch: mtl.Buffer, pub fn load(device: mtl.Device) !Pipelines { - return loadSource(device, sources.loop); + var out = try loadSource(device, sources.loop); + errdefer out.deinit(); + if (device.tensorUnits()) return out; + out.zeta_mma = try dense.Mma.loadSource(device, sources.dense_mma); + try out.loadMma(device, sources.loop_mma); + return out; + } + + /// The blend on simdgroup matrices from `text`; the contract's controls pass an edited one. + pub fn loadMma(p: *Pipelines, device: mtl.Device, text: []const u8) !void { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + p.blend_mma = try mtl.Pipeline.init(device, lib, "tf_ink2_loop_blend_mma", false); } pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); @@ -23,9 +47,20 @@ pub const Pipelines = struct { var messages = try mtl.Pipeline.init(device, lib, plan.Kind.messages.symbol(), false); errdefer messages.deinit(); const gate_pipeline = try mtl.Pipeline.init(device, lib, plan.Kind.gates.symbol(), false); - return .{ .messages = messages, .gates = gate_pipeline }; + errdefer gate_pipeline.deinit(); + const zeta = try mtl.Pipeline.init(device, lib, "tf_inkling2_loop_zeta", false); + errdefer zeta.deinit(); + const blend = try mtl.Pipeline.init(device, lib, "tf_inkling2_loop_blend", false); + errdefer blend.deinit(); + const scratch = try device.buffer(max_gates * 1024 * gate_row_bytes, mtl.ResourceOptions.shared); + return .{ .messages = messages, .gates = gate_pipeline, .zeta = zeta, .blend = blend, .scratch = scratch }; } pub fn deinit(p: *Pipelines) void { + if (p.blend_mma) |pipe| pipe.deinit(); + if (p.zeta_mma) |mma| mma.deinit(); + p.scratch.deinit(); + p.blend.deinit(); + p.zeta.deinit(); p.gates.deinit(); p.messages.deinit(); p.* = undefined; @@ -38,18 +73,73 @@ fn bind(e: mtl.ComputeEncoder, refs: []const Ref) void { /// Output layout is [token][12 core layers][q,k,v,mlp][H], all binary32. pub fn crossPassMessageAttention(p: *const Pipelines, e: mtl.ComputeEncoder, bank0: Ref, bank1: Ref, q_mlp: Ref, kv: Ref, out: Ref, rows: u32) void { - std.debug.assert(rows > 0 and rows <= 64); + std.debug.assert(rows > 0 and rows <= 1024); e.setPipeline(p.messages); bind(e, &.{ bank0, bank1, q_mlp, kv, out }); - e.setValue(RowsArgs{ .rows = rows }, 5); + e.setValue(GateArgs{ .rows = rows, .stride = hidden }, 5); e.dispatchGroups(mtl.Size.of(rows * message_entries, 1, 1), mtl.Size.of(256, 1, 1)); } +const GateArgs = extern struct { rows: u32, stride: u32 }; + /// One controller tuple; h, m and output are [token][H] binary32 tensors. pub fn gates(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, down: Ref, forget: Ref, gain: Ref, out: Ref, rows: u32) void { - std.debug.assert(rows > 0 and rows <= 64); - e.setPipeline(p.gates); - bind(e, &.{ h, m, down, forget, gain, out }); - e.setValue(RowsArgs{ .rows = rows }, 6); - e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + gatesStrided(p, e, h, m, down, forget, gain, out, rows, hidden); +} + +/// As gates, with row r's m at `m_stride` binary32 values from row r - 1's. +pub fn gatesStrided(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, down: Ref, forget: Ref, gain: Ref, out: Ref, rows: u32, m_stride: u32) void { + gatesEach(p, e, &.{.{ .h = h, .m = m, .down = down, .forget = forget, .gain = gain, .out = out }}, rows, m_stride); +} + +/// Controller tuples one call gates together: a visit's three attention roles. +pub const max_gates = 3; +pub const Gate = struct { h: Ref, m: Ref, down: Ref, forget: Ref, gain: Ref, out: Ref }; + +/// gatesStrided for each tuple a step at a time, a barrier between steps; the tuples' outputs must be distinct. +pub fn gatesEach(p: *const Pipelines, e: mtl.ComputeEncoder, items: []const Gate, rows: u32, m_stride: u32) void { + std.debug.assert(rows > 0 and rows <= 1024 and items.len > 0 and items.len <= max_gates); + const args = GateArgs{ .rows = rows, .stride = m_stride }; + for (items, 0..) |g, i| { + e.setPipeline(p.gates); + bind(e, &.{ g.h, g.m, normalizedOf(p, i) }); + e.setValue(args, 3); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + } + e.barrier(); + for (items, 0..) |g, i| { + // The same sums as zeta: a rank is a weight row of 2 H columns. + const call = dense.Call{ .rows = rows, .n = rank, .k = 2 * hidden, .ldy = rank }; + if (p.zeta_mma) |mma| if (dense.Mma.serves(call)) { + mma.launch(e, denseRef(normalizedOf(p, i)), denseRef(g.down), denseRef(zetaOf(p, i)), call); + continue; + }; + e.setPipeline(p.zeta); + bind(e, &.{ normalizedOf(p, i), g.down, zetaOf(p, i) }); + e.setValue(args, 3); + e.dispatchGroups(mtl.Size.of(rank / 8, rows, 1), mtl.Size.of(256, 1, 1)); + } + e.barrier(); + for (items, 0..) |g, i| { + bind(e, &.{ g.h, g.m, zetaOf(p, i), g.forget, g.gain, g.out }); + e.setValue(args, 6); + if (p.blend_mma) |pipe| if (rows >= dense.min_rows) { + e.setPipeline(pipe); + e.dispatchGroups(mtl.Size.of(hidden / 16, (rows + 15) / 16, 1), mtl.Size.of(32, 1, 1)); + continue; + }; + e.setPipeline(p.blend); + e.dispatchThreads(mtl.Size.of(hidden, rows, 1), mtl.Size.of(32, 1, 1)); + } +} + +fn denseRef(r: Ref) dense.Ref { + return .{ .buf = r.buf, .off = r.off }; +} + +fn normalizedOf(p: *const Pipelines, tuple: usize) Ref { + return .{ .buf = p.scratch, .off = tuple * 1024 * gate_row_bytes }; +} +fn zetaOf(p: *const Pipelines, tuple: usize) Ref { + return .{ .buf = p.scratch, .off = tuple * 1024 * gate_row_bytes + 1024 * 2 * hidden * 2 }; } diff --git a/zig/src/families/inkling2/metal/loop_plan.zig b/zig/src/families/inkling2/metal/loop_plan.zig index 86719e705b4..79fc638356a 100644 --- a/zig/src/families/inkling2/metal/loop_plan.zig +++ b/zig/src/families/inkling2/metal/loop_plan.zig @@ -33,7 +33,7 @@ pub const Call = struct { rows: usize, n: usize, k: usize }; pub const Geometry = struct { groups: usize, threads: u32 = 256, tg_memory: u32 }; pub fn valid(kind: Kind, c: Call) bool { - if (c.rows == 0 or c.rows > 64) return false; + if (c.rows == 0 or c.rows > 1024) return false; return switch (kind) { .messages => c.n == message_entries * hidden and c.k == hidden, .gates => c.n == hidden and c.k == rank, @@ -53,7 +53,7 @@ pub fn geometry(kind: Kind, c: Call) Geometry { }, .tg_memory = switch (kind) { .messages => 144, - .gates => 9552, + .gates => 80, }, }; } diff --git a/zig/src/families/inkling2/metal/metal.zig b/zig/src/families/inkling2/metal/metal.zig index bef58022713..735312a99c1 100644 --- a/zig/src/families/inkling2/metal/metal.zig +++ b/zig/src/families/inkling2/metal/metal.zig @@ -5,3 +5,4 @@ pub const glue = @import("glue.zig"); pub const experts = @import("experts.zig"); pub const experts_plan = @import("experts_plan.zig"); pub const loop = @import("loop.zig"); +pub const dense = @import("dense.zig"); diff --git a/zig/src/families/inkling2/metal/model.zig b/zig/src/families/inkling2/metal/model.zig index a60acf86d1e..114a6d64617 100644 --- a/zig/src/families/inkling2/metal/model.zig +++ b/zig/src/families/inkling2/metal/model.zig @@ -5,11 +5,12 @@ const sources = @import("kernel_sources"); const cfg = @import("../config.zig"); const layer_plan = @import("../plan.zig"); const ck = @import("../../../core/checkpoint_metal.zig"); -const shards = @import("core").checkpoint; +const shards = @import("core").checkpoint_host; const attention = @import("attention.zig"); const glue = @import("glue.zig"); const experts = @import("experts.zig"); const loop = @import("loop.zig"); +const dense = @import("dense.zig"); pub const Tensor = ck.Tensor; pub const DynamicConv = struct { static_w: Tensor, projection: Tensor }; @@ -203,6 +204,8 @@ pub const Model = struct { experts: experts.Pipelines, loop: loop.Pipelines, dense: [6]mtl.Pipeline, + /// A prompt's projections on simdgroup matrices, where the GPU has no tensor units. + dense_mma: ?dense.Mma, norm: mtl.Pipeline, runtime: [runtime_names.len]mtl.Pipeline, @@ -247,6 +250,8 @@ pub const Model = struct { errdefer m.experts.deinit(); m.loop = try loop.Pipelines.load(m.device); errdefer m.loop.deinit(); + m.dense_mma = try dense.Mma.load(m.device); + errdefer if (m.dense_mma) |mma| mma.deinit(); { const lib = try mtl.Library.fromSource(m.device, sources.spark25_glue, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); defer lib.deinit(); @@ -282,6 +287,7 @@ pub const Model = struct { for (m.runtime) |p| p.deinit(); m.norm.deinit(); for (m.dense) |p| p.deinit(); + if (m.dense_mma) |mma| mma.deinit(); m.loop.deinit(); m.experts.deinit(); m.glue.deinit(); diff --git a/zig/src/families/inkling2/metal/runtime_plan.zig b/zig/src/families/inkling2/metal/runtime_plan.zig index 4edc008967d..fcf93f4d5d4 100644 --- a/zig/src/families/inkling2/metal/runtime_plan.zig +++ b/zig/src/families/inkling2/metal/runtime_plan.zig @@ -4,7 +4,7 @@ const std = @import("std"); pub const hidden = 2304; pub const block_slots = 4; pub const tap_channels = 4; -pub const max_rows = 64; +pub const max_rows = 1024; pub const threads: u32 = 256; pub const RuntimeArgs = extern struct { count: u32, boundary: u32 }; diff --git a/zig/src/families/inkling2/metal/runtime_test.zig b/zig/src/families/inkling2/metal/runtime_test.zig index f8346da47e3..ee5396a5d56 100644 --- a/zig/src/families/inkling2/metal/runtime_test.zig +++ b/zig/src/families/inkling2/metal/runtime_test.zig @@ -78,15 +78,15 @@ test "Every visit and convolution role has disjoint persistent and staged bytes" if (slot != 0 or cs != 0) try std.testing.expect(off >= previous_persistent); previous_persistent = off + len; for (0..4) |accepted| { - const source = state.convByteOffset(slot, cs, accepted, 3 + state.max_rows); + const source = state.convByteOffset(slot, cs, accepted, state.stage_rows); try std.testing.expect(source + len <= state.taps_bytes); } }; try std.testing.expectEqual(state.conv_bytes, previous_persistent); // Decode acceptance k preserves exactly old[k], old[k+1], old[k+2] through raw[k..k+3]. for (0..state.window_rows + 1) |accepted| { - const old = state.convByteOffset(47, 3, 0, 3 + state.max_rows); - const selected = state.convByteOffset(47, 3, accepted, 3 + state.max_rows); + const old = state.convByteOffset(47, 3, 0, state.stage_rows); + const selected = state.convByteOffset(47, 3, accepted, state.stage_rows); try std.testing.expectEqual(old + accepted * state.hidden * 2, selected); } } diff --git a/zig/src/families/inkling2/metal/serving_test.zig b/zig/src/families/inkling2/metal/serving_test.zig index d78d6df3abd..ed39e48306a 100644 --- a/zig/src/families/inkling2/metal/serving_test.zig +++ b/zig/src/families/inkling2/metal/serving_test.zig @@ -294,3 +294,37 @@ test "Mini Metal opt-in DSpark drafting preserves target tokens and rolls back e try std.testing.expectEqual(@as(?u32, ids.len), restored.cached); try expectTokens(&refs.second.?, &restored); } + +test "Mini Metal fills a prompt a chunk a call to the whole pass's first row and features" { + const dir = try checkpoint(); + const ids = prompt(64, 5); + const cuts = [_]u32{ 20, 41 }; + const model = try Model.load(gpa, io, dir); + defer model.deinit(); + const target = try backend.Metal.init(gpa, model, .{ .capacity = context, .streams = 2, .budget = 2 * st.cacheBytes(context) }); + defer target.deinit(); + const b = target.backend(); + try b.vtable.prepare_features.?(b.ptr, &taps); + var whole = try lanes.Stream.init(gpa, .{ .id = "whole", .prompt = &ids, .max_new = made, .drafts = false, .logprobs = 3, .chunks = &cuts }); + defer whole.deinit(gpa); + try b.prefill(&whole); + defer b.release(&whole); + try std.testing.expectEqual(@as(u32, ids.len), whole.fill_at.load(.monotonic)); + var stepped = try lanes.Stream.init(gpa, .{ .id = "stepped", .prompt = &ids, .max_new = made, .drafts = false, .logprobs = 3, .chunks = &cuts }); + defer stepped.deinit(gpa); + defer b.release(&stepped); + var from: u32 = 0; + for ([_]u32{ 20, 41, ids.len }) |end| { + try std.testing.expectEqual(end == ids.len, try b.vtable.prefill_step.?(b.ptr, &stepped, 0)); + try std.testing.expectEqual(end, stepped.fill_at.load(.monotonic)); + // A chunk's rows are held until the next forward, and an earlier chunk's are not. + try std.testing.expectEqual(end - from, (try b.features(&stepped, &taps, from, end - from)).rows); + if (from > 0) try std.testing.expectError(error.Inkling2TapsNotHeld, b.features(&stepped, &taps, 0, from)); + from = end; + } + try std.testing.expectEqualSlices(u8, &(try featureRow(b, &whole, ids.len - 1)), &(try featureRow(b, &stepped, ids.len - 1))); + const whole_first = try b.read(try b.first(&whole, ids.len)); + const whole_row = try b.firstRow(&whole); + try std.testing.expectEqual(whole_first, try b.read(try b.first(&stepped, ids.len))); + try expectFirstRow(whole_row, try b.firstRow(&stepped)); +} diff --git a/zig/src/families/inkling2/metal/state.zig b/zig/src/families/inkling2/metal/state.zig index 01c2085e4b7..ff734d77f4f 100644 --- a/zig/src/families/inkling2/metal/state.zig +++ b/zig/src/families/inkling2/metal/state.zig @@ -6,8 +6,8 @@ const ap = @import("attention_plan.zig"); pub const window_rows = 16; pub const batch_rows = 32; -pub const prompt_rows = 64; -pub const max_rows = 64; +pub const prompt_rows = 1024; +pub const max_rows = 1024; pub const max_segments = batch_rows; pub const max_attention_stride = 64; pub const hidden = 2304; @@ -31,7 +31,13 @@ pub const sliding_ring = ap.ringFor(1024, max_rows); pub const conv_widths = [conv_states]usize{ 1024, 1024, 2304, 2304 }; pub const conv_row_values = 1024 + 1024 + 2304 + 2304; pub const conv_bytes = visit_slots * 3 * conv_row_values * 2; -pub const taps_bytes = visit_slots * (3 + max_rows) * conv_row_values * 2; +/// A cache stages a round's taps: three old rows and a window. A wider chunk stages in its scratch. +pub const stage_rows = 3 + window_rows; +pub const taps_bytes = visit_slots * stage_rows * conv_row_values * 2; +/// A scratch's staged taps for a chunk of up to `rows`; none where a cache's own staging holds them. +pub fn stageBytes(rows: usize) usize { + return if (rows > window_rows) visit_slots * (3 + rows) * conv_row_values * 2 else 0; +} pub fn globalSlots(capacity: usize) usize { return std.mem.alignForward(usize, capacity, ap.tile_keys); @@ -89,6 +95,8 @@ pub const Cache = struct { backup: mtl.Buffer, logits: mtl.Buffer, tap: Tap = .{}, + /// A stepped prompt chunk's rows, good until the next forward. + fill_tap: Tap = .{}, last_tap: ?mtl.Buffer = null, key_at: [visit_slots]usize, value_at: [visit_slots]usize, @@ -182,7 +190,7 @@ pub const Cache = struct { } pub fn staged(c: *const Cache, slot: usize, state: usize, rows_before: usize) Ref { - return .{ .buf = c.taps, .off = convByteOffset(slot, state, rows_before, 3 + max_rows) }; + return .{ .buf = c.taps, .off = convByteOffset(slot, state, rows_before, stage_rows) }; } pub fn attentionLayer(c: *const Cache, schedule: *const plan.Plan, slot: usize, rows: usize) ap.Layer { @@ -211,7 +219,7 @@ pub const Cache = struct { e.copy(c.backup, 0, c.conv, 0, conv_bytes); for (0..visit_slots) |slot| for (0..conv_states) |state| { const bytes = 3 * convWidth(state) * 2; - e.copy(c.taps, convByteOffset(slot, state, accepted, 3 + max_rows), c.conv, convByteOffset(slot, state, 0, 3), bytes); + e.copy(c.taps, convByteOffset(slot, state, accepted, stage_rows), c.conv, convByteOffset(slot, state, 0, 3), bytes); }; e.end(); cb.commit(); @@ -284,14 +292,14 @@ fn sizes(rows: usize) [fields.len]usize { r * h * fp, r * h * bf, r * h * bf, r * h * bf, r * q * bf, r * kv * bf, r * kv * bf, r * rel_width * bf, r * 24 * bf, r * q * bf, r * kv * bf, r * kv * bf, r * q * bf, r * rel_width * bf, r * 24 * ap.extent * bf, r * 24 * max_attention_stride * ap.head_dim * fp, r * 24 * max_attention_stride * 2 * fp, r * q * bf, r * h * bf, r * h * bf, r * h * bf, - r * experts_per_token * 4, r * experts_per_token * fp, r * experts_per_token * intermediate * bf, r * experts_per_token * h * bf, r * h * bf, r * h * bf, r * vocabulary * fp, + r * experts_per_token * 4, r * experts_per_token * fp, r * experts_per_token * intermediate * bf, r * experts_per_token * h * bf, r * h * bf, r * h * bf, @as(usize, @min(r, batch_rows)) * vocabulary * fp, }; } pub fn scratchBytes(rows: usize) usize { var out: usize = 0; for (sizes(rows)) |n| out += n; - return out; + return out + stageBytes(rows); } pub const Scratch = struct { @@ -339,6 +347,8 @@ pub const Scratch = struct { logits_all: mtl.Buffer, /// Opt-in DSpark features [row][tap][H], allocated by prepare_features. taps: ?mtl.Buffer = null, + /// The staged convolution taps of a chunk wider than a window: this scratch then holds one stream's rows. + stage: ?mtl.Buffer = null, rows: usize, pub fn init(device: mtl.Device, rows: usize) !Scratch { @@ -354,16 +364,22 @@ pub const Scratch = struct { } s.taps = null; s.rows = rows; + s.stage = if (stageBytes(rows) > 0) try device.buffer(stageBytes(rows), mtl.ResourceOptions.private) else null; return s; } pub fn deinit(s: *Scratch) void { inline for (fields) |f| @field(s, f).deinit(); if (s.taps) |b| b.deinit(); + if (s.stage) |b| b.deinit(); s.* = undefined; } + + pub fn staged(s: *const Scratch, slot: usize, state: usize, rows_before: usize) Ref { + return .{ .buf = s.stage.?, .off = convByteOffset(slot, state, rows_before, 3 + s.rows) }; + } }; comptime { - if (sliding_ring != 1088 or conv_bytes != 1916928) @compileError("Inkling cache geometry drift"); + if (sliding_ring != 2048 or conv_bytes != 1916928) @compileError("Inkling cache geometry drift"); } diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index ae6bfd08603..6391bfa51f1 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -25,6 +25,7 @@ pub const idol = @import("families/idol/idol.zig"); /// Unlimited-OCR-2 on Metal: document pages to text (its image encoder and decoder). pub const uocr = @import("families/uocr/uocr.zig"); pub const checkpoint = @import("core/checkpoint_metal.zig"); +pub const checkpoint_file_cache = @import("core/checkpoint_file_cache.zig"); pub const shard_edit = @import("core/shard_edit.zig"); pub const lora_merge = @import("core/lora_merge_dir.zig"); pub const npy = @import("core/npy.zig"); diff --git a/zig/tests/contract/metal_inkling2_attention.zig b/zig/tests/contract/metal_inkling2_attention.zig index 9b359464c85..7516ceb19d4 100644 --- a/zig/tests/contract/metal_inkling2_attention.zig +++ b/zig/tests/contract/metal_inkling2_attention.zig @@ -23,6 +23,8 @@ const rel_shapes = [_]c.Shape{ .{ .rows = 4, .n = H * EXTENT, .k = R }, .{ .rows const sliding_shapes = [_]c.Shape{ .{ .rows = 7, .n = H * D, .k = 1030 }, .{ .rows = 3, .n = H * D, .k = 2049 } }; const global_shapes = [_]c.Shape{ .{ .rows = 4, .n = H * D, .k = 1100 }, .{ .rows = 2, .n = H * D, .k = 1030 } }; const prompt_shapes = [_]c.Shape{ .{ .rows = 8, .n = H * D, .k = 1100 }, .{ .rows = 64, .n = H * D, .k = 80 } }; +/// A window that starts inside a tile, one that wraps the ring, and one not yet full. +const prompt_sliding_shapes = [_]c.Shape{ .{ .rows = 8, .n = H * D, .k = 1100 }, .{ .rows = 64, .n = H * D, .k = 2049 }, .{ .rows = 64, .n = H * D, .k = 80 } }; fn depth(s: c.Shape) usize { return D + 4 * s.k + 64; } @@ -62,6 +64,14 @@ fn spec(w: Which) c.Spec { s.name = "metal inkling2 prompt pre-m5 tf_ink2_attn_prompt"; s.served = &prompt_shapes; }, + .prompt_sliding_m5 => { + s.name = "metal inkling2 prompt m5 sliding tf_ink2_attn_prompt"; + s.served = &prompt_sliding_shapes; + }, + .prompt_sliding_pre_m5 => { + s.name = "metal inkling2 prompt pre-m5 sliding tf_ink2_attn_prompt"; + s.served = &prompt_sliding_shapes; + }, } return s; } @@ -163,7 +173,7 @@ pub const Probe = struct { pml: rig_.Ref = undefined, pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, w: Which, m: Mutation) !Probe { - const plain = if (controls.isPrompt(w)) (if (w == .prompt_pre_m5) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; + const plain = if (controls.isPrompt(w)) (if (controls.isPre(w)) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; const text = try controls.apply(a, plain, m); defer a.free(text); var lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); @@ -226,9 +236,10 @@ pub const Probe = struct { p.rig.reset(); p.shape = s; p.fill = fill; - const global = p.which == .prep_global or p.which == .decode_global or controls.isPrompt(p.which); - const sliding = p.which == .prep_sliding or p.which == .decode_sliding; - p.layer = .{ .window = if (sliding) 1024 else 0, .ring = 2048, .chunk = if (sliding) 256 else plan.global_chunk, .tau = global }; + const tiled = controls.isPromptSliding(p.which); + const global = p.which == .prep_global or p.which == .decode_global or (controls.isPrompt(p.which) and !tiled); + const sliding = p.which == .prep_sliding or p.which == .decode_sliding or tiled; + p.layer = .{ .window = if (sliding) 1024 else 0, .ring = 2048, .chunk = if (tiled) plan.tile_keys else if (sliding) 256 else plan.global_chunk, .tau = global }; const rows = s.rows; const rh = rows * H; const cache = KV * p.layer.ring * D; @@ -369,9 +380,9 @@ pub const Probe = struct { e.setBuffer(p.pml.buf, p.pml.off, 6); const sc: f32 = 1.0 / @sqrt(@as(f32, D)); if (controls.isPrompt(p.which)) { - e.setValue(plan.PromptArgs{ .heads = H, .kv_heads = KV, .ring = ring, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride, .scale = sc }, 7); - const blocks = (rows * (H / KV) + plan.prompt_pairs - 1) / plan.prompt_pairs; - e.dispatchGroups(mtl.Size.of(blocks, KV, stride), mtl.Size.of(256, 1, 1)); + const launch = try plan.attend(.{ .rows = @intCast(rows), .last_pos = @intCast(p.shape.k - 1), .prompt = p.layer.window > 0 }, p.layer, stride, 0); + e.setValue(plan.PromptArgs{ .heads = H, .kv_heads = KV, .ring = ring, .chunk = p.layer.chunk, .c0 = launch.c0, .chunks = stride, .scale = sc, .window = p.layer.window }, 7); + e.dispatchGroups(mtl.Size.of(launch.grid[0], launch.grid[1], launch.grid[2]), mtl.Size.of(256, 1, 1)); } else { e.setBuffer(p.meta[0].buf, p.meta[0].off, 7); e.setBuffer(p.meta[1].buf, p.meta[1].off, 8); @@ -519,8 +530,8 @@ pub const Probe = struct { fn supported(device: mtl.Device, w: Which) bool { return switch (w) { - .prompt_m5 => device.tensorUnits(), - .prompt_pre_m5 => !device.tensorUnits(), + .prompt_m5, .prompt_sliding_m5 => device.tensorUnits(), + .prompt_pre_m5, .prompt_sliding_pre_m5 => !device.tensorUnits(), else => true, }; } diff --git a/zig/tests/contract/metal_inkling2_attention_controls.zig b/zig/tests/contract/metal_inkling2_attention_controls.zig index f4b9cc69cb9..87510911e20 100644 --- a/zig/tests/contract/metal_inkling2_attention_controls.zig +++ b/zig/tests/contract/metal_inkling2_attention_controls.zig @@ -2,17 +2,25 @@ const std = @import("std"); const contract = @import("contract"); -pub const Which = enum { prep_sliding, prep_global, rel_table, decode_sliding, decode_global, prompt_m5, prompt_pre_m5 }; +pub const Which = enum { prep_sliding, prep_global, rel_table, decode_sliding, decode_global, prompt_m5, prompt_pre_m5, prompt_sliding_m5, prompt_sliding_pre_m5 }; pub fn function(w: Which) []const u8 { return switch (w) { .prep_sliding, .prep_global => "tf_ink2_prep", .rel_table => "tf_ink2_rel_table", .decode_sliding, .decode_global => "tf_ink2_attn_scalar", - .prompt_m5, .prompt_pre_m5 => "tf_ink2_attn_prompt", + .prompt_m5, .prompt_pre_m5, .prompt_sliding_m5, .prompt_sliding_pre_m5 => "tf_ink2_attn_prompt", }; } pub fn isPrompt(w: Which) bool { - return w == .prompt_m5 or w == .prompt_pre_m5; + return w == .prompt_m5 or w == .prompt_pre_m5 or isPromptSliding(w); +} +/// The prompt kernel on a sliding layer: a window of keys a row, a tile of keys a chunk. +pub fn isPromptSliding(w: Which) bool { + return w == .prompt_sliding_m5 or w == .prompt_sliding_pre_m5; +} +/// The prompt kernel built for chips before the M5. +pub fn isPre(w: Which) bool { + return w == .prompt_pre_m5 or w == .prompt_sliding_pre_m5; } pub fn isAttention(w: Which) bool { return w == .decode_sliding or w == .decode_global or isPrompt(w); @@ -27,6 +35,8 @@ pub const Mutation = enum { merge_no_sink, prompt_late_bias, prompt_pre_late_bias, + prompt_wide_window, + prompt_pre_wide_window, pub fn name(m: Mutation) []const u8 { return switch (m) { .none => "", @@ -37,6 +47,8 @@ pub const Mutation = enum { .merge_no_sink => "control: metal inkling2 attention global merge without sink tf_ink2_merge", .prompt_late_bias => "control: metal inkling2 prompt m5 first key bias boosted tf_ink2_attn_prompt", .prompt_pre_late_bias => "control: metal inkling2 prompt pre-m5 first key bias boosted tf_ink2_attn_prompt", + .prompt_wide_window => "control: metal inkling2 prompt m5 sliding window half as long tf_ink2_attn_prompt", + .prompt_pre_wide_window => "control: metal inkling2 prompt pre-m5 sliding window half as long tf_ink2_attn_prompt", }; } pub fn gate(m: Mutation) ?contract.gates.Gate { @@ -52,6 +64,8 @@ pub const Mutation = enum { .merge_no_sink => .decode_global, .prompt_late_bias => .prompt_m5, .prompt_pre_late_bias => .prompt_pre_m5, + .prompt_wide_window => .prompt_sliding_m5, + .prompt_pre_wide_window => .prompt_sliding_pre_m5, }; } const Edit = struct { from: []const u8, to: []const u8 }; @@ -82,6 +96,10 @@ pub const Mutation = enum { .from = "const float bias = live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f;", .to = "const float bias = (live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f) + (live && kp == b_lo ? 128.0f : 0.0f);", }, + .prompt_wide_window, .prompt_pre_wide_window => .{ + .from = "(a.window == 0u || kp + a.window > pos);", + .to = "(a.window == 0u || kp + a.window / 2u > pos);", + }, }; } }; @@ -99,7 +117,7 @@ test "Inkling 2 attention controls each hit one live statement and cannot apply for (std.enums.values(Mutation)) |m| { if (m == .none) continue; const w = m.which(); - const plain = if (isPrompt(w)) (if (w == .prompt_pre_m5) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; + const plain = if (isPrompt(w)) (if (isPre(w)) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; const edited = try apply(a, plain, m); defer a.free(edited); try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); diff --git a/zig/tests/contract/metal_inkling2_blend_mma.zig b/zig/tests/contract/metal_inkling2_blend_mma.zig new file mode 100644 index 00000000000..e8b0fa9e86c --- /dev/null +++ b/zig/tests/contract/metal_inkling2_blend_mma.zig @@ -0,0 +1,173 @@ +//! Inkling 2 Mini's loop blend on simdgroup matrices: each output equals the scalar blend's, byte for byte. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const loop = @import("tensorfold").inkling2_metal_host.loop; +const controls = @import("metal_inkling2_blend_mma_controls.zig"); +const src = @import("inkling2_metal"); + +const name = "metal inkling2 mma tf_ink2_loop_blend_mma"; +const hidden = 2304; +const rank = 64; +/// The scalar kernel's arguments: rows, and floats from one row's message to the next. +const Args = extern struct { rows: u32, stride: u32 }; +const stride = 2 * hidden; + +fn depth(_: c.Shape) usize { + return rank; +} + +pub fn spec(control: bool) c.Spec { + return .{ + .name = if (control) controls.Mutation.ranks.name() else name, + .accum = .none, + .depth = depth, + .out = .f32, + .replaces = "tf_inkling2_loop_blend, on the same tables, zeta and rows", + .nan = .{ .stated = "every output equals the scalar blend's: a non-finite input has the same class" }, + // Rows go 16 a tile; 37 rows leave the last tile part full. + .tiles = .{ .{ .size = 16 }, .{}, .{} }, + .served = &.{ .{ .rows = 16, .n = hidden, .k = rank }, .{ .rows = 37, .n = hidden, .k = rank } }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "the scalar blend's fp32 sums are the baseline, bit for bit" }, + }; +} + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: loop.Pipelines, + control: bool, + shape: c.Shape = undefined, + refs: [6]rig_.Ref = undefined, + baseline: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, control: bool) !Probe { + const text = try controls.apply(a, if (control) .ranks else .none); + defer a.free(text); + var pipes = try loop.Pipelines.loadSource(device, src.loop); + errdefer pipes.deinit(); + try pipes.loadMma(device, text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = pipes, .control = control }; + } + + pub fn deinit(p: *Probe) void { + p.rig.reset(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.control), .ctx = p, .vt = &vt, .control = if (p.control) .shapes else null }; + } + const vt = g.hooks(Probe); + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > 64 or shape.n != hidden or shape.k != rank) return false; + p.rig.reset(); + p.shape = shape; + const rows = shape.rows; + const padded = (rows + 15) / 16 * 16; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const h = try p.a.alloc(f32, rows * hidden); + defer p.a.free(h); + const m = try p.a.alloc(f32, rows * stride); + defer p.a.free(m); + // Zeta's tile rows past the call are read and not stored. + const zeta = try p.a.alloc(u16, padded * rank); + defer p.a.free(zeta); + const forget = try p.a.alloc(u16, hidden * rank); + defer p.a.free(forget); + const gain = try p.a.alloc(u16, hidden * rank); + defer p.a.free(gain); + for (h) |*v| v.* = (rng.float(f32) * 2 - 1) * 3; + for (m) |*v| v.* = (rng.float(f32) * 2 - 1) * 3; + for (zeta) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); + for (forget) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 0.4); + for (gain) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 0.4); + if (fill == .nonfinite) { + h[0] = std.math.nan(f32); + m[1] = std.math.inf(f32); + zeta[2] = c.toBf16(-std.math.inf(f32)); + } + const bytes = std.mem.sliceAsBytes; + const out = try p.rig.output(p.count() * 4); + p.refs = .{ try p.rig.input(bytes(h)), try p.rig.input(bytes(m)), try p.rig.input(bytes(zeta)), try p.rig.input(bytes(forget)), try p.rig.input(bytes(gain)), out }; + p.baseline = try p.rig.scratch(p.count() * 4); + return true; + } + + fn launch(p: *Probe, out: rig_.Ref, scalar: bool) !void { + const pass = p.rig.begin(); + const e = pass.e; + for (p.refs[0..5], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(out.buf, out.off, 5); + e.setValue(Args{ .rows = @intCast(p.shape.rows), .stride = stride }, 6); + if (scalar) { + e.setPipeline(p.pipes.blend); + e.dispatchThreads(mtl.Size.of(hidden, p.shape.rows, 1), mtl.Size.of(32, 1, 1)); + } else { + e.setPipeline(p.pipes.blend_mma.?); + e.dispatchGroups(mtl.Size.of(hidden / 16, (p.shape.rows + 15) / 16, 1), mtl.Size.of(32, 1, 1)); + } + try p.rig.finish(pass); + } + + pub fn run(p: *Probe) !void { + try p.launch(p.refs[5], false); + } + + pub fn replaced(p: *Probe) ![]const u8 { + try p.launch(p.baseline, true); + return p.rig.bytes(p.baseline, p.count() * 4); + } + + pub fn count(p: *const Probe) usize { + return p.shape.rows * hidden; + } + + pub fn reference(_: *Probe, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + + /// Non-finite inputs: every output has the scalar blend's class, and a finite one its bytes. + pub fn check(p: *Probe, _: g.Gate) !?[]const u8 { + const got = try p.rig.outputBytes(); + const want = try p.replaced(); + for (0..p.count()) |i| { + const a: f32 = @bitCast(std.mem.readInt(u32, got[4 * i ..][0..4], .little)); + const b: f32 = @bitCast(std.mem.readInt(u32, want[4 * i ..][0..4], .little)); + if (std.math.isNan(a) and std.math.isNan(b)) continue; + if (@as(u32, @bitCast(a)) != @as(u32, @bitCast(b))) return "an output differs from the scalar blend's"; + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [2]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + /// The entry exists where the GPU has no tensor units, the only GPUs whose loader builds the kernel. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (s.device.tensorUnits()) return; + for ([_]bool{ false, true }) |control| { + if (only) |needle| if (std.mem.indexOf(u8, spec(control).name, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + } + } +}; diff --git a/zig/tests/contract/metal_inkling2_blend_mma_controls.zig b/zig/tests/contract/metal_inkling2_blend_mma_controls.zig new file mode 100644 index 00000000000..1697b08937b --- /dev/null +++ b/zig/tests/contract/metal_inkling2_blend_mma_controls.zig @@ -0,0 +1,39 @@ +//! Count-checked mutation of the simdgroup-matrix loop blend: the ranks added in another order. +const std = @import("std"); +const src = @import("inkling2_metal"); +const g = @import("contract").gates; + +pub const Mutation = enum { + none, + ranks, + + pub fn name(m: Mutation) []const u8 { + return if (m == .none) "" else "control: metal inkling2 mma tf_ink2_loop_blend_mma ranks added in reverse"; + } + + pub fn gate(m: Mutation) ?g.Gate { + return if (m == .none) null else .shapes; + } + + const from = "for (uint o = 0u; o < INKLING_LOOP_RANK / 8u; ++o)"; + const to = "for (uint o = INKLING_LOOP_RANK / 8u; o-- != 0u;)"; +}; + +pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, src.loop_mma); + if (std.mem.count(u8, src.loop_mma, Mutation.from) != 1) return error.ControlEditCount; + return std.mem.replaceOwned(u8, a, src.loop_mma, Mutation.from, Mutation.to); +} + +test "the blend control edits exactly its rank loop" { + const a = std.testing.allocator; + const edited = try apply(a, .ranks); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, Mutation.to) != null); + try std.testing.expect(std.mem.indexOf(u8, edited, Mutation.from) == null); + try std.testing.expectEqual(g.Gate.shapes, Mutation.ranks.gate().?); + const plain = try apply(a, .none); + defer a.free(plain); + try std.testing.expectEqualStrings(src.loop_mma, plain); + try std.testing.expect(std.mem.indexOf(u8, src.loop_mma, "tf_ink2_loop_blend_mma") != null); +} diff --git a/zig/tests/contract/metal_inkling2_controls_host.zig b/zig/tests/contract/metal_inkling2_controls_host.zig index f60081c09ce..346500af713 100644 --- a/zig/tests/contract/metal_inkling2_controls_host.zig +++ b/zig/tests/contract/metal_inkling2_controls_host.zig @@ -4,6 +4,10 @@ test { _ = @import("metal_inkling2_attention_controls.zig"); _ = @import("metal_inkling2_glue_controls.zig"); _ = @import("metal_inkling2_experts_controls.zig"); + _ = @import("metal_inkling2_units_controls.zig"); + _ = @import("metal_inkling2_mma_controls.zig"); + _ = @import("metal_inkling2_dense_mma_controls.zig"); + _ = @import("metal_inkling2_blend_mma_controls.zig"); _ = @import("metal_inkling2_loop_controls.zig"); _ = @import("metal_inkling2_runtime_controls.zig"); _ = @import("metal_inkling2_dspark_controls.zig"); diff --git a/zig/tests/contract/metal_inkling2_dense_mma.zig b/zig/tests/contract/metal_inkling2_dense_mma.zig new file mode 100644 index 00000000000..284ce642f19 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dense_mma.zig @@ -0,0 +1,239 @@ +//! Inkling 2 Mini's projections on simdgroup matrices: each output equals the matvec kernel it replaces, byte for byte. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); +const tf = @import("tensorfold").inkling2_metal_host; +const dense = tf.dense; +const loop = tf.loop; +const controls = @import("metal_inkling2_dense_mma_controls.zig"); +const src = @import("inkling2_metal"); + +/// `project`'s widths, or the loop gate's down projection over the normalized [h | m] row. +pub const Kind = enum { project, zeta }; + +const name = "metal inkling2 mma tf_ink2_dense_mma"; + +fn label(k: Kind, control: bool) []const u8 { + if (control) return (if (k == .project) controls.Mutation.halves else controls.Mutation.groups).name(); + return if (k == .project) name else name ++ " as loop zeta"; +} + +fn depth(s: c.Shape) usize { + return s.k; +} + +/// The matvec's arguments and the loop's: rows, n, k and the output stride; rows and the row stride. +const MatvecArgs = extern struct { rows: u32, n: u32, k: u32, ldy: u32 }; +const ZetaArgs = extern struct { rows: u32, stride: u32 }; + +const project_shapes = [_]c.Shape{ .{ .rows = 16, .n = 24, .k = 2304 }, .{ .rows = 45, .n = 64, .k = 3072 }, .{ .rows = 100, .n = 16, .k = 2304 } }; +const zeta_shapes = [_]c.Shape{ .{ .rows = 16, .n = 64, .k = 4608 }, .{ .rows = 37, .n = 64, .k = 4608 } }; + +pub fn spec(k: Kind, control: bool) c.Spec { + return .{ + .name = label(k, control), + .accum = .none, + .depth = depth, + .out = .bf16, + .replaces = if (k == .project) "the bf16 matvec kernels sp_matvec_*, on the same weights and rows" else "tf_inkling2_loop_zeta, on the same weights and rows", + .nan = .{ .stated = "every output equals the replaced kernel's: a non-finite sum has the same class" }, + // Rows go 16 a tile, outputs 16 a tile and columns 256 a step; 45 rows and 24 outputs leave a tile part full. + .tiles = .{ .{ .size = 16 }, .{ .size = 16, .step = 8, .min = 8 }, .{} }, + .served = if (k == .project) &project_shapes else &zeta_shapes, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "the replaced kernel's fp32 sums are the baseline, bit for bit" }, + }; +} + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + mma: dense.Mma, + matvec: [6]mtl.Pipeline, + zeta: loop.Pipelines, + kind: Kind, + control: bool, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u16 = &.{}, + refs: [3]rig_.Ref = undefined, + baseline: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, control: bool) !Probe { + const text = try controls.apply(a, if (!control) .none else if (kind == .project) .halves else .groups); + defer a.free(text); + const mma = try dense.Mma.loadSource(device, text); + errdefer mma.deinit(); + // The loader's library: precise functions, one pipeline for each row count `dense` rounds up to. + const lib = try mtl.Library.fromSource(device, sources.spark25_glue, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + var matvec: [6]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (matvec[0..made]) |p| p.deinit(); + for ([_]u32{ 1, 2, 4, 8, 16, 32 }, 0..) |rows, i| { + var buf: [32]u8 = undefined; + matvec[i] = try mtl.Pipeline.init(device, lib, try std.fmt.bufPrintSentinel(&buf, "sp_matvec_{d}", .{rows}, 0), false); + made += 1; + } + var zeta = try loop.Pipelines.loadSource(device, src.loop); + errdefer zeta.deinit(); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .mma = mma, .matvec = matvec, .zeta = zeta, .kind = kind, .control = control }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.x = &.{}; + p.w = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.zeta.deinit(); + for (p.matvec) |m| m.deinit(); + p.mma.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.kind, p.control), .ctx = p, .vt = &vt, .control = if (p.control) .shapes else null }; + } + const vt = g.hooks(Probe); + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const widths: []const usize = if (p.kind == .project) &.{ 2304, 3072 } else &.{4608}; + const fits = for (widths) |k| { + if (shape.k == k) break true; + } else false; + // The loop's zeta kernel stores 64 ranks a row whatever the call. + if (!fits or shape.rows == 0 or shape.rows > 128 or shape.n == 0 or shape.n % 8 != 0 or shape.n > 128) return false; + if (p.kind == .zeta and shape.n != 64) return false; + p.clear(); + p.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.x = try p.a.alloc(u16, shape.rows * shape.k); + p.w = try p.a.alloc(u16, shape.n * shape.k); + for (p.x) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); + for (p.w) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); + // Huge terms that cancel (+2^20, -2^20) leave the small terms' sum less what each order of adding lost. + var marked = try p.a.alloc(bool, shape.k); + defer p.a.free(marked); + @memset(marked, false); + for (0..8) |j| { + const a = (37 + 331 * j) % shape.k; + const b = (a + 163) % shape.k; + if (marked[a] or marked[b]) continue; + marked[a] = true; + marked[b] = true; + for (0..shape.rows) |r| p.x[r * shape.k + a] = c.toBf16(1048576); + for (0..shape.rows) |r| p.x[r * shape.k + b] = c.toBf16(1048576); + for (0..shape.n) |n| { + p.w[n * shape.k + a] = c.toBf16(1); + p.w[n * shape.k + b] = c.toBf16(-1); + } + } + if (fill == .nonfinite) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.w)); + p.refs[2] = try p.rig.output(p.count() * 2); + p.baseline = try p.rig.scratch(p.count() * 2); + return true; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + p.mma.launch(pass.e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), .{ .rows = @intCast(p.shape.rows), .n = @intCast(p.shape.n), .k = @intCast(p.shape.k), .ldy = @intCast(p.shape.n) }); + try p.rig.finish(pass); + } + + fn hr(r: rig_.Ref) dense.Ref { + return .{ .buf = r.buf, .off = r.off }; + } + + /// The kernels it replaces: `dense`'s launches of up to 32 rows, or the loop's zeta. + pub fn replaced(p: *Probe) ![]const u8 { + const pass = p.rig.begin(); + const e = pass.e; + const rows = p.shape.rows; + const k = p.shape.k; + const n = p.shape.n; + if (p.kind == .zeta) { + e.setPipeline(p.zeta.zeta); + e.setBuffer(p.refs[0].buf, p.refs[0].off, 0); + e.setBuffer(p.refs[1].buf, p.refs[1].off, 1); + e.setBuffer(p.baseline.buf, p.baseline.off, 2); + e.setValue(ZetaArgs{ .rows = @intCast(rows), .stride = 0 }, 3); + e.dispatchGroups(mtl.Size.of(n / 8, rows, 1), mtl.Size.of(256, 1, 1)); + } else { + var base: usize = 0; + while (base < rows) { + const take: usize = @min(rows - base, 32); + const variant: usize = if (take > 16) 5 else if (take > 8) 4 else if (take > 4) 3 else if (take > 2) 2 else if (take > 1) 1 else 0; + e.setPipeline(p.matvec[variant]); + e.setBuffer(p.refs[0].buf, p.refs[0].off + base * k * 2, 0); + e.setBuffer(p.refs[1].buf, p.refs[1].off, 1); + e.setValue(MatvecArgs{ .rows = @intCast(take), .n = @intCast(n), .k = @intCast(k), .ldy = @intCast(n) }, 2); + e.setBuffer(p.baseline.buf, p.baseline.off + base * n * 2, 3); + e.dispatchGroups(mtl.Size.of((n + 7) / 8, 1, 1), mtl.Size.of(256, 1, 1)); + base += take; + } + } + try p.rig.finish(pass); + return p.rig.bytes(p.baseline, p.count() * 2); + } + + pub fn count(p: *const Probe) usize { + return p.shape.rows * p.shape.n; + } + + pub fn reference(_: *Probe, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + + /// Non-finite inputs: every output has the replaced kernel's class, and a finite one its bytes. + pub fn check(p: *Probe, _: g.Gate) !?[]const u8 { + const got = try p.rig.outputBytes(); + const want = try p.replaced(); + for (0..p.count()) |i| { + const a = c.fromBf16(std.mem.readInt(u16, got[2 * i ..][0..2], .little)); + const b = c.fromBf16(std.mem.readInt(u16, want[2 * i ..][0..2], .little)); + if (std.math.isNan(a) and std.math.isNan(b)) continue; + if (@as(u32, @bitCast(a)) != @as(u32, @bitCast(b))) return "an output differs from the replaced kernel's"; + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [4]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + /// The entries exist where the GPU has no tensor units; the units kernels serve the projections on the others. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (s.device.tensorUnits()) return; + for (std.enums.values(Kind)) |kind| for ([_]bool{ false, true }) |control| { + if (only) |needle| if (std.mem.indexOf(u8, label(kind, control), needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, kind, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + }; + } +}; diff --git a/zig/tests/contract/metal_inkling2_dense_mma_controls.zig b/zig/tests/contract/metal_inkling2_dense_mma_controls.zig new file mode 100644 index 00000000000..9124b85caba --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dense_mma_controls.zig @@ -0,0 +1,59 @@ +//! Count-checked mutations of the simdgroup-matrix projection: each moves one rounding in the sums. +const std = @import("std"); +const src = @import("inkling2_metal"); +const g = @import("contract").gates; + +pub const Mutation = enum { + none, + halves, + groups, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .halves => "control: metal inkling2 mma tf_ink2_dense_mma halves added one by one", + .groups => "control: metal inkling2 mma tf_ink2_dense_mma as loop zeta groups added in a line", + }; + } + + pub fn gate(m: Mutation) ?g.Gate { + return if (m == .none) null else .shapes; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .halves => .{ + .from = "acc[i][j][c].thread_elements()[0] += d0.thread_elements()[0] + d1.thread_elements()[0];", + .to = "acc[i][j][c].thread_elements()[0] = (acc[i][j][c].thread_elements()[0] + d0.thread_elements()[0]) + d1.thread_elements()[0];", + }, + .groups => .{ + .from = "(part[0][i][j][m][n] + part[1][i][j][m][n]) + (part[2][i][j][m][n] + part[3][i][j][m][n])", + .to = "((part[0][i][j][m][n] + part[1][i][j][m][n]) + part[2][i][j][m][n]) + part[3][i][j][m][n]", + }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, src.dense_mma); + const change = m.edit(); + if (std.mem.count(u8, src.dense_mma, change.from) != 1) return error.ControlEditCount; + return std.mem.replaceOwned(u8, a, src.dense_mma, change.from, change.to); +} + +test "every simdgroup-matrix projection control edits exactly its planted arithmetic" { + const a = std.testing.allocator; + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const edited = try apply(a, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectEqual(g.Gate.shapes, m.gate().?); + try std.testing.expect(std.mem.startsWith(u8, m.name(), "control: metal inkling2 mma tf_ink2_dense_mma")); + } + const plain = try apply(a, .none); + defer a.free(plain); + try std.testing.expectEqualStrings(src.dense_mma, plain); +} diff --git a/zig/tests/contract/metal_inkling2_dense_units.zig b/zig/tests/contract/metal_inkling2_dense_units.zig new file mode 100644 index 00000000000..2ebf6bc0ba3 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dense_units.zig @@ -0,0 +1,181 @@ +//! Inkling 2 Mini's prompt projections on the tensor units: an FP64 dot of BF16 values, stored as BF16. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const bf = contract.bf16_round.bf16; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.experts; +const controls = @import("metal_inkling2_units_controls.zig"); +const src = @import("inkling2_metal"); + +/// The columns the kernel takes: the hidden width, and the query width `wo` reads. +const widths = [_]usize{ 2304, 3072 }; +pub const name = "metal inkling2 units tf_ink2_dense_units"; + +fn depth(s: c.Shape) usize { + return s.k + 3; +} + +pub fn spec(control: bool) c.Spec { + return .{ + .name = if (control) controls.Mutation.dense_store.name() else name, + .accum = .f32, + .depth = depth, + .ops = 3, + .out = .bf16, + // Rows go 16 a band and outputs 32 a tile; 24 and 90 outputs leave the last tile part full. + .tiles = .{ .{ .size = 16 }, .{ .size = 32 }, .{} }, + .served = &.{ .{ .rows = 1, .n = 64, .k = 2304 }, .{ .rows = 8, .n = 24, .k = 2304 }, .{ .rows = 20, .n = 90, .k = 3072 } }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "independent FP64 terms and one BF16 store" }, + }; +} + +const Sim = struct { acc: c.Accum, order: g.Order }; +const Sample = struct { value: f64, magnitude: f64 }; + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: host.Pipelines, + control: bool, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u16 = &.{}, + refs: [3]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, control: bool) !Probe { + const text = try controls.apply(a, if (control) .dense_store else .none); + defer a.free(text); + var pipes = try host.Pipelines.loadSource(device, src.experts); + errdefer pipes.deinit(); + try pipes.loadUnits(device, text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = pipes, .control = control }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.x = &.{}; + p.w = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.control), .ctx = p, .vt = &vt, .control = if (p.control) controls.Mutation.dense_store.gate() else null }; + } + const vt = blk: { + var table = g.hooks(Probe); + table.check = null; + break :blk table; + }; + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > 40 or shape.n == 0 or shape.n > 128 or std.mem.indexOfScalar(usize, &widths, shape.k) == null) return false; + p.clear(); + p.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.x = try p.a.alloc(u16, shape.rows * shape.k); + p.w = try p.a.alloc(u16, shape.n * shape.k); + for (p.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 7 == 0) @as(f32, 3) else 1)); + for (p.w) |*v| v.* = c.toBf16(rng.float(f32) * 0.5 - 0.25); + if (fill == .stress) { + // Whole numbers times a power of two: every product and partial sum is exact. + for (p.x, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(128 * (1 + i % 13))) * (if (i >= p.x.len / 2) @as(f32, -1) else 1)); + for (p.w, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(@as(i32, @intCast(i % 7)) - 3)) * 0x1p-20); + } + if (fill == .nonfinite and p.x.len >= 3) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.w)); + p.refs[2] = try p.rig.output(p.count() * 2); + return true; + } + + fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + try host.denseUnits(&p.pipes, pass.e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), @intCast(p.shape.rows), @intCast(p.shape.n), @intCast(p.shape.k)); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return p.shape.rows * p.shape.n; + } + + fn evaluate(p: *const Probe, at: usize, sim: ?Sim) Sample { + const row = at / p.shape.n; + const v = at % p.shape.n; + const k = p.shape.k; + var store: [3072]f64 = undefined; + const terms = store[0..k]; + var magnitude: f64 = 0; + for (terms, 0..) |*term, d| { + term.* = @as(f64, c.fromBf16(p.w[v * k + d])) * @as(f64, c.fromBf16(p.x[row * k + d])); + magnitude += @abs(term.*); + } + const sum = if (sim) |s| rows.sumIn(s.acc, s.order, terms) else blk: { + var total: f64 = 0; + for (terms) |term| total += term; + break :blk total; + }; + return .{ .value = bf(sum), .magnitude = magnitude }; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*v, *m, i| { + const sample = p.evaluate(i, null); + v.* = sample.value; + m.* = sample.magnitude; + } + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + for (out, 0..) |*v, i| v.* = p.evaluate(i, .{ .acc = acc, .order = order }).value; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [2]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + /// The entry exists only where the GPU has tensor units; elsewhere a prompt's rows take the shared matvec. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (!s.device.tensorUnits()) return; + for ([_]bool{ false, true }) |control| { + const label = spec(control).name; + if (only) |needle| if (std.mem.indexOf(u8, label, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + } + } +}; + +test "the dense entry resolves to its symbol in the units source" { + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 units ")); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.experts_units, "tf_ink2_dense_units(")); +} diff --git a/zig/tests/contract/metal_inkling2_experts_controls.zig b/zig/tests/contract/metal_inkling2_experts_controls.zig index e28ae1f9cd3..b21fc9fb14f 100644 --- a/zig/tests/contract/metal_inkling2_experts_controls.zig +++ b/zig/tests/contract/metal_inkling2_experts_controls.zig @@ -38,12 +38,9 @@ pub const Mutation = enum { .mx_gu_up => .{ .from = "const uint gr = 2u * n, ur = gr + 1u;", .to = "const uint gr = 2u * n, ur = gr;" }, .nv_down_phi => .{ .from = "const float phi = ink2_phi(amax, denominator, expert);", .to = "const float phi = precise::divide(2.0f * amax[expert], denominator[0]);" }, .nv_decode_nibble => .{ .from = "W[row * (a.k / 2u) + col / 2u], col,", .to = "W[row * (a.k / 2u) + col / 2u], col + 1u," }, - .mx_down_scale => .{ .from = "S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k));", .to = "S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, a.k));" }, + .mx_down_scale => .{ .from = "S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k, lane);", .to = "S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, a.k, lane);" }, .mx_decode_scale => .{ .from = "S[row * (a.k / 32u) + col / 32u]", .to = "S[row * (a.k / 32u) + col / 16u]" }, - .combine_slot_order => .{ - .from = "for (uint expert = 0; expert < a.experts; ++expert)\n for (uint slot = 0; slot < a.topk; ++slot)\n if (uint(ids[group * a.topk + slot]) == expert)\n sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]);", - .to = "for (uint slot = 0; slot < a.topk; ++slot)\n sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]);", - }, + .combine_slot_order => .{ .from = "const uint slot = order[r];", .to = "const uint slot = r;" }, }; } }; diff --git a/zig/tests/contract/metal_inkling2_glue.zig b/zig/tests/contract/metal_inkling2_glue.zig index 496f4c69f98..fc2d9a1660b 100644 --- a/zig/tests/contract/metal_inkling2_glue.zig +++ b/zig/tests/contract/metal_inkling2_glue.zig @@ -51,7 +51,7 @@ pub const Probe = struct { .conv_dynamic => .{ .{ .rows = 1, .n = 128, .k = 4 }, .{ .rows = 5, .n = 512, .k = 4 }, .{ .rows = 7, .n = 1024, .k = 4 } }, .router => .{ .{ .rows = 1, .n = 8, .k = p.hidden }, .{ .rows = 5, .n = 8, .k = p.hidden }, .{ .rows = 7, .n = 8, .k = p.hidden } }, .swiglu => .{ .{ .rows = 1, .n = p.intermediate, .k = 2 }, .{ .rows = 5, .n = p.intermediate, .k = 2 }, .{ .rows = 7, .n = p.intermediate, .k = 2 } }, - .logits => .{ .{ .rows = 1, .n = 128, .k = p.hidden }, .{ .rows = 5, .n = 256, .k = p.hidden }, .{ .rows = 7, .n = 128, .k = p.hidden } }, + .logits => .{ .{ .rows = 1, .n = 128, .k = p.hidden }, .{ .rows = 5, .n = 256, .k = p.hidden }, .{ .rows = 11, .n = 128, .k = p.hidden } }, .expert_pick => .{ .{ .rows = 1, .n = p.intermediate, .k = 8 }, .{ .rows = 5, .n = p.intermediate, .k = 8 }, .{ .rows = 7, .n = p.intermediate, .k = 8 } }, .expert_combine => .{ .{ .rows = 1, .n = p.hidden, .k = 8 }, .{ .rows = 5, .n = p.hidden, .k = 8 }, .{ .rows = 7, .n = p.hidden, .k = 8 } }, }; diff --git a/zig/tests/contract/metal_inkling2_glue_controls.zig b/zig/tests/contract/metal_inkling2_glue_controls.zig index aba23199f09..d54c3199693 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 = "keys[t] = scores[t] + bias[t];", .to = "keys[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]" }, diff --git a/zig/tests/contract/metal_inkling2_logits_units.zig b/zig/tests/contract/metal_inkling2_logits_units.zig new file mode 100644 index 00000000000..d88e13f7441 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_logits_units.zig @@ -0,0 +1,179 @@ +//! Inkling 2 Mini's logits on the tensor units: the glue entry's FP64 dot, BF16 round and cap of 30. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const bf = contract.bf16_round.bf16; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.experts; +const controls = @import("metal_inkling2_units_controls.zig"); +const src = @import("inkling2_metal"); + +const hidden = 2304; +pub const name = "metal inkling2 units tf_ink2_logits_units"; + +fn depth(s: c.Shape) usize { + return s.k + 3; +} + +pub fn spec(control: bool) c.Spec { + return .{ + .name = if (control) controls.Mutation.logits_cap.name() else name, + .accum = .f32, + .depth = depth, + .ops = 8, + .mids = 1, + .out = .f32, + // Rows go 16 a band and vocabulary rows 32 a tile; 90 vocabulary rows leave the last tile part full. + .tiles = .{ .{ .size = 16 }, .{ .size = 32 }, .{} }, + .served = &.{ .{ .rows = 1, .n = 64, .k = hidden }, .{ .rows = 8, .n = 90, .k = hidden }, .{ .rows = 20, .n = 32, .k = hidden } }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "independent FP64 terms, an explicit BF16 node and a tanh" }, + }; +} + +const Sim = struct { acc: c.Accum, order: g.Order }; +const Sample = struct { value: f64, magnitude: f64 }; + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: host.Pipelines, + control: bool, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u16 = &.{}, + refs: [3]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, control: bool) !Probe { + const text = try controls.apply(a, if (control) .logits_cap else .none); + defer a.free(text); + var pipes = try host.Pipelines.loadSource(device, src.experts); + errdefer pipes.deinit(); + try pipes.loadUnits(device, text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = pipes, .control = control }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.x = &.{}; + p.w = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.control), .ctx = p, .vt = &vt, .control = if (p.control) controls.Mutation.logits_cap.gate() else null }; + } + const vt = blk: { + var table = g.hooks(Probe); + table.check = null; + break :blk table; + }; + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > 40 or shape.n == 0 or shape.n > 128 or shape.k != hidden) return false; + p.clear(); + p.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.x = try p.a.alloc(u16, shape.rows * hidden); + p.w = try p.a.alloc(u16, shape.n * hidden); + for (p.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 7 == 0) @as(f32, 3) else 1)); + for (p.w) |*v| v.* = c.toBf16(rng.float(f32) * 0.5 - 0.25); + if (fill == .stress) { + // Whole numbers times a power of two: every product and partial sum is exact, and the cap stays live. + for (p.x, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(128 * (1 + i % 13))) * (if (i >= p.x.len / 2) @as(f32, -1) else 1)); + for (p.w, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(@as(i32, @intCast(i % 7)) - 3)) * 0x1p-20); + } + if (fill == .nonfinite and p.x.len >= 3) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.w)); + p.refs[2] = try p.rig.output(p.count() * 4); + return true; + } + + fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + try host.logitsUnits(&p.pipes, pass.e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), @intCast(p.shape.rows), @intCast(p.shape.n)); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return p.shape.rows * p.shape.n; + } + + fn evaluate(p: *const Probe, at: usize, sim: ?Sim) Sample { + const row = at / p.shape.n; + const v = at % p.shape.n; + var terms: [hidden]f64 = undefined; + var magnitude: f64 = 0; + for (&terms, 0..) |*term, d| { + term.* = @as(f64, c.fromBf16(p.w[v * hidden + d])) * @as(f64, c.fromBf16(p.x[row * hidden + d])); + magnitude += @abs(term.*); + } + const sum = if (sim) |s| rows.sumIn(s.acc, s.order, &terms) else blk: { + var total: f64 = 0; + for (terms) |term| total += term; + break :blk total; + }; + return .{ .value = 30 * std.math.tanh(bf(sum) / 30), .magnitude = magnitude }; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*v, *m, i| { + const sample = p.evaluate(i, null); + v.* = sample.value; + m.* = sample.magnitude; + } + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + for (out, 0..) |*v, i| v.* = p.evaluate(i, .{ .acc = acc, .order = order }).value; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [2]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + /// The entry exists only where the GPU has tensor units; elsewhere the glue's kernel serves every width. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (!s.device.tensorUnits()) return; + for ([_]bool{ false, true }) |control| { + const label = spec(control).name; + if (only) |needle| if (std.mem.indexOf(u8, label, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + } + } +}; + +test "the logits entry resolves to its symbol in the units source" { + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 units ")); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.experts_units, "tf_ink2_logits_units(")); +} diff --git a/zig/tests/contract/metal_inkling2_loop_controls.zig b/zig/tests/contract/metal_inkling2_loop_controls.zig index 5464bf58e5d..0e7c0600010 100644 --- a/zig/tests/contract/metal_inkling2_loop_controls.zig +++ b/zig/tests/contract/metal_inkling2_loop_controls.zig @@ -8,7 +8,7 @@ fn edit(kind: p.Kind) Edit { // Drops the required post-dot binary32(1/48) scale. .messages => .{ .from = "weights[s] = dot * INKLING_LOOP_SCALE;", .to = "weights[s] = dot;" }, // Drops the model-dtype rounding between D accumulation and F/Gamma. - .gates => .{ .from = "zeta[t] = float(bfloat(dot));", .to = "zeta[t] = dot;" }, + .gates => .{ .from = "zeta[row * INKLING_LOOP_RANK + r] = bfloat(sum);", .to = "zeta[row * INKLING_LOOP_RANK + r] = bfloat(2.0f * sum);" }, }; } diff --git a/zig/tests/contract/metal_inkling2_main.zig b/zig/tests/contract/metal_inkling2_main.zig index 57f7558ce6d..c303e3c9708 100644 --- a/zig/tests/contract/metal_inkling2_main.zig +++ b/zig/tests/contract/metal_inkling2_main.zig @@ -7,15 +7,28 @@ pub const Suites = struct { attention: @import("metal_inkling2_attention.zig").Suite, glue: @import("metal_inkling2_glue.zig").Suite, experts: @import("metal_inkling2_experts.zig").Suite, + units: @import("metal_inkling2_units.zig").Suite, + mma: @import("metal_inkling2_mma.zig").Suite, + dense_mma: @import("metal_inkling2_dense_mma.zig").Suite, + blend_mma: @import("metal_inkling2_blend_mma.zig").Suite, + logits_units: @import("metal_inkling2_logits_units.zig").Suite, + dense_units: @import("metal_inkling2_dense_units.zig").Suite, loop: @import("metal_inkling2_loop.zig").Suite, runtime: @import("metal_inkling2_runtime.zig").Suite, dspark: @import("metal_inkling2_dspark.zig").Suite, - pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !Suites { - var s = Suites{ + /// In place: the kernels list holds pointers into `s`, so it must not move once its suites collect. + pub fn init(s: *Suites, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { + s.* = .{ .attention = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .glue = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .experts = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .mma = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .dense_mma = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .blend_mma = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .logits_units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .dense_units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .loop = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .runtime = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .dspark = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, @@ -24,16 +37,27 @@ pub const Suites = struct { try s.attention.collect(only); try s.glue.collect(only); try s.experts.collect(only); + try s.units.collect(only); + try s.mma.collect(only); + try s.dense_mma.collect(only); + try s.blend_mma.collect(only); + try s.logits_units.collect(only); + try s.dense_units.collect(only); try s.loop.collect(only); try s.runtime.collect(only); try s.dspark.collect(only); - return s; } pub fn deinit(s: *Suites) void { s.attention.deinit(); s.glue.deinit(); s.experts.deinit(); + s.units.deinit(); + s.mma.deinit(); + s.dense_mma.deinit(); + s.blend_mma.deinit(); + s.logits_units.deinit(); + s.dense_units.deinit(); s.loop.deinit(); s.runtime.deinit(); s.dspark.deinit(); diff --git a/zig/tests/contract/metal_inkling2_mma.zig b/zig/tests/contract/metal_inkling2_mma.zig new file mode 100644 index 00000000000..0269139439f --- /dev/null +++ b/zig/tests/contract/metal_inkling2_mma.zig @@ -0,0 +1,286 @@ +//! Inkling 2 Mini's routed experts on simdgroup matrices: each output equals its grouped kernel's, byte for byte. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.experts; +const controls = @import("metal_inkling2_mma_controls.zig"); +const src = @import("inkling2_metal"); + +pub const Kind = enum { nv_gu, nv_down, mx_gu, mx_down }; + +const experts = 128; +const topk = 2; + +fn symbol(k: Kind) []const u8 { + return switch (k) { + .nv_gu => "tf_ink2_nvfp4_gu_mma", + .nv_down => "tf_ink2_nvfp4_down_mma", + .mx_gu => "tf_ink2_mxfp8_gu_mma", + .mx_down => "tf_ink2_mxfp8_down_mma", + }; +} + +fn mutation(k: Kind) controls.Mutation { + return switch (k) { + .nv_gu => .nv_gu_phi, + .nv_down => .nv_down_passes, + .mx_gu => .mx_gu_scale, + .mx_down => .mx_down_chains, + }; +} + +fn isNv(k: Kind) bool { + return k == .nv_gu or k == .nv_down; +} +fn isGu(k: Kind) bool { + return k == .nv_gu or k == .mx_gu; +} +fn depth(_: c.Shape) usize { + return 0; +} + +const gu_shapes = [_]c.Shape{ .{ .rows = 2, .n = 32, .k = 2304 }, .{ .rows = 13, .n = 64, .k = 2304 }, .{ .rows = 45, .n = 64, .k = 2304 } }; +const down_shapes = [_]c.Shape{ .{ .rows = 2, .n = 64, .k = 1152 }, .{ .rows = 13, .n = 128, .k = 1152 }, .{ .rows = 45, .n = 128, .k = 1152 } }; + +pub fn spec(k: Kind, control: bool) c.Spec { + const base = if (control) mutation(k).name() else switch (k) { + .nv_gu => "metal inkling2 mma tf_ink2_nvfp4_gu_mma", + .nv_down => "metal inkling2 mma tf_ink2_nvfp4_down_mma", + .mx_gu => "metal inkling2 mma tf_ink2_mxfp8_gu_mma", + .mx_down => "metal inkling2 mma tf_ink2_mxfp8_down_mma", + }; + return .{ + .name = base, + .accum = .none, + .depth = depth, + .out = .bf16, + .replaces = "the grouped kernels tf_ink2_*_grouped, on the same weights, pairs and rows", + .nan = .{ .stated = "every output equals the grouped kernel's: a non-finite sum has the same class" }, + // One expert takes a pair of every row, so 45 rows cross a band of 32 pairs and end it at 13 of them. + .tiles = .{ .{ .size = 32 }, .{ .size = if (isGu(k)) 32 else 64, .step = if (isGu(k)) 32 else 64, .min = if (isGu(k)) 32 else 64 }, .{} }, + .served = if (isGu(k)) &gu_shapes else &down_shapes, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "the grouped kernels' fp32 sums are the baseline, bit for bit" }, + }; +} + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: host.Pipelines, + kind: Kind, + ctl: controls.Mutation, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u8 = &.{}, + scales: []u8 = &.{}, + amax: []f32 = &.{}, + denominator: []f32 = &.{}, + ids: []i32 = &.{}, + refs: [7]rig_.Ref = undefined, + baseline: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, control: bool) !Probe { + const text = try controls.apply(a, if (control) mutation(kind) else .none); + defer a.free(text); + var pipes = try host.Pipelines.loadSource(device, src.experts); + errdefer pipes.deinit(); + try pipes.loadMma(device, text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = pipes, .kind = kind, .ctl = if (control) mutation(kind) else .none }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.a.free(p.scales); + p.a.free(p.amax); + p.a.free(p.denominator); + p.a.free(p.ids); + p.x = &.{}; + p.w = &.{}; + p.scales = &.{}; + p.amax = &.{}; + p.denominator = &.{}; + p.ids = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.kind, p.ctl != .none), .ctx = p, .vt = &vt, .control = p.ctl.gate() }; + } + const vt = g.hooks(Probe); + + fn call(p: *const Probe) host.Call { + return .{ .rows = @intCast(p.shape.rows), .k = @intCast(p.shape.k), .n = @intCast(p.shape.n), .experts = experts, .topk = topk, .format = if (isNv(p.kind)) .nvfp4 else .mxfp8 }; + } + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const k = p.kind; + const unit: usize = if (isGu(k)) 32 else 64; + if (shape.rows == 0 or shape.rows > 64 or shape.n == 0 or shape.n % unit != 0 or shape.k == 0 or shape.k % 32 != 0) return false; + p.clear(); + p.shape = shape; + const nv = isNv(k); + const routes = shape.rows * topk; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.x = try p.a.alloc(u16, if (isGu(k)) shape.rows * shape.k else routes * shape.k); + for (p.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 7 == 0) @as(f32, 3) else 1)); + p.ids = try p.a.alloc(i32, routes); + // Expert 2 takes a pair of every row and experts 0 and 1 share the other, so one expert's pairs pass a band. + for (p.ids, 0..) |*id, i| id.* = @intCast(if (i % 2 == 0) 2 else (i / 2) % 2); + const matrices: usize = experts * (if (isGu(k)) 2 * shape.n else shape.n); + p.w = try p.a.alloc(u8, matrices * (if (nv) shape.k / 2 else shape.k)); + p.scales = try p.a.alloc(u8, matrices * (shape.k / @as(usize, if (nv) 16 else 32))); + for (p.w) |*v| v.* = rng.int(u8); + // Weights small enough that the gate and up sums stay in the activation's live range. + for (p.scales, 0..) |*v, i| v.* = if (nv) @intCast(0x30 + (i % 17)) else @intCast(112 + (i % 5)); + if (!nv) for (p.w) |*v| if (v.* & 0x7f == 0x7f) { + v.* = (v.* & 0x80) | 0x7e; + }; + if (!isGu(k)) p.plant(); + if (nv) { + p.amax = try p.a.alloc(f32, experts); + for (p.amax, 0..) |*v, i| v.* = 2688.125 + @as(f32, @floatFromInt(i % 4)) * 0.375; + p.denominator = try p.a.alloc(f32, 1); + p.denominator[0] = 2695.75 * 64; + } + if (fill == .nonfinite and p.x.len >= 3) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } + const out = try p.rig.output(p.count() * 2); + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(p.w); + p.refs[2] = try p.rig.input(p.scales); + if (nv) { + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.amax)); + p.refs[4] = try p.rig.input(std.mem.sliceAsBytes(p.denominator)); + p.refs[5] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[6] = out; + } else { + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[4] = out; + } + p.baseline = try p.rig.scratch(p.count() * 2); + return true; + } + + /// Huge terms that cancel (+2^20, -2^20) in blocks of every matrix and route leave what each order of adding lost. + fn plant(p: *Probe) void { + const nv = isNv(p.kind); + const unit: usize = if (nv) 16 else 32; + const bytes_per_block: usize = if (nv) 8 else 32; + const blocks = p.shape.k / unit; + const big = c.toBf16(1048576); + const up = [_]usize{ 1, 5, 9, 13, 17, 21 }; + const down = [_]usize{ 3, 7, 11, 15, 19, 23 }; + for (0..p.x.len / p.shape.k) |row| for (up ++ down) |blk| { + p.x[row * p.shape.k + blk * unit] = big; + p.x[row * p.shape.k + blk * unit + 1] = big; + }; + const matrices = p.scales.len / blocks; + for (0..matrices) |m| for (up, down) |a, b| { + for ([_]usize{ a, b }) |blk| p.scales[m * blocks + blk] = if (nv) 0x38 else 127; + const first = m * blocks * bytes_per_block; + // One FP4 byte holds two columns of 1.0 or -1.0; an FP8 byte holds one. + const plus: u8 = if (nv) 0x22 else 0x38; + const minus: u8 = if (nv) 0xaa else 0xb8; + for (0..if (nv) 1 else 2) |i| { + p.w[first + a * bytes_per_block + i] = plus; + p.w[first + b * bytes_per_block + i] = minus; + } + }; + } + + fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; + } + + /// The products into `out`: on the simdgroup matrices, or as the grouped kernels they replace. + fn launch(p: *Probe, out: rig_.Ref, grouped: bool) !void { + const pass = p.rig.begin(); + const e = pass.e; + const nv = isNv(p.kind); + const globals: ?host.Globals = if (nv) .{ .amax = hr(p.refs[3]), .denominator = hr(p.refs[4]) } else null; + try host.group(&p.pipes, e, hr(p.refs[if (nv) 5 else 3]), p.call()); + e.barrier(); + const path: host.Path = if (grouped) .scalar else .mma; + try host.products(&p.pipes, e, path, !isGu(p.kind), hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), globals, hr(out), p.call()); + try p.rig.finish(pass); + } + + pub fn run(p: *Probe) !void { + try p.launch(p.refs[if (isNv(p.kind)) 6 else 4], false); + } + + pub fn replaced(p: *Probe) ![]const u8 { + try p.launch(p.baseline, true); + return p.rig.bytes(p.baseline, p.count() * 2); + } + + pub fn count(p: *const Probe) usize { + return p.shape.rows * topk * p.shape.n; + } + + pub fn reference(_: *Probe, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + + /// Non-finite inputs: every output has the grouped kernel's class, and a finite one its bytes. + pub fn check(p: *Probe, _: g.Gate) !?[]const u8 { + try p.run(); + const got = try p.rig.outputBytes(); + const want = try p.replaced(); + for (0..p.count()) |i| { + const a = c.fromBf16(std.mem.readInt(u16, got[2 * i ..][0..2], .little)); + const b = c.fromBf16(std.mem.readInt(u16, want[2 * i ..][0..2], .little)); + if (std.math.isNan(a) and std.math.isNan(b)) continue; + if (@as(u32, @bitCast(a)) != @as(u32, @bitCast(b))) return "an output differs from the grouped kernel's"; + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [8]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + /// The entries exist where the GPU has no tensor units; the units kernels serve every width on the others. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (s.device.tensorUnits()) return; + for (std.enums.values(Kind)) |kind| for ([_]bool{ false, true }) |control| { + const label = if (control) mutation(kind).name() else spec(kind, false).name; + if (only) |needle| if (std.mem.indexOf(u8, label, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, kind, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + }; + } +}; + +test "contract labels resolve to the simdgroup-matrix entries" { + for (std.enums.values(Kind)) |kind| { + const name = spec(kind, false).name; + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 mma ")); + try std.testing.expect(std.mem.indexOf(u8, src.experts_mma, symbol(kind)) != null); + } +} diff --git a/zig/tests/contract/metal_inkling2_mma_controls.zig b/zig/tests/contract/metal_inkling2_mma_controls.zig new file mode 100644 index 00000000000..26ea29aeb5a --- /dev/null +++ b/zig/tests/contract/metal_inkling2_mma_controls.zig @@ -0,0 +1,69 @@ +//! Count-checked mutations of the simdgroup-matrix expert kernels: each plants a different kind of fault. +const std = @import("std"); +const src = @import("inkling2_metal"); +const g = @import("contract").gates; + +pub const Mutation = enum { + none, + nv_gu_phi, + nv_down_passes, + mx_gu_scale, + mx_down_chains, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .nv_gu_phi => "control: metal inkling2 mma tf_ink2_nvfp4_gu_mma phi", + .nv_down_passes => "control: metal inkling2 mma tf_ink2_nvfp4_down_mma pass order", + .mx_gu_scale => "control: metal inkling2 mma tf_ink2_mxfp8_gu_mma scale", + .mx_down_chains => "control: metal inkling2 mma tf_ink2_mxfp8_down_mma chain order", + }; + } + + pub fn gate(m: Mutation) ?g.Gate { + return if (m == .none) null else .shapes; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + // Both NVFP4 entries share a macro and so an edit; a control compiles only its selected entry. + .nv_gu_phi => .{ .from = "ink2_mma(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_mma(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + .nv_down_passes => .{ + .from = "for (uint s = 1u; s < INK2_MMA_NP; s <<= 1u)\n _Pragma(\"clang loop unroll(full)\") for (uint p = 0u; p < INK2_MMA_NP; p += 2u * s) sums[j][p] += sums[j][p + s];", + .to = "for (uint s = INK2_MMA_NP / 2u; s != 0u; s >>= 1u)\n _Pragma(\"clang loop unroll(full)\") for (uint p = 0u; p < s; ++p) sums[j][p] += sums[j][p + s];", + }, + .mx_gu_scale => .{ .from = "max(raw.code, 1u) << 23u", .to = "(max(raw.code, 1u) + 1u) << 23u" }, + .mx_down_chains => .{ .from = "sums[j][pass] = (c0 + c1) + (c2 + c3);", .to = "sums[j][pass] = (c0 + c2) + (c1 + c3);" }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, src.experts_mma); + const change = m.edit(); + if (std.mem.count(u8, src.experts_mma, change.from) != 1) return error.ControlEditCount; + return std.mem.replaceOwned(u8, a, src.experts_mma, change.from, change.to); +} + +test "every simdgroup-matrix expert control edits exactly its planted arithmetic" { + const a = std.testing.allocator; + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const edited = try apply(a, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectEqual(g.Gate.shapes, m.gate().?); + try std.testing.expect(std.mem.startsWith(u8, m.name(), "control: metal inkling2 mma ")); + } + const plain = try apply(a, .none); + defer a.free(plain); + try std.testing.expectEqualStrings(src.experts_mma, plain); +} + +test "the source exports all four entries after the grouped kernels" { + inline for ([_][]const u8{ "tf_ink2_nvfp4_gu_mma", "tf_ink2_nvfp4_down_mma", "tf_ink2_mxfp8_gu_mma", "tf_ink2_mxfp8_down_mma" }) |name| + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.experts_mma, name ++ ",")); + try std.testing.expect(std.mem.indexOf(u8, src.experts_mma, "tf_ink2_nvfp4_gu_grouped") != null); +} diff --git a/zig/tests/contract/metal_inkling2_units.zig b/zig/tests/contract/metal_inkling2_units.zig new file mode 100644 index 00000000000..6999e0f8760 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_units.zig @@ -0,0 +1,337 @@ +//! Inkling 2 Mini's routed experts on the tensor units: the same FP64 decode, dot and activation as the M3 entries. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const bf = contract.bf16_round.bf16; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.experts; +const controls = @import("metal_inkling2_units_controls.zig"); +const src = @import("inkling2_metal"); + +pub const Kind = enum { nv_gu, nv_down, mx_gu, mx_down, nv_gu_t, nv_down_t, mx_gu_t, mx_down_t }; + +/// The columns the kernels fix for each product, and the experts `group` lists. +const gu_k = 2304; +const down_k = 1152; +const experts = 128; +const topk = 2; + +fn symbol(k: Kind) []const u8 { + return switch (k) { + .nv_gu => "tf_ink2_nvfp4_gu_units", + .nv_down => "tf_ink2_nvfp4_down_units", + .mx_gu => "tf_ink2_mxfp8_gu_units", + .mx_down => "tf_ink2_mxfp8_down_units", + .nv_gu_t => "tf_ink2_nvfp4_gu_units_t", + .nv_down_t => "tf_ink2_nvfp4_down_units_t", + .mx_gu_t => "tf_ink2_mxfp8_gu_units_t", + .mx_down_t => "tf_ink2_mxfp8_down_units_t", + }; +} + +fn mutation(k: Kind) controls.Mutation { + return switch (k) { + .nv_gu => .nv_gu_phi, + .nv_down => .nv_down_phi, + .mx_gu => .mx_gu_scale, + .mx_down => .mx_down_scale, + .nv_gu_t => .nv_gu_t_phi, + .nv_down_t => .nv_down_t_phi, + .mx_gu_t => .mx_gu_t_scale, + .mx_down_t => .mx_down_t_scale, + }; +} + +fn isNv(k: Kind) bool { + return k == .nv_gu or k == .nv_down or k == .nv_gu_t or k == .nv_down_t; +} +fn isGu(k: Kind) bool { + return k == .nv_gu or k == .mx_gu or k == .nv_gu_t or k == .mx_gu_t; +} +/// The turned tiles: 16 weight rows by 32 of an expert's pairs an op. +fn isTurned(k: Kind) bool { + return k == .nv_gu_t or k == .nv_down_t or k == .mx_gu_t or k == .mx_down_t; +} +/// An op is 16 columns: the shared bound on its roundings a step, then the eight partial sums and the epilogue. +fn depth(s: c.Shape) usize { + return s.k / 16 * contract.attention_range.mma_step + 8 + 3; +} + +const gu_shapes = [_]c.Shape{ .{ .rows = 2, .n = 16, .k = gu_k }, .{ .rows = 5, .n = 32, .k = gu_k }, .{ .rows = 20, .n = 16, .k = gu_k } }; +const gu_turned_shapes = [_]c.Shape{ .{ .rows = 2, .n = 16, .k = gu_k }, .{ .rows = 5, .n = 32, .k = gu_k }, .{ .rows = 40, .n = 16, .k = gu_k } }; +const down_shapes = [_]c.Shape{ .{ .rows = 2, .n = 32, .k = down_k }, .{ .rows = 5, .n = 64, .k = down_k }, .{ .rows = 20, .n = 32, .k = down_k } }; +const down_turned_shapes = [_]c.Shape{ .{ .rows = 2, .n = 32, .k = down_k }, .{ .rows = 5, .n = 64, .k = down_k }, .{ .rows = 40, .n = 32, .k = down_k } }; + +pub fn spec(k: Kind, control: bool) c.Spec { + const base = if (control) mutation(k).name() else switch (k) { + .nv_gu => "metal inkling2 units tf_ink2_nvfp4_gu_units", + .nv_down => "metal inkling2 units tf_ink2_nvfp4_down_units", + .mx_gu => "metal inkling2 units tf_ink2_mxfp8_gu_units", + .mx_down => "metal inkling2 units tf_ink2_mxfp8_down_units", + .nv_gu_t => "metal inkling2 units tf_ink2_nvfp4_gu_units_t", + .nv_down_t => "metal inkling2 units tf_ink2_nvfp4_down_units_t", + .mx_gu_t => "metal inkling2 units tf_ink2_mxfp8_gu_units_t", + .mx_down_t => "metal inkling2 units tf_ink2_mxfp8_down_units_t", + }; + return .{ + .name = base, + .accum = .f32, + .depth = depth, + .ops = if (isGu(k)) 12 else 3, + .mids = if (isGu(k)) 3 else 0, + .out = .bf16, + // One expert takes every row here, so 20 rows cross a 16-pair band and 40 a turned tile's 32. + .tiles = .{ .{ .size = if (isTurned(k)) 32 else 16 }, .{}, .{} }, + .served = if (isGu(k)) (if (isTurned(k)) &gu_turned_shapes else &gu_shapes) else if (isTurned(k)) &down_turned_shapes else &down_shapes, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "independent FP64 terms and explicit BF16 nodes" }, + }; +} + +const Sim = struct { acc: c.Accum, order: g.Order }; +const Sample = struct { value: f64, magnitude: f64 }; +const Dot = struct { value: f64, magnitude: f64 }; + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: host.Pipelines, + kind: Kind, + ctl: controls.Mutation, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u8 = &.{}, + scales: []u8 = &.{}, + amax: []f32 = &.{}, + denominator: []f32 = &.{}, + ids: []i32 = &.{}, + refs: [7]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, control: bool) !Probe { + const text = try controls.apply(a, if (control) mutation(kind) else .none); + defer a.free(text); + var pipes = try host.Pipelines.loadSource(device, src.experts); + errdefer pipes.deinit(); + try pipes.loadUnits(device, text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = pipes, .kind = kind, .ctl = if (control) mutation(kind) else .none }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.a.free(p.scales); + p.a.free(p.amax); + p.a.free(p.denominator); + p.a.free(p.ids); + p.x = &.{}; + p.w = &.{}; + p.scales = &.{}; + p.amax = &.{}; + p.denominator = &.{}; + p.ids = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.kind, p.ctl != .none), .ctx = p, .vt = &vt, .control = p.ctl.gate() }; + } + const vt = blk: { + var table = g.hooks(Probe); + table.check = null; + break :blk table; + }; + + fn call(p: *const Probe) host.Call { + return .{ .rows = @intCast(p.shape.rows), .k = @intCast(p.shape.k), .n = @intCast(p.shape.n), .experts = experts, .topk = topk, .format = if (isNv(p.kind)) .nvfp4 else .mxfp8 }; + } + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const k = p.kind; + if (shape.rows == 0 or shape.rows > 40) return false; + if (isGu(k) and (shape.k != gu_k or shape.n == 0 or shape.n > 32 or shape.n % 16 != 0)) return false; + if (!isGu(k) and (shape.k != down_k or shape.n == 0 or shape.n > 64 or shape.n % 32 != 0)) return false; + p.clear(); + p.shape = shape; + const nv = isNv(k); + const routes = shape.rows * topk; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.x = try p.a.alloc(u16, if (isGu(k)) shape.rows * shape.k else routes * shape.k); + for (p.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 7 == 0) @as(f32, 3) else 1)); + p.ids = try p.a.alloc(i32, routes); + // Expert 2 takes a pair of every row and experts 0 and 1 share the other, so one expert's pairs pass 16. + for (p.ids, 0..) |*id, i| id.* = @intCast(if (i % 2 == 0) 2 else (i / 2) % 2); + const matrices: usize = experts * (if (isGu(k)) 2 * shape.n else shape.n); + p.w = try p.a.alloc(u8, matrices * (if (nv) shape.k / 2 else shape.k)); + p.scales = try p.a.alloc(u8, matrices * (shape.k / @as(usize, if (nv) 16 else 32))); + for (p.w) |*v| v.* = rng.int(u8); + // Weights small enough that the gate and up sums stay in the activation's live range. + for (p.scales, 0..) |*v, i| v.* = if (nv) @intCast(0x30 + (i % 17)) else @intCast(112 + (i % 5)); + if (!nv) for (p.w) |*v| if (v.* & 0x7f == 0x7f) { + v.* = (v.* & 0x80) | 0x7e; + }; + if (nv) { + p.amax = try p.a.alloc(f32, experts); + for (p.amax, 0..) |*v, i| v.* = 2688.125 + @as(f32, @floatFromInt(i % 4)) * 0.375; + p.denominator = try p.a.alloc(f32, 1); + p.denominator[0] = 2695.75 * 64; + } + if (fill == .stress) { + for (p.x, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(128 * (1 + i % 13))) * (if (i >= p.x.len / 2) @as(f32, -1) else 1)); + @memset(p.scales, if (nv) 0x38 else 127); + } + if (fill == .nonfinite and p.x.len >= 3) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } + const out = try p.rig.output(p.count() * 2); + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(p.w); + p.refs[2] = try p.rig.input(p.scales); + if (nv) { + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.amax)); + p.refs[4] = try p.rig.input(std.mem.sliceAsBytes(p.denominator)); + p.refs[5] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[6] = out; + } else { + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[4] = out; + } + return true; + } + + fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + const nv = isNv(p.kind); + const ids = hr(p.refs[if (nv) 5 else 3]); + const out = hr(p.refs[if (nv) 6 else 4]); + try host.group(&p.pipes, e, ids, p.call()); + e.barrier(); + const launch = if (isTurned(p.kind)) &host.unitsTurned else &host.units; + try launch(&p.pipes, e, !isGu(p.kind), hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), if (nv) .{ .amax = hr(p.refs[3]), .denominator = hr(p.refs[4]) } else null, out, p.call()); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return p.shape.rows * topk * p.shape.n; + } + + fn e2(code: u8) f64 { + const v = ([_]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 })[code & 7]; + return if (code & 8 != 0) -v else v; + } + fn e4(code: u8) f64 { + const exponent = (code >> 3) & 15; + const mantissa = code & 7; + if (exponent == 15 and mantissa == 7) return std.math.nan(f64); + const v = if (exponent == 0) @as(f64, @floatFromInt(mantissa)) / 512 else std.math.ldexp(@as(f64, 8 + @as(u16, mantissa)), @as(i32, exponent) - 10); + return if (code & 0x80 != 0) -v else v; + } + fn weight(p: *const Probe, expert: usize, row: usize, col: usize) f64 { + const k = p.shape.k; + const rows_per_expert: usize = if (isGu(p.kind)) 2 * p.shape.n else p.shape.n; + const matrix_row = expert * rows_per_expert + row; + if (!isNv(p.kind)) { + const value = p.w[matrix_row * k + col]; + const scale = p.scales[matrix_row * (k / 32) + col / 32]; + return bf(std.math.ldexp(e4(value), @as(i32, scale) - 127)); + } + const codes = p.w[matrix_row * (k / 2) + col / 2]; + const code = if (col % 2 == 0) codes & 15 else codes >> 4; + const scale = p.scales[matrix_row * (k / 16) + col / 16]; + const factor = bf(p.amax[expert]) / bf(p.denominator[0]); + return bf(@as(f32, @floatCast(e2(code) * e4(scale) * factor))); + } + + fn dot(p: *const Probe, expert: usize, row: usize, x: []const u16, sim: ?Sim) Dot { + var terms: [gu_k]f64 = undefined; + var magnitude: f64 = 0; + for (0..p.shape.k) |col| { + const term = p.weight(expert, row, col) * @as(f64, c.fromBf16(x[col])); + terms[col] = term; + magnitude += @abs(term); + } + return .{ .value = if (sim) |s| rows.sumIn(s.acc, s.order, terms[0..p.shape.k]) else blk: { + var sum: f64 = 0; + for (terms[0..p.shape.k]) |term| sum += term; + break :blk sum; + }, .magnitude = magnitude }; + } + + fn evaluate(p: *const Probe, at: usize, sim: ?Sim) Sample { + const pair = at / p.shape.n; + const n = at % p.shape.n; + const token = pair / topk; + const expert: usize = @intCast(p.ids[pair]); + const x = if (isGu(p.kind)) p.x[token * p.shape.k ..][0..p.shape.k] else p.x[pair * p.shape.k ..][0..p.shape.k]; + if (!isGu(p.kind)) { + const d = p.dot(expert, n, x, sim); + return .{ .value = bf(d.value), .magnitude = d.magnitude }; + } + const gd = p.dot(expert, 2 * n, x, sim); + const ud = p.dot(expert, 2 * n + 1, x, sim); + const gate = bf(gd.value); + const up = bf(ud.value); + const left = 4 * std.math.tanh(gate / 4) * (1 / (1 + @exp(-gate))); + return .{ .value = bf(left * (25 * std.math.tanh(up / 25))), .magnitude = gd.magnitude + ud.magnitude }; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*v, *m, i| { + const sample = p.evaluate(i, null); + v.* = sample.value; + m.* = sample.magnitude; + } + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + for (out, 0..) |*v, i| v.* = p.evaluate(i, .{ .acc = acc, .order = order }).value; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [16]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + /// The entries exist only where the GPU has tensor units; elsewhere the M3 kernels serve every width. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (!s.device.tensorUnits()) return; + for (std.enums.values(Kind)) |kind| for ([_]bool{ false, true }) |control| { + const label = if (control) mutation(kind).name() else spec(kind, false).name; + if (only) |needle| if (std.mem.indexOf(u8, label, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, kind, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + }; + } +}; + +test "contract labels resolve to the units entries" { + for (std.enums.values(Kind)) |kind| { + const name = spec(kind, false).name; + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 units ")); + try std.testing.expect(std.mem.indexOf(u8, src.experts_units, symbol(kind)) != null); + } +} diff --git a/zig/tests/contract/metal_inkling2_units_controls.zig b/zig/tests/contract/metal_inkling2_units_controls.zig new file mode 100644 index 00000000000..6026c52a2b2 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_units_controls.zig @@ -0,0 +1,81 @@ +//! Count-checked mutations of the tensor-unit kernels: every entry has a genuine arithmetic control. +const std = @import("std"); +const src = @import("inkling2_metal"); +const g = @import("contract").gates; + +pub const Mutation = enum { + none, + nv_gu_phi, + nv_down_phi, + mx_gu_scale, + mx_down_scale, + nv_gu_t_phi, + nv_down_t_phi, + mx_gu_t_scale, + mx_down_t_scale, + logits_cap, + dense_store, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .nv_gu_phi => "control: metal inkling2 units tf_ink2_nvfp4_gu_units phi", + .nv_down_phi => "control: metal inkling2 units tf_ink2_nvfp4_down_units phi", + .mx_gu_scale => "control: metal inkling2 units tf_ink2_mxfp8_gu_units scale", + .mx_down_scale => "control: metal inkling2 units tf_ink2_mxfp8_down_units scale", + .nv_gu_t_phi => "control: metal inkling2 units tf_ink2_nvfp4_gu_units_t phi", + .nv_down_t_phi => "control: metal inkling2 units tf_ink2_nvfp4_down_units_t phi", + .mx_gu_t_scale => "control: metal inkling2 units tf_ink2_mxfp8_gu_units_t scale", + .mx_down_t_scale => "control: metal inkling2 units tf_ink2_mxfp8_down_units_t scale", + .logits_cap => "control: metal inkling2 units tf_ink2_logits_units cap", + .dense_store => "control: metal inkling2 units tf_ink2_dense_units store", + }; + } + + pub fn gate(m: Mutation) ?g.Gate { + return if (m == .none) null else .shapes; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .nv_gu_phi => .{ .from = "ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + .nv_down_phi => .{ .from = "ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + // Both MXFP8 entries decode through one helper; a control compiles only its selected entry. + .nv_gu_t_phi => .{ .from = "ink2_units_t(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units_t(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + .nv_down_t_phi => .{ .from = "ink2_units_t(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units_t(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + .mx_gu_scale, .mx_down_scale, .mx_gu_t_scale, .mx_down_t_scale => .{ .from = "const int shift = int(scales[b / 2u]) - 127;", .to = "const int shift = int(scales[b / 2u]) - 126;" }, + .logits_cap => .{ .from = "precise::divide(float(bfloat(dot)), 30.0f)", .to = "precise::divide(float(bfloat(dot)), 15.0f)" }, + .dense_store => .{ .from = "Y[row * a.n + v] = bfloat(dot);", .to = "Y[row * a.n + v] = bfloat(2.0f * dot);" }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, src.experts_units); + const change = m.edit(); + if (std.mem.count(u8, src.experts_units, change.from) != 1) return error.ControlEditCount; + return std.mem.replaceOwned(u8, a, src.experts_units, change.from, change.to); +} + +test "every units control edits exactly its planted arithmetic" { + const a = std.testing.allocator; + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const edited = try apply(a, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectEqual(g.Gate.shapes, m.gate().?); + try std.testing.expect(std.mem.startsWith(u8, m.name(), "control: metal inkling2 units ")); + } + const plain = try apply(a, .none); + defer a.free(plain); + try std.testing.expectEqualStrings(src.experts_units, plain); +} + +test "units source exports all four entries after the decode helpers" { + inline for ([_][]const u8{ "tf_ink2_nvfp4_gu_units", "tf_ink2_nvfp4_down_units", "tf_ink2_mxfp8_gu_units", "tf_ink2_mxfp8_down_units" }) |name| + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.experts_units, name ++ "(")); + try std.testing.expect(std.mem.indexOf(u8, src.experts_units, "never quantize an activation") != null); +} diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 688db2625f8..71954107433 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -219,6 +219,14 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp @import("inkling2_metal").loop else if (std.mem.startsWith(u8, d.name, "metal inkling2 experts ")) @import("inkling2_metal").experts + else if (std.mem.startsWith(u8, d.name, "metal inkling2 units ")) + @import("inkling2_metal").experts_units + else if (std.mem.startsWith(u8, d.name, "metal inkling2 mma tf_ink2_dense")) + @import("inkling2_metal").dense_mma + else if (std.mem.startsWith(u8, d.name, "metal inkling2 mma tf_ink2_loop")) + @import("inkling2_metal").loop_mma + else if (std.mem.startsWith(u8, d.name, "metal inkling2 mma ")) + @import("inkling2_metal").experts_mma else if (std.mem.startsWith(u8, d.name, "metal inkling2 glue ")) @import("inkling2_metal").glue else if (std.mem.startsWith(u8, d.name, "metal inkling2 prompt ")) diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index cf80f33dc37..784f7aea7a8 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -359,7 +359,8 @@ pub fn main(init: std.process.Init) !u8 { var ling_mla_set = ling_mla.Suite{ .a = a, .device = device, .queue = queue }; defer ling_mla_set.deinit(); try ling_mla_set.collect(&kernels, o.only); - var inkling2_suites = try @import("metal_inkling2_main.zig").Suites.create(a, device, queue, &kernels, o.only); + var inkling2_suites: @import("metal_inkling2_main.zig").Suites = undefined; + try inkling2_suites.init(a, device, queue, &kernels, o.only); defer inkling2_suites.deinit(); for ([_][]const Reg{ &common, if (tensor) &m5_only else &.{} }) |list| for (list) |v| { if (!wanted(o, v.name)) continue;