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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- Inkling 2 on Metal: each gated-attention layer runs its K and V short convolutions in one dispatch, with tokens unchanged; decode is about 1-2% faster on an M3 Ultra (#5004). Thanks to @gilby.

- CUDA sparse attention contract: a third case covers one query head per key head, a negative key count, a duplicate across a tile edge and unnamed entries in a nonfinite replay; test only (#5242, follow-up to #5166). Thanks to @jschmied.



- Metal kernels: `core/row_projection_legacy.metal` and `core/row_projection.metal` take their shared helpers (`tf_rp_p2` to `tf_rp_qdot16`) and `tf_row_projection_indexed` with its 60 narrow instances from one copy each, placed in at comptime; the compiled shader sources are byte-identical to before (#5205, refs #2251).

- Changelog: Unreleased is tidied for 1.3.6: #4907's line moves out of 1.3.5 into Unreleased with its number, three bullets that repeated another PR's line are removed (#4918, #4931, #5003), and #5042's line thanks its author (#5196).
Expand Down
39 changes: 26 additions & 13 deletions zig/kernels/metal/inkling2/glue.metal
Original file line number Diff line number Diff line change
Expand Up @@ -314,27 +314,30 @@ kernel void tf_inkling2_mlp_partial_ar(
}

struct InkConvArgs { uint rows, channels; };
[[max_total_threads_per_threadgroup(32)]]
kernel void tf_inkling2_conv_static(
const device bfloat* taps [[buffer(0)]], const device bfloat* weight [[buffer(1)]],
device bfloat* out [[buffer(2)]], constant InkConvArgs& a [[buffer(3)]],
uint2 at [[thread_position_in_grid]]) {
const uint c = at.x, r = at.y;
inline void ink_conv_static_at(
const device bfloat* taps, const device bfloat* weight, device bfloat* out,
constant InkConvArgs& a, uint c, uint r) {
if (c >= a.channels || r >= a.rows) return;
float sum = float(taps[size_t(r + 3) * a.channels + c]);
for (uint tap = 0; tap < 4; ++tap)
sum += float(weight[c * 4 + tap]) * float(taps[size_t(r + tap) * a.channels + c]);
out[size_t(r) * a.channels + c] = bfloat(precise::divide(sum, precise::sqrt(5.0f)));
}

[[max_total_threads_per_threadgroup(256)]]
kernel void tf_inkling2_conv_dynamic(
const device bfloat* taps [[buffer(0)]], const device bfloat* input [[buffer(1)]],
const device bfloat* static_w [[buffer(2)]], const device bfloat* projection [[buffer(3)]],
device bfloat* out [[buffer(4)]], constant InkConvArgs& a [[buffer(5)]],
uint t [[thread_position_in_threadgroup]], uint r [[threadgroup_position_in_grid]]) {
[[max_total_threads_per_threadgroup(32)]]
kernel void tf_inkling2_conv_static(
const device bfloat* taps [[buffer(0)]], const device bfloat* weight [[buffer(1)]],
device bfloat* out [[buffer(2)]], constant InkConvArgs& a [[buffer(3)]],
uint2 at [[thread_position_in_grid]]) {
ink_conv_static_at(taps, weight, out, a, at.x, at.y);
}

inline void ink_conv_dynamic_row(
const device bfloat* taps, const device bfloat* input,
const device bfloat* static_w, const device bfloat* projection,
device bfloat* out, constant InkConvArgs& a,
uint t, uint r, threadgroup float* projected) {
if (r >= a.rows) return;
threadgroup float projected[32];
if (t < 32) {
projected[t] = float(bfloat(ink_chain(projection + size_t(t) * 2304, input + size_t(r) * 2304, 2304)));
}
Expand All @@ -349,6 +352,16 @@ kernel void tf_inkling2_conv_dynamic(
}
}

[[max_total_threads_per_threadgroup(256)]]
kernel void tf_inkling2_conv_dynamic(
const device bfloat* taps [[buffer(0)]], const device bfloat* input [[buffer(1)]],
const device bfloat* static_w [[buffer(2)]], const device bfloat* projection [[buffer(3)]],
device bfloat* out [[buffer(4)]], constant InkConvArgs& a [[buffer(5)]],
uint t [[thread_position_in_threadgroup]], uint r [[threadgroup_position_in_grid]]) {
threadgroup float projected[32];
ink_conv_dynamic_row(taps, input, static_w, projection, out, a, t, r, projected);
}

struct InkRouteArgs { uint rows; };
[[max_total_threads_per_threadgroup(256)]]
kernel void tf_inkling2_router(
Expand Down
29 changes: 29 additions & 0 deletions zig/kernels/metal/inkling2/glue_kv_conv.metal
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Paired K and V short convolutions in one dispatch, after glue.metal's inline bodies.

[[max_total_threads_per_threadgroup(32)]]
kernel void tf_inkling2_kv_conv_static(
const device bfloat* k_taps [[buffer(0)]], const device bfloat* k_weight [[buffer(1)]],
device bfloat* k_out [[buffer(2)]], const device bfloat* v_taps [[buffer(3)]],
const device bfloat* v_weight [[buffer(4)]], device bfloat* v_out [[buffer(5)]],
constant InkConvArgs& a [[buffer(6)]], uint3 at [[thread_position_in_grid]]) {
if (at.z >= 2) return;
const bool is_v = at.z != 0;
ink_conv_static_at(is_v ? v_taps : k_taps, is_v ? v_weight : k_weight, is_v ? v_out : k_out, a, at.x, at.y);
}

[[max_total_threads_per_threadgroup(256)]]
kernel void tf_inkling2_kv_conv_dynamic(
const device bfloat* k_taps [[buffer(0)]], const device bfloat* k_input [[buffer(1)]],
const device bfloat* k_static_w [[buffer(2)]], const device bfloat* k_projection [[buffer(3)]],
device bfloat* k_out [[buffer(4)]], const device bfloat* v_taps [[buffer(5)]],
const device bfloat* v_input [[buffer(6)]], const device bfloat* v_static_w [[buffer(7)]],
const device bfloat* v_projection [[buffer(8)]], device bfloat* v_out [[buffer(9)]],
constant InkConvArgs& a [[buffer(10)]], uint t [[thread_index_in_threadgroup]],
uint2 tg [[threadgroup_position_in_grid]]) {
if (tg.y >= 2) return;
threadgroup float projected[32];
const bool is_v = tg.y != 0;
ink_conv_dynamic_row(is_v ? v_taps : k_taps, is_v ? v_input : k_input,
is_v ? v_static_w : k_static_w, is_v ? v_projection : k_projection,
is_v ? v_out : k_out, a, t, tg.x, projected);
}
4 changes: 2 additions & 2 deletions zig/kernels/metal/inkling2/glue_sources.zig
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
//! Inkling 2 Mini's glue, then the split router (glue_split.metal), which the contract compares bit for bit.
pub const glue = @embedFile("glue.metal") ++ "\n" ++ @embedFile("glue_split.metal");
//! Inkling 2 Mini's glue, paired KV convs (glue_kv_conv.metal), and split router (glue_split.metal).
pub const glue = @embedFile("glue.metal") ++ "\n" ++ @embedFile("glue_kv_conv.metal") ++ "\n" ++ @embedFile("glue_split.metal");
2 changes: 2 additions & 0 deletions zig/src/core/contract/inkling2_glue_metal_records.zig
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ pub const records = [_]M{
.{ .name = "metal inkling2 glue mlp_partial_ar tf_inkling2_mlp_partial_ar", .threads = 256, .tg_memory = 240, .reserved = 256 },
.{ .name = "metal inkling2 glue conv_static tf_inkling2_conv_static", .threads = 32, .tg_memory = 0, .reserved = 32 },
.{ .name = "metal inkling2 glue conv_dynamic tf_inkling2_conv_dynamic", .threads = 256, .tg_memory = 128, .reserved = 256 },
.{ .name = "metal inkling2 glue kv_conv_static tf_inkling2_kv_conv_static", .threads = 32, .tg_memory = 0, .reserved = 32 },
.{ .name = "metal inkling2 glue kv_conv_dynamic tf_inkling2_kv_conv_dynamic", .threads = 256, .tg_memory = 128, .reserved = 256 },
.{ .name = "metal inkling2 glue router tf_inkling2_router", .threads = 256, .tg_memory = 1616, .reserved = 256 },
.{ .name = "metal inkling2 glue swiglu tf_inkling2_swiglu", .threads = 32, .tg_memory = 0, .reserved = 32 },
.{ .name = "metal inkling2 glue logits tf_inkling2_logits", .threads = 32, .tg_memory = 0, .reserved = 32 },
Expand Down
56 changes: 40 additions & 16 deletions zig/src/families/inkling2/metal/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -198,11 +198,17 @@ fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scra
}
}

fn staticPostConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, weight: ck.Tensor, out: Ref, base: usize, rows: usize, is_tree: bool) void {
fn stageConvInput(m: *const Model, e: mtl.ComputeEncoder, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, base: usize, rows: usize) Ref {
const channels = state.convWidth(conv_state);
const taps = cache.staged(slot, conv_state, 0);
copyBf16(m, e, cache.history(slot, conv_state), taps, 3 * channels);
copyBf16(m, e, at(raw.buf, raw.off + base * channels * 2), cache.staged(slot, conv_state, 3), rows * channels);
return taps;
}

fn staticPostConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, weight: ck.Tensor, out: Ref, base: usize, rows: usize, is_tree: bool) void {
const channels = state.convWidth(conv_state);
const taps = stageConvInput(m, e, cache, slot, conv_state, raw, base, rows);
if (is_tree) {
tree.convStatic(&m.tree, e, taps, r(weight), at(s.conv_src, base * 4 * 4), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels));
} else {
Expand All @@ -227,8 +233,7 @@ fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v:
.segs = a(at(s.segs, si * @sizeOf(ap.Seg))),
};
const kv = attention.Cache{ .k = a(cache.keys(v.cache_slot)), .v = a(cache.values(v.cache_slot)) };
try convInputForAttention(m, e, s, cache, v, base, rows, true, sm.is_tree);
try convInputForAttention(m, e, s, cache, v, base, rows, false, sm.is_tree);
convInputsForAttention(m, e, s, cache, v, base, rows, sm.is_tree);
const rel_ref = a(at(s.rel_prep, base * state.rel_width * 2));
const proj_ref = a(r(m.weights.layers[v.layer].attn.rel_projection));
const q_ref = a(at(s.q_prep, base * state.query_width * 2));
Expand All @@ -250,24 +255,43 @@ fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v:
}
}

fn convInputForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, key: bool, is_tree: bool) !void {
fn convInputsForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, is_tree: bool) void {
const lp = m.weight_plan.at(v.layer);
const w = &m.weights.layers[v.layer];
const raw = if (key) at(s.k_conv, base * state.kv_width * 2) else at(s.v_conv, base * state.kv_width * 2);
const projected = if (key) at(s.k_raw, base * state.kv_width * 2) else at(s.v_raw, base * state.kv_width * 2);
const normalized = if (key) at(s.k_norm, 0) else if (v.hasMessages() or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0);
const taps = cache.staged(v.cache_slot, if (key) 0 else 1, 0);
copyBf16(m, e, cache.history(v.cache_slot, if (key) 0 else 1), taps, 3 * state.kv_width);
copyBf16(m, e, projected, cache.staged(v.cache_slot, if (key) 0 else 1, 3), rows * state.kv_width);
const k_taps = stageConvInput(m, e, cache, v.cache_slot, 0, at(s.k_raw, 0), base, rows);
const v_taps = stageConvInput(m, e, cache, v.cache_slot, 1, at(s.v_raw, 0), base, rows);
const k_out = at(s.k_conv, base * state.kv_width * 2);
const v_out = at(s.v_conv, base * state.kv_width * 2);
const k_in = at(s.k_norm, base * state.hidden * 2);
const v_norm = if (v.hasMessages() or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0);
const v_in = at(v_norm.buf, v_norm.off + base * state.hidden * 2);
if (is_tree) {
const src = at(s.conv_src, base * 4 * 4);
switch (if (key) w.attn.k_conv else w.attn.v_conv) {
.static => |weight| tree.convStatic(&m.tree, e, taps, r(weight), src, raw, @intCast(rows), state.kv_width),
.dynamic => |d| tree.convDynamic(&m.tree, e, taps, at(normalized.buf, normalized.off + base * state.hidden * 2), r(d.static_w), r(d.projection), src, raw, @intCast(rows), state.kv_width),
switch (w.attn.k_conv) {
.static => |kw| tree.convStatic(&m.tree, e, k_taps, r(kw), src, k_out, @intCast(rows), state.kv_width),
.dynamic => |kd| tree.convDynamic(&m.tree, e, k_taps, k_in, r(kd.static_w), r(kd.projection), src, k_out, @intCast(rows), state.kv_width),
}
switch (w.attn.v_conv) {
.static => |vw| tree.convStatic(&m.tree, e, v_taps, r(vw), src, v_out, @intCast(rows), state.kv_width),
.dynamic => |vd| tree.convDynamic(&m.tree, e, v_taps, v_in, r(vd.static_w), r(vd.projection), src, v_out, @intCast(rows), state.kv_width),
}
} else switch (if (key) w.attn.k_conv else w.attn.v_conv) {
.static => |weight| glue.convStatic(&m.glue, e, taps, r(weight), raw, @intCast(rows), state.kv_width),
.dynamic => |d| glue.convDynamic(&m.glue, e, taps, at(normalized.buf, normalized.off + base * state.hidden * 2), r(d.static_w), r(d.projection), raw, @intCast(rows), state.kv_width),
return;
}
switch (w.attn.k_conv) {
.static => |kw| switch (w.attn.v_conv) {
.static => |vw| glue.convStaticKv(&m.glue, e, k_taps, r(kw), k_out, v_taps, r(vw), v_out, @intCast(rows), state.kv_width),
.dynamic => |vd| {
glue.convStatic(&m.glue, e, k_taps, r(kw), k_out, @intCast(rows), state.kv_width);
glue.convDynamic(&m.glue, e, v_taps, v_in, r(vd.static_w), r(vd.projection), v_out, @intCast(rows), state.kv_width);
},
},
.dynamic => |kd| switch (w.attn.v_conv) {
.dynamic => |vd| glue.convDynamicKv(&m.glue, e, k_taps, k_in, r(kd.static_w), r(kd.projection), k_out, v_taps, v_in, r(vd.static_w), r(vd.projection), v_out, @intCast(rows), state.kv_width),
.static => |vw| {
glue.convDynamic(&m.glue, e, k_taps, k_in, r(kd.static_w), r(kd.projection), k_out, @intCast(rows), state.kv_width);
glue.convStatic(&m.glue, e, v_taps, r(vw), v_out, @intCast(rows), state.kv_width);
},
},
}
}

Expand Down
77 changes: 64 additions & 13 deletions zig/src/families/inkling2/metal/glue.zig
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ pub const Pipelines = struct {
mlp_partial_ar: mtl.Pipeline,
conv_static: mtl.Pipeline,
conv_dynamic: mtl.Pipeline,
kv_conv_static: mtl.Pipeline,
kv_conv_dynamic: mtl.Pipeline,
router: mtl.Pipeline,
route_scores: mtl.Pipeline,
route_select: mtl.Pipeline,
Expand All @@ -38,7 +40,7 @@ pub const Pipelines = struct {
pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines {
const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx());
defer lib.deinit();
var pipes: [19]mtl.Pipeline = undefined;
var pipes: [21]mtl.Pipeline = undefined;
var made: usize = 0;
errdefer for (pipes[0..made]) |pipe| pipe.deinit();
for ([_][]const u8{
Expand All @@ -50,6 +52,8 @@ pub const Pipelines = struct {
"tf_inkling2_mlp_partial_ar",
"tf_inkling2_conv_static",
"tf_inkling2_conv_dynamic",
"tf_inkling2_kv_conv_static",
"tf_inkling2_kv_conv_dynamic",
"tf_inkling2_router",
"tf_inkling2_swiglu",
"tf_inkling2_logits",
Expand All @@ -61,7 +65,7 @@ pub const Pipelines = struct {
"tf_inkling2_coalesced_logits_r8",
"tf_inkling2_coalesced_logits_r16",
"tf_inkling2_coalesced_logits_r32",
}, [_]usize{ 256, 256, 256, 256, 256, 256, 32, 256, 256, 32, 32, 32, 32, 32, 32, 128, 128, 128, 256 }, &pipes) |name, req_threads, *pipe| {
}, [_]usize{ 256, 256, 256, 256, 256, 256, 32, 256, 32, 256, 256, 32, 32, 32, 32, 32, 32, 128, 128, 128, 256 }, &pipes) |name, req_threads, *pipe| {
pipe.* = try mtl.Pipeline.init(device, lib, name, false);
made += 1;
if (pipe.maxThreads() < req_threads) return error.GlueThreads;
Expand All @@ -75,17 +79,19 @@ pub const Pipelines = struct {
.mlp_partial_ar = pipes[5],
.conv_static = pipes[6],
.conv_dynamic = pipes[7],
.router = pipes[8],
.swiglu = pipes[9],
.logits = pipes[10],
.expert_pick = pipes[11],
.expert_combine = pipes[12],
.route_scores = pipes[13],
.route_select = pipes[14],
.logits_r4 = pipes[15],
.logits_r8 = pipes[16],
.logits_r16 = pipes[17],
.logits_r32 = pipes[18],
.kv_conv_static = pipes[8],
.kv_conv_dynamic = pipes[9],
.router = pipes[10],
.swiglu = pipes[11],
.logits = pipes[12],
.expert_pick = pipes[13],
.expert_combine = pipes[14],
.route_scores = pipes[15],
.route_select = pipes[16],
.logits_r4 = pipes[17],
.logits_r8 = pipes[18],
.logits_r16 = pipes[19],
.logits_r32 = pipes[20],
};
}
pub fn deinit(p: *Pipelines) void {
Expand Down Expand Up @@ -172,6 +178,51 @@ pub fn convDynamic(p: *const Pipelines, e: mtl.ComputeEncoder, taps: Ref, input:
e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1));
}

/// Paired K+V static short convolution in a single Metal compute dispatch.
pub fn convStaticKv(
p: *const Pipelines,
e: mtl.ComputeEncoder,
k_taps: Ref,
k_weight: Ref,
k_out: Ref,
v_taps: Ref,
v_weight: Ref,
v_out: Ref,
rows: u32,
channels: u32,
) void {
std.debug.assert(rows > 0 and channels > 0);
e.setPipeline(p.kv_conv_static);
inline for (.{ k_taps, k_weight, k_out, v_taps, v_weight, v_out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i);
e.setValue(ConvArgs{ .rows = rows, .channels = channels }, 6);
e.dispatchThreads(mtl.Size.of(channels, rows, 2), unit);
}

/// Paired K+V dynamic short convolution in a single Metal compute dispatch.
pub fn convDynamicKv(
p: *const Pipelines,
e: mtl.ComputeEncoder,
k_taps: Ref,
k_input: Ref,
k_static_w: Ref,
k_projection: Ref,
k_out: Ref,
v_taps: Ref,
v_input: Ref,
v_static_w: Ref,
v_projection: Ref,
v_out: Ref,
rows: u32,
channels: u32,
) void {
std.debug.assert(rows > 0 and channels > 0 and channels <= 1024);
e.setPipeline(p.kv_conv_dynamic);
inline for (.{ k_taps, k_input, k_static_w, k_projection, k_out, v_taps, v_input, v_static_w, v_projection, v_out }, 0..) |r, i|
e.setBuffer(r.buf, r.off, i);
e.setValue(ConvArgs{ .rows = rows, .channels = channels }, 10);
e.dispatchGroups(mtl.Size.of(rows, 2, 1), mtl.Size.of(256, 1, 1));
}

const RouteArgs = extern struct { rows: u32 };
/// Router IDs and weights are sorted by ascending expert index for the deterministic expert sum.
pub fn router(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, weight: Ref, bias: Ref, ids: Ref, weights: Ref, rows: u32) void {
Expand Down
Loading
Loading