Skip to content
Merged
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

- Inkling 2 on Metal: routed experts for 2 or more rows (concurrent decode, speculative verification and prompt prefill) group route pairs by expert on the GPU and share each expert's weight reads across up to 8 pairs, with every output bit equal to the one-pair-at-a-time path; on an M5 Ultra, prompt fill about 1.9x and 4-stream decode 15-19% faster. One row keeps the existing path (#4995). Thanks to @gilby.

- Desktop app: a Room seat's turn no longer stops at a fixed three minutes. The limit is now an idle watchdog that every streamed chunk or CLI activity re-arms, and the built-in engine's first output gets the engine's first-byte allowance, capped by the room's deliberation budget (#4977, fixes #3415). Thanks to @devopsfortunato.

- Qwen3.8-27B on Metal: `TF_QWEN27_MESSAGE_STARTS=1` (opt-in, default `0`) keeps prompt states at up to four of a chat request's latest message starts and puts the rewind state at the last user message's start, so a request that edits a tool result or replaces a message resumes from that message's start instead of re-reading the whole prompt; the states take only room the cache can already promise, and replies are unchanged; SenseNova-Loop, on the same host, keeps main's plan (#4932).
Expand Down
292 changes: 292 additions & 0 deletions zig/kernels/metal/inkling2/experts.metal

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions zig/src/core/contract/inkling2_experts_metal_records.zig
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ pub const records = [_]M{
.{ .name = "metal inkling2 experts tf_ink2_nvfp4_quantize", .threads = 32, .tg_memory = 0, .reserved = 32 },
.{ .name = "metal inkling2 experts tf_ink2_mxfp8_quantize", .threads = 32, .tg_memory = 0, .reserved = 32 },
.{ .name = "metal inkling2 experts tf_ink2_combine", .threads = 32, .tg_memory = 0, .reserved = 32 },
.{ .name = "metal inkling2 experts tf_ink2_expert_group", .threads = 128, .tg_memory = 2096, .reserved = 128 },
.{ .name = "metal inkling2 experts tf_ink2_nvfp4_gu_grouped", .threads = 32, .tg_memory = 0, .reserved = 32 },
.{ .name = "metal inkling2 experts tf_ink2_nvfp4_down_grouped", .threads = 32, .tg_memory = 0, .reserved = 32 },
.{ .name = "metal inkling2 experts tf_ink2_mxfp8_gu_grouped", .threads = 32, .tg_memory = 0, .reserved = 32 },
.{ .name = "metal inkling2 experts tf_ink2_mxfp8_down_grouped", .threads = 32, .tg_memory = 0, .reserved = 32 },
};

test "Inkling2 expert launches carry no fabricated M1/M2 compile receipts" {
Expand Down
77 changes: 75 additions & 2 deletions zig/src/families/inkling2/metal/experts.zig
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,20 @@ const plan = @import("experts_plan.zig");
pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 };
pub const Format = plan.Format;
pub const Call = plan.Call;
pub const Operation = enum { nvfp4_gu, nvfp4_down, mxfp8_gu, mxfp8_down, nvfp4_quantize, mxfp8_quantize, combine };
pub const Operation = enum {
nvfp4_gu,
nvfp4_down,
mxfp8_gu,
mxfp8_down,
nvfp4_quantize,
mxfp8_quantize,
combine,
expert_group,
nvfp4_gu_grouped,
nvfp4_down_grouped,
mxfp8_gu_grouped,
mxfp8_down_grouped,
};

pub const function_names = [_][:0]const u8{
"tf_ink2_nvfp4_gu",
Expand All @@ -17,6 +30,11 @@ pub const function_names = [_][:0]const u8{
"tf_ink2_nvfp4_quantize",
"tf_ink2_mxfp8_quantize",
"tf_ink2_combine",
"tf_ink2_expert_group",
"tf_ink2_nvfp4_gu_grouped",
"tf_ink2_nvfp4_down_grouped",
"tf_ink2_mxfp8_gu_grouped",
"tf_ink2_mxfp8_down_grouped",
};

/// The grouping launch, then gate-up and down for each format, on simdgroup matrices for GPUs without tensor units.
Expand All @@ -27,6 +45,7 @@ const mma_tile_rows = 64;
const mma_cap: u32 = 256;
/// A chunk of at least this many rows takes the simdgroup-matrix kernels, where the GPU has no tensor units.
pub const mma_rows: u32 = 16;
pub const max_grouped_rows: u32 = plan.max_grouped_rows;

const MmaGroupArgs = extern struct { pairs: u32, experts: u32, cap: u32 };
const MmaArgs = extern struct { k: u32, n: u32, topk: u32, cap: u32 };
Expand Down Expand Up @@ -72,7 +91,8 @@ pub const Pipelines = struct {
for (function_names, 0..) |name, i| {
out.entries[i] = try mtl.Pipeline.init(device, lib, name, false);
made += 1;
if (out.entries[i].maxThreads() < 32) return error.ExpertThreads;
const need: usize = if (i == @backingInt(Operation.expert_group)) 128 else 32;
if (out.entries[i].maxThreads() < need) return error.ExpertThreads;
}
return out;
}
Expand All @@ -92,6 +112,10 @@ fn args(c: Call) plan.MatrixArgs {
return .{ .k = c.k, .n = c.n, .topk = c.topk, .experts = c.experts };
}

fn groupedArgs(c: Call) plan.GroupedMatrixArgs {
return .{ .rows = c.rows, .k = c.k, .n = c.n, .topk = c.topk, .experts = c.experts };
}

fn launch(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, groups: u32) void {
e.setPipeline(p.get(op));
e.dispatchGroups(mtl.Size.of(groups, 1, 1), mtl.Size.of(32, 1, 1));
Expand Down Expand Up @@ -212,3 +236,52 @@ pub fn mma(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, x: Ref, w: Re
e.setValue(MmaArgs{ .k = c.k, .n = c.n, .topk = c.topk, .cap = mma_cap }, at + 3);
e.dispatchGroups(mtl.Size.of(weight_rows / mma_tile_rows, c.experts, 1), mtl.Size.of(256, 1, 1));
}

/// Bucket route pairs by expert ID into <= 8-pair work items on GPU without host readback.
pub fn groupBuckets(p: *const Pipelines, e: mtl.ComputeEncoder, ids: Ref, out: Ref, c: Call) !void {
try plan.checkGrouped(c);
e.setBuffer(ids.buf, ids.off, 0);
e.setBuffer(out.buf, out.off, 1);
e.setValue(plan.GroupArgs{ .rows = c.rows, .topk = c.topk, .experts = c.experts }, 2);
e.setPipeline(p.get(.expert_group));
e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(128, 1, 1));
}

pub fn nvfp4GuGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, amax: Ref, denominator: Ref, group_buf: Ref, out: Ref, c: Call) !void {
if (c.format != .nvfp4) return error.WrongExpertFormat;
try plan.checkGrouped(c);
for ([_]Ref{ x, w, scales, amax, denominator, group_buf, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i);
e.setValue(groupedArgs(c), 7);
try launchGrid(p, e, .nvfp4_gu_grouped, plan.groupedGeometry(c), &.{});
}

pub fn mxfp8GuGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, group_buf: Ref, out: Ref, c: Call) !void {
if (c.format != .mxfp8) return error.WrongExpertFormat;
try plan.checkGrouped(c);
for ([_]Ref{ x, w, scales, group_buf, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i);
e.setValue(groupedArgs(c), 5);
try launchGrid(p, e, .mxfp8_gu_grouped, plan.groupedGeometry(c), &.{});
}

pub fn nvfp4DownGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, amax: Ref, denominator: Ref, group_buf: Ref, out: Ref, c: Call) !void {
if (c.format != .nvfp4) return error.WrongExpertFormat;
try plan.checkGrouped(c);
for ([_]Ref{ act, w, scales, amax, denominator, group_buf, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i);
e.setValue(groupedArgs(c), 7);
try launchGrid(p, e, .nvfp4_down_grouped, plan.groupedGeometry(c), &.{});
}

pub fn mxfp8DownGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, group_buf: Ref, out: Ref, c: Call) !void {
if (c.format != .mxfp8) return error.WrongExpertFormat;
try plan.checkGrouped(c);
for ([_]Ref{ act, w, scales, group_buf, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i);
e.setValue(groupedArgs(c), 5);
try launchGrid(p, e, .mxfp8_down_grouped, plan.groupedGeometry(c), &.{});
}

pub fn guGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, nv_globals: ?struct { amax: Ref, denominator: Ref }, group_buf: Ref, out: Ref, c: Call) !void {
switch (c.format) {
.nvfp4 => if (nv_globals) |g| return nvfp4GuGrouped(p, e, x, w, scales, g.amax, g.denominator, group_buf, out, c) else return error.MissingNvfp4Globals,
.mxfp8 => return mxfp8GuGrouped(p, e, x, w, scales, group_buf, out, c),
}
}
29 changes: 29 additions & 0 deletions zig/src/families/inkling2/metal/experts_plan.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ pub const hidden: u32 = 2304;
pub const intermediate: u32 = 1152;
pub const expert_count: u32 = 128;
pub const top_k: u32 = 8;
pub const grouped_tile_m: u32 = 8;
pub const max_grouped_rows: u32 = 64;
pub const max_grouped_pairs: u32 = max_grouped_rows * top_k;

pub const Format = enum {
nvfp4,
Expand Down Expand Up @@ -55,13 +58,37 @@ pub fn combineGeometry(c: Call) Geometry {
return .{ .groups = c.rows, .blocks = blocks(c.n) };
}

/// Exact tight upper bound on active expert tiles for `rows * topk` pairs across `experts` with `grouped_tile_m`.
pub fn maxTiles(c: Call) u32 {
const pairs = c.rows * c.topk;
const active = @min(c.experts, pairs);
return active + (pairs - active) / grouped_tile_m;
}

/// GPU scratch bytes needed by tf_ink2_expert_group: tile count + packed work items + pair map.
pub fn groupBytes(rows: usize, topk: usize) usize {
return (1 + 2 * rows * topk) * @sizeOf(u32);
}

/// Grouped product grid: output blocks by worst-case expert tile count; inactive tiles exit on tile_id >= count.
pub fn groupedGeometry(c: Call) Geometry {
return .{ .groups = maxTiles(c), .blocks = blocks(c.n) };
}

pub fn check(c: Call) !void {
if (c.rows == 0 or c.k == 0 or c.n == 0 or c.experts == 0 or c.topk == 0 or c.topk > c.experts)
return error.BadExpertShape;
if (c.k % c.format.block() != 0 or (c.format == .nvfp4 and c.k % 2 != 0))
return error.BadExpertBlock;
}

pub fn checkGrouped(c: Call) !void {
try check(c);
const pairs = std.math.mul(u32, c.rows, c.topk) catch return error.BadExpertShape;
if (pairs > max_grouped_pairs or c.experts > std.math.maxInt(u16))
return error.BadExpertShape;
}

pub fn formatForLayer(layer: u32) !Format {
if (layer < 20) return .nvfp4;
if (layer < 24) return .mxfp8;
Expand Down Expand Up @@ -119,3 +146,5 @@ pub fn swiglu(gate: f32, up: f32) f32 {

pub const MatrixArgs = extern struct { k: u32, n: u32, topk: u32, experts: u32 };
pub const DecodeArgs = extern struct { rows: u32, k: u32 };
pub const GroupArgs = extern struct { rows: u32, topk: u32, experts: u32, tile_m: u32 = grouped_tile_m };
pub const GroupedMatrixArgs = extern struct { rows: u32, k: u32, n: u32, topk: u32, experts: u32 };
15 changes: 15 additions & 0 deletions zig/src/families/inkling2/metal/experts_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,18 @@ test "launch geometry is one thread an output over every route pair and validate
try std.testing.expectEqual(@as(usize, 0), @offsetOf(p.MatrixArgs, "k"));
try std.testing.expectEqual(@as(usize, 12), @offsetOf(p.MatrixArgs, "experts"));
}

test "grouped expert tile upper bound, buffer sizing and ABI layouts hold across all row tiers" {
const expected = [_][2]u32{ .{ 1, 8 }, .{ 2, 16 }, .{ 4, 32 }, .{ 8, 64 }, .{ 16, 128 }, .{ 32, 144 }, .{ 64, 176 } };
for (expected) |pair| {
const c = p.Call{ .rows = pair[0], .k = 2304, .n = 1152, .format = .nvfp4 };
try p.checkGrouped(c);
try std.testing.expectEqual(pair[1], p.maxTiles(c));
try std.testing.expectEqual(pair[1], p.groupedGeometry(c).groups);
}
try std.testing.expectEqual(@as(u32, 5), p.maxTiles(.{ .rows = 8, .k = 64, .n = 65, .experts = 4, .topk = 2, .format = .mxfp8 }));
try std.testing.expectEqual(@as(usize, 4100), p.groupBytes(64, 8));
try std.testing.expectError(error.BadExpertShape, p.checkGrouped(.{ .rows = 65, .k = 2304, .n = 1152, .format = .nvfp4 }));
try std.testing.expectEqual(@as(usize, 16), @sizeOf(p.GroupArgs));
try std.testing.expectEqual(@as(usize, 20), @sizeOf(p.GroupedMatrixArgs));
}
20 changes: 20 additions & 0 deletions zig/src/families/inkling2/metal/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,26 @@ fn routedExperts(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, laye
try experts.group(&m.experts, e, x(at(s.route_ids, 0)), gu_call);
try experts.mma(&m.experts, e, false, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), gu_globals, x(at(s.gu, 0)), gu_call);
try experts.mma(&m.experts, e, true, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), down_globals, x(at(s.down, 0)), down_call);
} else if (rows >= 2) {
var row0: usize = 0;
while (row0 < rows) {
const take: usize = @min(rows - row0, experts.max_grouped_rows);
const chunk_gu = experts.Call{ .rows = @intCast(take), .k = state.hidden, .n = state.intermediate, .format = precision };
const chunk_down = experts.Call{ .rows = @intCast(take), .k = state.intermediate, .n = state.hidden, .format = precision };
const x_in = x(row(s.mlp_normed, row0, state.hidden * 2));
const ids_in = x(row(s.route_ids, row0, state.experts_per_token * 4));
const gu_out = x(row(s.gu, row0, state.experts_per_token * state.intermediate * 2));
const down_out = x(row(s.down, row0, state.experts_per_token * state.hidden * 2));
try experts.groupBuckets(&m.experts, e, ids_in, x(at(s.expert_group, 0)), chunk_gu);
if (precision == .nvfp4) {
try experts.guGrouped(&m.experts, e, x_in, x(r(w.gu.weight)), x(r(w.gu.scale)), .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) }, x(at(s.expert_group, 0)), gu_out, chunk_gu);
try experts.nvfp4DownGrouped(&m.experts, e, gu_out, x(r(w.down.weight)), x(r(w.down.scale)), x(r(w.down.amax.?)), x(r(w.down.denominator.?)), x(at(s.expert_group, 0)), down_out, chunk_down);
} else {
try experts.guGrouped(&m.experts, e, x_in, x(r(w.gu.weight)), x(r(w.gu.scale)), null, x(at(s.expert_group, 0)), gu_out, chunk_gu);
try experts.mxfp8DownGrouped(&m.experts, e, gu_out, x(r(w.down.weight)), x(r(w.down.scale)), x(at(s.expert_group, 0)), down_out, chunk_down);
}
row0 += take;
}
} else {
if (precision == .nvfp4) {
try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) }, x(at(s.route_ids, 0)), x(at(s.gu, 0)), gu_call);
Expand Down
26 changes: 14 additions & 12 deletions zig/src/families/inkling2/metal/state.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const std = @import("std");
const mtl = @import("metal");
const plan = @import("../plan.zig");
const ap = @import("attention_plan.zig");
const experts_plan = @import("experts_plan.zig");

