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
Next Next commit
Gemma 4 dense: the 31B's config admission and a token oracle from gil…
…by's gemma4-dense Python engine

config.zig pins the 31B 4-bit geometry and names each layout it refuses (MoE, the 12B unified, per-layer inputs,
shared KV, keys apart from values, per-module widths); tools/zig/gemma4_gate.py records greedy ids and top-two
margins from gilby's RowDecode (lane kernels) through either prompt path, and compares a native run with them.
  • Loading branch information
BobClawblaw committed Oct 14, 2026
commit 51c9ccfd93d720c9e5958beda8ade4e494f0f91f
130 changes: 130 additions & 0 deletions tools/zig/gemma4_gate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"""Gemma 4 dense token oracle (gilby's gemma4-dense Python engine, lane kernels) and the native engine's checks."""
from __future__ import annotations

import argparse
import json
import platform
import time
from pathlib import Path

PROMPTS = {
"copy": "Reply with exactly: The quick brown fox jumps over the lazy dog.",
"arithmetic": "Compute 37 times 19 and explain the calculation briefly.",
"story": "Write a short story about a lighthouse keeper finding a message in a bottle.",
"code": "Write a Python function that returns the first n Fibonacci numbers.",
}


def first_difference(a: list[int], b: list[int]) -> int | None:
for i, (x, y) in enumerate(zip(a, b)):
if x != y:
return i
return min(len(a), len(b)) if len(a) != len(b) else None


def environment() -> dict:
import mlx.core as mx
import mlx_lm
import tensorfold

return {"mlx": mx.__version__, "mlx_lm": mlx_lm.__version__, "tensorfold": tensorfold.__version__,
"device": mx.metal.device_info().get("device_name", ""), "macos": platform.mac_ver()[0]}


def chat_ids(tokenizer, text: str) -> list[int]:
return list(tokenizer.apply_chat_template([{"role": "user", "content": text}], tokenize=True,
add_generation_prompt=True, enable_thinking=False))


def greedy(family, ids: list[int], count: int, prompt: str) -> tuple[list[int], list[dict]]:
"""`count` greedy tokens after `ids`; the prompt through mlx_lm's forward ("mlx") or one decode row a token."""
import mlx.core as mx

from qwen27_margins import capture

cache = family.make_cache()
if prompt == "mlx":
hidden = family.prefill(mx.array([ids]), cache)[:, -1:]
else:
for token in ids[:-1]:
mx.eval(family.hidden(mx.array([token]), cache))
hidden = family.hidden(mx.array([ids[-1]]), cache)
tokens, top2 = [], []
for step in range(count):
logits = family.head(hidden)
mx.eval(logits)
top2.extend(capture(logits, [len(ids) + step]))
token = top2[-1]["ids"][0]
tokens.append(token)
hidden = family.hidden(mx.array([token]), cache)
return tokens, top2


def oracle(args: argparse.Namespace) -> None:
import tensorfold

if tensorfold.__version__ != "0.6.5":
raise SystemExit(f"Need gilby's gemma4-dense branch (tensorfold 0.6.5), got {tensorfold.__version__}")
from tensorfold.families.gemma4.model import load

family, tokenizer = load(args.model, backend="lane", check=False)
out = args.out
out.mkdir(parents=True, exist_ok=False)
prompts = json.loads(args.ids.read_text()) if args.ids else {n: chat_ids(tokenizer, t) for n, t in PROMPTS.items()}
results = {}
for name, ids in prompts.items():
(out / f"{name}.ids.json").write_text(json.dumps(ids) + "\n")
started = time.perf_counter()
tokens, top2 = greedy(family, ids, args.tokens, args.prompt)
results[name] = {"tokens": tokens, "elapsed_s": round(time.perf_counter() - started, 3)}
(out / f"{name}.reference.json").write_text(json.dumps(tokens) + "\n")
(out / f"{name}.top2.json").write_text(json.dumps(top2) + "\n")
print(f"{name}: {len(ids)} prompt tokens, {tokenizer.decode(tokens)[:80]!r}", flush=True)
receipt = {"environment": environment(), "model": str(args.model), "prompt_path": args.prompt,
"decode": family.decode.backend, "kinds": sorted({k for p in family.decode.qkv for k in p.kinds}),
"tokens": args.tokens, "results": results}
(out / "oracle.json").write_text(json.dumps(receipt, indent=1) + "\n")


