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 31B served natively on Metal: registered as gemma4, served gr…
…eedy replies equal to the Python reference

native/gemma4.zig serves the dense 31B on the lane host (context 32,768 by default); metal.zig registers gemma4 in
mlx-q4g64 and refuses --speed-up and --learn for it by name; the tests that took gemma4 as an unserved type use
gemma4_unified, which still is. gemma4_gate.py served: on an M5 Ultra the four prompts' greedy token SHAs equal the
oracle's alone, with drafts and four at once; thinking stays in reasoning_content and a tool call parses.
docs/recipes/gemma-4-native.md is the recipe; docs/credits.md credits gilby's #360 and cshintov's #10.
  • Loading branch information
BobClawblaw committed Oct 14, 2026
commit e96fa2dd72d4ea84aea3da973b43af75a6783fe0
4 changes: 2 additions & 2 deletions app/electron/agent/engine/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,14 @@ async function main() {
assert.equal(parseVersion((await runEngineCli(h.binary, ['--version'], h.env)).stdout), '1.0.7')
assert.deepEqual(parseModelsOutput((await runEngineCli(h.binary, ['models'], h.env)).stdout), [])
await seedModel(h.hub, 'mlx-community/Qwen3.5-2B-MLX-4bit', { bytes: 4096 })
await seedModel(h.hub, 'Org/Gemma', { modelType: 'gemma4' })
await seedModel(h.hub, 'Org/Gemma', { modelType: 'gemma4_unified' })
assert.deepEqual(parseModelsOutput((await runEngineCli(h.binary, ['models'], h.env)).stdout).map((m) => m.repo), ['mlx-community/Qwen3.5-2B-MLX-4bit'])
const ok = await runEngineCli(h.binary, ['info', 'mlx-community/Qwen3.5-2B-MLX-4bit'], h.env)
assert.equal(ok.code, 0)
assert.equal(parseInfoOutput(ok.stdout).format, '4-bit, group 64')
const refused = await runEngineCli(h.binary, ['info', 'Org/Gemma'], h.env)
assert.equal(refused.code, 1)
assert.match(refused.stdout, /no registered Zig family serves model_type gemma4/)
assert.match(refused.stdout, /no registered Zig family serves model_type gemma4_unified/)
await assert.rejects(() => runEngineCli({ command: '/nonexistent/tensorfold-native', args: [] }, ['--version'], h.env), /Could not run tensorfold-native/)
} finally {
await h.cleanup()
Expand Down
4 changes: 2 additions & 2 deletions app/electron/agent/engine/hub.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,10 @@ async function main() {
assert.equal(installed.verdict, 'installed')

// Unsupported family, and a drafter on its own.
const gemma = mockHub(repoRoutes('google/gemma-9', { modelType: 'gemma4' }))
const gemma = mockHub(repoRoutes('google/gemma-9', { modelType: 'gemma4_unified' }))
const unsupported = await preflightRepo('google/gemma-9', null, context(gemma.fetchImpl))
assert.equal(unsupported.verdict, 'unsupported')
assert.match(unsupported.reasons[0], /serves no gemma4 family/)
assert.match(unsupported.reasons[0], /serves no gemma4_unified family/)
const drafterOnly = mockHub(repoRoutes('z-lab/Qwen3.8-27B-DFlash2', { dflash: true }))
assert.equal((await preflightRepo('z-lab/Qwen3.8-27B-DFlash2', null, context(drafterOnly.fetchImpl))).verdict, 'unsupported')

Expand Down
6 changes: 3 additions & 3 deletions app/electron/agent/engine/model-revisions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ function reviewedFetch(options: { invalidSha?: boolean; missingDrafter?: boolean
if (route === `/api/models/${REPO}/revision/unsupported`) body = { sha: OTHER }
if ([`/api/models/${REPO}/tree/${SHA}`, `/api/models/${REPO}/tree/${OTHER}`].includes(route)) body = [{ type: 'file', path: 'model.safetensors', size: 8192 }]
if (route === `/${REPO}/resolve/${SHA}/config.json`) body = { model_type: 'qwen3_5', quantization: { bits: 4, group_size: 64 } }
if (route === `/${REPO}/resolve/${OTHER}/config.json`) body = { model_type: 'gemma4' }
if (route === `/${REPO}/resolve/${OTHER}/config.json`) body = { model_type: 'gemma4_unified' }
return body ? new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json' } }) : new Response('missing', { status: 404 })
}) as typeof fetch
}
Expand All @@ -45,7 +45,7 @@ async function main() {
const pull = (await h.records()).find((r) => r.kind === 'pull')
assert.equal(pull.revision, SHA, 'the actual child must pull the immutable checkpoint whose format and memory were reviewed')
await service.preflight(REPO) // Re-populate the main-review cache after the completed pull invalidates it.
await assert.rejects(() => service.pull(REPO, 'unsupported'), /serves no gemma4/, 'a cached main preflight cannot authorize another revision')
await assert.rejects(() => service.pull(REPO, 'unsupported'), /serves no gemma4_unified/, 'a cached main preflight cannot authorize another revision')

const registry = path.join(h.root, 'engine', 'model-revisions.json')
const persisted = JSON.parse(await fs.readFile(registry, 'utf8'))
Expand All @@ -71,7 +71,7 @@ async function main() {
assert.equal(serve.args[serve.args.indexOf('--name') + 1], REPO, 'logical model identity is preserved for the API')
await assert.rejects(() => restarted.pull(REPO), /Unload/, 'a pull cannot change a currently serving selection')
await restarted.unload()
await seedModel(h.hub, REPO, { modelType: 'gemma4' })
await seedModel(h.hub, REPO, { modelType: 'gemma4_unified' })
const beforeRef = await fs.readFile(ref, 'utf8')
restarted = fresh()
assert.equal((await restarted.installed())[0].modelType, 'qwen3_5')
Expand Down
4 changes: 2 additions & 2 deletions app/electron/agent/engine/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ async function main() {
await assert.rejects(() => offline.search('qwen'), /HF_HUB_OFFLINE/)

// Unsupported repos are refused before any pull starts.
const refusing = new EngineService({ binaryPath: '/fake/tensorfold-native', binary: h.binary, appHome: h.root, childEnv: h.env, fetch: hubFetch('google/gemma-9', 1024, 'gemma4'), totalMemoryBytes: 32 * GIB, emit: () => {} })
await assert.rejects(() => refusing.pull('google/gemma-9'), /serves no gemma4 family/)
const refusing = new EngineService({ binaryPath: '/fake/tensorfold-native', binary: h.binary, appHome: h.root, childEnv: h.env, fetch: hubFetch('google/gemma-9', 1024, 'gemma4_unified'), totalMemoryBytes: 32 * GIB, emit: () => {} })
await assert.rejects(() => refusing.pull('google/gemma-9'), /serves no gemma4_unified family/)
await assert.rejects(() => refusing.pull('../../etc'), /owner\/name/)

// Load, then delete is refused until unloaded; delete removes only the cache folder.
Expand Down
5 changes: 4 additions & 1 deletion docs/credits.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ contributions are in it.
[prefill.py](https://github.com/ashhart/TensorFold/blob/v0.6.6/src/tensorfold/kernels/qwen/flash_next/v1/prefill.py)).
The native hyper-connection prompt kernels in `zig/kernels/metal/prefill/fn_prompt.metal` are the #29 kernels, and
`fn_attn.metal` reads only each row's selected blocks and tail, as the #29 attention did.
- @gilby wrote the dense Gemma 4 31B decode (`attn_tail`, `dense_tail`, the ring cache) in
[#360](https://github.com/ashhart/TensorFold/pull/360), the native port's reference and source of its glue.
- @gilby applied an n-gram table's `weight_scale` at lookup in [#148](https://github.com/ashhart/TensorFold/pull/148)
([embed.py](https://github.com/ashhart/TensorFold/blob/v0.6.6/src/tensorfold/kernels/qwen/flash_next/v1/embed.py)),
so oQ checkpoints of Flash Next load. The native `zig/src/families/flashnext/ple_scale.zig` applies the same rule.
Expand Down Expand Up @@ -169,7 +171,8 @@ credited here.
Flash Next vision patch adapted in #146), @mgoldwasser ([#101](https://github.com/ashhart/TensorFold/pull/101)),
@shantanugoel ([#146](https://github.com/ashhart/TensorFold/pull/146)), @BobClawblaw
([#473](https://github.com/ashhart/TensorFold/pull/473)).
- Model families: @cshintov (Gemma 4 in [#10](https://github.com/ashhart/TensorFold/pull/10), Qwen3.6 MoE on Macs in
- Model families: @cshintov (Gemma 4 in [#10](https://github.com/ashhart/TensorFold/pull/10), whose kernels the native
dense 31B carries, Qwen3.6 MoE on Macs in
[#138](https://github.com/ashhart/TensorFold/pull/138)), @di37 ([#224](https://github.com/ashhart/TensorFold/pull/224)),
@philip-pentatonic (Qwen3.6 on CUDA in [#78](https://github.com/ashhart/TensorFold/pull/78) and
[#84](https://github.com/ashhart/TensorFold/pull/84)), @BHCC2025 ([#270](https://github.com/ashhart/TensorFold/pull/270)).
Expand Down
1 change: 1 addition & 0 deletions docs/recipes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ the native engine, or the Python engine frozen at 0.6.6.
| Ternary Bonsai 2 27B | [MLX](ternary-bonsai-2.md) |
| GLM-5.3-Flash | [MLX on a 256 GB Mac, two-rank CUDA](glm-5.3-flash.md) |
| Gemma 4 26B-A4B | [MLX, fused one-row decode](gemma-4.md) |
| Gemma 4 31B | [Native Metal, affine 4-bit](gemma-4-native.md) |
| DeepSeek-V4-Flash | [MLX on a 256 GB Mac, DSpark and MTP drafts](deepseek-v4-flash.md) |
| Qwen3.6-35B-A3B | [MLX with MTP drafts, one-GPU CUDA](qwen3.6-moe.md) |

Expand Down
63 changes: 63 additions & 0 deletions docs/recipes/gemma-4-native.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Gemma 4 31B, native Metal

This recipe covers text generation with
[`mlx-community/gemma-4-31B-it-4bit`](https://huggingface.co/mlx-community/gemma-4-31B-it-4bit/tree/696d436c404745a59f30e4939a658162b0a9e57f),
revision `696d436c404745a59f30e4939a658162b0a9e57f`, the dense 31B in MLX affine 4-bit, groups of 64.
Build from `main` with Zig **0.17.0** and Xcode's Metal toolchain, as described in
[the native preview](../../ZIG-PREVIEW.md#build).

```bash
hf download mlx-community/gemma-4-31B-it-4bit --revision 696d436c404745a59f30e4939a658162b0a9e57f \
--local-dir "$HOME/models/gemma-4-31b"
zig build native -Dcpu=apple_m1
zig-out/native/bin/tensorfold-native serve "$HOME/models/gemma-4-31b" --port 8888 --parallel 4
```

The loader admits the dense 31B's geometry only: 60 layers, five sliding-window layers (window 1,024, head dim 256)
to each global one (head dim 512, keys reused as values, proportional RoPE), GeGLU, the tied 262,144-token head with
its logit soft-cap, uniform affine 4-bit in groups of 64. It refuses the 26B-A4B MoE, the 12B (`gemma4_unified`),
per-layer inputs, shared KV layers and per-module widths, each by name. The vision tower is not loaded.

Every linear, the tied head included, runs on the core lane projection (`zig/src/core/lane_projection.zig`) on M5
tensor units; the rest of a layer is `zig/kernels/metal/gemma4/glue.metal`. The glue ports the Python reference's
decode kernels (gilby's `gemma4-dense` branch, #360, built on cshintov's Gemma kernels from #10) with their rounding
points, and MLX's own ops where that reference calls them: the looped RMS norm, the 4-bit embedding times its bf16
scale, `geglu` and the soft-cap as bf16 ops, and the global layers' RoPE frequencies from MLX's precise `pow`.
Each output equals the reference's bit for bit at 1, 2 and 16 rows (`tf-gemma4-kernels`, `tf-gemma4-glue`, on
fixtures from `tools/zig/gemma4_dump.py`).

A stream keeps a ring of window + 128 slots for each sliding layer and a buffer for each global one; rolling back is
moving the cache's length. A forward takes up to 16 rows, from one stream or several, and every row keeps its bits.
Prompts run in 16-row decode windows. Drafts are context copies; the checkpoint has no draft head.

The context defaults to 32,768 tokens; `--context` raises it to the checkpoint's 262,144, at the cost of attention
scratch that grows with it. There is no cross-request prompt reuse yet.

| Checkpoint / platform | Qualification |
| --- | --- |
| The pinned 31B 4-bit, M5 Ultra, macOS 27 | Greedy decode, prompts, shared rounds, copy drafts and the server, below. |
| M1 to M4 | Refused: the lane projection needs M5 tensor units. |
| Other Gemma 4 checkpoints, widths, vision | Outside this recipe. |

## Verification

The oracle is gilby's `gemma4-dense` Python engine (`a6ff795e`, MLX 0.32.3, mlx-lm 0.32.0) with lane kernels.

```bash
python tools/zig/gemma4_gate.py oracle --model M --out O --tokens 128 --prompt decode # in the oracle's venv
zig-out/bin/tf-gemma4-run M O N 128 16 && python tools/zig/gemma4_gate.py check --oracle O --native N
zig-out/bin/tf-gemma4-lanes M O
python tools/zig/gemma4_gate.py served --oracle O --url http://127.0.0.1:8888
```

- Four chat prompts, 128 greedy tokens: every token and every top-two logit equals the oracle's, with prompts fed one
row at a time or in windows of 16.
- 8k and 32k prompts against the oracle's mlx-lm prompt forward: the first token is equal at both, and 49 tokens at
32k. At 8k the two part at token 32 on a tie within two bf16 steps; there the native run equals the oracle's own
decode-path prompt, tokens and last-row logits, and that path parts from mlx-lm at the same token.
- The lane core: plain and copy-drafted streams, and 4 and 8 streams in shared rounds, equal the oracle's tokens;
on copy-heavy prompts (11.1 and 3.3 tokens a round) drafted replies equal the engine's plain ones.
- Served on an M5 Ultra: greedy token SHAs equal the oracle's alone, with drafts and four at once; thinking replies
keep their reasoning apart, and tool calls parse.

Decode is about 33 tokens a second for one stream and 147 for eight together; prompts run at 240-340 tokens a second.
2 changes: 1 addition & 1 deletion docs/recipes/gemma-4.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ This page describes the Python engine's `gemma4` family, frozen at 0.6.6 and ava
[`v0.6.6` tag](https://github.com/ashhart/TensorFold/tree/v0.6.6); the packages, tools and tests it names are at that
tag. @cshintov wrote the family and its fused one-row kernels in [#10](https://github.com/ashhart/TensorFold/pull/10),
and @di37 made its `qkv_rows` kernel launch on M1 and M2 in [#224](https://github.com/ashhart/TensorFold/pull/224).
The native binary has no Gemma 4 family yet, so `tensorfold pull` and `tensorfold info` refuse the checkpoint.
The native binary serves the dense 31B ([Gemma 4 31B, native Metal](gemma-4-native.md)); it refuses the 26B-A4B.

Measured on an M4 Pro with 64 GB (273 GB/s) and MLX 0.31.2, with `mlx-community/gemma-4-26b-a4b-it-4bit`.
Packages: [`src/tensorfold/families/gemma4/`](https://github.com/ashhart/TensorFold/tree/v0.6.6/src/tensorfold/families/gemma4)
Expand Down
59 changes: 58 additions & 1 deletion tools/zig/gemma4_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,60 @@ def check(args: argparse.Namespace) -> None:
raise SystemExit(1)


def post(url: str, path: str, body: dict) -> dict:
from urllib.request import Request, urlopen

request = Request(url.rstrip("/") + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
with urlopen(request, timeout=900) as response:
return json.load(response)


def served(args: argparse.Namespace) -> None:
"""The served model's greedy replies equal the oracle's, alone and four at once; thinking and tool calls parse."""
import hashlib
from concurrent.futures import ThreadPoolExecutor

names = sorted(p.name.removesuffix(".reference.json") for p in args.oracle.glob("*.reference.json"))
want = {n: json.loads((args.oracle / f"{n}.reference.json").read_text()) for n in names}
ids = {n: json.loads((args.oracle / f"{n}.ids.json").read_text()) for n in names}

def one(name: str, draft: bool) -> tuple[str, bool]:
got = post(args.url, "/v1/completions", {"model": "gemma", "prompt": ids[name], "max_tokens": len(want[name]),
"temperature": 0, "draft": draft, "ignore_eos": True})
digest = hashlib.sha256(",".join(str(t) for t in want[name]).encode()).hexdigest()[:12]
return got.get("tensorfold", {}).get("token_sha", ""), got.get("tensorfold", {}).get("token_sha") == digest

failed = 0
for draft in (False, True):
for name in names:
sha, ok = one(name, draft)
failed += not ok
print(f"{'ok ' if ok else 'FAIL'} alone, drafts {'on ' if draft else 'off'}: {name} {sha}", flush=True)
with ThreadPoolExecutor(len(names)) as pool:
for name, (sha, ok) in zip(names, pool.map(lambda n: one(n, True), names)):
failed += not ok
print(f"{'ok ' if ok else 'FAIL'} four at once: {name} {sha}", flush=True)
think = post(args.url, "/v1/chat/completions", {"model": "gemma", "max_tokens": 400, "temperature": 0,
"chat_template_kwargs": {"enable_thinking": True},
"messages": [{"role": "user", "content": "What is 17 * 23? Think first."}]})
msg = think["choices"][0]["message"]
ok = bool(msg.get("reasoning_content")) and "391" in (msg.get("content") or "") and "<|channel>" not in (msg.get("content") or "")
failed += not ok
print(f"{'ok ' if ok else 'FAIL'} thinking apart from the answer: {len(msg.get('reasoning_content') or '')} reasoning chars, answer {(msg.get('content') or '')[:60]!r}")
tools = [{"type": "function", "function": {"name": "get_weather", "description": "Weather for a city",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}},
"required": ["city"]}}}]
call = post(args.url, "/v1/chat/completions", {"model": "gemma", "max_tokens": 200, "temperature": 0, "tools": tools,
"messages": [{"role": "user", "content": "What's the weather in Lisbon?"}]})
calls = call["choices"][0]["message"].get("tool_calls") or []
ok = len(calls) == 1 and calls[0]["function"]["name"] == "get_weather" and "Lisbon" in calls[0]["function"]["arguments"]
failed += not ok
print(f"{'ok ' if ok else 'FAIL'} tool call: {[c['function'] for c in calls]}")
print("PASS" if not failed else f"FAIL: {failed}")
if failed:
raise SystemExit(1)


def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="mode", required=True)
Expand All @@ -145,11 +199,14 @@ def main() -> None:
p.add_argument("--model", type=Path, required=True)
p.add_argument("--out", type=Path, required=True)
p.add_argument("--sizes", type=int, nargs="+", default=[8192, 32768])
v = sub.add_parser("served")
v.add_argument("--url", default="http://127.0.0.1:8888")
v.add_argument("--oracle", type=Path, required=True)
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, "prompts": prompts, "check": check}[args.mode](args)
{"oracle": oracle, "prompts": prompts, "served": served, "check": check}[args.mode](args)


if __name__ == "__main__":
Expand Down
3 changes: 2 additions & 1 deletion zig/src/cli/hub.zig
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const titles = [_]struct { model_type: []const u8, title: []const u8 }{
.{ .model_type = "qwen4_exp", .title = "Qwen3.8 Flash Next" },
.{ .model_type = "glm5_next", .title = "GLM-5.3-Flash" },
.{ .model_type = "qwen3_5", .title = "Qwen3.5-2B or Qwen3.8-27B" },
.{ .model_type = "gemma4", .title = "Gemma 4 31B" },
};

/// The family that serves `model_type` from the engine registry, or null when Zig cannot serve it (the 0.6 line may).
Expand Down Expand Up @@ -168,7 +169,7 @@ fn readSmall(a: Allocator, io: std.Io, path: []const u8) ?[]u8 {
test "family detection matches the registry and refuses unknown types" {
try std.testing.expectEqualStrings("Nemotron 3.5 Lightning", family("nemotron_h").?.title);
try std.testing.expectEqualStrings("Qwen3.8 Flash Next", family("qwen4_exp").?.title);
try std.testing.expect(family("gemma4") == null);
try std.testing.expect(family("gemma4_unified") == null);
try std.testing.expect(family("unknown") == null);
}

Expand Down
4 changes: 2 additions & 2 deletions zig/src/cli/info.zig
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ test "info prints family, format, context, weights and floor for a cached checkp

var refused: std.Io.Writer.Allocating = .init(a);
try w.createDirPath(io, try std.fs.path.join(a, &.{ root, "models--Org--Draft/snapshots/rev2" }));
try w.writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ root, "models--Org--Draft/snapshots/rev2/config.json" }), .data = "{\"model_type\": \"gemma4\"}" });
try w.writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ root, "models--Org--Draft/snapshots/rev2/config.json" }), .data = "{\"model_type\": \"gemma4_unified\"}" });
try std.testing.expectEqual(@as(u8, 1), try run(a, io, &refused.writer, null, root, "Org/Draft"));
try std.testing.expect(has(refused.written(), "no registered Zig family serves model_type gemma4"));
try std.testing.expect(has(refused.written(), "no registered Zig family serves model_type gemma4_unified"));
}

fn has(text: []const u8, needle: []const u8) bool {
Expand Down
Loading