Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
51c9ccf
Gemma 4 dense: the 31B's config admission and a token oracle from gil…
BobClawblaw Oct 14, 2026
269e56f
Gemma 4 dense: kernel fixtures from gilby's RowDecode, and the core l…
BobClawblaw Oct 14, 2026
bf4418b
Gemma 4 dense: the decode glue on Metal, bit-equal to gilby's RowDeco…
BobClawblaw Oct 14, 2026
bcf358f
Gemma 4 dense: native greedy decode on Metal, token for token and log…
BobClawblaw Oct 14, 2026
7cf144c
Gemma 4 dense: prompts prefilled in decode windows, the same bits at …
BobClawblaw Oct 14, 2026
f7197de
Gemma 4 dense on the lane core: shared rounds and copy drafts, every …
BobClawblaw Oct 14, 2026
e96fa2d
Gemma 4 31B served natively on Metal: registered as gemma4, served gr…
BobClawblaw Oct 14, 2026
d980d8e
Gemma 4 dense: the reg lane kernel for every projection, the same bit…
BobClawblaw Oct 14, 2026
1832cb0
Gemma 4 dense: prompts in 128-row windows, keys written before attent…
BobClawblaw Oct 14, 2026
3bd3467
tf-gemma4-bench: prompt-window and long-context forwards, and core af…
BobClawblaw Oct 14, 2026
1eacc91
Gemma 4 dense: prompt chunks of 512 rows on core affine_mm, from alig…
BobClawblaw Oct 14, 2026
2efafcc
Gemma 4 dense: prompt attention on the tensor units, the head dim in …
BobClawblaw Oct 14, 2026
41809bf
Gemma 4 dense: the server prefills in 512-row chunks on the tensor-un…
BobClawblaw Oct 14, 2026
42e7e61
tf-gemma4-bench: projections with their group sums given, against the…
BobClawblaw Oct 14, 2026
4e59002
Gemma 4 dense: global layers' decode attention on the tensor units, a…
BobClawblaw Oct 14, 2026
d2bf7bf
Gemma 4 dense: decode scratch sized by 256-key chunks, and long-conte…
BobClawblaw Oct 14, 2026
3e983d9
Gemma 4 dense: decode glue writes the projections' group sums and the…
BobClawblaw Oct 14, 2026
09d40af
Lane core: a target may hand a drafter each prompt chunk's tapped row…
BobClawblaw Oct 15, 2026
819618d
Gemma 4 dense drafts with z-lab's DFlash: 150-190 tokens a second for…
BobClawblaw Oct 15, 2026
abb860c
Gemma 4 drafter: a round's streams in one block forward and one absor…
BobClawblaw Oct 15, 2026
ae4cfdd
Gemma 4: the greedy draw's host fallback switch goes (a getenv a row …
BobClawblaw Oct 15, 2026
0acea2f
Gemma 4 gate: the mlx oracle prefills in 2048-token chunks, and the l…
BobClawblaw Oct 15, 2026
c05ce72
Gemma 4 prompt attention: a simdgroup scores 64 keys over the whole h…
BobClawblaw Oct 15, 2026
9a06f96
Core affine_mm: tile fragments in vector loads, and a step's codes, s…
BobClawblaw Oct 15, 2026
80d1aba
Gemma 4 prompt attention: 32 query rows a threadgroup, a simdgroup sc…
BobClawblaw Oct 15, 2026
127be33
Core affine_mm dequantizes each step's weights to bf16 in its tile, a…
BobClawblaw Oct 15, 2026
b775230
Gemma 4 decode: each shape's fastest K split, and the glue as the pro…
BobClawblaw Oct 15, 2026
31c0410
Gemma 4 decode: a sliding layer's attention kernel preps its own head…
BobClawblaw Oct 15, 2026
64f1895
Core lane kernel: pipelines without a prologue keep main's tile index…
BobClawblaw Oct 15, 2026
9e2afcb
Merge branch 'native-vision' into gemma4-native
BobClawblaw Oct 15, 2026
6d701ac
Gemma 4 startup: a refused drafter, or a failed allocation on the way…
BobClawblaw Oct 15, 2026
0fea59e
The server's image path: an engine names its template's part type, an…
BobClawblaw Oct 15, 2026
8965bbb
Gemma 4 reads images: its 27-layer tower on Metal, bidirectional imag…
BobClawblaw Oct 15, 2026
c530403
Third-party notices: Gemma 4's sources, gilby's RowDecode (#360), MLX…
BobClawblaw Oct 16, 2026
7daa48d
Structured output with DFlash drafts: the Drafted wrapper hands the d…
BobClawblaw Oct 16, 2026
7322cde
Gemma 4's long-lived buffers in one residency set the idle keepalive …
BobClawblaw Oct 16, 2026
d48368c
Gemma 4 docs: structured output with drafts, forced tool calls refuse…
BobClawblaw Oct 16, 2026
c048539
A grammar's read of held fillers leaves them for the verify, so both …
BobClawblaw Oct 16, 2026
0fbb3e2
Gemma 4's image projection is admitted only as u32 words with bf16 sc…
BobClawblaw Oct 16, 2026
5154a1b
Gemma 4's RMS kernel names its source: MLX 0.32's rms_looped (rms_nor…
BobClawblaw Oct 16, 2026
3338988
Merge main (TensorFold 1.0.12) into gemma4-native
BobClawblaw Oct 16, 2026
e8b6054
The kernel contract and tile-check read core affine_mm as it now comp…
BobClawblaw Oct 16, 2026
21e8040
Gemma 4 recipe on 1.0.12: the idle first token held by the residency …
BobClawblaw Oct 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Gemma 4 dense on the lane core: shared rounds and copy drafts, every …
…stream equal to its plain reply

forward.run takes several streams' windows in one forward (q/k/v prep, attention and the cache write per stream at
offsets, every other kernel over all rows); backend.zig puts it behind the lanes Backend, windows up to 16 rows,
keep rolling a cache back by its length. tf-gemma4-lanes: plain and copy-drafted single streams and 4- and 8-stream
shared rounds equal the oracle's 128 tokens; on copy-heavy prompts (11.1 and 3.3 tokens a round, drafts landing and
rolled back) one stream and 8 mixed streams equal the engine's own plain replies.
  • Loading branch information
