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
Merge main (TensorFold 1.0.12) into gemma4-native
#598 has landed with main's own image path, so Gemma 4 takes it: the server's wrap writes boi and eoi around an
image's rows (the pieces this branch added are gone), images decode through core's picture decoder, and the residency
set is Resident.hold's, whose keepalive tick runs a copy on the GPU. Info.vision keeps part_type, now carried by the
messages' Media, since Gemma 4's template writes <|image|> only for "image" parts. LFM2's prompt GEMMs take the core
affine_mm without row sums, as every other caller does since its weights are dequantized to bf16 in the tile. Both
sides load the tile's fragments in two 8-byte reads; this branch's am_tile_frag stays, since main's frag_get_tg form
of the same loads made Gemma 4's prompt GEMMs 11% slower (315 against 283 ms for a 512-row chunk at depth 8k).
  • Loading branch information
BobClawblaw committed Oct 16, 2026
commit 3338988a85bbc2300bf6b9308f7c1996bc4e6fef
4 changes: 3 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ chat fields that shape the prompt (`tools`, `reasoning_effort`, `chat_template_k
request, images and videos expanded. `/detokenize` takes `tokens` and returns `prompt`.
In the Python 0.6.6 engine, `--vision` lets supported Qwen3.5/3.8 dense checkpoints accept `image_url` content parts
alongside text in user messages and in tool results (`role: "tool"`), such as an agent's screenshots. The native
server reads images for GLM-5.3-Flash and Gemma 4 31B on Metal, with data URLs only ([image input](vision.md#the-native-server)).
server reads images for GLM-5.3-Flash, Qwen3.8-27B and Gemma 4 31B on Metal, with data URLs, and public HTTPS URLs under
`--vision-urls` ([image input](vision.md#the-native-server)); for GLM-5.3-Flash it also takes `video_url` parts in
user messages ([video](vision.md#video-on-the-native-server)).
See [image input](vision.md) for data URLs, public image URLs, limits and cache behavior.
The native binary refuses `--vision` for other models and answers their image parts with HTTP 400.
Unsupported image input, audio, video and non-text output requests receive HTTP 400.
Expand Down
7 changes: 2 additions & 5 deletions docs/known-issues.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,8 @@ release fixes it, and the release notes say which one.
greedy code drafts shallower, about 4% slower on an M3 Ultra. The tokens are the same.
- Qwen3.8-Flash-Next in speed-up mode: a drafted request right after a `"draft": false` one decodes slowly, and the next
request is back to speed. The tokens are the same.
- Qwen3.8-Flash-Next on a Mac: the first turn after the server has been idle for a few seconds takes about 2 s to its
first token on an M3 Ultra, even when its prompt is cached.
- Gemma 4 31B on a Mac: the first request after the server has been idle for six seconds or more takes 0.4-0.7 s to
its first token on an M5 Ultra, where a busy server takes 0.08 s. Its buffers are held in a residency set; the idle
keepalive's tick does no GPU work yet, and both are needed.
- Qwen3.8-Flash-Next on a Mac: a turn more than `--keep-warm` seconds after the last request (900 by default) takes
about 2 s to its first token on an M3 Ultra, even when its prompt is cached, while macOS wires the model again.
- On a Mac without tensor units (M1 to M4), Flash Next's uniform 6-bit checkpoint decodes different tokens from 1.0.9
since 1.0.10's faster products. `FZ_M3_LANES=1` keeps the earlier kernels and their tokens.

Expand Down
36 changes: 25 additions & 11 deletions docs/vision.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,17 +146,31 @@ For Qwen, each image request carries its own multimodal rotary positions and con
## The native server

`tensorfold-native serve` takes `--vision`, `--vision-max-images` (default 4) and `--vision-image-tokens` (default
4,096) for engines that read images; GLM-5.3-Flash and [Gemma 4 31B](recipes/gemma-4-native.md#images) on one Mac read
them so far, and other native engines refuse the flag at startup.

- Images arrive as `image_url` data URLs in user messages and tool results. Remote URLs are refused, since
`--vision-urls` isn't on the native server yet.
- PNG and JPEG are decoded by the platform's decoder (ImageIO on macOS). WebP is refused by name until a decoder
exists; other formats are refused.
- The limits and the processing are 0.6.6's: EXIF orientation, alpha composited over white, the model's processor's
sizing (GLM5-Next's, or Gemma 4's PIL processor) and PIL's bicubic resampler. Six drawn PNG fixtures give patches bit-equal to 0.6.6 with mlx-vlm
(`tools/zig/glm_vision_fixtures.py`). JPEG patches differ slightly, because ImageIO and libjpeg-turbo decode
differently.
4,096; 13,312 for Nemotron 3.5 Super VL) for engines that read images: GLM-5.3-Flash, Qwen3.8-27B and
[Gemma 4 31B](recipes/gemma-4-native.md#images) on one Mac, and Nemotron 3.5 Super VL on CUDA. Other native engines
refuse the flag at startup.

- Images arrive as `image_url` data URLs in user messages and tool results. With `--vision-urls` (it needs
`--vision`), a part may name a public HTTPS URL instead, fetched as 0.6.6 fetched it: port 443 without credentials
or a fragment; every address the host resolves to public (no private, loopback, link-local, carrier-grade NAT,
documentation, multicast or metadata address, and for IPv6 global unicast only, without 6to4 or Teredo); TLS
verified for the host against the system's certificates, on the address that was checked; up to 3 redirects,
each checked again; a declared `image/jpeg`, `image/png` or `image/webp`, uncompressed; 10 MB an image and 20 MB
a request across data URLs and downloads; 10 s a download and 30 s a request's downloads. The refusals are
0.6.6's words; a TLS failure, like any other failed connection, is "image download failed or timed out". Host
names that aren't ASCII and IPv6 address literals are refused. Without the flag, an HTTPS URL is refused with the
flag's name.
- PNG and JPEG are decoded to the pixels 0.6.6 decoded with Pillow 12.3 (`zig/src/core/picture/`, which d1-3B's
pictures on CUDA use too): PNG from the PNG specification, JPEG by libjpeg-turbo 3.1.4.1's TurboJPEG library
(`libturbojpeg`, the release Pillow 12.3 bundles) at Pillow's settings. TensorFold does not ship that library; the
server loads it at the first JPEG from the file `TENSORFOLD_LIBTURBOJPEG` names, else `lib/` beside the server's
folder, beside the server, Homebrew's `jpeg-turbo` on macOS, then the system's library path. It checks the version
libjpeg-turbo writes into the library and refuses JPEG images by name when the library is missing or another
release; PNG images still serve. WebP is refused by name until a decoder exists; other formats are refused.
- The limits and the processing are 0.6.6's: EXIF and XMP orientation, alpha composited over white, the model's
processor's sizing (GLM5-Next's, or Gemma 4's PIL processor) and Pillow's bicubic resampler. The decoder gives 0.6.6's pixels for every picture in
`zig/tests/fixtures/lfm2/images.json` and `zig/tests/fixtures/picture/edges.json`, except where it departs on
purpose: a CMYK JPEG is refused, and a JPEG holding several pictures (MPO) gives its first, which 0.6.6 refused.
- Images are counted from the request's image parts. A user or tool message whose text spells the model's image
markers (GLM's `<|image|>`, `<|begin_of_image|>`, `<|end_of_image|>`; Qwen's `<|vision_start|>`, `<|image_pad|>`,
`<|vision_end|>`) is tokenized as ordinary text, so only the chat template's own markers, one wrapper for each image
Expand Down
1 change: 1 addition & 0 deletions zig/kernels/metal/core/affine_mm.metal
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ inline void am_weights(thread const Codes& c, float s, float b, threadgroup bflo
}
}


// A lane's two rows (home.y and home.y + 8) of each of its TM fragments: their starts in x.
template <int TM>
struct AmRows {
Expand Down
1 change: 1 addition & 0 deletions zig/src/cli/hub.zig
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const titles = [_]struct { model_type: []const u8, title: []const u8 }{
.{ .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" },
.{ .model_type = "lfm2_moe", .title = "LFM2.5-24B-A2B" },
};

/// The family that serves `model_type` from the engine registry, or null when Zig cannot serve it (the 0.6 line may).
Expand Down
21 changes: 5 additions & 16 deletions zig/src/core/engine_api.zig
Original file line number Diff line number Diff line change
Expand Up @@ -110,18 +110,7 @@ pub const Request = struct {
};

/// An image prepared for the engine's tower (``Vision.prepare``): patches, patch grid, tokens and a content hash.
pub const PreparedImage = struct {
pixels: []f32,
gh: u32,
gw: u32,
tokens: u32,
hash: u64,
/// The image as tower inputs in order, each image tokens between `before` and `after`; empty: `pixels` alone.
pieces: []const Piece = &.{},
};

/// One tower input of an image, and the tokens the placeholder expands to around its rows.
pub const Piece = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, before: []const u32 = &.{}, after: []const u32 = &.{} };
pub const PreparedImage = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 };

/// Image input an engine serves (``Info.vision``): image bytes to tower input, and what a request may hold.
pub const Vision = struct {
Expand All @@ -132,10 +121,10 @@ pub const Vision = struct {
image_token: u32,
/// The tokens the template wraps an image in (the image token among them): text that spells one stays text.
markers: []const u32 = &.{},
/// The content part type the chat template looks for: "image_url" (OpenAI's) or "image" (most HF templates).
part_type: []const u8 = "image_url",
/// Image tokens one request may hold in all, and images.
image_tokens: u32,
part_type: []const u8 = "image_url", // the content part type the template reads: OpenAI's, or "image" (most HF ones)
/// Tokens the server writes around each image's rows (Nemotron Omni's <img> and </img>); null: the template's own.
wrap: ?[2]u32 = null,
image_tokens: u32, // the image tokens one request may hold in all, and its images
max_images: u32,
/// Video input, when the engine's family reads it.
video: ?VideoOffer = null,
Expand Down
30 changes: 17 additions & 13 deletions zig/src/families/gemma4/image.zig
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
//! An image's bytes to Gemma 4's tower inputs, as transformers' Gemma4ImageProcessorPil makes them.
const std = @import("std");
const img = @import("../glm/image.zig");
const picture = @import("../../core/picture/picture.zig");

pub const Error = img.Error || error{TooFewTokens};
/// The shared decoder's refusals, and sizes or budgets the processor cannot take.
pub const Error = picture.Error || error{ ImageTooSmall, ImageTooLarge, TooFewTokens };
pub const decoderProblem = picture.decoderProblem;

/// The processor's constants: patch side, the pooling kernel, and the soft-token budgets it accepts.
pub const patch = 16;
Expand Down Expand Up @@ -46,26 +48,28 @@ pub fn budget(max_tokens: u32) Error!u32 {
return best orelse error.TooFewTokens;
}

/// The image's bytes to its patches: resized with PIL's bicubic filter, scaled to [0, 1], patches in row order.
pub fn prepare(gpa: std.mem.Allocator, bytes: []const u8, max_tokens: u32) Error!Prepared {
/// Bytes to patches (core's picture decoder, Pillow's bicubic resize, [0, 1]); the hash covers the bytes and the grid.
pub fn prepare(io: std.Io, gpa: std.mem.Allocator, bytes: []const u8, max_tokens: u32) Error!Prepared {
const max_patches = try budget(max_tokens) * pool * pool;
var src = try img.decode(gpa, bytes);
var src = try picture.decode(io, gpa, bytes);
defer src.deinit(gpa);
const size = try targetSize(src.h, src.w, max_patches);
var scaled = if (size[0] == src.h and size[1] == src.w) src else try img.resize(gpa, src, size[1], size[0]);
defer if (scaled.px.ptr != src.px.ptr) scaled.deinit(gpa);
const size = try targetSize(@intCast(src.height), @intCast(src.width), max_patches);
const resized = try picture.resample.resize(gpa, .pillow, .of(src.pixels, src.width, src.height), size[1], size[0]);
defer gpa.free(resized);
const gh = size[0] / patch;
const gw = size[1] / patch;
return .{ .pixels = try patches(gpa, scaled), .gh = gh, .gw = gw, .tokens = gh * gw / (pool * pool), .hash = std.hash.Wyhash.hash(0x6e34, bytes) };
const grid = [2]u32{ gh, gw };
const hash = picture.identity.withGrid(picture.identity.ofBytes(0x6e34, bytes), grid);
return .{ .pixels = try patches(gpa, .{ .width = size[1], .height = size[0], .pixels = resized }), .gh = gh, .gw = gw, .tokens = gh * gw / (pool * pool), .hash = hash };
}

/// convert_image_to_patches after np_rescale (float64 times 1/255, then float32): a patch's pixels in row order, RGB.
fn patches(gpa: std.mem.Allocator, src: img.Rgb) Error![]f32 {
const gh = src.h / patch;
const gw = src.w / patch;
fn patches(gpa: std.mem.Allocator, src: picture.Rgb) Error![]f32 {
const gh = src.height / patch;
const gw = src.width / patch;
const out = try gpa.alloc(f32, @as(usize, gh) * gw * patch_width);
for (0..gh) |py| for (0..gw) |px| for (0..patch) |y| for (0..patch) |x| for (0..3) |c| {
const v = src.px[((py * patch + y) * src.w + px * patch + x) * 3 + c];
const v = src.pixels[((py * patch + y) * src.width + px * patch + x) * 3 + c];
out[(py * gw + px) * patch_width + (y * patch + x) * 3 + c] = @floatCast(@as(f64, @floatFromInt(v)) * (1.0 / 255.0));
};
return out;
Expand Down
14 changes: 4 additions & 10 deletions zig/src/families/lfm2_moe/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,11 @@ const Encoder = struct {
if (!self.prompt) return null;
return self.m.kernels.naxPipes(bits);
}
/// y[rows] = x[rows] W^T: the prompt tiles (on x's group sums), or their twin at decode and window rows.
/// y[rows] = x[rows] W^T: the tensor-unit prompt GEMM, else the tiles (on x's group sums) or their twin.
fn projection(self: Encoder, w: row.Weights, x: Buffer, x_off: usize, y: Buffer, y_off: usize, rows: usize) void {
const t = &self.m.kernels.tiles;
if (self.nax(w.bits)) |p| {
const xr = Ref{ .buf = x, .off = x_off };
const sums = Ref{ .buf = self.s.sums };
am.rowSums(self.e, p, c.group, xr, sums, @intCast(rows), @intCast(w.k));
am.dense(self.e, p, xr, sums, affine(w), Ref{ .buf = y, .off = y_off }, @intCast(rows));
am.dense(self.e, p, Ref{ .buf = x, .off = x_off }, affine(w), Ref{ .buf = y, .off = y_off }, @intCast(rows));
return;
}
if (self.prompt or !self.m.kernels.twin) {
Expand Down Expand Up @@ -289,16 +286,13 @@ fn moe(enc: Encoder, s: *st.Scratch, x: wts.Moe, scale: f32, total: usize) bool
enc.groups(.{ 1, 1, 1 }, .{ c.experts * 16, 1, 1 });
if (enc.nax(x.gate.one.bits)) |p| {
// Sorted slot j reads token row tokens[j]; gate and up SwiGLU'd into act, then down over act's sorted rows.
const sums = Ref{ .buf = s.sums };
const starts = Ref{ .buf = s.starts };
const act = Ref{ .buf = s.act };
am.rowSums(e, p, c.group, Ref{ .buf = s.x }, sums, @intCast(total), c.hidden);
const gate = affine(x.gate.one);
const up = affine(x.up.one);
const tokens = Ref{ .buf = s.tokens };
am.gatherGlu(e, p, Ref{ .buf = s.x }, sums, gate, up, starts, tokens, act, @intCast(slots), c.experts, 1, 0);
am.rowSums(e, p, c.group, act, sums, @intCast(slots), c.moe_intermediate);
am.gather(e, p, act, sums, affine(x.down.one), starts, Ref{ .buf = s.experts }, @intCast(slots), c.experts);
am.gatherGlu(e, p, Ref{ .buf = s.x }, gate, up, starts, tokens, act, @intCast(slots), c.experts, 1, 0);
am.gather(e, p, act, affine(x.down.one), starts, Ref{ .buf = s.experts }, @intCast(slots), c.experts);
} else {
tile.encodeWork(e, &enc.m.kernels.tiles, s.starts, c.experts, s.work);
tile.encodeSums(e, t, c.hidden, s.x, 0, s.sums, total);
Expand Down
21 changes: 11 additions & 10 deletions zig/src/native/gemma4.zig
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@ pub const takes_drafter = true;

const Host = struct {
gpa: std.mem.Allocator,
io: std.Io, // the image decoder's, on the HTTP thread
model: *g.Model,
metal: *g.backend.Metal,
draft: ?*g.dflash.Drafter = null,
wrap: ?lanes.drafted.Drafted = null,
warm: mtl.keepalive.Target = undefined, // the residency set's queue, for the lane host's idle ticker
resident: ?Resident = null, // weights, scratches, the drafter's and the tower's buffers, kept wired between requests
resident: ?Resident = null, // weights, scratches, the drafter's and the tower's buffers, wired between requests
config: lanes.Config,
clock: lanes.backend.WallClock,
core: lanes.Engine,
Expand Down Expand Up @@ -77,6 +78,7 @@ fn start(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open,
const h = try gpa.create(Host);
errdefer gpa.destroy(h);
h.gpa = gpa;
h.io = io;
h.model = model;
h.markers = .{ 255999, 258880, 258882 };
h.metal = try g.backend.Metal.init(gpa, io, model, .{ .capacity = @intCast(window), .streams = @max(o.lanes, 2) });
Expand All @@ -100,13 +102,14 @@ fn start(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open,
h.clock = .{ .io = io };
h.core = lanes.Engine.init(gpa, &h.config, if (h.wrap) |*w| w.backend() else h.metal.backend(), h.clock.clock());
errdefer h.core.deinit();
const vis: ?api.Vision = if (o.vision) |v| .{ .ctx = h, .prepare = prepareImage, .image_token = h.markers[1], .markers = &h.markers, .part_type = "image", .image_tokens = v.image_tokens, .max_images = v.max_images } else null;
const vis: ?api.Vision = if (o.vision) |v| .{ .ctx = h, .prepare = prepareImage, .image_token = h.markers[1], .markers = &h.markers, .wrap = .{ h.markers[0], h.markers[2] }, .part_type = "image", .image_tokens = v.image_tokens, .max_images = v.max_images, .explain = g.image.decoderProblem } else null;
h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = g.state.chunk_rows, .structures = true, .vision = vis });
h.cache = null;
try enableCache(h, a, o, @intCast(window), problem);
errdefer if (h.cache) |*store| store.deinit();
try holdResident(h);
errdefer h.resident.?.deinit();
h.warm = .{ .queue = model.queue };
holdResident(h) catch |err| std.log.warn("gemma4: no residency set ({s}); the first request after an idle second re-wires the weights", .{@errorName(err)});
errdefer if (h.resident) |*r| r.deinit();
h.host.keepalive_target = .{ .ctx = &h.warm, .tick = mtl.keepalive.Target.tick };
try h.host.start(); // the host's lists are empty until its thread runs, so a failed start leaves nothing to free
std.log.info("gemma4: the dense 31B, context {d} tokens, {d} streams{s}{s}", .{ window, @max(o.lanes, 2), if (h.draft != null) ", DFlash drafts" else "", if (vis != null) ", images" else "" });
Expand All @@ -128,7 +131,7 @@ fn holdResident(h: *Host) !void {
try buffersOf(h.gpa, &list, d);
}
if (m.vision) |v| try list.appendSlice(h.gpa, &.{ v.scratch, v.patches, v.cos, v.sin });
h.resident = try Resident.init(m.device, m.queue, list.items);
h.resident = try Resident.hold(h.gpa, h.io, m.device, m.queue, list.items, "gemma4") orelse return;
h.warm = (&h.resident.?).target();
}

Expand Down Expand Up @@ -193,11 +196,9 @@ fn enableCache(h: *Host, a: std.mem.Allocator, o: api.Open, window: usize, probl
h.host.info_.prompt_cache_plan = plan;
}

/// Info.vision's prepare (on the HTTP thread): the template writes <|image|> alone, so its rows go between boi and eoi.
/// Info.vision's prepare (on the HTTP thread); the template writes <|image|> alone: the server adds boi and eoi.
fn prepareImage(ctx: *anyopaque, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage {
const h: *Host = @ptrCast(@alignCast(ctx));
const p = try g.image.prepare(a, bytes, max_tokens);
const pieces = try a.alloc(api.Piece, 1);
pieces[0] = .{ .pixels = p.pixels, .gh = p.gh, .gw = p.gw, .tokens = p.tokens, .before = h.markers[0..1], .after = h.markers[2..3] };
return .{ .pixels = p.pixels, .gh = p.gh, .gw = p.gw, .tokens = p.tokens, .hash = p.hash, .pieces = pieces };
const p = try g.image.prepare(h.io, a, bytes, max_tokens);
return .{ .pixels = p.pixels, .gh = p.gh, .gw = p.gw, .tokens = p.tokens, .hash = p.hash };
}
Loading
You are viewing a condensed version of this merge commit. You can view the full changes here.