def check(args: argparse.Namespace) -> None:
"""Compare a native run's tokens and top-two margins with the oracle's, prompt by prompt."""
from qwen27_margins import verdict

oracle_dir, native_dir = args.oracle, args.native
report, failed = {}, False
for ref in sorted(oracle_dir.glob("*.reference.json")):
name = ref.name.removesuffix(".reference.json")
want = json.loads(ref.read_text())
got = json.loads((native_dir / f"{name}.tokens.json").read_text())
at = first_difference(want, got)
entry = {"equal": at is None, "first_difference": at}
if at is not None and at < min(len(want), len(got)):
python = json.loads((oracle_dir / f"{name}.top2.json").read_text())[at]
native = json.loads((native_dir / f"{name}.top2.json").read_text())[at]
entry["margins"] = verdict(native, python, want[at], got[at])
failed |= at is not None
report[name] = entry
print(f"{name}: {'equal' if at is None else f'differs at {at}'}", flush=True)
(native_dir / "token-gate.json").write_text(json.dumps(report, indent=1) + "\n")
if failed:
raise SystemExit(1)


def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="mode", required=True)
o = sub.add_parser("oracle")
o.add_argument("--model", type=Path, required=True)
o.add_argument("--out", type=Path, required=True)
o.add_argument("--ids", type=Path, help="JSON {name: [ids]} in place of the four chat prompts")
o.add_argument("--tokens", type=int, default=128)
o.add_argument("--prompt", choices=("decode", "mlx"), default="decode")
c = sub.add_parser("check")
c.add_argument("--oracle", type=Path, required=True)
c.add_argument("--native", type=Path, required=True)
args = parser.parse_args()
{"oracle": oracle, "check": check}[args.mode](args)


if __name__ == "__main__":
main()
231 changes: 231 additions & 0 deletions zig/src/families/gemma4/config.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
//! Admission for dense Gemma 4 MLX affine checkpoints (the 31B): pinned geometry and format, each refusal named.
const std = @import("std");

pub const hidden = 5376;
pub const vocab = 262144;
pub const layers = 60;
pub const intermediate = 21504;
pub const query_heads = 32;
pub const sliding_kv_heads = 16;
pub const global_kv_heads = 4;
pub const sliding_dim = 256;
pub const global_dim = 512;
pub const window = 1024;
pub const group = 64;
pub const bits = 4;
pub const eps: f32 = 1e-6;
pub const softcap: f32 = 30.0;
pub const sliding_theta: f64 = 10000.0;
pub const global_theta: f64 = 1000000.0;
/// Pairs the global layers' proportional RoPE rotates: partial_rotary_factor 0.25 of 512 dims, in pairs.
pub const global_rotated = 64;

pub const Error = error{
BadGemmaConfig,
GemmaMoeNotServed,
GemmaUnifiedNotServed,
GemmaPerLayerInputsNotServed,
GemmaSharedKvNotServed,
GemmaKeysNotValues,
UnsupportedGemmaGeometry,
UnsupportedGemmaRotary,
UnsupportedGemmaQuantization,
} || std.mem.Allocator.Error || std.json.ParseError(std.json.Scanner);

pub const Config = struct {
context: usize,
eos: [4]u32 = .{ 0, 0, 0, 0 },
eos_count: usize = 0,

pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config {
const path = try std.fs.path.join(gpa, &.{ dir, "config.json" });
defer gpa.free(path);
const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22));
defer gpa.free(bytes);
return parse(gpa, bytes);
}
};

/// Whether layer `index` is a global (full attention) layer: every sixth, and the last.
pub fn global(index: usize) bool {
return index % 6 == 5;
}

/// A layer's head dim and key heads.
pub fn headDim(index: usize) usize {
return if (global(index)) global_dim else sliding_dim;
}

pub fn kvHeads(index: usize) usize {
return if (global(index)) global_kv_heads else sliding_kv_heads;
}

/// RoPE inverse frequencies for a layer kind, as float32 [dim / 2]: zero for pairs proportional RoPE leaves alone.
pub fn inverseFrequencies(is_global: bool, out: []f32) void {
const dim: f64 = if (is_global) global_dim else sliding_dim;
const theta = if (is_global) global_theta else sliding_theta;
for (out, 0..) |*f, i| {
const rotated = !is_global or i < global_rotated;
f.* = if (rotated) @floatCast(1.0 / std.math.pow(f64, theta, 2.0 * @as(f64, @floatFromInt(i)) / dim)) else 0.0;
}
}

