Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
1 change: 1 addition & 0 deletions docs/environment.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
2 changes: 1 addition & 1 deletion zig/build/qwen27.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 } });
Expand Down
2 changes: 1 addition & 1 deletion zig/src/families/qwen27/decode_round.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
94 changes: 79 additions & 15 deletions zig/src/families/qwen27/simd_attention.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
}
Expand Down Expand Up @@ -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 <metal_stdlib>
\\#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
Expand All @@ -100,19 +143,29 @@ pub const check_source =
\\ threadgroup half Ps[16 * TK];
\\ tensor<threadgroup bfloat, dextents<int32_t, 2>, tensor_inline> tK32(KV, dextents<int32_t, 2>(D, 32));
\\ tensor<threadgroup bfloat, dextents<int32_t, 2>, tensor_inline> tVh(KV, dextents<int32_t, 2>(128, TK));
\\ tensor<device bfloat, dextents<int32_t, 2>, tensor_inline> tK64((device bfloat*)X, dextents<int32_t, 2>(D, TK));
\\ tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tP(Ps, dextents<int32_t, 2>(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<dS, execution_simdgroup> opS;
\\ matmul2d<dO, execution_simdgroup> opO;
\\ matmul2d<dW, execution_simdgroup> opW;
\\ auto S = opS.template get_destination_cooperative_tensor<decltype(tQ), decltype(tK32), float>();
\\ auto Wd = opW.template get_destination_cooperative_tensor<decltype(tQ), decltype(tK64), half>();
\\ auto Wp = opO.template get_left_input_cooperative_tensor<half, bfloat, float>(Wd);
\\ auto O = opO.template get_destination_cooperative_tensor<decltype(tP), decltype(tVh), float>();
\\ const int fm = ((lane & 16) >> 2) | ((lane >> 1) & 3), fn = ((lane & 8) >> 1) | ((lane & 1) << 1);
\\ bool ok = true;
\\ for (int i = 0; i < 16; i++) {
\\ 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);
Expand All @@ -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();
Expand All @@ -152,18 +205,29 @@ 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);
const begin = std.mem.indexOf(u8, text, "kernel void q27_attn_tail(").?;
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";
Expand Down
5 changes: 3 additions & 2 deletions zig/src/native/qwen27_served.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
1 change: 1 addition & 0 deletions zig/src/platform/environment.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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)" },
Expand Down
Loading
Loading