diff --git a/zig/kernels/metal/deepseek_v41/glue.metal b/zig/kernels/metal/deepseek_v41/glue.metal new file mode 100644 index 00000000000..ea5f085f510 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/glue.metal @@ -0,0 +1,181 @@ +// DeepSeek V4.1 glue: RMS norm rows, embedding gather, joins, RoPE and act-quant round trips, one fixed formula each. +#include +using namespace metal; +#pragma METAL fp contract(off) + +#ifndef TF_CTL +#define TF_CTL 0 +#endif + +struct TfRmsArgs { uint D, R; float eps; }; +struct TfEmbedArgs { uint D, R, V, reps; int lo; }; +struct TfMeanArgs { uint D, R, hc; }; +struct TfRopeArgs { uint R, H, pairs, ldx, hx, ox, ldy, hy, oy; }; +struct TfQuantArgs { uint N, R; }; + +// Control 1 of every kernel: a non-finite input is read as 0, so the output class changes. +inline float tf_g_in(float v) { return (TF_CTL == 1 && !isfinite(v)) ? 0.0f : v; } + +// RMSNorm.forward (model.py:288), a row a threadgroup: fma chains t, t+256, ..; xor butterfly 16..1; p0..p7 in order. +template +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_dsv41_rms( + const device bfloat* X [[buffer(0)]], const device W* Wt [[buffer(1)]], device bfloat* Y [[buffer(2)]], + constant TfRmsArgs& a [[buffer(3)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[8]; + const device bfloat* x = X + ulong(row) * a.D; + const uint n = (TF_CTL == 2 && a.D % 256 != 0) ? a.D - 1 : a.D; + float s = 0.0f; + for (uint i = t; i < n; i += 256) { + const float v = tf_g_in(float(x[i])); + s = fma(v, v, s); + if (TF_CTL == 3) s = float(half(s)); + } + for (uint m = 16; m > 0; m >>= 1) s += simd_shuffle_xor(s, m); + if (lane == 0) part[sg] = s; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = part[0]; + for (uint j = 1; j < 8; ++j) total += part[j]; + const float r = precise::rsqrt(precise::divide(total, float(a.D)) + a.eps); + for (uint i = t; i < a.D; i += 256) Y[ulong(row) * a.D + i] = bfloat(float(Wt[i]) * (float(x[i]) * r)); + if (TF_CTL == 4 && row == 0 && t == 0) Y[ulong(a.R) * a.D] = bfloat(1.0f); +} + +#define TF_RMS(W, NAME) template [[host_name(NAME)]] [[kernel]] decltype(tf_dsv41_rms) tf_dsv41_rms; +TF_RMS(bfloat, "tf_dsv41_rms_bf16w") +TF_RMS(float, "tf_dsv41_rms_f32w") + +// ParallelEmbedding.forward (model.py:168), one rank: slice row id - lo copied, zeros off it, `reps` times. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_embed( + const device int* ids [[buffer(0)]], const device uint* T [[buffer(1)]], device uint* Y [[buffer(2)]], + constant TfEmbedArgs& a [[buffer(3)]], uint2 at [[thread_position_in_grid]]) { + const uint half_d = a.D / 2; + if (at.x >= half_d || at.y >= a.R) return; + const int id = ids[at.y] - a.lo; + uint v = (id >= 0 && uint(id) < a.V) ? T[ulong(id) * half_d + at.x] : 0u; + if (TF_CTL == 1 && !all(isfinite(float2(as_type(v))))) v = 0u; + if (TF_CTL == 2 && at.x + 1 == half_d && a.D % 64 != 0) return; + for (uint j = 0; j < a.reps; ++j) Y[(ulong(at.y) * a.reps + j) * half_d + at.x] = v; + if (TF_CTL == 4 && at.x == 0 && at.y == 0) Y[ulong(a.R) * a.reps * half_d] = 0x3F803F80u; +} + +// MoE.forward's tail (model.py:905-906): y += shared (fp32 += bf16), then y.type_as(x): out = bf16(routed + shared). +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_moe_join( + const device float* routed [[buffer(0)]], const device bfloat* shared [[buffer(1)]], device bfloat* Y [[buffer(2)]], + constant uint& n [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i >= n) return; + const float r = tf_g_in(routed[i]); + Y[i] = bfloat((TF_CTL == 2 ? float(bfloat(r)) : r) + float(shared[i])); + if (TF_CTL == 4 && i == 0) Y[n] = bfloat(1.0f); +} + +// h.mean(dim=2) over the hc copies (model.py:1269): out = bf16(((c0 + c1) + c2) + ... / hc), fp32 adds in copy order. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_hc_mean( + const device bfloat* X [[buffer(0)]], device bfloat* Y [[buffer(1)]], constant TfMeanArgs& a [[buffer(2)]], + uint2 at [[thread_position_in_grid]]) { + if (at.x >= a.D || at.y >= a.R) return; + const device bfloat* x = X + ulong(at.y) * a.hc * a.D + at.x; + float s = tf_g_in(float(x[0])); + for (uint j = 1; j < (TF_CTL == 2 ? a.hc - 1 : a.hc); ++j) s += tf_g_in(float(x[ulong(j) * a.D])); + Y[ulong(at.y) * a.D + at.x] = bfloat(precise::divide(s, float(a.hc))); + if (TF_CTL == 4 && at.x == 0 && at.y == 0) Y[ulong(a.R) * a.D] = bfloat(1.0f); +} + +// apply_rotary_emb (model.py:392): (xr, xi) * (c, s) of the row's position, each product and sum in fp32; x may be y. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_rope( + const device uint* X [[buffer(0)]], device uint* Y [[buffer(1)]], const device int* pos [[buffer(2)]], + const device float2* tab [[buffer(3)]], constant TfRopeArgs& a [[buffer(4)]], + uint3 at [[thread_position_in_grid]]) { + if (at.x >= a.pairs || at.y >= a.H || at.z >= a.R) return; + const uint i = TF_CTL == 2 ? (at.x < a.pairs / 2 ? 2 * at.x : 2 * (at.x - a.pairs / 2) + 1) : at.x; + const float2 cs = tab[ulong(pos[at.z]) * a.pairs + at.x]; + const ulong from = (ulong(at.z) * a.ldx + at.y * a.hx + a.ox) / 2 + i; + float2 v = float2(as_type(X[from])); + v = float2(tf_g_in(v.x), tf_g_in(v.y)); + const float re = v.x * cs.x - v.y * cs.y; + const float im = v.x * cs.y + v.y * cs.x; + Y[(ulong(at.z) * a.ldy + at.y * a.hy + a.oy) / 2 + at.x] = as_type(bfloat2(bfloat(re), bfloat(im))); + if (TF_CTL == 4 && at.x == 0 && at.y == 0 && at.z == 0) Y[ulong(a.R) * a.H * a.pairs] = 0x3F803F80u; +} + +// The reference's act_quant scale exponent for an amax: ceil(log2(max(amax, lo) * inv)) from the product's bits. +inline int tf_g_exp(float amax, float lo, float inv) { + const uint b = as_type(max(amax, lo) * inv); + return int((b >> 23) & 0xFFu) - 127 + ((b & 0x7FFFFFu) != 0u && TF_CTL != 2 ? 1 : 0); +} + +inline float tf_g_pow2(int e) { return as_type(uint(e + 127) << 23); } + +// A magnitude of at most 448 as its nearest E4M3 code, ties to even (codes 0..8: subnormals and the first normal). +inline uint tf_g_code(float a) { + uint b = as_type(a); + b += TF_CTL == 3 ? 0x80000u : 0x7FFFFu + ((b >> 20) & 1u); + const uint sub = uint(TF_CTL == 3 ? round(a * 512.0f) : rint(a * 512.0f)); + return a < 0.015625f ? sub : (((b >> 23) - 120u) << 3) | ((b >> 20) & 7u); +} + +// An E4M3 magnitude code exactly: its bits placed as a half's exponent and mantissa, then scaled by 2^8. +inline float tf_g_val(uint c) { return float(as_type(ushort(c << 7))) * 256.0f; } + +// An fp32 magnitude of at most 6 as its nearest E2M1 value, ties to the even code. +inline float tf_g_fp4(float a) { + const bool t = TF_CTL == 3; + if (a < 0.25f || (!t && a == 0.25f)) return 0.0f; + if (a < 0.75f) return 0.5f; + if (a < 1.25f || (!t && a == 1.25f)) return 1.0f; + if (a < 1.75f) return 1.5f; + if (a < 2.5f || (!t && a == 2.5f)) return 2.0f; + if (a < 3.5f) return 3.0f; + return a < 5.0f || (!t && a == 5.0f) ? 4.0f : 6.0f; +} + +// Lane i of an amax over the block's `blk` lanes: a xor butterfly; max is order free, so any tree gives the same bits. +inline float tf_g_amax(float v, uint blk) { + for (uint m = blk / 2; m > 0; m >>= 1) v = max(v, simd_shuffle_xor(v, m)); + return v; +} + +// act_quant inplace (kernel.py:98): s = 2^ceil(log2(max(amax, 1e-4) / 448)), e4m3(x / s) * s; a bad block is NaN. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_fp8_rt( + const device bfloat* X [[buffer(0)]], device bfloat* Y [[buffer(1)]], constant TfQuantArgs& a [[buffer(2)]], + uint2 at [[thread_position_in_grid]]) { + if (at.y >= a.R) return; + const ulong i = ulong(at.y) * a.N + at.x; + const float v = float(X[i]); + const bool bad = TF_CTL == 1 ? false : tf_g_amax(isfinite(v) ? 0.0f : 1.0f, 32) > 0.0f; + const int e = tf_g_exp(tf_g_amax(fabs(v), 32), 1e-4f, 1.0f / 448.0f); + const float q = tf_g_val(tf_g_code(min(fabs(v) * tf_g_pow2(-e), 448.0f))) * tf_g_pow2(e); + Y[i] = bfloat(bad ? NAN : (signbit(v) ? -q : q)); + if (TF_CTL == 4 && at.x == 0 && at.y == 0) Y[ulong(a.R) * a.N] = bfloat(1.0f); +} + +// fp4_act_quant inplace (kernel.py:184): E8M0 blocks of 32 (s = 2^ceil(log2(max(amax, 6 2^-126) / 6))); E4: E4M3 of 16. +template +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_fp4_rt( + const device bfloat* X [[buffer(0)]], device bfloat* Y [[buffer(1)]], constant TfQuantArgs& a [[buffer(2)]], + uint2 at [[thread_position_in_grid]]) { + if (at.y >= a.R) return; + const ulong i = ulong(at.y) * a.N + at.x; + const float v = float(X[i]); + const float amax = tf_g_amax(fabs(v), BLK); + const bool bad = TF_CTL == 1 ? false : tf_g_amax(isfinite(v) ? 0.0f : 1.0f, BLK) > 0.0f; + float s, a_q; + if (E4) { + const float raw = precise::divide(max(amax, 0.01171875f), 6.0f); + s = TF_CTL == 2 ? raw : tf_g_val(tf_g_code(min(raw, 448.0f))); + a_q = min(precise::divide(fabs(v), s), 6.0f); + } else { + const int e = tf_g_exp(amax, 0x1.8p-124f, 1.0f / 6.0f); + s = tf_g_pow2(e); + a_q = min(fabs(v) * tf_g_pow2(-e), 6.0f); + } + const float f = tf_g_fp4(a_q) * s; + Y[i] = bfloat(bad ? NAN : (signbit(v) ? -f : f)); + if (TF_CTL == 4 && at.x == 0 && at.y == 0) Y[ulong(a.R) * a.N] = bfloat(1.0f); +} + +#define TF_FP4(BLK, E4, NAME) \ + template [[host_name(NAME)]] [[kernel]] decltype(tf_dsv41_fp4_rt) tf_dsv41_fp4_rt; +TF_FP4(32, false, "tf_dsv41_fp4_rt32") +TF_FP4(16, true, "tf_dsv41_fp4_rt16") diff --git a/zig/kernels/metal/deepseek_v41/sources.zig b/zig/kernels/metal/deepseek_v41/sources.zig index c9da1ec493d..73252916fe8 100644 --- a/zig/kernels/metal/deepseek_v41/sources.zig +++ b/zig/kernels/metal/deepseek_v41/sources.zig @@ -11,6 +11,7 @@ pub const experts_kimi = @embedFile("experts_kimi.metal"); /// DeepSeek V4.1's routed-expert gate/up (clamped SwiGLU, the reference's activation rounding) over the copy. pub const experts = @embedFile("experts.metal"); pub const xmma = @embedFile("experts_mma.metal"); +pub const glue = @embedFile("glue.metal"); /// DeepSeek-V4.1 router, indexer, compressor and head matvecs: lane chains over K, one butterfly, any row count. pub const mv = @embedFile("mv.metal"); /// DeepSeek-V4.1's phase-1 glue (deepseek_v41/glue_tmp.metal): the reference bits of the registered glue kernels. diff --git a/zig/src/core/contract/dsv41_glue_records.zig b/zig/src/core/contract/dsv41_glue_records.zig new file mode 100644 index 00000000000..9b42ed895e2 --- /dev/null +++ b/zig/src/core/contract/dsv41_glue_records.zig @@ -0,0 +1,18 @@ +//! DeepSeek V4.1's glue launches on Metal: each reserves its thread count, so none depends on the M1/M2 compile. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "dsv41 glue rms bf16w tf_dsv41_rms_bf16w", .threads = 256, .tg_memory = 32, .reserved = 256 }, + .{ .name = "dsv41 glue rms f32w tf_dsv41_rms_f32w", .threads = 256, .tg_memory = 32, .reserved = 256 }, + .{ .name = "dsv41 glue embed tf_dsv41_embed", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "dsv41 glue join tf_dsv41_moe_join", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "dsv41 glue mean tf_dsv41_hc_mean", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "dsv41 glue rope tf_dsv41_rope", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "dsv41 glue fp8 round trip tf_dsv41_fp8_rt", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "dsv41 glue fp4 e8m0 round trip tf_dsv41_fp4_rt32", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "dsv41 glue fp4 e4m3 round trip tf_dsv41_fp4_rt16", .threads = 32, .tg_memory = 0, .reserved = 32 }, +}; + +test "the DeepSeek V4.1 glue launches fit every Apple family" { + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/contract/dsv41_metal_records.zig b/zig/src/core/contract/dsv41_metal_records.zig index e644c92dc85..b8a5250c155 100644 --- a/zig/src/core/contract/dsv41_metal_records.zig +++ b/zig/src/core/contract/dsv41_metal_records.zig @@ -3,6 +3,7 @@ const M = @import("limits.zig").MetalLaunch; const head = @import("dsv41_fp8_records.zig").records ++ @import("dsv41_fp8_mma_records.zig").records ++ @import("dsv41_attn_records.zig").records ++ @import("dsv41_experts_records.zig").records ++ - @import("dsv41_xmma_records.zig").records ++ @import("dsv41_mv_records.zig").records; + @import("dsv41_glue_records.zig").records ++ @import("dsv41_xmma_records.zig").records ++ + @import("dsv41_mv_records.zig").records; pub const records = head ++ @import("dsv41_glue_tmp_records.zig").records; diff --git a/zig/src/families/deepseek_v41/metal/contract_exports.zig b/zig/src/families/deepseek_v41/metal/contract_exports.zig index 964c7b44c8a..0cf4950e363 100644 --- a/zig/src/families/deepseek_v41/metal/contract_exports.zig +++ b/zig/src/families/deepseek_v41/metal/contract_exports.zig @@ -4,5 +4,6 @@ pub const fp8_rows = @import("fp8_rows.zig"); pub const attn = @import("csa2_attn.zig"); pub const experts = @import("experts.zig"); pub const mv = @import("mv.zig"); +pub const glue = @import("glue_k.zig"); pub const xmma = @import("experts_mma.zig"); pub const glue_tmp = @import("glue.zig"); diff --git a/zig/src/families/deepseek_v41/metal/glue_k.zig b/zig/src/families/deepseek_v41/metal/glue_k.zig new file mode 100644 index 00000000000..e99c6f8dae6 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/glue_k.zig @@ -0,0 +1,208 @@ +//! DeepSeek V4.1 glue on Metal: RMS norm, embedding, joins, RoPE and act-quant round trips, and the RoPE tables. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; + +/// One pipeline a kernel; every kernel's rows are independent, so no launch shape changes a bit. +pub const Pipelines = struct { + rms_bf16: mtl.Pipeline, + rms_f32: mtl.Pipeline, + embed: mtl.Pipeline, + join: mtl.Pipeline, + mean: mtl.Pipeline, + rope: mtl.Pipeline, + fp8: mtl.Pipeline, + fp4_e8m0: mtl.Pipeline, + fp4_e4m3: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.dsv41.glue); + } + + /// The same kernels from other text: the contract's planted controls prefix a TF_CTL define. + 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 p: Pipelines = undefined; + p.rms_bf16 = try mtl.Pipeline.init(device, lib, "tf_dsv41_rms_bf16w", false); + p.rms_f32 = try mtl.Pipeline.init(device, lib, "tf_dsv41_rms_f32w", false); + p.embed = try mtl.Pipeline.init(device, lib, "tf_dsv41_embed", false); + p.join = try mtl.Pipeline.init(device, lib, "tf_dsv41_moe_join", false); + p.mean = try mtl.Pipeline.init(device, lib, "tf_dsv41_hc_mean", false); + p.rope = try mtl.Pipeline.init(device, lib, "tf_dsv41_rope", false); + p.fp8 = try mtl.Pipeline.init(device, lib, "tf_dsv41_fp8_rt", false); + p.fp4_e8m0 = try mtl.Pipeline.init(device, lib, "tf_dsv41_fp4_rt32", false); + p.fp4_e4m3 = try mtl.Pipeline.init(device, lib, "tf_dsv41_fp4_rt16", false); + return p; + } + + pub fn deinit(p: *Pipelines) void { + for ([_]mtl.Pipeline{ p.rms_bf16, p.rms_f32, p.embed, p.join, p.mean, p.rope, p.fp8, p.fp4_e8m0, p.fp4_e4m3 }) |x| x.deinit(); + } +}; + +pub const rms_threads = 256; + +const RmsArgs = extern struct { D: u32, R: u32, eps: f32 }; + +/// y [rows][d] bf16 = RMS norm of x with weight w (bf16, or fp32 when `w32`); d any size, one threadgroup a row. +pub fn rms(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, y: Ref, rows: u32, d: u32, eps: f32, w32: bool) void { + e.setPipeline(if (w32) p.rms_f32 else p.rms_bf16); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(w.buf, w.off, 1); + e.setBuffer(y.buf, y.off, 2); + e.setValue(RmsArgs{ .D = d, .R = rows, .eps = eps }, 3); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(rms_threads, 1, 1)); +} + +const EmbedArgs = extern struct { D: u32, R: u32, V: u32, reps: u32, lo: i32 }; + +/// out [n][reps][d] bf16 from the rank's slice table [v][d] (global ids lo .. lo + v); an id off it gives zeros. +pub fn embed(p: *const Pipelines, e: mtl.ComputeEncoder, ids: Ref, table: Ref, out: Ref, n: u32, d: u32, v: u32, lo: i32, reps: u32) void { + e.setPipeline(p.embed); + e.setBuffer(ids.buf, ids.off, 0); + e.setBuffer(table.buf, table.off, 1); + e.setBuffer(out.buf, out.off, 2); + e.setValue(EmbedArgs{ .D = d, .R = n, .V = v, .lo = lo, .reps = reps }, 3); + e.dispatchThreads(mtl.Size.of(d / 2, n, 1), mtl.Size.of(32, 1, 1)); +} + +/// y [n] bf16 = routed [n] fp32 + shared [n] bf16, one rounding. +pub fn moeJoin(p: *const Pipelines, e: mtl.ComputeEncoder, routed: Ref, shared: Ref, y: Ref, n: u32) void { + e.setPipeline(p.join); + e.setBuffer(routed.buf, routed.off, 0); + e.setBuffer(shared.buf, shared.off, 1); + e.setBuffer(y.buf, y.off, 2); + e.setValue(n, 3); + e.dispatchThreads(mtl.Size.of(n, 1, 1), mtl.Size.of(32, 1, 1)); +} + +const MeanArgs = extern struct { D: u32, R: u32, hc: u32 }; + +/// y [n][d] bf16 = mean over the hc copies of x [n][hc][d] bf16. +pub fn hcMean(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, y: Ref, n: u32, d: u32, hc: u32) void { + e.setPipeline(p.mean); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(y.buf, y.off, 1); + e.setValue(MeanArgs{ .D = d, .R = n, .hc = hc }, 2); + e.dispatchThreads(mtl.Size.of(d, n, 1), mtl.Size.of(32, 1, 1)); +} + +/// Rows of `heads` heads, the rope tail at element `off` of each head; strides in bf16 elements, all even. x may be y. +pub const RopeCall = struct { rows: u32, heads: u32 = 1, pairs: u32 = 32, ldx: u32, hx: u32, ox: u32, ldy: u32, hy: u32, oy: u32 }; + +const RopeArgs = extern struct { R: u32, H: u32, pairs: u32, ldx: u32, hx: u32, ox: u32, ldy: u32, hy: u32, oy: u32 }; + +/// An in-place call on [rows][heads][head_dim] rows: the last 2 * pairs elements of each head. +pub fn ropeInPlace(rows: u32, heads: u32, head_dim: u32, pairs: u32) RopeCall { + const tail = head_dim - 2 * pairs; + return .{ .rows = rows, .heads = heads, .pairs = pairs, .ldx = heads * head_dim, .hx = head_dim, .ox = tail, .ldy = heads * head_dim, .hy = head_dim, .oy = tail }; +} + +pub fn ropeCheck(c: RopeCall) !void { + for ([_]u32{ c.ldx, c.hx, c.ox, c.ldy, c.hy, c.oy }) |v| if (v % 2 != 0) return error.BadRopeStride; + if (c.rows == 0 or c.heads == 0 or c.pairs == 0 or c.pairs > 32) return error.BadRopeShape; +} + +/// pos [rows] i32 indexes tab [position][pairs] float2 (cos, sin); the tail of each head is rotated into y. +pub fn rope(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, y: Ref, pos: Ref, tab: Ref, c: RopeCall) !void { + try ropeCheck(c); + e.setPipeline(p.rope); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(y.buf, y.off, 1); + e.setBuffer(pos.buf, pos.off, 2); + e.setBuffer(tab.buf, tab.off, 3); + e.setValue(RopeArgs{ .R = c.rows, .H = c.heads, .pairs = c.pairs, .ldx = c.ldx, .hx = c.hx, .ox = c.ox, .ldy = c.ldy, .hy = c.hy, .oy = c.oy }, 4); + e.dispatchThreads(mtl.Size.of(c.pairs, c.heads, c.rows), mtl.Size.of(32, 1, 1)); +} + +/// fp8: act_quant blocks of 32; fp4_e8m0: indexer q and k, blocks of 32; fp4_e4m3: compressed KV, blocks of 16. +pub const Quant = enum { fp8, fp4_e8m0, fp4_e4m3 }; + +const QuantArgs = extern struct { N: u32, R: u32 }; + +/// y [rows][n] bf16 = the round trip of x [rows][n] bf16; n a multiple of 32. x may be y (a block is read whole first). +pub fn quant(p: *const Pipelines, e: mtl.ComputeEncoder, kind: Quant, x: Ref, y: Ref, rows: u32, n: u32) !void { + if (rows == 0 or n == 0 or n % 32 != 0) return error.BadQuantShape; + e.setPipeline(switch (kind) { + .fp8 => p.fp8, + .fp4_e8m0 => p.fp4_e8m0, + .fp4_e4m3 => p.fp4_e4m3, + }); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(y.buf, y.off, 1); + e.setValue(QuantArgs{ .N = n, .R = rows }, 2); + e.dispatchThreads(mtl.Size.of(n, rows, 1), mtl.Size.of(32, 1, 1)); +} + +/// A RoPE spectrum (model.py:369): inverse frequencies theta^(-2i/dim), YaRN-blended when `original` is not 0. +pub const RopeSpec = struct { + theta: f64, + dim: u32 = 64, + factor: f32 = 1, + beta_fast: f64 = 32, + beta_slow: f64 = 1, + original: u32 = 0, + + /// Layers without compression: plain rope_theta, no YaRN. + pub const sliding: RopeSpec = .{ .theta = 10000 }; + /// Compressed layers: compress_rope_theta with the release's rope_scaling. + pub const compressed: RopeSpec = .{ .theta = 160000, .factor = 16, .original = 65536 }; +}; + +fn correctedDim(s: RopeSpec, rotations: f64) f64 { + const dim: f64 = @floatFromInt(s.dim); + return dim * @log(@as(f64, @floatFromInt(s.original)) / (rotations * 2 * std.math.pi)) / (2 * @log(s.theta)); +} + +/// The spectrum's dim / 2 fp32 frequencies, each step rounded to fp32 as torch's eager ops do. +pub fn ropeFreqs(s: RopeSpec, out: []f32) void { + const dim: f32 = @floatFromInt(s.dim); + for (out, 0..) |*f, i| { + const e = @as(f32, @floatFromInt(2 * i)) / dim; + f.* = 1.0 / @as(f32, @floatCast(std.math.pow(f64, s.theta, e))); + } + if (s.original == 0) return; + const low = @max(@floor(correctedDim(s, s.beta_fast)), 0); + const high = @min(@ceil(correctedDim(s, s.beta_slow)), @as(f64, @floatFromInt(s.dim)) - 1); + const span: f32 = @floatCast(@max(high - low, 1e-3)); + for (out, 0..) |*f, i| { + const ramp = std.math.clamp((@as(f32, @floatFromInt(i)) - @as(f32, @floatCast(low))) / span, 0, 1); + const smooth = 1 - ramp; + f.* = f.* / s.factor * (1 - smooth) + f.* * smooth; + } +} + +/// Position `pos`'s (cos, sin) pairs: the fp32 angle pos * freq, then its cos and sin rounded once to fp32. +pub fn ropeRow(freqs: []const f32, pos: u32, out: [][2]f32) void { + for (freqs, out) |f, *o| { + const angle: f64 = @as(f32, @floatFromInt(pos)) * f; + o.* = .{ @floatCast(@cos(angle)), @floatCast(@sin(angle)) }; + } +} + +/// The table [positions][dim / 2] of (cos, sin) the rope kernel reads, built for one spectrum. +pub fn ropeTable(a: std.mem.Allocator, s: RopeSpec, positions: u32) ![][2]f32 { + const freqs = try a.alloc(f32, s.dim / 2); + defer a.free(freqs); + ropeFreqs(s, freqs); + const out = try a.alloc([2]f32, @as(usize, positions) * freqs.len); + for (0..positions) |p| ropeRow(freqs, @intCast(p), out[p * freqs.len ..][0..freqs.len]); + return out; +} + +test "the two spectra: sliding is plain theta, compressed divides the slow end by the factor and keeps the fast end" { + var plain: [32]f32 = undefined; + var yarn: [32]f32 = undefined; + ropeFreqs(RopeSpec.sliding, &plain); + ropeFreqs(RopeSpec.compressed, &yarn); + try std.testing.expectEqual(@as(f32, 1.0), plain[0]); + try std.testing.expectEqual(@as(f32, 1.0), yarn[0]); + try std.testing.expectApproxEqRel(@as(f32, 1.3335e-4), plain[31], 1e-3); + var base: [32]f32 = undefined; + ropeFreqs(.{ .theta = 160000 }, &base); + try std.testing.expectApproxEqRel(base[31] / 16, yarn[31], 1e-6); + try std.testing.expectEqual(base[0], yarn[0]); +} diff --git a/zig/tests/contract/metal_dsv41_glue.zig b/zig/tests/contract/metal_dsv41_glue.zig new file mode 100644 index 00000000000..6adf7a1907f --- /dev/null +++ b/zig/tests/contract/metal_dsv41_glue.zig @@ -0,0 +1,550 @@ +//! DeepSeek V4.1's glue kernels under the contract on Metal: RMS norm, embedding, joins, RoPE and act-quant. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const sources = @import("kernel_sources"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const ref = @import("dsv41_glue_ref.zig"); + +const c = contract.spec; +const g = contract.gates; +const rows_ = contract.rows; +const gl = tf.dsv41_metal.glue; +const base = "dsv41 glue "; +const eps: f32 = 1e-20; // rms_norm_eps +const rope_positions = 66560; // past the YaRN original length, 65,536 +const vocab: u32 = 300; // the embed probe's rank slice holds ids 100 to 399 +const vocab_lo: i32 = 100; + +pub const Fam = enum { rms_bf16, rms_f32, embed, join, mean, rope_sliding, rope_yarn, fp8, fp4_e8m0, fp4_e4m3 }; + +fn isQuant(f: Fam) bool { + return f == .fp8 or f == .fp4_e8m0 or f == .fp4_e4m3; +} + +fn isRope(f: Fam) bool { + return f == .rope_sliding or f == .rope_yarn; +} + +fn noSums(_: c.Shape) usize { + return 0; +} + +/// Per thread a chain over every 256th square, then the 5-step butterfly and the seven adds over simdgroups. +fn rmsDepth(s: c.Shape) usize { + return (s.k + 255) / 256 + 12; +} + +const rms_why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps"; +const quant_rule = "a block holding a NaN or an infinity is all NaN; every other output is the reference's round trip, exact"; + +pub fn spec(f: Fam, name: []const u8) c.Spec { + const tiles16: c.Tile = .{ .size = 16 }; + return switch (f) { + .rms_bf16, .rms_f32 => .{ .name = name, .accum = .f32, .depth = rmsDepth, .ops = 8, .out = .bf16, .tiles = .{ tiles16, .{}, .{ .size = 256, .step = 64, .min = 64 } }, .served = &.{ + .{ .rows = 16, .n = 5120, .k = 5120 }, .{ .rows = 1, .n = 5120, .k = 5120 }, .{ .rows = 4, .n = 1280, .k = 1280 }, + .{ .rows = 8, .n = 512, .k = 512 }, .{ .rows = 16, .n = 128, .k = 128 }, .{ .rows = 3, .n = 2048, .k = 2048 }, + }, .sums = .{ .bf16 = 0, .why = rms_why } }, + .embed => .{ .name = name, .accum = .none, .depth = noSums, .out = .bf16, .tiles = .{ tiles16, .{ .size = 64, .step = 2, .min = 2 }, .{} }, .served = &.{ + .{ .rows = 16, .n = 5120, .k = 4 }, .{ .rows = 1, .n = 5120, .k = 1 }, .{ .rows = 5, .n = 5120, .k = 4 }, .{ .rows = 9, .n = 128, .k = 4 }, + } }, + .join => .{ .name = name, .accum = .none, .depth = noSums, .ops = 1, .out = .bf16, .tiles = .{ tiles16, .{ .size = 64 }, .{} }, .served = &.{ + .{ .rows = 16, .n = 5120, .k = 1 }, .{ .rows = 1, .n = 5120, .k = 1 }, .{ .rows = 5, .n = 1280, .k = 1 }, .{ .rows = 8, .n = 2304, .k = 1 }, + } }, + .mean => .{ .name = name, .accum = .none, .depth = noSums, .out = .bf16, .tiles = .{ tiles16, .{ .size = 64 }, .{} }, .served = &.{ + .{ .rows = 16, .n = 5120, .k = 4 }, .{ .rows = 1, .n = 5120, .k = 4 }, .{ .rows = 6, .n = 512, .k = 4 }, + } }, + .rope_sliding, .rope_yarn => .{ .name = name, .accum = .none, .depth = noSums, .out = .bf16, .tiles = .{ tiles16, .{ .size = 8 }, .{} }, .served = &.{ + .{ .rows = 16, .n = 64, .k = 512 }, .{ .rows = 1, .n = 1, .k = 512 }, .{ .rows = 5, .n = 1, .k = 512 }, + .{ .rows = 8, .n = 32, .k = 128 }, .{ .rows = 6, .n = 1, .k = 128 }, + } }, + .fp8, .fp4_e8m0, .fp4_e4m3 => .{ .name = name, .accum = .none, .depth = noSums, .out = .bf16, .nan = .{ .stated = quant_rule }, .tiles = .{ tiles16, .{ .size = 256, .step = 32, .min = 32 }, .{} }, .served = &.{ + .{ .rows = 16, .n = 5120, .k = 5120 }, .{ .rows = 1, .n = 1280, .k = 1280 }, .{ .rows = 5, .n = 4096, .k = 4096 }, .{ .rows = 8, .n = 8192, .k = 8192 }, + .{ .rows = 16, .n = 512, .k = 512 }, .{ .rows = 6, .n = 128, .k = 128 }, .{ .rows = 2, .n = 2304, .k = 2304 }, + } }, + }; +} + +var table_cache: [2]?[][2]f32 = .{ null, null }; + +fn tableFor(f: Fam) ![][2]f32 { + const i: usize = if (f == .rope_yarn) 1 else 0; + if (table_cache[i]) |t| return t; + const t = try gl.ropeTable(std.heap.page_allocator, if (i == 1) gl.RopeSpec.compressed else gl.RopeSpec.sliding, rope_positions); + table_cache[i] = t; + return t; +} + +fn pow2(e: i32) f32 { + return std.math.pow(f32, 2, @floatFromInt(e)); +} + +fn spread(rng: std.Random, lo: i32, hi: i32) f32 { + return (rng.float(f32) * 2 - 1) * pow2(rng.intRangeAtMost(i32, lo, hi)); +} + +fn at(r: rig_.Ref, extra: usize) gl.Ref { + return .{ .buf = r.buf, .off = r.off + extra }; +} + +const vt_checked = g.hooks(Proj); +const vt_plain = blk: { + var v = g.hooks(Proj); + v.check = null; + break :blk v; +}; + +pub const Proj = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + fam: Fam, + ctl: u8, + name: []const u8, + pipes: gl.Pipelines, + shape: c.Shape = undefined, + rows_f: ?rows_.Rows = null, + x: []u16 = &.{}, + r32: []f32 = &.{}, + ids: []i32 = &.{}, + pos: []i32 = &.{}, + table: []u16 = &.{}, + tab: [][2]f32 = &.{}, + plants: usize = 0, + in: [3]rig_.Ref = undefined, + out: rig_.Ref = undefined, + msg: [200]u8 = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, f: Fam, ctl: u8, name: []const u8) !Proj { + var p: Proj = .{ .a = a, .arena = std.heap.ArenaAllocator.init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .fam = f, .ctl = ctl, .name = name, .pipes = undefined }; + if (ctl == 0) { + p.pipes = try gl.Pipelines.load(device); + } else { + const text = try std.fmt.allocPrint(a, "#define TF_CTL {d}\n{s}", .{ ctl, sources.dsv41.glue }); + defer a.free(text); + p.pipes = try gl.Pipelines.loadSource(device, text); + } + return p; + } + + pub fn deinit(p: *Proj) void { + p.arena.deinit(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Proj) g.Kernel { + const control: ?g.Gate = switch (p.ctl) { + 0 => null, + 1 => .nonfinite, + 2 => .shapes, + 3 => if (isQuant(p.fam)) .shapes else .sums, + else => .repeat, + }; + return .{ .spec = spec(p.fam, p.name), .ctx = p, .vt = if (isQuant(p.fam)) &vt_checked else &vt_plain, .control = control }; + } + + fn quantKind(p: *const Proj) ref.Kind { + return switch (p.fam) { + .fp8 => .fp8, + .fp4_e8m0 => .fp4_e8m0, + else => .fp4_e4m3, + }; + } + + fn glQuant(p: *const Proj) gl.Quant { + return switch (p.fam) { + .fp8 => .fp8, + .fp4_e8m0 => .fp4_e8m0, + else => .fp4_e4m3, + }; + } + + pub fn count(p: *Proj) usize { + const s = p.shape; + return switch (p.fam) { + .rms_bf16, .rms_f32 => s.rows * s.k, + .embed => s.rows * s.k * s.n, + .join, .mean => s.rows * s.n, + .rope_sliding, .rope_yarn => s.rows * s.n * 64, + else => s.rows * s.n, + }; + } + + fn bf16s(a: std.mem.Allocator, n: usize, rng: std.Random, lo: i32, hi: i32) ![]u16 { + const v = try a.alloc(u16, n); + for (v) |*o| o.* = c.toBf16(spread(rng, lo, hi)); + return v; + } + + pub fn prepare(p: *Proj, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + p.rig.reset(); + _ = p.arena.reset(.retain_capacity); + const a = p.arena.allocator(); + p.shape = shape; + p.plants = 0; + p.rows_f = null; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const nf = fill == .nonfinite; + switch (p.fam) { + .rms_bf16, .rms_f32 => { + var r = try rows_.Rows.init(a, .rms, .{ .rows = shape.rows, .n = shape.k, .k = shape.k }); + r.eps = eps; + r.fill(fill, seed); + p.rows_f = r; + p.in[0] = try p.rig.input(std.mem.sliceAsBytes(r.x)); + if (p.fam == .rms_f32) { + p.r32 = try a.alloc(f32, r.w.len); + for (p.r32, r.w) |*o, w| o.* = c.fromBf16(w); + p.in[1] = try p.rig.input(std.mem.sliceAsBytes(p.r32)); + } else p.in[1] = try p.rig.input(std.mem.sliceAsBytes(r.w)); + }, + .embed => { + if (shape.n % 2 != 0 or shape.n == 0) return false; + p.table = try bf16s(a, vocab * shape.n, rng, -2, 2); + p.ids = try a.alloc(i32, shape.rows); + for (p.ids) |*id| id.* = if (rng.uintLessThan(u32, 4) == 0) rng.intRangeLessThan(i32, -3, 520) else vocab_lo + @as(i32, @intCast(rng.uintLessThan(u32, vocab))); + if (nf) { + for (0..@min(4, shape.rows)) |i| p.ids[i] = vocab_lo + @as(i32, @intCast(i)); + p.plants = ref.plant(p.table, 4, shape.n, 0, shape.n); + } + p.in[0] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.in[1] = try p.rig.input(std.mem.sliceAsBytes(p.table)); + }, + .join => { + const n = shape.rows * shape.n; + p.r32 = try a.alloc(f32, n); + for (p.r32) |*o| o.* = spread(rng, -6, 6); + p.x = try bf16s(a, n, rng, -6, 6); + if (nf) { + const d = shape.n; + p.r32[d / 3] = std.math.nan(f32); + p.r32[d + d / 2] = std.math.inf(f32); + p.x[d + d / 2] = c.toBf16(-std.math.inf(f32)); + p.r32[2 * d + d - 1] = -std.math.inf(f32); + p.x[3 * d] = c.toBf16(std.math.inf(f32)); + p.plants = 4; + } + p.in[0] = try p.rig.input(std.mem.sliceAsBytes(p.r32)); + p.in[1] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + }, + .mean => { + p.x = try bf16s(a, shape.rows * shape.k * shape.n, rng, -8, 8); + if (nf) p.plants = ref.plant(p.x, shape.rows, shape.k * shape.n, 0, shape.k * shape.n); + p.in[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + }, + .rope_sliding, .rope_yarn => { + if (shape.k < 64) return false; + p.tab = try tableFor(p.fam); + p.x = try bf16s(a, shape.rows * shape.n * shape.k, rng, -3, 3); + p.pos = try a.alloc(i32, shape.rows); + const edge = [_]i32{ 65535, 65536, 65537, rope_positions - 1 }; + for (p.pos, 0..) |*o, i| o.* = if (i % 4 == 0) edge[i / 4 % 4] else @intCast(rng.uintLessThan(u32, rope_positions)); + if (nf) p.plants = ref.plant(p.x, shape.rows, shape.n * shape.k, shape.k - 64, 64); + p.in[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.in[1] = try p.rig.input(std.mem.sliceAsBytes(p.pos)); + p.in[2] = try p.rig.input(std.mem.sliceAsBytes(p.tab)); + }, + .fp8, .fp4_e8m0, .fp4_e4m3 => { + if (shape.n % 32 != 0 or shape.n == 0) return false; + p.x = try a.alloc(u16, shape.rows * shape.n); + ref.fillQuant(p.quantKind(), p.x, ref.block(p.quantKind()), seed); + if (nf) p.plants = ref.plant(p.x, shape.rows, shape.n, 0, shape.n); + p.in[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + }, + } + p.out = try p.rig.output(p.count() * 2); + return true; + } + + /// Rows r0 to r0 + n of the prepared call as one launch (tokens, or elements for the join); p.in[] are whole. + pub fn encode(p: *Proj, e: anytype, r0: usize, n: usize) !void { + const s = p.shape; + const pl = &p.pipes; + switch (p.fam) { + .rms_bf16, .rms_f32 => gl.rms(pl, e, at(p.in[0], r0 * s.k * 2), at(p.in[1], 0), at(p.out, r0 * s.k * 2), @intCast(n), @intCast(s.k), eps, p.fam == .rms_f32), + .embed => gl.embed(pl, e, at(p.in[0], r0 * 4), at(p.in[1], 0), at(p.out, r0 * s.k * s.n * 2), @intCast(n), @intCast(s.n), vocab, vocab_lo, @intCast(s.k)), + .join => gl.moeJoin(pl, e, at(p.in[0], r0 * s.n * 4), at(p.in[1], r0 * s.n * 2), at(p.out, r0 * s.n * 2), @intCast(n * s.n)), + .mean => gl.hcMean(pl, e, at(p.in[0], r0 * s.k * s.n * 2), at(p.out, r0 * s.n * 2), @intCast(n), @intCast(s.n), @intCast(s.k)), + .rope_sliding, .rope_yarn => { + const hd: u32 = @intCast(s.k); + const h: u32 = @intCast(s.n); + const call: gl.RopeCall = .{ .rows = @intCast(n), .heads = h, .ldx = h * hd, .hx = hd, .ox = hd - 64, .ldy = h * 64, .hy = 64, .oy = 0 }; + try gl.rope(pl, e, at(p.in[0], r0 * h * hd * 2), at(p.out, r0 * h * 64 * 2), at(p.in[1], r0 * 4), at(p.in[2], 0), call); + }, + else => try gl.quant(pl, e, p.glQuant(), at(p.in[0], r0 * s.n * 2), at(p.out, r0 * s.n * 2), @intCast(n), @intCast(s.n)), + } + } + + pub fn run(p: *Proj) !void { + const pass = p.rig.begin(); + try p.encode(pass.e, 0, p.shape.rows); + try p.rig.finish(pass); + } + + pub fn reference(p: *Proj, want: []f64, mag: []f64) !void { + const s = p.shape; + @memset(mag, 0); + switch (p.fam) { + .rms_bf16, .rms_f32 => try p.rows_f.?.reference(want, mag), + .embed => for (0..s.rows) |t| for (0..s.k) |j| for (0..s.n) |d| { + const id = p.ids[t] - vocab_lo; + want[(t * s.k + j) * s.n + d] = if (id >= 0 and id < vocab) c.fromBf16(p.table[@as(usize, @intCast(id)) * s.n + d]) else 0; + }, + .join => for (want, p.r32, p.x) |*w, r, sh| { + w.* = @as(f64, r) + c.fromBf16(sh); + }, + .mean => for (0..s.rows) |t| for (0..s.n) |d| { + var sum: f64 = 0; + var abs: f64 = 0; + for (0..s.k) |j| { + const v: f64 = c.fromBf16(p.x[(t * s.k + j) * s.n + d]); + sum += v; + abs += @abs(v); + } + want[t * s.n + d] = sum / @as(f64, @floatFromInt(s.k)); + mag[t * s.n + d] = abs / @as(f64, @floatFromInt(s.k)); + }, + .rope_sliding, .rope_yarn => for (0..s.rows) |t| for (0..s.n) |h| for (0..32) |i| { + const from = (t * s.n + h) * s.k + s.k - 64 + 2 * i; + const xr: f64 = c.fromBf16(p.x[from]); + const xi: f64 = c.fromBf16(p.x[from + 1]); + const cs = p.tab[@as(usize, @intCast(p.pos[t])) * 32 + i]; + const co: f64 = cs[0]; + const si: f64 = cs[1]; + const o = (t * s.n + h) * 64 + 2 * i; + want[o] = xr * co - xi * si; + want[o + 1] = xr * si + xi * co; + mag[o] = @abs(xr * co) + @abs(xi * si); + mag[o + 1] = @abs(xr * si) + @abs(xi * co); + }, + else => @memset(want, 0), + } + } + + /// Embedding gathers are exact; the fp32 steps of the mean and RoPE add 2^-24 of their term magnitudes. + pub fn bounds(p: *Proj, want: []const f64, mag: []const f64, allow: []f64) !void { + switch (p.fam) { + .embed => @memset(allow, 0), + .mean, .rope_sliding, .rope_yarn => { + const steps: f64 = if (p.fam == .mean) @floatFromInt(p.shape.k + 1) else 4; + for (allow, want, mag) |*l, w, m| { + const e32 = steps * 0x1p-24 * m; + l.* = e32 + 0x1p-8 * (@abs(w) + e32) + 0x1p-133; + } + }, + else => {}, + } + } + + pub fn simulate(p: *Proj, acc: c.Accum, order: g.Order, out: []f64) !void { + return (p.rows_f orelse return error.NoSums).simulate(acc, order, out); + } + + fn nanBits(v: u16) bool { + return (v & 0x7fff) > 0x7f80; + } + + /// Every block against the oracle's bits (any NaN equals any NaN); gate 1 also needs the plants to have landed. + pub fn check(p: *Proj, gate: g.Gate) !?[]const u8 { + const s = p.shape; + const kind = p.quantKind(); + const blk = ref.block(kind); + const got = std.mem.bytesAsSlice(u16, p.rig.bytes(p.out, p.count() * 2)); + var xs: [32]f32 = undefined; + var want: [32]u16 = undefined; + var bad_blocks: usize = 0; + for (0..s.rows * s.n / blk) |b| { + const x = p.x[b * blk ..][0..blk]; + for (xs[0..blk], x) |*o, v| o.* = c.fromBf16(v); + ref.roundTrip(kind, xs[0..blk], want[0..blk]); + for (want[0..blk], got[b * blk ..][0..blk], 0..) |w, h, i| { + if (w != h and !(nanBits(w) and nanBits(h))) return try std.fmt.bufPrint(&p.msg, "block {d} element {d} of {d}x{d}: got 0x{x:0>4}, the round trip gives 0x{x:0>4}", .{ b, i, s.rows, s.n, h, w }); + } + if (nanBits(want[0])) bad_blocks += 1; + } + if (gate == .nonfinite and (p.plants < 5 or bad_blocks < 4)) return try std.fmt.bufPrint(&p.msg, "{d} plants, {d} NaN blocks: no proof", .{ p.plants, bad_blocks }); + return null; + } +}; + +/// Every registered variant and the launch-split and in-place probes after the gates. +pub const Suite = struct { + a: std.mem.Allocator, + probes: std.ArrayList(*Proj) = .empty, + + const E = struct { f: Fam, ctl: u8, name: []const u8 }; + const list = [_]E{ + .{ .f = .rms_bf16, .ctl = 0, .name = base ++ "rms bf16 weight tf_dsv41_rms_bf16w" }, + .{ .f = .rms_f32, .ctl = 0, .name = base ++ "rms f32 weight tf_dsv41_rms_f32w" }, + .{ .f = .rms_bf16, .ctl = 1, .name = base ++ "control: rms non-finite inputs flushed" }, + .{ .f = .rms_bf16, .ctl = 2, .name = base ++ "control: rms last input dropped from the sum" }, + .{ .f = .rms_bf16, .ctl = 3, .name = base ++ "control: rms partial sums rounded to fp16" }, + .{ .f = .rms_bf16, .ctl = 4, .name = base ++ "control: rms writes past its output" }, + .{ .f = .embed, .ctl = 0, .name = base ++ "embed tf_dsv41_embed" }, + .{ .f = .embed, .ctl = 1, .name = base ++ "control: embed NaN and infinity rows flushed" }, + .{ .f = .embed, .ctl = 2, .name = base ++ "control: embed last pair of a row skipped" }, + .{ .f = .embed, .ctl = 4, .name = base ++ "control: embed writes past its output" }, + .{ .f = .join, .ctl = 0, .name = base ++ "moe join tf_dsv41_moe_join" }, + .{ .f = .join, .ctl = 1, .name = base ++ "control: join non-finite inputs flushed" }, + .{ .f = .join, .ctl = 2, .name = base ++ "control: join rounds the routed sum to bf16 first" }, + .{ .f = .join, .ctl = 4, .name = base ++ "control: join writes past its output" }, + .{ .f = .mean, .ctl = 0, .name = base ++ "hc mean tf_dsv41_hc_mean" }, + .{ .f = .mean, .ctl = 1, .name = base ++ "control: hc mean non-finite inputs flushed" }, + .{ .f = .mean, .ctl = 2, .name = base ++ "control: hc mean drops the last copy" }, + .{ .f = .mean, .ctl = 4, .name = base ++ "control: hc mean writes past its output" }, + .{ .f = .rope_sliding, .ctl = 0, .name = base ++ "rope sliding spectrum tf_dsv41_rope" }, + .{ .f = .rope_yarn, .ctl = 0, .name = base ++ "rope compressed YaRN spectrum tf_dsv41_rope" }, + .{ .f = .rope_yarn, .ctl = 1, .name = base ++ "control: rope non-finite inputs flushed" }, + .{ .f = .rope_yarn, .ctl = 2, .name = base ++ "control: rope reads the wrong pairs" }, + .{ .f = .rope_yarn, .ctl = 4, .name = base ++ "control: rope writes past its output" }, + .{ .f = .fp8, .ctl = 0, .name = base ++ "fp8 round trip tf_dsv41_fp8_rt" }, + .{ .f = .fp8, .ctl = 1, .name = base ++ "control: fp8 NaN not flagged" }, + .{ .f = .fp8, .ctl = 2, .name = base ++ "control: fp8 scale exponent floored" }, + .{ .f = .fp8, .ctl = 3, .name = base ++ "control: fp8 ties rounded away from zero" }, + .{ .f = .fp8, .ctl = 4, .name = base ++ "control: fp8 writes past its output" }, + .{ .f = .fp4_e8m0, .ctl = 0, .name = base ++ "fp4 e8m0 block 32 round trip tf_dsv41_fp4_rt32" }, + .{ .f = .fp4_e8m0, .ctl = 1, .name = base ++ "control: fp4 e8m0 NaN not flagged" }, + .{ .f = .fp4_e8m0, .ctl = 2, .name = base ++ "control: fp4 e8m0 scale exponent floored" }, + .{ .f = .fp4_e8m0, .ctl = 3, .name = base ++ "control: fp4 e8m0 ties rounded away from zero" }, + .{ .f = .fp4_e8m0, .ctl = 4, .name = base ++ "control: fp4 e8m0 writes past its output" }, + .{ .f = .fp4_e4m3, .ctl = 0, .name = base ++ "fp4 e4m3 block 16 round trip tf_dsv41_fp4_rt16" }, + .{ .f = .fp4_e4m3, .ctl = 1, .name = base ++ "control: fp4 e4m3 NaN not flagged" }, + .{ .f = .fp4_e4m3, .ctl = 2, .name = base ++ "control: fp4 e4m3 scale left unrounded to E4M3" }, + .{ .f = .fp4_e4m3, .ctl = 4, .name = base ++ "control: fp4 e4m3 writes past its output" }, + }; + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { + const s = try a.create(Suite); + s.* = .{ .a = a }; + for (list) |entry| { + if (only) |text| if (std.mem.indexOf(u8, entry.name, text) == null) continue; + const p = try a.create(Proj); + p.* = try Proj.init(a, device, queue, entry.f, entry.ctl, entry.name); + try s.probes.append(a, p); + try kernels.append(a, p.kernel()); + } + return s; + } + + pub fn destroy(s: *Suite) void { + for (s.probes.items) |p| { + p.deinit(); + s.a.destroy(p); + } + s.probes.deinit(s.a); + s.a.destroy(s); + } + + fn invShapes(f: Fam) []const c.Shape { + return switch (f) { + .rms_bf16, .rms_f32 => &.{ .{ .rows = 33, .n = 5120, .k = 5120 }, .{ .rows = 16, .n = 1280, .k = 1280 } }, + .embed => &.{.{ .rows = 20, .n = 5120, .k = 4 }}, + .join => &.{.{ .rows = 20, .n = 2304, .k = 1 }}, + .mean => &.{.{ .rows = 20, .n = 5120, .k = 4 }}, + .rope_sliding, .rope_yarn => &.{ .{ .rows = 17, .n = 64, .k = 512 }, .{ .rows = 9, .n = 32, .k = 128 } }, + else => &.{ .{ .rows = 20, .n = 5120, .k = 5120 }, .{ .rows = 9, .n = 512, .k = 512 } }, + }; + } + + /// Launches of 1, 7 and rows/3 rows, and one in place for RoPE and the round trips, equal the whole launch's bytes. + fn probe(s: *Suite, p: *Proj, shape: c.Shape, seed: u64, bad: *usize, launches: *usize) !void { + if (!try p.prepare(shape, .random, seed)) return error.Refused; + try p.run(); + const len = p.count() * 2; + const whole = try s.a.dupe(u8, p.rig.bytes(p.out, len)); + defer s.a.free(whole); + for ([_]usize{ 1, 7, @max(1, shape.rows / 3) }) |step| { + @memset(p.rig.bytes(p.out, len), 0x55); + const pass = p.rig.begin(); + var r0: usize = 0; + while (r0 < shape.rows) : (r0 += step) { + try p.encode(pass.e, r0, @min(step, shape.rows - r0)); + launches.* += 1; + } + try p.rig.finish(pass); + if (!std.mem.eql(u8, whole, p.rig.bytes(p.out, len))) { + bad.* += 1; + std.debug.print("FAIL row invariance {s} {d}x{d}x{d}: {d} rows a launch differs from one launch\n", .{ p.name, shape.rows, shape.n, shape.k, step }); + } + } + if (!isQuant(p.fam) and !isRope(p.fam)) return; + const xlen = p.x.len * 2; + const scr = try p.rig.scratch(xlen); + @memcpy(p.rig.bytes(scr, xlen), std.mem.sliceAsBytes(p.x)); + const pass = p.rig.begin(); + const rows: u32 = @intCast(shape.rows); + if (isQuant(p.fam)) { + try gl.quant(&p.pipes, pass.e, p.glQuant(), at(scr, 0), at(scr, 0), rows, @intCast(shape.n)); + } else { + const call = gl.ropeInPlace(rows, @intCast(shape.n), @intCast(shape.k), 32); + try gl.rope(&p.pipes, pass.e, at(scr, 0), at(scr, 0), at(p.in[1], 0), at(p.in[2], 0), call); + } + try p.rig.finish(pass); + launches.* += 1; + const done = p.rig.bytes(scr, xlen); + var same = true; + if (isQuant(p.fam)) { + same = std.mem.eql(u8, whole, done); + } else for (0..shape.rows * shape.n) |rh| { + const from = rh * shape.k * 2 + (shape.k - 64) * 2; + if (!std.mem.eql(u8, whole[rh * 128 ..][0..128], done[from..][0..128])) same = false; + } + if (!same) { + bad.* += 1; + std.debug.print("FAIL in place {s} {d}x{d}x{d}: differs from the out-of-place bytes\n", .{ p.name, shape.rows, shape.n, shape.k }); + } + } + + pub fn invariance(s: *Suite, seed: u64) !usize { + var bad: usize = 0; + var launches: usize = 0; + var kernels: usize = 0; + for (s.probes.items) |p| { + if (p.ctl != 0) continue; + kernels += 1; + for (invShapes(p.fam), 0..) |shape, i| try s.probe(p, shape, seed + i, &bad, &launches); + } + if (kernels == 0) return 0; + std.debug.print("{s} row invariance {s}: {d} kernels at 1, 7 and rows/3 rows a launch and in place ({d} launches) byte-equal to one launch, {d} differ\n", .{ if (bad == 0) "PASS" else "FAIL", base, kernels, launches, bad }); + return bad; + } + + fn freq64(sp: gl.RopeSpec, i: usize) f64 { + const dim: f64 = @floatFromInt(sp.dim); + const f = 1.0 / std.math.pow(f64, sp.theta, @as(f64, @floatFromInt(2 * i)) / dim); + if (sp.original == 0) return f; + const orig: f64 = @floatFromInt(sp.original); + const low = @max(@floor(dim * @log(orig / (sp.beta_fast * 2 * std.math.pi)) / (2 * @log(sp.theta))), 0); + const high = @min(@ceil(dim * @log(orig / (sp.beta_slow * 2 * std.math.pi)) / (2 * @log(sp.theta))), dim - 1); + const ramp = std.math.clamp((@as(f64, @floatFromInt(i)) - low) / @max(high - low, 1e-3), 0, 1); + return f / sp.factor * ramp + f * (1 - ramp); + } + + /// The RoPE tables against float64: frequencies within 4 fp32 ulps, cos and sin correctly rounded. + pub fn tables(s: *Suite) !usize { + if (s.probes.items.len == 0) return 0; + var bad: usize = 0; + for ([_]gl.RopeSpec{ gl.RopeSpec.sliding, gl.RopeSpec.compressed }) |sp| { + var freqs: [32]f32 = undefined; + gl.ropeFreqs(sp, &freqs); + for (freqs, 0..) |f, i| { + const want = freq64(sp, i); + if (@abs(f - want) > 4 * std.math.floatEps(f32) * want) bad += 1; + } + var row: [32][2]f32 = undefined; + for ([_]u32{ 0, 1, 777, 65535, 65536, 1048575 }) |pos| { + gl.ropeRow(&freqs, pos, &row); + for (freqs, row) |f, cs| { + const angle: f64 = @as(f32, @floatFromInt(pos)) * f; + const want: [2]f32 = .{ @floatCast(@cos(angle)), @floatCast(@sin(angle)) }; + if (cs[0] != want[0] or cs[1] != want[1] or @abs(cs[0]) > 1 or @abs(cs[1]) > 1) bad += 1; + } + } + } + std.debug.print("{s} rope tables {s}: both spectra within 4 ulps of float64 frequencies, cos and sin correctly rounded, {d} misses\n", .{ if (bad == 0) "PASS" else "FAIL", base, bad }); + return bad; + } +}; diff --git a/zig/tests/contract/metal_dsv41_limits.zig b/zig/tests/contract/metal_dsv41_limits.zig index 12b4ef8e8ea..1063c5ea641 100644 --- a/zig/tests/contract/metal_dsv41_limits.zig +++ b/zig/tests/contract/metal_dsv41_limits.zig @@ -20,6 +20,7 @@ pub fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, return .{ .decl = d, .function = fun, .here = body, .pre_m5 = body }; } if (std.mem.startsWith(u8, d.name, "dsv41 glue_tmp ")) return .{ .decl = d, .function = fun, .here = sources.dsv41.glue_tmp, .pre_m5 = sources.dsv41.glue_tmp }; + if (std.mem.startsWith(u8, d.name, "dsv41 glue ")) return .{ .decl = d, .function = fun, .here = sources.dsv41.glue, .pre_m5 = sources.dsv41.glue }; if (std.mem.startsWith(u8, d.name, "dsv41 mv ")) return .{ .decl = d, .function = fun, .here = sources.dsv41.mv, .pre_m5 = sources.dsv41.mv }; if (std.mem.startsWith(u8, d.name, "dsv41 fp8 rows ")) return .{ .decl = d, .function = fun, .here = sources.dsv41.fp8_rows, .pre_m5 = sources.dsv41.fp8_rows }; return null; diff --git a/zig/tests/contract/metal_dsv41_main.zig b/zig/tests/contract/metal_dsv41_main.zig index 7ea597884f2..1f181e106bb 100644 --- a/zig/tests/contract/metal_dsv41_main.zig +++ b/zig/tests/contract/metal_dsv41_main.zig @@ -9,6 +9,7 @@ const dsv41_fp8_rows = @import("metal_dsv41_fp8_rows.zig"); const dsv41_fp8_mma = @import("metal_dsv41_fp8_mma.zig"); const dsv41_experts = @import("metal_dsv41_experts.zig"); const dsv41_xmma = @import("metal_dsv41_xmma.zig"); +const dsv41_glue = @import("metal_dsv41_glue.zig"); const dsv41_mv = @import("metal_dsv41_mv.zig"); const dsv41_glue_tmp = @import("metal_dsv41_glue_tmp.zig"); const dsv41_glue_tmp2 = @import("metal_dsv41_glue_tmp2.zig"); @@ -20,6 +21,7 @@ pub const Suites = struct { attn: *dsv41_attn.Suite, experts: *dsv41_experts.Suite, xmma: *dsv41_xmma.Suite, + glue: *dsv41_glue.Suite, mv: *dsv41_mv.Suite, glue_tmp: *dsv41_glue_tmp.Suite, glue_tmp2: *dsv41_glue_tmp2.Suite, @@ -35,19 +37,22 @@ pub const Suites = struct { errdefer experts.destroy(); const xmma = try dsv41_xmma.Suite.create(a, device, queue, kernels, only); errdefer xmma.destroy(); + const glue = try dsv41_glue.Suite.create(a, device, queue, kernels, only); + errdefer glue.destroy(); const mv = try dsv41_mv.Suite.create(a, device, queue, kernels, only); errdefer mv.destroy(); const glue_tmp = try dsv41_glue_tmp.Suite.create(a, device, queue, kernels, only); errdefer glue_tmp.destroy(); const glue_tmp2 = try dsv41_glue_tmp2.Suite.create(a, device, queue, kernels, only); errdefer glue_tmp2.destroy(); - return .{ .fp8 = fp8, .fp8_mma = fp8_mma, .attn = attn, .experts = experts, .xmma = xmma, .mv = mv, .glue_tmp = glue_tmp, .glue_tmp2 = glue_tmp2 }; + return .{ .fp8 = fp8, .fp8_mma = fp8_mma, .attn = attn, .experts = experts, .xmma = xmma, .glue = glue, .mv = mv, .glue_tmp = glue_tmp, .glue_tmp2 = glue_tmp2 }; } pub fn destroy(s: *Suites) void { s.glue_tmp2.destroy(); s.glue_tmp.destroy(); s.mv.destroy(); + s.glue.destroy(); s.xmma.destroy(); s.experts.destroy(); s.attn.destroy(); @@ -68,11 +73,13 @@ pub const Suites = struct { if (std.c.getenv("TF_DSV41_TIME") != null) try s.fp8_mma.timing(io); try s.attn.invariance(io, seed, t); if (std.c.getenv("TF_DSV41_TIME") != null) try s.attn.timing(io); + t.failed += try s.glue.invariance(seed); if (s.mv.probes.items.len > 0) { t.failed += try s.mv.invariance(seed); t.failed += try s.mv.equality(seed); t.failed += try s.mv.head(io, seed, std.c.getenv("TF_DSV41_TIME") != null); } + t.failed += try s.glue.tables(); t.failed += try s.glue_tmp.invariance(seed); t.failed += try s.glue_tmp.bounds(seed); t.failed += try s.glue_tmp2.invariance(seed);