pub const window_rows = 16;
pub const batch_rows = 32;
Expand Down Expand Up @@ -264,11 +265,11 @@ fn copyGpu(queue: mtl.Queue, from: mtl.Buffer, from_off: usize, to: mtl.Buffer,
}

pub const fields = [_][]const u8{
"ids", "pos", "seg_of", "segs", "p", "prelude", "blocks", "bank0", "bank1", "messages",
"partial", "ar", "gated", "mlp_ar", "mlp_gated", "q_norm", "k_norm", "v_norm", "q_raw", "k_raw",
"v_raw", "rel_raw", "sink", "gate", "k_conv", "v_conv", "q_prep", "rel_prep", "part_o", "part_ml",
"att", "attn_dense", "attn_conv", "mlp_normed", "route_ids", "route_weights", "gu", "down", "mlp_out", "mlp_conv",
"logits_all", "route_scores", "gate_norm", "gate_zeta",
"ids", "pos", "seg_of", "segs", "p", "prelude", "blocks", "bank0", "bank1", "messages",
"partial", "ar", "gated", "mlp_ar", "mlp_gated", "q_norm", "k_norm", "v_norm", "q_raw", "k_raw",
"v_raw", "rel_raw", "sink", "gate", "k_conv", "v_conv", "q_prep", "rel_prep", "part_o", "part_ml",
"att", "attn_dense", "attn_conv", "mlp_normed", "route_ids", "route_weights", "gu", "down", "mlp_out", "mlp_conv",
"logits_all", "route_scores", "gate_norm", "gate_zeta", "expert_group",
};

