From 457f6a9fbd193bcc7ad053c6d9040c2c46d1643f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:48:28 +0000 Subject: [PATCH 001/265] h3: MiniMax-H3-Image's VAE rules on the host, and Pillow's Lanczos-3 in core/picture picture_vae.zig: the released VAE config, the tile split (256 pixels, overlaps of at least 64 spread 16 at a time), the float32 band blend and placement, the latent statistics, ImageNet pixels with truncating bytes, and the fp16-kept posterior sample. resample.zig gains Pillow's LANCZOS filter, sinc(x) sinc(x / 3) within 3. --- zig/src/core/picture/resample.zig | 48 ++++- zig/src/families/h3/geometry_test.zig | 1 + zig/src/families/h3/h3.zig | 1 + zig/src/families/h3/picture_vae.zig | 246 +++++++++++++++++++++++ zig/src/families/h3/picture_vae_test.zig | 143 +++++++++++++ 5 files changed, 437 insertions(+), 2 deletions(-) create mode 100644 zig/src/families/h3/picture_vae.zig create mode 100644 zig/src/families/h3/picture_vae_test.zig diff --git a/zig/src/core/picture/resample.zig b/zig/src/core/picture/resample.zig index 6833b5c61a5..5b596db6b1e 100644 --- a/zig/src/core/picture/resample.zig +++ b/zig/src/core/picture/resample.zig @@ -1,4 +1,4 @@ -//! Resizes of 8-bit RGB: Keys' cubic (a = -0.5) or Pillow's triangle, widened by the shrink factor, width then height. +//! Resizes of 8-bit RGB: Keys' cubic (a = -0.5), Pillow's triangle or Lanczos-3, widened when shrinking, width first. const std = @import("std"); const Allocator = std.mem.Allocator; @@ -9,15 +9,17 @@ pub const Kind = enum { torch, // torch's antialiased uint8 bicubic: int16 weights at the most bits (at most 22) the largest allows }; -/// The kernel: Keys' cubic, or the triangle of Pillow's BILINEAR (Step3-VL's processor). +/// The kernel: Keys' cubic, the triangle of Pillow's BILINEAR (Step3-VL), or Pillow's LANCZOS (MiniMax-H3-Image). pub const Filter = enum { bicubic, bilinear, + lanczos, fn support(f: Filter) f64 { return switch (f) { .bicubic => 2, .bilinear => 1, + .lanczos => 3, }; } @@ -25,10 +27,18 @@ pub const Filter = enum { return switch (f) { .bicubic => cubic(x), .bilinear => if (@abs(x) < 1) 1 - @abs(x) else 0, + .lanczos => if (@abs(x) < 3) sinc(x) * sinc(x / 3) else 0, }; } }; +/// sin(pi x) / (pi x), and 1 at 0. +fn sinc(x: f64) f64 { + if (x == 0) return 1; + const t = x * std.math.pi; + return @sin(t) / t; +} + /// RGB rows `stride` bytes apart. pub const View = struct { pixels: []const u8, @@ -363,3 +373,37 @@ test "bilinear matches Pillow 12.3's Image.resize(BILINEAR), shrinking and enlar 199, 236, 17, 127, 164, 73, 73, 110, 147, 146, 183, 220, 93, 130, 167, 20, 57, 94, }, big); } + +test "lanczos: sinc(x) sinc(x / 3) within 3, normalized taps, flat stays flat, ringing clamped" { + const a = std.testing.allocator; + try std.testing.expectEqual(@as(f64, 1), Filter.lanczos.at(0)); + for ([_]f64{ 1, 2, -1, -2 }) |x| try std.testing.expectApproxEqAbs(@as(f64, 0), Filter.lanczos.at(x), 1e-16); + try std.testing.expectApproxEqAbs(@as(f64, 6.0) / (std.math.pi * std.math.pi), Filter.lanczos.at(0.5), 1e-15); + try std.testing.expectEqual(@as(f64, 0), Filter.lanczos.at(3)); + try std.testing.expect(Filter.lanczos.at(1.5) < 0); + for ([_][2]usize{ .{ 2720, 1280 }, .{ 1536, 720 }, .{ 7, 13 } }) |s| { + var w = try Weights.init(a, .lanczos, s[0], s[1]); + defer w.deinit(a); + for (0..s[1]) |i| { + var total: f64 = 0; + for (w.at(i)[1]) |v| total += v; + try std.testing.expectApproxEqAbs(@as(f64, 1), total, 1e-12); + } + } + const px = try a.alloc(u8, 9 * 4 * 3); + defer a.free(px); + @memset(px, 77); + for ([_][2]usize{ .{ 4, 2 }, .{ 20, 9 }, .{ 9, 4 } }) |s| { + const out = try resizeWith(a, .pillow, .lanczos, View.of(px, 9, 4), s[0], s[1]); + defer a.free(out); + for (out) |v| try std.testing.expectEqual(@as(u8, 77), v); + } + // a hard edge enlarged rings past 0 and 255, and both passes clamp + var edge: [4 * 1 * 3]u8 = .{ 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255 }; + const up = try resizeWith(a, .pillow, .lanczos, View.of(&edge, 4, 1), 16, 1); + defer a.free(up); + for (0..16) |i| try std.testing.expectEqual(@as(usize, 255), @as(usize, up[3 * i]) + up[3 * (15 - i)]); + try std.testing.expectEqual(@as(u8, 0), std.mem.min(u8, up[3 * 2 .. 3 * 6])); + try std.testing.expectEqual(@as(u8, 255), std.mem.max(u8, up[3 * 10 .. 3 * 14])); + try std.testing.expect(up[3 * 1] > 0 and up[3 * 14] < 255); +} diff --git a/zig/src/families/h3/geometry_test.zig b/zig/src/families/h3/geometry_test.zig index 20371265285..6a4133c6475 100644 --- a/zig/src/families/h3/geometry_test.zig +++ b/zig/src/families/h3/geometry_test.zig @@ -390,6 +390,7 @@ test "H3 serialized full64 tiles no text or held frame and last valid slots" { test { _ = @import("schedule_replace_test.zig"); _ = @import("picture_test.zig"); + _ = @import("picture_vae_test.zig"); } /// MiniMax-H3-Image's case: text and picture rows only, no audio tensor, two rows in two tiles. diff --git a/zig/src/families/h3/h3.zig b/zig/src/families/h3/h3.zig index fcbec20a948..b9a4dae0cee 100644 --- a/zig/src/families/h3/h3.zig +++ b/zig/src/families/h3/h3.zig @@ -9,6 +9,7 @@ pub const modulation = @import("modulation.zig"); pub const schedule = @import("schedule.zig"); pub const geometry = @import("geometry.zig"); pub const picture = @import("picture.zig"); +pub const picture_vae = @import("picture_vae.zig"); pub const Tensors = tensors.Tensors; pub const Ref = tensors.Ref; diff --git a/zig/src/families/h3/picture_vae.zig b/zig/src/families/h3/picture_vae.zig new file mode 100644 index 00000000000..f1dd2a1638d --- /dev/null +++ b/zig/src/families/h3/picture_vae.zig @@ -0,0 +1,246 @@ +//! MiniMax-H3-Image's VAE on the host: its config, the tile split and blend, latent statistics, pixels, posterior. +const std = @import("std"); +const geometry = @import("geometry.zig"); + +pub const latent_channels = 24; +/// Pixels a latent cell covers a side. +pub const cell_pixels = 16; +/// The decoder's transformer: 24 layers of 16 heads of 64, a gated FFN of 4,096, 4 register tokens. +pub const layers = 24; +pub const heads = 16; +pub const head_dim = 64; +pub const width = heads * head_dim; +pub const ffn = 4096; +pub const registers = 4; +/// Rotated dims a head: `rope_dim_ratio` of the head; 8 frequencies an axis over two axes. +pub const rotated = 32; +pub const axis_freqs = rotated / 4; +/// Every decoder norm's epsilon, and the encoder's GroupNorm's. +pub const eps: f32 = 1e-5; +pub const group_eps: f32 = 1e-6; +/// ImageNet's statistics, which map decoded values to [0, 1] pixels and pixels to the encoder's input. +pub const pixel_mean = [3]f32{ 0.485, 0.456, 0.406 }; +pub const pixel_std = [3]f32{ 0.229, 0.224, 0.225 }; + +/// `vae/config.json` at the released geometry: the latent statistics, the tiles and the decoder's rotary theta. +pub const Config = struct { + mean: [latent_channels]f32, + std: [latent_channels]f32, + tile: usize, + overlap: usize, + rope_theta: f32, +}; + +fn number(v: std.json.Value) !f64 { + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |f| f, + else => error.H3BadVaeConfig, + }; +} + +fn get(o: std.json.ObjectMap, key: []const u8) !std.json.Value { + return o.get(key) orelse error.H3BadVaeConfig; +} + +fn expectInt(o: std.json.ObjectMap, key: []const u8, want: i64) !void { + const v = try get(o, key); + if (v != .integer or v.integer != want) return error.H3UnsupportedVae; +} + +fn expectText(o: std.json.ObjectMap, key: []const u8, want: []const u8) !void { + const v = try get(o, key); + if (v != .string or !std.mem.eql(u8, v.string, want)) return error.H3UnsupportedVae; +} + +fn expectBool(o: std.json.ObjectMap, key: []const u8, want: bool) !void { + const v = try get(o, key); + if (v != .bool or v.bool != want) return error.H3UnsupportedVae; +} + +/// Accepts `MiniMaxH3ImageVAE` at the released decoder and tiling, else an error naming what differs. +pub fn config(a: std.mem.Allocator, json: []const u8) !Config { + const doc = std.json.parseFromSliceLeaky(std.json.Value, a, json, .{}) catch return error.H3BadVaeConfig; + if (doc != .object) return error.H3BadVaeConfig; + const o = doc.object; + try expectText(o, "_class_name", "MiniMaxH3ImageVAE"); + try expectInt(o, "latent_channels", latent_channels); + try expectInt(o, "vae_token_drop", 0); + try expectBool(o, "vit_decoder_2d", true); + try expectInt(o, "vae_decoder_tiling", 1); + const kw = try get(o, "vit_decoder_kwargs"); + if (kw != .object) return error.H3BadVaeConfig; + const k = kw.object; + inline for (.{ .{ "num_layers", layers }, .{ "heads", heads }, .{ "dim_head", head_dim } }) |kv| try expectInt(k, kv[0], kv[1]); + inline for (.{ .{ "norm_type", "rms_norm" }, .{ "qk_norm_type", "rms_norm" }, .{ "ffn_activation_fn", "silu" } }) |kv| try expectText(k, kv[0], kv[1]); + try expectBool(k, "norm_affine", true); + try expectBool(k, "qk_norm_affine", false); + try expectBool(k, "ffn_use_gated", true); + if (try number(try get(k, "rope_dim_ratio")) != 0.5) return error.H3UnsupportedVae; + const theta = try number(try get(k, "rope_theta")); + if (!(theta > 0) or !std.math.isFinite(theta)) return error.H3BadVaeConfig; + var c: Config = .{ .mean = undefined, .std = undefined, .tile = 0, .overlap = 0, .rope_theta = @floatCast(theta) }; + inline for (.{ .{ "latents_mean", &c.mean }, .{ "latents_std", &c.std } }) |kv| { + const list = try get(o, kv[0]); + if (list != .array or list.array.items.len != latent_channels) return error.H3BadVaeConfig; + for (kv[1], list.array.items) |*d, v| { + const f = try number(v); + if (!std.math.isFinite(f)) return error.H3BadVaeConfig; + d.* = @floatCast(f); + } + } + for (c.std) |s| if (!(s > 0)) return error.H3BadVaeConfig; + const tile = try get(o, "vae_tile_size"); + const overlap = try get(o, "vae_tile_overlap_min"); + if (tile != .integer or overlap != .integer) return error.H3BadVaeConfig; + if (tile.integer < cell_pixels or overlap.integer < 0 or overlap.integer >= tile.integer or + @rem(tile.integer, cell_pixels) != 0 or @rem(overlap.integer, cell_pixels) != 0) return error.H3BadVaeConfig; + c.tile = @intCast(tile.integer); + c.overlap = @intCast(overlap.integer); + return c; +} + +/// One tile of an axis: its first pixel, its length and its overlap with the next tile (0 for the last). +pub const Span = struct { start: usize, len: usize, overlap: usize }; + +/// An axis in tiles overlapping by at least `least`, the spare spread 16 pixels at a time from the first overlap. +pub fn split(a: std.mem.Allocator, length: usize, tile: usize, least: usize) ![]Span { + if (length == 0 or length % cell_pixels != 0 or tile % cell_pixels != 0 or least % cell_pixels != 0 or least >= tile) + return error.H3BadTiles; + if (tile >= length) { + const one = try a.alloc(Span, 1); + one[0] = .{ .start = 0, .len = length, .overlap = 0 }; + return one; + } + var count = (length + tile - 1) / tile; + while (count * tile < (count - 1) * least + length) count += 1; + if (count > geometry.tile_max) return error.H3BadTiles; + const spare = (count * tile - (count - 1) * least - length) / cell_pixels; + const spans = try a.alloc(Span, count); + var start: usize = 0; + for (spans, 0..) |*s, i| { + const last = i + 1 == count; + const extra: usize = if (last) 0 else spare / (count - 1) + @intFromBool(i < spare % (count - 1)); + s.* = .{ .start = start, .len = tile, .overlap = if (last) 0 else least + extra * cell_pixels }; + start += tile - s.overlap; + } + return spans; +} + +/// Decoded tiles, row-major: top band blended with the tile above, left band with the left one (both as decoded). +pub const Assembler = struct { + rows: []const Span, + cols: []const Span, + channels: usize, + out: []f32, + height: usize, + width: usize, + above: [][]f32, + current: [][]f32, + scratch: []f32, + + pub fn init(a: std.mem.Allocator, rows: []const Span, cols: []const Span, channels: usize, out: []f32) !Assembler { + const height = rows[rows.len - 1].start + rows[rows.len - 1].len; + const w = cols[cols.len - 1].start + cols[cols.len - 1].len; + if (out.len != try geometry.product(&.{ channels, height, w })) return error.H3BadLatentLength; + const most = try geometry.product(&.{ channels, rows[0].len, cols[0].len }); + const above = try a.alloc([]f32, cols.len); + const current = try a.alloc([]f32, cols.len); + for (above, current) |*x, *y| { + x.* = try a.alloc(f32, most); + y.* = try a.alloc(f32, most); + } + return .{ .rows = rows, .cols = cols, .channels = channels, .out = out, .height = height, .width = w, .above = above, .current = current, .scratch = try a.alloc(f32, most) }; + } + + /// The fp32 weights of band row or column `p` of `extent`: the neighbour's 1 - p / e and this tile's p / e. + pub fn weights(p: usize, extent: usize) [2]f32 { + const t = @as(f64, @floatFromInt(p)) / @as(f64, @floatFromInt(extent)); + return .{ @floatCast(1.0 - t), @floatCast(t) }; + } + + /// Tile (r, c) as decoded; tiles must come in row-major order. + pub fn place(s: *Assembler, r: usize, c: usize, tile: []const f32) !void { + const th = s.rows[r].len; + const tw = s.cols[c].len; + if (tile.len != s.channels * th * tw) return error.H3BadLatentLength; + if (c == 0 and r > 0) std.mem.swap([][]f32, &s.above, &s.current); + @memcpy(s.current[c][0..tile.len], tile); + const t = s.scratch[0..tile.len]; + @memcpy(t, tile); + if (r > 0) { + const e = s.rows[r - 1].overlap; + const up = s.above[c]; + const uh = s.rows[r - 1].len; + for (0..s.channels) |ch| for (0..e) |p| { + const w = weights(p, e); + for (0..tw) |x| { + const at = (ch * th + p) * tw + x; + t[at] = up[(ch * uh + uh - e + p) * tw + x] * w[0] + t[at] * w[1]; + } + }; + } + if (c > 0) { + const e = s.cols[c - 1].overlap; + const left = s.current[c - 1]; + const lw = s.cols[c - 1].len; + for (0..s.channels) |ch| for (0..th) |y| for (0..e) |p| { + const w = weights(p, e); + const at = (ch * th + y) * tw + p; + t[at] = left[(ch * th + y) * lw + lw - e + p] * w[0] + t[at] * w[1]; + }; + } + const keep_h = th - s.rows[r].overlap; + const keep_w = tw - s.cols[c].overlap; + for (0..s.channels) |ch| for (0..keep_h) |y| { + const to = (ch * s.height + s.rows[r].start + y) * s.width + s.cols[c].start; + @memcpy(s.out[to..][0..keep_w], t[(ch * th + y) * tw ..][0..keep_w]); + }; + } +}; + +/// A normalised latent [24, rows, columns] to the VAE's raw latent, in place: x * std + mean, float32. +pub fn denormalize(c: *const Config, latent: []f32) !void { + if (latent.len % latent_channels != 0) return error.H3BadLatentLength; + const plane = latent.len / latent_channels; + for (0..latent_channels) |ch| for (latent[ch * plane ..][0..plane]) |*v| { + v.* = v.* * c.std[ch] + c.mean[ch]; + }; +} + +/// The inverse, in place: (x - mean) / std, float32. +pub fn normalize(c: *const Config, latent: []f32) !void { + if (latent.len % latent_channels != 0) return error.H3BadLatentLength; + const plane = latent.len / latent_channels; + for (0..latent_channels) |ch| for (latent[ch * plane ..][0..plane]) |*v| { + v.* = (v.* - c.mean[ch]) / c.std[ch]; + }; +} + +/// A [0, 1] value as a byte: x * 255 clamped, then truncated, not rounded. +pub fn quantise(x: f32) u8 { + return @intFromFloat(std.math.clamp(x * 255.0, 0.0, 255.0)); +} + +/// One decoded value of channel `ch` mapped to [0, 1] with ImageNet's statistics, clamped, then quantised. +pub fn byte(decoded: f32, ch: usize) u8 { + return quantise(std.math.clamp(decoded * pixel_std[ch] + pixel_mean[ch], 0.0, 1.0)); +} + +/// Decoded [3, height, width] float32 to RGB bytes [height, width, 3]. +pub fn pixels(decoded: []const f32, h: usize, w: usize, rgb: []u8) !void { + const plane = try geometry.product(&.{ h, w }); + if (decoded.len != 3 * plane or rgb.len != 3 * plane) return error.H3BadLatentLength; + for (0..3) |ch| for (0..plane) |i| { + rgb[3 * i + ch] = byte(decoded[ch * plane + i], ch); + }; +} + +/// The encoder's posterior sample: mean + exp(0.5 * clamp(logvar, -30, 20)) * noise, kept as fp16 does. +pub fn posterior(mean: []const f32, logvar: []const f32, noise: []const f32, out: []f32) !void { + if (mean.len != logvar.len or mean.len != noise.len or mean.len != out.len) return error.H3BadLatentLength; + for (out, mean, logvar, noise) |*o, m, lv, n| { + const s = @exp(0.5 * std.math.clamp(lv, -30.0, 20.0)); + o.* = @floatCast(@as(f16, @floatCast(m + s * n))); + } +} diff --git a/zig/src/families/h3/picture_vae_test.zig b/zig/src/families/h3/picture_vae_test.zig new file mode 100644 index 00000000000..63b2fce3752 --- /dev/null +++ b/zig/src/families/h3/picture_vae_test.zig @@ -0,0 +1,143 @@ +//! MiniMax-H3-Image's VAE host rules (picture_vae.zig): config, tiles, blend, statistics, bytes, posterior. +const std = @import("std"); +const v = @import("picture_vae.zig"); +const testing = std.testing; + +fn arena() std.heap.ArenaAllocator { + return std.heap.ArenaAllocator.init(testing.allocator); +} + +fn configJson(a: std.mem.Allocator, change: []const u8) ![]const u8 { + var mean: []const u8 = "0.5"; + for (1..24) |_| mean = try std.fmt.allocPrint(a, "{s}, 0.5", .{mean}); + const base = try std.fmt.allocPrint(a, + \\{{"_class_name": "MiniMaxH3ImageVAE", "latent_channels": 24, "latents_mean": [{s}], "latents_std": [{s}], + \\"vae_tile_size": 256, "vae_tile_overlap_min": 64, "vae_token_drop": 0, "vit_decoder_2d": true, + \\"vae_decoder_tiling": 1, "vit_decoder_kwargs": {{"dim_head": 64, "ffn_activation_fn": "silu", + \\"ffn_use_gated": true, "heads": 16, "norm_affine": true, "norm_type": "rms_norm", "num_layers": 24, + \\"qk_norm_affine": false, "qk_norm_type": "rms_norm", "rope_dim_ratio": 0.5, "rope_theta": 100.0}}}} + , .{ mean, mean }); + if (change.len == 0) return base; + const at = std.mem.indexOf(u8, change, "=>").?; + return std.mem.replaceOwned(u8, a, base, change[0..at], change[at + 2 ..]); +} + +test "picture vae config: the released geometry, and every difference refused" { + var a = arena(); + defer a.deinit(); + const x = a.allocator(); + const c = try v.config(x, try configJson(x, "")); + try testing.expectEqual(@as(usize, 256), c.tile); + try testing.expectEqual(@as(usize, 64), c.overlap); + try testing.expectEqual(@as(f32, 100), c.rope_theta); + try testing.expectEqual(@as(f32, 0.5), c.std[23]); + for ([_][]const u8{ + "MiniMaxH3ImageVAE=>AutoencoderKL", "\"vae_token_drop\": 0=>\"vae_token_drop\": 1", + "\"qk_norm_affine\": false=>\"qk_norm_affine\": true", "\"num_layers\": 24=>\"num_layers\": 26", + "\"rope_dim_ratio\": 0.5=>\"rope_dim_ratio\": 1.0", "\"vit_decoder_2d\": true=>\"vit_decoder_2d\": false", + }) |change| try testing.expectError(error.H3UnsupportedVae, v.config(x, try configJson(x, change))); + for ([_][]const u8{ + "\"vae_tile_size\": 256=>\"vae_tile_size\": 250", "\"vae_tile_overlap_min\": 64=>\"vae_tile_overlap_min\": 256", + "[0.5, 0.5=>[0.5", "\"rope_theta\": 100.0=>\"rope_theta\": 0", + }) |change| try testing.expectError(error.H3BadVaeConfig, v.config(x, try configJson(x, change))); +} + +fn expectSplit(length: usize, starts: []const usize, overlaps: []const usize) !void { + var a = arena(); + defer a.deinit(); + const s = try v.split(a.allocator(), length, 256, 64); + try testing.expectEqual(starts.len, s.len); + for (s, starts, overlaps) |span, start, o| { + try testing.expectEqual(start, span.start); + try testing.expectEqual(o, span.overlap); + } +} + +test "picture vae tiles: 1024, 2048 and 4096 pixels at 256 with at least 64 shared" { + try expectSplit(1024, &.{ 0, 192, 384, 576, 768 }, &.{ 64, 64, 64, 64, 0 }); + try expectSplit(2048, &.{ 0, 176, 352, 528, 704, 880, 1056, 1232, 1408, 1600, 1792 }, &.{ 80, 80, 80, 80, 80, 80, 80, 80, 64, 64, 0 }); + var a = arena(); + defer a.deinit(); + const big = try v.split(a.allocator(), 4096, 256, 64); + try testing.expectEqual(@as(usize, 21), big.len); + for (big[0..20]) |s| try testing.expectEqual(@as(usize, 64), s.overlap); + const one = try v.split(a.allocator(), 192, 256, 64); + try testing.expectEqual(@as(usize, 1), one.len); + try testing.expectEqual(@as(usize, 192), one[0].len); + try testing.expectError(error.H3BadTiles, v.split(a.allocator(), 1000, 256, 64)); +} + +test "picture vae tiles: every 32-pixel length ends its last tile on the edge, overlaps at least the least" { + var a = arena(); + defer a.deinit(); + var n: usize = 32; + while (n <= 8192) : (n += 32) { + const s = try v.split(a.allocator(), n, 256, 64); + const last = s[s.len - 1]; + try testing.expectEqual(n, last.start + last.len); + for (s[0 .. s.len - 1], s[1..]) |x, y| { + try testing.expect(x.overlap >= 64 and x.overlap % 16 == 0 and x.overlap < 256); + try testing.expectEqual(x.start + x.len - x.overlap, y.start); + } + } +} + +test "picture vae assembly: band weights, copies of one picture reassemble it, a band blends its two tiles" { + var a = arena(); + defer a.deinit(); + const x = a.allocator(); + try testing.expectEqual([2]f32{ 1, 0 }, v.Assembler.weights(0, 80)); + try testing.expectEqual([2]f32{ @floatCast(1.0 - 40.0 / 80.0), @floatCast(40.0 / 80.0) }, v.Assembler.weights(40, 80)); + // a 2-channel 1024 x 1024 picture of small integers, cut into its tiles and put back + const rows = try v.split(x, 1024, 256, 64); + const src = try x.alloc(f32, 2 * 1024 * 1024); + for (src, 0..) |*p, i| p.* = @floatFromInt(i % 7); + const out = try x.alloc(f32, src.len); + var asm_ = try v.Assembler.init(x, rows, rows, 2, out); + const tile = try x.alloc(f32, 2 * 256 * 256); + for (rows, 0..) |r, ri| for (rows, 0..) |c, ci| { + for (0..2) |ch| for (0..256) |y| for (0..256) |col| { + tile[(ch * 256 + y) * 256 + col] = src[(ch * 1024 + r.start + y) * 1024 + c.start + col]; + }; + try asm_.place(ri, ci, tile); + }; + for (out, src) |o, s| try testing.expectApproxEqAbs(s, o, 1e-5); + // two tiles of 0 and 1 side by side: column p of the band is 0 * (1 - p / 64) + 1 * p / 64 + const cols = try v.split(x, 448, 256, 64); + const one = [_]v.Span{.{ .start = 0, .len = 16, .overlap = 0 }}; + const two = try x.alloc(f32, 16 * 448); + var pair = try v.Assembler.init(x, &one, cols, 1, two); + const left = try x.alloc(f32, 16 * 256); + @memset(left, 0); + const right = try x.alloc(f32, 16 * 256); + @memset(right, 1); + try pair.place(0, 0, left); + try pair.place(0, 1, right); + try testing.expectEqual(cols[1].start, @as(usize, 192)); + for (0..64) |p| try testing.expectEqual(v.Assembler.weights(p, 64)[1], two[5 * 448 + 192 + p]); + try testing.expectEqual(@as(f32, 0), two[5 * 448 + 191]); + try testing.expectEqual(@as(f32, 1), two[5 * 448 + 447]); +} + +test "picture vae bytes truncate; statistics go both ways; the posterior is kept as fp16" { + try testing.expectEqual(@as(u8, 0), v.quantise(0)); + try testing.expectEqual(@as(u8, 127), v.quantise(0.5)); + try testing.expectEqual(@as(u8, 254), v.quantise(254.9 / 255.0)); + try testing.expectEqual(@as(u8, 255), v.quantise(1)); + try testing.expectEqual(@as(u8, 0), v.quantise(-0.25)); + try testing.expectEqual(@as(u8, 255), v.byte(100, 0)); + try testing.expectEqual(@as(u8, 0), v.byte(-100, 2)); + var c: v.Config = .{ .mean = @splat(0.25), .std = @splat(2), .tile = 256, .overlap = 64, .rope_theta = 100 }; + c.mean[1] = -1; + var lat: [48]f32 = @splat(0.5); + try v.denormalize(&c, &lat); + try testing.expectEqual(@as(f32, 1.25), lat[0]); + try testing.expectEqual(@as(f32, 0), lat[2]); + try v.normalize(&c, &lat); + for (lat) |p| try testing.expectEqual(@as(f32, 0.5), p); + var out: [3]f32 = undefined; + try v.posterior(&.{ 1, 0, 0 }, &.{ 0, 100, -100 }, &.{ 1.0 / 3.0, 1, 1 }, &out); + try testing.expectEqual(@as(f32, @floatCast(@as(f16, @floatCast(@as(f32, 1) + 1.0 / 3.0)))), out[0]); + try testing.expectEqual(@as(f32, @floatCast(@as(f16, @floatCast(@exp(@as(f32, 10)))))), out[1]); + try testing.expectEqual(@as(f32, @floatCast(@as(f16, @floatCast(@exp(@as(f32, -15)))))), out[2]); +} From f5f5d01a611bd0fcfacc5d4766595f80d6f4dd0f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:12:21 +0000 Subject: [PATCH 002/265] h3: tf-h3-image on main: core for safetensors and its fixture, Model.load's io, and H3's Metal tools in h3_metal.zig Main moved H3's safetensors import into the core module (h3_core in metal_targets.zig, core in h3_host.zig). This series came from before that move: tf-h3-image imported safetensors and checkpoint_fixture modules of their own. It now imports core and reads both from it, since a file may sit in one module of a build only and core holds both. Main's h3.Model.load also takes the process's io now, so tf-h3-image passes init.io as tf-h3-dit does. Main's metal_targets.zig is at the 600-line cap, so tf-h3-image's target, and main's tf-h3-dit beside it, move to h3_metal.zig with the H3 modules they share (and the kernel sources they take); metal_targets.zig calls it in one line (589 lines). The steps and their modules are otherwise unchanged. --- zig/build/h3_metal.zig | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 zig/build/h3_metal.zig diff --git a/zig/build/h3_metal.zig b/zig/build/h3_metal.zig new file mode 100644 index 00000000000..d75282d845b --- /dev/null +++ b/zig/build/h3_metal.zig @@ -0,0 +1,26 @@ +//! MiniMax H3's Metal tools: FastH3's transformer (tf-h3-dit) and MiniMax-H3-Image's (tf-h3-image). +const std = @import("std"); + +pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, sources: *std.Build.Module) void { + // MiniMax H3 / FastH3's transformer: the packed rows' denoising forwards against a case file (M5 tensor units). + const h3_kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/kernels.zig") }); + const h3_core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); + const h3_mod = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = h3_core }, .{ .name = "h3_kernels", .module = h3_kernels }, .{ .name = "kernel_sources", .module = sources } } }); + const h3_dit = b.addExecutable(.{ .name = "tf-h3-dit", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/h3_dit.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3", .module = h3_mod } }, + }) }); + b.step("tf-h3-dit", "FastH3's Metal transformer against a case file: velocities, every step, timings").dependOn(&b.addInstallArtifact(h3_dit, .{}).step); + // MiniMax-H3-Image: the same transformer on a picture case, its six distilled steps gated against a reference + const h3_image = b.addExecutable(.{ .name = "tf-h3-image", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/h3_image.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3", .module = h3_mod }, .{ .name = "core", .module = h3_core } }, + }) }); + b.step("tf-h3-image", "MiniMax-H3-Image's Metal transformer on a picture case: six distilled steps, teacher-forced and gated").dependOn(&b.addInstallArtifact(h3_image, .{}).step); +} From e1aecf55956a58e1ebfc4a99c77010244f6cb280 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:50:22 +0000 Subject: [PATCH 003/265] changelog: #2775 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a2f5bfdbd9..de86edf4173 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- MiniMax-H3-Image on Metal: `tf-h3-image` runs its transformer (MiniMax H3's, without the audio layers, on M5 tensor units) from a picture case through its six distilled steps, each with its own output head, beside the engine; the VAE's rules (config, tiles and blend, latent statistics, pixels) run on the host, and core/picture gains Pillow's Lanczos-3 resampling. Clip cases run as before (#2775). + - Kernel contract: the GLM record for `df_sumn` under nvcc 13.3 (40 registers) is the one checked; a stale generic 33-register entry no longer overrides it (#4291). Thanks to @Bizuayeu. - Docs: Desktop's packaged release notes move to `app/CHANGELOG.md`, apart from the engine's, with a link each way (#4284). Thanks to @garvrao80. From 73b002cea2c5f4dc5e963a8335f12ecc2a7d509a Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:32:22 +0100 Subject: [PATCH 004/265] glm metal: vectorize pre-M5 Metal prompt, KDA, and indexer kernels Optimize GLM-5.3-Flash Metal prompt matmul, KDA prep/scan/post, and indexer kernels on !tensorUnits() Apple Silicon GPUs via GLM-scoped TF_GLM_M3_FAST paths and 32-row affine_mm tiling, keeping M5 tensor-unit paths and output tokens bit-identical. Refs #3152. --- zig/kernels/metal/core/affine_mm.metal | 70 ++- zig/kernels/metal/glm_index_nax.metal | 128 ++++- zig/kernels/metal/glm_kda_prompt.metal | 148 +++++- zig/kernels/metal/nax.h | 92 ++++ zig/src/core/affine_mm.zig | 20 +- zig/src/families/glm/checks.zig | 2 +- zig/src/families/glm/forward.zig | 3 +- zig/src/families/glm/kernels.zig | 12 +- zig/src/families/glm/prompt.zig | 13 +- zig/src/families/glm/wide.zig | 21 +- zig/tests/contract/metal_affine.zig | 9 +- zig/tests/contract/metal_affine_gather.zig | 15 +- zig/tests/contract/metal_glm_prompt.zig | 565 +++++++++++++++++++++ zig/tests/contract/metal_limits.zig | 17 +- zig/tests/contract/metal_main.zig | 16 +- zig/tests/glm_rows_batch.zig | 4 +- zig/tests/glm_rows_check.zig | 11 +- zig/tests/glm_rows_classes.zig | 6 +- zig/tests/glm_rows_speed_prompt.zig | 21 +- 19 files changed, 1103 insertions(+), 70 deletions(-) create mode 100644 zig/tests/contract/metal_glm_prompt.zig diff --git a/zig/kernels/metal/core/affine_mm.metal b/zig/kernels/metal/core/affine_mm.metal index c5b94d93d98..a6d07acb0a9 100644 --- a/zig/kernels/metal/core/affine_mm.metal +++ b/zig/kernels/metal/core/affine_mm.metal @@ -152,6 +152,47 @@ inline void am_codes(thread const Codes& c, threadgroup bfloat* out) { #endif } +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) +// GLM pre-M5: codes in [K=64][N=64] layout so frag_get reads transposed weights with zero bank conflict. +inline void am_codes_kn(thread const Codes& c, threadgroup bfloat* tile, int w_n, int w_kh) { +#if TF_BITS == 2 + TF_UNROLL + for (short i = 0; i < 2; i++) { + const uint w = c.v[i]; + TF_UNROLL + for (short j = 0; j < 16; j++) tile[(w_kh * 32 + i * 16 + j) * PAD + w_n] = bfloat(float((w >> (2 * j)) & 3u)); + } +#elif TF_BITS % 4 != 0 + TF_UNROLL + for (short j = 0; j < 32; j++) { + const short at = TF_BITS * j, word = at / 32, shift = at % 32; + uint v = c.v[word] >> shift; + if (shift + TF_BITS > 32) v |= c.v[word + 1] << (32 - shift); + tile[(w_kh * 32 + j) * PAD + w_n] = bfloat(float(v & ((1u << TF_BITS) - 1u))); + } +#elif TF_BITS == 4 + TF_UNROLL + for (short i = 0; i < 4; i++) { + const uint w = c.v[0][i]; + TF_UNROLL + for (short j = 0; j < 8; j++) { + tile[(w_kh * 32 + i * 8 + j) * PAD + w_n] = as_type(ushort(0x4300u | ((w >> (4 * j)) & 0xfu))); + } + } +#else + TF_UNROLL + for (short i = 0; i < 8; i++) { + const uchar4 f = as_type(c.v[i / 4][i % 4]); + const int b = w_kh * 32 + i * 4; + tile[b * PAD + w_n] = bfloat(float(f.x)); + tile[(b + 1) * PAD + w_n] = bfloat(float(f.y)); + tile[(b + 2) * PAD + w_n] = bfloat(float(f.z)); + tile[(b + 3) * PAD + w_n] = bfloat(float(f.w)); + } +#endif +} +#endif + // A block of the code tile as the transposed right operand: 8-byte loads on M5 (PAD rows, 16-column blocks). #ifndef TF_SIMD_FRAGS #define am_tile_frag frag_get_tg @@ -188,8 +229,13 @@ inline void am_step(thread frag (&acc)[TM][2], thread const AmRows& r TF_UNROLL for (short q = 0; q < 4; q++) { // the step's four 16-deep slices, every row fragment's chain interleaved frag b0, b1, a[TL]; +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + frag_get(b0, tile, PAD, 16 * q, tn, home); + frag_get(b1, tile, PAD, 16 * q, tn + 16, home); +#else am_tile_frag(b0, tile, PAD, tn, 16 * q, home); am_tile_frag(b1, tile, PAD, tn + 16, 16 * q, home); +#endif TF_UNROLL for (short m = 0; m < TL; m++) { a[m] = am_frag(rows.x[m][0], rows.x[m][1], k + 16 * q, home); @@ -231,8 +277,13 @@ inline void am_step128(thread frag (&acc)[TM][2], thread frag (&pa TF_UNROLL for (short q = 0; q < 4; q++) { frag b0, b1, a[TL]; +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + frag_get(b0, tile, PAD, 16 * q, tn, home); + frag_get(b1, tile, PAD, 16 * q, tn + 16, home); +#else frag_get_t(b0, tile, PAD, tn, 16 * q, home); frag_get_t(b1, tile, PAD, tn + 16, 16 * q, home); +#endif TF_UNROLL for (short m = 0; m < TL; m++) { a[m] = am_frag(rows.x[m][0], rows.x[m][1], k + 16 * q, home); @@ -268,7 +319,11 @@ template inline void am_k_loop(thread frag (&acc)[TM][2], thread const AmRows& rows, int K, int live, const device uchar* wq, const device bfloat* scales, const device bfloat* biases, threadgroup bfloat* tile, threadgroup float* sb, int tn, uint t, short2 home) { +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + const int w_n = int(t / 2), w_kh = int(t % 2); +#else threadgroup bfloat* mine = tile + (t / 2) * PAD + 32 * (t % 2); +#endif const int g_mine = TF_GROUP == 32 ? int(t % 2) : 0; // at g32 each thread of a pair takes one group's scale and bias #if TF_GROUP == 128 frag part[TM][2]; // a group's sums across its two steps @@ -280,7 +335,11 @@ inline void am_k_loop(thread frag (&acc)[TM][2], thread const AmRows& } for (int k = 0; k < K; k += 64) { threadgroup_barrier(mem_flags::mem_threadgroup); +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + am_codes_kn(am_load(wq), tile, w_n, w_kh); +#else am_codes(am_load(wq), mine); +#endif if (TF_GROUP == 32 || t % 2 == 0) { const float s = float(scales[g_mine]); sb[g_mine * 128 + t / 2] = s; @@ -417,9 +476,14 @@ inline void am_block(const device bfloat* x, int ldx, const device float* xs, in uint3 tg [[threadgroup_position_in_grid]]) { threadgroup bfloat tile[64 * PAD]; threadgroup float sb[NG * 128]; - const int row = int(tg.y) * 64, col = int(tg.x) * 64, b = int(tg.z); - am_block<64>(X + long(b) * st.x_batch, st.x_row, XS + long(b) * st.sums_batch * (a.k / TF_GROUP), - st.sums_row * (a.k / TF_GROUP), row, min(64, a.rows - row), a.k, st.y_row, col, +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + constexpr int BM = 32; +#else + constexpr int BM = 64; +#endif + const int row = int(tg.y) * BM, col = int(tg.x) * 64, b = int(tg.z); + am_block(X + long(b) * st.x_batch, st.x_row, XS + long(b) * st.sums_batch * (a.k / TF_GROUP), + st.sums_row * (a.k / TF_GROUP), row, min(BM, a.rows - row), a.k, st.y_row, col, long(b) * st.w_batch + col, W, S, B, Y + long(b) * st.y_batch, tile, sb, sg, lane); } diff --git a/zig/kernels/metal/glm_index_nax.metal b/zig/kernels/metal/glm_index_nax.metal index 921845be010..e0e5c2c543d 100644 --- a/zig/kernels/metal/glm_index_nax.metal +++ b/zig/kernels/metal/glm_index_nax.metal @@ -10,10 +10,16 @@ struct GlmScoreArgs { uint p0, q_stride, w_stride, s_stride, rows; }; -// A fragment of q at column c from a lane's two row starts (8-byte loads on M5). +// A fragment of q at column c from a lane's two row starts (8-byte loads on M5, 4-byte on pre-M5 GLM). inline frag ix_frag(const device bfloat* r0, const device bfloat* r1, int c, short2 home) { #ifndef TF_SIMD_FRAGS return frag(*(const device bfloat4*)(r0 + c + home.x), *(const device bfloat4*)(r1 + c + home.x)); +#elif defined(TF_GLM_M3_FAST) + const bfloat2 a0 = *(const device bfloat2*)(r0 + c + home.x); + const bfloat2 a1 = *(const device bfloat2*)(r0 + c + home.x + 8); + const bfloat2 b0 = *(const device bfloat2*)(r1 + c + home.x); + const bfloat2 b1 = *(const device bfloat2*)(r1 + c + home.x + 8); + return frag(a0.x, a0.y, a1.x, a1.y, b0.x, b0.y, b1.x, b1.y); #else frag f; TF_UNROLL @@ -30,6 +36,64 @@ inline frag ix_frag(const device bfloat* r0, const device bfloat* r1, in constant GlmScoreArgs& a [[buffer(4)]], uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]], uint sgs [[simdgroups_per_threadgroup]]) { +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + constexpr int TPAD = 64 + 8; + threadgroup bfloat tileT[DI * TPAD]; + const int b0 = int(tg.x) * 64, r0 = int(tg.y) * 32; + const int rows = min(32, int(a.rows) - r0); + if (rows <= 0 || b0 >= (int(a.p0) + r0 + rows) / 4) return; + const uint t = sg * 32 + lane; + for (uint i = t; i < 64 * (DI / 8); i += 128) { + const uint rr = i / (DI / 8), cc = (i % (DI / 8)) * 8; + const int b = min(b0 + int(rr), int(a.s_stride) - 1); + const uint4 v = *(const device uint4*)(pool + size_t(b) * DI + cc); + const bfloat2 p0 = as_type(v.x), p1 = as_type(v.y); + const bfloat2 p2 = as_type(v.z), p3 = as_type(v.w); + tileT[(cc + 0) * TPAD + rr] = p0.x; tileT[(cc + 1) * TPAD + rr] = p0.y; + tileT[(cc + 2) * TPAD + rr] = p1.x; tileT[(cc + 3) * TPAD + rr] = p1.y; + tileT[(cc + 4) * TPAD + rr] = p2.x; tileT[(cc + 5) * TPAD + rr] = p2.y; + tileT[(cc + 6) * TPAD + rr] = p3.x; tileT[(cc + 7) * TPAD + rr] = p3.y; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const short2 home = frag_home(ushort(lane)); + const int tm = 16 * int(sg / 2), tn = 32 * int(sg % 2); + const device bfloat* qr[2]; + const device bfloat* wr[2]; + TF_UNROLL + for (short h = 0; h < 2; h++) { + const int r = tm + home.y + 8 * h; + const long at = long(r0 + (r < rows ? r : 0)); + qr[h] = iq + at * a.q_stride; + wr[h] = iw + at * a.w_stride; + } + frag total[2] = {frag(0), frag(0)}; + for (int hd = 0; hd < HI; hd++) { + frag s[2] = {frag(0), frag(0)}; + TF_UNROLL + for (short q = 0; q < DI / 16; q++) { + frag k0, k1; + frag_get(k0, tileT, TPAD, 16 * q, tn, home); + frag_get(k1, tileT, TPAD, 16 * q, tn + 16, home); + const frag qa = ix_frag(qr[0] + hd * DI, qr[1] + hd * DI, 16 * q, home); + mma_16x32(s[0], s[1], qa, k0, k1); + } + const float w0 = float(wr[0][hd]), w1 = float(wr[1][hd]); + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) total[j][e] = fma(e < 4 ? w0 : w1, metal::max(s[j][e], 0.0f), total[j][e]); + } + } + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int r = tm + home.y + (e >> 2) * 8; + const int b = b0 + tn + 16 * j + home.x + TF_COL(e); + if (r < rows && b < (int(a.p0) + r0 + r + 1) / 4) scores[size_t(r0 + r) * a.s_stride + b] = total[j][e]; + } + } +#else threadgroup bfloat tile[64 * PAD]; const int tile_rows = 16 * int(sgs); const int b0 = int(tg.x) * 64, r0 = int(tg.y) * tile_rows; @@ -87,6 +151,7 @@ inline frag ix_frag(const device bfloat* r0, const device bfloat* r1, in if (r < rows && b < (int(a.p0) + r0 + r + 1) / 4) scores[size_t(r0 + r) * a.s_stride + b] = total[j][e]; } } +#endif } // A transposed right operand's element e: key (a block, the op's column), dim (on M5 the op loads it as any operand). @@ -98,11 +163,69 @@ inline short ix_key(short e, short2 home) { return home.x + TF_COL(e); } inline short ix_dim(short e, short2 home) { return home.y + (e >> 2) * 8; } #endif -// Decode index scores, grid (128-tile blocks, rows) of 4 simdgroups: 32 heads, bf16 products, relu, weights, head sum. +// Decode index scores, grid (128-tile or 64-tile under TF_GLM_M3_FAST, rows) of 4 simdgroups: 32 heads, head sum. [[kernel]] void glm_index_decode(const device bfloat* iq [[buffer(0)]], const device bfloat* iw [[buffer(1)]], const device bfloat* pool [[buffer(2)]], device float* scores [[buffer(3)]], constant GlmScoreArgs& a [[buffer(4)]], uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + constexpr int TPAD = 64 + 8; + threadgroup bfloat tileT[64 * TPAD]; + const int row = int(tg.y), blk0 = int(tg.x) * 64; + const int blocks = (int(a.p0) + row + 1) / 4; + if (blk0 >= blocks) return; + const uint t = sg * 32 + lane; + const short2 home = frag_home(ushort(lane)); + const int bs = blk0 + 16 * int(sg); + const device bfloat* q = iq + long(row) * a.q_stride; + frag s[2] = {frag(0), frag(0)}; + for (int kd = 0; kd < DI; kd += 64) { + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = t; i < 64u * 8u; i += 128u) { + const uint rr = i >> 3, cc = (i & 7u) * 8u; + const int bk = min(blk0 + int(rr), blocks - 1); + const uint4 v = *(const device uint4*)(pool + long(bk) * DI + kd + cc); + const bfloat2 p0 = as_type(v.x), p1 = as_type(v.y); + const bfloat2 p2 = as_type(v.z), p3 = as_type(v.w); + tileT[(cc + 0) * TPAD + rr] = p0.x; tileT[(cc + 1) * TPAD + rr] = p0.y; + tileT[(cc + 2) * TPAD + rr] = p1.x; tileT[(cc + 3) * TPAD + rr] = p1.y; + tileT[(cc + 4) * TPAD + rr] = p2.x; tileT[(cc + 5) * TPAD + rr] = p2.y; + tileT[(cc + 6) * TPAD + rr] = p3.x; tileT[(cc + 7) * TPAD + rr] = p3.y; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (bs < blocks) { + TF_UNROLL + for (short sub = 0; sub < 4; sub++) { + const int kq = (kd / 16) + sub; + frag k0; + frag_get(k0, tileT, TPAD, 16 * sub, 16 * int(sg), home); + const frag qa0 = ix_frag(q + home.y * DI, q + (home.y + 8) * DI, 16 * kq, home); + const frag qa1 = ix_frag(q + (16 + home.y) * DI, q + (24 + home.y) * DI, 16 * kq, home); + mma_16x16(s[0], qa0, k0); + mma_16x16(s[1], qa1, k0); + } + } + } + if (bs >= blocks) return; + float w[2][2]; + TF_UNROLL + for (short m = 0; m < 2; m++) { + w[m][0] = float(iw[long(row) * a.w_stride + 16 * m + home.y]); + w[m][1] = float(iw[long(row) * a.w_stride + 16 * m + home.y + 8]); + } + TF_UNROLL + for (short c = 0; c < 4; c++) { + float tv = w[0][0] * metal::max(s[0][c], 0.0f); + tv = fma(w[0][1], metal::max(s[0][4 + c], 0.0f), tv); + tv = fma(w[1][0], metal::max(s[1][c], 0.0f), tv); + tv = fma(w[1][1], metal::max(s[1][4 + c], 0.0f), tv); + tv += simd_shuffle_xor(tv, ushort(2)); + tv += simd_shuffle_xor(tv, ushort(4)); + tv += simd_shuffle_xor(tv, ushort(16)); + const int b = bs + home.x + TF_COL(c); + if (home.y == 0 && b < blocks) scores[long(row) * a.s_stride + b] = tv; + } +#else const int row = int(tg.y), b0 = int(tg.x) * 128 + 32 * int(sg); const int blocks = (int(a.p0) + row + 1) / 4; if (b0 >= blocks) return; @@ -156,4 +279,5 @@ inline short ix_dim(short e, short2 home) { return home.y + (e >> 2) * 8; } if (home.y == 0 && b < blocks) scores[long(row) * a.s_stride + b] = t; } } +#endif } diff --git a/zig/kernels/metal/glm_kda_prompt.metal b/zig/kernels/metal/glm_kda_prompt.metal index 79ced70bf9d..910fe908391 100644 --- a/zig/kernels/metal/glm_kda_prompt.metal +++ b/zig/kernels/metal/glm_kda_prompt.metal @@ -19,6 +19,50 @@ template const uint h = tg.y * (uint)HB + sg; const uint PS = (uint)P_shape[1]; const size_t at = (size_t)rl * W + h * (uint)D; +#ifdef TF_GLM_M3_FAST + const uint d = 4u * lane; + float4 sq = float4(0.0f), sk = float4(0.0f); + for (uint part = 0; part < 3u; ++part) { + const uint c = part * W + h * (uint)D + d; + float4 acc = float4(0.0f); + for (int j = 0; j < TAPS; ++j) { + const int e = r + j; + const bfloat4 xv = e < TAPS - 1 + ? *(const device bfloat4*)(CS + (size_t)e * C3 + c) + : *(const device bfloat4*)(P + (size_t)(e - (TAPS - 1)) * PS + c); + const float4 cw = *(const device float4*)(CW + (size_t)j * C3 + c); + const float4 term = float4(xv) * cw; + acc = j == 0 ? term : (acc + term); + } + const bfloat4 xb = bfloat4(acc); + bfloat4 sl; + sl.x = xb.x * mlx_sigmoid_precise(xb.x); + sl.y = xb.y * mlx_sigmoid_precise(xb.y); + sl.z = xb.z * mlx_sigmoid_precise(xb.z); + sl.w = xb.w * mlx_sigmoid_precise(xb.w); + if (part == 0u) sq = float4(sl); + else if (part == 1u) sk = float4(sl); + else *(device bfloat4*)(VO + at + d) = sl; + } + const float a_h = A[h], lb = LB[0]; + const float4 av = float4(*(const device bfloat4*)(FB + at + d)) + *(const device float4*)(DTB + h * (uint)D + d); + float4 go; + go.x = metal::precise::exp(lb * mlx_sigmoid_precise(a_h * av.x)); + go.y = metal::precise::exp(lb * mlx_sigmoid_precise(a_h * av.y)); + go.z = metal::precise::exp(lb * mlx_sigmoid_precise(a_h * av.z)); + go.w = metal::precise::exp(lb * mlx_sigmoid_precise(a_h * av.w)); + *(device float4*)(GO + at + d) = go; + if (lane == 0u) BETA[(size_t)rl * H + h] = float(mlx_sigmoid_precise(P[(size_t)r * PS + BO + h])); + float pq = 0.0f, pk = 0.0f; + pq = sq_acc(pq, sq.x); pq = sq_acc(pq, sq.y); pq = sq_acc(pq, sq.z); pq = sq_acc(pq, sq.w); + pk = sq_acc(pk, sk.x); pk = sq_acc(pk, sk.y); pk = sq_acc(pk, sk.z); pk = sq_acc(pk, sk.w); + pq = simd_sum(pq); + pk = simd_sum(pk); + const float rq = metal::precise::rsqrt(pq + 1.0e-6f), rk = metal::precise::rsqrt(pk + 1.0e-6f); + const float qscale = metal::precise::rsqrt(float(D)); + *(device bfloat4*)(QO + at + d) = bfloat4((sq * rq) * qscale); + *(device bfloat4*)(KO + at + d) = bfloat4(sk * rk); +#else float sq[NDK], sk[NDK]; for (uint part = 0; part < 3u; ++part) { for (int i = 0; i < NDK; ++i) { @@ -60,6 +104,7 @@ template QO[at + d] = bfloat((sq[i] * rq) * qscale); KO[at + d] = bfloat(sk[i] * rk); } +#endif } // Recurrence over R rows: 8 lanes a value column (16 key dims each, 8-way xor-shuffle sums), rows staged B at a time. @@ -81,6 +126,73 @@ template const int c = int(sg) * 4 + int(lane >> 3); // this lane's value column in the threadgroup const uint dv = tg.x * (uint)VC + (uint)c; const int k0 = NK * int(lane & 7u); +#ifdef TF_GLM_M3_FAST + const device float4* si4 = (const device float4*)(ST + ((size_t)h * D + dv) * D + k0); + float4 st4[4]; + for (int i = 0; i < 4; ++i) st4[i] = si4[i]; + for (int r0 = 0; r0 < R; r0 += B) { + const int n = min(B, R - r0); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int idx = int(tid); idx < n * (D / 8); idx += NT) { + const int b = idx / (D / 8), d8 = (idx % (D / 8)) * 8; + const size_t at = (size_t)(r0 + b) * W + h * (uint)D + (uint)d8; + *(threadgroup uint4*)(sqs + b * D + d8) = *(const device uint4*)(QO + at); + *(threadgroup uint4*)(sks + b * D + d8) = *(const device uint4*)(KO + at); + *(threadgroup float4*)(sgs + b * D + d8) = *(const device float4*)(GO + at); + *(threadgroup float4*)(sgs + b * D + d8 + 4) = *(const device float4*)(GO + at + 4); + } + for (int idx = int(tid); idx < n * (VC / 8); idx += NT) { + const int b = idx / (VC / 8), cc = (idx % (VC / 8)) * 8; + *(threadgroup uint4*)(svs + b * VC + cc) = *(const device uint4*)(VO + (size_t)(r0 + b) * W + h * (uint)D + tg.x * (uint)VC + (uint)cc); + } + if (int(tid) < n) sbs[tid] = BETA[(size_t)(r0 + int(tid)) * H + h]; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int b = 0; b < n; ++b) { + const threadgroup uint4* qv = (const threadgroup uint4*)(sqs + b * D + k0); + const threadgroup uint4* kv4 = (const threadgroup uint4*)(sks + b * D + k0); + const threadgroup float4* gv = (const threadgroup float4*)(sgs + b * D + k0); + const uint4 k_lo = kv4[0], k_hi = kv4[1]; + const uint4 q_lo = qv[0], q_hi = qv[1]; + float kv = 0.0f; + float4 kf[4]; + _Pragma("clang loop unroll(full)") + for (int j = 0; j < 4; ++j) { + const uint w0 = j < 2 ? k_lo[2 * j] : k_hi[2 * (j - 2)]; + const uint w1 = j < 2 ? k_lo[2 * j + 1] : k_hi[2 * (j - 2) + 1]; + const bfloat2 b0 = as_type(w0), b1 = as_type(w1); + kf[j] = float4(float(b0.x), float(b0.y), float(b1.x), float(b1.y)); + st4[j] = st4[j] * gv[j]; + kv += st4[j].x * kf[j].x; + kv += st4[j].y * kf[j].y; + kv += st4[j].z * kf[j].z; + kv += st4[j].w * kf[j].w; + } + kv += simd_shuffle_xor(kv, ushort(1)); + kv += simd_shuffle_xor(kv, ushort(2)); + kv += simd_shuffle_xor(kv, ushort(4)); + const float delta = (float(svs[b * VC + c]) - kv) * sbs[b]; + float o = 0.0f; + _Pragma("clang loop unroll(full)") + for (int j = 0; j < 4; ++j) { + const uint w0 = j < 2 ? q_lo[2 * j] : q_hi[2 * (j - 2)]; + const uint w1 = j < 2 ? q_lo[2 * j + 1] : q_hi[2 * (j - 2) + 1]; + const bfloat2 b0 = as_type(w0), b1 = as_type(w1); + const float4 qf = float4(float(b0.x), float(b0.y), float(b1.x), float(b1.y)); + st4[j] = st4[j] + kf[j] * delta; + o += st4[j].x * qf.x; + o += st4[j].y * qf.y; + o += st4[j].z * qf.z; + o += st4[j].w * qf.w; + } + o += simd_shuffle_xor(o, ushort(1)); + o += simd_shuffle_xor(o, ushort(2)); + o += simd_shuffle_xor(o, ushort(4)); + if ((lane & 7u) == 0u) SY[(size_t)(r0 + b) * W + h * (uint)D + dv] = bfloat(o); + } + } + device float4* so4 = (device float4*)(ST_OUT + ((size_t)h * D + dv) * D + k0); + for (int i = 0; i < 4; ++i) so4[i] = st4[i]; +#else device const float* si = ST + ((size_t)h * D + dv) * D + k0; float st[NK]; _Pragma("clang loop unroll(full)") @@ -130,6 +242,7 @@ template device float* so = ST_OUT + ((size_t)h * D + dv) * D + k0; _Pragma("clang loop unroll(full)") for (int i = 0; i < NK; ++i) so[i] = st[i]; +#endif } template @@ -137,10 +250,15 @@ template const device float* ONW [[buffer(2)]], const constant float* EPS [[buffer(3)]], device bfloat16_t* Y [[buffer(4)]], const device bfloat16_t* P [[buffer(5)]], const constant int* P_shape [[buffer(6)]], const device bfloat16_t* CS [[buffer(7)]], - device bfloat16_t* CS_OUT [[buffer(8)]], uint lane [[thread_index_in_simdgroup]], + device bfloat16_t* CS_OUT [[buffer(8)]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { const int r = int(threadgroup_position_in_grid.x); +#ifdef TF_GLM_M3_FAST + const uint h = threadgroup_position_in_grid.y * 4u + sg; +#else const uint h = threadgroup_position_in_grid.y; +#endif constexpr int RBLK = D / 128; constexpr int REXTRA = D - RBLK * 128; constexpr uint W = (uint)(H * D); @@ -149,6 +267,25 @@ template const uint PS = (uint)P_shape[1]; const float eps = EPS[0]; const size_t at = (size_t)r * W + h * (uint)D; +#ifdef TF_GLM_M3_FAST + const uint base = 4u * lane; + const float4 sy4 = float4(*(const device bfloat4*)(SY + at + base)); + float po = 0.0f; + po = sq_acc(po, sy4.x); + po = sq_acc(po, sy4.y); + po = sq_acc(po, sy4.z); + po = sq_acc(po, sy4.w); + po = simd_sum(po); + const float rn = metal::precise::rsqrt(po / (float)D + eps); + const float4 onw = *(const device float4*)(ONW + base); + const float4 g4 = float4(*(const device bfloat4*)(GATE + at + base)); + float4 y4 = (sy4 * rn) * onw; + y4.x *= mlx_sigmoid_precise(g4.x); + y4.y *= mlx_sigmoid_precise(g4.y); + y4.z *= mlx_sigmoid_precise(g4.z); + y4.w *= mlx_sigmoid_precise(g4.w); + *(device bfloat4*)(Y + at + base) = bfloat4(y4); +#else float po = 0.0f; for (int blk = 0; blk < RBLK; ++blk) { const uint base = (uint)(blk * 128) + 4u * lane; @@ -164,6 +301,7 @@ template x = x * mlx_sigmoid_precise(float(GATE[at + d])); Y[at + d] = bfloat(x); } +#endif if (r != 0) return; for (uint idx = lane; idx < 3u * (uint)D * (uint)(TAPS - 1); idx += 32u) { // the next chunk's window: the last rows const uint m = idx / (3u * (uint)D); @@ -177,9 +315,17 @@ template } template [[host_name("glm_kda_prep")]] [[kernel]] decltype(glm_kda_prep<64, 128, 4, 4>) glm_kda_prep<64, 128, 4, 4>; +#ifdef TF_GLM_M3_FAST +template [[host_name("glm_kda_scan")]] [[kernel]] decltype(glm_kda_scan<64, 128, 4, 24>) glm_kda_scan<64, 128, 4, 24>; +#else template [[host_name("glm_kda_scan")]] [[kernel]] decltype(glm_kda_scan<64, 128, 16, 16>) glm_kda_scan<64, 128, 16, 16>; +#endif template [[host_name("glm_kda_post")]] [[kernel]] decltype(glm_kda_post<64, 128, 4, 32, 4, 4>) glm_kda_post<64, 128, 4, 32, 4, 4>; // TP2: one Mac's 32 heads template [[host_name("glm_kda_prep_tp")]] [[kernel]] decltype(glm_kda_prep<32, 128, 4, 4>) glm_kda_prep<32, 128, 4, 4>; +#ifdef TF_GLM_M3_FAST +template [[host_name("glm_kda_scan_tp")]] [[kernel]] decltype(glm_kda_scan<32, 128, 4, 24>) glm_kda_scan<32, 128, 4, 24>; +#else template [[host_name("glm_kda_scan_tp")]] [[kernel]] decltype(glm_kda_scan<32, 128, 16, 16>) glm_kda_scan<32, 128, 16, 16>; +#endif template [[host_name("glm_kda_post_tp")]] [[kernel]] decltype(glm_kda_post<32, 128, 4, 32, 4, 4>) glm_kda_post<32, 128, 4, 32, 4, 4>; diff --git a/zig/kernels/metal/nax.h b/zig/kernels/metal/nax.h index 210c6aaa4c0..341859f2cb7 100644 --- a/zig/kernels/metal/nax.h +++ b/zig/kernels/metal/nax.h @@ -1,6 +1,9 @@ // M5 tensor-unit fragments shared by every NAX kernel (ops and prefill): layout, loads, stores and the 16x32x16 op. #include #include +#if defined(TF_SIMD_FRAGS) && defined(TF_GLM_M3_FAST) +#include +#endif namespace tfp { using namespace metal; @@ -107,10 +110,15 @@ inline short2 frag_home(ushort l) { template inline void frag_get(thread frag& f, P p, int ld, int r, int c, short2 home) { const P q = p + (r + home.y) * ld + (c + home.x); +#ifdef TF_GLM_M3_FAST + f[0] = T(q[0]); f[1] = T(q[1]); f[2] = T(q[8]); f[3] = T(q[9]); + f[4] = T(q[8 * ld]); f[5] = T(q[8 * ld + 1]); f[6] = T(q[8 * ld + 8]); f[7] = T(q[8 * ld + 9]); +#else TF_UNROLL for (short e = 0; e < 8; e++) { f[e] = T(q[(e >> 2) * 8 * ld + TF_COL(e)]); } +#endif } template @@ -164,6 +172,55 @@ inline void frag_put_in(thread const frag& f, device O* p, int ld, int r, template inline void mma_16x32(thread frag& lo, thread frag& hi, thread const frag& a, thread const frag& b0, thread const frag& b1) { +#ifdef TF_GLM_M3_FAST + simdgroup_matrix a00, a01, a10, a11; + simdgroup_matrix b00, b01, b10, b11, c00, c01, c10, c11; + simdgroup_matrix d00, d01, d10, d11, e00, e01, e10, e11; + a00.thread_elements()[0] = a[0]; a00.thread_elements()[1] = a[1]; + a01.thread_elements()[0] = a[2]; a01.thread_elements()[1] = a[3]; + a10.thread_elements()[0] = a[4]; a10.thread_elements()[1] = a[5]; + a11.thread_elements()[0] = a[6]; a11.thread_elements()[1] = a[7]; + b00.thread_elements()[0] = b0[0]; b00.thread_elements()[1] = b0[1]; + b01.thread_elements()[0] = b0[2]; b01.thread_elements()[1] = b0[3]; + b10.thread_elements()[0] = b0[4]; b10.thread_elements()[1] = b0[5]; + b11.thread_elements()[0] = b0[6]; b11.thread_elements()[1] = b0[7]; + c00.thread_elements()[0] = b1[0]; c00.thread_elements()[1] = b1[1]; + c01.thread_elements()[0] = b1[2]; c01.thread_elements()[1] = b1[3]; + c10.thread_elements()[0] = b1[4]; c10.thread_elements()[1] = b1[5]; + c11.thread_elements()[0] = b1[6]; c11.thread_elements()[1] = b1[7]; + d00.thread_elements()[0] = lo[0]; d00.thread_elements()[1] = lo[1]; + d01.thread_elements()[0] = lo[2]; d01.thread_elements()[1] = lo[3]; + d10.thread_elements()[0] = lo[4]; d10.thread_elements()[1] = lo[5]; + d11.thread_elements()[0] = lo[6]; d11.thread_elements()[1] = lo[7]; + e00.thread_elements()[0] = hi[0]; e00.thread_elements()[1] = hi[1]; + e01.thread_elements()[0] = hi[2]; e01.thread_elements()[1] = hi[3]; + e10.thread_elements()[0] = hi[4]; e10.thread_elements()[1] = hi[5]; + e11.thread_elements()[0] = hi[6]; e11.thread_elements()[1] = hi[7]; + simdgroup_multiply_accumulate(d00, a00, b00, d00); + simdgroup_multiply_accumulate(d01, a00, b01, d01); + simdgroup_multiply_accumulate(d10, a10, b00, d10); + simdgroup_multiply_accumulate(d11, a10, b01, d11); + simdgroup_multiply_accumulate(e00, a00, c00, e00); + simdgroup_multiply_accumulate(e01, a00, c01, e01); + simdgroup_multiply_accumulate(e10, a10, c00, e10); + simdgroup_multiply_accumulate(e11, a10, c01, e11); + simdgroup_multiply_accumulate(d00, a01, b10, d00); + simdgroup_multiply_accumulate(d01, a01, b11, d01); + simdgroup_multiply_accumulate(d10, a11, b10, d10); + simdgroup_multiply_accumulate(d11, a11, b11, d11); + simdgroup_multiply_accumulate(e00, a01, c10, e00); + simdgroup_multiply_accumulate(e01, a01, c11, e01); + simdgroup_multiply_accumulate(e10, a11, c10, e10); + simdgroup_multiply_accumulate(e11, a11, c11, e11); + lo[0] = d00.thread_elements()[0]; lo[1] = d00.thread_elements()[1]; + lo[2] = d01.thread_elements()[0]; lo[3] = d01.thread_elements()[1]; + lo[4] = d10.thread_elements()[0]; lo[5] = d10.thread_elements()[1]; + lo[6] = d11.thread_elements()[0]; lo[7] = d11.thread_elements()[1]; + hi[0] = e00.thread_elements()[0]; hi[1] = e00.thread_elements()[1]; + hi[2] = e01.thread_elements()[0]; hi[3] = e01.thread_elements()[1]; + hi[4] = e10.thread_elements()[0]; hi[5] = e10.thread_elements()[1]; + hi[6] = e11.thread_elements()[0]; hi[7] = e11.thread_elements()[1]; +#else using namespace mpp::tensor_ops; constexpr auto shape = matmul2d_descriptor(16, 32, 16, TA, TB, true, matmul2d_descriptor::mode::multiply_accumulate); matmul2d op; @@ -187,8 +244,43 @@ inline void mma_16x32(thread frag& lo, thread frag& hi, thread const frag< lo[e] = acc[j]; hi[e] = acc[j + 4]; } +#endif +} + +#ifdef TF_GLM_M3_FAST +// Half-width 16x16 multiply-accumulate used by GLM's decode index kernel when TF_GLM_M3_FAST is active. +template +inline void mma_16x16(thread frag& d, thread const frag& a, thread const frag& b) { + simdgroup_matrix a00, a01, a10, a11; + simdgroup_matrix b00, b01, b10, b11; + simdgroup_matrix d00, d01, d10, d11; + a00.thread_elements()[0] = a[0]; a00.thread_elements()[1] = a[1]; + a01.thread_elements()[0] = a[2]; a01.thread_elements()[1] = a[3]; + a10.thread_elements()[0] = a[4]; a10.thread_elements()[1] = a[5]; + a11.thread_elements()[0] = a[6]; a11.thread_elements()[1] = a[7]; + b00.thread_elements()[0] = b[0]; b00.thread_elements()[1] = b[1]; + b01.thread_elements()[0] = b[2]; b01.thread_elements()[1] = b[3]; + b10.thread_elements()[0] = b[4]; b10.thread_elements()[1] = b[5]; + b11.thread_elements()[0] = b[6]; b11.thread_elements()[1] = b[7]; + d00.thread_elements()[0] = d[0]; d00.thread_elements()[1] = d[1]; + d01.thread_elements()[0] = d[2]; d01.thread_elements()[1] = d[3]; + d10.thread_elements()[0] = d[4]; d10.thread_elements()[1] = d[5]; + d11.thread_elements()[0] = d[6]; d11.thread_elements()[1] = d[7]; + simdgroup_multiply_accumulate(d00, a00, b00, d00); + simdgroup_multiply_accumulate(d01, a00, b01, d01); + simdgroup_multiply_accumulate(d10, a10, b00, d10); + simdgroup_multiply_accumulate(d11, a10, b01, d11); + simdgroup_multiply_accumulate(d00, a01, b10, d00); + simdgroup_multiply_accumulate(d01, a01, b11, d01); + simdgroup_multiply_accumulate(d10, a11, b10, d10); + simdgroup_multiply_accumulate(d11, a11, b11, d11); + d[0] = d00.thread_elements()[0]; d[1] = d00.thread_elements()[1]; + d[2] = d01.thread_elements()[0]; d[3] = d01.thread_elements()[1]; + d[4] = d10.thread_elements()[0]; d[5] = d10.thread_elements()[1]; + d[6] = d11.thread_elements()[0]; d[7] = d11.thread_elements()[1]; } #endif +#endif // frag_get from a block whose rows home.y and home.y + 8 start at r0 and r1; an unflagged row reads as zero. template diff --git a/zig/src/core/affine_mm.zig b/zig/src/core/affine_mm.zig index 3630543d02b..df0ec0108db 100644 --- a/zig/src/core/affine_mm.zig +++ b/zig/src/core/affine_mm.zig @@ -14,6 +14,7 @@ pub const Format = struct { group: u16 = 64, out_f32: bool = false, glu: Glu = .clipped, + glm_m3_fast: bool = false, /// Scatter and GLU gathers read this batch's active-to-global expert map. mapped_experts: bool = false, }; @@ -29,10 +30,11 @@ pub fn source(device: mtl.Device, a: std.mem.Allocator, f: Format) ![]u8 { .clipped_silu => "#define TF_GLU_ROUND_SILU 1\n", .clipped => "", }; + const m3 = if (f.glm_m3_fast and !device.tensorUnits()) "#define TF_GLM_M3_FAST 1\n" else ""; const map = if (f.mapped_experts) "#define TF_AM_MAPPED_EXPERTS 1\n" else ""; const out = if (f.out_f32) "float" else "bfloat"; - const head = "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T {s}\n{s}{s}{s}"; - return std.fmt.allocPrint(a, head, .{ f.bits, f.group, out, glu, map, body }); + const head = "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T {s}\n{s}{s}{s}{s}"; + return std.fmt.allocPrint(a, head, .{ f.bits, f.group, out, glu, map, m3, body }); } /// Entry points: row sums, dense matmul, tiled and scattering gathers, ordered expert gate/up into SwiGLU. @@ -66,12 +68,22 @@ pub fn rowSumsAt(e: mtl.ComputeEncoder, p: Pipes, group: u32, x: anytype, sums: /// y = x W^T using group `sums`; x is [rows, q.k], y is [rows, n], n = q.n rounded up to 64 (padded weights). pub fn dense(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, y: anytype, rows: u32) void { + denseBm(e, p, x, sums, q, y, rows, 64); +} + +/// `dense` with an explicit row-tile height `bm` (32 when compiled with TF_GLM_M3_FAST, 64 otherwise). +pub fn denseBm(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, y: anytype, rows: u32, bm: u32) void { const n = std.mem.alignForward(u32, q.n, 64); - denseBatch(e, p, x, sums, q, y, rows, 1, .{ .x_row = @intCast(q.k), .y_row = @intCast(n) }); + denseBatchBm(e, p, x, sums, q, y, rows, 1, .{ .x_row = @intCast(q.k), .y_row = @intCast(n) }, bm); } /// `batch` dense products over per-batch weight rows with strides `s`; q.n is a multiple of 64 (e.g. heads). pub fn denseBatch(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, y: anytype, rows: u32, batch: u32, s: Strides) void { + denseBatchBm(e, p, x, sums, q, y, rows, batch, s, 64); +} + +/// `denseBatch` with an explicit row-tile height `bm` (32 when compiled with TF_GLM_M3_FAST, 64 otherwise). +pub fn denseBatchBm(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, y: anytype, rows: u32, batch: u32, s: Strides, bm: u32) void { const n = std.mem.alignForward(u32, q.n, 64); e.setPipeline(p[1]); bind(e, 0, x); @@ -82,7 +94,7 @@ pub fn denseBatch(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: e.setValue(Args{ .rows = @intCast(rows), .n = @intCast(n), .k = @intCast(q.k), .experts = 0 }, 5); bind(e, 6, y); e.setValue(s, 7); - e.dispatchGroups(mtl.Size.of(n / 64, (rows + 63) / 64, batch), mtl.Size.of(32, 2, 2)); + e.dispatchGroups(mtl.Size.of(n / 64, (rows + bm - 1) / bm, batch), mtl.Size.of(32, 2, 2)); } /// y [rows, q.n]: x times its row expert's W^T, rows expert-sorted (`offsets`: experts' first rows); q [experts, n, k]. diff --git a/zig/src/families/glm/checks.zig b/zig/src/families/glm/checks.zig index c2a5799a2c0..74f19290fbc 100644 --- a/zig/src/families/glm/checks.zig +++ b/zig/src/families/glm/checks.zig @@ -179,7 +179,7 @@ pub fn checkMatmul(e: *Engine, prompt: []const u32) !void { fwd.boundary(&x, b.enc, rows, false, L.hc.?[0], L.in_norm); fwd.qmv(&x, b.enc, e.k.qmv_kda_in, e.sc.normed, a.in_proj, out, rows); affine_mm.rowSums(b.enc, e.k.mm_bf16, 64, e.sc.normed, pr.sums, rows, a.in_proj.k); - affine_mm.dense(b.enc, e.k.mm_bf16, e.sc.normed, pr.sums, a.in_proj, pr.proj, rows); + affine_mm.denseBm(b.enc, e.k.mm_bf16, e.sc.normed, pr.sums, a.in_proj, pr.proj, rows, if (e.k.m3_fast) 32 else 64); try e.finish(b.cb, b.enc); const want: [*]const u16 = @ptrCast(@alignCast(out.addr())); const got: [*]const u16 = @ptrCast(@alignCast(pr.proj.addr())); diff --git a/zig/src/families/glm/forward.zig b/zig/src/families/glm/forward.zig index 105430e1dbf..dc9bc96670e 100644 --- a/zig/src/families/glm/forward.zig +++ b/zig/src/families/glm/forward.zig @@ -441,7 +441,8 @@ pub fn selectKeys(x: *const Ctx, e: mtl.ComputeEncoder, mi: usize, iq: Ref, q_st e.setPipeline(k.index_decode); // a row's heads as the tensor op's rows (glm_index_nax.metal) bind(e, 0, .{ iq, iw, x.s.mla[mi].pool, scores }); e.setValue(ScoreArgs{ .p0 = p0, .q_stride = q_stride, .w_stride = c.i_heads, .s_stride = s_stride, .rows = n }, 4); - e.dispatchGroups(size((most + 127) / 128, n, 1), size(128, 1, 1)); + const blk_step: u32 = if (k.m3_fast) 64 else 128; + e.dispatchGroups(size((most + blk_step - 1) / blk_step, n, 1), size(128, 1, 1)); const sel = SelectArgs{ .p0 = p0, .top = c.i_topk / c.kpool, .width = c.keyWidth(), .s_stride = s_stride, .i_stride = c.keyWidth() }; if (most > select_cap and most <= select_marks) { // between them glm_index_select's one group a row is quicker e.setPipeline(k.index_select); diff --git a/zig/src/families/glm/kernels.zig b/zig/src/families/glm/kernels.zig index 5497de4d8f0..4e801dd0c72 100644 --- a/zig/src/families/glm/kernels.zig +++ b/zig/src/families/glm/kernels.zig @@ -120,6 +120,7 @@ pub const Kernels = struct { mm_groups: mm_groups.Pipes, // the routed gathers walked in column groups (mm_groups.zig): mm_bf16's bits mm_f32: affine_mm.Pipes, // and with fp32 out: expert parallel by rows' down partials wide: ?wide.Pipes = null, // the products at other widths (wide.zig), for a checkpoint that has one + m3_fast: bool, // pre-M5 Metal dispatch geometry (32x64 affine_mm, 4-sg KDA scan, 32x64/64 index NAX) pub fn deinit(k: *Kernels) void { const info = @typeInfo(Kernels).@"struct"; @@ -279,6 +280,8 @@ pub fn visitSources(gpa: std.mem.Allocator, device: mtl.Device, visitor: anytype fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: anytype) !void { k.wide = null; + const m3_fast = !device.tensorUnits(); + k.m3_fast = m3_fast; var jobs: [generated.len + 27]Job = undefined; inline for (generated, 0..) |g, i| { const src = comptime kernelOf(g.key); @@ -317,12 +320,13 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an jobs[generated.len + 6] = .{ .device = device, .source = igate_src, .names = &.{ moe_route.names[0], "glm_route_logits_one" }, .out = &igate_out }; const m16_src = try mm_groups.source(device, gpa); // affine_mm.names, then the column-group gathers defer gpa.free(m16_src); - const m32_src = try affine_mm.source(device, gpa, .{ .out_f32 = true }); + const m32_src = try affine_mm.source(device, gpa, .{ .out_f32 = true, .glm_m3_fast = m3_fast }); defer gpa.free(m32_src); var m16_out: [m16_names.len]mtl.Pipeline = undefined; jobs[generated.len + 7] = .{ .device = device, .source = m16_src, .names = &m16_names, .out = &m16_out }; jobs[generated.len + 8] = .{ .device = device, .source = m32_src, .names = &affine_mm.names, .out = &k.mm_f32 }; - const kda_src = try std.mem.concat(gpa, u8, &.{ comptime kernelOf("kda_rows").source, sources.glm_kda_prompt, sources.glm_kda_window, sources.glm_kda_parts }); + const m3_def = if (m3_fast) "#define TF_GLM_M3_FAST 1\n" else ""; + const kda_src = try std.mem.concat(gpa, u8, &.{ comptime kernelOf("kda_rows").source, m3_def, sources.glm_kda_prompt, sources.glm_kda_window, sources.glm_kda_parts }); defer gpa.free(kda_src); var kda_out: [10]mtl.Pipeline = undefined; jobs[generated.len + 9] = .{ .device = device, .source = kda_src, .names = &.{ "glm_kda_prep", "glm_kda_scan", "glm_kda_post", "glm_kda_prep_tp", "glm_kda_scan_tp", "glm_kda_post_tp", "glm_kda_window", "glm_kda_window_tp", "glm_kda_parts", "glm_kda_norm" }, .out = &kda_out }; @@ -347,7 +351,9 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an const absorb_tp_src = try frags.source(device, gpa, absorb_tp_raw); defer gpa.free(absorb_tp_src); jobs[generated.len + 14] = .{ .device = device, .source = absorb_tp_src, .names = &.{"glm_absorb_nax"}, .out = @as(*[1]mtl.Pipeline, &k.absorb_nax_tp) }; - const index_src = try frags.source(device, gpa, sources.glm_index_nax); + const index_raw = try std.mem.concat(gpa, u8, &.{ m3_def, sources.glm_index_nax }); + defer gpa.free(index_raw); + const index_src = try frags.source(device, gpa, index_raw); defer gpa.free(index_src); var index_out: [2]mtl.Pipeline = undefined; jobs[generated.len + 15] = .{ .device = device, .source = index_src, .names = &.{ "glm_index_scores_nax", "glm_index_decode" }, .out = &index_out }; diff --git a/zig/src/families/glm/prompt.zig b/zig/src/families/glm/prompt.zig index c5444c56219..953e3c7ae8f 100644 --- a/zig/src/families/glm/prompt.zig +++ b/zig/src/families/glm/prompt.zig @@ -201,7 +201,7 @@ fn qmm(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, q: wts.Affine, y: Ref, M /// affine_mm's dense product at one batch: deep ones in column groups (mm_groups.zig, the same bits). fn denseOf(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, q: wts.Affine, y: Ref, M: u32, s: affine_mm.Strides) void { if (q.k >= mm_groups.dense_from) return mm_groups.dense(e, p.mm.mm_groups, x, p.sums, q, y, M, s); - affine_mm.denseBatch(e, p.mm.mm_bf16, x, p.sums, q, y, M, 1, s); + affine_mm.denseBatchBm(e, p.mm.mm_bf16, x, p.sums, q, y, M, 1, s, if (p.mm.m3_fast) 32 else 64); } /// `qmm` over x's rows `ld` elements apart (a slice of a wider row). @@ -221,7 +221,7 @@ fn qmmAt(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, ld: u32, q: wts.Affine /// `qmm` with fp32 out (TP2: one Mac's partial of a row-split projection). fn qmmF32(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, q: wts.Affine, y: Ref, M: u32) void { affine_mm.rowSums(e, p.mm.mm_bf16, 64, x, p.sums, M, q.k); - affine_mm.dense(e, p.mm.mm_f32, x, p.sums, q, y, M); + affine_mm.denseBm(e, p.mm.mm_f32, x, p.sums, q, y, M, if (p.mm.m3_fast) 32 else 64); } /// Routed experts' gate, up and SwiGLU into `act` ([n, gate.n]); `groups`: 4/64 in column groups (the same bits). @@ -397,7 +397,7 @@ fn kdaChunk(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, ki: usiz e.setPipeline(if (tp) k.kda_scan_tp else k.kda_scan); bind(e, 0, .{ q, kk, v, g, beta, L.st[if (r0 == 0) cur else 1 - cur], L.st[1 - cur], sy }); e.setValue(@as(i32, @intCast(m)), 8); - e.dispatchGroups(size(c.kda_dim / 64, H, 1), size(512, 1, 1)); + if (x.k.m3_fast) e.dispatchGroups(size(c.kda_dim / 16, H, 1), size(128, 1, 1)) else e.dispatchGroups(size(c.kda_dim / 64, H, 1), size(512, 1, 1)); } if (!fwd.on(x, "kda_post")) continue; e.setPipeline(if (tp) k.kda_post_tp else k.kda_post); @@ -406,7 +406,7 @@ fn kdaChunk(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, ki: usiz bind(e, 4, .{ p.y.at(@as(usize, r0) * W * 2), p.proj }); fwd.shape(e, 6, .{ M, pitch }); // every block writes the next chunk's conv window, the same rows bind(e, 7, .{ L.cs[cur], L.cs[1 - cur] }); - e.dispatchGroups(size(m, H, 1), size(32, 1, 1)); + if (x.k.m3_fast) e.dispatchGroups(size(m, H / 4, 1), size(128, 1, 1)) else e.dispatchGroups(size(m, H, 1), size(32, 1, 1)); } } @@ -431,7 +431,8 @@ fn unabsorb(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, w: *cons q.b = q.b.at(@as(usize, c.nope) * (K / 64) * 2); q.n = c.v_dim; affine_mm.rowSums(e, p.mm.mm_bf16, 64, p.att, p.sums, M * H, K); - affine_mm.denseBatch(e, p.mm.mm_bf16, p.att, p.sums, q, p.vals, M, H, .{ .x_row = @intCast(H * K), .y_row = @intCast(H * c.v_dim), .sums_row = @intCast(H), .x_batch = @intCast(K), .y_batch = @intCast(c.v_dim), .sums_batch = 1, .w_batch = @intCast(per) }); + const bs: affine_mm.Strides = .{ .x_row = @intCast(H * K), .y_row = @intCast(H * c.v_dim), .sums_row = @intCast(H), .x_batch = @intCast(K), .y_batch = @intCast(c.v_dim), .sums_batch = 1, .w_batch = @intCast(per) }; + affine_mm.denseBatchBm(e, p.mm.mm_bf16, p.att, p.sums, q, p.vals, M, H, bs, if (p.mm.m3_fast) 32 else 64); } /// The index scores' tile rows: 128 (a row's queries read once for 64 blocks), 64 where that leaves the GPU half idle. @@ -447,7 +448,7 @@ fn selectKeys(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, mi: us e.setPipeline(x.k.index_scores_nax); bind(e, 0, .{ iq, iw, x.s.mla[mi].pool, p.sscore }); e.setValue([5]u32{ p0, c.qrProj(), c.i_heads, s_stride, n }, 4); - const rows = scoreRows(most, n); + const rows = if (x.k.m3_fast) 32 else scoreRows(most, n); e.dispatchGroups(size((most + 63) / 64, (n + rows - 1) / rows, 1), size(2 * rows, 1, 1)); e.setPipeline(x.k.index_select); bind(e, 0, .{ p.sscore, indices }); diff --git a/zig/src/families/glm/wide.zig b/zig/src/families/glm/wide.zig index 52cc962efd4..b7cd74dbeb4 100644 --- a/zig/src/families/glm/wide.zig +++ b/zig/src/families/glm/wide.zig @@ -45,6 +45,7 @@ pub const Pipes = struct { mm6: affine_mm.Pipes, zeros: mtl.Buffer, // expert ids all 0: a dense GLU through the by-ids kernel (the shared expert) hash: u64, // every source compiled here + mm_bm: u32, // affine_mm dense row-tile height: 32 pre-M5 (TF_GLM_M3_FAST), 64 on M5 pub fn deinit(p: *Pipes) void { inline for (.{ @@ -188,11 +189,12 @@ fn build(gpa: std.mem.Allocator, device: mtl.Device, kda: []const u8, made: *Mad h.update(sources.ops_embed_norm); try lib(made, device, sources.ops_embed_norm, &.{ "tf_embed_b6_g64", "tf_embed_b8_g64" }, &p.embed); for ([_]u8{ 8, 2, 5, 6 }, [_]*affine_mm.Pipes{ &p.mm8, &p.mm2, &p.mm5, &p.mm6 }) |bits, out| { - const src = try affine_mm.source(device, gpa, .{ .bits = bits, .group = 64 }); + const src = try affine_mm.source(device, gpa, .{ .bits = bits, .group = 64, .glm_m3_fast = !device.tensorUnits() }); defer gpa.free(src); h.update(src); try lib(made, device, src, &affine_mm.names, out); } + p.mm_bm = if (device.tensorUnits()) 64 else 32; p.zeros = try device.buffer(64 * 4, mtl.ResourceOptions.shared); @memset(p.zeros.slice(i32, 64), 0); p.hash = h.final(); @@ -263,7 +265,7 @@ pub fn headsBatch(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, h: u32, io: var head = q; head.n = ny; affine_mm.rowSumsAt(e, pipes, 64, io.in, sums, io.rows, h * kx, io.ldx); // a head's sums one row apart - affine_mm.denseBatch(e, pipes, io.in, sums, head, io.out, io.rows, h, .{ + affine_mm.denseBatchBm(e, pipes, io.in, sums, head, io.out, io.rows, h, .{ .x_row = @intCast(io.ldx), .y_row = @intCast(io.ldo), .sums_row = @intCast(h), @@ -271,7 +273,7 @@ pub fn headsBatch(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, h: u32, io: .y_batch = @intCast(ny), .sums_batch = 1, .w_batch = @intCast(ny), - }); + }, p.mm_bm); } /// x [rows, k] through bf16 W [n, k]: scalar path, kept for tests / non-prefill callers (decode-side eh uses mtp.zig). @@ -470,17 +472,8 @@ pub fn denseMm(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, io: Io, sums: }; if (!summed) affine_mm.rowSumsAt(e, pipes, 64, io.in, sums, io.rows, q.k, io.ldx); // every member's: one k, g64 summed = true; - affine_mm.denseBatch( - e, - pipes, - io.in, - sums, - one, - part.out, - io.rows, - 1, - .{ .x_row = @intCast(io.ldx), .y_row = @intCast(io.ldo) }, - ); + const strides: affine_mm.Strides = .{ .x_row = @intCast(io.ldx), .y_row = @intCast(io.ldo) }; + affine_mm.denseBatchBm(e, pipes, io.in, sums, one, part.out, io.rows, 1, strides, p.mm_bm); } } diff --git a/zig/tests/contract/metal_affine.zig b/zig/tests/contract/metal_affine.zig index 8359fa44fa9..de0fb725818 100644 --- a/zig/tests/contract/metal_affine.zig +++ b/zig/tests/contract/metal_affine.zig @@ -17,7 +17,7 @@ const lane = tf.lane_projection; pub const Kind = enum { row, affine_mm, simd, simd_half, simd_sums, simd_bits, lane, lane_reg }; /// One variant: kernel, code width and group, output, lane K slices; control: simd_half's or simd_sums' planted fault. -pub const Variant = struct { kind: Kind, bits: u8 = 4, group: usize = 64, f32_out: bool = false, sk: usize = 1, coop: bool = false, control: bool = false, served: ?[]const c.Shape = null, inline_sums: bool = false }; +pub const Variant = struct { kind: Kind, bits: u8 = 4, group: usize = 64, f32_out: bool = false, sk: usize = 1, coop: bool = false, glm_m3_fast: bool = false, control: bool = false, served: ?[]const c.Shape = null, inline_sums: bool = false }; pub const Reg = struct { v: Variant, name: []const u8 }; /// The half-operand tiles, the chunk pairs on the prepass's sums, and their planted controls, beside simd_qmm's entry. pub const half = [_]Reg{ @@ -65,7 +65,7 @@ pub fn spec(v: Variant, name: []const u8) c.Spec { const step: usize = @max(16, v.group); return switch (v.kind) { .row => .{ .name = name, .accum = .f32, .depth = rowDepth, .out = out, .tiles = .{ .{ .size = 2 }, .{ .size = 8, .step = 8, .min = 8 }, .{ .size = 512, .step = step, .min = step } }, .served = &.{ .{ .rows = 16, .n = 2688, .k = 4096 }, .{ .rows = 3, .n = 4608, .k = 2688 } } }, - .affine_mm => .{ .name = name, .accum = .f32, .depth = groupDepth64, .out = out, .known = if (v.bits == 4) offset_inf else null, .tiles = .{ .{ .size = 64 }, .{ .size = 64, .step = 64, .min = 64 }, .{ .size = 128, .step = 64, .min = 64 } }, .served = if (v.bits == 8 and v.group == 64) &router_rows else &.{ .{ .rows = 128, .n = 2048, .k = 4096 }, .{ .rows = 65, .n = 1024, .k = 1024 } } }, + .affine_mm => .{ .name = name, .accum = .f32, .depth = groupDepth64, .out = out, .known = if (v.bits == 4) offset_inf else null, .tiles = .{ .{ .size = 64 }, .{ .size = 64, .step = 64, .min = 64 }, .{ .size = 128, .step = @max(64, v.group), .min = @max(64, v.group) } }, .served = if (v.bits == 8 and v.group == 64) &router_rows else &.{ .{ .rows = 128, .n = 2048, .k = 4096 }, .{ .rows = 65, .n = 1024, .k = 1024 } } }, .simd, .simd_bits => .{ .name = name, .accum = .f32, .depth = simdDepth, .out = out, .tiles = .{ .{ .size = 8 }, .{ .size = 32, .step = 8, .min = 8 }, .{ .size = 512, .step = 64, .min = 64 } }, .served = &.{ .{ .rows = 16, .n = 2688, .k = 4096 }, .{ .rows = 9, .n = 6400, .k = 256 } } }, // the 27B's norm-fed widths past 6,144 (8 chunks), as the prompt chunk's tiles and its 9-row tail take them .simd_half => .{ .name = name, .accum = .f32, .depth = simdDepth, .out = out, .replaces = "simd_qmm's fp32 tiles", .tiles = .{ .{ .size = 8 }, .{ .size = 32, .step = 8, .min = 8 }, .{ .size = 512, .step = 64, .min = 64 } }, .served = &.{ .{ .rows = 32, .n = 6240, .k = 512 }, .{ .rows = 9, .n = 12288, .k = 256 } } }, @@ -112,7 +112,7 @@ pub const Proj = struct { .simd, .simd_half, .simd_sums => p.sq_p = try sq.Pipelines.load(device), .simd_bits => p.sqb_p = try sqb.Pipelines.load(device), .affine_mm => { - const src = try mm.source(device, a, .{ .bits = v.bits, .group = @intCast(v.group), .out_f32 = v.f32_out }); + const src = try mm.source(device, a, .{ .bits = v.bits, .group = @intCast(v.group), .out_f32 = v.f32_out, .glm_m3_fast = v.glm_m3_fast }); defer a.free(src); const lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); defer lib.deinit(); @@ -272,7 +272,8 @@ pub const Proj = struct { const xs = .{ .buf = p.sums.buf, .off = p.sums.off }; const q = .{ .w = .{ .buf = p.w.buf, .off = p.w.off }, .s = .{ .buf = p.s.buf, .off = p.s.off }, .b = .{ .buf = p.b.buf, .off = p.b.off }, .n = @as(u32, @intCast(shape.n)), .k = @as(u32, @intCast(shape.k)) }; mm.rowSums(e, p.mm_p.?, @intCast(p.v.group), x, xs, @intCast(shape.rows), @intCast(shape.k)); - mm.dense(e, p.mm_p.?, x, xs, q, .{ .buf = p.out.buf, .off = p.out.off }, @intCast(shape.rows)); + const bm: u32 = if (p.v.glm_m3_fast and p.v.control) 128 else if (p.v.glm_m3_fast and !p.rig.device.tensorUnits()) 32 else 64; + mm.denseBm(e, p.mm_p.?, x, xs, q, .{ .buf = p.out.buf, .off = p.out.off }, @intCast(shape.rows), bm); }, .lane, .lane_reg => try p.lane_p.?.encode(e, ref(p.x), ref(p.w), ref(p.s), ref(p.out), @intCast(shape.rows)), } diff --git a/zig/tests/contract/metal_affine_gather.zig b/zig/tests/contract/metal_affine_gather.zig index f977d501910..d3c52abe424 100644 --- a/zig/tests/contract/metal_affine_gather.zig +++ b/zig/tests/contract/metal_affine_gather.zig @@ -34,15 +34,18 @@ pub const Mutation = enum { }; /// One registered gather: the weights' bits (groups of 64), whether each output goes back to its row's own place. -pub const Variant = struct { bits: u8, scatter: bool, mutation: Mutation = .none }; +pub const Variant = struct { bits: u8, scatter: bool, glm_m3_fast: bool = false, mutation: Mutation = .none }; -/// The widths qwen27 admits for its routed experts on tensor units, each plain and scattering, and three controls. +/// The widths qwen27 admits for its routed experts on tensor units, each plain and scattering, and controls. pub const registered = [_]Variant{ .{ .bits = 4, .scatter = false }, .{ .bits = 4, .scatter = true }, .{ .bits = 8, .scatter = false }, .{ .bits = 8, .scatter = true }, + .{ .bits = 4, .scatter = false, .glm_m3_fast = true }, + .{ .bits = 8, .scatter = true, .glm_m3_fast = true }, .{ .bits = 4, .scatter = false, .mutation = .tail }, + .{ .bits = 4, .scatter = false, .glm_m3_fast = true, .mutation = .tail }, .{ .bits = 8, .scatter = false, .mutation = .expert }, .{ .bits = 4, .scatter = true, .mutation = .scatter }, }; @@ -50,10 +53,10 @@ pub const registered = [_]Variant{ pub fn name(v: Variant) []const u8 { return switch (v.mutation) { .none => switch (v.bits) { - 4 => if (v.scatter) "metal affine_mm q4 g64 gather scatter" else "metal affine_mm q4 g64 gather", - else => if (v.scatter) "metal affine_mm q8 g64 gather scatter" else "metal affine_mm q8 g64 gather", + 4 => if (v.glm_m3_fast) (if (v.scatter) "metal affine_mm glm m3 q4 g64 gather scatter" else "metal affine_mm glm m3 q4 g64 gather") else if (v.scatter) "metal affine_mm q4 g64 gather scatter" else "metal affine_mm q4 g64 gather", + else => if (v.glm_m3_fast) (if (v.scatter) "metal affine_mm glm m3 q8 g64 gather scatter" else "metal affine_mm glm m3 q8 g64 gather") else if (v.scatter) "metal affine_mm q8 g64 gather scatter" else "metal affine_mm q8 g64 gather", }, - .tail => "control: metal affine_mm gather q4 g64, each expert's last row dropped", + .tail => if (v.glm_m3_fast) "control: metal affine_mm glm m3 gather q4 g64, each expert's last row dropped" else "control: metal affine_mm gather q4 g64, each expert's last row dropped", .expert => "control: metal affine_mm gather q8 g64, a tile reads its neighbour expert's weights", .scatter => "control: metal affine_mm gather scatter q4 g64, outputs left in sorted order", }; @@ -93,7 +96,7 @@ pub const Gather = struct { out: rig_.Ref = undefined, pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant) !Gather { - const plain = try mm.source(device, a, .{ .bits = v.bits, .group = 64 }); + const plain = try mm.source(device, a, .{ .bits = v.bits, .group = 64, .glm_m3_fast = v.glm_m3_fast }); defer a.free(plain); const src = if (v.mutation == .none) try a.dupe(u8, plain) else blk: { const e = v.mutation.edit(); diff --git a/zig/tests/contract/metal_glm_prompt.zig b/zig/tests/contract/metal_glm_prompt.zig new file mode 100644 index 00000000000..3577db06182 --- /dev/null +++ b/zig/tests/contract/metal_glm_prompt.zig @@ -0,0 +1,565 @@ +//! GLM-5.3-Flash M3 prompt index and KDA contracts: byte-exact against unvectorized baseline, plus planted controls. +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 c = contract.spec; +const g = contract.gates; +const hi: usize = 32; +const di: usize = 128; +const d_kda: usize = 128; +const taps: usize = 4; + +const ScoreArgs = extern struct { p0: u32, q_stride: u32, w_stride: u32, s_stride: u32, rows: u32 }; + +fn bfVal(x: f32) u16 { + return c.toBf16(x); +} + +fn fillBf(dst: []u16, rng: std.Random, scale: f32) void { + for (dst) |*v| v.* = bfVal((rng.float(f32) * 2 - 1) * scale); +} + +fn fillF32(dst: []f32, rng: std.Random, lo: f32, hi_v: f32) void { + for (dst) |*v| v.* = lo + rng.float(f32) * (hi_v - lo); +} + +fn packRefs(a: std.mem.Allocator, rig: *const rig_.Rig, refs: []const rig_.Ref, lens: []const usize, out: *std.ArrayList(u8)) ![]const u8 { + out.clearRetainingCapacity(); + for (refs, lens) |r, len| try out.appendSlice(a, rig.bytes(r, len)); + return out.items; +} + +fn allocOutputSet(rig: *rig_.Rig, lens: []const usize, refs: []rig_.Ref, bases: []rig_.Ref) !void { + for (lens, 0..) |len, i| { + refs[i] = try rig.output(len); + bases[i] = try rig.scratch(len); + @memset(rig.bytes(bases[i], len), 0xff); + } +} + +pub const IndexKind = enum { scores, decode }; + +pub const Index = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + kind: IndexKind, + control: bool, + name: []const u8, + pipe: mtl.Pipeline, + base_pipe: mtl.Pipeline, + rows: usize = 0, + p0: usize = 0, + most: usize = 0, + s_stride: usize = 0, + refs: [3]rig_.Ref = undefined, + out: rig_.Ref = undefined, + base: rig_.Ref = undefined, + bytes: std.ArrayList(u8) = .empty, + base_bytes: std.ArrayList(u8) = .empty, + + fn depth(s: c.Shape) usize { + _ = s; + return 0; + } + + pub fn spec(kind: IndexKind, control: bool, name: []const u8) c.Spec { + const served: []const c.Shape = switch (kind) { + .scores => &.{ .{ .rows = 1, .n = di, .k = 16 }, .{ .rows = 33, .n = di, .k = 128 }, .{ .rows = 65, .n = di, .k = 260 } }, + .decode => &.{ .{ .rows = 1, .n = di, .k = 16 }, .{ .rows = 4, .n = di, .k = 516 }, .{ .rows = 16, .n = di, .k = 1028 } }, + }; + const tiles: [3]c.Tile = switch (kind) { + .scores => .{ .{ .size = 32, .step = 1, .min = 1 }, .{ .size = di, .step = di, .min = di }, .{ .size = 256, .step = 4, .min = 16 } }, + .decode => .{ .{ .size = 4, .step = 1, .min = 1 }, .{ .size = di, .step = di, .min = di }, .{ .size = 256, .step = 4, .min = 16 } }, + }; + return .{ + .name = name, + .accum = .none, + .depth = depth, + .out = .f32, + .replaces = if (control) null else "unvectorized M3 glm_index_nax kernel", + .nan = .{ .stated = "every output bit matches the unvectorized baseline, non-finite inputs included" }, + .tiles = tiles, + .served = served, + .sums = .{ .why = "bit-preserving layout optimization; arithmetic and accumulation order match the baseline" }, + }; + } + + const vt = blk: { + var v = g.hooks(Index); + v.output = output; + v.intact = intact; + v.check = checkNonfinite; + break :blk v; + }; + + pub fn kernel(self: *Index) g.Kernel { + return .{ .spec = spec(self.kind, self.control, self.name), .ctx = self, .vt = &vt, .control = if (self.control) .shapes else null }; + } + + pub fn deinit(self: *Index) void { + self.rig.deinit(); + self.bytes.deinit(self.a); + self.base_bytes.deinit(self.a); + } + + pub fn prepare(self: *Index, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + if (shape.rows == 0 or shape.n != di or shape.k + shape.rows < 4) return false; + self.rows = shape.rows; + self.p0 = shape.k; + self.most = (self.p0 + self.rows) / 4; + const q_stride = hi * di + 64; + const w_stride = hi + 16; + self.s_stride = self.most + 5; + const iq = try self.a.alloc(u16, self.rows * q_stride); + defer self.a.free(iq); + const iw = try self.a.alloc(u16, self.rows * w_stride); + defer self.a.free(iw); + const pool = try self.a.alloc(u16, self.most * di); + defer self.a.free(pool); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + fillBf(iq, rng, 1.5); + fillBf(iw, rng, 1.5); + fillBf(pool, rng, 1.5); + if (fill == .nonfinite) { + iq[0] = bfVal(std.math.nan(f32)); + iq[di + 3] = bfVal(std.math.inf(f32)); + iq[2 * di + 7] = bfVal(-std.math.inf(f32)); + iw[1] = bfVal(std.math.inf(f32)); + pool[0] = bfVal(std.math.nan(f32)); + pool[(self.most - 1) * di + 5] = bfVal(-std.math.inf(f32)); + } + self.refs[0] = try self.rig.input(std.mem.sliceAsBytes(iq)); + self.refs[1] = try self.rig.input(std.mem.sliceAsBytes(iw)); + self.refs[2] = try self.rig.input(std.mem.sliceAsBytes(pool)); + self.out = try self.rig.output(self.rows * self.s_stride * 4); + self.base = try self.rig.scratch(self.rows * self.s_stride * 4); + @memset(self.rig.bytes(self.base, self.rows * self.s_stride * 4), 0xff); + return true; + } + + fn encode(self: *const Index, e: mtl.ComputeEncoder, pipe: mtl.Pipeline, out_ref: rig_.Ref, rm: u32, bs: u32) void { + const q_stride: u32 = hi * di + 64; + const w_stride: u32 = hi + 16; + const n: u32 = @intCast(self.rows); + const most: u32 = @intCast(self.most); + e.setPipeline(pipe); + e.setBuffer(self.refs[0].buf, self.refs[0].off, 0); + e.setBuffer(self.refs[1].buf, self.refs[1].off, 1); + e.setBuffer(self.refs[2].buf, self.refs[2].off, 2); + e.setBuffer(out_ref.buf, out_ref.off, 3); + const args = ScoreArgs{ .p0 = @intCast(self.p0), .q_stride = q_stride, .w_stride = w_stride, .s_stride = @intCast(self.s_stride), .rows = n }; + e.setBytes(std.mem.asBytes(&args), 4); + const gx = if (self.kind == .scores) (most + 63) / 64 else (most + bs - 1) / bs; + const gy = if (self.kind == .scores) (n + rm - 1) / rm else n; + e.dispatchGroups(mtl.Size.of(gx, gy, 1), mtl.Size.of(128, 1, 1)); + } + + pub fn run(self: *Index) !void { + const p = self.rig.begin(); + const m3 = !self.rig.device.tensorUnits(); + const rm: u32 = if (self.control) (if (m3) 64 else 128) else if (m3) 32 else 64; + const bs: u32 = if (self.control) (if (m3) 128 else 256) else if (m3) 64 else 128; + self.encode(p.e, self.pipe, self.out, rm, bs); + try self.rig.finish(p); + } + + fn writtenCount(self: *const Index) usize { + var total: usize = 0; + for (0..self.rows) |r| total += (self.p0 + r + 1) / 4; + return total; + } + + pub fn count(self: *Index) usize { + return self.writtenCount(); + } + + fn pack(self: *const Index, from: rig_.Ref, dst: *std.ArrayList(u8)) ![]const u8 { + dst.clearRetainingCapacity(); + const raw = self.rig.bytes(from, self.rows * self.s_stride * 4); + for (0..self.rows) |r| { + const b = (self.p0 + r + 1) / 4; + try dst.appendSlice(self.a, raw[r * self.s_stride * 4 ..][0 .. b * 4]); + } + return dst.items; + } + + fn intact(ctx: *anyopaque) !bool { + const self: *Index = @ptrCast(@alignCast(ctx)); + if (!try self.rig.intact()) return false; + const raw = self.rig.bytes(self.out, self.rows * self.s_stride * 4); + for (0..self.rows) |r| { + const b = (self.p0 + r + 1) / 4; + for (raw[(r * self.s_stride + b) * 4 .. (r + 1) * self.s_stride * 4]) |byte| if (byte != 0xff) return false; + } + return true; + } + + fn output(ctx: *anyopaque) ![]const u8 { + const self: *Index = @ptrCast(@alignCast(ctx)); + if (!try intact(self)) return error.WroteOutsideOutputs; + return self.pack(self.out, &self.bytes); + } + + pub fn replaced(self: *Index) ![]const u8 { + const p = self.rig.begin(); + self.encode(p.e, self.base_pipe, self.base, 64, 128); + try self.rig.finish(p); + return self.pack(self.base, &self.base_bytes); + } + + fn checkNonfinite(ctx: *anyopaque, gate: g.Gate) !?[]const u8 { + const self: *Index = @ptrCast(@alignCast(ctx)); + const want = try self.replaced(); + const got = try output(self); + if (!std.mem.eql(u8, got, want)) { + return if (gate == .nonfinite) "index outputs differ from baseline on nonfinite inputs" else "index outputs differ from baseline"; + } + return null; + } + + pub fn reference(_: *Index, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } +}; + +pub const KdaKind = enum { prep, scan, post }; + +pub const Kda = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + kind: KdaKind, + heads: u32, + control: bool, + name: []const u8, + pipe: mtl.Pipeline, + base_pipe: mtl.Pipeline, + rows: usize = 0, + r0: usize = 0, + in_refs: [8]rig_.Ref = undefined, + out_refs: [5]rig_.Ref = undefined, + base_refs: [5]rig_.Ref = undefined, + out_lens: [5]usize = undefined, + n_outs: usize = 0, + bytes: std.ArrayList(u8) = .empty, + base_bytes: std.ArrayList(u8) = .empty, + + fn depth(s: c.Shape) usize { + _ = s; + return 0; + } + + fn kdaServed(comptime w: usize, kind: KdaKind) []const c.Shape { + return switch (kind) { + .prep => &.{ .{ .rows = 1, .n = w, .k = 0 }, .{ .rows = 5, .n = w, .k = 4 }, .{ .rows = 16, .n = w, .k = 0 } }, + .scan => &.{ .{ .rows = 1, .n = w, .k = d_kda }, .{ .rows = 24, .n = w, .k = d_kda }, .{ .rows = 25, .n = w, .k = d_kda } }, + .post => &.{ .{ .rows = 1, .n = w, .k = 0 }, .{ .rows = 2, .n = w, .k = 0 }, .{ .rows = 5, .n = w, .k = 0 } }, + }; + } + + pub fn spec(kind: KdaKind, heads: u32, control: bool, name: []const u8) c.Spec { + const w: usize = @as(usize, heads) * d_kda; + const served = if (heads == 32) kdaServed(32 * d_kda, kind) else kdaServed(64 * d_kda, kind); + const tiles: [3]c.Tile = switch (kind) { + .prep => .{ .{ .size = 8, .step = 1, .min = 1 }, .{ .size = w, .step = w, .min = w }, .{ .size = 4, .step = 4, .min = 0 } }, + .scan => .{ .{ .size = 24, .step = 1, .min = 1 }, .{ .size = w, .step = w, .min = w }, .{ .size = d_kda, .step = d_kda, .min = d_kda } }, + .post => .{ .{ .size = 4, .step = 1, .min = 1 }, .{ .size = w, .step = w, .min = w }, .{} }, + }; + return .{ + .name = name, + .accum = .none, + .depth = depth, + .out = .raw, + .replaces = if (control) null else "unvectorized M3 glm_kda_prompt kernel", + .nan = .{ .stated = "every output bit matches the unvectorized baseline, non-finite inputs included" }, + .tiles = tiles, + .served = served, + .sums = .{ .why = "bit-preserving layout optimization; arithmetic and recurrence order match the baseline" }, + }; + } + + const vt = blk: { + var v = g.hooks(Kda); + v.output = output; + v.check = checkNonfinite; + break :blk v; + }; + + pub fn kernel(self: *Kda) g.Kernel { + return .{ .spec = spec(self.kind, self.heads, self.control, self.name), .ctx = self, .vt = &vt, .control = if (self.control) .shapes else null }; + } + + pub fn deinit(self: *Kda) void { + self.rig.deinit(); + self.bytes.deinit(self.a); + self.base_bytes.deinit(self.a); + } + + fn allocBfIn(self: *Kda, len: usize, rng: std.Random, scale: f32, idx: usize, nf: bool) !void { + const buf = try self.a.alloc(u16, len); + defer self.a.free(buf); + fillBf(buf, rng, scale); + if (nf and len > 0) buf[0] = bfVal(std.math.nan(f32)); + if (nf and len > 4) buf[4] = bfVal(std.math.inf(f32)); + if (nf and len > 9) buf[9] = bfVal(-std.math.inf(f32)); + self.in_refs[idx] = try self.rig.input(std.mem.sliceAsBytes(buf)); + } + + fn allocF32In(self: *Kda, len: usize, rng: std.Random, lo: f32, hi_v: f32, idx: usize, nf: bool) !void { + const buf = try self.a.alloc(f32, len); + defer self.a.free(buf); + fillF32(buf, rng, lo, hi_v); + if (nf and len > 0) buf[0] = std.math.inf(f32); + if (nf and len > 3) buf[3] = std.math.nan(f32); + self.in_refs[idx] = try self.rig.input(std.mem.sliceAsBytes(buf)); + } + + pub fn prepare(self: *Kda, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + const w: usize = @as(usize, self.heads) * d_kda; + if (shape.rows == 0 or shape.n != w) return false; + self.rows = shape.rows; + self.r0 = if (self.kind == .prep) shape.k else 0; + const c3 = 3 * w; + const ps = c3 + 2 * d_kda + self.heads; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const nf = fill == .nonfinite; + switch (self.kind) { + .prep => { + try self.allocBfIn((self.r0 + self.rows) * ps, rng, 0.5, 0, nf); + try self.allocBfIn((taps - 1) * c3, rng, 0.5, 1, nf); + try self.allocF32In(taps * c3, rng, -0.5, 0.5, 2, false); + try self.allocBfIn(self.rows * w, rng, 0.5, 3, nf); + try self.allocF32In(self.heads, rng, -1.5, -0.2, 4, nf); + try self.allocF32In(w, rng, -0.5, 0.5, 5, false); + self.out_lens[0..5].* = .{ self.rows * w * 2, self.rows * w * 2, self.rows * w * 2, self.rows * w * 4, self.rows * self.heads * 4 }; + self.n_outs = 5; + }, + .scan => { + for (0..3) |i| try self.allocBfIn(self.rows * w, rng, 0.4, i, nf); + try self.allocF32In(self.rows * w, rng, 0.5, 1.0, 3, nf); + try self.allocF32In(self.rows * self.heads, rng, 0.1, 0.9, 4, nf); + try self.allocF32In(@as(usize, self.heads) * d_kda * d_kda, rng, -0.5, 0.5, 5, nf); + self.out_lens[0..2].* = .{ @as(usize, self.heads) * d_kda * d_kda * 4, self.rows * w * 2 }; + self.n_outs = 2; + }, + .post => { + try self.allocBfIn(self.rows * w, rng, 0.8, 0, nf); + try self.allocBfIn(self.rows * w, rng, 0.8, 1, nf); + try self.allocF32In(d_kda, rng, 0.5, 1.5, 2, nf); + try self.allocBfIn(self.rows * ps, rng, 0.5, 3, nf); + try self.allocBfIn((taps - 1) * c3, rng, 0.5, 4, nf); + self.out_lens[0..2].* = .{ self.rows * w * 2, (taps - 1) * c3 * 2 }; + self.n_outs = 2; + }, + } + try allocOutputSet(&self.rig, self.out_lens[0..self.n_outs], self.out_refs[0..self.n_outs], self.base_refs[0..self.n_outs]); + return true; + } + + fn encode(self: *const Kda, e: mtl.ComputeEncoder, pipe: mtl.Pipeline, outs: []const rig_.Ref, m3: bool, ctrl: bool) void { + const w: usize = @as(usize, self.heads) * d_kda; + const ps: i32 = @intCast(3 * w + 2 * d_kda + self.heads); + e.setPipeline(pipe); + switch (self.kind) { + .prep => { + const shape = [3]i32{ @intCast(self.rows), ps, @intCast(self.r0) }; + const lb: f32 = -1.0; + e.setBuffer(self.in_refs[0].buf, self.in_refs[0].off, 0); + e.setBytes(std.mem.asBytes(&shape), 1); + for (self.in_refs[1..6], 2..) |r, idx| e.setBuffer(r.buf, r.off, idx); + e.setBytes(std.mem.asBytes(&lb), 7); + for (outs[0..5], 8..) |r, idx| e.setBuffer(r.buf, r.off, idx); + const gy: usize = if (ctrl) self.heads / 8 else self.heads / 4; + e.dispatchGroups(mtl.Size.of(self.rows, gy, 1), mtl.Size.of(128, 1, 1)); + }, + .scan => { + const r_val: i32 = @intCast(self.rows); + for (self.in_refs[0..6], 0..) |r, idx| e.setBuffer(r.buf, r.off, idx); + e.setBuffer(outs[0].buf, outs[0].off, 6); + e.setBuffer(outs[1].buf, outs[1].off, 7); + e.setBytes(std.mem.asBytes(&r_val), 8); + const sg_cols: usize = if (m3) 16 else 64; + const th: usize = if (m3) 128 else 512; + const gx = if (ctrl) (d_kda / sg_cols) / 2 else d_kda / sg_cols; + e.dispatchGroups(mtl.Size.of(gx, self.heads, 1), mtl.Size.of(th, 1, 1)); + }, + .post => { + const shape = [2]i32{ @intCast(self.rows), ps }; + const eps: f32 = 1e-5; + for (self.in_refs[0..3], 0..) |r, idx| e.setBuffer(r.buf, r.off, idx); + e.setBytes(std.mem.asBytes(&eps), 3); + e.setBuffer(outs[0].buf, outs[0].off, 4); + e.setBuffer(self.in_refs[3].buf, self.in_refs[3].off, 5); + e.setBytes(std.mem.asBytes(&shape), 6); + e.setBuffer(self.in_refs[4].buf, self.in_refs[4].off, 7); + e.setBuffer(outs[1].buf, outs[1].off, 8); + const hb: usize = if (m3) 4 else 1; + const th: usize = if (m3) 128 else 32; + const gy = if (ctrl) (self.heads / hb) / 2 else self.heads / hb; + e.dispatchGroups(mtl.Size.of(self.rows, gy, 1), mtl.Size.of(th, 1, 1)); + }, + } + } + + pub fn run(self: *Kda) !void { + const p = self.rig.begin(); + const m3 = !self.rig.device.tensorUnits(); + self.encode(p.e, self.pipe, self.out_refs[0..self.n_outs], m3, self.control); + try self.rig.finish(p); + } + + pub fn count(self: *Kda) usize { + var total: usize = 0; + for (self.out_lens[0..self.n_outs]) |len| total += len; + return total; + } + + fn output(ctx: *anyopaque) ![]const u8 { + const self: *Kda = @ptrCast(@alignCast(ctx)); + return packRefs(self.a, &self.rig, self.out_refs[0..self.n_outs], self.out_lens[0..self.n_outs], &self.bytes); + } + + pub fn replaced(self: *Kda) ![]const u8 { + const p = self.rig.begin(); + self.encode(p.e, self.base_pipe, self.base_refs[0..self.n_outs], false, false); + try self.rig.finish(p); + return packRefs(self.a, &self.rig, self.base_refs[0..self.n_outs], self.out_lens[0..self.n_outs], &self.base_bytes); + } + + fn checkNonfinite(ctx: *anyopaque, gate: g.Gate) !?[]const u8 { + const self: *Kda = @ptrCast(@alignCast(ctx)); + const want = try self.replaced(); + const got = try output(self); + if (!std.mem.eql(u8, got, want)) { + return if (gate == .nonfinite) "kda outputs differ from baseline on nonfinite inputs" else "kda outputs differ from baseline"; + } + return null; + } + + pub fn reference(_: *Kda, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } +}; + +fn wanted(only: ?[]const u8, name: []const u8) bool { + const text = only orelse return true; + return std.mem.indexOf(u8, name, text) != null; +} + +const kda_specs = [_]struct { kind: KdaKind, heads: u32, fn_name: []const u8, control: bool, name: []const u8 }{ + .{ .kind = .prep, .heads = 64, .fn_name = "glm_kda_prep", .control = false, .name = "metal glm m3 kda_prep" }, + .{ .kind = .prep, .heads = 64, .fn_name = "glm_kda_prep", .control = true, .name = "control: metal glm m3 kda_prep, wrong head tile grid" }, + .{ .kind = .scan, .heads = 64, .fn_name = "glm_kda_scan", .control = false, .name = "metal glm m3 kda_scan" }, + .{ .kind = .scan, .heads = 64, .fn_name = "glm_kda_scan", .control = true, .name = "control: metal glm m3 kda_scan, half value-column grid" }, + .{ .kind = .scan, .heads = 32, .fn_name = "glm_kda_scan_tp", .control = false, .name = "metal glm m3 kda_scan_tp" }, + .{ .kind = .post, .heads = 64, .fn_name = "glm_kda_post", .control = false, .name = "metal glm m3 kda_post" }, + .{ .kind = .post, .heads = 64, .fn_name = "glm_kda_post", .control = true, .name = "control: metal glm m3 kda_post, wrong head tile grid" }, +}; + +const index_specs = [_]struct { kind: IndexKind, fn_name: []const u8, control: bool, name: []const u8 }{ + .{ .kind = .scores, .fn_name = "glm_index_scores_nax", .control = false, .name = "metal glm m3 index_scores_nax" }, + .{ .kind = .scores, .fn_name = "glm_index_scores_nax", .control = true, .name = "control: metal glm m3 index_scores_nax, wrong row tile height" }, + .{ .kind = .decode, .fn_name = "glm_index_decode", .control = false, .name = "metal glm m3 index_decode" }, + .{ .kind = .decode, .fn_name = "glm_index_decode", .control = true, .name = "control: metal glm m3 index_decode, wrong block tile width" }, +}; + +pub const Suite = struct { + a: std.mem.Allocator, + pipes: std.ArrayList(mtl.Pipeline) = .empty, + indices: [index_specs.len]Index = undefined, + index_made: usize = 0, + kdas: [kda_specs.len]Kda = undefined, + kda_made: usize = 0, + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, out: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { + const s = try a.create(Suite); + s.* = .{ .a = a }; + errdefer s.destroy(); + var need_idx = false; + for (index_specs) |e| if (wanted(only, e.name)) { + need_idx = true; + }; + var need_kda = false; + for (kda_specs) |e| if (wanted(only, e.name)) { + need_kda = true; + }; + const m3_def = if (!device.tensorUnits()) "#define TF_GLM_M3_FAST 1\n" else ""; + if (need_idx) { + const idx_raw = try std.mem.concat(a, u8, &.{ m3_def, sources.glm_index_nax }); + defer a.free(idx_raw); + const idx_src = try tf.frags.source(device, a, idx_raw); + defer a.free(idx_src); + const idx_base_src = try tf.frags.source(device, a, sources.glm_index_nax); + defer a.free(idx_base_src); + const idx_lib = try mtl.Library.fromSource(device, idx_src, mtl.CompileOptions.mlx()); + defer idx_lib.deinit(); + const base_lib = try mtl.Library.fromSource(device, idx_base_src, mtl.CompileOptions.mlx()); + defer base_lib.deinit(); + for (index_specs) |e| { + if (!wanted(only, e.name)) continue; + const pipe = try mtl.Pipeline.init(device, idx_lib, e.fn_name, false); + try s.pipes.append(a, pipe); + const base_pipe = try mtl.Pipeline.init(device, base_lib, e.fn_name, false); + try s.pipes.append(a, base_pipe); + s.indices[s.index_made] = .{ + .a = a, + .rig = .{ .a = a, .device = device, .queue = queue }, + .kind = e.kind, + .control = e.control, + .name = e.name, + .pipe = pipe, + .base_pipe = base_pipe, + }; + try out.append(a, s.indices[s.index_made].kernel()); + s.index_made += 1; + } + } + if (need_kda) { + const kda_prefix = comptime tf.glm.kernels.generatedSource("kda_rows"); + const kda_src = try std.mem.concat(a, u8, &.{ kda_prefix, m3_def, sources.glm_kda_prompt }); + defer a.free(kda_src); + const kda_base_src = kda_prefix ++ sources.glm_kda_prompt; + const kda_lib = try mtl.Library.fromSource(device, kda_src, mtl.CompileOptions.mlx()); + defer kda_lib.deinit(); + const base_lib = try mtl.Library.fromSource(device, kda_base_src, mtl.CompileOptions.mlx()); + defer base_lib.deinit(); + for (kda_specs) |e| { + if (!wanted(only, e.name)) continue; + const pipe = try mtl.Pipeline.init(device, kda_lib, e.fn_name, false); + try s.pipes.append(a, pipe); + const base_pipe = try mtl.Pipeline.init(device, base_lib, e.fn_name, false); + try s.pipes.append(a, base_pipe); + s.kdas[s.kda_made] = .{ + .a = a, + .rig = .{ .a = a, .device = device, .queue = queue }, + .kind = e.kind, + .heads = e.heads, + .control = e.control, + .name = e.name, + .pipe = pipe, + .base_pipe = base_pipe, + }; + try out.append(a, s.kdas[s.kda_made].kernel()); + s.kda_made += 1; + } + } + return s; + } + + pub fn destroy(s: *Suite) void { + for (s.indices[0..s.index_made]) |*it| it.deinit(); + for (s.kdas[0..s.kda_made]) |*it| it.deinit(); + for (s.pipes.items) |p| p.deinit(); + s.pipes.deinit(s.a); + s.a.destroy(s); + } +}; diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 5d4fc8929eb..790b720bb0f 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -372,11 +372,18 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp text = sources.core_simd_qmm; } else if (has(d.name, "affine_mm")) { if (!assemble) return undefined; - const bits: u8 = if (has(d.name, "q8")) 8 else 4; - const group: u16 = if (has(d.name, "g32")) 32 else 64; - head = try std.fmt.allocPrint(a, "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T bfloat\n", .{ bits, group }); - text = sources.core_affine_mm; - frags = true; + const bits: u8 = if (has(d.name, "q8")) 8 else if (has(d.name, "q6")) 6 else if (has(d.name, "q5")) 5 else if (has(d.name, "q2")) 2 else 4; + const group: u16 = if (has(d.name, "g128")) 128 else if (has(d.name, "g32")) 32 else 64; + const out_t: []const u8 = if (has(d.name, "fp32")) "float" else "bfloat"; + const m3_head: []const u8 = if (has(d.name, "glm m3")) "#define TF_GLM_M3_FAST 1\n" else ""; + head = try std.fmt.allocPrint(a, "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T {s}\n", .{ bits, group, out_t }); + const pre_head = if (m3_head.len == 0) head else try std.mem.concat(a, u8, &.{ head, m3_head }); + const pre = try preM5(a, pre_head, sources.core_affine_mm); + const here = if (device.tensorUnits()) blk: { + const body = try tf.frags.source(device, a, sources.core_affine_mm); + break :blk try std.mem.concat(a, u8, &.{ head, body }); + } else pre; + return .{ .decl = d, .function = fun, .here = here, .pre_m5 = pre }; } else if (has(d.name, "lane projection")) { if (!assemble) return undefined; const sk: usize = if (has(d.name, "sk4")) 4 else 1; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index f5b61da3f2d..e30cb244cc4 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -69,6 +69,15 @@ const common = [_]Reg{ .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .f32_out = true }, .name = "metal affine_mm q4 g64 fp32 out" }, .{ .v = .{ .kind = .affine_mm, .bits = 8, .group = 32 }, .name = "metal affine_mm q8 g32" }, .{ .v = .{ .kind = .affine_mm, .bits = 8, .group = 64 }, .name = "metal affine_mm q8 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .f32_out = true, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g64 fp32 out" }, + .{ .v = .{ .kind = .affine_mm, .bits = 2, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q2 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 5, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q5 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 6, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q6 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 8, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q8 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 32, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g32" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 128, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g128" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .glm_m3_fast = true, .control = true }, .name = "control: metal affine_mm glm m3 q4 g64, wrong row tile height" }, .{ .v = .{ .kind = .simd, .bits = 4, .group = 64 }, .name = "metal simd_qmm q4 g64" }, .{ .v = .{ .kind = .simd_bits, .bits = 3, .group = 64 }, .name = "metal simd_qmm_bits q3 g64" }, .{ .v = .{ .kind = .simd_bits, .bits = 6, .group = 64 }, .name = "metal simd_qmm_bits q6 g64" }, @@ -377,14 +386,15 @@ pub fn main(init: std.process.Init) !u8 { } gathers.deinit(a); } - if (tensor) for (gather_k.registered) |v| { + for (gather_k.registered) |v| { + if (!tensor and !v.glm_m3_fast) continue; if (!wanted(o, gather_k.name(v))) continue; const p = try a.create(gather_k.Gather); errdefer a.destroy(p); p.* = try gather_k.Gather.init(a, device, queue, v); try gathers.append(a, p); try kernels.append(a, p.kernel()); - }; + } var h3_list: std.ArrayList(*h3_k.H3) = .empty; defer for (h3_list.items) |x| x.deinit(); var qwen3_heads: @import("metal_qwen3_heads.zig").Suite = .{}; @@ -572,6 +582,8 @@ pub fn main(init: std.process.Init) !u8 { defer idol_decoder.destroy(); const idol_vae = try @import("metal_idol_vae.zig").Suite.create(a, device, queue, &kernels, o.only); defer idol_vae.destroy(); + const glm_prompt = try @import("metal_glm_prompt.zig").Suite.create(a, device, queue, &kernels, o.only); + defer glm_prompt.destroy(); var t: g.Tally = .{}; const t0 = std.Io.Clock.awake.now(init.io); if (o.gates) { diff --git a/zig/tests/glm_rows_batch.zig b/zig/tests/glm_rows_batch.zig index d7e0de77358..eb63df441c1 100644 --- a/zig/tests/glm_rows_batch.zig +++ b/zig/tests/glm_rows_batch.zig @@ -64,7 +64,7 @@ pub fn headsCheck(g: *const Gpu, mm: affine_mm.Pipes, bits: u8, n: usize, k: usi bs[3].slice(u16, m * k)[i * k ..][0..k], bs[0].slice(u16, m * ldx)[i * ldx + h * k ..][0..k], ); - try g.run(mmDense, .{ mm, w.part(h, nh), ref(bs[3]), ref(bs[1]), ref(bs[4]), @as(u32, m) }); + try g.run(mmDense, .{ mm, g.p.mm_bm, w.part(h, nh), ref(bs[3]), ref(bs[1]), ref(bs[4]), @as(u32, m) }); for (0..m) |i| try eql(all[(i * nh + h) * n ..][0..n], bs[4].slice(u16, m * n)[i * n ..][0..n]); t.pairs += m * n; } @@ -117,7 +117,7 @@ pub fn splitMmCheck(g: *const Gpu, k: usize, ns: []const usize, bits: []const u8 for (ms[0..ns.len], 0..) |x, i| { const run = q.run(i); if (wide.mm(&g.p, x.q) != null and run.n % 64 == 0) { - try g.run(mmDense, .{ wide.mm(&g.p, x.q).?, x.q, ref(bs[0]), ref(bs[1]), ref(bs[3]), @as(u32, m) }); + try g.run(mmDense, .{ wide.mm(&g.p, x.q).?, g.p.mm_bm, x.q, ref(bs[0]), ref(bs[1]), ref(bs[3]), @as(u32, m) }); on_mm += 1; } else try g.run( dense, diff --git a/zig/tests/glm_rows_check.zig b/zig/tests/glm_rows_check.zig index fefe0d2c2cd..1cc09572bd3 100644 --- a/zig/tests/glm_rows_check.zig +++ b/zig/tests/glm_rows_check.zig @@ -310,6 +310,7 @@ fn partsCheck(g: *const Gpu, m: Mat, up: Mat, t: *Tally) !void { pub fn mmDense( e: mtl.ComputeEncoder, mm: affine_mm.Pipes, + bm: u32, q: affine.Affine, x: Ref, sums: Ref, @@ -317,7 +318,7 @@ pub fn mmDense( n_rows: u32, ) void { affine_mm.rowSums(e, mm, 64, x, sums, n_rows, q.k); - affine_mm.dense(e, mm, x, sums, q, y, n_rows); + affine_mm.denseBm(e, mm, x, sums, q, y, n_rows, bm); } /// dims: x rows, sorted pairs, experts, picks a row. @@ -365,7 +366,8 @@ fn gatherCheck(g: *const Gpu, m: Mat, up: Mat, t: *Tally) !void { upq.n = @intCast(r); // every expert's gate and up, dense on every x row: [2][parts][rows, r] for (0..parts) |e| for ([2]Mat{ m, up }, 0..) |w, j| { - try g.run(mmDense, .{ mm, w.part(e, parts), ref(m.x()), sums, ref(bs[1]).at(((j * parts + e) * rows * r) * 2), @as(u32, rows) }); + const y_at = ref(bs[1]).at(((j * parts + e) * rows * r) * 2); + try g.run(mmDense, .{ mm, g.p.mm_bm, w.part(e, parts), ref(m.x()), sums, y_at, @as(u32, rows) }); }; const dg = bs[1].slice(u16, 2 * parts * rows * r); const gu = bs[2].slice(u16, slots * 2 * r); @@ -384,7 +386,10 @@ fn gatherCheck(g: *const Gpu, m: Mat, up: Mat, t: *Tally) !void { for (order, 0..) |o, i| @memcpy(xs[i * k ..][0..k], m.x().slice(u16, rows * k)[@as(usize, @intCast(o)) * k ..][0..k]); const y = bs[5].slice(u16, (parts + 1) * slots * r); try g.run(mmDown, .{ mm, gate, ref(bs[4]), sums, sorted, ref(bs[5]), @as(u32, slots), @as(u32, parts) }); - for (0..parts) |e| try g.run(mmDense, .{ mm, m.part(e, parts), ref(bs[4]), sums, ref(bs[5]).at((1 + e) * slots * r * 2), @as(u32, slots) }); + for (0..parts) |e| { + const y_at = ref(bs[5]).at((1 + e) * slots * r * 2); + try g.run(mmDense, .{ mm, g.p.mm_bm, m.part(e, parts), ref(bs[4]), sums, y_at, @as(u32, slots) }); + } for (order, 0..) |o, i| { const e: usize = @intCast(picks[@intCast(o)]); try eql(y[@as(usize, @intCast(o)) * r ..][0..r], y[((1 + e) * slots + i) * r ..][0..r]); diff --git a/zig/tests/glm_rows_classes.zig b/zig/tests/glm_rows_classes.zig index 4b9f99d4f6e..978ea2eed01 100644 --- a/zig/tests/glm_rows_classes.zig +++ b/zig/tests/glm_rows_classes.zig @@ -123,11 +123,11 @@ fn rowsLaunch(e: mtl.ComputeEncoder, p: *const wide.Pipes, q: affine.Affine, x: wide.dense(p, e, q, .{ .in = (affine.Ref{ .buf = x }).at(at), .ldx = q.k, .out = .{ .buf = out }, .ldo = q.n, .rows = m }); } -fn mmLaunch(e: mtl.ComputeEncoder, mm: affine_mm.Pipes, q: affine.Affine, x: mtl.Buffer, sums: mtl.Buffer, out: mtl.Buffer, m: u32) void { +fn mmLaunch(e: mtl.ComputeEncoder, mm: affine_mm.Pipes, bm: u32, q: affine.Affine, x: mtl.Buffer, sums: mtl.Buffer, out: mtl.Buffer, m: u32) void { const xr: affine.Ref = .{ .buf = x }; const sr: affine.Ref = .{ .buf = sums }; affine_mm.rowSums(e, mm, 64, xr, sr, m, q.k); - affine_mm.dense(e, mm, xr, sr, q, affine.Ref{ .buf = out }, m); + affine_mm.denseBm(e, mm, xr, sr, q, affine.Ref{ .buf = out }, m, bm); } /// Each class at its widths (g64): decode rows (alone == windowed) and the prompt's product vs fp64, every column. @@ -167,7 +167,7 @@ pub fn check(p: *const wide.Pipes, device: mtl.Device, queue: mtl.Queue) !Tally // prompt: the chunk's product at rows 0 and 32; on the row kernels every row's bits equal the decode's const mm: ?affine_mm.Pipes = wide.mm(p, q); // prompt.zig's (2: the routed experts' gathers) const on_mm = mm != null; - if (mm) |pipes| try submit(queue, mmLaunch, .{ pipes, q, bufs[3], bufs[6], bufs[5], prompt_rows }) else try submit(queue, rowsLaunch, .{ p, q, bufs[3], 0, bufs[5], prompt_rows }); + if (mm) |pipes| try submit(queue, mmLaunch, .{ pipes, p.mm_bm, q, bufs[3], bufs[6], bufs[5], prompt_rows }) else try submit(queue, rowsLaunch, .{ p, q, bufs[3], 0, bufs[5], prompt_rows }); t.worst = 0; const pitch = if (on_mm) np else n; for ([_]usize{ 0, prompt_rows - 1 }) |i| try against(q, w, s, b, x, bufs[5].slice(u16, prompt_rows * pitch), pitch, i, &t, 1); diff --git a/zig/tests/glm_rows_speed_prompt.zig b/zig/tests/glm_rows_speed_prompt.zig index 0aab170c6ec..55cab5c132f 100644 --- a/zig/tests/glm_rows_speed_prompt.zig +++ b/zig/tests/glm_rows_speed_prompt.zig @@ -25,11 +25,11 @@ fn headsRows(e: mtl.ComputeEncoder, i: usize, p: *const wide.Pipes, pool: Pool, wide.perHead(p, e, q, H, .{ .in = rf(io.x), .ldx = ldx, .out = rf(io.y), .ldo = q.n, .rows = PM }, kx, q.n / H); } /// The same as one affine_mm batch (prompt.zig headsMm). -fn headsMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, pool: Pool, io: Io, ldx: u32, kx: u32) void { +fn headsMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, bm: u32, pool: Pool, io: Io, ldx: u32, kx: u32) void { var head = pool.at(i); head.n /= H; tf.affine_mm.rowSumsAt(e, mm, 64, rf(io.x), rf(io.z), PM, H * kx, ldx); - tf.affine_mm.denseBatch(e, mm, rf(io.x), rf(io.z), head, rf(io.y), PM, H, .{ + tf.affine_mm.denseBatchBm(e, mm, rf(io.x), rf(io.z), head, rf(io.y), PM, H, .{ .x_row = @intCast(ldx), .y_row = @intCast(H * head.n), .sums_row = H, @@ -37,7 +37,7 @@ fn headsMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, pool: Pool, .y_batch = @intCast(head.n), .sums_batch = 1, .w_batch = @intCast(head.n), - }); + }, bm); } fn ehRows(e: mtl.ComputeEncoder, i: usize, p: *const wide.Pipes, eh: mtl.Buffer, io: Io) void { _ = i; @@ -49,10 +49,10 @@ fn chunkRows(e: mtl.ComputeEncoder, i: usize, p: *const wide.Pipes, pool: Pool, const q = pool.at(i); wide.dense(p, e, q, .{ .in = rf(io.x), .ldx = q.k, .out = rf(io.y), .ldo = q.n, .rows = PM }); } -fn chunkMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, pool: Pool, io: Io) void { +fn chunkMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, bm: u32, pool: Pool, io: Io) void { const q = pool.at(i); tf.affine_mm.rowSums(e, mm, 64, rf(io.x), rf(io.z), PM, q.k); - tf.affine_mm.dense(e, mm, rf(io.x), rf(io.z), q, rf(io.y), PM); + tf.affine_mm.denseBm(e, mm, rf(io.x), rf(io.z), q, rf(io.y), PM, bm); } /// A prompt chunk's products where oQ's paths differ from uniform's, ms a chunk of 2048 rows. @@ -64,13 +64,13 @@ pub fn prompt(b: *Bench, k: *const kernels.Kernels, p: *const wide.Pipes) !void defer eq.deinit(); std.debug.print(" embed_q q8 per-head rows {d:8.2} affine_mm batch {d:8.2} (x11 a chunk)\n", .{ try b.time(headsRows, .{ p, eq, b.io, @as(u32, QR), @as(u32, 256) }) / 1e3, - try b.time(headsMm, .{ p.mm8, eq, b.io, @as(u32, QR), @as(u32, 256) }) / 1e3, + try b.time(headsMm, .{ p.mm8, p.mm_bm, eq, b.io, @as(u32, QR), @as(u32, 256) }) / 1e3, }); const uo = try Pool.init(b.device, H * 256, 512, 8, 1, 2); defer uo.deinit(); std.debug.print(" unembed_out q8 per-head rows {d:8.2} affine_mm batch {d:8.2} (x11 a chunk)\n", .{ try b.time(headsRows, .{ p, uo, b.io, @as(u32, H * 512), @as(u32, 512) }) / 1e3, - try b.time(headsMm, .{ p.mm8, uo, b.io, @as(u32, H * 512), @as(u32, 512) }) / 1e3, + try b.time(headsMm, .{ p.mm8, p.mm_bm, uo, b.io, @as(u32, H * 512), @as(u32, 512) }) / 1e3, }); { // the MTP head's bf16 eh_proj [4096, 8192] over the chunk (prompt.zig mtp) const eh = try buf(b.device, D * 2 * D * 2); @@ -86,12 +86,13 @@ pub fn prompt(b: *Bench, k: *const kernels.Kernels, p: *const wide.Pipes) !void defer m8.deinit(); const m4 = try Pool.init(b.device, s[0], s[1], 4, 1, 2); defer m4.deinit(); - const t8 = try b.time(chunkMm, .{ p.mm8, m8, b.io }); - const t4 = try b.time(chunkMm, .{ k.mm_bf16, m4, b.io }); + const t8 = try b.time(chunkMm, .{ p.mm8, p.mm_bm, m8, b.io }); + const k_bm: u32 = if (k.m3_fast) 32 else 64; + const t4 = try b.time(chunkMm, .{ k.mm_bf16, k_bm, m4, b.io }); for ([_]u8{ 5, 6 }) |bits| { const m = try Pool.init(b.device, s[0], s[1], bits, 1, 2); defer m.deinit(); - const on_mm = if (wide.mm(p, m.at(0))) |mm| try b.time(chunkMm, .{ mm, m, b.io }) else 0; + const on_mm = if (wide.mm(p, m.at(0))) |mm| try b.time(chunkMm, .{ mm, p.mm_bm, m, b.io }) else 0; std.debug.print( " [{d}, {d}] q{d} rows {d:8.2} affine_mm {d:8.2} (affine_mm q8 {d:.2}, q4 {d:.2})\n", .{ s[0], s[1], bits, try b.time(chunkRows, .{ p, m, b.io }) / 1e3, on_mm / 1e3, t8 / 1e3, t4 / 1e3 }, From 246dda603c388d12e2b252595c5ee05b01bd93cb Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:30:50 +0000 Subject: [PATCH 005/265] glm metal: follow main column-group library split for pre-M5 affine kernels --- zig/src/families/glm/forward.zig | 3 +-- zig/src/families/glm/kernels.zig | 19 ++++++++++++------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/zig/src/families/glm/forward.zig b/zig/src/families/glm/forward.zig index dc9bc96670e..ff367f519e6 100644 --- a/zig/src/families/glm/forward.zig +++ b/zig/src/families/glm/forward.zig @@ -441,8 +441,7 @@ pub fn selectKeys(x: *const Ctx, e: mtl.ComputeEncoder, mi: usize, iq: Ref, q_st e.setPipeline(k.index_decode); // a row's heads as the tensor op's rows (glm_index_nax.metal) bind(e, 0, .{ iq, iw, x.s.mla[mi].pool, scores }); e.setValue(ScoreArgs{ .p0 = p0, .q_stride = q_stride, .w_stride = c.i_heads, .s_stride = s_stride, .rows = n }, 4); - const blk_step: u32 = if (k.m3_fast) 64 else 128; - e.dispatchGroups(size((most + blk_step - 1) / blk_step, n, 1), size(128, 1, 1)); + e.dispatchGroups(size(std.math.divCeil(u32, most, if (k.m3_fast) 64 else 128) catch unreachable, n, 1), size(128, 1, 1)); const sel = SelectArgs{ .p0 = p0, .top = c.i_topk / c.kpool, .width = c.keyWidth(), .s_stride = s_stride, .i_stride = c.keyWidth() }; if (most > select_cap and most <= select_marks) { // between them glm_index_select's one group a row is quicker e.setPipeline(k.index_select); diff --git a/zig/src/families/glm/kernels.zig b/zig/src/families/glm/kernels.zig index 4e801dd0c72..0d8915d684e 100644 --- a/zig/src/families/glm/kernels.zig +++ b/zig/src/families/glm/kernels.zig @@ -282,7 +282,7 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an k.wide = null; const m3_fast = !device.tensorUnits(); k.m3_fast = m3_fast; - var jobs: [generated.len + 27]Job = undefined; + var jobs: [generated.len + 28]Job = undefined; inline for (generated, 0..) |g, i| { const src = comptime kernelOf(g.key); const FT = @FieldType(Kernels, g.field); @@ -393,12 +393,17 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an const softmax_rows_src = comptime sources.ops_softmax ++ sources.glm_softmax_rows; jobs[generated.len + 24] = .{ .device = device, .source = softmax_rows_src, .names = &.{"glm_softmax_rows"}, .out = @as(*[1]mtl.Pipeline, &k.softmax_rows) }; + const m3_src = if (m3_fast) try affine_mm.source(device, gpa, .{ .glm_m3_fast = true }) else try gpa.dupe(u8, ""); + defer gpa.free(m3_src); + var m3_out: affine_mm.Pipes = undefined; + if (m3_fast) jobs[generated.len + 27] = .{ .device = device, .source = m3_src, .names = &affine_mm.names, .out = &m3_out }; + const all = jobs[0 .. jobs.len - @intFromBool(!m3_fast)]; if (comptime @TypeOf(visitor) != void) { - for (jobs) |j| try visitor.raw("glm", j.names[0], j.source); + for (all) |j| try visitor.raw("glm", j.names[0], j.source); return; } var sources_seen = std.hash.Wyhash.init(0x6b); - for (jobs) |j| sources_seen.update(j.source); + for (all) |j| sources_seen.update(j.source); k.source_hash = sources_seen.final(); var next = std.atomic.Value(usize).init(0); const Worker = struct { @@ -411,17 +416,17 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an } }; var threads: [8]?std.Thread = @splat(null); - for (&threads) |*t| t.* = std.Thread.spawn(.{}, Worker.run, .{ &jobs, &next }) catch null; - Worker.run(&jobs, &next); + for (&threads) |*t| t.* = std.Thread.spawn(.{}, Worker.run, .{ all, &next }) catch null; + Worker.run(all, &next); for (threads) |t| if (t) |th| th.join(); - for (jobs) |j| if (j.failed) return error.KernelCompile; + for (all) |j| if (j.failed) return error.KernelCompile; inline for (glue, 0..) |g, i| @field(k, g.field) = glue_out[i]; k.sample = sample_out[0]; // the shared sampler's own library: glm_glue's table never named it k.latent_scores = attn_out[0]; k.latent_values = attn_out[1]; k.latent_scores_rows = attn_out[2]; k.latent_values_rows = attn_out[3]; - k.mm_bf16 = m16_out[0..affine_mm.names.len].*; + k.mm_bf16 = if (m3_fast) m3_out else m16_out[0..affine_mm.names.len].*; k.mm_groups = m16_out[affine_mm.names.len..].*; k.route_logits = route_out[0]; k.route_select = route_out[1]; From e7e3edab12e2596d738f86eb253c638c7d39e5a8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:34:09 +0000 Subject: [PATCH 006/265] glm metal: follow main score tile sizing and affine source growth --- zig/kernels/metal/core/affine_mm.metal | 77 ---------------------- zig/kernels/metal/core/affine_mm_glu.metal | 77 ++++++++++++++++++++++ zig/kernels/metal/sources.zig | 2 +- zig/src/families/glm/kernels.zig | 12 ++-- zig/src/families/glm/prompt.zig | 2 +- 5 files changed, 85 insertions(+), 85 deletions(-) create mode 100644 zig/kernels/metal/core/affine_mm_glu.metal diff --git a/zig/kernels/metal/core/affine_mm.metal b/zig/kernels/metal/core/affine_mm.metal index a6d07acb0a9..2f138603938 100644 --- a/zig/kernels/metal/core/affine_mm.metal +++ b/zig/kernels/metal/core/affine_mm.metal @@ -532,80 +532,3 @@ TF_GATHER(64) } TF_GATHER_SCATTER(32) TF_GATHER_SCATTER(64) - -#ifdef TF_GLU_PLAIN -// mlx-lm's compiled SwiGLU on bf16 rows (LFM2): silu(g) * u, rounded to bf16 at each step; `limit` unused. -inline bfloat am_swiglu(float g, float u, float limit) { - const float gt = float(bfloat(g)); - const bfloat s = static_cast(1.0f / (1.0f + metal::precise::exp(-gt))); - const bfloat silu = static_cast(gt * float(s)); - return static_cast(float(silu) * float(bfloat(u))); -} -#else -// The glue's SwiGLU in bf16 (glm_act2): MLX's bf16 exp and abs, nn.silu's x*sigmoid(x), gate and up clipped at `limit`. -inline bfloat am_sigmoid(bfloat x) { - const bfloat e = bfloat(__metal_exp(float(bfloat(__metal_fabs(float(x), __METAL_MAYBE_FAST_MATH__))), __METAL_MAYBE_FAST_MATH__)); - const bfloat y = bfloat(1) / (bfloat(1) + e); - return (x < 0) ? y : (bfloat(1) - y); -} - -inline bfloat am_swiglu(float g, float u, float limit) { - const float lim = float(bfloat(limit)); - const bfloat gt = bfloat(metal::min(float(bfloat(g)), lim)); - const bfloat up = bfloat(metal::min(metal::max(float(bfloat(u)), -lim), lim)); -#ifdef TF_GLU_ROUND_SILU - const bfloat sl = bfloat(precise::divide(float(gt), 1.0f + precise::exp(-float(gt)))); -#else - const bfloat sl = gt * am_sigmoid(gt); -#endif - return sl * up; -} -#endif - -// A simdgroup's gate (j 0) and up (j 1) fragments as SwiGLU outputs into y (ld N), rows below live only. -template -inline void am_store_glu(thread const frag (&acc)[TM][2], device bfloat* y, int N, int live, short2 home, - float limit) { - TF_UNROLL - for (short i = 0; i < TM; i++) { - TF_UNROLL - for (short e = 0; e < 8; e++) { - const int r = 16 * i + home.y + (e >> 2) * 8; - if (r < live) y[long(r) * N + home.x + TF_COL(e)] = am_swiglu(acc[i][0][e], acc[i][1][e], limit); - } - } -} - -// The routed experts' gate and up over ORDER's token rows (pair / topk), SwiGLU'd to act [rows, n]: 32 columns a tile. -#define TF_GATHER_GLU(BM) \ - [[kernel]] void tf_affine_gather_glu_##BM( \ - const device bfloat* X [[buffer(0)]], const device uint32_t* WG [[buffer(1)]], \ - const device bfloat* SG [[buffer(2)]], const device bfloat* BG [[buffer(3)]], \ - const device float* XS [[buffer(4)]], constant MmArgs& a [[buffer(5)]], device bfloat* Y [[buffer(6)]], \ - const device int32_t* OFFS [[buffer(7)]], const device int32_t* ORDER [[buffer(8)]], \ - const device uint32_t* WU [[buffer(9)]], const device bfloat* SU [[buffer(10)]], \ - const device bfloat* BU [[buffer(11)]], constant float2& glu [[buffer(12)]], TF_AM_MAP_ARG \ - uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], \ - uint3 tg [[threadgroup_position_in_grid]]) { \ - constexpr int SM = BM / 2; \ - constexpr int TM = SM / 16; \ - threadgroup bfloat tile[64 * PAD]; \ - threadgroup float sb[NG * 128]; \ - int expert, row, rows; \ - if (!am_tile(OFFS, a.experts, a.rows, int(tg.y), lane, expert, row, rows)) return; \ - const int c0 = int(tg.x) * 32, t = int(sg) * 32 + int(lane), tr = t / 2; \ - const bool up = ((tr >> 4) & 1) != 0; \ - const long wrow = long(TF_AM_EXPERT(expert)) * a.n + c0 + (tr >> 5) * 16 + (tr & 15); \ - const int tm = SM * int(sg / 2), tn = 32 * int(sg % 2), live = clamp(rows - tm, 0, SM); \ - const short2 home = frag_home(ushort(lane)); \ - const AmRows starts = am_rows(X, a.k, XS, a.k / TF_GROUP, row, rows, tm, home, ORDER, int(glu.x)); \ - frag acc[TM][2]; \ - am_k_loop(acc, starts, a.k, live, \ - (const device uchar*)(up ? WU : WG) + wrow * (a.k * TF_BITS / 8) + HALF_BYTES * (t % 2), \ - (up ? SU : SG) + wrow * (a.k / TF_GROUP), (up ? BU : BG) + wrow * (a.k / TF_GROUP), tile, sb, tn, \ - uint(t), home); \ - am_store_glu(acc, Y + long(row + tm) * a.n + c0 + tn / 2, a.n, live, home, glu.y); \ - } -// Tile rows by 16: gate, up, gate, up for columns c0.., c0 + 16.. -TF_GATHER_GLU(32) -TF_GATHER_GLU(64) diff --git a/zig/kernels/metal/core/affine_mm_glu.metal b/zig/kernels/metal/core/affine_mm_glu.metal new file mode 100644 index 00000000000..8214549e7e2 --- /dev/null +++ b/zig/kernels/metal/core/affine_mm_glu.metal @@ -0,0 +1,77 @@ + +#ifdef TF_GLU_PLAIN +// mlx-lm's compiled SwiGLU on bf16 rows (LFM2): silu(g) * u, rounded to bf16 at each step; `limit` unused. +inline bfloat am_swiglu(float g, float u, float limit) { + const float gt = float(bfloat(g)); + const bfloat s = static_cast(1.0f / (1.0f + metal::precise::exp(-gt))); + const bfloat silu = static_cast(gt * float(s)); + return static_cast(float(silu) * float(bfloat(u))); +} +#else +// The glue's SwiGLU in bf16 (glm_act2): MLX's bf16 exp and abs, nn.silu's x*sigmoid(x), gate and up clipped at `limit`. +inline bfloat am_sigmoid(bfloat x) { + const bfloat e = bfloat(__metal_exp(float(bfloat(__metal_fabs(float(x), __METAL_MAYBE_FAST_MATH__))), __METAL_MAYBE_FAST_MATH__)); + const bfloat y = bfloat(1) / (bfloat(1) + e); + return (x < 0) ? y : (bfloat(1) - y); +} + +inline bfloat am_swiglu(float g, float u, float limit) { + const float lim = float(bfloat(limit)); + const bfloat gt = bfloat(metal::min(float(bfloat(g)), lim)); + const bfloat up = bfloat(metal::min(metal::max(float(bfloat(u)), -lim), lim)); +#ifdef TF_GLU_ROUND_SILU + const bfloat sl = bfloat(precise::divide(float(gt), 1.0f + precise::exp(-float(gt)))); +#else + const bfloat sl = gt * am_sigmoid(gt); +#endif + return sl * up; +} +#endif + +// A simdgroup's gate (j 0) and up (j 1) fragments as SwiGLU outputs into y (ld N), rows below live only. +template +inline void am_store_glu(thread const frag (&acc)[TM][2], device bfloat* y, int N, int live, short2 home, + float limit) { + TF_UNROLL + for (short i = 0; i < TM; i++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int r = 16 * i + home.y + (e >> 2) * 8; + if (r < live) y[long(r) * N + home.x + TF_COL(e)] = am_swiglu(acc[i][0][e], acc[i][1][e], limit); + } + } +} + +// The routed experts' gate and up over ORDER's token rows (pair / topk), SwiGLU'd to act [rows, n]: 32 columns a tile. +#define TF_GATHER_GLU(BM) \ + [[kernel]] void tf_affine_gather_glu_##BM( \ + const device bfloat* X [[buffer(0)]], const device uint32_t* WG [[buffer(1)]], \ + const device bfloat* SG [[buffer(2)]], const device bfloat* BG [[buffer(3)]], \ + const device float* XS [[buffer(4)]], constant MmArgs& a [[buffer(5)]], device bfloat* Y [[buffer(6)]], \ + const device int32_t* OFFS [[buffer(7)]], const device int32_t* ORDER [[buffer(8)]], \ + const device uint32_t* WU [[buffer(9)]], const device bfloat* SU [[buffer(10)]], \ + const device bfloat* BU [[buffer(11)]], constant float2& glu [[buffer(12)]], TF_AM_MAP_ARG \ + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], \ + uint3 tg [[threadgroup_position_in_grid]]) { \ + constexpr int SM = BM / 2; \ + constexpr int TM = SM / 16; \ + threadgroup bfloat tile[64 * PAD]; \ + threadgroup float sb[NG * 128]; \ + int expert, row, rows; \ + if (!am_tile(OFFS, a.experts, a.rows, int(tg.y), lane, expert, row, rows)) return; \ + const int c0 = int(tg.x) * 32, t = int(sg) * 32 + int(lane), tr = t / 2; \ + const bool up = ((tr >> 4) & 1) != 0; \ + const long wrow = long(TF_AM_EXPERT(expert)) * a.n + c0 + (tr >> 5) * 16 + (tr & 15); \ + const int tm = SM * int(sg / 2), tn = 32 * int(sg % 2), live = clamp(rows - tm, 0, SM); \ + const short2 home = frag_home(ushort(lane)); \ + const AmRows starts = am_rows(X, a.k, XS, a.k / TF_GROUP, row, rows, tm, home, ORDER, int(glu.x)); \ + frag acc[TM][2]; \ + am_k_loop(acc, starts, a.k, live, \ + (const device uchar*)(up ? WU : WG) + wrow * (a.k * TF_BITS / 8) + HALF_BYTES * (t % 2), \ + (up ? SU : SG) + wrow * (a.k / TF_GROUP), (up ? BU : BG) + wrow * (a.k / TF_GROUP), tile, sb, tn, \ + uint(t), home); \ + am_store_glu(acc, Y + long(row + tm) * a.n + c0 + tn / 2, a.n, live, home, glu.y); \ + } +// Tile rows by 16: gate, up, gate, up for columns c0.., c0 + 16.. +TF_GATHER_GLU(32) +TF_GATHER_GLU(64) diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index db94659e847..b07432e1270 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -202,7 +202,7 @@ pub const glm_select = @embedFile("glm_select.metal"); pub const glm_absorb_nax = @embedFile("glm_absorb_nax.metal"); /// A MoE layer's route in two launches (core/moe_route.zig): router logits, then the top-k and the expert groups. pub const core_moe_route = @embedFile("core/moe_route.metal"); -pub const core_affine_mm = @embedFile("core/affine_mm.metal"); +pub const core_affine_mm = @embedFile("core/affine_mm.metal") ++ @embedFile("core/affine_mm_glu.metal"); /// A hyper-connection block boundary in two launches (core/hc.zig). pub const core_hc_boundary = @embedFile("core/hc_boundary.metal"); /// MLX's precise row softmax and its embedding and RMS kernels, as the replicas in ops/ write them. diff --git a/zig/src/families/glm/kernels.zig b/zig/src/families/glm/kernels.zig index 0d8915d684e..67e36522a6c 100644 --- a/zig/src/families/glm/kernels.zig +++ b/zig/src/families/glm/kernels.zig @@ -397,13 +397,13 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an defer gpa.free(m3_src); var m3_out: affine_mm.Pipes = undefined; if (m3_fast) jobs[generated.len + 27] = .{ .device = device, .source = m3_src, .names = &affine_mm.names, .out = &m3_out }; - const all = jobs[0 .. jobs.len - @intFromBool(!m3_fast)]; + const active_jobs = jobs[0 .. jobs.len - @intFromBool(!m3_fast)]; if (comptime @TypeOf(visitor) != void) { - for (all) |j| try visitor.raw("glm", j.names[0], j.source); + for (active_jobs) |j| try visitor.raw("glm", j.names[0], j.source); return; } var sources_seen = std.hash.Wyhash.init(0x6b); - for (all) |j| sources_seen.update(j.source); + for (active_jobs) |j| sources_seen.update(j.source); k.source_hash = sources_seen.final(); var next = std.atomic.Value(usize).init(0); const Worker = struct { @@ -416,10 +416,10 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an } }; var threads: [8]?std.Thread = @splat(null); - for (&threads) |*t| t.* = std.Thread.spawn(.{}, Worker.run, .{ all, &next }) catch null; - Worker.run(all, &next); + for (&threads) |*t| t.* = std.Thread.spawn(.{}, Worker.run, .{ active_jobs, &next }) catch null; + Worker.run(active_jobs, &next); for (threads) |t| if (t) |th| th.join(); - for (all) |j| if (j.failed) return error.KernelCompile; + for (active_jobs) |j| if (j.failed) return error.KernelCompile; inline for (glue, 0..) |g, i| @field(k, g.field) = glue_out[i]; k.sample = sample_out[0]; // the shared sampler's own library: glm_glue's table never named it k.latent_scores = attn_out[0]; diff --git a/zig/src/families/glm/prompt.zig b/zig/src/families/glm/prompt.zig index 953e3c7ae8f..7b10409c5f1 100644 --- a/zig/src/families/glm/prompt.zig +++ b/zig/src/families/glm/prompt.zig @@ -449,7 +449,7 @@ fn selectKeys(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, mi: us bind(e, 0, .{ iq, iw, x.s.mla[mi].pool, p.sscore }); e.setValue([5]u32{ p0, c.qrProj(), c.i_heads, s_stride, n }, 4); const rows = if (x.k.m3_fast) 32 else scoreRows(most, n); - e.dispatchGroups(size((most + 63) / 64, (n + rows - 1) / rows, 1), size(2 * rows, 1, 1)); + e.dispatchGroups(size((most + 63) / 64, (n + rows - 1) / rows, 1), size(if (x.k.m3_fast) 128 else 2 * rows, 1, 1)); e.setPipeline(x.k.index_select); bind(e, 0, .{ p.sscore, indices }); e.setValue([5]u32{ p0, c.i_topk / c.kpool, c.keyWidth(), s_stride, c.keyWidth() }, 2); From 141268e8a651aca5382f17812f504903cf4a1905 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:12:21 +0000 Subject: [PATCH 007/265] glm metal: retain main grouped-pipeline ownership with the pre-M5 split Create only grouped pipelines from the combined library before M5, leaving the affine pipelines owned by the separate library. Exercise the actual loader and destructor on both capability paths without a device. --- zig/build/glm_rows_contract.zig | 8 +++++ zig/glm_kernel_ownership_host.zig | 19 ++++++++++ zig/glm_kernel_ownership_metal.zig | 56 ++++++++++++++++++++++++++++++ zig/glm_rows_contract_family.zig | 1 + zig/src/families/glm/kernels.zig | 3 +- 5 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 zig/glm_kernel_ownership_host.zig create mode 100644 zig/glm_kernel_ownership_metal.zig diff --git a/zig/build/glm_rows_contract.zig b/zig/build/glm_rows_contract.zig index b2be197e026..ba5099310af 100644 --- a/zig/build/glm_rows_contract.zig +++ b/zig/build/glm_rows_contract.zig @@ -14,5 +14,13 @@ pub fn host(b: *std.Build, sources: *std.Build.Module) *std.Build.Step { run.has_side_effects = true; const step = b.step("test-glm-window-contract-host", "Register and validate actual GLM replacement operators without a GPU"); step.dependOn(&run.step); + const ownership_metal = b.createModule(.{ .root_source_file = b.path("zig/glm_kernel_ownership_metal.zig"), .target = b.graph.host }); + const loader = b.createModule(.{ .root_source_file = b.path("zig/glm_rows_contract_family.zig"), .target = b.graph.host, .imports = &.{ .{ .name = "metal", .module = ownership_metal }, .{ .name = "kernel_sources", .module = sources } } }); + const ownership_root = b.createModule(.{ .root_source_file = b.path("zig/glm_kernel_ownership_host.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = ownership_metal }, .{ .name = "glm_kernels", .module = loader } } }); + const ownership_run = b.addRunArtifact(b.addTest(.{ .root_module = ownership_root, .filters = &.{"GLM kernel ownership:"} })); + ownership_run.has_side_effects = true; + const ownership_step = b.step("test-glm-kernel-ownership-host", "Actual GLM loader pipelines are all released once on both capability paths"); + ownership_step.dependOn(&ownership_run.step); + step.dependOn(ownership_step); return step; } diff --git a/zig/glm_kernel_ownership_host.zig b/zig/glm_kernel_ownership_host.zig new file mode 100644 index 00000000000..3c8c22e70d5 --- /dev/null +++ b/zig/glm_kernel_ownership_host.zig @@ -0,0 +1,19 @@ +//! Exercise the actual GLM loader and destructor on both Metal capability paths. +const std = @import("std"); +const metal = @import("metal"); +const kernels = @import("glm_kernels").glm.kernels; +fn check(tensor: bool) !void { + metal.reset(); + const a = std.testing.allocator; + const k = try kernels.load(a, .{ .tensor = tensor }); + defer a.destroy(k); + k.deinit(); + try std.testing.expectEqual(metal.created.load(.monotonic), metal.released.load(.monotonic)); + try std.testing.expect(metal.created.load(.monotonic) > 0); +} +test "GLM kernel ownership: pre-M5 releases every compiled pipeline exactly once" { + try check(false); +} +test "GLM kernel ownership: M5 releases every compiled pipeline exactly once" { + try check(true); +} diff --git a/zig/glm_kernel_ownership_metal.zig b/zig/glm_kernel_ownership_metal.zig new file mode 100644 index 00000000000..ae1d50f2e07 --- /dev/null +++ b/zig/glm_kernel_ownership_metal.zig @@ -0,0 +1,56 @@ +//! Count loader pipeline ownership without a device, shader compiler or driver. +const std = @import("std"); +pub var created = std.atomic.Value(usize).init(0); +pub var released = std.atomic.Value(usize).init(0); +var ended: [4096]std.atomic.Value(bool) = @splat(std.atomic.Value(bool).init(false)); +pub fn reset() void { + created.store(0, .monotonic); + released.store(0, .monotonic); + for (&ended) |*v| v.store(false, .monotonic); +} +pub const Device = struct { + tensor: bool, + pub fn tensorUnits(d: Device) bool { + return d.tensor; + } + pub fn name(_: Device) [*:0]const u8 { + return "ownership fixture"; + } +}; +pub const CompileOptions = struct { + pub fn mlx() CompileOptions { + return .{}; + } +}; +pub const Library = struct { + pub fn fromSource(_: Device, _: []const u8, _: CompileOptions) !Library { + return .{}; + } + pub fn deinit(_: Library) void {} +}; +pub const Pipeline = struct { + id: usize, + pub fn init(_: Device, _: Library, _: [:0]const u8, _: bool) !Pipeline { + const id = created.fetchAdd(1, .monotonic); + std.debug.assert(id < ended.len); + return .{ .id = id }; + } + pub fn deinit(p: Pipeline) void { + std.debug.assert(!ended[p.id].swap(true, .monotonic)); + _ = released.fetchAdd(1, .monotonic); + } +}; +pub const Buffer = struct { + pub fn deinit(_: Buffer) void {} +}; +pub const ComputeEncoder = struct {}; +pub const Queue = struct {}; +pub const Size = @import("gemma4_recording_metal.zig").Size; +pub const objc = struct { + pub const Pool = struct { + pub fn push() Pool { + return .{}; + } + pub fn pop(_: Pool) void {} + }; +}; diff --git a/zig/glm_rows_contract_family.zig b/zig/glm_rows_contract_family.zig index f7f77134df5..b7ebe2d5b90 100644 --- a/zig/glm_rows_contract_family.zig +++ b/zig/glm_rows_contract_family.zig @@ -1,5 +1,6 @@ //! Shared GLM owners for recording-only contract tests. pub const glm = struct { + pub const kernels = @import("src/families/glm/kernels.zig"); pub const wide = @import("src/families/glm/wide.zig"); pub const affine = @import("src/families/glm/affine.zig"); }; diff --git a/zig/src/families/glm/kernels.zig b/zig/src/families/glm/kernels.zig index 67e36522a6c..ee7e9ab2112 100644 --- a/zig/src/families/glm/kernels.zig +++ b/zig/src/families/glm/kernels.zig @@ -323,7 +323,8 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an const m32_src = try affine_mm.source(device, gpa, .{ .out_f32 = true, .glm_m3_fast = m3_fast }); defer gpa.free(m32_src); var m16_out: [m16_names.len]mtl.Pipeline = undefined; - jobs[generated.len + 7] = .{ .device = device, .source = m16_src, .names = &m16_names, .out = &m16_out }; + const grouped_from: usize = if (m3_fast) affine_mm.names.len else 0; + jobs[generated.len + 7] = .{ .device = device, .source = m16_src, .names = m16_names[grouped_from..], .out = m16_out[grouped_from..] }; jobs[generated.len + 8] = .{ .device = device, .source = m32_src, .names = &affine_mm.names, .out = &k.mm_f32 }; const m3_def = if (m3_fast) "#define TF_GLM_M3_FAST 1\n" else ""; const kda_src = try std.mem.concat(gpa, u8, &.{ comptime kernelOf("kda_rows").source, m3_def, sources.glm_kda_prompt, sources.glm_kda_window, sources.glm_kda_parts }); From c253e41c562881d56b6034f212d9ee4721c98ecd Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 03:37:13 +0000 Subject: [PATCH 008/265] tests: re-pin the affine Metal source after #3921's kernels and GLU split --- zig/gemma4_shared_affine_test.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/gemma4_shared_affine_test.zig b/zig/gemma4_shared_affine_test.zig index 6c2b89115f0..27303b25f3e 100644 --- a/zig/gemma4_shared_affine_test.zig +++ b/zig/gemma4_shared_affine_test.zig @@ -104,7 +104,7 @@ test "landed Metal source bytes are pinned without shader compilation" { var hash: [32]u8 = undefined; std.crypto.hash.sha2.Sha256.hash(ks.core_affine_mm, &hash, .{}); // Hy4-flash's mapped experts and rounded SiLU, both behind defines that are off for every other caller - try std.testing.expectEqualStrings("2cf4deb55455fda30efb4fce3043ef5d90052d71f48ce7660960e8b588478aca", &std.fmt.bytesToHex(hash, .lower)); + try std.testing.expectEqualStrings("9a01998f26f80c9faa511dce14d1f545264c9ab343d189d8f0f005d83cc632b7", &std.fmt.bytesToHex(hash, .lower)); } { var hash: [32]u8 = undefined; From cf37b2a32d526c3c578e9e38247599e52d2e2b96 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 04:37:55 +0000 Subject: [PATCH 009/265] glm metal: prompt.zig and the Metal contract main back to 600 lines after main's #3920 Format only: the unabsorb strides go back inline and the limits gate is one line. Nothing else changes. --- zig/src/families/glm/prompt.zig | 3 +-- zig/tests/contract/metal_main.zig | 4 +--- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/zig/src/families/glm/prompt.zig b/zig/src/families/glm/prompt.zig index 7b10409c5f1..3cbbe242ffc 100644 --- a/zig/src/families/glm/prompt.zig +++ b/zig/src/families/glm/prompt.zig @@ -431,8 +431,7 @@ fn unabsorb(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, w: *cons q.b = q.b.at(@as(usize, c.nope) * (K / 64) * 2); q.n = c.v_dim; affine_mm.rowSums(e, p.mm.mm_bf16, 64, p.att, p.sums, M * H, K); - const bs: affine_mm.Strides = .{ .x_row = @intCast(H * K), .y_row = @intCast(H * c.v_dim), .sums_row = @intCast(H), .x_batch = @intCast(K), .y_batch = @intCast(c.v_dim), .sums_batch = 1, .w_batch = @intCast(per) }; - affine_mm.denseBatchBm(e, p.mm.mm_bf16, p.att, p.sums, q, p.vals, M, H, bs, if (p.mm.m3_fast) 32 else 64); + affine_mm.denseBatchBm(e, p.mm.mm_bf16, p.att, p.sums, q, p.vals, M, H, .{ .x_row = @intCast(H * K), .y_row = @intCast(H * c.v_dim), .sums_row = @intCast(H), .x_batch = @intCast(K), .y_batch = @intCast(c.v_dim), .sums_batch = 1, .w_batch = @intCast(per) }, if (p.mm.m3_fast) 32 else 64); } /// The index scores' tile rows: 128 (a row's queries read once for 64 blocks), 64 where that leaves the GPU half idle. diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index e30cb244cc4..54a23326484 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -593,9 +593,7 @@ pub fn main(init: std.process.Init) !u8 { } const t1 = std.Io.Clock.awake.now(init.io); var lim: usize = 0; - if (o.limits) { - lim = try @import("metal_limits_all.zig").gate(a, init.io, device, o.offline, o.only); - } + if (o.limits) lim = try @import("metal_limits_all.zig").gate(a, init.io, device, o.offline, o.only); const t2 = std.Io.Clock.awake.now(init.io); const ms = struct { fn of(x: std.Io.Timestamp, y: std.Io.Timestamp) i64 { From 8b56ac2c3c9f1c7b1bf430b5cca6c9582eb2b6a2 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:06:49 +0000 Subject: [PATCH 010/265] contract: GLM's M3 affine_mm entries in metal_affine.zig beside the half tiles metal_main.zig grows with every family and sat over 600 lines with main; the nine glm_m3_fast registrations join the list as affine_k.glm_m3, as the half tiles already do. Order and names are unchanged apart from where they sit. --- zig/tests/contract/metal_affine.zig | 13 +++++++++++++ zig/tests/contract/metal_main.zig | 11 +---------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/zig/tests/contract/metal_affine.zig b/zig/tests/contract/metal_affine.zig index de0fb725818..2ae78e13c6d 100644 --- a/zig/tests/contract/metal_affine.zig +++ b/zig/tests/contract/metal_affine.zig @@ -18,6 +18,19 @@ pub const Kind = enum { row, affine_mm, simd, simd_half, simd_sums, simd_bits, l /// One variant: kernel, code width and group, output, lane K slices; control: simd_half's or simd_sums' planted fault. pub const Variant = struct { kind: Kind, bits: u8 = 4, group: usize = 64, f32_out: bool = false, sk: usize = 1, coop: bool = false, glm_m3_fast: bool = false, control: bool = false, served: ?[]const c.Shape = null, inline_sums: bool = false }; +/// GLM-5.3-Flash's M3 fast tiles (#3921): row tile 32 a block where the plain path takes 64. +pub const glm_m3 = [_]Reg{ + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .f32_out = true, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g64 fp32 out" }, + .{ .v = .{ .kind = .affine_mm, .bits = 2, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q2 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 5, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q5 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 6, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q6 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 8, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q8 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 32, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g32" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 128, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g128" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .glm_m3_fast = true, .control = true }, .name = "control: metal affine_mm glm m3 q4 g64, wrong row tile height" }, +}; + pub const Reg = struct { v: Variant, name: []const u8 }; /// The half-operand tiles, the chunk pairs on the prepass's sums, and their planted controls, beside simd_qmm's entry. pub const half = [_]Reg{ diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index 54a23326484..eb44a76eab1 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -69,22 +69,13 @@ const common = [_]Reg{ .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .f32_out = true }, .name = "metal affine_mm q4 g64 fp32 out" }, .{ .v = .{ .kind = .affine_mm, .bits = 8, .group = 32 }, .name = "metal affine_mm q8 g32" }, .{ .v = .{ .kind = .affine_mm, .bits = 8, .group = 64 }, .name = "metal affine_mm q8 g64" }, - .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g64" }, - .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .f32_out = true, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g64 fp32 out" }, - .{ .v = .{ .kind = .affine_mm, .bits = 2, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q2 g64" }, - .{ .v = .{ .kind = .affine_mm, .bits = 5, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q5 g64" }, - .{ .v = .{ .kind = .affine_mm, .bits = 6, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q6 g64" }, - .{ .v = .{ .kind = .affine_mm, .bits = 8, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q8 g64" }, - .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 32, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g32" }, - .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 128, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g128" }, - .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .glm_m3_fast = true, .control = true }, .name = "control: metal affine_mm glm m3 q4 g64, wrong row tile height" }, .{ .v = .{ .kind = .simd, .bits = 4, .group = 64 }, .name = "metal simd_qmm q4 g64" }, .{ .v = .{ .kind = .simd_bits, .bits = 3, .group = 64 }, .name = "metal simd_qmm_bits q3 g64" }, .{ .v = .{ .kind = .simd_bits, .bits = 6, .group = 64 }, .name = "metal simd_qmm_bits q6 g64" }, .{ .v = .{ .kind = .simd_bits, .bits = 8, .group = 64 }, .name = "metal simd_qmm_bits q8 g64" }, .{ .v = .{ .kind = .lane, .bits = 6, .group = 32 }, .name = "metal lane projection q6 g32 sk1" }, .{ .v = .{ .kind = .lane, .bits = 6, .group = 32, .sk = 4, .f32_out = true }, .name = "metal lane projection q6 g32 sk4 fp32 out" }, -} ++ affine_k.half; +} ++ affine_k.half ++ affine_k.glm_m3; /// The lane kernel takes every format on the M5's tensor units, and 6-bit groups of 32 alone before them. const m5_only = @import("metal_lane_variants.zig").m5; From d24cb5e791e5d1c9740064739b2787c8430096b8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:18:31 +0000 Subject: [PATCH 011/265] changelog: #3921 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index de86edf4173..5535fc7b4be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- GLM on Metal: vectorized prompt, KDA and indexer kernels on Macs without tensor units cut cold prompt time 5.17% to 5.68% (2K to 64K tokens) with 0/64 token differences (#3921, refs #3152). Thanks to @gilby. + - MiniMax-H3-Image on Metal: `tf-h3-image` runs its transformer (MiniMax H3's, without the audio layers, on M5 tensor units) from a picture case through its six distilled steps, each with its own output head, beside the engine; the VAE's rules (config, tiles and blend, latent statistics, pixels) run on the host, and core/picture gains Pillow's Lanczos-3 resampling. Clip cases run as before (#2775). - Kernel contract: the GLM record for `df_sumn` under nvcc 13.3 (40 registers) is the one checked; a stale generic 33-register entry no longer overrides it (#4291). Thanks to @Bizuayeu. From 0d8a69f6e800eb49a2cac7a2f89f38954e96a084 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:16:21 +0000 Subject: [PATCH 012/265] moss_image: torch.randn draws chained on one generator, for pipelines that draw several tensors --- zig/src/families/moss_image/noise.zig | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/zig/src/families/moss_image/noise.zig b/zig/src/families/moss_image/noise.zig index 5a3c3a6c9d9..1b5314e4ccd 100644 --- a/zig/src/families/moss_image/noise.zig +++ b/zig/src/families/moss_image/noise.zig @@ -122,8 +122,13 @@ fn fill16(d: *[16]f32) void { /// torch.randn of `out.len` float32 values (16 or more) in torch's order, as manual_seed(seed) makes them. pub fn randn(seed: u64, out: []f32) void { - std.debug.assert(out.len >= 16); var t = Twister.init(seed); + draw(&t, out); +} + +/// The next torch.randn of `out.len` values (16 or more) from `t`: consecutive draws on one generator chain this way. +pub fn draw(t: *Twister, out: []f32) void { + std.debug.assert(out.len >= 16); for (out) |*v| v.* = t.uniform(); var i: usize = 0; while (i + 16 <= out.len) : (i += 16) fill16(out[i..][0..16]); From db758e7f3bc0e28279896fa0c550be9f5c8de52b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:16:21 +0000 Subject: [PATCH 013/265] h3: MiniMax-H3-Image's edit reference rules on the host: sizes, crops, grids, encoder layers, clean and anchor rows --- zig/src/families/h3/geometry_test.zig | 1 + zig/src/families/h3/picture_reference.zig | 219 ++++++++++++++++++ .../families/h3/picture_reference_test.zig | 219 ++++++++++++++++++ 3 files changed, 439 insertions(+) create mode 100644 zig/src/families/h3/picture_reference.zig create mode 100644 zig/src/families/h3/picture_reference_test.zig diff --git a/zig/src/families/h3/geometry_test.zig b/zig/src/families/h3/geometry_test.zig index 6a4133c6475..21d5a38a819 100644 --- a/zig/src/families/h3/geometry_test.zig +++ b/zig/src/families/h3/geometry_test.zig @@ -391,6 +391,7 @@ test { _ = @import("schedule_replace_test.zig"); _ = @import("picture_test.zig"); _ = @import("picture_vae_test.zig"); + _ = @import("picture_reference_test.zig"); } /// MiniMax-H3-Image's case: text and picture rows only, no audio tensor, two rows in two tiles. diff --git a/zig/src/families/h3/picture_reference.zig b/zig/src/families/h3/picture_reference.zig new file mode 100644 index 00000000000..bbedf23c4a0 --- /dev/null +++ b/zig/src/families/h3/picture_reference.zig @@ -0,0 +1,219 @@ +//! MiniMax-H3-Image's edit references on the host: sizes, the encoder's input and layers, clean and anchor rows. +const std = @import("std"); +const st = @import("safetensors"); +const geometry = @import("geometry.zig"); +const picture = @import("picture.zig"); +const vae = @import("picture_vae.zig"); + +pub const Size = picture.Size; +pub const Grid = picture.Grid; +const cell = vae.cell_pixels; + +/// A reference's sides must be at least this long. +pub const min_side = 32; +/// The short edge of each copy: the VAE's lies in 1024..2048, the Qwen encoder's is exactly 1024. +pub const Bound = struct { least: usize, most: usize }; +pub const vae_bound: Bound = .{ .least = 1024, .most = 2048 }; +pub const qwen_bound: Bound = .{ .least = 1024, .most = 1024 }; +/// The largest VAE copy taken: 64 MP, above any 8:1 reference (2048 x 16384) vLLM-Omni admits. +pub const max_area: u64 = 8192 * 8192; +/// An anchor row keeps this much of the clean row (float32 0.999); the rest is noise. +pub const anchor_clean: f32 = 0.999; +/// 1 - c in float32 (exact), not float32(0.001). +pub const anchor_noise: f32 = 1.0 - anchor_clean; + +/// A copy whose short edge lies in `b`: kept when it does, else scaled to the nearer end and snapped to 32. +pub fn bounded(width: usize, height: usize, b: Bound) !Size { + if (width < min_side or height < min_side) return error.H3ReferenceTooSmall; + const short = @min(width, height); + var s: Size = .{ .width = width, .height = height }; + if (short < b.least or short > b.most) { + const scale = @as(f64, @floatFromInt(if (short < b.least) b.least else b.most)) / @as(f64, @floatFromInt(short)); + s = .{ .width = try snap(width, scale), .height = try snap(height, scale) }; + } + if (@as(u64, s.width) * s.height > max_area) return error.H3ReferenceTooLarge; + return s; +} + +/// side x scale to the nearest multiple of 32 (halves to even, as Python's round), at least 32. +fn snap(side: usize, scale: f64) !usize { + const n = @max(1.0, picture.roundEven(@as(f64, @floatFromInt(side)) * scale / picture.row_pixels)); + if (n > @as(f64, @floatFromInt(max_area / picture.row_pixels))) return error.H3ReferenceTooLarge; + return @as(usize, @intFromFloat(n)) * picture.row_pixels; +} + +/// The encoder's input size: the VAE copy cropped top-left to multiples of 16 pixels. +pub fn cropped(s: Size) !Size { + if (s.width < cell or s.height < cell) return error.H3ReferenceTooSmall; + return .{ .width = s.width / cell * cell, .height = s.height / cell * cell }; +} + +/// The encoder's latent grid of a cropped input: a cell every 16 pixels, rows or columns of any parity. +pub fn fullGrid(s: Size) Grid { + return .{ .rows = s.height / cell, .columns = s.width / cell }; +} + +/// The reference's grid: the full grid cropped top-left to even sides (a 2 x 2 patch a row). +pub fn evenGrid(full: Grid) !Grid { + const g: Grid = .{ .rows = full.rows / 2 * 2, .columns = full.columns / 2 * 2 }; + if (g.rows == 0 or g.columns == 0) return error.H3ReferenceTooSmall; + return g; +} + +/// The encoder's input from RGB bytes [height, width, 3]: cropped to 16s, x / 255, ImageNet-normalised, fp32 [h, w, 3]. +pub fn input(rgb: []const u8, width: usize, height: usize, out: []f32) !Size { + const s = try cropped(.{ .width = width, .height = height }); + if (rgb.len != try geometry.product(&.{ width, height, 3 }) or out.len != s.width * s.height * 3) return error.H3BadPictureSize; + for (0..s.height) |y| for (0..s.width) |x| for (0..3) |c| { + const v = @as(f32, @floatFromInt(rgb[(y * width + x) * 3 + c])) / 255.0; + out[(y * s.width + x) * 3 + c] = (v - vae.pixel_mean[c]) / vae.pixel_std[c]; + }; + return s; +} + +/// Index `i` of an axis of `n` reflected at its edges (-1 reads 1, n reads n - 2): reflect padding by one. +pub fn reflect(i: isize, n: usize) usize { + const last: isize = @intCast(n - 1); + return @intCast(if (i < 0) -i else if (i > last) 2 * last - i else i); +} + +pub const levels = 6; +/// Levels 0-3 end with a stride-2 downsample: 16 pixels a cell. +pub const downsampled = 4; +pub const groups = 32; +/// The encoder's output: 24 means, then 24 log-variances. +pub const moments = 2 * vae.latent_channels; + +/// The encoder's width a level: the released one's, or smaller ones for a self-test. +pub const Arch = struct { widths: [levels]usize }; +pub const released: Arch = .{ .widths = .{ 128, 256, 256, 512, 512, 1024 } }; + +/// A layer: a 3x3x3 convolution run on its last time slice, a 1x1x1 one, or a GroupNorm. +pub const Kind = enum { conv3, conv1, norm }; +/// One layer: its tensors' prefix, its kind, and its channels in and out (equal for a norm). +pub const Item = struct { name: []const u8, kind: Kind, cin: usize, cout: usize }; + +fn join(a: std.mem.Allocator, prefix: []const u8, part: []const u8) ![]const u8 { + return std.fmt.allocPrint(a, "{s}{s}", .{ prefix, part }); +} + +/// Every layer in run order: conv_in, each level's blocks and downsample, norm_out, conv_out, quant_conv. +pub fn items(a: std.mem.Allocator, arch: Arch) ![]Item { + var list: std.ArrayList(Item) = .empty; + try list.append(a, .{ .name = "encoder.conv_in", .kind = .conv3, .cin = 3, .cout = arch.widths[0] }); + var cin = arch.widths[0]; + for (arch.widths, 0..) |w, l| { + if (w == 0 or w % groups != 0) return error.H3BadEncoderWidths; + for (0..2) |b| { + const p = try std.fmt.allocPrint(a, "encoder.down.{d}.block.{d}.", .{ l, b }); + try list.appendSlice(a, &.{ + .{ .name = try join(a, p, "norm1"), .kind = .norm, .cin = cin, .cout = cin }, + .{ .name = try join(a, p, "conv1"), .kind = .conv3, .cin = cin, .cout = w }, + .{ .name = try join(a, p, "norm2"), .kind = .norm, .cin = w, .cout = w }, + .{ .name = try join(a, p, "conv2"), .kind = .conv3, .cin = w, .cout = w }, + }); + if (cin != w) try list.append(a, .{ .name = try join(a, p, "nin_shortcut"), .kind = .conv1, .cin = cin, .cout = w }); + cin = w; + } + if (l < downsampled) try list.append(a, .{ .name = try std.fmt.allocPrint(a, "encoder.down.{d}.downsample.conv", .{l}), .kind = .conv3, .cin = w, .cout = w }); + } + try list.appendSlice(a, &.{ + .{ .name = "encoder.norm_out", .kind = .norm, .cin = cin, .cout = cin }, + .{ .name = "encoder.conv_out", .kind = .conv3, .cin = cin, .cout = moments }, + .{ .name = "quant_conv", .kind = .conv1, .cin = moments, .cout = moments }, + }); + return list.items; +} + +/// A checkpoint shape of up to five dimensions. +pub const Shape = struct { + dims: [5]usize, + rank: usize, + + pub fn slice(s: *const Shape) []const usize { + return s.dims[0..s.rank]; + } +}; + +/// The checkpoint's shape of an item's weight: [cout, cin, 3, 3, 3], [cout, cin, 1, 1, 1] or a norm's [c]. +pub fn weightShape(it: Item) Shape { + const k: usize = if (it.kind == .conv3) 3 else 1; + return .{ .dims = .{ it.cout, it.cin, k, k, k }, .rank = if (it.kind == .norm) 1 else 5 }; +} + +/// Each layer's F32 weight and bias at its shape, no other `encoder.` or `quant_conv.` tensor; `culprit` names a miss. +pub fn checkHeader(a: std.mem.Allocator, header: *const st.Header, culprit: *[]const u8) !void { + const list = try items(a, released); + for (list) |it| for ([_][]const u8{ ".weight", ".bias" }) |part| { + const name = try join(a, it.name, part); + culprit.* = name; + const e = header.get(name) orelse return error.H3MissingEncoderTensor; + const want: Shape = if (part[1] == 'w') weightShape(it) else .{ .dims = .{ it.cout, 0, 0, 0, 0 }, .rank = 1 }; + if (e.dtype != .f32 or !std.mem.eql(usize, e.shape[0..e.rank], want.slice())) return error.H3BadEncoderTensor; + }; + var count: usize = 0; + for (header.keys()) |k| if (std.mem.startsWith(u8, k, "encoder.") or std.mem.startsWith(u8, k, "quant_conv.")) { + culprit.* = k; + count += 1; + }; + if (count != 2 * list.len) return error.H3UnexpectedEncoderTensor; + culprit.* = ""; +} + +/// A weight row's length on the GPU: cout padded to 64, the kernel's channel tile. +pub fn rowLength(cout: usize) usize { + return std.mem.alignForward(usize, cout, 64); +} + +/// Taps a layer's kernel has. +pub fn taps(it: Item) usize { + return if (it.kind == .conv3) 9 else 1; +} + +/// A convolution's weight as the GPU reads it, [taps, cin, rowLength] zero-padded; a 3x3x3 gives [:, :, 2]. +pub fn pack(it: Item, weight: []align(1) const f32, out: []f32) !void { + const t = taps(it); + const ldw = rowLength(it.cout); + const each: usize = if (t == 9) 27 else 1; + if (it.kind == .norm or weight.len != it.cout * it.cin * each or out.len != t * it.cin * ldw) + return error.H3BadEncoderTensor; + @memset(out, 0); + for (0..it.cout) |co| for (0..it.cin) |ci| for (0..t) |tap| { + out[(tap * it.cin + ci) * ldw + co] = if (t == 9) weight[((co * it.cin + ci) * 3 + 2) * 9 + tap] else weight[co * it.cin + ci]; + }; +} + +/// `vae/config.json` must keep `vae_encoder_tiling` on: the tiles and their blend are part of the encoder's numbers. +pub fn checkTiling(a: std.mem.Allocator, json: []const u8) !void { + const doc = std.json.parseFromSliceLeaky(std.json.Value, a, json, .{}) catch return error.H3BadVaeConfig; + if (doc != .object) return error.H3BadVaeConfig; + const v = doc.object.get("vae_encoder_tiling") orelse return error.H3BadVaeConfig; + if (v != .integer or v.integer != 1) return error.H3UnsupportedVae; +} + +pub const Clean = struct { rows: []f32, grid: Grid }; + +/// Clean rows from moments [48, full grid]: sampled as fp16 with `noise`, normalised, cropped even, patchified. +pub fn clean(a: std.mem.Allocator, c: *const vae.Config, m: []const f32, full: Grid, noise: []const f32) !Clean { + const n = try geometry.product(&.{ vae.latent_channels, full.rows, full.columns }); + if (m.len != 2 * n or noise.len != n) return error.H3BadLatentLength; + const sample = try a.alloc(f32, n); + defer a.free(sample); + try vae.posterior(m[0..n], m[n..], noise, sample); + try vae.normalize(c, sample); + const g = try evenGrid(full); + const latent = try a.alloc(f32, vae.latent_channels * g.rows * g.columns); + defer a.free(latent); + for (0..vae.latent_channels) |ch| for (0..g.rows) |y| { + @memcpy(latent[(ch * g.rows + y) * g.columns ..][0..g.columns], sample[(ch * full.rows + y) * full.columns ..][0..g.columns]); + }; + const rows = try a.alloc(f32, latent.len); + try picture.patchify(latent, g, rows); + return .{ .rows = rows, .grid = g }; +} + +/// The anchor rows: c x clean + (1 - c) x noise, c = f32(0.999) and 1 - c taken in fp32, every product in fp32. +pub fn anchors(clean_rows: []const f32, noise_rows: []const f32, out: []f32) !void { + if (clean_rows.len != noise_rows.len or out.len != clean_rows.len) return error.H3BadLatentLength; + for (out, clean_rows, noise_rows) |*o, x, z| o.* = anchor_clean * x + anchor_noise * z; +} diff --git a/zig/src/families/h3/picture_reference_test.zig b/zig/src/families/h3/picture_reference_test.zig new file mode 100644 index 00000000000..32639f94d1d --- /dev/null +++ b/zig/src/families/h3/picture_reference_test.zig @@ -0,0 +1,219 @@ +//! MiniMax-H3-Image's edit reference rules (picture_reference.zig): sizes, crops, grids, layers, weights, rows. +const std = @import("std"); +const st = @import("safetensors"); +const r = @import("picture_reference.zig"); +const vae = @import("picture_vae.zig"); +const testing = std.testing; + +fn arena() std.heap.ArenaAllocator { + return std.heap.ArenaAllocator.init(testing.allocator); +} + +fn expectSize(want: [2]usize, got: r.Size) !void { + try testing.expectEqual(want[0], got.width); + try testing.expectEqual(want[1], got.height); +} + +test "picture reference sizes: the VAE bound's and the Qwen bound's examples, halves to even, refusals" { + try expectSize(.{ 1024, 1536 }, try r.bounded(512, 768, r.vae_bound)); + try expectSize(.{ 2048, 2720 }, try r.bounded(3000, 4000, r.vae_bound)); + try expectSize(.{ 1536, 2048 }, try r.bounded(1536, 2048, r.vae_bound)); + try expectSize(.{ 1024, 1376 }, try r.bounded(1500, 2000, r.qwen_bound)); + // inside the VAE's range a side need not be a multiple of 32 + try expectSize(.{ 1500, 2000 }, try r.bounded(1500, 2000, r.vae_bound)); + try expectSize(.{ 1024, 1024 }, try r.bounded(1024, 1024, r.qwen_bound)); + // 520 x 2 / 32 = 32.5 goes down to 32, 536 x 2 / 32 = 33.5 up to 34 + try expectSize(.{ 1024, 1024 }, try r.bounded(520, 512, r.vae_bound)); + try expectSize(.{ 1088, 1024 }, try r.bounded(536, 512, r.vae_bound)); + try expectSize(.{ 1024, 4096 }, try r.bounded(32, 128, r.vae_bound)); + try testing.expectError(error.H3ReferenceTooSmall, r.bounded(31, 2000, r.vae_bound)); + try testing.expectError(error.H3ReferenceTooSmall, r.bounded(2000, 20, r.qwen_bound)); + try testing.expectError(error.H3ReferenceTooLarge, r.bounded(32, 8192, r.vae_bound)); + try testing.expectError(error.H3ReferenceTooLarge, r.bounded(2048, 32769, r.vae_bound)); +} + +test "picture reference grids: 16-pixel crop, full grid, even grid" { + const square = try r.cropped(.{ .width = 1024, .height = 1024 }); + try testing.expectEqual(r.Grid{ .rows = 64, .columns = 64 }, try r.evenGrid(r.fullGrid(square))); + // width 1050, height 1000: 1040 x 992 pixels, 62 x 65 cells, then 62 rows by 64 columns + const wide = try r.cropped(.{ .width = 1050, .height = 1000 }); + try expectSize(.{ 1040, 992 }, wide); + try testing.expectEqual(r.Grid{ .rows = 62, .columns = 65 }, r.fullGrid(wide)); + try testing.expectEqual(r.Grid{ .rows = 62, .columns = 64 }, try r.evenGrid(r.fullGrid(wide))); + try testing.expectEqual(r.Grid{ .rows = 2, .columns = 4 }, try r.evenGrid(.{ .rows = 3, .columns = 5 })); + try testing.expectError(error.H3ReferenceTooSmall, r.cropped(.{ .width = 15, .height = 40 })); + try testing.expectError(error.H3ReferenceTooSmall, r.evenGrid(.{ .rows = 1, .columns = 8 })); +} + +test "picture reference input: cropped top-left to 16s, x / 255 then ImageNet's statistics, in fp32" { + var a = arena(); + defer a.deinit(); + const x = a.allocator(); + const w = 18; + const h = 17; + const rgb = try x.alloc(u8, w * h * 3); + for (rgb, 0..) |*b, i| b.* = @intCast((i * 37) % 256); + const out = try x.alloc(f32, 16 * 16 * 3); + try expectSize(.{ 16, 16 }, try r.input(rgb, w, h, out)); + for (0..16) |y| for (0..16) |col| for (0..3) |c| { + const b: f32 = @floatFromInt(rgb[(y * w + col) * 3 + c]); + try testing.expectEqual((b / 255.0 - vae.pixel_mean[c]) / vae.pixel_std[c], out[(y * 16 + col) * 3 + c]); + }; + try testing.expectError(error.H3BadPictureSize, r.input(rgb, w, h, out[1..])); + try testing.expectError(error.H3BadPictureSize, r.input(rgb[3..], w, h, out)); +} + +test "picture reference reflect padding: -1 reads 1, n reads n - 2, the inside as is" { + try testing.expectEqual(@as(usize, 1), r.reflect(-1, 5)); + try testing.expectEqual(@as(usize, 3), r.reflect(5, 5)); + for (0..5) |i| try testing.expectEqual(i, r.reflect(@intCast(i), 5)); + // a downsample's right and bottom pad, and the smallest axis reflect allows + try testing.expectEqual(@as(usize, 254), r.reflect(256, 256)); + try testing.expectEqual(@as(usize, 1), r.reflect(-1, 2)); + try testing.expectEqual(@as(usize, 0), r.reflect(2, 2)); +} + +fn shapeJson(a: std.mem.Allocator, dims: []const usize) ![]const u8 { + return std.json.Stringify.valueAlloc(a, dims, .{}); +} + +const Entry = struct { []const u8, []const u8, []const usize }; + +/// A safetensors header for `entries` (name, dtype, shape), laid end to end; returns it parsed. +fn header(a: std.mem.Allocator, entries: []const Entry) !st.Header { + var json: []const u8 = "{"; + var at: usize = 0; + for (entries, 0..) |e, i| { + var n: usize = if (std.mem.eql(u8, e[1], "BF16")) 2 else 4; + for (e[2]) |d| n *= d; + json = try std.fmt.allocPrint(a, "{s}{s}\"{s}\":{{\"dtype\":\"{s}\",\"shape\":{s},\"data_offsets\":[{d},{d}]}}", .{ json, if (i == 0) "" else ",", e[0], e[1], try shapeJson(a, e[2]), at, at + n }); + at += n; + } + return st.parseHeader(a, try std.fmt.allocPrint(a, "{s}}}", .{json}), at); +} + +/// The released encoder's entries, with `change` applied to the one named (null drops it), plus the decoder's. +fn released(a: std.mem.Allocator, name: []const u8, change: ?Entry) ![]Entry { + var list: std.ArrayList(Entry) = .empty; + try list.append(a, .{ "decoder.norm_out.weight", "F32", &.{1024} }); + try list.append(a, .{ "post_quant_conv.weight", "F32", &.{ 24, 24, 1, 1 } }); + for (try r.items(a, r.released)) |it| for ([_][]const u8{ ".weight", ".bias" }) |part| { + const full = try std.fmt.allocPrint(a, "{s}{s}", .{ it.name, part }); + const shape = r.weightShape(it); + const dims = if (part[1] == 'w') try a.dupe(usize, shape.slice()) else try a.dupe(usize, &.{it.cout}); + const e: Entry = .{ full, "F32", dims }; + if (!std.mem.eql(u8, full, name)) try list.append(a, e) else if (change) |c| try list.append(a, c); + }; + return list.items; +} + +test "picture reference layers: the released names and shapes pass the header check, every difference refused" { + var a = arena(); + defer a.deinit(); + const x = a.allocator(); + const list = try r.items(x, r.released); + try testing.expectEqual(@as(usize, 59), list.len); + try testing.expectEqualStrings("encoder.conv_in", list[0].name); + try testing.expectEqual(@as(usize, 3), list[0].cin); + var shortcuts: usize = 0; + var downs: usize = 0; + for (list) |it| { + if (std.mem.endsWith(u8, it.name, "nin_shortcut")) { + shortcuts += 1; + try testing.expect(it.kind == .conv1 and it.cin * 2 == it.cout); + } + if (std.mem.endsWith(u8, it.name, "downsample.conv")) downs += 1; + } + try testing.expectEqual(@as(usize, 3), shortcuts); + try testing.expectEqual(@as(usize, 4), downs); + try testing.expectEqualStrings("encoder.down.1.block.0.nin_shortcut", list[14].name); + try testing.expectEqualStrings("quant_conv", list[58].name); + try testing.expectEqual(@as(usize, 1024), list[57].cin); + var culprit: []const u8 = ""; + const good = try header(x, try released(x, "", null)); + try r.checkHeader(x, &good, &culprit); + const conv_in = "encoder.conv_in.weight"; + try testing.expectError(error.H3MissingEncoderTensor, r.checkHeader(x, &(try header(x, try released(x, conv_in, null))), &culprit)); + try testing.expectEqualStrings(conv_in, culprit); + const flat: Entry = .{ conv_in, "F32", &.{ 128, 3, 3, 3 } }; + try testing.expectError(error.H3BadEncoderTensor, r.checkHeader(x, &(try header(x, try released(x, conv_in, flat))), &culprit)); + const half: Entry = .{ "quant_conv.bias", "BF16", &.{48} }; + try testing.expectError(error.H3BadEncoderTensor, r.checkHeader(x, &(try header(x, try released(x, "quant_conv.bias", half))), &culprit)); + try testing.expectEqualStrings("quant_conv.bias", culprit); + const mid = [_]Entry{.{ "encoder.mid.block_1.conv1.weight", "F32", &.{ 8, 8, 3, 3, 3 } }}; + const extra = try std.mem.concat(x, Entry, &.{ try released(x, "", null), &mid }); + try testing.expectError(error.H3UnexpectedEncoderTensor, r.checkHeader(x, &(try header(x, extra)), &culprit)); + try testing.expectError(error.H3BadEncoderWidths, r.items(x, .{ .widths = .{ 128, 256, 256, 500, 512, 1024 } })); +} + +test "picture reference weights: a 3x3x3 kernel's last time slice, a 1x1x1 kernel, rows padded to 64" { + var a = arena(); + defer a.deinit(); + const x = a.allocator(); + const conv: r.Item = .{ .name = "c", .kind = .conv3, .cin = 2, .cout = 3 }; + const w = try x.alloc(f32, 3 * 2 * 27); + for (0..3) |co| for (0..2) |ci| for (0..3) |t| for (0..9) |tap| { + w[((co * 2 + ci) * 3 + t) * 9 + tap] = @floatFromInt(co * 1000 + ci * 100 + t * 10 + tap); + }; + const out = try x.alloc(f32, 9 * 2 * 64); + try r.pack(conv, w, out); + for (0..9) |tap| for (0..2) |ci| for (0..64) |co| { + const want: f32 = if (co < 3) @floatFromInt(co * 1000 + ci * 100 + 20 + tap) else 0; + try testing.expectEqual(want, out[(tap * 2 + ci) * 64 + co]); + }; + const one: r.Item = .{ .name = "q", .kind = .conv1, .cin = 2, .cout = 65 }; + const w1 = try x.alloc(f32, 65 * 2); + for (w1, 0..) |*v, i| v.* = @floatFromInt(i); + const out1 = try x.alloc(f32, 2 * 128); + try r.pack(one, w1, out1); + try testing.expectEqual(@as(f32, 64 * 2 + 1), out1[128 + 64]); + try testing.expectEqual(@as(f32, 0), out1[128 + 65]); + try testing.expectError(error.H3BadEncoderTensor, r.pack(conv, w[1..], out)); + try testing.expectError(error.H3BadEncoderTensor, r.pack(.{ .name = "n", .kind = .norm, .cin = 2, .cout = 2 }, w1[0..2], out1[0..2])); +} + +test "picture reference config: encoder tiling must stay on" { + var a = arena(); + defer a.deinit(); + try r.checkTiling(a.allocator(), "{\"vae_encoder_tiling\": 1}"); + try testing.expectError(error.H3UnsupportedVae, r.checkTiling(a.allocator(), "{\"vae_encoder_tiling\": 0}")); + try testing.expectError(error.H3BadVaeConfig, r.checkTiling(a.allocator(), "{\"vae_decoder_tiling\": 1}")); +} + +test "picture reference clean rows: sampled as fp16, normalised, the full grid cropped top-left to even, patchified" { + var a = arena(); + defer a.deinit(); + const x = a.allocator(); + var c: vae.Config = .{ .mean = undefined, .std = undefined, .tile = 256, .overlap = 64, .rope_theta = 100 }; + for (&c.mean, &c.std, 0..) |*mu, *sd, i| { + mu.* = @as(f32, @floatFromInt(i)) * 0.1 - 1; + sd.* = 0.5 + @as(f32, @floatFromInt(i)) * 0.05; + } + const full: r.Grid = .{ .rows = 3, .columns = 5 }; + const n = 24 * 15; + const m = try x.alloc(f32, 2 * n); + const noise = try x.alloc(f32, n); + for (m, 0..) |*v, i| v.* = @as(f32, @floatFromInt(i % 97)) * 0.0137 - 0.5; + for (noise, 0..) |*v, i| v.* = @as(f32, @floatFromInt(i % 13)) * 0.21 - 1.3; + const got = try r.clean(x, &c, m, full, noise); + try testing.expectEqual(r.Grid{ .rows = 2, .columns = 4 }, got.grid); + try testing.expectEqual(@as(usize, 2 * 96), got.rows.len); + for (0..2) |pc| for (0..24) |ch| for (0..2) |dy| for (0..2) |dx| { + const at = (ch * 3 + dy) * 5 + 2 * pc + dx; + const s = @exp(0.5 * std.math.clamp(m[n + at], -30.0, 20.0)); + const kept: f32 = @floatCast(@as(f16, @floatCast(m[at] + s * noise[at]))); + try testing.expectEqual((kept - c.mean[ch]) / c.std[ch], got.rows[pc * 96 + ch * 4 + dy * 2 + dx]); + }; + try testing.expectError(error.H3BadLatentLength, r.clean(x, &c, m[1..], full, noise)); + try testing.expectError(error.H3ReferenceTooSmall, r.clean(x, &c, m[0 .. 2 * 24 * 5], .{ .rows = 1, .columns = 5 }, noise[0 .. 24 * 5])); +} + +test "picture reference anchors: 0.999 of the clean row and 1 - 0.999 in fp32 of the noise" { + try testing.expectEqual(@as(f64, 1) - @as(f64, @as(f32, 0.999)), @as(f64, r.anchor_noise)); + try testing.expect(r.anchor_noise != @as(f32, 0.001)); + var out: [2]f32 = undefined; + try r.anchors(&.{ 2, -1 }, &.{ 4, 0.5 }, &out); + try testing.expectEqual(@as(f32, 0.999) * 2 + r.anchor_noise * 4, out[0]); + try testing.expectEqual(@as(f32, 0.999) * -1 + r.anchor_noise * 0.5, out[1]); + try testing.expectError(error.H3BadLatentLength, r.anchors(&.{1}, &.{ 1, 2 }, &out)); +} From a124b9d6e580c0c1a6f9ad6013666fd993aeedf0 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:16:21 +0000 Subject: [PATCH 014/265] h3: MiniMax-H3-Image's edit encoder on Metal in fp32, tf-h3-image-encoder and its selftest --- zig/build/h3_host.zig | 1 + zig/build/h3_image_encoder.zig | 23 ++ zig/build/h3_metal.zig | 1 + zig/kernels/metal/h3/h3_image_encoder.metal | 149 ++++++++ zig/kernels/metal/h3/image_encoder.zig | 3 + zig/src/families/h3/image_encoder.zig | 362 ++++++++++++++++++++ zig/tests/h3_image_encoder.zig | 122 +++++++ zig/tests/h3_image_encoder_selftest.zig | 305 +++++++++++++++++ 8 files changed, 966 insertions(+) create mode 100644 zig/build/h3_image_encoder.zig create mode 100644 zig/kernels/metal/h3/h3_image_encoder.metal create mode 100644 zig/kernels/metal/h3/image_encoder.zig create mode 100644 zig/src/families/h3/image_encoder.zig create mode 100644 zig/tests/h3_image_encoder.zig create mode 100644 zig/tests/h3_image_encoder_selftest.zig diff --git a/zig/build/h3_host.zig b/zig/build/h3_host.zig index 3cb413670f0..31db6c3c0fa 100644 --- a/zig/build/h3_host.zig +++ b/zig/build/h3_host.zig @@ -15,6 +15,7 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu metal.linkFramework("Foundation", .{}); metal.linkFramework("IOSurface", .{}); metal.linkSystemLibrary("objc", .{}); + @import("h3_image_encoder.zig").compileHost(b, target, metal); const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); const kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/kernels.zig") }); const model = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels } } }); diff --git a/zig/build/h3_image_encoder.zig b/zig/build/h3_image_encoder.zig new file mode 100644 index 00000000000..22eb497a781 --- /dev/null +++ b/zig/build/h3_image_encoder.zig @@ -0,0 +1,23 @@ +//! MiniMax-H3-Image's edit encoder: `tf-h3-image-encoder`, whose Metal is compiled at load, and its host compile check. +const std = @import("std"); + +fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module) *std.Build.Module { + const st = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target, .optimize = optimize }); + const kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/image_encoder.zig") }); + const encoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "safetensors", .module = st }, .{ .name = "h3_image_encoder_kernels", .module = kernels } } }); + const codec = b.createModule(.{ .root_source_file = b.path("zig/src/core/picture/picture.zig"), .target = target, .optimize = optimize, .link_libc = true }); + const noise = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/noise.zig"), .target = target, .optimize = optimize }); + return b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3_image_encoder", .module = encoder }, .{ .name = "picture_codec", .module = codec }, .{ .name = "torch_noise", .module = noise } } }); +} + +/// `zig build tf-h3-image-encoder`: a reference picture to its clean rows, or `selftest`; needs no Metal compiler. +pub fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module) void { + const exe = b.addExecutable(.{ .name = "tf-h3-image-encoder", .root_module = module(b, target, optimize, metal) }); + b.step("tf-h3-image-encoder", "MiniMax-H3-Image's edit encoder on Metal: a reference to its clean rows, or its selftest").dependOn(&b.addInstallArtifact(exe, .{}).step); +} + +/// `zig build compile-h3-image-encoder`: the tool compiled in Debug, no shader compiled or run. +pub fn compileHost(b: *std.Build, target: std.Build.ResolvedTarget, metal: *std.Build.Module) void { + const exe = b.addExecutable(.{ .name = "tf-h3-image-encoder-host-compile", .root_module = module(b, target, .Debug, metal) }); + b.step("compile-h3-image-encoder", "Compile tf-h3-image-encoder without compiling or running its shaders").dependOn(&exe.step); +} diff --git a/zig/build/h3_metal.zig b/zig/build/h3_metal.zig index d75282d845b..e253bed25e6 100644 --- a/zig/build/h3_metal.zig +++ b/zig/build/h3_metal.zig @@ -23,4 +23,5 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3", .module = h3_mod }, .{ .name = "core", .module = h3_core } }, }) }); b.step("tf-h3-image", "MiniMax-H3-Image's Metal transformer on a picture case: six distilled steps, teacher-forced and gated").dependOn(&b.addInstallArtifact(h3_image, .{}).step); + @import("h3_image_encoder.zig").tool(b, target, optimize, metal); } diff --git a/zig/kernels/metal/h3/h3_image_encoder.metal b/zig/kernels/metal/h3/h3_image_encoder.metal new file mode 100644 index 00000000000..0ca11cff011 --- /dev/null +++ b/zig/kernels/metal/h3/h3_image_encoder.metal @@ -0,0 +1,149 @@ +// MiniMax-H3-Image's edit encoder (the VAE's CNN on one frame) in fp32; each picture tensor is [pixels, channels]. + +#include +#include +using namespace metal; + +#define TF_UNROLL_HIE _Pragma("clang loop unroll(full)") + +// A convolution: input and output sides, channels, the weight row length, the kernel side, stride, padding, add. +struct HieConv { + uint h; + uint w; + uint oh; + uint ow; + uint cin; + uint cout; + uint ldw; + uint k; + uint stride; + uint pad; + uint add; +}; + +// Index i of an axis of n read with reflect padding (-1 reads 1, n reads n - 2). +inline int hie_reflect(int i, int n) { + return i < 0 ? -i : (i >= n ? 2 * n - 2 - i : i); +} + +// y = conv(x) + b (+ r), x [h * w, cin], w [k * k, cin, ldw]: 64 pixels by 64 channels a group, 16 by 32 a simdgroup. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void hie_conv( + const device float* x [[buffer(0)]], const device float* wt [[buffer(1)]], const device float* b [[buffer(2)]], + const device float* r [[buffer(3)]], device float* y [[buffer(4)]], constant HieConv& s [[buffer(5)]], + uint2 tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float smem[64 * 64]; + threadgroup float* at = smem; + threadgroup float* bt = smem + 64 * 32; + const uint p0 = tg.x * 64; + const uint n0 = tg.y * 64; + const uint pixels = s.oh * s.ow; + // this thread's loads: pixel row t / 4, channels (t % 4) * 8 + 8; weight row t / 8, columns (t % 8) * 8 + 8 + const uint ar = t / 4; + const uint ak = (t % 4) * 8; + const uint br = t / 8; + const uint bc = (t % 8) * 8; + const bool live = p0 + ar < pixels; + const int oy = live ? int((p0 + ar) / s.ow) : 0; + const int ox = live ? int((p0 + ar) % s.ow) : 0; + const uint sm = (sg % 4) * 16; + const uint sn = (sg / 4) * 32; + simdgroup_float8x8 acc[2][4]; + TF_UNROLL_HIE for (uint i = 0; i < 2; i++) TF_UNROLL_HIE for (uint j = 0; j < 4; j++) + acc[i][j] = simdgroup_float8x8(0.0f); + for (uint tap = 0; tap < s.k * s.k; tap++) { + const int iy = hie_reflect(oy * int(s.stride) + int(tap / s.k) - int(s.pad), int(s.h)); + const int ix = hie_reflect(ox * int(s.stride) + int(tap % s.k) - int(s.pad), int(s.w)); + const device float* src = x + (uint(iy) * s.w + uint(ix)) * s.cin; + const device float* ws = wt + tap * s.cin * s.ldw + n0 + bc; + for (uint c0 = 0; c0 < s.cin; c0 += 32) { + TF_UNROLL_HIE for (uint j = 0; j < 8; j++) { + const uint c = c0 + ak + j; + at[ar * 32 + ak + j] = (live && c < s.cin) ? src[c] : 0.0f; + } + const uint kr = c0 + br; + TF_UNROLL_HIE for (uint j = 0; j < 8; j++) bt[br * 64 + bc + j] = kr < s.cin ? ws[kr * s.ldw + j] : 0.0f; + threadgroup_barrier(mem_flags::mem_threadgroup); + TF_UNROLL_HIE for (uint kk = 0; kk < 32; kk += 8) { + simdgroup_float8x8 am[2]; + simdgroup_float8x8 bm[4]; + TF_UNROLL_HIE for (uint i = 0; i < 2; i++) simdgroup_load(am[i], at + (sm + i * 8) * 32 + kk, 32); + TF_UNROLL_HIE for (uint j = 0; j < 4; j++) simdgroup_load(bm[j], bt + kk * 64 + sn + j * 8, 64); + TF_UNROLL_HIE for (uint i = 0; i < 2; i++) TF_UNROLL_HIE for (uint j = 0; j < 4; j++) + simdgroup_multiply_accumulate(acc[i][j], am[i], bm[j], acc[i][j]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + TF_UNROLL_HIE for (uint i = 0; i < 2; i++) TF_UNROLL_HIE for (uint j = 0; j < 4; j++) + simdgroup_store(acc[i][j], smem + (sm + i * 8) * 64 + sn + j * 8, 64); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint e = t; e < 64 * 64; e += 256) { + const uint p = p0 + e / 64; + const uint n = n0 + e % 64; + if (p >= pixels || n >= s.cout) continue; + float v = smem[e] + b[n]; + if (s.add != 0) v += r[p * s.cout + n]; + y[p * s.cout + n] = v; + } +} + +// GroupNorm's 32 groups over `pixels` of x [pixels, channels], summed in chunks of `chunk` pixels. +struct HieGroup { + uint pixels; + uint channels; + uint chunk; + uint chunks; + uint centered; + float eps; +}; + +// part [chunks, channels]: each channel's sum over one chunk of x, or (centered) of (x - its group's mean)^2. +[[max_total_threads_per_threadgroup(1024)]] [[kernel]] void hie_group_part( + const device float* x [[buffer(0)]], const device float* stats [[buffer(1)]], device float* part [[buffer(2)]], + constant HieGroup& g [[buffer(3)]], uint chunk [[threadgroup_position_in_grid]], + uint c [[thread_position_in_threadgroup]]) { + if (c >= g.channels) return; + const float mean = g.centered != 0 ? stats[c / (g.channels / 32)] : 0.0f; + const uint last = min((chunk + 1) * g.chunk, g.pixels); + float sum = 0.0f; + for (uint p = chunk * g.chunk; p < last; p++) { + const float v = x[p * g.channels + c] - mean; + sum += g.centered != 0 ? v * v : v; + } + part[chunk * g.channels + c] = sum; +} + +// stats: a group's mean at its index, or (centered) 1 / sqrt(variance + eps) at 32 + its index; a simdgroup a group. +[[max_total_threads_per_threadgroup(1024)]] [[kernel]] void hie_group_finish( + const device float* part [[buffer(0)]], device float* stats [[buffer(1)]], constant HieGroup& g [[buffer(2)]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + const uint per = g.channels / 32; + float sum = 0.0f; + for (uint i = lane; i < g.chunks * per; i += 32) sum += part[(i / per) * g.channels + sg * per + i % per]; + sum = simd_sum(sum); + if (lane != 0) return; + const float v = sum / float(g.pixels * per); + if (g.centered != 0) { + stats[32 + sg] = 1.0f / sqrt(v + g.eps); + } else { + stats[sg] = v; + } +} + +struct HieNorm { + uint pixels; + uint channels; +}; + +// y = SiLU((x - mean) * rstd * gamma + beta) with x's group statistics. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void hie_norm_silu( + const device float* x [[buffer(0)]], const device float* stats [[buffer(1)]], + const device float* gamma [[buffer(2)]], const device float* beta [[buffer(3)]], device float* y [[buffer(4)]], + constant HieNorm& n [[buffer(5)]], uint2 i [[thread_position_in_grid]]) { + if (i.x >= n.channels || i.y >= n.pixels) return; + const uint g = i.x / (n.channels / 32); + const uint at = i.y * n.channels + i.x; + const float v = (x[at] - stats[g]) * stats[32 + g] * gamma[i.x] + beta[i.x]; + y[at] = v / (1.0f + exp(-v)); +} diff --git a/zig/kernels/metal/h3/image_encoder.zig b/zig/kernels/metal/h3/image_encoder.zig new file mode 100644 index 00000000000..2a0c9339dfe --- /dev/null +++ b/zig/kernels/metal/h3/image_encoder.zig @@ -0,0 +1,3 @@ +//! MiniMax-H3-Image's edit encoder kernels, compiled at load from source on any Apple GPU. +pub const source = @embedFile("h3_image_encoder.metal"); +pub const names = [_][:0]const u8{ "hie_conv", "hie_group_part", "hie_group_finish", "hie_norm_silu" }; diff --git a/zig/src/families/h3/image_encoder.zig b/zig/src/families/h3/image_encoder.zig new file mode 100644 index 00000000000..658a14cd545 --- /dev/null +++ b/zig/src/families/h3/image_encoder.zig @@ -0,0 +1,362 @@ +//! MiniMax-H3-Image's edit encoder on Metal in fp32: a reference's tiles through the VAE's CNN to blended moments. +const std = @import("std"); +const mtl = @import("metal"); +const st = @import("safetensors"); +const kernels = @import("h3_image_encoder_kernels"); +pub const reference = @import("picture_reference.zig"); +pub const vae = @import("picture_vae.zig"); +pub const picture = @import("picture.zig"); + +const Item = reference.Item; +const moments = reference.moments; +const cell = vae.cell_pixels; + +/// The largest tile side the scratch is planned for (the release's is 256). +pub const max_tile = 512; +/// Pixels a GroupNorm part sums. +pub const chunk = 256; + +/// A buffer and a byte offset into it. +pub const Ref = struct { + buf: mtl.Buffer, + off: usize = 0, + + pub fn floats(r: Ref, n: usize) []f32 { + return @as([*]f32, @ptrCast(@alignCast(r.buf.contents() + r.off)))[0..n]; + } +}; + +pub const Timing = struct { wall: f64 = 0, gpu: f64 = 0 }; + +/// The four pipelines, compiled from source now with precise fp32 functions. +pub const Kernels = struct { + lib: mtl.Library, + p: [kernels.names.len]mtl.Pipeline, + + pub fn init(device: mtl.Device) !Kernels { + var options = mtl.CompileOptions.mlx(); + options.math_functions = .precise; + var k: Kernels = .{ .lib = try mtl.Library.fromSource(device, kernels.source, options), .p = undefined }; + errdefer k.lib.deinit(); + var made: usize = 0; + errdefer for (k.p[0..made]) |p| p.deinit(); + for (kernels.names, 0..) |name, i| { + k.p[i] = try mtl.Pipeline.init(device, k.lib, name, false); + made += 1; + } + return k; + } + + pub fn deinit(k: *Kernels) void { + for (k.p) |p| p.deinit(); + k.lib.deinit(); + } + + fn get(k: *const Kernels, comptime name: []const u8) mtl.Pipeline { + inline for (kernels.names, 0..) |n, i| if (comptime std.mem.eql(u8, n, name)) return k.p[i]; + @compileError("no pipeline " ++ name); + } +}; + +fn bind(e: mtl.ComputeEncoder, p: mtl.Pipeline, refs: []const Ref, params: anytype) void { + e.setPipeline(p); + for (refs, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(params, refs.len); +} + +/// A layer's weights on the GPU: a convolution's [taps, cin, ldw] and bias, or a norm's gamma and beta. +pub const Layer = struct { item: Item, w: Ref, b: Ref }; + +/// y = conv(x) + b (+ r) at h x w input; `down`: stride 2, the padded row and column h, w read as h - 2, w - 2. +pub fn conv(e: mtl.ComputeEncoder, k: *const Kernels, l: Layer, x: Ref, y: Ref, r: ?Ref, h: usize, w: usize, down: bool) void { + const side: u32 = if (l.item.kind == .conv3) 3 else 1; + const oh = if (down) h / 2 else h; + const ow = if (down) w / 2 else w; + const shape = extern struct { h: u32, w: u32, oh: u32, ow: u32, cin: u32, cout: u32, ldw: u32, k: u32, stride: u32, pad: u32, add: u32 }{ + .h = @intCast(h), + .w = @intCast(w), + .oh = @intCast(oh), + .ow = @intCast(ow), + .cin = @intCast(l.item.cin), + .cout = @intCast(l.item.cout), + .ldw = @intCast(reference.rowLength(l.item.cout)), + .k = side, + .stride = if (down) 2 else 1, + .pad = if (side == 3 and !down) 1 else 0, + .add = @intFromBool(r != null), + }; + bind(e, k.get("hie_conv"), &.{ x, l.w, l.b, r orelse y, y }, shape); + e.dispatchGroups(mtl.Size.of((oh * ow + 63) / 64, shape.ldw / 64, 1), mtl.Size.of(256, 1, 1)); +} + +/// GroupNorm's parts for `pixels`. +pub fn chunks(pixels: usize) usize { + return (pixels + chunk - 1) / chunk; +} + +/// y = SiLU(GroupNorm(x)) over `pixels` of x [pixels, channels]: two passes of parts and their finish, then the map. +pub fn normSilu(e: mtl.ComputeEncoder, k: *const Kernels, l: Layer, x: Ref, y: Ref, stats: Ref, part: Ref, pixels: usize) void { + const c = l.item.cin; + for ([_]u32{ 0, 1 }) |centered| { + const g = extern struct { pixels: u32, channels: u32, chunk: u32, chunks: u32, centered: u32, eps: f32 }{ + .pixels = @intCast(pixels), + .channels = @intCast(c), + .chunk = chunk, + .chunks = @intCast(chunks(pixels)), + .centered = centered, + .eps = vae.group_eps, + }; + bind(e, k.get("hie_group_part"), &.{ x, stats, part }, g); + e.dispatchGroups(mtl.Size.of(chunks(pixels), 1, 1), mtl.Size.of(c, 1, 1)); + bind(e, k.get("hie_group_finish"), &.{ part, stats }, g); + e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(32 * reference.groups, 1, 1)); + } + const n = extern struct { pixels: u32, channels: u32 }{ .pixels = @intCast(pixels), .channels = @intCast(c) }; + bind(e, k.get("hie_norm_silu"), &.{ x, stats, l.w, l.b, y }, n); + e.dispatchThreads(mtl.Size.of(c, pixels, 1), mtl.Size.of(32, 8, 1)); +} + +/// A block (norm1, conv1, norm2, conv2, any shortcut) on t[x] at h x w; returns the index of the t it wrote. +pub fn block(e: mtl.ComputeEncoder, k: *const Kernels, ls: []const Layer, t: [3]Ref, x: usize, stats: Ref, part: Ref, h: usize, w: usize) usize { + const n = (x + 1) % 3; + const o = (x + 2) % 3; + normSilu(e, k, ls[0], t[x], t[n], stats, part, h * w); + conv(e, k, ls[1], t[n], t[o], null, h, w, false); + normSilu(e, k, ls[2], t[o], t[n], stats, part, h * w); + if (ls.len == 5) { + // the shortcut into o, then conv2 adds itself onto it in place + conv(e, k, ls[4], t[x], t[o], null, h, w, false); + conv(e, k, ls[3], t[n], t[o], t[o], h, w, false); + return o; + } + conv(e, k, ls[3], t[n], t[x], t[x], h, w, false); + return x; +} + +/// Floats a layer takes in the weights buffer, each part aligned to 64. +fn footprint(it: Item) [2]usize { + if (it.kind == .norm) return .{ std.mem.alignForward(usize, it.cin, 64), std.mem.alignForward(usize, it.cin, 64) }; + return .{ reference.taps(it) * it.cin * reference.rowLength(it.cout), std.mem.alignForward(usize, it.cout, 64) }; +} + +/// The layers of `items` packed into one shared buffer from `source.get(name)` (a []align(1) const f32 or null). +pub fn packLayers(gpa: std.mem.Allocator, device: mtl.Device, list: []const Item, source: anytype) !struct { mtl.Buffer, []Layer } { + var total: usize = 0; + for (list) |it| { + const f = footprint(it); + total += f[0] + f[1]; + } + const buf = try device.buffer(total * 4, mtl.ResourceOptions.shared); + errdefer buf.deinit(); + const all = @as([*]f32, @ptrCast(@alignCast(buf.contents())))[0..total]; + const layers = try gpa.alloc(Layer, list.len); + errdefer gpa.free(layers); + var at: usize = 0; + var name: [96]u8 = undefined; + for (list, layers) |it, *l| { + const f = footprint(it); + l.* = .{ .item = it, .w = .{ .buf = buf, .off = at * 4 }, .b = .{ .buf = buf, .off = (at + f[0]) * 4 } }; + const w = source.get(try std.fmt.bufPrint(&name, "{s}.weight", .{it.name})) orelse return error.H3MissingEncoderTensor; + const b = source.get(try std.fmt.bufPrint(&name, "{s}.bias", .{it.name})) orelse return error.H3MissingEncoderTensor; + if (b.len != it.cout) return error.H3BadEncoderTensor; + const wd = all[at..][0..f[0]]; + if (it.kind == .norm) { + if (w.len != it.cin) return error.H3BadEncoderTensor; + @memset(wd, 0); + for (wd[0..it.cin], w) |*d, v| d.* = v; + } else try reference.pack(it, w, wd); + @memset(all[at + f[0] ..][0..f[1]], 0); + for (all[at + f[0] ..][0..it.cout], b) |*d, v| d.* = v; + at += f[0] + f[1]; + } + return .{ buf, layers }; +} + +/// Tensors of a mapped checkpoint as float32 slices, for `packLayers`. +pub const FileSource = struct { + file: *const st.File, + + pub fn get(s: FileSource, name: []const u8) ?[]align(1) const f32 { + const t = s.file.get(name) orelse return null; + if (t.dtype != .f32) return null; + return std.mem.bytesAsSlice(f32, t.bytes); + } +}; + +pub const Encoder = struct { + gpa: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + k: Kernels, + weights: mtl.Buffer, + layers: []Layer, + /// The tile side the scratch holds. + tile: usize, + scratch: mtl.Buffer, + input: Ref, + t: [3]Ref, + stats: Ref, + part: Ref, + out: Ref, + + /// Pipelines, `arch`'s layers packed from `source`, and scratch for tiles up to `tile` a side. + pub fn init(gpa: std.mem.Allocator, device: mtl.Device, arch: reference.Arch, tile: usize, source: anytype) !*Encoder { + if (tile < 2 * cell or tile % cell != 0 or tile > max_tile) return error.H3BadTiles; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const list = try reference.items(arena.allocator(), arch); + const enc = try gpa.create(Encoder); + errdefer gpa.destroy(enc); + enc.* = undefined; + enc.gpa = gpa; + enc.device = device; + enc.tile = tile; + enc.queue = try device.queue(); + errdefer enc.queue.deinit(); + enc.k = try Kernels.init(device); + errdefer enc.k.deinit(); + enc.weights, enc.layers = try packLayers(gpa, device, list, source); + errdefer enc.weights.deinit(); + errdefer gpa.free(enc.layers); + // the names live in the arena; a forward reads kinds and widths only + for (enc.layers) |*l| l.item.name = ""; + try enc.plan(arch); + return enc; + } + + pub fn deinit(enc: *Encoder) void { + enc.scratch.deinit(); + enc.weights.deinit(); + enc.gpa.free(enc.layers); + enc.k.deinit(); + enc.queue.deinit(); + enc.gpa.destroy(enc); + } + + /// The tensors a tile needs at most: input, three activations, GroupNorm statistics and parts, moments. + fn plan(enc: *Encoder, arch: reference.Arch) !void { + var most: usize = 0; + var parts: usize = 0; + var cin = arch.widths[0]; + for (arch.widths, 0..) |w, l| { + const side = enc.tile >> @intCast(@min(l, reference.downsampled)); + const wide = @max(cin, w); + most = @max(most, side * side * wide); + parts = @max(parts, chunks(side * side) * wide); + cin = w; + } + const last = enc.tile / cell; + most = @max(most, last * last * moments); + const sizes = [_]usize{ enc.tile * enc.tile * 3, most, most, most, 64, parts, last * last * moments }; + var total: usize = 0; + for (sizes) |n| total += std.mem.alignForward(usize, n * 4, 256); + enc.scratch = try enc.device.buffer(total, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + var at: usize = 0; + const views = [_]*Ref{ &enc.input, &enc.t[0], &enc.t[1], &enc.t[2], &enc.stats, &enc.part, &enc.out }; + for (views, sizes) |v, n| { + v.* = .{ .buf = enc.scratch, .off = at }; + at += std.mem.alignForward(usize, n * 4, 256); + } + } + + /// One tile's moments [48, h / 16, w / 16] from its normalised pixels [h, w, 3]. + pub fn encodeTile(enc: *Encoder, pixels: []const f32, h: usize, w: usize, out: []f32) !Timing { + if (h < 2 * cell or w < 2 * cell or h % cell != 0 or w % cell != 0 or h > enc.tile or w > enc.tile) return error.H3BadTiles; + const lh = h / cell; + const lw = w / cell; + if (pixels.len != h * w * 3 or out.len != moments * lh * lw) return error.H3BadLatentLength; + @memcpy(enc.input.floats(pixels.len), pixels); + const started = mtl.clock.seconds(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = enc.queue.commandBuffer(); + const e = cb.compute(.serial); + const ls = enc.layers; + conv(e, &enc.k, ls[0], enc.input, enc.t[0], null, h, w, false); + var at: usize = 1; + var x: usize = 0; + var rh = h; + var rw = w; + for (0..reference.levels) |l| { + for (0..2) |_| { + const n: usize = if (ls[at].item.cin != ls[at + 1].item.cout) 5 else 4; + x = block(e, &enc.k, ls[at..][0..n], enc.t, x, enc.stats, enc.part, rh, rw); + at += n; + } + if (l < reference.downsampled) { + conv(e, &enc.k, ls[at], enc.t[x], enc.t[(x + 1) % 3], null, rh, rw, true); + at += 1; + x = (x + 1) % 3; + rh /= 2; + rw /= 2; + } + } + const n = (x + 1) % 3; + normSilu(e, &enc.k, ls[at], enc.t[x], enc.t[n], enc.stats, enc.part, rh * rw); + conv(e, &enc.k, ls[at + 1], enc.t[n], enc.t[x], null, rh, rw, false); + conv(e, &enc.k, ls[at + 2], enc.t[x], enc.out, null, rh, rw, false); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("h3 image encoder: a tile failed on the GPU: {s}", .{msg}); + return error.GpuFailure; + } + const got = enc.out.floats(lh * lw * moments); + for (0..lh * lw) |p| for (0..moments) |c| { + out[c * lh * lw + p] = got[p * moments + c]; + }; + return .{ .wall = mtl.clock.seconds() - started, .gpu = cb.gpuSeconds() }; + } + + /// A cropped picture's moments [48, height / 16, width / 16]: its tiles encoded, blended in latent cells. + pub fn encode(enc: *Encoder, a: std.mem.Allocator, c: *const vae.Config, image: []const f32, s: reference.Size, out: []f32) !Timing { + if (c.tile > enc.tile) return error.H3BadTiles; + const g = reference.fullGrid(s); + if (image.len != s.width * s.height * 3 or out.len != moments * g.rows * g.columns) return error.H3BadLatentLength; + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const x = arena.allocator(); + const rows = try vae.split(x, s.height, c.tile, c.overlap); + const cols = try vae.split(x, s.width, c.tile, c.overlap); + var blend = try vae.Assembler.init(x, try cells(x, rows), try cells(x, cols), moments, out); + const pixels = try x.alloc(f32, rows[0].len * cols[0].len * 3); + const tile = try x.alloc(f32, moments * (rows[0].len / cell) * (cols[0].len / cell)); + var sum: Timing = .{}; + for (rows, 0..) |r, ri| for (cols, 0..) |col, ci| { + for (0..r.len) |y| { + @memcpy(pixels[y * col.len * 3 ..][0 .. col.len * 3], image[((r.start + y) * s.width + col.start) * 3 ..][0 .. col.len * 3]); + } + const t = try enc.encodeTile(pixels[0 .. r.len * col.len * 3], r.len, col.len, tile[0 .. moments * (r.len / cell) * (col.len / cell)]); + sum.wall += t.wall; + sum.gpu += t.gpu; + try blend.place(ri, ci, tile[0 .. moments * (r.len / cell) * (col.len / cell)]); + }; + return sum; + } +}; + +/// Pixel spans in latent cells. +fn cells(a: std.mem.Allocator, spans: []const vae.Span) ![]vae.Span { + const out = try a.alloc(vae.Span, spans.len); + for (out, spans) |*o, s| o.* = .{ .start = s.start / cell, .len = s.len / cell, .overlap = s.overlap / cell }; + return out; +} + +/// The released encoder from a `vae/` folder: its config (encoder tiling on) and checkpoint, header checked first. +pub fn load(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8) !struct { *Encoder, vae.Config } { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const json = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(a, &.{ dir, "config.json" }), a, .limited(1 << 20)); + const c = try vae.config(a, json); + try reference.checkTiling(a, json); + var file = try st.File.openPrefixes(gpa, io, try std.fs.path.join(a, &.{ dir, "diffusion_pytorch_model.safetensors" }), &.{ "encoder.", "quant_conv." }); + defer file.close(io); + var culprit: []const u8 = ""; + reference.checkHeader(a, &file.names, &culprit) catch |err| { + std.log.err("h3 image encoder: {s} is missing or not at its released shape ({s})", .{ culprit, @errorName(err) }); + return err; + }; + return .{ try Encoder.init(gpa, device, reference.released, c.tile, FileSource{ .file = &file }), c }; +} diff --git a/zig/tests/h3_image_encoder.zig b/zig/tests/h3_image_encoder.zig new file mode 100644 index 00000000000..9a605fe959b --- /dev/null +++ b/zig/tests/h3_image_encoder.zig @@ -0,0 +1,122 @@ +//! tf-h3-image-encoder: MiniMax-H3-Image's edit encoder on Metal, a reference picture to its clean rows, or a selftest. +const std = @import("std"); +const mtl = @import("metal"); +const he = @import("h3_image_encoder"); +const codec = @import("picture_codec"); +const noise = @import("torch_noise"); +const selftest = @import("h3_image_encoder_selftest.zig"); + +const ref = he.reference; +const latent_channels = he.vae.latent_channels; + +const usage = + \\usage: tf-h3-image-encoder MODEL_DIR reference.png SEED OUT_PREFIX [CANVAS] + \\ tf-h3-image-encoder selftest + \\ MODEL_DIR the MiniMax-H3-Image folder; vae/ holds config.json and diffusion_pytorch_model.safetensors + \\ reference a PNG, read upright in RGB (any alpha dropped), resized so its short edge lies in 1024..2048 + \\ SEED the request's seed: the noise is torch.randn on one CPU generator seeded with it + \\ CANVAS WxH, the edit's canvas: the generator first draws the target's noise and this reference's anchor + \\ noise, as a one-reference edit does, and OUT_PREFIX.anchors.f32 is written too; without it the + \\ posterior's noise is the seed's first draw + \\Writes OUT_PREFIX.rows.f32 (the clean rows [rows, 96]), .moments.f32 ([48, h, w], before sampling), .grid.json. + \\selftest: each kernel on small synthetic weights against a float64 host reference; exit 1 on a miss. + \\ +; + +/// A PNG upright in RGB, as Pillow's convert("RGB") gives it: alpha dropped, not composited. +fn load(io: std.Io, a: std.mem.Allocator, path: []const u8) !codec.Rgb { + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(512 << 20)); + if (codec.sniff(bytes) != .png) return error.NotPng; + var s = try codec.png.decodeWithLimits(a, bytes, .{ .side = 1 << 15, .pixels = 1 << 26 }); + if (s.channels == 4) { + var i: usize = 3; + while (i < s.data.len) : (i += 4) s.data[i] = 255; + } + return codec.finish(a, s); +} + +/// CANVAS as width x height, both whole multiples of 32. +fn parseCanvas(text: []const u8) ?ref.Size { + const x = std.mem.indexOfScalar(u8, text, 'x') orelse return null; + const w = std.fmt.parseInt(usize, text[0..x], 10) catch return null; + const h = std.fmt.parseInt(usize, text[x + 1 ..], 10) catch return null; + if (w == 0 or h == 0 or w % 32 != 0 or h % 32 != 0 or w > 1 << 16 or h > 1 << 16) return null; + return .{ .width = w, .height = h }; +} + +fn write(io: std.Io, a: std.mem.Allocator, prefix: []const u8, suffix: []const u8, data: []const u8) !void { + const path = try std.fmt.allocPrint(a, "{s}{s}", .{ prefix, suffix }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = data }); +} + +pub fn main(init: std.process.Init) !u8 { + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + if (args.len == 2 and std.mem.eql(u8, args[1], "selftest")) return selftest.run(init.gpa, a); + if (args.len != 5 and args.len != 6) { + std.debug.print("{s}", .{usage}); + return 2; + } + const seed = std.fmt.parseInt(u64, args[3], 10) catch { + std.debug.print("SEED must be a whole number\n{s}", .{usage}); + return 2; + }; + const canvas: ?ref.Size = if (args.len == 6) parseCanvas(args[5]) orelse { + std.debug.print("CANVAS must be WxH, both multiples of 32\n", .{}); + return 2; + } else null; + + const rgb = load(io, a, args[2]) catch |err| { + std.debug.print("{s}: {s}\n", .{ args[2], if (err == error.NotPng) "not a PNG" else @errorName(err) }); + return 2; + }; + const size = ref.bounded(rgb.width, rgb.height, ref.vae_bound) catch |err| { + std.debug.print("{s}: {d}x{d} is refused: {s}\n", .{ args[2], rgb.width, rgb.height, @errorName(err) }); + return 2; + }; + const same = size.width == rgb.width and size.height == rgb.height; + const pixels = if (same) rgb.pixels else try codec.resample.resizeWith(a, .pillow, .lanczos, .of(rgb.pixels, rgb.width, rgb.height), size.width, size.height); + const cropped = try ref.cropped(size); + const image = try a.alloc(f32, cropped.width * cropped.height * 3); + _ = try ref.input(pixels, size.width, size.height, image); + const full = ref.fullGrid(cropped); + const grid = try ref.evenGrid(full); + + // one generator, drawn in the edit's order: target, the reference's anchor, then the posterior on the full grid + var gen = noise.Twister.init(seed); + var anchor_noise: ?[]f32 = null; + if (canvas) |c| { + noise.draw(&gen, try a.alloc(f32, latent_channels * (c.height / 16) * (c.width / 16))); + anchor_noise = try a.alloc(f32, latent_channels * grid.rows * grid.columns); + noise.draw(&gen, anchor_noise.?); + } + const posterior = try a.alloc(f32, latent_channels * full.rows * full.columns); + noise.draw(&gen, posterior); + + const device = try mtl.Device.init(); + defer device.deinit(); + const loading = mtl.clock.seconds(); + const enc, const config = try he.load(init.gpa, io, device, try std.fs.path.join(a, &.{ args[1], "vae" })); + defer enc.deinit(); + const loaded = mtl.clock.seconds() - loading; + const moments = try a.alloc(f32, ref.moments * full.rows * full.columns); + const took = try enc.encode(a, &config, image, cropped, moments); + const clean = try ref.clean(a, &config, moments, full, posterior); + + const prefix = args[4]; + try write(io, a, prefix, ".rows.f32", std.mem.sliceAsBytes(clean.rows)); + try write(io, a, prefix, ".moments.f32", std.mem.sliceAsBytes(moments)); + const json = try std.fmt.allocPrint(a, "{{\"rows\": {d}, \"columns\": {d}, \"moment_rows\": {d}, \"moment_columns\": {d}, \"width\": {d}, \"height\": {d}, \"seed\": {d}}}\n", .{ grid.rows, grid.columns, full.rows, full.columns, size.width, size.height, seed }); + try write(io, a, prefix, ".grid.json", json); + if (anchor_noise) |z| { + const noise_rows = try a.alloc(f32, z.len); + try he.picture.patchify(z, grid, noise_rows); + const out = try a.alloc(f32, z.len); + try ref.anchors(clean.rows, noise_rows, out); + try write(io, a, prefix, ".anchors.f32", std.mem.sliceAsBytes(out)); + } + std.debug.print("{s}: {d}x{d} reference, VAE copy {d}x{d}, encoded {d}x{d}, grid {d} x {d} ({d} rows); loaded in {d:.1} s, encoded in {d:.2} s wall, {d:.2} s GPU\n", .{ device.name(), rgb.width, rgb.height, size.width, size.height, cropped.width, cropped.height, grid.rows, grid.columns, clean.rows.len / he.picture.row_width, loaded, took.wall, took.gpu }); + std.debug.print("wrote {s}.rows.f32, .moments.f32, .grid.json{s}\n", .{ prefix, if (anchor_noise != null) ", .anchors.f32" else "" }); + return 0; +} diff --git a/zig/tests/h3_image_encoder_selftest.zig b/zig/tests/h3_image_encoder_selftest.zig new file mode 100644 index 00000000000..95d9e306772 --- /dev/null +++ b/zig/tests/h3_image_encoder_selftest.zig @@ -0,0 +1,305 @@ +//! tf-h3-image-encoder selftest: each kernel on small synthetic weights against a float64 host reference, gated. +const std = @import("std"); +const mtl = @import("metal"); +const he = @import("h3_image_encoder"); + +const ref = he.reference; +const vae = he.vae; +const Item = ref.Item; + +/// Bounds fixed before any run: the worst |GPU - host| over the case's largest |host|. +pub const op_bound: f64 = 1e-5; +pub const encode_bound: f64 = 1e-4; +/// The fp16 posterior samples: one fp16 step at the largest sample's magnitude (a step near zero is far finer). +pub const sample_bound: f64 = 1.0 / 1024.0; + +/// Widths that change where the release's do (levels 1, 3, 5), with 1 to 4 channels a group. +const small: ref.Arch = .{ .widths = .{ 32, 64, 64, 96, 96, 128 } }; + +/// Synthetic tensors by name, as `packLayers` reads a checkpoint. +const Weights = struct { + map: std.StringHashMapUnmanaged([]f32) = .empty, + + pub fn get(w: Weights, name: []const u8) ?[]align(1) const f32 { + return w.map.get(name); + } + + fn of(w: Weights, it: Item, part: []const u8) []const f32 { + var buf: [96]u8 = undefined; + return w.map.get(std.fmt.bufPrint(&buf, "{s}.{s}", .{ it.name, part }) catch unreachable).?; + } +}; + +fn uniform(a: std.mem.Allocator, rng: std.Random, n: usize, centre: f32, scale: f32) ![]f32 { + const out = try a.alloc(f32, n); + for (out) |*v| v.* = centre + scale * (rng.float(f32) * 2 - 1); + return out; +} + +/// Kernels at about 1.7 / sqrt(fan in) in all three time slices, small biases, norms near 1 and 0. +fn weights(a: std.mem.Allocator, rng: std.Random, list: []const Item) !Weights { + var w: Weights = .{}; + for (list) |it| { + const fan: f32 = @floatFromInt(it.cin * ref.taps(it)); + const n = if (it.kind == .norm) it.cin else it.cout * it.cin * (if (it.kind == .conv3) @as(usize, 27) else 1); + const kernel = if (it.kind == .norm) try uniform(a, rng, n, 1, 0.2) else try uniform(a, rng, n, 0, 1.7 / @sqrt(fan)); + try w.map.put(a, try std.fmt.allocPrint(a, "{s}.weight", .{it.name}), kernel); + try w.map.put(a, try std.fmt.allocPrint(a, "{s}.bias", .{it.name}), try uniform(a, rng, it.cout, 0, if (it.kind == .norm) 0.2 else 0.1)); + } + return w; +} + +/// fp64 convolution of x [h * w, cin] with a kernel's last time slice, reflect-padded by one (or the downsample's). +fn hostConv(a: std.mem.Allocator, it: Item, ws: Weights, x: []const f64, h: usize, w: usize, down: bool, r: ?[]const f64) ![]f64 { + const k: usize = if (it.kind == .conv3) 3 else 1; + const kw = ws.of(it, "weight"); + const b = ws.of(it, "bias"); + const oh = if (down) h / 2 else h; + const ow = if (down) w / 2 else w; + const stride: isize = if (down) 2 else 1; + const pad: isize = if (k == 3 and !down) 1 else 0; + const wt = try a.alloc(f64, k * k * it.cin * it.cout); + for (0..it.cout) |co| for (0..it.cin) |ci| for (0..k * k) |tap| { + wt[(tap * it.cin + ci) * it.cout + co] = if (k == 3) kw[((co * it.cin + ci) * 3 + 2) * 9 + tap] else kw[co * it.cin + ci]; + }; + const y = try a.alloc(f64, oh * ow * it.cout); + for (0..oh) |oy| for (0..ow) |ox| { + const acc = y[(oy * ow + ox) * it.cout ..][0..it.cout]; + for (acc, b) |*v, bias| v.* = bias; + for (0..k * k) |tap| { + const iy = ref.reflect(@as(isize, @intCast(oy)) * stride + @as(isize, @intCast(tap / k)) - pad, h); + const ix = ref.reflect(@as(isize, @intCast(ox)) * stride + @as(isize, @intCast(tap % k)) - pad, w); + for (0..it.cin) |ci| { + const xv = x[(iy * w + ix) * it.cin + ci]; + for (acc, wt[(tap * it.cin + ci) * it.cout ..][0..it.cout]) |*v, wv| v.* += xv * wv; + } + } + if (r) |res| for (acc, res[(oy * ow + ox) * it.cout ..][0..it.cout]) |*v, rv| { + v.* += rv; + }; + }; + return y; +} + +/// fp64 SiLU(GroupNorm(x)) over x [pixels, channels]: 32 groups, biased variance, eps 1e-6. +fn hostNorm(a: std.mem.Allocator, it: Item, ws: Weights, x: []const f64, pixels: usize) ![]f64 { + const c = it.cin; + const per = c / ref.groups; + const g = ws.of(it, "weight"); + const b = ws.of(it, "bias"); + const y = try a.alloc(f64, x.len); + for (0..ref.groups) |gr| { + var sum: f64 = 0; + for (0..pixels) |p| for (0..per) |j| { + sum += x[p * c + gr * per + j]; + }; + const n: f64 = @floatFromInt(pixels * per); + const mean = sum / n; + var sq: f64 = 0; + for (0..pixels) |p| for (0..per) |j| { + const d = x[p * c + gr * per + j] - mean; + sq += d * d; + }; + const rstd = 1 / @sqrt(sq / n + vae.group_eps); + for (0..pixels) |p| for (0..per) |j| { + const at = p * c + gr * per + j; + const v = (x[at] - mean) * rstd * @as(f64, g[gr * per + j]) + @as(f64, b[gr * per + j]); + y[at] = v / (1 + @exp(-v)); + }; + } + return y; +} + +/// fp64 block: items norm1, conv1, norm2, conv2 and any shortcut. +fn hostBlock(a: std.mem.Allocator, ls: []const Item, ws: Weights, x: []const f64, h: usize, w: usize) ![]f64 { + const n1 = try hostNorm(a, ls[0], ws, x, h * w); + const c1 = try hostConv(a, ls[1], ws, n1, h, w, false, null); + const n2 = try hostNorm(a, ls[2], ws, c1, h * w); + const skip = if (ls.len == 5) try hostConv(a, ls[4], ws, x, h, w, false, null) else x; + return hostConv(a, ls[3], ws, n2, h, w, false, skip); +} + +/// fp64 tile: pixels [h, w, 3] to moments [48, h / 16, w / 16], rounded once to fp32. +fn hostTile(a: std.mem.Allocator, list: []const Item, ws: Weights, pixels: []const f32, h: usize, w: usize, out: []f32) !void { + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const x = arena.allocator(); + const in = try x.alloc(f64, pixels.len); + for (in, pixels) |*d, v| d.* = v; + var t = try hostConv(x, list[0], ws, in, h, w, false, null); + var at: usize = 1; + var rh = h; + var rw = w; + for (0..ref.levels) |l| { + for (0..2) |_| { + const n: usize = if (list[at].cin != list[at + 1].cout) 5 else 4; + t = try hostBlock(x, list[at..][0..n], ws, t, rh, rw); + at += n; + } + if (l < ref.downsampled) { + t = try hostConv(x, list[at], ws, t, rh, rw, true, null); + at += 1; + rh /= 2; + rw /= 2; + } + } + t = try hostConv(x, list[at + 1], ws, try hostNorm(x, list[at], ws, t, rh * rw), rh, rw, false, null); + t = try hostConv(x, list[at + 2], ws, t, rh, rw, false, null); + for (0..rh * rw) |p| for (0..ref.moments) |c| { + out[c * rh * rw + p] = @floatCast(t[p * ref.moments + c]); + }; +} + +var failed = false; + +/// One check's line: the worst |GPU - host| over the largest |host|, against its bound. +fn gate(name: []const u8, gpu: []const f32, host: []const f64, bound: f64) void { + var worst: f64 = 0; + var top: f64 = 1e-30; + for (gpu, host) |g, h| { + worst = @max(worst, @abs(@as(f64, g) - h)); + top = @max(top, @abs(h)); + } + const ok = std.math.isFinite(worst) and worst / top <= bound; + failed = failed or !ok; + std.debug.print("{s}: worst |gpu - host| {e:.3} over max |host| {d:.3} = {e:.3} (bound {e:.0}): {s}\n", .{ name, worst, top, worst / top, bound, if (ok) "pass" else "FAIL" }); +} + +const Gpu = struct { + device: mtl.Device, + queue: mtl.Queue, + k: he.Kernels, + + /// A shared buffer holding `data`, with room for `room` floats. + fn upload(g: *const Gpu, data: []const f32, room: usize) !he.Ref { + const r: he.Ref = .{ .buf = try g.device.buffer(@max(room, data.len, 64) * 4, mtl.ResourceOptions.shared) }; + @memcpy(r.floats(data.len), data); + return r; + } + + fn submit(_: *const Gpu, cb: mtl.CommandBuffer, e: mtl.ComputeEncoder) !void { + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.debug.print("GPU failure: {s}\n", .{msg}); + return error.GpuFailure; + } + } +}; + +fn wide(a: std.mem.Allocator, v: []const f32) ![]f64 { + const out = try a.alloc(f64, v.len); + for (out, v) |*o, x| o.* = x; + return out; +} + +/// `list` (a block, or one layer) on random h x w input against the host; `down` makes a conv the downsample. +fn layerCase(a: std.mem.Allocator, g: *const Gpu, rng: std.Random, name: []const u8, list: []const Item, h: usize, w: usize, down: bool, residual: bool) !void { + const ws = try weights(a, rng, list); + const buf, const layers = try he.packLayers(a, g.device, list, ws); + defer buf.deinit(); + const cin = list[0].cin; + const cout = list[list.len - 1].cout; + const most = h * w * @max(cin, list[1 % list.len].cout); + const x = try uniform(a, rng, h * w * cin, 0, 1); + const r = try uniform(a, rng, h * w * cout, 0, 1); + const t = [3]he.Ref{ try g.upload(x, most), try g.upload(r, most), try g.upload(&.{}, most) }; + const stats = try g.upload(&.{}, 64); + const part = try g.upload(&.{}, he.chunks(h * w) * @max(cin, cout)); + defer for (t ++ [2]he.Ref{ stats, part }) |b| b.buf.deinit(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = g.queue.commandBuffer(); + const e = cb.compute(.serial); + var out = t[1]; + var host: []f64 = undefined; + const in = try wide(a, x); + if (list.len >= 4) { + out = t[he.block(e, &g.k, layers, t, 0, stats, part, h, w)]; + host = try hostBlock(a, list, ws, in, h, w); + } else if (list[0].kind == .norm) { + he.normSilu(e, &g.k, layers[0], t[0], t[2], stats, part, h * w); + out = t[2]; + host = try hostNorm(a, list[0], ws, in, h * w); + } else { + he.conv(e, &g.k, layers[0], t[0], t[1], if (residual) t[1] else null, h, w, down); + host = try hostConv(a, list[0], ws, in, h, w, down, if (residual) try wide(a, r) else null); + } + try g.submit(cb, e); + gate(name, out.floats(host.len), host, op_bound); +} + +/// The small encoder on a picture in overlapping tiles, against the host's tiles and the same blend. +fn encodeCase(gpa: std.mem.Allocator, a: std.mem.Allocator, g: *const Gpu, rng: std.Random) !void { + const list = try ref.items(a, small); + const ws = try weights(a, rng, list); + const c: vae.Config = .{ .mean = @splat(0), .std = @splat(1), .tile = 64, .overlap = 32, .rope_theta = 100 }; + const s: ref.Size = .{ .width = 176, .height = 96 }; + const full = ref.fullGrid(s); + const image = try uniform(a, rng, s.width * s.height * 3, 0, 2); + const enc = try he.Encoder.init(gpa, g.device, small, c.tile, ws); + defer enc.deinit(); + const n = ref.moments * full.rows * full.columns; + const gpu = try a.alloc(f32, n); + const took = try enc.encode(a, &c, image, s, gpu); + const again = try a.alloc(f32, n); + _ = try enc.encode(a, &c, image, s, again); + const rows = try vae.split(a, s.height, c.tile, c.overlap); + const cols = try vae.split(a, s.width, c.tile, c.overlap); + const host = try a.alloc(f32, n); + var blend = try vae.Assembler.init(a, try spans(a, rows), try spans(a, cols), ref.moments, host); + const pixels = try a.alloc(f32, c.tile * c.tile * 3); + const tile = try a.alloc(f32, ref.moments * (c.tile / 16) * (c.tile / 16)); + for (rows, 0..) |r, ri| for (cols, 0..) |col, ci| { + for (0..r.len) |y| @memcpy(pixels[y * col.len * 3 ..][0 .. col.len * 3], image[((r.start + y) * s.width + col.start) * 3 ..][0 .. col.len * 3]); + try hostTile(a, list, ws, pixels[0 .. r.len * col.len * 3], r.len, col.len, tile); + try blend.place(ri, ci, tile); + }; + std.debug.print("tiled encode: {d}x{d} in {d} x {d} tiles of {d} (overlaps {d} and {d}), {d:.3} s GPU\n", .{ s.width, s.height, rows.len, cols.len, c.tile, cols[0].overlap, cols[cols.len - 2].overlap, took.gpu }); + gate("tiled encode, blended moments", gpu, try wide(a, host), encode_bound); + const same = std.mem.eql(u8, std.mem.sliceAsBytes(gpu), std.mem.sliceAsBytes(again)); + failed = failed or !same; + std.debug.print("tiled encode, a second run: {s}\n", .{if (same) "bit-identical: pass" else "differs: FAIL"}); + const z = try uniform(a, rng, n / 2, 0, 2); + const ours = try a.alloc(f32, n / 2); + const theirs = try a.alloc(f32, n / 2); + try vae.posterior(gpu[0 .. n / 2], gpu[n / 2 ..], z, ours); + try vae.posterior(host[0 .. n / 2], host[n / 2 ..], z, theirs); + var most: u32 = 0; + var moved: usize = 0; + for (ours, theirs) |o, t| { + const d = he.picture.ulps(@bitCast(@as(f16, @floatCast(o))), @bitCast(@as(f16, @floatCast(t)))); + most = @max(most, d); + moved += @intFromBool(d != 0); + } + std.debug.print("tiled encode, fp16 posterior samples: {d} of {d} differ, by at most {d} fp16 steps of their own\n", .{ moved, ours.len, most }); + gate("tiled encode, fp16 posterior samples", ours, try wide(a, theirs), sample_bound); +} + +fn spans(a: std.mem.Allocator, px: []const vae.Span) ![]vae.Span { + const out = try a.alloc(vae.Span, px.len); + for (out, px) |*o, s| o.* = .{ .start = s.start / 16, .len = s.len / 16, .overlap = s.overlap / 16 }; + return out; +} + +pub fn run(gpa: std.mem.Allocator, a: std.mem.Allocator) !u8 { + const device = try mtl.Device.init(); + defer device.deinit(); + var g: Gpu = .{ .device = device, .queue = try device.queue(), .k = try he.Kernels.init(device) }; + defer g.queue.deinit(); + defer g.k.deinit(); + std.debug.print("{s}: bounds {e:.0} a layer, {e:.0} a tiled encode, {e:.3} a sample\n", .{ device.name(), op_bound, encode_bound, sample_bound }); + var prng = std.Random.DefaultPrng.init(0x4833); + const rng = prng.random(); + try layerCase(a, &g, rng, "conv 3x3, reflect padding, 40 -> 72 at 13x17", &.{.{ .name = "c", .kind = .conv3, .cin = 40, .cout = 72 }}, 13, 17, false, false); + try layerCase(a, &g, rng, "downsample 3x3 stride 2, right and bottom reflected, 64 at 14x18", &.{.{ .name = "d", .kind = .conv3, .cin = 64, .cout = 64 }}, 14, 18, true, false); + try layerCase(a, &g, rng, "conv 1x1 plus a residual in place, 96 -> 48 at 10x6", &.{.{ .name = "q", .kind = .conv1, .cin = 96, .cout = 48 }}, 10, 6, false, true); + try layerCase(a, &g, rng, "GroupNorm(32) + SiLU, 96 channels over 576 pixels", &.{.{ .name = "n", .kind = .norm, .cin = 96, .cout = 96 }}, 24, 24, false, false); + const blocks = try ref.items(a, small); + try layerCase(a, &g, rng, "ResNet block with nin_shortcut, 32 -> 64 at 16x16", blocks[10..15], 16, 16, false, false); + try layerCase(a, &g, rng, "ResNet block, identity shortcut, 32 at 12x20", blocks[1..5], 12, 20, false, false); + try encodeCase(gpa, a, &g, rng); + std.debug.print("{s}\n", .{if (failed) "selftest FAILED" else "selftest passed"}); + return if (failed) 1 else 0; +} From f64c08a1117015c87e0f1db38ad9ff9ed32aeadf Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:24:47 +0000 Subject: [PATCH 015/265] docs: MiniMax-H3-Image's edit encoder in its recipe --- docs/recipes/minimax-h3-image-metal.md | 66 ++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/docs/recipes/minimax-h3-image-metal.md b/docs/recipes/minimax-h3-image-metal.md index 694a5207a34..4d0cd21c502 100644 --- a/docs/recipes/minimax-h3-image-metal.md +++ b/docs/recipes/minimax-h3-image-metal.md @@ -90,6 +90,72 @@ float32. The text encoder is MiniMax-H3's Qwen3-VL; its 50th layer's rows are th MiniMax-H3-Image Community License, which excludes the European Union, the United Kingdom, the Republic of Korea and the United States of America. Read it before use. +## Edit encoder + +An edit's reference reaches the transformer as clean latent rows made by the VAE's CNN encoder. `tf-h3-image-encoder` +makes them on Metal in fp32, on any Apple GPU; no tensor units are needed. Its kernels are compiled from source when it +starts, so it builds without the Metal compiler. + +- **The VAE copy.** The reference is read upright in RGB, with any alpha dropped. A short edge already in 1024..2048 + keeps the original pixels. Otherwise the picture is scaled to the nearer bound, each side snapped to 32 (halves to + even) and resampled with Pillow's LANCZOS: 512x768 becomes 1024x1536, 3000x4000 becomes 2048x2720, and 1536x2048 is + kept. A side under 32 pixels, or a copy over 64 MP, is refused. +- **The input.** Bytes / 255, then ImageNet's mean and std, in fp32, cropped top-left to multiples of 16 pixels. +- **The network.** + - Each 3x3x3 causal convolution runs as the 2D convolution of its last time slice, reflect-padded by one. + - `conv_in` maps 3 channels to 128. + - Six levels of two ResNet blocks follow, at widths 128, 256, 256, 512, 512 and 1,024, with `nin_shortcut` where the + width changes. + - Levels 0 to 3 end with a stride-2 downsample that reflects the right and bottom edges by one pixel. + - Then GroupNorm(32, eps 1e-6) with SiLU, `conv_out` (1,024 to 48) and `quant_conv`. + - Every tensor name and shape is checked against the checkpoint's header before anything loads. +- **Tiles.** 256-pixel tiles overlapping by at least 64, split as the decoder splits. Each tile's 48 moment channels + are blended in latent cells (overlap / 16) with the decoder's rule. +- **The rows.** + - The posterior sample, mean + exp(0.5 clamp(logvar, -30, 20)) x noise, is rounded to fp16. + - It is normalised with the latent statistics and cropped top-left to the even grid: 1024x1024 gives 64 x 64, and + 1050x1000 gives 62 rows by 64 columns. + - Then it is patchified. + - Anchor rows are 0.999 x clean + (1 - 0.999 in fp32) x the anchor noise. +- **The noise.** One CPU torch generator per request (`moss_image/noise.zig`, its draws chained), drawn in order: the + target, each reference's anchor noise, then each reference's posterior noise on its full grid. + +```sh +zig build tf-h3-image-encoder -Dcpu=apple_m1 -Doptimize=ReleaseFast +zig-out/bin/tf-h3-image-encoder MODEL_DIR reference.png SEED out/ref [CANVAS] +zig-out/bin/tf-h3-image-encoder selftest +``` + +It writes: + +- `out/ref.rows.f32`: the clean rows [rows, 96]; +- `out/ref.moments.f32`: the blended moments [48, h, w], before sampling; +- `out/ref.grid.json`. + +With `CANVAS` (WxH), the generator first draws the target's noise and this reference's anchor noise, as a +one-reference edit does, and `out/ref.anchors.f32` is written too. Without it, the posterior's noise is the seed's +first draw. + +`selftest` runs each kernel on small synthetic weights against a float64 host reference and exits 1 on a miss. It +covers: + +- a reflect-padded 3x3 convolution and the stride-2 downsample; +- a 1x1 convolution with a residual; +- GroupNorm with SiLU; +- both kinds of ResNet block; +- a small encode over uneven tiles, run twice. + +Its gates, measured on an M3 Ultra: + +| Check | Gate | Measured | +|---|---|---| +| Each layer, worst error over the largest value | 1e-5 | 2e-7 to 9e-7 | +| The tiled moments | 1e-4 | 1.6e-6 | +| The fp16 samples | one fp16 step at the largest value | within it | +| Repeat runs | bit-identical | bit-identical | + +A 1024 x 1024 reference at the released widths encodes in 0.6 s. + ## Not done - The prompt's rows come from the case. The text encoder (Qwen3-VL, 50 of 64 layers), `condition_proj` and the token From 3d1ab6fce0719a6f974fc57dad1c798840dd13cf Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:13:22 +0000 Subject: [PATCH 016/265] h3: the edit encoder, its reference rules and its tool read safetensors and pictures through core, as main does On main, H3's geometry.zig reads safetensors as core.safetensors. The encoder's module pulls geometry.zig in through picture_reference.zig, so it now imports core instead of a safetensors module of its own, and image_encoder.zig, picture_reference.zig and its test read st from core.safetensors. The tool reads PNGs through core.picture, since core already holds picture.zig and a file may sit in one module of a build only. --- zig/build/h3_image_encoder.zig | 7 +++---- zig/src/families/h3/image_encoder.zig | 2 +- zig/src/families/h3/picture_reference.zig | 2 +- zig/src/families/h3/picture_reference_test.zig | 2 +- zig/tests/h3_image_encoder.zig | 2 +- 5 files changed, 7 insertions(+), 8 deletions(-) diff --git a/zig/build/h3_image_encoder.zig b/zig/build/h3_image_encoder.zig index 22eb497a781..a280f2b9a59 100644 --- a/zig/build/h3_image_encoder.zig +++ b/zig/build/h3_image_encoder.zig @@ -2,12 +2,11 @@ const std = @import("std"); fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module) *std.Build.Module { - const st = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target, .optimize = optimize }); + const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); const kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/image_encoder.zig") }); - const encoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "safetensors", .module = st }, .{ .name = "h3_image_encoder_kernels", .module = kernels } } }); - const codec = b.createModule(.{ .root_source_file = b.path("zig/src/core/picture/picture.zig"), .target = target, .optimize = optimize, .link_libc = true }); + const encoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "h3_image_encoder_kernels", .module = kernels } } }); const noise = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/noise.zig"), .target = target, .optimize = optimize }); - return b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3_image_encoder", .module = encoder }, .{ .name = "picture_codec", .module = codec }, .{ .name = "torch_noise", .module = noise } } }); + return b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3_image_encoder", .module = encoder }, .{ .name = "core", .module = core }, .{ .name = "torch_noise", .module = noise } } }); } /// `zig build tf-h3-image-encoder`: a reference picture to its clean rows, or `selftest`; needs no Metal compiler. diff --git a/zig/src/families/h3/image_encoder.zig b/zig/src/families/h3/image_encoder.zig index 658a14cd545..252194f571c 100644 --- a/zig/src/families/h3/image_encoder.zig +++ b/zig/src/families/h3/image_encoder.zig @@ -1,7 +1,7 @@ //! MiniMax-H3-Image's edit encoder on Metal in fp32: a reference's tiles through the VAE's CNN to blended moments. const std = @import("std"); const mtl = @import("metal"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const kernels = @import("h3_image_encoder_kernels"); pub const reference = @import("picture_reference.zig"); pub const vae = @import("picture_vae.zig"); diff --git a/zig/src/families/h3/picture_reference.zig b/zig/src/families/h3/picture_reference.zig index bbedf23c4a0..c22a32a36ca 100644 --- a/zig/src/families/h3/picture_reference.zig +++ b/zig/src/families/h3/picture_reference.zig @@ -1,6 +1,6 @@ //! MiniMax-H3-Image's edit references on the host: sizes, the encoder's input and layers, clean and anchor rows. const std = @import("std"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const geometry = @import("geometry.zig"); const picture = @import("picture.zig"); const vae = @import("picture_vae.zig"); diff --git a/zig/src/families/h3/picture_reference_test.zig b/zig/src/families/h3/picture_reference_test.zig index 32639f94d1d..9a4810a9b7b 100644 --- a/zig/src/families/h3/picture_reference_test.zig +++ b/zig/src/families/h3/picture_reference_test.zig @@ -1,6 +1,6 @@ //! MiniMax-H3-Image's edit reference rules (picture_reference.zig): sizes, crops, grids, layers, weights, rows. const std = @import("std"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const r = @import("picture_reference.zig"); const vae = @import("picture_vae.zig"); const testing = std.testing; diff --git a/zig/tests/h3_image_encoder.zig b/zig/tests/h3_image_encoder.zig index 9a605fe959b..324bca21261 100644 --- a/zig/tests/h3_image_encoder.zig +++ b/zig/tests/h3_image_encoder.zig @@ -2,7 +2,7 @@ const std = @import("std"); const mtl = @import("metal"); const he = @import("h3_image_encoder"); -const codec = @import("picture_codec"); +const codec = @import("core").picture; const noise = @import("torch_noise"); const selftest = @import("h3_image_encoder_selftest.zig"); From 760e8222426a43aafd9b53964de3cade7cec38c5 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:53:16 +0000 Subject: [PATCH 017/265] changelog: #2778 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5535fc7b4be..1ef9bda7544 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- MiniMax-H3-Image on Metal: `tf-h3-image-encoder` turns an edit's reference pictures into their clean rows with the VAE's encoder in fp32 on any Apple GPU, with a selftest of each kernel against a float64 host reference; the reference rules (sizes, crops, grids, encoder layers, clean and anchor rows) run on the host (#2778, on #2775). + - GLM on Metal: vectorized prompt, KDA and indexer kernels on Macs without tensor units cut cold prompt time 5.17% to 5.68% (2K to 64K tokens) with 0/64 token differences (#3921, refs #3152). Thanks to @gilby. - MiniMax-H3-Image on Metal: `tf-h3-image` runs its transformer (MiniMax H3's, without the audio layers, on M5 tensor units) from a picture case through its six distilled steps, each with its own output head, beside the engine; the VAE's rules (config, tiles and blend, latent statistics, pixels) run on the host, and core/picture gains Pillow's Lanczos-3 resampling. Clip cases run as before (#2775). From 556a0d497df6be7a01061e7ab4ed2eca8d254f00 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:31:27 +0000 Subject: [PATCH 018/265] feat(ocr): add the GLM-OCR page reader GLM-OCR reads a page as Markdown without boxes, so a reader now states its geometry, a block's quad is optional, and GLM-OCR offers an Ocr reader with the model card's text recognition prompt and no geometry: the page becomes one block whose Markdown is the model's reply, with HTML tables rewritten as pipe tables or clean spanned HTML and \( \) and \[ \] math as $ and $$, cells included, while fenced and inline code stays verbatim in a linear scan. A reader without boxes refuses header and footer extraction, the page pixel limit grows to GLM-OCR's, and greedy Hugging Face oracle outputs pin the prompt and the parser in the fixture tests. --- zig/build/glm_ocr.zig | 4 +- zig/src/core/engine_ocr.zig | 10 +- zig/src/families/dots_mocr/ocr.zig | 2 +- zig/src/families/dots_mocr/ocr_test.zig | 15 +- zig/src/families/glm_ocr/fixtures/README.md | 32 +++ .../families/glm_ocr/fixtures/ocr-table.json | 13 ++ .../families/glm_ocr/fixtures/ocr-text.json | 13 ++ zig/src/families/glm_ocr/hip_native.zig | 5 +- zig/src/families/glm_ocr/host_test.zig | 4 + zig/src/families/glm_ocr/ocr.zig | 206 ++++++++++++++++++ zig/src/families/glm_ocr/ocr_test.zig | 150 +++++++++++++ zig/src/server/ocr/harness_test.zig | 6 +- zig/src/server/ocr/mistral.zig | 8 +- zig/src/server/ocr/mistral_reply.zig | 11 +- zig/src/server/ocr/mistral_test.zig | 7 +- zig/src/server/ocr/prompt_ids_test.zig | 2 +- zig/src/server/ocr/run.zig | 8 +- zig/src/server/ocr/run_test.zig | 18 +- 18 files changed, 479 insertions(+), 35 deletions(-) create mode 100644 zig/src/families/glm_ocr/fixtures/README.md create mode 100644 zig/src/families/glm_ocr/fixtures/ocr-table.json create mode 100644 zig/src/families/glm_ocr/fixtures/ocr-text.json create mode 100644 zig/src/families/glm_ocr/ocr.zig create mode 100644 zig/src/families/glm_ocr/ocr_test.zig diff --git a/zig/build/glm_ocr.zig b/zig/build/glm_ocr.zig index a8f90137667..2f78af8633e 100644 --- a/zig/build/glm_ocr.zig +++ b/zig/build/glm_ocr.zig @@ -6,6 +6,8 @@ pub fn hostTests(b: *std.Build, all: *std.Build.Step) void { const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .link_libc = true }); core.addImport("gpu_memory", @import("gpu_memory.zig").module(b, target)); core.addImport("tokenizer", b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .link_libc = true })); + const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = target, .link_libc = true }); + const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); const options = b.addOptions(); options.addOption(?[]const u8, "model_dir", b.option([]const u8, "glm-ocr-model-dir", "Existing GLM-OCR checkpoint for host validation")); for ([_]std.builtin.OptimizeMode{ .debug, .fast }) |mode| { @@ -14,7 +16,7 @@ pub fn hostTests(b: *std.Build, all: *std.Build.Step) void { .target = target, .optimize = mode, .link_libc = true, - .imports = &.{.{ .name = "core", .module = core }}, + .imports = &.{ .{ .name = "core", .module = core }, .{ .name = "engine_api", .module = api } }, }); tests.addOptions("glm_ocr_options", options); const run = b.addRunArtifact(b.addTest(.{ .root_module = tests })); diff --git a/zig/src/core/engine_ocr.zig b/zig/src/core/engine_ocr.zig index a00315b2d50..52026a5c8ec 100644 --- a/zig/src/core/engine_ocr.zig +++ b/zig/src/core/engine_ocr.zig @@ -9,7 +9,7 @@ pub const html = @import("ocr_html.zig"); /// TL, TR, BR, BL of the text in its upright reading frame, in original-image pixels (rotated text keeps its order). pub const Quad = [4][2]f32; -/// What a block holds. +/// What a block holds; ``page`` only for a ``.none`` reader (the whole page's Markdown in one block). pub const Kind = enum { text, title, @@ -23,12 +23,16 @@ pub const Kind = enum { page_header, page_footer, picture, + page, }; +/// The geometry a reader gives: none, or one quad a block. +pub const Geometry = enum { none, block }; + /// One block of a page in reading order. pub const OcrBlock = struct { content: []const u8, // normalized Markdown (docs/api.md OCR: Reader Markdown); empty only for .picture - quad: Quad, + quad: ?Quad, // null only for a reader whose geometry is .none kind: Kind, }; @@ -39,6 +43,8 @@ pub const Error = error{Unreadable}; pub const Ocr = struct { /// Text parts that follow the image in the single user turn (may be empty). prompt: []const u8, + /// What geometry `parse` gives. + geometry: Geometry, /// Text to blocks in pixels of ``original``; ``frame`` is the tower input size the prepare step used. parse: *const fn (a: Allocator, text: []const u8, original: Size, frame: Size) anyerror![]OcrBlock, }; diff --git a/zig/src/families/dots_mocr/ocr.zig b/zig/src/families/dots_mocr/ocr.zig index f45c860adcb..326c21f6d9b 100644 --- a/zig/src/families/dots_mocr/ocr.zig +++ b/zig/src/families/dots_mocr/ocr.zig @@ -10,7 +10,7 @@ const log = std.log.scoped(.dots_ocr); pub const prompt = @embedFile("prompt.txt"); /// The reader the family offers (Offer.ocr). -pub const reader: ocr.Ocr = .{ .prompt = prompt, .parse = parse }; +pub const reader: ocr.Ocr = .{ .prompt = prompt, .geometry = .block, .parse = parse }; const categories = std.StaticStringMap(ocr.Kind).initComptime(.{ .{ "Caption", .caption }, diff --git a/zig/src/families/dots_mocr/ocr_test.zig b/zig/src/families/dots_mocr/ocr_test.zig index 86e695fdcf4..0d06727d842 100644 --- a/zig/src/families/dots_mocr/ocr_test.zig +++ b/zig/src/families/dots_mocr/ocr_test.zig @@ -76,6 +76,7 @@ test "dots: the reader's prompt is the one every oracle run recorded" { defer arena.deinit(); for ([_][]const u8{ page_json, line_json, cut_json }) |text| try t.expectEqualStrings((try fixture(arena.allocator(), text)).prompt_sha256, &hex(ocr.prompt)); + try t.expectEqual(api.ocr.Geometry.block, ocr.reader.geometry); } test "dots: oracle runs in TF_DOTS_OCR_DIR match their fixtures' hashes and read as their pages" { @@ -90,7 +91,7 @@ test "dots: oracle runs in TF_DOTS_OCR_DIR match their fixtures' hashes and read for (kinds, blocks) |kind, b| { try t.expectEqual(kind, b.kind); try t.expect(b.content.len > 0); - for (b.quad) |q| try t.expect(q[0] >= 0 and q[0] <= 1240 and q[1] >= 0 and q[1] <= 1754); + for (b.quad.?) |q| try t.expect(q[0] >= 0 and q[0] <= 1240 and q[1] >= 0 and q[1] <= 1754); } // The page's table has a spanned header cell, so it stays one clean HTML table. try t.expect(std.mem.startsWith(u8, blocks[6].content, "") and std.mem.endsWith(u8, blocks[6].content, "
")); @@ -128,7 +129,7 @@ test "dots: a page reads as headers, title, text, caption, spanned table, list a const sx: f32 = 1240.0 / 1232.0; const sy: f32 = 1754.0 / 1764.0; const want: api.ocr.Quad = .{ .{ 70 * sx, 50 * sy }, .{ 410 * sx, 50 * sy }, .{ 410 * sx, 90 * sy }, .{ 70 * sx, 90 * sy } }; - for (want, blocks[0].quad) |w, g| for (w, g) |x, y| try t.expectApproxEqAbs(x, y, 1e-3); + for (want, blocks[0].quad.?) |w, g| for (w, g) |x, y| try t.expectApproxEqAbs(x, y, 1e-3); try t.expectEqualStrings("TENSORFOLD READER NOTES", blocks[0].content); try t.expectEqualStrings("# Reading a Page Twice", blocks[2].content); try t.expectEqualStrings("## 1. Why the second read matters", blocks[3].content); @@ -174,7 +175,7 @@ test "dots: boxes scale to the original from the frames of two token budgets" { // One block covering the frame's middle half covers the original's middle half. const text = try std.fmt.allocPrint(a, "[{{\"bbox\": [{d}, {d}, {d}, {d}], \"category\": \"Text\", \"text\": \"x\"}}]", .{ frame.width / 4, frame.height / 4, frame.width / 4 * 3, frame.height / 4 * 3 }); const blocks = try ocr.parse(a, text, original, frame.*); - const q = blocks[0].quad; + const q = blocks[0].quad.?; const sx = 1700.0 / @as(f32, @floatFromInt(frame.width)); const sy = 2250.0 / @as(f32, @floatFromInt(frame.height)); try t.expectApproxEqAbs(@as(f32, @floatFromInt(frame.width / 4)) * sx, q[0][0], 1e-3); @@ -214,7 +215,7 @@ test "dots: golden boxes on a 1000 x 333 page come back in the client's pixels f const text = try std.fmt.allocPrint(a, "[{{\"bbox\": [{d}, {d}, {d}, {d}], \"category\": \"Text\", \"text\": \"x\"}}]", .{ g.model[0], g.model[1], g.model[2], g.model[3] }); const blocks = try ocr.parse(a, text, original, prepared.frame.?); try t.expectEqual(@as(usize, 1), blocks.len); - const q = blocks[0].quad; + const q = blocks[0].quad.?; const want: api.ocr.Quad = .{ .{ g.client[0], g.client[1] }, .{ g.client[2], g.client[1] }, .{ g.client[2], g.client[3] }, .{ g.client[0], g.client[3] } }; for (want, q) |w, got| { try t.expectApproxEqAbs(w[0], got[0], 1e-3); @@ -285,10 +286,10 @@ test "dots: pictures keep empty content, empty blocks drop, reversed boxes swap" try t.expectEqual(@as(usize, 3), blocks.len); try t.expectEqual(api.ocr.Kind.picture, blocks[0].kind); try t.expectEqualStrings("", blocks[0].content); - try t.expectEqual(api.ocr.Quad{ .{ 20, 40 }, .{ 60, 40 }, .{ 60, 80 }, .{ 20, 80 } }, blocks[0].quad); + try t.expectEqual(api.ocr.Quad{ .{ 20, 40 }, .{ 60, 40 }, .{ 60, 80 }, .{ 20, 80 } }, blocks[0].quad.?); try t.expectEqualStrings("kept", blocks[1].content); - try t.expectEqual(api.ocr.Quad{ .{ 20, 40 }, .{ 100, 40 }, .{ 100, 120 }, .{ 20, 120 } }, blocks[1].quad); - try t.expectEqual(api.ocr.Quad{ .{ 1, 3 }, .{ 5, 3 }, .{ 5, 7 }, .{ 1, 7 } }, blocks[2].quad); + try t.expectEqual(api.ocr.Quad{ .{ 20, 40 }, .{ 100, 40 }, .{ 100, 120 }, .{ 20, 120 } }, blocks[1].quad.?); + try t.expectEqual(api.ocr.Quad{ .{ 1, 3 }, .{ 5, 3 }, .{ 5, 7 }, .{ 1, 7 } }, blocks[2].quad.?); try t.expectEqual(@as(usize, 0), (try ocr.parse(a, " [] \n", .{ .width = 1, .height = 1 }, .{ .width = 1, .height = 1 })).len); } diff --git a/zig/src/families/glm_ocr/fixtures/README.md b/zig/src/families/glm_ocr/fixtures/README.md new file mode 100644 index 00000000000..fcfa17f857f --- /dev/null +++ b/zig/src/families/glm_ocr/fixtures/README.md @@ -0,0 +1,32 @@ +# GLM-OCR fixtures + +`config.json`, `preprocessor_config.json` and `processor.json` come from +the `processor` command of `tools/zig/glm_ocr_reference.py`. + +## OCR reader fixtures + +The `ocr-*.json` files are greedy outputs of the script's `capture` +command (official Transformers 5.5.4, checkpoint revision +`2e85a62840ccac27daa451df36c736c4636b8628`), for `ocr_test.zig`. Each +holds `text` (the receipt's `text`), `original` (the case image's width +and height), `frame` (the `image_grid_thw` height and width times the +14-pixel patch, the tower input size), `source` and `prompt_sha256` (the +SHA-256 of the case prompt). + +| Fixture | `examples.json` case | Prompt | +| --- | --- | --- | +| `ocr-text.json` | `text` | `Text Recognition:` | +| `ocr-table.json` | `table` | `Table Recognition:` | + +The `examples` command draws the case images with the font that +`--font` names; these runs used Liberation Sans Regular +(SHA-256 `baccc64becc3eb7d104b7c84d99f5314a0a1f896e2b3ea6c2f22fc08d2003bee`). +The command also copies the model card's car and bee photos from a local +copy of `huggingface/documentation-images` at the revision the script +pins. + +```sh +python tools/zig/glm_ocr_reference.py examples HF_IMAGES EXAMPLES_DIR --font FONT +HIP_VISIBLE_DEVICES=N python tools/zig/glm_ocr_reference.py capture \ + CHECKPOINT_DIR EXAMPLES_DIR/examples.json CASE OUTPUT_DIR --pci PCI_ID +``` diff --git a/zig/src/families/glm_ocr/fixtures/ocr-table.json b/zig/src/families/glm_ocr/fixtures/ocr-table.json new file mode 100644 index 00000000000..b0126885903 --- /dev/null +++ b/zig/src/families/glm_ocr/fixtures/ocr-table.json @@ -0,0 +1,13 @@ +{ + "text": "
ItemQuantity
Apples3
Pears5
", + "original": [ + 560, + 252 + ], + "frame": [ + 560, + 252 + ], + "source": "glm_ocr_reference.py capture, examples.json case table (Table Recognition:)", + "prompt_sha256": "9e485ad53e473bd38f054ecfab4feb5a571bfbb4cc1e6f9c4e8597b2bfdb8f07" +} diff --git a/zig/src/families/glm_ocr/fixtures/ocr-text.json b/zig/src/families/glm_ocr/fixtures/ocr-text.json new file mode 100644 index 00000000000..de1792ca77a --- /dev/null +++ b/zig/src/families/glm_ocr/fixtures/ocr-text.json @@ -0,0 +1,13 @@ +{ + "text": "TensorFold OCR test\n\nInvoice 0042\n\nTotal: 123.45 USD", + "original": [ + 840, + 220 + ], + "frame": [ + 840, + 224 + ], + "source": "glm_ocr_reference.py capture, examples.json case text (Text Recognition:)", + "prompt_sha256": "77e8207573e1b8ba857d25db3a5080ae8651d6ddc2ea79007af5ca7958b80017" +} diff --git a/zig/src/families/glm_ocr/hip_native.zig b/zig/src/families/glm_ocr/hip_native.zig index d406870e22f..8273ab2ebb6 100644 --- a/zig/src/families/glm_ocr/hip_native.zig +++ b/zig/src/families/glm_ocr/hip_native.zig @@ -7,6 +7,7 @@ const serve = @import("hip_serve"); const c = @import("config.zig"); const Engine = @import("hip_engine.zig").Engine; const Hip = @import("hip_lanes.zig").Hip; +const ocr = @import("ocr.zig"); pub const model_type = c.model_type; pub const formats: []const []const u8 = &.{"bf16"}; @@ -56,8 +57,7 @@ fn release(ptr: *anyopaque) void { } fn prepare(ptr: *anyopaque, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) !api.PreparedImage { const own: *Owned = @ptrCast(@alignCast(ptr)); - const p = try @import("processor.zig").prepare(own.e.io, a, bytes, @min(max_tokens, 6144)); - return .{ .pixels = p.pixels, .gh = @intCast(p.geometry.h / 14), .gw = @intCast(p.geometry.w / 14), .tokens = @intCast(p.geometry.tokens()), .hash = p.hash }; + return ocr.prepared(try @import("processor.zig").prepare(own.e.io, a, bytes, @min(max_tokens, 6144))); } const markers = [_]u32{ c.image_start, c.image_token, c.image_end }; pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: serve.Options, problem: *[]const u8) !Loaded { @@ -78,6 +78,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.D const vision: ?api.Vision = if (o.vision) |v| .{ .ctx = own, .prepare = prepare, .image_token = c.image_token, .markers = &markers, .part_type = "image", .image_tokens = if (v.image_tokens_set) v.image_tokens else 6144, .max_images = v.max_images, .explain = @import("sys").optional_libraries.explain } else null; return .{ .backend = h.backend(), .facts = h.facts(), .ctx = own, .deinit = release, .streams = e.streams, .startup = startup, .offer = .{ .vision = vision, + .ocr = ocr.reader, .cache = if (e.cache_bytes > 0) &h.store else null, .cache_capacity = .{ .budget_bytes = e.cache_bytes, .minimum_state_bytes = @import("hip_snapshot.zig").Snapshot.bytes(1) }, } }; diff --git a/zig/src/families/glm_ocr/host_test.zig b/zig/src/families/glm_ocr/host_test.zig index c367f6a00b2..3eb5482b032 100644 --- a/zig/src/families/glm_ocr/host_test.zig +++ b/zig/src/families/glm_ocr/host_test.zig @@ -175,3 +175,7 @@ test "GLM-OCR refuses invalid geometry, pixel buffers and budgets before allocat try std.testing.expectError(error.BadPixels, processor.prepareRgb(a, .{ .height = 84, .width = 112, .pixels = &.{} }, 6144)); try std.testing.expectError(error.ImageBudget, processor.prepareRgb(a, .{ .height = 84, .width = 112, .pixels = &.{} }, 1)); } + +test { + _ = @import("ocr_test.zig"); +} diff --git a/zig/src/families/glm_ocr/ocr.zig b/zig/src/families/glm_ocr/ocr.zig new file mode 100644 index 00000000000..ee12120e68c --- /dev/null +++ b/zig/src/families/glm_ocr/ocr.zig @@ -0,0 +1,206 @@ +//! GLM-OCR's OCR reader: the model card's text prompt, and the page as one block with tables and math normalized. +const std = @import("std"); +const api = @import("engine_api"); +const c = @import("config.zig"); +const processor = @import("processor.zig"); +const ocr = api.ocr; +const Allocator = std.mem.Allocator; + +/// The model card's text recognition prompt. +pub const prompt = "Text Recognition:"; + +/// The reader the family offers (Offer.ocr). +pub const reader: ocr.Ocr = .{ .prompt = prompt, .geometry = .none, .parse = parse }; + +/// The prepared image the tower reads, with its frame: the resized size, one patch a grid cell. +pub fn prepared(p: processor.Prepared) api.PreparedImage { + const gh: u32 = @intCast(p.geometry.h / c.patch); + const gw: u32 = @intCast(p.geometry.w / c.patch); + return .{ .pixels = p.pixels, .gh = gh, .gw = gw, .tokens = @intCast(p.geometry.tokens()), .hash = p.hash, .frame = .{ .width = gw * c.patch, .height = gh * c.patch } }; +} + +/// The page as one `.page` block (no geometry); empty text is an empty page. ``a`` is a request arena. +pub fn parse(a: Allocator, text: []const u8, original: api.Size, frame: api.Size) anyerror![]ocr.OcrBlock { + _ = original; + _ = frame; + const page = std.mem.trim(u8, text, &std.ascii.whitespace); + if (page.len == 0) return &.{}; + const blocks = try a.alloc(ocr.OcrBlock, 1); + blocks[0] = .{ .content = try markdown(a, page), .quad = null, .kind = .page }; + return blocks; +} + +/// Backtick runs this long or longer are literal text: the failed-closer set stays small and the scan linear. +const max_tick = 64; + +/// The page with code (fenced blocks, backtick spans) verbatim; tables and math normalized in the prose between. +fn markdown(a: Allocator, page: []const u8) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + try split(a, &out, page, true, prose); + return out.toOwnedSlice(a); +} + +/// ``text`` to ``out``: code verbatim, the prose between through ``each``; ``tables``: a table is one prose range. +fn split(a: Allocator, out: *std.ArrayList(u8), text: []const u8, tables: bool, comptime each: anytype) !void { + var scanner: Scanner = .{ .page = text, .unclosed_table = !tables }; + var start: usize = 0; + var i: usize = 0; + while (i < text.len) { + const s = scanner.at(i); + if (s.code) { + try each(a, out, text[start..i]); + try out.appendSlice(a, text[i..s.end]); + start = s.end; + } + i = s.end; + } + try each(a, out, text[start..]); +} + +const Span = struct { end: usize, code: bool }; + +/// A forward scan for code; every search it remembers failing covers a range no later search can reach past. +const Scanner = struct { + page: []const u8, + /// Backtick run lengths with no closer before ``paragraph`` (the current paragraph's end). + failed: std.StaticBitSet(max_tick) = .empty, + paragraph: usize = 0, + /// No `` follows a `")) |end| return .{ .end = end + "".len, .code = false }; + s.unclosed_table = true; + } + if (page[i] != '`') return .{ .end = i + 1, .code = false }; + const k = run(page, i, '`'); + if (i >= s.paragraph) { + s.paragraph = paragraphEnd(page, i); + s.failed = .empty; + } + // No closer of length k before the paragraph's end after one position means none after any later one. + if (k < max_tick and !s.failed.isSet(k)) { + const within = page[0..s.paragraph]; + var j = i + k; + while (std.mem.indexOfScalarPos(u8, within, j, '`')) |closer| { + const r = run(within, closer, '`'); + if (r == k) return .{ .end = closer + r, .code = true }; + j = closer + r; + } + s.failed.set(k); + } + return .{ .end = i + k, .code = false }; + } +}; + +/// The start of the first line after ``i``'s line that is blank or opens a fence, or the text's end. +fn paragraphEnd(page: []const u8, i: usize) usize { + var at = i; + while (std.mem.indexOfScalarPos(u8, page, at, '\n')) |nl| { + const next = nl + 1; + const line_end = std.mem.indexOfScalarPos(u8, page, next, '\n') orelse page.len; + if (std.mem.trim(u8, page[next..line_end], " \t\r").len == 0 or opens(page, next) != null) return next; + at = line_end; + } + return page.len; +} + +const Fence = struct { ch: u8, n: usize, at: usize }; + +/// The fence a line starting at ``i`` opens: up to 3 spaces, then 3 or more ` or ~. +fn opens(page: []const u8, i: usize) ?Fence { + var j = i; + while (j < page.len and j - i < 3 and page[j] == ' ') j += 1; + if (j >= page.len or (page[j] != '`' and page[j] != '~')) return null; + const n = run(page, j, page[j]); + return if (n >= 3) .{ .ch = page[j], .n = n, .at = j } else null; +} + +/// The end of a fenced block opening at line start ``i``: its closing fence line (3 spaces at most), or the text's end. +fn fence(page: []const u8, i: usize) ?usize { + const f = opens(page, i) orelse return null; + var at = std.mem.indexOfScalarPos(u8, page, f.at, '\n') orelse return page.len; + while (true) { + const line_end = std.mem.indexOfScalarPos(u8, page, at + 1, '\n') orelse page.len; + const line = page[at + 1 .. line_end]; + const indent = run(line[0..@min(line.len, 3)], 0, ' '); + const r = run(line, indent, f.ch); + if (r >= f.n and std.mem.trim(u8, line[indent + r ..], " \t\r").len == 0) return line_end; + if (line_end == page.len) return page.len; + at = line_end; + } +} + +/// How many ``ch`` bytes start at ``i``. +fn run(text: []const u8, i: usize, ch: u8) usize { + var j = i; + while (j < text.len and text[j] == ch) j += 1; + return j - i; +} + +/// Prose with HTML tables as pipe tables (clean HTML when spanned), and math outside code as `$…$`, cells included. +fn prose(a: Allocator, out: *std.ArrayList(u8), text: []const u8) !void { + var rest = text; + while (std.mem.indexOf(u8, rest, "") orelse break) + "".len; + var html: std.ArrayList(u8) = .empty; + try split(a, &html, rest[open..end], false, math); + const t = ocr.html.parse(a, html.items) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + error.Malformed => { + // A table the subset cannot read stays as the model wrote it: raw HTML is still Markdown. + try math(a, out, rest[0..open]); + try out.appendSlice(a, html.items); + rest = rest[end..]; + continue; + }, + }; + try math(a, out, rest[0..open]); + if (out.items.len > 0) try separate(a, out); + try out.appendSlice(a, if (t.spanned) try ocr.html.normalized(a, t) else try ocr.html.pipe(a, t)); + rest = rest[end..]; + if (std.mem.trim(u8, rest, &std.ascii.whitespace).len > 0) { + try separate(a, out); + rest = std.mem.trimStart(u8, rest, &std.ascii.whitespace); + } + } + try math(a, out, rest); +} + +/// Ends ``out`` with one blank line, so a pipe table starts and ends a Markdown block. +fn separate(a: Allocator, out: *std.ArrayList(u8)) !void { + out.shrinkRetainingCapacity(std.mem.trimEnd(u8, out.items, &std.ascii.whitespace).len); + if (out.items.len > 0) try out.appendSlice(a, "\n\n"); +} + +/// ``text`` with each closed `\[…\]` as `$$…$$` and `\(…\)` as `$…$`; an unclosed opener stays. +fn math(a: Allocator, out: *std.ArrayList(u8), text: []const u8) !void { + // A closer missing after one opener is missing after every later one: each closer is searched until it fails. + var open_paren = true; + var open_bracket = true; + var i: usize = 0; + while (i < text.len) { + if (text[i] == '\\' and i + 1 < text.len and (text[i + 1] == '[' or text[i + 1] == '(')) { + const display = text[i + 1] == '['; + const searching = if (display) &open_bracket else &open_paren; + if (searching.*) { + if (std.mem.indexOfPos(u8, text, i + 2, if (display) "\\]" else "\\)")) |end| { + const delimiter = if (display) "$$" else "$"; + try out.appendSlice(a, delimiter); + try out.appendSlice(a, text[i + 2 .. end]); + try out.appendSlice(a, delimiter); + i = end + 2; + continue; + } + searching.* = false; + } + } + try out.append(a, text[i]); + i += 1; + } +} diff --git a/zig/src/families/glm_ocr/ocr_test.zig b/zig/src/families/glm_ocr/ocr_test.zig new file mode 100644 index 00000000000..27222f2e3eb --- /dev/null +++ b/zig/src/families/glm_ocr/ocr_test.zig @@ -0,0 +1,150 @@ +//! GLM-OCR's reader against Hugging Face oracle outputs, page Markdown normalization, and the prepared frame. +const std = @import("std"); +const api = @import("engine_api"); +const ocr = @import("ocr.zig"); +const processor = @import("processor.zig"); +const t = std.testing; + +const Fixture = struct { text: []const u8, original: [2]u32, frame: [2]u32, source: []const u8, prompt_sha256: []const u8 }; +const text_json = @embedFile("fixtures/ocr-text.json"); +const table_json = @embedFile("fixtures/ocr-table.json"); + +fn fixture(a: std.mem.Allocator, text: []const u8) !Fixture { + return std.json.parseFromSliceLeaky(Fixture, a, text, .{}); +} + +fn page(a: std.mem.Allocator, text: []const u8) ![]const u8 { + const blocks = try ocr.parse(a, text, .{ .width = 10, .height = 10 }, .{ .width = 28, .height = 28 }); + try t.expectEqual(@as(usize, 1), blocks.len); + try t.expectEqual(api.ocr.Kind.page, blocks[0].kind); + try t.expect(blocks[0].quad == null); + return blocks[0].content; +} + +test "GLM-OCR reader: the text oracle reads as one page block under the served prompt" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const f = try fixture(a, text_json); + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(ocr.prompt, &digest, .{}); + try t.expectEqualStrings(f.prompt_sha256, &std.fmt.bytesToHex(digest, .lower)); + try t.expectEqual(api.ocr.Geometry.none, ocr.reader.geometry); + const content = try page(a, f.text); + for ([_][]const u8{ "TensorFold OCR test", "Invoice 0042", "Total: 123.45 USD" }) |line| + try t.expect(std.mem.indexOf(u8, content, line) != null); +} + +test "GLM-OCR reader: the table oracle reads as a pipe table" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const f = try fixture(a, table_json); + try t.expectEqualStrings("| Item | Quantity |\n| --- | --- |\n| Apples | 3 |\n| Pears | 5 |", try page(a, f.text)); +} + +test "GLM-OCR reader: the page Markdown is the model's reply as the chat route returns it, but HTML tables and \\( math" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // the text oracle is GLM-OCR's own reply to this image and prompt: /v1/chat/completions returns it as content + const f = try fixture(a, text_json); + try t.expectEqualStrings(std.mem.trim(u8, f.text, &std.ascii.whitespace), try page(a, f.text)); + // the model's Markdown stays byte for byte (headings, lists, pipe tables, `$…$` math, code), only trimmed + const markdown = "# Invoice 0042\n\n- Apples: 3\n- Pears: 5\n\n| Item | Qty |\n| --- | --- |\n| Apples | 3 |\n\nArea $\\pi r^2$, `code`"; + try t.expectEqualStrings(markdown, try page(a, "\n" ++ markdown ++ "\n\n")); + // only an HTML table (to a pipe table, or clean HTML when spanned) and \( \) / \[ \] math (to $ / $$) are rewritten + const table = try fixture(a, table_json); + try t.expectEqualStrings("| Item | Quantity |\n| --- | --- |\n| Apples | 3 |\n| Pears | 5 |", try page(a, table.text)); + try t.expectEqualStrings("Area $\\pi r^2$ and\n$$ x $$", try page(a, "Area \\(\\pi r^2\\) and\n\\[ x \\]")); +} + +test "GLM-OCR reader: empty text is an empty page" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_][]const u8{ "", " \n\t " }) |text| + try t.expectEqual(@as(usize, 0), (try ocr.parse(a, text, .{ .width = 1, .height = 1 }, .{ .width = 28, .height = 28 })).len); +} + +test "GLM-OCR reader: tables inside the page and LaTeX delimiters become Markdown" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const Case = struct { []const u8, []const u8 }; + for ([_]Case{ + .{ " plain text\n", "plain text" }, + .{ "Area \\(\\pi r^2\\) and\n\\[ E = mc^2 \\]", "Area $\\pi r^2$ and\n$$ E = mc^2 $$" }, + .{ "open \\( stays and \\[ too", "open \\( stays and \\[ too" }, + .{ "Before
ab
after", "Before\n\n| a | b |\n| --- | --- |\n\nafter" }, + .{ "
ab
12
\n\n
x
", "
ab
12
\n\n| x |\n| --- |" }, + .{ "
\\(x\\)
", "| $x$ |\n| --- |" }, + .{ "
\\[ y \\]b
", "| $$ y $$ | b |\n| --- | --- |" }, + .{ "
[x](y)*not bold*a_b
", "| \\[x\\](y) | \\*not bold\\* | a_b |\n| --- | --- | --- |" }, + .{ "kept
a
as written", "kept
a
as written" }, + .{ "cut
a", "cut
a" }, + }) |k| try t.expectEqualStrings(k[1], try page(a, k[0])); +} + +fn repeat(a: std.mem.Allocator, part: []const u8, n: usize) ![]u8 { + const text = try a.alloc(u8, part.len * n); + for (0..n) |k| @memcpy(text[k * part.len ..][0..part.len], part); + return text; +} + +test "GLM-OCR reader: many unclosed math openers stay as written" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_][]const u8{ "\\(", "\\[" }) |opener| { + const text = try repeat(a, opener, 32768); + try t.expectEqualStrings(text, try page(a, text)); + } + // A closer after many unclosed openers of the other kind still converts. + const openers = try repeat(a, "\\[", 64); + const mixed = try std.mem.concat(a, u8, &.{ openers, " \\(x\\)" }); + try t.expectEqualStrings(try std.mem.concat(a, u8, &.{ openers, " $x$" }), try page(a, mixed)); +} + +test "GLM-OCR reader: code blocks and code spans stay verbatim" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const table = "
a
"; + const Case = struct { []const u8, []const u8 }; + for ([_]Case{ + .{ "```python\nprint(r\"\\(x\\)\")\n" ++ table ++ "\n```\nafter \\(y\\)", "```python\nprint(r\"\\(x\\)\")\n" ++ table ++ "\n```\nafter $y$" }, + .{ "~~~~\n\\[ z \\]\n~~~\nstill code " ++ table, "~~~~\n\\[ z \\]\n~~~\nstill code " ++ table }, + .{ "use `\\(x\\)` and ``" ++ table ++ "`` here \\(y\\)", "use `\\(x\\)` and ``" ++ table ++ "`` here $y$" }, + .{ "`\\(a\\)` then ` lone \\(z\\)", "`\\(a\\)` then ` lone $z$" }, + .{ "a `` b ` c `` \\(x\\)", "a `` b ` c `` $x$" }, + .{ "x ``` inline ``` and ``` open \\(x\\)", "x ``` inline ``` and ``` open $x$" }, + .{ "text\n``` fence to the end \\(x\\)", "text\n``` fence to the end \\(x\\)" }, + .{ "intro\n ~~~python\nprint(r\"\\(x\\)\")\n ~~~", "intro\n ~~~python\nprint(r\"\\(x\\)\")\n ~~~" }, + .{ "```\n\\(x\\)\n ```\nafter \\(y\\)", "```\n\\(x\\)\n ```\nafter $y$" }, + .{ "x\n ```\n\\(x\\)", "x\n ```\n$x$" }, + .{ "lead `\n\n~~~text\n`\n~~~\nafter \\(y\\)", "lead `\n\n~~~text\n`\n~~~\nafter $y$" }, + .{ "a `b\n\nc` \\(x\\)", "a `b\n\nc` $x$" }, + // a cell's text is literal in the pipe table: its backticks are escaped, its math (outside code) converted + .{ "
`x`\\(y\\)
", "| \\`x\\` | $y$ |\n| --- | --- |" }, + .{ "
`\\(x\\)`
", "| \\`\\\\(x\\\\)\\` |\n| --- |" }, + .{ "bad
`\\(x\\)` \\(y\\)
", "bad
`\\(x\\)` $y$
" }, + .{ " `\\(x\\)` and
again", "
`\\(x\\)` and
again" }, + }) |k| try t.expectEqualStrings(k[1], try page(a, k[0])); +} + +test "GLM-OCR reader: prepare reports the processor's resized size as the frame" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_][]const u8{ text_json, table_json }) |json| { + const f = try fixture(a, json); + const rgb = try a.alloc(u8, @as(usize, f.original[0]) * f.original[1] * 3); + @memset(rgb, 255); + const p = try processor.prepareRgb(a, .{ .width = f.original[0], .height = f.original[1], .pixels = rgb }, 6144); + const prepared = ocr.prepared(p); + try t.expectEqual(api.Size{ .width = f.frame[0], .height = f.frame[1] }, prepared.frame.?); + try t.expectEqual(p.geometry.w * p.geometry.h, @as(usize, prepared.frame.?.width) * prepared.frame.?.height); + try t.expectEqual(prepared.gw * 14, prepared.frame.?.width); + } +} diff --git a/zig/src/server/ocr/harness_test.zig b/zig/src/server/ocr/harness_test.zig index 916e6603112..da97396ac8e 100644 --- a/zig/src/server/ocr/harness_test.zig +++ b/zig/src/server/ocr/harness_test.zig @@ -19,7 +19,7 @@ pub const Harness = struct { next: usize = 0, /// The tower input size the vision step reports; null: the missing-frame path. frame: ?api.Size = .{ .width = 100, .height = 50 }, - reader: ?api.ocr.Ocr = .{ .prompt = "Read the page.", .parse = parse }, + reader: ?api.ocr.Ocr = .{ .prompt = "Read the page.", .geometry = .block, .parse = parse }, vision: bool = true, srv: *Server = undefined, @@ -78,6 +78,10 @@ fn parse(a: Allocator, src: []const u8, original: api.Size, frame: api.Size) any var words = std.mem.tokenizeScalar(u8, block[0..nl], ' '); const kind = std.meta.stringToEnum(api.ocr.Kind, words.next() orelse return error.Unreadable) orelse return error.Unreadable; const content = if (nl < block.len) block[nl + 1 ..] else ""; + if (kind == .page) { + try out.append(a, .{ .content = content, .quad = null, .kind = kind }); + continue; + } var v: [4]f32 = undefined; for (&v) |*x| x.* = try std.fmt.parseFloat(f32, words.next() orelse return error.Unreadable); const sx = @as(f32, @floatFromInt(original.width)) / @as(f32, @floatFromInt(frame.width)); diff --git a/zig/src/server/ocr/mistral.zig b/zig/src/server/ocr/mistral.zig index f9bd52d6da9..4bf8f24375a 100644 --- a/zig/src/server/ocr/mistral.zig +++ b/zig/src/server/ocr/mistral.zig @@ -1,6 +1,7 @@ //! POST /v1/ocr in Mistral's OCR contract: fields and document, then the page loop (docs/api.md OCR: Mistral). const std = @import("std"); const Allocator = std.mem.Allocator; +const api = @import("engine_api"); const json = @import("json"); const errors = @import("../errors.zig"); const images = @import("../images.zig"); @@ -23,14 +24,15 @@ pub const Options = reply.Options; /// The most page entries a ``pages`` value may name before expansion (a range counts its length). pub const max_page_entries = 1024; -/// What decoding needs from the server: the PDF switch, the URL fetcher and the page budget. +/// What decoding needs from the server: the reader's geometry, the PDF switch, the URL fetcher and the page budget. pub const Facts = struct { + geometry: api.ocr.Geometry, pdf: bool, fetch: ?images.Fetch, pages_left: u32, pub fn of(srv: *const Server) Facts { - return .{ .pdf = srv.config.vision_pdf, .fetch = if (srv.config.vision_urls) images.Fetch.network(srv.io) else null, .pages_left = budget.Pages.init().left }; + return .{ .geometry = srv.info.ocr.?.geometry, .pdf = srv.config.vision_pdf, .fetch = if (srv.config.vision_urls) images.Fetch.network(srv.io) else null, .pages_left = budget.Pages.init().left }; } }; @@ -98,6 +100,8 @@ pub fn decode(a: Allocator, body: Value, facts: Facts, fault: *Fault) Step!Reque const ok = v == .string and (std.mem.eql(u8, v.string, "word") or std.mem.eql(u8, v.string, "page") or std.mem.eql(u8, v.string, "block")); if (!ok) return bad(a, fault, &.{ "body", "confidence_scores_granularity" }, "confidence_scores_granularity must be \"word\", \"page\", \"block\" or null", .{}); } + if (facts.geometry == .none and (o.header or o.footer)) + return bad(a, fault, &.{ "body", if (o.header) "extract_header" else "extract_footer" }, "this model does not mark page headers or footers", .{}); const pages: ?[]const u32 = if (body.field("pages")) |v| try pageList(a, fault, v, facts.pages_left) else null; const bytes = try document(a, fault, body, facts); const image = switch (images.sniff(bytes)) { diff --git a/zig/src/server/ocr/mistral_reply.zig b/zig/src/server/ocr/mistral_reply.zig index 30c7e2237e7..fec25c381d9 100644 --- a/zig/src/server/ocr/mistral_reply.zig +++ b/zig/src/server/ocr/mistral_reply.zig @@ -75,7 +75,9 @@ pub const Encoder = struct { var blocks: std.ArrayList(Value) = .empty; for (page.blocks) |b| { if (b.kind == .picture) { - const box = geometry.mistralBox(b.quad); + // a picture without a box cannot be cropped or placed: no reader with geometry writes one + const q = b.quad orelse continue; + const box = geometry.mistralBox(q); if (!e.keeps(box)) continue; const id = try std.fmt.allocPrint(a, "img-{d}.jpeg", .{e.images}); e.images += 1; @@ -98,7 +100,8 @@ pub const Encoder = struct { try footer.append(a, t.markdown); } else if (std.mem.trim(u8, t.markdown, " \t\r\n").len > 0) try md.append(a, t.markdown); if (!e.o.blocks) continue; - const blk = try boxObject(a, "type", blockType(b.kind), geometry.mistralBox(b.quad)); + const q = b.quad orelse continue; // a .page block has no geometry and so no block entry + const blk = try boxObject(a, "type", blockType(b.kind), geometry.mistralBox(q)); try blk.put(a, "content", .{ .string = t.content }); if (b.kind == .table and e.o.tables != null) if (t.first) |tid| try blk.put(a, "table_id", .{ .string = tid }); try blocks.append(a, .{ .object = blk }); @@ -212,10 +215,10 @@ pub fn tableText(a: Allocator, mode: ?TableFormat, src: []const u8, is_html: boo return .{ .text = try html.pipe(a, parsed), .format = .markdown }; } -/// Mistral's block type for a kind (docs/api.md OCR: Mistral). +/// Mistral's block type for a kind (docs/api.md OCR: Mistral); ``page`` never reaches here, having no geometry. pub fn blockType(kind: api.ocr.Kind) []const u8 { return switch (kind) { - .text, .footnote => "text", + .text, .footnote, .page => "text", .title, .section_header => "title", .list => "list", .table => "table", diff --git a/zig/src/server/ocr/mistral_test.zig b/zig/src/server/ocr/mistral_test.zig index 1646f3e379d..d1b17961d63 100644 --- a/zig/src/server/ocr/mistral_test.zig +++ b/zig/src/server/ocr/mistral_test.zig @@ -56,7 +56,7 @@ test "ocr mistral: pages bounds hold before any allocation and dedupe within the } } -const facts: mistral.Facts = .{ .pdf = false, .fetch = null, .pages_left = 16 }; +const facts: mistral.Facts = .{ .geometry = .block, .pdf = false, .fetch = null, .pages_left = 16 }; /// A request body around ``doc`` (a document object) and ``extra`` fields. fn body(a: Allocator, doc: []const u8, extra: []const u8) !json.Value { @@ -130,7 +130,12 @@ test "ocr mistral: content-changing and malformed fields are refused with their return error.TestUnexpectedResult; } } + // a reader without geometry marks no headers or footers var fault: types.Fault = undefined; + const none: mistral.Facts = .{ .geometry = .none, .pdf = false, .fetch = null, .pages_left = 16 }; + try t.expectError(error.Faulted, mistral.decode(a, try body(a, doc, ", \"extract_footer\": true"), none, &fault)); + try t.expectEqualStrings("this model does not mark page headers or footers", fault.message); + _ = try mistral.decode(a, try body(a, doc, ", \"extract_footer\": false"), none, &fault); try t.expectError(error.Faulted, mistral.decode(a, try value(a, "[1]"), facts, &fault)); try t.expectError(error.Faulted, mistral.decode(a, try value(a, "{\"model\": null}"), facts, &fault)); try t.expectEqualStrings("document is required", fault.message); diff --git a/zig/src/server/ocr/prompt_ids_test.zig b/zig/src/server/ocr/prompt_ids_test.zig index ac98f45c7d4..5878aa331d0 100644 --- a/zig/src/server/ocr/prompt_ids_test.zig +++ b/zig/src/server/ocr/prompt_ids_test.zig @@ -112,7 +112,7 @@ const Recorder = struct { fn info(ctx: *anyopaque) api.Info { const r: *Recorder = @ptrCast(@alignCast(ctx)); const v: api.Vision = .{ .ctx = r, .prepare = prepare, .image_token = image_byte, .image_tokens = 64, .max_images = 4 }; - return .{ .context_window = 1 << 16, .vision = v, .ocr = .{ .prompt = r.reader, .parse = noBlocks } }; + return .{ .context_window = 1 << 16, .vision = v, .ocr = .{ .prompt = r.reader, .geometry = .block, .parse = noBlocks } }; } fn submit(ctx: *anyopaque, id: api.Id, req: *const api.Request, sink: api.Sink) api.SubmitError!void { const r: *Recorder = @ptrCast(@alignCast(ctx)); diff --git a/zig/src/server/ocr/run.zig b/zig/src/server/ocr/run.zig index d6ecdffd117..b778717d4e9 100644 --- a/zig/src/server/ocr/run.zig +++ b/zig/src/server/ocr/run.zig @@ -37,8 +37,8 @@ pub const PageSink = struct { pub const no_reader = "this model has no OCR reader; use POST /v1/chat/completions"; /// The gate's refusal for a server started without --vision. pub const no_vision = "OCR needs image input; start the server with --vision"; -/// The decoded-pixel limit of one page: dots.mocr's processor input limit, the one reader family's. -pub const max_page_pixels = picture.max_pixels; +/// The decoded-pixel limit of one page: GLM-OCR's processor input limit, the larger of the two reader families'. +pub const max_page_pixels = 32 << 20; /// Refuses as bad input unless the engine has an OCR reader and the server reads images. pub fn gate(srv: *const Server, a: Allocator, fault: *Fault) Step!void { @@ -175,10 +175,10 @@ fn onePage(srv: *Server, a: Allocator, reader: api.ocr.Ocr, id: []const u8, p: P }; const blocks = try a.alloc(api.ocr.OcrBlock, parsed.len); for (parsed, blocks) |b, *o| { - const quad = geometry.validate(b.quad, w, h) catch { + const quad: ?api.ocr.Quad = if (b.quad) |q| geometry.validate(q, w, h) catch { log.line("{s}: page {d}: a box is not finite: {s}", .{ id, p.index, got.content }); return fault.fail(a, .unreadable, "page {d}: the model's output has a box that is not finite", .{p.index}); - }; + } else null; o.* = .{ .content = try a.dupe(u8, b.content), .quad = quad, .kind = b.kind }; } const page: OcrPage = .{ .index = p.index, .width = w, .height = h, .dpi = p.dpi, .blocks = blocks }; diff --git a/zig/src/server/ocr/run_test.zig b/zig/src/server/ocr/run_test.zig index ba639072ad7..2793ea6c01b 100644 --- a/zig/src/server/ocr/run_test.zig +++ b/zig/src/server/ocr/run_test.zig @@ -62,7 +62,7 @@ test "ocr run: blocks scale from the frame, quads are validated, and the sink se var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); const a = arena.allocator(); - var h: Harness = .{ .replies = &.{ .{ .text = "title 10 5 90 10\n# T\n;;\ntext -5 40 120 60\nbody" }, .{ .text = "text 0 0 100 50\nall" } } }; + var h: Harness = .{ .replies = &.{ .{ .text = "title 10 5 90 10\n# T\n;;\ntext -5 40 120 60\nbody" }, .{ .text = "page\nall" } } }; try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }); defer h.stop(); var seen: Seen = .{}; @@ -73,11 +73,11 @@ test "ocr run: blocks scale from the frame, quads are validated, and the sink se try t.expectEqual(@as(u32, 200), p.width); try t.expectEqual(@as(u32, 72), p.dpi); try t.expectEqual([2]usize{ 200, 100 }, seen.sizes.items[0]); - try t.expectEqual(api.ocr.Quad{ .{ 20, 10 }, .{ 180, 10 }, .{ 180, 20 }, .{ 20, 20 } }, p.blocks[0].quad); + try t.expectEqual(api.ocr.Quad{ .{ 20, 10 }, .{ 180, 10 }, .{ 180, 20 }, .{ 20, 20 } }, p.blocks[0].quad.?); // a box past the page is clamped into it - try t.expectEqual(api.ocr.Quad{ .{ 0, 80 }, .{ 200, 80 }, .{ 200, 100 }, .{ 0, 100 } }, p.blocks[1].quad); + try t.expectEqual(api.ocr.Quad{ .{ 0, 80 }, .{ 200, 80 }, .{ 200, 100 }, .{ 0, 100 } }, p.blocks[1].quad.?); try t.expectEqualStrings("body", p.blocks[1].content); - try t.expectEqual(api.ocr.Quad{ .{ 0, 0 }, .{ 30, 0 }, .{ 30, 20 }, .{ 0, 20 } }, seen.pages.items[1].blocks[0].quad); + try t.expectEqual(@as(?api.ocr.Quad, null), seen.pages.items[1].blocks[0].quad); // the encode limit grew by four times each page's pixels try t.expectEqual(@as(u64, 4 * (200 * 100 + 30 * 20)), seen.limit); try t.expectEqual(@as(i64, 0), h.srv.preparing.load(.acquire)); @@ -146,7 +146,7 @@ test "ocr run: the encode budget is the whole request's, so a first page may use var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); const a = arena.allocator(); - var h: Harness = .{ .replies = &.{ .{ .text = "text 0 0 1 1\na" }, .{ .text = "text 0 0 1 1\nb" }, .{ .text = "text 0 0 1 1\nc" } } }; + var h: Harness = .{ .replies = &.{ .{ .text = "page\na" }, .{ .text = "page\nb" }, .{ .text = "page\nc" } } }; try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }); defer h.stop(); var g: Greedy = .{}; @@ -193,7 +193,7 @@ test "ocr run: an image whose first header and its pixels disagree is refused be var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); const a = arena.allocator(); - var h: Harness = .{ .replies = &.{.{ .text = "text 0 0 1 1\na" }} }; + var h: Harness = .{ .replies = &.{.{ .text = "page\na" }} }; try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }); defer h.stop(); const orders = [_][2][2]u32{ .{ .{ 80, 60 }, .{ 40, 30 } }, .{ .{ 40, 30 }, .{ 80, 60 } } }; @@ -431,9 +431,9 @@ test "ocr mistral: a page past the decoded-pixel limit answers 400 with the deco var h: Harness = undefined; try serve(&h, &.{.{ .text = "text 0 0 1 1\na" }}); defer h.stop(); - // 4097 x 4096 is 16 Mi pixels and 4096 more, under 8192 a side: only the pixel limit refuses it - const w = 4097; - const ht = 4096; + // 8192 x 4097 is 32 Mi pixels and 8192 more, under 8192 a side: only the pixel limit refuses it + const w = 8192; + const ht = 4097; try t.expect(@as(u64, w) * ht > run.max_page_pixels and @max(w, ht) <= picture.max_side); var status: u16 = 0; const r = try postPng(a, &h, try bigHeader(a, .{ w, ht }), "", &status); From 62a988d39b06e789fbddeafdf257fb545decfac8 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:29:22 +0000 Subject: [PATCH 019/265] test(ocr): prove a GLM-OCR page reads as its chat reply Issue 2440 asks that GLM-OCR's Markdown equal what the chat route returns for the same image and prompt. The prompt-id test gains GLM-OCR's prompt, so both routes give the model the same ids, and a scripted reply sent through POST /v1/ocr with a reader of GLM-OCR's contract and through /v1/chat/completions gives page Markdown equal to the chat content; the reader test shows the reply kept verbatim but for HTML tables and LaTeX delimiters. --- zig/src/server/ocr/page_markdown_test.zig | 51 +++++++++++++++++++++++ zig/src/server/ocr/prompt_ids_test.zig | 3 ++ zig/src/server/root.zig | 1 + 3 files changed, 55 insertions(+) create mode 100644 zig/src/server/ocr/page_markdown_test.zig diff --git a/zig/src/server/ocr/page_markdown_test.zig b/zig/src/server/ocr/page_markdown_test.zig new file mode 100644 index 00000000000..bda2ae25a6e --- /dev/null +++ b/zig/src/server/ocr/page_markdown_test.zig @@ -0,0 +1,51 @@ +//! A page-Markdown reader (geometry none, as GLM-OCR) through /v1/ocr against /v1/chat/completions for one reply. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const routes = @import("../routes.zig"); +const harness = @import("harness_test.zig"); +const Harness = harness.Harness; +const t = std.testing; +const Allocator = std.mem.Allocator; + +/// GLM-OCR's reader on Markdown without HTML tables or \( \[ math: the whole reply, trimmed, as one page block. +fn wholePage(a: Allocator, text: []const u8, _: api.Size, _: api.Size) anyerror![]api.ocr.OcrBlock { + const page = std.mem.trim(u8, text, &std.ascii.whitespace); + if (page.len == 0) return &.{}; + return a.dupe(api.ocr.OcrBlock, &.{.{ .content = page, .quad = null, .kind = .page }}); +} + +/// A POST through the dispatcher; the reply must be a 200, and its JSON body is returned. +fn post(a: Allocator, h: *Harness, path: []const u8, body: []const u8) !json.Value { + var wire: harness.Wire = .{ .a = a }; + routes.dispatch(h.srv, try harness.request(a, &wire, path, "application/json", body), a); + try t.expectEqual(@as(u16, 200), wire.status()); + return wire.parsed(); +} + +test "ocr mistral: a page-Markdown reader's page markdown is the chat route's reply for the same image and prompt" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // what GLM-OCR writes for a page: headings, a list, a pipe table, inline math and code, and a trailing newline + const reply = "# Invoice 0042\n\n- Apples: 3\n- Pears: 5\n\n| Item | Qty |\n| --- | --- |\n| Apples | 3 |\n\nArea $\\pi r^2$, `code`\n"; + var h: Harness = .{ .replies = &.{ .{ .text = reply }, .{ .text = reply } }, .reader = .{ .prompt = "Text Recognition:", .geometry = .none, .parse = wholePage } }; + try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }); + defer h.stop(); + const png = try harness.png(a, 40, 20); + const enc = std.base64.standard.Encoder; + const b64 = try a.alloc(u8, enc.calcSize(png.len)); + const url = try std.fmt.allocPrint(a, "data:image/png;base64,{s}", .{enc.encode(b64, png)}); + const ocr = try post(a, &h, "/v1/ocr", try std.fmt.allocPrint(a, "{{\"model\": \"m\", \"document\": {{\"type\": \"image_url\", \"image_url\": \"{s}\"}}}}", .{url})); + const chat_body = try std.fmt.allocPrint(a, "{{\"model\": \"m\", \"temperature\": 0, \"chat_template_kwargs\": {{\"enable_thinking\": false}}, " ++ + "\"messages\": [{{\"role\": \"user\", \"content\": [{{\"type\": \"image_url\", \"image_url\": {{\"url\": \"{s}\"}}}}, " ++ + "{{\"type\": \"text\", \"text\": \"Text Recognition:\"}}]}}]}}", .{url}); + const chat = try post(a, &h, "/v1/chat/completions", chat_body); + const content = chat.get("choices").?.array[0].get("message").?.strField("content").?; + try t.expectEqualStrings(reply, content); + const page = ocr.get("pages").?.array[0]; + // the page markdown is the reply byte for byte, only trimmed; a reader without boxes gives no blocks + try t.expectEqualStrings(std.mem.trim(u8, content, &std.ascii.whitespace), page.strField("markdown").?); + try t.expectEqual(@as(usize, 0), page.get("blocks").?.array.len); + try t.expectEqual(@as(usize, 0), page.get("tables").?.array.len); +} diff --git a/zig/src/server/ocr/prompt_ids_test.zig b/zig/src/server/ocr/prompt_ids_test.zig index 5878aa331d0..9641cbe590d 100644 --- a/zig/src/server/ocr/prompt_ids_test.zig +++ b/zig/src/server/ocr/prompt_ids_test.zig @@ -29,11 +29,14 @@ const dots_prompt = \\5. Answer with a single JSON object and nothing else. \\ ; +/// GLM-OCR's reader prompt (families/glm_ocr/ocr.zig). +const glm_prompt = "Text Recognition:"; /// The SHA-256 each family's reader test checks its prompt against: the prompt every oracle run recorded. const Pinned = struct { prompt: []const u8, sha256: []const u8 }; const readers = [_]Pinned{ .{ .prompt = dots_prompt, .sha256 = "c06a55ac6420f7b725306c52be3c5fe0822c0ae80b2a8565fc07607d9d0f5308" }, + .{ .prompt = glm_prompt, .sha256 = "77e8207573e1b8ba857d25db3a5080ae8651d6ddc2ea79007af5ca7958b80017" }, }; /// The template's image placeholder: a byte no request text holds. diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 4f3fe6b754d..9ea6fcfd2e1 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -355,6 +355,7 @@ test { _ = @import("ocr/geometry_test.zig"); _ = @import("ocr/markdown_test.zig"); _ = @import("ocr/budget_test.zig"); + _ = @import("ocr/page_markdown_test.zig"); _ = @import("ocr/mistral_test.zig"); _ = @import("ocr/mistral_sdk_test.zig"); _ = @import("ocr/run_test.zig"); From 8c7e2134bdf1a1b6e9528267c946a029064ef97d Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:31:42 +0000 Subject: [PATCH 020/265] docs(ocr): document the GLM-OCR reader on POST /v1/ocr The API guide named one reader. It now lists GLM-OCR with its single page block, the header and footer refusal for a reader without boxes, and the context a dense page needs under GLM-OCR's default window; the changelog line stays with the maintainer. --- docs/api.md | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/api.md b/docs/api.md index 308e95118c3..5fbe0e39c6d 100644 --- a/docs/api.md +++ b/docs/api.md @@ -281,12 +281,13 @@ and `--vision`. | --- | --- | --- | --- | --- | | `POST /v1/ocr` | Mistral OCR | JSON `{"model", "document", ...}` | `{"pages", "model", "document_annotation", "usage_info"}` | the `mistralai` Python and `@mistralai/mistralai` TypeScript SDKs, with `server_url` set to the server root | -One family has a reader. A reader gives Markdown blocks in pixels of the page the client sent (after EXIF +Two families have a reader. A reader gives Markdown blocks in pixels of the page the client sent (after EXIF orientation), never in the model's resized frame. | Model | What the reader returns | Geometry | | --- | --- | --- | | dots.mocr | one block a layout region (title, text, table, formula, picture, header, footer, ...), tables as pipe tables or, when cells span, HTML | a box a block | +| GLM-OCR | the page's Markdown as one block, tables as pipe tables or spanned HTML | none | Any other model answers the route with HTTP 400 "this model has no OCR reader; use POST /v1/chat/completions", and a server started without `--vision` answers "OCR needs image input; start the server with --vision". @@ -295,7 +296,7 @@ key scope. ### Reader Markdown -The reader writes block text in one Markdown flavour, the one Mistral's page Markdown uses: +Both readers write block text in one Markdown flavour, the one Mistral's page Markdown uses: - Headings with `#` markers: a title is `#`, a section header `##` unless the model gives a level. - GFM pipe tables, or one HTML `
` when a table has row or column spans a pipe table cannot hold; a table @@ -304,12 +305,13 @@ The reader writes block text in one Markdown flavour, the one Mistral's page Mar - Lists with `-` or `1.` markers, and code in fenced blocks. - No images: a picture block has empty text, and its caption, if any, is its own block. The contract writes its own image references. +- GLM-OCR's single block holds the whole page's Markdown, headings, tables and math included. ### Pages and budgets - Images are PNG, JPEG or WebP, one page each, up to the 32 MiB body limit and the reader's decoded-pixel limit: - 16 megapixels and 8192 pixels a side for dots.mocr; a larger image is bad input. An image whose header and - decoded pixels disagree is refused as bad input. + 16 megapixels and 8192 pixels a side for dots.mocr, 32 megapixels for GLM-OCR; a larger image is bad input. An + image whose header and decoded pixels disagree is refused as bad input. - PDFs need `--vision-pdf`. PDFium renders each selected page at up to 144 DPI, at most 2048 pixels a side and about 3.6 megapixels; boxes and sizes are in pixels of the rendered page. Mistral reports that DPI (72 for an image). Every PDF of a request is measured before the first page is read (its page count and each selected @@ -353,7 +355,7 @@ stops the request before its next page or PDF render. | `document` | `{"type": "document_url", "document_url"}` or `{"type": "image_url", "image_url"}` (a string or `{"url"}`): a `data:` URL, or an `https://` URL as above. The bytes decide PDF or image. `{"type": "file"}` is HTTP 400 | | `pages` | 0-based page indices as a list or a string such as `"0,2-4"`; duplicates are merged. An image has only page `0`. At most 1024 entries (a range counts its length) before merging, and the page budget after | | `table_format` | Null: tables stay in the page Markdown as pipe tables (a spanned HTML table becomes a pipe table with the spanned text in its first cell). `"markdown"` or `"html"`: each table becomes a `tables[]` entry (`tbl-N.md` or `tbl-N.html`) and the Markdown links it; under `"markdown"` a table with spanned cells stays HTML, the only form that keeps it | -| `extract_header`, `extract_footer` | Move page headers or footers out of `markdown` into `header` and `footer` | +| `extract_header`, `extract_footer` | Move page headers or footers out of `markdown` into `header` and `footer`. GLM-OCR marks neither, so `true` is HTTP 400 "this model does not mark page headers or footers" | | `include_blocks` | Default `true`: one block for each region with a box. `false` leaves `blocks` out | | `image_limit`, `image_min_size` | Choose which pictures to keep, in reading order (`image_min_size` against the box's width and height, then the running count against `image_limit`). A dropped picture has no image entry, Markdown link or block | | `include_image_base64` | Add `image_base64`, a `data:image/jpeg;base64,...` crop of the picture's box, to each kept image | @@ -367,6 +369,12 @@ stops the request before its next page or PDF render. `content`, its own Markdown with its tables in the `table_format` form; image blocks add `image_id` and table blocks `table_id`. `usage_info` gives `pages_processed` and `doc_size_bytes`, the decoded document's size. +### GLM-OCR context + +GLM-OCR's default 8192-token window leaves about 2000 tokens for the reply after a full image budget (6144 +tokens). A dense page needs more: start the server with a larger `--context`, or such pages fail as unreadable, +"the model's output was cut at the context limit". + ## System One on a Clef engine `POST /v1/systemone` on a Clef checkpoint (Cloudflare's clef-flash: BF16 Qwen3.5 weights with From acf5a6c5f1a1492b4513a36216c2c0461fc5e4e3 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:00:10 +0000 Subject: [PATCH 021/265] changelog: #2572 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ef9bda7544..77ec79e4782 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- OCR: GLM-OCR on native HIP serves `POST /v1/ocr`, returning normalized page Markdown with pipe or spanned-HTML tables and `$`/`$$` math, `blocks: []` because it has no geometry, and named refusals for header/footer extraction (#2572). Thanks to @laudney. + - MiniMax-H3-Image on Metal: `tf-h3-image-encoder` turns an edit's reference pictures into their clean rows with the VAE's encoder in fp32 on any Apple GPU, with a selftest of each kernel against a float64 host reference; the reference rules (sizes, crops, grids, encoder layers, clean and anchor rows) run on the host (#2778, on #2775). - GLM on Metal: vectorized prompt, KDA and indexer kernels on Macs without tensor units cut cold prompt time 5.17% to 5.68% (2K to 64K tokens) with 0/64 token differences (#3921, refs #3152). Thanks to @gilby. From 759347105954176a3f12f50345946c5f9e99ce92 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:00:10 +0000 Subject: [PATCH 022/265] changelog: #2572 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77ec79e4782..183b17320a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - OCR: GLM-OCR on native HIP serves `POST /v1/ocr`, returning normalized page Markdown with pipe or spanned-HTML tables and `$`/`$$` math, `blocks: []` because it has no geometry, and named refusals for header/footer extraction (#2572). Thanks to @laudney. + + - MiniMax-H3-Image on Metal: `tf-h3-image-encoder` turns an edit's reference pictures into their clean rows with the VAE's encoder in fp32 on any Apple GPU, with a selftest of each kernel against a float64 host reference; the reference rules (sizes, crops, grids, encoder layers, clean and anchor rows) run on the host (#2778, on #2775). - GLM on Metal: vectorized prompt, KDA and indexer kernels on Macs without tensor units cut cold prompt time 5.17% to 5.68% (2K to 64K tokens) with 0/64 token differences (#3921, refs #3152). Thanks to @gilby. From 80dfd8182623ac2cd7a3f9e5a8173a7ddf789f7c Mon Sep 17 00:00:00 2001 From: devopsfortunato <57877156+devopsfortunato@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:03:39 +0100 Subject: [PATCH 023/265] server: --vision-image-share fixed gives every image the same share of the visual-token budget (#2510) The default stays the per-request split, so replies without the flag are unchanged. With fixed, each image takes --vision-image-tokens / --vision-max-images whatever the request's image count, so a turn that adds an image leaves earlier images' rows where they were and the prompt cache resumes from the first image. A share of 0 is refused naming both flags. --- docs/recipes/dots-mocr-hip.md | 4 +- docs/vision.md | 19 ++- zig/src/core/engine_api.zig | 1 + zig/src/core/engine_vision.zig | 9 +- zig/src/families/dots_mocr/hip_native.zig | 1 + zig/src/families/glm_ocr/hip_native.zig | 2 +- .../lighton_ocr/backend/hip/native.zig | 2 +- .../lighton_ocr/backend/hip/vision.zig | 1 + zig/src/families/nemotron_parse/hip.zig | 2 +- zig/src/hip_serve/vision.zig | 1 + zig/src/native/cuda_vision_offer.zig | 4 +- zig/src/native/flashnext_images.zig | 2 +- zig/src/native/gemma4.zig | 2 +- zig/src/native/glm_host.zig | 2 +- zig/src/native/minimax_m3.zig | 2 +- zig/src/native/qwen27_served.zig | 2 +- zig/src/native/step5.zig | 2 +- zig/src/native/uocr.zig | 2 +- zig/src/server/cli.zig | 16 +- zig/src/server/cli_test.zig | 12 +- zig/src/server/image_reuse_test.zig | 97 ++++++++++- zig/src/server/image_share_test.zig | 154 ++++++++++++++++++ zig/src/server/images.zig | 11 +- zig/src/server/root.zig | 1 + 24 files changed, 310 insertions(+), 41 deletions(-) create mode 100644 zig/src/server/image_share_test.zig diff --git a/docs/recipes/dots-mocr-hip.md b/docs/recipes/dots-mocr-hip.md index a3a80b8a1f7..284e31968a9 100644 --- a/docs/recipes/dots-mocr-hip.md +++ b/docs/recipes/dots-mocr-hip.md @@ -44,7 +44,9 @@ thinking setting. `return_token_ids: true` also returns the IDs in the The default total image budget is 14,400 merged tokens per request. `--vision-image-tokens` sets a different total budget, divided across -the images. Each image has independent tower attention. Quoted image +the images; `--vision-image-share fixed` divides it over +`--vision-max-images` instead, so each image keeps its rows as later +turns add pictures. Each image has independent tower attention. Quoted image markers remain text. Video, tensor parallelism, MTP heads, external drafters, and incompatible quantized checkpoints are refused. Copy proposals remain available with ordinary `draft: true` requests. diff --git a/docs/vision.md b/docs/vision.md index 073d9e05982..fbcfe945414 100644 --- a/docs/vision.md +++ b/docs/vision.md @@ -117,9 +117,17 @@ the images. Remove older image content from the submitted history, start a new c the server with a larger count limit. The server does not discard images automatically. A request's images share 4,096 visual tokens, so a higher count makes each image smaller: eight images get about -512 tokens each. On CUDA Qwen checkpoints (Qwen3.5/3.8 dense and Flash Next), `--vision-image-tokens N` raises -that shared budget, up to 65,536, while each image keeps at most 4,096, so one image is sized as before. The tower -encodes runs of whole images of at most 16,384 patches, the scratch one full-size image already needs; a request +512 tokens each. `--vision-image-share fixed` trades that for a stable share: every image then takes +`--vision-image-tokens / --vision-max-images` tokens, 1,024 under the defaults, whatever the request's own image +count. A lone image therefore gets less than the default gives it, and in return an image keeps its rows from one +turn to the next, so the prompt cache resumes from the first image instead of re-encoding it. The flag takes +`request` (the default, the request's own count) or `fixed`; any other value is refused by name, and it matters only +together with `--vision`. Where a share divides into nothing — a budget below the image limit — the request is +refused, naming the image and both `--vision-image-tokens` and `--vision-max-images`. +On CUDA Qwen checkpoints (Qwen3.5/3.8 dense and Flash Next), `--vision-image-tokens N` raises +that shared budget, up to 65,536, while each image keeps at most 4,096, so one image is sized as before; under +`--vision-image-share fixed` an image keeps the smaller of that 4,096 and `--vision-image-tokens / --vision-max-images`. +The tower encodes runs of whole images of at most 16,384 patches, the scratch one full-size image already needs; a request that fits one run is encoded in one call, as before. The byte and pixel limits still apply, and the longer prompt counts against the context window. @@ -145,8 +153,9 @@ For Qwen, each image request carries its own multimodal rotary positions and con ## The native server -`tensorfold-native serve` takes `--vision`, `--vision-max-images` (default 4) and `--vision-image-tokens` (default -4,096; 13,312 for Nemotron 3.5 Super VL) for engines that read images: GLM-5.3-Flash, Qwen3.8-27B, Qwen3.8 Flash Next, Gemma 4 +`tensorfold-native serve` takes `--vision`, `--vision-max-images` (default 4), `--vision-image-tokens` (default +4,096; 13,312 for Nemotron 3.5 Super VL) and `--vision-image-share` (`request`, the default, or `fixed`) for engines +that read images: GLM-5.3-Flash, Qwen3.8-27B, Qwen3.8 Flash Next, Gemma 4 [31B](recipes/gemma-4-native.md#images) and [12B](recipes/gemma-4-12b-native.md#images) and Step-5-Preview on one Mac, GLM-5.3-Flash on [CUDA ranks](recipes/glm-5.3-flash-cuda.md#requests) and Nemotron 3.5 Super VL on CUDA. Other native engines refuse the flag at startup. diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index 4e74ef7e623..3195f3e790f 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -121,6 +121,7 @@ pub const FrameSink = vision_types.FrameSink; pub const PreparedVideo = vision_types.PreparedVideo; pub const VideoOffer = vision_types.VideoOffer; pub const VisionOpen = vision_types.VisionOpen; +pub const ImageShare = vision_types.ImageShare; pub const Size = vision_types.Size; pub const ocr = @import("engine_ocr.zig"); diff --git a/zig/src/core/engine_vision.zig b/zig/src/core/engine_vision.zig index 285b697bbe0..1f0ae2720c7 100644 --- a/zig/src/core/engine_vision.zig +++ b/zig/src/core/engine_vision.zig @@ -23,6 +23,9 @@ pub const Size = struct { width: u32, height: u32 }; /// One tower input of an image, and the tokens the placeholder expands to around its rows. pub const Piece = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, before: []const u32 = &.{}, after: []const u32 = &.{} }; +/// How a request's images share ``image_tokens`` (--vision-image-share): its own count, or the image limit (#2510). +pub const ImageShare = enum { request, fixed }; + /// Image input an engine serves (``Info.vision``): image bytes to tower input, and what a request may hold. pub const Vision = struct { ctx: *anyopaque, @@ -38,6 +41,8 @@ pub const Vision = struct { /// Image tokens one request may hold in all, and images. image_tokens: u32, max_images: u32, + /// How the images share ``image_tokens``: the request's count, or the fixed share over ``max_images``. + image_share: ImageShare = .request, /// Video input, when the engine's family reads it. video: ?VideoOffer = null, /// The engine's words for a prepare error the server cannot word (a decoder library it lacks); null: the server's. @@ -85,5 +90,5 @@ pub const VideoOffer = struct { max_frames: u32, }; -/// --vision: image and video input's limits (``Open.vision``); image_tokens_set: the flag given, over a family default. -pub const VisionOpen = struct { image_tokens: u32 = 4096, image_tokens_set: bool = false, max_images: u32 = 4, video_tokens: u32 = 16384, max_videos: u32 = 2, max_frames: u32 = 256 }; +/// --vision's limits (``Open.vision``); image_tokens_set: the flag given; image_share: --vision-image-share's value. +pub const VisionOpen = struct { image_tokens: u32 = 4096, image_tokens_set: bool = false, max_images: u32 = 4, video_tokens: u32 = 16384, max_videos: u32 = 2, max_frames: u32 = 256, image_share: ImageShare = .request }; diff --git a/zig/src/families/dots_mocr/hip_native.zig b/zig/src/families/dots_mocr/hip_native.zig index cd26e347487..82d36c983bd 100644 --- a/zig/src/families/dots_mocr/hip_native.zig +++ b/zig/src/families/dots_mocr/hip_native.zig @@ -95,6 +95,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.D .part_type = "image", .image_tokens = @intCast(image_tokens), .max_images = v.max_images, + .image_share = v.image_share, } else null; return .{ .backend = back.backend(), .facts = .{ .exact_width = @intCast(rows), .drafts = 0, .mtp = false, .copy_drafts = true, .streams_exact = true }, .rows = @intCast(e.p.rows), .streams = e.p.streams, .ctx = own, .deinit = Owner.close, .startup = startup, .offer = .{ .vision = vision, diff --git a/zig/src/families/glm_ocr/hip_native.zig b/zig/src/families/glm_ocr/hip_native.zig index 8273ab2ebb6..1907d8b7860 100644 --- a/zig/src/families/glm_ocr/hip_native.zig +++ b/zig/src/families/glm_ocr/hip_native.zig @@ -75,7 +75,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.D errdefer gpa.destroy(own); const startup = try std.fmt.allocPrint(gpa, "GLM-OCR BF16 on HIP {s}, device {d}; {d} shared lanes at context {d}; exact verification through 32 rows; full-shape prompt cache {d} bytes in at most {d} slots", .{ hip.kernels.arch, dev.index, e.streams, e.window, e.cache_bytes, e.cache_slots }); own.* = .{ .gpa = gpa, .e = e, .h = h, .startup = startup }; - const vision: ?api.Vision = if (o.vision) |v| .{ .ctx = own, .prepare = prepare, .image_token = c.image_token, .markers = &markers, .part_type = "image", .image_tokens = if (v.image_tokens_set) v.image_tokens else 6144, .max_images = v.max_images, .explain = @import("sys").optional_libraries.explain } else null; + const vision: ?api.Vision = if (o.vision) |v| .{ .ctx = own, .prepare = prepare, .image_token = c.image_token, .markers = &markers, .part_type = "image", .image_tokens = if (v.image_tokens_set) v.image_tokens else 6144, .max_images = v.max_images, .image_share = v.image_share, .explain = @import("sys").optional_libraries.explain } else null; return .{ .backend = h.backend(), .facts = h.facts(), .ctx = own, .deinit = release, .streams = e.streams, .startup = startup, .offer = .{ .vision = vision, .ocr = ocr.reader, diff --git a/zig/src/families/lighton_ocr/backend/hip/native.zig b/zig/src/families/lighton_ocr/backend/hip/native.zig index e36d64b7e9d..503d8dcda05 100644 --- a/zig/src/families/lighton_ocr/backend/hip/native.zig +++ b/zig/src/families/lighton_ocr/backend/hip/native.zig @@ -156,7 +156,7 @@ fn load(gpa: Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: anytype defer ck.close(); own.layout = try weights.Layout.init(gpa, &ck, c); errdefer own.layout.deinit(); - const limits: ?vision.Limits = if (@hasField(@TypeOf(o), "vision")) if (o.vision) |v| .{ .image_tokens = @intCast(@min(v.image_tokens, o.window)), .max_images = v.max_images } else null else null; + const limits: ?vision.Limits = if (@hasField(@TypeOf(o), "vision")) if (o.vision) |v| .{ .image_tokens = @intCast(@min(v.image_tokens, o.window)), .max_images = v.max_images, .image_share = v.image_share } else null else null; if (limits != null) try image.readProcessor(gpa, io, dir, c); const plan = try Plan.init(c, own.layout.bytes, o.window, limits); own.r = try hip.Runtime.open(); diff --git a/zig/src/families/lighton_ocr/backend/hip/vision.zig b/zig/src/families/lighton_ocr/backend/hip/vision.zig index ebf49db42c6..ee2abe1ad33 100644 --- a/zig/src/families/lighton_ocr/backend/hip/vision.zig +++ b/zig/src/families/lighton_ocr/backend/hip/vision.zig @@ -10,6 +10,7 @@ const cancels = @import("hip_serve").cancel; pub const Limits = struct { image_tokens: u32, max_images: u32, + image_share: @import("engine_api").ImageShare = .request, pub fn check(l: Limits, context: usize) !void { if (l.image_tokens == 0 or l.image_tokens > context or l.max_images == 0 or l.max_images > 64) diff --git a/zig/src/families/nemotron_parse/hip.zig b/zig/src/families/nemotron_parse/hip.zig index b4100027e96..75733da1514 100644 --- a/zig/src/families/nemotron_parse/hip.zig +++ b/zig/src/families/nemotron_parse/hip.zig @@ -90,7 +90,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.D const startup = try std.fmt.allocPrint(gpa, "HIP Nemotron Parse BF16: {d} streams, {d} context rows including image; native RADIO and mBART, one-step MTP", .{ e.streams, e.window }); own.* = .{ .a = gpa, .e = e, .h = h, .startup = startup, .image_tokens = @min(o.vision.?.image_tokens, engine.max_image_rows) }; return .{ .backend = h.backend(), .facts = h.facts(), .rows = @import("backend.zig").max_window, .ctx = own, .deinit = release, .streams = e.streams, .startup = startup, .offer = .{ - .vision = .{ .ctx = own, .prepare = prepare, .image_token = 1, .markers = &.{1}, .image_tokens = own.image_tokens, .max_images = 1 }, + .vision = .{ .ctx = own, .prepare = prepare, .image_token = 1, .markers = &.{1}, .image_tokens = own.image_tokens, .max_images = 1, .image_share = o.vision.?.image_share }, .cache = if (h.cache.budget > 0) &h.cache else null, } }; } diff --git a/zig/src/hip_serve/vision.zig b/zig/src/hip_serve/vision.zig index 49f9647a1a0..db705508463 100644 --- a/zig/src/hip_serve/vision.zig +++ b/zig/src/hip_serve/vision.zig @@ -19,6 +19,7 @@ pub fn offer(tower: anytype) ?api.Vision { .image_token = x.c.image_token, .image_tokens = x.limits.image_tokens, .max_images = x.limits.max_images, + .image_share = if (comptime @hasField(@TypeOf(x.limits), "image_share")) x.limits.image_share else .request, .explain = T.explain, }; if (comptime @hasField(T, "markers")) { diff --git a/zig/src/native/cuda_vision_offer.zig b/zig/src/native/cuda_vision_offer.zig index 7a3e00ac534..f0a0b398e62 100644 --- a/zig/src/native/cuda_vision_offer.zig +++ b/zig/src/native/cuda_vision_offer.zig @@ -19,11 +19,11 @@ pub fn offer(v: anytype, open: ?api.VisionOpen) ?api.Vision { if (comptime T == qwen35.native.vision.Vision) { // the template writes Qwen's vision_start and vision_end around the image token itself const image = x.shared.image_token; - return .{ .ctx = x, .prepare = prepare, .image_token = image, .markers = &x.markers, .image_tokens = x.limits.image_tokens, .max_images = x.limits.max_images, .explain = T.explain }; + return .{ .ctx = x, .prepare = prepare, .image_token = image, .markers = &x.markers, .image_tokens = x.limits.image_tokens, .max_images = x.limits.max_images, .image_share = if (open) |o| o.image_share else .request, .explain = T.explain }; } // a template that writes each image's begin and end itself: the server expands the image token alone const wrap: ?[2]u32 = if (@hasDecl(T, "template_wraps")) null else .{ x.marks.open, x.marks.close }; - var out: api.Vision = .{ .ctx = x, .prepare = prepare, .image_token = x.marks.image, .markers = &x.mark_ids, .wrap = wrap, .image_tokens = x.limits.image_tokens, .max_images = x.limits.max_images, .explain = T.explain }; + var out: api.Vision = .{ .ctx = x, .prepare = prepare, .image_token = x.marks.image, .markers = &x.mark_ids, .wrap = wrap, .image_tokens = x.limits.image_tokens, .max_images = x.limits.max_images, .image_share = if (open) |o| o.image_share else .request, .explain = T.explain }; if (comptime @hasDecl(T, "part_type")) out.part_type = T.part_type; // the template's name for an image part if (comptime T == nemotron.native.vision.Vision) { // video: the checkpoint's temporal projection, and a reserved token for the template's `