BobClawblaw committed Oct 14, 2026
commit f7197de77cd2a94fe7ff4e9659a663fa3d1ae770
1 change: 1 addition & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,7 @@ fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b
.{ .name = "tf-gemma4-kernels", .path = "zig/tests/gemma4/kernels.zig", .about = "Gemma 4 dense decode kernels against gemma4_dump.py's fixtures, bit for bit by window width" },
.{ .name = "tf-gemma4-glue", .path = "zig/tests/gemma4/glue.zig", .about = "Gemma 4 dense glue kernels against gemma4_dump.py's fixtures: embed, norm, q/k/v, attention, tails, softcap" },
.{ .name = "tf-gemma4-run", .path = "zig/tests/gemma4/run.zig", .about = "Gemma 4 dense greedy decode, tokens and top-two margins for gemma4_gate.py check" },
.{ .name = "tf-gemma4-lanes", .path = "zig/tests/gemma4/lanes.zig", .about = "Gemma 4 dense on the lane core: plain, copy-drafted and shared-round streams against the oracle's tokens" },
.{ .name = "tf-qwen36-row-seam", .path = "zig/tests/qwen36_row_seam.zig", .about = "Model-free fixture: the row projection's bias sums stay fp32 at every width" },
};
for (engine_programs) |p| {
Expand Down
169 changes: 169 additions & 0 deletions zig/src/families/gemma4/backend.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
//! Gemma 4 dense behind the lane engine's backend: windows of up to 16 rows, several streams a forward, copy drafts.
const std = @import("std");
const lanes = @import("lanes");
const cfg = @import("config.zig");
const st = @import("state.zig");
const fwd = @import("forward.zig");
const Model = @import("model.zig").Model;
const draw = @import("../qwen3_5/backend.zig").draw;
const be = lanes.backend;

pub const Options = struct { capacity: usize, streams: u32 = 8 };

pub const Metal = struct {
gpa: std.mem.Allocator,
model: *Model,
options: Options,
scratch: st.Scratch,
caches: std.AutoHashMapUnmanaged(*lanes.Stream, *st.Cache) = .empty,

pub fn init(gpa: std.mem.Allocator, model: *Model, options: Options) !*Metal {
const out = try gpa.create(Metal);
errdefer gpa.destroy(out);
out.* = .{ .gpa = gpa, .model = model, .options = options, .scratch = try st.Scratch.init(model.device, options.capacity) };
return out;
}

pub fn deinit(self: *Metal) void {
var it = self.caches.valueIterator();
while (it.next()) |cache| {
cache.*.deinit();
self.gpa.destroy(cache.*);
}
self.caches.deinit(self.gpa);
self.scratch.deinit();
self.gpa.destroy(self);
}

/// Every kernel keeps a row's bits at any window width and beside any other stream's rows (tf-gemma4-glue).
pub fn facts(self: *const Metal) lanes.Model {
return .{ .exact_width = st.max_rows, .hidden_rows = true, .batch_rows = st.max_rows, .max_streams = self.options.streams, .streams_exact = true };
}

pub fn backend(self: *Metal) be.Backend {
return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn } };
}

