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: prompt chunks of 512 rows on core affine_mm, from alig…
…ned copies of the MLX tensors

prompt.zig runs a chunk's projections on affine_mm (the decode glue for the rest, the head on its last row only);
affine_mm reads words as u32, and checkpoint tensors can sit at any byte offset in a shard, so weights.zig copies
each linear's tensors to aligned storage. The sliding ring holds the window plus a chunk. Against the oracle's mlx-lm
prompt receipts: first tokens equal at 8k and 32k, 49 tokens at 32k, the short prompts as the Python engine's own
decode path; prompt attention is still the per-row decode kernel (637 tokens a second at 8k).
  • Loading branch information
BobClawblaw committed Oct 14, 2026
commit 1eacc9129239cbe56af9036829074e2152ff4a8a
1 change: 1 addition & 0 deletions zig/src/families/gemma4/gemma4.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub const kernels = @import("kernels.zig");
pub const weights = @import("weights.zig");
pub const state = @import("state.zig");
pub const forward = @import("forward.zig");
pub const prompt = @import("prompt.zig");
pub const Model = @import("model.zig").Model;
pub const backend = @import("backend.zig");

Expand Down
11 changes: 11 additions & 0 deletions zig/src/families/gemma4/model.zig
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const ckpt = @import("../../core/checkpoint_metal.zig");
const shards = @import("../../core/checkpoint.zig");
const weights = @import("weights.zig");
const kernels = @import("kernels.zig");
const affine_mm = @import("../../core/affine_mm.zig");

