From d71165ab5ae712824873cacd8da11223d19c0466 Mon Sep 17 00:00:00 2001 From: plotarmordev <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:48:06 +0800 Subject: [PATCH 01/10] feat(server): expose open connections gauge (cherry picked from commit 8c07b5cb396de6c2057323984515d2ec13c36a39) --- docs/memory-diagnostics.md | 1 + zig/src/server/metrics.zig | 16 ++++ zig/src/server/status_routes.zig | 1 + zig/tests/server/open_connections_smoke.py | 90 ++++++++++++++++++++++ 4 files changed, 108 insertions(+) create mode 100755 zig/tests/server/open_connections_smoke.py diff --git a/docs/memory-diagnostics.md b/docs/memory-diagnostics.md index f8c71742e45..f5f70408545 100644 --- a/docs/memory-diagnostics.md +++ b/docs/memory-diagnostics.md @@ -43,6 +43,7 @@ device gauges retain their backend scope and reset behavior. Process and device unified memory: do not add them. RSS, allocator peaks and physical footprint are different measurements. The Darwin structure follows Apple's `sys/resource.h` `rusage_info_v4` layout; host tests check its size and both footprint offsets, and exercise the kernel reader on macOS. +`tensorfold:open_connections` gauges admitted client TCP connections until close, including the scrape itself and idle keep-alive connections; rejected-over-limit connections are excluded. Linux has no physical footprint count, so the footprint gauges stay macOS only. On Linux, `/metrics` reads `/proc/self/status` at scrape time and reports the resident set: `tensorfold:process_resident_bytes` (`VmRSS`), diff --git a/zig/src/server/metrics.zig b/zig/src/server/metrics.zig index aba3ed5efba..bb9e7681301 100644 --- a/zig/src/server/metrics.zig +++ b/zig/src/server/metrics.zig @@ -247,6 +247,22 @@ fn gauge(w: *std.Io.Writer, name: []const u8, kind: []const u8, help: []const u8 try w.print("{s}{s} {d}\n", .{ prefix, name, value }); } +pub fn renderConnections(w: *std.Io.Writer, open: u32) !void { + try gauge(w, "open_connections", "gauge", "Client TCP connections admitted and not yet closed, including the one serving this scrape; keep-alive idle connections count.", open); +} + +test "open connections render help, gauge type and admitted count" { + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + try renderConnections(&out.writer, 3); + try std.testing.expectEqualStrings( + "# HELP tensorfold:open_connections Client TCP connections admitted and not yet closed, including the one serving this scrape; keep-alive idle connections count.\n" ++ + "# TYPE tensorfold:open_connections gauge\n" ++ + "tensorfold:open_connections 3\n", + out.written(), + ); +} + fn processGauges(w: *std.Io.Writer, sample: ?process.Snapshot) !void { const p = sample orelse return; try gauge(w, "process_footprint_bytes", "gauge", "Current OS physical footprint including Metal buffers (macOS).", p.physical_footprint_bytes); diff --git a/zig/src/server/status_routes.zig b/zig/src/server/status_routes.zig index 140b6ada6e7..b7fa45e78b5 100644 --- a/zig/src/server/status_routes.zig +++ b/zig/src/server/status_routes.zig @@ -176,6 +176,7 @@ pub fn metrics(srv: *Server, conn: *Conn, a: Allocator) void { } @import("load_metrics.zig").render(&out.writer, snap, .{ .model = srv.config.served_name, .backend = srv.config.identity.backend, .version = srv.config.identity.version }) catch return; if (srv.config.admission.enabled()) @import("metrics.zig").renderAdmission(&out.writer, srv.admission.snapshot(srv.io)) catch return; + @import("metrics.zig").renderConnections(&out.writer, srv.open_connections.load(.acquire)) catch return; const body = out.written(); conn.startResponse(200, null) catch return; conn.addHeader("Content-Type", "text/plain; version=0.0.4; charset=utf-8") catch return; diff --git a/zig/tests/server/open_connections_smoke.py b/zig/tests/server/open_connections_smoke.py new file mode 100755 index 00000000000..dbc45110bb0 --- /dev/null +++ b/zig/tests/server/open_connections_smoke.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Model-free connection gauge smoke: pass fake_serve and its fixture directory.""" +import contextlib +import http.client +import os +from pathlib import Path +import selectors +import socket +import subprocess +import sys +import time + + +def listener(proc): + deadline = time.monotonic() + 10 + with selectors.DefaultSelector() as selector: + selector.register(proc.stdout, selectors.EVENT_READ) + while time.monotonic() < deadline: + if not selector.select(max(0, deadline - time.monotonic())): + break + line = proc.stdout.readline() + if line.startswith(b"PORT "): + return int(line.split()[1]) + if not line: + break + raise RuntimeError("fake server did not announce its listener") + + +def scrape(port): + with contextlib.closing(http.client.HTTPConnection("127.0.0.1", port, timeout=1)) as conn: + conn.request("GET", "/metrics", headers={"Connection": "close"}) + response = conn.getresponse() + body = response.read().decode() + if response.status != 200: + raise AssertionError(f"metrics status: {response.status}") + values = [int(line.split()[1]) for line in body.splitlines() + if line.startswith("tensorfold:open_connections ")] + if len(values) != 1: + raise AssertionError(f"expected one connection gauge, got {values}") + print(f"tensorfold:open_connections {values[0]}", flush=True) + return values[0] + + +def expect(port, expected): + deadline = time.monotonic() + 2 + while True: + observed = scrape(port) + if observed == expected: + return + if time.monotonic() >= deadline: + raise AssertionError(f"expected {expected} open connections, observed {observed}") + time.sleep(0.02) + + +def main(binary, fixtures): + proc = subprocess.Popen( + [str(binary), "serve", str(fixtures), "--name", "fixture", "--port", "0", + "--host", "127.0.0.1", "--keep-warm", "0"], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0, + env={**os.environ, "TENSORFOLD_NO_LIVE": "1"}, + ) + try: + port = listener(proc) + observed = scrape(port) + if observed != 1: + raise AssertionError(f"expected 1 open connection, observed {observed}") + with contextlib.ExitStack() as stack: + for _ in range(3): + sock = stack.enter_context(socket.create_connection(("127.0.0.1", port), timeout=1)) + sock.sendall(b"GET /health HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n") + with http.client.HTTPResponse(sock) as response: + response.begin() + response.read() + if response.status != 200 or response.will_close: + raise AssertionError("health did not retain the keep-alive connection") + expect(port, 4) + expect(port, 1) + finally: + proc.terminate() + try: + proc.communicate(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + proc.communicate(timeout=5) + + +if __name__ == "__main__": + if len(sys.argv) != 3: + sys.exit("usage: open_connections_smoke.py FAKE_SERVE FIXTURES") + main(*(Path(arg).resolve() for arg in sys.argv[1:])) From 3a8e4065fe815ecdc10e82facfcb715f7ff47cc4 Mon Sep 17 00:00:00 2001 From: plotarmordev <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:57:45 +0800 Subject: [PATCH 02/10] test(server): assert open connections metric contract, not help prose (cherry picked from commit 1f5a2cbc372f53aa4aba2a2d3ac7255ebc9726de) --- zig/src/server/metrics.zig | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/zig/src/server/metrics.zig b/zig/src/server/metrics.zig index bb9e7681301..a1274ca5abf 100644 --- a/zig/src/server/metrics.zig +++ b/zig/src/server/metrics.zig @@ -251,16 +251,27 @@ pub fn renderConnections(w: *std.Io.Writer, open: u32) !void { try gauge(w, "open_connections", "gauge", "Client TCP connections admitted and not yet closed, including the one serving this scrape; keep-alive idle connections count.", open); } -test "open connections render help, gauge type and admitted count" { +test "open connections export gauge name, type and admitted count" { var out: std.Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); try renderConnections(&out.writer, 3); - try std.testing.expectEqualStrings( - "# HELP tensorfold:open_connections Client TCP connections admitted and not yet closed, including the one serving this scrape; keep-alive idle connections count.\n" ++ - "# TYPE tensorfold:open_connections gauge\n" ++ - "tensorfold:open_connections 3\n", - out.written(), - ); + var help = false; + var gauge_type = false; + var sample = false; + var lines = std.mem.splitScalar(u8, out.written(), '\n'); + while (lines.next()) |line| { + const help_prefix = "# HELP tensorfold:open_connections "; + const sample_prefix = "tensorfold:open_connections "; + if (std.mem.startsWith(u8, line, help_prefix)) + help = std.mem.trim(u8, line[help_prefix.len..], " \t").len > 0; + if (std.mem.eql(u8, line, "# TYPE tensorfold:open_connections gauge")) + gauge_type = true; + if (std.mem.startsWith(u8, line, sample_prefix)) { + try std.testing.expectEqual(@as(f64, 3), try std.fmt.parseFloat(f64, line[sample_prefix.len..])); + sample = true; + } + } + try std.testing.expect(help and gauge_type and sample); } fn processGauges(w: *std.Io.Writer, sample: ?process.Snapshot) !void { From 7a8126a6f9cfb3d8b52e69bb1e8ca7ed290c160b Mon Sep 17 00:00:00 2001 From: plotarmordev <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:14:52 +0800 Subject: [PATCH 03/10] test(server): drive the open-connections gauge through the metrics route in every idle-manager state I add three route-level tests that GET /metrics through the production dispatch with no idle manager, a healthy manager, and a parked manager; each asserts exactly one tensorfold:open_connections sample line, the exact TYPE line, and the admitted count, and the parked body keeps its request-and-process-only family split. (cherry picked from commit 38060568b51b8a1de0fd1f53f4d538873a07650b) --- .../server/open_connections_route_test.zig | 97 +++++++++++++++++++ zig/src/server/root.zig | 4 + 2 files changed, 101 insertions(+) create mode 100644 zig/src/server/open_connections_route_test.zig diff --git a/zig/src/server/open_connections_route_test.zig b/zig/src/server/open_connections_route_test.zig new file mode 100644 index 00000000000..3c92c5b6ca6 --- /dev/null +++ b/zig/src/server/open_connections_route_test.zig @@ -0,0 +1,97 @@ +//! The /metrics route's open-connections gauge through the production dispatch, in every idle-manager state. +const std = @import("std"); +const http = @import("http_conn.zig"); +const idle = @import("idle_unload.zig"); +const server_mod = @import("server.zig"); +const Harness = @import("idle_unload_test.zig").Harness; +const t = std.testing; + +/// What the route wrote, as the socket would have read it. +const Wire = struct { + a: std.mem.Allocator, + bytes: std.ArrayList(u8) = .empty, + + fn write(ctx: *anyopaque, bytes: []const u8) error{Closed}!void { + const w: *Wire = @ptrCast(@alignCast(ctx)); + w.bytes.appendSlice(w.a, bytes) catch return error.Closed; + } +}; + +/// One GET /metrics served by the production route table with `open` admitted connections, its body. +fn scrape(srv: *server_mod.Server, a: std.mem.Allocator, open: u32) ![]const u8 { + var conn = try http.Conn.init(a, -1, "fixture"); + defer conn.deinit(); + conn.method = "GET"; + conn.path = "/metrics"; + conn.version = "HTTP/1.1"; + var wire: Wire = .{ .a = a }; + conn.write_hooks = .{ .ctx = &wire, .write = Wire.write }; + srv.open_connections.store(open, .release); // the count the admission path leaves behind + srv.dispatch(&conn, a); + try t.expect(conn.response_complete); + try t.expect(std.mem.startsWith(u8, wire.bytes.items, "HTTP/1.1 200 ")); + const head = std.mem.indexOf(u8, wire.bytes.items, "\r\n\r\n") orelse return error.MissingBody; + return wire.bytes.items[head + 4 ..]; +} + +/// The gauge exactly once: one sample line carrying `open`, and its exact TYPE line; no HELP prose pinned. +fn expectGauge(body: []const u8, open: u32) !void { + const sample = "tensorfold:open_connections "; + var samples: usize = 0; + var types: usize = 0; + var value: ?u32 = null; + var lines = std.mem.splitScalar(u8, body, '\n'); + while (lines.next()) |line| { + if (std.mem.startsWith(u8, line, sample)) { + samples += 1; + value = try std.fmt.parseInt(u32, line[sample.len..], 10); + } + if (std.mem.eql(u8, line, "# TYPE tensorfold:open_connections gauge")) types += 1; + } + try t.expectEqual(@as(usize, 1), samples); + try t.expectEqual(@as(usize, 1), types); + try t.expectEqual(open, value.?); +} + +test "open connections route: no idle manager serves one gauge with the admitted count" { + var h: Harness = .{}; + defer h.deinit(); + try h.setup(3600); + idle.stopServer(h.srv.?); // the manager stops behind a resident engine, as shutdown does + h.man = null; + try t.expectEqual(@as(?*idle.Manager, null), h.srv.?.idle_manager); + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const body = try scrape(h.srv.?, arena.allocator(), 7); + try expectGauge(body, 7); + // the resident engine's families rendered, not the parked body + try t.expect(std.mem.indexOf(u8, body, "tensorfold:kv_cache_usage_ratio") != null); +} + +test "open connections route: a healthy idle manager serves one gauge with the admitted count" { + var h: Harness = .{}; + defer h.deinit(); + try h.setup(3600); + try t.expect(h.srv.?.idle_manager != null and !h.man.?.isParked()); + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const body = try scrape(h.srv.?, arena.allocator(), 12); + try expectGauge(body, 12); + // the resident engine's families rendered, not the parked body + try t.expect(std.mem.indexOf(u8, body, "tensorfold:kv_cache_usage_ratio") != null); +} + +test "open connections route: a parked idle manager serves one gauge with the admitted count" { + var h: Harness = .{}; + defer h.deinit(); + try h.setup(3600); + h.expire(); + try h.waitParked(2000); + try t.expect(h.man.?.isParked()); + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const body = try scrape(h.srv.?, arena.allocator(), 23); + try expectGauge(body, 23); + // parked: the request and process families only, no engine KV families + try t.expect(std.mem.indexOf(u8, body, "tensorfold:kv_cache_usage_ratio") == null); +} diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 834352dbc08..29ab8464273 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -332,3 +332,7 @@ test { _ = @import("ocr/prompt_ids_test.zig"); _ = @import("ollama_e2e_test.zig"); } + +test { + _ = @import("open_connections_route_test.zig"); +} From a21f15a3b7a7fc9a6907570828286263e2d5d169 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:22:31 +0800 Subject: [PATCH 04/10] refactor(server): render open_connections beside the server-level gauges metrics.zig crossed the 600-line lean rule, so the gauge renderer and its unit test move to load_metrics.zig (engine_parked, lanes); the route calls it from there. The help and docs now count Unix-socket clients too, the docs line wraps with the surrounding prose, the smoke script is named in zig/tests/server/README.md, and the lone test block in root.zig folds into the previous one. --- docs/memory-diagnostics.md | 4 +++- zig/src/server/load_metrics.zig | 5 +++++ zig/src/server/load_metrics_test.zig | 23 +++++++++++++++++++++++ zig/src/server/metrics.zig | 27 --------------------------- zig/src/server/root.zig | 3 --- zig/src/server/status_routes.zig | 2 +- zig/tests/server/README.md | 6 ++++++ 7 files changed, 38 insertions(+), 32 deletions(-) diff --git a/docs/memory-diagnostics.md b/docs/memory-diagnostics.md index f5f70408545..5bf01149f1d 100644 --- a/docs/memory-diagnostics.md +++ b/docs/memory-diagnostics.md @@ -43,7 +43,9 @@ device gauges retain their backend scope and reset behavior. Process and device unified memory: do not add them. RSS, allocator peaks and physical footprint are different measurements. The Darwin structure follows Apple's `sys/resource.h` `rusage_info_v4` layout; host tests check its size and both footprint offsets, and exercise the kernel reader on macOS. -`tensorfold:open_connections` gauges admitted client TCP connections until close, including the scrape itself and idle keep-alive connections; rejected-over-limit connections are excluded. +`tensorfold:open_connections` gauges admitted client connections — over TCP and the Unix socket alike — until +close, including the scrape itself and idle keep-alive connections; rejected-over-limit connections are +excluded. Linux has no physical footprint count, so the footprint gauges stay macOS only. On Linux, `/metrics` reads `/proc/self/status` at scrape time and reports the resident set: `tensorfold:process_resident_bytes` (`VmRSS`), diff --git a/zig/src/server/load_metrics.zig b/zig/src/server/load_metrics.zig index b37f610138a..78083ba4eca 100644 --- a/zig/src/server/load_metrics.zig +++ b/zig/src/server/load_metrics.zig @@ -61,6 +61,11 @@ pub fn render(w: *std.Io.Writer, s: ledger.Snapshot, id: Identity) !void { } } +/// The admitted-client gauge: outside the ledger read, it keeps the scrape's own connection in the count. +pub fn renderConnections(w: *std.Io.Writer, open: u32) !void { + try gauge(w, "open_connections", "gauge", "Client connections admitted and not yet closed, over TCP or the Unix socket, including the one serving this scrape; keep-alive idle connections count.", open); +} + /// GET /v1/load: the whole ledger as one object from one read; a group no host fills leaves its keys out. pub fn get(srv: anytype, conn: anytype, a: Allocator) void { const snap = srv.load.read(); diff --git a/zig/src/server/load_metrics_test.zig b/zig/src/server/load_metrics_test.zig index f0f9b2fd432..c425ee83137 100644 --- a/zig/src/server/load_metrics_test.zig +++ b/zig/src/server/load_metrics_test.zig @@ -139,3 +139,26 @@ test "the /v1/load object carries every group a host fills, and only server valu // as keys: a refusal label such as admission_capacity_exceeded is a server value, shown while parked too for ([_][]const u8{ "\"running\":", "\"tokens\":", "\"capacity\":", "\"busy_us\":", "\"fill_unknown\":" }) |key| try std.testing.expect(!has(parked, key)); } + +test "open connections exports gauge name, type and admitted count" { + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + try load_metrics.renderConnections(&out.writer, 3); + var help = false; + var gauge_type = false; + var sample = false; + var lines = std.mem.splitScalar(u8, out.written(), '\n'); + while (lines.next()) |line| { + const help_prefix = "# HELP tensorfold:open_connections "; + const sample_prefix = "tensorfold:open_connections "; + if (std.mem.startsWith(u8, line, help_prefix)) + help = std.mem.trim(u8, line[help_prefix.len..], " \t").len > 0; + if (std.mem.eql(u8, line, "# TYPE tensorfold:open_connections gauge")) + gauge_type = true; + if (std.mem.startsWith(u8, line, sample_prefix)) { + try std.testing.expectEqual(@as(f64, 3), try std.fmt.parseFloat(f64, line[sample_prefix.len..])); + sample = true; + } + } + try std.testing.expect(help and gauge_type and sample); +} diff --git a/zig/src/server/metrics.zig b/zig/src/server/metrics.zig index a1274ca5abf..aba3ed5efba 100644 --- a/zig/src/server/metrics.zig +++ b/zig/src/server/metrics.zig @@ -247,33 +247,6 @@ fn gauge(w: *std.Io.Writer, name: []const u8, kind: []const u8, help: []const u8 try w.print("{s}{s} {d}\n", .{ prefix, name, value }); } -pub fn renderConnections(w: *std.Io.Writer, open: u32) !void { - try gauge(w, "open_connections", "gauge", "Client TCP connections admitted and not yet closed, including the one serving this scrape; keep-alive idle connections count.", open); -} - -test "open connections export gauge name, type and admitted count" { - var out: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer out.deinit(); - try renderConnections(&out.writer, 3); - var help = false; - var gauge_type = false; - var sample = false; - var lines = std.mem.splitScalar(u8, out.written(), '\n'); - while (lines.next()) |line| { - const help_prefix = "# HELP tensorfold:open_connections "; - const sample_prefix = "tensorfold:open_connections "; - if (std.mem.startsWith(u8, line, help_prefix)) - help = std.mem.trim(u8, line[help_prefix.len..], " \t").len > 0; - if (std.mem.eql(u8, line, "# TYPE tensorfold:open_connections gauge")) - gauge_type = true; - if (std.mem.startsWith(u8, line, sample_prefix)) { - try std.testing.expectEqual(@as(f64, 3), try std.fmt.parseFloat(f64, line[sample_prefix.len..])); - sample = true; - } - } - try std.testing.expect(help and gauge_type and sample); -} - fn processGauges(w: *std.Io.Writer, sample: ?process.Snapshot) !void { const p = sample orelse return; try gauge(w, "process_footprint_bytes", "gauge", "Current OS physical footprint including Metal buffers (macOS).", p.physical_footprint_bytes); diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 29ab8464273..75d7bea418d 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -331,8 +331,5 @@ test { _ = @import("ocr/size_test.zig"); _ = @import("ocr/prompt_ids_test.zig"); _ = @import("ollama_e2e_test.zig"); -} - -test { _ = @import("open_connections_route_test.zig"); } diff --git a/zig/src/server/status_routes.zig b/zig/src/server/status_routes.zig index b7fa45e78b5..04eb9ef0c57 100644 --- a/zig/src/server/status_routes.zig +++ b/zig/src/server/status_routes.zig @@ -176,7 +176,7 @@ pub fn metrics(srv: *Server, conn: *Conn, a: Allocator) void { } @import("load_metrics.zig").render(&out.writer, snap, .{ .model = srv.config.served_name, .backend = srv.config.identity.backend, .version = srv.config.identity.version }) catch return; if (srv.config.admission.enabled()) @import("metrics.zig").renderAdmission(&out.writer, srv.admission.snapshot(srv.io)) catch return; - @import("metrics.zig").renderConnections(&out.writer, srv.open_connections.load(.acquire)) catch return; + @import("load_metrics.zig").renderConnections(&out.writer, srv.open_connections.load(.acquire)) catch return; const body = out.written(); conn.startResponse(200, null) catch return; conn.addHeader("Content-Type", "text/plain; version=0.0.4; charset=utf-8") catch return; diff --git a/zig/tests/server/README.md b/zig/tests/server/README.md index dbca5365302..9a4f5db6241 100644 --- a/zig/tests/server/README.md +++ b/zig/tests/server/README.md @@ -8,6 +8,12 @@ The Python files here support the native tests: - `corpus.py`, `fake_text.py`, `wire.py` and `freeze_cases.py` build the golden request corpus. - `security_cases.py` and `security_check.py` exercise the native server's HTTP and authentication boundaries. - `test_memory_http.py` supplies the HTTP checks used by memory receipts. +- `open_connections_smoke.py` watches `tensorfold:open_connections` rise and fall with live clients: + + ```sh + zig build server-cpu + python3 zig/tests/server/open_connections_smoke.py zig-out/server/fake_serve zig/tests/server/fixtures + ``` Regenerate request cases with `python3 -B zig/tests/server/freeze_cases.py`. Review changes to expected responses separately; do not replace them wholesale with the candidate server's output. From c51ec40707aec7cf6a1acc3aee4bdf1ed3faee48 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:55:40 +0000 Subject: [PATCH 05/10] changelog: #3925 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b5ae195e21..d75bf3faeb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Server: `/v1/metrics` reports a `tensorfold:open_connections` gauge, the client connections admitted over TCP or the Unix socket and not yet closed, including idle keep-alive ones (#3925). Thanks to @plotarmordev. + - Docs: the optimization ledger adds rows 30 to 32 (small-kernel fusion, stream-tile prefetch and the filled-item prompt grid), each `failed` for Flash Next on HIP with the measurements from #1603 (#3160, refs #1603). Thanks to @gilby. - Docs: the Qwen3.8-27B recipe says to serve with `--thinking-budget 4096` when thinking is on, and gives its GPQA Diamond result on TensorFold 1.2.7 and one GB10: replies cut at the limit from 78 of 198 to 0, and correct from 58.1% to 82.8% (#3373, fixes #3323). From 87df5616d718338396c02b639986eeca43c71302 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:57:33 +0100 Subject: [PATCH 06/10] dsv41 metal: image prompts The ViT and aligner on Metal (--vision), bias_vl routing for image rows, Engram shut on image tokens, an image span prefilled in one chunk, and the prompt cache keyed by the image's hash. The server writes the template's image token for an image part when the engine reads images, and refuses the reserved mark in request text. --- zig/build/dsv41_metal.zig | 21 +- zig/src/families/deepseek_v41/draft/iface.zig | 7 + zig/src/families/deepseek_v41/draft/lanes.zig | 1 + zig/src/families/deepseek_v41/metal/boot.zig | 44 ++- zig/src/families/deepseek_v41/metal/entry.zig | 3 + zig/src/families/deepseek_v41/metal/metal.zig | 10 + .../families/deepseek_v41/metal/prompt.zig | 27 +- zig/src/families/deepseek_v41/metal/serve.zig | 32 ++ .../families/deepseek_v41/metal/target.zig | 73 +++- .../deepseek_v41/metal/vision_prep.zig | 166 ++++++++ .../deepseek_v41/metal/vision_prepare.zig | 122 ++++++ .../deepseek_v41/metal/vision_rows.zig | 147 +++++++ .../deepseek_v41/metal/vision_tower.zig | 174 ++++++++ .../deepseek_v41/metal/vision_weights.zig | 108 +++++ .../families/deepseek_v41/phases_timed.zig | 6 +- zig/src/server/deepseek_chat_test.zig | 14 +- zig/tests/dsv41_metal/fixture_vis.zig | 87 ++++ zig/tests/dsv41_metal/layer_test.zig | 1 + zig/tests/dsv41_metal/serve_test.zig | 1 + zig/tests/dsv41_metal/vision_boot_test.zig | 179 +++++++++ zig/tests/dsv41_metal/vision_real_test.zig | 108 +++++ zig/tests/dsv41_metal/vision_ref.zig | 231 +++++++++++ zig/tests/dsv41_metal/vision_test.zig | 370 ++++++++++++++++++ 23 files changed, 1912 insertions(+), 20 deletions(-) create mode 100644 zig/src/families/deepseek_v41/metal/vision_prep.zig create mode 100644 zig/src/families/deepseek_v41/metal/vision_prepare.zig create mode 100644 zig/src/families/deepseek_v41/metal/vision_rows.zig create mode 100644 zig/src/families/deepseek_v41/metal/vision_tower.zig create mode 100644 zig/src/families/deepseek_v41/metal/vision_weights.zig create mode 100644 zig/tests/dsv41_metal/fixture_vis.zig create mode 100644 zig/tests/dsv41_metal/vision_boot_test.zig create mode 100644 zig/tests/dsv41_metal/vision_real_test.zig create mode 100644 zig/tests/dsv41_metal/vision_ref.zig create mode 100644 zig/tests/dsv41_metal/vision_test.zig diff --git a/zig/build/dsv41_metal.zig b/zig/build/dsv41_metal.zig index ba1a6593f31..bf0bf6d50bf 100644 --- a/zig/build/dsv41_metal.zig +++ b/zig/build/dsv41_metal.zig @@ -13,6 +13,7 @@ pub fn package(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Modu .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "dsv41", .module = host } }, }); + pkg.addImport("core", host.import_table.get("core").?); // the picture decoder image input reads return .{ .pkg = pkg, .host = host }; } @@ -55,6 +56,12 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module const run = b.addRunArtifact(b.addTest(.{ .root_module = tests })); run.has_side_effects = true; // a device run: never cached step.dependOn(&run.step); + const vis_run = b.addRunArtifact(b.addTest(.{ .root_module = tests, .filters = &.{"dsv41 metal vision"} })); + vis_run.has_side_effects = true; + const vis_step = b.step("test-dsv41-metal-vision", "DeepSeek-V4.1 Metal vision: the tower against float64, image rows in prompts"); + vis_step.dependOn(&vis_run.step); + const prepare_run = b.addRunArtifact(b.addTest(.{ .root_module = p.pkg, .filters = &.{"prepare"} })); + b.step("test-dsv41-metal-prepare", "DeepSeek-V4.1 Metal: image bytes to patches").dependOn(&prepare_run.step); // the served engine over the tiny model: LaneHost replies, drafts, the prompt cache, seeds, cancels const serve = b.createModule(.{ .root_source_file = b.path("zig/tests/dsv41_metal/serve_test.zig"), @@ -70,9 +77,10 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module const serve_step = b.step("test-dsv41-metal-serve", "DeepSeek-V4.1 Metal served through LaneHost: concurrent, drafted, cached, seeded, cancelled"); serve_step.dependOn(&serve_run.step); // the release-checkpoint steps (TF_DSV41_REAL) stay opt-in, so the umbrella holds the default device suites - const all = b.step("test-dsv41-metal-all", "DeepSeek-V4.1 Metal: every device test step on this GPU (layer, served)"); + const all = b.step("test-dsv41-metal-all", "DeepSeek-V4.1 Metal: every device test step on this GPU (layer, served, vision)"); all.dependOn(step); all.dependOn(serve_step); + all.dependOn(vis_step); const fast = package(b, metal, sources, .ReleaseSafe); const real = b.createModule(.{ .root_source_file = b.path("zig/tests/dsv41_metal/real_test.zig"), @@ -107,6 +115,17 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module const synth_run = b.addRunArtifact(b.addTest(.{ .root_module = synth })); synth_run.has_side_effects = true; b.step("time-dsv41-metal-synth", "DeepSeek-V4.1 Metal: synthetic release-shape layers timed per row and dispatch class").dependOn(&synth_run.step); + // the release's own vision tower (TF_DSV41_REAL_VISION) against float64 + const vreal = b.createModule(.{ + .root_source_file = b.path("zig/tests/dsv41_metal/vision_real_test.zig"), + .target = b.graph.host, + .optimize = .ReleaseSafe, + .link_libc = true, + .imports = &.{ .{ .name = "dsv41_metal", .module = fast.pkg }, .{ .name = "metal", .module = metal }, .{ .name = "dsv41", .module = fast.host } }, + }); + const vreal_run = b.addRunArtifact(b.addTest(.{ .root_module = vreal })); + vreal_run.has_side_effects = true; + b.step("test-dsv41-metal-vision-real", "DeepSeek-V4.1 Metal: the release's vision tower (TF_DSV41_REAL_VISION) against float64").dependOn(&vreal_run.step); const ptime = b.createModule(.{ .root_source_file = b.path("zig/tests/dsv41_metal/prompt_time.zig"), .target = b.graph.host, diff --git a/zig/src/families/deepseek_v41/draft/iface.zig b/zig/src/families/deepseek_v41/draft/iface.zig index d63cae1b376..623d369c02d 100644 --- a/zig/src/families/deepseek_v41/draft/iface.zig +++ b/zig/src/families/deepseek_v41/draft/iface.zig @@ -46,6 +46,8 @@ pub const Target = struct { replays: ?*const fn (ptr: *anyopaque, list: []const Final) anyerror!void = null, /// Engram reads ahead of the next window (TF_DSV41_ENGRAM_WARM); reads only, window bits are unaffected. warm: ?*const fn (ptr: *anyopaque, asks: []const Warm) void = null, + /// Before `prefill`: the slot's prompt images (their rows replace placeholder ids); borrowed until it returns. + images: ?*const fn (ptr: *anyopaque, slot: u32, images: []const lanes.stream.Image) anyerror!void = null, /// After `prefill`: the prompt rows the slot took from kept state (its first row computed is this one). resumed: ?*const fn (ptr: *anyopaque, slot: u32) u64 = null, /// Committed rows' taps for positions [start, start + rows), in order; null: not kept. null fn: none kept. @@ -61,6 +63,11 @@ pub const Target = struct { return if (t.vtable.history) |f| f(t.ptr, slot, start, rows) else null; } + /// The slot's prompt images for its next `prefill`; error.NoImages when the target has no image path. + pub fn setImages(t: Target, slot: u32, images: []const lanes.stream.Image) !void { + return (t.vtable.images orelse return error.NoImages)(t.ptr, slot, images); + } + /// The prompt rows the slot's last `prefill` took from kept state (0: none, or a target that keeps none). pub fn resumedRows(t: Target, slot: u32) u64 { return if (t.vtable.resumed) |f| f(t.ptr, slot) else 0; diff --git a/zig/src/families/deepseek_v41/draft/lanes.zig b/zig/src/families/deepseek_v41/draft/lanes.zig index 70d176a0656..3c6dae34071 100644 --- a/zig/src/families/deepseek_v41/draft/lanes.zig +++ b/zig/src/families/deepseek_v41/draft/lanes.zig @@ -174,6 +174,7 @@ pub const Lanes = struct { x.policy.depth.reset(slot); const ids = s.prompt(); x.target.admit(slot, s.max_new); + if (s.images.len > 0) try x.target.setImages(slot, s.images); st.first = try x.target.prefill(slot, ids, s.sampling, ids.len); s.cached = @intCast(x.target.resumedRows(slot)); st.len = ids.len; diff --git a/zig/src/families/deepseek_v41/metal/boot.zig b/zig/src/families/deepseek_v41/metal/boot.zig index bdd3e60e783..c2dc7b35845 100644 --- a/zig/src/families/deepseek_v41/metal/boot.zig +++ b/zig/src/families/deepseek_v41/metal/boot.zig @@ -10,6 +10,8 @@ const scratch = @import("scratch.zig"); const forward = @import("forward.zig"); const serve = @import("serve.zig"); const target_ = @import("target.zig"); +const vision = @import("vision.zig"); +const vw = @import("vision_weights.zig"); const Config = host.config.Config; const eh = host.engram_host; @@ -30,6 +32,11 @@ pub const Options = struct { small: bool = false, /// Engram row shards (null: TF_DSV41_ENGRAM_DIR, else the config's engram_table_dir beside the checkpoint) engram_dir: ?[]const u8 = null, + /// --vision: load the checkpoint's image tower (its tensors read beside the backbone) + vision: bool = false, + /// a request's image tokens in all, and its images (--vision-image-tokens, --vision-max-images) + image_tokens: u32 = 4096, + max_images: u32 = 4, }; /// Everything a served model borrows, owned here and closed after the model's target and pass. @@ -47,6 +54,8 @@ pub const Boot = struct { lbuf: [eh.max_layers]u32 = undefined, eng: eh.Host = undefined, rows: ?*er.Rows = null, + kit: ?vision.Kit = null, + vw: ?vw.Weights = null, /// The checkpoint in `dir` loaded and served by a `serve.Metal` (the caller's `serve_lanes.Served` closes it). pub fn open(a: Allocator, io: std.Io, dir: []const u8, o: Options) !*serve.Metal { @@ -56,6 +65,8 @@ pub const Boot = struct { b.ds = null; b.map_bytes = &.{}; b.rows = null; + b.kit = null; + b.vw = null; b.c = try readConfig(a, io, dir, o.small); const c = &b.c; const limit: u32 = @intCast(@min(o.context orelse 262144, c.rope.max_positions)); @@ -71,6 +82,8 @@ pub const Boot = struct { errdefer b.w.deinit(); if (o.drafts and c.mtp_layers > 0) b.ds = try dspark.loadWeights(a, io, b.device, &pack, c); errdefer if (b.ds) |*w| w.deinit(); + try b.loadVision(io, dir, &pack, o); + errdefer b.closeVision(); b.tables = try rope.Tables.init(b.device, c, limit); errdefer b.tables.deinit(); b.s = try scratch.Scratch.init(b.device, c, limit); @@ -79,8 +92,34 @@ pub const Boot = struct { errdefer b.closeEngram(); const r = b.w.report(); std.log.info("dsv41 metal: {d} layers, {d} shards ({d} MiB mapped, {d} MiB copied), {d} slots of {d} positions, DSpark {s}", .{ c.layers, r.shards, r.shard_bytes >> 20, r.arena_bytes >> 20, o.slots, limit, if (b.ds != null) "on" else "off" }); - const env: target_.Env = .{ .device = b.device, .queue = b.queue, .c = c, .p = &b.p, .tables = &b.tables, .s = &b.s, .model = b.w.view(), .lookup = lookup }; - return serve.Metal.open(a, .{ .env = env, .top = &b.w.top, .dspark = if (b.ds) |*w| w else null, .owner = .{ .ctx = b, .close = close }, .resident = if (b.w.resident) |*wr| wr else null }, .{ .slots = o.slots, .limit = limit, .drafts = o.drafts, .cache_bytes = o.cache_bytes }); + const env: target_.Env = .{ .device = b.device, .queue = b.queue, .c = c, .p = &b.p, .tables = &b.tables, .s = &b.s, .model = b.w.view(), .lookup = lookup, .vision = if (b.vw) |*w| .{ .kit = &b.kit.?, .w = w } else null }; + return serve.Metal.open(a, .{ .env = env, .top = &b.w.top, .dspark = if (b.ds) |*w| w else null, .owner = .{ .ctx = b, .close = close }, .resident = if (b.w.resident) |*wr| wr else null, .images = if (b.vw != null) .{ .io = io, .tokens = o.image_tokens, .count = o.max_images } else null }, .{ .slots = o.slots, .limit = limit, .drafts = o.drafts, .cache_bytes = o.cache_bytes }); + } + + /// The tower's kernels and weights, and each layer's image routing bias attached to the backbone's layers. + fn loadVision(b: *Boot, io: std.Io, dir: []const u8, pack: *const host.pack.Pack, o: Options) !void { + if (!o.vision) return; + if (!vw.Weights.present(pack)) { + std.log.err("dsv41 metal: --vision, but {s} has no vision tower (no vision.* tensors)", .{dir}); + return error.NoVisionTower; + } + const path = try std.fs.path.join(b.a, &.{ dir, "config.json" }); + defer b.a.free(path); + const text = try std.Io.Dir.cwd().readFileAlloc(io, path, b.a, .limited(1 << 24)); + defer b.a.free(text); + const cfg = (try vision.Config.parse(b.a, text, b.c.hidden)) orelse vision.Config{ .out_dim = b.c.hidden }; + b.kit = try vision.Kit.load(b.device); + errdefer b.closeVision(); + b.vw = try vw.Weights.load(b.a, io, b.device, pack, cfg, b.c.layers, b.c.experts); + for (b.w.layers, b.vw.?.bias_vl) |*l, r| l.gate_bvl = r; + std.log.info("dsv41 metal: vision tower on ({d} blocks of {d}, patches of {d}, up to {d} tokens an image)", .{ cfg.layers, cfg.dim, cfg.patch, cfg.max_tokens }); + } + + fn closeVision(b: *Boot) void { + if (b.vw) |*w| w.deinit(); + if (b.kit) |*k| k.deinit(); + b.vw = null; + b.kit = null; } fn readConfig(a: Allocator, io: std.Io, dir: []const u8, small: bool) !Config { @@ -151,6 +190,7 @@ pub const Boot = struct { b.s.deinit(); b.tables.deinit(); if (b.ds) |*w| w.deinit(); + b.closeVision(); b.w.deinit(); b.p.deinit(); b.queue.deinit(); diff --git a/zig/src/families/deepseek_v41/metal/entry.zig b/zig/src/families/deepseek_v41/metal/entry.zig index 9efb4f120e8..5aedfde1fad 100644 --- a/zig/src/families/deepseek_v41/metal/entry.zig +++ b/zig/src/families/deepseek_v41/metal/entry.zig @@ -30,6 +30,9 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c .context = if (o.context) |c| @intCast(@max(c, 1)) else null, .drafts = o.drafts, .cache_bytes = if (o.prompt_cache_gib) |g| @intFromFloat(@max(g, 0) * (1 << 30)) else 4 << 30, + .vision = o.vision != null, + .image_tokens = if (o.vision) |v| v.image_tokens else 4096, + .max_images = if (o.vision) |v| v.max_images else 4, .small = try env.read(bool, "TF_DSV41_SMALL", false), }; const m = pkg.boot.Boot.open(gpa, io, o.dir, opts) catch |e| { diff --git a/zig/src/families/deepseek_v41/metal/metal.zig b/zig/src/families/deepseek_v41/metal/metal.zig index 619936fbf58..b62e8873893 100644 --- a/zig/src/families/deepseek_v41/metal/metal.zig +++ b/zig/src/families/deepseek_v41/metal/metal.zig @@ -30,6 +30,12 @@ pub const target = @import("target.zig"); pub const tree = @import("tree.zig"); pub const pass = @import("pass.zig"); pub const serve = @import("serve.zig"); +pub const vision = @import("vision.zig"); +pub const vision_weights = @import("vision_weights.zig"); +pub const vision_tower = @import("vision_tower.zig"); +pub const vision_prep = @import("vision_prep.zig"); +pub const vision_rows = @import("vision_rows.zig"); +pub const vision_prepare = @import("vision_prepare.zig"); pub const boot = @import("boot.zig"); test { @@ -42,4 +48,8 @@ test { _ = dspark_plan; _ = pass; _ = tree; + _ = vision; + _ = vision_prep; + _ = vision_rows; + _ = vision_prepare; } diff --git a/zig/src/families/deepseek_v41/metal/prompt.zig b/zig/src/families/deepseek_v41/metal/prompt.zig index a2b426881e1..3d8ad06f85d 100644 --- a/zig/src/families/deepseek_v41/metal/prompt.zig +++ b/zig/src/families/deepseek_v41/metal/prompt.zig @@ -11,6 +11,8 @@ const pipelines = @import("pipelines.zig"); const ps = @import("prompt_scratch.zig"); const pb = @import("prompt_bufs.zig"); const pl = @import("prompt_layer.zig"); +const vrows = @import("vision_rows.zig"); +const prep = @import("vision_prep.zig"); const Config = host.config.Config; const ced = host.ced; @@ -93,6 +95,8 @@ pub const Prompt = struct { /// rows of logits and taps the last finish wrote (the prompt's last rows) head: u32 = 0, taps: u32 = 0, + /// the image rows of the prompt being run (null: text only); its image positions carry virtual ids + images: ?*const vrows.Rows = null, prof: Prof = .{}, pub fn init(device: mtl.Device, c: *const Config, o: Opts, limit: u32) !Prompt { @@ -160,9 +164,12 @@ pub const Prompt = struct { } } - /// The end of the chunk starting at `a`: `chunk` rows, at most `upto`. + /// The end of the chunk starting at `a`: `chunk` rows, cut so an image's span runs inside one chunk. fn chunkEnd(p: *const Prompt, a: u32, upto: u32) !u32 { - return @min(upto, a + p.o.chunk); + var b = @min(upto, a + p.o.chunk); + if (p.images) |im| b = try im.chunkEnd(a, b); + if (b > upto) return error.ImageSpanSplit; + return b; } /// Commits the chunk [a, b) reading input set `set` (its ids written; its Engram rows too unless `late`). @@ -191,6 +198,7 @@ pub const Prompt = struct { const x = p.px(env, slot, a, b); const bb = &p.b; try g.embed(&env.p.glue, ch.e, env.model.top.embed, bb.ids, bb.streams[0], bb.pres[0], rows, c.hidden, c.vocab); + if (p.images) |im| im.merge(ch.e, bb.streams[0], a, b); for (0..p.d) |i| { const w = &env.model.layers[i]; if (w.layer != i) return error.LayerOrder; @@ -334,12 +342,13 @@ pub const Prompt = struct { return .{ .x = p.b.streams[at], .pre = p.b.pres[at], .x_out = p.b.streams[1 - at], .pre_out = p.b.pres[1 - at] }; } - /// Each row's image flag (the route's bias_vl) for rows [a, b): text rows, all clear. + /// Each row's image flag (the route's bias_vl) for rows [a, b), and the merge's sources. fn imageFlags(p: *const Prompt, a: u32, b: u32) void { - @memset(p.s.bytes(p.s.image, b - a), 0); + const flags = p.s.bytes(p.s.image, b - a); + if (p.images) |im| im.describe(a, b, flags) else @memset(flags, 0); } - /// The chunk's ids (every row's Engram gate open) and Engram rows. + /// The chunk's ids (image positions embed the image token, the Engram gate shuts there) and Engram rows. fn prepare(p: *const Prompt, env: Env, hist: []const u32, a: u32, b: u32, set: usize) !void { try p.writeIds(env, hist, a, b, set); for (0..env.c.engram_layers.len) |li| try p.engramRows(env, hist, a, b, set, li); @@ -368,9 +377,11 @@ pub const Prompt = struct { const emb: []u32 = @alignCast(std.mem.bytesAsSlice(u32, p.b.bytes(st.ids, 4 * ids.len))); const mask = p.b.bytes(st.mask, ids.len); for (ids, emb, mask) |id, *o, *m| { - if (id >= env.c.vocab) return error.BadToken; - o.* = id; - m.* = 1; + const image = prep.isVid(id); + if (image and p.images == null) return error.BadToken; + if (!image and id >= c.vocab) return error.BadToken; + o.* = if (image) p.images.?.embed_id else id; + m.* = @intFromBool(!image); } } diff --git a/zig/src/families/deepseek_v41/metal/serve.zig b/zig/src/families/deepseek_v41/metal/serve.zig index da40fd79f9e..c71e0140a89 100644 --- a/zig/src/families/deepseek_v41/metal/serve.zig +++ b/zig/src/families/deepseek_v41/metal/serve.zig @@ -8,6 +8,7 @@ const prompt = @import("prompt.zig"); const target_ = @import("target.zig"); const pass_ = @import("pass.zig"); const pipelines = @import("pipelines.zig"); +const vision_prepare = @import("vision_prepare.zig"); const serve_lanes = host.serve_lanes; const iface = host.iface; @@ -23,8 +24,13 @@ pub const Parts = struct { owner: ?Owner = null, /// the weights' residency owner the target's buffers join (null: none join) resident: ?*mtl.resident.Resident = null, + /// what a request's images may hold (null: the server is told of no image input) + images: ?Images = null, }; +/// Image input as served: the decoder's io and a request's limits. +pub const Images = struct { io: std.Io, tokens: u32 = 4096, count: u32 = 4 }; + pub const Owner = struct { ctx: *anyopaque, close: *const fn (ctx: *anyopaque) void }; pub const Options = struct { @@ -48,6 +54,9 @@ pub const Metal = struct { /// the idle ticker's target: the weights' residency set (the target's buffers joined it), on a queue of its own warm: ?mtl.keepalive.Target = null, ad: pass_.Pass = undefined, + prep: Prep = undefined, + + const Prep = struct { io: std.Io, cfg: @import("vision.zig").Config }; pub fn open(a: Allocator, parts: Parts, opt: Options) !*Metal { const m = try a.create(Metal); @@ -84,6 +93,7 @@ pub const Metal = struct { const shape: host.dspark.Shape = .{ .block = c.dspark_block, .noise = c.dspark_noise_token, .window = c.window, .rank = c.dspark_markov_rank, .hidden = c.hidden, .candidates = @min(candidates, c.vocab) }; return .{ .ptr = m, + .vision = m.vision(), .name = "dsv41-metal", .slots = m.opt.slots, .limit = m.opt.limit, @@ -103,6 +113,28 @@ pub const Metal = struct { }; } + /// The server's image input: PNG, JPEG or WebP bytes to the tower's patches (null: no tower, or no limits given). + fn vision(m: *Metal) ?api.Vision { + const v = m.parts.env.vision orelse return null; + const lim = m.parts.images orelse return null; + m.prep = .{ .io = lim.io, .cfg = v.w.cfg }; + return .{ .ctx = &m.prep, .prepare = prepare, .image_token = v.w.cfg.image_token_id, .image_tokens = lim.tokens, .max_images = lim.count, .explain = explain }; + } + + /// The server's words for this family's prepare errors it cannot word. + fn explain(err: anyerror) ?[]const u8 { + return switch (err) { + error.TooFewTokens => "the visual-token budget is too small", + else => null, + }; + } + + fn prepare(ctx: *anyopaque, a: Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage { + const p: *const Prep = @ptrCast(@alignCast(ctx)); + const got = try vision_prepare.prepare(p.io, a, bytes, max_tokens, p.cfg); + return .{ .pixels = got.pixels, .gh = got.gh, .gw = got.gw, .tokens = got.tokens, .hash = got.hash }; + } + fn self(ctx: *anyopaque) *Metal { return @ptrCast(@alignCast(ctx)); } diff --git a/zig/src/families/deepseek_v41/metal/target.zig b/zig/src/families/deepseek_v41/metal/target.zig index 5bb25c9394e..f64193c5cf6 100644 --- a/zig/src/families/deepseek_v41/metal/target.zig +++ b/zig/src/families/deepseek_v41/metal/target.zig @@ -11,6 +11,11 @@ const prompt = @import("prompt.zig"); const pipelines = @import("pipelines.zig"); const snapshots = @import("snapshots.zig"); const tree_ = @import("tree.zig"); +const vision = @import("vision.zig"); +const vw = @import("vision_weights.zig"); +const vt = @import("vision_tower.zig"); +const vrows = @import("vision_rows.zig"); +const prep = @import("vision_prep.zig"); const iface = host.iface; const lanes = host.lanes; @@ -30,8 +35,12 @@ pub const Env = struct { s: *const scratch.Scratch, model: forward.Model, lookup: ?forward.Lookup, + /// the vision tower's kernels and weights (null: text only; a prompt with images is refused) + vision: ?VisionRefs = null, }; +pub const VisionRefs = struct { kit: *const vision.Kit, w: *const vw.Weights }; + pub const Options = struct { slots: u32, /// positions a slot holds (the context limit) @@ -66,6 +75,8 @@ pub const Slot = struct { live: bool = false, /// every launch since the request began completed (a release keeps only a whole state) whole: bool = false, + /// the images `setImages` named for the next prompt (their pixels borrowed until it is prefilled) + images: []vrows.Image = &.{}, /// the rows the last prompt took from kept state resumed: u32 = 0, }; @@ -85,6 +96,8 @@ pub const Target = struct { joined: bool = false, /// draft trees: the branches' shadow slots and the open tree window (tree.zig) tree: tree_.Tree = .{}, + /// the ViT and aligner, when the environment has a tower + tower: ?vt.Tower = null, pub fn init(a: Allocator, env: Env, opt: Options) !*Target { const c = env.c; @@ -116,6 +129,7 @@ pub const Target = struct { made += 1; } t.slots = slots; + if (env.vision) |v| t.tower = vt.Tower.init(a, env.device, env.queue, v.kit, v.w); t.joinResident() catch {}; return t; } @@ -151,6 +165,7 @@ pub const Target = struct { s.ptaps.deinit(); a.free(s.ring); s.hist.deinit(a); + a.free(s.images); } pub fn deinit(t: *Target) void { @@ -161,6 +176,7 @@ pub const Target = struct { t.ownBuffers(&bufs) catch {}; for (bufs.items) |b| t.opt.resident.?.remove(b); } + if (t.tower) |*w| w.deinit(); for (t.slots) |*s| freeSlot(t.a, s); t.a.free(t.slots); t.cache.deinit(); @@ -180,7 +196,7 @@ pub const Target = struct { } pub fn target(t: *Target) iface.Target { - return .{ .ptr = t, .vtable = &.{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release, .resumed = resumedFn, .history = history } }; + return .{ .ptr = t, .vtable = &.{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release, .images = imagesFn, .resumed = resumedFn, .history = history } }; } fn self(ptr: *anyopaque) *Target { @@ -201,27 +217,65 @@ pub const Target = struct { // prompts ------------------------------------------------------------------------------------------------------ + /// The images of the slot's next prompt, their pixels borrowed until `prefill` returns. + pub fn setImages(t: *Target, slot: u32, images: []const vrows.Image) !void { + if (slot >= t.slots.len) return error.NoSlot; + const s = &t.slots[slot]; + if (images.len > 0 and t.tower == null) return error.NoVision; + const copy = try t.a.dupe(vrows.Image, images); + t.a.free(s.images); + s.images = copy; + } + + fn imagesFn(ptr: *anyopaque, slot: u32, images: []const vrows.Image) anyerror!void { + return self(ptr).setImages(slot, images); + } + fn resumedFn(ptr: *anyopaque, slot: u32) u64 { const t = self(ptr); return if (slot < t.slots.len) t.slots[slot].resumed else 0; } - fn prefill(ptr: *anyopaque, slot: u32, ids: []const u32, smp: ?lanes.Sampling, draw: u64) anyerror!u32 { + /// `ids` with each image position replaced by its virtual id (the prompt cache's and the Engram hash's view of it). + fn withVids(t: *Target, ids: []const u32, images: []const vrows.Image) ![]u32 { + const out = try t.a.dupe(u32, ids); + errdefer t.a.free(out); + for (images) |im| { + if (@as(u64, im.at) + im.tokens > ids.len) return error.BadImageSpan; + for (0..im.tokens) |p| out[im.at + p] = prep.vid(im.hash, @intCast(p)); + } + return out; + } + + fn prefill(ptr: *anyopaque, slot: u32, ids_in: []const u32, smp: ?lanes.Sampling, draw: u64) anyerror!u32 { const t = self(ptr); if (slot >= t.slots.len) return error.NoSlot; const s = &t.slots[slot]; const c = t.env.c; if (s.live) return error.SlotLive; - if (ids.len == 0) return error.EmptyPrompt; - if (ids.len >= t.opt.limit) return error.PastLimit; - for (ids) |id| if (id >= c.vocab) return error.BadToken; + if (ids_in.len == 0) return error.EmptyPrompt; + if (ids_in.len >= t.opt.limit) return error.PastLimit; + const images = s.images; + s.images = &.{}; + defer t.a.free(images); + var vids: ?[]u32 = null; + defer if (vids) |v| t.a.free(v); + if (images.len > 0) { + if (t.tower == null) return error.NoVision; + vids = try t.withVids(ids_in, images); + } + const ids: []const u32 = vids orelse ids_in; + for (ids) |id| if (id >= c.vocab and !prep.isVid(id)) return error.BadToken; t.tree.forget(slot); s.whole = false; s.open = false; s.rows = 0; t.stats.prompts += 1; - // a kept state that starts this prompt, else a cleared slot - const hit = if (t.cache.on()) t.cache.best(ids) else null; + // a kept state that starts this prompt (not one that ends inside an image's span), else a cleared slot + var hit = if (t.cache.on()) t.cache.best(ids) else null; + if (hit) |e| for (images) |im| if (e.ids.len > im.at and e.ids.len < im.at + im.tokens) { + hit = null; + }; const at: u32 = if (hit) |e| @intCast(e.ids.len) else 0; if (hit) |e| { t.cache.restore(c, e, &s.kv, s.high, s.ring); @@ -240,6 +294,11 @@ pub const Target = struct { // states later prompts can resume from that share less than all of this one (kept as the prompt passes them) const kp = t.keepPoints(ids, at); if (at == n) logits = hit.?.logits.? else { + var rows: ?vrows.Rows = null; + if (images.len > 0) rows = vrows.Rows.build(t.a, t.env.device, &t.tower.?, images, n, t.opt.prompt.chunk, at) catch |e| return t.fail(e); + defer if (rows) |*r| r.deinit(); + t.pr.images = if (rows) |*r| r else null; + defer t.pr.images = null; for ([3]u32{ kp[0], kp[1], n }) |end| { if (end == 0) continue; t.pr.run(t.promptEnv(), &s.kv, &s.tail, ids[0..end]) catch |e| return t.fail(e); diff --git a/zig/src/families/deepseek_v41/metal/vision_prep.zig b/zig/src/families/deepseek_v41/metal/vision_prep.zig new file mode 100644 index 00000000000..67391447a77 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/vision_prep.zig @@ -0,0 +1,166 @@ +//! Image geometry and layout as DeepSeek's image_processor.py has them: resize plan, patches, span layout. +const std = @import("std"); +const vision = @import("vision.zig"); + +/// The first virtual id of an image position: text ids sit below it, and the Engram hash reads it as dead. +pub const vbase: u32 = 1 << 24; + +pub fn isVid(id: u32) bool { + return id >= vbase; +} + +/// What the aligner makes of a patch grid: ceil(patches / ratio) a side. +pub fn llmGrid(gh: u32, gw: u32, ratio: u32) [2]u32 { + return .{ (gh + ratio - 1) / ratio, (gw + ratio - 1) / ratio }; +} + +/// Tokens of an image's span: start, each row of aligner columns then a newline, end. +pub fn spanTokens(lh: u32, lw: u32) u32 { + return lh * (lw + 1) + 2; +} + +/// What a span position holds: the start delimiter, an aligner row, a row's newline, or the end delimiter. +pub const Kind = enum { start, row, newline, end }; + +/// Span position `p` of an image whose aligner grid is lh x lw: its kind and, for a row, its index in reading order. +pub fn kindAt(p: u32, lh: u32, lw: u32) struct { Kind, u32 } { + if (p == 0) return .{ .start, 0 }; + if (p == spanTokens(lh, lw) - 1) return .{ .end, 0 }; + const q = p - 1; + const c = q % (lw + 1); + if (c == lw) return .{ .newline, 0 }; + return .{ .row, (q / (lw + 1)) * lw + c }; +} + +/// A virtual id for position `p` of an image: 31 bits of the image's hash, mixed with the position, above `vbase`. +pub fn vid(hash: u64, p: u32) u32 { + var h = std.hash.Wyhash.init(0x6d6167); + h.update(std.mem.asBytes(&hash)); + h.update(std.mem.asBytes(&p)); + const x: u32 = @truncate(h.final()); + return vbase + x % (std.math.maxInt(u32) - vbase); +} + +/// The pixel size an image is padded to and its grids. +pub const Plan = struct { height: u32, width: u32, vit_h: u32, vit_w: u32, llm_h: u32, llm_w: u32 }; + +fn ceilDiv(x: u32, y: u32) u32 { + return (x + y - 1) / y; +} + +/// The largest aspect-preserving pixel size (height, width) whose token grid fits in `max_n`. +fn solve(height: f64, width: f64, patch: u32, ratio: u32, max_n: u32) [2]u32 { + const r = height / width; + const max_w = @sqrt(@as(f64, @floatFromInt(max_n - 2)) / r + 0.25) - 0.5; + const max_h = max_w * r; + const cell: u32 = patch * ratio; + if (max_w < 1.0) return .{ (max_n - 2) / 2 * cell, cell }; + if (max_h < 1.0) return .{ cell, (max_n - 3) * cell }; + const c: f64 = @floatFromInt(cell); + const beta = @min(@floor(max_w) * c / width, @floor(max_h) * c / height); + const p: f64 = @floatFromInt(patch); + return .{ @as(u32, @intFromFloat(@floor(height * beta / p))) * patch, @as(u32, @intFromFloat(@floor(width * beta / p))) * patch }; +} + +/// plan_image_grid: the pixel size for an image of `width` x `height`, its ViT patch grid and its aligner grid. +pub fn plan(width_in: u32, height_in: u32, cfg: vision.Config) Plan { + var w: f64 = @floatFromInt(width_in); + var h: f64 = @floatFromInt(height_in); + if (cfg.max_wh_ratio) |r| if (w > h * @as(f64, @floatFromInt(r))) { + w = h * @as(f64, @floatFromInt(r)); + }; + if (w * h > 0 and w * h < @as(f64, @floatFromInt(cfg.min_pixels))) { + const ratio = @sqrt(@as(f64, @floatFromInt(cfg.min_pixels)) / (w * h)); + w = @floatFromInt(@as(u64, @intFromFloat(w * ratio))); + h = @floatFromInt(@as(u64, @intFromFloat(h * ratio))); + } + const p = cfg.patch; + var bw: u32 = @as(u32, @intFromFloat(@ceil(w / @as(f64, @floatFromInt(p))))) * p; + var bh: u32 = @as(u32, @intFromFloat(@ceil(h / @as(f64, @floatFromInt(p))))) * p; + var g = llmGrid(bh / p, bw / p, cfg.ratio); + if (spanTokens(g[0], g[1]) > cfg.max_tokens) { + const s = solve(h, w, p, cfg.ratio, cfg.max_tokens); + bh = s[0]; + bw = s[1]; + g = llmGrid(bh / p, bw / p, cfg.ratio); + } + return .{ .height = bh, .width = bw, .vit_h = bh / p, .vit_w = bw / p, .llm_h = g[0], .llm_w = g[1] }; +} + +/// Python's round(): halves to the even integer. +pub fn roundEven(x: f64) u32 { + const f = @floor(x); + const d = x - f; + const i: u32 = @intFromFloat(f); + if (d > 0.5) return i + 1; + if (d < 0.5) return i; + return if (i % 2 == 0) i else i + 1; +} + +/// ImageOps.contain's size: the image fitted inside `bw` x `bh`, aspect kept. +pub fn contain(w: u32, h: u32, bw: u32, bh: u32) [2]u32 { + const im: f64 = @as(f64, @floatFromInt(w)) / @as(f64, @floatFromInt(h)); + const dest: f64 = @as(f64, @floatFromInt(bw)) / @as(f64, @floatFromInt(bh)); + if (im == dest) return .{ bw, bh }; + if (im > dest) { + const nh = roundEven(@as(f64, @floatFromInt(h)) / @as(f64, @floatFromInt(w)) * @as(f64, @floatFromInt(bw))); + return .{ bw, if (nh != bh) nh else bh }; + } + const nw = roundEven(@as(f64, @floatFromInt(w)) / @as(f64, @floatFromInt(h)) * @as(f64, @floatFromInt(bh))); + return .{ if (nw != bw) nw else bw, bh }; +} + +/// The offset ImageOps.pad pastes at along the one axis that is short: round(gap * 0.5). +pub fn padOffset(gap: u32) u32 { + return roundEven(@as(f64, @floatFromInt(gap)) * 0.5); +} + +fn bf16Value(v: f32) f32 { + return @as(f32, @bitCast(@as(u32, @import("weights.zig").bf16Round(v)) << 16)); +} + +/// The ViT's patches [n_h * n_w][3 * p * p] of RGB bytes: (v / 255 - 0.5) / 0.5 in fp32, rounded to bf16. +pub fn patches(rgb: []const u8, height: u32, width: u32, p: u32, out: []f32) void { + const nh = height / p; + const nw = width / p; + std.debug.assert(rgb.len == @as(usize, height) * width * 3 and out.len == @as(usize, nh) * nw * 3 * p * p); + for (0..nh) |by| for (0..nw) |bx| for (0..3) |c| for (0..p) |y| for (0..p) |x| { + const v: f32 = @floatFromInt(rgb[((by * p + y) * width + bx * p + x) * 3 + c]); + const t = ((v / 255.0) - 0.5) / 0.5; + out[((by * nw + bx) * 3 + c) * p * p + y * p + x] = bf16Value(t); + }; +} + +test "the span's layout: start, rows with a newline each, end" { + try std.testing.expectEqual(@as(u32, 2 * 4 + 2), spanTokens(2, 3)); + const k = [_]Kind{ .start, .row, .row, .row, .newline, .row, .row, .row, .newline, .end }; + for (k, 0..) |want, p| try std.testing.expectEqual(want, kindAt(@intCast(p), 2, 3)[0]); + try std.testing.expectEqual(@as(u32, 4), kindAt(6, 2, 3)[1]); +} + +test "the plan: a small image grows to the minimum pixels, a large one shrinks to the token budget" { + const cfg: vision.Config = .{}; + const small = plan(100, 100, cfg); + try std.testing.expect(@as(u64, small.height) * small.width >= cfg.min_pixels); + try std.testing.expectEqual(small.height % 14, 0); + const big = plan(4000, 3000, cfg); + try std.testing.expect(spanTokens(big.llm_h, big.llm_w) <= cfg.max_tokens); + try std.testing.expectEqual(llmGrid(big.vit_h, big.vit_w, 3), [2]u32{ big.llm_h, big.llm_w }); + const tall = plan(10, 20000, cfg); + try std.testing.expect(spanTokens(tall.llm_h, tall.llm_w) <= cfg.max_tokens); +} + +test "Python's round: halves go to even, contain and pad follow" { + try std.testing.expectEqual(@as(u32, 2), roundEven(2.5)); + try std.testing.expectEqual(@as(u32, 4), roundEven(3.5)); + try std.testing.expectEqual(@as(u32, 3), roundEven(3.2)); + try std.testing.expectEqual([2]u32{ 100, 50 }, contain(400, 200, 100, 100)); + try std.testing.expectEqual([2]u32{ 50, 100 }, contain(200, 400, 100, 100)); + try std.testing.expectEqual(@as(u32, 2), padOffset(5)); +} + +test "virtual ids sit above the base and differ by image and position" { + try std.testing.expect(vid(1, 0) >= vbase and vid(1, 5) >= vbase); + try std.testing.expect(vid(1, 0) != vid(2, 0) and vid(1, 0) != vid(1, 1)); + try std.testing.expectEqual(vid(7, 3), vid(7, 3)); +} diff --git a/zig/src/families/deepseek_v41/metal/vision_prepare.zig b/zig/src/families/deepseek_v41/metal/vision_prepare.zig new file mode 100644 index 00000000000..f1a7d6fd6d2 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/vision_prepare.zig @@ -0,0 +1,122 @@ +//! Image bytes to the tower's inputs as DeepSeek's image_processor.py makes them: decode, resize, pad, patches. +const std = @import("std"); +const picture = @import("core").picture; +const vision = @import("vision.zig"); +const prep = @import("vision_prep.zig"); +const weights = @import("weights.zig"); + +/// An image for the tower (PreparedImage's fields): patches on bf16's grid, their grid, span tokens, identity. +pub const Prepared = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 }; + +pub const Error = picture.Error || error{ OutOfMemory, TooFewTokens }; + +/// The family tag of an image's identity: DeepSeek V4.1's vision rows. +const tag: u64 = 0x6473_7634_3176; + +/// `bytes` (PNG, JPEG or WebP) prepared within `max_tokens` span tokens (and the checkpoint's own limit). +pub fn prepare(io: std.Io, gpa: std.mem.Allocator, bytes: []const u8, max_tokens: u32, cfg: vision.Config) Error!Prepared { + var c = cfg; + c.max_tokens = @min(max_tokens, cfg.max_tokens); + if (c.max_tokens < 5) return error.TooFewTokens; + var src = try picture.decode(io, gpa, bytes); + defer src.deinit(gpa); + const pl = prep.plan(@intCast(src.width), @intCast(src.height), c); + const canvas = try gpa.alloc(u8, @as(usize, pl.height) * pl.width * 3); + defer gpa.free(canvas); + const view = picture.resample.View.of(src.pixels, src.width, src.height); + if (c.max_wh_ratio) |r| if (src.width >= @as(usize, r) * src.height) { + // the direct resize of a very wide image + try picture.resample.into(gpa, .pillow, view, pl.width, pl.height, canvas); + return finish(gpa, canvas, pl, bytes, c); + }; + // ImageOps.pad: fit inside, centered on gray 127 + const fit = prep.contain(@intCast(src.width), @intCast(src.height), pl.width, pl.height); + @memset(canvas, 127); + const resized = try gpa.alloc(u8, @as(usize, fit[0]) * fit[1] * 3); + defer gpa.free(resized); + try picture.resample.into(gpa, .pillow, view, fit[0], fit[1], resized); + const x0: usize = if (fit[0] != pl.width) prep.padOffset(pl.width - fit[0]) else 0; + const y0: usize = if (fit[0] == pl.width and fit[1] != pl.height) prep.padOffset(pl.height - fit[1]) else 0; + for (0..fit[1]) |y| @memcpy(canvas[((y0 + y) * pl.width + x0) * 3 ..][0 .. fit[0] * 3], resized[y * fit[0] * 3 ..][0 .. fit[0] * 3]); + return finish(gpa, canvas, pl, bytes, c); +} + +fn finish(gpa: std.mem.Allocator, canvas: []const u8, pl: prep.Plan, bytes: []const u8, c: vision.Config) Error!Prepared { + const px = try gpa.alloc(f32, @as(usize, pl.vit_h) * pl.vit_w * c.patchValues()); + prep.patches(canvas, pl.height, pl.width, c.patch, px); + const grid = [2]u32{ pl.vit_h, pl.vit_w }; + return .{ .pixels = px, .gh = pl.vit_h, .gw = pl.vit_w, .tokens = prep.spanTokens(pl.llm_h, pl.llm_w), .hash = picture.identity.withGrid(picture.identity.ofBytes(tag, bytes), grid) }; +} + +/// A PNG of one colour: stored (uncompressed) deflate blocks, so the test needs no encoder. +pub fn solidPng(a: std.mem.Allocator, w: u32, h: u32, rgb: [3]u8) ![]u8 { + const row = 1 + 3 * @as(usize, w); + const raw = try a.alloc(u8, row * h); + defer a.free(raw); + for (0..h) |y| { + raw[y * row] = 0; + for (0..w) |x| @memcpy(raw[y * row + 1 + 3 * x ..][0..3], &rgb); + } + var z: std.ArrayList(u8) = .empty; + defer z.deinit(a); + try z.appendSlice(a, &.{ 0x78, 0x01 }); + var at: usize = 0; + while (at < raw.len) { + const n: u16 = @intCast(@min(raw.len - at, 65535)); + try z.append(a, if (at + n == raw.len) 1 else 0); + try z.appendSlice(a, &std.mem.toBytes(std.mem.nativeToLittle(u16, n))); + try z.appendSlice(a, &std.mem.toBytes(std.mem.nativeToLittle(u16, ~n))); + try z.appendSlice(a, raw[at..][0..n]); + at += n; + } + try z.appendSlice(a, &std.mem.toBytes(std.mem.nativeToBig(u32, std.hash.Adler32.hash(raw)))); + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(a); + try out.appendSlice(a, "\x89PNG\r\n\x1a\n"); + const ihdr = std.mem.toBytes(std.mem.nativeToBig(u32, w)) ++ std.mem.toBytes(std.mem.nativeToBig(u32, h)) ++ [5]u8{ 8, 2, 0, 0, 0 }; + for ([_]struct { *const [4]u8, []const u8 }{ .{ "IHDR", &ihdr }, .{ "IDAT", z.items }, .{ "IEND", "" } }) |c| { + try out.appendSlice(a, &std.mem.toBytes(std.mem.nativeToBig(u32, @intCast(c[1].len)))); + try out.appendSlice(a, c[0]); + try out.appendSlice(a, c[1]); + var crc = std.hash.Crc32.init(); + crc.update(c[0]); + crc.update(c[1]); + try out.appendSlice(a, &std.mem.toBytes(std.mem.nativeToBig(u32, crc.final()))); + } + return out.toOwnedSlice(a); +} + +fn bf(v: f32) f32 { + return @as(f32, @bitCast(@as(u32, weights.bf16Round(v)) << 16)); +} + +test "prepare: a 60x50 image grows to 602x502 inside 602x504, padded one row top and bottom with gray 127" { + const a = std.testing.allocator; + const png = try solidPng(a, 60, 50, .{ 200, 100, 50 }); + defer a.free(png); + const cfg: vision.Config = .{}; + const p = try prepare(std.testing.io, a, png, 1024, cfg); + defer a.free(p.pixels); + try std.testing.expectEqual(@as(u32, 36), p.gh); + try std.testing.expectEqual(@as(u32, 43), p.gw); + try std.testing.expectEqual(prep.spanTokens(12, 15), p.tokens); + const gray = bf((127.0 / 255.0 - 0.5) / 0.5); + const want = [3]f32{ bf((200.0 / 255.0 - 0.5) / 0.5), bf((100.0 / 255.0 - 0.5) / 0.5), bf((50.0 / 255.0 - 0.5) / 0.5) }; + const pp: usize = 14 * 14; + // patch (0, 0): pixel row 0 is the pad, row 1 the image; patch (35, 0): row 12 the image, row 13 the pad + for (0..3) |c| { + try std.testing.expectEqual(gray, p.pixels[c * pp]); + try std.testing.expectEqual(want[c], p.pixels[c * pp + 14]); + const last = (35 * 43) * 3 * pp; + try std.testing.expectEqual(want[c], p.pixels[last + c * pp + 12 * 14]); + try std.testing.expectEqual(gray, p.pixels[last + c * pp + 13 * 14]); + } + const again = try prepare(std.testing.io, a, png, 1024, cfg); + defer a.free(again.pixels); + try std.testing.expectEqual(p.hash, again.hash); + // a smaller budget shrinks the grid and changes the identity + const small = try prepare(std.testing.io, a, png, 100, cfg); + defer a.free(small.pixels); + try std.testing.expect(small.tokens <= 100 and small.hash != p.hash); + try std.testing.expectError(error.TooFewTokens, prepare(std.testing.io, a, png, 4, cfg)); +} diff --git a/zig/src/families/deepseek_v41/metal/vision_rows.zig b/zig/src/families/deepseek_v41/metal/vision_rows.zig new file mode 100644 index 00000000000..1cc67fc046e --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/vision_rows.zig @@ -0,0 +1,147 @@ +//! A prompt's image rows: where each image's span sits, its aligner rows, and what each prompt row of a chunk takes. +const std = @import("std"); +const mtl = @import("metal"); +const host = @import("dsv41"); +const vision = @import("vision.zig"); +const prep = @import("vision_prep.zig"); +const vt = @import("vision_tower.zig"); + +pub const Image = host.lanes.stream.Image; +const Ref = vision.Ref; + +/// One image's span in the prompt: positions [at, at + tokens), its aligner grid, and its first row in the features. +pub const Span = struct { at: u32, tokens: u32, lh: u32, lw: u32, feat: u32 }; + +pub const Rows = struct { + a: std.mem.Allocator, + pipes: *const vision.Pipelines, + spans: []Span, + /// the aligner rows of every image the prompt still has to run: bf16 [rows][dim], image after image + feat: mtl.Buffer, + delims: Ref, + dim: u32, + /// the embedding row an image position takes before its rows are merged in + embed_id: u32, + /// the chunk's merge sources, int32 [chunk] + src: mtl.Buffer, + chunk: u32, + + /// The spans of `images` (sorted, apart, as long as their grids say) in a prompt of `n` ids. + pub fn init(a: std.mem.Allocator, device: mtl.Device, pipes: *const vision.Pipelines, cfg: vision.Config, delims: Ref, images: []const Image, n: u32, chunk: u32, feat_rows: u32) !Rows { + const spans = try a.alloc(Span, images.len); + errdefer a.free(spans); + var end: u32 = 0; + var row: u32 = 0; + for (images, spans) |im, *s| { + const g = prep.llmGrid(im.gh, im.gw, cfg.ratio); + if (im.tokens != prep.spanTokens(g[0], g[1]) or im.at < end or @as(u64, im.at) + im.tokens > n) return error.BadImageSpan; + if (im.tokens > chunk) return error.ImageSpanTooLong; + s.* = .{ .at = im.at, .tokens = im.tokens, .lh = g[0], .lw = g[1], .feat = row }; + end = im.at + im.tokens; + row += g[0] * g[1]; + } + const feat = try device.buffer(@max(@as(usize, feat_rows) * cfg.out_dim * 2, 256), mtl.ResourceOptions.shared); + errdefer feat.deinit(); + const src = try device.buffer(@max(@as(usize, chunk) * 4, 256), mtl.ResourceOptions.shared); + return .{ .a = a, .pipes = pipes, .spans = spans, .feat = feat, .delims = delims, .dim = cfg.out_dim, .embed_id = cfg.image_token_id, .src = src, .chunk = chunk }; + } + + pub fn deinit(r: *Rows) void { + r.a.free(r.spans); + r.feat.deinit(); + r.src.deinit(); + } + + /// The rows of the images reaching past position `from` (the others are in the state), run through `tower`. + pub fn build(a: std.mem.Allocator, device: mtl.Device, tower: *vt.Tower, images: []const Image, n: u32, chunk: u32, from: u32) !Rows { + const cfg = tower.w.cfg; + var run: std.ArrayList(Image) = .empty; + defer run.deinit(a); + var feat_rows: u32 = 0; + for (images) |im| if (im.at + im.tokens > from) { + try run.append(a, im); + const g = prep.llmGrid(im.gh, im.gw, cfg.ratio); + feat_rows += g[0] * g[1]; + }; + var rows = try init(a, device, &tower.kit.v, cfg, tower.w.delims, run.items, n, chunk, feat_rows); + errdefer rows.deinit(); + const dim: usize = cfg.out_dim; + for (run.items, rows.spans) |im, sp| { + try tower.run(im.pixels, im.gh, im.gw, .{}); + const out = tower.output(); + const bytes = @as(usize, sp.lh) * sp.lw * dim * 2; + @memcpy(rows.feat.contents()[@as(usize, sp.feat) * dim * 2 ..][0..bytes], (out.buf.contents() + out.off)[0..bytes]); + } + return rows; + } + + /// The aligner rows of every span, in the order the spans were given. + pub fn totalRows(spans: []const Span) u32 { + var n: u32 = 0; + for (spans) |s| n += s.lh * s.lw; + return n; + } + + fn spanOf(r: *const Rows, pos: u32) ?*const Span { + for (r.spans) |*s| if (pos >= s.at and pos < s.at + s.tokens) return s; + return null; + } + + /// Whether prompt position `pos` is an image position. + pub fn isImage(r: *const Rows, pos: u32) bool { + return r.spanOf(pos) != null; + } + + /// The end of the chunk [a, b): pulled back to a span's start, or pushed past it, when it would cut one. + pub fn chunkEnd(r: *const Rows, a: u32, b: u32) !u32 { + if (r.spanOf(a)) |s| if (s.at != a) return error.ImageSpanSplit; + const s = r.spanOf(b) orelse return b; + if (s.at == b) return b; + if (s.at > a) return s.at; + if (s.at + s.tokens > a + r.chunk) return error.ImageSpanTooLong; + return s.at + s.tokens; + } + + /// For rows [a, b): the merge sources into `src`, and the image flags (1 on an image position) into `flags`. + pub fn describe(r: *const Rows, a: u32, b: u32, flags: []u8) void { + const src: []i32 = r.src.slice(i32, b - a); + for (a..b) |q| { + const i = q - a; + const s = r.spanOf(@intCast(q)) orelse { + src[i] = -4; + flags[i] = 0; + continue; + }; + flags[i] = 1; + const k = prep.kindAt(@as(u32, @intCast(q)) - s.at, s.lh, s.lw); + src[i] = switch (k[0]) { + .start => -1, + .end => -2, + .newline => -3, + .row => @intCast(s.feat + k[1]), + }; + } + } + + /// The merge of rows [a, b) into the streams' first buffer (after the embedding, before the first layer). + pub fn merge(r: *const Rows, e: mtl.ComputeEncoder, streams: Ref, a: u32, b: u32) void { + vision.merge(r.pipes, e, .{ .buf = r.feat }, r.delims, .{ .buf = r.src }, streams, b - a, r.dim); + } + + /// The ids the embedding reads for rows of `ids`: image positions take the image token's row. + pub fn embedId(r: *const Rows, id: u32) u32 { + return if (prep.isVid(id)) r.embed_id else id; + } +}; + +test "a span's chunk end: pulled back to the start, or pushed past the span" { + var r: Rows = undefined; + var spans = [_]Span{.{ .at = 10, .tokens = 6, .lh = 1, .lw = 3, .feat = 0 }}; + r.spans = &spans; + r.chunk = 8; + try std.testing.expectEqual(@as(u32, 10), try r.chunkEnd(0, 12)); + try std.testing.expectEqual(@as(u32, 9), try r.chunkEnd(0, 9)); + try std.testing.expectEqual(@as(u32, 16), try r.chunkEnd(10, 12)); + try std.testing.expectEqual(@as(u32, 20), try r.chunkEnd(16, 20)); + try std.testing.expectError(error.ImageSpanSplit, r.chunkEnd(12, 14)); +} diff --git a/zig/src/families/deepseek_v41/metal/vision_tower.zig b/zig/src/families/deepseek_v41/metal/vision_tower.zig new file mode 100644 index 00000000000..253fa574a86 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/vision_tower.zig @@ -0,0 +1,174 @@ +//! One image through the ViT and aligner: patches in, the aligner's rows (bf16 [tokens][out_dim]) out. +const std = @import("std"); +const mtl = @import("metal"); +const vision = @import("vision.zig"); +const vw = @import("vision_weights.zig"); +const glue = @import("glue.zig"); + +const Ref = vision.Ref; + +/// What a run covers: the first `blocks` ViT blocks (null: all), then the final norm and aligner (`align`). +pub const Run = struct { blocks: ?u32 = null, finish: bool = true }; + +pub const Tower = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kit: *const vision.Kit, + w: *const vw.Weights, + /// scratch for the largest image so far (grown, never shrunk) + buf: ?mtl.Buffer = null, + cap_n: u32 = 0, + cap_t: u32 = 0, + cs: ?mtl.Buffer = null, + table: std.ArrayList([2]f32) = .empty, + /// patches in, the residual stream and the aligner's output of the last run + refs: Refs = undefined, + + const Refs = struct { pin: Ref, x: Ref, xn: Ref, acc: Ref, qkv: Ref, o: Ref, h: Ref, u: Ref, t: Ref, out: Ref }; + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kit: *const vision.Kit, w: *const vw.Weights) Tower { + return .{ .a = a, .device = device, .queue = queue, .kit = kit, .w = w }; + } + + pub fn deinit(t: *Tower) void { + if (t.buf) |b| b.deinit(); + if (t.cs) |b| b.deinit(); + t.table.deinit(t.a); + } + + /// The scratch's places for `n` patches and `tokens` aligner rows; the total bytes. + fn layout(t: *Tower, n: u32, tokens: u32) usize { + const c = t.w.cfg; + var off: usize = 0; + const take = struct { + fn f(o: *usize, len: usize) usize { + const at = std.mem.alignForward(usize, o.*, 256); + o.* = at + @max(len, 4); + return at; + } + }.f; + const N: usize = n; + const L: usize = tokens; + const at = [10]usize{ + take(&off, N * c.patchValues() * 2), + take(&off, N * c.dim * 2), + take(&off, N * c.dim * 2), + take(&off, @max(N * 2 * c.inter, @max(N * 3 * c.dim, L * c.out_dim)) * 4), + take(&off, N * 3 * c.dim * 2), + take(&off, N * c.dim * 2), + take(&off, N * c.inter * 2), + take(&off, L * c.alignIn() * 2), + take(&off, L * c.out_dim * 2), + take(&off, L * c.out_dim * 2), + }; + if (t.buf) |b| { + const f = struct { + fn r(bb: mtl.Buffer, o: usize) Ref { + return .{ .buf = bb, .off = o }; + } + }.r; + t.refs = .{ .pin = f(b, at[0]), .x = f(b, at[1]), .xn = f(b, at[2]), .acc = f(b, at[3]), .qkv = f(b, at[4]), .o = f(b, at[5]), .h = f(b, at[6]), .u = f(b, at[7]), .t = f(b, at[8]), .out = f(b, at[9]) }; + } + return off; + } + + /// The scratch for `n` patches and `tokens` aligner rows, regrown when this run is larger than any before. + fn ensure(t: *Tower, n: u32, tokens: u32) !void { + if (n <= t.cap_n and tokens <= t.cap_t) return; + if (t.buf) |b| b.deinit(); + t.buf = null; + t.cap_n = @max(n, t.cap_n); + t.cap_t = @max(tokens, t.cap_t); + t.buf = try t.device.buffer(t.layout(t.cap_n, t.cap_t), mtl.ResourceOptions.shared); + _ = t.layout(t.cap_n, t.cap_t); + } + + pub fn tokensOf(t: *const Tower, gh: u32, gw: u32) u32 { + const r = t.w.cfg.ratio; + return ((gh + r - 1) / r) * ((gw + r - 1) / r); + } + + /// The aligner's rows of the last `run` (bf16 [tokens][out_dim]); the residual stream after the last block is `x`. + pub fn output(t: *const Tower) Ref { + return t.refs.out; + } + + pub fn stream(t: *const Tower) Ref { + return t.refs.x; + } + + /// `patches` [gh * gw][3 * patch^2] (values bf16 holds exactly) through the tower into `output()`. + pub fn run(t: *Tower, patches: []const f32, gh: u32, gw: u32, o: Run) !void { + const c = t.w.cfg; + const n = gh * gw; + if (n == 0 or patches.len != @as(usize, n) * c.patchValues()) return error.BadPatches; + const tokens = t.tokensOf(gh, gw); + try t.ensure(n, tokens); + const r = t.refs; + const pin: []u16 = @alignCast(std.mem.bytesAsSlice(u16, (r.pin.buf.contents() + r.pin.off)[0 .. patches.len * 2])); + for (pin, patches) |*d, v| d.* = bf16(v); + try t.cosSin(gh, gw); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = t.queue.commandBuffer(); + const e = cb.compute(.serial); + try t.encode(e, gh, gw, tokens, o); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.debug.print("dsv41 vision command buffer failed: {s}\n", .{msg}); + return error.CommandBufferFailed; + } + } + + fn cosSin(t: *Tower, gh: u32, gw: u32) !void { + const half = t.w.cfg.headDim() / 2; + try t.table.resize(t.a, @as(usize, gh) * gw * half); + vision.ropeTable(t.table.items, gh, gw, t.w.cfg.headDim(), t.w.cfg.theta); + const bytes = std.mem.sliceAsBytes(t.table.items); + if (t.cs == null or t.cs.?.length() < bytes.len) { + if (t.cs) |b| b.deinit(); + t.cs = try t.device.buffer(bytes.len, mtl.ResourceOptions.shared); + } + @memcpy(t.cs.?.contents()[0..bytes.len], bytes); + } + + fn encode(t: *Tower, e: mtl.ComputeEncoder, gh: u32, gw: u32, tokens: u32, o: Run) !void { + const c = t.w.cfg; + const w = t.w; + const v = &t.kit.v; + const gp = &t.kit.g; + const r = t.refs; + const n = gh * gw; + const D = c.dim; + try glue.mv(gp, e, r.pin, w.patch_w, r.acc, n, c.patchValues(), D, true); + vision.epilogue(v, e, r.acc, w.patch_b, null, r.x, n, D, false); + const cs: Ref = .{ .buf = t.cs.? }; + for (w.blocks[0..@min(o.blocks orelse c.layers, c.layers)]) |b| { + glue.rmsnorm(gp, e, r.x, b.norm1, r.xn, n, D, c.eps); + try glue.mv(gp, e, r.xn, b.wqkv, r.acc, n, D, 3 * D, true); + vision.qkv(v, e, r.acc, b.bqkv, cs, r.qkv, n, c.heads, c.headDim()); + vision.attention(v, e, r.qkv, r.o, n, c.heads); + try glue.mv(gp, e, r.o, b.wo, r.acc, n, D, D, true); + vision.epilogue(v, e, r.acc, b.bo, r.x, r.x, n, D, false); + glue.rmsnorm(gp, e, r.x, b.norm2, r.xn, n, D, c.eps); + try glue.mv(gp, e, r.xn, b.w1, r.acc, n, D, 2 * c.inter, true); + vision.swiglu(v, e, r.acc, r.h, n, c.inter); + try glue.mv(gp, e, r.h, b.w2, r.acc, n, c.inter, D, true); + vision.epilogue(v, e, r.acc, null, r.x, r.x, n, D, false); + } + if (!o.finish) return; + glue.rmsnorm(gp, e, r.x, w.norm, r.xn, n, D, c.eps); + vision.unshuffle(v, e, r.xn, r.u, gh, gw, D, c.ratio); + try glue.mv(gp, e, r.u, w.al_w1, r.acc, tokens, c.alignIn(), c.out_dim, true); + vision.epilogue(v, e, r.acc, w.al_b1, null, r.t, tokens, c.out_dim, true); + try glue.mv(gp, e, r.t, w.al_w2, r.acc, tokens, c.out_dim, c.out_dim, true); + vision.epilogue(v, e, r.acc, w.al_b2, null, r.out, tokens, c.out_dim, false); + } +}; + +pub fn bf16(v: f32) u16 { + return @import("weights.zig").bf16Round(v); +} diff --git a/zig/src/families/deepseek_v41/metal/vision_weights.zig b/zig/src/families/deepseek_v41/metal/vision_weights.zig new file mode 100644 index 00000000000..c45be614a29 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/vision_weights.zig @@ -0,0 +1,108 @@ +//! The release's vision tensors in one arena: ViT blocks, aligner, span delimiters and image routing biases. +const std = @import("std"); +const mtl = @import("metal"); +const host = @import("dsv41"); +const weights = @import("weights.zig"); +const vision = @import("vision.zig"); + +const Ref = vision.Ref; +const Pack = host.pack.Pack; +const align_raw: u32 = 8; + +/// One ViT block: fp32 norm weights, bf16 projections [n][k] and biases. +pub const Block = struct { norm1: Ref, wqkv: Ref, bqkv: Ref, wo: Ref, bo: Ref, norm2: Ref, w1: Ref, w2: Ref }; + +pub const Weights = struct { + a: std.mem.Allocator, + cfg: vision.Config, + arena: mtl.Buffer, + patch_w: Ref, + patch_b: Ref, + blocks: []Block, + norm: Ref, + al_w1: Ref, + al_b1: Ref, + al_w2: Ref, + al_b2: Ref, + /// image_start, image_end, image_newline: bf16 [out_dim] each, in that order, one array [3][out_dim] + delims: Ref, + /// each text layer's `ffn.gate.bias_vl` [experts] fp32 (the routing bias of image rows) + bias_vl: []Ref, + + pub fn deinit(w: *Weights) void { + w.arena.deinit(); + w.delims.buf.deinit(); + w.a.free(w.blocks); + w.a.free(w.bias_vl); + } + + /// Whether the pack carries the tower. + pub fn present(pack: *const Pack) bool { + return pack.has("vision.patch_embed.proj.weight"); + } + + /// The tower's tensors read from `pack` into one arena; `layers` and `experts` are the text model's. + pub fn load(a: std.mem.Allocator, io: std.Io, device: mtl.Device, pack: *const Pack, cfg: vision.Config, layers: u32, experts: u32) !Weights { + try cfg.check(); + var l: weights.Loader = .{ .a = a, .pack = pack }; + defer l.items.deinit(a); + var buf: [96]u8 = undefined; + const D = cfg.dim; + const S = struct { + fn tensor(ld: *weights.Loader, b: []u8, comptime fmt: []const u8, args: anytype, dtype: host.pack.DType, shape: []const usize, into: weights.Into) !weights.Place { + const name = try std.fmt.bufPrint(b, fmt, args); + const info = try ld.pack.need(name); + if (!info.is(dtype, shape)) return error.BadVisionTensor; + return ld.add(info, into, align_raw); + } + }; + const patch_w = try S.tensor(&l, &buf, "vision.patch_embed.proj.weight", .{}, .bf16, &.{ D, cfg.patchValues() }, .raw); + const patch_b = try S.tensor(&l, &buf, "vision.patch_embed.proj.bias", .{}, .bf16, &.{D}, .raw); + const places = try a.alloc([8]weights.Place, cfg.layers); + defer a.free(places); + for (places, 0..) |*p, i| { + const k: u32 = @intCast(i); + p.* = .{ + try S.tensor(&l, &buf, "vision.blocks.{d}.norm1.weight", .{k}, .bf16, &.{D}, .f32), + try S.tensor(&l, &buf, "vision.blocks.{d}.attn.wqkv.weight", .{k}, .bf16, &.{ 3 * D, D }, .raw), + try S.tensor(&l, &buf, "vision.blocks.{d}.attn.wqkv.bias", .{k}, .bf16, &.{3 * D}, .raw), + try S.tensor(&l, &buf, "vision.blocks.{d}.attn.wo.weight", .{k}, .bf16, &.{ D, D }, .raw), + try S.tensor(&l, &buf, "vision.blocks.{d}.attn.wo.bias", .{k}, .bf16, &.{D}, .raw), + try S.tensor(&l, &buf, "vision.blocks.{d}.norm2.weight", .{k}, .bf16, &.{D}, .f32), + try S.tensor(&l, &buf, "vision.blocks.{d}.mlp.w1.weight", .{k}, .bf16, &.{ 2 * cfg.inter, D }, .raw), + try S.tensor(&l, &buf, "vision.blocks.{d}.mlp.w2.weight", .{k}, .bf16, &.{ D, cfg.inter }, .raw), + }; + } + const norm = try S.tensor(&l, &buf, "vision.norm.weight", .{}, .bf16, &.{D}, .f32); + const A = cfg.out_dim; + const al_w1 = try S.tensor(&l, &buf, "aligner.w1.weight", .{}, .bf16, &.{ A, cfg.alignIn() }, .raw); + const al_b1 = try S.tensor(&l, &buf, "aligner.w1.bias", .{}, .bf16, &.{A}, .raw); + const al_w2 = try S.tensor(&l, &buf, "aligner.w2.weight", .{}, .bf16, &.{ A, A }, .raw); + const al_b2 = try S.tensor(&l, &buf, "aligner.w2.bias", .{}, .bf16, &.{A}, .raw); + // the delimiters are three tensors, so they land in one run of the arena: aligned, consecutive + var dl: [3]weights.Place = undefined; + for ([_][]const u8{ "image_start", "image_end", "image_newline" }, 0..) |n, i| { + const info = try pack.need(n); + if (!info.is(.bf16, &.{A})) return error.BadVisionTensor; + dl[i] = try l.add(info, .raw, align_raw); + } + const bias = try a.alloc(weights.Place, layers); + defer a.free(bias); + for (bias, 0..) |*p, i| p.* = try S.tensor(&l, &buf, "layers.{d}.ffn.gate.bias_vl", .{@as(u32, @intCast(i))}, .f32, &.{experts}, .f32); + const arena = try device.buffer(@max(l.size, 256), mtl.ResourceOptions.shared); + errdefer arena.deinit(); + try l.fill(io, arena.contents()[0..l.size]); + var w: Weights = .{ .a = a, .cfg = cfg, .arena = arena, .patch_w = patch_w.ref(arena), .patch_b = patch_b.ref(arena), .blocks = &.{}, .norm = norm.ref(arena), .al_w1 = al_w1.ref(arena), .al_b1 = al_b1.ref(arena), .al_w2 = al_w2.ref(arena), .al_b2 = al_b2.ref(arena), .delims = undefined, .bias_vl = &.{} }; + // the delimiters are copied side by side (the merge kernel reads them as one [3][out_dim] array) + const dbuf = try device.buffer(3 * A * 2, mtl.ResourceOptions.shared); + errdefer dbuf.deinit(); + for (dl, 0..) |p, i| @memcpy(dbuf.contents()[i * A * 2 ..][0 .. A * 2], arena.contents()[p.off..][0 .. A * 2]); + w.delims = .{ .buf = dbuf }; + w.blocks = try a.alloc(Block, cfg.layers); + errdefer a.free(w.blocks); + for (w.blocks, places) |*b, p| b.* = .{ .norm1 = p[0].ref(arena), .wqkv = p[1].ref(arena), .bqkv = p[2].ref(arena), .wo = p[3].ref(arena), .bo = p[4].ref(arena), .norm2 = p[5].ref(arena), .w1 = p[6].ref(arena), .w2 = p[7].ref(arena) }; + w.bias_vl = try a.alloc(Ref, layers); + for (w.bias_vl, bias) |*r, p| r.* = p.ref(arena); + return w; + } +}; diff --git a/zig/src/families/deepseek_v41/phases_timed.zig b/zig/src/families/deepseek_v41/phases_timed.zig index b2c38fadaeb..43a9b8c67ad 100644 --- a/zig/src/families/deepseek_v41/phases_timed.zig +++ b/zig/src/families/deepseek_v41/phases_timed.zig @@ -17,7 +17,11 @@ pub const TimedTarget = struct { return .{ .ptr = t, .vtable = &vtable }; } - const vtable: iface.Target.VTable = .{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release, .admit = admit, .begin = begin, .piece = piece, .finish = finish, .tail = tail, .pieces = pieces, .replays = replays, .warm = warm, .resumed = resumed }; + const vtable: iface.Target.VTable = .{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release, .admit = admit, .begin = begin, .piece = piece, .finish = finish, .tail = tail, .pieces = pieces, .replays = replays, .warm = warm, .images = images, .resumed = resumed }; + + fn images(p: *anyopaque, slot: u32, list: []const lanes.stream.Image) anyerror!void { + return self(p).inner.setImages(slot, list); + } fn resumed(p: *anyopaque, slot: u32) u64 { return self(p).inner.resumedRows(slot); diff --git a/zig/src/server/deepseek_chat_test.zig b/zig/src/server/deepseek_chat_test.zig index 1001362650c..1a70e1b663e 100644 --- a/zig/src/server/deepseek_chat_test.zig +++ b/zig/src/server/deepseek_chat_test.zig @@ -133,7 +133,19 @@ test "DeepSeek chat: an explicit override wins, a checkpoint Jinja does not, and // a server with image input: the part becomes the image token, which images.zig expands const served = try native.text().render(a, images, .{ .images = true }, &problem); const ids = try served.encode(native.text(), a, &problem); - try t.expect(std.mem.indexOfScalar(u32, ids, native.text().tokenId("<|deepseek_image|>").?) != null); + const image_token = "<|deepseek_image|>"; + const image_id = native.text().tokenId(image_token).?; + try t.expect(std.mem.indexOfScalar(u32, ids, image_id) != null); + // a text part that spells the token beside an image part: two spellings, only the image's is the template's + const typed = (try json.parseText(a, "[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"<|deepseek_image|>\"},{\"type\":\"image_url\",\"image_url\":{\"url\":\"x\"}}]}]")).ok; + const both = try native.text().render(a, typed, .{ .images = true }, &problem); + try t.expectEqual(@as(usize, 2), std.mem.count(u8, both.text, image_token)); + const first = std.mem.indexOf(u8, both.text, image_token).?; + const second = std.mem.indexOfPos(u8, both.text, first + 1, image_token).?; + try t.expect(!both.isTemplate(first, first + image_token.len)); + try t.expect(both.isTemplate(second, second + image_token.len)); + const both_ids = try both.encode(native.text(), a, &problem); + try t.expectEqual(@as(usize, 1), std.mem.count(u32, both_ids, &.{image_id})); } test "DeepSeek chat: response_format shows its schema unless TF_DSV41_SCHEMA_PROMPT=0" { diff --git a/zig/tests/dsv41_metal/fixture_vis.zig b/zig/tests/dsv41_metal/fixture_vis.zig new file mode 100644 index 00000000000..f0ca833ee6e --- /dev/null +++ b/zig/tests/dsv41_metal/fixture_vis.zig @@ -0,0 +1,87 @@ +//! A tiny vision tower's tensors under the release's names as a safetensors image, and synthetic patches for it. +const std = @import("std"); +const pkg = @import("dsv41_metal"); +const host = @import("dsv41"); +const ref = @import("ref.zig"); + +const Spec = host.pack.Spec; +pub const vision = pkg.vision; + +/// 2 blocks of 2 heads, 4-pixel patches, 3x3 blocks into the tiny model's 256 hidden. +pub fn config() vision.Config { + return .{ .layers = 2, .dim = 128, .heads = 2, .inter = 192, .patch = 4, .ratio = 3, .max_tokens = 64, .out_dim = 256, .image_token_id = 255, .min_pixels = 1024 }; +} + +const Gen = enum { norm, unit, bias, delim, f32 }; + +/// The tower's tensors, the delimiters and each text layer's image routing bias, drawn from `seed`. +pub fn image(a: std.mem.Allocator, cfg: vision.Config, layers: u32, experts: u32, seed: u64) ![]u8 { + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const al = arena.allocator(); + var specs: std.ArrayList(Spec) = .empty; + var gens: std.ArrayList(Gen) = .empty; + var ks: std.ArrayList(usize) = .empty; + const add = struct { + fn f(s: *std.ArrayList(Spec), g: *std.ArrayList(Gen), k: *std.ArrayList(usize), x: std.mem.Allocator, name: []const u8, dtype: []const u8, shape: []const usize, gen: Gen, kk: usize) !void { + try s.append(x, .{ .name = try x.dupe(u8, name), .dtype = dtype, .shape = try x.dupe(usize, shape) }); + try g.append(x, gen); + try k.append(x, kk); + } + }.f; + const D: usize = cfg.dim; + const A: usize = cfg.out_dim; + var nb: [96]u8 = undefined; + try add(&specs, &gens, &ks, al, "vision.patch_embed.proj.weight", "BF16", &.{ D, cfg.patchValues() }, .unit, cfg.patchValues()); + try add(&specs, &gens, &ks, al, "vision.patch_embed.proj.bias", "BF16", &.{D}, .bias, 1); + for (0..cfg.layers) |i| { + const t = [_]struct { []const u8, []const usize, Gen, usize }{ + .{ "norm1.weight", &.{D}, .norm, 1 }, .{ "attn.wqkv.weight", &.{ 3 * D, D }, .unit, D }, + .{ "attn.wqkv.bias", &.{3 * D}, .bias, 1 }, .{ "attn.wo.weight", &.{ D, D }, .unit, D }, + .{ "attn.wo.bias", &.{D}, .bias, 1 }, .{ "norm2.weight", &.{D}, .norm, 1 }, + .{ "mlp.w1.weight", &.{ 2 * cfg.inter, D }, .unit, D }, .{ "mlp.w2.weight", &.{ D, cfg.inter }, .unit, cfg.inter }, + }; + for (t) |x| try add(&specs, &gens, &ks, al, try std.fmt.bufPrint(&nb, "vision.blocks.{d}.{s}", .{ i, x[0] }), "BF16", x[1], x[2], x[3]); + } + try add(&specs, &gens, &ks, al, "vision.norm.weight", "BF16", &.{D}, .norm, 1); + try add(&specs, &gens, &ks, al, "aligner.w1.weight", "BF16", &.{ A, cfg.alignIn() }, .unit, cfg.alignIn()); + try add(&specs, &gens, &ks, al, "aligner.w1.bias", "BF16", &.{A}, .bias, 1); + try add(&specs, &gens, &ks, al, "aligner.w2.weight", "BF16", &.{ A, A }, .unit, A); + try add(&specs, &gens, &ks, al, "aligner.w2.bias", "BF16", &.{A}, .bias, 1); + for ([_][]const u8{ "image_start", "image_end", "image_newline" }) |n| try add(&specs, &gens, &ks, al, n, "BF16", &.{A}, .delim, 1); + for (0..layers) |i| try add(&specs, &gens, &ks, al, try std.fmt.bufPrint(&nb, "layers.{d}.ffn.gate.bias_vl", .{i}), "F32", &.{experts}, .f32, 1); + const bytes = try host.pack.image(a, specs.items); + const head: usize = @intCast(std.mem.readInt(u64, bytes[0..8], .little)); + var at = 8 + head; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (specs.items, gens.items, ks.items) |s, g, k| { + var n = host.pack.DType.parse(s.dtype).?.size(); + for (s.shape) |d| n *= d; + const out = bytes[at..][0..n]; + for (0..n / (if (g == .f32) @as(usize, 4) else 2)) |i| { + const u = rng.float(f32) * 2 - 1; + switch (g) { + .norm => std.mem.writeInt(u16, out[2 * i ..][0..2], ref.toBf(1 + 0.1 * u), .little), + .unit => std.mem.writeInt(u16, out[2 * i ..][0..2], ref.toBf(u * @sqrt(3.0 / @as(f32, @floatFromInt(k)))), .little), + .bias => std.mem.writeInt(u16, out[2 * i ..][0..2], ref.toBf(0.1 * u), .little), + .delim => std.mem.writeInt(u16, out[2 * i ..][0..2], ref.toBf(u), .little), + .f32 => std.mem.writeInt(u32, out[4 * i ..][0..4], @bitCast(u), .little), + } + } + at += n; + } + return bytes; +} + +/// Patches [gh * gw][patchValues] as the preprocessor makes them: values in [-1, 1] on bf16's grid, with structure. +pub fn patches(a: std.mem.Allocator, cfg: vision.Config, gh: u32, gw: u32, seed: u64) ![]f32 { + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const out = try a.alloc(f32, @as(usize, gh) * gw * cfg.patchValues()); + for (out, 0..) |*v, i| { + const smooth = @sin(@as(f32, @floatFromInt(i % 97)) * 0.3); + v.* = @as(f32, @bitCast(@as(u32, ref.toBf(0.7 * smooth + 0.3 * (rng.float(f32) * 2 - 1))) << 16)); + } + return out; +} diff --git a/zig/tests/dsv41_metal/layer_test.zig b/zig/tests/dsv41_metal/layer_test.zig index 9e3aa03a2a2..0ebf4f33899 100644 --- a/zig/tests/dsv41_metal/layer_test.zig +++ b/zig/tests/dsv41_metal/layer_test.zig @@ -20,6 +20,7 @@ test { _ = @import("multi_test.zig"); _ = @import("units_test.zig"); _ = @import("tile_test.zig"); + _ = @import("vision_test.zig"); } test "dsv41 metal: every stage of every layer kind within its float64 bound" { diff --git a/zig/tests/dsv41_metal/serve_test.zig b/zig/tests/dsv41_metal/serve_test.zig index 2f39ad8b534..b4127fde798 100644 --- a/zig/tests/dsv41_metal/serve_test.zig +++ b/zig/tests/dsv41_metal/serve_test.zig @@ -15,6 +15,7 @@ const seed = 71; test { _ = @import("boot_test.zig"); _ = @import("tree_test.zig"); + _ = @import("vision_boot_test.zig"); } /// A reply's tokens and finish, written on LaneHost's thread and read on the test's. diff --git a/zig/tests/dsv41_metal/vision_boot_test.zig b/zig/tests/dsv41_metal/vision_boot_test.zig new file mode 100644 index 00000000000..8e36a48a718 --- /dev/null +++ b/zig/tests/dsv41_metal/vision_boot_test.zig @@ -0,0 +1,179 @@ +//! --vision on a small checkpoint booted as the server boots one: the tower, the image biases, an image prompt. +const std = @import("std"); +const pkg = @import("dsv41_metal"); +const fv = @import("fixture_vis.zig"); +const boot_test = @import("boot_test.zig"); +const vt = @import("vision_test.zig"); + +const testing = std.testing; +const host = @import("dsv41"); +const api = host.api; +const vis = pkg.vision; +const prep = pkg.vision_prep; +const vrows = pkg.vision_rows; +const say = vt.say; + +/// A booted small checkpoint's folder with the tiny tower's tensors as a fourth shard named in the index. +fn writeWithVision(a: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, cfg: vis.Config, seed: u64) !void { + try boot_test.write(a, io, dir, seed); + const c = boot_test.config(); + const img = try fv.image(a, cfg, c.layers, c.experts, seed + 1); + defer a.free(img); + try dir.writeFile(io, .{ .sub_path = "model-vision.safetensors", .data = img }); + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const al = arena.allocator(); + const hlen: usize = @intCast(std.mem.readInt(u64, img[0..8], .little)); + const head = try std.json.parseFromSliceLeaky(std.json.Value, al, img[8..][0..hlen], .{}); + var index: []const u8 = try dir.readFileAlloc(io, "model.safetensors.index.json", al, .limited(1 << 24)); + index = std.mem.trimEnd(u8, index, "}"); + var out: std.Io.Writer.Allocating = .init(al); + try out.writer.writeAll(index); + var it = head.object.iterator(); + while (it.next()) |e| if (!std.mem.eql(u8, e.key_ptr.*, "__metadata__")) try out.writer.print(",\"{s}\":\"model-vision.safetensors\"", .{e.key_ptr.*}); + try out.writer.writeAll("}}"); + try dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = out.written() }); + // the config names the tower and the image token + var json: []const u8 = try dir.readFileAlloc(io, "config.json", al, .limited(1 << 24)); + json = std.mem.trimEnd(u8, json, " \n"); + json = json[0 .. json.len - 1]; + const extra = try std.fmt.allocPrint(al, ",\"image_token_id\":{d},\"vision_config\":{{\"num_hidden_layers\":{d},\"hidden_size\":{d},\"num_attention_heads\":{d},\"intermediate_size\":{d},\"patch_size\":{d},\"rope_theta\":10000,\"downsample_ratio\":{d},\"max_image_tokens\":{d},\"min_pixels\":{d}}}}}", .{ cfg.image_token_id, cfg.layers, cfg.dim, cfg.heads, cfg.inter, cfg.patch, cfg.ratio, cfg.max_tokens, cfg.min_pixels }); + try dir.writeFile(io, .{ .sub_path = "config.json", .data = try std.mem.concat(al, u8, &.{ json, extra }) }); +} + +test "dsv41 metal vision: --vision at boot loads the tower and the image biases; an image prompt replies, then resumes from the cache" { + const a = testing.allocator; + const io = testing.io; + var cfg = fv.config(); + cfg.image_token_id = 300; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try writeWithVision(a, io, tmp.dir, cfg, 85); + const dir = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(dir); + const m = try pkg.boot.Boot.open(a, io, dir, .{ .slots = 2, .context = 1024, .small = true, .cache_bytes = 1 << 26, .vision = true }); + defer { + const md = m.model(); + md.close(md.ptr); + } + const layers = m.parts.env.model.layers; + var biased: usize = 0; + for (layers) |l| biased += @intFromBool(l.gate_bvl != null); + try testing.expect(m.t.tower != null); + try testing.expectEqual(layers.len, biased); + // 40 text tokens, an image of 10 span tokens, 30 more + const px = try fv.patches(a, cfg, 5, 7, 86); + defer a.free(px); + const lg = prep.llmGrid(5, 7, cfg.ratio); + const image: vrows.Image = .{ .pixels = px, .gh = 5, .gw = 7, .at = 40, .tokens = prep.spanTokens(lg[0], lg[1]), .hash = 0x1234567 }; + var ids: [80]u32 = undefined; + for (&ids, 0..) |*id, i| id.* = if (i >= 40 and i < 50) cfg.image_token_id else @intCast(70 + i % 50); + try m.t.setImages(0, &.{image}); + const first = try m.t.serial(0, &ids, 6, null); + defer a.free(first); + const hits = m.t.stats.hits; + try m.t.setImages(1, &.{image}); + const again = try m.t.serial(1, &ids, 6, null); + defer a.free(again); + say(m.t.stats.hits == hits + 1 and std.mem.eql(u32, first, again), "(boot) {d} layers with image biases, a 10-token image prompt replied {any}, again from the cache: {any}", .{ biased, first, again }); + try testing.expectEqual(hits + 1, m.t.stats.hits); + try testing.expectEqualSlices(u32, first, again); +} + +/// One reply of the served engine: its tokens and the prompt rows it took from kept state. +const Got = struct { + mutex: std.Io.Mutex = .init, + out: std.ArrayList(u32) = .empty, + done: bool = false, + cached: u32 = 0, + + fn event(ctx: *anyopaque, _: api.Id, e: *const api.Event) void { + const g: *Got = @ptrCast(@alignCast(ctx)); + g.mutex.lockUncancelable(testing.io); + defer g.mutex.unlock(testing.io); + switch (e.*) { + .tokens => |ts| g.out.appendSlice(testing.allocator, ts) catch {}, + .prefilled => |n| g.cached = n, + .finished => g.done = true, + else => {}, + } + } + + fn wait(g: *Got) !void { + for (0..600_000) |_| { + g.mutex.lockUncancelable(testing.io); + const done = g.done; + g.mutex.unlock(testing.io); + if (done) return; + std.Io.sleep(testing.io, .fromMilliseconds(1), .awake) catch {}; + } + return error.Timeout; + } +}; + +var request_id: api.Id = 500; + +/// One request to the engine, waited for: its reply (testing.allocator's) and the rows it resumed. +fn ask(e: api.Engine, ids: []const u32, images: []const api.Image, n: u32) !struct { []u32, u32 } { + var g: Got = .{}; + defer g.out.deinit(testing.allocator); + const r: api.Request = .{ .prompt = ids, .max_tokens = n, .drafts = false, .images = images }; + request_id += 1; + try e.submit(request_id, &r, .{ .ctx = &g, .event = Got.event }); + try g.wait(); + return .{ try g.out.toOwnedSlice(testing.allocator), g.cached }; +} + +test "dsv41 metal vision: a PNG through the engine's image input and an image request == the target's reply, again from the cache" { + const a = testing.allocator; + const io = testing.io; + var cfg = fv.config(); + cfg.image_token_id = 300; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try writeWithVision(a, io, tmp.dir, cfg, 87); + const dir = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(dir); + const o: pkg.boot.Options = .{ .slots = 2, .context = 1024, .small = true, .vision = true }; + var served = o; + served.cache_bytes = 1 << 26; + const m = try pkg.boot.Boot.open(a, io, dir, served); + const s = try host.serve_lanes.Served.open(a, io, m.model(), dir, null); + defer host.serve_lanes.Served.close(s); + var plain = o; + plain.cache_bytes = 0; + const ref = try pkg.boot.Boot.open(a, io, dir, plain); + defer ref.model().close(ref.model().ptr); + const e = s.engine(); + const v = e.info().vision orelse return error.TestNoVision; + try testing.expectEqual(cfg.image_token_id, v.image_token); + // the engine's prepare is the package's: the bytes to patches, a grid, span tokens and an identity + const png = try pkg.vision_prepare.solidPng(a, 60, 50, .{ 200, 100, 50 }); + defer a.free(png); + const p = try v.prepare(v.ctx, a, png, 64); + defer a.free(p.pixels); + const direct = try pkg.vision_prepare.prepare(io, a, png, 64, cfg); + defer a.free(direct.pixels); + try testing.expect(p.tokens <= 64 and p.tokens == direct.tokens and p.hash == direct.hash); + try testing.expectEqualSlices(f32, direct.pixels, p.pixels); + // 20 text tokens, the image token once a span token, 25 more: the prompt as the server expands it + var ids: std.ArrayList(u32) = .empty; + defer ids.deinit(a); + for (0..20) |i| try ids.append(a, @intCast(70 + i % 50)); + for (0..p.tokens) |_| try ids.append(a, cfg.image_token_id); + for (0..25) |i| try ids.append(a, @intCast(90 + i % 50)); + const image: api.Image = .{ .pixels = p.pixels, .gh = p.gh, .gw = p.gw, .at = 20, .tokens = p.tokens, .hash = p.hash }; + const first = try ask(e, ids.items, &.{image}, 6); + defer a.free(first[0]); + const again = try ask(e, ids.items, &.{image}, 6); + defer a.free(again[0]); + try ref.t.setImages(0, &.{image}); + const want = try ref.t.serial(0, ids.items, 6, null); + defer a.free(want); + const ok = std.mem.eql(u32, want, first[0]) and std.mem.eql(u32, want, again[0]) and first[1] == 0 and again[1] > 0; + say(ok, "(serve) a {d}-token PNG image request replied {any} == the target's; resumed rows {d} then {d}", .{ p.tokens, first[0], first[1], again[1] }); + try testing.expectEqualSlices(u32, want, first[0]); + try testing.expectEqualSlices(u32, want, again[0]); + try testing.expectEqual(@as(u32, 0), first[1]); + try testing.expect(again[1] > 0 and again[1] <= ids.items.len); +} diff --git a/zig/tests/dsv41_metal/vision_real_test.zig b/zig/tests/dsv41_metal/vision_real_test.zig new file mode 100644 index 00000000000..876c60797bd --- /dev/null +++ b/zig/tests/dsv41_metal/vision_real_test.zig @@ -0,0 +1,108 @@ +//! The release's own vision tower (TF_DSV41_REAL_VISION: its shard and the delimiters) against float64. +const std = @import("std"); +const mtl = @import("metal"); +const pkg = @import("dsv41_metal"); +const host = @import("dsv41"); +const vref = @import("vision_ref.zig"); +const vt = @import("vision_test.zig"); + +const testing = std.testing; +const vis = pkg.vision; + +/// A picture-like grid of patches on bf16's grid: smooth colour fields with edges and noise, values in [-1, 1]. +fn scene(a: std.mem.Allocator, cfg: vis.Config, gh: u32, gw: u32) ![]f32 { + var prng = std.Random.DefaultPrng.init(404); + const rng = prng.random(); + const p = cfg.patch; + const out = try a.alloc(f32, @as(usize, gh) * gw * cfg.patchValues()); + for (0..gh) |by| for (0..gw) |bx| for (0..3) |c| for (0..p) |y| for (0..p) |x| { + const fy = @as(f32, @floatFromInt(by * p + y)) / @as(f32, @floatFromInt(gh * p)); + const fx = @as(f32, @floatFromInt(bx * p + x)) / @as(f32, @floatFromInt(gw * p)); + const edge: f32 = if (fx > 0.55 and fy > 0.3) 0.6 else -0.2; + const v = 0.5 * @sin(6.0 * fx + @as(f32, @floatFromInt(c))) * @cos(4.0 * fy) + edge + 0.08 * (rng.float(f32) * 2 - 1); + const q: f32 = @max(-1, @min(1, v)); + out[((by * gw + bx) * 3 + c) * p * p + y * p + x] = @as(f32, @bitCast(@as(u32, pkg.weights.bf16Round(q)) << 16)); + }; + return out; +} + +test "dsv41 metal vision (real weights): the release's ViT stages and aligner against float64 on one image" { + const dir_c = std.c.getenv("TF_DSV41_REAL_VISION") orelse return error.SkipZigTest; + const dir = std.mem.span(dir_c); + const a = testing.allocator; + const cfg: vis.Config = .{}; + var pack = try host.pack.Pack.open(a, testing.io, dir); + defer pack.deinit(); + const device = try mtl.Device.init(); + defer device.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + var kit = try vis.Kit.load(device); + defer kit.deinit(); + var w = try pkg.vision_weights.Weights.load(a, testing.io, device, &pack, cfg, 0, 384); + defer w.deinit(); + var tower = pkg.vision_tower.Tower.init(a, device, queue, &kit, &w); + defer tower.deinit(); + var m = try vref.Model.load(a, testing.io, &pack, cfg); + defer m.deinit(); + const gh: u32 = 6; + const gw: u32 = 9; + const px = try scene(a, cfg, gh, gw); + defer a.free(px); + const pd = try vt.widen(a, px); + defer a.free(pd); + const n = gh * gw; + const x = try vref.embed(a, &m, pd, n); + defer a.free(x); + var done: u32 = 0; + var worst: f64 = 0; + for ([_]u32{ 0, 1, 4, 16, 32 }) |stop| { + try vref.advance(a, &m, x, gh, gw, done, stop); + done = stop; + try tower.run(px, gh, gw, .{ .blocks = stop, .finish = false }); + const e = vt.compare(vt.bytesOf(tower.stream(), n * cfg.dim), x, cfg.dim); + vt.say(e.rms < 0.05, "real tower after {d} of 32 blocks: relative RMS error {d:.5}, worst element {d:.3} of its row's RMS", .{ stop, e.rms, e.worst }); + try testing.expect(e.rms < 0.05); + worst = @max(worst, e.rms); + } + const want = try vref.aligner(a, &m, x, gh, gw); + defer a.free(want); + try tower.run(px, gh, gw, .{}); + const t = tower.tokensOf(gh, gw); + const e = vt.compare(vt.bytesOf(tower.output(), t * cfg.out_dim), want, cfg.out_dim); + vt.say(e.rms < 0.05, "(d) real tower and aligner on a {d}x{d} patch grid: {d} rows of {d}, relative RMS error {d:.5}, worst element {d:.3}", .{ gh, gw, t, cfg.out_dim, e.rms, e.worst }); + try testing.expect(e.rms < 0.05); + // the delimiters are the checkpoint's three vectors + const d = vt.bytesOf(w.delims, 3 * cfg.out_dim); + var nz: usize = 0; + for (d) |v| nz += @intFromBool(v != 0); + vt.say(nz > 3 * cfg.out_dim / 2, "(d) image_start, image_end and image_newline loaded: {d} of {d} values non-zero", .{ nz, d.len }); + try testing.expect(nz > 3 * cfg.out_dim / 2); +} + +test "dsv41 metal vision (real weights): the tower's time on the sizes an image takes" { + const dir_c = std.c.getenv("TF_DSV41_REAL_VISION") orelse return error.SkipZigTest; + const a = testing.allocator; + const cfg: vis.Config = .{}; + var pack = try host.pack.Pack.open(a, testing.io, std.mem.span(dir_c)); + defer pack.deinit(); + const device = try mtl.Device.init(); + defer device.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + var kit = try vis.Kit.load(device); + defer kit.deinit(); + var w = try pkg.vision_weights.Weights.load(a, testing.io, device, &pack, cfg, 0, 384); + defer w.deinit(); + var tower = pkg.vision_tower.Tower.init(a, device, queue, &kit, &w); + defer tower.deinit(); + for ([_][2]u32{ .{ 39, 39 }, .{ 64, 64 } }) |g| { + const px = try scene(a, cfg, g[0], g[1]); + defer a.free(px); + try tower.run(px, g[0], g[1], .{}); + const t0 = std.Io.Clock.awake.now(testing.io); + try tower.run(px, g[0], g[1], .{}); + const ms = @as(f64, @floatFromInt(t0.durationTo(std.Io.Clock.awake.now(testing.io)).toNanoseconds())) / 1e6; + vt.say(true, "real tower on {d}x{d} patches ({d} aligner rows): {d:.0} ms", .{ g[0], g[1], tower.tokensOf(g[0], g[1]), ms }); + } +} diff --git a/zig/tests/dsv41_metal/vision_ref.zig b/zig/tests/dsv41_metal/vision_ref.zig new file mode 100644 index 00000000000..959ce07def4 --- /dev/null +++ b/zig/tests/dsv41_metal/vision_ref.zig @@ -0,0 +1,231 @@ +//! The vision tower in float64 from the math alone: the ViT's stages and the aligner, over the release's bf16 weights. +const std = @import("std"); +const host = @import("dsv41"); + +pub const Block = struct { n1: []f64, wqkv: []f64, bqkv: []f64, wo: []f64, bo: []f64, n2: []f64, w1: []f64, w2: []f64 }; + +pub const Model = struct { + a: std.mem.Allocator, + layers: u32, + dim: u32, + heads: u32, + inter: u32, + patch_values: u32, + ratio: u32, + out_dim: u32, + theta: f64, + eps: f64, + pw: []f64, + pb: []f64, + blocks: []Block, + norm: []f64, + a1: []f64, + ab1: []f64, + a2: []f64, + ab2: []f64, + + /// Every tensor of the pack as float64 (the bf16 values widened exactly). + pub fn load(a: std.mem.Allocator, io: std.Io, pack: *const host.pack.Pack, cfg: anytype) !Model { + var m: Model = .{ .a = a, .layers = cfg.layers, .dim = cfg.dim, .heads = cfg.heads, .inter = cfg.inter, .patch_values = cfg.patchValues(), .ratio = cfg.ratio, .out_dim = cfg.out_dim, .theta = cfg.theta, .eps = cfg.eps, .pw = undefined, .pb = undefined, .blocks = undefined, .norm = undefined, .a1 = undefined, .ab1 = undefined, .a2 = undefined, .ab2 = undefined }; + m.pw = try read(a, io, pack, "vision.patch_embed.proj.weight"); + m.pb = try read(a, io, pack, "vision.patch_embed.proj.bias"); + m.blocks = try a.alloc(Block, cfg.layers); + var buf: [96]u8 = undefined; + for (m.blocks, 0..) |*b, i| { + const f = struct { + fn r(al: std.mem.Allocator, io_: std.Io, p: *const host.pack.Pack, bb: []u8, k: usize, s: []const u8) ![]f64 { + return read(al, io_, p, try std.fmt.bufPrint(bb, "vision.blocks.{d}.{s}", .{ k, s })); + } + }.r; + b.* = .{ .n1 = try f(a, io, pack, &buf, i, "norm1.weight"), .wqkv = try f(a, io, pack, &buf, i, "attn.wqkv.weight"), .bqkv = try f(a, io, pack, &buf, i, "attn.wqkv.bias"), .wo = try f(a, io, pack, &buf, i, "attn.wo.weight"), .bo = try f(a, io, pack, &buf, i, "attn.wo.bias"), .n2 = try f(a, io, pack, &buf, i, "norm2.weight"), .w1 = try f(a, io, pack, &buf, i, "mlp.w1.weight"), .w2 = try f(a, io, pack, &buf, i, "mlp.w2.weight") }; + } + m.norm = try read(a, io, pack, "vision.norm.weight"); + m.a1 = try read(a, io, pack, "aligner.w1.weight"); + m.ab1 = try read(a, io, pack, "aligner.w1.bias"); + m.a2 = try read(a, io, pack, "aligner.w2.weight"); + m.ab2 = try read(a, io, pack, "aligner.w2.bias"); + return m; + } + + fn read(a: std.mem.Allocator, io: std.Io, pack: *const host.pack.Pack, name: []const u8) ![]f64 { + const info = try pack.need(name); + const raw = try a.alloc(u8, @intCast(info.nbytes)); + defer a.free(raw); + try pack.read(io, info, .{ .offset = 0, .len = info.nbytes }, raw); + const out = try a.alloc(f64, raw.len / 2); + for (out, 0..) |*o, i| o.* = @as(f32, @bitCast(@as(u32, std.mem.readInt(u16, raw[2 * i ..][0..2], .little)) << 16)); + return out; + } + + pub fn deinit(m: *Model) void { + for (m.blocks) |b| for ([_][]f64{ b.n1, b.wqkv, b.bqkv, b.wo, b.bo, b.n2, b.w1, b.w2 }) |s| m.a.free(s); + m.a.free(m.blocks); + for ([_][]f64{ m.pw, m.pb, m.norm, m.a1, m.ab1, m.a2, m.ab2 }) |s| m.a.free(s); + } +}; + +/// y [rows][n] = x [rows][k] w^T + bias. +fn linear(y: []f64, x: []const f64, w: []const f64, bias: ?[]const f64, rows: usize, k: usize, n: usize) void { + for (0..rows) |r| for (0..n) |c| { + var s: f64 = if (bias) |b| b[c] else 0; + for (0..k) |i| s += x[r * k + i] * w[c * k + i]; + y[r * n + c] = s; + }; +} + +fn rms(y: []f64, x: []const f64, w: []const f64, rows: usize, d: usize, eps: f64) void { + for (0..rows) |r| { + var s: f64 = 0; + for (x[r * d ..][0..d]) |v| s += v * v; + const inv = 1.0 / @sqrt(s / @as(f64, @floatFromInt(d)) + eps); + for (0..d) |i| y[r * d + i] = w[i] * x[r * d + i] * inv; + } +} + +/// erf by its series below |x| = 4 (about 1e-9 absolute there) and the complementary asymptotic series past it. +pub fn erf(x: f64) f64 { + const ax = @abs(x); + if (ax >= 6) return std.math.sign(x); + if (ax < 4) { + var term = ax; + var sum = ax; + var n: f64 = 0; + while (@abs(term) > 1e-18 * @abs(sum)) { + n += 1; + term *= -ax * ax / n; + sum += term / (2 * n + 1); + } + return std.math.sign(x) * sum * 2 / @sqrt(std.math.pi); + } + // erfc(x) = exp(-x^2) / (x sqrt(pi)) * (1 - 1/(2x^2) + 3/(4x^4) - ...), 14 terms + var t: f64 = 1; + var s: f64 = 1; + for (1..14) |i| { + t *= -@as(f64, @floatFromInt(2 * i - 1)) / (2 * ax * ax); + s += t; + } + return std.math.sign(x) * (1 - @exp(-ax * ax) / (ax * @sqrt(std.math.pi)) * s); +} + +pub fn gelu(x: f64) f64 { + return 0.5 * x * (1 + erf(x * 0.7071067811865476)); +} + +/// The residual stream after the patch embedding: [n][dim]. +pub fn embed(a: std.mem.Allocator, m: *const Model, patches: []const f64, n: usize) ![]f64 { + const x = try a.alloc(f64, n * m.dim); + linear(x, patches, m.pw, m.pb, n, m.patch_values, m.dim); + return x; +} + +/// The residual stream after the patch embedding and the first `blocks` blocks: [n][dim]. +pub fn stream(a: std.mem.Allocator, m: *const Model, patches: []const f64, gh: usize, gw: usize, blocks: u32) ![]f64 { + const x = try embed(a, m, patches, gh * gw); + try advance(a, m, x, gh, gw, 0, blocks); + return x; +} + +/// Blocks [from, to) over the stream `x` in place. +pub fn advance(a: std.mem.Allocator, m: *const Model, x: []f64, gh: usize, gw: usize, from: u32, to: u32) !void { + const n = gh * gw; + const D: usize = m.dim; + const hd = D / m.heads; + const xn = try a.alloc(f64, n * D); + defer a.free(xn); + const qkv = try a.alloc(f64, n * 3 * D); + defer a.free(qkv); + const o = try a.alloc(f64, n * D); + defer a.free(o); + const t = try a.alloc(f64, n * D); + defer a.free(t); + const g = try a.alloc(f64, n * 2 * m.inter); + defer a.free(g); + const h = try a.alloc(f64, n * m.inter); + defer a.free(h); + const scores = try a.alloc(f64, n); + defer a.free(scores); + for (m.blocks[from..to]) |b| { + rms(xn, x, b.n1, n, D, m.eps); + linear(qkv, xn, b.wqkv, b.bqkv, n, D, 3 * D); + // 2D RoPE on q and k: the first quarter of the pairs by the row, the rest by the column + const half = hd / 2; + const quarter = half / 2; + for (0..n) |p| for (0..m.heads) |head| for ([_]usize{ 0, 1 }) |part| for (0..half) |j| { + const pos: f64 = @floatFromInt(if (j < quarter) p / gw else p % gw); + const inv = 1.0 / std.math.pow(f64, m.theta, @as(f64, @floatFromInt(2 * (j % quarter))) / @as(f64, @floatFromInt(half))); + const cs = @cos(pos * inv); + const sn = @sin(pos * inv); + const at = p * 3 * D + part * D + head * hd + j; + const x1 = qkv[at]; + const x2 = qkv[at + half]; + qkv[at] = x1 * cs - x2 * sn; + qkv[at + half] = x2 * cs + x1 * sn; + }; + for (0..n) |p| for (0..m.heads) |head| { + const q = qkv[p * 3 * D + head * hd ..][0..hd]; + var mx: f64 = -std.math.inf(f64); + for (0..n) |j| { + const k = qkv[j * 3 * D + D + head * hd ..][0..hd]; + var s: f64 = 0; + for (q, k) |u, v| s += u * v; + scores[j] = s / 8.0; + mx = @max(mx, scores[j]); + } + var sum: f64 = 0; + for (scores) |*s| { + s.* = @exp(s.* - mx); + sum += s.*; + } + for (0..hd) |d| { + var acc: f64 = 0; + for (0..n) |j| acc += scores[j] * qkv[j * 3 * D + 2 * D + head * hd + d]; + o[p * D + head * hd + d] = acc / sum; + } + }; + linear(t, o, b.wo, b.bo, n, D, D); + for (x, t) |*xv, tv| xv.* += tv; + rms(xn, x, b.n2, n, D, m.eps); + linear(g, xn, b.w1, null, n, D, 2 * m.inter); + for (0..n) |p| for (0..m.inter) |c| { + const gt = g[p * 2 * m.inter + c]; + h[p * m.inter + c] = gt / (1 + @exp(-gt)) * g[p * 2 * m.inter + m.inter + c]; + }; + linear(t, h, b.w2, null, n, m.inter, D); + for (x, t) |*xv, tv| xv.* += tv; + } +} + +/// The aligner's rows [lh * lw][out_dim] of a residual stream `x` after the last block: norm, unshuffle, w1, GELU, w2. +pub fn aligner(a: std.mem.Allocator, m: *const Model, x: []const f64, gh: usize, gw: usize) ![]f64 { + const n = gh * gw; + const D: usize = m.dim; + const r: usize = m.ratio; + const lh = (gh + r - 1) / r; + const lw = (gw + r - 1) / r; + const xn = try a.alloc(f64, n * D); + defer a.free(xn); + rms(xn, x, m.norm, n, D, m.eps); + const kin = D * r * r; + const u = try a.alloc(f64, lh * lw * kin); + defer a.free(u); + for (0..lh * lw) |l| for (0..D) |c| for (0..r * r) |k| { + const py = (l / lw) * r + k / r; + const px = (l % lw) * r + k % r; + u[l * kin + c * r * r + k] = if (py < gh and px < gw) xn[(py * gw + px) * D + c] else 0; + }; + const A: usize = m.out_dim; + const t = try a.alloc(f64, lh * lw * A); + defer a.free(t); + linear(t, u, m.a1, m.ab1, lh * lw, kin, A); + for (t) |*v| v.* = gelu(v.*); + const out = try a.alloc(f64, lh * lw * A); + linear(out, t, m.a2, m.ab2, lh * lw, A, A); + return out; +} + +test "erf: the series and the asymptotic branch meet, and known values hold" { + try std.testing.expectApproxEqAbs(@as(f64, 0.8427007929497149), erf(1), 1e-15); + try std.testing.expectApproxEqAbs(@as(f64, 0.9999779095030014), erf(3), 1e-9); + try std.testing.expectApproxEqAbs(@as(f64, -0.9999999845827421), erf(-4), 1e-9); + try std.testing.expectApproxEqAbs(erf(3.9999999), erf(4.0000001), 1e-8); +} diff --git a/zig/tests/dsv41_metal/vision_test.zig b/zig/tests/dsv41_metal/vision_test.zig new file mode 100644 index 00000000000..ccc8c6fbd94 --- /dev/null +++ b/zig/tests/dsv41_metal/vision_test.zig @@ -0,0 +1,370 @@ +//! DeepSeek-V4.1's Metal vision tower: the ViT and aligner against float64, image rows in prompts. +const std = @import("std"); +const mtl = @import("metal"); +const pkg = @import("dsv41_metal"); +const host = @import("dsv41"); +const fv = @import("fixture_vis.zig"); +const vref = @import("vision_ref.zig"); +const fixture = @import("fixture.zig"); +const ff = @import("fixture_fwd.zig"); +const pt = @import("prompt_test.zig"); +const prep = pkg.vision_prep; +const vrows = pkg.vision_rows; +const pr = pkg.prompt; +const fwd = pkg.forward; + +const testing = std.testing; +const vis = pkg.vision; + +pub fn say(ok: bool, comptime fmt: []const u8, args: anytype) void { + std.debug.print("{s} dsv41 metal vision: ", .{if (ok) "PASS" else "FAIL"}); + std.debug.print(fmt ++ "\n", args); +} + +/// A device, the kernels and the tiny tower's weights read through the release loader. +pub const Rig = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kit: vis.Kit, + w: pkg.vision_weights.Weights, + tower: pkg.vision_tower.Tower, + pack: host.pack.Pack, + tmp: std.testing.TmpDir, + + pub fn init(a: std.mem.Allocator, io: std.Io, cfg: vis.Config, layers: u32, experts: u32, seed: u64) !*Rig { + const r = try a.create(Rig); + errdefer a.destroy(r); + r.a = a; + r.device = try mtl.Device.init(); + r.queue = try r.device.queue(); + r.kit = try vis.Kit.load(r.device); + r.tmp = std.testing.tmpDir(.{}); + const img = try fv.image(a, cfg, layers, experts, seed); + defer a.free(img); + try r.tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = img }); + const dir = try r.tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(dir); + r.pack = try host.pack.Pack.open(a, io, dir); + r.w = try pkg.vision_weights.Weights.load(a, io, r.device, &r.pack, cfg, layers, experts); + r.tower = pkg.vision_tower.Tower.init(a, r.device, r.queue, &r.kit, &r.w); + return r; + } + + pub fn deinit(r: *Rig) void { + r.tower.deinit(); + r.w.deinit(); + r.pack.deinit(); + r.tmp.cleanup(); + r.kit.deinit(); + r.queue.deinit(); + r.device.deinit(); + r.a.destroy(r); + } +}; + +/// Relative RMS error of bf16 values against float64, and the worst element against its own row's RMS scale. +pub const Err = struct { rms: f64, worst: f64 }; + +pub fn compare(got: []const u16, want: []const f64, width: usize) Err { + var num: f64 = 0; + var den: f64 = 0; + var worst: f64 = 0; + const rows = want.len / width; + for (0..rows) |r| { + var scale: f64 = 0; + for (want[r * width ..][0..width]) |v| scale += v * v; + scale = @sqrt(scale / @as(f64, @floatFromInt(width))); + for (0..width) |i| { + const g: f64 = @as(f32, @bitCast(@as(u32, got[r * width + i]) << 16)); + const d = g - want[r * width + i]; + num += d * d; + den += want[r * width + i] * want[r * width + i]; + worst = @max(worst, @abs(d) / @max(scale, 1e-6)); + } + } + return .{ .rms = @sqrt(num / den), .worst = worst }; +} + +pub fn bytesOf(r: pkg.vision.Ref, n: usize) []const u16 { + return @alignCast(std.mem.bytesAsSlice(u16, (r.buf.contents() + r.off)[0 .. n * 2])); +} + +pub fn widen(a: std.mem.Allocator, x: []const f32) ![]f64 { + const out = try a.alloc(f64, x.len); + for (out, x) |*o, v| o.* = v; + return out; +} + +test "dsv41 metal vision: the ViT's stages and the aligner against float64, a grid that pads both ways" { + const a = testing.allocator; + const cfg = fv.config(); + const r = try Rig.init(a, testing.io, cfg, 2, 16, 71); + defer r.deinit(); + var m = try vref.Model.load(a, testing.io, &r.pack, cfg); + defer m.deinit(); + var worst_rms: f64 = 0; + var worst_el: f64 = 0; + for ([_][2]u32{ .{ 5, 7 }, .{ 6, 6 }, .{ 1, 4 } }, 0..) |g, gi| { + const px = try fv.patches(a, cfg, g[0], g[1], 72 + gi); + defer a.free(px); + const pd = try widen(a, px); + defer a.free(pd); + const n = g[0] * g[1]; + // stages: the patch embedding, one block, both blocks; then the aligner's rows + for ([_]u32{ 0, 1, 2 }) |blocks| { + try r.tower.run(px, g[0], g[1], .{ .blocks = blocks, .finish = false }); + const want = try vref.stream(a, &m, pd, g[0], g[1], blocks); + defer a.free(want); + const e = compare(bytesOf(r.tower.stream(), n * cfg.dim), want, cfg.dim); + say(e.rms < 0.01 and e.worst < 0.06, "grid {d}x{d} after {d} blocks: relative RMS error {d:.5}, worst element {d:.4} of its row's RMS", .{ g[0], g[1], blocks, e.rms, e.worst }); + worst_rms = @max(worst_rms, e.rms); + worst_el = @max(worst_el, e.worst); + try testing.expect(e.rms < 0.01 and e.worst < 0.06); + } + try r.tower.run(px, g[0], g[1], .{}); + const x = try vref.stream(a, &m, pd, g[0], g[1], cfg.layers); + defer a.free(x); + const want = try vref.aligner(a, &m, x, g[0], g[1]); + defer a.free(want); + const tokens = r.tower.tokensOf(g[0], g[1]); + const e = compare(bytesOf(r.tower.output(), tokens * cfg.out_dim), want, cfg.out_dim); + say(e.rms < 0.02 and e.worst < 0.1, "grid {d}x{d}: {d} aligner rows, relative RMS error {d:.5}, worst element {d:.4}", .{ g[0], g[1], tokens, e.rms, e.worst }); + worst_rms = @max(worst_rms, e.rms); + worst_el = @max(worst_el, e.worst); + try testing.expect(e.rms < 0.02 and e.worst < 0.1); + } + say(true, "(a) over 3 grids: worst relative RMS {d:.5}, worst element {d:.4}", .{ worst_rms, worst_el }); +} + +test "dsv41 metal vision: an image alone equals the same image after a larger one in the scratch" { + const a = testing.allocator; + const cfg = fv.config(); + const r = try Rig.init(a, testing.io, cfg, 2, 16, 73); + defer r.deinit(); + const small = try fv.patches(a, cfg, 5, 7, 74); + defer a.free(small); + const big = try fv.patches(a, cfg, 9, 12, 75); + defer a.free(big); + try r.tower.run(small, 5, 7, .{}); + const t = r.tower.tokensOf(5, 7); + const alone = try a.dupe(u16, bytesOf(r.tower.output(), t * cfg.out_dim)); + defer a.free(alone); + try r.tower.run(big, 9, 12, .{}); + try r.tower.run(small, 5, 7, .{}); + const after = bytesOf(r.tower.output(), t * cfg.out_dim); + var bad: usize = 0; + for (alone, after) |x, y| bad += @intFromBool(x != y); + say(bad == 0, "(b) tower: an image alone vs after a 9x12 one through the same scratch: {d} of {d} values differ", .{ bad, alone.len }); + try testing.expectEqual(@as(usize, 0), bad); +} + +/// A tiny prompt with two images among text: its ids (virtual ids at image positions), the images and their pixels. +const Scene = struct { + a: std.mem.Allocator, + ids: []u32, + images: [2]vrows.Image, + pixels: [2][]f32, + + const at = [2]u32{ 300, 510 }; + const grids = [2][2]u32{ .{ 5, 7 }, .{ 4, 4 } }; + + fn init(a: std.mem.Allocator, f: *ff.Fwd, cfg: vis.Config, total: usize, seed: u64) !Scene { + var sc: Scene = .{ .a = a, .ids = try ff.ids(a, &f.r.c, total, seed), .images = undefined, .pixels = undefined }; + for (&sc.images, &sc.pixels, at, grids, 0..) |*im, *px, pos, g, i| { + px.* = try fv.patches(a, cfg, g[0], g[1], seed + 10 + i); + const lg = prep.llmGrid(g[0], g[1], cfg.ratio); + im.* = .{ .pixels = px.*, .gh = g[0], .gw = g[1], .at = pos, .tokens = prep.spanTokens(lg[0], lg[1]), .hash = 0x9e3779b97f4a7c15 *% (seed + i + 1) }; + for (0..im.tokens) |p| sc.ids[pos + p] = prep.vid(im.hash, @intCast(p)); + } + return sc; + } + + fn deinit(sc: *Scene) void { + sc.a.free(sc.ids); + for (sc.pixels) |p| sc.a.free(p); + } +}; + +/// One tiny prompt model with the tower beside it and the layers' image biases attached. +fn sceneRig(a: std.mem.Allocator, seed: u64) !struct { f: *ff.Fwd, v: *Rig } { + const f = try ff.Fwd.initWith(a, testing.io, fixture.promptConfig(), pt.limit, seed); + errdefer f.deinit(); + const c = &f.r.c; + const v = try Rig.init(a, testing.io, fv.config(), c.layers, c.experts, seed + 1); + for (f.r.layers, v.w.bias_vl) |*l, b| l.gate_bvl = b; + return .{ .f = f, .v = v }; +} + +/// Positions [from, to) one row a launch through the decode forward, image rows merged in as the prompt path does. +fn decodeImages(f: *ff.Fwd, rows: ?*const vrows.Rows, slot: *const pkg.kv.Slot, hist: []const u32, from: usize, to: usize, out: ?pt.Out) !void { + const r = f.r; + const c = &r.c; + const V: usize = c.vocab; + const TH = c.dspark_targets.len * c.hidden; + const look = c.engram_max_ngram - 1; + for (from..to) |p| { + const image = prep.isVid(hist[p]); + const id: u32 = if (image) rows.?.embed_id else hist[p]; + const one = [1]u32{id}; + try fwd.prepare(&f.b, c, &one, hist[p -| look..p], f.lookup()); + f.b.bytes(f.b.mask, 1)[0] = @intFromBool(!image); + try r.s.writeRows(c, @intCast(p), 1); + if (rows) |rs| rs.describe(@intCast(p), @intCast(p + 1), r.s.bytes(r.s.image, 1)) else r.s.bytes(r.s.image, 1)[0] = 0; + const x = r.ctx(slot, @intCast(p), 1); + const pass = fixture.Pass.begin(r.queue); + try fwd.encodeEmbed(&x, pass.e, f.model(), &f.b); + if (rows) |rs| rs.merge(pass.e, f.b.streams[0], @intCast(p), @intCast(p + 1)); + for (0..f.model().layers.len) |i| try fwd.encodeLayer(&x, pass.e, f.model(), &f.b, i); + try fwd.encodeHead(&x, pass.e, f.model(), &f.b); + try pass.finish(); + if (out) |o| { + @memcpy(o.logits[(p - from) * V ..][0..V], f.b.logitsOf(c, 1)); + @memcpy(o.taps[(p - from) * TH ..][0..TH], slot.taps.?.slice(u16, TH)); + } + } +} + +test "dsv41 metal vision: a prompt with two images then 8 decode steps equals one-row decode launches; chunk plans agree" { + const a = testing.allocator; + const rig = try sceneRig(a, 81); + const f = rig.f; + defer f.deinit(); + defer rig.v.deinit(); + const c = &f.r.c; + const n_prompt: u32 = 580; + const steps = 8; + var sc = try Scene.init(a, rig.f, fv.config(), n_prompt + steps, 82); + defer sc.deinit(); + const V: usize = c.vocab; + const TH = c.dspark_targets.len * c.hidden; + // reference: every position one row a launch (image rows merged, flagged and ungated), features from the tower + var rows = try vrows.Rows.build(a, f.r.device, &rig.v.tower, &sc.images, n_prompt, 64, 0); + defer rows.deinit(); + var dslot = try pkg.kv.Slot.init(a, f.r.device, c, pt.limit); + defer dslot.deinit(); + const dref = try pt.Out.init(a, c, n_prompt + steps); + defer dref.deinit(a); + try decodeImages(f, &rows, &dslot, sc.ids, 0, n_prompt + steps, dref); + // the prompt path, chunks of 64 + var run = try pt.Run.init(a, f, pt.head_opts, 0); + defer run.deinit(); + run.p.images = &rows; + try run.p.run(pt.env(f), &run.slot, &run.tail, sc.ids[0..n_prompt]); + const first = n_prompt - 128; + const lg = pt.bitsDiff(run.p.logits(c), dref.logits[first * V .. n_prompt * V]); + const tp = pt.halfDiff(run.p.tapRows(c), dref.taps[first * TH .. n_prompt * TH]); + const dout = try pt.Out.init(a, c, steps); + defer dout.deinit(a); + try decodeImages(f, &rows, &run.slot, sc.ids, n_prompt, n_prompt + steps, dout); + try run.tail.advance(n_prompt + steps); + const dl = pt.bitsDiff(dout.logits, dref.logits[n_prompt * V ..]); + const dt = pt.halfDiff(dout.taps, dref.taps[n_prompt * TH ..]); + const st = pt.stateDiff(&run.slot, &dslot); + const bad = lg + tp + dl + dt + st; + say(bad == 0, "(c) 2 images + {d} tokens + {d} steps vs one-row decode launches: {d} head logits, {d} taps, {d} step logits, {d} step taps, {d} state bytes differ", .{ n_prompt, steps, lg, tp, dl, dt, st }); + try testing.expectEqual(@as(usize, 0), bad); + // the image rows route by bias_vl and shut the Engram gate: the same prompt without them differs + var plain = try pt.Run.init(a, f, pt.head_opts, 0); + defer plain.deinit(); + const text = try a.dupe(u32, sc.ids[0..n_prompt]); + defer a.free(text); + for (text) |*id| if (prep.isVid(id.*)) { + id.* = rows.embed_id; + }; + try plain.p.run(pt.env(f), &plain.slot, &plain.tail, text); + const moved = pt.bitsDiff(plain.p.logits(c), run.p.logits(c)); + say(moved > 0, "(c) the same ids as plain text give other logits: {d} of {d} differ", .{ moved, run.p.head * c.vocab }); + try testing.expect(moved > 0); + // the image rows route by bias_vl: without it the same prompt gives other logits + { + for (f.r.layers) |*l| l.gate_bvl = null; + var nob = try pt.Run.init(a, f, pt.head_opts, 0); + defer nob.deinit(); + nob.p.images = &rows; + try nob.p.run(pt.env(f), &nob.slot, &nob.tail, sc.ids[0..n_prompt]); + for (f.r.layers, rig.v.w.bias_vl) |*l, b| l.gate_bvl = b; + const d = pt.bitsDiff(nob.p.logits(c), run.p.logits(c)); + say(d > 0, "(c) image rows without bias_vl give other logits: {d} of {d} differ", .{ d, run.p.head * c.vocab }); + try testing.expect(d > 0); + } + // (b) chunk plans: an image's chunk alone, or with its neighbours, give the same logits, taps, slot and tail + var bad_b: usize = 0; + for ([_]u32{ 16, 32, 100, 600 }) |chunk| { + var o = pt.head_opts; + o.chunk = chunk; + var rs = try vrows.Rows.build(a, f.r.device, &rig.v.tower, &sc.images, n_prompt, chunk, 0); + defer rs.deinit(); + var other = try pt.Run.init(a, f, o, 0); + defer other.deinit(); + other.p.images = &rs; + try other.p.run(pt.env(f), &other.slot, &other.tail, sc.ids[0..n_prompt]); + const d = pt.runDiff(c, &other, &run); + const td = pt.tailDiff(&other.tail, &run.tail); + _ = td; // the other run's tail was not advanced by the steps + say(d[0] + d[1] == 0, "(b) chunk {d} vs 64: {d} logits, {d} taps differ", .{ chunk, d[0], d[1] }); + bad_b += d[0] + d[1]; + } + try testing.expectEqual(@as(usize, 0), bad_b); +} + +fn targetOver(f: *ff.Fwd, v: *Rig, cache: u64) !*pkg.target.Target { + const r = f.r; + const env: pkg.target.Env = .{ .device = r.device, .queue = r.queue, .c = &r.c, .p = &r.p, .tables = &r.tables, .s = &r.s, .model = f.model(), .lookup = f.lookup(), .vision = .{ .kit = &v.kit, .w = &v.w } }; + return pkg.target.Target.init(f.a, env, .{ .slots = 2, .limit = pt.limit, .prompt = pt.head_opts, .cache_bytes = cache }); +} + +test "dsv41 metal vision: a Target takes images, keys its cache by them, and resumes a prompt past them" { + const a = testing.allocator; + const rig = try sceneRig(a, 91); + const f = rig.f; + defer f.deinit(); + defer rig.v.deinit(); + const n: u32 = 580; + var sc = try Scene.init(a, f, fv.config(), n + 6, 92); + defer sc.deinit(); + // the prompt as the server sends it: the image token at every span position + const ids = try a.dupe(u32, sc.ids); + defer a.free(ids); + for (ids) |*id| if (prep.isVid(id.*)) { + id.* = fv.config().image_token_id; + }; + var t = try targetOver(f, rig.v, 1 << 28); + defer t.deinit(); + try t.setImages(0, &sc.images); + const first = try t.serial(0, ids[0..n], 5, null); + defer a.free(first); + // the same prompt again: a kept state, the same reply + try t.setImages(1, &sc.images); + const hits = t.stats.hits; + const again = try t.serial(1, ids[0..n], 5, null); + defer a.free(again); + say(t.stats.hits == hits + 1 and std.mem.eql(u32, first, again), "(t) the same images resume the kept state ({d} hits) with the same reply", .{t.stats.hits - hits}); + try testing.expectEqual(hits + 1, t.stats.hits); + try testing.expectEqualSlices(u32, first, again); + // another image behind the same ids: no state of the first applies + var other = sc.images; + other[0].hash +%= 1; + try t.setImages(0, &other); + const hits2 = t.stats.hits; + const third = try t.serial(0, ids[0..n], 5, null); + defer a.free(third); + say(t.stats.hits == hits2, "(t) another image's hash finds no kept state", .{}); + try testing.expectEqual(hits2, t.stats.hits); + // a longer prompt over the kept one runs only its new rows; its reply equals a fresh target's + try t.setImages(1, &sc.images); + const more = try t.serial(1, ids[0 .. n + 6], 4, null); + defer a.free(more); + var fresh = try targetOver(f, rig.v, 0); + defer fresh.deinit(); + try fresh.setImages(0, &sc.images); + const want = try fresh.serial(0, ids[0 .. n + 6], 4, null); + defer a.free(want); + say(std.mem.eql(u32, more, want), "(t) a prompt resumed past two images equals a fresh run: {any} vs {any}", .{ more, want }); + try testing.expectEqualSlices(u32, want, more); + try testing.expectError(error.NoVision, blk: { + var plain = try pkg.target.Target.init(a, .{ .device = f.r.device, .queue = f.r.queue, .c = &f.r.c, .p = &f.r.p, .tables = &f.r.tables, .s = &f.r.s, .model = f.model(), .lookup = f.lookup() }, .{ .slots = 1, .limit = pt.limit }); + defer plain.deinit(); + break :blk plain.setImages(0, &sc.images); + }); +} From 7fb940a7fdce2f4b264cd7b1f918353e2d48d9a4 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:57:33 +0100 Subject: [PATCH 07/10] notices: DeepSeek-V4.1 Metal image preparation follows image_processor.py --- THIRD_PARTY_NOTICES.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index aca46293952..c5f2618ddb3 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -446,6 +446,14 @@ common EXL3 operators and their per-slot epilogues; tile decoding is shared. The ExLlamaV3 MIT attribution, Copyright (c) 2025 Turboderp, applies as described above. No external reference, captured cubin, model shard or CUDA compiler is bundled by this patch. +## DeepSeek-V4.1 Metal image preparation + +The image preparation (`zig/src/families/deepseek_v41/metal/vision_prep.zig`, +`zig/src/families/deepseek_v41/metal/vision_prepare.zig`) follows the image budgets and geometry of +`image_processor.py` in DeepSeek AI's MIT licensed +[deepseek-ai/DeepSeek-V4.1-Flash-1017](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017) +(revision 08c8657f02291e11b6f6b63e0e16014f8e748518), Copyright (c) 2023 DeepSeek. + ## Shared EXL3 resolver setup The shared EXL3 resolver split and CUDA lane option forwarding retain work from PR #728 by @ajensenwaud, From e02e46afc34863915b6560debc2749e2f5236b12 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:57:33 +0100 Subject: [PATCH 08/10] dsv41 metal: keep a thin image's short side at one pixel, refuse degenerate vision configs --- zig/build/dsv41_metal.zig | 12 +++++- .../families/deepseek_v41/metal/prompt.zig | 2 +- .../families/deepseek_v41/metal/vision.zig | 7 +++- .../deepseek_v41/metal/vision_prep.zig | 4 +- zig/tests/dsv41_metal/vision_prepare_test.zig | 41 +++++++++++++++++++ 5 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 zig/tests/dsv41_metal/vision_prepare_test.zig diff --git a/zig/build/dsv41_metal.zig b/zig/build/dsv41_metal.zig index bf0bf6d50bf..c8d9795c998 100644 --- a/zig/build/dsv41_metal.zig +++ b/zig/build/dsv41_metal.zig @@ -61,7 +61,17 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module const vis_step = b.step("test-dsv41-metal-vision", "DeepSeek-V4.1 Metal vision: the tower against float64, image rows in prompts"); vis_step.dependOn(&vis_run.step); const prepare_run = b.addRunArtifact(b.addTest(.{ .root_module = p.pkg, .filters = &.{"prepare"} })); - b.step("test-dsv41-metal-prepare", "DeepSeek-V4.1 Metal: image bytes to patches").dependOn(&prepare_run.step); + const prepare_test_mod = b.createModule(.{ + .root_source_file = b.path("zig/tests/dsv41_metal/vision_prepare_test.zig"), + .target = b.graph.host, + .optimize = .Debug, + .link_libc = true, + .imports = &.{.{ .name = "dsv41_metal", .module = p.pkg }}, + }); + const prepare_test_run = b.addRunArtifact(b.addTest(.{ .root_module = prepare_test_mod })); + const prepare_step = b.step("test-dsv41-metal-prepare", "DeepSeek-V4.1 Metal: image bytes to patches"); + prepare_step.dependOn(&prepare_run.step); + prepare_step.dependOn(&prepare_test_run.step); // the served engine over the tiny model: LaneHost replies, drafts, the prompt cache, seeds, cancels const serve = b.createModule(.{ .root_source_file = b.path("zig/tests/dsv41_metal/serve_test.zig"), diff --git a/zig/src/families/deepseek_v41/metal/prompt.zig b/zig/src/families/deepseek_v41/metal/prompt.zig index 3d8ad06f85d..fbe76b96aa4 100644 --- a/zig/src/families/deepseek_v41/metal/prompt.zig +++ b/zig/src/families/deepseek_v41/metal/prompt.zig @@ -379,7 +379,7 @@ pub const Prompt = struct { for (ids, emb, mask) |id, *o, *m| { const image = prep.isVid(id); if (image and p.images == null) return error.BadToken; - if (!image and id >= c.vocab) return error.BadToken; + if (!image and id >= env.c.vocab) return error.BadToken; o.* = if (image) p.images.?.embed_id else id; m.* = @intFromBool(!image); } diff --git a/zig/src/families/deepseek_v41/metal/vision.zig b/zig/src/families/deepseek_v41/metal/vision.zig index a577a614d9a..0a81ecec346 100644 --- a/zig/src/families/deepseek_v41/metal/vision.zig +++ b/zig/src/families/deepseek_v41/metal/vision.zig @@ -76,8 +76,11 @@ pub const Config = struct { } pub fn check(c: Config) !void { - if (c.headDim() != 64 or c.dim % c.heads != 0) return error.UnsupportedVision; - if (c.layers == 0 or c.ratio == 0 or c.patch == 0 or c.inter == 0) return error.UnsupportedVision; + if (c.heads == 0) return error.ZeroHeads; + if (c.dim % c.heads != 0 or c.headDim() != 64) return error.UnsupportedVision; + if (c.layers == 0 or c.patch == 0 or c.inter == 0) return error.UnsupportedVision; + if (c.ratio < 2) return error.LowDownsampleRatio; + if (c.max_wh_ratio != null and c.max_wh_ratio.? == 0) return error.ZeroMaxWhRatio; } }; diff --git a/zig/src/families/deepseek_v41/metal/vision_prep.zig b/zig/src/families/deepseek_v41/metal/vision_prep.zig index 67391447a77..692c705eb28 100644 --- a/zig/src/families/deepseek_v41/metal/vision_prep.zig +++ b/zig/src/families/deepseek_v41/metal/vision_prep.zig @@ -103,10 +103,10 @@ pub fn contain(w: u32, h: u32, bw: u32, bh: u32) [2]u32 { const dest: f64 = @as(f64, @floatFromInt(bw)) / @as(f64, @floatFromInt(bh)); if (im == dest) return .{ bw, bh }; if (im > dest) { - const nh = roundEven(@as(f64, @floatFromInt(h)) / @as(f64, @floatFromInt(w)) * @as(f64, @floatFromInt(bw))); + const nh = @max(1, roundEven(@as(f64, @floatFromInt(h)) / @as(f64, @floatFromInt(w)) * @as(f64, @floatFromInt(bw)))); return .{ bw, if (nh != bh) nh else bh }; } - const nw = roundEven(@as(f64, @floatFromInt(w)) / @as(f64, @floatFromInt(h)) * @as(f64, @floatFromInt(bh))); + const nw = @max(1, roundEven(@as(f64, @floatFromInt(w)) / @as(f64, @floatFromInt(h)) * @as(f64, @floatFromInt(bh)))); return .{ if (nw != bw) nw else bw, bh }; } diff --git a/zig/tests/dsv41_metal/vision_prepare_test.zig b/zig/tests/dsv41_metal/vision_prepare_test.zig new file mode 100644 index 00000000000..06410e2fbc4 --- /dev/null +++ b/zig/tests/dsv41_metal/vision_prepare_test.zig @@ -0,0 +1,41 @@ +//! DeepSeek-V4.1's Metal image preparation: a thin image's short side, and degenerate vision config refusals. +const std = @import("std"); +const vision = @import("dsv41_metal").vision; +const prep = @import("dsv41_metal").vision_prep; +const vprep = @import("dsv41_metal").vision_prepare; + +test "prepare: a one-pixel image keeps a one-pixel short side, never a zero side" { + const a = std.testing.allocator; + const cfg: vision.Config = .{}; + // 1x84 and 8192x1 at budget 5, 1x2604 at 64: each used to fit a zero side, which resample.into divided by. + const cases = [_]struct { u32, u32, u32 }{ .{ 1, 84, 5 }, .{ 8192, 1, 5 }, .{ 1, 2604, 64 } }; + for (cases) |c| { + const png = try vprep.solidPng(a, c[0], c[1], .{ 90, 120, 150 }); + defer a.free(png); + const p = try vprep.prepare(std.testing.io, a, png, c[2], cfg); + defer a.free(p.pixels); + try std.testing.expect(p.gh >= 1 and p.gw >= 1); + try std.testing.expect(p.tokens >= 1 and p.tokens <= c[2]); + } + // contain itself keeps both sides at one pixel or more at every aspect a one-pixel image can take. + for ([_]u32{ 1, 42, 126, 8192 }) |bh| { + for ([_]u32{ 1, 42, 126, 8192 }) |bw| { + const f = prep.contain(1, @max(84, 2 * bh), bw, bh); + try std.testing.expect(f[0] >= 1 and f[1] >= 1); + const g = prep.contain(@max(84, 2 * bw), 1, bw, bh); + try std.testing.expect(g[0] >= 1 and g[1] >= 1); + } + } +} + +test "check: a degenerate vision config is refused by a named error" { + const a = std.testing.allocator; + try std.testing.expectError(error.ZeroHeads, vision.Config.parse(a, "{\"vision_config\": {\"num_hidden_layers\": 32, \"hidden_size\": 1024, \"num_attention_heads\": 0, \"intermediate_size\": 2816, \"patch_size\": 14, \"rope_theta\": 10000, \"downsample_ratio\": 3, \"max_image_tokens\": 1024, \"min_pixels\": 295936, \"max_wh_ratio\": null}}", 5120)); + try std.testing.expectError(error.LowDownsampleRatio, vision.Config.parse(a, "{\"vision_config\": {\"num_hidden_layers\": 32, \"hidden_size\": 1024, \"num_attention_heads\": 16, \"intermediate_size\": 2816, \"patch_size\": 14, \"rope_theta\": 10000, \"downsample_ratio\": 1, \"max_image_tokens\": 1024, \"min_pixels\": 295936, \"max_wh_ratio\": null}}", 5120)); + try std.testing.expectError(error.ZeroMaxWhRatio, vision.Config.parse(a, "{\"vision_config\": {\"num_hidden_layers\": 32, \"hidden_size\": 1024, \"num_attention_heads\": 16, \"intermediate_size\": 2816, \"patch_size\": 14, \"rope_theta\": 10000, \"downsample_ratio\": 3, \"max_image_tokens\": 1024, \"min_pixels\": 295936, \"max_wh_ratio\": 0}}", 5120)); + for ([_]u32{ 1, 2, 3, 4 }) |b| { + const png = try vprep.solidPng(a, 40, 30, .{ 1, 2, 3 }); + defer a.free(png); + try std.testing.expectError(error.TooFewTokens, vprep.prepare(std.testing.io, a, png, b, .{})); + } +} From 77d6224ec8e5684e65b5adba1ec206186679a36e Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:46:18 +0100 Subject: [PATCH 09/10] changelog: #3926's line --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d75bf3faeb7..5b4a833b5c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Idol on CUDA: `tf-idol` runs Idol's denoiser on GB10 (sm_121) and on RTX 50-series and RTX PRO Blackwell (sm_120) cards against a reference case, gated step by step against idol-sdk's float32 run as on Metal, and refuses other GPUs by name (#1767, for #1757). Thanks to @jayleaton, with device runs from @GustavBlack and @Nipale-ai. +- On Macs, DeepSeek V4.1 chats with image parts now render the vision tower's rows into the prompt (image bytes to patches, the tower merged into the stream); text that spells the image token stays request text, and a text-only build refuses the image part by name (#3926, part of #1676). - Docs: the drafter training recipe gains a section on adapting an already released drafter, budgeted from a few passes over the scarcest class at a low learning rate with early checkpoints, with the Qwen3.8-27B pilot behind it (#3369, refs #2667). Thanks to @Maxrio9. From 6acffd77777aeaa6335bc91a73ab3b0ca501db21 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:55:42 +0000 Subject: [PATCH 10/10] changelog: #3926's line from lines/3926.txt in place of its own --- CHANGELOG.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b4a833b5c8..602b427bc31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,16 +4,15 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- DeepSeek V4.1 on Metal: with `--vision`, the server loads the checkpoint's vision tower (a checkpoint without `vision.*` tensors stops at load), and chats with PNG, JPEG or WebP image parts put the tower's rows into the prompt, within `--vision-image-tokens` (4,096 by default) and `--vision-max-images` (4); an image's span is prefilled in one chunk, the prompt cache keys image rows by the image's hash, text that spells the image token stays text, and a vision config with zero heads, a zero `max_wh_ratio` or a `downsample_ratio` below 2 is refused by name (#3926, part of #1676). Thanks to @gilby. + - Server: `/v1/metrics` reports a `tensorfold:open_connections` gauge, the client connections admitted over TCP or the Unix socket and not yet closed, including idle keep-alive ones (#3925). Thanks to @plotarmordev. - Docs: the optimization ledger adds rows 30 to 32 (small-kernel fusion, stream-tile prefetch and the filled-item prompt grid), each `failed` for Flash Next on HIP with the measurements from #1603 (#3160, refs #1603). Thanks to @gilby. - Docs: the Qwen3.8-27B recipe says to serve with `--thinking-budget 4096` when thinking is on, and gives its GPQA Diamond result on TensorFold 1.2.7 and one GB10: replies cut at the limit from 78 of 198 to 0, and correct from 58.1% to 82.8% (#3373, fixes #3323). - - - Idol on CUDA: `tf-idol` runs Idol's denoiser on GB10 (sm_121) and on RTX 50-series and RTX PRO Blackwell (sm_120) cards against a reference case, gated step by step against idol-sdk's float32 run as on Metal, and refuses other GPUs by name (#1767, for #1757). Thanks to @jayleaton, with device runs from @GustavBlack and @Nipale-ai. -- On Macs, DeepSeek V4.1 chats with image parts now render the vision tower's rows into the prompt (image bytes to patches, the tower merged into the stream); text that spells the image token stays request text, and a text-only build refuses the image part by name (#3926, part of #1676). - Docs: the drafter training recipe gains a section on adapting an already released drafter, budgeted from a few passes over the scarcest class at a low learning rate with early checkpoints, with the Qwen3.8-27B pilot behind it (#3369, refs #2667). Thanks to @Maxrio9.