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
Core affine_mm dequantizes each step's weights to bf16 in its tile, a…
…nd the row sums go

The tile held exact codes (4-bit ones plus 128) and every 64-deep group's partial product was scaled and bias-corrected
in a scalar epilogue, the bias times fp32 row sums from a kernel of its own. Now each thread writes its 32 weights as
bf16(fma(scale, code, bias)), one rounding, as mlx-lm's quantized matmul dequantizes, and the tensor unit accumulates
over the whole depth with nothing after it: a 512-row chunk's 60 Gemma 4 layers take 284 ms on the GEMMs where they
took 344 (mlx-lm's 302). tf_affine_row_sums, rowSums/rowSumsAt, the sums strides and every caller's sums buffer are
removed (Gemma 4, GLM, the tests and mm_bench).

The prompt path's weights now round as mlx-lm's do while the lane kernels keep the codes exact, so prompt receipts
move: affine_ref checks affine_mm against the rounded weights (its own reference stays exact for simd_qmm) with the
tensor unit's 16-deep chain as the bound, and glm_rows_classes' fp64 check takes the rounding. Gemma 4 long prompts:
8k 1362, 32k 1202, 64k 1047, 128k 892, 252k 564 tok/s (mlx-lm 1305/1139/944/651/440); equal at 32k and 64k, parting
at 8k, 128k and 252k where mlx-lm's top two logits tie. The four decode receipts all equal the oracle now; lanes with
and without the drafter and the served gate are unchanged.
  • Loading branch information
BobClawblaw committed Oct 15, 2026
commit 127be333f79b55f968e77b2109342bd83fdbc126
28 changes: 16 additions & 12 deletions docs/recipes/gemma-4-native.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ fixtures from `tools/zig/gemma4_dump.py`).

A stream keeps a ring of window + 512 slots for each sliding layer and a buffer for each global one; rolling back is
moving the cache's length. A decode forward takes up to 16 rows of one stream and 128 of several, and every row keeps
its bits. Prompts run in chunks of 512 rows on `core/affine_mm` and a tensor-unit attention kernel, at about 1,190
tokens a second at 8k, 1,050 at 32k and 530 at 252k.
its bits. Prompts run in chunks of 512 rows on `core/affine_mm` and a tensor-unit attention kernel, at about 1,360
tokens a second at 8k, 1,200 at 32k and 560 at 252k.

The drafter is z-lab's DFlash (`zig/src/families/gemma4/dflash.zig`): five Qwen3-style layers reading six of the
target's layer outputs (1, 12, 23, 35, 46, 57) through `fc` and a norm, drafting a block of the pending token and up
Expand Down Expand Up @@ -77,8 +77,9 @@ zig-out/bin/tf-gemma4-run M L NL 49 512 && python tools/zig/gemma4_gate.py check
and the native run ties them (its decode attention sums 256-key chunks in its own order). Every row keeps its bits
at any window width and beside other streams' rows.
- Long prompts against the oracle's mlx-lm prompt forward (fed in 2048-token chunks, as `mlx_lm.generate` feeds a
prompt), 49 greedy tokens each: equal at 32k, 64k and 252k. At 8k and 128k the two part at tokens 25 and 30, each
where mlx-lm's top two logits are equal (28.25 and 26.25) and the native run puts them 0.625 and 0.375 apart.
prompt), 49 greedy tokens each: equal at 32k and 64k. At 8k, 128k and 252k the two part at tokens 25, 30 and 45,
each where mlx-lm's top two logits are equal (28.25, 26.25 and 28.625); the native run puts them 0.125, 0.625 and
0.125 apart.
- The lane core: copy-drafted and DFlash-drafted streams, alone and 4 and 8 in shared rounds, equal the engine's
plain replies token for token, on the four prompts and on two copy-heavy ones.
- Served on an M5 Ultra with the drafter: greedy token SHAs equal the engine's receipts alone, with drafts off and on,
Expand All @@ -96,17 +97,20 @@ Long prompts, one after the other on the same M5 Ultra: native in 512-row chunks