fn sizes(rows: usize) [fields.len]usize {
Expand All @@ -279,13 +280,13 @@ fn sizes(rows: usize) [fields.len]usize {
const bf = 2;
const fp = 4;
return .{
r * 4, r * 4, r * 4, max_segments * @sizeOf(ap.Seg), r * h * bf, r * h * bf, r * block_slots * h * bf,
r * h * bf, r * h * bf, r * message_entries * h * fp, r * h * fp, 3 * r * h * fp, 3 * r * h * fp, r * h * fp,
r * h * fp, r * h * bf, r * h * bf, r * h * bf, r * q * bf, r * kv * bf, r * kv * bf,
r * rel_width * bf, r * 24 * bf, r * q * bf, r * kv * bf, r * kv * bf, r * q * bf, r * rel_width * bf,
r * 24 * max_attention_stride * ap.head_dim * fp, r * 24 * max_attention_stride * 2 * fp, r * q * bf, r * h * bf, r * h * bf, r * h * bf, r * experts_per_token * 4,
r * experts_per_token * fp, r * experts_per_token * intermediate * bf, r * experts_per_token * h * bf, r * h * bf, r * h * bf, r * vocabulary * fp, r * 128 * fp,
r * 2 * h * bf, r * 64 * fp,
r * 4, r * 4, r * 4, max_segments * @sizeOf(ap.Seg), r * h * bf, r * h * bf, r * block_slots * h * bf,
r * h * bf, r * h * bf, r * message_entries * h * fp, r * h * fp, 3 * r * h * fp, 3 * r * h * fp, r * h * fp,
r * h * fp, r * h * bf, r * h * bf, r * h * bf, r * q * bf, r * kv * bf, r * kv * bf,
r * rel_width * bf, r * 24 * bf, r * q * bf, r * kv * bf, r * kv * bf, r * q * bf, r * rel_width * bf,
r * 24 * max_attention_stride * ap.head_dim * fp, r * 24 * max_attention_stride * 2 * fp, r * q * bf, r * h * bf, r * h * bf, r * h * bf, r * experts_per_token * 4,
r * experts_per_token * fp, r * experts_per_token * intermediate * bf, r * experts_per_token * h * bf, r * h * bf, r * h * bf, r * vocabulary * fp, r * 128 * fp,
r * 2 * h * bf, r * 64 * fp, experts_plan.groupBytes(r, experts_per_token),
};
}

Expand Down Expand Up @@ -341,6 +342,7 @@ pub const Scratch = struct {
route_scores: mtl.Buffer,
gate_norm: mtl.Buffer,
gate_zeta: mtl.Buffer,
expert_group: mtl.Buffer,
/// Opt-in DSpark features [row][tap][H], allocated by prepare_features.
taps: ?mtl.Buffer = null,
rows: usize,
Expand Down
Loading
Loading