diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c74f87adbe..6e08df7db3b 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 +- 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. diff --git a/zig/kernels/metal/inkling2/attention.metal b/zig/kernels/metal/inkling2/attention.metal index cc4aa7a79f7..d34d8d5e132 100644 --- a/zig/kernels/metal/inkling2/attention.metal +++ b/zig/kernels/metal/inkling2/attention.metal @@ -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; @@ -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); diff --git a/zig/kernels/metal/inkling2/prompt_attention.metal b/zig/kernels/metal/inkling2/prompt_attention.metal index 06f4459bd7e..8ac88d01066 100644 --- a/zig/kernels/metal/inkling2/prompt_attention.metal +++ b/zig/kernels/metal/inkling2/prompt_attention.metal @@ -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; }; @@ -35,9 +35,10 @@ inline void ink_rows(thread const tfp::frag* 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]; @@ -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]; diff --git a/zig/src/core/contract/inkling2_attention_metal_records.zig b/zig/src/core/contract/inkling2_attention_metal_records.zig index 14a887d12dd..36ae0dfe302 100644 --- a/zig/src/core/contract/inkling2_attention_metal_records.zig +++ b/zig/src/core/contract/inkling2_attention_metal_records.zig @@ -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 }, diff --git a/zig/src/families/inkling2/metal/attention.zig b/zig/src/families/inkling2/metal/attention.zig index 60aadbf8141..497f5bbdbbb 100644 --- a/zig/src/families/inkling2/metal/attention.zig +++ b/zig/src/families/inkling2/metal/attention.zig @@ -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, @@ -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(); @@ -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(); diff --git a/zig/src/families/inkling2/metal/attention_plan.zig b/zig/src/families/inkling2/metal/attention_plan.zig index 49095e4facc..6aee427591e 100644 --- a/zig/src/families/inkling2/metal/attention_plan.zig +++ b/zig/src/families/inkling2/metal/attention_plan.zig @@ -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); } diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index 75f098952f4..ad3e53e9137 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -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; } } diff --git a/zig/src/families/inkling2/metal/state.zig b/zig/src/families/inkling2/metal/state.zig index 6c64c1e61cd..cb22b666639 100644 --- a/zig/src/families/inkling2/metal/state.zig +++ b/zig/src/families/inkling2/metal/state.zig @@ -264,11 +264,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", "rel_tab", "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", }; fn sizes(rows: usize) [fields.len]usize { @@ -279,13 +279,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 * ap.extent * 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, }; } @@ -324,7 +324,6 @@ pub const Scratch = struct { v_conv: mtl.Buffer, q_prep: mtl.Buffer, rel_prep: mtl.Buffer, - rel_tab: mtl.Buffer, part_o: mtl.Buffer, part_ml: mtl.Buffer, att: mtl.Buffer, diff --git a/zig/tests/contract/baselines/inkling2_attention_main.metal.txt b/zig/tests/contract/baselines/inkling2_attention_main.metal.txt new file mode 100644 index 00000000000..cc4aa7a79f7 --- /dev/null +++ b/zig/tests/contract/baselines/inkling2_attention_main.metal.txt @@ -0,0 +1,170 @@ +//! Inkling 2 Mini's scalar attention preparation, chunk decode and ordered sink/gate merge. +#include +using namespace metal; +#pragma METAL fp contract(off) + +constant constexpr uint D = 128, REL = 16, EXTENT = 1024; +constant constexpr float LOG2E = 1.4426950408889634f; + +struct InkSeg { + int row0, n, p0, pad; + long off; +}; +struct InkPrepArgs { + uint heads, kv_heads, ring, global; + float qk_clip, rel_clip, floor_pos, alpha, eps; +}; +struct InkAttnArgs { + uint heads, kv_heads, ring, window, chunk, c0, chunks; + float scale; +}; +struct InkMergeArgs { + uint heads, window, chunk, c0, chunks, subs; +}; + +inline float ink_warp_sum(float v) { + for (uint o = 16; o; o >>= 1) v += simd_shuffle_xor(v, ushort(o)); + return v; +} +inline float ink_clip_factor(float ss, float threshold) { + return fmin(threshold / (precise::sqrt(ss) + 1e-6f), 1.0f); +} + +// One 32-thread group handles a row and head; independent q/k/v and relative rows keep their first BF16 rounding. +[[max_total_threads_per_threadgroup(32)]] +kernel void tf_ink2_prep(const device bfloat* q_raw [[buffer(0)]], const device bfloat* k_raw [[buffer(1)]], + const device bfloat* v_raw [[buffer(2)]], const device bfloat* rel_raw [[buffer(3)]], + const device bfloat* q_scale [[buffer(4)]], const device bfloat* rel_scale [[buffer(5)]], + const device int* rpos [[buffer(6)]], const device int* rseg [[buffer(7)]], + const device InkSeg* segs [[buffer(8)]], device bfloat* q_out [[buffer(9)]], + device bfloat* rel_out [[buffer(10)]], device bfloat* kc [[buffer(11)]], device bfloat* vc [[buffer(12)]], + constant InkPrepArgs& a [[buffer(13)]], uint2 tg [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_threadgroup]]) { + const uint row = tg.x, unit = tg.y, pos = uint(rpos[row]); + const float tau = a.global ? 1.0f + a.alpha * precise::log(max(float(pos + 1) / a.floor_pos, 1.0f)) : 1.0f; + float x[4]; + if (unit < a.heads) { + const size_t rh = size_t(row) * a.heads + unit; + for (uint i = 0; i < 4; ++i) x[i] = float(q_raw[rh * D + lane * 4 + i]) * float(q_scale[unit * D + lane * 4 + i]); + float ss = ((x[0] * x[0] + x[1] * x[1]) + x[2] * x[2]) + x[3] * x[3]; + const float f = ink_clip_factor(ink_warp_sum(ss), a.qk_clip); + for (uint i = 0; i < 4; ++i) { + x[i] *= f; + const bfloat once = bfloat(x[i]); + q_out[rh * D + lane * 4 + i] = a.global ? bfloat(float(once) * tau) : once; + } + const float r = lane < REL ? float(rel_raw[rh * REL + lane]) * float(rel_scale[unit * REL + lane]) : 0.0f; + const float rf = ink_clip_factor(ink_warp_sum(r * r), a.rel_clip); + if (lane < REL) { + const bfloat once = bfloat(r * rf); + rel_out[rh * REL + lane] = a.global ? bfloat(float(once) * tau) : once; + } + return; + } + const bool key = unit < a.heads + a.kv_heads; + const uint h = key ? unit - a.heads : unit - a.heads - a.kv_heads; + const device bfloat* src = (key ? k_raw : v_raw) + (size_t(row) * a.kv_heads + h) * D; + for (uint i = 0; i < 4; ++i) x[i] = float(src[lane * 4 + i]); + float scale; + if (key) { + const float ss = ((x[0] * x[0] + x[1] * x[1]) + x[2] * x[2]) + x[3] * x[3]; + scale = ink_clip_factor(ink_warp_sum(ss), a.qk_clip); + } else { + const float ss = ((x[0] * x[0] + x[1] * x[1]) + x[2] * x[2]) + x[3] * x[3]; + scale = precise::rsqrt(ink_warp_sum(ss) / float(D) + a.eps); + } + const InkSeg s = segs[rseg[row]]; + device bfloat* dst = (key ? kc : vc) + s.off + (size_t(h) * a.ring + pos % a.ring) * D; + 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. +[[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 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; + const uint first = a.window ? lo / a.chunk : a.c0; + const uint c = first + tg.y; + if (c > pos / a.chunk || (a.window && c < lo / a.chunk)) return; + const uint from = max(lo, c * a.chunk), to = min(pos + 1, (c + 1) * a.chunk); + const InkSeg s = segs[rseg[row]]; + const size_t head = s.off + size_t(kvh) * a.ring * D; + const size_t prow = rh; + 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; + } + const size_t slot = size_t(prow) * a.chunks + tg.y; + if (lane == 0) part_ml[slot] = float2(top, total); + for (uint i = 0; i < 4; ++i) part_o[slot * D + lane * 4 + i] = acc[i]; +} + +// Fold chunks and any sub-chunks in order, add the sink logit, apply the gate, round once to bf16. +[[max_total_threads_per_threadgroup(128)]] +kernel void tf_ink2_merge(const device float* part_o [[buffer(0)]], const device float2* part_ml [[buffer(1)]], + const device bfloat* sink [[buffer(2)]], const device bfloat* gate [[buffer(3)]], const device int* rpos [[buffer(4)]], + device bfloat* out [[buffer(5)]], constant InkMergeArgs& a [[buffer(6)]], uint rh [[threadgroup_position_in_grid]], + uint d [[thread_index_in_threadgroup]]) { + const uint row = rh / a.heads, pos = uint(rpos[row]); + const uint lo = a.window && pos + 1 > a.window ? pos + 1 - a.window : 0; + float mm = -INFINITY, ll = 0.0f, o = 0.0f; + for (uint c = lo / a.chunk; c <= pos / a.chunk; ++c) { + float cm, cl, co; + if (a.subs > 1) { + float sm = -INFINITY, sl = 0.0f, so = 0.0f; + const uint last = min(a.subs - 1, (pos - c * a.chunk) / 1024); + for (uint u = 0; u <= last; ++u) { + const size_t at = size_t(rh) * a.chunks + (c - a.c0) * a.subs + u; + const float2 ml = part_ml[at]; + const float mn = max(sm, ml.x); + const float x = precise::exp2(sm - mn), y = precise::exp2(ml.x - mn); + sl = sl * x + ml.y * y; + so = so * x + part_o[at * D + d] * y; + sm = mn; + } + cm = sm; cl = sl; co = so; + } else { + const size_t at = size_t(rh) * a.chunks + c - (a.window ? lo / a.chunk : a.c0); + const float2 ml = part_ml[at]; + cm = ml.x; cl = ml.y; co = part_o[at * D + d]; + } + const float mn = max(mm, cm), x = precise::exp2(mm - mn), y = precise::exp2(cm - mn); + ll = ll * x + cl * y; + o = o * x + co * y; + mm = mn; + } + const float sk = float(sink[rh]) * LOG2E, mf = max(mm, sk), a0 = precise::exp2(mm - mf); + const float y = o * a0 / (ll * a0 + precise::exp2(sk - mf)); + const float gv = float(gate[rh * D + d]); + out[rh * D + d] = bfloat(y * (1.0f / (1.0f + precise::exp(-gv)))); +} diff --git a/zig/tests/contract/baselines/inkling2_prompt_attention_main.metal.txt b/zig/tests/contract/baselines/inkling2_prompt_attention_main.metal.txt new file mode 100644 index 00000000000..06f4459bd7e --- /dev/null +++ b/zig/tests/contract/baselines/inkling2_prompt_attention_main.metal.txt @@ -0,0 +1,145 @@ +//! Inkling 2 Mini's prompt attention; attention_sources prepends the tensor-fragment helpers. +#include +using namespace metal; +#pragma METAL fp contract(off) + +constant constexpr uint D = 128, 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; }; + +inline size_t ink_prompt_rh(const InkPromptSeg& s, uint heads, uint group, uint kvh, uint pair) { + return (size_t(s.row0) + pair / group) * heads + kvh * group + pair % group; +} + +inline void ink_fold(float& mm, float& ll, float m, float l, float& a, float& b) { + const float mn = max(mm, m); + a = precise::exp2(mm - mn); + b = precise::exp2(m - mn); + ll = ll * a + l * b; + mm = mn; +} +inline void ink_rows(thread const tfp::frag* s, thread float (&r)[2], bool maximum) { + for (uint f = 0; f < 4; ++f) for (uint h = 0; h < 2; ++h) { + const uint b = 4 * h; + float v = maximum ? max(max(s[f][b], s[f][b + 1]), max(s[f][b + 2], s[f][b + 3])) + : (s[f][b] + s[f][b + 1]) + (s[f][b + 2] + s[f][b + 3]); + const float x = simd_shuffle_xor(v, ushort(1)); + v = maximum ? max(v, x) : v + x; + const float y = simd_shuffle_xor(v, ushort(8)); + v = maximum ? max(v, y) : v + y; + r[h] = maximum ? max(r[h], v) : r[h] + v; + } +} + +// 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]], + 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]; + const uint group = a.heads / a.kv_heads, total = uint(s.n) * group, m0 = tg.x * PAIRS; + if (m0 >= total) return; + const uint kvh = tg.y, c = a.c0 + tg.z, b_lo = c * a.chunk; + const uint tile_hi = uint(s.p0) + min(m0 + PAIRS - 1, total - 1) / group; + if (b_lo > tile_hi) return; + const uint k_hi = min(b_lo + a.chunk - 1, tile_hi), m = m0 + 16 * sg; + const short2 home = tfp::frag_home(ushort(lane)); + const uint row_a = m + uint(home.y), row_b = row_a + 8; + const uint pair_a = min(row_a, total - 1), pair_b = min(row_b, total - 1); + const device bfloat* qb0 = q + ink_prompt_rh(s, a.heads, group, kvh, pair_a) * D; + const device bfloat* qb1 = q + ink_prompt_rh(s, a.heads, group, kvh, pair_b) * D; + const size_t hb = s.off + size_t(kvh) * a.ring * D; + tfp::frag acc[8], out[8]; + for (uint d = 0; d < 8; ++d) { acc[d] = tfp::frag(0); out[d] = tfp::frag(0); } + float top[2] = {-INFINITY, -INFINITY}, mass[2] = {0.0f, 0.0f}; + float upper[2] = {-INFINITY, -INFINITY}, whole[2] = {0.0f, 0.0f}; + for (uint kt = b_lo; kt <= k_hi; kt += KEYS) { + const uint tile_end = min(kt + KEYS, k_hi + 1); + for (uint e = t; e < KEYS * D; e += 256) { + const uint key = e / D, col = e % D, kp = kt + key; + const bool live = kp < tile_end; + const size_t at = hb + size_t((live ? kp : kt) % a.ring) * D + col; + ks[e] = live ? kc[at] : bfloat(0); + vs[e] = live ? vc[at] : bfloat(0); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if ((kt - b_lo) % 1024 == 0) { + for (uint d = 0; d < 8; ++d) acc[d] = tfp::frag(0); + top[0] = top[1] = -INFINITY; mass[0] = mass[1] = 0.0f; + } + tfp::frag score[4] = {tfp::frag(0), tfp::frag(0), tfp::frag(0), tfp::frag(0)}; + if (m < total && kt <= uint(s.p0) + min(m + 15, total - 1) / group) { + for (uint d = 0; d < 8; ++d) { + tfp::frag qa, kb0, kb1, kb2, kb3; + tfp::frag_get_rows(qa, qb0, qb1, 16 * d, home, row_a < total, row_b < total); + tfp::frag_get_t(kb0, ks, D, 0, 16 * d, home); + tfp::frag_get_t(kb1, ks, D, 16, 16 * d, home); + tfp::frag_get_t(kb2, ks, D, 32, 16 * d, home); + tfp::frag_get_t(kb3, ks, D, 48, 16 * d, home); + tfp::mma_16x32(score[0], score[1], qa, kb0, kb1); + tfp::mma_16x32(score[2], score[3], qa, kb2, kb3); + } + 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; + } + ink_rows(score, peak, true); + float keep[2]; + for (uint h = 0; h < 2; ++h) { + const float mu = peak[h] == -INFINITY ? 0.0f : peak[h]; + keep[h] = precise::exp2(top[h] - mu); + top[h] = peak[h]; mass[h] *= keep[h]; + } + tfp::frag p[4]; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) { + const float mu = peak[e >> 2] == -INFINITY ? 0.0f : peak[e >> 2]; + p[f][e] = bfloat(precise::exp2(score[f][e] - mu)); + } + // Reduce the rounded P, not its pre-bf16 exponential. + tfp::frag rounded[4]; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) rounded[f][e] = float(p[f][e]); + ink_rows(rounded, mass, false); + for (uint d = 0; d < 8; ++d) for (uint e = 0; e < 8; ++e) acc[d][e] *= keep[e >> 2]; + for (uint f = 0; f < 4; ++f) for (uint d = 0; d < 8; d += 2) { + tfp::frag v0, v1; + tfp::frag_get(v0, vs, D, 16 * f, 16 * d, home); + tfp::frag_get(v1, vs, D, 16 * f, 16 * d + 16, home); + tfp::mma_16x32(acc[d], acc[d + 1], p[f], v0, v1); + } + } + const bool fold_now = (kt - b_lo) % 1024 == 960 || kt + KEYS > k_hi; + if (fold_now && m < total) for (uint h = 0; h < 2; ++h) { + if (top[h] == -INFINITY) continue; + float x, y; + ink_fold(upper[h], whole[h], top[h], mass[h], x, y); + for (uint d = 0; d < 8; ++d) for (uint e = 4 * h; e < 4 * h + 4; ++e) out[d][e] = out[d][e] * x + acc[d][e] * y; + } + threadgroup_barrier(mem_flags::mem_threadgroup); // no simdgroup reads ks/vs when the next tile overwrites them + } + if (m >= total) return; + for (uint d = 0; d < 8; ++d) for (uint e = 0; e < 8; ++e) { + const uint row = m + uint(home.y) + (e >> 2) * 8, col = uint(home.x) + TF_COL(e); + if (row >= total) continue; + const uint pos = uint(s.p0) + row / group; + if (b_lo > pos) continue; + const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); + part_o[(prow * a.chunks + c - a.c0) * D + 16 * d + col] = out[d][e]; + } + if (home.x == 0) for (uint h = 0; h < 2; ++h) { + const uint row = m + uint(home.y) + 8 * h; + if (row >= total || b_lo > uint(s.p0) + row / group) continue; + const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); + part_ml[prow * a.chunks + c - a.c0] = float2(upper[h], whole[h]); + } +} diff --git a/zig/tests/contract/metal_inkling2_attention.zig b/zig/tests/contract/metal_inkling2_attention.zig index 670189cd409..6934cd0a85b 100644 --- a/zig/tests/contract/metal_inkling2_attention.zig +++ b/zig/tests/contract/metal_inkling2_attention.zig @@ -1,34 +1,31 @@ -//! Inkling 2 Mini Metal attention gates 1-4 with an independent float64 formula and both prompt layouts. +//! Inkling 2 Mini Metal attention gates 1-4 with an independent float64 formula, baselines and both prompt layouts. const std = @import("std"); const mtl = @import("metal"); const contract = @import("contract"); const rig_ = @import("rig.zig"); const controls = @import("metal_inkling2_attention_controls.zig"); +const ref = @import("metal_inkling2_attention_ref.zig"); const sources = @import("inkling2_metal"); const plan = @import("tensorfold").inkling2_metal_host.attention.planning; const c = contract.spec; const g = contract.gates; const Which = controls.Which; const Mutation = controls.Mutation; -const D = 128; -const H = 24; -const KV = 8; -const R = 16; -const EXTENT = 1024; -const scale = 0.08838834764831845; +const D = ref.D; +const H = ref.H; +const KV = ref.KV; +const R = ref.R; +const EXTENT = ref.EXTENT; const prep_shapes = [_]c.Shape{ .{ .rows = 7, .n = H * D, .k = 1030 }, .{ .rows = 3, .n = H * D, .k = 9000 } }; const prep_global_shapes = [_]c.Shape{ prep_shapes[0], prep_shapes[1], .{ .rows = 4, .n = H * D, .k = 1048576 } }; -const rel_shapes = [_]c.Shape{ .{ .rows = 4, .n = H * EXTENT, .k = R }, .{ .rows = 1, .n = H * EXTENT, .k = R } }; -const sliding_shapes = [_]c.Shape{ .{ .rows = 7, .n = H * D, .k = 1030 }, .{ .rows = 3, .n = H * D, .k = 2049 } }; -const global_shapes = [_]c.Shape{ .{ .rows = 4, .n = H * D, .k = 1100 }, .{ .rows = 2, .n = H * D, .k = 1030 } }; -const prompt_shapes = [_]c.Shape{ .{ .rows = 8, .n = H * D, .k = 1100 }, .{ .rows = 64, .n = H * D, .k = 80 } }; +const sliding_shapes = [_]c.Shape{ .{ .rows = 7, .n = H * D, .k = 1030 }, .{ .rows = 3, .n = H * D, .k = 2049 }, .{ .rows = 5, .n = H * D, .k = 17 }, .{ .rows = 1, .n = H * D, .k = 1024 } }; +const global_shapes = [_]c.Shape{ .{ .rows = 4, .n = H * D, .k = 1100 }, .{ .rows = 2, .n = H * D, .k = 1030 }, .{ .rows = 3, .n = H * D, .k = 17 }, .{ .rows = 1, .n = H * D, .k = 1025 } }; +const prompt_shapes = [_]c.Shape{ .{ .rows = 8, .n = H * D, .k = 1100 }, .{ .rows = 64, .n = H * D, .k = 80 }, .{ .rows = 3, .n = H * D, .k = 17 }, .{ .rows = 1, .n = H * D, .k = 1025 } }; +const long_shapes = [_]c.Shape{.{ .rows = 5, .n = H * D, .k = 17450 }}; fn depth(s: c.Shape) usize { return D + 4 * s.k + 64; } -fn flat(_: c.Shape) usize { - return R; -} fn spec(w: Which) c.Spec { const x: c.Spec = .{ .name = "", .accum = .f32, .depth = depth, .ops = 64, .mids = 8, .out = .bf16, .served = &global_shapes, .sums = .{ .f16 = 0, .bf16 = 0, .exact = true, .why = "P and outputs have required bf16 roundings" } }; var s = x; @@ -39,98 +36,50 @@ fn spec(w: Which) c.Spec { s.ops = 32; s.mids = 2; }, - .rel_table => { - s.name = "metal inkling2 attention relative table tf_ink2_rel_table"; - s.served = &rel_shapes; - s.depth = flat; - s.ops = 4; - s.mids = 0; - }, .decode_sliding => { s.name = "metal inkling2 attention scalar sliding tf_ink2_attn_scalar"; s.served = &sliding_shapes; + s.replaces = "main tf_ink2_rel_table then tf_ink2_attn_scalar"; }, .decode_global => { s.name = "metal inkling2 attention scalar global tf_ink2_attn_scalar"; s.served = &global_shapes; + s.replaces = "main tf_ink2_rel_table then tf_ink2_attn_scalar"; + }, + .decode_global_long => { + s.name = "metal inkling2 attention scalar global long tf_ink2_attn_scalar"; + s.accum = .none; + s.sums = .{ .f16 = 0, .bf16 = 0, .why = "byte-exact against main on multi-chunk long context" }; + s.served = &long_shapes; + s.replaces = "main tf_ink2_rel_table then tf_ink2_attn_scalar"; }, .prompt_m5 => { s.name = "metal inkling2 prompt m5 tf_ink2_attn_prompt"; s.served = &prompt_shapes; + s.replaces = "main tf_ink2_rel_table then tf_ink2_attn_prompt"; + }, + .prompt_m5_long => { + s.name = "metal inkling2 prompt m5 long tf_ink2_attn_prompt"; + s.accum = .none; + s.sums = .{ .f16 = 0, .bf16 = 0, .why = "byte-exact against main on multi-chunk long context" }; + s.served = &long_shapes; + s.replaces = "main tf_ink2_rel_table then tf_ink2_attn_prompt"; }, .prompt_pre_m5 => { s.name = "metal inkling2 prompt pre-m5 tf_ink2_attn_prompt"; s.served = &prompt_shapes; + s.replaces = "main tf_ink2_rel_table then tf_ink2_attn_prompt"; + }, + .prompt_pre_m5_long => { + s.name = "metal inkling2 prompt pre-m5 long tf_ink2_attn_prompt"; + s.accum = .none; + s.sums = .{ .f16 = 0, .bf16 = 0, .why = "byte-exact against main on multi-chunk long context" }; + s.served = &long_shapes; + s.replaces = "main tf_ink2_rel_table then tf_ink2_attn_prompt"; }, } return s; } -fn bf(x: u16) f64 { - return c.fromBf16(x); -} -fn rn(x: f64) f64 { - return c.fromBf16(c.toBf16(@floatCast(x))); -} -fn bits(x: f64) u16 { - return c.toBf16(@floatCast(x)); -} -fn minNum(x: f64, y: f64) f64 { - return if (std.math.isNan(x)) y else if (std.math.isNan(y)) x else @min(x, y); -} -fn maxNan(x: f64, y: f64) f64 { - return if (std.math.isNan(x) or std.math.isNan(y)) std.math.nan(f64) else @max(x, y); -} -fn sigmoid(x: f64) f64 { - return 1 / (1 + @exp(-x)); -} -/// Prompt P rounds to BF16 at each tile maximum; later rescaling does not round twice. The result anchors weights. -fn promptWeights(score: []const f64, weights: []f64) f64 { - const tile_keys = 64; - const sub_keys = 1024; - var top = -std.math.inf(f64); - var upper = -std.math.inf(f64); - var first: usize = 0; - while (first < score.len) { - const end = @min(first + tile_keys, score.len); - const sub_first = first - first % sub_keys; - var tile_peak = top; - for (score[first..end]) |sc| tile_peak = maxNan(tile_peak, sc); - const mu = if (tile_peak == -std.math.inf(f64)) 0 else tile_peak; - const keep = @exp(top - mu); - for (weights[sub_first..first]) |*w| w.* *= keep; - for (weights[first..end], score[first..end]) |*w, sc| w.* = rn(@exp(sc - mu)); - top = tile_peak; - if (first % sub_keys == sub_keys - tile_keys or end == score.len) { - if (top != -std.math.inf(f64)) { - const merged = maxNan(upper, top); - const old_scale = @exp(upper - merged); - const new_scale = @exp(top - merged); - for (weights[0..sub_first]) |*w| w.* *= old_scale; - for (weights[sub_first..end]) |*w| w.* *= new_scale; - upper = merged; - } - top = -std.math.inf(f64); - } - first = end; - } - return upper; -} -fn tau(pos: usize) f64 { - return 1 + 0.1 * @log(@max(@as(f64, @floatFromInt(pos + 1)) / 8192, 1)); -} -fn periodic(p: usize, col: usize) f64 { - const i = p % 1024; - if (i < 512) return @floatFromInt(129 + (i * 73 + col * 31) % 127); - const j = i - 512; - return -@as(f64, @floatFromInt(129 + ((j + 1) * 73 + col * 31) % 127)) + @as(f64, if (j < 8) 1 else 0); -} -const Sim = struct { acc: c.Accum, order: g.Order }; -fn sum(v: []const f64, sim: ?Sim) f64 { - if (sim) |s| return contract.rows.sumIn(s.acc, s.order, v); - var total: f64 = 0; - for (v) |x| total += x; - return total; -} pub const Probe = struct { a: std.mem.Allocator, @@ -141,6 +90,7 @@ pub const Probe = struct { main: mtl.Pipeline, merge_lib: ?mtl.Library = null, merge: mtl.Pipeline = undefined, + base: ?ref.Baseline = null, fused: bool = false, shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, fill: g.Fill = .random, @@ -148,7 +98,6 @@ pub const Probe = struct { q: []u16 = &.{}, kc: []u16 = &.{}, vc: []u16 = &.{}, - tab: []u16 = &.{}, sink: []u16 = &.{}, gate: []u16 = &.{}, rel: []u16 = &.{}, @@ -161,9 +110,13 @@ pub const Probe = struct { meta: [3]rig_.Ref = undefined, po: rig_.Ref = undefined, pml: rig_.Ref = undefined, + base_tab: rig_.Ref = undefined, + base_po: rig_.Ref = undefined, + base_pml: rig_.Ref = undefined, + base_out: rig_.Ref = undefined, pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, w: Which, m: Mutation) !Probe { - const plain = if (controls.isPrompt(w)) (if (w == .prompt_pre_m5) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; + const plain = if (controls.isPrompt(w)) (if (controls.isPreM5(w)) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; const text = try controls.apply(a, plain, m); defer a.free(text); var lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); @@ -176,13 +129,14 @@ pub const Probe = struct { const fused = controls.isAttention(w); if (fused) { if (controls.isPrompt(w)) merge_lib = try mtl.Library.fromSource(device, sources.attention, mtl.CompileOptions.mlx()); - const merge_library = if (merge_lib) |loaded| loaded else lib; - merge = try mtl.Pipeline.init(device, merge_library, "tf_ink2_merge", false); + merge = try mtl.Pipeline.init(device, merge_lib orelse lib, "tf_ink2_merge", false); } - return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .which = w, .mutation = m, .lib = lib, .main = main, .merge_lib = merge_lib, .merge = merge, .fused = fused }; + errdefer if (fused) merge.deinit(); + const base = if (fused and m == .none) try ref.Baseline.init(a, device, w) else null; + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .which = w, .mutation = m, .lib = lib, .main = main, .merge_lib = merge_lib, .merge = merge, .base = base, .fused = fused }; } fn hostFree(p: *Probe) void { - inline for (.{ "q", "kc", "vc", "tab", "sink", "gate", "rel", "proj", "qs", "rs", "pos" }) |f| { + inline for (.{ "q", "kc", "vc", "sink", "gate", "rel", "proj", "qs", "rs", "pos" }) |f| { p.a.free(@field(p, f)); @field(p, f) = &.{}; } @@ -190,6 +144,7 @@ pub const Probe = struct { pub fn deinit(p: *Probe) void { p.hostFree(); p.rig.deinit(); + if (p.base) |*b| b.deinit(); if (p.fused) p.merge.deinit(); if (p.merge_lib) |loaded| loaded.deinit(); p.main.deinit(); @@ -201,6 +156,7 @@ pub const Probe = struct { if (p.mutation != .none) { k.spec.name = p.mutation.name(); k.control = p.mutation.gate(); + k.spec.replaces = null; } return k; } @@ -212,96 +168,76 @@ pub const Probe = struct { return KV * p.layer.ring * D; } pub fn count(p: *const Probe) usize { - if (p.which == .rel_table) return p.shape.rows * H * EXTENT; if (controls.isAttention(p.which)) return p.shape.rows * H * D; const z = p.sizes(); return z[0] + z[1] + z[2] + z[3]; } pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { - if (s.rows == 0 or s.k < s.rows) return false; - if (p.which == .rel_table) { - if (s.n != H * EXTENT or s.k != R) return false; - } else if (s.n != H * D) return false; + if (s.rows == 0 or s.k < s.rows or s.n != H * D) return false; p.hostFree(); p.rig.reset(); p.shape = s; p.fill = fill; - const global = p.which == .prep_global or p.which == .decode_global or controls.isPrompt(p.which); + const global = p.which == .prep_global or p.which == .decode_global or p.which == .decode_global_long or controls.isPrompt(p.which); const sliding = p.which == .prep_sliding or p.which == .decode_sliding; - p.layer = .{ .window = if (sliding) 1024 else 0, .ring = 2048, .chunk = if (sliding) 256 else plan.global_chunk, .tau = global }; + const ring: u32 = if (controls.isAttention(p.which)) @intCast(std.mem.alignForward(usize, @max(2048, s.k), 64)) else 2048; + p.layer = .{ .window = if (sliding) 1024 else 0, .ring = ring, .chunk = if (sliding) 256 else plan.global_chunk, .tau = global }; const rows = s.rows; const rh = rows * H; const cache = KV * p.layer.ring * D; p.pos = try p.a.alloc(usize, rows); for (p.pos, 0..) |*v, r| v.* = s.k - rows + r; - if (p.which != .rel_table) { - p.q = try p.a.alloc(u16, rh * D); - p.tab = try p.a.alloc(u16, rh * EXTENT); - @memset(p.q, 0); - @memset(p.tab, 0); - } else { - p.rel = try p.a.alloc(u16, rh * R); - p.proj = try p.a.alloc(u16, R * EXTENT); - @memset(p.rel, 0); - @memset(p.proj, 0); - } - if (!controls.isAttention(p.which) and p.which != .rel_table) p.rel = try p.a.alloc(u16, rh * R); - if (p.which != .rel_table) { - p.kc = try p.a.alloc(u16, if (controls.isAttention(p.which)) cache else rows * KV * D); - p.vc = try p.a.alloc(u16, p.kc.len); - @memset(p.kc, 0); - @memset(p.vc, 0); - } + p.q = try p.a.alloc(u16, rh * D); + p.rel = try p.a.alloc(u16, rh * R); + p.kc = try p.a.alloc(u16, if (controls.isAttention(p.which)) cache else rows * KV * D); + p.vc = try p.a.alloc(u16, p.kc.len); + @memset(p.q, 0); + @memset(p.rel, 0); + @memset(p.kc, 0); + @memset(p.vc, 0); if (controls.isAttention(p.which)) { + p.proj = try p.a.alloc(u16, R * EXTENT); p.sink = try p.a.alloc(u16, rh); p.gate = try p.a.alloc(u16, rh * D); + @memset(p.proj, 0); @memset(p.sink, 0); @memset(p.gate, 0); - } - if (p.which == .prep_sliding or p.which == .prep_global) { + } else { p.qs = try p.a.alloc(u16, H * D); p.rs = try p.a.alloc(u16, H * R); @memset(p.qs, 0); @memset(p.rs, 0); } var prng = std.Random.DefaultPrng.init(seed); - const rng = prng.random(); - p.fillValues(rng, global); + p.fillValues(prng.random(), global); if (fill == .nonfinite) p.plant(); try p.bind(); return true; } fn fillValues(p: *Probe, rng: std.Random, global: bool) void { const stress = p.fill == .stress; - for (p.q) |*v| v.* = bits(if (stress and controls.isAttention(p.which)) 0 else if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 511))) - 255) else rng.floatNorm(f64) * 0.3); - for (p.kc) |*v| v.* = bits(if (stress and controls.isAttention(p.which)) 0 else if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 255))) - 127) else rng.floatNorm(f64) * 0.3); - for (p.vc, 0..) |*v, i| v.* = if (stress and controls.isAttention(p.which)) bits(periodic(i / D % p.layer.ring, i % D)) else bits(if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 255))) - 127) else rng.floatNorm(f64)); - for (p.tab) |*v| v.* = bits(if (stress) 0 else rng.floatNorm(f64) * 0.25); - for (p.sink) |*v| v.* = bits(if (stress) -std.math.inf(f64) else 2 + 4 * rng.float(f64)); - for (p.gate) |*v| v.* = bits(if (stress) 32 else rng.floatNorm(f64)); - for (p.rel, 0..) |*v, i| v.* = bits(if (stress) @floatFromInt(2 * (i % 31) + 1) else rng.floatNorm(f64)); - for (p.proj, 0..) |*v, i| v.* = bits(if (stress) @floatFromInt(1 + i % 2) else rng.floatNorm(f64) * 0.5); - for (p.qs) |*v| v.* = bits(if (stress) 1 else 0.5 + 2 * rng.float(f64)); - for (p.rs) |*v| v.* = bits(if (stress) 1 else 0.5 + 2 * rng.float(f64)); - if (global and !controls.isAttention(p.which)) { - _ = tau(p.pos[0]); - } + const attn = controls.isAttention(p.which); + for (p.q) |*v| v.* = ref.bits(if (stress and attn) 0 else if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 511))) - 255) else rng.floatNorm(f64) * 0.3); + for (p.kc) |*v| v.* = ref.bits(if (stress and attn) 0 else if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 255))) - 127) else rng.floatNorm(f64) * 0.3); + for (p.vc, 0..) |*v, i| v.* = if (stress and attn) ref.bits(ref.periodic(i / D % p.layer.ring, i % D)) else ref.bits(if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 255))) - 127) else rng.floatNorm(f64)); + for (p.sink) |*v| v.* = ref.bits(if (stress) -std.math.inf(f64) else 2 + 4 * rng.float(f64)); + for (p.gate) |*v| v.* = ref.bits(if (stress) 32 else rng.floatNorm(f64)); + for (p.rel, 0..) |*v, i| v.* = ref.bits(if (stress and attn) 0 else if (stress) @floatFromInt(2 * (i % 31) + 1) else rng.floatNorm(f64)); + for (p.proj) |*v| v.* = ref.bits(if (stress) 0 else rng.floatNorm(f64) * 0.5); + for (p.qs) |*v| v.* = ref.bits(if (stress) 1 else 0.5 + 2 * rng.float(f64)); + for (p.rs) |*v| v.* = ref.bits(if (stress) 1 else 0.5 + 2 * rng.float(f64)); + if (global and !attn) _ = ref.tau(p.pos[0]); } fn plant(p: *Probe) void { - const nan = bits(std.math.nan(f64)); - const inf = bits(std.math.inf(f64)); - if (p.which == .rel_table) { - p.rel[3] = nan; - if (p.rel.len > R + 5) p.rel[R + 5] = inf; - if (p.rel.len > 2 * R + 1) { - p.rel[2 * R] = inf; - p.rel[2 * R + 1] = inf | 0x8000; - } - } else if (controls.isAttention(p.which)) { + const nan = ref.bits(std.math.nan(f64)); + const inf = ref.bits(std.math.inf(f64)); + if (controls.isAttention(p.which)) { p.q[D + 5] = nan; p.sink[2] = inf; p.gate[3 * D] = inf; p.gate[3 * D + 1] = inf | 0x8000; + p.rel[4 * R + 2] = nan; + p.rel[5 * R + 1] = inf; } else { p.q[D + 3] = nan; p.kc[5] = inf; @@ -311,14 +247,8 @@ pub const Probe = struct { } fn bind(p: *Probe) !void { const rows = p.shape.rows; - if (p.which == .rel_table) { - p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.rel)); - p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.proj)); - p.out[0] = try p.rig.output(p.count() * 2); - return; - } if (controls.isAttention(p.which)) { - const arrays = [_][]u16{ p.q, p.kc, p.vc, p.tab, p.sink, p.gate }; + const arrays = [_][]u16{ p.q, p.kc, p.vc, p.rel, p.proj, p.sink, p.gate }; for (arrays, 0..) |x, i| p.refs[i] = try p.rig.input(std.mem.sliceAsBytes(x)); } else { const arrays = [_][]u16{ p.q, p.kc, p.vc, p.rel, p.qs, p.rs }; @@ -340,6 +270,12 @@ pub const Probe = struct { p.po = try p.rig.scratch(parts * D * 4); p.pml = try p.rig.scratch(parts * 8); p.out[0] = try p.rig.output(p.count() * 2); + if (p.base != null) { + p.base_tab = try p.rig.scratch(rows * H * EXTENT * 2); + p.base_po = try p.rig.scratch(parts * D * 4); + p.base_pml = try p.rig.scratch(parts * 8); + p.base_out = try p.rig.scratch(p.count() * 2); + } } else for (p.sizes(), 0..) |n, i| p.out[i] = try p.rig.output(n * 2); } pub fn run(p: *Probe) !void { @@ -348,12 +284,7 @@ pub const Probe = struct { e.setPipeline(p.main); const rows: u32 = @intCast(p.shape.rows); const ring = p.layer.ring; - if (p.which == .rel_table) { - e.setBuffer(p.refs[0].buf, p.refs[0].off, 0); - e.setBuffer(p.refs[1].buf, p.refs[1].off, 1); - e.setBuffer(p.out[0].buf, p.out[0].off, 2); - e.dispatchGroups(mtl.Size.of(rows * H, 1, 1), mtl.Size.of(256, 1, 1)); - } else if (!controls.isAttention(p.which)) { + if (!controls.isAttention(p.which)) { @memset(p.rig.bytes(p.out[2], p.sizes()[2] * 2), 0); @memset(p.rig.bytes(p.out[3], p.sizes()[3] * 2), 0); for (p.refs[0..6], 0..) |r, i| e.setBuffer(r.buf, r.off, i); @@ -363,164 +294,50 @@ pub const Probe = struct { e.dispatchGroups(mtl.Size.of(rows, H + 2 * KV, 1), mtl.Size.of(32, 1, 1)); } else { const stride = plan.slotsFor(p.layer, p.shape.k); - for (p.refs[0..4], 0..) |r, i| e.setBuffer(r.buf, r.off, i); - e.setBuffer(p.meta[2].buf, p.meta[2].off, 4); - e.setBuffer(p.po.buf, p.po.off, 5); - e.setBuffer(p.pml.buf, p.pml.off, 6); + for (p.refs[0..5], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(p.meta[2].buf, p.meta[2].off, 5); + e.setBuffer(p.po.buf, p.po.off, 6); + e.setBuffer(p.pml.buf, p.pml.off, 7); const sc: f32 = 1.0 / @sqrt(@as(f32, D)); if (controls.isPrompt(p.which)) { - e.setValue(plan.PromptArgs{ .heads = H, .kv_heads = KV, .ring = ring, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride, .scale = sc }, 7); + e.setValue(plan.PromptArgs{ .heads = H, .kv_heads = KV, .ring = ring, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride, .scale = sc }, 8); const blocks = (rows * (H / KV) + plan.prompt_pairs - 1) / plan.prompt_pairs; e.dispatchGroups(mtl.Size.of(blocks, KV, stride), mtl.Size.of(256, 1, 1)); } else { - e.setBuffer(p.meta[0].buf, p.meta[0].off, 7); - e.setBuffer(p.meta[1].buf, p.meta[1].off, 8); - e.setValue(plan.AttnArgs{ .heads = H, .kv_heads = KV, .ring = ring, .window = p.layer.window, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride, .scale = sc }, 9); + e.setBuffer(p.meta[0].buf, p.meta[0].off, 8); + e.setBuffer(p.meta[1].buf, p.meta[1].off, 9); + e.setValue(plan.AttnArgs{ .heads = H, .kv_heads = KV, .ring = ring, .window = p.layer.window, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride, .scale = sc }, 10); e.dispatchGroups(mtl.Size.of(rows * H, stride, 1), mtl.Size.of(32, 1, 1)); } e.barrier(); - e.setPipeline(p.merge); - e.setBuffer(p.po.buf, p.po.off, 0); - e.setBuffer(p.pml.buf, p.pml.off, 1); - e.setBuffer(p.refs[4].buf, p.refs[4].off, 2); - e.setBuffer(p.refs[5].buf, p.refs[5].off, 3); - e.setBuffer(p.meta[0].buf, p.meta[0].off, 4); - e.setBuffer(p.out[0].buf, p.out[0].off, 5); - e.setValue(plan.MergeArgs{ .heads = H, .window = p.layer.window, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride }, 6); - e.dispatchGroups(mtl.Size.of(rows * H, 1, 1), mtl.Size.of(D, 1, 1)); + ref.encodeMerge(e, p.merge, p.po, p.pml, p.refs[5], p.refs[6], p.meta[0], p.out[0], p.layer, rows, stride); } try p.rig.finish(pass); } + pub fn replaced(p: *Probe) ![]const u8 { + const b = p.base orelse return error.NoBaseline; + return b.run(&p.rig, p.which, p.layer, p.shape, &p.refs, &p.meta, p.base_tab, p.base_po, p.base_pml, p.base_out); + } + fn inputs(p: *const Probe) ref.Inputs { + return .{ .which = p.which, .shape = p.shape, .layer = p.layer, .q = p.q, .kc = p.kc, .vc = p.vc, .sink = p.sink, .gate = p.gate, .rel = p.rel, .proj = p.proj, .qs = p.qs, .rs = p.rs, .pos = p.pos, .sizes = p.sizes() }; + } pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { - if (p.which == .rel_table) return p.tableRef(null, want, mag); - if (controls.isAttention(p.which)) return p.attentionRef(null, want, mag); - return p.prepRef(null, want, mag); + if (controls.isAttention(p.which)) return ref.attentionRef(p.a, p.inputs(), null, want, mag); + return ref.prepRef(p.inputs(), null, want, mag); } pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { const mag = try p.a.alloc(f64, out.len); defer p.a.free(mag); - const sim: Sim = .{ .acc = acc, .order = order }; - if (p.which == .rel_table) return p.tableRef(sim, out, mag); - if (controls.isAttention(p.which)) return p.attentionRef(sim, out, mag); - return p.prepRef(sim, out, mag); - } - fn tableRef(p: *Probe, sim: ?Sim, want: []f64, mag: []f64) !void { - var terms: [R]f64 = undefined; - for (want, mag, 0..) |*w, *m, o| { - const rh = o / EXTENT; - const d = o % EXTENT; - for (&terms, 0..) |*v, j| v.* = bf(p.rel[rh * R + j]) * bf(p.proj[j * EXTENT + d]); - m.* = 0; - for (terms) |x| m.* += @abs(x); - const x = sum(&terms, sim); - w.* = if (sim != null) rn(x) else x; - } - } - fn headClip(x: []const f64, threshold: f64, sim: ?Sim, t: ?f64, want: []f64, mag: []f64) void { - var sq: [D]f64 = undefined; - mZero(mag); - for (sq[0..x.len], x, 0..) |*v, y, i| { - v.* = y * y; - mag[i] = @abs(y); - } - const f = minNum(threshold / (@sqrt(sum(sq[0..x.len], sim)) + 1e-6), 1); - for (want, x, mag) |*w, v, *m| { - w.* = rn(v * f); - if (t) |tv| w.* = rn(w.* * tv); - m.* = @abs(v) + v * v; - } - } - /// prep uses independent K/V and attention uses populated ring caches; q and rel never alias either one. - fn prepRef(p: *Probe, sim: ?Sim, want: []f64, mag: []f64) !void { - @memset(want, 0); - @memset(mag, 0); - const z = p.sizes(); - var x: [D]f64 = undefined; - for (0..p.shape.rows) |r| { - const tv: ?f64 = if (p.layer.tau) tau(p.pos[r]) else null; - for (0..H) |h| { - for (&x, 0..) |*v, d| v.* = bf(p.q[(r * H + h) * D + d]) * bf(p.qs[h * D + d]); - headClip(&x, 22.627416997969522, sim, tv, want[(r * H + h) * D ..][0..D], mag[(r * H + h) * D ..][0..D]); - for (x[0..R], 0..) |*v, d| v.* = bf(p.rel[(r * H + h) * R + d]) * bf(p.rs[h * R + d]); - const at = z[0] + (r * H + h) * R; - headClip(x[0..R], 8, sim, tv, want[at..][0..R], mag[at..][0..R]); - } - for (0..KV) |h| { - const slot = (h * p.layer.ring + p.pos[r] % p.layer.ring) * D; - for (&x, 0..) |*v, d| v.* = bf(p.kc[(r * KV + h) * D + d]); - headClip(&x, 22.627416997969522, sim, null, want[z[0] + z[1] + slot ..][0..D], mag[z[0] + z[1] + slot ..][0..D]); - var sq: [D]f64 = undefined; - for (&x, &sq, 0..) |*v, *ss, d| { - v.* = bf(p.vc[(r * KV + h) * D + d]); - ss.* = v.* * v.*; - } - const inv = 1 / @sqrt(sum(&sq, sim) / D + 1e-6); - for (0..D) |d| { - const at = z[0] + z[1] + z[2] + slot + d; - want[at] = rn(x[d] * inv); - mag[at] = sq[d] + @abs(x[d]); - } - } - } - } - fn mZero(mag: []f64) void { - @memset(mag, 0); - } - fn attentionRef(p: *Probe, sim: ?Sim, want: []f64, mag: []f64) !void { - const most = p.shape.k; - const score = try p.a.alloc(f64, most); - defer p.a.free(score); - const weights = try p.a.alloc(f64, most); - defer p.a.free(weights); - const terms = try p.a.alloc(f64, @max(most, D)); - defer p.a.free(terms); - for (0..p.shape.rows) |r| { - for (0..H) |h| { - const rh = r * H + h; - const pos = p.pos[r]; - const lo = if (p.layer.window > 0) (pos + 1) -| p.layer.window else 0; - const n = pos + 1 - lo; - const kvh = h / (H / KV); - const z = bf(p.sink[rh]); - // Prompt P is BF16 at the keys' maximum; the sink joins in the final merge using the shared maximum. - const prompt = sim == null and controls.isPrompt(p.which); - var peak = if (prompt) -std.math.inf(f64) else z; - for (lo..pos + 1) |kp| { - const j = kp - lo; - const at = (kvh * p.layer.ring + kp % p.layer.ring) * D; - for (0..D) |d| terms[d] = bf(p.q[rh * D + d]) * bf(p.kc[at + d]); - const distance = pos - kp; - const bias = if (distance < EXTENT) bf(p.tab[rh * EXTENT + distance]) else 0; - score[j] = sum(terms[0..D], sim) * scale + bias; - peak = maxNan(peak, score[j]); - } - if (prompt) { - peak = promptWeights(score[0..n], weights[0..n]); - } else for (weights[0..n], score[0..n]) |*w, sc| w.* = @exp(sc - peak); - const merged_peak = if (prompt) maxNan(peak, z) else peak; - const rescale = if (prompt) @exp(peak - merged_peak) else 1; - const den = sum(weights[0..n], sim) * rescale + @exp(z - merged_peak); - for (0..D) |d| { - for (lo..pos + 1) |kp| { - const j = kp - lo; - const at = (kvh * p.layer.ring + kp % p.layer.ring) * D; - terms[j] = weights[j] * bf(p.vc[at + d]); - } - const num = sum(terms[0..n], sim) * rescale; - const y = num / den * sigmoid(bf(p.gate[rh * D + d])); - want[rh * D + d] = if (sim != null) rn(y) else y; - mag[rh * D + d] = (@abs(num) + den + 1) * (1 + @abs(y)); - for (terms[0..n]) |v| mag[rh * D + d] += @abs(v * rescale); - } - } - } + const sim: ref.Sim = .{ .acc = acc, .order = order }; + if (controls.isAttention(p.which)) return ref.attentionRef(p.a, p.inputs(), sim, out, mag); + return ref.prepRef(p.inputs(), sim, out, mag); } }; fn supported(device: mtl.Device, w: Which) bool { return switch (w) { - .prompt_m5 => device.tensorUnits(), - .prompt_pre_m5 => !device.tensorUnits(), + .prompt_m5, .prompt_m5_long => device.tensorUnits(), + .prompt_pre_m5, .prompt_pre_m5_long => !device.tensorUnits(), else => true, }; } diff --git a/zig/tests/contract/metal_inkling2_attention_controls.zig b/zig/tests/contract/metal_inkling2_attention_controls.zig index f4b9cc69cb9..749f9a20fab 100644 --- a/zig/tests/contract/metal_inkling2_attention_controls.zig +++ b/zig/tests/contract/metal_inkling2_attention_controls.zig @@ -2,40 +2,59 @@ const std = @import("std"); const contract = @import("contract"); -pub const Which = enum { prep_sliding, prep_global, rel_table, decode_sliding, decode_global, prompt_m5, prompt_pre_m5 }; +pub const Which = enum { + prep_sliding, + prep_global, + decode_sliding, + decode_global, + decode_global_long, + prompt_m5, + prompt_m5_long, + prompt_pre_m5, + prompt_pre_m5_long, +}; pub fn function(w: Which) []const u8 { return switch (w) { .prep_sliding, .prep_global => "tf_ink2_prep", - .rel_table => "tf_ink2_rel_table", - .decode_sliding, .decode_global => "tf_ink2_attn_scalar", - .prompt_m5, .prompt_pre_m5 => "tf_ink2_attn_prompt", + .decode_sliding, .decode_global, .decode_global_long => "tf_ink2_attn_scalar", + .prompt_m5, .prompt_m5_long, .prompt_pre_m5, .prompt_pre_m5_long => "tf_ink2_attn_prompt", }; } pub fn isPrompt(w: Which) bool { - return w == .prompt_m5 or w == .prompt_pre_m5; + return w == .prompt_m5 or w == .prompt_m5_long or w == .prompt_pre_m5 or w == .prompt_pre_m5_long; +} +pub fn isPreM5(w: Which) bool { + return w == .prompt_pre_m5 or w == .prompt_pre_m5_long; +} +pub fn isLong(w: Which) bool { + return w == .decode_global_long or w == .prompt_m5_long or w == .prompt_pre_m5_long; } pub fn isAttention(w: Which) bool { - return w == .decode_sliding or w == .decode_global or isPrompt(w); + return w == .decode_sliding or w == .decode_global or w == .decode_global_long or isPrompt(w); } pub const Mutation = enum { none, prep_swap_kv, prep_tau_off, - rel_late, + decode_rel_late, decode_late_bias, merge_no_sink, + prompt_rel_late, prompt_late_bias, + prompt_pre_rel_late, prompt_pre_late_bias, pub fn name(m: Mutation) []const u8 { return switch (m) { .none => "", .prep_swap_kv => "control: metal inkling2 attention prep sliding with gated K/V inputs exchanged tf_ink2_prep", .prep_tau_off => "control: metal inkling2 attention global prep without tau tf_ink2_prep", - .rel_late => "control: metal inkling2 attention relative projection one column late tf_ink2_rel_table", + .decode_rel_late => "control: metal inkling2 attention sliding relative projection one column late tf_ink2_attn_scalar", .decode_late_bias => "control: metal inkling2 attention sliding first key score boosted tf_ink2_attn_scalar", .merge_no_sink => "control: metal inkling2 attention global merge without sink tf_ink2_merge", + .prompt_rel_late => "control: metal inkling2 prompt m5 relative projection one column late tf_ink2_attn_prompt", .prompt_late_bias => "control: metal inkling2 prompt m5 first key bias boosted tf_ink2_attn_prompt", + .prompt_pre_rel_late => "control: metal inkling2 prompt pre-m5 relative projection one column late tf_ink2_attn_prompt", .prompt_pre_late_bias => "control: metal inkling2 prompt pre-m5 first key bias boosted tf_ink2_attn_prompt", }; } @@ -47,11 +66,10 @@ pub const Mutation = enum { .none => unreachable, .prep_swap_kv => .prep_sliding, .prep_tau_off => .prep_global, - .rel_late => .rel_table, - .decode_late_bias => .decode_sliding, + .decode_rel_late, .decode_late_bias => .decode_sliding, .merge_no_sink => .decode_global, - .prompt_late_bias => .prompt_m5, - .prompt_pre_late_bias => .prompt_pre_m5, + .prompt_rel_late, .prompt_late_bias => .prompt_m5, + .prompt_pre_rel_late, .prompt_pre_late_bias => .prompt_pre_m5, }; } const Edit = struct { from: []const u8, to: []const u8 }; @@ -66,9 +84,9 @@ pub const Mutation = enum { .from = "const float tau = a.global ? 1.0f + a.alpha * precise::log(max(float(pos + 1) / a.floor_pos, 1.0f)) : 1.0f;", .to = "const float tau = 1.0f;", }, - .rel_late => .{ - .from = "acc += r[j] * float(proj[j * EXTENT + d]);", - .to = "acc += r[j] * float(proj[j * EXTENT + (d + 1) % EXTENT]);", + .decode_rel_late => .{ + .from = "acc_b += r_j * (need_bias ? float(proj[j * EXTENT + dist_safe]) : 0.0f);", + .to = "acc_b += r_j * (need_bias ? float(proj[j * EXTENT + (dist_safe + 1) % EXTENT]) : 0.0f);", }, .decode_late_bias => .{ .from = "const float score = (dot_score * a.scale + bias) * LOG2E;", @@ -78,9 +96,13 @@ pub const Mutation = enum { .from = "const float sk = float(sink[rh]) * LOG2E, mf = max(mm, sk), a0 = precise::exp2(mm - mf);", .to = "const float sk = -INFINITY, mf = max(mm, sk), a0 = precise::exp2(mm - mf);", }, + .prompt_rel_late, .prompt_pre_rel_late => .{ + .from = "for (uint j = 0; j < REL; ++j) acc_b += r[j] * float(proj[j * EXTENT + distance]);", + .to = "for (uint j = 0; j < REL; ++j) acc_b += r[j] * float(proj[j * EXTENT + (distance + 1) % EXTENT]);", + }, .prompt_late_bias, .prompt_pre_late_bias => .{ - .from = "const float bias = live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f;", - .to = "const float bias = (live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f) + (live && kp == b_lo ? 128.0f : 0.0f);", + .from = "score[f][e] = live ? (score[f][e] * a.scale + bias) * LOG2E : -INFINITY;", + .to = "score[f][e] = live ? (score[f][e] * a.scale + bias + (kp == b_lo ? 128.0f : 0.0f)) * LOG2E : -INFINITY;", }, }; } @@ -99,7 +121,7 @@ test "Inkling 2 attention controls each hit one live statement and cannot apply for (std.enums.values(Mutation)) |m| { if (m == .none) continue; const w = m.which(); - const plain = if (isPrompt(w)) (if (w == .prompt_pre_m5) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; + const plain = if (isPrompt(w)) (if (isPreM5(w)) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; const edited = try apply(a, plain, m); defer a.free(edited); try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); diff --git a/zig/tests/contract/metal_inkling2_attention_ref.zig b/zig/tests/contract/metal_inkling2_attention_ref.zig new file mode 100644 index 00000000000..85e48876ef6 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_attention_ref.zig @@ -0,0 +1,285 @@ +//! Float64 references and frozen main baselines for Inkling 2 Mini Metal attention gates 1-4. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_inkling2_attention_controls.zig"); +const nax_src = @import("kernel_sources").nax; +const plan = @import("tensorfold").inkling2_metal_host.attention.planning; +const c = contract.spec; +const g = contract.gates; +const Which = controls.Which; + +pub const D = 128; +pub const H = 24; +pub const KV = 8; +pub const R = 16; +pub const EXTENT = 1024; +pub const scale = 0.08838834764831845; +const base_attn_src = @embedFile("baselines/inkling2_attention_main.metal.txt"); +const base_prompt_src = @embedFile("baselines/inkling2_prompt_attention_main.metal.txt"); + +pub const Sim = struct { acc: c.Accum, order: g.Order }; +pub const Inputs = struct { + which: Which, + shape: c.Shape, + layer: plan.Layer, + q: []const u16, + kc: []const u16, + vc: []const u16, + sink: []const u16, + gate: []const u16, + rel: []const u16, + proj: []const u16, + qs: []const u16, + rs: []const u16, + pos: []const usize, + sizes: [4]usize, +}; + +pub fn bf(x: u16) f64 { + return c.fromBf16(x); +} +pub fn rn(x: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(x))); +} +pub fn bits(x: f64) u16 { + return c.toBf16(@floatCast(x)); +} +fn minNum(x: f64, y: f64) f64 { + return if (std.math.isNan(x)) y else if (std.math.isNan(y)) x else @min(x, y); +} +fn maxNan(x: f64, y: f64) f64 { + return if (std.math.isNan(x) or std.math.isNan(y)) std.math.nan(f64) else @max(x, y); +} +fn sigmoid(x: f64) f64 { + return 1 / (1 + @exp(-x)); +} +pub fn tau(pos: usize) f64 { + return 1 + 0.1 * @log(@max(@as(f64, @floatFromInt(pos + 1)) / 8192, 1)); +} +pub fn periodic(p: usize, col: usize) f64 { + const i = p % 1024; + if (i < 512) return @floatFromInt(129 + (i * 73 + col * 31) % 127); + const j = i - 512; + return -@as(f64, @floatFromInt(129 + ((j + 1) * 73 + col * 31) % 127)) + @as(f64, if (j < 8) 1 else 0); +} +fn sum(v: []const f64, sim: ?Sim) f64 { + if (sim) |s| return contract.rows.sumIn(s.acc, s.order, v); + var total: f64 = 0; + for (v) |x| total += x; + return total; +} +/// Prompt P rounds to BF16 at each tile maximum; later rescaling does not round twice. The result anchors weights. +fn promptWeights(score: []const f64, weights: []f64) f64 { + const tile_keys = 64; + const sub_keys = 1024; + var top = -std.math.inf(f64); + var upper = -std.math.inf(f64); + var first: usize = 0; + while (first < score.len) { + const end = @min(first + tile_keys, score.len); + const sub_first = first - first % sub_keys; + var tile_peak = top; + for (score[first..end]) |sc| tile_peak = maxNan(tile_peak, sc); + const mu = if (tile_peak == -std.math.inf(f64)) 0 else tile_peak; + const keep = @exp(top - mu); + for (weights[sub_first..first]) |*w| w.* *= keep; + for (weights[first..end], score[first..end]) |*w, sc| w.* = rn(@exp(sc - mu)); + top = tile_peak; + if (first % sub_keys == sub_keys - tile_keys or end == score.len) { + if (top != -std.math.inf(f64)) { + const merged = maxNan(upper, top); + const old_scale = @exp(upper - merged); + const new_scale = @exp(top - merged); + for (weights[0..sub_first]) |*w| w.* *= old_scale; + for (weights[sub_first..end]) |*w| w.* *= new_scale; + upper = merged; + } + top = -std.math.inf(f64); + } + first = end; + } + return upper; +} +fn headClip(x: []const f64, threshold: f64, sim: ?Sim, t: ?f64, want: []f64, mag: []f64) void { + var sq: [D]f64 = undefined; + @memset(mag, 0); + for (sq[0..x.len], x, 0..) |*v, y, i| { + v.* = y * y; + mag[i] = @abs(y); + } + const f = minNum(threshold / (@sqrt(sum(sq[0..x.len], sim)) + 1e-6), 1); + for (want, x, mag) |*w, v, *m| { + w.* = rn(v * f); + if (t) |tv| w.* = rn(w.* * tv); + m.* = @abs(v) + v * v; + } +} +/// prep uses independent K/V and attention uses populated ring caches; q and rel never alias either one. +pub fn prepRef(in: Inputs, sim: ?Sim, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + const z = in.sizes; + var x: [D]f64 = undefined; + for (0..in.shape.rows) |r| { + const tv: ?f64 = if (in.layer.tau) tau(in.pos[r]) else null; + for (0..H) |h| { + for (&x, 0..) |*v, d| v.* = bf(in.q[(r * H + h) * D + d]) * bf(in.qs[h * D + d]); + headClip(&x, 22.627416997969522, sim, tv, want[(r * H + h) * D ..][0..D], mag[(r * H + h) * D ..][0..D]); + for (x[0..R], 0..) |*v, d| v.* = bf(in.rel[(r * H + h) * R + d]) * bf(in.rs[h * R + d]); + const at = z[0] + (r * H + h) * R; + headClip(x[0..R], 8, sim, tv, want[at..][0..R], mag[at..][0..R]); + } + for (0..KV) |h| { + const slot = (h * in.layer.ring + in.pos[r] % in.layer.ring) * D; + for (&x, 0..) |*v, d| v.* = bf(in.kc[(r * KV + h) * D + d]); + headClip(&x, 22.627416997969522, sim, null, want[z[0] + z[1] + slot ..][0..D], mag[z[0] + z[1] + slot ..][0..D]); + var sq: [D]f64 = undefined; + for (&x, &sq, 0..) |*v, *ss, d| { + v.* = bf(in.vc[(r * KV + h) * D + d]); + ss.* = v.* * v.*; + } + const inv = 1 / @sqrt(sum(&sq, sim) / D + 1e-6); + for (0..D) |d| { + const at = z[0] + z[1] + z[2] + slot + d; + want[at] = rn(x[d] * inv); + mag[at] = sq[d] + @abs(x[d]); + } + } + } +} +pub fn attentionRef(a: std.mem.Allocator, in: Inputs, sim: ?Sim, want: []f64, mag: []f64) !void { + const most = in.shape.k; + const score = try a.alloc(f64, most); + defer a.free(score); + const weights = try a.alloc(f64, most); + defer a.free(weights); + const terms = try a.alloc(f64, @max(most, D)); + defer a.free(terms); + for (0..in.shape.rows) |r| { + for (0..H) |h| { + const rh = r * H + h; + const pos = in.pos[r]; + const lo = if (in.layer.window > 0) (pos + 1) -| in.layer.window else 0; + const n = pos + 1 - lo; + const kvh = h / (H / KV); + const z = bf(in.sink[rh]); + // Prompt P is BF16 at the keys' maximum; the sink joins in the final merge using the shared maximum. + const prompt = sim == null and controls.isPrompt(in.which); + var peak = if (prompt) -std.math.inf(f64) else z; + for (lo..pos + 1) |kp| { + const j = kp - lo; + const at = (kvh * in.layer.ring + kp % in.layer.ring) * D; + for (0..D) |d| terms[d] = bf(in.q[rh * D + d]) * bf(in.kc[at + d]); + const distance = pos - kp; + var bias: f64 = 0; + if (distance < EXTENT) { + var rterms: [R]f64 = undefined; + for (&rterms, 0..) |*v, rj| v.* = bf(in.rel[rh * R + rj]) * bf(in.proj[rj * EXTENT + distance]); + bias = rn(sum(&rterms, sim)); + } + score[j] = sum(terms[0..D], sim) * scale + bias; + peak = maxNan(peak, score[j]); + } + if (prompt) { + peak = promptWeights(score[0..n], weights[0..n]); + } else for (weights[0..n], score[0..n]) |*w, sc| w.* = @exp(sc - peak); + const merged_peak = if (prompt) maxNan(peak, z) else peak; + const rescale = if (prompt) @exp(peak - merged_peak) else 1; + const den = sum(weights[0..n], sim) * rescale + @exp(z - merged_peak); + for (0..D) |d| { + for (lo..pos + 1) |kp| { + const j = kp - lo; + const at = (kvh * in.layer.ring + kp % in.layer.ring) * D; + terms[j] = weights[j] * bf(in.vc[at + d]); + } + const num = sum(terms[0..n], sim) * rescale; + const y = num / den * sigmoid(bf(in.gate[rh * D + d])); + want[rh * D + d] = if (sim != null) rn(y) else y; + mag[rh * D + d] = (@abs(num) + den + 1) * (1 + @abs(y)); + for (terms[0..n]) |v| mag[rh * D + d] += @abs(v * rescale); + } + } + } +} +pub fn encodeMerge(e: mtl.ComputeEncoder, pipe: mtl.Pipeline, po: rig_.Ref, pml: rig_.Ref, sink: rig_.Ref, gate: rig_.Ref, pos: rig_.Ref, out: rig_.Ref, layer: plan.Layer, rows: u32, stride: u32) void { + e.setPipeline(pipe); + e.setBuffer(po.buf, po.off, 0); + e.setBuffer(pml.buf, pml.off, 1); + e.setBuffer(sink.buf, sink.off, 2); + e.setBuffer(gate.buf, gate.off, 3); + e.setBuffer(pos.buf, pos.off, 4); + e.setBuffer(out.buf, out.off, 5); + e.setValue(plan.MergeArgs{ .heads = H, .window = layer.window, .chunk = layer.chunk, .c0 = 0, .chunks = stride }, 6); + e.dispatchGroups(mtl.Size.of(rows * H, 1, 1), mtl.Size.of(D, 1, 1)); +} +pub const Baseline = struct { + scalar_lib: mtl.Library, + prompt_lib: ?mtl.Library = null, + rel_table: mtl.Pipeline, + attn: mtl.Pipeline, + merge: mtl.Pipeline, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, w: Which) !Baseline { + var scalar_lib = try mtl.Library.fromSource(device, base_attn_src, mtl.CompileOptions.mlx()); + errdefer scalar_lib.deinit(); + var rel_table = try mtl.Pipeline.init(device, scalar_lib, "tf_ink2_rel_table", false); + errdefer rel_table.deinit(); + var merge = try mtl.Pipeline.init(device, scalar_lib, "tf_ink2_merge", false); + errdefer merge.deinit(); + var prompt_lib: ?mtl.Library = null; + errdefer if (prompt_lib) |loaded| loaded.deinit(); + if (controls.isPrompt(w)) { + const prefix = if (controls.isPreM5(w)) "#define TF_SIMD_FRAGS 1\n" else ""; + const p_src = try std.mem.concat(a, u8, &.{ prefix, nax_src, base_prompt_src }); + defer a.free(p_src); + prompt_lib = try mtl.Library.fromSource(device, p_src, mtl.CompileOptions.mlx()); + } + const attn = try mtl.Pipeline.init(device, prompt_lib orelse scalar_lib, if (controls.isPrompt(w)) "tf_ink2_attn_prompt" else "tf_ink2_attn_scalar", false); + return .{ .scalar_lib = scalar_lib, .prompt_lib = prompt_lib, .rel_table = rel_table, .attn = attn, .merge = merge }; + } + pub fn deinit(b: *Baseline) void { + b.attn.deinit(); + b.merge.deinit(); + b.rel_table.deinit(); + if (b.prompt_lib) |loaded| loaded.deinit(); + b.scalar_lib.deinit(); + } + pub fn run(b: *const Baseline, rig: *rig_.Rig, which: Which, layer: plan.Layer, shape: c.Shape, refs: []const rig_.Ref, meta: []const rig_.Ref, tab: rig_.Ref, po: rig_.Ref, pml: rig_.Ref, out: rig_.Ref) ![]const u8 { + const rows: u32 = @intCast(shape.rows); + const stride = plan.slotsFor(layer, shape.k); + const out_bytes = shape.rows * H * D * 2; + @memset(rig.bytes(tab, shape.rows * H * EXTENT * 2), 0xff); + @memset(rig.bytes(out, out_bytes), 0xff); + const pass = rig.begin(); + const e = pass.e; + e.setPipeline(b.rel_table); + e.setBuffer(refs[3].buf, refs[3].off, 0); + e.setBuffer(refs[4].buf, refs[4].off, 1); + e.setBuffer(tab.buf, tab.off, 2); + e.dispatchGroups(mtl.Size.of(rows * H, 1, 1), mtl.Size.of(256, 1, 1)); + e.barrier(); + e.setPipeline(b.attn); + for (refs[0..3], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(tab.buf, tab.off, 3); + e.setBuffer(meta[2].buf, meta[2].off, 4); + e.setBuffer(po.buf, po.off, 5); + e.setBuffer(pml.buf, pml.off, 6); + const sc: f32 = 1.0 / @sqrt(@as(f32, D)); + if (controls.isPrompt(which)) { + e.setValue(plan.PromptArgs{ .heads = H, .kv_heads = KV, .ring = layer.ring, .chunk = layer.chunk, .c0 = 0, .chunks = stride, .scale = sc }, 7); + const blocks = (rows * (H / KV) + plan.prompt_pairs - 1) / plan.prompt_pairs; + e.dispatchGroups(mtl.Size.of(blocks, KV, stride), mtl.Size.of(256, 1, 1)); + } else { + e.setBuffer(meta[0].buf, meta[0].off, 7); + e.setBuffer(meta[1].buf, meta[1].off, 8); + e.setValue(plan.AttnArgs{ .heads = H, .kv_heads = KV, .ring = layer.ring, .window = layer.window, .chunk = layer.chunk, .c0 = 0, .chunks = stride, .scale = sc }, 9); + e.dispatchGroups(mtl.Size.of(rows * H, stride, 1), mtl.Size.of(32, 1, 1)); + } + e.barrier(); + encodeMerge(e, b.merge, po, pml, refs[5], refs[6], meta[0], out, layer, rows, stride); + try rig.finish(pass); + return rig.bytes(out, out_bytes); + } +};