diff --git a/zig/src/families/inkling2/metal/attention.zig b/zig/src/families/inkling2/metal/attention.zig index 2e4a2f2b178..d1278fa5669 100644 --- a/zig/src/families/inkling2/metal/attention.zig +++ b/zig/src/families/inkling2/metal/attention.zig @@ -145,7 +145,7 @@ pub fn prepTree(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: p prepLaunch(k.prep_tree, e, r, l, c, meta, raw, scales, q, rel, kv); } -fn attendImpl(k: *const Kernels, e: anytype, 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, cached: ?Ref) !void { +fn partialsImpl(k: *const Kernels, e: anytype, 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, cached: ?Ref) !planning.Launch { const launch = try planning.attend(r, l, stride, slots); explain.reportAttention(launch, r.rows); const scale: f32 = 1.0 / @sqrt(@as(f32, planning.head_dim)); @@ -176,12 +176,18 @@ fn attendImpl(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Layer }, } e.dispatchGroups(mtl.Size.of(launch.grid[0], launch.grid[1], launch.grid[2]), mtl.Size.of(launch.threads, 1, 1)); + return launch; +} +pub fn partials(k: *const Kernels, e: anytype, 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) !planning.Launch { + return partialsImpl(k, e, r, l, stride, slots, meta, q, kv, rel, proj, part_o, part_ml, null); +} + +fn attendImpl(k: *const Kernels, e: anytype, 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, cached: ?Ref) !void { + const launch = try partialsImpl(k, e, r, l, stride, slots, meta, q, kv, rel, proj, part_o, part_ml, cached); e.barrier(); - e.setPipeline(k.merge); - bind(e, &.{ part_o, part_ml, sink, gate, meta.pos, out }, 0); - e.setValue(planning.MergeArgs{ .heads = r.heads, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .subs = launch.subs }, 6); - e.dispatchGroups(mtl.Size.of(launch.merge_grid[0], 1, 1), mtl.Size.of(planning.merge_threads, 1, 1)); + mergeRaw(k, e, r, l, launch.partials_rh, launch.subs, meta, part_o, part_ml, sink, gate, out); } + pub fn attend(k: *const Kernels, e: anytype, 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 { return attendImpl(k, e, r, l, stride, slots, meta, q, kv, rel, proj, part_o, part_ml, sink, gate, out, null); } @@ -226,7 +232,7 @@ pub fn attendCached(k: *const Kernels, e: anytype, r: planning.Rows, l: planning } /// The table is opt-out at sixteen active global chunks, and never serves prompt, tree or batched paths. -pub fn attendReusable(k: *const Kernels, e: anytype, 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, min_context: u32, segments: usize, tree: bool, decode: bool, tab: Ref) !void { +pub fn partialsReusable(k: *const Kernels, e: anytype, 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, min_context: u32, segments: usize, tree: bool, decode: bool, tab: Ref) !planning.Launch { const decode_slots = @as(usize, r.rows) * r.heads * stride * planning.subs; const launch = try planning.attend(r, l, stride, if (decode) decode_slots else slots); const kind: relbias.Kind = switch (launch.path) { @@ -244,10 +250,17 @@ pub fn attendReusable(k: *const Kernels, e: anytype, r: planning.Rows, l: planni tree, kind, )) { - return attendImpl(k, e, r, l, stride, slots, meta, q, kv, rel, proj, part_o, part_ml, sink, gate, out, null); + return partialsImpl(k, e, r, l, stride, slots, meta, q, kv, rel, proj, part_o, part_ml, null); } try projectRelTable(k, e, r, meta.pos, rel, proj, tab); - return attendImpl(k, e, r, l, stride, decode_slots, meta, q, kv, rel, proj, part_o, part_ml, sink, gate, out, tab); + e.barrier(); + return partialsImpl(k, e, r, l, stride, decode_slots, meta, q, kv, rel, proj, part_o, part_ml, tab); +} + +pub fn attendReusable(k: *const Kernels, e: anytype, 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, min_context: u32, segments: usize, tree: bool, decode: bool, tab: Ref) !void { + const launch = try partialsReusable(k, e, r, l, stride, slots, meta, q, kv, rel, proj, part_o, part_ml, min_context, segments, tree, decode, tab); + e.barrier(); + mergeRaw(k, e, r, l, launch.partials_rh, launch.subs, meta, part_o, part_ml, sink, gate, out); } fn fillBatchedSegs(e: mtl.ComputeEncoder, caches: []const BatchedCache, usage: usize, out: *[planning.max_batched_segments]planning.BatchedSeg) ![]const planning.BatchedSeg { @@ -298,35 +311,52 @@ pub fn attendBatched(k: *const Kernels, e: mtl.ComputeEncoder, launch: planning. e.dispatchGroups(mtl.Size.of(launch.merge_grid[0], 1, 1), mtl.Size.of(planning.merge_threads, 1, 1)); } -pub fn attendTree(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, start: u32, meta: RowMeta, tree_paths: Ref, tail_o: Ref, tail_ml: Ref, 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.attendTree(r, l, stride, start); - explain.reportTree(launch, r.rows); +pub fn treePrefix(k: *const Kernels, e: mtl.ComputeEncoder, launch: planning.TreeLaunch, r: planning.Rows, l: planning.Layer, meta: RowMeta, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref, tail_o: Ref, tail_ml: Ref) bool { + if (!launch.global or launch.p_tile == 0) return false; + const scale: f32 = 1.0 / @sqrt(@as(f32, planning.head_dim)); + const prompt_segs = meta.prompt_segs orelse meta.segs; + const args = planning.PromptTreeArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale, .p_tile = launch.p_tile, .c_off = launch.c_off, .max_pos = r.last_pos }; + e.setPipeline(k.prompt_tree_prefix); + bind(e, &.{ q, kv.k, kv.v, rel, proj, prompt_segs, part_o, part_ml, meta.pos, tail_o, tail_ml }, 0); + e.setValue(args, 11); + e.dispatchGroups(mtl.Size.of(launch.prefix_grid[0], launch.prefix_grid[1], launch.prefix_grid[2]), mtl.Size.of(launch.threads, 1, 1)); + return true; +} + +pub fn treePartials(k: *const Kernels, e: mtl.ComputeEncoder, launch: planning.TreeLaunch, r: planning.Rows, l: planning.Layer, meta: RowMeta, tree_paths: Ref, tail_o: Ref, tail_ml: Ref, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref) void { const scale: f32 = 1.0 / @sqrt(@as(f32, planning.head_dim)); if (launch.global) { const prompt_segs = meta.prompt_segs orelse meta.segs; const args = planning.PromptTreeArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale, .p_tile = launch.p_tile, .c_off = launch.c_off, .max_pos = r.last_pos }; - if (launch.p_tile > 0) { - e.setPipeline(k.prompt_tree_prefix); - bind(e, &.{ q, kv.k, kv.v, rel, proj, prompt_segs, part_o, part_ml, meta.pos, tail_o, tail_ml }, 0); - e.setValue(args, 11); - e.dispatchGroups(mtl.Size.of(launch.prefix_grid[0], launch.prefix_grid[1], launch.prefix_grid[2]), mtl.Size.of(launch.threads, 1, 1)); - e.barrier(); - } e.setPipeline(k.prompt_tree_tail); bind(e, &.{ q, kv.k, kv.v, rel, proj, prompt_segs, part_o, part_ml, meta.pos, tree_paths, tail_o, tail_ml }, 0); e.setValue(args, 12); - e.dispatchGroups(mtl.Size.of(launch.tail_grid[0], launch.tail_grid[1], launch.tail_grid[2]), mtl.Size.of(launch.threads, 1, 1)); } else { e.setPipeline(k.decode_tree); bind(e, &.{ q, kv.k, kv.v, rel, proj, meta.segs, part_o, part_ml, meta.pos, meta.seg_of, tree_paths }, 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 }, 11); - e.dispatchGroups(mtl.Size.of(launch.tail_grid[0], launch.tail_grid[1], launch.tail_grid[2]), mtl.Size.of(launch.threads, 1, 1)); } - e.barrier(); + e.dispatchGroups(mtl.Size.of(launch.tail_grid[0], launch.tail_grid[1], launch.tail_grid[2]), mtl.Size.of(launch.threads, 1, 1)); +} + +pub fn mergeRaw(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Layer, partials_rh: u32, subs: u32, meta: RowMeta, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) void { e.setPipeline(k.merge); bind(e, &.{ part_o, part_ml, sink, gate, meta.pos, out }, 0); - e.setValue(planning.MergeArgs{ .heads = r.heads, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .subs = 1 }, 6); - e.dispatchGroups(mtl.Size.of(launch.merge_grid[0], 1, 1), mtl.Size.of(planning.merge_threads, 1, 1)); + e.setValue(planning.MergeArgs{ .heads = r.heads, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = partials_rh, .subs = subs }, 6); + e.dispatchGroups(mtl.Size.of(r.rows * r.heads, 1, 1), mtl.Size.of(planning.merge_threads, 1, 1)); +} + +pub fn merge(k: *const Kernels, e: mtl.ComputeEncoder, launch: planning.Launch, r: planning.Rows, l: planning.Layer, meta: RowMeta, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) void { + mergeRaw(k, e, r, l, launch.partials_rh, launch.subs, meta, part_o, part_ml, sink, gate, out); +} + +pub fn attendTree(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, start: u32, meta: RowMeta, tree_paths: Ref, tail_o: Ref, tail_ml: Ref, 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.attendTree(r, l, stride, start); + explain.reportTree(launch, r.rows); + if (treePrefix(k, e, launch, r, l, meta, q, kv, rel, proj, part_o, part_ml, tail_o, tail_ml)) e.barrier(); + treePartials(k, e, launch, r, l, meta, tree_paths, tail_o, tail_ml, q, kv, rel, proj, part_o, part_ml); + e.barrier(); + mergeRaw(k, e, r, l, launch.partials_rh, 1, meta, part_o, part_ml, sink, gate, out); } test { diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index 08341e36455..76f98e484f8 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -7,7 +7,11 @@ const ap = @import("attention_plan.zig"); const attention = @import("attention.zig"); const glue = @import("glue.zig"); const metal_reset = @import("reset.zig"); -const experts = @import("experts.zig"); +const forward_experts = @import("forward_experts.zig"); +const forward_attention = @import("forward_attention.zig"); +const forward_dispatch = @import("forward_dispatch.zig"); +pub const runtime = forward_dispatch.runtime; +pub const copyBf16 = forward_dispatch.copyBf16; const loop = @import("loop.zig"); const dense_mma = @import("dense.zig"); const attention_dense = @import("forward_attention_dense.zig"); @@ -26,6 +30,9 @@ pub const Draw = sample.Draw; pub const DrawMode = sample.DrawMode; pub const drawMode = sample.drawMode; pub const Segment = struct { cache: *state.Cache, rows: usize, parents: ?[]const i32 = null }; +pub const fusedConv = forward_attention.fusedConv; +pub const postConv = forward_attention.postConv; +pub const convInputsForAttention = forward_attention.convInputsForAttention; pub const SegMeta = struct { is_tree: bool = false, max_depth: u32 = 0 }; /// The BF16 rows [off, off + rows * hidden * 2) of `buf` replace the normed embeddings of chunk rows [row, row + rows). pub const ImageRows = struct { row: u32, rows: u32, buf: mtl.Buffer, off: usize = 0 }; @@ -46,7 +53,6 @@ pub const Options = struct { pub const FinalPlan = @import("forward_final.zig").Plan; pub const finalPlan = @import("forward_final.zig").plan; -const RArgs = extern struct { count: u32, boundary: u32 = 0 }; const NormArgs = extern struct { rows: u32, width: u32, heads: u32 = 0, bits: u32 = 0, group: u32 = 0, eps: f32 }; pub const DenseArgs = extern struct { rows: u32, n: u32, k: u32, ldy: u32 }; @@ -62,9 +68,6 @@ pub fn row(buf: mtl.Buffer, i: usize, row_bytes: usize) Ref { pub fn a(x_: Ref) attention.Ref { return .{ .buf = x_.buf, .off = x_.off }; } -pub fn x(x_: Ref) experts.Ref { - return .{ .buf = x_.buf, .off = x_.off }; -} pub fn l(x_: Ref) loop.Ref { return .{ .buf = x_.buf, .off = x_.off }; } @@ -89,16 +92,6 @@ pub fn gates(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, h: Ref, loop.gatesSplit(&m.loop, e, l(h), l(msg), stride, l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(out), l(at(s.gate_norm, 0)), l(at(s.gate_zeta, 0)), @intCast(rows)); } -pub fn runtime(m: *const Model, e: mtl.ComputeEncoder, op: model_file.RuntimeOp, refs: []const Ref, count: usize, boundary: usize) void { - e.setPipeline(m.runtime[@backingInt(op)]); - for (refs, 0..) |r_, i| e.setBuffer(r_.buf, r_.off, i); - e.setValue(RArgs{ .count = @intCast(count), .boundary = @intCast(boundary) }, refs.len); - e.dispatchThreads(mtl.Size.of(count, 1, 1), mtl.Size.of(256, 1, 1)); -} - -pub fn copyBf16(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, count: usize) void { - runtime(m, e, .copy_bf16, &.{ from, to }, count, 0); -} pub fn captureTap(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, rows: usize, channel: usize) void { std.debug.assert(channel < state.feature_taps); runtime(m, e, .capture_tap, &.{ from, to }, rows * state.hidden, channel); @@ -172,9 +165,11 @@ pub fn bankAndReset(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, r copyBf16(m, e, at(s.blocks, (i * state.block_slots + 2) * state.hidden * 2), row(s.bank0, i, state.hidden * 2), state.hidden); } copyBf16(m, e, at(s.p, 0), at(s.bank1, 0), rows * state.hidden); + e.barrier(); loop.crossPassMessageAttention(&m.loop, e, l(at(s.bank0, 0)), l(at(s.bank1, 0)), l(r(m.weights.cross_queries)), l(r(m.weights.cross_kv_queries)), l(at(s.messages, 0)), @intCast(rows)); // The prelude p is restored, but every visit's KV and convolution state remains live. copyBf16(m, e, at(s.prelude, 0), at(s.p, 0), rows * state.hidden); + e.barrier(); } pub fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, rows: usize, pre_fused: bool, pre_fused_norm: bool) !void { @@ -188,6 +183,7 @@ pub fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state. if (!pre_fused) { metal_reset.cachedAttention(m, e, s, v, rows); } + e.barrier(); if (v.hasMessages()) { const controllers = w.controllers.?; const core = v.layer - 6; @@ -208,6 +204,7 @@ pub fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state. loop.gatesEach(&m.loop, e, &roles, @intCast(rows), state.message_entries * state.hidden); } } + e.barrier(); const gated = v.hasMessages(); // An ungated local visit has exactly one AR result and one norm result; Q/K/V alias. if (!gated and lp.kind == .local) { @@ -219,132 +216,6 @@ pub fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state. } } -pub fn fusedConv(segments: []const Segment, meta: []const SegMeta) bool { - for (meta) |m| if (m.is_tree) return false; - return segments.len > 1 or segments[0].rows <= state.window_rows; -} - -pub fn postConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: []const Segment, meta: []const SegMeta, slot: usize, cs: usize, raw: Ref, weight: ck.Tensor, out: Ref) void { - if (fusedConv(segments, meta)) return conv.postConv(m, e, s, segments, slot, cs, raw, weight, out); - var base: usize = 0; - for (segments, meta) |seg, sm| { - staticPostConv(m, e, s, seg.cache, slot, cs, raw, weight, out, base, seg.rows, sm.is_tree); - base += seg.rows; - } -} - -fn stageConvInput(m: *const Model, e: mtl.ComputeEncoder, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, base: usize, rows: usize) Ref { - const channels = state.convWidth(conv_state); - const taps = cache.staged(slot, conv_state, 0); - copyBf16(m, e, cache.history(slot, conv_state), taps, 3 * channels); - copyBf16(m, e, at(raw.buf, raw.off + base * channels * 2), cache.staged(slot, conv_state, 3), rows * channels); - return taps; -} - -fn staticPostConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, weight: ck.Tensor, out: Ref, base: usize, rows: usize, is_tree: bool) void { - const channels = state.convWidth(conv_state); - const taps = stageConvInput(m, e, cache, slot, conv_state, raw, base, rows); - if (is_tree) { - tree.convStatic(&m.tree, e, taps, r(weight), at(s.conv_src, base * 4 * 4), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels)); - } else { - glue.convStatic(&m.glue, e, taps, r(weight), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels)); - } -} - -pub fn convInputsForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, is_tree: bool) void { - const lp = m.weight_plan.at(v.layer); - const w = &m.weights.layers[v.layer]; - const k_taps = stageConvInput(m, e, cache, v.cache_slot, 0, at(s.k_raw, 0), base, rows); - const v_taps = stageConvInput(m, e, cache, v.cache_slot, 1, at(s.v_raw, 0), base, rows); - const k_out = at(s.k_conv, base * state.kv_width * 2); - const v_out = at(s.v_conv, base * state.kv_width * 2); - const k_in = at(s.k_norm, base * state.hidden * 2); - const v_norm = if (v.hasMessages() or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); - const v_in = at(v_norm.buf, v_norm.off + base * state.hidden * 2); - if (is_tree) { - const src = at(s.conv_src, base * 4 * 4); - switch (w.attn.k_conv) { - .static => |kw| tree.convStatic(&m.tree, e, k_taps, r(kw), src, k_out, @intCast(rows), state.kv_width), - .dynamic => |kd| tree.convDynamic(&m.tree, e, k_taps, k_in, r(kd.static_w), r(kd.projection), src, k_out, @intCast(rows), state.kv_width), - } - switch (w.attn.v_conv) { - .static => |vw| tree.convStatic(&m.tree, e, v_taps, r(vw), src, v_out, @intCast(rows), state.kv_width), - .dynamic => |vd| tree.convDynamic(&m.tree, e, v_taps, v_in, r(vd.static_w), r(vd.projection), src, v_out, @intCast(rows), state.kv_width), - } - return; - } - switch (w.attn.k_conv) { - .static => |kw| switch (w.attn.v_conv) { - .static => |vw| glue.convStaticKv(&m.glue, e, k_taps, r(kw), k_out, v_taps, r(vw), v_out, @intCast(rows), state.kv_width), - .dynamic => |vd| { - glue.convStatic(&m.glue, e, k_taps, r(kw), k_out, @intCast(rows), state.kv_width); - glue.convDynamic(&m.glue, e, v_taps, v_in, r(vd.static_w), r(vd.projection), v_out, @intCast(rows), state.kv_width); - }, - }, - .dynamic => |kd| switch (w.attn.v_conv) { - .dynamic => |vd| glue.convDynamicKv(&m.glue, e, k_taps, k_in, r(kd.static_w), r(kd.projection), k_out, v_taps, v_in, r(vd.static_w), r(vd.projection), v_out, @intCast(rows), state.kv_width), - .static => |vw| { - glue.convDynamic(&m.glue, e, k_taps, k_in, r(kd.static_w), r(kd.projection), k_out, @intCast(rows), state.kv_width); - glue.convStatic(&m.glue, e, v_taps, r(vw), v_out, @intCast(rows), state.kv_width); - }, - }, - } -} - -pub fn routedExperts(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, layer: usize, rows: usize) !void { - const w = &m.weights.layers[layer]; - const lp = m.weight_plan.at(@intCast(layer)).precision; - const down_call = experts.Call{ .rows = @intCast(rows), .k = state.intermediate, .n = state.hidden, .format = if (lp == .mxfp8) .mxfp8 else .nvfp4 }; - _ = explain.reportExpert(lp, rows, m.experts.mma != null); - if (lp == .tfq5) { - try m.dispatchTfq5Moe(e, w.tfq5 orelse return error.Tfq5NotLoaded, s.mlp_normed, s.route_ids, s.gu, s.down, rows); - return experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); - } - if (lp == .tfq3) { - const pipes = if (m.tfq3_pipes) |*p| p else return error.Tfq3NotLoaded; - try pipes.dispatch(e, w.tfq3 orelse return error.Tfq3NotLoaded, at(s.mlp_normed, 0), at(s.route_ids, 0), at(s.gu, 0), at(s.down, 0), rows); - return experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); - } - const precision: experts.Format = if (lp == .nvfp4) .nvfp4 else if (lp == .mxfp8) .mxfp8 else return error.UnsupportedInkling2ExpertFormat; - const gu_call = experts.Call{ .rows = @intCast(rows), .k = state.hidden, .n = state.intermediate, .format = precision }; - if (m.experts.mma != null and rows >= experts.mma_rows) { - // A row's sums are the same on either path, so a chunk or window takes the one that fits its width. - const nv = precision == .nvfp4; - const gu_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) } else null; - const down_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.down.amax.?)), .denominator = x(r(w.down.denominator.?)) } else null; - try experts.group(&m.experts, e, x(at(s.route_ids, 0)), gu_call); - try experts.mma(&m.experts, e, false, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), gu_globals, x(at(s.gu, 0)), gu_call); - try experts.mma(&m.experts, e, true, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), down_globals, x(at(s.down, 0)), down_call); - } else if (rows >= 2) { - var row0: usize = 0; - while (row0 < rows) { - const take: usize = @min(rows - row0, experts.max_grouped_rows); - const chunk_gu = experts.Call{ .rows = @intCast(take), .k = state.hidden, .n = state.intermediate, .format = precision }; - const chunk_down = experts.Call{ .rows = @intCast(take), .k = state.intermediate, .n = state.hidden, .format = precision }; - const x_in = x(row(s.mlp_normed, row0, state.hidden * 2)); - const ids_in = x(row(s.route_ids, row0, state.experts_per_token * 4)); - const gu_out = x(row(s.gu, row0, state.experts_per_token * state.intermediate * 2)); - const down_out = x(row(s.down, row0, state.experts_per_token * state.hidden * 2)); - try experts.groupBuckets(&m.experts, e, ids_in, x(at(s.expert_group, 0)), chunk_gu); - if (precision == .nvfp4) { - try experts.guGrouped(&m.experts, e, x_in, x(r(w.gu.weight)), x(r(w.gu.scale)), .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) }, x(at(s.expert_group, 0)), gu_out, chunk_gu); - try experts.nvfp4DownGrouped(&m.experts, e, gu_out, x(r(w.down.weight)), x(r(w.down.scale)), x(r(w.down.amax.?)), x(r(w.down.denominator.?)), x(at(s.expert_group, 0)), down_out, chunk_down); - } else { - try experts.guGrouped(&m.experts, e, x_in, x(r(w.gu.weight)), x(r(w.gu.scale)), null, x(at(s.expert_group, 0)), gu_out, chunk_gu); - try experts.mxfp8DownGrouped(&m.experts, e, gu_out, x(r(w.down.weight)), x(r(w.down.scale)), x(at(s.expert_group, 0)), down_out, chunk_down); - } - row0 += take; - } - } else { - try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), if (precision == .nvfp4) .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) } else null, x(at(s.route_ids, 0)), x(at(s.gu, 0)), gu_call); - switch (precision) { - .nvfp4 => try experts.nvfp4Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(r(w.down.amax.?)), x(r(w.down.denominator.?)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), - .mxfp8 => try experts.mxfp8Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), - } - } - try experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); -} - fn commitFullHistories(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: []const Segment, meta: []const SegMeta) void { _ = s; if (fusedConv(segments, meta)) { @@ -442,13 +313,15 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, p.completed(.cache, 0, cb.gpuSeconds() * 1e3); } } - var e: mtl.ComputeEncoder = if (trace == null) cb.compute(.serial) else undefined; + var e: mtl.ComputeEncoder = if (trace == null) cb.compute(.concurrent) else undefined; var scope = prof.begin(trace, e, .embedding, 0); errdefer scope.cancel(); e = scope.encoder; if (use_fused_conv) conv.declareConvResources(e, s, segments); glue.embedNorm(&m.glue, e, options.ids orelse at(s.ids, 0), r(m.weights.embed), r(m.weights.embed_norm), at(s.p, 0), @intCast(rows)); + e.barrier(); for (options.images) |im| copyBf16(m, e, at(im.buf, im.off), at(s.p, im.row * state.hidden * 2), im.rows * state.hidden); + e.barrier(); for (visits, 0..) |*v, vi| { const prev_fused = vi > 0 and canPreFuse(v); const prev_fused_norm = vi > 0 and canPreFuseNorm(&m.weight_plan, v); @@ -461,6 +334,7 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, const logits = if (options.all) at(s.logits_all, 0) else at(segments[0].cache.logits, 0); if (options.logits) { glue.logits(&m.glue, e, at(s.mlp_normed, final.logits_row * state.hidden * 2), r(m.weights.unembed), logits, @intCast(final.logits_rows), m.config.text.unpadded_vocab); + e.barrier(); try visit_impl.transition(m, s, segments, use_fused_conv, trace, &scope, &e, .sampling, 0); sample.encodeForwardDraw(m, e, s, logits, options.draw, options.draws, m.config.text.unpadded_vocab); } diff --git a/zig/src/families/inkling2/metal/forward_attention.zig b/zig/src/families/inkling2/metal/forward_attention.zig new file mode 100644 index 00000000000..fcf072cdc75 --- /dev/null +++ b/zig/src/families/inkling2/metal/forward_attention.zig @@ -0,0 +1,178 @@ +//! Current attention and convolution routes, staged for independent launches between producer barriers. +const mtl = @import("metal"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const layer_plan = @import("../plan.zig"); +const ap = @import("attention_plan.zig"); +const attention = @import("attention.zig"); +const glue = @import("glue.zig"); +const tree = @import("tree.zig"); +const conv = @import("forward_conv.zig"); +const state = @import("state.zig"); +const Model = @import("model.zig").Model; +const Ref = state.Ref; +const copyBf16 = @import("forward_dispatch.zig").copyBf16; +fn r(t: ck.Tensor) Ref { + return .{ .buf = t.buffer, .off = t.offset }; +} +fn at(buf: mtl.Buffer, off: usize) Ref { + return .{ .buf = buf, .off = off }; +} +fn a(x: Ref) attention.Ref { + return .{ .buf = x.buf, .off = x.off }; +} + +pub fn fusedConv(segments: anytype, meta: anytype) bool { + for (meta) |m| if (m.is_tree) return false; + return segments.len > 1 or segments[0].rows <= state.window_rows; +} + +pub fn postConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: anytype, meta: anytype, slot: usize, cs: usize, raw: Ref, weight: ck.Tensor, out: Ref) void { + if (fusedConv(segments, meta)) return conv.postConv(m, e, s, segments, slot, cs, raw, weight, out); + var base: usize = 0; + for (segments, meta) |seg, sm| { + staticPostConv(m, e, s, seg.cache, slot, cs, raw, weight, out, base, seg.rows, sm.is_tree); + base += seg.rows; + } + e.barrier(); +} + +fn stageConvInput(m: *const Model, e: mtl.ComputeEncoder, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, base: usize, rows: usize) Ref { + const channels = state.convWidth(conv_state); + const taps = cache.staged(slot, conv_state, 0); + copyBf16(m, e, cache.history(slot, conv_state), taps, 3 * channels); + copyBf16(m, e, at(raw.buf, raw.off + base * channels * 2), cache.staged(slot, conv_state, 3), rows * channels); + return taps; +} + +fn staticPostConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, weight: ck.Tensor, out: Ref, base: usize, rows: usize, is_tree: bool) void { + const channels = state.convWidth(conv_state); + const taps = stageConvInput(m, e, cache, slot, conv_state, raw, base, rows); + e.barrier(); + if (is_tree) { + tree.convStatic(&m.tree, e, taps, r(weight), at(s.conv_src, base * 4 * 4), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels)); + } else { + glue.convStatic(&m.glue, e, taps, r(weight), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels)); + } +} +pub fn convInputsForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, is_tree: bool) void { + const lp = m.weight_plan.at(v.layer); + const w = &m.weights.layers[v.layer]; + const k_taps = stageConvInput(m, e, cache, v.cache_slot, 0, at(s.k_raw, 0), base, rows); + const v_taps = stageConvInput(m, e, cache, v.cache_slot, 1, at(s.v_raw, 0), base, rows); + e.barrier(); + const k_out = at(s.k_conv, base * state.kv_width * 2); + const v_out = at(s.v_conv, base * state.kv_width * 2); + const k_in = at(s.k_norm, base * state.hidden * 2); + const v_norm = if (v.hasMessages() or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); + const v_in = at(v_norm.buf, v_norm.off + base * state.hidden * 2); + if (is_tree) { + const src = at(s.conv_src, base * 4 * 4); + switch (w.attn.k_conv) { + .static => |kw| tree.convStatic(&m.tree, e, k_taps, r(kw), src, k_out, @intCast(rows), state.kv_width), + .dynamic => |kd| tree.convDynamic(&m.tree, e, k_taps, k_in, r(kd.static_w), r(kd.projection), src, k_out, @intCast(rows), state.kv_width), + } + switch (w.attn.v_conv) { + .static => |vw| tree.convStatic(&m.tree, e, v_taps, r(vw), src, v_out, @intCast(rows), state.kv_width), + .dynamic => |vd| tree.convDynamic(&m.tree, e, v_taps, v_in, r(vd.static_w), r(vd.projection), src, v_out, @intCast(rows), state.kv_width), + } + return; + } + switch (w.attn.k_conv) { + .static => |kw| switch (w.attn.v_conv) { + .static => |vw| glue.convStaticKv(&m.glue, e, k_taps, r(kw), k_out, v_taps, r(vw), v_out, @intCast(rows), state.kv_width), + .dynamic => |vd| { + glue.convStatic(&m.glue, e, k_taps, r(kw), k_out, @intCast(rows), state.kv_width); + glue.convDynamic(&m.glue, e, v_taps, v_in, r(vd.static_w), r(vd.projection), v_out, @intCast(rows), state.kv_width); + }, + }, + .dynamic => |kd| switch (w.attn.v_conv) { + .dynamic => |vd| glue.convDynamicKv(&m.glue, e, k_taps, k_in, r(kd.static_w), r(kd.projection), k_out, v_taps, v_in, r(vd.static_w), r(vd.projection), v_out, @intCast(rows), state.kv_width), + .static => |vw| { + glue.convDynamic(&m.glue, e, k_taps, k_in, r(kd.static_w), r(kd.projection), k_out, @intCast(rows), state.kv_width); + glue.convStatic(&m.glue, e, v_taps, r(vw), v_out, @intCast(rows), state.kv_width); + }, + }, + } +} + +pub fn attendEach(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: anytype, seg_meta: anytype, specs: []const ap.BatchedSegSpec, prep_cfg: ap.Prep, proj_ref: attention.Ref, scale_refs: [2]attention.Ref, meta_override: ?attention.RowMeta, decode: bool, original: bool) !void { + var launches: [state.max_segments]ap.Launch = undefined; + var depths: [state.max_segments]bool = @splat(false); // segments main's depth kernel serves whole + var tree_launches: [state.max_segments]ap.TreeLaunch = undefined; + var layers: [state.max_segments]ap.Layer = undefined; + var rrs: [state.max_segments]ap.Rows = undefined; + var strides: [state.max_segments]usize = undefined; + var metas: [state.max_segments]attention.RowMeta = undefined; + var kvs: [state.max_segments]attention.Cache = undefined; + var bases: [state.max_segments]usize = undefined; + var starts: [state.max_segments]u32 = undefined; + var base: usize = 0; + for (segments, 0..) |seg, si| { + const rows = seg.rows; + const cache = seg.cache; + const layer0 = cache.attentionLayer(&m.weight_plan, v.cache_slot, rows); + bases[si] = base; + starts[si] = @intCast(cache.len); + layers[si] = .{ .window = layer0.window, .ring = @intCast(cache.ring(v.cache_slot)), .chunk = layer0.chunk, .tau = layer0.tau }; + rrs[si] = .{ .rows = @intCast(rows), .heads = 24, .kv_heads = 8, .last_pos = specs[si].last_pos, .streams = 1 }; + metas[si] = meta_override orelse attention.RowMeta{ + .pos = a(at(s.pos, base * 4)), + .seg_of = a(at(s.seg_of, base * 4)), + .segs = a(at(s.segs, 0)), + .prompt_segs = a(at(s.segs, si * @sizeOf(ap.Seg))), + }; + kvs[si] = .{ .k = a(cache.keys(v.cache_slot)), .v = a(cache.values(v.cache_slot)) }; + base += rows; + } + for (seg_meta, 0..) |sm, si| { + const b = bases[si]; + const raw_refs = [4]attention.Ref{ a(at(s.q_raw, b * state.query_width * 2)), a(at(s.k_conv, b * state.kv_width * 2)), a(at(s.v_conv, b * state.kv_width * 2)), a(at(s.rel_raw, b * state.rel_width * 2)) }; + const q_ref = a(at(s.q_prep, b * state.query_width * 2)); + const rel_ref = a(at(s.rel_prep, b * state.rel_width * 2)); + if (sm.is_tree) { + attention.prepTree(&m.attention, e, rrs[si], layers[si], prep_cfg, metas[si], raw_refs, scale_refs, q_ref, rel_ref, kvs[si]); + } else { + strides[si] = ap.slotsFor(layers[si], @as(usize, specs[si].last_pos) + 1); + if (strides[si] > state.max_attention_stride) return error.Inkling2Partials; + attention.prep(&m.attention, e, rrs[si], layers[si], prep_cfg, metas[si], raw_refs, scale_refs, q_ref, rel_ref, kvs[si]); + } + } + e.barrier(); + var ran_prefix = false; + for (seg_meta, 0..) |sm, si| { + if (!sm.is_tree) continue; + const b = bases[si]; + tree_launches[si] = try ap.attendTree(rrs[si], layers[si], state.max_attention_stride, starts[si]); + @import("explain.zig").reportTree(tree_launches[si], rrs[si].rows); // main's TF_EXPLAIN line, as attendTree reports + if (attention.treePrefix(&m.attention, e, tree_launches[si], rrs[si], layers[si], metas[si], a(at(s.q_prep, b * state.query_width * 2)), kvs[si], a(at(s.rel_prep, b * state.rel_width * 2)), proj_ref, a(at(s.part_o, b * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, b * 24 * state.max_attention_stride * 8)), a(at(s.tree_tail_o, b * 2 * 24 * ap.head_dim * 4)), a(at(s.tree_tail_ml, b * 24 * 16)))) { + ran_prefix = true; + } + } + if (ran_prefix) e.barrier(); + for (seg_meta, 0..) |sm, si| { + const b = bases[si]; + const q_ref = a(at(s.q_prep, b * state.query_width * 2)); + const rel_ref = a(at(s.rel_prep, b * state.rel_width * 2)); + const po_ref = a(at(s.part_o, b * 24 * state.max_attention_stride * ap.head_dim * 4)); + const pml_ref = a(at(s.part_ml, b * 24 * state.max_attention_stride * 8)); + if (sm.is_tree) { + attention.treePartials(&m.attention, e, tree_launches[si], rrs[si], layers[si], metas[si], a(at(s.tree_paths, b * state.window_rows * 4)), a(at(s.tree_tail_o, b * 2 * 24 * ap.head_dim * 4)), a(at(s.tree_tail_ml, b * 24 * 16)), q_ref, kvs[si], rel_ref, proj_ref, po_ref, pml_ref); + } else { + const sink_ref = a(at(s.sink, b * 24 * 2)); + const gate_ref = a(at(s.gate, b * state.query_width * 2)); + const att_ref = a(at(s.att, b * state.query_width * 2)); + // main's depth path, as attendSegments takes it: raw states, fold and merge in one call, so no merge below + depths[si] = attention.attendDepth(&m.attention, e, .{ .decode = decode, .pending_rows = segments[si].cache.pending, .original = original, .segments = segments.len }, rrs[si], layers[si], @intCast(strides[si]), s.depthStride(segments[si].cache.capacity), metas[si], q_ref, kvs[si], rel_ref, proj_ref, po_ref, pml_ref, sink_ref, gate_ref, att_ref); + if (!depths[si]) launches[si] = try attention.partialsReusable(&m.attention, e, rrs[si], layers[si], @intCast(strides[si]), 0, metas[si], q_ref, kvs[si], rel_ref, proj_ref, po_ref, pml_ref, m.relbias_min, segments.len, false, decode, a(at(s.rel_bias, 0))); + } + } + e.barrier(); + for (seg_meta, 0..) |sm, si| { + if (depths[si]) continue; + const b = bases[si]; + const partials_rh = if (sm.is_tree) tree_launches[si].partials_rh else launches[si].partials_rh; + const subs = if (sm.is_tree) @as(u32, 1) else launches[si].subs; + attention.mergeRaw(&m.attention, e, rrs[si], layers[si], partials_rh, subs, metas[si], a(at(s.part_o, b * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, b * 24 * state.max_attention_stride * 8)), a(at(s.sink, b * 24 * 2)), a(at(s.gate, b * state.query_width * 2)), a(at(s.att, b * state.query_width * 2))); + } + e.barrier(); +} diff --git a/zig/src/families/inkling2/metal/forward_conv.zig b/zig/src/families/inkling2/metal/forward_conv.zig index 4653def1356..6e5e2b7d649 100644 --- a/zig/src/families/inkling2/metal/forward_conv.zig +++ b/zig/src/families/inkling2/metal/forward_conv.zig @@ -153,6 +153,7 @@ pub fn fusedAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, stageConvStatic(m, e, segs_ref, r(w.attn.k_conv.static), r(w.attn.v_conv.static), segments.len, state.kv_width, 2); } else { stageConvSegs(m, e, segs_ref, segments.len, state.kv_width, 2); + e.barrier(); if (w.attn.k_conv == .dynamic and w.attn.v_conv == .dynamic) { var total: usize = 0; for (segments) |seg| total += seg.rows; diff --git a/zig/src/families/inkling2/metal/forward_dispatch.zig b/zig/src/families/inkling2/metal/forward_dispatch.zig new file mode 100644 index 00000000000..9e0c00083da --- /dev/null +++ b/zig/src/families/inkling2/metal/forward_dispatch.zig @@ -0,0 +1,18 @@ +//! Existing runtime and BF16-copy encoders shared by the forward's extracted scheduling helpers. +const mtl = @import("metal"); +const state = @import("state.zig"); +const model_file = @import("model.zig"); +const Model = model_file.Model; +const Ref = state.Ref; +const RArgs = extern struct { count: u32, boundary: u32 = 0 }; + +pub fn runtime(m: *const Model, e: mtl.ComputeEncoder, op: model_file.RuntimeOp, refs: []const Ref, count: usize, boundary: usize) void { + e.setPipeline(m.runtime[@backingInt(op)]); + for (refs, 0..) |r_, i| e.setBuffer(r_.buf, r_.off, i); + e.setValue(RArgs{ .count = @intCast(count), .boundary = @intCast(boundary) }, refs.len); + e.dispatchThreads(mtl.Size.of(count, 1, 1), mtl.Size.of(256, 1, 1)); +} + +pub fn copyBf16(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, count: usize) void { + runtime(m, e, .copy_bf16, &.{ from, to }, count, 0); +} diff --git a/zig/src/families/inkling2/metal/forward_experts.zig b/zig/src/families/inkling2/metal/forward_experts.zig new file mode 100644 index 00000000000..5cb2af31ff2 --- /dev/null +++ b/zig/src/families/inkling2/metal/forward_experts.zig @@ -0,0 +1,92 @@ +//! Mini's routed experts for one visit: the experts' launches in turn, a barrier after each step a later launch reads. +const mtl = @import("metal"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const experts = @import("experts.zig"); +const state = @import("state.zig"); +const Model = @import("model.zig").Model; + +const Ref = state.Ref; + +fn r(t: ck.Tensor) Ref { + return .{ .buf = t.buffer, .off = t.offset }; +} +fn at(buf: mtl.Buffer, off: usize) Ref { + return .{ .buf = buf, .off = off }; +} +fn row(buf: mtl.Buffer, i: usize, row_bytes: usize) Ref { + return at(buf, i * row_bytes); +} +fn x(x_: Ref) experts.Ref { + return .{ .buf = x_.buf, .off = x_.off }; +} + +/// Ends with a barrier: the combine's output is written. +pub fn routed(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, layer: usize, rows: usize) !void { + const w = &m.weights.layers[layer]; + const lp = m.weight_plan.at(@intCast(layer)).precision; + const down_call = experts.Call{ .rows = @intCast(rows), .k = state.intermediate, .n = state.hidden, .format = if (lp == .mxfp8) .mxfp8 else .nvfp4 }; + _ = @import("explain.zig").reportExpert(lp, rows, m.experts.mma != null); // main's TF_EXPLAIN line + if (lp == .tfq5) { + try m.dispatchTfq5Moe(e, w.tfq5 orelse return error.Tfq5NotLoaded, s.mlp_normed, s.route_ids, s.gu, s.down, rows); + e.barrier(); + try experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); + e.barrier(); + return; + } + if (lp == .tfq3) { + const pipes = if (m.tfq3_pipes) |*p| p else return error.Tfq3NotLoaded; + try pipes.dispatch(e, w.tfq3 orelse return error.Tfq3NotLoaded, at(s.mlp_normed, 0), at(s.route_ids, 0), at(s.gu, 0), at(s.down, 0), rows); + e.barrier(); + try experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); + e.barrier(); + return; + } + const precision: experts.Format = if (lp == .nvfp4) .nvfp4 else if (lp == .mxfp8) .mxfp8 else return error.UnsupportedInkling2ExpertFormat; + const gu_call = experts.Call{ .rows = @intCast(rows), .k = state.hidden, .n = state.intermediate, .format = precision }; + if (m.experts.mma != null and rows >= experts.mma_rows) { + // A row's sums are the same on either path, so a chunk or window takes the one that fits its width. + const nv = precision == .nvfp4; + const gu_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) } else null; + const down_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.down.amax.?)), .denominator = x(r(w.down.denominator.?)) } else null; + try experts.group(&m.experts, e, x(at(s.route_ids, 0)), gu_call); + e.barrier(); + try experts.mma(&m.experts, e, false, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), gu_globals, x(at(s.gu, 0)), gu_call); + e.barrier(); + try experts.mma(&m.experts, e, true, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), down_globals, x(at(s.down, 0)), down_call); + } else if (rows >= 2) { + var row0: usize = 0; + while (row0 < rows) { + const take: usize = @min(rows - row0, experts.max_grouped_rows); + const chunk_gu = experts.Call{ .rows = @intCast(take), .k = state.hidden, .n = state.intermediate, .format = precision }; + const chunk_down = experts.Call{ .rows = @intCast(take), .k = state.intermediate, .n = state.hidden, .format = precision }; + const x_in = x(row(s.mlp_normed, row0, state.hidden * 2)); + const ids_in = x(row(s.route_ids, row0, state.experts_per_token * 4)); + const gu_out = x(row(s.gu, row0, state.experts_per_token * state.intermediate * 2)); + const down_out = x(row(s.down, row0, state.experts_per_token * state.hidden * 2)); + // The chunks share the bucket table: each chunk's steps run in turn. + if (row0 > 0) e.barrier(); + try experts.groupBuckets(&m.experts, e, ids_in, x(at(s.expert_group, 0)), chunk_gu); + e.barrier(); + if (precision == .nvfp4) { + try experts.guGrouped(&m.experts, e, x_in, x(r(w.gu.weight)), x(r(w.gu.scale)), .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) }, x(at(s.expert_group, 0)), gu_out, chunk_gu); + e.barrier(); + try experts.nvfp4DownGrouped(&m.experts, e, gu_out, x(r(w.down.weight)), x(r(w.down.scale)), x(r(w.down.amax.?)), x(r(w.down.denominator.?)), x(at(s.expert_group, 0)), down_out, chunk_down); + } else { + try experts.guGrouped(&m.experts, e, x_in, x(r(w.gu.weight)), x(r(w.gu.scale)), null, x(at(s.expert_group, 0)), gu_out, chunk_gu); + e.barrier(); + try experts.mxfp8DownGrouped(&m.experts, e, gu_out, x(r(w.down.weight)), x(r(w.down.scale)), x(at(s.expert_group, 0)), down_out, chunk_down); + } + row0 += take; + } + } else { + try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), if (precision == .nvfp4) .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) } else null, x(at(s.route_ids, 0)), x(at(s.gu, 0)), gu_call); + e.barrier(); + switch (precision) { + .nvfp4 => try experts.nvfp4Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(r(w.down.amax.?)), x(r(w.down.denominator.?)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), + .mxfp8 => try experts.mxfp8Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), + } + } + e.barrier(); + try experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); + e.barrier(); +} diff --git a/zig/src/families/inkling2/metal/forward_visit.zig b/zig/src/families/inkling2/metal/forward_visit.zig index 2f53b56f2e7..aa579c5bc2b 100644 --- a/zig/src/families/inkling2/metal/forward_visit.zig +++ b/zig/src/families/inkling2/metal/forward_visit.zig @@ -31,7 +31,7 @@ const bankAndReset = f.bankAndReset; const prepareAttentionInputs = f.prepareAttentionInputs; const postConv = f.postConv; const convInputsForAttention = f.convInputsForAttention; -const routedExperts = f.routedExperts; +const routedExperts = @import("forward_experts.zig").routed; const fusedConv = f.fusedConv; const canPreFuse = f.canPreFuse; const canPreFuseNorm = f.canPreFuseNorm; @@ -51,7 +51,7 @@ fn attendSegments(m: *const Model, e: *mtl.ComputeEncoder, s: *state.Scratch, v: if (fused) { try transition(m, s, segments, fused, trace, scope, e, .conv, visit_index); conv.fusedAttention(m, e.*, s, v, segments); - try transition(m, s, segments, fused, trace, scope, e, .attention, visit_index); + e.barrier(); } const prep = ap.Prep{ .qk_clip = m.config.text.qk_clip, .rel_clip = m.config.text.rel_clip, .floor = @floatFromInt(m.config.text.log_floor), .alpha = m.config.text.log_alpha, .eps = m.config.text.eps }; const proj_ref = a(r(m.weights.layers[v.layer].attn.rel_projection)); @@ -79,6 +79,7 @@ fn attendSegments(m: *const Model, e: *mtl.ComputeEncoder, s: *state.Scratch, v: }; base += seg.rows; } + e.barrier(); try transition(m, s, segments, fused, trace, scope, e, .attention, visit_index); const rr = ap.Rows{ .rows = batch.total_rows, .heads = 24, .kv_heads = 8, .last_pos = 0, .streams = @intCast(segments.len) }; const raw_refs = [4]attention.Ref{ a(at(s.q_raw, 0)), a(at(s.k_conv, 0)), a(at(s.v_conv, 0)), a(at(s.rel_raw, 0)) }; @@ -87,47 +88,19 @@ fn attendSegments(m: *const Model, e: *mtl.ComputeEncoder, s: *state.Scratch, v: try attention.attendBatched(&m.attention, e.*, batch, 24, 8, a(at(s.pos, 0)), a(at(s.seg_of, 0)), caches[0..segments.len], a(at(s.q_prep, 0)), a(at(s.rel_prep, 0)), proj_ref, a(at(s.part_o, 0)), a(at(s.part_ml, 0)), a(at(s.sink, 0)), a(at(s.gate, 0)), a(at(s.att, 0))); return; } - var base: usize = 0; - for (segments, seg_meta, 0..) |seg, sm, si| { - const rows = seg.rows; - const cache = seg.cache; - const layer = specs[si].layer; - const start = cache.len; - const last_pos = specs[si].last_pos; - const rr = ap.Rows{ .rows = @intCast(rows), .heads = 24, .kv_heads = 8, .last_pos = last_pos, .streams = 1 }; - const meta = meta_override orelse attention.RowMeta{ - .pos = a(at(s.pos, base * 4)), - .seg_of = a(at(s.seg_of, base * 4)), - .segs = a(at(s.segs, 0)), - .prompt_segs = a(at(s.segs, si * @sizeOf(ap.Seg))), - }; - const kv = attention.Cache{ .k = a(cache.keys(v.cache_slot)), .v = a(cache.values(v.cache_slot)) }; - if (!fused) { - try transition(m, s, segments, fused, trace, scope, e, .conv, visit_index); - convInputsForAttention(m, e.*, s, cache, v, base, rows, sm.is_tree); - } - try transition(m, s, segments, fused, trace, scope, e, .attention, visit_index); - const rel_ref = a(at(s.rel_prep, base * state.rel_width * 2)); - const q_ref = a(at(s.q_prep, base * state.query_width * 2)); - const po_ref = a(at(s.part_o, base * 24 * state.max_attention_stride * ap.head_dim * 4)); - const pml_ref = a(at(s.part_ml, base * 24 * state.max_attention_stride * 8)); - const sink_ref = a(at(s.sink, base * 24 * 2)); - const gate_ref = a(at(s.gate, base * state.query_width * 2)); - const att_ref = a(at(s.att, base * state.query_width * 2)); - const raw_refs = [4]attention.Ref{ 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)) }; - if (sm.is_tree) { - attention.prepTree(&m.attention, e.*, rr, layer, prep, meta, raw_refs, scale_refs, q_ref, rel_ref, kv); - try attention.attendTree(&m.attention, e.*, rr, layer, state.max_attention_stride, @intCast(start), meta, a(at(s.tree_paths, base * state.window_rows * 4)), a(at(s.tree_tail_o, base * 2 * 24 * ap.head_dim * 4)), a(at(s.tree_tail_ml, base * 24 * 16)), q_ref, kv, rel_ref, proj_ref, po_ref, pml_ref, sink_ref, gate_ref, att_ref); - } else { - const stride = ap.slotsFor(layer, @as(usize, last_pos) + 1); - if (stride > state.max_attention_stride) return error.Inkling2Partials; - attention.prep(&m.attention, e.*, rr, layer, prep, meta, raw_refs, scale_refs, q_ref, rel_ref, kv); - const depth = attention.attendDepth(&m.attention, e.*, .{ .decode = decode, .pending_rows = cache.pending, .original = original, .segments = segments.len }, rr, layer, stride, s.depthStride(cache.capacity), meta, q_ref, kv, rel_ref, proj_ref, po_ref, pml_ref, sink_ref, gate_ref, att_ref); - if (!depth) try attention.attendReusable(&m.attention, e.*, rr, layer, stride, 0, meta, q_ref, kv, rel_ref, proj_ref, po_ref, pml_ref, sink_ref, gate_ref, att_ref, m.relbias_min, segments.len, false, decode, a(at(s.rel_bias, 0))); + if (!fused) { + try transition(m, s, segments, fused, trace, scope, e, .conv, visit_index); + var base: usize = 0; + for (segments, seg_meta) |seg, sm| { + convInputsForAttention(m, e.*, s, seg.cache, v, base, seg.rows, sm.is_tree); + base += seg.rows; } - base += rows; + e.barrier(); } + try transition(m, s, segments, fused, trace, scope, e, .attention, visit_index); + try @import("forward_attention.zig").attendEach(m, e.*, s, v, segments, seg_meta, specs[0..segments.len], prep, proj_ref, scale_refs, meta_override, decode, original); } + pub fn visit(m: *const Model, e: *mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, prev_fused: bool, prev_fused_norm: bool, next_v: ?*const layer_plan.Visit, final_rows: usize, segments: []const Segment, seg_meta: []const SegMeta, rows: usize, taps: ?state.Ref, meta_override: ?attention.RowMeta, decode: bool, trace: ?*prof.Profiler, scope: *prof.Profiler.Scope, visit_index: usize) !void { const lp = m.weight_plan.at(v.layer); const fused = fusedConv(segments, seg_meta); @@ -144,12 +117,17 @@ pub fn visit(m: *const Model, e: *mtl.ComputeEncoder, s: *state.Scratch, v: *con if (v.pass > 1 and v.layer == 6) bankAndReset(m, e.*, s, rows); const w = &m.weights.layers[v.layer]; if (v.layer != 0 and !prev_fused) widen(m, e.*, at(s.p, 0), at(s.partial, 0), rows * state.hidden); + e.barrier(); try prepareAttentionInputs(m, e.*, s, v, rows, prev_fused, prev_fused_norm); + e.barrier(); const knorm = if (gated or lp.kind == .global) at(s.k_norm, 0) else at(s.q_norm, 0); const vnorm = if (gated or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); attention_dense.project(m, e.*, w, s, knorm, vnorm, rows, project); + e.barrier(); try attendSegments(m, e, s, v, segments, seg_meta, meta_override, decode, trace, scope, visit_index); + e.barrier(); project(m, e.*, w.attn.wo, at(s.att, 0), at(s.attn_dense, 0), rows); + e.barrier(); try transition(m, s, segments, fused, trace, scope, e, .conv, visit_index); postConv(m, e.*, s, segments, seg_meta, v.cache_slot, 2, at(s.attn_dense, 0), w.attn_conv, at(s.attn_conv, 0)); try transition(m, s, segments, fused, trace, scope, e, .mlp, visit_index); @@ -158,14 +136,18 @@ pub fn visit(m: *const Model, e: *mtl.ComputeEncoder, s: *state.Scratch, v: *con glue.attnPartialAr(&m.glue, e.*, at(s.p, 0), at(s.attn_conv, 0), at(s.blocks, 0), at(s.block_inv_rms, 0), at(s.partial, 0), r(m.weights.mlp_queries[v.layer]), at(s.mlp_ar, 0), @intCast(rows), lp.mlp_sources, boundary); const c = w.controllers.?[3]; const core = v.layer - 6; + e.barrier(); try gates(m, e.*, s, at(s.mlp_ar, 0), messageRow(s, core, 3, 0), c, at(s.mlp_gated, 0), rows); + e.barrier(); norm(m, e.*, at(s.mlp_gated, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); } else glue.attnPartialArNorm(&m.glue, e.*, at(s.p, 0), at(s.attn_conv, 0), at(s.blocks, 0), at(s.block_inv_rms, 0), at(s.partial, 0), r(m.weights.mlp_queries[v.layer]), r(w.mlp_norm), at(s.mlp_normed, 0), @intCast(rows), lp.mlp_sources, boundary); + e.barrier(); try transition(m, s, segments, fused, trace, scope, e, .router, visit_index); if (loop.plan.splitRows(rows)) glue.routerSplit(&m.glue, e.*, at(s.mlp_normed, 0), r(w.router_weight), r(w.router_bias), at(s.route_scores, 0), at(s.route_ids, 0), at(s.route_weights, 0), @intCast(rows)) else glue.router(&m.glue, e.*, at(s.mlp_normed, 0), r(w.router_weight), r(w.router_bias), at(s.route_ids, 0), at(s.route_weights, 0), @intCast(rows)); + e.barrier(); try transition(m, s, segments, fused, trace, scope, e, .mlp, visit_index); try routedExperts(m, e.*, s, v.layer, rows); try transition(m, s, segments, fused, trace, scope, e, .conv, visit_index); @@ -181,7 +163,10 @@ pub fn visit(m: *const Model, e: *mtl.ComputeEncoder, s: *state.Scratch, v: *con } else { runtime(m, e.*, .mlp_partial, &.{ at(s.partial, 0), at(s.mlp_conv, 0), at(s.p, 0) }, rows * state.hidden, 0); } - if (v.cache_slot == 5) copyBf16(m, e.*, at(s.p, 0), at(s.prelude, 0), rows * state.hidden); + if (v.cache_slot == 5) { + e.barrier(); + copyBf16(m, e.*, at(s.p, 0), at(s.prelude, 0), rows * state.hidden); + } } else if (final_rows == rows) { try transition(m, s, segments, fused, trace, scope, e, .norm, visit_index); glue.mlpPartialArNorm(&m.glue, e.*, at(s.partial, 0), at(s.mlp_conv, 0), at(s.blocks, 0), at(s.block_inv_rms, 0), r(m.weights.output_query), r(m.weights.norm), at(s.p, 0), at(s.partial, 0), at(s.mlp_normed, 0), @intCast(rows), m.weight_plan.final_sources); @@ -192,4 +177,5 @@ pub fn visit(m: *const Model, e: *mtl.ComputeEncoder, s: *state.Scratch, v: *con try transition(m, s, segments, fused, trace, scope, e, .norm, visit_index); glue.mlpPartialArNorm(&m.glue, e.*, row(s.partial, last, state.hidden * 4), row(s.mlp_conv, last, state.hidden * 2), at(s.blocks, last * state.block_slots * state.hidden * 2), at(s.block_inv_rms, last * state.block_slots * 4), r(m.weights.output_query), r(m.weights.norm), row(s.p, last, state.hidden * 2), row(s.partial, last, state.hidden * 4), at(s.mlp_normed, 0), 1, m.weight_plan.final_sources); } + e.barrier(); } diff --git a/zig/src/families/inkling2/metal/glue.zig b/zig/src/families/inkling2/metal/glue.zig index 8120430df43..942cfb215d8 100644 --- a/zig/src/families/inkling2/metal/glue.zig +++ b/zig/src/families/inkling2/metal/glue.zig @@ -318,6 +318,7 @@ pub fn routerSplit(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, weight: R inline for (.{ x, weight, scores }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); e.setValue(RouteArgs{ .rows = rows }, 3); e.dispatchGroups(mtl.Size.of(experts / 32, rows, 1), unit); + e.barrier(); e.setPipeline(p.route_select); inline for (.{ scores, bias, ids, weights }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); e.setValue(RouteArgs{ .rows = rows }, 4); diff --git a/zig/src/families/inkling2/metal/loop.zig b/zig/src/families/inkling2/metal/loop.zig index 64df1f503c1..533b04ce590 100644 --- a/zig/src/families/inkling2/metal/loop.zig +++ b/zig/src/families/inkling2/metal/loop.zig @@ -103,10 +103,12 @@ pub fn gatesSplit(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, m_ bind(e, &.{ h, m, normalized }); e.setValue(args, 3); e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + e.barrier(); e.setPipeline(p.down); bind(e, &.{ normalized, down, zeta }); e.setValue(args, 3); e.dispatchGroups(mtl.Size.of(rank / 32, rows, 1), mtl.Size.of(32, 1, 1)); + e.barrier(); e.setPipeline(p.apply); bind(e, &.{ h, m, zeta, forget, gain, out }); e.setValue(args, 6); diff --git a/zig/src/families/inkling2/metal/tfq3_pipelines.zig b/zig/src/families/inkling2/metal/tfq3_pipelines.zig index 525728b93cb..88646888f3b 100644 --- a/zig/src/families/inkling2/metal/tfq3_pipelines.zig +++ b/zig/src/families/inkling2/metal/tfq3_pipelines.zig @@ -110,6 +110,7 @@ pub const Pipelines = struct { e.setBuffer(p.xrot, 0, 1); e.setValue(a, 2); e.dispatchGroups(mtl.Size.of(layer.hidden / 128, rows, 1), mtl.Size.of(32, 1, 1)); + e.barrier(); if (layer.has_tfq4) { const t4 = layer.tables4 orelse return error.MissingTfq4Tables; @@ -125,6 +126,7 @@ pub const Pipelines = struct { e.setBuffer(act_rot_gu.buf, act_rot_gu.off, 7); e.setValue(a, 8); e.dispatchGroups(mtl.Size.of(layer.inter / 128, slots, 1), mtl.Size.of(256, 1, 1)); + e.barrier(); e.setPipeline(p.moe4_down); e.setBuffer(layer.weights, 0, 0); @@ -151,6 +153,7 @@ pub const Pipelines = struct { e.setBuffer(act_rot_gu.buf, act_rot_gu.off, 6); e.setValue(a, 7); e.dispatchGroups(mtl.Size.of(layer.inter / 128, slots, 1), mtl.Size.of(256, 1, 1)); + e.barrier(); e.setPipeline(p.moe_down); e.setBuffer(layer.weights, 0, 0); diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 8c62805db68..0165dc6936d 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -182,9 +182,9 @@ zig/src/native/qwen27_served.zig 3449bf91a49f4e9d513032a1505ca3f60edd57e4b1a03ca zig/kernels/metal/inkling2/decode_depth.metal 44070decd6bce6652ac3139adcfdb2bfef059c16b055d1945cb14acc4914db7c raw original raw-state arithmetic, ordered 1K/16K folds and original scalar merge; device qualification pending zig/kernels/metal/inkling2/attention_sources.zig 765bc3ddde0c86e5a7763bc7e7ba86c2c6f15ce623ba8a74f40e3be67d7064b1 raw original raw-state arithmetic, ordered 1K/16K folds and original scalar merge; device qualification pending zig/src/families/inkling2/metal/decode_depth.zig 9012bbb3aaf41334fe5ff4d15b10890517e9e22301c5ecbacc09c5cb4942f553 raw original raw-state arithmetic, ordered 1K/16K folds and original scalar merge; device qualification pending; pending single-row verification selects depth without changing fallback decode policy; short one-row depth from 1K keys preserves the original prompt folds; depth borrows counted row partials through the served context with original fold order -zig/src/families/inkling2/metal/attention.zig 96d0dcced91692fb3d2f0daf9fa822b667d79a3cd536794efecc624769c96046 raw original raw-state arithmetic, ordered 1K/16K folds and original scalar merge; device qualification pending; pending single-row verification selects depth without changing fallback decode policy -zig/src/families/inkling2/metal/forward.zig 5aba25b7589c1dfc012711de79418dd2186edb3b17d6bea7fe55b14c7ea56b26 raw original raw-state arithmetic, ordered 1K/16K folds and original scalar merge; device qualification pending; pending single-row verification selects depth without changing fallback decode policy; depth borrows counted row partials through the served context with original fold order; #5693: opt-in queued prompt chunks; main decode and relative-bias paths retained; device equality and timing unrun -zig/src/families/inkling2/metal/forward_visit.zig 4ca4152bf72996fb09b873f889c91bddfe0b415687bd0f8146b991470702494a raw original raw-state arithmetic, ordered 1K/16K folds and original scalar merge; device qualification pending; pending single-row verification selects depth without changing fallback decode policy; depth borrows counted row partials through the served context with original fold order; depth dispatch in profiled visit +zig/src/families/inkling2/metal/attention.zig d5f1197c6c6fc9232d0d8bae92255e8164194247edafc1dd0473cdd41f8b10a5 raw original raw-state arithmetic, ordered 1K/16K folds and original scalar merge; device qualification pending; pending single-row verification selects depth without changing fallback decode policy; #5435 tree prefix and partials as separate calls on a concurrent encoder, the same launches +zig/src/families/inkling2/metal/forward.zig 3c81d2fe83f7eeec64ec9a3c2a2f05dcf090646d6189b4a7bf783ff50876c3b5 raw original raw-state arithmetic, ordered 1K/16K folds and original scalar merge; device qualification pending; pending single-row verification selects depth without changing fallback decode policy; depth borrows counted row partials through the served context with original fold order; #5435 concurrent encoder with a barrier between dependent launches, the same launches +zig/src/families/inkling2/metal/forward_visit.zig 2ead51f8c643f8642fee7668052949da5d961bf16247c8a855f3eceaaea16409 raw original raw-state arithmetic, ordered 1K/16K folds and original scalar merge; device qualification pending; pending single-row verification selects depth without changing fallback decode policy; depth borrows counted row partials through the served context with original fold order; depth dispatch in profiled visit; #5435 visit barriers; segments' attention through forward_attention.attendEach, depth there zig/src/families/inkling2/metal/backend.zig a044a05d061fc524c911208c6a8a47637c26d507433ac69e2f3271da407ca253 raw #5693: opt-in queued prompt chunks; main decode and relative-bias paths retained; device equality and timing unrun; main #6104 (Zig 0.17 dupeSentinel in the profiling-switch test) carried zig/src/families/inkling2/metal/forward_final.zig 51f7d543c16cd18133860dc8ac3c1381a90be52605913005d229c2770e64c1fd raw #5693: opt-in queued prompt chunks; main decode and relative-bias paths retained; device equality and timing unrun zig/src/families/inkling2/metal/prefill_chunks.zig 8767fb1051541768f2ec0420013030d723697b3fa04a63312ec9d61340d5ba69 raw #5693: opt-in queued prompt chunks; main decode and relative-bias paths retained; device equality and timing unrun