From d98995b4325fc9f51bfe121426342fabc179c607 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 06:14:50 +0000 Subject: [PATCH 1/3] changelog: #3661 under Unreleased # Conflicts: # CHANGELOG.md From db64aa340c089c84a870c2c0cc623bc6d35da68d Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:16:19 +0100 Subject: [PATCH 2/3] dsv41 metal: the vision tower's kernels under the kernel contract vision.metal holds the ViT's epilogues, RoPE, attention, SwiGLU, the aligner's unshuffle and the stream merge, each registered with the contract against float64. --- CHANGELOG.md | 1 + zig/kernels/metal/deepseek_v41/sources.zig | 2 + zig/kernels/metal/deepseek_v41/vision.metal | 181 ++++++++ zig/src/core/contract/dsv41_metal_records.zig | 3 +- .../core/contract/dsv41_vision_records.zig | 15 + .../deepseek_v41/metal/contract_exports.zig | 1 + .../families/deepseek_v41/metal/vision.zig | 227 ++++++++++ zig/tests/contract/dsv41_vision_ref.zig | 73 ++++ zig/tests/contract/metal_dsv41_limits.zig | 4 + zig/tests/contract/metal_dsv41_main.zig | 8 +- zig/tests/contract/metal_dsv41_vision.zig | 409 ++++++++++++++++++ 11 files changed, 922 insertions(+), 2 deletions(-) create mode 100644 zig/kernels/metal/deepseek_v41/vision.metal create mode 100644 zig/src/core/contract/dsv41_vision_records.zig create mode 100644 zig/src/families/deepseek_v41/metal/vision.zig create mode 100644 zig/tests/contract/dsv41_vision_ref.zig create mode 100644 zig/tests/contract/metal_dsv41_vision.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index 732b3c2c538..0bed15ba902 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -230,6 +230,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel same way; its departures are listed in the recipe beside float32's (#2074). Thanks to @BobClawblaw. - GLM-5.3-Flash on CUDA with `TF_KV_SHARE` and no `--prompt-cache-gib`: the kept states' slots, `TF_KV_SHARE` at most, now come where an asked cache goes, before the windows past the engine's own, so a room that holds one more whole window no longer keeps fewer states; Jammed XSFP4 at TP=3 on three GB10s keeps all 32 at `TF_KV_SHARE=32` instead of 8, with the same tokens (#3125). Thanks to @Bizuayeu. +- On Macs, DeepSeek V4.1's vision tower (epilogues, RoPE, attention, SwiGLU, the aligner's unshuffle and the stream merge) has its own Metal kernels under the kernel contract, each with a planted control; nothing serves through them until #1722 (#1721, part of #1676). - Server: with thinking off, the reasoning effort a request names reaches the chat template (GLM's head follows it), and the reply reports it; a server's own `--reasoning-effort` no longer changes a thinking-off prompt (#3017, fixes #1911). Thanks to @ss-cong for the report. diff --git a/zig/kernels/metal/deepseek_v41/sources.zig b/zig/kernels/metal/deepseek_v41/sources.zig index bc983dda559..9262341b67c 100644 --- a/zig/kernels/metal/deepseek_v41/sources.zig +++ b/zig/kernels/metal/deepseek_v41/sources.zig @@ -35,3 +35,5 @@ pub const route = @embedFile("route.metal"); pub const hc = @embedFile("hc.metal"); /// DeepSeek-V4.1's phase-1 glue (deepseek_v41/glue_tmp.metal): the reference bits of the registered glue kernels. pub const glue_tmp = @embedFile("glue_tmp.metal"); +/// DeepSeek V4.1's vision tower: epilogues, RoPE, attention, SwiGLU, the aligner's unshuffle and the stream merge. +pub const vision = @embedFile("vision.metal"); diff --git a/zig/kernels/metal/deepseek_v41/vision.metal b/zig/kernels/metal/deepseek_v41/vision.metal new file mode 100644 index 00000000000..554d0b1c040 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/vision.metal @@ -0,0 +1,181 @@ +// DeepSeek V4.1's vision tower: epilogues, 2D RoPE, full attention, SwiGLU, the aligner's unshuffle, the merge. +#include +using namespace metal; +#pragma clang fp contract(off) + +#ifndef TF_CTL +#define TF_CTL 0 // planted faults 1 to 6, one per kernel; 0 is the kernel as served +#endif + +inline float tf_vis_bf(float v) { + return float(bfloat(v)); +} + +// erf to fp32 precision (W. J. Cody's rational approximations, as libm's erff). +inline float tf_vis_erf(float x) { + const float ax = fabs(x); + if (ax < 0.84375f) { + const float z = x * x; + const float r = 1.28379167e-01f + z * (-3.25042108e-01f + z * (-2.84817495e-02f + z * (-5.77027029e-03f + z * -2.37630166e-05f))); + const float s = 1.0f + z * (3.97917233e-01f + z * (6.50222499e-02f + z * (5.08130628e-03f + z * (1.32494738e-04f + z * -3.96022827e-06f)))); + return x + x * (r / s); + } + if (ax < 1.25f) { + const float s = ax - 1.0f; + const float P = -2.36211857e-03f + s * (4.14856106e-01f + s * (-3.72207481e-01f + s * (3.18346620e-01f + s * (-1.10894694e-01f + s * (3.54783031e-02f + s * -2.16637559e-03f))))); + const float Q = 1.0f + s * (1.06420882e-01f + s * (5.40397942e-01f + s * (7.18286547e-02f + s * (1.26171216e-01f + s * (1.36370836e-02f + s * 1.19844998e-02f))))); + const float e = 8.45062911e-01f + P / Q; + return x >= 0 ? e : -e; + } + if (ax >= 6.0f) return x >= 0 ? 1.0f : -1.0f; + const float s = 1.0f / (ax * ax); + float R, S; + if (ax < 1.0f / 0.35f) { + R = -9.86494403e-03f + s * (-6.93858570e-01f + s * (-1.05586262e+01f + s * (-6.23753357e+01f + s * (-1.62396660e+02f + s * (-1.84605087e+02f + s * (-8.12874374e+01f + s * -9.81432934e+00f)))))); + S = 1.0f + s * (1.96512714e+01f + s * (1.37657754e+02f + s * (4.34565887e+02f + s * (6.45387268e+02f + s * (4.29008148e+02f + s * (1.08635002e+02f + s * (6.57024977e+00f + s * -6.04244141e-02f))))))); + } else { + R = -9.86494310e-03f + s * (-7.99283242e-01f + s * (-1.77579556e+01f + s * (-1.60636383e+02f + s * (-6.37566467e+02f + s * (-1.02509509e+03f + s * -4.83519196e+02f))))); + S = 1.0f + s * (3.03380604e+01f + s * (3.25792511e+02f + s * (1.53672961e+03f + s * (3.19985820e+03f + s * (2.55305029e+03f + s * (4.74528534e+02f + s * -2.24409515e+01f)))))); + } + const float zh = as_type(as_type(ax) & 0xfffff000u); + const float r = metal::precise::exp(-zh * zh - 0.5625f) * metal::precise::exp((zh - ax) * (zh + ax) + R / S); + const float e = 1.0f - r / ax; + return x >= 0 ? e : -e; +} + +struct TfVisEpiArgs { + uint rows, n, gelu, has_bias, has_res; +}; + +// A linear's fp32 sums to bf16: + bias, one rounding; then GELU (rounded) and the residual add (rounded) when asked. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_vis_epi(const device float* ACC [[buffer(0)]], const device bfloat* BIAS [[buffer(1)]], + const device bfloat* RES [[buffer(2)]], device bfloat* Y [[buffer(3)]], + constant TfVisEpiArgs& a [[buffer(4)]], uint2 g [[thread_position_in_grid]]) { + if (g.x >= a.n || g.y >= a.rows) return; + const ulong at = ulong(g.y) * a.n + g.x; + float v = ACC[at]; + if (a.has_bias != 0 && TF_CTL != 1) v = v + float(BIAS[g.x]); // control 1: the bias dropped + float z = tf_vis_bf(v); + if (a.gelu != 0) z = tf_vis_bf(0.5f * z * (1.0f + tf_vis_erf(z * 0.70710678118654752f))); + if (a.has_res != 0) z = tf_vis_bf(float(RES[at]) + z); + Y[at] = bfloat(z); +} + +struct TfVisQkvArgs { + uint rows, heads, hd; +}; + +// The qkv linear's sums [rows][3][heads][hd] to bf16 with the bias, q and k rotated by their patch's (cos, sin) pairs. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_vis_qkv(const device float* ACC [[buffer(0)]], const device bfloat* BIAS [[buffer(1)]], + const device float2* CS [[buffer(2)]], device bfloat* QKV [[buffer(3)]], + constant TfVisQkvArgs& a [[buffer(4)]], uint3 g [[thread_position_in_grid]]) { + const uint half_hd = a.hd / 2; + if (g.x >= half_hd || g.y >= a.rows || g.z >= 3 * a.heads) return; + const uint part = g.z / a.heads, head = g.z % a.heads; + const uint D = a.heads * a.hd; + const uint c1 = part * D + head * a.hd + g.x; + const ulong at = ulong(g.y) * 3 * D + c1; + const float x1 = tf_vis_bf(ACC[at] + float(BIAS[c1])); + const float x2 = tf_vis_bf(ACC[at + half_hd] + float(BIAS[c1 + half_hd])); + if (part == 2) { + QKV[at] = bfloat(x1); + QKV[at + half_hd] = bfloat(x2); + return; + } + const float2 raw = CS[ulong(g.y) * half_hd + g.x]; + const float2 cs = TF_CTL == 2 ? float2(raw.y, raw.x) : raw; // control 2: sin and cos swapped + const float p = x1 * cs.x, q = x2 * cs.y, r = x2 * cs.x, s = x1 * cs.y; + QKV[at] = bfloat(p - q); + QKV[at + half_hd] = bfloat(r + s); +} + +struct TfVisAttnArgs { + uint n, heads; + float scale; +}; + +// One simdgroup a (query, head): 32 keys a step, online softmax in fp32, values by the shuffled weights. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_vis_attn( + const device bfloat* QKV [[buffer(0)]], device bfloat* O [[buffer(1)]], constant TfVisAttnArgs& a [[buffer(2)]], + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + const uint D = a.heads * 64u; + const ulong stride = 3ul * D; + const device bfloat* qp = QKV + ulong(tg.x) * stride + tg.y * 64u; + float q[64]; + for (uint d = 0; d < 64u; ++d) q[d] = float(qp[d]); + float m = -3.0e38f, l = 0.0f, acc0 = 0.0f, acc1 = 0.0f; + for (uint j0 = 0; j0 < a.n; j0 += 32u) { + const uint j = j0 + lane; + float s = -3.0e38f; + if (j < a.n) { + const device bfloat* kp = QKV + ulong(j) * stride + D + tg.y * 64u; + float t = 0.0f; + for (uint d = 0; d < 64u; ++d) t = t + q[d] * float(kp[d]); + s = t * a.scale; + } + const float mn = max(m, simd_max(s)); + const float alpha = metal::precise::exp(m - mn); + const float p = j < a.n ? metal::precise::exp(s - (TF_CTL == 3 ? 0.0f : mn)) : 0.0f; // control 3: no max in the exponent + l = l * alpha + simd_sum(p); + acc0 = acc0 * alpha; + acc1 = acc1 * alpha; + const uint cnt = min(32u, a.n - j0); + for (uint jj = 0; jj < cnt; ++jj) { + const float pj = simd_shuffle(p, ushort(jj)); + const device bfloat* vp = QKV + ulong(j0 + jj) * stride + 2u * D + tg.y * 64u + 2u * lane; + acc0 = acc0 + pj * float(vp[0]); + acc1 = acc1 + pj * float(vp[1]); + } + m = mn; + } + device bfloat* op = O + ulong(tg.x) * D + tg.y * 64u + 2u * lane; + op[0] = bfloat(acc0 / l); + op[1] = bfloat(acc1 / l); +} + +struct TfVisSwiArgs { + uint rows, inter; +}; + +// The MLP's w1 sums [rows][2][inter] (gate, then up), each rounded to bf16: silu(gate) rounded, times up, rounded. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_vis_swiglu(const device float* ACC [[buffer(0)]], device bfloat* Y [[buffer(1)]], + constant TfVisSwiArgs& a [[buffer(2)]], uint2 g [[thread_position_in_grid]]) { + if (g.x >= a.inter || g.y >= a.rows) return; + const ulong at = ulong(g.y) * 2ul * a.inter + g.x; + const float gt = tf_vis_bf(ACC[at + (TF_CTL == 4 ? a.inter : 0u)]); // control 4: gate and up swapped + const float up = tf_vis_bf(ACC[at + (TF_CTL == 4 ? 0u : a.inter)]); + const float s = tf_vis_bf(gt / (1.0f + metal::precise::exp(-gt))); + Y[ulong(g.y) * a.inter + g.x] = bfloat(s * up); +} + +struct TfVisUnshufArgs { + uint nh, nw, lh, lw, dim, r; +}; + +// The aligner's F.unfold of the zero-padded patch grid: out [lh * lw][dim * r * r], column c * r * r + ky * r + kx. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_vis_unshuffle(const device bfloat* X [[buffer(0)]], device bfloat* Y [[buffer(1)]], + constant TfVisUnshufArgs& a [[buffer(2)]], uint2 g [[thread_position_in_grid]]) { + const uint rr = a.r * a.r; + if (g.x >= a.dim * rr || g.y >= a.lh * a.lw) return; + const uint c = g.x / rr, k = g.x % rr; + const uint rd = TF_CTL == 5 ? a.r + 1u : a.r; // control 5: the unfold's stride off by one + const uint py = (g.y / a.lw) * a.r + k / rd, px = (g.y % a.lw) * a.r + k % rd; + const bool in = py < a.nh && px < a.nw; + Y[ulong(g.y) * a.dim * rr + g.x] = in ? X[(ulong(py) * a.nw + px) * a.dim + c] : bfloat(0.0f); +} + +struct TfVisMergeArgs { + uint dim, rows; +}; + +// Stream rows [rows][4][dim] take an aligner row (SRC >= 0) or a delimiter (-1 start, -2 end, -3 newline). +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_vis_merge(const device bfloat* FEAT [[buffer(0)]], const device bfloat* DELIM [[buffer(1)]], + const device int* SRC [[buffer(2)]], device bfloat* Y [[buffer(3)]], + constant TfVisMergeArgs& a [[buffer(4)]], uint2 g [[thread_position_in_grid]]) { + if (g.x >= a.dim || g.y >= a.rows) return; + const int s = SRC[g.y]; + if (s <= -4) return; + const uint di = TF_CTL == 6 ? (uint(-1 - s) + 1u) % 3u : uint(-1 - s); // control 6: the wrong delimiter + const bfloat v = s >= 0 ? FEAT[ulong(s) * a.dim + g.x] : DELIM[ulong(di) * a.dim + g.x]; + for (uint k = 0; k < 4u; ++k) Y[(ulong(g.y) * 4ul + k) * a.dim + g.x] = v; +} diff --git a/zig/src/core/contract/dsv41_metal_records.zig b/zig/src/core/contract/dsv41_metal_records.zig index b24ae23ad26..68735c8a950 100644 --- a/zig/src/core/contract/dsv41_metal_records.zig +++ b/zig/src/core/contract/dsv41_metal_records.zig @@ -10,4 +10,5 @@ const head = @import("dsv41_fp8_records.zig").records ++ @import("dsv41_fp8_mma_ @import("dsv41_hc_records.zig").records; pub const records = head ++ @import("dsv41_fold_records.zig").records ++ @import("dsv41_glue_tmp_records.zig").records ++ - @import("dsv41_fused_records.zig").records ++ @import("dsv41_route_records.zig").records; + @import("dsv41_fused_records.zig").records ++ @import("dsv41_route_records.zig").records ++ + @import("dsv41_vision_records.zig").records; diff --git a/zig/src/core/contract/dsv41_vision_records.zig b/zig/src/core/contract/dsv41_vision_records.zig new file mode 100644 index 00000000000..a6eab020a55 --- /dev/null +++ b/zig/src/core/contract/dsv41_vision_records.zig @@ -0,0 +1,15 @@ +//! DeepSeek V4.1's vision launches on Metal: each reserves its thread count, so none depends on M1/M2. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "dsv41 vision epilogue tf_dsv41_vis_epi", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "dsv41 vision qkv rope tf_dsv41_vis_qkv", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "dsv41 vision attention tf_dsv41_vis_attn", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "dsv41 vision swiglu tf_dsv41_vis_swiglu", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "dsv41 vision unshuffle tf_dsv41_vis_unshuffle", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "dsv41 vision merge tf_dsv41_vis_merge", .threads = 32, .tg_memory = 0, .reserved = 32 }, +}; + +test "the DeepSeek V4.1 vision 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/families/deepseek_v41/metal/contract_exports.zig b/zig/src/families/deepseek_v41/metal/contract_exports.zig index 79b356064de..d30c285c094 100644 --- a/zig/src/families/deepseek_v41/metal/contract_exports.zig +++ b/zig/src/families/deepseek_v41/metal/contract_exports.zig @@ -13,3 +13,4 @@ pub const hc = @import("hc.zig"); pub const fused = @import("fused.zig"); pub const fold = @import("fold.zig"); pub const glue_tmp = @import("glue.zig"); +pub const vision = @import("vision.zig"); diff --git a/zig/src/families/deepseek_v41/metal/vision.zig b/zig/src/families/deepseek_v41/metal/vision.zig new file mode 100644 index 00000000000..a577a614d9a --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/vision.zig @@ -0,0 +1,227 @@ +//! DeepSeek V4.1's vision tower on Metal: the release's ViT (2D RoPE, full attention) and 3x3 aligner. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const glue = @import("glue.zig"); + +pub const Ref = glue.Ref; + +/// The release's `vision_config` (and the text hidden width the aligner maps to); defaults are the shipped values. +pub const Config = struct { + layers: u32 = 32, + dim: u32 = 1024, + heads: u32 = 16, + inter: u32 = 2816, + patch: u32 = 14, + theta: f64 = 10000, + ratio: u32 = 3, + max_tokens: u32 = 1024, + min_pixels: u32 = 295936, + max_wh_ratio: ?u32 = null, + out_dim: u32 = 5120, + image_token_id: u32 = 129264, + eps: f32 = 1e-6, + + pub fn headDim(c: Config) u32 { + return c.dim / c.heads; + } + + /// Values in a flattened patch: three channels of patch x patch. + pub fn patchValues(c: Config) u32 { + return 3 * c.patch * c.patch; + } + + /// Values in an aligner input row: ratio x ratio patches of the tower's width. + pub fn alignIn(c: Config) u32 { + return c.dim * c.ratio * c.ratio; + } + + /// The most patches an image can have: every token of the budget a ratio x ratio block. + pub fn maxPatches(c: Config) u32 { + return c.max_tokens * c.ratio * c.ratio; + } + + /// The `vision_config` and `image_token_id` of a config.json (null: no tower); `out_dim` is the text hidden width. + pub fn parse(a: std.mem.Allocator, text: []const u8, out_dim: u32) !?Config { + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const root = try std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), text, .{}); + if (root != .object) return error.BadConfig; + const v = (root.object.get("vision_config") orelse return null); + if (v != .object) return error.BadConfig; + var c: Config = .{ .out_dim = out_dim }; + const U = struct { + fn num(o: std.json.ObjectMap, key: []const u8) ?f64 { + const x = o.get(key) orelse return null; + return switch (x) { + .integer => |i| @floatFromInt(i), + .float => |f| f, + else => null, + }; + } + }; + if (U.num(v.object, "num_hidden_layers")) |x| c.layers = @intFromFloat(x); + if (U.num(v.object, "hidden_size")) |x| c.dim = @intFromFloat(x); + if (U.num(v.object, "num_attention_heads")) |x| c.heads = @intFromFloat(x); + if (U.num(v.object, "intermediate_size")) |x| c.inter = @intFromFloat(x); + if (U.num(v.object, "patch_size")) |x| c.patch = @intFromFloat(x); + if (U.num(v.object, "rope_theta")) |x| c.theta = x; + if (U.num(v.object, "downsample_ratio")) |x| c.ratio = @intFromFloat(x); + if (U.num(v.object, "max_image_tokens")) |x| c.max_tokens = @intFromFloat(x); + if (U.num(v.object, "min_pixels")) |x| c.min_pixels = @intFromFloat(x); + if (U.num(v.object, "max_wh_ratio")) |x| c.max_wh_ratio = @intFromFloat(x); + if (U.num(root.object, "image_token_id")) |x| c.image_token_id = @intFromFloat(x); + try c.check(); + return c; + } + + pub fn check(c: Config) !void { + if (c.headDim() != 64 or c.dim % c.heads != 0) return error.UnsupportedVision; + if (c.layers == 0 or c.ratio == 0 or c.patch == 0 or c.inter == 0) return error.UnsupportedVision; + } +}; + +const names = [_][:0]const u8{ "tf_dsv41_vis_epi", "tf_dsv41_vis_qkv", "tf_dsv41_vis_attn", "tf_dsv41_vis_swiglu", "tf_dsv41_vis_unshuffle", "tf_dsv41_vis_merge" }; + +/// The tower's kernels (deepseek_v41/vision.metal). +pub const Pipelines = struct { + p: [names.len]mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.dsv41.vision); + } + + /// 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 out: Pipelines = undefined; + for (names, 0..) |n, i| out.p[i] = try mtl.Pipeline.init(device, lib, n, false); + return out; + } + + pub fn deinit(p: *Pipelines) void { + for (p.p) |x| x.deinit(); + } +}; + +fn pipe(p: *const Pipelines, k: usize) mtl.Pipeline { + return p.p[k]; +} + +const k_epi = 0; +const k_qkv = 1; +const k_attn = 2; +const k_swiglu = 3; +const k_unshuffle = 4; +const k_merge = 5; + +fn bind(e: mtl.ComputeEncoder, refs: []const Ref) void { + for (refs, 0..) |r, i| e.setBuffer(r.buf, r.off, i); +} + +fn grid(e: mtl.ComputeEncoder, x: usize, y: usize, z: usize) void { + e.dispatchThreads(mtl.Size.of(x, y, z), mtl.Size.of(@min(x, 32), 1, 1)); +} + +/// A linear's fp32 sums acc [rows][n] to bf16 y: + bias (bf16 [n]) when given, GELU when asked, then + res [rows][n]. +pub fn epilogue(p: *const Pipelines, e: mtl.ComputeEncoder, acc: Ref, bias: ?Ref, res: ?Ref, y: Ref, rows: u32, n: u32, gelu: bool) void { + e.setPipeline(pipe(p, k_epi)); + bind(e, &.{ acc, bias orelse acc, res orelse acc, y }); + e.setValue(extern struct { rows: u32, n: u32, gelu: u32, has_bias: u32, has_res: u32 }{ .rows = rows, .n = n, .gelu = @intFromBool(gelu), .has_bias = @intFromBool(bias != null), .has_res = @intFromBool(res != null) }, 4); + grid(e, n, rows, 1); +} + +/// The qkv sums acc [rows][3 * dim] to bf16 qkv with the bias; q and k rotated by cs [rows][head_dim / 2] (cos, sin). +pub fn qkv(p: *const Pipelines, e: mtl.ComputeEncoder, acc: Ref, bias: Ref, cs: Ref, out: Ref, rows: u32, heads: u32, hd: u32) void { + e.setPipeline(pipe(p, k_qkv)); + bind(e, &.{ acc, bias, cs, out }); + e.setValue(extern struct { rows: u32, heads: u32, hd: u32 }{ .rows = rows, .heads = heads, .hd = hd }, 4); + grid(e, hd / 2, rows, 3 * heads); +} + +/// Full attention of every row over all rows, one simdgroup a (row, head): out [rows][dim] from qkv [rows][3 * dim]. +pub fn attention(p: *const Pipelines, e: mtl.ComputeEncoder, qkv_: Ref, out: Ref, rows: u32, heads: u32) void { + e.setPipeline(pipe(p, k_attn)); + bind(e, &.{ qkv_, out }); + e.setValue(extern struct { n: u32, heads: u32, scale: f32 }{ .n = rows, .heads = heads, .scale = 0.125 }, 2); + e.dispatchGroups(mtl.Size.of(rows, heads, 1), mtl.Size.of(32, 1, 1)); +} + +/// The MLP's w1 sums acc [rows][2 * inter] to y [rows][inter] bf16: silu(gate) * up. +pub fn swiglu(p: *const Pipelines, e: mtl.ComputeEncoder, acc: Ref, y: Ref, rows: u32, inter: u32) void { + e.setPipeline(pipe(p, k_swiglu)); + bind(e, &.{ acc, y }); + e.setValue(extern struct { rows: u32, inter: u32 }{ .rows = rows, .inter = inter }, 2); + grid(e, inter, rows, 1); +} + +/// The aligner's unfold: x [nh * nw][dim] to y [lh * lw][dim * r * r], the grid zero-padded to whole blocks. +pub fn unshuffle(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, y: Ref, nh: u32, nw: u32, dim: u32, r: u32) void { + const lh = (nh + r - 1) / r; + const lw = (nw + r - 1) / r; + e.setPipeline(pipe(p, k_unshuffle)); + bind(e, &.{ x, y }); + e.setValue(extern struct { nh: u32, nw: u32, lh: u32, lw: u32, dim: u32, r: u32 }{ .nh = nh, .nw = nw, .lh = lh, .lw = lw, .dim = dim, .r = r }, 2); + grid(e, dim * r * r, lh * lw, 1); +} + +/// Stream rows [rows][4][dim] take feat's rows or the delimiters as `src` [rows] (int32) names them; others stay. +pub fn merge(p: *const Pipelines, e: mtl.ComputeEncoder, feat: Ref, delims: Ref, src: Ref, y: Ref, rows: u32, dim: u32) void { + e.setPipeline(pipe(p, k_merge)); + bind(e, &.{ feat, delims, src, y }); + e.setValue(extern struct { dim: u32, rows: u32 }{ .dim = dim, .rows = rows }, 4); + grid(e, dim, rows, 1); +} + +/// The tower's kernels and the glue ones it shares (RMS norm, bf16 matvecs), loaded together. +pub const Kit = struct { + v: Pipelines, + g: glue.Pipelines, + + pub fn load(device: mtl.Device) !Kit { + var v = try Pipelines.load(device); + errdefer v.deinit(); + return .{ .v = v, .g = try glue.Pipelines.load(device, sources.dsv41.glue_tmp) }; + } + + pub fn deinit(k: *Kit) void { + k.v.deinit(); + k.g.deinit(); + } +}; + +/// The 2D RoPE's (cos, sin) pairs [nh * nw][head_dim / 2]: the first half rotates by row, the second by column. +pub fn ropeTable(out: [][2]f32, nh: u32, nw: u32, hd: u32, theta: f64) void { + const half = hd / 2; + const m = half / 2; + std.debug.assert(out.len == @as(usize, nh) * nw * half); + var inv: [32]f32 = undefined; + for (0..m) |i| inv[i] = @floatCast(1.0 / std.math.pow(f64, theta, @as(f64, @floatFromInt(2 * i)) / @as(f64, @floatFromInt(half)))); + for (0..nh) |h| for (0..nw) |w| for (0..half) |j| { + const pos: f32 = @floatFromInt(if (j < m) h else w); + const angle: f64 = pos * inv[j % m]; + out[(h * nw + w) * half + j] = .{ @floatCast(@cos(angle)), @floatCast(@sin(angle)) }; + }; +} + +test "the release's vision_config parses to the defaults" { + const text = + \\{"image_token_id": 129264, "vision_config": {"num_hidden_layers": 32, "hidden_size": 1024, "num_attention_heads": 16, + \\ "intermediate_size": 2816, "patch_size": 14, "rope_theta": 10000, "downsample_ratio": 3, "max_image_tokens": 1024, + \\ "min_pixels": 295936, "max_wh_ratio": null}} + ; + const c = (try Config.parse(std.testing.allocator, text, 5120)).?; + try std.testing.expectEqual(Config{}, c); + try std.testing.expect((try Config.parse(std.testing.allocator, "{}", 5120)) == null); +} + +test "the 2D RoPE table: row angles first, column angles after, position 0 is the identity" { + var t: [6 * 32][2]f32 = undefined; + ropeTable(&t, 2, 3, 64, 10000); + for (t[0..32]) |cs| try std.testing.expectEqual([2]f32{ 1, 0 }, cs); + // patch (1, 2): the first 16 pairs rotate by 1 * inv_freq, the next 16 by 2 * inv_freq + const at = (1 * 3 + 2) * 32; + try std.testing.expectApproxEqAbs(@as(f32, @floatCast(@cos(@as(f64, 1.0)))), t[at][0], 1e-7); + try std.testing.expectApproxEqAbs(@as(f32, @floatCast(@cos(@as(f64, 2.0)))), t[at + 16][0], 1e-7); +} diff --git a/zig/tests/contract/dsv41_vision_ref.zig b/zig/tests/contract/dsv41_vision_ref.zig new file mode 100644 index 00000000000..23af0002c26 --- /dev/null +++ b/zig/tests/contract/dsv41_vision_ref.zig @@ -0,0 +1,73 @@ +//! Float64 oracles of DeepSeek V4.1's vision kernels from the math alone: epilogues, attention, SwiGLU. +const std = @import("std"); + +/// erf by its series below |x| = 4 (about 1e-9 absolute) and the complementary asymptotic series past it; erf(inf) = 1. +pub fn erf(x: f64) f64 { + if (std.math.isNan(x)) return x; + const ax = @abs(x); + if (ax >= 6) return std.math.sign(x); + if (ax < 4) { + var term = ax; + var sum = ax; + var n: f64 = 0; + while (@abs(term) > 1e-18 * @abs(sum) and ax > 0) { + n += 1; + term *= -ax * ax / n; + sum += term / (2 * n + 1); + } + return std.math.sign(x) * sum * 2 / @sqrt(std.math.pi); + } + var t: f64 = 1; + var s: f64 = 1; + for (1..14) |i| { + t *= -@as(f64, @floatFromInt(2 * i - 1)) / (2 * ax * ax); + s += t; + } + return std.math.sign(x) * (1 - @exp(-ax * ax) / (ax * @sqrt(std.math.pi)) * s); +} + +pub fn gelu(x: f64) f64 { + return 0.5 * x * (1 + erf(x * 0.7071067811865476)); +} + +pub fn silu(x: f64) f64 { + return x / (1 + @exp(-x)); +} + +/// One query row of one head against `n` keys: the softmax-weighted values, and the weights' magnitude of the values. +pub fn attend(out: []f64, mag: []f64, q: []const f64, keys: []const f64, vals: []const f64, n: usize, hd: usize, stride: usize) void { + var scores: [512]f64 = undefined; + var mx: f64 = -std.math.inf(f64); + for (0..n) |j| { + var s: f64 = 0; + for (0..hd) |d| s += q[d] * keys[j * stride + d]; + scores[j] = s / 8.0; + if (std.math.isNan(scores[j])) mx = std.math.nan(f64) else if (!std.math.isNan(mx)) mx = @max(mx, scores[j]); + } + var sum: f64 = 0; + for (0..n) |j| { + scores[j] = @exp(scores[j] - mx); + sum += scores[j]; + } + for (0..hd) |d| { + var acc: f64 = 0; + var m: f64 = 0; + for (0..n) |j| { + acc += scores[j] * vals[j * stride + d]; + m += @abs(scores[j] * vals[j * stride + d]); + } + out[d] = acc / sum; + mag[d] = m / sum; + } +} + +test "the oracle's erf and attention" { + try std.testing.expectApproxEqAbs(@as(f64, 0.8427007929497149), erf(1), 1e-12); + try std.testing.expectEqual(@as(f64, 1), erf(std.math.inf(f64))); + var out: [2]f64 = undefined; + var mag: [2]f64 = undefined; + // two equal keys: the mean of the values + attend(&out, &mag, &.{ 1, 0 }, &.{ 1, 0, 1, 0 }, &.{ 2, 4, 6, 8 }, 2, 2, 2); + try std.testing.expectApproxEqAbs(@as(f64, 4), out[0], 1e-12); + try std.testing.expectApproxEqAbs(@as(f64, 6), out[1], 1e-12); +} diff --git a/zig/tests/contract/metal_dsv41_limits.zig b/zig/tests/contract/metal_dsv41_limits.zig index 08541c93553..77e7c7ec0b6 100644 --- a/zig/tests/contract/metal_dsv41_limits.zig +++ b/zig/tests/contract/metal_dsv41_limits.zig @@ -74,6 +74,10 @@ pub fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, if (!assemble) return @as(Launch, undefined); return .{ .decl = d, .function = fun, .here = sources.dsv41.mv, .pre_m5 = sources.dsv41.mv }; } + if (std.mem.startsWith(u8, d.name, "dsv41 vision ")) { + if (!assemble) return @as(Launch, undefined); + return .{ .decl = d, .function = fun, .here = sources.dsv41.vision, .pre_m5 = sources.dsv41.vision }; + } if (std.mem.startsWith(u8, d.name, "dsv41 fold ")) { if (!assemble) return @as(Launch, undefined); return .{ .decl = d, .function = fun, .here = sources.dsv41.fold, .pre_m5 = sources.dsv41.fold }; diff --git a/zig/tests/contract/metal_dsv41_main.zig b/zig/tests/contract/metal_dsv41_main.zig index dae57e7be39..31caf058298 100644 --- a/zig/tests/contract/metal_dsv41_main.zig +++ b/zig/tests/contract/metal_dsv41_main.zig @@ -17,6 +17,7 @@ const dsv41_engram = @import("metal_dsv41_engram.zig"); const dsv41_glue = @import("metal_dsv41_glue.zig"); const dsv41_compress = @import("metal_dsv41_compress.zig"); const dsv41_mv = @import("metal_dsv41_mv.zig"); +const dsv41_vision = @import("metal_dsv41_vision.zig"); const dsv41_hc = @import("metal_dsv41_hc.zig"); const dsv41_fold = @import("metal_dsv41_fold.zig"); const dsv41_glue_tmp = @import("metal_dsv41_glue_tmp.zig"); @@ -85,6 +86,7 @@ pub const Suites = struct { glue: *dsv41_glue.Suite, compress: *dsv41_compress.Suite, mv: *dsv41_mv.Suite, + vision: *dsv41_vision.Suite, hc: *dsv41_hc.Suite, fold: *dsv41_fold.Suite, glue_tmp: *dsv41_glue_tmp.Suite, @@ -120,6 +122,8 @@ pub const Suites = struct { errdefer compress.destroy(); const mv = try dsv41_mv.Suite.create(a, device, queue, kernels, only); errdefer mv.destroy(); + const vision = try dsv41_vision.Suite.create(a, device, queue, kernels, only); + errdefer vision.destroy(); const hc = try dsv41_hc.Suite.create(a, device, queue, kernels, only); errdefer hc.destroy(); const fold = try dsv41_fold.Suite.create(a, device, queue, kernels, only); @@ -138,7 +142,7 @@ pub const Suites = struct { errdefer fused5.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, .topk = topk, .cand = cand, .attn = attn, .experts = experts, .xmma = xmma, .ix = ix, .engram = engram, .glue = glue, .compress = compress, .mv = mv, .hc = hc, .fold = fold, .glue_tmp = glue_tmp, .fused = fused, .fused2 = fused2, .fused3 = fused3, .fused4 = fused4, .fused5 = fused5, .glue_tmp2 = glue_tmp2 }; + return .{ .fp8 = fp8, .fp8_mma = fp8_mma, .topk = topk, .cand = cand, .attn = attn, .experts = experts, .xmma = xmma, .ix = ix, .engram = engram, .glue = glue, .compress = compress, .mv = mv, .vision = vision, .hc = hc, .fold = fold, .glue_tmp = glue_tmp, .fused = fused, .fused2 = fused2, .fused3 = fused3, .fused4 = fused4, .fused5 = fused5, .glue_tmp2 = glue_tmp2 }; } pub fn destroy(s: *Suites) void { @@ -152,6 +156,7 @@ pub const Suites = struct { s.fold.destroy(); s.hc.destroy(); s.mv.destroy(); + s.vision.destroy(); s.compress.destroy(); s.glue.destroy(); s.engram.destroy(); @@ -192,6 +197,7 @@ pub const Suites = struct { 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.vision.invariance(seed); t.failed += try s.compress.invariance(seed); t.failed += try s.compress.equality(seed); t.failed += try s.hc.invariance(seed); diff --git a/zig/tests/contract/metal_dsv41_vision.zig b/zig/tests/contract/metal_dsv41_vision.zig new file mode 100644 index 00000000000..55c91a0aafc --- /dev/null +++ b/zig/tests/contract/metal_dsv41_vision.zig @@ -0,0 +1,409 @@ +//! DeepSeek V4.1's vision kernels under the contract on Metal: epilogues, RoPE, attention, SwiGLU, layout. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const ref = @import("dsv41_vision_ref.zig"); + +const c = contract.spec; +const g = contract.gates; +const vis = tf.dsv41_metal.vision; +const base = "dsv41 vision "; +const u: f64 = 0x1p-8; // half a bf16 ulp, relative + +pub const Fam = enum { epi_bias, epi_gelu, epi_res, epi_res0, qkv, swiglu, unshuffle, merge, attn }; + +fn noSums(_: c.Shape) usize { + return 0; +} + +pub fn spec(f: Fam, name: []const u8) c.Spec { + const t32: c.Tile = .{ .size = 32 }; + return switch (f) { + .epi_bias, .epi_gelu, .epi_res, .epi_res0 => .{ .name = name, .accum = .none, .depth = noSums, .out = .bf16, .tiles = .{ .{}, t32, .{} }, .served = &.{ + .{ .rows = 300, .n = 1024, .k = 1 }, .{ .rows = 64, .n = 5120, .k = 1 }, .{ .rows = 33, .n = 3072, .k = 1 }, .{ .rows = 5, .n = 2816, .k = 1 }, .{ .rows = 1, .n = 1024, .k = 1 }, + } }, + .qkv => .{ .name = name, .accum = .none, .depth = noSums, .out = .bf16, .tiles = .{ .{}, .{}, .{ .size = 64, .step = 2, .min = 2 } }, .served = &.{ + .{ .rows = 96, .n = 16, .k = 64 }, .{ .rows = 7, .n = 2, .k = 64 }, .{ .rows = 1, .n = 16, .k = 64 }, .{ .rows = 33, .n = 3, .k = 64 }, + } }, + .swiglu => .{ .name = name, .accum = .none, .depth = noSums, .out = .bf16, .tiles = .{ .{}, t32, .{} }, .served = &.{ + .{ .rows = 128, .n = 2816, .k = 1 }, .{ .rows = 5, .n = 192, .k = 1 }, .{ .rows = 1, .n = 2816, .k = 1 }, .{ .rows = 40, .n = 1000, .k = 1 }, + } }, + .unshuffle => .{ .name = name, .accum = .none, .depth = noSums, .out = .bf16, .tiles = .{ .{ .size = 3 }, .{ .size = 3 }, .{ .size = 32 } }, .served = &.{ + .{ .rows = 36, .n = 43, .k = 1024 }, .{ .rows = 5, .n = 7, .k = 128 }, .{ .rows = 1, .n = 1, .k = 64 }, .{ .rows = 9, .n = 4, .k = 100 }, + } }, + .merge => .{ .name = name, .accum = .none, .depth = noSums, .out = .bf16, .tiles = .{ .{}, t32, .{} }, .served = &.{ + .{ .rows = 200, .n = 5120, .k = 40 }, .{ .rows = 16, .n = 256, .k = 9 }, .{ .rows = 1, .n = 5120, .k = 1 }, .{ .rows = 70, .n = 100, .k = 20 }, + } }, + .attn => .{ .name = name, .accum = .none, .depth = noSums, .out = .bf16, .tiles = .{ .{ .size = 32 }, .{}, .{} }, .served = &.{ + .{ .rows = 96, .n = 16, .k = 64 }, .{ .rows = 37, .n = 4, .k = 64 }, .{ .rows = 1, .n = 16, .k = 64 }, .{ .rows = 130, .n = 2, .k = 64 }, + } }, + }; +} + +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) vis.Ref { + return .{ .buf = r.buf, .off = r.off + extra }; +} + +/// The five planted values of the rows family (a NaN, both infinities, two at one row's ends) into fp32 rows. +fn plant32(x: []f32, rows: usize, width: usize) usize { + const place = [_][2]usize{ .{ 0, width / 3 }, .{ 1, width / 2 }, .{ 2, width - 1 }, .{ 3, 0 }, .{ 3, width - 1 } }; + const put = [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32), std.math.inf(f32), -std.math.inf(f32) }; + var n: usize = 0; + for (place, put) |p, v| if (p[0] < rows) { + x[p[0] * width + p[1]] = v; + n += 1; + }; + return 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; +} + +fn f32s(a: std.mem.Allocator, n: usize, rng: std.Random, lo: i32, hi: i32) ![]f32 { + const v = try a.alloc(f32, n); + for (v) |*o| o.* = spread(rng, lo, hi); + return v; +} + +const vt = g.hooks(Proj); + +pub const Proj = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + fam: Fam, + name: []const u8, + /// the planted fault this kernel's text carries (0: the kernel as served) + ctl: u8 = 0, + pipes: vis.Pipelines, + shape: c.Shape = undefined, + acc: []f32 = &.{}, + x: []u16 = &.{}, + bias: []u16 = &.{}, + res: []u16 = &.{}, + cs: [][2]f32 = &.{}, + src: []i32 = &.{}, + in: [4]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, f: Fam, name: []const u8, ctl: u8) !Proj { + const sources = @import("kernel_sources"); + const text = try std.fmt.allocPrint(a, "#define TF_CTL {d}\n{s}", .{ ctl, sources.dsv41.vision }); + defer a.free(text); + return .{ .a = a, .arena = std.heap.ArenaAllocator.init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .fam = f, .name = name, .ctl = ctl, .pipes = try vis.Pipelines.loadSource(device, text) }; + } + + 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 = if (p.ctl != 0) .shapes else null; + return .{ .spec = spec(p.fam, p.name), .ctx = p, .vt = &vt, .control = control }; + } + + fn isEpi(p: *const Proj) bool { + return p.fam == .epi_bias or p.fam == .epi_gelu or p.fam == .epi_res or p.fam == .epi_res0; + } + + /// qkv: the three parts of every head; the others: a row's outputs. + pub fn count(p: *Proj) usize { + const s = p.shape; + return switch (p.fam) { + .qkv => s.rows * 3 * s.n * s.k, + .swiglu => s.rows * s.n, + .unshuffle => ((s.rows + 2) / 3) * ((s.n + 2) / 3) * s.k * 9, + .merge => s.rows * 4 * s.n, + .attn => s.rows * s.n * 64, + else => s.rows * s.n, + }; + } + + pub fn prepare(p: *Proj, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (p.fam == .qkv and shape.k % 2 != 0) return false; + if (p.fam == .attn and (shape.k != 64 or shape.rows > 500)) return false; + p.rig.reset(); + _ = p.arena.reset(.retain_capacity); + const al = p.arena.allocator(); + p.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const nf = fill == .nonfinite; + const s = shape; + switch (p.fam) { + .epi_bias, .epi_gelu, .epi_res, .epi_res0 => { + p.acc = try f32s(al, s.rows * s.n, rng, -5, 3); + p.bias = try bf16s(al, s.n, rng, -4, 1); + p.res = try bf16s(al, s.rows * s.n, rng, -4, 3); + if (nf) _ = plant32(p.acc, s.rows, s.n); + if (nf and p.fam == .epi_res) p.res[s.n + 1] = c.toBf16(-std.math.inf(f32)); + p.in[0] = try p.rig.input(std.mem.sliceAsBytes(p.acc)); + p.in[1] = try p.rig.input(std.mem.sliceAsBytes(p.bias)); + p.in[2] = try p.rig.input(std.mem.sliceAsBytes(p.res)); + }, + .qkv => { + const w = 3 * s.n * s.k; + p.acc = try f32s(al, s.rows * w, rng, -4, 2); + p.bias = try bf16s(al, w, rng, -4, 1); + p.cs = try al.alloc([2]f32, s.rows * s.k / 2); + for (p.cs) |*o| { + const angle = (rng.float(f64) * 2 - 1) * std.math.pi; + o.* = .{ @floatCast(@cos(angle)), @floatCast(@sin(angle)) }; + } + if (nf) _ = plant32(p.acc, s.rows, w); + p.in[0] = try p.rig.input(std.mem.sliceAsBytes(p.acc)); + p.in[1] = try p.rig.input(std.mem.sliceAsBytes(p.bias)); + p.in[2] = try p.rig.input(std.mem.sliceAsBytes(p.cs)); + }, + .swiglu => { + p.acc = try f32s(al, s.rows * 2 * s.n, rng, -5, 3); + if (nf) _ = plant32(p.acc, s.rows, 2 * s.n); + p.in[0] = try p.rig.input(std.mem.sliceAsBytes(p.acc)); + }, + .unshuffle => { + p.x = try bf16s(al, s.rows * s.n * s.k, rng, -3, 3); + if (nf) p.x[0] = c.toBf16(std.math.nan(f32)); + p.in[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + }, + .merge => { + p.x = try bf16s(al, s.k * s.n, rng, -3, 3); + p.bias = try bf16s(al, 3 * s.n, rng, -3, 3); + p.src = try al.alloc(i32, s.rows); + for (p.src, 0..) |*o, i| o.* = if (i % 5 == 4) -1 - @as(i32, @intCast(i % 3)) else @intCast(rng.uintLessThan(usize, s.k)); + if (nf) { + // a NaN feature row and an infinite delimiter, each read by a row + p.x[0] = c.toBf16(std.math.nan(f32)); + p.bias[s.n + 1] = c.toBf16(std.math.inf(f32)); + p.src[0] = 0; + p.src[4] = -2; + } + p.in[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.in[1] = try p.rig.input(std.mem.sliceAsBytes(p.bias)); + p.in[2] = try p.rig.input(std.mem.sliceAsBytes(p.src)); + }, + .attn => { + const D = s.n * 64; + p.x = try bf16s(al, s.rows * 3 * D, rng, -2, 1); + if (nf) { + // NaN and infinities in four queries of the first head only: those rows' head goes non-finite + const qs = [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32), std.math.inf(f32) }; + for (qs, 0..) |v, r| if (r < s.rows) { + p.x[r * 3 * D + 3 + r] = c.toBf16(v); + }; + } + 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 (the attention and unshuffle take whole calls). + pub fn encode(p: *Proj, e: anytype, r0: usize, n: usize) !void { + const s = p.shape; + const pl = &p.pipes; + const n32: u32 = @intCast(n); + switch (p.fam) { + .epi_bias, .epi_gelu, .epi_res, .epi_res0 => { + const w = s.n; + const bias: ?vis.Ref = if (p.fam == .epi_res0) null else at(p.in[1], 0); + const res: ?vis.Ref = if (p.fam == .epi_res or p.fam == .epi_res0) at(p.in[2], r0 * w * 2) else null; + vis.epilogue(pl, e, at(p.in[0], r0 * w * 4), bias, res, at(p.out, r0 * w * 2), n32, @intCast(w), p.fam == .epi_gelu); + }, + .qkv => vis.qkv(pl, e, at(p.in[0], r0 * 3 * s.n * s.k * 4), at(p.in[1], 0), at(p.in[2], r0 * s.k / 2 * 8), at(p.out, r0 * 3 * s.n * s.k * 2), n32, @intCast(s.n), @intCast(s.k)), + .swiglu => vis.swiglu(pl, e, at(p.in[0], r0 * 2 * s.n * 4), at(p.out, r0 * s.n * 2), n32, @intCast(s.n)), + .unshuffle => vis.unshuffle(pl, e, at(p.in[0], 0), at(p.out, 0), @intCast(s.rows), @intCast(s.n), @intCast(s.k), 3), + .merge => vis.merge(pl, e, at(p.in[0], 0), at(p.in[1], 0), at(p.in[2], r0 * 4), at(p.out, r0 * 4 * s.n * 2), n32, @intCast(s.n)), + .attn => vis.attention(pl, e, at(p.in[0], 0), at(p.out, 0), @intCast(s.rows), @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) { + .epi_bias, .epi_gelu, .epi_res, .epi_res0 => for (want, mag, 0..) |*w, *m, i| { + const z: f64 = @as(f64, p.acc[i]) + (if (p.fam == .epi_res0) 0 else c.fromBf16(p.bias[i % s.n])); + const y = if (p.fam == .epi_gelu) ref.gelu(z) else z; + const r: f64 = if (p.fam == .epi_res or p.fam == .epi_res0) c.fromBf16(p.res[i]) else 0; + w.* = y + r; + m.* = @abs(z) + @abs(r); + }, + .qkv => for (0..s.rows) |r| for (0..3 * s.n) |ph| for (0..s.k / 2) |j| { + const part = ph / s.n; + const o = (r * 3 * s.n + ph) * s.k + j; + const col = ph * s.k + j; + const x1: f64 = @as(f64, p.acc[r * 3 * s.n * s.k + col]) + c.fromBf16(p.bias[col]); + const x2: f64 = @as(f64, p.acc[r * 3 * s.n * s.k + col + s.k / 2]) + c.fromBf16(p.bias[col + s.k / 2]); + if (part == 2) { + want[o] = x1; + want[o + s.k / 2] = x2; + mag[o] = @abs(x1); + mag[o + s.k / 2] = @abs(x2); + continue; + } + const cs = p.cs[r * s.k / 2 + j]; + const co: f64 = cs[0]; + const si: f64 = cs[1]; + want[o] = x1 * co - x2 * si; + want[o + s.k / 2] = x2 * co + x1 * si; + mag[o] = @abs(x1 * co) + @abs(x2 * si); + mag[o + s.k / 2] = @abs(x2 * co) + @abs(x1 * si); + }, + .swiglu => for (0..s.rows) |r| for (0..s.n) |j| { + const gt: f64 = p.acc[r * 2 * s.n + j]; + const up: f64 = p.acc[r * 2 * s.n + s.n + j]; + want[r * s.n + j] = ref.silu(gt) * up; + mag[r * s.n + j] = @abs(gt); // the gate's own size sets how far its rounding moves the output + }, + .unshuffle => { + const lw = (s.n + 2) / 3; + for (0..((s.rows + 2) / 3) * lw) |l| for (0..s.k) |ch| for (0..9) |kk| { + const py = (l / lw) * 3 + kk / 3; + const px = (l % lw) * 3 + kk % 3; + want[(l * s.k + ch) * 9 + kk] = if (py < s.rows and px < s.n) c.fromBf16(p.x[(py * s.n + px) * s.k + ch]) else 0; + }; + }, + .merge => for (0..s.rows) |r| for (0..4) |st| for (0..s.n) |d| { + const sr = p.src[r]; + want[(r * 4 + st) * s.n + d] = if (sr >= 0) c.fromBf16(p.x[@as(usize, @intCast(sr)) * s.n + d]) else c.fromBf16(p.bias[@as(usize, @intCast(-1 - sr)) * s.n + d]); + }, + .attn => { + const D = s.n * 64; + const q = try p.a.alloc(f64, 64); + defer p.a.free(q); + const kk = try p.a.alloc(f64, s.rows * 3 * D); + defer p.a.free(kk); + for (kk, p.x) |*o, v| o.* = c.fromBf16(v); + for (0..s.rows) |r| for (0..s.n) |h| { + for (q, 0..) |*o, d| o.* = kk[r * 3 * D + h * 64 + d]; + ref.attend(want[(r * s.n + h) * 64 ..][0..64], mag[(r * s.n + h) * 64 ..][0..64], q, kk[D + h * 64 ..], kk[2 * D + h * 64 ..], s.rows, 64, 3 * D); + }; + }, + } + } + + /// The allowed |got - want|: the intermediate bf16 roundings of each formula, fp32's own, then the output's. + pub fn bounds(p: *Proj, want: []const f64, mag: []const f64, allow: []f64) !void { + const e32: f64 = 0x1p-24; + for (allow, want, mag) |*l, w, m| { + const work: f64 = switch (p.fam) { + .epi_bias => e32 * m, + .epi_gelu => 1.2 * u * m + 0x1p-20 * m, + .epi_res, .epi_res0 => u * m + e32 * m, + .qkv => (u + 4 * e32) * m, + .swiglu => u * (3 + m) * @abs(w) + 0x1p-20 * @abs(w), + .attn => 0x1p-14 * m, + else => 0, + }; + l.* = work + (if (p.fam == .unshuffle or p.fam == .merge) 0 else u * (@abs(w) + work)) + 0x1p-133; + } + } +}; + +/// Every registered variant and the launch-split probes after the gates. +pub const Suite = struct { + a: std.mem.Allocator, + probes: std.ArrayList(*Proj) = .empty, + + const E = struct { f: Fam, name: []const u8, ctl: u8 = 0 }; + const list = [_]E{ + .{ .f = .epi_bias, .name = base ++ "epilogue bias tf_dsv41_vis_epi" }, + .{ .f = .epi_gelu, .name = base ++ "epilogue bias gelu tf_dsv41_vis_epi" }, + .{ .f = .epi_res, .name = base ++ "epilogue bias residual tf_dsv41_vis_epi" }, + .{ .f = .epi_res0, .name = base ++ "epilogue residual tf_dsv41_vis_epi" }, + .{ .f = .qkv, .name = base ++ "qkv bias rope tf_dsv41_vis_qkv" }, + .{ .f = .swiglu, .name = base ++ "swiglu tf_dsv41_vis_swiglu" }, + .{ .f = .unshuffle, .name = base ++ "unshuffle tf_dsv41_vis_unshuffle" }, + .{ .f = .merge, .name = base ++ "merge tf_dsv41_vis_merge" }, + .{ .f = .attn, .name = base ++ "attention tf_dsv41_vis_attn" }, + .{ .f = .epi_bias, .name = base ++ "epilogue bias control: the bias dropped", .ctl = 1 }, + .{ .f = .qkv, .name = base ++ "qkv control: sin and cos swapped", .ctl = 2 }, + .{ .f = .attn, .name = base ++ "attention control: the max not subtracted", .ctl = 3 }, + .{ .f = .swiglu, .name = base ++ "swiglu control: gate and up swapped", .ctl = 4 }, + .{ .f = .unshuffle, .name = base ++ "unshuffle control: a stride off by one", .ctl = 5 }, + .{ .f = .merge, .name = base ++ "merge control: wrong delimiter", .ctl = 6 }, + }; + + 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.name, entry.ctl); + 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 splits(f: Fam) bool { + return f != .attn and f != .unshuffle; + } + + /// Launches of 1, 7 and rows/3 rows give the whole launch's bytes. + 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 (!splits(p.fam)) continue; + kernels += 1; + const shape = spec(p.fam, p.name).served[1]; + if (!try p.prepare(.{ .rows = shape.rows + 20, .n = shape.n, .k = shape.k }, .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); + const rows = p.shape.rows; + for ([_]usize{ 1, 7, @max(1, rows / 3) }) |step| { + @memset(p.rig.bytes(p.out, len), 0x55); + const pass = p.rig.begin(); + var r0: usize = 0; + while (r0 < rows) : (r0 += step) { + try p.encode(pass.e, r0, @min(step, 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} rows a launch differs from one launch\n", .{ p.name, step }); + } + } + } + if (kernels == 0) return 0; + std.debug.print("{s} row invariance {s}: {d} kernels at 1, 7 and rows/3 rows a launch ({d} launches) byte-equal to one launch, {d} differ\n", .{ if (bad == 0) "PASS" else "FAIL", base, kernels, launches, bad }); + return bad; + } +}; From 7ff4a4901db426cedf7b93b1b47f43075389d48b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:14:14 +0000 Subject: [PATCH 3/3] changelog: back under Unreleased --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bed15ba902..75b3ad56c83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- On Macs, DeepSeek V4.1's vision tower (epilogues, RoPE, attention, SwiGLU, the aligner's unshuffle and the stream merge) has its own Metal kernels under the kernel contract, each with a planted control; nothing serves through them until #1722 (#1721, part of #1676). - DeepSeek V4.1 on CUDA: a request whose prompt and reply don't fit the free KV pool now waits in the queue until a running request ends instead of running unreserved (one that can never fit fails at once with a reason), and at TP=2 the ranks agree on each new KV page and roll back together before any device table changes; replies are unchanged (#1682). Thanks to @jayleaton. - Metal on M1 to M4: the 4-bit prompt matrix multiply reads each input row's group sums and half-precision operands from a prepass, bit-equal to the existing tiles; Qwen3.8-27B prompts run 3% to 4% faster on an M3 Ultra from 2K to 64K tokens, with decode level (#3215, toward #2089). Thanks to @jschmied. @@ -230,7 +231,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel same way; its departures are listed in the recipe beside float32's (#2074). Thanks to @BobClawblaw. - GLM-5.3-Flash on CUDA with `TF_KV_SHARE` and no `--prompt-cache-gib`: the kept states' slots, `TF_KV_SHARE` at most, now come where an asked cache goes, before the windows past the engine's own, so a room that holds one more whole window no longer keeps fewer states; Jammed XSFP4 at TP=3 on three GB10s keeps all 32 at `TF_KV_SHARE=32` instead of 8, with the same tokens (#3125). Thanks to @Bizuayeu. -- On Macs, DeepSeek V4.1's vision tower (epilogues, RoPE, attention, SwiGLU, the aligner's unshuffle and the stream merge) has its own Metal kernels under the kernel contract, each with a planted control; nothing serves through them until #1722 (#1721, part of #1676). - Server: with thinking off, the reasoning effort a request names reaches the chat template (GLM's head follows it), and the reply reports it; a server's own `--reasoning-effort` no longer changes a thinking-off prompt (#3017, fixes #1911). Thanks to @ss-cong for the report.