| Prompt | Native prompt tok/s | mlx-lm prompt tok/s | Native decode tok/s | mlx-lm decode tok/s |
|---|---|---|---|---|
| 8k | 1187 | 1305 | about 35 | 39 |
| 32k | 1054 | 1139 | about 33 | 32 |
| 64k | 949 | 944 | about 29 | 32 |
| 128k | 806 | 651 | about 24 | 25 |
| 252k | 527 | 440 | about 18 | 16 |
| 8k | 1362 | 1305 | about 35 | 39 |
| 32k | 1202 | 1139 | about 33 | 32 |
| 64k | 1047 | 944 | about 29 | 32 |
| 128k | 892 | 651 | about 24 | 25 |
| 252k | 564 | 440 | about 18 | 16 |

Prompt attention takes 32 query rows of a head a threadgroup: each simdgroup scores 32 keys of a block over the whole
head and accumulates its own 64 output columns, the row maxes and fp32 probabilities crossing threadgroup memory 128
keys at a time. A 512-row chunk's 60 layers spend 138 ms there at 32k and 527 ms at 128k, where 16 rows a threadgroup
spent 194 and 810 (mlx-lm's fused attention about 161 at 32k): the kernel streams keys and values, so what each load
serves decides its rate, and vector loads, fetching a step ahead, and sparing interior blocks the mask and the rescale
moved nothing. Only the row sums regroup, so the long prompts' bits move at a tie or two. The prompt GEMMs are core
affine_mm's: a 512-row chunk's 60 layers take 344 ms there (mlx-lm's quantized matmuls 302), the whole of the gap to
mlx-lm at 8k.
moved nothing. The prompt GEMMs are core affine_mm's, which dequantizes each step's weights to bf16 in its tile (scale
times code plus bias in fp32, rounded once, as mlx-lm's quantized matmul does) and accumulates on the tensor unit over
the whole depth: a 512-row chunk's 60 layers take 284 ms there (mlx-lm's quantized matmuls 302), where the exact-codes
design, its per-group scale and bias epilogue and its row-sums pass took 344. So the prompt path rounds its weights as
mlx-lm does while the decode path's lane kernels keep the codes exact: over 40 tokens their last-row logits part by up
to 1.4 (0.8 with exact codes in both).
225 changes: 60 additions & 165 deletions zig/kernels/metal/core/affine_mm.metal

Large diffs are not rendered by default.

130 changes: 44 additions & 86 deletions zig/src/core/affine_mm.zig

Large diffs are not rendered by default.

37 changes: 14 additions & 23 deletions zig/src/families/gemma4/prompt.zig
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ pub const Scratch = struct {
pos: mtl.Buffer,
h: [2]mtl.Buffer,
normed: [2]mtl.Buffer,
sums: mtl.Buffer,
qkv: mtl.Buffer,
q: mtl.Buffer,
k: mtl.Buffer,
Expand All @@ -43,32 +42,28 @@ pub const Scratch = struct {
_ = capacity;
var s: Scratch = undefined;
s.taps = null;
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 }, .{ "logits", cfg.vocab * 2, true } }) |f|
inline for (.{ .{ "ids", R * 4, true }, .{ "pos", R * 4, true }, .{ "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 }, .{ "logits", cfg.vocab * 2, true } }) |f|
@field(s, f[0]) = try device.buffer(f[1], if (f[2]) shared else private);
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", "logits" }) |f| @field(s, f).deinit();
inline for (.{ "ids", "pos", "qkv", "q", "k", "v", "attn", "o", "hn", "n_mlp", "gate_up", "act", "y", "logits" }) |f| @field(s, f).deinit();
for (s.h ++ s.normed) |b| b.deinit();
if (s.taps) |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) });
/// y[:, col..col + q.n] (row pitch `pitch`) = x q^T.
fn mm(m: *Model, e: mtl.ComputeEncoder, q: Q, x: mtl.Buffer, y: mtl.Buffer, col: usize, pitch: usize, rows: u32) void {
affine_mm.denseBatch(e, m.mm, Ref{ .buf = x }, 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);
}

/// The glue's optional group sums off: affine_mm takes its own (rowSums).
/// The glue's optional group sums off (the lane kernels' operand; affine_mm dequantizes its weights instead).
fn noSums(e: mtl.ComputeEncoder, s: *Scratch, index: usize) void {
e.setBuffer(s.sums, 0, index);
e.setBuffer(s.pos, 0, index);
e.setValue(@as(i32, 0), index + 1);
}

Expand Down Expand Up @@ -139,10 +134,9 @@ pub fn layer(m: *Model, e: mtl.ComputeEncoder, s: *Scratch, c: *state.Cache, i:
const qn = cfg.query_heads * dh;
const width = qn + nk * dh * @as(usize, if (global) 1 else 2);
if (st.mm) {
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);
mm(m, e, l.mlx[0], s.normed[cur], s.qkv, 0, width, rows);
mm(m, e, l.mlx[1], s.normed[cur], s.qkv, qn, width, rows);
if (!global) mm(m, e, l.mlx[2], s.normed[cur], s.qkv, qn + nk * dh, width, rows);
}
if (st.glue) {
e.setPipeline(kd.qkv);
Expand All @@ -162,8 +156,7 @@ pub fn layer(m: *Model, e: mtl.ComputeEncoder, s: *Scratch, c: *state.Cache, i:
e.dispatchGroups(.{ .width = (rows + 31) / 32, .height = cfg.query_heads }, .{ .width = 32 * dh / 64 });
}
if (st.mm) {
sums(m, e, s, s.attn, rows, @intCast(qn));
mm(m, e, s, l.mlx[3], s.attn, s.o, 0, cfg.hidden, rows);
mm(m, e, l.mlx[3], s.attn, s.o, 0, cfg.hidden, rows);
}
if (st.glue) {
e.setPipeline(kd.attn_tail);
Expand All @@ -176,9 +169,8 @@ pub fn layer(m: *Model, e: mtl.ComputeEncoder, s: *Scratch, c: *state.Cache, i:
e.dispatchGroups(.{ .width = rows }, .{ .width = 256 });
}
if (st.mm) {
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);
mm(m, e, l.mlx[4], s.n_mlp, s.gate_up, 0, 2 * cfg.intermediate, rows);
mm(m, e, l.mlx[5], s.n_mlp, s.gate_up, cfg.intermediate, 2 * cfg.intermediate, rows);
}
if (st.glue) {
e.setPipeline(kd.geglu);
Expand All @@ -188,8 +180,7 @@ pub fn layer(m: *Model, e: mtl.ComputeEncoder, s: *Scratch, c: *state.Cache, i:
e.dispatchGroups(.{ .width = cfg.intermediate / 64, .height = rows }, .{ .width = 64 });
}
if (st.mm) {
sums(m, e, s, s.act, rows, cfg.intermediate);
mm(m, e, s, l.mlx[6], s.act, s.y, 0, cfg.hidden, rows);
mm(m, e, l.mlx[6], s.act, s.y, 0, cfg.hidden, rows);
}
if (!st.glue) return;
e.setPipeline(kd.dense_tail);
Expand Down
3 changes: 1 addition & 2 deletions zig/src/families/glm/checks.zig
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,7 @@ pub fn checkMatmul(e: *Engine, prompt: []const u32) !void {
fwd.embed(&x, b.enc, e.prompt_ids, rows);
fwd.boundary(&x, b.enc, rows, false, L.hc.?[0], L.in_norm);
fwd.qmv(&x, b.enc, e.k.qmv_kda_in, e.sc.normed, a.in_proj, out, rows);
affine_mm.rowSums(b.enc, e.k.mm_bf16, 64, e.sc.normed, pr.sums, rows, a.in_proj.k);
affine_mm.dense(b.enc, e.k.mm_bf16, e.sc.normed, pr.sums, a.in_proj, pr.proj, rows);
affine_mm.dense(b.enc, e.k.mm_bf16, e.sc.normed, a.in_proj, pr.proj, rows);
try e.finish(b.cb, b.enc);
const want: [*]const u16 = @ptrCast(@alignCast(out.addr()));
const got: [*]const u16 = @ptrCast(@alignCast(pr.proj.addr()));
Expand Down
32 changes: 10 additions & 22 deletions zig/src/families/glm/prompt.zig
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ pub const Prompt = struct {
m_x: Ref,
m_xn: Ref,
m_out: Ref,
sums: Ref, // fp32 group sums of a matmul's rows (affine_mm's bias operand)
sparse_nax: bool, // the sparse MLA attention on the tensor units (GLM_SPARSE_NAX=0: the row kernel)
rows: u32, // a chunk's rows at most (the buffers' height)
kda_rows: u32, // the rows a KDA block's planes hold (half a chunk)
Expand Down Expand Up @@ -129,7 +128,6 @@ fn buffers(p: *Prompt, arena: *st.Arena, c: *const cfg.Config, decode: *const st
p.offsets = try big.of(arena, (c.experts + 1) * 4);
p.order = try big.of(arena, n * 4);
p.sorted = try big.of(arena, n * 4);
p.sums = try big.of(arena, @max(R * 16384, n * D) / 64 * 4); // the widest dense K (MLA's out-projection), or a gather's
// the rest share three regions by layer; proj: KDA's projection, MLA's queries and key lists then values, the experts' planes, the dense gate and up
const pitch = std.mem.alignForward(usize, c.kdaProj(), 64); // the matmul's padded pitch
const qp = up(R * c.qrProj() * 2);
Expand Down Expand Up @@ -189,8 +187,7 @@ fn run(e: mtl.ComputeEncoder, grid: [3]usize, group: [3]usize) void {
/// y [M, N] = x [M, K] W^T for a 4-bit matrix (64x64 tiles; N rounded up to the weights' padded rows, y's row pitch).
fn qmm(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, q: wts.Affine, y: Ref, M: u32) void {
if (!wide.native(q)) return qmmAt(p, e, x, q.k, q, y, M);
affine_mm.rowSums(e, p.mm.mm_bf16, 64, x, p.sums, M, q.k);
affine_mm.dense(e, p.mm.mm_bf16, x, p.sums, q, y, M);
affine_mm.dense(e, p.mm.mm_bf16, x, q, y, M);
}

/// `qmm` over x's rows `ld` elements apart (a slice of a wider row).
Expand All @@ -201,24 +198,18 @@ fn qmmAt(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, ld: u32, q: wts.Affine
e,
q,
.{ .in = x, .ldx = ld, .out = y, .ldo = pitch, .rows = M },
p.sums,
);
const mm = p.mm.mm_bf16;
affine_mm.rowSumsAt(e, mm, 64, x, p.sums, M, q.k, ld);
affine_mm.denseBatch(e, mm, x, p.sums, q, y, M, 1, .{ .x_row = @intCast(ld), .y_row = @intCast(pitch) });
affine_mm.denseBatch(e, p.mm.mm_bf16, x, q, y, M, 1, .{ .x_row = @intCast(ld), .y_row = @intCast(pitch) });
}

/// `qmm` with fp32 out (TP2: one Mac's partial of a row-split projection).
fn qmmF32(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, q: wts.Affine, y: Ref, M: u32) void {
affine_mm.rowSums(e, p.mm.mm_bf16, 64, x, p.sums, M, q.k);
affine_mm.dense(e, p.mm.mm_f32, x, p.sums, q, y, M);
affine_mm.dense(e, p.mm.mm_f32, x, q, y, M);
}

/// The routed experts' gate, up and SwiGLU on the M rows of `x_in` its pairs read (in expert order) into `act` ([n, gate.n]).
fn gateUp(p: *const Prompt, mm: affine_mm.Pipes, x: *const fwd.Ctx, e: mtl.ComputeEncoder, w: *const wts.Moe, x_in: Ref, M: u32, n: u32) void {
affine_mm.rowSums(e, mm, 64, x_in, p.sums, M, w.gate.k);
affine_mm.gatherGlu(e, mm, x_in, p.sums, w.gate, w.up, p.offsets, p.order, p.act, n, x.c.experts, x.c.topk, x.c.swiglu_limit);
affine_mm.rowSums(e, mm, 64, p.act, p.sums, n, w.down.k);
fn gateUp(p: *const Prompt, mm: affine_mm.Pipes, x: *const fwd.Ctx, e: mtl.ComputeEncoder, w: *const wts.Moe, x_in: Ref, n: u32) void {
affine_mm.gatherGlu(e, mm, x_in, w.gate, w.up, p.offsets, p.order, p.act, n, x.c.experts, x.c.topk, x.c.swiglu_limit);
}

fn swiglu(x: *const fwd.Ctx, e: mtl.ComputeEncoder, gu: Ref, act: Ref, rows: u32, width: u32) void {
Expand Down Expand Up @@ -258,8 +249,8 @@ fn moe(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, w: *const wts
if (s & Class.route == 0) route(p, x, e, w, x_in, M);
if (ep) |t| {
if (s & Class.routed == 0) { // down's fp32 partials put back in (row, slot) order for the decode's combine
gateUp(p, p.mm.mm_bf16, x, e, w, x_in, M, n);
affine_mm.gatherTo(e, p.mm.mm_f32, p.act, p.sums, w.down, p.offsets, p.yf, p.order, n, E);
gateUp(p, p.mm.mm_bf16, x, e, w, x_in, n);
affine_mm.gatherTo(e, p.mm.mm_f32, p.act, w.down, p.offsets, p.yf, p.order, n, E);
}
if (s & Class.exchange == 0) t.sendRows(e, p.yf, p.wts, M);
if (s & Class.shared == 0) shared(p, x, e, w, x_in, M);
Expand All @@ -272,8 +263,8 @@ fn moe(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, w: *const wts
wide.bySorted(&p.mm.wide.?, e, .{ .w = w.down, .experts = E, .repeat = 1 }, p.act, p.offsets, p.order, p.yp, D);
} else if (s & Class.routed == 0) { // down's rows put back in (row, slot) order for the combine
const mm = if (path == .mm4) p.mm.mm_bf16 else p.mm.wide.?.mm2;
gateUp(p, mm, x, e, w, x_in, M, n);
affine_mm.gatherTo(e, mm, p.act, p.sums, w.down, p.offsets, p.yp, p.order, n, E);
gateUp(p, mm, x, e, w, x_in, n);
affine_mm.gatherTo(e, mm, p.act, w.down, p.offsets, p.yp, p.order, n, E);
}
if (s & Class.combine != 0) return;
e.setPipeline(k.moe_combine);
Expand Down Expand Up @@ -378,15 +369,13 @@ fn unabsorb(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, w: *cons
H,
.{ .in = p.att, .ldx = H * K, .out = p.vals, .ldo = H * c.v_dim, .rows = M },
K,
p.sums,
);
var q = w.kv_b;
q.w = q.w.at(@as(usize, c.nope) * K / 2);
q.s = q.s.at(@as(usize, c.nope) * (K / 64) * 2);
q.b = q.b.at(@as(usize, c.nope) * (K / 64) * 2);
q.n = c.v_dim;
affine_mm.rowSums(e, p.mm.mm_bf16, 64, p.att, p.sums, M * H, K);
affine_mm.denseBatch(e, p.mm.mm_bf16, p.att, p.sums, q, p.vals, M, H, .{ .x_row = @intCast(H * K), .y_row = @intCast(H * c.v_dim), .sums_row = @intCast(H), .x_batch = @intCast(K), .y_batch = @intCast(c.v_dim), .sums_batch = 1, .w_batch = @intCast(per) });
affine_mm.denseBatch(e, p.mm.mm_bf16, p.att, q, p.vals, M, H, .{ .x_row = @intCast(H * K), .y_row = @intCast(H * c.v_dim), .x_batch = @intCast(K), .y_batch = @intCast(c.v_dim), .w_batch = @intCast(per) });
}

/// `n` rows' key lists from their index scores over every pooled block they read (positions p0..), the scores on the tensor units.
Expand Down Expand Up @@ -423,7 +412,6 @@ fn mla(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, mi: usize, w:
c.mla_heads,
.{ .in = p.qp, .ldx = c.qrProj(), .out = p.ql, .ldo = c.mla_heads * c.kv_lora, .rows = M },
c.nope,
p.sums,
); // mlx-lm's embed_q
} else if (fwd.on(x, "mla_absorb")) {
e.setPipeline(if (c.tp > 1) x.k.absorb_nax_tp else x.k.absorb_nax); // the row kernel's qvm, weights in three bf16 parts
Expand Down
13 changes: 3 additions & 10 deletions zig/src/families/glm/wide.zig
Original file line number Diff line number Diff line change
Expand Up @@ -241,19 +241,16 @@ pub fn perHead(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, heads: u32, io
}

/// A chunk's x slices (`kx` apart) through q's heads into out [rows, heads, n / heads]: one affine_mm batch, else rows.
pub fn headsBatch(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, h: u32, io: Io, kx: u32, sums: Ref) void {
pub fn headsBatch(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, h: u32, io: Io, kx: u32) void {
const ny = q.n / h;
const pipes = mm(p, q) orelse return perHead(p, e, q, h, io, kx, ny);
var head = q;
head.n = ny;
affine_mm.rowSumsAt(e, pipes, 64, io.in, sums, io.rows, h * kx, io.ldx); // a head's sums one row apart
affine_mm.denseBatch(e, pipes, io.in, sums, head, io.out, io.rows, h, .{
affine_mm.denseBatch(e, pipes, io.in, head, io.out, io.rows, h, .{
.x_row = @intCast(io.ldx),
.y_row = @intCast(io.ldo),
.sums_row = @intCast(h),
.x_batch = @intCast(kx),
.y_batch = @intCast(ny),
.sums_batch = 1,
.w_batch = @intCast(ny),
});
}
Expand Down Expand Up @@ -398,8 +395,7 @@ pub fn mm(p: *const Pipes, q: Affine) ?affine_mm.Pipes {
}

/// A chunk's product into io.out: each member on affine_mm at its width if it fills 64-row tiles, else the row kernels.
pub fn denseMm(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, io: Io, sums: Ref) void {
var summed = false;
pub fn denseMm(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, io: Io) void {
for (0..@as(usize, q.more) + 1) |i| {
const r = q.run(i);
const one: Affine = .{ .w = r.w, .s = r.s, .b = r.b, .n = r.n, .k = q.k, .bits = r.bits, .group = r.group };
Expand All @@ -409,13 +405,10 @@ pub fn denseMm(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, io: Io, sums:
dense(p, e, one, part);
continue;
};
if (!summed) affine_mm.rowSumsAt(e, pipes, 64, io.in, sums, io.rows, q.k, io.ldx); // every member's: one k, g64
summed = true;
affine_mm.denseBatch(
e,
pipes,
io.in,
sums,
one,
part.out,
io.rows,
Expand Down
Loading
Loading