fn object(v: std.json.Value) Error!std.json.ObjectMap {
return if (v == .object) v.object else error.BadGemmaConfig;
}

fn field(o: std.json.ObjectMap, key: []const u8) Error!std.json.Value {
return o.get(key) orelse error.BadGemmaConfig;
}

fn number(v: std.json.Value) Error!f64 {
return switch (v) {
.integer => |i| @floatFromInt(i),
.float => |f| f,
else => error.BadGemmaConfig,
};
}

fn integer(o: std.json.ObjectMap, key: []const u8) Error!i64 {
const v = try field(o, key);
return if (v == .integer) v.integer else error.BadGemmaConfig;
}

fn optionalInt(o: std.json.ObjectMap, key: []const u8) i64 {
const v = o.get(key) orelse return 0;
return if (v == .integer) v.integer else 0;
}

fn isString(v: ?std.json.Value, expected: []const u8) bool {
const s = v orelse return false;
return s == .string and std.mem.eql(u8, s.string, expected);
}

fn isTrue(o: std.json.ObjectMap, key: []const u8) bool {
const v = o.get(key) orelse return false;
return v == .bool and v.bool;
}

fn quantization(v: std.json.Value) Error!void {
const o = try object(v);
if (try integer(o, "bits") != bits or try integer(o, "group_size") != group) return error.UnsupportedGemmaQuantization;
var it = o.iterator();
while (it.next()) |e| {
const k = e.key_ptr.*;
if (std.mem.eql(u8, k, "mode")) {
if (!isString(e.value_ptr.*, "affine")) return error.UnsupportedGemmaQuantization;
} else if (!std.mem.eql(u8, k, "bits") and !std.mem.eql(u8, k, "group_size")) {
return error.UnsupportedGemmaQuantization; // a per-module width (oQ) is the mixed-width path's
}
}
}

fn rope(o: std.json.ObjectMap, kind: []const u8, kind_type: []const u8, theta: f64, partial: ?f64) Error!void {
const r = try object(try field(o, kind));
if (!isString(r.get("rope_type"), kind_type)) return error.UnsupportedGemmaRotary;
if (try number(try field(r, "rope_theta")) != theta) return error.UnsupportedGemmaRotary;
if (partial) |p| if (try number(try field(r, "partial_rotary_factor")) != p) return error.UnsupportedGemmaRotary;
}

fn eosIds(v: std.json.Value, c: *Config) void {
switch (v) {
.integer => |i| if (c.eos_count < c.eos.len) {
c.eos[c.eos_count] = @intCast(i);
c.eos_count += 1;
},
.array => |a| for (a.items) |x| eosIds(x, c),
else => {},
}
}

pub fn parse(gpa: std.mem.Allocator, bytes: []const u8) Error!Config {
const parsed = try std.json.parseFromSlice(std.json.Value, gpa, bytes, .{});
defer parsed.deinit();
const root = try object(parsed.value);
if (isString(root.get("model_type"), "gemma4_unified")) return error.GemmaUnifiedNotServed;
if (!isString(root.get("model_type"), "gemma4")) return error.BadGemmaConfig;
const text = try object(try field(root, "text_config"));
if (isTrue(text, "enable_moe_block")) return error.GemmaMoeNotServed;
if (optionalInt(text, "hidden_size_per_layer_input") != 0) return error.GemmaPerLayerInputsNotServed;
if (optionalInt(text, "num_kv_shared_layers") != 0) return error.GemmaSharedKvNotServed;
if (!isTrue(text, "attention_k_eq_v")) return error.GemmaKeysNotValues;
if (isTrue(text, "use_double_wide_mlp") or isTrue(text, "attention_bias")) return error.UnsupportedGemmaGeometry;
if (!isString(text.get("hidden_activation"), "gelu_pytorch_tanh")) return error.UnsupportedGemmaGeometry;
if (!isTrue(text, "tie_word_embeddings")) return error.UnsupportedGemmaGeometry;
const dims = .{
.{ "hidden_size", hidden }, .{ "vocab_size", vocab }, .{ "num_hidden_layers", layers },
.{ "intermediate_size", intermediate }, .{ "num_attention_heads", query_heads }, .{ "num_key_value_heads", sliding_kv_heads },
.{ "head_dim", sliding_dim }, .{ "global_head_dim", global_dim }, .{ "num_global_key_value_heads", global_kv_heads },
.{ "sliding_window", window },
};
inline for (dims) |d| if (try integer(text, d[0]) != d[1]) return error.UnsupportedGemmaGeometry;
if (try number(try field(text, "rms_norm_eps")) != 1e-6) return error.UnsupportedGemmaGeometry;
if (try number(try field(text, "final_logit_softcapping")) != softcap) return error.UnsupportedGemmaGeometry;
const types = try field(text, "layer_types");
if (types != .array or types.array.items.len != layers) return error.UnsupportedGemmaGeometry;
for (types.array.items, 0..) |kind, i| {
if (!isString(kind, if (global(i)) "full_attention" else "sliding_attention")) return error.UnsupportedGemmaGeometry;
}
const ropes = try object(try field(text, "rope_parameters"));
try rope(ropes, "sliding_attention", "default", sliding_theta, null);
try rope(ropes, "full_attention", "proportional", global_theta, 0.25);
try quantization(root.get("quantization") orelse return error.UnsupportedGemmaQuantization);
if (root.get("quantization_config")) |q| try quantization(q);
const context: usize = @intCast(try integer(text, "max_position_embeddings"));
if (context < 1 or context > 262144) return error.UnsupportedGemmaGeometry;
var c: Config = .{ .context = context };
eosIds(root.get("eos_token_id") orelse try field(text, "eos_token_id"), &c);
if (c.eos_count == 0) return error.BadGemmaConfig;
return c;
}

