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: decode and prompt attention fold the relative-bias projection into the attention kernels, with each score's FP32 order and BF16 rounding unchanged; decode about 3-7% faster on an M3 Ultra (#5000). Thanks to @gilby.

- Tests: kernel-contract suites register each probe and its kernel through one helper, `contract.register`, which reserves room in both lists before publishing, so an allocation failure no longer frees a probe twice or leaks it; all 85 registration sites in 59 suites use it, with a failing-allocator test (#5058).

- Inkling 2 on Metal: the DSpark drafter's pipeline guards check the thread widths its shaders reserve (kappa 64, attention 768), so a valid drafter loads; arithmetic unchanged (#5041). Thanks to @gilby.
Expand Down
68 changes: 37 additions & 31 deletions zig/kernels/metal/inkling2/attention.metal
Original file line number Diff line number Diff line change
Expand Up @@ -78,26 +78,15 @@ kernel void tf_ink2_prep(const device bfloat* q_raw [[buffer(0)]], const device
for (uint i = 0; i < 4; ++i) dst[lane * 4 + i] = bfloat(x[i] * scale);
}

// The bf16 relative-bias table, one fp32 accumulation in projection tap order.
[[max_total_threads_per_threadgroup(256)]]
kernel void tf_ink2_rel_table(const device bfloat* rel [[buffer(0)]], const device bfloat* proj [[buffer(1)]],
device bfloat* tab [[buffer(2)]], uint rh [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) {
float r[REL];
for (uint j = 0; j < REL; ++j) r[j] = float(rel[rh * REL + j]);
for (uint d = t; d < EXTENT; d += 256) {
float acc = 0.0f;
for (uint j = 0; j < REL; ++j) acc += r[j] * float(proj[j * EXTENT + d]);
tab[rh * EXTENT + d] = bfloat(acc);
}
}

// A (row, head, key chunk) a simdgroup. Every P is bf16 before both its denominator add and P.V product.
// A (row, head, key chunk) a simdgroup; relative biases project on the fly in tap order and round to bf16.
[[max_total_threads_per_threadgroup(32)]]
kernel void tf_ink2_attn_scalar(const device bfloat* q [[buffer(0)]], const device bfloat* kc [[buffer(1)]],
const device bfloat* vc [[buffer(2)]], const device bfloat* tab [[buffer(3)]],
const device InkSeg* segs [[buffer(4)]], device float* part_o [[buffer(5)]], device float2* part_ml [[buffer(6)]],
const device int* rpos [[buffer(7)]], const device int* rseg [[buffer(8)]], constant InkAttnArgs& a [[buffer(9)]],
uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) {
const device bfloat* vc [[buffer(2)]], const device bfloat* rel [[buffer(3)]],
const device bfloat* proj [[buffer(4)]], const device InkSeg* segs [[buffer(5)]],
device float* part_o [[buffer(6)]], device float2* part_ml [[buffer(7)]],
const device int* rpos [[buffer(8)]], const device int* rseg [[buffer(9)]],
constant InkAttnArgs& a [[buffer(10)]], uint2 tg [[threadgroup_position_in_grid]],
uint lane [[thread_index_in_simdgroup]]) {
const uint rh = tg.x, row = rh / a.heads, h = rh % a.heads, group = a.heads / a.kv_heads, kvh = h / group;
const uint pos = uint(rpos[row]);
const uint lo = a.window && pos + 1 > a.window ? pos + 1 - a.window : 0;
Expand All @@ -108,21 +97,38 @@ kernel void tf_ink2_attn_scalar(const device bfloat* q [[buffer(0)]], const devi
const InkSeg s = segs[rseg[row]];
const size_t head = s.off + size_t(kvh) * a.ring * D;
const size_t prow = rh;
const float4 qv = float4(*(const device bfloat4*)(q + prow * D + lane * 4));
const bool has_rel = from < to && (pos - (to - 1)) < EXTENT;
const float r_lane = (has_rel && lane < REL) ? float(rel[prow * REL + lane]) : 0.0f;
float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};
float top = -INFINITY, total = 0.0f;
for (uint kp = from; kp < to; ++kp) {
const size_t at = head + size_t(kp % a.ring) * D;
float4 qv = float4(*(const device bfloat4*)(q + prow * D + lane * 4));
float4 kv = float4(*(const device bfloat4*)(kc + at + lane * 4));
const float dot_score = ink_warp_sum(dot(qv, kv));
const uint distance = pos - kp;
const float bias = distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f;
const float score = (dot_score * a.scale + bias) * LOG2E;
const float next = max(top, score), a0 = precise::exp2(top - next), b0 = precise::exp2(score - next);
const bfloat p = bfloat(b0);
total = total * a0 + float(p);
for (uint i = 0; i < 4; ++i) acc[i] = acc[i] * a0 + float(p) * float(vc[at + lane * 4 + i]);
top = next;
for (uint k0 = from; k0 < to; k0 += 32) {
const uint tile_to = min(k0 + 32, to);
const bool tile_bias = has_rel && (pos - (tile_to - 1)) < EXTENT;
float bias_lane = 0.0f;
if (tile_bias) {
const uint kp_lane = k0 + lane;
const bool need_bias = kp_lane < tile_to && (pos - kp_lane) < EXTENT;
const uint dist_safe = need_bias ? (pos - kp_lane) : 0;
float acc_b = 0.0f;
for (uint j = 0; j < REL; ++j) {
const float r_j = simd_shuffle(r_lane, ushort(j));
acc_b += r_j * (need_bias ? float(proj[j * EXTENT + dist_safe]) : 0.0f);
}
bias_lane = need_bias ? float(bfloat(acc_b)) : 0.0f;
}
for (uint kp = k0; kp < tile_to; ++kp) {
const size_t at = head + size_t(kp % a.ring) * D;
const float4 kv = float4(*(const device bfloat4*)(kc + at + lane * 4));
const float dot_score = ink_warp_sum(dot(qv, kv));
const float bias = tile_bias ? simd_shuffle(bias_lane, ushort(kp - k0)) : 0.0f;
const float score = (dot_score * a.scale + bias) * LOG2E;
const float next = max(top, score), a0 = precise::exp2(top - next), b0 = precise::exp2(score - next);
const bfloat p = bfloat(b0);
total = total * a0 + float(p);
for (uint i = 0; i < 4; ++i) acc[i] = acc[i] * a0 + float(p) * float(vc[at + lane * 4 + i]);
top = next;
}
}
const size_t slot = size_t(prow) * a.chunks + tg.y;
if (lane == 0) part_ml[slot] = float2(top, total);
Expand Down
42 changes: 30 additions & 12 deletions zig/kernels/metal/inkling2/prompt_attention.metal
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using namespace metal;
#pragma METAL fp contract(off)

constant constexpr uint D = 128, EXTENT = 1024, KEYS = 64, PAIRS = 128;
constant constexpr uint D = 128, REL = 16, EXTENT = 1024, KEYS = 64, PAIRS = 128;
constant constexpr float LOG2E = 1.4426950408889634f;
struct InkPromptSeg { int row0, n, p0, pad; long off; };
struct InkPromptArgs { uint heads, kv_heads, ring, chunk, c0, chunks; float scale; };
Expand Down Expand Up @@ -35,9 +35,10 @@ inline void ink_rows(thread const tfp::frag<float>* s, thread float (&r)[2], boo
// 128 (row, head) pairs and one key head/chunk a 256-thread group; each simdgroup owns 16 pairs.
[[max_total_threads_per_threadgroup(256)]]
kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const device bfloat* kc [[buffer(1)]],
const device bfloat* vc [[buffer(2)]], const device bfloat* tab [[buffer(3)]],
const device InkPromptSeg* segs [[buffer(4)]], device float* part_o [[buffer(5)]], device float2* part_ml [[buffer(6)]],
constant InkPromptArgs& a [[buffer(7)]], uint3 tg [[threadgroup_position_in_grid]],
const device bfloat* vc [[buffer(2)]], const device bfloat* rel [[buffer(3)]],
const device bfloat* proj [[buffer(4)]], const device InkPromptSeg* segs [[buffer(5)]],
device float* part_o [[buffer(6)]], device float2* part_ml [[buffer(7)]],
constant InkPromptArgs& a [[buffer(8)]], uint3 tg [[threadgroup_position_in_grid]],
uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint t [[thread_index_in_threadgroup]]) {
threadgroup bfloat ks[KEYS * D], vs[KEYS * D];
const InkPromptSeg s = segs[0];
Expand Down Expand Up @@ -85,14 +86,31 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi
}
float peak[2] = {top[0], top[1]};
const uint sub_lo = b_lo + ((kt - b_lo) / 1024) * 1024, sub_hi = sub_lo + 1023;
for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) {
const uint row = m + uint(home.y) + (e >> 2) * 8, col = uint(home.x) + TF_COL(e), kp = kt + 16 * f + col;
const uint lr = row < total ? row / group : 0, pos = uint(s.p0) + lr;
const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row);
const bool live = row < total && kp <= pos && kp >= sub_lo && kp <= sub_hi;
const uint distance = live ? pos - kp : 0;
const float bias = live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f;
score[f][e] = live ? (score[f][e] * a.scale + bias) * LOG2E : -INFINITY;
for (uint h = 0; h < 2; ++h) {
const uint row = m + uint(home.y) + 8 * h;
const bool row_live = row < total;
const uint pos = row_live ? uint(s.p0) + row / group : 0;
const uint row_k_lo = max(kt, sub_lo), row_k_hi = min(kt + KEYS - 1, min(pos, sub_hi));
const bool row_needs_rel = row_live && row_k_lo <= row_k_hi && (pos - row_k_hi) < EXTENT;
float r[REL];
if (row_needs_rel) {
const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row);
TF_UNROLL
for (uint j = 0; j < REL; ++j) r[j] = float(rel[prow * REL + j]);
}
for (uint f = 0; f < 4; ++f) for (uint ce = 0; ce < 4; ++ce) {
const uint e = 4 * h + ce, col = uint(home.x) + TF_COL(e), kp = kt + 16 * f + col;
const bool live = row_live && kp <= pos && kp >= sub_lo && kp <= sub_hi;
const uint distance = live ? pos - kp : 0;
float bias = 0.0f;
if (live && distance < EXTENT) {
float acc_b = 0.0f;
TF_UNROLL
for (uint j = 0; j < REL; ++j) acc_b += r[j] * float(proj[j * EXTENT + distance]);
bias = float(bfloat(acc_b));
}
score[f][e] = live ? (score[f][e] * a.scale + bias) * LOG2E : -INFINITY;
}
}
ink_rows(score, peak, true);
float keep[2];
Expand Down
1 change: 0 additions & 1 deletion zig/src/core/contract/inkling2_attention_metal_records.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ const std = @import("std");
const M = @import("limits.zig").MetalLaunch;
pub const records = [_]M{
.{ .name = "metal inkling2 attention prep tf_ink2_prep", .threads = 32, .tg_memory = 0, .reserved = 32 },
.{ .name = "metal inkling2 attention relative table tf_ink2_rel_table", .threads = 256, .tg_memory = 0, .reserved = 256 },
.{ .name = "metal inkling2 attention scalar tf_ink2_attn_scalar", .threads = 32, .tg_memory = 0, .reserved = 32 },
.{ .name = "metal inkling2 attention merge tf_ink2_merge", .threads = 128, .tg_memory = 0, .reserved = 128 },
.{ .name = "metal inkling2 prompt m5 tf_ink2_attn_prompt", .threads = 256, .tg_memory = 32768, .reserved = 256, .offline = false },
Expand Down
24 changes: 8 additions & 16 deletions zig/src/families/inkling2/metal/attention.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ pub const Kernels = struct {
scalar_lib: mtl.Library,
prompt_lib: mtl.Library,
prep: mtl.Pipeline,
rel_table: mtl.Pipeline,
decode: mtl.Pipeline,
merge: mtl.Pipeline,
prompt: mtl.Pipeline,
Expand All @@ -26,21 +25,20 @@ pub const Kernels = struct {
defer a.free(prompt_src);
var prompt_lib = try mtl.Library.fromSource(device, prompt_src, mtl.CompileOptions.mlx());
errdefer prompt_lib.deinit();
var pipes: [5]mtl.Pipeline = undefined;
var pipes: [4]mtl.Pipeline = undefined;
var made: usize = 0;
errdefer for (pipes[0..made]) |pipe| pipe.deinit();
for ([_]mtl.Library{ scalar_lib, scalar_lib, scalar_lib, scalar_lib, prompt_lib }, [_][]const u8{ "tf_ink2_prep", "tf_ink2_rel_table", "tf_ink2_attn_scalar", "tf_ink2_merge", "tf_ink2_attn_prompt" }, [_]usize{ 32, 256, 32, 128, 256 }, &pipes) |lib, name, req_threads, *pipe| {
for ([_]mtl.Library{ scalar_lib, scalar_lib, scalar_lib, prompt_lib }, [_][]const u8{ "tf_ink2_prep", "tf_ink2_attn_scalar", "tf_ink2_merge", "tf_ink2_attn_prompt" }, [_]usize{ 32, 32, 128, 256 }, &pipes) |lib, name, req_threads, *pipe| {
pipe.* = try mtl.Pipeline.init(device, lib, name, false);
made += 1;
if (pipe.maxThreads() < req_threads) return error.AttentionThreads;
}
return .{ .scalar_lib = scalar_lib, .prompt_lib = prompt_lib, .prep = pipes[0], .rel_table = pipes[1], .decode = pipes[2], .merge = pipes[3], .prompt = pipes[4], .units = units };
return .{ .scalar_lib = scalar_lib, .prompt_lib = prompt_lib, .prep = pipes[0], .decode = pipes[1], .merge = pipes[2], .prompt = pipes[3], .units = units };
}
pub fn deinit(k: *Kernels) void {
k.prompt.deinit();
k.merge.deinit();
k.decode.deinit();
k.rel_table.deinit();
k.prep.deinit();
k.prompt_lib.deinit();
k.scalar_lib.deinit();
Expand All @@ -62,23 +60,17 @@ pub fn prep(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: plann
e.dispatchGroups(mtl.Size.of(r.rows, r.heads + 2 * r.kv_heads, 1), mtl.Size.of(32, 1, 1));
}

pub fn relTable(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, rel: Ref, proj: Ref, tab: Ref) void {
e.setPipeline(k.rel_table);
bind(e, &.{ rel, proj, tab }, 0);
e.dispatchGroups(mtl.Size.of(r.rows * r.heads, 1, 1), mtl.Size.of(256, 1, 1));
}

pub fn attend(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, tab: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) !void {
pub fn attend(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) !void {
const launch = try planning.attend(r, l, stride, slots);
const scale: f32 = 1.0 / @sqrt(@as(f32, planning.head_dim));
if (launch.path == .decode) {
e.setPipeline(k.decode);
bind(e, &.{ q, kv.k, kv.v, tab, meta.segs, part_o, part_ml, meta.pos, meta.seg_of }, 0);
e.setValue(planning.AttnArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale }, 9);
bind(e, &.{ q, kv.k, kv.v, rel, proj, meta.segs, part_o, part_ml, meta.pos, meta.seg_of }, 0);
e.setValue(planning.AttnArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale }, 10);
} else {
e.setPipeline(k.prompt);
bind(e, &.{ q, kv.k, kv.v, tab, meta.segs, part_o, part_ml }, 0);
e.setValue(planning.PromptArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale }, 7);
bind(e, &.{ q, kv.k, kv.v, rel, proj, meta.segs, part_o, part_ml }, 0);
e.setValue(planning.PromptArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale }, 8);
}
e.dispatchGroups(mtl.Size.of(launch.grid[0], launch.grid[1], launch.grid[2]), mtl.Size.of(launch.threads, 1, 1));
e.barrier();
Expand Down
3 changes: 0 additions & 3 deletions zig/src/families/inkling2/metal/attention_plan.zig
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,6 @@ pub fn partialSlot(l: Layer, c: usize, pos: usize) ?usize {
if (c < lo / l.chunk or c > pos / l.chunk) return null;
return c - lo / l.chunk;
}
pub fn tableBytes(rows: usize, heads: u32) usize {
return rows * heads * extent * 2;
}
pub fn partialBytes(rows: usize, heads: u32, n_chunks: u32) usize {
return rows * heads * n_chunks * (head_dim * 4 + 8);
}
Expand Down
3 changes: 1 addition & 2 deletions zig/src/families/inkling2/metal/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,7 @@ fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v:
try convInputForAttention(m, e, s, cache, v, base, rows, true);
try convInputForAttention(m, e, s, cache, v, base, rows, false);
attention.prep(&m.attention, e, rr, layer, prep, meta, .{ a(at(s.q_raw, base * state.query_width * 2)), a(at(s.k_conv, base * state.kv_width * 2)), a(at(s.v_conv, base * state.kv_width * 2)), a(at(s.rel_raw, base * state.rel_width * 2)) }, .{ a(r(m.weights.layers[v.layer].attn.q_scale)), a(r(m.weights.layers[v.layer].attn.rel_scale)) }, a(at(s.q_prep, base * state.query_width * 2)), a(at(s.rel_prep, base * state.rel_width * 2)), kv);
attention.relTable(&m.attention, e, rr, a(at(s.rel_prep, base * state.rel_width * 2)), a(r(m.weights.layers[v.layer].attn.rel_projection)), a(at(s.rel_tab, base * 24 * ap.extent * 2)));
try attention.attend(&m.attention, e, rr, layer, state.max_attention_stride, 0, meta, a(at(s.q_prep, base * state.query_width * 2)), kv, a(at(s.rel_tab, base * 24 * ap.extent * 2)), a(at(s.part_o, base * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, base * 24 * state.max_attention_stride * 8)), a(at(s.sink, base * 24 * 2)), a(at(s.gate, base * state.query_width * 2)), a(at(s.att, base * state.query_width * 2)));
try attention.attend(&m.attention, e, rr, layer, state.max_attention_stride, 0, meta, a(at(s.q_prep, base * state.query_width * 2)), kv, a(at(s.rel_prep, base * state.rel_width * 2)), a(r(m.weights.layers[v.layer].attn.rel_projection)), a(at(s.part_o, base * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, base * 24 * state.max_attention_stride * 8)), a(at(s.sink, base * 24 * 2)), a(at(s.gate, base * state.query_width * 2)), a(at(s.att, base * state.query_width * 2)));
base += rows;
}
}
Expand Down
Loading
Loading