diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bbac8260fa..6639f0000f4 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 +- Qwen3.8-27B on Metal before M5: decode rounds read their cached keys through the prefix kernels, as on an M5, and prompt passes size their memory the same way; `TF_QWEN27_SHARED_PREFIX=0` keeps cached keys on the tail kernel (#3677, refs #3604). Thanks to @hobbesd. + - CLI: `tensorfold models` lists the chat checkpoints from the supported-models guide that fit this machine, largest first, with the memory each needs, a quality score from TensorFold Web's quality suite (receipts in `docs/receipts/quality-suite`) and a rough one-stream speed (measured on this chip, or estimated from another chip by memory bandwidth); `--all` adds the rest, `--json` adds `machine` and `catalog` to schema 1, and the cached checkpoints follow as before (#3483). - gpt-oss: a first host-only slice reads `openai/gpt-oss-20b`'s config and refuses unknown or unsupported fields by name, checks all 459 tensor names of the published checkpoint, and adds an MXFP4 reader for 32-value E2M1 blocks with UE8M0 scales that never rewrites checkpoint bytes; nothing is registered with the server yet (#3513). diff --git a/docs/environment.md b/docs/environment.md index bf11b83c5f3..8bb4c15759d 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -63,6 +63,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | | `TF_FLASHNEXT_SCALE_INDEX` | Flash Next on Metal before tensor units: exactly `0` or `1`; default 1, where the 4-bit expert kernels (decode, grouped and prompt gathers) read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values from fewer weight bytes, and the routed experts' stored scales and biases are not kept in memory; `0` keeps and reads the stored arrays; ignored with `--ssd-experts` | | `TF_FLASHNEXT_GROUPED_ROWS` | Flash Next on Metal without tensor units: `0`, or the rows (`1` through `32`) from which a decode window runs its 4-bit experts grouped by expert, with the same output bits; default 5; ignored with `--ssd-experts` and in speed-up mode | +| `TF_QWEN27_SHARED_PREFIX` | Qwen3.8-27B on Metal before M5: exactly `0` or `1`; `0` keeps cached keys on the tail attention kernel; unset or blank is `1` | | `TF_QWEN27_SLOT_RESUME` | Qwen3.8-27B on Metal: exactly `0` or `1`; `0` stops slot 0 resuming a later prompt; unset or blank keeps it on | | `TF_QWEN27_METAL_KV_PAGES` | Qwen3.8-27B on Metal: exactly `0` or `1`; `1` puts keys and values in core-pool pages (refused on Macs with tensor units); unset or blank is `0` | | `TF_QWEN27_JOIN` | Qwen3.8-27B on Metal before M5: exactly `0` or `1`; `1` runs a window's rows in pairs over the keys below it in the decode tail attention (same replies); unset or blank is `1` | diff --git a/zig/build/qwen27.zig b/zig/build/qwen27.zig index 53a9cb00f17..30d289f1ba1 100644 --- a/zig/build/qwen27.zig +++ b/zig/build/qwen27.zig @@ -107,7 +107,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu const family: []const std.Build.Module.Import = &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "core", .module = qwen_core }, .{ .name = "metal", .module = metal } }; _ = program(b, "tf-qwen27-run", "Build the native greedy, chunk and prompt-speed check on real weights", "zig/tests/qwen27/run.zig", target, true, &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "core", .module = qwen_core }, .{ .name = "metal", .module = metal }, .{ .name = "core_lane", .module = core_lane }, .{ .name = "qwen_runtime_sources", .module = s.runtime_sources }, .{ .name = "qwen_gdn_source", .module = s.gdn_source } }); - _ = program(b, "tf-qwen27-attention-fused", "Build the fused-chain versus tail-kernel attention byte check on this Mac's tensor units, no models", "zig/tests/qwen27/attention_fused.zig", target, false, &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "metal", .module = metal }, .{ .name = "qwen_runtime_sources", .module = s.runtime_sources } }); + _ = program(b, "tf-qwen27-attention-fused", "Build the fused-chain versus tail-kernel attention byte check on this Mac's GPU, no models", "zig/tests/qwen27/attention_fused.zig", target, false, &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "metal", .module = metal }, .{ .name = "qwen_runtime_sources", .module = s.runtime_sources } }); _ = program(b, "tf-qwen27-attention-pages", "Build the KV-page attention kernels against main's, bit for bit through shuffled pages, no models", "zig/tests/qwen27/attention_pages.zig", target, false, &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "metal", .module = metal } }); _ = program(b, "tf-qwen27-attention-share", "Build the KV-page attention timed with streams on one prefix's pages against copies, no models", "zig/tests/qwen27/attention_share.zig", target, false, &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "metal", .module = metal } }); _ = program(b, "tf-qwen27-attention-precision", "Build decode attention's error against a float64 reference on this Mac, no models", "zig/tests/qwen27/attention_precision.zig", target, false, &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "metal", .module = metal }, .{ .name = "qwen_runtime_sources", .module = s.runtime_sources } }); diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 3db4d341fd4..309103c8d83 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -88,7 +88,7 @@ pub const Runner = struct { fn build(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32, ready: u32, paged: bool) !Runner { if (slots == 0 or slots > attn.planning.max_streams or capacity == 0 or m.frame.capacity % 16 != 0 or ready == 0 or ready > slots) return error.BadRoundCapacity; - const geometry = try attn.planning.Geometry.fromConfig(m.config, m.device.tensorUnits()); + const geometry = try attn.planning.Geometry.fromConfig(m.config, try @import("simd_attention.zig").sharedPrefix(m.device.tensorUnits())); const linear_index = try a.alloc(u32, m.config.layers); errdefer a.free(linear_index); const attention_index = try a.alloc(u32, m.config.layers); diff --git a/zig/src/families/qwen27/simd_attention.zig b/zig/src/families/qwen27/simd_attention.zig index 695489a10ad..512f2e39bc6 100644 --- a/zig/src/families/qwen27/simd_attention.zig +++ b/zig/src/families/qwen27/simd_attention.zig @@ -30,7 +30,44 @@ const rewrites = [_][2][]const u8{ }, }; -/// The attention kernels as this chip builds them (before M5: the tail rewritten, the prompt kernels if `prompt`). +/// The prefix kernels before M5: scores 16 x 64 (row half at i & 16), outputs 16 x 128, sums in the tail's order. +const prefix_rewrites = [_][2][]const u8{ + .{ " const short fn = ((qid & 2) | (lane & 1)) * 4;\n", " const short fn = ((lane & 8) >> 1) | ((lane & 1) << 1);\n" }, + .{ + " const int key = kt + (i >> 3) * 16 + fn + (i & 3);\n s[i] = key < ((i & 4) ? e1 : e0) ? S[i] * scale[0] : -INFINITY;\n", + " const int key = kt + fn + (i & 1) + 8 * ((i >> 1) & 7);\n s[i] = key < ((i & 16) ? e1 : e0) ? S[i] * scale[0] : -INFINITY;\n", + }, + .{ "{ if (i & 4) x1 = max(x1, s[i]); else x0 = max(x0, s[i]); }", "{ if (i & 16) x1 = max(x1, s[i]); else x0 = max(x0, s[i]); }" }, + .{ "fast::exp(s[i] - ((i & 4) ? nm1 : nm0));", "fast::exp(s[i] - ((i & 16) ? nm1 : nm0));" }, + .{ + " y0 += (p[b * 8] + p[b * 8 + 1]) + (p[b * 8 + 2] + p[b * 8 + 3]);\n y1 += (p[b * 8 + 4] + p[b * 8 + 5]) + (p[b * 8 + 6] + p[b * 8 + 7]);\n", + " y0 += (p[b * 4] + p[b * 4 + 1]) + (p[b * 4 + 2] + p[b * 4 + 3]);\n y1 += (p[b * 4 + 16] + p[b * 4 + 17]) + (p[b * 4 + 18] + p[b * 4 + 19]);\n", + }, + .{ " for (int i = 0; i < 64; i++) O[i] *= (i & 4) ? f1 : f0;\n", " for (int i = 0; i < 64; i++) O[i] *= (i & 32) ? f1 : f0;\n" }, + .{ + " const int b = d >> 4, u = d & 3;\n", + " const int at = ((d >> 3) << 1) | (d & 1); // element 2 (d / 8) + d % 2 (+ 16) of the lane with fn = d % 8 rounded to 2\n", + }, + .{ + " if ((i >> 2) == b && (i & 3) == u) { va = p[(i >> 2) * 8 + (i & 3)]; vb = p[(i >> 2) * 8 + 4 + (i & 3)]; }\n const short g = (d >> 2) & 3;\n", + " if (i == at) { va = p[i]; vb = p[16 + i]; }\n const short g = (d >> 1) & 3;\n", + }, + .{ + " for (int t = 0; t < 8; t++)\n for (int x = 0; x < 4; x++) {\n const float val = float(vk[t * 16 + x]);\n if (key < e0) O[t * 8 + x] += pa * val;\n if (key < e1) O[t * 8 + 4 + x] += pb * val;\n", + " for (int t = 0; t < 16; t++)\n for (int x = 0; x < 2; x++) {\n const float val = float(vk[t * 8 + x]);\n if (key < e0) O[t * 2 + x] += pa * val;\n if (key < e1) O[32 + t * 2 + x] += pb * val;\n", + }, + .{ + " for (int q = 0; q < 16; q++) {\n if ((q & 1) ? q1 >= G * NQ : q0 >= G * NQ) continue;\n device float* dst = PO + (base + tile * 16 + fm + (q & 1) * 8) * D + (hi ? 128 : 0) + (q >> 1) * 16 + fn;\n *(device float4*)dst = float4(O[4 * q], O[4 * q + 1], O[4 * q + 2], O[4 * q + 3]);\n", + " for (int q = 0; q < 32; q++) {\n if ((q / 16) ? q1 >= G * NQ : q0 >= G * NQ) continue;\n device float* dst = PO + (base + tile * 16 + fm + (q / 16) * 8) * D + (hi ? 128 : 0) + fn + 8 * (q % 16);\n *(device float2*)dst = float2(O[2 * q], O[2 * q + 1]);\n", + }, +}; + +/// Whether cached keys take the batched prefix kernels: M5 always; before M5 unless TF_QWEN27_SHARED_PREFIX=0. +pub fn sharedPrefix(units: bool) !bool { + return units or try @import("sys").environment.read(bool, "TF_QWEN27_SHARED_PREFIX", true); +} + +/// The attention kernels as this chip builds them (before M5: prefix and tail rewritten, prompt kernels if `prompt`). pub fn library(a: std.mem.Allocator, units: bool, prompt: bool) ![]u8 { return compose(a, units, prompt, @import("qwen_runtime_sources")); } @@ -72,22 +109,28 @@ pub fn joined(a: std.mem.Allocator, units: bool, prompt: bool, group: u32, kv_he return std.mem.concat(a, u8, &.{ "#define Q27_JOIN 1\n", body }); } -/// The attention source with the tail kernel's result indexing in the simdgroup-matrix layout; the caller frees it. +/// The attention source, its prefix and tail kernels indexing results in the simdgroup-matrix layout; caller frees. pub fn rewrite(a: std.mem.Allocator, source: []const u8) ![]u8 { - const begin = std.mem.indexOf(u8, source, "kernel void q27_attn_tail(") orelse return error.AttentionSource; - const end = begin + (std.mem.indexOf(u8, source[begin..], "kernel void q27_attn_merge(") orelse return error.AttentionSource); - var tail = try a.dupe(u8, source[begin..end]); + const tail = try region(a, source, "kernel void q27_attn_tail(", "kernel void q27_attn_merge(", &rewrites); defer a.free(tail); - for (rewrites) |r| { - if (std.mem.count(u8, tail, r[0]) != 1) return error.AttentionSource; - const next = try std.mem.replaceOwned(u8, a, tail, r[0], r[1]); - a.free(tail); - tail = next; + return region(a, tail, "kernel void q27_attn_prefix(", "#define Q27_PREFIX_AS(", &prefix_rewrites); +} + +fn region(a: std.mem.Allocator, source: []const u8, from: []const u8, to: []const u8, pairs: []const [2][]const u8) ![]u8 { + const begin = std.mem.indexOf(u8, source, from) orelse return error.AttentionSource; + const end = begin + (std.mem.indexOf(u8, source[begin..], to) orelse return error.AttentionSource); + var part = try a.dupe(u8, source[begin..end]); + defer a.free(part); + for (pairs) |r| { + if (std.mem.count(u8, part, r[0]) != 1) return error.AttentionSource; + const next = try std.mem.replaceOwned(u8, a, part, r[0], r[1]); + a.free(part); + part = next; } - return std.mem.concat(a, u8, &.{ source[0..begin], tail, source[end..] }); + return std.mem.concat(a, u8, &.{ source[0..begin], part, source[end..] }); } -/// The tail kernel's ops (scores 16x32 over 256, outputs 16x128 over 64), each element where it is read. +/// The tail and prefix kernels' ops (scores 16x32 and 16x64 over 256, outputs 16x128 over 64), each element where read. pub const check_source = \\#include \\#include @@ -100,12 +143,17 @@ pub const check_source = \\ threadgroup half Ps[16 * TK]; \\ tensor, tensor_inline> tK32(KV, dextents(D, 32)); \\ tensor, tensor_inline> tVh(KV, dextents(128, TK)); + \\ tensor, tensor_inline> tK64((device bfloat*)X, dextents(D, TK)); \\ tensor, tensor_inline> tP(Ps, dextents(TK, 16)); \\ constexpr auto dS = matmul2d_descriptor(16, 32, D, false, true, false, matmul2d_descriptor::mode::multiply); \\ constexpr auto dO = matmul2d_descriptor(16, 128, TK, false, false, false, matmul2d_descriptor::mode::multiply_accumulate); + \\ constexpr auto dW = matmul2d_descriptor(16, TK, D, false, true, false, matmul2d_descriptor::mode::multiply); \\ matmul2d opS; \\ matmul2d opO; + \\ matmul2d opW; \\ auto S = opS.template get_destination_cooperative_tensor(); + \\ auto Wd = opW.template get_destination_cooperative_tensor(); + \\ auto Wp = opO.template get_left_input_cooperative_tensor(Wd); \\ auto O = opO.template get_destination_cooperative_tensor(); \\ const int fm = ((lane & 16) >> 2) | ((lane >> 1) & 3), fn = ((lane & 8) >> 1) | ((lane & 1) << 1); \\ bool ok = true; @@ -113,6 +161,11 @@ pub const check_source = \\ auto at = S.get_multidimensional_index(i); \\ ok = ok && at[1] == fm + ((i & 8) ? 8 : 0) && at[0] == fn + (i & 1) + 8 * ((i >> 1) & 3); \\ } + \\ for (int i = 0; i < 32; i++) { + \\ auto at = Wd.get_multidimensional_index(i); + \\ auto in = Wp.get_multidimensional_index(i); + \\ ok = ok && at[1] == fm + ((i & 16) ? 8 : 0) && at[0] == fn + (i & 1) + 8 * ((i >> 1) & 7) && in[0] == at[0] && in[1] == at[1]; + \\ } \\ for (int i = 0; i < 64; i++) { \\ auto at = O.get_multidimensional_index(i); \\ ok = ok && at[1] == fm + ((i & 32) ? 8 : 0) && at[0] == fn + (i & 1) + 8 * ((i >> 1) % 16); @@ -129,7 +182,7 @@ pub fn check(device: mtl.Device, queue: mtl.Queue) !void { defer lib.deinit(); const pipe = try mtl.Pipeline.init(device, lib, "tf_q27_attn_layout", false); defer pipe.deinit(); - const x = try device.buffer(256 * 16 * 2, mtl.ResourceOptions.shared); + const x = try device.buffer(256 * 64 * 2, mtl.ResourceOptions.shared); defer x.deinit(); const ok = try device.buffer(32 * 4, mtl.ResourceOptions.shared); defer ok.deinit(); @@ -152,7 +205,7 @@ pub fn check(device: mtl.Device, queue: mtl.Queue) !void { }; } -test "the rewrite changes every M5-indexed line of the tail kernel once and leaves the other kernels alone" { +test "the rewrite changes every M5-indexed line of the tail kernel once and leaves the kernels after it alone" { const source = @import("qwen_runtime_sources").attention_mpp; const text = try rewrite(std.testing.allocator, source); defer std.testing.allocator.free(text); @@ -160,10 +213,21 @@ test "the rewrite changes every M5-indexed line of the tail kernel once and leav const end = begin + std.mem.indexOf(u8, text[begin..], "kernel void q27_attn_merge(").?; try std.testing.expect(std.mem.indexOf(u8, text[begin..end], "(i & 4)") == null); try std.testing.expect(std.mem.indexOf(u8, text[begin..end], "float4(Olo") == null); - try std.testing.expectEqualStrings(source[0..begin], text[0..begin]); try std.testing.expectEqualStrings(source[source.len - (text.len - end) ..], text[end..]); } +test "the rewrite changes every M5-indexed line of the prefix kernel once" { + const source = @import("qwen_runtime_sources").attention_mpp; + const text = try rewrite(std.testing.allocator, source); + defer std.testing.allocator.free(text); + const begin = std.mem.indexOf(u8, text, "kernel void q27_attn_prefix(").?; + const end = begin + std.mem.indexOf(u8, text[begin..], "#define Q27_PREFIX_AS(").?; + try std.testing.expect(std.mem.indexOf(u8, text[begin..end], "(i & 4)") == null); + try std.testing.expect(std.mem.indexOf(u8, text[begin..end], "float4(O[") == null); + try std.testing.expect(std.mem.indexOf(u8, text[begin..end], "* 16 + fn") == null); + try std.testing.expectEqualStrings(source[0..begin], text[0..begin]); +} + test "both attention builds, with and without the prompt kernels, open with the KV-group defines" { const a = std.testing.allocator; const defines = "#define Q27_G 4\n#define Q27_KVH 4\n"; diff --git a/zig/src/native/qwen27_served.zig b/zig/src/native/qwen27_served.zig index e705a1e58d6..8fae791948b 100644 --- a/zig/src/native/qwen27_served.zig +++ b/zig/src/native/qwen27_served.zig @@ -344,7 +344,8 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q var draft_owned = owns_draft; errdefer if (draft_owned) draft_model.?.deinit(); const memory = q.prompt_memory; - const fit_prompt = reserve.fit(model.config, capacity, window, o.streams, model.device.tensorUnits(), if (draft_model) |d| @as(usize, d.ring().window) * d.ring().stride else 0, if (draft_model) |d| d.graph.config.tap_count else q.taps.layers.len, model.frame.capacity, room(model)); + const shared = try q.simd_attention.sharedPrefix(model.device.tensorUnits()); + const fit_prompt = reserve.fit(model.config, capacity, window, o.streams, shared, if (draft_model) |d| @as(usize, d.ring().window) * d.ring().stride else 0, if (draft_model) |d| d.graph.config.tap_count else q.taps.layers.len, model.frame.capacity, room(model)); const rows = try reserve.rows(fit_prompt, model.device.generation(), window); const slots = fit_prompt.streams(rows, o.streams_fixed) catch |err| { const dev = model.device; @@ -358,7 +359,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q model.frame.deinit(); model.frame = next; } - std.log.info("qwen27: prompt capacity={d} rows, startup stream and scratch reserve={d} bytes", .{ rows, try memory.runnerBytes(model.config, capacity + window, slots, rows, model.device.tensorUnits(), fit_prompt.ring, fit_prompt.planes) }); + std.log.info("qwen27: prompt capacity={d} rows, startup stream and scratch reserve={d} bytes", .{ rows, try memory.runnerBytes(model.config, capacity + window, slots, rows, shared, fit_prompt.ring, fit_prompt.planes) }); h.gpa = gpa; h.model = model; h.owns_model = false; diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index e997400ad92..1313966fa37 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -71,6 +71,7 @@ pub const rules = [_]Rule{ .{ .name = "GLM_EHPROJ_NAX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 serves GLM's MTP eh_proj on the scalar kernel)" }, .{ .name = "TF_FLASHNEXT_GROUPED_ROWS", .scope = .metal, .kind = .size, .forms = "0 (never) or the rows, 1 to 32, from which a window's experts run grouped", .max = 32 }, .{ .name = "TF_QWEN27_SLOT_RESUME", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 stops slot 0 resuming a later prompt; unset or blank keeps it on)" }, + .{ .name = "TF_QWEN27_SHARED_PREFIX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 keeps the 27B's cached keys on the tail kernel before M5; unset or blank is 1)" }, .{ .name = "TF_QWEN27_METAL_KV_PAGES", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 puts the 27B's keys and values in core-pool pages; unset or blank is 0)" }, .{ .name = "TF_QWEN27_JOIN", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 runs a window's rows in pairs in the 27B's decode tail before M5; unset or blank is 1)" }, .{ .name = "TF_QWEN35_METAL_KV_PAGES", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 puts the streams' keys and values in core-pool pages; unset or blank is 0)" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 32c4130724e..b11d30d5af2 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -105,6 +105,8 @@ const valid = [_]Case{ .{ .name = "GLM_EHPROJ_NAX", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN27_SLOT_RESUME", .raw = "0", .n = 0 }, .{ .name = "TF_QWEN27_SLOT_RESUME", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN27_SHARED_PREFIX", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN27_SHARED_PREFIX", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN27_METAL_KV_PAGES", .raw = "0", .n = 0 }, .{ .name = "TF_QWEN27_METAL_KV_PAGES", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN27_JOIN", .raw = "0", .n = 0 }, @@ -334,7 +336,7 @@ test "environment: a legacy alias is checked only while its canonical name is un } test "environment: the Metal Qwen and slide-learning switches take their forms, read blank as unset and name a refusal" { - const flags = [_][:0]const u8{ "TF_QWEN27_SLOT_RESUME", "TF_QWEN27_METAL_KV_PAGES", "TF_QWEN27_JOIN", "TF_QWEN35_METAL_KV_PAGES", "TF_SLIDE_TAKE_OUT_CHECK", "TF_SLIDE_TAP_CHECK" }; + const flags = [_][:0]const u8{ "TF_QWEN27_SLOT_RESUME", "TF_QWEN27_SHARED_PREFIX", "TF_QWEN27_METAL_KV_PAGES", "TF_QWEN27_JOIN", "TF_QWEN35_METAL_KV_PAGES", "TF_SLIDE_TAKE_OUT_CHECK", "TF_SLIDE_TAP_CHECK" }; for (flags) |name| { try t.expectEqual(@as(?u64, 0), try e.parse(name, "0")); try t.expectEqual(@as(?u64, 1), try e.parse(name, "1")); diff --git a/zig/tests/contract/metal_q27_attn_io.zig b/zig/tests/contract/metal_q27_attn_io.zig index 5605c999e06..377198408f5 100644 --- a/zig/tests/contract/metal_q27_attn_io.zig +++ b/zig/tests/contract/metal_q27_attn_io.zig @@ -58,7 +58,7 @@ pub const Io = struct { rig: rig_.Rig, reg: Reg, op: attn.Attention, - tensor: bool, + shared: bool, st: ?at_.State = null, rd: at_.Round = .{}, host: [3][]u16 = .{ &.{}, &.{}, &.{} }, @@ -81,7 +81,7 @@ pub const Io = struct { const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); defer lib.deinit(); const op = try attn.Attention.init(device, lib); - return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .reg = r, .op = op, .tensor = tensor }; + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .reg = r, .op = op, .shared = try tf.qwen27.simd_attention.sharedPrefix(tensor) }; } pub fn deinit(t: *Io) void { @@ -106,7 +106,7 @@ pub const Io = struct { const vt = g.hooks(Io); fn geo(t: *const Io) planning.Geometry { - return at_.geometry(t.reg.heads, t.tensor); + return at_.geometry(t.reg.heads, t.shared); } fn bits(rng: std.Random, xs: []u16) void { diff --git a/zig/tests/contract/metal_q27_attn_rows.zig b/zig/tests/contract/metal_q27_attn_rows.zig index cf4e62089bb..80900cee45c 100644 --- a/zig/tests/contract/metal_q27_attn_rows.zig +++ b/zig/tests/contract/metal_q27_attn_rows.zig @@ -26,11 +26,11 @@ pub const Which = enum { decode, prompt }; /// `control`: values that aren't finite go to P V as they are, so a row's 0 for a key it must not see gives NaN. pub const Reg = struct { heads: at_.Heads, which: Which, control: bool = false }; -/// The control's edit: prompts never pick the masked kernel; decode rows before M5 take the tail (no control). -fn controlEdit(w: Which, tensor: bool) ?at_.Edit { +/// The control's edit: prompts never pick the masked kernel; decode rows off a shared prefix take the tail, no control. +fn controlEdit(w: Which, shared: bool) ?at_.Edit { return switch (w) { .prompt => .{ .from = "if (simd_any(inf != 0) && lane == 0) atomic_fetch_or", .to = "if (false && lane == 0) atomic_fetch_or" }, - .decode => if (tensor) .{ .from = "const bool masked = MASKED && q27_nonfinite(", .to = "const bool masked = false && q27_nonfinite(" } else null, + .decode => if (shared) .{ .from = "const bool masked = MASKED && q27_nonfinite(", .to = "const bool masked = false && q27_nonfinite(" } else null, }; } @@ -77,9 +77,9 @@ pub fn spec(r: Reg) c.Spec { }; } -/// Whether this chip has the control: decode rows before M5 run the tail kernel, whose round sees every key it reads. -pub fn hasControl(w: Which, tensor: bool) bool { - return controlEdit(w, tensor) != null; +/// Whether these rows have the control: off a shared prefix decode rows run the tail kernel, which sees every key. +pub fn hasControl(w: Which, shared: bool) bool { + return controlEdit(w, shared) != null; } fn bf(x: u16) f64 { @@ -91,7 +91,7 @@ pub const Attn = struct { rig: rig_.Rig, reg: Reg, op: attn.Attention, - tensor: bool, + shared: bool, st: ?at_.State = null, rd: at_.Round = .{}, q_in: []u16 = &.{}, @@ -106,11 +106,12 @@ pub const Attn = struct { pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, r: Reg) !Attn { const tensor = device.tensorUnits(); if (!tensor) try q.simd_attention.check(device, queue); - const gm = at_.geometry(r.heads, tensor); + const shared = try q.simd_attention.sharedPrefix(tensor); + const gm = at_.geometry(r.heads, shared); const body = try q.simd_attention.grouped(a, tensor, true, gm.group(), gm.kv_heads, false); defer a.free(body); const text = if (!r.control) try a.dupe(u8, body) else edit: { - const e = controlEdit(r.which, tensor) orelse return error.ControlEdit; + const e = controlEdit(r.which, shared) orelse return error.ControlEdit; if (std.mem.count(u8, body, e.from) != 1) return error.ControlEdit; break :edit try std.mem.replaceOwned(u8, a, body, e.from, e.to); }; @@ -118,7 +119,7 @@ pub const Attn = struct { const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); defer lib.deinit(); const op = try attn.Attention.init(device, lib); - return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .reg = r, .op = op, .tensor = tensor }; + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .reg = r, .op = op, .shared = shared }; } pub fn deinit(t: *Attn) void { @@ -143,7 +144,7 @@ pub const Attn = struct { const vt = g.hooks(Attn); fn geo(t: *const Attn) planning.Geometry { - return at_.geometry(t.reg.heads, t.tensor); + return at_.geometry(t.reg.heads, t.shared); } fn at(t: *const Attn, s: usize, hk: usize, row: usize) usize { @@ -161,8 +162,8 @@ pub const Attn = struct { t.rig.reset(); var prng = std.Random.DefaultPrng.init(seed); const rng = prng.random(); - // on an M5 gate 1's decode round is a chain: only a chain's prefix kernel reads keys that a row must not see - const trees = t.reg.which == .decode and !(t.tensor and fill == .nonfinite); + // a shared prefix makes gate 1's decode round a chain: only its prefix kernel reads keys a row must not see + const trees = t.reg.which == .decode and !(t.shared and fill == .nonfinite); t.rd = at_.Round.init(shape, t.reg.which == .prompt, trees, rng); const r = &t.rd; t.q_in = try t.a.alloc(u16, r.rows * nh * D); @@ -191,7 +192,7 @@ pub const Attn = struct { } t.refs[4] = try t.rig.output(r.rows * nh * D * 2); t.st = try at_.State.init(t.a, t.rig.device, r, gm, t.caches[0..r.streams]); - if (t.tensor and t.reg.which == .decode and fill == .nonfinite and !t.st.?.plan.fused) return error.PlantedRoundMissesPrefix; + if (t.shared and t.reg.which == .decode and fill == .nonfinite and !t.st.?.plan.fused) return error.PlantedRoundMissesPrefix; return true; } @@ -357,20 +358,23 @@ pub const Suite = struct { pub fn collect(s: *Suite, only: ?[]const u8) !void { // each chip's control edit must match its source once, checked on every chip, so an M4 run sees a stale M5 edit - for ([_]bool{ false, true }) |units| for (std.enums.values(Which)) |w| if (controlEdit(w, units)) |e| { - const gm = at_.geometry(.q27b, units); - const body = try q.simd_attention.grouped(s.a, units, true, gm.group(), gm.kv_heads, false); - defer s.a.free(body); - if (std.mem.count(u8, body, e.from) != 1) { - std.debug.print("control edit for {s} rows (tensor units {}) matches {d} times, not once: {s}\n", .{ @tagName(w), units, std.mem.count(u8, body, e.from), e.from }); - return error.ControlEdit; - } - }; + for ([_]bool{ false, true }) |units| { + const shared = try q.simd_attention.sharedPrefix(units); + for (std.enums.values(Which)) |w| if (controlEdit(w, shared)) |e| { + const gm = at_.geometry(.q27b, shared); + const body = try q.simd_attention.grouped(s.a, units, true, gm.group(), gm.kv_heads, false); + defer s.a.free(body); + if (std.mem.count(u8, body, e.from) != 1) { + std.debug.print("control edit for {s} rows (tensor units {}) matches {d} times, not once: {s}\n", .{ @tagName(w), units, std.mem.count(u8, body, e.from), e.from }); + return error.ControlEdit; + } + }; + } const tensor = s.device.tensorUnits(); var regs: std.ArrayList(Reg) = .empty; defer regs.deinit(s.a); for (heads) |h| for (std.enums.values(Which)) |w| try regs.append(s.a, .{ .heads = h, .which = w }); - for (std.enums.values(Which)) |w| if (hasControl(w, tensor)) try regs.append(s.a, .{ .heads = .q27b, .which = w, .control = true }); + for (std.enums.values(Which)) |w| if (hasControl(w, try q.simd_attention.sharedPrefix(tensor))) try regs.append(s.a, .{ .heads = .q27b, .which = w, .control = true }); for (regs.items) |r| { if (only) |o| if (std.mem.indexOf(u8, spec(r).name, o) == null) continue; const x = try s.a.create(Attn); diff --git a/zig/tests/qwen27/attention_fused.zig b/zig/tests/qwen27/attention_fused.zig index 63a394a7a30..f32cff4bed4 100644 --- a/zig/tests/qwen27/attention_fused.zig +++ b/zig/tests/qwen27/attention_fused.zig @@ -385,13 +385,11 @@ pub fn main(init: std.process.Init) !void { defer pool.pop(); const device = try mtl.Device.init(); defer device.deinit(); - if (!device.tensorUnits()) { - std.debug.print("attention_fused: no tensor units on {s}, nothing to check\n", .{std.mem.span(device.name())}); - return; - } const queue = try device.queue(); const args = try init.minimal.args.toSlice(a); - const text = try a.dupe(u8, source.glue ++ source.attention_mpp ++ source.attention_io ++ source.attention_prompt); + // before M5 the prefix and tail kernels read their results in the simdgroup-matrix layout (simd_attention.zig) + if (!device.tensorUnits()) try q.simd_attention.check(device, queue); + const text = try q.simd_attention.library(a, device.tensorUnits(), true); const library = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); defer library.deinit(); var op = try attn.Attention.init(device, library); @@ -411,7 +409,7 @@ pub fn main(init: std.process.Init) !void { defer scratch.deinit(); var binding = try attn.Binding.init(device, limits); defer binding.deinit(); - // Chips without tensor units plan with shared_prefix off: no prefix kernel, every key through the tail kernel. + // shared_prefix off (before M5: TF_QWEN27_SHARED_PREFIX=0): no prefix kernel, every key through the tail kernel. const plain_limits = attn.Limits{ .rows = round_rows, .streams = 8, .keys = capacity, .shared_prefix = false }; var plain_scratch = try attn.Scratch.init(device, plain_limits); defer plain_scratch.deinit(); diff --git a/zig/tests/qwen27/forward_diff_runner.zig b/zig/tests/qwen27/forward_diff_runner.zig index 84644a8d7aa..2256d9688cb 100644 --- a/zig/tests/qwen27/forward_diff_runner.zig +++ b/zig/tests/qwen27/forward_diff_runner.zig @@ -83,7 +83,7 @@ pub fn verify(comptime S: type, r: *q.decode_round.Runner, round: *const Round, const params = try r.gdn.budget.shape.params(round.ids.len, r.slots, .{ .conv = .bf16, .a_log = .bf16, .dt = .bf16, .norm = .bf16 }); var recurrent = try round.recurrent(params, &.{&.{}}); defer recurrent.deinit(); - var attention = try q.attention.Plan.init(r.allocator, &.{.{ .parents = round.windows[0].parents, .start = round.windows[0].start, .capacity = r.capacity }}, .{ .shared_prefix = r.model.device.tensorUnits() }); + var attention = try q.attention.Plan.init(r.allocator, &.{.{ .parents = round.windows[0].parents, .start = round.windows[0].start, .capacity = r.capacity }}, .{ .shared_prefix = r.geometry.shared_prefix }); defer attention.deinit(); try r.model.frame.setRows(round.ids, round.feed_positions); try r.scratch.upload(attention);