fn cast(ptr: *anyopaque) *Metal {
return @ptrCast(@alignCast(ptr));
}

fn cacheOf(self: *Metal, stream: *lanes.Stream) !*st.Cache {
return self.caches.get(stream) orelse error.UnknownGemmaStream;
}

/// The last row of the scratch logits into the stream's cache.
fn keepLast(self: *Metal, cache: *st.Cache, row: usize) void {
@memcpy(cache.logits.slice(u16, cfg.vocab), self.scratch.logits.slice(u16, st.max_rows * cfg.vocab)[row * cfg.vocab ..][0..cfg.vocab]);
}

fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void {
const self = cast(ptr);
const ids = stream.prompt();
if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidGemmaPrompt;
const cache = try self.gpa.create(st.Cache);
errdefer self.gpa.destroy(cache);
const capacity = @min(self.options.capacity, (ids.len + stream.max_new + st.max_rows + 63) / 64 * 64);
cache.* = try st.Cache.init(self.model.device, capacity);
errdefer cache.deinit();
var at: usize = 0;
while (at < ids.len) {
const end = @min(ids.len, at + st.max_rows);
try fwd.run(self.model, &self.scratch, &.{.{ .cache = cache, .rows = end - at }}, ids[at..end]);
at = end;
}
self.keepLast(cache, (ids.len - 1) % st.max_rows);
try self.caches.put(self.gpa, stream, cache);
}

fn firstFn(ptr: *anyopaque, stream: *lanes.Stream, position: u64) !u64 {
const self = cast(ptr);
const cache = try self.cacheOf(stream);
if (position != cache.len) return error.InvalidGemmaPosition;
return try draw(self.gpa, cache.logits.slice(u16, cfg.vocab), stream.sampling, position, &.{});
}

fn firstMaskedFn(ptr: *anyopaque, stream: *lanes.Stream, position: u64, mask: []const u32) !u64 {
const self = cast(ptr);
const cache = try self.cacheOf(stream);
if (position != cache.len) return error.InvalidGemmaPosition;
return try draw(self.gpa, cache.logits.slice(u16, cfg.vocab), stream.sampling, position, mask);
}

fn queueFn(ptr: *anyopaque, stream: *lanes.Stream, feed: be.Feed, position: u64) !u64 {
const self = cast(ptr);
const cache = try self.cacheOf(stream);
if (position != cache.len + 1) return error.InvalidGemmaPosition;
const token: u32 = switch (feed) {
.value => |v| v,
.handle => |h| @intCast(h),
};
cache.from = cache.len;
try fwd.run(self.model, &self.scratch, &.{.{ .cache = cache, .rows = 1 }}, &.{token});
self.keepLast(cache, 0);
return try draw(self.gpa, cache.logits.slice(u16, cfg.vocab), stream.sampling, position, &.{});
}

fn readFn(_: *anyopaque, handle: u64) !u32 {
if (handle >= cfg.vocab) return error.InvalidGemmaToken;
return @intCast(handle);
}

fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) !void {
const self = cast(ptr);
var segments: [st.max_rows]fwd.Segment = undefined;
var ids: [st.max_rows]u32 = undefined;
var total: usize = 0;
if (windows.len > segments.len or windows.len != out.len) return error.InvalidGemmaWindows;
for (windows, 0..) |w, i| {
const rows = w.rows();
if (w.parents != null or w.held != 0 or total + rows > st.max_rows or w.positions.len != rows) return error.UnsupportedGemmaWindow;
if (w.masks.len != 0 and w.masks.len != rows * mask_words) return error.InvalidGemmaMasks;
const cache = try self.cacheOf(w.stream);
for (w.positions, 0..) |p, r| if (p != cache.len + r + 1) return error.InvalidGemmaPosition;
cache.from = cache.len;
segments[i] = .{ .cache = cache, .rows = rows };
ids[total] = w.pending;
@memcpy(ids[total + 1 ..][0..w.tokens.len], w.tokens);
total += rows;
}
try fwd.run(self.model, &self.scratch, segments[0..windows.len], ids[0..total]);
const logits = self.scratch.logits.slice(u16, total * cfg.vocab);
var base: usize = 0;
for (windows, out) |w, o| {
if (o.sampled.len != w.rows() or o.drafts.len != w.tokens.len) return error.InvalidGemmaOutputs;
for (o.sampled, w.positions, 0..) |*t, p, r| {
const mask = if (w.masks.len > 0) w.masks[r * mask_words ..][0..mask_words] else &.{};
t.* = try draw(self.gpa, logits[(base + r) * cfg.vocab ..][0..cfg.vocab], w.stream.sampling, p, mask);
}
@memcpy(o.drafts, w.tokens);
base += w.rows();
}
}