const fixture = @embedFile("fixtures/config.json");

fn edited(gpa: std.mem.Allocator, from: []const u8, to: []const u8) ![]u8 {
return std.mem.replaceOwned(u8, gpa, fixture, from, to);
}

test "the 31B 4-bit checkpoint's config is admitted, with its context and end tokens" {
const c = try parse(std.testing.allocator, fixture);
try std.testing.expectEqual(@as(usize, 262144), c.context);
try std.testing.expectEqualSlices(u32, &.{ 1, 106, 50 }, c.eos[0..c.eos_count]);
}

test "each other Gemma 4 layout is refused by name" {
const gpa = std.testing.allocator;
const cases = .{
.{ "\"enable_moe_block\": false", "\"enable_moe_block\": true", error.GemmaMoeNotServed },
.{ "\"model_type\": \"gemma4\"", "\"model_type\": \"gemma4_unified\"", error.GemmaUnifiedNotServed },
.{ "\"attention_k_eq_v\": true", "\"attention_k_eq_v\": false", error.GemmaKeysNotValues },
.{ "\"num_kv_shared_layers\": 0", "\"num_kv_shared_layers\": 18", error.GemmaSharedKvNotServed },
.{ "\"hidden_size_per_layer_input\": 0", "\"hidden_size_per_layer_input\": 256", error.GemmaPerLayerInputsNotServed },
.{ "\"sliding_window\": 1024", "\"sliding_window\": 512", error.UnsupportedGemmaGeometry },
};
inline for (cases) |c| {
const bytes = try edited(gpa, c[0], c[1]);
defer gpa.free(bytes);
try std.testing.expect(!std.mem.eql(u8, bytes, fixture));
try std.testing.expectError(c[2], parse(gpa, bytes));
}
}

test "a per-module width override is the mixed-width path's, refused here" {
const gpa = std.testing.allocator;
const bytes = try edited(gpa, "\"group_size\": 64,", "\"group_size\": 64, \"language_model.model.layers.0.mlp.down_proj\": {\"bits\": 8, \"group_size\": 64},");
defer gpa.free(bytes);
try std.testing.expect(!std.mem.eql(u8, bytes, fixture));
try std.testing.expectError(error.UnsupportedGemmaQuantization, parse(gpa, bytes));
}

test "layer kinds, head dims and the proportional RoPE table" {
try std.testing.expect(!global(0) and global(5) and global(59) and !global(58));
try std.testing.expectEqual(@as(usize, 512), headDim(11));
try std.testing.expectEqual(@as(usize, 16), kvHeads(1));
var g: [global_dim / 2]f32 = undefined;
inverseFrequencies(true, &g);
try std.testing.expectEqual(@as(f32, 1.0), g[0]);
try std.testing.expect(g[63] > 0 and g[64] == 0 and g[255] == 0);
var s: [sliding_dim / 2]f32 = undefined;
inverseFrequencies(false, &s);
try std.testing.expect(s[127] > 0 and s[127] < s[1]);
}
Loading