pub const Model = struct {
gpa: std.mem.Allocator,
Expand All @@ -16,6 +17,8 @@ pub const Model = struct {
weights: weights.Weights,
kernels: kernels.Kernels,
projections: weights.Projections = .{},
/// core/affine_mm's pipelines for prompt chunks: 4-bit groups of 64 from the checkpoint's own tensors.
mm: affine_mm.Pipes,
/// RoPE inverse frequencies, float32 [dim / 2], for sliding and for global layers.
inv_sliding: mtl.Buffer,
inv_global: mtl.Buffer,
Expand All @@ -41,6 +44,13 @@ pub const Model = struct {
errdefer m.weights.deinit(gpa);
m.kernels = try kernels.Kernels.init(gpa, m.device);
errdefer m.kernels.deinit();
{
const text = try affine_mm.source(m.device, gpa, .{});
defer gpa.free(text);
const lib = try mtl.Library.fromSource(m.device, text, mtl.CompileOptions.mlx());
defer lib.deinit();
for (&m.mm, affine_mm.names) |*p, name| p.* = try mtl.Pipeline.init(m.device, lib, name, false);
}
const opts = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked;
m.inv_sliding = try m.device.buffer(cfg.sliding_dim / 2 * 4, opts);
m.inv_global = try m.device.buffer(cfg.global_dim / 2 * 4, opts);
Expand All @@ -53,6 +63,7 @@ pub const Model = struct {
m.inv_sliding.deinit();
m.inv_global.deinit();
m.projections.deinit(m.gpa);
for (m.mm) |p| p.deinit();
m.kernels.deinit();
m.weights.deinit(m.gpa);
m.checkpoint.deinit();
Expand Down
211 changes: 211 additions & 0 deletions zig/src/families/gemma4/prompt.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
//! A prompt chunk of up to 512 rows of one stream: core/affine_mm projections, the decode glue, the last row's logits.
const std = @import("std");
const mtl = @import("metal");
const cfg = @import("config.zig");
const state = @import("state.zig");
const kernels = @import("kernels.zig");
const affine_mm = @import("../../core/affine_mm.zig");
const lane = @import("../../core/lane_projection.zig");
const Model = @import("model.zig").Model;

const Ref = lane.Ref;
const R = state.chunk_rows;
const private = mtl.ResourceOptions.private | mtl.ResourceOptions.untracked;
const shared = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked;

const Q = @import("weights.zig").Mlx;

pub const Scratch = struct {
ids: mtl.Buffer,
pos: mtl.Buffer,
lo: [2]mtl.Buffer,
meta: [2]mtl.Buffer,
h: [2]mtl.Buffer,
normed: [2]mtl.Buffer,
sums: mtl.Buffer,
qkv: mtl.Buffer,
q: mtl.Buffer,
k: mtl.Buffer,
v: mtl.Buffer,
attn: mtl.Buffer,
o: mtl.Buffer,
hn: mtl.Buffer,
n_mlp: mtl.Buffer,
gate_up: mtl.Buffer,
act: mtl.Buffer,
y: mtl.Buffer,
pm: mtl.Buffer,
pl: mtl.Buffer,
po: mtl.Buffer,
logits: mtl.Buffer,
slots: usize,

pub fn init(device: mtl.Device, capacity: usize) !Scratch {
const d = cfg.hidden;
const qd = cfg.query_heads * cfg.global_dim;
const slots = cfg.query_heads * state.max_rows * (capacity / 64 + 2);
var s: Scratch = undefined;
s.slots = slots;
inline for (.{ .{ "ids", R * 4, true }, .{ "pos", R * 4, true }, .{ "sums", R * (cfg.intermediate / 64) * 4, false }, .{ "qkv", R * (qd + 2 * 16 * 256) * 2, false }, .{ "q", R * qd * 2, false }, .{ "k", R * 16 * 256 * 2, false }, .{ "v", R * 16 * 256 * 2, false }, .{ "attn", R * qd * 2, false }, .{ "o", R * d * 2, false }, .{ "hn", R * d * 2, false }, .{ "n_mlp", R * d * 2, false }, .{ "gate_up", R * 2 * cfg.intermediate * 2, false }, .{ "act", R * cfg.intermediate * 2, false }, .{ "y", R * d * 2, false }, .{ "pm", slots * 4, false }, .{ "pl", slots * 4, false }, .{ "po", slots * cfg.global_dim * 4, false }, .{ "logits", cfg.vocab * 2, true } }) |f|
@field(s, f[0]) = try device.buffer(f[1], if (f[2]) shared else private);
for (&s.lo) |*b| b.* = try device.buffer(R * 4, shared);
for (&s.meta) |*b| b.* = try device.buffer(R * state.meta_ints * 4, shared);
for (&s.h) |*b| b.* = try device.buffer(R * d * 2, private);
for (&s.normed) |*b| b.* = try device.buffer(R * d * 2, private);
return s;
}

pub fn deinit(s: *Scratch) void {
inline for (.{ "ids", "pos", "sums", "qkv", "q", "k", "v", "attn", "o", "hn", "n_mlp", "gate_up", "act", "y", "pm", "pl", "po", "logits" }) |f| @field(s, f).deinit();
for (s.lo ++ s.meta ++ s.h ++ s.normed) |b| b.deinit();
}
};

/// y[:, col..col + q.n] (row pitch `pitch`) = x q^T, x's group sums already in s.sums.
fn mm(m: *Model, e: mtl.ComputeEncoder, s: *Scratch, q: Q, x: mtl.Buffer, y: mtl.Buffer, col: usize, pitch: usize, rows: u32) void {
affine_mm.denseBatch(e, m.mm, Ref{ .buf = x }, Ref{ .buf = s.sums }, q, Ref{ .buf = y, .off = col * 2 }, rows, 1, .{ .x_row = @intCast(q.k), .y_row = @intCast(pitch) });
}

fn sums(m: *Model, e: mtl.ComputeEncoder, s: *Scratch, x: mtl.Buffer, rows: u32, k: u32) void {
affine_mm.rowSums(e, m.mm, 64, Ref{ .buf = x }, Ref{ .buf = s.sums }, rows, k);
}

fn bind(e: mtl.ComputeEncoder, bufs: []const mtl.Buffer, first: usize) void {
for (bufs, first..) |b, i| e.setBuffer(b, 0, i);
}

/// `ids` (at most 512) at the cache's length: the cache keeps their keys and values; s.logits has the last row's.
pub fn run(m: *Model, s: *Scratch, c: *state.Cache, ids: []const u32) !void {
const rows = ids.len;
if (rows == 0 or rows > R) return error.BadChunk;
if (c.len + rows > c.capacity) return error.ContextFull;
const p0 = c.len;
@memcpy(s.ids.slice(u32, rows), ids);
for (s.pos.slice(i32, rows), 0..) |*p, i| p.* = @intCast(p0 + i);
var chunks: [R][2]usize = undefined;
for (0..2) |kind| {
const global = kind == 1;
const ck: usize = if (global) 64 else 128;
const lo = s.lo[kind].slice(i32, rows);
for (lo, 0..) |*l, i| l.* = @intCast(if (global or p0 + i + 1 <= cfg.window) 0 else p0 + i + 1 - cfg.window);
var sub: usize = 0;
while (sub < rows) : (sub += state.max_rows) {
const n = @min(state.max_rows, rows - sub);
const first = @as(usize, @intCast(lo[sub])) / ck;
chunks[sub][kind] = (p0 + sub + n - 1) / ck - first + 1;
if (cfg.query_heads * state.max_rows * chunks[sub][kind] > s.slots) return error.ContextFull;
s.meta[kind].slice(i32, R * state.meta_ints)[sub * state.meta_ints ..][0..5].* = .{ @intCast(first), @intCast(chunks[sub][kind]), if (global) 0 else state.ring, @intCast(n), std.math.maxInt(i32) };
}
}
const ks = &m.kernels.sliding;
const w = &m.weights;
const cb = m.queue.commandBuffer();
const e = cb.compute(.serial);
const r32: u32 = @intCast(rows);
e.setPipeline(ks.embed);
bind(e, &.{s.ids}, 0);
e.setBuffer(w.embed_w.buf, w.embed_w.off, 1);
e.setBuffer(w.embed_s.buf, w.embed_s.off, 2);
e.setBuffer(w.embed_b.buf, w.embed_b.off, 3);
bind(e, &.{s.h[0]}, 4);
e.setValue(@import("forward.zig").embedScale(), 5);
e.dispatchThreads(.{ .width = cfg.hidden / 2, .height = rows }, .{ .width = 256 });
e.setPipeline(ks.rms);
bind(e, &.{s.h[0]}, 0);
e.setBuffer(w.layers[0].input_norm.buf, w.layers[0].input_norm.off, 1);
bind(e, &.{s.normed[0]}, 2);
e.setValue(cfg.eps, 3);
e.dispatchGroups(.{ .width = rows }, .{ .width = 1024 });
var cur: usize = 0;
for (0..cfg.layers) |i| {
try layer(m, e, s, c, &chunks, i, cur, r32);
cur = 1 - cur;
}
// the head on the last row only (the lane kernel's one-row bits), soft-capped
const head = try m.projections.get(m.gpa, m.device, w.head.n, w.head.k);
try head.encode(e, .{ .buf = s.normed[cur], .off = (rows - 1) * cfg.hidden * 2 }, .{ .buf = w.head.w }, .{ .buf = w.head.sb }, .{ .buf = s.logits }, 1);
e.setPipeline(ks.softcap);
bind(e, &.{s.logits}, 0);
e.setValue(cfg.softcap, 1);
e.dispatchThreads(.{ .width = cfg.vocab }, .{ .width = 256 });
e.end();
cb.commit();
cb.wait();
if (cb.failure()) |msg| {
std.log.err("gemma4: prompt chunk failed: {s}", .{msg});
return error.GpuFailed;
}
c.len += rows;
}

fn layer(m: *Model, e: mtl.ComputeEncoder, s: *Scratch, c: *state.Cache, chunks: *const [R][2]usize, i: usize, cur: usize, rows: u32) !void {
const global = cfg.global(i);
const kd: *const kernels.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 qn = cfg.query_heads * dh;
const width = qn + nk * dh * @as(usize, if (global) 1 else 2);
sums(m, e, s, s.normed[cur], rows, cfg.hidden);
mm(m, e, s, l.mlx[0], s.normed[cur], s.qkv, 0, width, rows);
mm(m, e, s, l.mlx[1], s.normed[cur], s.qkv, qn, width, rows);
if (!global) mm(m, e, s, l.mlx[2], s.normed[cur], s.qkv, qn + nk * dh, width, rows);
e.setPipeline(kd.qkv);
bind(e, &.{s.qkv}, 0);
e.setBuffer(l.q_norm.buf, l.q_norm.off, 1);
e.setBuffer(l.k_norm.buf, l.k_norm.off, 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.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 sub: usize = 0;
while (sub < rows) : (sub += state.max_rows) {
const rn = @min(state.max_rows, rows - sub);
e.setPipeline(kd.partial);
e.setBuffer(s.q, sub * cfg.query_heads * dh * 2, 0);
bind(e, &.{ c.k[i], c.v[i], c.k[i], c.v[i] }, 1);
e.setBuffer(s.pos, sub * 4, 5);
e.setBuffer(s.lo[kind], sub * 4, 6);
e.setBuffer(s.meta[kind], sub * state.meta_ints * 4, 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[sub][kind], .height = nk, .depth = rn }, .{ .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], sub * state.meta_ints * 4, 3);
e.setBuffer(s.attn, sub * cfg.query_heads * dh * 2, 4);
e.dispatchGroups(.{ .width = 1, .height = cfg.query_heads, .depth = rn }, .{ .width = 32 });
}
sums(m, e, s, s.attn, rows, @intCast(qn));
mm(m, e, s, l.mlx[3], s.attn, s.o, 0, cfg.hidden, rows);
e.setPipeline(kd.attn_tail);
bind(e, &.{ s.h[cur], s.o }, 0);
e.setBuffer(l.post_attention.buf, l.post_attention.off, 2);
e.setBuffer(l.pre_feedforward.buf, l.pre_feedforward.off, 3);
e.setValue(cfg.eps, 4);
bind(e, &.{ s.hn, s.n_mlp }, 5);
e.dispatchGroups(.{ .width = rows }, .{ .width = 256 });
sums(m, e, s, s.n_mlp, rows, cfg.hidden);
mm(m, e, s, l.mlx[4], s.n_mlp, s.gate_up, 0, 2 * cfg.intermediate, rows);
mm(m, e, s, l.mlx[5], s.n_mlp, s.gate_up, cfg.intermediate, 2 * cfg.intermediate, rows);
e.setPipeline(kd.geglu);
bind(e, &.{ s.gate_up, s.act }, 0);
e.setValue(@as(u32, cfg.intermediate), 2);
e.dispatchThreads(.{ .width = cfg.intermediate, .height = rows }, .{ .width = 256 });
sums(m, e, s, s.act, rows, cfg.intermediate);
mm(m, e, s, l.mlx[6], s.act, s.y, 0, cfg.hidden, rows);
e.setPipeline(kd.dense_tail);
bind(e, &.{ s.hn, s.y }, 0);
e.setBuffer(l.post_feedforward.buf, l.post_feedforward.off, 2);
e.setBuffer(l.scalar.buf, l.scalar.off, 3);
const nx = if (i + 1 < cfg.layers) m.weights.layers[i + 1].input_norm else m.weights.final_norm;
e.setBuffer(nx.buf, nx.off, 4);
e.setValue(cfg.eps, 5);
bind(e, &.{ s.h[1 - cur], s.normed[1 - cur] }, 6);
e.dispatchGroups(.{ .width = rows }, .{ .width = 256 });
}
5 changes: 3 additions & 2 deletions zig/src/families/gemma4/state.zig
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ pub const max_rows = 16;
pub const prompt_rows = 128;
/// Ints a row's attention meta takes: first chunk, chunks, ring, rows, first new key, padding.
pub const meta_ints = 8;
/// A sliding layer's ring: the window plus rows a window may write past it (gilby's RingKVCache, WINDOW_ROWS).
pub const ring = cfg.window + 128;
/// Rows a prompt chunk takes (prompt.zig), and a sliding layer's ring: the window plus a chunk written past it.
pub const chunk_rows = 512;
pub const ring = cfg.window + chunk_rows;

/// One stream's keys and values, per layer [kv heads, slots, head dim] bf16, and how many positions it holds.
pub const Cache = struct {
Expand Down
26 changes: 26 additions & 0 deletions zig/src/families/gemma4/weights.zig
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@ pub const Ref = lane.Ref;
/// One packed linear (a stack of members along N): its lane layout's words and scale/bias pairs.
pub const Linear = struct { w: mtl.Buffer, sb: mtl.Buffer, n: usize, k: usize };

/// A linear as core/affine_mm reads it (prompt chunks): MLX's words, scales and biases, copied to aligned storage.
pub const Mlx = struct { w: Ref, s: Ref, b: Ref, n: u32, k: u32 };

pub const Layer = struct {
/// q, k, v (k again on global layers, which have none), o, gate, up, down for prompt chunks.
mlx: [7]Mlx,
qkv: Linear,
o: Linear,
gate_up: Linear,
Expand Down Expand Up @@ -55,6 +60,24 @@ pub const Weights = struct {
}
};

/// A linear's three tensors copied into one aligned buffer: checkpoint tensors can sit at any byte offset in a shard.
fn mlxCopy(gpa: std.mem.Allocator, device: mtl.Device, c: *const ckpt.Checkpoint, owned: *std.ArrayList(mtl.Buffer), prefix: []const u8, member: []const u8) !Mlx {
var name: [160]u8 = undefined;
const w = try c.get(try std.fmt.bufPrint(&name, "{s}{s}.weight", .{ prefix, member }));
const s = try c.get(try std.fmt.bufPrint(&name, "{s}{s}.scales", .{ prefix, member }));
const b = try c.get(try std.fmt.bufPrint(&name, "{s}{s}.biases", .{ prefix, member }));
const sb_at = std.mem.alignForward(usize, w.bytes, 256);
const bb_at = sb_at + std.mem.alignForward(usize, s.bytes, 256);
const buf = try device.buffer(bb_at + b.bytes, shared);
errdefer buf.deinit();
const dst = buf.slice(u8, bb_at + b.bytes);
@memcpy(dst[0..w.bytes], w.host(u8)[0..w.bytes]);
@memcpy(dst[sb_at..][0..s.bytes], s.host(u8)[0..s.bytes]);
@memcpy(dst[bb_at..][0..b.bytes], b.host(u8)[0..b.bytes]);
try owned.append(gpa, buf);
return .{ .w = .{ .buf = buf }, .s = .{ .buf = buf, .off = sb_at }, .b = .{ .buf = buf, .off = bb_at }, .n = @intCast(w.shape[0]), .k = @intCast(w.shape[1] * 8) };
}

fn ref(c: *const ckpt.Checkpoint, name: []const u8) !Ref {
const t = try c.get(name);
return .{ .buf = t.buffer, .off = t.offset };
Expand Down Expand Up @@ -114,6 +137,9 @@ pub fn load(gpa: std.mem.Allocator, device: mtl.Device, c: *const ckpt.Checkpoin
l.o = try pack(gpa, device, c, &w.owned, pre, &.{"self_attn.o_proj"});
l.gate_up = try pack(gpa, device, c, &w.owned, pre, &.{ "mlp.gate_proj", "mlp.up_proj" });
l.down = try pack(gpa, device, c, &w.owned, pre, &.{"mlp.down_proj"});
for (&l.mlx, [_][]const u8{ "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj", "mlp.gate_proj", "mlp.up_proj", "mlp.down_proj" }) |*x, member| {
x.* = if (cfg.global(i) and std.mem.eql(u8, member, "self_attn.v_proj")) l.mlx[1] else try mlxCopy(gpa, device, c, &w.owned, pre, member); // global layers: no v_proj, never read
}
inline for (.{ "q_norm", "k_norm", "input_norm", "post_attention", "pre_feedforward", "post_feedforward", "scalar" }, .{ "self_attn.q_norm.weight", "self_attn.k_norm.weight", "input_layernorm.weight", "post_attention_layernorm.weight", "pre_feedforward_layernorm.weight", "post_feedforward_layernorm.weight", "layer_scalar" }) |field, t|
@field(l, field) = try ref(c, try std.fmt.bufPrint(&name, "{s}{s}", .{ pre, t }));
}
Expand Down
26 changes: 26 additions & 0 deletions zig/tests/gemma4/bench.zig
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,32 @@ pub fn main(init: std.process.Init) !void {
std.debug.print("affine_mm projections, {d} rows: {d:.2} ms GPU ({d:.0} tok/s)\n", .{ rows, best, @as(f64, @floatFromInt(rows)) * 1e3 / best });
}
}
{
var ss = try g4.state.Scratch.init(m.device, 4096);
defer ss.deinit();
var ps = try g4.prompt.Scratch.init(m.device, 4096);
defer ps.deinit();
var tok: [40]u32 = undefined;
for (&tok, 0..) |*t, i| t.* = @intCast(2000 + i * 37);
{
var ca = try g4.state.Cache.init(m.device, 4096);
defer ca.deinit();
var cbk = try g4.state.Cache.init(m.device, 4096);
defer cbk.deinit();
const step: usize = if (std.c.getenv("GEMMA_STEP")) |v| std.fmt.parseInt(usize, std.mem.span(v), 10) catch 40 else 40;
var at: usize = 0;
while (at < tok.len) : (at += step) try g4.prompt.run(m, &ps, &ca, tok[at..@min(at + step, tok.len)]);
try g4.forward.run(m, &ss, &.{.{ .cache = &cbk, .rows = 16 }}, tok[0..16]);
try g4.forward.run(m, &ss, &.{.{ .cache = &cbk, .rows = 16 }}, tok[16..32]);
try g4.forward.run(m, &ss, &.{.{ .cache = &cbk, .rows = 8 }}, tok[32..40]);
const a = ps.logits.slice(u16, cfg.vocab);
const b = ss.logits.slice(u16, 16 * cfg.vocab)[7 * cfg.vocab ..][0..cfg.vocab];
var worst: f32 = 0;
for (a, b) |x0, y0| worst = @max(worst, @abs(@as(f32, @bitCast(@as(u32, x0) << 16)) - @as(f32, @bitCast(@as(u32, y0) << 16))));
std.debug.print("prompt path vs decode path, 40 tokens, last-row logits: worst |diff| {d}\n", .{worst});
}
if (std.c.getenv("GEMMA_DEBUG_ONLY") != null) return;
}
var s = try g4.state.Scratch.init(m.device, 33024);
defer s.deinit();
var c = try g4.state.Cache.init(m.device, 33024);
Expand Down
Loading