/// A chain's kept rows: the cache rolls back to where the verify began plus them; later rows are rewritten.
fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) !void {
const self = cast(ptr);
for (windows, paths) |w, path| {
const cache = try self.cacheOf(w.stream);
for (path, 0..) |r, j| if (r != j) return error.UnsupportedGemmaTree;
if (cache.from + path.len > cache.len) return error.InvalidGemmaKeep;
cache.len = cache.from + path.len;
}
}

fn draftFn(_: *anyopaque, requests: []const be.DraftRequest) !void {
for (requests) |r| if (r.depth != 0) return error.GemmaCheckpointHasNoDraftHead;
}

fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void {
const self = cast(ptr);
if (self.caches.fetchRemove(stream)) |entry| {
entry.value.deinit();
self.gpa.destroy(entry.value);
}
}
};

/// A row's allowed-token bits (structured output): one bit a logit.
const mask_words = (cfg.vocab + 31) / 32;
138 changes: 88 additions & 50 deletions zig/src/families/gemma4/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,33 @@ const Model = @import("model.zig").Model;

const Kind = kernels.Kind;

/// The window's host-side inputs: token ids, positions, and each layer kind's key ranges and attention chunks.
fn prepare(s: *state.Scratch, ids: []const u32, p0: usize) [2]usize {
const rows = ids.len;
@memcpy(s.ids.slice(u32, rows), ids);
for (s.pos.slice(i32, rows), 0..) |*p, i| p.* = @intCast(p0 + i);
var chunks: [2]usize = undefined;
for (0..2) |kind| {
const global = kind == 1;
const ck: usize = if (global) 64 else 128;
var low: usize = std.math.maxInt(usize);
for (s.lo[kind].slice(i32, rows), 0..) |*l, i| {
const p = p0 + i;
const first: usize = if (global or p + 1 <= cfg.window) 0 else p + 1 - cfg.window;
l.* = @intCast(first);
low = @min(low, first);
/// One stream's rows in a forward: its cache, and how many rows it adds at the cache's length.
pub const Segment = struct { cache: *state.Cache, rows: usize };

/// Host-side inputs: ids, each row's position, and per stream and layer kind its keys' ranges and attention chunks.
fn prepare(s: *state.Scratch, segments: []const Segment, ids: []const u32, chunks: *[state.max_rows][2]usize) void {
@memcpy(s.ids.slice(u32, ids.len), ids);
var at: usize = 0;
for (segments, 0..) |seg, j| {
const p0 = seg.cache.len;
for (s.pos.slice(i32, ids.len)[at..][0..seg.rows], 0..) |*p, i| p.* = @intCast(p0 + i);
for (0..2) |kind| {
const global = kind == 1;
const ck: usize = if (global) 64 else 128;
var low: usize = std.math.maxInt(usize);
for (s.lo[kind].slice(i32, ids.len)[at..][0..seg.rows], 0..) |*l, i| {
const p = p0 + i;
const first: usize = if (global or p + 1 <= cfg.window) 0 else p + 1 - cfg.window;
l.* = @intCast(first);
low = @min(low, first);
}
const first_chunk = low / ck;
chunks[j][kind] = (p0 + seg.rows - 1) / ck - first_chunk + 1;
const ring: i32 = if (global) 0 else state.ring;
s.meta[kind].slice(i32, 4 * state.max_rows)[4 * j ..][0..4].* = .{ @intCast(first_chunk), @intCast(chunks[j][kind]), ring, @intCast(seg.rows) };
}
const first_chunk = low / ck;
chunks[kind] = (p0 + rows - 1) / ck - first_chunk + 1;
const ring: i32 = if (global) 0 else state.ring;
s.meta[kind].slice(i32, 4)[0..4].* = .{ @intCast(first_chunk), @intCast(chunks[kind]), ring, @intCast(rows) };
at += seg.rows;
}
return chunks;
}

fn project(m: *Model, e: mtl.ComputeEncoder, l: weights.Linear, x: mtl.Buffer, y: mtl.Buffer, rows: usize) !void {
Expand All @@ -46,13 +51,17 @@ fn bindRef(e: mtl.ComputeEncoder, r: weights.Ref, i: usize) void {
e.setBuffer(r.buf, r.off, i);
}

/// The window's logits [rows, vocab] bf16 (soft-capped) in s.logits; the cache keeps the window's keys and values.
pub fn window(m: *Model, s: *state.Scratch, c: *state.Cache, ids: []const u32, p0: usize) !void {
const rows = ids.len;
if (rows == 0 or rows > state.max_rows) return error.BadWindow;
if (p0 + rows > c.capacity) return error.ContextFull;
const chunks = prepare(s, ids, p0);
for (chunks) |n| if (cfg.query_heads * rows * n > s.slots) return error.ContextFull;
/// Every segment's rows in one forward: soft-capped logits in s.logits by segment; each cache grows by its rows.
pub fn run(m: *Model, s: *state.Scratch, segments: []const Segment, ids: []const u32) !void {
var rows: usize = 0;
for (segments) |seg| {
if (seg.rows == 0 or seg.cache.len + seg.rows > seg.cache.capacity) return error.ContextFull;
rows += seg.rows;
}
if (rows == 0 or rows > state.max_rows or rows != ids.len) return error.BadWindow;
var chunks: [state.max_rows][2]usize = undefined;
prepare(s, segments, ids, &chunks);
for (segments, 0..) |seg, j| for (chunks[j]) |n| if (cfg.query_heads * seg.rows * n > s.slots) return error.ContextFull;
const w = &m.weights;
const ks = &m.kernels.sliding;
const cb = m.queue.commandBuffer();
Expand All @@ -73,7 +82,7 @@ pub fn window(m: *Model, s: *state.Scratch, c: *state.Cache, ids: []const u32, p
e.dispatchGroups(.{ .width = rows }, .{ .width = 1024 });
var cur: usize = 0;
for (0..cfg.layers) |i| {
try layer(m, e, s, c, i, cur, rows, chunks[@intFromBool(cfg.global(i))]);
try layer(m, e, s, segments, &chunks, i, cur, rows);
cur = 1 - cur;
}
try project(m, e, w.head, s.normed[cur], s.logits, rows);
Expand All @@ -88,7 +97,13 @@ pub fn window(m: *Model, s: *state.Scratch, c: *state.Cache, ids: []const u32, p
std.log.err("gemma4: command buffer failed: {s}", .{msg});
return error.GpuFailed;
}
c.len = p0 + rows;
for (segments) |seg| seg.cache.len += seg.rows;
}

/// One stream's window at the cache's length (`p0` must equal it).
pub fn window(m: *Model, s: *state.Scratch, c: *state.Cache, ids: []const u32, p0: usize) !void {
if (p0 != c.len) return error.BadPosition;
return run(m, s, &.{.{ .cache = c, .rows = ids.len }}, ids);
}

/// sqrt(hidden) as MLX multiplies by it: a weak-typed scalar, rounded to bf16 first.
Expand All @@ -98,34 +113,57 @@ pub fn embedScale() f32 {
return @bitCast((b + 0x7FFF + ((b >> 16) & 1)) & 0xFFFF0000);
}

fn layer(m: *Model, e: mtl.ComputeEncoder, s: *state.Scratch, c: *state.Cache, i: usize, cur: usize, rows: usize, chunks: usize) !void {
fn layer(m: *Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: []const Segment, chunks: *const [state.max_rows][2]usize, i: usize, cur: usize, rows: usize) !void {
const global = cfg.global(i);
const kd: *const Kind = m.kernels.kind(global);
const l = &m.weights.layers[i];
const nk = cfg.kvHeads(i);
const dh = cfg.headDim(i);
const kind: usize = @intFromBool(global);
const width = l.qkv.n;
try project(m, e, l.qkv, s.normed[cur], s.qkv, rows);
e.setPipeline(kd.qkv);
bind(e, &.{s.qkv}, 0);
bindRef(e, l.q_norm, 1);
bindRef(e, l.k_norm, 2);
bind(e, &.{ if (global) m.inv_global else m.inv_sliding, s.pos }, 3);
e.setValue(cfg.eps, 5);
bind(e, &.{ s.q, s.k, s.v }, 6);
e.dispatchGroups(.{ .width = cfg.query_heads + 2 * nk, .height = rows }, .{ .width = 32 });
e.setPipeline(kd.partial);
bind(e, &.{ s.q, c.k[i], c.v[i], s.k, s.v, s.pos, s.lo[kind], s.meta[kind] }, 0);
e.setValue(@as(i32, @intCast(state.slotsOf(i, c.capacity))), 8);
bind(e, &.{ s.pm, s.pl, s.po }, 9);
e.dispatchGroups(.{ .width = chunks, .height = nk, .depth = rows }, .{ .width = 32 * kd.heads_per_kv * kd.split });
e.setPipeline(kd.merge);
bind(e, &.{ s.pm, s.pl, s.po, s.meta[kind], s.attn }, 0);
e.dispatchGroups(.{ .width = 1, .height = cfg.query_heads, .depth = rows }, .{ .width = 32 });
e.setPipeline(kd.kv_write);
bind(e, &.{ s.k, s.v, c.k[i], c.v[i], s.pos }, 0);
e.setValue([3]i32{ @intCast(rows), if (global) 0 else state.ring, @intCast(state.slotsOf(i, c.capacity)) }, 5);
e.dispatchThreads(.{ .width = dh, .height = rows, .depth = nk }, .{ .width = @min(dh, 256) });
var at: usize = 0;
for (segments, 0..) |seg, j| {
const n = seg.rows;
const c = seg.cache;
const kv_off = at * nk * dh * 2; // this stream's keys and values [nk, n, dh] in s.k, s.v
const q_off = at * cfg.query_heads * dh * 2;
e.setPipeline(kd.qkv);
e.setBuffer(s.qkv, at * width * 2, 0);
bindRef(e, l.q_norm, 1);
bindRef(e, l.k_norm, 2);
bind(e, &.{if (global) m.inv_global else m.inv_sliding}, 3);
e.setBuffer(s.pos, at * 4, 4);
e.setValue(cfg.eps, 5);
e.setBuffer(s.q, q_off, 6);
e.setBuffer(s.k, kv_off, 7);
e.setBuffer(s.v, kv_off, 8);
e.dispatchGroups(.{ .width = cfg.query_heads + 2 * nk, .height = n }, .{ .width = 32 });
e.setPipeline(kd.partial);
e.setBuffer(s.q, q_off, 0);
bind(e, &.{ c.k[i], c.v[i] }, 1);
e.setBuffer(s.k, kv_off, 3);
e.setBuffer(s.v, kv_off, 4);
e.setBuffer(s.pos, at * 4, 5);
e.setBuffer(s.lo[kind], at * 4, 6);
e.setBuffer(s.meta[kind], j * 16, 7);
e.setValue(@as(i32, @intCast(state.slotsOf(i, c.capacity))), 8);
bind(e, &.{ s.pm, s.pl, s.po }, 9);
e.dispatchGroups(.{ .width = chunks[j][kind], .height = nk, .depth = n }, .{ .width = 32 * kd.heads_per_kv * kd.split });
e.setPipeline(kd.merge);
bind(e, &.{ s.pm, s.pl, s.po }, 0);
e.setBuffer(s.meta[kind], j * 16, 3);
e.setBuffer(s.attn, q_off, 4);
e.dispatchGroups(.{ .width = 1, .height = cfg.query_heads, .depth = n }, .{ .width = 32 });
e.setPipeline(kd.kv_write);
e.setBuffer(s.k, kv_off, 0);
e.setBuffer(s.v, kv_off, 1);
bind(e, &.{ c.k[i], c.v[i] }, 2);
e.setBuffer(s.pos, at * 4, 4);
e.setValue([3]i32{ @intCast(n), if (global) 0 else state.ring, @intCast(state.slotsOf(i, c.capacity)) }, 5);
e.dispatchThreads(.{ .width = dh, .height = n, .depth = nk }, .{ .width = @min(dh, 256) });
at += n;
}
try project(m, e, l.o, s.attn, s.o, rows);
e.setPipeline(kd.attn_tail);
bind(e, &.{ s.h[cur], s.o }, 0);
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/gemma4/gemma4.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub const weights = @import("weights.zig");
pub const state = @import("state.zig");
pub const forward = @import("forward.zig");
pub const Model = @import("model.zig").Model;
pub const backend = @import("backend.zig");

test {
_ = config;
Expand Down
Loading