Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- CUDA and HIP: one core gate decides `--vision` at startup: `--vision` on a checkpoint without a vision tower is refused as "--vision given but this <model> checkpoint has no vision tower", on Qwen3.5 on HIP (which served text) and Flash Next on CUDA too; LFM2 on CUDA loads its tower only with `--vision`; a cluster model's `"vision"` that is not true or false is refused, and the System One picture refusal now says to start with `--vision` (#3456). Thanks to @jschmied.

- Qwen 3.5 diagnostics: large output files are written in chunks of at most 256 MiB, with the same bytes in the same order (#4296).

- Inkling 2 on HIP: attention kernels under the kernel contract (#N).

- Qwen3.6-35B-A3B on Metal: the text-only checkpoint serves on the routed expert path, `--vision` refuses it by name, and `tf-qwen27-run --stages DIR` writes each layer's stream for a float64 comparison (#3239). Thanks to @cshintov.
Expand Down
1 change: 1 addition & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ pub fn build(b: *std.Build) void {
@import("zig/build/save_guard.zig").wire(b);
@import("zig/build/cpu_contract.zig").steps(b, test_step);
@import("zig/build/bf16_round.zig").wire(b, test_step);
@import("zig/build/chunked_write.zig").wire(b, test_step);
@import("zig/build/qwen35_layers.zig").wire(b, test_step);
@import("zig/build/dev_tools.zig").wire(b, target);
@import("zig/build/profile.zig").wire(b, test_step);
Expand Down
3 changes: 3 additions & 0 deletions docs/vision.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@ that read images: GLM-5.3-Flash, Qwen3.8-27B, Qwen3.8 Flash Next, Gemma 4
[31B](recipes/gemma-4-native.md#images) and [12B](recipes/gemma-4-12b-native.md#images) and Step-5-Preview on one
Mac, GLM-5.3-Flash on [CUDA ranks](recipes/glm-5.3-flash-cuda.md#requests) and Nemotron 3.5 Super VL on CUDA. Other
native engines refuse the flag at startup.
On CUDA and HIP a tower loads only with `--vision`, d1-3B's pictures included; a checkpoint with a tower starts
text-only without it. `--vision` on a checkpoint without a tower is refused at startup as "--vision given but this
<model> checkpoint has no vision tower" (core's gate, `zig/src/core/engine_vision.zig`), on Qwen3.5 HIP too.
The CLI accepts explicit image budgets from 16 to 262,144 tokens; each engine still applies its own limits and memory admission.

- Images arrive as `image_url` data URLs in user messages and tool results. With `--vision-urls` (it needs
Expand Down
9 changes: 9 additions & 0 deletions zig/build/chunked_write.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//! Registers the chunked-writer host tests as `test-chunked-write`.
const std = @import("std");

pub fn wire(b: *std.Build, parent: *std.Build.Step) void {
const tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/core/chunked_write_test_file.zig"), .target = b.graph.host }) });
const step = b.step("test-chunked-write", "Bounded chunked output writes: cap respected, order preserved, the old one-shot path fails the enforcing sink");
step.dependOn(&b.addRunArtifact(tests).step);
parent.dependOn(step);
}
2 changes: 1 addition & 1 deletion zig/build/hip.zig
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ fn checksExe(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil
.target = target,
.optimize = optimize,
.link_libc = true,
.imports = &.{ .{ .name = "hip", .module = e.hip }, .{ .name = "qwen3_5", .module = e.family }, .{ .name = "lanes", .module = e.lanes }, .{ .name = "npy", .module = b.createModule(.{ .root_source_file = b.path("zig/npy_from_core.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "core", .module = e.hip.import_table.get("core").? }} }) } },
.imports = &.{ .{ .name = "hip", .module = e.hip }, .{ .name = "core", .module = e.hip.import_table.get("core").? }, .{ .name = "qwen3_5", .module = e.family }, .{ .name = "lanes", .module = e.lanes }, .{ .name = "npy", .module = b.createModule(.{ .root_source_file = b.path("zig/npy_from_core.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "core", .module = e.hip.import_table.get("core").? }} }) } },
}) });
}
fn clefExe(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, e: Engine) *std.Build.Step.Compile {
Expand Down
4 changes: 3 additions & 1 deletion zig/src/cluster/config.zig
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,9 @@ fn models(a: Allocator, v: ?Value, probs: *Problems) ![]Model {
if (str(o.get("mla"))) |split| {
if (std.mem.eql(u8, split, "heads")) m.mla = .heads else if (std.mem.eql(u8, split, "streams")) m.mla = .streams else if (!std.mem.eql(u8, split, "auto")) probs.add("models.{s}.mla: \"heads\", \"streams\" or \"auto\"", .{id});
}
if (o.get("vision")) |b| m.vision = b == .bool and b.bool;
if (o.get("vision")) |b| {
if (b == .bool) m.vision = b.bool else probs.add("models.{s}.vision: true or false", .{id});
}
if (o.get("memory")) |mem| if (mem == .object) if (num(mem.object.get("margin_gb"))) |g| {
m.margin = @intFromFloat(g * @as(f64, @floatFromInt(node.gib)));
};
Expand Down
1 change: 1 addition & 0 deletions zig/src/cluster/config_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ test "every broken file names what to change" {
try check(head ++ four ++ "\"models\":{\"k\":{\"path\":\"/m\",\"mode\":\"disaggregated\",\"prefill\":[\"c1\"],\"decode\":[\"c1\",\"zz\"]}}}", &.{ "both a prefill and a decode", "\"zz\" is not a node" });
try check(head ++ four ++ "\"models\":{\"k\":{\"path\":\"/m\",\"mode\":\"disaggregated\"}}}", &.{"needs \"prefill\" and \"decode\""});
try check(head ++ four ++ "\"models\":{\"k\":{\"nodes\":[\"m9\"],\"parallel\":{\"tensor\":\"many\"}}}}", &.{ "path: required", "\"m9\" is not a node", "or \"auto\"" });
try check(head ++ four ++ "\"models\":{\"k\":{\"path\":\"/m\",\"nodes\":[\"c1\"],\"vision\":\"yes\"}}}", &.{"vision: true or false"});
try check("{\"cluster\":1}", &.{ "schema: must be", "nodes: at least one" });
try check("not json", &.{"not JSON"});
}
Expand Down
18 changes: 16 additions & 2 deletions zig/src/core/checkpoint_weights.zig
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
//! Header-based admission bytes for the text side and optional RADIO tower, including mixed shards.
//! Header-based admission bytes for the text side and an optional vision tower, including mixed shards.
const std = @import("std");
const ck = @import("checkpoint.zig");
const st = @import("safetensors.zig");

/// Tower and projector prefixes: RADIO's, then Qwen-VL's, Gemma 4's, LFM2-VL's, LightOn's, DeepSeek's and GLM's.
const vision_prefixes = [_][]const u8{
"vision_model.", "vision_projector.", "mlp1.", "model.visual.", "visual.",
"vision_tower.", "model.vision_tower.", "vision_embedder.", "embed_vision.", "model.vision_model.",
"model.vision_encoder.", "model.vision_projection.", "vision.",
};

pub fn visionTensor(name: []const u8) bool {
for ([_][]const u8{ "vision_model.", "vision_projector.", "mlp1." }) |p|
for (vision_prefixes) |p|
if (std.mem.startsWith(u8, name, p)) return true;
return false;
}
Expand Down Expand Up @@ -50,3 +57,10 @@ test "text admission excludes RADIO tensors even in a shared shard" {
try std.testing.expectEqual(@as(u64, 8), try count(a, io, dir, false));
try std.testing.expectEqual(@as(u64, 24), try count(a, io, dir, true));
}

test "every family's tower prefix is a vision tensor, and no text tensor of theirs is" {
for ([_][]const u8{ "model.visual.blocks.0.attn.qkv.weight", "vision_tower.blocks.0.norm1.weight", "vision.blocks.3.mlp.w1.weight", "model.vision_model.embeddings.patch_embedding.weight", "model.vision_tower.vision_model.post_layernorm.weight", "vision_embedder.patch_dense.weight", "model.vision_encoder.patch_conv.weight" }) |n|
try std.testing.expect(visionTensor(n));
for ([_][]const u8{ "model.language_model.embed_tokens.weight", "language_model.model.layers.0.mlp.gate_proj.weight", "model.layers.0.self_attn.q_proj.weight", "backbone.layers.0.mixer.in_proj.weight", "lm_head.weight", "model.embed_tokens.weight", "mtp.layers.0.eh_proj.weight", "model.multi_modal_projector.linear_1.weight" }) |n|
try std.testing.expect(!visionTensor(n));
}
36 changes: 36 additions & 0 deletions zig/src/core/chunked_write.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//! XNU rejects individual writes larger than INT_MAX.
const std = @import("std");

/// Upper bound for a single write request, well under XNU's INT_MAX cap.
pub const max_write_bytes: usize = 1 << 28; // 256 MiB

comptime {
std.debug.assert(max_write_bytes < std.math.maxInt(c_int));
}

/// Write bounded chunks; sink errors pass through, and a nonempty write with a zero cap refuses.
pub fn writeChunked(sink: anytype, bytes: []const u8, cap: usize) !void {
if (cap == 0 and bytes.len > 0) return error.ZeroWriteCap;
var at: usize = 0;
while (at < bytes.len) {
const n = @min(bytes.len - at, cap);
try sink.writeAll(bytes[at..][0..n]);
at += n;
}
}

/// Write `bytes` to `sub_path` in bounded chunks; write errors pass through.
pub fn writeFileChunked(io: std.Io, dir: std.Io.Dir, sub_path: []const u8, bytes: []const u8) !void {
var file = try dir.createFile(io, sub_path, .{});
defer file.close(io);
const FileSink = struct {
file: std.Io.File,
io: std.Io,

fn writeAll(self: *@This(), chunk: []const u8) !void {
try self.file.writeStreamingAll(self.io, chunk);
}
};
var sink = FileSink{ .file = file, .io = io };
try writeChunked(&sink, bytes, max_write_bytes);
}
79 changes: 79 additions & 0 deletions zig/src/core/chunked_write_test_file.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//! Regression tests for bounded output writes.
const std = @import("std");
const cw = @import("chunked_write.zig");

const testing = std.testing;

const LimitedSink = struct {
buf: std.ArrayList(u8),
cap: usize,

const WriteError = error{ OutOfMemory, WriteTooLarge, ZeroWriteCap };

pub fn writeAll(self: *LimitedSink, bytes: []const u8) WriteError!void {
if (bytes.len > self.cap) return error.WriteTooLarge;
try self.buf.appendSlice(testing.allocator, bytes);
}
};

test "a zero cap refuses a nonempty buffer without progress" {
const zero = 0;
var sink = LimitedSink{ .buf = .empty, .cap = zero };
defer sink.buf.deinit(testing.allocator);

var data: [4]u8 = .{ 1, 2, 3, 4 };
try testing.expectError(error.ZeroWriteCap, cw.writeChunked(&sink, &data, zero));
try testing.expectEqual(@as(usize, 0), sink.buf.items.len); // no write happened
// an empty buffer is fine at a zero cap: nothing to write, nothing to refuse
try cw.writeChunked(&sink, &.{}, zero);
try testing.expectEqual(@as(usize, 0), sink.buf.items.len);
}

test "chunked writes respect the cap and preserve order" {
const cap = 64; // injected cap: the test never allocates the production 256 MiB
var sink = LimitedSink{ .buf = .empty, .cap = cap };
defer sink.buf.deinit(testing.allocator);

var data: [cap + 1]u8 = undefined;
for (&data, 0..) |*b, i| b.* = @truncate(i * 31 + 7);

try cw.writeChunked(&sink, &data, cap);
try testing.expectEqual(data.len, sink.buf.items.len);
try testing.expect(std.mem.eql(u8, sink.buf.items, &data));
}

test "a sink-refused request fails through the writer without flattening" {
var sink = LimitedSink{ .buf = .empty, .cap = 16 };
defer sink.buf.deinit(testing.allocator);

var big: [33]u8 = undefined;
@memset(&big, 1);
try testing.expectError(error.WriteTooLarge, cw.writeChunked(&sink, &big, 32));
}

test "empty and exact-cap buffers pass through" {
var sink = LimitedSink{ .buf = .empty, .cap = 16 };
defer sink.buf.deinit(testing.allocator);

try cw.writeChunked(&sink, "", 16);
try testing.expectEqual(@as(usize, 0), sink.buf.items.len);

const exact = [_]u8{ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
try cw.writeChunked(&sink, &exact, 16);
try testing.expect(std.mem.eql(u8, sink.buf.items, &exact));
}

test "writeFileChunked round-trips through the real file path" {
var single: std.Io.Threaded = .init_single_threaded;
defer single.deinit();
const io = single.io();

var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const data = "bounded file output";
try cw.writeFileChunked(io, tmp.dir, "cw-roundtrip.bin", data);

const result = try tmp.dir.readFileAlloc(io, "cw-roundtrip.bin", testing.allocator, .limited(data.len + 1));
defer testing.allocator.free(result);
try testing.expectEqualSlices(u8, data, result);
}
4 changes: 4 additions & 0 deletions zig/src/core/engine_api.zig
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ pub const VideoOffer = vision_types.VideoOffer;
pub const VisionOpen = vision_types.VisionOpen;
pub const ImageShare = vision_types.ImageShare;
pub const Size = vision_types.Size;
pub const visionGate = vision_types.gate;
pub const visionDeclared = vision_types.declared;
pub const visionWords = vision_types.words;
pub const ocr = @import("engine_ocr.zig");

pub const SpeechRequest = @import("speech_api.zig").SpeechRequest;
Expand Down Expand Up @@ -518,5 +521,6 @@ pub const save_guard = @import("save_guard");

test {
_ = @import("engine_api_test.zig");
_ = vision_types;
_ = @import("engine_capabilities.zig");
}
45 changes: 45 additions & 0 deletions zig/src/core/engine_vision.zig
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,48 @@ pub const VideoOffer = struct {

/// --vision's limits (``Open.vision``); image_tokens_set: the flag given; image_share: --vision-image-share's value.
pub const VisionOpen = struct { image_tokens: u32 = 4096, image_tokens_set: bool = false, max_images: u32 = 4, video_tokens: u32 = 16384, max_videos: u32 = 2, max_frames: u32 = 256, image_share: ImageShare = .request };

/// --vision against the checkpoint: given without a tower, refused by name; a tower without it stays unread.
pub fn gate(requested: bool, tower: bool) error{VisionWithoutTower}!bool {
if (requested and !tower) return error.VisionWithoutTower;
return requested;
}

/// Whether config.json's bytes name a vision_config other than null; JSON that does not parse counts as one.
pub fn declared(a: Allocator, config: []const u8) bool {
const doc = std.json.parseFromSlice(std.json.Value, a, config, .{}) catch return true;
defer doc.deinit();
if (doc.value != .object) return true;
const vc = doc.value.object.get("vision_config") orelse return false;
return vc != .null;
}

/// The gate's words for `model` ("this LFM2 checkpoint"): one format in every family; null for any other error.
pub fn words(comptime model: []const u8, err: anyerror) ?[]const u8 {
return switch (err) {
error.VisionWithoutTower => "--vision given but " ++ model ++ " has no vision tower",
error.VisionNotLoaded => model ++ " has a vision tower; pass --vision to load it",
else => null,
};
}

test "the gate refuses --vision without a tower by name and leaves a tower unread without --vision" {
try std.testing.expectError(error.VisionWithoutTower, gate(true, false));
try std.testing.expect(try gate(true, true));
try std.testing.expect(!try gate(false, true));
try std.testing.expect(!try gate(false, false));
const m = "this X checkpoint";
try std.testing.expectEqualStrings("--vision given but this X checkpoint has no vision tower", words(m, error.VisionWithoutTower).?);
try std.testing.expectEqualStrings("this X checkpoint has a vision tower; pass --vision to load it", words(m, error.VisionNotLoaded).?);
try std.testing.expect(words(m, error.OutOfMemory) == null);
}

test "a vision_config is declared unless absent or null" {
const a = std.testing.allocator;
try std.testing.expect(declared(a, "{\"vision_config\":{\"depth\":2}}"));
try std.testing.expect(declared(a, "{\"vision_config\":[]}"));
try std.testing.expect(declared(a, "{\"vision_config\":\"x\"}"));
try std.testing.expect(!declared(a, "{\"vision_config\":null}"));
try std.testing.expect(!declared(a, "{\"text_config\":{}}"));
try std.testing.expect(declared(a, "not json"));
}
1 change: 1 addition & 0 deletions zig/src/core/root.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

pub const startup_receipt = @import("profile").startup_receipt;
pub const benchmark_group = @import("benchmark_group.zig");
pub const chunked_write = @import("chunked_write.zig");
pub const weight_only = @import("weight_only.zig");
pub const profile = @import("profile");
pub const safetensors = @import("safetensors.zig");
Expand Down
3 changes: 2 additions & 1 deletion zig/src/families/flashnext/cuda_images.zig
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ pub const Vision = struct {
return switch (err) {
error.BadImageLimits, error.BadImageCount => "image count or row budget exceeds the configured limits",
error.BadImageGrid, error.BadImagePatches, error.BadImagePlaceholders => "image rows do not match the prompt placeholders",
error.NoVisionTower, error.BadVisionWidth, error.UnsupportedQwenVision => "unsupported Flash Next Qwen-VL tower configuration",
error.NoVisionTower => @import("engine_api").visionWords("this Flash Next checkpoint", error.VisionWithoutTower),
error.BadVisionWidth, error.UnsupportedQwenVision => "unsupported Flash Next Qwen-VL tower configuration",
else => core.qwen_vl.geometry.problem(err),
};
}
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/flashnext/cuda_lanes.zig
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,7 @@ pub fn Namespace(comptime Tri: type) type {
_ = @import("cuda_lanes_restore_test.zig").Cases(Cuda, Cuda.open, snaps.restore, dropLane);
_ = @import("cuda_lanes_admission_test.zig").Cases(Cuda, Cuda.open, dropLane);
_ = @import("cuda_score.zig").CapabilityCases(Cuda);
_ = @import("cuda_lanes_vision_test.zig").Cases(@This());
}

test "a bad TF_FLASHNEXT_CHUNK, _CHUNK_SOLO or TF_FLASHNEXT_LOAD_THREADS is refused at load before the loader takes a stream, a module or a buffer" {
Expand Down
2 changes: 1 addition & 1 deletion zig/src/families/flashnext/cuda_lanes_bytes.zig
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,6 @@ pub const worlds = struct {
pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8, rank: u32, _: u32) !u64 {
if (rank != 0) return 0;
const v = @import("qwen_vision");
const c = ((try v.Settings.read(a, io, dir)) orelse return error.NoVisionTower).tower;
const c = ((try v.Settings.read(a, io, dir)) orelse return 0).tower; // no tower: open refuses --vision by name
return v.Tower.weightBytes(c) + v.Tower.scratchBytes(c, v.max_patches);
}
1 change: 1 addition & 0 deletions zig/src/families/flashnext/cuda_lanes_explain.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub fn open(err: anyerror) ?[]const u8 {
error.FlashNextRanksOnCapturedGlue => "--tp 2 runs Flash Next's own glue, not a captured set: set TENSORFOLD_CUDA_KERNELS=native, or serve on one GPU",
error.BadFlashNextKvPages, error.BadFlashNextPageTest, error.FlashNextPagesUnsupported, error.UnsupportedCheckpoint => explain(err),
error.UnsupportedLearningFormat, error.TrainingOnCapturedGlue => explain(err),
error.VisionWithoutTower => @import("engine_api").visionWords("this Flash Next checkpoint", err),
else => null,
};
}
Expand Down
2 changes: 2 additions & 0 deletions zig/src/families/flashnext/cuda_lanes_load.zig
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const images = @import("cuda_images.zig");
pub fn open(comptime F: type, gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, captured: ?[]const u8, o: F.Options) !F.Loaded {
try @import("env_validate.zig").startup();
if (o.vision) |v| try @import("qwen_vision").media.checkLimits(v);
// --vision on a checkpoint without a tower refuses by name (core's gate) before a stream or a weight loads
if (o.vision != null) _ = try @import("engine_api").visionGate(true, try @import("qwen_vision").Settings.read(gpa, io, dir) != null);
var load_cache = @import("core").checkpoint.cache.Load.begin(io, o.tp > 1);
defer load_cache.deinit();
const Cuda = F.Cuda;
Expand Down
Loading
Loading