From c213141b3c7cbb8c1311761269891442d028bc81 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:15:42 +0000 Subject: [PATCH 01/25] feat(server): measure and render selected PDF pages per call OCR reads PDF pages by index under a page budget sized for one generation per page, and must know every page's size before any inference while holding one rendered page at a time. renderPages takes a page selection and caps from the caller over its running budget, measurePages reports the document's page count and each selected page's size and DPI without a bitmap, the render worker's request carries both and renderer failures take the caller's error kind. Chat PDF input keeps its limits, messages and error kinds. --- zig/src/server/pdf.zig | 329 +++++++++++++++++++++++----- zig/src/server/pdf_measure_test.zig | 94 ++++++++ zig/src/server/pdf_worker.zig | 233 ++++++++++++++------ zig/src/server/pdf_worker_test.zig | 88 +++++++- zig/src/server/root.zig | 1 + 5 files changed, 620 insertions(+), 125 deletions(-) create mode 100644 zig/src/server/pdf_measure_test.zig diff --git a/zig/src/server/pdf.zig b/zig/src/server/pdf.zig index 837bbc02661..6276f91e3b4 100644 --- a/zig/src/server/pdf.zig +++ b/zig/src/server/pdf.zig @@ -1,5 +1,6 @@ //! PDF document input (--vision --vision-pdf): renders PDF pages via PDFium and libjpeg-turbo in a bounded worker. const std = @import("std"); +const builtin = @import("builtin"); const sys = @import("sys"); const json = @import("json"); const errors = @import("errors.zig"); @@ -19,7 +20,19 @@ pub const render_timeout_ns: i96 = 10 * std.time.ns_per_s; pub const max_child_heap_bytes: u64 = 1 << 30; pub const off_message = "PDF inputs are off on this server; start the server with --vision --vision-pdf"; -pub const Budget = struct { images_used: u32 = 0, pdf_pages_used: u32 = 0, encoded_bytes: usize = 0, pixels_used: u64 = 0 }; +pub const Budget = struct { + images_used: u32 = 0, + pdf_pages_used: u32 = 0, + encoded_bytes: usize = 0, + pixels_used: u64 = 0, + /// Counts one rendered page of `px` pixels and `len` JPEG bytes. + pub fn add(b: *Budget, px: u64, len: usize) void { + b.pdf_pages_used += 1; + b.images_used += 1; + b.pixels_used += px; + b.encoded_bytes += len; + } +}; pub const IfsdkPause = extern struct { version: c_int = 1, NeedToPauseNow: *const fn (*IfsdkPause) callconv(.c) c_int, user: ?*anyopaque = null }; pub const PdfiumFns = struct { @@ -164,21 +177,112 @@ pub fn decodeFileData(cx: *Cx, raw: []const u8) errors.Refused![]const u8 { return bytes; } +/// Which pages `renderPages` renders, by 0-based index. +pub const Selection = union(enum) { + /// Every page; refused when the document has more (the page budget left). + all_within: u32, + /// The first n pages; the rest are dropped (PaddleX). + first: u32, + /// These indices, ascending and distinct; one past the last page is refused. + list: []const u32, +}; +/// One call's limits over the caller's running Budget; `infra` is the error kind of a renderer failure. +pub const Caps = struct { request_pixels: u64, request_bytes: usize, page_bytes: usize, max_images: u32, infra: errors.Kind }; +/// A rendered page: its 0-based index, JPEG bytes, pixel size and the DPI it was rendered at. +pub const Page = struct { index: u32, jpeg: []const u8, width: u32, height: u32, dpi: u32 }; +/// The rendered pages in selection order, and the document's page count. +pub const Rendered = struct { pages: []Page, total: u32 }; +/// One render call as the in-process renderer and the POSIX worker (pdf_worker.zig) take it. +pub const Job = struct { + pdf_bytes: []const u8, + sel: Selection, + caps: Caps, + deadline_ns: i96, + /// Each selected page's index, size and DPI from its geometry alone: no bitmap, no JPEG (`jpeg` empty). + measure: bool = false, +}; + +/// A rendered page's shortest and longest side in pixels and its highest DPI, from pageDimensions. +pub const min_side: u32 = 28; +pub const max_side: u32 = 2048; +pub const max_dpi: u32 = 144; + +/// Chat caps: 32 MP, 20 MB encoded, 10 MB a page and `max_images` images (0: no cap); a renderer failure is a 400. +pub fn chatCaps(max_images: u32) Caps { + return .{ .request_pixels = max_request_pixels, .request_bytes = images.max_request_bytes, .page_bytes = images.max_image_bytes, .max_images = max_images, .infra = .request }; +} + +/// An OCR call's caps for `pages` pages: 2048 px a side and 10 MB each, no image cap; a renderer failure is a 500. +pub fn ocrCaps(pages: u32) Caps { + return .{ .request_pixels = @as(u64, pages) * max_side * max_side, .request_bytes = @as(usize, pages) * images.max_image_bytes, .page_bytes = images.max_image_bytes, .max_images = 0, .infra = .server }; +} + /// Renders all pages of `pdf_bytes` within the request-wide `budget` into `image_url` parts appended to `parts`. pub fn expandBytes(cx: *Cx, pdf_bytes: []const u8, image_type: []const u8, max_images: u32, max_pages: u32, budget: *Budget, parts: *std.ArrayList(Value)) errors.Refused!void { + const sel: Selection = .{ .all_within = @max(@as(u32, 1), max_pages) -| budget.pdf_pages_used }; + const r = try renderPages(cx, pdf_bytes, sel, chatCaps(max_images), budget, null); + for (r.pages) |p| try appendImageUrlPart(cx.a, parts, image_type, try makeDataUrl(cx.a, "image/jpeg", p.jpeg)); +} + +/// renderPages' errors: a probe's `error.Cancelled` besides the refusals; without a probe (chat) the refusals alone. +pub fn RenderError(comptime Gone: type) type { + return if (Gone == @TypeOf(null)) errors.Refused else errors.Refused || error{Cancelled}; +} + +/// Renders `sel` within `caps` and the running `budget`, one worker a call; `gone`: null or a probe, asked once locked. +pub fn renderPages(cx: *Cx, pdf_bytes: []const u8, sel: Selection, caps: Caps, budget: *Budget, gone: anytype) RenderError(@TypeOf(gone))!Rendered { + return call(cx, pdf_bytes, sel, caps, budget, gone, false); +} + +/// renderPages' admission, sizes and DPI with no page rendered: each page charged with no bytes, its `jpeg` empty. +pub fn measurePages(cx: *Cx, pdf_bytes: []const u8, sel: Selection, caps: Caps, budget: *Budget, gone: anytype) RenderError(@TypeOf(gone))!Rendered { + return call(cx, pdf_bytes, sel, caps, budget, gone, true); +} + +fn call(cx: *Cx, pdf_bytes: []const u8, sel: Selection, caps: Caps, budget: *Budget, gone: anytype, measure: bool) RenderError(@TypeOf(gone))!Rendered { const jf = jpeg_out.get(cx.a) orelse return cx.fail(.unimplemented, "{s}", .{sys.optional_libraries.spec(.jpeg).message}); const io = log.io(); pdfium_mutex.lockUncancelable(io); defer pdfium_mutex.unlock(io); + // a client that left while queued here starts no worker with a fresh deadline ahead of live requests + if (@TypeOf(gone) != @TypeOf(null) and gone.check()) return error.Cancelled; if (pdfium_state == .unknown) pdfium_state = findPdfium(cx.a); const f = if (pdfium_state == .ready) pdfium_state.ready else return cx.fail(.unimplemented, "{s}", .{sys.optional_libraries.spec(.pdfium).message}); - const deadline_ns = std.Io.Clock.awake.now(io).toNanoseconds() + render_timeout_ns; - var jpegs: std.ArrayList([]const u8) = .empty; - if (comptime sys.windows) try renderInProcess(cx, f, jf, pdf_bytes, max_images, max_pages, deadline_ns, budget, &jpegs) else { - const cmd = worker.argv(cx.a) catch return cx.refuse("PDF rendering worker process could not be started"); - try worker.render(cx, cmd, pdf_bytes, max_images, max_pages, deadline_ns, budget, &jpegs); - } - for (jpegs.items) |jb| try appendImageUrlPart(cx.a, parts, image_type, try makeDataUrl(cx.a, "image/jpeg", jb)); + const job: Job = .{ .pdf_bytes = pdf_bytes, .sel = sel, .caps = caps, .deadline_ns = std.Io.Clock.awake.now(io).toNanoseconds() + render_timeout_ns, .measure = measure }; + var pages: std.ArrayList(Page) = .empty; + const total = if (comptime sys.windows) try renderInProcess(cx, f, jf, job, budget, &pages) else blk: { + const cmd = worker.argv(cx.a) catch return cx.fail(caps.infra, "PDF rendering worker process could not be started", .{}); + break :blk try worker.render(cx, cmd, job, budget, &pages); + }; + return .{ .pages = pages.items, .total = total }; +} + +/// How many pages `sel` takes from `total`, refused over the page or image budget; pdf_worker.zig checks with it too. +pub fn admitCount(cx: *Cx, sel: Selection, caps: Caps, budget: *const Budget, total: u32) errors.Refused!u32 { + if (total == 0) return cx.refuse("PDF document contains no pages"); + const count: u32 = switch (sel) { + .all_within => |n| if (total <= n) total else return cx.fail(.request, "a PDF may have at most {d} pages (--vision-max-images, TENSORFOLD_MAX_PDF_PAGES); this request has {d}", .{ budget.pdf_pages_used +| n, budget.pdf_pages_used +| total }), + .first => |n| @min(n, total), + .list => |l| for (l, 0..) |i, k| { + if (k > 0 and i <= l[k - 1]) return cx.refuse("PDF page indices must be ascending and distinct"); + if (i >= total) return cx.fail(.request, "page {d} is out of range; the document has {d} pages", .{ i, total }); + } else @intCast(l.len), + }; + if (caps.max_images > 0 and budget.images_used +| count > caps.max_images) + return cx.fail(.request, "a request may hold at most {d} images (--vision-max-images); it has {d}", .{ caps.max_images, budget.images_used +| count }); + return count; +} + +/// The index of the selection's `k`-th page. +pub fn pageAt(sel: Selection, k: u32) u32 { + return if (sel == .list) sel.list[k] else k; +} + +/// Refuses a page of `px` pixels and `len` JPEG bytes (0 before the encode: some room must be left) over `caps`. +pub fn checkPage(cx: *Cx, caps: Caps, budget: *const Budget, px: u64, len: usize) errors.Refused!void { + if (budget.pixels_used +| px > caps.request_pixels) return cx.fail(.request, "the request's images exceed the {d}-megapixel limit", .{caps.request_pixels >> 20}); + if (len > caps.page_bytes) return cx.fail(.request, "rendered PDF page exceeds the {d} MB image byte limit", .{caps.page_bytes >> 20}); + if (budget.encoded_bytes +| @max(len, 1) > caps.request_bytes) return cx.fail(.request, "the request's images exceed {d} MB encoded", .{caps.request_bytes >> 20}); } const PauseState = struct { @@ -193,85 +297,94 @@ const PauseState = struct { } }; +fn expired(deadline_ns: i96) bool { + return std.Io.Clock.awake.now(log.io()).toNanoseconds() >= deadline_ns; +} + pub const render_flags: c_int = 0x01; // FPDF_ANNOT; 0x10 is REVERSE_BYTE_ORDER, RGBA where the JPEG reads BGRA -fn renderPageWithDeadline(cx: *Cx, f: PdfiumFns, bmp: ?*anyopaque, page: ?*anyopaque, w: c_int, h: c_int, idx: usize, deadline_ns: i96) errors.Refused!void { +fn renderPageWithDeadline(cx: *Cx, f: PdfiumFns, job: Job, bmp: ?*anyopaque, page: ?*anyopaque, w: c_int, h: c_int, idx: usize) errors.Refused!void { if (f.FPDF_RenderPageBitmap_Start != null and f.FPDF_RenderPage_Continue != null and f.FPDF_RenderPage_Close != null) { - var state: PauseState = .{ .pause = .{ .version = 1, .NeedToPauseNow = PauseState.check }, .deadline_ns = deadline_ns }; + var state: PauseState = .{ .pause = .{ .version = 1, .NeedToPauseNow = PauseState.check }, .deadline_ns = job.deadline_ns }; var status = f.FPDF_RenderPageBitmap_Start.?(bmp, page, 0, 0, w, h, 0, render_flags, &state.pause); while (status == 1) { - if (state.timed_out or std.Io.Clock.awake.now(log.io()).toNanoseconds() >= deadline_ns) { + if (state.timed_out or expired(job.deadline_ns)) { f.FPDF_RenderPage_Close.?(page); - return cx.refuse("PDF rendering timed out"); + return cx.fail(job.caps.infra, "PDF rendering timed out", .{}); } status = f.FPDF_RenderPage_Continue.?(page, &state.pause); } f.FPDF_RenderPage_Close.?(page); - if (state.timed_out or std.Io.Clock.awake.now(log.io()).toNanoseconds() >= deadline_ns) return cx.refuse("PDF rendering timed out"); + if (state.timed_out or expired(job.deadline_ns)) return cx.fail(job.caps.infra, "PDF rendering timed out", .{}); if (status == 3) return cx.refuse(try std.fmt.allocPrint(cx.a, "PDF page {d} could not be rendered", .{idx + 1})); return; } f.FPDF_RenderPageBitmap(bmp, page, 0, 0, w, h, 0, render_flags); - if (std.Io.Clock.awake.now(log.io()).toNanoseconds() >= deadline_ns) return cx.refuse("PDF rendering timed out"); + if (expired(job.deadline_ns)) return cx.fail(job.caps.infra, "PDF rendering timed out", .{}); } -pub fn renderInProcess(cx: *Cx, f: PdfiumFns, jf: jpeg_out.Fns, pdf_bytes: []const u8, max_images: u32, max_pages: u32, deadline_ns: i96, budget: *Budget, out_jpegs: *std.ArrayList([]const u8)) errors.Refused!void { - if (pdf_bytes.len > std.math.maxInt(c_int)) return cx.refuse("PDF exceeds the encoded byte limit"); - if (std.Io.Clock.awake.now(log.io()).toNanoseconds() >= deadline_ns) return cx.refuse("PDF rendering timed out"); - const doc = f.FPDF_LoadMemDocument(pdf_bytes.ptr, @intCast(pdf_bytes.len), null) orelse +/// Renders `job` in this process (Windows, and the POSIX worker); returns the document's page count. +pub fn renderInProcess(cx: *Cx, f: PdfiumFns, jf: jpeg_out.Fns, job: Job, budget: *Budget, out: *std.ArrayList(Page)) errors.Refused!u32 { + if (job.pdf_bytes.len > std.math.maxInt(c_int)) return cx.refuse("PDF exceeds the encoded byte limit"); + if (expired(job.deadline_ns)) return cx.fail(job.caps.infra, "PDF rendering timed out", .{}); + const doc = f.FPDF_LoadMemDocument(job.pdf_bytes.ptr, @intCast(job.pdf_bytes.len), null) orelse return cx.refuse("PDF document could not be opened (corrupt or password-protected)"); defer f.FPDF_CloseDocument(doc); - const total_pages = f.FPDF_GetPageCount(doc); - if (total_pages <= 0) return cx.refuse("PDF document contains no pages"); - const pages: u32 = @intCast(total_pages); - const limit: u32 = @max(@as(u32, 1), max_pages); - if (budget.pdf_pages_used + pages > limit) - return cx.refuse(try std.fmt.allocPrint(cx.a, "a PDF may have at most {d} pages (--vision-max-images, TENSORFOLD_MAX_PDF_PAGES); this request has {d}", .{ limit, budget.pdf_pages_used + pages })); - if (max_images > 0 and budget.images_used + pages > max_images) - return cx.refuse(try std.fmt.allocPrint(cx.a, "a request may hold at most {d} images (--vision-max-images); it has {d}", .{ max_images, budget.images_used + pages })); - for (0..pages) |idx| { - if (std.Io.Clock.awake.now(log.io()).toNanoseconds() >= deadline_ns) return cx.refuse("PDF rendering timed out"); + const total: u32 = @intCast(@max(0, f.FPDF_GetPageCount(doc))); + const count = try admitCount(cx, job.sel, job.caps, budget, total); + for (0..count) |k| { + const idx = pageAt(job.sel, @intCast(k)); + if (expired(job.deadline_ns)) return cx.fail(job.caps.infra, "PDF rendering timed out", .{}); const page = f.FPDF_LoadPage(doc, @intCast(idx)) orelse return cx.refuse(try std.fmt.allocPrint(cx.a, "PDF page {d} could not be rendered", .{idx + 1})); defer f.FPDF_ClosePage(page); const dims = pageDimensions(f.FPDF_GetPageWidthF(page), f.FPDF_GetPageHeightF(page)); - const page_pixels = @as(u64, @intCast(dims[0])) * @as(u64, @intCast(dims[1])); - if (budget.pixels_used + page_pixels > max_request_pixels) return cx.refuse("the request's images exceed the 32-megapixel limit"); - if (budget.encoded_bytes >= images.max_request_bytes) return cx.refuse("the request's images exceed 20 MB encoded"); - const bmp = f.FPDFBitmap_Create(dims[0], dims[1], 0) orelse return error.OutOfMemory; + const page_pixels = @as(u64, @intCast(dims.w)) * @as(u64, @intCast(dims.h)); + try checkPage(cx, job.caps, budget, page_pixels, 0); + if (job.measure) { + // the parent's deadline guards the POSIX worker; in process, a load past the deadline must not pass + if (expired(job.deadline_ns)) return cx.fail(job.caps.infra, "PDF rendering timed out", .{}); + budget.add(page_pixels, 0); + try out.append(cx.a, .{ .index = idx, .jpeg = &.{}, .width = @intCast(dims.w), .height = @intCast(dims.h), .dpi = pageDpi(dims) }); + continue; + } + const bmp = f.FPDFBitmap_Create(dims.w, dims.h, 0) orelse return error.OutOfMemory; defer f.FPDFBitmap_Destroy(bmp); const stride = f.FPDFBitmap_GetStride(bmp); const buf_ptr = f.FPDFBitmap_GetBuffer(bmp) orelse return error.OutOfMemory; - if (stride < dims[0] * 4) return cx.refuse("PDF page bitmap has invalid stride"); + if (stride < dims.w * 4) return cx.refuse("PDF page bitmap has invalid stride"); const bgra: [*]u8 = @ptrCast(buf_ptr); - const total_bytes = @as(usize, @intCast(stride)) * @as(usize, @intCast(dims[1])); + const total_bytes = @as(usize, @intCast(stride)) * @as(usize, @intCast(dims.h)); @memset(bgra[0..total_bytes], 0xFF); - try renderPageWithDeadline(cx, f, bmp, page, dims[0], dims[1], idx, deadline_ns); - const jpeg_bytes = jpeg_out.encodeBgra(cx.a, jf, bgra[0..total_bytes], @intCast(dims[0]), @intCast(dims[1]), @intCast(stride)) catch |err| switch (err) { + try renderPageWithDeadline(cx, f, job, bmp, page, dims.w, dims.h, idx); + const jpeg_bytes = jpeg_out.encodeBgra(cx.a, jf, bgra[0..total_bytes], @intCast(dims.w), @intCast(dims.h), @intCast(stride)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.EncodeFailed => return cx.refuse("rendered PDF page could not be encoded as JPEG"), }; - if (jpeg_bytes.len > images.max_image_bytes) return cx.refuse("rendered PDF page exceeds the 10 MB image byte limit"); - if (budget.encoded_bytes + jpeg_bytes.len > images.max_request_bytes) return cx.refuse("the request's images exceed 20 MB encoded"); - budget.pdf_pages_used += 1; - budget.images_used += 1; - budget.pixels_used += page_pixels; - budget.encoded_bytes += jpeg_bytes.len; - try out_jpegs.append(cx.a, jpeg_bytes); + try checkPage(cx, job.caps, budget, page_pixels, jpeg_bytes.len); + budget.add(page_pixels, jpeg_bytes.len); + try out.append(cx.a, .{ .index = idx, .jpeg = jpeg_bytes, .width = @intCast(dims.w), .height = @intCast(dims.h), .dpi = pageDpi(dims) }); } + return total; +} + +const Dims = struct { w: c_int, h: c_int, scale: f32 }; +/// round(72 x scale), at least 1: a huge page's scale can round to 0 DPI. +fn pageDpi(dims: Dims) u32 { + return @max(1, @as(u32, @intFromFloat(@round(72.0 * dims.scale)))); } -fn pageDimensions(pw_raw: f32, ph_raw: f32) [2]c_int { +fn pageDimensions(pw_raw: f32, ph_raw: f32) Dims { const pw: f32 = if (std.math.isFinite(pw_raw) and pw_raw > 1.0) pw_raw else 595.0; const ph: f32 = if (std.math.isFinite(ph_raw) and ph_raw > 1.0) ph_raw else 842.0; - var scale: f32 = 2.0; // 144 DPI baseline - const max_side: f32 = 2048.0; + var scale: f32 = @as(f32, @floatFromInt(max_dpi)) / 72.0; // 144 DPI baseline + const side: f32 = @floatFromInt(max_side); const max_area: f32 = 3_600_000.0; - if (pw * scale > max_side) scale = max_side / pw; - if (ph * scale > max_side) scale = max_side / ph; + if (pw * scale > side) scale = side / pw; + if (ph * scale > side) scale = side / ph; if ((pw * scale) * (ph * scale) > max_area) scale = @sqrt(max_area / (pw * ph)); - const w: c_int = @max(28, @min(4096, @as(c_int, @intFromFloat(@round(pw * scale))))); - const h: c_int = @max(28, @min(4096, @as(c_int, @intFromFloat(@round(ph * scale))))); - return .{ w, h }; + const w: c_int = @max(min_side, @min(4096, @as(c_int, @intFromFloat(@round(pw * scale))))); + const h: c_int = @max(min_side, @min(4096, @as(c_int, @intFromFloat(@round(ph * scale))))); + return .{ .w = w, .h = h, .scale = scale }; } /// The width and height a baseline or progressive JPEG's frame header names, or null when it has none. @@ -332,8 +445,118 @@ test "decodeFileData and parseChildReply validate untrusted input and recompute try std.testing.expect(std.mem.indexOf(u8, url_cx.message, "URLs are not accepted") != null); var bad_reply_cx: Cx = .{ .a = a }; var budget: Budget = .{}; - var jpegs: std.ArrayList([]const u8) = .empty; - try std.testing.expectError(error.Refused, worker.parseChildReply(&bad_reply_cx, &.{ 1, 0xFF, 3, 0, 0, 0, 'b', 'a', 'd' }, 4, 4, &budget, &jpegs)); + var pages: std.ArrayList(Page) = .empty; + const reply = [_]u8{ 1, 0, 3, 0, 0, 0, 'b', 'a', 'd' }; + try std.testing.expectError(error.Refused, worker.parseChildReply(&bad_reply_cx, &reply, .{ .all_within = 4 }, false, chatCaps(4), &budget, &pages)); try std.testing.expectEqual(errors.Kind.request, bad_reply_cx.kind); try std.testing.expectEqualStrings("bad", bad_reply_cx.message); } + +/// Renders `sel` of the two-page fixture in this process by `timeout_ns`; skips without PDFium or libjpeg-turbo. +fn renderFixture(cx: *Cx, sel: Selection, caps: Caps, budget: *Budget, timeout_ns: i96) !Rendered { + const jf = jpeg_out.get(cx.a) orelse return error.SkipZigTest; + const f = jpeg_out.loadDynLib(PdfiumFns, .pdfium, cx.a) orelse return error.SkipZigTest; + f.FPDF_InitLibrary(); // a test runner cannot be the worker (pdf_worker_test.zig renders through it) + var pages: std.ArrayList(Page) = .empty; + const job: Job = .{ .pdf_bytes = minimal_two_page_pdf, .sel = sel, .caps = caps, .deadline_ns = std.Io.Clock.awake.now(log.io()).toNanoseconds() + timeout_ns }; + const total = try renderInProcess(cx, f, jf, job, budget, &pages); + return .{ .pages = pages.items, .total = total }; +} + +test "pdf pages: a list renders only its pages, with their indices, size and DPI" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + var budget: Budget = .{}; + const r = try renderFixture(&cx, .{ .list = &.{1} }, ocrCaps(16), &budget, render_timeout_ns); + try std.testing.expectEqual(@as(u32, 2), r.total); + try std.testing.expectEqual(@as(usize, 1), r.pages.len); + const p = r.pages[0]; + try std.testing.expectEqual(Page{ .index = 1, .jpeg = p.jpeg, .width = 400, .height = 400, .dpi = 144 }, p); + try std.testing.expectEqual([2]u32{ 400, 400 }, jpegSize(p.jpeg).?); + try std.testing.expectEqual(Budget{ .images_used = 1, .pdf_pages_used = 1, .encoded_bytes = p.jpeg.len, .pixels_used = 400 * 400 }, budget); + var out_cx: Cx = .{ .a = a }; + try std.testing.expectError(error.Refused, renderFixture(&out_cx, .{ .list = &.{ 0, 2 } }, ocrCaps(16), &budget, render_timeout_ns)); + try std.testing.expectEqualStrings("page 2 is out of range; the document has 2 pages", out_cx.message); + try std.testing.expectEqual(errors.Kind.request, out_cx.kind); +} + +test "pdf pages: first(1) renders page 0 and reports the document's two pages" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var cx: Cx = .{ .a = arena.allocator() }; + var budget: Budget = .{}; + const r = try renderFixture(&cx, .{ .first = 1 }, chatCaps(4), &budget, render_timeout_ns); + try std.testing.expectEqual(@as(u32, 2), r.total); + try std.testing.expectEqual(@as(usize, 1), r.pages.len); + try std.testing.expectEqual(@as(u32, 0), r.pages[0].index); + try std.testing.expectEqual(@as(u32, 1), budget.pdf_pages_used); +} + +test "pdf pages: a renderer deadline is a server error under OCR caps and a request error under chat caps" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + for ([_]Caps{ ocrCaps(16), chatCaps(4) }) |caps| { + var cx: Cx = .{ .a = arena.allocator() }; + var budget: Budget = .{}; + if (renderFixture(&cx, .{ .all_within = 16 }, caps, &budget, 0)) |_| return error.TestUnexpectedResult else |err| if (err != error.Refused) return err; + try std.testing.expectEqual(caps.infra, cx.kind); + try std.testing.expectEqualStrings("PDF rendering timed out", cx.message); + try std.testing.expectEqual(Budget{}, budget); + } +} + +test "pdf pages: a huge page fits 2048 px a side and keeps a DPI of at least 1" { + const dims = pageDimensions(400_000, 200_000); + try std.testing.expectEqual(@as(c_int, 2048), dims.w); + try std.testing.expectEqual(@as(c_int, 1024), dims.h); + try std.testing.expectEqual(@as(u32, 0), @as(u32, @intFromFloat(@round(72.0 * dims.scale)))); + try std.testing.expectEqual(@as(u32, 1), pageDpi(dims)); + try std.testing.expectEqual(max_dpi, pageDpi(pageDimensions(200, 200))); +} + +/// A cancellation probe that counts its calls, says whether the renderer was held then, and reports `left`. +const Probe = struct { + left: bool, + calls: u32 = 0, + held: bool = false, + pub fn check(p: *Probe) bool { + p.calls += 1; + p.held = !pdfium_mutex.tryLock(); + if (!p.held) pdfium_mutex.unlock(log.io()); + return p.left; + } +}; + +test "pdf pages: a client that left while queued for the renderer gets Cancelled and starts no worker" { + if (comptime builtin.os.tag == .windows) return error.SkipZigTest; // Windows renders in process, with no worker to refuse + log.init(std.testing.io, false); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + if (jpeg_out.get(a) == null) return error.SkipZigTest; // without libjpeg-turbo the call refuses before the lock + // a worker start would refuse with "could not be started", never Cancelled + const saved = worker.server_exe; + defer worker.server_exe = saved; + worker.server_exe = "/nonexistent/tensorfold-native"; + var budget: Budget = .{}; + var cx: Cx = .{ .a = a }; + var left: Probe = .{ .left = true }; + try std.testing.expectError(error.Cancelled, renderPages(&cx, minimal_two_page_pdf, .{ .all_within = 16 }, ocrCaps(16), &budget, &left)); + try std.testing.expectEqual(@as(u32, 1), left.calls); + try std.testing.expect(left.held); // asked with the renderer held: after the wait, before any worker + try std.testing.expectEqual(Budget{}, budget); + try std.testing.expectEqualStrings("", cx.message); + // a client still there, and chat's null probe (whose error set stays Refused), take the same path past the check + comptime std.debug.assert(RenderError(@TypeOf(null)) == errors.Refused); + var here: Probe = .{ .left = false }; + var here_cx: Cx = .{ .a = a }; + var chat_cx: Cx = .{ .a = a }; + try std.testing.expectError(error.Refused, renderPages(&here_cx, minimal_two_page_pdf, .{ .all_within = 16 }, chatCaps(4), &budget, &here)); + try std.testing.expectError(error.Refused, renderPages(&chat_cx, minimal_two_page_pdf, .{ .all_within = 16 }, chatCaps(4), &budget, null)); + try std.testing.expectEqual(@as(u32, 1), here.calls); + try std.testing.expectEqualStrings(chat_cx.message, here_cx.message); + try std.testing.expectEqual(chat_cx.kind, here_cx.kind); + try std.testing.expectEqual(Budget{}, budget); +} diff --git a/zig/src/server/pdf_measure_test.zig b/zig/src/server/pdf_measure_test.zig new file mode 100644 index 00000000000..1883bfc65c0 --- /dev/null +++ b/zig/src/server/pdf_measure_test.zig @@ -0,0 +1,94 @@ +//! Measured PDF pages (Job.measure): each selected page's size and DPI without a bitmap or a JPEG, as OCR plans them. +const std = @import("std"); +const builtin = @import("builtin"); +const errors = @import("errors.zig"); +const jpeg_out = @import("jpeg_out.zig"); +const log = @import("log.zig"); +const pdf = @import("pdf.zig"); +const worker = @import("pdf_worker.zig"); +const Cx = errors.Cx; +const t = std.testing; + +/// `sel` of the two-page fixture in this process, measured or rendered; skips without PDFium or libjpeg-turbo. +fn fixture(cx: *Cx, sel: pdf.Selection, caps: pdf.Caps, budget: *pdf.Budget, measure: bool) !pdf.Rendered { + log.init(t.io, false); + const jf = jpeg_out.get(cx.a) orelse return error.SkipZigTest; + const f = jpeg_out.loadDynLib(pdf.PdfiumFns, .pdfium, cx.a) orelse return error.SkipZigTest; + f.FPDF_InitLibrary(); // a test runner cannot be the worker (pdf_worker_test.zig measures through it) + var pages: std.ArrayList(pdf.Page) = .empty; + const job: pdf.Job = .{ .pdf_bytes = pdf.minimal_two_page_pdf, .sel = sel, .caps = caps, .deadline_ns = std.Io.Clock.awake.now(log.io()).toNanoseconds() + pdf.render_timeout_ns, .measure = measure }; + const total = try pdf.renderInProcess(cx, f, jf, job, budget, &pages); + return .{ .pages = pages.items, .total = total }; +} + +test "pdf measure: both pages' sizes and DPI equal a real render's, with no JPEG bytes and no bytes charged" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + var cx: Cx = .{ .a = arena.allocator() }; + var measured_budget: pdf.Budget = .{}; + var rendered_budget: pdf.Budget = .{}; + const measured = try fixture(&cx, .{ .all_within = 16 }, pdf.ocrCaps(16), &measured_budget, true); + const rendered = try fixture(&cx, .{ .all_within = 16 }, pdf.ocrCaps(16), &rendered_budget, false); + try t.expectEqual(@as(u32, 2), measured.total); + try t.expectEqual(@as(usize, 2), measured.pages.len); + for (measured.pages, rendered.pages) |m, r| { + try t.expectEqual(@as(usize, 0), m.jpeg.len); + try t.expectEqual(pdf.Page{ .index = r.index, .jpeg = m.jpeg, .width = r.width, .height = r.height, .dpi = r.dpi }, m); + try t.expectEqual([2]u32{ m.width, m.height }, pdf.jpegSize(r.jpeg).?); + } + try t.expectEqual(pdf.Budget{ .images_used = 2, .pdf_pages_used = 2, .encoded_bytes = 0, .pixels_used = rendered_budget.pixels_used }, measured_budget); +} + +/// Expects `sel` of the fixture refused, measured or rendered; a missing library still skips the test. +fn expectRefused(cx: *Cx, sel: pdf.Selection, budget: *pdf.Budget, measure: bool) !void { + if (fixture(cx, sel, pdf.ocrCaps(16), budget, measure)) |_| return error.TestUnexpectedResult else |e| switch (e) { + error.Refused => {}, + else => return e, + } +} + +test "pdf measure: a selection over the page budget is refused whole, as a render refuses it" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_]bool{ true, false }) |measure| { + var cx: Cx = .{ .a = a }; + var budget: pdf.Budget = .{}; + try expectRefused(&cx, .{ .all_within = 1 }, &budget, measure); + try t.expectEqualStrings("a PDF may have at most 1 pages (--vision-max-images, TENSORFOLD_MAX_PDF_PAGES); this request has 2", cx.message); + try t.expectEqual(pdf.Budget{}, budget); + var out_cx: Cx = .{ .a = a }; + try expectRefused(&out_cx, .{ .list = &.{ 0, 2 } }, &budget, measure); + try t.expectEqualStrings("page 2 is out of range; the document has 2 pages", out_cx.message); + } +} + +test "pdf measure: a worker frame without JPEG bytes passes only for a measure, and one with them only for a render" { + if (comptime builtin.os.tag == .windows) return error.SkipZigTest; // the worker is POSIX only; Windows renders in process + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // first(1) of a two-page document: page 0 at 400 x 400 and 144 DPI, its JPEG length 0 + const sized = [_]u8{ 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0x90, 1, 0, 0, 0x90, 1, 0, 0, 144, 0, 0, 0, 0, 0, 0, 0 }; + var budget: pdf.Budget = .{}; + var pages: std.ArrayList(pdf.Page) = .empty; + var cx: Cx = .{ .a = a }; + try t.expectEqual(@as(u32, 2), try worker.parseChildReply(&cx, &sized, .{ .first = 1 }, true, pdf.ocrCaps(4), &budget, &pages)); + try t.expectEqual(pdf.Page{ .index = 0, .jpeg = pages.items[0].jpeg, .width = 400, .height = 400, .dpi = 144 }, pages.items[0]); + try t.expectEqual(@as(usize, 0), pages.items[0].jpeg.len); + try t.expectEqual(pdf.Budget{ .images_used = 1, .pdf_pages_used = 1, .pixels_used = 400 * 400 }, budget); + // the same frame for a render is a renderer failure of the caller's kind, and leaves the budget alone + for ([_]pdf.Caps{ pdf.ocrCaps(4), pdf.chatCaps(4) }) |caps| { + var render_cx: Cx = .{ .a = a }; + var fresh: pdf.Budget = .{}; + try t.expectError(error.Refused, worker.parseChildReply(&render_cx, &sized, .{ .first = 1 }, false, caps, &fresh, &pages)); + try t.expectEqual(caps.infra, render_cx.kind); + try t.expectEqual(pdf.Budget{}, fresh); + } + // a page with bytes in a measure's frame is refused too + const with_bytes = [_]u8{ 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0x90, 1, 0, 0, 0x90, 1, 0, 0, 144, 0, 0, 0, 1, 0, 0, 0, 0xFF }; + var bytes_cx: Cx = .{ .a = a }; + var fresh: pdf.Budget = .{}; + try t.expectError(error.Refused, worker.parseChildReply(&bytes_cx, &with_bytes, .{ .first = 1 }, true, pdf.ocrCaps(4), &fresh, &pages)); + try t.expectEqual(errors.Kind.server, bytes_cx.kind); +} diff --git a/zig/src/server/pdf_worker.zig b/zig/src/server/pdf_worker.zig index 099b751a447..f897a5999c2 100644 --- a/zig/src/server/pdf_worker.zig +++ b/zig/src/server/pdf_worker.zig @@ -3,12 +3,12 @@ const std = @import("std"); const builtin = @import("builtin"); const sys = @import("sys"); const errors = @import("errors.zig"); -const images = @import("images.zig"); const log = @import("log.zig"); const pdf = @import("pdf.zig"); const jpeg_out = @import("jpeg_out.zig"); const Cx = errors.Cx; const Budget = pdf.Budget; +const Page = pdf.Page; const Allocator = std.mem.Allocator; /// The hidden argument that makes tensorfold-native run only the PDF render worker (main.zig). @@ -16,9 +16,28 @@ pub const arg = "--pdf-render-worker"; /// The binary started as the worker when set: tests name the server binary, since a test runner cannot be the worker. pub var server_exe: ?[]const u8 = null; const failed = "PDF rendering exceeded resource limits or failed"; +/// Reply: 0, count, total, per page index, width, height, dpi, length (u32s) and JPEG; 1, kind, length, message; 2. +const page_head = 5 * 4; // a page's five u32s +/// The most page indices a selection list may send the worker. +const max_list: u32 = 1 << 16; -/// The parent's request on the worker's stdin, ahead of the PDF bytes; both ends are the same build. -const Request = extern struct { remaining_ns: u64, encoded_bytes: u64, pixels_used: u64, pdf_len: u64, max_images: u32, max_pages: u32, images_used: u32, pdf_pages_used: u32 }; +/// The parent's request on the worker's stdin, ahead of a list selection's indices and the PDF bytes; same build. +const Request = extern struct { + remaining_ns: u64, + encoded_bytes: u64, + pixels_used: u64, + pdf_len: u64, + request_pixels: u64, + request_bytes: u64, + page_bytes: u64, + max_images: u32, + images_used: u32, + pdf_pages_used: u32, + sel_kind: u32, // pdf.Selection's tag + sel_n: u32, // all_within's or first's count, or the list's length + infra: u32, // caps.infra + measure: u32, // 1: job.measure, sizes without bitmaps or JPEGs +}; /// This executable and the hidden argument; Linux's /proc/self/exe still names the running file once it is replaced. pub fn argv(a: Allocator) ![]const []const u8 { @@ -26,41 +45,64 @@ pub fn argv(a: Allocator) ![]const []const u8 { return a.dupe([]const u8, &.{ exe, arg }); } -/// Renders `pdf_bytes` in a fresh worker started from `cmd`, killed at `deadline_ns`, and checks its reply. -pub fn render(cx: *Cx, cmd: []const []const u8, pdf_bytes: []const u8, max_images: u32, max_pages: u32, deadline_ns: i96, budget: *Budget, out_jpegs: *std.ArrayList([]const u8)) errors.Refused!void { +/// Renders `job` in a fresh worker started from `cmd`, killed at its deadline; returns the document's page count. +pub fn render(cx: *Cx, cmd: []const []const u8, job: pdf.Job, budget: *Budget, out: *std.ArrayList(Page)) errors.Refused!u32 { + const infra = job.caps.infra; + const list: []const u32 = if (job.sel == .list) job.sel.list else &.{}; + if (list.len > max_list) return cx.fail(.request, "a PDF page selection may name at most {d} pages", .{max_list}); const io = log.io(); - var child = std.process.spawn(io, .{ .argv = cmd, .stdin = .pipe, .stdout = .pipe }) catch return cx.refuse("PDF rendering worker process could not be started"); + var child = std.process.spawn(io, .{ .argv = cmd, .stdin = .pipe, .stdout = .pipe }) catch return cx.fail(infra, "PDF rendering worker process could not be started", .{}); defer if (child.id) |pid| { std.posix.kill(pid, .KILL) catch {}; _ = child.wait(io) catch {}; }; - const left = deadline_ns - std.Io.Clock.awake.now(io).toNanoseconds(); - const req: Request = .{ .remaining_ns = @intCast(@max(0, left)), .encoded_bytes = budget.encoded_bytes, .pixels_used = budget.pixels_used, .pdf_len = pdf_bytes.len, .max_images = max_images, .max_pages = max_pages, .images_used = budget.images_used, .pdf_pages_used = budget.pdf_pages_used }; + const left = job.deadline_ns - std.Io.Clock.awake.now(io).toNanoseconds(); + const n: u32 = switch (job.sel) { + .all_within, .first => |k| k, + .list => |l| @intCast(l.len), + }; + const req: Request = .{ + .remaining_ns = @intCast(@max(0, left)), + .encoded_bytes = budget.encoded_bytes, + .pixels_used = budget.pixels_used, + .pdf_len = job.pdf_bytes.len, + .request_pixels = job.caps.request_pixels, + .request_bytes = job.caps.request_bytes, + .page_bytes = job.caps.page_bytes, + .max_images = job.caps.max_images, + .images_used = budget.images_used, + .pdf_pages_used = budget.pdf_pages_used, + .sel_kind = @backingInt(std.meta.activeTag(job.sel)), + .sel_n = n, + .infra = @backingInt(infra), + .measure = @intFromBool(job.measure), + }; const in = child.stdin.?.handle; const nonblock: u32 = @bitCast(std.c.O{ .NONBLOCK = true }); _ = std.c.fcntl(in, std.c.F.SETFL, std.c.fcntl(in, std.c.F.GETFL) | @as(c_int, @bitCast(nonblock))); - _ = sendAll(in, std.mem.asBytes(&req), deadline_ns) and sendAll(in, pdf_bytes, deadline_ns); + _ = sendAll(in, std.mem.asBytes(&req), job.deadline_ns) and sendAll(in, std.mem.sliceAsBytes(list), job.deadline_ns) and sendAll(in, job.pdf_bytes, job.deadline_ns); child.stdin.?.close(io); child.stdin = null; - const frame = readChildPipe(cx.a, child.stdout.?.handle, deadline_ns, images.max_request_bytes + (64 << 10)) catch |err| switch (err) { + const frame = readChildPipe(cx.a, child.stdout.?.handle, job.deadline_ns, job.caps.request_bytes +| (1 << 20)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, - error.Timeout => return cx.refuse("PDF rendering timed out"), - error.Overflow => return cx.refuse("the request's images exceed 20 MB encoded"), + error.Timeout => return cx.fail(infra, "PDF rendering timed out", .{}), + // chat keeps its byte-limit message; under OCR an oversized reply is a renderer failure + error.Overflow => return if (infra == .request) cx.fail(infra, "the request's images exceed {d} MB encoded", .{job.caps.request_bytes >> 20}) else cx.fail(infra, failed, .{}), }; - const term = child.wait(io) catch return cx.refuse(failed); - return reply(cx, term, frame, max_images, max_pages, budget, out_jpegs); + const term = child.wait(io) catch return cx.fail(infra, failed, .{}); + return reply(cx, term, frame, job.sel, job.measure, job.caps, budget, out); } /// A worker the kernel stopped at a limit keeps the limit message; any other signal is named as a crash. -fn reply(cx: *Cx, term: std.process.Child.Term, frame: []const u8, max_images: u32, max_pages: u32, budget: *Budget, out_jpegs: *std.ArrayList([]const u8)) errors.Refused!void { +fn reply(cx: *Cx, term: std.process.Child.Term, frame: []const u8, sel: pdf.Selection, measure: bool, caps: pdf.Caps, budget: *Budget, out: *std.ArrayList(Page)) errors.Refused!u32 { if (term == .signal) switch (term.signal) { - .KILL, .XCPU, .XFSZ => return cx.refuse(failed), + .KILL, .XCPU, .XFSZ => return cx.fail(caps.infra, failed, .{}), else => |sig| if (std.enums.tagName(std.posix.SIG, sig)) |name| - return cx.fail(.request, "the PDF render worker crashed (SIG{s})", .{name}) + return cx.fail(caps.infra, "the PDF render worker crashed (SIG{s})", .{name}) else - return cx.fail(.request, "the PDF render worker crashed (signal {d})", .{@backingInt(sig)}), + return cx.fail(caps.infra, "the PDF render worker crashed (signal {d})", .{@backingInt(sig)}), }; - return parseChildReply(cx, frame, max_images, max_pages, budget, out_jpegs); + return parseChildReply(cx, frame, sel, measure, caps, budget, out); } fn ready(fd: c_int, events: i16, deadline_ns: i96) bool { @@ -97,49 +139,52 @@ fn readChildPipe(a: Allocator, fd: c_int, deadline_ns: i96, max_bytes: usize) er return out.items; } -pub fn parseChildReply(cx: *Cx, frame: []const u8, max_images: u32, max_pages: u32, budget: *Budget, out_jpegs: *std.ArrayList([]const u8)) errors.Refused!void { - if (frame.len == 0) return cx.refuse(failed); +fn readU32(bytes: []const u8, at: usize) u32 { + return std.mem.readInt(u32, bytes[at..][0..4], .little); +} + +/// Checks the frame against `sel`, `caps` and the running `budget`, appends its pages; a measure's pages carry no JPEG. +pub fn parseChildReply(cx: *Cx, frame: []const u8, sel: pdf.Selection, measure: bool, caps: pdf.Caps, budget: *Budget, out: *std.ArrayList(Page)) errors.Refused!u32 { + if (frame.len == 0) return cx.fail(caps.infra, failed, .{}); switch (frame[0]) { 0 => { - if (frame.len < 5) return cx.refuse(failed); - const count = std.mem.readInt(u32, frame[1..5], .little); - if (count == 0) return cx.refuse("PDF document contains no pages"); - const limit: u32 = @max(@as(u32, 1), max_pages); - if (budget.pdf_pages_used +| count > limit) - return cx.refuse(try std.fmt.allocPrint(cx.a, "a PDF may have at most {d} pages (--vision-max-images, TENSORFOLD_MAX_PDF_PAGES); this request has {d}", .{ limit, budget.pdf_pages_used +| count })); - if (max_images > 0 and budget.images_used +| count > max_images) - return cx.refuse(try std.fmt.allocPrint(cx.a, "a request may hold at most {d} images (--vision-max-images); it has {d}", .{ max_images, budget.images_used +| count })); - var pos: usize = 5; - for (0..count) |_| { - if (pos + 4 > frame.len) return cx.refuse(failed); - const len: usize = std.mem.readInt(u32, frame[pos..][0..4], .little); - pos += 4; - if (len == 0 or pos + len > frame.len) return cx.refuse(failed); - if (len > images.max_image_bytes) return cx.refuse("rendered PDF page exceeds the 10 MB image byte limit"); - if (budget.encoded_bytes + len > images.max_request_bytes) return cx.refuse("the request's images exceed 20 MB encoded"); + if (frame.len < 9) return cx.fail(caps.infra, failed, .{}); + const count = readU32(frame, 1); + const total = readU32(frame, 5); + if (count > total or count != try pdf.admitCount(cx, sel, caps, budget, total)) return cx.fail(caps.infra, failed, .{}); + var pos: usize = 9; + for (0..count) |k| { + if (frame.len - pos < page_head) return cx.fail(caps.infra, failed, .{}); + const index, const width, const height, const dpi, const len = .{ readU32(frame, pos), readU32(frame, pos + 4), readU32(frame, pos + 8), readU32(frame, pos + 12), readU32(frame, pos + 16) }; + pos += page_head; + if (index != pdf.pageAt(sel, @intCast(k)) or dpi == 0 or dpi > pdf.max_dpi or (len == 0) != measure or frame.len - pos < len) + return cx.fail(caps.infra, failed, .{}); const jb = frame[pos .. pos + len]; - const size = pdf.jpegSize(jb) orelse return cx.refuse("rendered PDF page could not be encoded as JPEG"); - const px = @as(u64, size[0]) * size[1]; - if (budget.pixels_used + px > pdf.max_request_pixels) return cx.refuse("the request's images exceed the 32-megapixel limit"); - budget.pdf_pages_used += 1; - budget.images_used += 1; - budget.encoded_bytes += len; - budget.pixels_used += px; - try out_jpegs.append(cx.a, jb); + if (!measure) { + const size = pdf.jpegSize(jb) orelse return cx.fail(caps.infra, "rendered PDF page could not be encoded as JPEG", .{}); + if (size[0] != width or size[1] != height) return cx.fail(caps.infra, failed, .{}); + } + if (@min(width, height) < pdf.min_side or @max(width, height) > pdf.max_side) return cx.fail(caps.infra, failed, .{}); + const px = @as(u64, width) * height; + try pdf.checkPage(cx, caps, budget, px, len); + budget.add(px, len); + try out.append(cx.a, .{ .index = index, .jpeg = jb, .width = width, .height = height, .dpi = dpi }); pos += len; } - if (pos != frame.len) return cx.refuse(failed); + if (pos != frame.len) return cx.fail(caps.infra, failed, .{}); + return total; }, 1 => { - if (frame.len < 6) return cx.refuse("PDF rendering failed"); - cx.kind = std.enums.fromInt(errors.Kind, frame[1]) orelse .request; - const len: usize = std.mem.readInt(u32, frame[2..6], .little); - if (6 + len != frame.len) return cx.refuse("PDF rendering failed"); + if (frame.len < 6) return cx.fail(caps.infra, "PDF rendering failed", .{}); + const kind = std.enums.fromInt(errors.Kind, frame[1]) orelse return cx.fail(caps.infra, "PDF rendering failed", .{}); + const len: usize = readU32(frame, 2); + if (6 + len != frame.len) return cx.fail(caps.infra, "PDF rendering failed", .{}); + cx.kind = kind; cx.message = frame[6 .. 6 + len]; return error.Refused; }, 2 => return error.OutOfMemory, - else => return cx.refuse(failed), + else => return cx.fail(caps.infra, failed, .{}), } } @@ -148,13 +193,14 @@ pub fn serve() noreturn { closeRange(3, ~@as(c_uint, 0)); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); var cx: Cx = .{ .a = arena.allocator() }; - var jpegs: std.ArrayList([]const u8) = .empty; - if (work(&cx, &jpegs)) |_| { + var pages: std.ArrayList(Page) = .empty; + if (work(&cx, &pages)) |total| { _ = writeAll(1, &.{0}); - _ = writeInt(u32, 1, @intCast(jpegs.items.len)); - for (jpegs.items) |jb| { - _ = writeInt(u32, 1, @intCast(jb.len)); - _ = writeAll(1, jb); + _ = writeInt(u32, 1, @intCast(pages.items.len)); + _ = writeInt(u32, 1, total); + for (pages.items) |p| { + for ([_]u32{ p.index, p.width, p.height, p.dpi, @intCast(p.jpeg.len) }) |v| _ = writeInt(u32, 1, v); + _ = writeAll(1, p.jpeg); } } else |err| switch (err) { error.OutOfMemory => _ = writeAll(1, &.{2}), @@ -167,19 +213,34 @@ pub fn serve() noreturn { std.c._exit(0); } -fn work(cx: *Cx, jpegs: *std.ArrayList([]const u8)) errors.Refused!void { +fn work(cx: *Cx, pages: *std.ArrayList(Page)) errors.Refused!u32 { var req: Request = undefined; if (!readAll(0, std.mem.asBytes(&req)) or req.pdf_len > pdf.max_pdf_bytes) return cx.refuse(failed); const deadline_ns = std.Io.Clock.awake.now(log.io()).toNanoseconds() + req.remaining_ns; + const infra = std.enums.fromInt(errors.Kind, req.infra) orelse return cx.refuse(failed); + const Tag = std.meta.Tag(pdf.Selection); + const sel: pdf.Selection = switch (req.sel_kind) { + @backingInt(Tag.all_within) => .{ .all_within = req.sel_n }, + @backingInt(Tag.first) => .{ .first = req.sel_n }, + @backingInt(Tag.list) => blk: { + if (req.sel_n > max_list) return cx.fail(infra, failed, .{}); + const list = try cx.a.alloc(u32, req.sel_n); + if (!readAll(0, std.mem.sliceAsBytes(list))) return cx.fail(infra, failed, .{}); + break :blk .{ .list = list }; + }, + else => return cx.fail(infra, failed, .{}), + }; const pdf_bytes = try cx.a.alloc(u8, @intCast(req.pdf_len)); - if (!readAll(0, pdf_bytes)) return cx.refuse(failed); + if (!readAll(0, pdf_bytes)) return cx.fail(infra, failed, .{}); applyChildLimits(); const libs = sys.optional_libraries; const f = jpeg_out.loadDynLib(pdf.PdfiumFns, .pdfium, cx.a) orelse return cx.fail(.unimplemented, "{s}", .{libs.spec(.pdfium).message}); const jf = jpeg_out.loadDynLib(jpeg_out.Fns, .jpeg, cx.a) orelse return cx.fail(.unimplemented, "{s}", .{libs.spec(.jpeg).message}); f.FPDF_InitLibrary(); + const caps: pdf.Caps = .{ .request_pixels = req.request_pixels, .request_bytes = @intCast(req.request_bytes), .page_bytes = @intCast(req.page_bytes), .max_images = req.max_images, .infra = infra }; var budget: Budget = .{ .images_used = req.images_used, .pdf_pages_used = req.pdf_pages_used, .encoded_bytes = @intCast(req.encoded_bytes), .pixels_used = req.pixels_used }; - return pdf.renderInProcess(cx, f, jf, pdf_bytes, req.max_images, req.max_pages, deadline_ns, &budget, jpegs); + if (req.measure > 1) return cx.fail(infra, failed, .{}); + return pdf.renderInProcess(cx, f, jf, .{ .pdf_bytes = pdf_bytes, .sel = sel, .caps = caps, .deadline_ns = deadline_ns, .measure = req.measure == 1 }, &budget, pages); } fn applyChildLimits() void { @@ -239,15 +300,21 @@ fn writeInt(comptime T: type, fd: c_int, val: T) bool { return writeAll(fd, &b); } -fn fakeWorker(a: Allocator, script: []const u8, ms: i96) ![]const u8 { +/// A refused render of the two-page fixture by a `script` worker under `caps`, within `ms`; the budget stays untouched. +fn fakeWorkerCx(a: Allocator, script: []const u8, ms: i96, caps: pdf.Caps) !Cx { log.init(std.testing.io, false); var cx: Cx = .{ .a = a }; var budget: Budget = .{}; - var jpegs: std.ArrayList([]const u8) = .empty; + var pages: std.ArrayList(Page) = .empty; const deadline_ns = std.Io.Clock.awake.now(log.io()).toNanoseconds() + ms * std.time.ns_per_ms; - try std.testing.expectError(error.Refused, render(&cx, &.{ "/bin/sh", "-c", script }, pdf.minimal_two_page_pdf, 4, 4, deadline_ns, &budget, &jpegs)); + const job: pdf.Job = .{ .pdf_bytes = pdf.minimal_two_page_pdf, .sel = .{ .all_within = 4 }, .caps = caps, .deadline_ns = deadline_ns }; + try std.testing.expectError(error.Refused, render(&cx, &.{ "/bin/sh", "-c", script }, job, &budget, &pages)); try std.testing.expectEqual(Budget{}, budget); - return cx.message; + return cx; +} + +fn fakeWorker(a: Allocator, script: []const u8, ms: i96) ![]const u8 { + return (try fakeWorkerCx(a, script, ms, pdf.chatCaps(4))).message; } test "PDF render worker: a worker killed by a signal is named as a crash; a limit or a missing reply keeps today's message" { @@ -262,8 +329,8 @@ test "PDF render worker: a worker killed by a signal is named as a crash; a limi for ([_]std.process.Child.Term{ .{ .signal = .KILL }, .{ .signal = .XCPU }, .{ .signal = .XFSZ }, .{ .signal = .ABRT } }) |term| { var cx: Cx = .{ .a = a }; var budget: Budget = .{}; - var jpegs: std.ArrayList([]const u8) = .empty; - try std.testing.expectError(error.Refused, reply(&cx, term, &.{ 0, 0, 0, 0, 0 }, 4, 4, &budget, &jpegs)); + var pages: std.ArrayList(Page) = .empty; + try std.testing.expectError(error.Refused, reply(&cx, term, &.{ 0, 0, 0, 0, 0 }, .{ .all_within = 4 }, false, pdf.chatCaps(4), &budget, &pages)); try std.testing.expectEqualStrings(if (term.signal == .ABRT) "the PDF render worker crashed (SIGABRT)" else failed, cx.message); } } @@ -276,3 +343,37 @@ test "PDF render worker: a worker past its deadline is killed and reported as ti try std.testing.expectEqualStrings("PDF rendering timed out", try fakeWorker(arena.allocator(), "exec sleep 30", 300)); try std.testing.expect(std.Io.Clock.awake.now(log.io()).toNanoseconds() - started < 10 * std.time.ns_per_s); } + +test "pdf pages: a malformed worker frame, a crash or an oversized reply is a renderer failure of the caller's kind" { + if (comptime builtin.os.tag == .windows) return error.SkipZigTest; // the worker is POSIX only; Windows renders in process + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var budget: Budget = .{}; + var pages: std.ArrayList(Page) = .empty; + const ocr = pdf.ocrCaps(4); + const index_wrong = [_]u8{ 0, 2, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 28, 0, 0, 0, 28, 0, 0, 0, 144, 0, 0, 0, 1, 0, 0, 0, 0xFF }; + const sof = [_]u8{ 0xFF, 0xD8, 0xFF, 0xC0, 0, 11, 8, 0x10, 0, 0x10, 0, 1, 1, 0x11, 0 }; // a 4096 x 4096 frame header + const too_big = [_]u8{ 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0x10, 0, 0, 0, 0x10, 0, 0, 144, 0, 0, 0, sof.len, 0, 0, 0 } ++ sof; + const bad_kind = [_]u8{ 1, 0xFF, 3, 0, 0, 0, 'b', 'a', 'd' }; + const frames = [_][]const u8{ &.{}, &.{ 0, 1 }, &.{ 1, 0 }, &.{ 0, 1, 0, 0, 0, 2, 0, 0, 0 }, &index_wrong, &.{9}, &bad_kind }; + for ([_]pdf.Caps{ ocr, pdf.chatCaps(4) }) |caps| { + for (frames) |frame| { + var cx: Cx = .{ .a = a }; + try std.testing.expectError(error.Refused, parseChildReply(&cx, frame, .{ .first = 2 }, false, caps, &budget, &pages)); + try std.testing.expectEqual(caps.infra, cx.kind); + } + var cx: Cx = .{ .a = a }; + try std.testing.expectError(error.Refused, parseChildReply(&cx, &too_big, .{ .first = 1 }, false, caps, &budget, &pages)); + try std.testing.expectEqual(caps.infra, cx.kind); + // a crash, and a reply past the caps' encoded bytes, are the caller's kind too + try std.testing.expectEqual(caps.infra, (try fakeWorkerCx(a, "cat >/dev/null; kill -SEGV $$", 10_000, caps)).kind); + } + const over = try fakeWorkerCx(a, "cat >/dev/null; head -c 2000000 /dev/zero", 10_000, pdf.ocrCaps(0)); + try std.testing.expectEqualStrings(failed, over.message); + try std.testing.expectEqual(errors.Kind.server, over.kind); + try std.testing.expectEqual(Budget{}, budget); + try std.testing.expectEqual(@as(usize, 0), pages.items.len); + var oom_cx: Cx = .{ .a = a }; + try std.testing.expectError(error.OutOfMemory, parseChildReply(&oom_cx, &.{2}, .{ .first = 2 }, false, ocr, &budget, &pages)); +} diff --git a/zig/src/server/pdf_worker_test.zig b/zig/src/server/pdf_worker_test.zig index 446f093a483..da210c97bd8 100644 --- a/zig/src/server/pdf_worker_test.zig +++ b/zig/src/server/pdf_worker_test.zig @@ -16,6 +16,11 @@ fn useServer() void { worker.server_exe = @import("pdf_worker_exe").path; } +/// One render of `pdf_bytes` by the render deadline. +fn job(pdf_bytes: []const u8, sel: pdf.Selection, caps: pdf.Caps) pdf.Job { + return .{ .pdf_bytes = pdf_bytes, .sel = sel, .caps = caps, .deadline_ns = std.Io.Clock.awake.now(std.testing.io).toNanoseconds() + pdf.render_timeout_ns }; +} + fn expectMissingLibrary(cx: Cx) !void { const libs = sys.optional_libraries; try std.testing.expectEqual(errors.Kind.unimplemented, cx.kind); @@ -29,15 +34,15 @@ test "tensorfold-native PDF render worker: renders a text PDF in its spawned wor const a = arena.allocator(); var cx: Cx = .{ .a = a }; var budget: pdf.Budget = .{}; - var jpegs: std.ArrayList([]const u8) = .empty; - const deadline_ns = std.Io.Clock.awake.now(std.testing.io).toNanoseconds() + pdf.render_timeout_ns; - worker.render(&cx, try worker.argv(a), text_pdf, 4, 4, deadline_ns, &budget, &jpegs) catch |err| { + var pages: std.ArrayList(pdf.Page) = .empty; + const total = worker.render(&cx, try worker.argv(a), job(text_pdf, .{ .all_within = 4 }, pdf.chatCaps(4)), &budget, &pages) catch |err| { try std.testing.expectEqual(error.Refused, err); return expectMissingLibrary(cx); }; - try std.testing.expectEqual(@as(usize, 1), jpegs.items.len); - try std.testing.expectEqual(pdf.Budget{ .images_used = 1, .pdf_pages_used = 1, .encoded_bytes = jpegs.items[0].len, .pixels_used = 400 * 400 }, budget); - try std.testing.expectEqual([2]u32{ 400, 400 }, pdf.jpegSize(jpegs.items[0]).?); + try std.testing.expectEqual(@as(u32, 1), total); + try std.testing.expectEqual(@as(usize, 1), pages.items.len); + try std.testing.expectEqual(pdf.Budget{ .images_used = 1, .pdf_pages_used = 1, .encoded_bytes = pages.items[0].jpeg.len, .pixels_used = 400 * 400 }, budget); + try std.testing.expectEqual([2]u32{ 400, 400 }, pdf.jpegSize(pages.items[0].jpeg).?); } test "tensorfold-native PDF render worker: libpdfium renders in the spawned worker and enforces request-wide page, byte and pixel caps" { @@ -65,3 +70,74 @@ test "tensorfold-native PDF render worker: libpdfium renders in the spawned work try std.testing.expectError(error.Refused, pdf.expandBytes(&second_cx, pdf.minimal_two_page_pdf, "image_url", 4, 3, &budget, &parts)); try std.testing.expect(std.mem.indexOf(u8, second_cx.message, "at most 3 pages") != null); } + +test "tensorfold-native PDF render worker: a list selection renders only its pages, with their indices, size and DPI" { + useServer(); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + var budget: pdf.Budget = .{}; + var pages: std.ArrayList(pdf.Page) = .empty; + const total = worker.render(&cx, try worker.argv(a), job(pdf.minimal_two_page_pdf, .{ .list = &.{1} }, pdf.ocrCaps(16)), &budget, &pages) catch |err| { + try std.testing.expectEqual(error.Refused, err); + return expectMissingLibrary(cx); + }; + try std.testing.expectEqual(@as(u32, 2), total); + try std.testing.expectEqual(@as(usize, 1), pages.items.len); + const p = pages.items[0]; + try std.testing.expectEqual(pdf.Page{ .index = 1, .jpeg = p.jpeg, .width = 400, .height = 400, .dpi = 144 }, p); + var out_cx: Cx = .{ .a = a }; + try std.testing.expectError(error.Refused, worker.render(&out_cx, try worker.argv(a), job(pdf.minimal_two_page_pdf, .{ .list = &.{ 0, 2 } }, pdf.ocrCaps(16)), &budget, &pages)); + try std.testing.expectEqualStrings("page 2 is out of range; the document has 2 pages", out_cx.message); + try std.testing.expectEqual(errors.Kind.request, out_cx.kind); +} + +test "tensorfold-native PDF render worker: two chat PDFs share one request budget" { + useServer(); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var parts: std.ArrayList(Value) = .empty; + var budget: pdf.Budget = .{}; + for (0..2) |_| { + var cx: Cx = .{ .a = a }; + pdf.expandBytes(&cx, pdf.minimal_two_page_pdf, "image_url", 4, 4, &budget, &parts) catch |err| { + if (err == error.Refused and cx.kind == .unimplemented) return expectMissingLibrary(cx); + return err; + }; + } + try std.testing.expectEqual(@as(usize, 4), parts.items.len); + try std.testing.expectEqual(@as(u32, 4), budget.pdf_pages_used); + try std.testing.expectEqual(@as(u64, 4 * 400 * 400), budget.pixels_used); + var pages_cx: Cx = .{ .a = a }; + try std.testing.expectError(error.Refused, pdf.expandBytes(&pages_cx, pdf.minimal_two_page_pdf, "image_url", 4, 4, &budget, &parts)); + try std.testing.expectEqualStrings("a PDF may have at most 4 pages (--vision-max-images, TENSORFOLD_MAX_PDF_PAGES); this request has 6", pages_cx.message); + var images_cx: Cx = .{ .a = a }; + try std.testing.expectError(error.Refused, pdf.expandBytes(&images_cx, pdf.minimal_two_page_pdf, "image_url", 4, 8, &budget, &parts)); + try std.testing.expectEqualStrings("a request may hold at most 4 images (--vision-max-images); it has 6", images_cx.message); + try std.testing.expectEqual(@as(usize, 4), parts.items.len); +} + +test "tensorfold-native PDF render worker: a measure returns each page's size and DPI with no JPEG bytes" { + useServer(); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + var budget: pdf.Budget = .{}; + var pages: std.ArrayList(pdf.Page) = .empty; + var measure = job(pdf.minimal_two_page_pdf, .{ .all_within = 16 }, pdf.ocrCaps(16)); + measure.measure = true; + const total = worker.render(&cx, try worker.argv(a), measure, &budget, &pages) catch |err| { + try std.testing.expectEqual(error.Refused, err); + return expectMissingLibrary(cx); + }; + try std.testing.expectEqual(@as(u32, 2), total); + try std.testing.expectEqual(@as(usize, 2), pages.items.len); + for (pages.items, 0..) |p, i| { + try std.testing.expectEqual(@as(usize, 0), p.jpeg.len); + try std.testing.expectEqual(pdf.Page{ .index = @intCast(i), .jpeg = p.jpeg, .width = 400, .height = 400, .dpi = 144 }, p); + } + try std.testing.expectEqual(pdf.Budget{ .images_used = 2, .pdf_pages_used = 2, .pixels_used = 2 * 400 * 400 }, budget); +} diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 834352dbc08..771af549eb1 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -124,6 +124,7 @@ test { _ = @import("messages.zig"); _ = @import("pdf.zig"); _ = @import("pdf_flags_test.zig"); + _ = @import("pdf_measure_test.zig"); _ = @import("jpeg_out.zig"); _ = @import("images.zig"); _ = @import("images_video_marker_test.zig"); From 018d904a0f2c7e73c541e822cdf39a64d809d9b0 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:21:50 +0000 Subject: [PATCH 02/25] feat(ocr): read PDF documents and pages on POST /v1/ocr A Mistral client sends whole PDFs and picks pages with pages, so the route now reads PDF documents with --vision-pdf and the pages list or range string, bounded before it expands and deduplicated under the request's page budget. Every PDF is measured before the first generation, so an index out of range or a request over the budget is refused whole before any inference, and each page then renders alone in its page arena just before it is read, so one rendered page is in memory at a time; a client that leaves renders nothing. --- zig/src/server/ocr/budget.zig | 22 +++++- zig/src/server/ocr/budget_test.zig | 13 +++- zig/src/server/ocr/fetch.zig | 8 ++- zig/src/server/ocr/mistral.zig | 84 +++++++++++++++++++--- zig/src/server/ocr/mistral_test.zig | 62 +++++++++++++--- zig/src/server/ocr/run.zig | 104 +++++++++++++++++++++------ zig/src/server/ocr/run_pdf_test.zig | 105 ++++++++++++++++++++++++++++ zig/src/server/ocr/run_test.zig | 46 ++++++++++-- zig/src/server/ocr/types.zig | 7 +- zig/src/server/root.zig | 1 + 10 files changed, 400 insertions(+), 52 deletions(-) create mode 100644 zig/src/server/ocr/run_pdf_test.zig diff --git a/zig/src/server/ocr/budget.zig b/zig/src/server/ocr/budget.zig index df62906b28b..d2dcbc4c654 100644 --- a/zig/src/server/ocr/budget.zig +++ b/zig/src/server/ocr/budget.zig @@ -1,10 +1,11 @@ -//! A request's image-encode budget (docs/api.md OCR: Pages and budgets). +//! A request's page budget and image-encode budget (docs/api.md OCR: Pages and budgets). +const pdf = @import("../pdf.zig"); const types = @import("types.zig"); const Fault = types.Fault; /// The most images one request may encode. pub const max_count = 256; -/// The encoded bytes every request may hold, and what each page adds. +/// The encoded bytes every request may hold, and what each selected page adds. pub const base_bytes = 16 << 20; pub const page_bytes = 2 << 20; /// Encoded pixels may reach this many times the request's page pixels. @@ -12,6 +13,23 @@ pub const pixel_factor = 4; /// The unreadable-page reason for any encode limit. pub const over_message = "too many image regions"; +/// Pages a request may still read: images count 1 each, PDF pages as selected. +pub const Pages = struct { + left: u32, + + /// ``TENSORFOLD_MAX_PDF_PAGES`` (default and ceiling 16); ``--vision-max-images`` does not apply. + pub fn init() Pages { + return .{ .left = pdf.maxPagesLimit(0) }; + } + + /// Takes ``n`` pages; false, and nothing taken, when fewer than ``n`` are left. + pub fn take(p: *Pages, n: u32) bool { + if (n > p.left) return false; + p.left -= n; + return true; + } +}; + /// The crops a request has encoded, against its limits. pub const Encodes = struct { count: u32 = 0, diff --git a/zig/src/server/ocr/budget_test.zig b/zig/src/server/ocr/budget_test.zig index 9c9f8b487a2..31d334f119b 100644 --- a/zig/src/server/ocr/budget_test.zig +++ b/zig/src/server/ocr/budget_test.zig @@ -1,9 +1,20 @@ -//! The image-encode budget (docs/api.md OCR: Pages and budgets). +//! The page budget and the image-encode budget (docs/api.md OCR: Pages and budgets). const std = @import("std"); const budget = @import("budget.zig"); const types = @import("types.zig"); const t = std.testing; +test "ocr budget: pages default to at most 16 and take only what is left" { + const p = budget.Pages.init(); + try t.expect(p.left >= 1 and p.left <= 16); + var q: budget.Pages = .{ .left = 3 }; + try t.expect(q.take(2)); + try t.expect(!q.take(2)); + try t.expectEqual(@as(u32, 1), q.left); + try t.expect(q.take(1)); + try t.expect(!q.take(1)); +} + test "ocr budget: the 257th encode faults before it runs" { var fault: types.Fault = undefined; var e = budget.Encodes.init(1 << 30, 1); diff --git a/zig/src/server/ocr/fetch.zig b/zig/src/server/ocr/fetch.zig index 2da7af279ac..dc99305de3e 100644 --- a/zig/src/server/ocr/fetch.zig +++ b/zig/src/server/ocr/fetch.zig @@ -8,14 +8,16 @@ const pdf = @import("../pdf.zig"); /// The fetched bytes, or the words of a refusal (bad input). pub const Got = union(enum) { bytes: []const u8, refused: []const u8 }; -/// ``url`` fetched when --vision-urls gave a fetcher: an image, at most 32 MiB. -pub fn https(a: Allocator, fetch: ?images.Fetch, url: []const u8) Allocator.Error!Got { +/// ``url`` fetched when --vision-urls gave a fetcher: an image, or a PDF too when ``pdf_on``; at most 32 MiB. +pub fn https(a: Allocator, fetch: ?images.Fetch, url: []const u8, pdf_on: bool) Allocator.Error!Got { if (!std.mem.startsWith(u8, url, "https://")) return .{ .refused = "documents require data URLs or public HTTPS URLs" }; const f = fetch orelse return .{ .refused = "document URLs are off on this server; send a data URL, or start the server with --vision-urls" }; if (url.len > media_fetch.max_url_chars) return .{ .refused = "document URL is too long" }; + const with_pdf = media_fetch.image_media ++ [_][]const u8{"application/pdf"}; + const media: []const []const u8 = if (pdf_on) &with_pdf else &media_fetch.image_media; var failure: media_fetch.Failure = .{}; const deadline = std.Io.Clock.awake.now(f.io).addDuration(.fromSeconds(media_fetch.timeout_s)); - const bytes = f.get(f.ctx, a, f.io, url, pdf.max_pdf_bytes, deadline, &media_fetch.image_media, &failure) catch |e| switch (e) { + const bytes = f.get(f.ctx, a, f.io, url, pdf.max_pdf_bytes, deadline, media, &failure) catch |e| switch (e) { error.OutOfMemory => return error.OutOfMemory, error.Media => return .{ .refused = failure.text }, }; diff --git a/zig/src/server/ocr/mistral.zig b/zig/src/server/ocr/mistral.zig index 89d24ee6ee4..f9bd52d6da9 100644 --- a/zig/src/server/ocr/mistral.zig +++ b/zig/src/server/ocr/mistral.zig @@ -6,9 +6,11 @@ const errors = @import("../errors.zig"); const images = @import("../images.zig"); const http_body = @import("../http_body.zig"); const openai = @import("../openai.zig"); +const pdf = @import("../pdf.zig"); const Conn = @import("../http_conn.zig").Conn; const Server = @import("../server.zig").Server; const types = @import("types.zig"); +const budget = @import("budget.zig"); const run = @import("run.zig"); const fetch = @import("fetch.zig"); const reply = @import("mistral_reply.zig"); @@ -18,12 +20,17 @@ const Step = run.Step; pub const Options = reply.Options; -/// What decoding needs from the server: the URL fetcher. +/// The most page entries a ``pages`` value may name before expansion (a range counts its length). +pub const max_page_entries = 1024; + +/// What decoding needs from the server: the PDF switch, the URL fetcher and the page budget. pub const Facts = struct { + pdf: bool, fetch: ?images.Fetch, + pages_left: u32, pub fn of(srv: *const Server) Facts { - return .{ .fetch = if (srv.config.vision_urls) images.Fetch.network(srv.io) else null }; + return .{ .pdf = srv.config.vision_pdf, .fetch = if (srv.config.vision_urls) images.Fetch.network(srv.io) else null, .pages_left = budget.Pages.init().left }; } }; @@ -91,8 +98,7 @@ pub fn decode(a: Allocator, body: Value, facts: Facts, fault: *Fault) Step!Reque const ok = v == .string and (std.mem.eql(u8, v.string, "word") or std.mem.eql(u8, v.string, "page") or std.mem.eql(u8, v.string, "block")); if (!ok) return bad(a, fault, &.{ "body", "confidence_scores_granularity" }, "confidence_scores_granularity must be \"word\", \"page\", \"block\" or null", .{}); } - // this route reads one page image: pages selects PDF pages, and a PDF document is refused - if (body.field("pages") != null) return bad(a, fault, &.{ "body", "pages" }, "pages selects pages of a PDF document; POST /v1/ocr reads one page image", .{}); + const pages: ?[]const u32 = if (body.field("pages")) |v| try pageList(a, fault, v, facts.pages_left) else null; const bytes = try document(a, fault, body, facts); const image = switch (images.sniff(bytes)) { .png, .jpeg, .webp => true, @@ -100,9 +106,14 @@ pub fn decode(a: Allocator, body: Value, facts: Facts, fault: *Fault) Step!Reque }; // the image signature first: a PNG text chunk or a JPEG comment may hold "%PDF-" const is_pdf = !image and std.mem.indexOf(u8, bytes[0..@min(bytes.len, 1024)], "%PDF-") != null; - if (is_pdf) return bad(a, fault, &.{ "body", "document" }, "PDF documents are not read on POST /v1/ocr; send each page as a PNG, JPEG or WebP image", .{}); - if (!image) return bad(a, fault, &.{ "body", "document" }, "the document is not a PNG, JPEG or WebP image", .{}); - return .{ .options = o, .source = .{ .bytes = bytes }, .doc_size = bytes.len }; + if (is_pdf) { + if (!facts.pdf) return bad(a, fault, &.{ "body", "document" }, "{s}", .{pdf.off_message}); + const sel: pdf.Selection = if (pages) |l| .{ .list = l } else .{ .all_within = std.math.maxInt(u32) }; + return .{ .options = o, .source = .{ .bytes = bytes, .kind = .pdf, .sel = sel }, .doc_size = bytes.len }; + } + if (!image) return bad(a, fault, &.{ "body", "document" }, "the document is not a PDF, PNG, JPEG or WebP file", .{}); + if (pages) |l| if (l.len != 1 or l[0] != 0) return bad(a, fault, &.{ "body", "pages" }, "an image has one page; pages may select only page 0", .{}); + return .{ .options = o, .source = .{ .bytes = bytes, .kind = .image, .sel = .{ .all_within = 1 } }, .doc_size = bytes.len }; } fn flag(a: Allocator, fault: *Fault, body: Value, name: []const u8) Step!?bool { @@ -117,6 +128,63 @@ fn count(a: Allocator, fault: *Fault, body: Value, name: []const u8) Step!?u64 { return std.fmt.parseInt(u64, v.int, 10) catch std.math.maxInt(u64); // past u64: no bound, as an unbounded count } +/// ``pages`` (indices, or a string of ``n`` and ``a-b`` ranges) as sorted distinct indices, bounded before expanding. +pub fn pageList(a: Allocator, fault: *Fault, v: Value, left: u32) Step![]const u32 { + const loc: []const []const u8 = &.{ "body", "pages" }; + var ranges: std.ArrayList([2]u32) = .empty; + var sum: u64 = 0; + switch (v) { + .array => |items| for (items) |item| { + const n = (if (item == .int) std.fmt.parseInt(u32, item.int, 10) catch null else null) orelse + return bad(a, fault, loc, "pages must hold page indices from 0 to 4294967295", .{}); + sum += 1; + if (sum > max_page_entries) return bad(a, fault, loc, "pages selects too many pages", .{}); + try ranges.append(a, .{ n, n }); + }, + .string => |s| if (std.mem.trim(u8, s, " \t").len > 0) { + var it = std.mem.splitScalar(u8, s, ','); + while (it.next()) |raw| { + const part = std.mem.trim(u8, raw, " \t"); + const dash = std.mem.indexOfScalar(u8, part, '-'); + const lo = try index(a, fault, if (dash) |d| part[0..d] else part); + const hi = if (dash) |d| try index(a, fault, part[d + 1 ..]) else lo; + if (lo > hi) return bad(a, fault, loc, "pages range {s} runs backwards", .{part}); + sum += @as(u64, hi) - lo + 1; + if (sum > max_page_entries) return bad(a, fault, loc, "pages selects too many pages", .{}); + try ranges.append(a, .{ lo, hi }); + } + }, + else => return bad(a, fault, loc, "pages must be a list of page indices or a string such as \"0,2-4\"", .{}), + } + if (ranges.items.len == 0) return bad(a, fault, loc, "pages selects no pages", .{}); + const all = try a.alloc(u32, @intCast(sum)); + var k: usize = 0; + for (ranges.items) |r| { + var i = r[0]; + while (true) : (i += 1) { + all[k] = i; + k += 1; + if (i == r[1]) break; + } + } + std.mem.sort(u32, all, {}, std.sort.asc(u32)); + var n: usize = 0; + for (all) |i| if (n == 0 or all[n - 1] != i) { + all[n] = i; + n += 1; + }; + if (n > left) return bad(a, fault, loc, "pages selects {d} pages; a request may read at most {d} (TENSORFOLD_MAX_PDF_PAGES)", .{ n, left }); + return all[0..n]; +} + +fn index(a: Allocator, fault: *Fault, text: []const u8) Step!u32 { + const t = std.mem.trim(u8, text, " \t"); + var digits = t.len > 0; + for (t) |ch| digits = digits and std.ascii.isDigit(ch); + if (digits) if (std.fmt.parseInt(u32, t, 10)) |n| return n else |_| {}; + return bad(a, fault, &.{ "body", "pages" }, "pages: \"{s}\" is not a page index from 0 to 4294967295", .{t}); +} + /// The document's bytes: a data URL, or an https URL fetched when --vision-urls is on. fn document(a: Allocator, fault: *Fault, body: Value, facts: Facts) Step![]const u8 { const doc = body.field("document") orelse return bad(a, fault, &.{ "body", "document" }, "document is required", .{}); @@ -137,7 +205,7 @@ fn document(a: Allocator, fault: *Fault, body: Value, facts: Facts) Step![]const error.OutOfMemory => error.OutOfMemory, error.Refused => bad(a, fault, loc, "{s}", .{cx.message}), }; - return switch (try fetch.https(a, facts.fetch, url)) { + return switch (try fetch.https(a, facts.fetch, url, facts.pdf)) { .bytes => |b| b, .refused => |m| bad(a, fault, loc, "{s}", .{m}), }; diff --git a/zig/src/server/ocr/mistral_test.zig b/zig/src/server/ocr/mistral_test.zig index ac081aee845..1646f3e379d 100644 --- a/zig/src/server/ocr/mistral_test.zig +++ b/zig/src/server/ocr/mistral_test.zig @@ -1,4 +1,4 @@ -//! Mistral /v1/ocr request decoding (field refusals), table forms and the error envelope. +//! Mistral /v1/ocr request decoding (pages bounds, field refusals), table forms and the error envelope. const std = @import("std"); const api = @import("engine_api"); const json = @import("json"); @@ -17,7 +17,46 @@ fn value(a: Allocator, text: []const u8) !json.Value { }; } -const facts: mistral.Facts = .{ .fetch = null }; +/// ``pages`` decoded against a 16-page budget: the indices, or the fault's message. +fn pages(a: Allocator, text: []const u8, fault: *types.Fault) ![]const u32 { + return mistral.pageList(a, fault, try value(a, text), 16); +} + +test "ocr mistral: pages bounds hold before any allocation and dedupe within the page budget" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var fault: types.Fault = undefined; + try t.expectError(error.Faulted, pages(a, "\"0-4294967295\"", &fault)); + try t.expectEqualStrings("pages selects too many pages", fault.message); + try t.expectEqual(types.Class.bad_input, fault.class); + try t.expectEqualStrings("pages", fault.loc[1]); + try t.expectError(error.Faulted, pages(a, "\"0-99999999999\"", &fault)); + try t.expect(std.mem.indexOf(u8, fault.message, "99999999999") != null); + var hundred: std.ArrayList(u8) = .empty; + var two_thousand: std.ArrayList(u8) = .empty; + for ([_]struct { *std.ArrayList(u8), usize }{ .{ &hundred, 100 }, .{ &two_thousand, 2000 } }) |c| { + try c[0].append(a, '['); + for (0..c[1]) |i| try c[0].appendSlice(a, if (i == 0) "0" else ",0"); + try c[0].append(a, ']'); + } + try t.expectEqualSlices(u32, &.{0}, try pages(a, hundred.items, &fault)); + try t.expectError(error.Faulted, pages(a, two_thousand.items, &fault)); + try t.expectEqualStrings("pages selects too many pages", fault.message); + const sixteen = try pages(a, "\"0-15,0-15\"", &fault); + try t.expectEqual(@as(usize, 16), sixteen.len); + try t.expectEqual(@as(u32, 15), sixteen[15]); + try t.expectEqualSlices(u32, &.{ 0, 2, 3, 4, 7 }, try pages(a, "\" 7 , 2 - 4,0\"", &fault)); + try t.expectEqualSlices(u32, &.{ 1, 3 }, try pages(a, "[3, 1, 3]", &fault)); + try t.expectError(error.Faulted, pages(a, "\"0-16\"", &fault)); + try t.expect(std.mem.indexOf(u8, fault.message, "TENSORFOLD_MAX_PDF_PAGES") != null); + for ([_][]const u8{ "\"4-2\"", "\"\"", "[]", "\"1,,2\"", "\"x\"", "[-1]", "[1.0]", "true", "\"-3\"" }) |bad| { + try t.expectError(error.Faulted, pages(a, bad, &fault)); + try t.expectEqual(types.Class.bad_input, fault.class); + } +} + +const facts: mistral.Facts = .{ .pdf = false, .fetch = null, .pages_left = 16 }; /// A request body around ``doc`` (a document object) and ``extra`` fields. fn body(a: Allocator, doc: []const u8, extra: []const u8) !json.Value { @@ -42,16 +81,17 @@ test "ocr mistral: explicit nulls mean absent, and each document form decodes" { const doc = try imageDoc(a); const r = try mistral.decode(a, try body(a, doc, nulls), facts, &fault); try t.expectEqual(mistral.Options{}, r.options); + try t.expect(r.source.kind == .image); try t.expectEqual(r.source.bytes.len, r.doc_size); - // image_url as {url, detail}, and document_url with an image data URL + // image_url as {url, detail}, document_url with an image data URL, and pages [0] or "0" on an image const url = doc[std.mem.indexOf(u8, doc, "data:").? .. doc.len - 2]; for ([_][]const u8{ try std.fmt.allocPrint(a, "{{\"type\": \"image_url\", \"image_url\": {{\"url\": \"{s}\", \"detail\": \"high\"}}}}", .{url}), try std.fmt.allocPrint(a, "{{\"type\": \"document_url\", \"document_url\": \"{s}\", \"document_name\": \"scan\"}}", .{url}), - }) |d| { - const got = try mistral.decode(a, try body(a, d, ""), facts, &fault); + }) |d| for ([_][]const u8{ "", ", \"pages\": [0]", ", \"pages\": \"0\"" }) |extra| { + const got = try mistral.decode(a, try body(a, d, extra), facts, &fault); try t.expectEqualSlices(u8, r.source.bytes, got.source.bytes); - } + }; const set = try mistral.decode(a, try body(a, doc, ", \"table_format\": \"html\", \"extract_header\": true, \"include_blocks\": false, \"image_limit\": 2, \"image_min_size\": 9, \"confidence_scores_granularity\": \"word\""), facts, &fault); try t.expectEqual(mistral.Options{ .tables = .html, .header = true, .blocks = false, .image_limit = 2, .image_min_size = 9 }, set.options); } @@ -69,16 +109,15 @@ test "ocr mistral: content-changing and malformed fields are refused with their .{ .doc = doc, .extra = ", \"include_image_base64\": \"yes\"", .field = "include_image_base64", .says = "must be a boolean" }, .{ .doc = doc, .extra = ", \"image_limit\": -1", .field = "image_limit", .says = "non-negative integer" }, .{ .doc = doc, .extra = ", \"confidence_scores_granularity\": \"line\"", .field = "confidence_scores_granularity", .says = "must be" }, - .{ .doc = doc, .extra = ", \"pages\": [0]", .field = "pages", .says = "pages selects pages of a PDF document; POST /v1/ocr reads one page image" }, - .{ .doc = doc, .extra = ", \"pages\": \"0-2\"", .field = "pages", .says = "pages selects pages of a PDF document" }, + .{ .doc = doc, .extra = ", \"pages\": [1]", .field = "pages", .says = "only page 0" }, .{ .doc = doc, .extra = ", \"model\": 3", .field = "model", .says = "model must be" }, .{ .doc = "{\"type\": \"file\", \"file_id\": \"f\"}", .extra = "", .field = "document", .says = "file documents are not supported; send document_url with a data URL" }, .{ .doc = "{\"type\": \"document_url\", \"document_url\": \"https://example.com/a.pdf\"}", .extra = "", .field = "document", .says = "--vision-urls" }, .{ .doc = "{\"type\": \"image_url\", \"image_url\": \"http://example.com/a.png\"}", .extra = "", .field = "document", .says = "public HTTPS URLs" }, .{ .doc = "{\"type\": \"image_url\", \"image_url\": \"data:image/png;base64,!!\"}", .extra = "", .field = "document", .says = "invalid document data URL encoding" }, - .{ .doc = "{\"type\": \"image_url\", \"image_url\": \"data:text/plain,hello\"}", .extra = "", .field = "document", .says = "the document is not a PNG, JPEG or WebP image" }, + .{ .doc = "{\"type\": \"image_url\", \"image_url\": \"data:text/plain,hello\"}", .extra = "", .field = "document", .says = "not a PDF, PNG, JPEG or WebP" }, .{ .doc = "{\"type\": \"video_url\"}", .extra = "", .field = "document", .says = "document.type must be" }, - .{ .doc = pdf_doc, .extra = "", .field = "document", .says = "PDF documents are not read on POST /v1/ocr; send each page as a PNG, JPEG or WebP image" }, + .{ .doc = pdf_doc, .extra = "", .field = "document", .says = "--vision-pdf" }, }; for (cases) |c| { var fault: types.Fault = undefined; @@ -167,7 +206,8 @@ test "ocr mistral: a PNG whose text chunk says %PDF- is an image, not a PDF" { const b64 = try a.alloc(u8, enc.calcSize(png.len)); const doc = try std.fmt.allocPrint(a, "{{\"type\": \"image_url\", \"image_url\": \"data:image/png;base64,{s}\"}}", .{enc.encode(b64, png)}); var fault: types.Fault = undefined; - // a PDF document would be refused; the image is read + // with --vision-pdf off a PDF would be refused; the image is read const req = try mistral.decode(a, try body(a, doc, ""), facts, &fault); + try t.expectEqual(.image, req.source.kind); try t.expectEqual(png.len, req.source.bytes.len); } diff --git a/zig/src/server/ocr/run.zig b/zig/src/server/ocr/run.zig index dfd68630d0f..d6ecdffd117 100644 --- a/zig/src/server/ocr/run.zig +++ b/zig/src/server/ocr/run.zig @@ -46,8 +46,10 @@ pub fn gate(srv: *const Server, a: Allocator, fault: *Fault) Step!void { if (srv.info.vision == null) return fault.fail(a, .bad_input, "{s}", .{no_vision}); } -/// One page to read: its encoded image and its pixel count. -const Planned = struct { bytes: []const u8, pixels: u64 }; +/// Where a page's encoded image comes from: an image source's bytes, or a measured PDF page rendered just before use. +const Origin = union(enum) { image: []const u8, pdf: struct { bytes: []const u8, width: u32, height: u32 } }; +/// One page to read: its index in its source, where its image comes from, its DPI and its pixel count. +const Planned = struct { index: u32, origin: Origin, dpi: u32, pixels: u64 }; /// Reads every page of ``sources`` in order into ``sink``; ``a`` is the request arena, ``gone`` says the client left. pub fn run(srv: *Server, a: Allocator, sources: []const Source, sink: PageSink, fault: *Fault, gone: anytype) Step!void { @@ -55,7 +57,7 @@ pub fn run(srv: *Server, a: Allocator, sources: []const Source, sink: PageSink, const reader = srv.info.ocr.?; const id = try ids.make(a, "ocr-", 24); if (gone.check()) return error.Cancelled; - const pages = try plan(srv, a, sources, fault); + const pages = try plan(srv, a, sources, fault, gone); var total: u64 = 0; for (pages) |p| total +|= p.pixels; // one limit for the whole request, from every page's pixels, so no encode depends on the order of the pages @@ -66,11 +68,45 @@ pub fn run(srv: *Server, a: Allocator, sources: []const Source, sink: PageSink, } } -/// Every source's page, its pixels counted before any inference. -fn plan(srv: *const Server, a: Allocator, sources: []const Source, fault: *Fault) Step![]const Planned { - const out = try a.alloc(Planned, sources.len); - for (sources, out) |s, *p| p.* = .{ .bytes = s.bytes, .pixels = try imagePixels(srv, a, s.bytes, fault) }; - return out; +/// Every source's pages within one page budget; PDFs are measured here, so a bad page fails before any inference. +fn plan(srv: *const Server, a: Allocator, sources: []const Source, fault: *Fault, gone: anytype) Step![]const Planned { + var left = budget.Pages.init(); + const cap = left.left; + // pdf.zig's running budget; images count among its pages, so its page-limit refusal names the request's totals + var used: pdf.Budget = .{}; + var cx: Cx = .{ .a = a }; + var out: std.ArrayList(Planned) = .empty; + for (sources) |s| { + switch (s.kind) { + .image => { + if (!left.take(1)) return overBudget(a, fault, cap); + used.pdf_pages_used += 1; + const px = try imagePixels(srv, a, s.bytes, fault); + try out.append(a, .{ .index = 0, .origin = .{ .image = s.bytes }, .dpi = 72, .pixels = px }); + }, + .pdf => { + if (!srv.config.vision_pdf) return fault.fail(a, .bad_input, "{s}", .{pdf.off_message}); + const sel: pdf.Selection = switch (s.sel) { + .all_within => |n| .{ .all_within = @min(n, left.left) }, + .first => |n| .{ .first = @min(n, left.left) }, + .list => |l| if (l.len > left.left) return overBudget(a, fault, cap) else s.sel, + }; + // a client that left must not hold the shared renderer for its deadline + if (gone.check()) return error.Cancelled; + // sizes and DPI only: each page renders alone just before its generation (onePage) + const r = pdf.measurePages(&cx, s.bytes, sel, pdf.ocrCaps(cap), &used, gone) catch |e| return switch (e) { + error.Cancelled => error.Cancelled, // it left while another request held the renderer + else => |refusal| refused(a, &cx, fault, refusal), + }; + if (!left.take(@intCast(r.pages.len))) return overBudget(a, fault, cap); + for (r.pages) |p| { + const origin: Origin = .{ .pdf = .{ .bytes = s.bytes, .width = p.width, .height = p.height } }; + try out.append(a, .{ .index = p.index, .origin = origin, .dpi = p.dpi, .pixels = @as(u64, p.width) * p.height }); + } + }, + } + } + return out.items; } /// An image's pixel count from its header, else from one decode within the page limit (freed at once). @@ -89,44 +125,70 @@ fn decodeFault(a: Allocator, fault: *Fault, e: picture.Error) Step { }; } -/// An image is page 0 of its source: the index its reply and its messages give. -const page_index = 0; +fn overBudget(a: Allocator, fault: *Fault, cap: u32) Step { + return fault.fail(a, .bad_input, "a request may read at most {d} pages (TENSORFOLD_MAX_PDF_PAGES); this one selects more", .{cap}); +} + +fn refused(a: Allocator, cx: *const Cx, fault: *Fault, e: errors.Refused) Step { + return switch (e) { + error.Refused => Fault.fromCx(a, cx, fault), + error.OutOfMemory => error.OutOfMemory, + }; +} + +/// One measured PDF page rendered alone into ``pa``; a size other than its measure's is an internal fault. +fn renderOne(a: Allocator, pa: Allocator, doc: []const u8, index: u32, width: u32, height: u32, fault: *Fault, gone: anytype) Step![]const u8 { + var cx: Cx = .{ .a = pa }; + var used: pdf.Budget = .{}; + const list = [_]u32{index}; + const r = pdf.renderPages(&cx, doc, .{ .list = &list }, pdf.ocrCaps(1), &used, gone) catch |e| return switch (e) { + error.Cancelled => error.Cancelled, // it left while another request held the renderer + else => |refusal| refused(a, &cx, fault, refusal), + }; + if (r.pages.len != 1 or r.pages[0].width != width or r.pages[0].height != height) + return fault.fail(a, .internal, "page {d}: the rendered page's size differs from its measure", .{index}); + return r.pages[0].jpeg; +} /// One page in its own arena: decode, generate, parse, validate, then the sink while the pixels live. fn onePage(srv: *Server, a: Allocator, reader: api.ocr.Ocr, id: []const u8, p: Planned, sink: PageSink, enc: *budget.Encodes, fault: *Fault, gone: anytype) Step!void { var arena = std.heap.ArenaAllocator.init(srv.gpa); defer arena.deinit(); const pa = arena.allocator(); - const bytes = p.bytes; + // a PDF page's JPEG lives in the page arena and goes with it, so one rendered page is in memory at a time + const bytes = switch (p.origin) { + .image => |b| b, + .pdf => |doc| try renderOne(a, pa, doc.bytes, p.index, doc.width, doc.height, fault, gone), + }; const rgb = picture.decodeWithLimits(srv.io, pa, bytes, .{ .pixels = max_page_pixels }) catch |e| return decodeFault(a, fault, e); const w: u32 = @intCast(rgb.width); const h: u32 = @intCast(rgb.height); // the budget was planned from the header; pixels that disagree (an EXIF turn keeps the product) fail the request - if (@min(@as(u64, w) * h, max_page_pixels) != p.pixels) return fault.fail(a, .bad_input, "page {d}: the image's header and its pixels disagree", .{page_index}); + if (@min(@as(u64, w) * h, max_page_pixels) != p.pixels) return fault.fail(a, .bad_input, "page {d}: the image's header and its pixels disagree", .{p.index}); var pcx: Cx = .{ .a = pa }; - const got = try generate(srv, &pcx, a, reader, id, bytes, fault, gone); + const got = try generate(srv, &pcx, a, reader, id, p, bytes, fault, gone); const parsed = reader.parse(pa, got.content, .{ .width = w, .height = h }, got.frame) catch |e| { if (e == error.OutOfMemory) return error.OutOfMemory; - if (e != error.Unreadable) return fault.fail(a, .internal, "page {d}: the OCR reader failed ({s})", .{ page_index, @errorName(e) }); - log.line("{s}: page {d}: the model's output does not follow its format: {s}", .{ id, page_index, got.content }); - return fault.fail(a, .unreadable, "page {d}: the model's output does not follow its format", .{page_index}); + if (e != error.Unreadable) return fault.fail(a, .internal, "page {d}: the OCR reader failed ({s})", .{ p.index, @errorName(e) }); + log.line("{s}: page {d}: the model's output does not follow its format: {s}", .{ id, p.index, got.content }); + return fault.fail(a, .unreadable, "page {d}: the model's output does not follow its format", .{p.index}); }; const blocks = try a.alloc(api.ocr.OcrBlock, parsed.len); for (parsed, blocks) |b, *o| { const quad = geometry.validate(b.quad, w, h) catch { - log.line("{s}: page {d}: a box is not finite: {s}", .{ id, page_index, got.content }); - return fault.fail(a, .unreadable, "page {d}: the model's output has a box that is not finite", .{page_index}); + log.line("{s}: page {d}: a box is not finite: {s}", .{ id, p.index, got.content }); + return fault.fail(a, .unreadable, "page {d}: the model's output has a box that is not finite", .{p.index}); }; o.* = .{ .content = try a.dupe(u8, b.content), .quad = quad, .kind = b.kind }; } - const page: OcrPage = .{ .index = page_index, .width = w, .height = h, .dpi = 72, .blocks = blocks }; + const page: OcrPage = .{ .index = p.index, .width = w, .height = h, .dpi = p.dpi, .blocks = blocks }; try sink.page(sink.ctx, a, &page, rgb, enc, fault); } const Generated = struct { content: []const u8, frame: api.Size }; /// The page as one user turn (image, then the reader's prompt) through chat.prepare and chat.generate, greedy. -fn generate(srv: *Server, pcx: *Cx, a: Allocator, reader: api.ocr.Ocr, id: []const u8, bytes: []const u8, fault: *Fault, gone: anytype) Step!Generated { +fn generate(srv: *Server, pcx: *Cx, a: Allocator, reader: api.ocr.Ocr, id: []const u8, p: Planned, bytes: []const u8, fault: *Fault, gone: anytype) Step!Generated { const pa = pcx.a; const mime: []const u8 = switch (images.sniff(bytes)) { .png => "image/png", @@ -146,7 +208,7 @@ fn generate(srv: *Server, pcx: *Cx, a: Allocator, reader: api.ocr.Ocr, id: []con return fault.fail(a, .internal, "the model's image step reported no frame", .{}); }; const reply = chat.generate(srv, pcx, prepared, null, gone) catch |e| return chatFault(a, pcx, fault, e); - finished(a, fault, reply.finish_reason, page_index, gone) catch |e| { + finished(a, fault, reply.finish_reason, p.index, gone) catch |e| { if (e == error.Faulted and fault.class == .unreadable) log.line("{s}: {s}: {s}", .{ id, fault.message, reply.content }); // the message names the page return e; }; diff --git a/zig/src/server/ocr/run_pdf_test.zig b/zig/src/server/ocr/run_pdf_test.zig new file mode 100644 index 00000000000..d3b212cc902 --- /dev/null +++ b/zig/src/server/ocr/run_pdf_test.zig @@ -0,0 +1,105 @@ +//! One rendered PDF page at a time: a scripted render worker answers each call in turn, the sink counts them per page. +const std = @import("std"); +const builtin = @import("builtin"); +const picture = @import("core").picture; +const jpeg_out = @import("../jpeg_out.zig"); +const log = @import("../log.zig"); +const pdf = @import("../pdf.zig"); +const worker = @import("../pdf_worker.zig"); +const run = @import("run.zig"); +const types = @import("types.zig"); +const budget = @import("budget.zig"); +const harness = @import("harness_test.zig"); +const t = std.testing; +const Allocator = std.mem.Allocator; + +const Gone = struct { + pub fn check(_: @This()) bool { + return false; + } +}; + +/// The script the server starts as its render worker: it reads the request and answers the n-th call with reply.bin. +const script = + \\#!/bin/sh + \\cd "$(dirname "$0")" || exit 1 + \\cat >/dev/null + \\n=$(cat calls 2>/dev/null || echo 0) + \\echo $((n + 1)) >calls + \\exec cat "reply$n.bin" +; + +/// A worker reply frame for a two-page document: each page at 400 x 400 and 144 DPI with `jpeg` (empty: measured). +fn frame(a: Allocator, indices: []const u32, jpeg: []const u8) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + try out.append(a, 0); + for ([_]u32{ @intCast(indices.len), 2 }) |v| try out.appendSlice(a, &std.mem.toBytes(std.mem.nativeToLittle(u32, v))); + for (indices) |i| { + for ([_]u32{ i, 400, 400, 144, @intCast(jpeg.len) }) |v| try out.appendSlice(a, &std.mem.toBytes(std.mem.nativeToLittle(u32, v))); + try out.appendSlice(a, jpeg); + } + return out.items; +} + +/// Records, as each page reaches the sink, how many times the render worker had been started. +const Order = struct { + dir: std.Io.Dir, + calls: std.ArrayList(u32) = .empty, + indices: std.ArrayList(u32) = .empty, + widths: std.ArrayList(u32) = .empty, + fn sink(o: *Order) run.PageSink { + return .{ .ctx = o, .page = page }; + } + fn page(ctx: *anyopaque, a: Allocator, p: *const types.OcrPage, rgb: picture.Rgb, _: *budget.Encodes, _: *types.Fault) run.Step!void { + const o: *Order = @ptrCast(@alignCast(ctx)); + const calls: u32 = blk: { // 0 when the count cannot be read, which the test then reports + const text = o.dir.readFileAlloc(t.io, "calls", a, .limited(64)) catch break :blk 0; + break :blk std.fmt.parseInt(u32, std.mem.trim(u8, text, " \n"), 10) catch 0; + }; + try o.calls.append(a, calls); + try o.indices.append(a, p.index); + try o.widths.append(a, @intCast(rgb.width)); + } +}; + +test "ocr run: PDF pages are measured first, and page k renders only after page k-1's sink returned" { + if (comptime builtin.os.tag == .windows) return error.SkipZigTest; // the worker is POSIX only; Windows renders in process + log.init(t.io, false); + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // the parent opens PDFium before it starts a worker; the pages decode through the pinned libjpeg-turbo + if (jpeg_out.loadDynLib(pdf.PdfiumFns, .pdfium, a) == null) return error.SkipZigTest; + const rgb = try a.alloc(u8, 400 * 400 * 3); + @memset(rgb, 0xC0); + const jpeg = jpeg_out.encodeRgb(a, rgb, 400, 400, 85) catch |e| return if (e == error.NoLibrary) error.SkipZigTest else e; + _ = picture.decode(t.io, a, jpeg) catch |e| return switch (e) { + error.NoJpegLibrary, error.JpegLibraryVersion => error.SkipZigTest, + else => e, + }; + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + // call 0 measures both pages (no JPEG bytes); calls 1 and 2 render page 0 and page 1, one page each + try tmp.dir.writeFile(t.io, .{ .sub_path = "reply0.bin", .data = try frame(a, &.{ 0, 1 }, "") }); + try tmp.dir.writeFile(t.io, .{ .sub_path = "reply1.bin", .data = try frame(a, &.{0}, jpeg) }); + try tmp.dir.writeFile(t.io, .{ .sub_path = "reply2.bin", .data = try frame(a, &.{1}, jpeg) }); + try tmp.dir.writeFile(t.io, .{ .sub_path = "worker", .data = script, .flags = .{ .permissions = .fromMode(0o755) } }); + const saved = worker.server_exe; + defer worker.server_exe = saved; + worker.server_exe = try std.fs.path.join(a, &.{ try tmp.dir.realPathFileAlloc(t.io, ".", a), "worker" }); + var h: harness.Harness = .{ .replies = &.{ .{ .text = "text 0 0 10 10\na" }, .{ .text = "text 0 0 10 10\nb" } } }; + try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false, .vision_pdf = true }); + defer h.stop(); + var order: Order = .{ .dir = tmp.dir }; + var fault: types.Fault = undefined; + const doc: types.Source = .{ .bytes = pdf.minimal_two_page_pdf, .kind = .pdf, .sel = .{ .all_within = 16 } }; + run.run(h.srv, a, &.{doc}, order.sink(), &fault, Gone{}) catch |e| { + if (e == error.Faulted) std.debug.print("ocr run: {s}\n", .{fault.message}); + return e; + }; + try t.expectEqualSlices(u32, &.{ 0, 1 }, order.indices.items); + try t.expectEqualSlices(u32, &.{ 400, 400 }, order.widths.items); + // page 0's sink saw the measure and its own render only; page 1 rendered after it returned + try t.expectEqualSlices(u32, &.{ 2, 3 }, order.calls.items); + try t.expectEqual(@as(usize, 2), h.next); +} diff --git a/zig/src/server/ocr/run_test.zig b/zig/src/server/ocr/run_test.zig index 066a76d922a..ba639072ad7 100644 --- a/zig/src/server/ocr/run_test.zig +++ b/zig/src/server/ocr/run_test.zig @@ -55,7 +55,7 @@ const Seen = struct { }; fn imageSource(a: Allocator, w: u32, h: u32) !types.Source { - return .{ .bytes = try harness.png(a, w, h) }; + return .{ .bytes = try harness.png(a, w, h), .kind = .image, .sel = .{ .all_within = 1 } }; } test "ocr run: blocks scale from the frame, quads are validated, and the sink sees the live pixels" { @@ -101,7 +101,7 @@ test "ocr run: a missing frame releases the prepared request and fails as intern try t.expectError(error.Cancelled, run.run(h.srv, a, &.{try imageSource(a, 8, 8)}, seen.sink(), &fault, Gone{ .left = true })); } -test "ocr run: undecodable bytes refuse before any generation" { +test "ocr run: the page budget, undecodable bytes and the gate refuse before any generation" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -110,9 +110,18 @@ test "ocr run: undecodable bytes refuse before any generation" { defer h.stop(); var seen: Seen = .{}; var fault: types.Fault = undefined; - const junk: types.Source = .{ .bytes = "\x89PNG\r\n\x1a\nnope" }; + const one = try imageSource(a, 8, 8); + const many = try a.alloc(types.Source, budget.Pages.init().left + 1); + @memset(many, one); + try t.expectError(error.Faulted, run.run(h.srv, a, many, seen.sink(), &fault, Gone{})); + try t.expectEqual(types.Class.bad_input, fault.class); + try t.expect(std.mem.indexOf(u8, fault.message, "TENSORFOLD_MAX_PDF_PAGES") != null); + const junk: types.Source = .{ .bytes = "\x89PNG\r\n\x1a\nnope", .kind = .image, .sel = .{ .all_within = 1 } }; try t.expectError(error.Faulted, run.run(h.srv, a, &.{junk}, seen.sink(), &fault, Gone{})); try t.expectEqual(types.Class.bad_input, fault.class); + const doc: types.Source = .{ .bytes = "%PDF-1.4\n", .kind = .pdf, .sel = .{ .all_within = 16 } }; + try t.expectError(error.Faulted, run.run(h.srv, a, &.{doc}, seen.sink(), &fault, Gone{})); + try t.expect(std.mem.indexOf(u8, fault.message, "--vision-pdf") != null); try t.expectEqual(@as(usize, 0), h.next); } @@ -191,7 +200,7 @@ test "ocr run: an image whose first header and its pixels disagree is refused be for (orders) |o| { var seen: Seen = .{}; var fault: types.Fault = undefined; - const src: types.Source = .{ .bytes = try twoHeaders(a, o[0], o[1]) }; + const src: types.Source = .{ .bytes = try twoHeaders(a, o[0], o[1]), .kind = .image, .sel = .{ .all_within = 1 } }; try t.expectError(error.Faulted, run.run(h.srv, a, &.{src}, seen.sink(), &fault, Gone{})); try t.expectEqual(types.Class.bad_input, fault.class); try t.expectEqualStrings("page 0: the image's header and its pixels disagree", fault.message); @@ -200,6 +209,35 @@ test "ocr run: an image whose first header and its pixels disagree is refused be try t.expectEqual(@as(usize, 0), h.next); } +/// A client that leaves after ``after`` checks. +const LeavesAfter = struct { + checks: *u32, + after: u32, + pub fn check(g: @This()) bool { + g.checks.* += 1; + return g.checks.* > g.after; + } +}; + +test "ocr run: a client that left renders no PDF and generates no page" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: Harness = .{}; + try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false, .vision_pdf = true }); + defer h.stop(); + var seen: Seen = .{}; + var fault: types.Fault = undefined; + // not a renderable document: a render would refuse it, so Cancelled shows no render was tried + const doc: types.Source = .{ .bytes = "%PDF-1.4\nnot a document", .kind = .pdf, .sel = .{ .all_within = 16 } }; + for ([_]u32{ 0, 1 }) |after| { + var checks: u32 = 0; + try t.expectError(error.Cancelled, run.run(h.srv, a, &.{ try imageSource(a, 8, 8), doc }, seen.sink(), &fault, LeavesAfter{ .checks = &checks, .after = after })); + try t.expectEqual(after + 1, checks); + } + try t.expectEqual(@as(usize, 0), h.next); +} + const page_text = "page_header 0 0 100 5\nRunning head\n;;\n" ++ "title 10 5 90 10\n# Report\n;;\n" ++ diff --git a/zig/src/server/ocr/types.zig b/zig/src/server/ocr/types.zig index f2251a7cdf5..014913802c6 100644 --- a/zig/src/server/ocr/types.zig +++ b/zig/src/server/ocr/types.zig @@ -3,13 +3,14 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const api = @import("engine_api"); const errors = @import("../errors.zig"); +const pdf = @import("../pdf.zig"); /// One page of a request: its index in the source document, the pixel size its quads refer to, and its blocks. pub const OcrPage = struct { index: u32, // 0-based page index in the source document width: u32, height: u32, - dpi: u32, // 72 for an image + dpi: u32, // render DPI of a PDF page; 72 for an image blocks: []api.ocr.OcrBlock, // validated, reading order }; @@ -44,7 +45,9 @@ pub const Fault = struct { } }; -/// One document of a request: a page image. +/// One document of a request: an image or a PDF and the pages chosen from it. pub const Source = struct { bytes: []const u8, + kind: enum { image, pdf }, + sel: pdf.Selection, }; diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 771af549eb1..ce8ea5bbd0d 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -329,6 +329,7 @@ test { _ = @import("ocr/mistral_test.zig"); _ = @import("ocr/mistral_sdk_test.zig"); _ = @import("ocr/run_test.zig"); + _ = @import("ocr/run_pdf_test.zig"); _ = @import("ocr/size_test.zig"); _ = @import("ocr/prompt_ids_test.zig"); _ = @import("ollama_e2e_test.zig"); From 9096e89ddfca56c041d46aef79c448a48c80dda1 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:22:13 +0000 Subject: [PATCH 03/25] docs(ocr): document PDF documents and pages on POST /v1/ocr The API guide described an image-only route. It now gives the PDF render limits and DPI, the measuring before inference with one rendered page in memory at a time, the shared page budget, PDF fetches under --vision-pdf, renderer failures, and the pages field; the changelog line names PDFs and the page budget. --- docs/api.md | 42 ++++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/docs/api.md b/docs/api.md index 69d25a57235..9440442958c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -260,7 +260,7 @@ context-window check still applies. Cohere-style requests retain the reranker's ## OCR -The native HIP engine reads page images through Mistral's OCR contract when it serves a model with an OCR reader +The native HIP engine reads pages through Mistral's OCR contract when it serves a model with an OCR reader and `--vision`. | Route | Contract | Request | Reply | Written for | @@ -296,41 +296,48 @@ The reader writes block text in one Markdown flavour, the one Mistral's page Mar - Images are PNG, JPEG or WebP, one page each, up to the 32 MiB body limit and the reader's decoded-pixel limit: 16 megapixels and 8192 pixels a side for dots.mocr; a larger image is bad input. An image whose header and decoded pixels disagree is refused as bad input. -- PDF documents and `pages` are not read: a PDF document is HTTP 400 "PDF documents are not read on POST /v1/ocr; - send each page as a PNG, JPEG or WebP image", and any non-null `pages` is HTTP 400 "pages selects pages of a PDF - document; POST /v1/ocr reads one page image". -- `https://` URLs (`document_url` and `image_url`) are fetched only with `--vision-urls`: images, at most 32 MiB. - `http://` URLs are refused. +- PDFs need `--vision-pdf`. PDFium renders each selected page at up to 144 DPI, at most 2048 pixels a side and + about 3.6 megapixels; boxes and sizes are in pixels of the rendered page. Mistral reports that DPI (72 for an + image). Every PDF of a request is measured before the first page is read (its page count and each selected + page's size, with no rendering), so a page index out of range, the page budget or a page that does not load fails + before any GPU work. Each page is then rendered just before it is read and freed when it is done, so one rendered + page is in memory at a time; a page that loads but does not render fails the request when it is reached. +- `https://` URLs (`document_url` and `image_url`) are fetched only with `--vision-urls`: images, and PDFs when + `--vision-pdf` is on, at most 32 MiB. `http://` URLs are refused. +- Page budget: images count one page each and PDFs their selected pages; a request reads at most + `TENSORFOLD_MAX_PDF_PAGES` pages (default 16, also the most it may be set to). `--vision-max-images` does not + apply. Over the budget, a request is refused before any inference. - Image budget, for Mistral crops (`include_image_base64`): at most 256 encoded images, 4 times the request's page pixels, and 16 MiB plus 2 MiB a page of encoded bytes. Crossing one fails the whole request as an unreadable page, "too many image regions". The encode needs libjpeg-turbo 3.1.4.1 (`TENSORFOLD_LIBTURBOJPEG` names its file); without it `include_image_base64` is HTTP 400. -The page is read as one user turn (the page image, then the reader's prompt), greedy, with thinking off and -`max_tokens` equal to all the context the prompt leaves. It succeeds only when the reply stops on its end token -and the reader can parse it. +Pages are read one at a time, each as one user turn (the page image, then the reader's prompt), greedy, with +thinking off and `max_tokens` equal to all the context the prompt leaves. A page succeeds only when the reply +stops on its end token and the reader can parse it. ### Failures | Failure | Mistral | | --- | --- | -| Bad input: an undecodable or unsupported file, a page or option the server cannot serve | 400 | +| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | | Unreadable page: the reply was cut at the context limit, repeated without end, broke the model's format or gave a box that is not finite; the image budget was crossed | 422 | | The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | -| Engine fault or out of memory | 500 | +| Engine fault, out of memory, PDF renderer crash or deadline | 500 | | Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | -An unreadable page's message names its index, and the model's raw text goes to the server log, never to the -client. 422 means the same request fails the same way again under greedy decoding; a 503 carries `Retry-After`. -A client that disconnects stops the request before its page is read. +A failed page fails the whole request: no reply returns some pages and drops others. An unreadable page's +message names its index, and the model's raw text goes to the server log, never to the client. 422 means the +same request fails the same way again under greedy decoding; a 503 carries `Retry-After`. A client that disconnects +stops the request before its next page or PDF render. ### Mistral: `POST /v1/ocr` | Field | Meaning | | --- | --- | | `model` | Any string or null. The reply names the requested id when it is the served name or an `--alias`, else the served name, so `--alias mistral-ocr-latest` lets copied examples echo it | -| `document` | `{"type": "document_url", "document_url"}` or `{"type": "image_url", "image_url"}` (a string or `{"url"}`): a `data:` URL, or an `https://` URL as above. The bytes must be a PNG, JPEG or WebP image; a PDF is HTTP 400 (above). `{"type": "file"}` is HTTP 400 | -| `pages` | Any non-null value is HTTP 400 (above): an image has one page | +| `document` | `{"type": "document_url", "document_url"}` or `{"type": "image_url", "image_url"}` (a string or `{"url"}`): a `data:` URL, or an `https://` URL as above. The bytes decide PDF or image. `{"type": "file"}` is HTTP 400 | +| `pages` | 0-based page indices as a list or a string such as `"0,2-4"`; duplicates are merged. An image has only page `0`. At most 1024 entries (a range counts its length) before merging, and the page budget after | | `table_format` | Null: tables stay in the page Markdown as pipe tables (a spanned HTML table becomes a pipe table with the spanned text in its first cell). `"markdown"` or `"html"`: each table becomes a `tables[]` entry (`tbl-N.md` or `tbl-N.html`) and the Markdown links it; under `"markdown"` a table with spanned cells stays HTML, the only form that keeps it | | `extract_header`, `extract_footer` | Move page headers or footers out of `markdown` into `header` and `footer` | | `include_blocks` | Default `true`: one block for each region with a box. `false` leaves `blocks` out | @@ -344,8 +351,7 @@ A client that disconnects stops the request before its page is read. `dimensions` (`dpi`, `height`, `width`) and `blocks`; `hyperlinks` is left out. A block has `type` (`text`, `title`, `list`, `table`, `equation`, `code`, `caption`, `header`, `footer` or `image`), an integer box and `content`, its own Markdown with its tables in the `table_format` form; image blocks add `image_id` and table -blocks `table_id`. `usage_info` gives `pages_processed` and `doc_size_bytes`, the decoded document's size. An -image's `dimensions.dpi` is 72. +blocks `table_id`. `usage_info` gives `pages_processed` and `doc_size_bytes`, the decoded document's size. ## System One on a Clef engine From 1ea013c0d0b49bc71dbb995553cee52199b4515a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:24:46 +0000 Subject: [PATCH 04/25] changelog: #2571 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 375ae6915f8..2a750c63505 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 +- OCR: the native HIP engine reads documents through `POST /v1/ocr` in Mistral's OCR contract (its Python and TypeScript SDKs), with dots.mocr's reader (a box for each layout block). Images and PDFs (`--vision-pdf`) share one page budget per request (`TENSORFOLD_MAX_PDF_PAGES`, default 16), each PDF measured before any inference and each page rendered just before it is read, and Mistral crops share one image budget (256 images, 4 times the page pixels, 16 MiB plus 2 MiB a page). An option that changes content and that TensorFold cannot apply, such as annotations, is refused. A page cut at the context limit or out of its model's format fails the whole request with HTTP 422; `docs/api.md` lists the contract's fields, statuses and limits (#2570, #2571, #2440). Thanks to @laudney. + - Core prompt cache: the radix store can keep a checkpoint inside a page as a writable tail, a store-held copy of that page's rows that is never written again; no family turns tails on yet, so every current store behaves as before (#3329, part of #2444). Thanks to @laudney. - CUDA: on a GB10, the one-launch path for two to four affine-4 prompt projections (`tf_qmm_prefill_many`) works out each thread's copy addresses once, before the K loop, instead of at every stage; the copies, their order and the math are unchanged (#2825). Thanks to @GumbiiDigital. From b84ad640099b19f11f41e2a4bb1c661175cb904f Mon Sep 17 00:00:00 2001 From: gilby Date: Tue, 10 Nov 2026 03:23:29 +0100 Subject: [PATCH 05/25] flashnext hip: a verify window holds eight rows, so a copy lands up to seven tokens a round --- zig/src/families/flashnext/hip/cache.zig | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/zig/src/families/flashnext/hip/cache.zig b/zig/src/families/flashnext/hip/cache.zig index 87177044727..ee1c0167fb0 100644 --- a/zig/src/families/flashnext/hip/cache.zig +++ b/zig/src/families/flashnext/hip/cache.zig @@ -5,8 +5,8 @@ const model = @import("model.zig"); const Dims = model.Dims; -/// Most rows a verified window holds: the pending token and up to three drafts. -pub const max_window = 4; +/// Most rows a verified window holds: the pending token and up to seven drafts (copies use the width; MTP drafts 3). +pub const max_window = 8; /// Where the bytes of one sparse layer's caches start, and their strides. pub const SparseView = struct { k: u64, v: u64, raw: u64, pooled: u64 }; @@ -257,3 +257,16 @@ test "a stream's bytes at tp 4: 12 sparse layers' caches, 36 DeltaNet states and const linear = 3 * 2560 * 4 + 12 * 128 * 128 * 4; try std.testing.expectEqual(@as(usize, 12 * per_layer + 36 * linear + 9 * 10240 * 2), l.bytes()); } + +test "a window's snapshots hold eight rows at tp 4: the pending token and seven copied or drafted ones" { + const config = @import("../config.zig"); + var c = try config.parse(std.testing.allocator, @embedFile("../fixtures/config.json")); + defer c.deinit(); + const d = try Dims.of(&c, 4); + var kinds: [48]bool = undefined; + for (&kinds, 0..) |*k, i| k.* = (try c.kind(i)) == .linear_attention; + const l = Layout.of(d, &kinds, 4096, .f16); + const linear = 3 * 2560 * 4 + 12 * 128 * 128 * 4; + try std.testing.expectEqual(@as(usize, 8 * 36 * linear), l.windowBytes()); + try std.testing.expectEqual(l.tail_bytes + 8 * (l.tail_bytes / l.tail_rows), l.cinBytes()); +} From 9a9975c9c0dfffef861cb20831e653d5dff09b3d Mon Sep 17 00:00:00 2001 From: gilby Date: Tue, 10 Nov 2026 03:44:10 +0100 Subject: [PATCH 06/25] flashnext hip: shared rounds keep three-token copies; a lone stream's copies grow to the window --- zig/src/families/flashnext/hip/lanes.zig | 3 +++ 1 file changed, 3 insertions(+) diff --git a/zig/src/families/flashnext/hip/lanes.zig b/zig/src/families/flashnext/hip/lanes.zig index 8c84d8f2aec..63d3faa1498 100644 --- a/zig/src/families/flashnext/hip/lanes.zig +++ b/zig/src/families/flashnext/hip/lanes.zig @@ -20,6 +20,8 @@ const draw = serve.draw; pub const ring = 1024; /// Drafts the head holds for a stream at most. pub const max_depth = cache.max_window - 1; +/// A shared round's copy window and a lone stream's first: the pending row and three copies; lone runs grow past it. +const shared_copy_rows = 4; pub const Fill = struct { at: usize, @@ -209,6 +211,7 @@ pub const Fx = struct { const drafting = f.e.weights.model.mtp != null and f.drafts > 0; return .{ .exact_width = cache.max_window, + .first_copy_rows = shared_copy_rows, .gpu_tokens = false, .mtp = drafting, .speculate = drafting, From 41ca6218b53080b127d9b9a139473b78b9b43e64 Mon Sep 17 00:00:00 2001 From: gilby Date: Tue, 10 Nov 2026 06:10:04 +0100 Subject: [PATCH 07/25] changelog: the HIP Flash Next eight-row window under Unreleased --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a750c63505..a58a1d66d99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -793,6 +793,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## 1.2.6 - Prompt cache: long conversations survive 8 to 16 agents sending follow-ups at once. Redundant states are evicted before each conversation's newest one, admission never evicts a state a queued request resumes, concurrent keeps reserve their room, and the default budget scales with the room left after streams on Metal and unified-memory CUDA (discrete CUDA hosts keep 8 GiB, Flash Next's batch host 16 GiB). On Qwen3.8-27B with DFlash2 at 16 agents, a follow-up's median first token drops from 546 s to 15.9 s on an M3 Ultra and from 105 s to 25.8 s on a GB10, with every reply unchanged (#2699). +- Qwen3.8-Flash-Next on Strix Halo (gfx1151): a verify window holds eight rows, so a lone stream's copy drafts grow to seven tokens a round while they land, where they stopped at three; rounds shared by several streams keep three-token copies, and MTP drafts stay at three. A lone stream rewriting text it has seen runs about 26% faster; other cells are unchanged, and so are replies. Thanks to @gilby. - Evidence index: reads saved native capabilities, including unknown and XPU chip labels; advertised facts stay unqualified, and invalid supplied input stops with a bounded error (#2708). From 56c78e48cfb284f184b4ca66906dd15077e9c599 Mon Sep 17 00:00:00 2001 From: gilby Date: Tue, 10 Nov 2026 14:00:57 +0100 Subject: [PATCH 08/25] flashnext hip: a host test drives the facts' copy widths through the lane core's setup --- zig/src/families/flashnext/hip/facts.zig | 33 ++++++++++++++++++++++++ zig/src/families/flashnext/hip/lanes.zig | 18 ++----------- 2 files changed, 35 insertions(+), 16 deletions(-) create mode 100644 zig/src/families/flashnext/hip/facts.zig diff --git a/zig/src/families/flashnext/hip/facts.zig b/zig/src/families/flashnext/hip/facts.zig new file mode 100644 index 00000000000..12ab5c1ac47 --- /dev/null +++ b/zig/src/families/flashnext/hip/facts.zig @@ -0,0 +1,33 @@ +//! The lane core's facts of a loaded Flash Next model, pure so a host test drives them without a device. +const std = @import("std"); +const lanes = @import("lanes"); +const cache = @import("cache.zig"); + +/// A shared round's copy window and a lone stream's first: the pending row and three copies; lone runs grow past it. +const shared_copy_rows = 4; + +/// The lane core's facts of a loaded model: `drafting` names a head that drafts, `drafts` its capped chains. +pub fn factsFor(exact_width: u32, streams: usize, drafting: bool, drafts: u32) lanes.Model { + return .{ + .exact_width = exact_width, + .first_copy_rows = shared_copy_rows, + .gpu_tokens = false, + .mtp = drafting, + .speculate = drafting, + .speculate_early = false, + .drafts = drafts, + .hidden_rows = true, + .batch_rows = @intCast(exact_width * streams), + .max_streams = @intCast(streams), + .draft_streams = false, + }; +} + +test "the shared round's copy window: the lane core takes three copies, a lone stream the whole window" { + const a = std.testing.allocator; + var cfg = try lanes.Config.init(a, factsFor(cache.max_window, 2, true, 3), cache.max_window, cache.max_window - 1); + defer cfg.deinit(a); + try std.testing.expectEqual(@as(u32, 3), cfg.first_copy); + try std.testing.expectEqual(@as(u32, 7), cfg.max_copy); + try std.testing.expectEqual(@as(u32, 4), cfg.base_width); +} diff --git a/zig/src/families/flashnext/hip/lanes.zig b/zig/src/families/flashnext/hip/lanes.zig index 63d3faa1498..1c6b425f2f8 100644 --- a/zig/src/families/flashnext/hip/lanes.zig +++ b/zig/src/families/flashnext/hip/lanes.zig @@ -5,6 +5,7 @@ const lanes = @import("lanes"); const serve = @import("hip_serve"); const Engine = @import("engine.zig").Engine; const cache = @import("cache.zig"); +const facts_mod = @import("facts.zig"); const forward = @import("forward.zig"); const head_mod = @import("head.zig"); const draft_batch = @import("draft_batch.zig"); @@ -20,8 +21,6 @@ const draw = serve.draw; pub const ring = 1024; /// Drafts the head holds for a stream at most. pub const max_depth = cache.max_window - 1; -/// A shared round's copy window and a lone stream's first: the pending row and three copies; lone runs grow past it. -const shared_copy_rows = 4; pub const Fill = struct { at: usize, @@ -208,20 +207,7 @@ pub const Fx = struct { } pub fn facts(f: *const Fx) lanes.Model { - const drafting = f.e.weights.model.mtp != null and f.drafts > 0; - return .{ - .exact_width = cache.max_window, - .first_copy_rows = shared_copy_rows, - .gpu_tokens = false, - .mtp = drafting, - .speculate = drafting, - .speculate_early = false, - .drafts = f.drafts, - .hidden_rows = true, - .batch_rows = @intCast(cache.max_window * f.streams), - .max_streams = @intCast(f.streams), - .draft_streams = drafting, - }; + return facts_mod.factsFor(cache.max_window, f.streams, f.e.weights.model.mtp != null and f.drafts > 0, f.drafts); } fn free(f: *Fx, l: *Lane) void { From f8dd5d1ec94846748f908423b513edcf23867c4d Mon Sep 17 00:00:00 2001 From: gilby Date: Tue, 10 Nov 2026 14:00:57 +0100 Subject: [PATCH 09/25] changelog: the eight-row window's line ends with its number and the thanks --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a58a1d66d99..c4c383df8fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -504,6 +504,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## 1.2.8 +- Qwen3.8-Flash-Next on Strix Halo (gfx1151): a verify window holds eight rows, so a lone stream's copy drafts grow to seven tokens a round while they land, where they stopped at three; rounds shared by several streams keep three-token copies, and MTP drafts stay at three. A lone stream rewriting text it has seen runs about 26% faster; other cells are unchanged, and so are replies (#2730). Thanks to @gilby. - GLM-5.3-Flash on CUDA: a tensor-parallel abort reaches the ranks' communicator from the engine's start, once, and a start-up failure after an abort no longer destroys the communicator again; serving and replies are unchanged (#2918, part of #2560). Thanks to @laudney. - Metal: MiniMax-M3, Spark2.5 and Llama take their NaN-aware bf16 argmax from one shared source; the compiled code is unchanged (#2949, part of #2251). Thanks to @jschmied. From ac9591c334b4f9f80cee6d9d9f9defc1bc1ac779 Mon Sep 17 00:00:00 2001 From: gilby Date: Tue, 10 Nov 2026 14:00:57 +0100 Subject: [PATCH 10/25] flashnext hip: the MTP head's three-draft cap is a named constant the facts obey --- zig/src/families/flashnext/hip/lanes.zig | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/zig/src/families/flashnext/hip/lanes.zig b/zig/src/families/flashnext/hip/lanes.zig index 1c6b425f2f8..5e9f8510487 100644 --- a/zig/src/families/flashnext/hip/lanes.zig +++ b/zig/src/families/flashnext/hip/lanes.zig @@ -21,6 +21,14 @@ const draw = serve.draw; pub const ring = 1024; /// Drafts the head holds for a stream at most. pub const max_depth = cache.max_window - 1; +/// MTP drafts the HIP head takes at most: `--mtp-drafts` is refused past it (native/hip.zig's check). +pub const mtp_max_drafts: u32 = 3; + +/// The policy's `--mtp-drafts` capped at the head's. +pub fn capDrafts(asked: u8) u32 { + const n: u32 = @intCast(asked); + return @min(mtp_max_drafts, n); +} pub const Fill = struct { at: usize, @@ -83,7 +91,7 @@ pub const Fx = struct { .streams = streams, .ones = try hip.DeviceBuffer.fromHost(&e.driver, std.mem.sliceAsBytes(host)), .draft_ids = &.{}, - .drafts = @min(max_depth, e.o.policy.mtp.drafts), + .drafts = capDrafts(e.o.policy.mtp.drafts), }; errdefer f.ones.free(); if (e.weights.model.mtp != null) f.draft_ids = try load.draftIds(gpa); @@ -511,3 +519,14 @@ pub const Fx = struct { f.free(kv.value); } }; + +test "MTP stays at three: the constant, the cap and the facts never report more" { + try std.testing.expectEqual(@as(u32, 3), mtp_max_drafts); + try std.testing.expectEqual(@as(u32, 3), capDrafts(3)); + try std.testing.expectEqual(@as(u32, 3), capDrafts(7)); + const m = facts_mod.factsFor(cache.max_window, 2, true, capDrafts(7)); + try std.testing.expectEqual(@as(u32, 3), m.drafts); + var cfg = try lanes.Config.init(std.testing.allocator, m, cache.max_window, cache.max_window - 1); + defer cfg.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(u32, 3), cfg.most_drafts); +} From 18d1478326dde9ec7f690ff6f2320424c5c9638f Mon Sep 17 00:00:00 2001 From: gilby Date: Thu, 12 Nov 2026 08:01:22 +0100 Subject: [PATCH 11/25] native hip: a host test refuses --mtp-drafts 4 by name, so the head's three-draft cap has a test --- zig/src/native/hip.zig | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig index 344a1319f5d..8a3c0fd4755 100644 --- a/zig/src/native/hip.zig +++ b/zig/src/native/hip.zig @@ -537,6 +537,18 @@ test "--drafter is refused before any load, on every rank, until the HIP engine try std.testing.expectError(error.Refused, checkGroup(a, follower, &problem)); } +test "--mtp-drafts past three is refused by name before any load; three and fewer are not" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + var o: api.Open = .{ .dir = "d", .model_type = "qwen4_exp", .mtp_drafts = 3 }; + try checkGroup(a, o, &problem); + o.mtp_drafts = 4; + try std.testing.expectError(error.Refused, checkGroup(a, o, &problem)); + try std.testing.expectEqualStrings("--mtp-drafts 4: the HIP engine drafts at most 3", problem); +} + test "--kv-cache fp8 is refused by name on HIP; bf16 caches are not" { const fp8: api.Open = .{ .dir = "d", .model_type = "qwen3_5", .kv8 = true }; try std.testing.expectEqualStrings(kv8_refusal, cacheRefused(fp8).?); From 8c52ce5141dae3ec3c405a5270b8e5db346fbe02 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:39:34 +0000 Subject: [PATCH 12/25] changelog: #2730's line once, under Unreleased (rebase onto main) --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4c383df8fc..f38bdb3aca8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -794,7 +794,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## 1.2.6 - Prompt cache: long conversations survive 8 to 16 agents sending follow-ups at once. Redundant states are evicted before each conversation's newest one, admission never evicts a state a queued request resumes, concurrent keeps reserve their room, and the default budget scales with the room left after streams on Metal and unified-memory CUDA (discrete CUDA hosts keep 8 GiB, Flash Next's batch host 16 GiB). On Qwen3.8-27B with DFlash2 at 16 agents, a follow-up's median first token drops from 546 s to 15.9 s on an M3 Ultra and from 105 s to 25.8 s on a GB10, with every reply unchanged (#2699). -- Qwen3.8-Flash-Next on Strix Halo (gfx1151): a verify window holds eight rows, so a lone stream's copy drafts grow to seven tokens a round while they land, where they stopped at three; rounds shared by several streams keep three-token copies, and MTP drafts stay at three. A lone stream rewriting text it has seen runs about 26% faster; other cells are unchanged, and so are replies. Thanks to @gilby. - Evidence index: reads saved native capabilities, including unknown and XPU chip labels; advertised facts stay unqualified, and invalid supplied input stops with a bounded error (#2708). From 431f7a43319c8fe5c3281255c855599cf3d3b92f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:41:08 +0000 Subject: [PATCH 13/25] flashnext hip: the MTP draft cap lives in facts.zig, so lanes.zig stays under 600 lines on today's main --- zig/src/families/flashnext/hip/facts.zig | 8 ++++++++ zig/src/families/flashnext/hip/lanes.zig | 19 +++++-------------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/zig/src/families/flashnext/hip/facts.zig b/zig/src/families/flashnext/hip/facts.zig index 12ab5c1ac47..9e7aba30128 100644 --- a/zig/src/families/flashnext/hip/facts.zig +++ b/zig/src/families/flashnext/hip/facts.zig @@ -3,6 +3,14 @@ const std = @import("std"); const lanes = @import("lanes"); const cache = @import("cache.zig"); +/// MTP drafts the HIP head takes at most: `--mtp-drafts` is refused past it (native/hip.zig's check). +pub const mtp_max_drafts: u32 = 3; + +/// The policy's `--mtp-drafts` capped at the head's. +pub fn capDrafts(asked: u8) u32 { + return @min(mtp_max_drafts, @as(u32, asked)); +} + /// A shared round's copy window and a lone stream's first: the pending row and three copies; lone runs grow past it. const shared_copy_rows = 4; diff --git a/zig/src/families/flashnext/hip/lanes.zig b/zig/src/families/flashnext/hip/lanes.zig index 5e9f8510487..8cd05d12829 100644 --- a/zig/src/families/flashnext/hip/lanes.zig +++ b/zig/src/families/flashnext/hip/lanes.zig @@ -21,15 +21,6 @@ const draw = serve.draw; pub const ring = 1024; /// Drafts the head holds for a stream at most. pub const max_depth = cache.max_window - 1; -/// MTP drafts the HIP head takes at most: `--mtp-drafts` is refused past it (native/hip.zig's check). -pub const mtp_max_drafts: u32 = 3; - -/// The policy's `--mtp-drafts` capped at the head's. -pub fn capDrafts(asked: u8) u32 { - const n: u32 = @intCast(asked); - return @min(mtp_max_drafts, n); -} - pub const Fill = struct { at: usize, stops: [16]u32 = undefined, @@ -91,7 +82,7 @@ pub const Fx = struct { .streams = streams, .ones = try hip.DeviceBuffer.fromHost(&e.driver, std.mem.sliceAsBytes(host)), .draft_ids = &.{}, - .drafts = capDrafts(e.o.policy.mtp.drafts), + .drafts = facts_mod.capDrafts(e.o.policy.mtp.drafts), }; errdefer f.ones.free(); if (e.weights.model.mtp != null) f.draft_ids = try load.draftIds(gpa); @@ -521,10 +512,10 @@ pub const Fx = struct { }; test "MTP stays at three: the constant, the cap and the facts never report more" { - try std.testing.expectEqual(@as(u32, 3), mtp_max_drafts); - try std.testing.expectEqual(@as(u32, 3), capDrafts(3)); - try std.testing.expectEqual(@as(u32, 3), capDrafts(7)); - const m = facts_mod.factsFor(cache.max_window, 2, true, capDrafts(7)); + try std.testing.expectEqual(@as(u32, 3), facts_mod.mtp_max_drafts); + try std.testing.expectEqual(@as(u32, 3), facts_mod.capDrafts(3)); + try std.testing.expectEqual(@as(u32, 3), facts_mod.capDrafts(7)); + const m = facts_mod.factsFor(cache.max_window, 2, true, facts_mod.capDrafts(7)); try std.testing.expectEqual(@as(u32, 3), m.drafts); var cfg = try lanes.Config.init(std.testing.allocator, m, cache.max_window, cache.max_window - 1); defer cfg.deinit(std.testing.allocator); From 052577b723f3430825ec93d6e7b2aab70f6746d8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:30:17 +0000 Subject: [PATCH 14/25] flashnext hip: one refusal test for --drafter and --mtp-drafts, so hip.zig stays within 600 lines --- zig/src/native/hip.zig | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig index 8a3c0fd4755..eed8a2d8eec 100644 --- a/zig/src/native/hip.zig +++ b/zig/src/native/hip.zig @@ -522,7 +522,7 @@ test "the group flags: one rank source, a supported world, a master past one ran try std.testing.expectError(error.Refused, checkGroup(a, outside, &problem)); } -test "--drafter is refused before any load, on every rank, until the HIP engine runs DFlash2" { +test "--drafter, and --mtp-drafts past three, are refused before any load, on every rank" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -535,13 +535,7 @@ test "--drafter is refused before any load, on every rank, until the HIP engine follower.rank = 1; follower.master = "node0"; try std.testing.expectError(error.Refused, checkGroup(a, follower, &problem)); -} - -test "--mtp-drafts past three is refused by name before any load; three and fewer are not" { - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - var problem: []const u8 = ""; + // three drafts and fewer are not refused var o: api.Open = .{ .dir = "d", .model_type = "qwen4_exp", .mtp_drafts = 3 }; try checkGroup(a, o, &problem); o.mtp_drafts = 4; From c84f088f27c9b5c8556a7b6bb2cee22192cf1b28 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:46:25 +0000 Subject: [PATCH 15/25] flashnext hip: preserve drafting facts and leave #2730 changelog to landing --- CHANGELOG.md | 1 - zig/src/families/flashnext/hip/facts.zig | 9 ++++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f38bdb3aca8..2a750c63505 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -504,7 +504,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## 1.2.8 -- Qwen3.8-Flash-Next on Strix Halo (gfx1151): a verify window holds eight rows, so a lone stream's copy drafts grow to seven tokens a round while they land, where they stopped at three; rounds shared by several streams keep three-token copies, and MTP drafts stay at three. A lone stream rewriting text it has seen runs about 26% faster; other cells are unchanged, and so are replies (#2730). Thanks to @gilby. - GLM-5.3-Flash on CUDA: a tensor-parallel abort reaches the ranks' communicator from the engine's start, once, and a start-up failure after an abort no longer destroys the communicator again; serving and replies are unchanged (#2918, part of #2560). Thanks to @laudney. - Metal: MiniMax-M3, Spark2.5 and Llama take their NaN-aware bf16 argmax from one shared source; the compiled code is unchanged (#2949, part of #2251). Thanks to @jschmied. diff --git a/zig/src/families/flashnext/hip/facts.zig b/zig/src/families/flashnext/hip/facts.zig index 9e7aba30128..fe82e50eab6 100644 --- a/zig/src/families/flashnext/hip/facts.zig +++ b/zig/src/families/flashnext/hip/facts.zig @@ -27,7 +27,7 @@ pub fn factsFor(exact_width: u32, streams: usize, drafting: bool, drafts: u32) l .hidden_rows = true, .batch_rows = @intCast(exact_width * streams), .max_streams = @intCast(streams), - .draft_streams = false, + .draft_streams = drafting, }; } @@ -39,3 +39,10 @@ test "the shared round's copy window: the lane core takes three copies, a lone s try std.testing.expectEqual(@as(u32, 7), cfg.max_copy); try std.testing.expectEqual(@as(u32, 4), cfg.base_width); } + +test "the extracted facts retain the loaded head drafting mode" { + for ([_]bool{ false, true }) |drafting| { + const facts = factsFor(cache.max_window, 2, drafting, 3); + try std.testing.expectEqual(drafting, facts.draft_streams); + } +} From 52792e9bc843a10fde38937c27c86ca85b0f5232 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:24:48 +0000 Subject: [PATCH 16/25] changelog: #2730 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a750c63505..5688c595b5c 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 +- Flash Next on HIP: the verify window holds eight rows instead of four, so a stream alone in a round can land copy drafts of up to seven tokens a round; rounds shared by several streams keep three-token copies, MTP still drafts at most three, and each stream's window snapshots take more device memory, which admission counts (#2730). Thanks to @gilby. + - OCR: the native HIP engine reads documents through `POST /v1/ocr` in Mistral's OCR contract (its Python and TypeScript SDKs), with dots.mocr's reader (a box for each layout block). Images and PDFs (`--vision-pdf`) share one page budget per request (`TENSORFOLD_MAX_PDF_PAGES`, default 16), each PDF measured before any inference and each page rendered just before it is read, and Mistral crops share one image budget (256 images, 4 times the page pixels, 16 MiB plus 2 MiB a page). An option that changes content and that TensorFold cannot apply, such as annotations, is refused. A page cut at the context limit or out of its model's format fails the whole request with HTTP 422; `docs/api.md` lists the contract's fields, statuses and limits (#2570, #2571, #2440). Thanks to @laudney. - Core prompt cache: the radix store can keep a checkpoint inside a page as a writable tail, a store-held copy of that page's rows that is never written again; no family turns tails on yet, so every current store behaves as before (#3329, part of #2444). Thanks to @laudney. From 1c8c8da94c1d58c4ca1ecbdbd52862536d460542 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:34:19 +0000 Subject: [PATCH 17/25] metal: a Metal 4 backend under the queue, command buffer and encoder calls, for queues made with Device.queue4 A queue from Device.queue4 (macOS 26 and later) takes the same calls as a Metal 3 queue and sends them through an MTL4CommandQueue: a ring of command buffers, each with its own allocator, argument table and constants pages in place of setBytes; a queue barrier at each encoder's start where Metal 3's hazard tracking ordered encoders; barriers that flush to the device's coherence point, and one after each dispatch of a serial encoder; copies and fills on a compute encoder; a shared event for waits; commit feedback for GPU times and failures; and a residency set that follows every buffer bound, releasing a freed buffer once the queue has nothing in flight. Metal 3 queues are unchanged. TF_METAL4_TIMELINE=n stamps every stage of n named rounds on a Metal 4 queue and logs their GPU time by kernel and the longest stages. Pipelines carry their kernel's name as their label. --- docs/environment.md | 1 + zig/src/metal/command.zig | 77 +++- zig/src/metal/device.zig | 15 + zig/src/metal/library.zig | 4 + zig/src/metal/metal.zig | 1 + zig/src/metal/metal4.zig | 541 ++++++++++++++++++++++++++ zig/src/metal/metal4_timeline.zig | 255 ++++++++++++ zig/src/platform/environment.zig | 1 + zig/src/platform/environment_test.zig | 2 + 9 files changed, 891 insertions(+), 6 deletions(-) create mode 100644 zig/src/metal/metal4.zig create mode 100644 zig/src/metal/metal4_timeline.zig diff --git a/docs/environment.md b/docs/environment.md index bf11b83c5f3..608b33c39c4 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -61,6 +61,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_MINIMAX_WORLD` | MiniMax-M3.1-Flash on CUDA: a whole rank count, 2 at CUDA, set with `TF_MINIMAX_RANK`; unset with it gives one rank | | `TF_PROMPT_ROWS` | Native serving: a multiple of 16 from 128 through 2048; unset keeps the chip/family default | | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | +| `TF_METAL4_TIMELINE` | Metal 4: a whole round count, default 0; `n` puts a GPU timestamp at every stage (between barriers) of `n` rounds of each kind a family names, after 8 warm ones, and logs their time by kernel and the longest stages. DeepSeek-V4.1 names its decode rounds by rows. Stamps cost GPU time, so stamped rounds read a little long | | `TF_FLASHNEXT_SCALE_INDEX` | Flash Next on Metal before tensor units: exactly `0` or `1`; default 1, where the 4-bit expert kernels (decode, grouped and prompt gathers) read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values from fewer weight bytes, and the routed experts' stored scales and biases are not kept in memory; `0` keeps and reads the stored arrays; ignored with `--ssd-experts` | | `TF_FLASHNEXT_GROUPED_ROWS` | Flash Next on Metal without tensor units: `0`, or the rows (`1` through `32`) from which a decode window runs its 4-bit experts grouped by expert, with the same output bits; default 5; ignored with `--ssd-experts` and in speed-up mode | | `TF_QWEN27_SLOT_RESUME` | Qwen3.8-27B on Metal: exactly `0` or `1`; `0` stops slot 0 resuming a later prompt; unset or blank keeps it on | diff --git a/zig/src/metal/command.zig b/zig/src/metal/command.zig index 769e0995674..0587d5bc1a2 100644 --- a/zig/src/metal/command.zig +++ b/zig/src/metal/command.zig @@ -1,4 +1,4 @@ -//! Command queues, command buffers and compute encoders (serial or concurrent dispatch). +//! Command queues, command buffers and compute encoders (serial or concurrent), on Metal 3 or Metal 4 (metal4.zig). const std = @import("std"); const objc = @import("objc.zig"); const types = @import("types.zig"); @@ -8,12 +8,14 @@ const SharedEvent = @import("sync.zig").SharedEvent; const Event = @import("sync.zig").Event; const IndirectCommandBuffer = @import("icb.zig").IndirectCommandBuffer; const ResidencySet = @import("residency.zig").ResidencySet; +const metal4 = @import("metal4.zig"); const Id = objc.Id; const Size = types.Size; pub const Queue = struct { id: Id, + m4: ?*metal4.State = null, pub fn deviceId(self: Queue) Id { return objc.msg(Id, self.id, "device", .{}); @@ -21,11 +23,13 @@ pub const Queue = struct { /// A command buffer that retains what it references (autoreleased: keep a pool around it). pub fn commandBuffer(self: Queue) CommandBuffer { + if (self.m4) |q| return CommandBuffer.of(q.acquire()); return .{ .id = objc.msg(Id, self.id, "commandBuffer", .{}) }; } /// A command buffer that does not retain its resources: the caller keeps them alive until it completes. pub fn commandBufferUnretained(self: Queue) CommandBuffer { + if (self.m4) |q| return CommandBuffer.of(q.acquire()); return .{ .id = objc.msg(Id, self.id, "commandBufferWithUnretainedReferences", .{}) }; } @@ -39,38 +43,66 @@ pub const Queue = struct { } pub fn deinit(self: Queue) void { + if (self.m4) |q| return q.close(); objc.release(self.id); } + + pub fn isMetal4(self: Queue) bool { + return self.m4 != null; + } + + /// Names a round of work for the Metal 4 timeline (TF_METAL4_TIMELINE); nothing on Metal 3. + pub fn roundBegin(self: Queue, name: []const u8) void { + if (self.m4) |q| q.roundBegin(name); + } + + /// After the round's last wait. + pub fn roundEnd(self: Queue) void { + if (self.m4) |q| q.roundEnd(); + } }; pub const CommandBuffer = struct { id: Id, + m4: ?*metal4.Slot = null, + /// the slot's use this handle names + use: u32 = 0, + + fn of(s: *metal4.Slot) CommandBuffer { + return .{ .id = s.cb, .m4 = s, .use = s.use }; + } pub fn compute(self: CommandBuffer, dispatch: types.DispatchType) ComputeEncoder { + if (self.m4) |s| return .{ .id = s.compute(dispatch == .serial), .m4 = s }; return .{ .id = objc.msg(Id, self.id, "computeCommandEncoderWithDispatchType:", .{@backingInt(dispatch)}) }; } /// A blit encoder on this buffer, for copies between buffers on the GPU. pub fn blit(self: CommandBuffer) BlitEncoder { + if (self.m4) |s| return .{ .id = s.blitEncoder(), .m4 = s }; return .{ .id = objc.msg(Id, self.id, "blitCommandEncoder", .{}) }; } /// The GPU waits here until `event` reaches `value`. pub fn waitFor(self: CommandBuffer, event: SharedEvent, value: u64) void { + if (self.m4) |s| return s.waitEvent(event.id, value); objc.msg(void, self.id, "encodeWaitForEvent:value:", .{ event.id, value }); } /// The GPU sets `event` to `value` once the work before this point completes. pub fn signal(self: CommandBuffer, event: SharedEvent, value: u64) void { + if (self.m4) |s| return s.signalEvent(event.id, value); objc.msg(void, self.id, "encodeSignalEvent:value:", .{ event.id, value }); } /// waitFor and signal with a GPU-only event. pub fn waitForEvent(self: CommandBuffer, event: Event, value: u64) void { + if (self.m4) |s| return s.waitEvent(event.id, value); objc.msg(void, self.id, "encodeWaitForEvent:value:", .{ event.id, value }); } pub fn signalEvent(self: CommandBuffer, event: Event, value: u64) void { + if (self.m4) |s| return s.signalEvent(event.id, value); objc.msg(void, self.id, "encodeSignalEvent:value:", .{ event.id, value }); } @@ -80,22 +112,25 @@ pub const CommandBuffer = struct { pub fn commit(self: CommandBuffer) void { @import("pass_metrics.zig").commit(); + if (self.m4) |s| return s.commit(); objc.msg(void, self.id, "commit", .{}); } pub fn wait(self: CommandBuffer) void { const metrics = @import("pass_metrics.zig"); const start = metrics.time(); - objc.msg(void, self.id, "waitUntilCompleted", .{}); + if (self.m4) |s| s.wait(self.use) else objc.msg(void, self.id, "waitUntilCompleted", .{}); if (start != 0) metrics.wait(start, self.gpuSeconds()); } pub fn status(self: CommandBuffer) types.CommandBufferStatus { + if (self.m4) |s| return s.status(self.use); return @fromBackingInt(@intCast(objc.msg(usize, self.id, "status", .{}))); } - /// The error text when the command buffer failed, else null. + /// The error text when the command buffer failed, else null; on Metal 4, any failure on its queue not yet reported. pub fn failure(self: CommandBuffer) ?[*:0]const u8 { + if (self.m4) |s| return s.failure(self.use); if (self.status() != .@"error") return null; return objc.errorText(objc.msg(?Id, self.id, "error", .{})); } @@ -106,31 +141,44 @@ pub const CommandBuffer = struct { } pub fn gpuStart(self: CommandBuffer) f64 { + if (self.m4) |s| return if (s.times(self.use, true)) |t| t[0] else 0; return objc.msg(f64, self.id, "GPUStartTime", .{}); } pub fn gpuEnd(self: CommandBuffer) f64 { + if (self.m4) |s| return if (s.times(self.use, true)) |t| t[1] else 0; return objc.msg(f64, self.id, "GPUEndTime", .{}); } + /// The GPU's start and end once reported, without waiting for the report (Metal 4), else null. + pub fn gpuTimes(self: CommandBuffer) ?[2]f64 { + if (self.m4) |s| return s.times(self.use, false); + return .{ self.gpuStart(), self.gpuEnd() }; + } + + /// Metal 4's command buffers belong to their queue's slots: retain and release do nothing there. pub fn retain(self: CommandBuffer) CommandBuffer { + if (self.m4 != null) return self; return .{ .id = objc.retain(self.id) }; } pub fn release(self: CommandBuffer) void { - objc.release(self.id); + if (self.m4 == null) objc.release(self.id); } }; /// Copies between buffers on the GPU. pub const BlitEncoder = struct { id: Id, + m4: ?*metal4.Slot = null, pub fn copy(self: BlitEncoder, from: Buffer, from_offset: usize, to: Buffer, to_offset: usize, size: usize) void { + if (self.m4) |s| return s.copy(self.id, from.id, from_offset, to.id, to_offset, size); objc.msg(void, self.id, "copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:", .{ from.id, from_offset, to.id, to_offset, size }); } pub fn fill(self: BlitEncoder, buffer: Buffer, offset: usize, size: usize, value: u8) void { + if (self.m4) |s| return s.fill(self.id, buffer.id, offset, size, value); objc.msg(void, self.id, "fillBuffer:range:value:", .{ buffer.id, types.Range{ .location = offset, .length = size }, value }); } @@ -141,21 +189,26 @@ pub const BlitEncoder = struct { pub const ComputeEncoder = struct { id: Id, + m4: ?*metal4.Slot = null, pub fn deviceId(self: ComputeEncoder) Id { + if (self.m4) |s| return s.q.device; return objc.msg(Id, self.id, "device", .{}); } pub fn setPipeline(self: ComputeEncoder, pipeline: Pipeline) void { objc.msg(void, self.id, "setComputePipelineState:", .{pipeline.id}); + if (self.m4) |s| s.pipeline(pipeline.id); } pub fn setBuffer(self: ComputeEncoder, buffer: Buffer, offset: usize, index: usize) void { + if (self.m4) |s| return s.bind(buffer.id, offset, index); objc.msg(void, self.id, "setBuffer:offset:atIndex:", .{ buffer.id, offset, index }); } - /// Small constants copied into the command stream (at most 4 KB). + /// Small constants copied into the command stream (at most 4 KB); on Metal 4 into the slot's constants pages. pub fn setBytes(self: ComputeEncoder, bytes: []const u8, index: usize) void { + if (self.m4) |s| return s.bytes(bytes, index); objc.msg(void, self.id, "setBytes:length:atIndex:", .{ bytes.ptr, bytes.len, index }); } @@ -170,43 +223,55 @@ pub const ComputeEncoder = struct { /// Whole threadgroups: `groups` of `threads` each. pub fn dispatchGroups(self: ComputeEncoder, groups: Size, threads: Size) void { objc.msg(void, self.id, "dispatchThreadgroups:threadsPerThreadgroup:", .{ groups, threads }); + if (self.m4) |s| s.dispatched(self.id); } /// Whole threadgroups of `threads` each, their counts (3 u32) read from `args` at `offset` when the dispatch runs. pub fn dispatchIndirect(self: ComputeEncoder, args: Buffer, offset: usize, threads: Size) void { + if (self.m4) |s| return s.dispatchIndirect(self.id, args.id, offset, threads); objc.msg(void, self.id, "dispatchThreadgroupsWithIndirectBuffer:indirectBufferOffset:threadsPerThreadgroup:", .{ args.id, offset, threads }); } /// A grid of `grid` threads in groups of `threads` (edge groups may be partial), as MLX dispatches. pub fn dispatchThreads(self: ComputeEncoder, grid: Size, threads: Size) void { objc.msg(void, self.id, "dispatchThreads:threadsPerThreadgroup:", .{ grid, threads }); + if (self.m4) |s| s.dispatched(self.id); } /// Later dispatches see every buffer write before this point (concurrent encoders). pub fn barrier(self: ComputeEncoder) void { + if (self.m4) |s| return s.barrier(self.id); objc.msg(void, self.id, "memoryBarrierWithScope:", .{types.BarrierScope.buffers}); } - /// Declare a resource used through indirect commands or argument buffers. + /// Declare a resource used through indirect commands or argument buffers (on Metal 4: it joins the residency set). pub fn useResource(self: ComputeEncoder, buffer: Buffer, usage: usize) void { + if (self.m4) |s| { + _ = s.q.address(buffer.id); + return; + } objc.msg(void, self.id, "useResource:usage:", .{ buffer.id, usage }); } pub fn execute(self: ComputeEncoder, icb: IndirectCommandBuffer, first: usize, count: usize) void { objc.msg(void, self.id, "executeCommandsInBuffer:withRange:", .{ icb.id, types.Range{ .location = first, .length = count } }); + if (self.m4) |s| s.dispatched(self.id); } pub fn end(self: ComputeEncoder) void { + if (self.m4) |s| s.ending(self.id); objc.msg(void, self.id, "endEncoding", .{}); } /// The command buffer this encoder was opened from, for the event ops a seam encodes BETWEEN encoders. pub fn commandBuffer(self: ComputeEncoder) CommandBuffer { + if (self.m4) |s| return CommandBuffer.of(s); return .{ .id = objc.msg(Id, self.id, "commandBuffer", .{}) }; } /// Whether this encoder dispatches serially or concurrently: a seam reopens it in the same mode. pub fn dispatchType(self: ComputeEncoder) types.DispatchType { + if (self.m4) |s| return if (s.serial) .serial else .concurrent; return @fromBackingInt(@intCast(objc.msg(usize, self.id, "dispatchType", .{}))); } }; diff --git a/zig/src/metal/device.zig b/zig/src/metal/device.zig index 769a1b7e994..0a54054999f 100644 --- a/zig/src/metal/device.zig +++ b/zig/src/metal/device.zig @@ -6,6 +6,7 @@ const types = @import("types.zig"); const command = @import("command.zig"); const sync = @import("sync.zig"); const residency = @import("residency.zig"); +const metal4 = @import("metal4.zig"); const Id = objc.Id; @@ -38,6 +39,7 @@ pub const Buffer = struct { } pub fn deinit(self: Buffer) void { + metal4.forget(self.id); objc.release(self.id); } }; @@ -91,6 +93,19 @@ pub const Device = struct { return .{ .id = objc.msg(?Id, self.id, "newCommandQueue", .{}) orelse return error.NoQueue }; } + /// Whether this Mac has Metal 4's command queues (macOS 26 and later). + pub fn hasMetal4(self: Device) bool { + return self.responds("newMTL4CommandQueue"); + } + + /// A queue taking `queue`'s calls through Metal 4, or error.Unsupported; TF_METAL4_TIMELINE=n stamps n rounds. + pub fn queue4(self: Device) Error!command.Queue { + if (!self.hasMetal4()) return error.Unsupported; + const rounds = platform.environment.read(u32, "TF_METAL4_TIMELINE", 0) catch 0; + const q = metal4.State.open(self.id, rounds) orelse return error.Unsupported; + return .{ .id = q.queue, .m4 = q }; + } + /// A new buffer of `len` bytes; `options` from types.ResourceOptions (shared storage by default). pub fn buffer(self: Device, len: usize, options: usize) Error!Buffer { @import("pass_metrics.zig").buffer(); diff --git a/zig/src/metal/library.zig b/zig/src/metal/library.zig index c8ecd55e6b3..08ee88271ea 100644 --- a/zig/src/metal/library.zig +++ b/zig/src/metal/library.zig @@ -117,6 +117,10 @@ pub const Pipeline = struct { defer objc.release(desc); objc.msg(void, desc, "setComputeFunction:", .{func}); objc.msg(void, desc, "setSupportIndirectCommandBuffers:", .{indirect}); + // the kernel's name on the pipeline, for GPU captures and the Metal 4 timeline + const label = objc.string(name); + defer objc.release(label); + objc.msg(void, desc, "setLabel:", .{label}); const id = objc.msg(?Id, device.id, "newComputePipelineStateWithDescriptor:options:reflection:error:", .{ desc, @as(usize, 0), @as(?*anyopaque, null), &err }); return .{ .id = id orelse { if (optional) std.log.info("pipeline {s}: {s}", .{ name, objc.errorText(err) }) else std.log.err("pipeline {s}: {s}", .{ name, objc.errorText(err) }); diff --git a/zig/src/metal/metal.zig b/zig/src/metal/metal.zig index e1da53b0a32..33a49b696d2 100644 --- a/zig/src/metal/metal.zig +++ b/zig/src/metal/metal.zig @@ -30,6 +30,7 @@ pub const clock = @import("clock.zig"); pub const pass_metrics = @import("pass_metrics.zig"); pub const counters = @import("counters.zig"); pub const ane = @import("ane.zig"); +pub const metal4 = @import("metal4.zig"); test { std.testing.refAllDecls(@This()); diff --git a/zig/src/metal/metal4.zig b/zig/src/metal/metal4.zig new file mode 100644 index 00000000000..35d107893a7 --- /dev/null +++ b/zig/src/metal/metal4.zig @@ -0,0 +1,541 @@ +//! Metal 4 under command.zig's calls: slots of command buffers, argument tables, constants pages, barriers, an event. +const std = @import("std"); +const sys = @import("sys"); +const objc = @import("objc.zig"); +const types = @import("types.zig"); +const Timeline = @import("metal4_timeline.zig").Timeline; + +const Id = objc.Id; +const heap = std.heap.c_allocator; + +pub const stage_dispatch: usize = 1 << 27; +pub const stage_blit: usize = 1 << 28; +const queue_stages = stage_dispatch | stage_blit; +const flush_device: usize = 1; + +/// Command buffers a queue keeps; a slot is begun again once its last commit has completed. +pub const ring = 64; +const page_bytes: usize = 256 << 10; +const max_pages = 32; +const max_events = 4; +/// Feedback kept a slot, by commit: a reader is never more than one commit behind. +const history = 4; + +/// The Objective-C block ABI for the commit feedback handler: a global block, so nothing copies or frees it. +const BlockDescriptor = extern struct { reserved: c_ulong, size: c_ulong, signature: [*:0]const u8 }; +const Block = extern struct { + isa: *const anyopaque, + flags: c_int, + reserved: c_int, + invoke: *const fn (*const Block, Id) callconv(.c) void, + descriptor: *const BlockDescriptor, + slot: *Slot, +}; +extern const _NSConcreteGlobalBlock: anyopaque; +const block_global: c_int = 1 << 28; +const block_signature: c_int = 1 << 30; +const descriptor: BlockDescriptor = .{ .reserved = 0, .size = @sizeOf(Block), .signature = "v16@?0@8" }; + +const Page = struct { buf: Id, ptr: [*]u8, addr: u64 }; +const Event = struct { id: Id, value: u64 }; + +pub const Slot = struct { + q: *State, + cb: Id, + allocator: Id, + table: Id, + block: Block, + /// how many times the slot was begun: a handle from an earlier use finds its work done + use: u32 = 0, + commits: u32 = 0, + /// the event value this use's commit signals; 0 before it commits + value: u64 = 0, + open: bool = false, + serial: bool = false, + blit: bool = false, + dirty: bool = false, + pages: [max_pages]?Page = @splat(null), + page: usize = 0, + bump: usize = 0, + waits: [max_events]Event = undefined, + nwaits: usize = 0, + signals: [max_events]Event = undefined, + nsignals: usize = 0, + /// commit feedbacks received; the newest ones' GPU span and whether they failed + seen: std.atomic.Value(u32) = .init(0), + start: [history]f64 = @splat(0), + end: [history]f64 = @splat(0), + bad: [history]bool = @splat(false), + + /// A compute encoder on this slot's command buffer, after every earlier command of the queue. + pub fn compute(s: *Slot, serial: bool) Id { + const e = objc.msg(Id, s.cb, "computeCommandEncoder", .{}); + objc.msg(void, e, "setArgumentTable:", .{s.table}); + objc.msg(void, e, "barrierAfterQueueStages:beforeStages:visibilityOptions:", .{ queue_stages, queue_stages, flush_device }); + s.serial = serial; + s.blit = false; + s.dirty = false; + if (s.q.timeline) |t| t.started(e); + return e; + } + + /// Copies and fills, in order: Metal 4 encodes them on a compute encoder. + pub fn blitEncoder(s: *Slot) Id { + const e = s.compute(true); + s.blit = true; + return e; + } + + pub fn bind(s: *Slot, buffer: Id, offset: usize, index: usize) void { + objc.msg(void, s.table, "setAddress:atIndex:", .{ s.q.address(buffer) + offset, index }); + } + + /// Constants copied into this use's pages, read by address. + pub fn bytes(s: *Slot, data: []const u8, index: usize) void { + const len = std.mem.alignForward(usize, @max(data.len, 1), 64); + if (len > page_bytes) std.debug.panic("metal 4: {d} bytes of constants in one call", .{data.len}); + if (s.bump + len > page_bytes) { + s.page += 1; + s.bump = 0; + } + const p = s.pageAt(s.page); + @memcpy(p.ptr[s.bump..][0..data.len], data); + objc.msg(void, s.table, "setAddress:atIndex:", .{ p.addr + s.bump, index }); + s.bump += len; + } + + fn pageAt(s: *Slot, i: usize) Page { + if (i >= max_pages) std.debug.panic("metal 4: more than {d} KiB of constants in one command buffer", .{max_pages * page_bytes >> 10}); + if (s.pages[i]) |p| return p; + const buf = objc.msg(?Id, s.q.device, "newBufferWithLength:options:", .{ page_bytes, types.ResourceOptions.shared }) orelse + std.debug.panic("metal 4: no buffer for constants", .{}); + const p: Page = .{ .buf = buf, .ptr = objc.msg([*]u8, buf, "contents", .{}), .addr = s.q.address(buf) }; + s.pages[i] = p; + return p; + } + + pub fn pipeline(s: *Slot, id: Id) void { + if (s.q.timeline) |t| t.piped(id); + } + + pub fn dispatched(s: *Slot, e: Id) void { + s.dirty = true; + if (s.q.timeline) |t| t.dispatched(); + if (s.serial) s.barrier(e); + } + + pub fn dispatchIndirect(s: *Slot, e: Id, args: Id, offset: usize, threads: types.Size) void { + objc.msg(void, e, "dispatchThreadgroupsWithIndirectBuffer:threadsPerThreadgroup:", .{ s.q.address(args) + offset, threads }); + s.dispatched(e); + } + + /// Later commands of this encoder see every write before it; with nothing since the last one it does nothing. + pub fn barrier(s: *Slot, e: Id) void { + if (!s.dirty) return; + s.dirty = false; + const st = if (s.blit) stage_blit else stage_dispatch; + objc.msg(void, e, "barrierAfterEncoderStages:beforeEncoderStages:visibilityOptions:", .{ st, st, flush_device }); + if (s.q.timeline) |t| t.stage(e); + } + + pub fn copy(s: *Slot, e: Id, from: Id, from_offset: usize, to: Id, to_offset: usize, size: usize) void { + _ = s.q.address(from); + _ = s.q.address(to); + objc.msg(void, e, "copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:", .{ from, from_offset, to, to_offset, size }); + s.dispatched(e); + } + + pub fn fill(s: *Slot, e: Id, buffer: Id, offset: usize, size: usize, value: u8) void { + _ = s.q.address(buffer); + objc.msg(void, e, "fillBuffer:range:value:", .{ buffer, types.Range{ .location = offset, .length = size }, value }); + s.dispatched(e); + } + + pub fn ending(s: *Slot, e: Id) void { + if (s.q.timeline) |t| if (s.dirty) t.ended(e); + } + + /// Event waits and signals at the command buffer's edges: Metal 4 puts them on the queue, around the commit. + pub fn waitEvent(s: *Slot, event: Id, value: u64) void { + if (s.nwaits == max_events) std.debug.panic("metal 4: more than {d} event waits in one command buffer", .{max_events}); + s.waits[s.nwaits] = .{ .id = event, .value = value }; + s.nwaits += 1; + } + + pub fn signalEvent(s: *Slot, event: Id, value: u64) void { + if (s.nsignals == max_events) std.debug.panic("metal 4: more than {d} event signals in one command buffer", .{max_events}); + s.signals[s.nsignals] = .{ .id = event, .value = value }; + s.nsignals += 1; + } + + pub fn commit(s: *Slot) void { + s.q.commit(s); + } + + /// Blocks until use `use` of this slot completed (at once for a later use's handle or one never committed). + pub fn wait(s: *Slot, use: u32) void { + if (use != s.use or s.value == 0) return; + s.q.reach(s.value); + s.q.drain(); + } + + /// The GPU's start and end of use `use`, in host seconds; null when gone or, unless `block`, not yet reported. + pub fn times(s: *Slot, use: u32, block: bool) ?[2]f64 { + if (use != s.use or s.value == 0) return null; + const k = s.commits; + var tries: u32 = 0; + while (s.seen.load(.acquire) < k) : (tries += 1) { + if (!block or tries == 100_000) return null; + nap(10_000); + } + const i = (k - 1) % history; + return .{ s.start[i], s.end[i] }; + } + + /// The text of a failure the queue has not reported yet: Metal 4 reports failures apart from command buffers. + pub fn failure(s: *Slot, use: u32) ?[*:0]const u8 { + _ = use; + const q = s.q; + if (q.failures.load(.acquire) == q.reported) return null; + q.reported = q.failures.load(.acquire); + return @ptrCast(&q.failure_text); + } + + pub fn status(s: *Slot, use: u32) types.CommandBufferStatus { + if (use != s.use) return .completed; + if (s.value == 0) return if (s.open) .not_enqueued else .completed; + if (objc.msg(u64, s.q.event, "signaledValue", .{}) < s.value) return .committed; + const k = s.commits; + if (s.seen.load(.acquire) >= k and s.bad[(k - 1) % history]) return .@"error"; + return .completed; + } + + fn feedback(b: *const Block, fb: Id) callconv(.c) void { + const s = b.slot; + const n = s.seen.load(.monotonic); + const i = n % history; + s.start[i] = objc.msg(f64, fb, "GPUStartTime", .{}); + s.end[i] = objc.msg(f64, fb, "GPUEndTime", .{}); + const err = objc.msg(?Id, fb, "error", .{}); + s.bad[i] = err != null; + if (err) |e| s.q.fail(e); + s.seen.store(n + 1, .release); + } +}; + +/// Buffers bound so far and their GPU addresses: open addressing, read without the lock and written under it. +const Table = struct { + keys: []std.atomic.Value(usize), + addrs: []u64, + used: usize = 0, + + const tomb: usize = 1; + + fn init(n: usize) *Table { + const t = heap.create(Table) catch @panic("metal 4: out of memory"); + t.* = .{ .keys = heap.alloc(std.atomic.Value(usize), n) catch @panic("metal 4: out of memory"), .addrs = heap.alloc(u64, n) catch @panic("metal 4: out of memory") }; + for (t.keys) |*k| k.* = .init(0); + return t; + } + + fn deinit(t: *Table) void { + heap.free(t.keys); + heap.free(t.addrs); + heap.destroy(t); + } + + fn home(t: *const Table, k: usize) usize { + return @as(usize, @truncate(((k >> 4) *% 0x9E3779B97F4A7C15) >> 24)) & (t.keys.len - 1); + } + + fn find(t: *const Table, k: usize) ?usize { + var i = t.home(k); + while (true) : (i = (i + 1) & (t.keys.len - 1)) { + const key = t.keys[i].load(.acquire); + if (key == k) return i; + if (key == 0) return null; + } + } + + /// Under the lock, a key that is not there: its address first, so a reader that sees the key sees the address. + fn put(t: *Table, k: usize, addr: u64) void { + var i = t.home(k); + while (true) : (i = (i + 1) & (t.keys.len - 1)) { + const key = t.keys[i].load(.monotonic); + if (key != 0 and key != tomb) continue; + if (key == 0) t.used += 1; + t.addrs[i] = addr; + t.keys[i].store(k, .release); + return; + } + } +}; + +/// Queues whose buffers Buffer.deinit must hand back. +var registry: [8]std.atomic.Value(?*State) = @splat(.init(null)); +var registered: std.atomic.Value(u32) = .init(0); + +/// A buffer's owner let it go: queues that bound it release it from their sets once their work in flight is done. +pub fn forget(buffer: Id) void { + if (registered.load(.acquire) == 0) return; + for (®istry) |*r| if (r.load(.acquire)) |q| q.drop(buffer); +} + +fn nap(ns: u64) void { + const t: std.c.timespec = .{ .sec = 0, .nsec = @intCast(ns) }; + _ = sys.c.nanosleep(&t, null); +} + +pub const State = struct { + device: Id, + queue: Id, + event: Id, + set: Id, + lock_word: std.c.os_unfair_lock = .{}, + tick: u64 = 0, + next: usize = 0, + /// slots begun and not yet committed + unsent: usize = 0, + table: std.atomic.Value(*Table), + retired: std.ArrayList(*Table) = .empty, + /// buffers whose owners freed them: still in the set until the queue has nothing in flight + dropped: std.ArrayList(Id) = .empty, + set_dirty: bool = false, + set_grew: bool = false, + failures: std.atomic.Value(u32) = .init(0), + reported: u32 = 0, + failure_text: [256]u8 = @splat(0), + timeline: ?*Timeline = null, + slots: [ring]Slot = undefined, + + /// A Metal 4 queue on `device` with its slots and its residency set, or null where Metal 4 is missing. + pub fn open(device: Id, timeline_rounds: u32) ?*State { + const queue = objc.msg(?Id, device, "newMTL4CommandQueue", .{}) orelse return null; + const q = heap.create(State) catch @panic("metal 4: out of memory"); + q.* = .{ + .device = device, + .queue = queue, + .event = objc.msg(?Id, device, "newSharedEvent", .{}) orelse @panic("metal 4: no shared event"), + .set = newSet(device), + .table = .init(Table.init(4096)), + }; + const td = objc.msg(Id, objc.msg(Id, objc.class("MTL4ArgumentTableDescriptor"), "alloc", .{}), "init", .{}); + defer objc.release(td); + objc.msg(void, td, "setMaxBufferBindCount:", .{@as(usize, 31)}); + for (&q.slots) |*s| { + var err: ?Id = null; + s.* = .{ + .q = q, + .cb = objc.msg(?Id, device, "newCommandBuffer", .{}) orelse @panic("metal 4: no command buffer"), + .allocator = objc.msg(?Id, device, "newCommandAllocator", .{}) orelse @panic("metal 4: no command allocator"), + .table = objc.msg(?Id, device, "newArgumentTableWithDescriptor:error:", .{ td, &err }) orelse @panic("metal 4: no argument table"), + .block = .{ .isa = &_NSConcreteGlobalBlock, .flags = block_global | block_signature, .reserved = 0, .invoke = Slot.feedback, .descriptor = &descriptor, .slot = s }, + }; + } + objc.msg(void, queue, "addResidencySet:", .{q.set}); + if (timeline_rounds > 0) q.timeline = Timeline.init(device, timeline_rounds); + for (®istry) |*r| if (r.cmpxchgStrong(null, q, .acq_rel, .acquire) == null) { + _ = registered.fetchAdd(1, .acq_rel); + break; + }; + return q; + } + + fn newSet(device: Id) Id { + const d = objc.msg(Id, objc.msg(Id, objc.class("MTLResidencySetDescriptor"), "alloc", .{}), "init", .{}); + defer objc.release(d); + objc.msg(void, d, "setInitialCapacity:", .{@as(usize, 1024)}); + var err: ?Id = null; + return objc.msg(?Id, device, "newResidencySetWithDescriptor:error:", .{ d, &err }) orelse @panic("metal 4: no residency set"); + } + + fn lock(q: *State) void { + std.c.os_unfair_lock_lock(&q.lock_word); + } + + fn unlock(q: *State) void { + std.c.os_unfair_lock_unlock(&q.lock_word); + } + + /// The next slot, begun: its previous use has completed (it is waited for if not) and its allocator is reset. + pub fn acquire(q: *State) *Slot { + q.lock(); + defer q.unlock(); + const s = &q.slots[q.next]; + q.next = (q.next + 1) % ring; + if (s.open) { + objc.msg(void, s.cb, "endCommandBuffer", .{}); + s.open = false; + q.unsent -= 1; + } + if (s.value > 0) q.reach(s.value); + objc.msg(void, s.allocator, "reset", .{}); + objc.msg(void, s.cb, "beginCommandBufferWithAllocator:", .{s.allocator}); + s.use +%= 1; + s.value = 0; + s.page = 0; + s.bump = 0; + s.nwaits = 0; + s.nsignals = 0; + s.open = true; + q.unsent += 1; + return s; + } + + fn commit(q: *State, s: *Slot) void { + objc.msg(void, s.cb, "endCommandBuffer", .{}); + const options = objc.msg(Id, objc.msg(Id, objc.class("MTL4CommitOptions"), "alloc", .{}), "init", .{}); + defer objc.release(options); + objc.msg(void, options, "addFeedbackHandler:", .{&s.block}); + q.lock(); + defer q.unlock(); + if (q.set_dirty) { + objc.msg(void, q.set, "commit", .{}); + if (q.set_grew) objc.msg(void, q.set, "requestResidency", .{}); + q.set_dirty = false; + q.set_grew = false; + } + for (s.waits[0..s.nwaits]) |w| objc.msg(void, q.queue, "waitForEvent:value:", .{ w.id, w.value }); + const list = [1]Id{s.cb}; + objc.msg(void, q.queue, "commit:count:options:", .{ @as([*]const Id, &list), @as(usize, 1), options }); + q.tick += 1; + s.value = q.tick; + s.commits += 1; + s.open = false; + q.unsent -= 1; + objc.msg(void, q.queue, "signalEvent:value:", .{ q.event, q.tick }); + for (s.signals[0..s.nsignals]) |g| objc.msg(void, q.queue, "signalEvent:value:", .{ g.id, g.value }); + } + + /// Blocks until the queue's event reaches `v`. + fn reach(q: *State, v: u64) void { + if (objc.msg(u64, q.event, "signaledValue", .{}) >= v) return; + var seconds: u32 = 0; + while (!objc.msg(bool, q.event, "waitUntilSignaledValue:timeoutMS:", .{ v, @as(u64, 1000) })) { + seconds += 1; + if (seconds == 10) std.log.warn("metal 4: a command buffer has run for 10 s", .{}); + } + } + + /// With nothing in flight or being encoded, the buffers their owners freed leave the set. + fn drain(q: *State) void { + if (q.dropped.items.len == 0) return; + q.lock(); + defer q.unlock(); + if (q.unsent != 0 or objc.msg(u64, q.event, "signaledValue", .{}) < q.tick) return; + for (q.dropped.items) |id| objc.msg(void, q.set, "removeAllocation:", .{id}); + q.dropped.clearRetainingCapacity(); + objc.msg(void, q.set, "commit", .{}); + } + + /// A buffer's GPU address, the buffer joining the residency set the first time it is seen. + pub fn address(q: *State, buffer: Id) u64 { + const k = @intFromPtr(buffer); + const t = q.table.load(.acquire); + if (t.find(k)) |i| return t.addrs[i]; + return q.admit(buffer); + } + + fn admit(q: *State, buffer: Id) u64 { + const k = @intFromPtr(buffer); + q.lock(); + defer q.unlock(); + var t = q.table.load(.monotonic); + if (t.find(k)) |i| return t.addrs[i]; + if ((t.used + 1) * 2 > t.keys.len) t = q.grow(t); + const addr = objc.msg(u64, buffer, "gpuAddress", .{}); + objc.msg(void, q.set, "addAllocation:", .{buffer}); + q.set_dirty = true; + q.set_grew = true; + t.put(k, addr); + return addr; + } + + /// A table with room, its live keys moved over; the old one stays readable until the queue closes. + fn grow(q: *State, t: *Table) *Table { + var live: usize = 0; + for (t.keys) |*k| live += @intFromBool(k.load(.monotonic) > Table.tomb); + var n = t.keys.len; + while ((live + 1) * 4 > n) n *= 2; + const g = Table.init(n); + for (t.keys, t.addrs) |*k, a| { + const key = k.load(.monotonic); + if (key > Table.tomb) g.put(key, a); + } + q.retired.append(heap, t) catch @panic("metal 4: out of memory"); + q.table.store(g, .release); + return g; + } + + fn drop(q: *State, buffer: Id) void { + const k = @intFromPtr(buffer); + q.lock(); + defer q.unlock(); + const t = q.table.load(.monotonic); + const i = t.find(k) orelse return; + t.keys[i].store(Table.tomb, .release); + q.dropped.append(heap, buffer) catch { + objc.msg(void, q.set, "removeAllocation:", .{buffer}); + q.set_dirty = true; + }; + } + + fn fail(q: *State, err: Id) void { + const text = std.mem.span(objc.errorText(err)); + std.log.err("metal 4: a command buffer failed: {s}", .{text}); + const n = @min(text.len, q.failure_text.len - 1); + @memcpy(q.failure_text[0..n], text[0..n]); + q.failure_text[n] = 0; + _ = q.failures.fetchAdd(1, .acq_rel); + } + + /// Everything committed has run and reported; then the queue, its slots and its set go. + pub fn close(q: *State) void { + for (®istry) |*r| if (r.cmpxchgStrong(q, null, .acq_rel, .acquire) == null) { + _ = registered.fetchSub(1, .acq_rel); + break; + }; + if (q.tick > 0) q.reach(q.tick); + for (&q.slots) |*s| { + var tries: u32 = 0; + while (s.seen.load(.acquire) < s.commits and tries < 200_000) : (tries += 1) nap(10_000); + if (s.open) objc.msg(void, s.cb, "endCommandBuffer", .{}); + for (s.pages) |p| if (p) |pg| objc.release(pg.buf); + for ([_]Id{ s.table, s.allocator, s.cb }) |id| objc.release(id); + } + objc.msg(void, q.set, "removeAllAllocations", .{}); + objc.msg(void, q.set, "commit", .{}); + objc.msg(void, q.queue, "removeResidencySet:", .{q.set}); + if (q.timeline) |t| t.deinit(); + for ([_]Id{ q.set, q.event, q.queue }) |id| objc.release(id); + for (q.retired.items) |t| t.deinit(); + q.retired.deinit(heap); + q.dropped.deinit(heap); + q.table.load(.monotonic).deinit(); + heap.destroy(q); + } + + /// A round of named work: under TF_METAL4_TIMELINE some rounds of each name get a timestamp at every stage. + pub fn roundBegin(q: *State, name: []const u8) void { + if (q.timeline) |t| t.begin(name); + } + + /// After the round's last wait: a stamped round's stages are read and summed. + pub fn roundEnd(q: *State) void { + if (q.timeline) |t| t.end(); + } +}; + +test "the follow table: lookups, a dropped key, growth keeps every live address" { + const t = Table.init(8); + defer t.deinit(); + for (1..4) |i| t.put(i * 64, i * 1000); + try std.testing.expectEqual(@as(?usize, null), t.find(5 * 64)); + try std.testing.expectEqual(@as(u64, 2000), t.addrs[t.find(2 * 64).?]); + t.keys[t.find(2 * 64).?].store(Table.tomb, .release); + try std.testing.expectEqual(@as(?usize, null), t.find(2 * 64)); + try std.testing.expectEqual(@as(u64, 3000), t.addrs[t.find(3 * 64).?]); + t.put(2 * 64, 2222); + try std.testing.expectEqual(@as(u64, 2222), t.addrs[t.find(2 * 64).?]); + try std.testing.expectEqual(@as(usize, 3), t.used); +} diff --git a/zig/src/metal/metal4_timeline.zig b/zig/src/metal/metal4_timeline.zig new file mode 100644 index 00000000000..3f6d1b32e1a --- /dev/null +++ b/zig/src/metal/metal4_timeline.zig @@ -0,0 +1,255 @@ +//! TF_METAL4_TIMELINE: a GPU timestamp between every two stages of a named round, logged by kernel and by stage. +const std = @import("std"); +const objc = @import("objc.zig"); +const types = @import("types.zig"); + +const Id = objc.Id; +const heap = std.heap.c_allocator; +/// Stamps a round at most: the most a timestamp heap holds. +const cap = 4096; +const warm = 8; +/// Kernels a stage is named by; more are counted, not named. +const kept = 3; +const shown_kernels = 25; +const shown_stages = 15; + +/// What ran before stamp i: the stage it closes (`n` dispatches), or an encoder's start when `n` is 0. +const Mark = struct { enc: u32 = 0, n: u32 = 0, pipes: [kept]?Id = @splat(null), more: bool = false }; + +const Sum = struct { s: f64 = 0, stages: u64 = 0 }; + +/// One name's rounds, summed: the whole span, inside encoders and between them, by kernel and by stage index. +const Rounds = struct { + name: []u8, + seen: u32 = 0, + done: u32 = 0, + span: f64 = 0, + inside: f64 = 0, + between: f64 = 0, + encoders: u32 = 0, + dispatches: u64 = 0, + kernels: std.StringArrayHashMapUnmanaged(Sum) = .empty, + each: std.ArrayList(f64) = .empty, + keys: std.ArrayList([]const u8) = .empty, + encs: std.ArrayList(u32) = .empty, + fits: bool = true, +}; + +pub const Timeline = struct { + counters: Id, + freq: f64, + want: u32, + on: bool = false, + cur: ?*Rounds = null, + count: usize = 0, + enc: u32 = 0, + pipe: ?Id = null, + open: Mark = .{}, + marks: []Mark, + rounds: std.ArrayList(*Rounds) = .empty, + labels: std.AutoHashMapUnmanaged(usize, []const u8) = .empty, + + pub fn init(device: Id, want: u32) ?*Timeline { + const d = objc.msg(Id, objc.msg(Id, objc.class("MTL4CounterHeapDescriptor"), "alloc", .{}), "init", .{}); + defer objc.release(d); + objc.msg(void, d, "setType:", .{@as(isize, 1)}); + objc.msg(void, d, "setCount:", .{@as(usize, cap)}); + var err: ?Id = null; + const counters = objc.msg(?Id, device, "newCounterHeapWithDescriptor:error:", .{ d, &err }) orelse { + std.log.warn("metal 4 timeline: no timestamp heap ({s})", .{objc.errorText(err)}); + return null; + }; + const t = heap.create(Timeline) catch return null; + t.* = .{ + .counters = counters, + .freq = @floatFromInt(objc.msg(u64, device, "queryTimestampFrequency", .{})), + .want = want, + .marks = heap.alloc(Mark, cap) catch return null, + }; + return t; + } + + pub fn deinit(t: *Timeline) void { + for (t.rounds.items) |r| { + for (r.kernels.keys()) |k| heap.free(k); + r.kernels.deinit(heap); + r.each.deinit(heap); + for (r.keys.items) |k| heap.free(k); + r.keys.deinit(heap); + r.encs.deinit(heap); + heap.free(r.name); + heap.destroy(r); + } + t.rounds.deinit(heap); + var it = t.labels.valueIterator(); + while (it.next()) |v| heap.free(v.*); + t.labels.deinit(heap); + heap.free(t.marks); + objc.release(t.counters); + heap.destroy(t); + } + + pub fn begin(t: *Timeline, name: []const u8) void { + t.on = false; + const r = t.find(name) orelse return; + r.seen += 1; + if (r.seen <= warm or r.done >= t.want) return; + t.on = true; + t.cur = r; + t.count = 0; + t.enc = 0; + t.open = .{}; + } + + fn find(t: *Timeline, name: []const u8) ?*Rounds { + for (t.rounds.items) |r| if (std.mem.eql(u8, r.name, name)) return r; + const r = heap.create(Rounds) catch return null; + r.* = .{ .name = heap.dupe(u8, name) catch return null }; + t.rounds.append(heap, r) catch return null; + return r; + } + + fn stamp(t: *Timeline, e: Id, m: Mark) void { + if (t.count == cap) { + t.on = false; + return; + } + objc.msg(void, e, "writeTimestampWithGranularity:intoHeap:atIndex:", .{ @as(isize, 1), t.counters, t.count }); + t.marks[t.count] = m; + t.count += 1; + } + + pub fn started(t: *Timeline, e: Id) void { + if (!t.on) return; + t.enc += 1; + t.open = .{ .enc = t.enc }; + t.stamp(e, t.open); + } + + pub fn piped(t: *Timeline, id: Id) void { + if (t.on) t.pipe = id; + } + + pub fn dispatched(t: *Timeline) void { + if (!t.on) return; + t.open.n += 1; + for (&t.open.pipes) |*p| { + if (p.* == t.pipe) return; + if (p.* == null) { + p.* = t.pipe; + return; + } + } + t.open.more = true; + } + + pub fn stage(t: *Timeline, e: Id) void { + if (!t.on) return; + t.stamp(e, t.open); + t.open = .{ .enc = t.enc }; + } + + pub fn ended(t: *Timeline, e: Id) void { + t.stage(e); + } + + /// After the round's last wait: its stamps read back and added to its name's sums. + pub fn end(t: *Timeline) void { + if (!t.on) return; + t.on = false; + const r = t.cur orelse return; + if (t.count < 2) return; + const data = objc.msg(?Id, t.counters, "resolveCounterRange:", .{types.Range{ .location = 0, .length = t.count }}) orelse return; + const w: [*]align(1) const u64 = @ptrCast(objc.msg([*]const u8, data, "bytes", .{})); + const first = r.done == 0; + r.done += 1; + r.span += t.secs(w[0], w[t.count - 1]); + r.encoders = t.enc; + var j: usize = 0; + for (1..t.count) |i| { + const d = t.secs(w[i - 1], w[i]); + const m = t.marks[i]; + if (m.n == 0) { + r.between += d; + continue; + } + r.inside += d; + r.dispatches += m.n; + const key = t.keyOf(m) catch continue; + const g = r.kernels.getOrPut(heap, key) catch continue; + if (g.found_existing) heap.free(key) else g.value_ptr.* = .{}; + g.value_ptr.s += d; + g.value_ptr.stages += 1; + if (first) { + r.each.append(heap, d) catch {}; + r.keys.append(heap, heap.dupe(u8, g.key_ptr.*) catch "") catch {}; + r.encs.append(heap, m.enc) catch {}; + } else if (j < r.each.items.len) r.each.items[j] += d else r.fits = false; + j += 1; + } + if (j != r.each.items.len) r.fits = false; + if (r.done == t.want) t.report(r); + } + + fn secs(t: *const Timeline, a: u64, b: u64) f64 { + return if (b > a) @as(f64, @floatFromInt(b - a)) / t.freq else 0; + } + + /// The stage's kernels by label, joined. + fn keyOf(t: *Timeline, m: Mark) ![]u8 { + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(heap); + for (m.pipes) |p| if (p) |id| { + if (out.items.len > 0) try out.appendSlice(heap, " + "); + try out.appendSlice(heap, t.label(id)); + }; + if (m.more) try out.appendSlice(heap, " + more"); + return out.toOwnedSlice(heap); + } + + fn label(t: *Timeline, id: Id) []const u8 { + const g = t.labels.getOrPut(heap, @intFromPtr(id)) catch return "?"; + if (g.found_existing) return g.value_ptr.*; + const text = if (objc.msg(?Id, id, "label", .{})) |s| std.mem.span(objc.utf8(s)) else "unnamed kernel"; + g.value_ptr.* = heap.dupe(u8, text) catch "?"; + return g.value_ptr.*; + } + + fn report(t: *Timeline, r: *Rounds) void { + _ = t; + const n: f64 = @floatFromInt(r.done); + const ms = 1e3 / n; + var stages: u64 = 0; + for (r.kernels.values()) |v| stages += v.stages; + std.log.info("metal 4 timeline: {s}, {d} rounds after {d} warm: {d} encoders, {d} stages and {d} dispatches a round", .{ r.name, r.done, warm, r.encoders, stages / r.done, r.dispatches / r.done }); + std.log.info("metal 4 timeline: {s}: {d:.3} ms a round from the first stamp to the last, {d:.3} in stages, {d:.3} between encoders", .{ r.name, r.span * ms, r.inside * ms, r.between * ms }); + const order = heap.alloc(usize, r.kernels.count()) catch return; + defer heap.free(order); + for (order, 0..) |*o, i| o.* = i; + const vals = r.kernels.values(); + std.mem.sort(usize, order, vals, struct { + fn more(v: []const Sum, a: usize, b: usize) bool { + return v[a].s > v[b].s; + } + }.more); + std.log.info("metal 4 timeline: {s} by kernel: ms a round, stages a round, us a stage", .{r.name}); + for (order[0..@min(order.len, shown_kernels)]) |i| { + const v = vals[i]; + const per = @as(f64, @floatFromInt(v.stages)) / n; + std.log.info(" {d:>8.3} {d:>6.1} {d:>8.1} {s}", .{ v.s * ms, per, v.s * 1e6 / @as(f64, @floatFromInt(v.stages)), r.kernels.keys()[i] }); + } + if (!r.fits) return std.log.info("metal 4 timeline: {s}: rounds differ in stages, so no stage-by-stage list", .{r.name}); + const idx = heap.alloc(usize, r.each.items.len) catch return; + defer heap.free(idx); + for (idx, 0..) |*o, i| o.* = i; + std.mem.sort(usize, idx, r.each.items, struct { + fn more(v: []const f64, a: usize, b: usize) bool { + return v[a] > v[b]; + } + }.more); + std.log.info("metal 4 timeline: {s}: the longest single stages, us a round", .{r.name}); + for (idx[0..@min(idx.len, shown_stages)]) |i| { + std.log.info(" stage {d:>4} of encoder {d}: {d:>8.1} {s}", .{ i, r.encs.items[i], r.each.items[i] * 1e6 / n, r.keys.items[i] }); + } + } +}; diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 438892aa48c..9b310180ea3 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -66,6 +66,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_HEAD_GEOMETRY", .scope = .metal, .kind = .size, .forms = "a whole nonnegative native-size geometry count" }, .{ .name = "TF_PROMPT_ROWS", .scope = .metal, .kind = .prompt, .forms = "a multiple of 16 from 128 to 2048 for native serving" }, .{ .name = "TF_ANE_COLUMNS", .scope = .metal, .kind = .u32, .forms = "a whole column count from 0 to 4294967295 (0 disables the share)" }, + .{ .name = "TF_METAL4_TIMELINE", .scope = .metal, .kind = .u32, .forms = "a whole round count from 0 to 4294967295 (0, the default, stamps nothing; n stamps every stage of n rounds of each kind on a Metal 4 queue and logs them)" }, .{ .name = "TF_FLASHNEXT_SCALE_INDEX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0: Flash Next's 4-bit expert kernels read the stored scales and biases, not their 16-bit index)" }, .{ .name = "GLM_EHPROJ_NAX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 serves GLM's MTP eh_proj on the scalar kernel)" }, .{ .name = "TF_FLASHNEXT_GROUPED_ROWS", .scope = .metal, .kind = .size, .forms = "0 (never) or the rows, 1 to 32, from which a window's experts run grouped", .max = 32 }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index de938481524..82267bf7c41 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -126,6 +126,8 @@ const valid = [_]Case{ .{ .name = "TF_SLIDE_POCKET_DUMP", .raw = "/tmp/pocket rows", .n = 0 }, .{ .name = "TENSORFOLD_CUDA_KERNELS", .raw = "/tmp/captured set", .n = 0 }, .{ .name = "TF_SLIDE_FORGET_FAIL", .raw = " 0 ", .n = 0 }, + .{ .name = "TF_METAL4_TIMELINE", .raw = "0", .n = 0 }, + .{ .name = "TF_METAL4_TIMELINE", .raw = "3", .n = 3 }, .{ .name = "TF_DSV41_SMALL", .raw = "1", .n = 1 }, .{ .name = "TF_DSV41_ASSETS", .raw = "deepseek assets", .n = 0 }, .{ .name = "TF_DSV41_ENGRAM_DIR", .raw = "engram-rows", .n = 0 }, From a09abfa13c8378fd372797485ffc3e22774dfbc7 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:34:19 +0000 Subject: [PATCH 18/25] dsv41 metal: TF_METAL4=1 runs the family on a Metal 4 queue, decode rounds named for the timeline boot.openQueue gives the family, and its test rigs, a Metal 4 queue under TF_METAL4=1 where the Mac has one, and Metal 3 otherwise; the kernels and their order are the same. The decode forward names each round by its rows for TF_METAL4_TIMELINE, and TF_DSV41_ROUND_PROF=1 logs rounds' host and GPU milliseconds by rows on either queue. A new device test checks decode rounds of 1 to 16 rows, a prompt's chunks and timestamped rounds on a Metal 4 queue against a Metal 3 queue, bit for bit. --- docs/environment.md | 2 + zig/src/families/deepseek_v41/metal/boot.zig | 12 +- .../families/deepseek_v41/metal/forward.zig | 6 + .../deepseek_v41/metal/round_prof.zig | 50 +++++++ zig/src/platform/environment.zig | 2 + zig/src/platform/environment_test.zig | 3 + zig/tests/dsv41_metal/fixture.zig | 2 +- zig/tests/dsv41_metal/layer_test.zig | 1 + zig/tests/dsv41_metal/metal4_test.zig | 141 ++++++++++++++++++ 9 files changed, 217 insertions(+), 2 deletions(-) create mode 100644 zig/src/families/deepseek_v41/metal/round_prof.zig create mode 100644 zig/tests/dsv41_metal/metal4_test.zig diff --git a/docs/environment.md b/docs/environment.md index 608b33c39c4..0a1c653f5f9 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -61,6 +61,8 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_MINIMAX_WORLD` | MiniMax-M3.1-Flash on CUDA: a whole rank count, 2 at CUDA, set with `TF_MINIMAX_RANK`; unset with it gives one rank | | `TF_PROMPT_ROWS` | Native serving: a multiple of 16 from 128 through 2048; unset keeps the chip/family default | | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | +| `TF_METAL4` | Metal: exactly `0` or `1`; `1` sends a family's GPU work through Metal 4 (macOS 26 and later) where the family supports it, DeepSeek-V4.1 for now: the same kernels in the same order, with Metal 4's command queue, allocators, argument tables and barriers, and bit-identical outputs. Macs without Metal 4 stay on Metal 3; default 0 | +| `TF_DSV41_ROUND_PROF` | DeepSeek-V4.1 on Metal: exactly `0` or `1`; `1` logs decode rounds' host milliseconds (first encode to last wait) and GPU milliseconds by rows, every 1,024 rounds; default 0 | | `TF_METAL4_TIMELINE` | Metal 4: a whole round count, default 0; `n` puts a GPU timestamp at every stage (between barriers) of `n` rounds of each kind a family names, after 8 warm ones, and logs their time by kernel and the longest stages. DeepSeek-V4.1 names its decode rounds by rows. Stamps cost GPU time, so stamped rounds read a little long | | `TF_FLASHNEXT_SCALE_INDEX` | Flash Next on Metal before tensor units: exactly `0` or `1`; default 1, where the 4-bit expert kernels (decode, grouped and prompt gathers) read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values from fewer weight bytes, and the routed experts' stored scales and biases are not kept in memory; `0` keeps and reads the stored arrays; ignored with `--ssd-experts` | | `TF_FLASHNEXT_GROUPED_ROWS` | Flash Next on Metal without tensor units: `0`, or the rows (`1` through `32`) from which a decode window runs its 4-bit experts grouped by expert, with the same output bits; default 5; ignored with `--ssd-experts` and in speed-up mode | diff --git a/zig/src/families/deepseek_v41/metal/boot.zig b/zig/src/families/deepseek_v41/metal/boot.zig index 4f0c56d1e08..2416291c906 100644 --- a/zig/src/families/deepseek_v41/metal/boot.zig +++ b/zig/src/families/deepseek_v41/metal/boot.zig @@ -36,6 +36,16 @@ pub const Options = struct { decode_share: ?f64 = null, }; +/// The family's queue: Metal 4 under TF_METAL4=1 where this Mac has it, else Metal 3; the kernels are the same. +pub fn openQueue(device: mtl.Device) !mtl.Queue { + if (!try environment.read(bool, "TF_METAL4", false)) return device.queue(); + if (device.queue4()) |q| { + std.log.info("dsv41 metal: Metal 4 command queue", .{}); + return q; + } else |_| std.log.warn("dsv41 metal: TF_METAL4=1 but this Mac has no Metal 4 queue; Metal 3 it is", .{}); + return device.queue(); +} + /// Everything a served model borrows, owned here and closed after the model's target and pass. pub const Boot = struct { a: Allocator, @@ -65,7 +75,7 @@ pub const Boot = struct { const limit: u32 = @intCast(@min(o.context orelse 262144, c.rope.max_positions)); b.device = try mtl.Device.init(); errdefer b.device.deinit(); - b.queue = try b.device.queue(); + b.queue = try openQueue(b.device); errdefer b.queue.deinit(); b.p = try pipelines.Pipelines.load(a, b.device, c); errdefer b.p.deinit(); diff --git a/zig/src/families/deepseek_v41/metal/forward.zig b/zig/src/families/deepseek_v41/metal/forward.zig index 622ec616b42..55a4bbda3b8 100644 --- a/zig/src/families/deepseek_v41/metal/forward.zig +++ b/zig/src/families/deepseek_v41/metal/forward.zig @@ -12,6 +12,7 @@ const Ctx = ctx_.Ctx; const Ref = ctx_.Ref; const g = pipelines.glue; const cl = @import("calls.zig"); +const round_prof = @import("round_prof.zig"); const eng = pipelines.engram; const cv = ctx_.cv; const R = pipelines.max_rows; @@ -215,6 +216,9 @@ pub fn run(x: *const Ctx, q: mtl.Queue, m: Model, b: *const Bufs) !void { var cbs: [max_buffers]mtl.CommandBuffer = undefined; var n: usize = 0; defer for (cbs[0..n]) |cb| cb.release(); + const t0 = round_prof.begin(); + var name: [24]u8 = undefined; + q.roundBegin(std.fmt.bufPrint(&name, "decode {d} rows", .{x.rows}) catch "decode"); var lo: usize = 0; while (true) { const hi = chunkEnd(lo, m.layers.len); @@ -234,6 +238,8 @@ pub fn run(x: *const Ctx, q: mtl.Queue, m: Model, b: *const Bufs) !void { lo = hi; } cbs[n - 1].wait(); + q.roundEnd(); + if (t0) |t| round_prof.end(t, x.rows, cbs[0], cbs[n - 1]); for (cbs[0..n]) |cb| if (cb.failure()) |msg| { std.debug.print("dsv41 metal window failed: {s}\n", .{msg}); return error.CommandBufferFailed; diff --git a/zig/src/families/deepseek_v41/metal/round_prof.zig b/zig/src/families/deepseek_v41/metal/round_prof.zig new file mode 100644 index 00000000000..2b6843bb87c --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/round_prof.zig @@ -0,0 +1,50 @@ +//! TF_DSV41_ROUND_PROF=1: decode rounds' host (encode to last wait) and GPU milliseconds by rows, logged now and then. +const std = @import("std"); +const mtl = @import("metal"); + +const Sum = struct { n: u64 = 0, host: f64 = 0, gpu: f64 = 0, timed: u64 = 0 }; +const every = 1024; + +var state: enum { unread, off, on } = .unread; +var sums: [17]Sum = @splat(.{}); +var rounds: u64 = 0; + +/// The host clock at a round's start, or null when off. +pub fn begin() ?f64 { + if (state == .unread) state = if (@import("sys").environment.read(bool, "TF_DSV41_ROUND_PROF", false) catch false) .on else .off; + return if (state == .on) mtl.clock.seconds() else null; +} + +/// Metal 4 reports a command buffer's GPU times after its wait returns: a round's are read at the next round's end. +var pending: ?struct { first: mtl.CommandBuffer, last: mtl.CommandBuffer, rows: u32 } = null; + +/// A round of `rows` rows from `t0`, its command buffers' first and last. +pub fn end(t0: f64, rows: u32, first: mtl.CommandBuffer, last: mtl.CommandBuffer) void { + const s = &sums[@min(rows, sums.len - 1)]; + s.n += 1; + s.host += mtl.clock.seconds() - t0; + if (pending) |p| gpu(p.rows, p.first, p.last); + pending = null; + if (first.m4 != null) pending = .{ .first = first, .last = last, .rows = rows } else gpu(rows, first, last); + rounds += 1; + if (rounds % every == 0) log(); +} + +fn gpu(rows: u32, first: mtl.CommandBuffer, last: mtl.CommandBuffer) void { + const s = &sums[@min(rows, sums.len - 1)]; + const a = first.gpuTimes() orelse return; + const b = last.gpuTimes() orelse return; + s.gpu += b[1] - a[0]; + s.timed += 1; +} + +fn log() void { + var buf: [1024]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + for (sums, 0..) |s, rows| { + if (s.n == 0) continue; + const g = if (s.timed > 0) s.gpu / @as(f64, @floatFromInt(s.timed)) * 1e3 else 0; + w.print(" {d} rows: {d:.2} host, {d:.2} gpu ({d});", .{ rows, s.host / @as(f64, @floatFromInt(s.n)) * 1e3, g, s.n }) catch break; + } + std.log.info("dsv41 rounds, ms a round over {d}:{s}", .{ rounds, w.buffered() }); +} diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 9b310180ea3..f0319f3f6bb 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -66,7 +66,9 @@ pub const rules = [_]Rule{ .{ .name = "TF_HEAD_GEOMETRY", .scope = .metal, .kind = .size, .forms = "a whole nonnegative native-size geometry count" }, .{ .name = "TF_PROMPT_ROWS", .scope = .metal, .kind = .prompt, .forms = "a multiple of 16 from 128 to 2048 for native serving" }, .{ .name = "TF_ANE_COLUMNS", .scope = .metal, .kind = .u32, .forms = "a whole column count from 0 to 4294967295 (0 disables the share)" }, + .{ .name = "TF_METAL4", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 sends the work of a family that supports it, DeepSeek-V4.1 for now, through Metal 4 on macOS 26 and later; 0, the default, keeps Metal 3)" }, .{ .name = "TF_METAL4_TIMELINE", .scope = .metal, .kind = .u32, .forms = "a whole round count from 0 to 4294967295 (0, the default, stamps nothing; n stamps every stage of n rounds of each kind on a Metal 4 queue and logs them)" }, + .{ .name = "TF_DSV41_ROUND_PROF", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 logs DeepSeek-V4.1 Metal decode rounds' host and GPU milliseconds by rows)" }, .{ .name = "TF_FLASHNEXT_SCALE_INDEX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0: Flash Next's 4-bit expert kernels read the stored scales and biases, not their 16-bit index)" }, .{ .name = "GLM_EHPROJ_NAX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 serves GLM's MTP eh_proj on the scalar kernel)" }, .{ .name = "TF_FLASHNEXT_GROUPED_ROWS", .scope = .metal, .kind = .size, .forms = "0 (never) or the rows, 1 to 32, from which a window's experts run grouped", .max = 32 }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 82267bf7c41..310ceab4172 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -126,8 +126,11 @@ const valid = [_]Case{ .{ .name = "TF_SLIDE_POCKET_DUMP", .raw = "/tmp/pocket rows", .n = 0 }, .{ .name = "TENSORFOLD_CUDA_KERNELS", .raw = "/tmp/captured set", .n = 0 }, .{ .name = "TF_SLIDE_FORGET_FAIL", .raw = " 0 ", .n = 0 }, + .{ .name = "TF_METAL4", .raw = "0", .n = 0 }, + .{ .name = "TF_METAL4", .raw = "1", .n = 1 }, .{ .name = "TF_METAL4_TIMELINE", .raw = "0", .n = 0 }, .{ .name = "TF_METAL4_TIMELINE", .raw = "3", .n = 3 }, + .{ .name = "TF_DSV41_ROUND_PROF", .raw = "1", .n = 1 }, .{ .name = "TF_DSV41_SMALL", .raw = "1", .n = 1 }, .{ .name = "TF_DSV41_ASSETS", .raw = "deepseek assets", .n = 0 }, .{ .name = "TF_DSV41_ENGRAM_DIR", .raw = "engram-rows", .n = 0 }, diff --git a/zig/tests/dsv41_metal/fixture.zig b/zig/tests/dsv41_metal/fixture.zig index 30684318743..c3a5ec6937c 100644 --- a/zig/tests/dsv41_metal/fixture.zig +++ b/zig/tests/dsv41_metal/fixture.zig @@ -237,7 +237,7 @@ pub const Rig = struct { r.c = c; try r.c.validate(); r.device = try mtl.Device.init(); - r.queue = try r.device.queue(); + r.queue = try pkg.boot.openQueue(r.device); r.p = try pkg.pipelines.Pipelines.load(a, r.device, &r.c); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); diff --git a/zig/tests/dsv41_metal/layer_test.zig b/zig/tests/dsv41_metal/layer_test.zig index 9e3aa03a2a2..e2bec04a36e 100644 --- a/zig/tests/dsv41_metal/layer_test.zig +++ b/zig/tests/dsv41_metal/layer_test.zig @@ -15,6 +15,7 @@ test { _ = @import("ref.zig"); _ = @import("forward_test.zig"); _ = @import("zerocopy_test.zig"); + _ = @import("metal4_test.zig"); _ = @import("prompt_test.zig"); _ = @import("dspark_test.zig"); _ = @import("multi_test.zig"); diff --git a/zig/tests/dsv41_metal/metal4_test.zig b/zig/tests/dsv41_metal/metal4_test.zig new file mode 100644 index 00000000000..4aecf6ecc41 --- /dev/null +++ b/zig/tests/dsv41_metal/metal4_test.zig @@ -0,0 +1,141 @@ +//! DeepSeek-V4.1 on a Metal 4 queue against a Metal 3 queue, bit for bit: decode rounds, prompt chunks, timestamps. +const std = @import("std"); +const mtl = @import("metal"); +const pkg = @import("dsv41_metal"); +const fixture = @import("fixture.zig"); +const ff = @import("fixture_fwd.zig"); +const pt = @import("prompt_test.zig"); + +const testing = std.testing; +const fwd = pkg.forward; +const limit = 1280; +const look = 3; + +const Out = struct { + logits: []f32, + taps: []u16, + + fn deinit(o: Out, a: std.mem.Allocator) void { + a.free(o.logits); + a.free(o.taps); + } +}; + +fn reset(q: mtl.Queue, to: *const pkg.kv.Slot, from: *const pkg.kv.Slot) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = q.commandBuffer(); + to.copyFrom(cb, from); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.CommandBufferFailed; +} + +/// `steps` decode rounds of `rows` rows from p0 through forward.run on `q`, the slot first copied from `pristine`. +fn rounds(a: std.mem.Allocator, f: *ff.Fwd, q: mtl.Queue, slot: *const pkg.kv.Slot, pristine: *const pkg.kv.Slot, hist: []const u32, p0: u32, rows: usize, steps: usize) !Out { + const r = f.r; + const c = &r.c; + try reset(q, slot, pristine); + const V: usize = c.vocab; + const TH = c.dspark_targets.len * c.hidden; + const out: Out = .{ .logits = try a.alloc(f32, rows * steps * V), .taps = try a.alloc(u16, rows * steps * TH) }; + for (0..steps) |k| { + const at = k * rows; + try fwd.prepare(&f.b, c, hist[look + at ..][0..rows], ff.lookbackAt(hist, look + at, look), f.lookup()); + const p: u32 = p0 + @as(u32, @intCast(at)); + try r.s.writeRows(c, p, @intCast(rows)); + const x = r.ctx(slot, p, @intCast(rows)); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + try fwd.run(&x, q, f.model(), &f.b); + @memcpy(out.logits[at * V ..][0 .. rows * V], f.b.logitsOf(c, rows)); + @memcpy(out.taps[at * TH ..][0 .. rows * TH], slot.taps.?.slice(u16, rows * TH)); + } + return out; +} + +/// The same rounds on both queues: logits, taps and slot bytes that differ. +fn compare(a: std.mem.Allocator, f: *ff.Fwd, m3: mtl.Queue, m4: mtl.Queue, pristine: *const pkg.kv.Slot, rows: usize, steps: usize, seed: u64) !usize { + const r = f.r; + var s3 = try pkg.kv.Slot.init(a, r.device, &r.c, limit); + defer s3.deinit(); + var s4 = try pkg.kv.Slot.init(a, r.device, &r.c, limit); + defer s4.deinit(); + const hist = try ff.ids(a, &r.c, look + rows * steps, seed); + defer a.free(hist); + const o3 = try rounds(a, f, m3, &s3, pristine, hist, 1101, rows, steps); + defer o3.deinit(a); + const o4 = try rounds(a, f, m4, &s4, pristine, hist, 1101, rows, steps); + defer o4.deinit(a); + const lb = pt.bitsDiff(o3.logits, o4.logits); + const tb = pt.halfDiff(o3.taps, o4.taps); + const sb = pt.stateDiff(&s3, &s4); + const word = if (lb + tb + sb == 0) "PASS" else "FAIL"; + std.debug.print("{s} dsv41 metal 4 == metal 3: {d} rounds of {d} rows: {d} logits, {d} tap values, {d} state bytes differ\n", .{ word, steps, rows, lb, tb, sb }); + return lb + tb + sb; +} + +test "dsv41 metal: decode rounds on a Metal 4 queue equal a Metal 3 queue's bit for bit, 1 to 16 rows" { + const a = testing.allocator; + const f = try ff.Fwd.init(a, testing.io, limit, 71); + defer f.deinit(); + if (!f.r.device.hasMetal4()) return error.SkipZigTest; + const m3 = try f.r.device.queue(); + defer m3.deinit(); + const m4 = try f.r.device.queue4(); + defer m4.deinit(); + try testing.expect(m4.isMetal4() and !m3.isMetal4()); + var pristine = try pkg.kv.Slot.init(a, f.r.device, &f.r.c, limit); + defer pristine.deinit(); + fixture.fillPast(&f.r.c, &pristine, 1101, 12); + var bad: usize = 0; + for ([_]usize{ 1, 2, 4, 6, 16 }) |rows| bad += try compare(a, f, m3, m4, &pristine, rows, 3, 300 + rows); + try testing.expectEqual(@as(usize, 0), bad); +} + +test "dsv41 metal: a prompt's chunks on a Metal 4 queue equal a Metal 3 queue's: logits, taps, slot and tail" { + const a = testing.allocator; + const f = try ff.Fwd.initWith(a, testing.io, fixture.promptConfig(), limit, 72); + defer f.deinit(); + if (!f.r.device.hasMetal4()) return error.SkipZigTest; + const c = &f.r.c; + const hist = try ff.ids(a, c, 900, 73); + defer a.free(hist); + var runs: [2]pt.Run = undefined; + const qs = [2]mtl.Queue{ try f.r.device.queue(), try f.r.device.queue4() }; + defer for (qs) |q| q.deinit(); + for (&runs, qs) |*run, q| { + run.* = try pt.Run.init(a, f, pt.head_opts, 0); + var e = pt.env(f); + e.queue = q; + try run.p.run(e, &run.slot, &run.tail, hist); + } + defer for (&runs) |*run| run.deinit(); + const d = pt.runDiff(c, &runs[0], &runs[1]); + const td = pt.tailDiff(&runs[0].tail, &runs[1].tail); + const word = if (d[0] + d[1] + d[2] + td == 0) "PASS" else "FAIL"; + std.debug.print("{s} dsv41 metal 4 prompt == metal 3: {d} logits, {d} taps, {d} state bytes, {d} tail bytes differ\n", .{ word, d[0], d[1], d[2], td }); + try testing.expectEqual(@as(usize, 0), d[0] + d[1] + d[2] + td); +} + +test "dsv41 metal: timestamped decode rounds on Metal 4 change no bit, and their stages are summed" { + const a = testing.allocator; + const f = try ff.Fwd.init(a, testing.io, limit, 74); + defer f.deinit(); + if (!f.r.device.hasMetal4()) return error.SkipZigTest; + const m3 = try f.r.device.queue(); + defer m3.deinit(); + const st = mtl.metal4.State.open(f.r.device.id, 2) orelse return error.SkipZigTest; + const m4: mtl.Queue = .{ .id = st.queue, .m4 = st }; + defer m4.deinit(); + var pristine = try pkg.kv.Slot.init(a, f.r.device, &f.r.c, limit); + defer pristine.deinit(); + fixture.fillPast(&f.r.c, &pristine, 1101, 13); + // 8 warm rounds, then 2 stamped + try testing.expectEqual(@as(usize, 0), try compare(a, f, m3, m4, &pristine, 1, 11, 400)); + const t = st.timeline orelse return error.NoTimeline; + const r = t.rounds.items[0]; + std.debug.print("dsv41 metal 4 timeline: {s}: {d} stamped rounds, {d} encoders, {d} kernels, {d:.3} ms in stages a round\n", .{ r.name, r.done, r.encoders, r.kernels.count(), r.inside * 1e3 / @as(f64, @floatFromInt(r.done)) }); + try testing.expectEqual(@as(u32, 2), r.done); + try testing.expect(r.encoders >= 1 and r.kernels.count() > 4 and r.inside > 0 and r.fits); +} From d52b7aa7066bf8379a10d9257ed914c577a4e728 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:57:16 +0000 Subject: [PATCH 19/25] dsv41 metal: Metal 4 by default where the Mac has it, TF_METAL4=0 keeps Metal 3 Served DeepSeek-V4.1 replies were equal on Metal 3 and Metal 4 (48 of 48 in every pairing of two runs each), and decode rounds took less GPU time on Metal 4 at every row count, so the served family's queue is Metal 4 wherever the device has Metal 4's command queues. Macs without it, and TF_METAL4=0, stay on Metal 3. The device test rigs stay on Metal 3 unless TF_METAL4=1, as the timing harnesses sample Metal 3 encoders; metal4_test compares both. --- docs/environment.md | 2 +- zig/src/families/deepseek_v41/metal/boot.zig | 8 ++++---- zig/src/platform/environment.zig | 2 +- zig/tests/dsv41_metal/fixture.zig | 3 ++- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/environment.md b/docs/environment.md index 0a1c653f5f9..6452f853298 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -61,7 +61,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_MINIMAX_WORLD` | MiniMax-M3.1-Flash on CUDA: a whole rank count, 2 at CUDA, set with `TF_MINIMAX_RANK`; unset with it gives one rank | | `TF_PROMPT_ROWS` | Native serving: a multiple of 16 from 128 through 2048; unset keeps the chip/family default | | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | -| `TF_METAL4` | Metal: exactly `0` or `1`; `1` sends a family's GPU work through Metal 4 (macOS 26 and later) where the family supports it, DeepSeek-V4.1 for now: the same kernels in the same order, with Metal 4's command queue, allocators, argument tables and barriers, and bit-identical outputs. Macs without Metal 4 stay on Metal 3; default 0 | +| `TF_METAL4` | Metal: exactly `0` or `1`; `1` sends a family's GPU work through Metal 4 (macOS 26 and later) where the family supports it: the same kernels in the same order, with Metal 4's command queue, allocators, argument tables and barriers, and bit-identical outputs; `0` keeps Metal 3. DeepSeek-V4.1 defaults to `1` where the Mac has Metal 4 (its device test rigs to `0`); Macs without it stay on Metal 3 | | `TF_DSV41_ROUND_PROF` | DeepSeek-V4.1 on Metal: exactly `0` or `1`; `1` logs decode rounds' host milliseconds (first encode to last wait) and GPU milliseconds by rows, every 1,024 rounds; default 0 | | `TF_METAL4_TIMELINE` | Metal 4: a whole round count, default 0; `n` puts a GPU timestamp at every stage (between barriers) of `n` rounds of each kind a family names, after 8 warm ones, and logs their time by kernel and the longest stages. DeepSeek-V4.1 names its decode rounds by rows. Stamps cost GPU time, so stamped rounds read a little long | | `TF_FLASHNEXT_SCALE_INDEX` | Flash Next on Metal before tensor units: exactly `0` or `1`; default 1, where the 4-bit expert kernels (decode, grouped and prompt gathers) read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values from fewer weight bytes, and the routed experts' stored scales and biases are not kept in memory; `0` keeps and reads the stored arrays; ignored with `--ssd-experts` | diff --git a/zig/src/families/deepseek_v41/metal/boot.zig b/zig/src/families/deepseek_v41/metal/boot.zig index 2416291c906..a5a9d0119c3 100644 --- a/zig/src/families/deepseek_v41/metal/boot.zig +++ b/zig/src/families/deepseek_v41/metal/boot.zig @@ -36,9 +36,9 @@ pub const Options = struct { decode_share: ?f64 = null, }; -/// The family's queue: Metal 4 under TF_METAL4=1 where this Mac has it, else Metal 3; the kernels are the same. -pub fn openQueue(device: mtl.Device) !mtl.Queue { - if (!try environment.read(bool, "TF_METAL4", false)) return device.queue(); +/// The family's queue: Metal 4 under TF_METAL4=1, or by default when `metal4` holds, else Metal 3; the same kernels. +pub fn openQueue(device: mtl.Device, metal4: bool) !mtl.Queue { + if (!try environment.read(bool, "TF_METAL4", metal4)) return device.queue(); if (device.queue4()) |q| { std.log.info("dsv41 metal: Metal 4 command queue", .{}); return q; @@ -75,7 +75,7 @@ pub const Boot = struct { const limit: u32 = @intCast(@min(o.context orelse 262144, c.rope.max_positions)); b.device = try mtl.Device.init(); errdefer b.device.deinit(); - b.queue = try openQueue(b.device); + b.queue = try openQueue(b.device, b.device.hasMetal4()); errdefer b.queue.deinit(); b.p = try pipelines.Pipelines.load(a, b.device, c); errdefer b.p.deinit(); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index f0319f3f6bb..d6064a6ce25 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -66,7 +66,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_HEAD_GEOMETRY", .scope = .metal, .kind = .size, .forms = "a whole nonnegative native-size geometry count" }, .{ .name = "TF_PROMPT_ROWS", .scope = .metal, .kind = .prompt, .forms = "a multiple of 16 from 128 to 2048 for native serving" }, .{ .name = "TF_ANE_COLUMNS", .scope = .metal, .kind = .u32, .forms = "a whole column count from 0 to 4294967295 (0 disables the share)" }, - .{ .name = "TF_METAL4", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 sends the work of a family that supports it, DeepSeek-V4.1 for now, through Metal 4 on macOS 26 and later; 0, the default, keeps Metal 3)" }, + .{ .name = "TF_METAL4", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 keeps Metal 3; 1 sends the work of a family that supports it through Metal 4 on macOS 26 and later, the default for DeepSeek-V4.1 there)" }, .{ .name = "TF_METAL4_TIMELINE", .scope = .metal, .kind = .u32, .forms = "a whole round count from 0 to 4294967295 (0, the default, stamps nothing; n stamps every stage of n rounds of each kind on a Metal 4 queue and logs them)" }, .{ .name = "TF_DSV41_ROUND_PROF", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 logs DeepSeek-V4.1 Metal decode rounds' host and GPU milliseconds by rows)" }, .{ .name = "TF_FLASHNEXT_SCALE_INDEX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0: Flash Next's 4-bit expert kernels read the stored scales and biases, not their 16-bit index)" }, diff --git a/zig/tests/dsv41_metal/fixture.zig b/zig/tests/dsv41_metal/fixture.zig index c3a5ec6937c..6c20e293394 100644 --- a/zig/tests/dsv41_metal/fixture.zig +++ b/zig/tests/dsv41_metal/fixture.zig @@ -237,7 +237,8 @@ pub const Rig = struct { r.c = c; try r.c.validate(); r.device = try mtl.Device.init(); - r.queue = try pkg.boot.openQueue(r.device); + // Metal 3 unless TF_METAL4=1: the timing harnesses sample Metal 3 encoders, and metal4_test compares the two + r.queue = try pkg.boot.openQueue(r.device, false); r.p = try pkg.pipelines.Pipelines.load(a, r.device, &r.c); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); From 009de59a87668a04c819676267f6c8cac78e33ac Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:11:25 +0000 Subject: [PATCH 20/25] changelog: #3374's line names its PR From 7cce8cec6fa1459b96d60aec8b371ff11bbb8af9 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:36:11 +0000 Subject: [PATCH 21/25] metal 4: a closing queue keeps its memory while a feedback is owed, a failure check awaits its own feedback Review fixes. A queue's commit feedback handlers live in its State: close now waits for every commit's feedback and, if one is still owed after 2 s, keeps the State's memory instead of freeing it, so a late handler never writes freed storage (closeWithin is the bounded form; a test closes one queue with every feedback in and one with a feedback owed). A command buffer's failure check waits for that use's own feedback (a short spin, then naps up to 2 s) before it reports no failure, since Metal 4 delivers errors in the handler apart from the GPU event a wait watches; one that never arrives is a failure. The DeepSeek-V4.1 round profiler reads and drops its pending round before the engine closes its queue (a test checks nothing is left pending). Pipelines carry their kernel's name only under TF_METAL4_TIMELINE, the label's one reader, so other families' pipeline builds do no extra work. --- zig/src/families/deepseek_v41/metal/boot.zig | 2 + zig/src/families/deepseek_v41/metal/metal.zig | 1 + .../deepseek_v41/metal/round_prof.zig | 16 +++++++ zig/src/metal/library.zig | 27 +++++++++-- zig/src/metal/metal4.zig | 39 +++++++++++++-- zig/tests/dsv41_metal/metal4_test.zig | 48 +++++++++++++++++++ 6 files changed, 125 insertions(+), 8 deletions(-) diff --git a/zig/src/families/deepseek_v41/metal/boot.zig b/zig/src/families/deepseek_v41/metal/boot.zig index a5a9d0119c3..80a1f863fb3 100644 --- a/zig/src/families/deepseek_v41/metal/boot.zig +++ b/zig/src/families/deepseek_v41/metal/boot.zig @@ -8,6 +8,7 @@ const dspark = @import("dspark.zig"); const rope = @import("rope.zig"); const scratch = @import("scratch.zig"); const forward = @import("forward.zig"); +const round_prof = @import("round_prof.zig"); const serve = @import("serve.zig"); const target_ = @import("target.zig"); @@ -167,6 +168,7 @@ pub const Boot = struct { if (b.ds) |*w| w.deinit(); b.w.deinit(); b.p.deinit(); + round_prof.forget(); b.queue.deinit(); b.device.deinit(); b.a.destroy(b); diff --git a/zig/src/families/deepseek_v41/metal/metal.zig b/zig/src/families/deepseek_v41/metal/metal.zig index 619936fbf58..ec28981e711 100644 --- a/zig/src/families/deepseek_v41/metal/metal.zig +++ b/zig/src/families/deepseek_v41/metal/metal.zig @@ -17,6 +17,7 @@ pub const attn = @import("attn.zig"); pub const indexer = @import("indexer.zig"); pub const moe = @import("moe.zig"); pub const forward = @import("forward.zig"); +pub const round_prof = @import("round_prof.zig"); pub const prompt = @import("prompt.zig"); pub const prompt_layer = @import("prompt_layer.zig"); pub const prompt_scratch = @import("prompt_scratch.zig"); diff --git a/zig/src/families/deepseek_v41/metal/round_prof.zig b/zig/src/families/deepseek_v41/metal/round_prof.zig index 2b6843bb87c..6d215bd011c 100644 --- a/zig/src/families/deepseek_v41/metal/round_prof.zig +++ b/zig/src/families/deepseek_v41/metal/round_prof.zig @@ -30,6 +30,22 @@ pub fn end(t0: f64, rows: u32, first: mtl.CommandBuffer, last: mtl.CommandBuffer if (rounds % every == 0) log(); } +/// Reads and drops the pending round while its queue lives: an engine calls this before closing the queue. +pub fn forget() void { + if (pending) |p| gpu(p.rows, p.first, p.last); + pending = null; +} + +/// Whether a round's buffers wait to be read (tests). +pub fn holding() bool { + return pending != null; +} + +/// Turns the profiler on or off without the environment (tests). +pub fn force(on: bool) void { + state = if (on) .on else .off; +} + fn gpu(rows: u32, first: mtl.CommandBuffer, last: mtl.CommandBuffer) void { const s = &sums[@min(rows, sums.len - 1)]; const a = first.gpuTimes() orelse return; diff --git a/zig/src/metal/library.zig b/zig/src/metal/library.zig index 08ee88271ea..b5a11a6b3a4 100644 --- a/zig/src/metal/library.zig +++ b/zig/src/metal/library.zig @@ -1,6 +1,7 @@ //! Libraries (a build-time metallib, or source compiled at run time) and compute pipelines. const std = @import("std"); const objc = @import("objc.zig"); +const platform = @import("sys"); const types = @import("types.zig"); const Device = @import("device.zig").Device; @@ -8,6 +9,17 @@ const Id = objc.Id; pub const Error = error{ LibraryLoad, NoFunction, PipelineBuild }; +var timeline_on: std.atomic.Value(u8) = .init(2); + +/// TF_METAL4_TIMELINE set above 0, read once. +fn timelineOn() bool { + const v = timeline_on.load(.monotonic); + if (v != 2) return v == 1; + const on: u8 = @intFromBool((platform.environment.read(u32, "TF_METAL4_TIMELINE", 0) catch 0) > 0); + timeline_on.store(on, .monotonic); + return on == 1; +} + extern "c" fn dispatch_data_create(buffer: *const anyopaque, size: usize, queue: ?*anyopaque, destructor: ?*anyopaque) ?*anyopaque; extern "c" fn dispatch_release(object: *anyopaque) void; @@ -97,6 +109,11 @@ fn fail(comptime fmt: []const u8, what: anytype, err: ?Id) Error { pub const Pipeline = struct { id: Id, + /// Whether pipelines made from now on carry their kernel's name (tests reading the timeline set it on). + pub fn labels(on: bool) void { + timeline_on.store(@intFromBool(on), .monotonic); + } + /// The kernel `name` of `library`; `indirect` lets indirect command buffers use it. pub fn init(device: Device, library: Library, name: []const u8, indirect: bool) Error!Pipeline { return make(device, library, name, indirect, false); @@ -117,10 +134,12 @@ pub const Pipeline = struct { defer objc.release(desc); objc.msg(void, desc, "setComputeFunction:", .{func}); objc.msg(void, desc, "setSupportIndirectCommandBuffers:", .{indirect}); - // the kernel's name on the pipeline, for GPU captures and the Metal 4 timeline - const label = objc.string(name); - defer objc.release(label); - objc.msg(void, desc, "setLabel:", .{label}); + // the kernel's name on the pipeline, for the Metal 4 timeline only (TF_METAL4_TIMELINE): nothing else reads it + if (timelineOn()) { + const label = objc.string(name); + defer objc.release(label); + objc.msg(void, desc, "setLabel:", .{label}); + } const id = objc.msg(?Id, device.id, "newComputePipelineStateWithDescriptor:options:reflection:error:", .{ desc, @as(usize, 0), @as(?*anyopaque, null), &err }); return .{ .id = id orelse { if (optional) std.log.info("pipeline {s}: {s}", .{ name, objc.errorText(err) }) else std.log.err("pipeline {s}: {s}", .{ name, objc.errorText(err) }); diff --git a/zig/src/metal/metal4.zig b/zig/src/metal/metal4.zig index 35d107893a7..a9323ee5922 100644 --- a/zig/src/metal/metal4.zig +++ b/zig/src/metal/metal4.zig @@ -20,6 +20,9 @@ const max_pages = 32; const max_events = 4; /// Feedback kept a slot, by commit: a reader is never more than one commit behind. const history = 4; +/// How long a reader waits for a completed commit's feedback: spins, then naps of 10 us (2 s in all). +const spins = 4096; +const feedback_naps = 200_000; /// The Objective-C block ABI for the commit feedback handler: a global block, so nothing copies or frees it. const BlockDescriptor = extern struct { reserved: c_ulong, size: c_ulong, signature: [*:0]const u8 }; @@ -192,15 +195,29 @@ pub const Slot = struct { return .{ s.start[i], s.end[i] }; } - /// The text of a failure the queue has not reported yet: Metal 4 reports failures apart from command buffers. + /// A failure the queue has not reported yet; this use's own feedback (apart from its GPU event) is awaited first. pub fn failure(s: *Slot, use: u32) ?[*:0]const u8 { - _ = use; const q = s.q; + if (use == s.use and s.value != 0 and !s.fed(s.commits, feedback_naps)) return "metal 4: a command buffer's feedback never arrived"; if (q.failures.load(.acquire) == q.reported) return null; q.reported = q.failures.load(.acquire); return @ptrCast(&q.failure_text); } + /// Waits for commit `k`'s feedback: a short spin (it follows the GPU closely), then up to `naps` naps of 10 us. + fn fed(s: *const Slot, k: u32, naps: u32) bool { + var i: u32 = 0; + while (s.seen.load(.acquire) < k) : (i += 1) { + if (i < spins) { + std.atomic.spinLoopHint(); + continue; + } + if (i - spins >= naps) return false; + nap(10_000); + } + return true; + } + pub fn status(s: *Slot, use: u32) types.CommandBufferStatus { if (use != s.use) return .completed; if (s.value == 0) return if (s.open) .not_enqueued else .completed; @@ -491,14 +508,23 @@ pub const State = struct { /// Everything committed has run and reported; then the queue, its slots and its set go. pub fn close(q: *State) void { + _ = q.closeWithin(feedback_naps); + } + + /// As close with at most `naps` naps for owed feedback; while one is owed the State (its handlers' storage) stays. + pub fn closeWithin(q: *State, naps: u32) bool { for (®istry) |*r| if (r.cmpxchgStrong(q, null, .acq_rel, .acquire) == null) { _ = registered.fetchSub(1, .acq_rel); break; }; if (q.tick > 0) q.reach(q.tick); + var left = naps; + var owed = false; for (&q.slots) |*s| { - var tries: u32 = 0; - while (s.seen.load(.acquire) < s.commits and tries < 200_000) : (tries += 1) nap(10_000); + while (s.seen.load(.acquire) < s.commits and !owed) { + if (left == 0) owed = true else nap(10_000); + left -|= 1; + } if (s.open) objc.msg(void, s.cb, "endCommandBuffer", .{}); for (s.pages) |p| if (p) |pg| objc.release(pg.buf); for ([_]Id{ s.table, s.allocator, s.cb }) |id| objc.release(id); @@ -512,7 +538,12 @@ pub const State = struct { q.retired.deinit(heap); q.dropped.deinit(heap); q.table.load(.monotonic).deinit(); + if (owed) { + std.log.warn("metal 4: a command buffer's feedback was still owed at close; the queue's memory is kept for it", .{}); + return true; + } heap.destroy(q); + return false; } /// A round of named work: under TF_METAL4_TIMELINE some rounds of each name get a timestamp at every stage. diff --git a/zig/tests/dsv41_metal/metal4_test.zig b/zig/tests/dsv41_metal/metal4_test.zig index 4aecf6ecc41..3feb07f84b6 100644 --- a/zig/tests/dsv41_metal/metal4_test.zig +++ b/zig/tests/dsv41_metal/metal4_test.zig @@ -120,6 +120,8 @@ test "dsv41 metal: a prompt's chunks on a Metal 4 queue equal a Metal 3 queue's: test "dsv41 metal: timestamped decode rounds on Metal 4 change no bit, and their stages are summed" { const a = testing.allocator; + mtl.Pipeline.labels(true); // the timeline names stages by their pipelines' labels + defer mtl.Pipeline.labels(false); const f = try ff.Fwd.init(a, testing.io, limit, 74); defer f.deinit(); if (!f.r.device.hasMetal4()) return error.SkipZigTest; @@ -139,3 +141,49 @@ test "dsv41 metal: timestamped decode rounds on Metal 4 change no bit, and their try testing.expectEqual(@as(u32, 2), r.done); try testing.expect(r.encoders >= 1 and r.kernels.count() > 4 and r.inside > 0 and r.fits); } + +test "metal 4: a queue closed while a feedback is still owed keeps its memory; one with every feedback frees it" { + const a = testing.allocator; + const f = try ff.Fwd.init(a, testing.io, limit, 75); + defer f.deinit(); + if (!f.r.device.hasMetal4()) return error.SkipZigTest; + // every commit reported: freed + const done = mtl.metal4.State.open(f.r.device.id, 0) orelse return error.SkipZigTest; + const q1: mtl.Queue = .{ .id = done.queue, .m4 = done }; + const cb = q1.commandBuffer(); + cb.blit().end(); + cb.commit(); + cb.wait(); + try testing.expect(cb.failure() == null); + try testing.expect(!done.closeWithin(1000)); + // a commit whose feedback has not arrived (a late handler): the State stays, so the handler writes live memory + const late = mtl.metal4.State.open(f.r.device.id, 0) orelse return error.SkipZigTest; + late.slots[0].commits += 1; + try testing.expect(late.closeWithin(100)); + _ = late.slots[0].seen.fetchAdd(1, .release); // the late feedback lands on storage that is still there + std.debug.print("PASS metal 4 close: freed with every feedback in, kept with one owed\n", .{}); +} + +test "dsv41 metal: the round profiler reads and drops its pending round before the queue closes" { + const a = testing.allocator; + const f = try ff.Fwd.init(a, testing.io, limit, 76); + defer f.deinit(); + if (!f.r.device.hasMetal4()) return error.SkipZigTest; + const m4 = try f.r.device.queue4(); + var slot = try pkg.kv.Slot.init(a, f.r.device, &f.r.c, limit); + defer slot.deinit(); + fixture.fillPast(&f.r.c, &slot, 1101, 14); + pkg.round_prof.force(true); + defer pkg.round_prof.force(false); + const hist = try ff.ids(a, &f.r.c, look + 1, 77); + defer a.free(hist); + try fwd.prepare(&f.b, &f.r.c, hist[look..][0..1], ff.lookbackAt(hist, look, look), f.lookup()); + try f.r.s.writeRows(&f.r.c, 1101, 1); + const x = f.r.ctx(&slot, 1101, 1); + try fwd.run(&x, m4, f.model(), &f.b); + try testing.expect(pkg.round_prof.holding()); // Metal 4 reports GPU times later: the round waits to be read + pkg.round_prof.forget(); + try testing.expect(!pkg.round_prof.holding()); + m4.deinit(); + std.debug.print("PASS dsv41 metal round profiler: nothing pending once its queue closes\n", .{}); +} From d4e33d0a94a079b6d9b2be32f6c7c2ba965e023f Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:25:06 +0000 Subject: [PATCH 22/25] metal: Metal 4 compiled in only for a binary whose engines use it, and in tests A balanced 27B rerun on the native binary showed tiny but consistent losses against main under a rule fixed before the run. The Metal 4 path is now compiled in only where the program's root asks for it (the server's root reads the engines' `metal4`, which DeepSeek-V4.1's Metal entry sets) and in tests. Elsewhere the wrapper's calls go through inline accessors that are compile-time null, so the Metal 3 path carries no Metal 4 branch, a buffer's release no Metal 4 step (forget also sits behind a plain flag set when the first Metal 4 queue opens), queue4 is Unsupported and pipelines take no label. The native binary has none of the Metal 4 selectors; tensorfold-dsv41 keeps them. test-dsv41-metal still compares Metal 4 against Metal 3 bit for bit. --- zig/src/families/deepseek_v41/metal/entry.zig | 2 + zig/src/metal/command.zig | 92 +++++++++++-------- zig/src/metal/device.zig | 3 +- zig/src/metal/library.zig | 3 +- zig/src/metal/metal4.zig | 8 +- zig/src/server/engines.zig | 3 + zig/src/server/main.zig | 3 + 7 files changed, 75 insertions(+), 39 deletions(-) diff --git a/zig/src/families/deepseek_v41/metal/entry.zig b/zig/src/families/deepseek_v41/metal/entry.zig index 9053b6f8c7d..b244bb199fd 100644 --- a/zig/src/families/deepseek_v41/metal/entry.zig +++ b/zig/src/families/deepseek_v41/metal/entry.zig @@ -9,6 +9,8 @@ const env = @import("sys").environment; const Allocator = std.mem.Allocator; pub const backends: []const []const u8 = &.{"metal"}; +/// This family submits through Metal 4 (where the Mac has it): the server compiles the wrapper's Metal 4 path in. +pub const metal4 = true; pub const families: []const api.Family = &.{.{ .model_type = "deepseek_v41", .formats = &.{"fp8"}, .raw_text = false }}; pub fn chip(_: Allocator) ?[]const u8 { diff --git a/zig/src/metal/command.zig b/zig/src/metal/command.zig index 0587d5bc1a2..2ee2ac62449 100644 --- a/zig/src/metal/command.zig +++ b/zig/src/metal/command.zig @@ -17,19 +17,24 @@ pub const Queue = struct { id: Id, m4: ?*metal4.State = null, + /// The Metal 4 queue, a compile-time null where Metal 4 is not compiled in. + inline fn state(self: Queue) ?*metal4.State { + return if (comptime metal4.enabled) self.m4 else null; + } + pub fn deviceId(self: Queue) Id { return objc.msg(Id, self.id, "device", .{}); } /// A command buffer that retains what it references (autoreleased: keep a pool around it). pub fn commandBuffer(self: Queue) CommandBuffer { - if (self.m4) |q| return CommandBuffer.of(q.acquire()); + if (self.state()) |q| return CommandBuffer.of(q.acquire()); return .{ .id = objc.msg(Id, self.id, "commandBuffer", .{}) }; } /// A command buffer that does not retain its resources: the caller keeps them alive until it completes. pub fn commandBufferUnretained(self: Queue) CommandBuffer { - if (self.m4) |q| return CommandBuffer.of(q.acquire()); + if (self.state()) |q| return CommandBuffer.of(q.acquire()); return .{ .id = objc.msg(Id, self.id, "commandBufferWithUnretainedReferences", .{}) }; } @@ -43,22 +48,22 @@ pub const Queue = struct { } pub fn deinit(self: Queue) void { - if (self.m4) |q| return q.close(); + if (self.state()) |q| return q.close(); objc.release(self.id); } pub fn isMetal4(self: Queue) bool { - return self.m4 != null; + return self.state() != null; } /// Names a round of work for the Metal 4 timeline (TF_METAL4_TIMELINE); nothing on Metal 3. pub fn roundBegin(self: Queue, name: []const u8) void { - if (self.m4) |q| q.roundBegin(name); + if (self.state()) |q| q.roundBegin(name); } /// After the round's last wait. pub fn roundEnd(self: Queue) void { - if (self.m4) |q| q.roundEnd(); + if (self.state()) |q| q.roundEnd(); } }; @@ -68,41 +73,46 @@ pub const CommandBuffer = struct { /// the slot's use this handle names use: u32 = 0, + /// The Metal 4 slot, a compile-time null where Metal 4 is not compiled in. + inline fn slot(self: CommandBuffer) ?*metal4.Slot { + return if (comptime metal4.enabled) self.m4 else null; + } + fn of(s: *metal4.Slot) CommandBuffer { return .{ .id = s.cb, .m4 = s, .use = s.use }; } pub fn compute(self: CommandBuffer, dispatch: types.DispatchType) ComputeEncoder { - if (self.m4) |s| return .{ .id = s.compute(dispatch == .serial), .m4 = s }; + if (self.slot()) |s| return .{ .id = s.compute(dispatch == .serial), .m4 = s }; return .{ .id = objc.msg(Id, self.id, "computeCommandEncoderWithDispatchType:", .{@backingInt(dispatch)}) }; } /// A blit encoder on this buffer, for copies between buffers on the GPU. pub fn blit(self: CommandBuffer) BlitEncoder { - if (self.m4) |s| return .{ .id = s.blitEncoder(), .m4 = s }; + if (self.slot()) |s| return .{ .id = s.blitEncoder(), .m4 = s }; return .{ .id = objc.msg(Id, self.id, "blitCommandEncoder", .{}) }; } /// The GPU waits here until `event` reaches `value`. pub fn waitFor(self: CommandBuffer, event: SharedEvent, value: u64) void { - if (self.m4) |s| return s.waitEvent(event.id, value); + if (self.slot()) |s| return s.waitEvent(event.id, value); objc.msg(void, self.id, "encodeWaitForEvent:value:", .{ event.id, value }); } /// The GPU sets `event` to `value` once the work before this point completes. pub fn signal(self: CommandBuffer, event: SharedEvent, value: u64) void { - if (self.m4) |s| return s.signalEvent(event.id, value); + if (self.slot()) |s| return s.signalEvent(event.id, value); objc.msg(void, self.id, "encodeSignalEvent:value:", .{ event.id, value }); } /// waitFor and signal with a GPU-only event. pub fn waitForEvent(self: CommandBuffer, event: Event, value: u64) void { - if (self.m4) |s| return s.waitEvent(event.id, value); + if (self.slot()) |s| return s.waitEvent(event.id, value); objc.msg(void, self.id, "encodeWaitForEvent:value:", .{ event.id, value }); } pub fn signalEvent(self: CommandBuffer, event: Event, value: u64) void { - if (self.m4) |s| return s.signalEvent(event.id, value); + if (self.slot()) |s| return s.signalEvent(event.id, value); objc.msg(void, self.id, "encodeSignalEvent:value:", .{ event.id, value }); } @@ -112,25 +122,25 @@ pub const CommandBuffer = struct { pub fn commit(self: CommandBuffer) void { @import("pass_metrics.zig").commit(); - if (self.m4) |s| return s.commit(); + if (self.slot()) |s| return s.commit(); objc.msg(void, self.id, "commit", .{}); } pub fn wait(self: CommandBuffer) void { const metrics = @import("pass_metrics.zig"); const start = metrics.time(); - if (self.m4) |s| s.wait(self.use) else objc.msg(void, self.id, "waitUntilCompleted", .{}); + if (self.slot()) |s| s.wait(self.use) else objc.msg(void, self.id, "waitUntilCompleted", .{}); if (start != 0) metrics.wait(start, self.gpuSeconds()); } pub fn status(self: CommandBuffer) types.CommandBufferStatus { - if (self.m4) |s| return s.status(self.use); + if (self.slot()) |s| return s.status(self.use); return @fromBackingInt(@intCast(objc.msg(usize, self.id, "status", .{}))); } /// The error text when the command buffer failed, else null; on Metal 4, any failure on its queue not yet reported. pub fn failure(self: CommandBuffer) ?[*:0]const u8 { - if (self.m4) |s| return s.failure(self.use); + if (self.slot()) |s| return s.failure(self.use); if (self.status() != .@"error") return null; return objc.errorText(objc.msg(?Id, self.id, "error", .{})); } @@ -141,29 +151,29 @@ pub const CommandBuffer = struct { } pub fn gpuStart(self: CommandBuffer) f64 { - if (self.m4) |s| return if (s.times(self.use, true)) |t| t[0] else 0; + if (self.slot()) |s| return if (s.times(self.use, true)) |t| t[0] else 0; return objc.msg(f64, self.id, "GPUStartTime", .{}); } pub fn gpuEnd(self: CommandBuffer) f64 { - if (self.m4) |s| return if (s.times(self.use, true)) |t| t[1] else 0; + if (self.slot()) |s| return if (s.times(self.use, true)) |t| t[1] else 0; return objc.msg(f64, self.id, "GPUEndTime", .{}); } /// The GPU's start and end once reported, without waiting for the report (Metal 4), else null. pub fn gpuTimes(self: CommandBuffer) ?[2]f64 { - if (self.m4) |s| return s.times(self.use, false); + if (self.slot()) |s| return s.times(self.use, false); return .{ self.gpuStart(), self.gpuEnd() }; } /// Metal 4's command buffers belong to their queue's slots: retain and release do nothing there. pub fn retain(self: CommandBuffer) CommandBuffer { - if (self.m4 != null) return self; + if (self.slot() != null) return self; return .{ .id = objc.retain(self.id) }; } pub fn release(self: CommandBuffer) void { - if (self.m4 == null) objc.release(self.id); + if (self.slot() == null) objc.release(self.id); } }; @@ -172,13 +182,18 @@ pub const BlitEncoder = struct { id: Id, m4: ?*metal4.Slot = null, + /// The Metal 4 slot, a compile-time null where Metal 4 is not compiled in. + inline fn slot(self: BlitEncoder) ?*metal4.Slot { + return if (comptime metal4.enabled) self.m4 else null; + } + pub fn copy(self: BlitEncoder, from: Buffer, from_offset: usize, to: Buffer, to_offset: usize, size: usize) void { - if (self.m4) |s| return s.copy(self.id, from.id, from_offset, to.id, to_offset, size); + if (self.slot()) |s| return s.copy(self.id, from.id, from_offset, to.id, to_offset, size); objc.msg(void, self.id, "copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:", .{ from.id, from_offset, to.id, to_offset, size }); } pub fn fill(self: BlitEncoder, buffer: Buffer, offset: usize, size: usize, value: u8) void { - if (self.m4) |s| return s.fill(self.id, buffer.id, offset, size, value); + if (self.slot()) |s| return s.fill(self.id, buffer.id, offset, size, value); objc.msg(void, self.id, "fillBuffer:range:value:", .{ buffer.id, types.Range{ .location = offset, .length = size }, value }); } @@ -191,24 +206,29 @@ pub const ComputeEncoder = struct { id: Id, m4: ?*metal4.Slot = null, + /// The Metal 4 slot, a compile-time null where Metal 4 is not compiled in. + inline fn slot(self: ComputeEncoder) ?*metal4.Slot { + return if (comptime metal4.enabled) self.m4 else null; + } + pub fn deviceId(self: ComputeEncoder) Id { - if (self.m4) |s| return s.q.device; + if (self.slot()) |s| return s.q.device; return objc.msg(Id, self.id, "device", .{}); } pub fn setPipeline(self: ComputeEncoder, pipeline: Pipeline) void { objc.msg(void, self.id, "setComputePipelineState:", .{pipeline.id}); - if (self.m4) |s| s.pipeline(pipeline.id); + if (self.slot()) |s| s.pipeline(pipeline.id); } pub fn setBuffer(self: ComputeEncoder, buffer: Buffer, offset: usize, index: usize) void { - if (self.m4) |s| return s.bind(buffer.id, offset, index); + if (self.slot()) |s| return s.bind(buffer.id, offset, index); objc.msg(void, self.id, "setBuffer:offset:atIndex:", .{ buffer.id, offset, index }); } /// Small constants copied into the command stream (at most 4 KB); on Metal 4 into the slot's constants pages. pub fn setBytes(self: ComputeEncoder, bytes: []const u8, index: usize) void { - if (self.m4) |s| return s.bytes(bytes, index); + if (self.slot()) |s| return s.bytes(bytes, index); objc.msg(void, self.id, "setBytes:length:atIndex:", .{ bytes.ptr, bytes.len, index }); } @@ -223,30 +243,30 @@ pub const ComputeEncoder = struct { /// Whole threadgroups: `groups` of `threads` each. pub fn dispatchGroups(self: ComputeEncoder, groups: Size, threads: Size) void { objc.msg(void, self.id, "dispatchThreadgroups:threadsPerThreadgroup:", .{ groups, threads }); - if (self.m4) |s| s.dispatched(self.id); + if (self.slot()) |s| s.dispatched(self.id); } /// Whole threadgroups of `threads` each, their counts (3 u32) read from `args` at `offset` when the dispatch runs. pub fn dispatchIndirect(self: ComputeEncoder, args: Buffer, offset: usize, threads: Size) void { - if (self.m4) |s| return s.dispatchIndirect(self.id, args.id, offset, threads); + if (self.slot()) |s| return s.dispatchIndirect(self.id, args.id, offset, threads); objc.msg(void, self.id, "dispatchThreadgroupsWithIndirectBuffer:indirectBufferOffset:threadsPerThreadgroup:", .{ args.id, offset, threads }); } /// A grid of `grid` threads in groups of `threads` (edge groups may be partial), as MLX dispatches. pub fn dispatchThreads(self: ComputeEncoder, grid: Size, threads: Size) void { objc.msg(void, self.id, "dispatchThreads:threadsPerThreadgroup:", .{ grid, threads }); - if (self.m4) |s| s.dispatched(self.id); + if (self.slot()) |s| s.dispatched(self.id); } /// Later dispatches see every buffer write before this point (concurrent encoders). pub fn barrier(self: ComputeEncoder) void { - if (self.m4) |s| return s.barrier(self.id); + if (self.slot()) |s| return s.barrier(self.id); objc.msg(void, self.id, "memoryBarrierWithScope:", .{types.BarrierScope.buffers}); } /// Declare a resource used through indirect commands or argument buffers (on Metal 4: it joins the residency set). pub fn useResource(self: ComputeEncoder, buffer: Buffer, usage: usize) void { - if (self.m4) |s| { + if (self.slot()) |s| { _ = s.q.address(buffer.id); return; } @@ -255,23 +275,23 @@ pub const ComputeEncoder = struct { pub fn execute(self: ComputeEncoder, icb: IndirectCommandBuffer, first: usize, count: usize) void { objc.msg(void, self.id, "executeCommandsInBuffer:withRange:", .{ icb.id, types.Range{ .location = first, .length = count } }); - if (self.m4) |s| s.dispatched(self.id); + if (self.slot()) |s| s.dispatched(self.id); } pub fn end(self: ComputeEncoder) void { - if (self.m4) |s| s.ending(self.id); + if (self.slot()) |s| s.ending(self.id); objc.msg(void, self.id, "endEncoding", .{}); } /// The command buffer this encoder was opened from, for the event ops a seam encodes BETWEEN encoders. pub fn commandBuffer(self: ComputeEncoder) CommandBuffer { - if (self.m4) |s| return CommandBuffer.of(s); + if (self.slot()) |s| return CommandBuffer.of(s); return .{ .id = objc.msg(Id, self.id, "commandBuffer", .{}) }; } /// Whether this encoder dispatches serially or concurrently: a seam reopens it in the same mode. pub fn dispatchType(self: ComputeEncoder) types.DispatchType { - if (self.m4) |s| return if (s.serial) .serial else .concurrent; + if (self.slot()) |s| return if (s.serial) .serial else .concurrent; return @fromBackingInt(@intCast(objc.msg(usize, self.id, "dispatchType", .{}))); } }; diff --git a/zig/src/metal/device.zig b/zig/src/metal/device.zig index 0a54054999f..b0504d4537c 100644 --- a/zig/src/metal/device.zig +++ b/zig/src/metal/device.zig @@ -39,7 +39,7 @@ pub const Buffer = struct { } pub fn deinit(self: Buffer) void { - metal4.forget(self.id); + if (comptime metal4.enabled) metal4.forget(self.id); objc.release(self.id); } }; @@ -100,6 +100,7 @@ pub const Device = struct { /// A queue taking `queue`'s calls through Metal 4, or error.Unsupported; TF_METAL4_TIMELINE=n stamps n rounds. pub fn queue4(self: Device) Error!command.Queue { + if (comptime !metal4.enabled) return error.Unsupported; if (!self.hasMetal4()) return error.Unsupported; const rounds = platform.environment.read(u32, "TF_METAL4_TIMELINE", 0) catch 0; const q = metal4.State.open(self.id, rounds) orelse return error.Unsupported; diff --git a/zig/src/metal/library.zig b/zig/src/metal/library.zig index b5a11a6b3a4..90cfe238cfa 100644 --- a/zig/src/metal/library.zig +++ b/zig/src/metal/library.zig @@ -2,6 +2,7 @@ const std = @import("std"); const objc = @import("objc.zig"); const platform = @import("sys"); +const metal4 = @import("metal4.zig"); const types = @import("types.zig"); const Device = @import("device.zig").Device; @@ -135,7 +136,7 @@ pub const Pipeline = struct { objc.msg(void, desc, "setComputeFunction:", .{func}); objc.msg(void, desc, "setSupportIndirectCommandBuffers:", .{indirect}); // the kernel's name on the pipeline, for the Metal 4 timeline only (TF_METAL4_TIMELINE): nothing else reads it - if (timelineOn()) { + if (metal4.enabled and timelineOn()) { const label = objc.string(name); defer objc.release(label); objc.msg(void, desc, "setLabel:", .{label}); diff --git a/zig/src/metal/metal4.zig b/zig/src/metal/metal4.zig index a9323ee5922..91fe3eda409 100644 --- a/zig/src/metal/metal4.zig +++ b/zig/src/metal/metal4.zig @@ -8,6 +8,9 @@ const Timeline = @import("metal4_timeline.zig").Timeline; const Id = objc.Id; const heap = std.heap.c_allocator; +/// In only where the root declares `tf_metal4 = true` (the DeepSeek server) and in tests; elsewhere compiled out. +pub const enabled = @import("builtin").is_test or (@hasDecl(@import("root"), "tf_metal4") and @import("root").tf_metal4); + pub const stage_dispatch: usize = 1 << 27; pub const stage_blit: usize = 1 << 28; const queue_stages = stage_dispatch | stage_blit; @@ -291,10 +294,12 @@ const Table = struct { /// Queues whose buffers Buffer.deinit must hand back. var registry: [8]std.atomic.Value(?*State) = @splat(.init(null)); var registered: std.atomic.Value(u32) = .init(0); +/// Set when the first Metal 4 queue opens (never cleared): until then a buffer's release skips the registry. +var any_queue: bool = false; /// A buffer's owner let it go: queues that bound it release it from their sets once their work in flight is done. pub fn forget(buffer: Id) void { - if (registered.load(.acquire) == 0) return; + if (!any_queue or registered.load(.acquire) == 0) return; for (®istry) |*r| if (r.load(.acquire)) |q| q.drop(buffer); } @@ -353,6 +358,7 @@ pub const State = struct { if (timeline_rounds > 0) q.timeline = Timeline.init(device, timeline_rounds); for (®istry) |*r| if (r.cmpxchgStrong(null, q, .acq_rel, .acquire) == null) { _ = registered.fetchAdd(1, .acq_rel); + any_queue = true; break; }; return q; diff --git a/zig/src/server/engines.zig b/zig/src/server/engines.zig index dca07818f41..7aa4f7f8f57 100644 --- a/zig/src/server/engines.zig +++ b/zig/src/server/engines.zig @@ -25,6 +25,9 @@ pub fn environment(a: Allocator, args: cli.Args) !?[]const u8 { /// The serve flags past the common ones the backend lists (tensor parallelism, MTP, kept entries, policy). pub const serves: []const []const u8 = if (@hasDecl(native, "serves")) native.serves else &.{}; +/// Whether this binary's engines use Metal 4 (the DeepSeek server's do): the Metal wrapper compiles it in only then. +pub const metal4: bool = @hasDecl(native, "metal4") and native.metal4; + /// The backend's std options when it has any (HIP: no alternate signal stack for RCCL's threads); else the defaults. pub const std_options: std.Options = @import("std_options.zig").of(native); diff --git a/zig/src/server/main.zig b/zig/src/server/main.zig index 4cc71962897..239e84dbe09 100644 --- a/zig/src/server/main.zig +++ b/zig/src/server/main.zig @@ -53,6 +53,9 @@ pub const serves = engines.serves; pub const std_options = engines.std_options; +/// Read by the Metal wrapper at compile time: Metal 4 only in a binary whose engines use it. +pub const tf_metal4 = engines.metal4; + pub fn main(init: std.process.Init) !u8 { const entry = std.Io.Clock.awake.now(init.io).toNanoseconds(); const gpa = init.gpa; From 22ef341a27cd9182514cef529c0776e133a82a70 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:24:50 +0000 Subject: [PATCH 23/25] changelog: #3374 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5688c595b5c..048e5828eb8 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 +- DeepSeek-V4.1 on Metal: its GPU work goes through a Metal 4 command queue by default where the Mac has one (macOS 26 and later), with the same kernels in the same order and bit-identical outputs; `TF_METAL4=0` keeps Metal 3, `TF_METAL4_TIMELINE=n` logs per-stage GPU times for n rounds of each kind, and `TF_DSV41_ROUND_PROF=1` logs decode rounds' host and GPU milliseconds (#3374). + - Flash Next on HIP: the verify window holds eight rows instead of four, so a stream alone in a round can land copy drafts of up to seven tokens a round; rounds shared by several streams keep three-token copies, MTP still drafts at most three, and each stream's window snapshots take more device memory, which admission counts (#2730). Thanks to @gilby. - OCR: the native HIP engine reads documents through `POST /v1/ocr` in Mistral's OCR contract (its Python and TypeScript SDKs), with dots.mocr's reader (a box for each layout block). Images and PDFs (`--vision-pdf`) share one page budget per request (`TENSORFOLD_MAX_PDF_PAGES`, default 16), each PDF measured before any inference and each page rendered just before it is read, and Mistral crops share one image budget (256 images, 4 times the page pixels, 16 MiB plus 2 MiB a page). An option that changes content and that TensorFold cannot apply, such as annotations, is refused. A page cut at the context limit or out of its model's format fails the whole request with HTTP 422; `docs/api.md` lists the contract's fields, statuses and limits (#2570, #2571, #2440). Thanks to @laudney. From 0d172c62a748a969b1a387d09f41249a4d43e773 Mon Sep 17 00:00:00 2001 From: gilby Date: Sun, 15 Nov 2026 08:34:39 +0100 Subject: [PATCH 24/25] flashnext hip: the chunk fallback measures room after the window plan slots --- zig/src/families/flashnext/hip/engine.zig | 32 ++++++++++++++++------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/zig/src/families/flashnext/hip/engine.zig b/zig/src/families/flashnext/hip/engine.zig index e36b0924a28..e4cf3866bef 100644 --- a/zig/src/families/flashnext/hip/engine.zig +++ b/zig/src/families/flashnext/hip/engine.zig @@ -32,9 +32,9 @@ pub const Options = struct { want: usize = 1, }; -/// Whether the smaller chunk's scratch admits more of `want` streams of `per` bytes in `room` than the larger's. -pub fn narrows(room: u64, larger: u64, smaller: u64, per: u64, want: u64) bool { - return @min(want, (room -| smaller) / per) > @min(want, (room -| larger) / per); +/// Whether the smaller chunk admits more of `want` streams than the larger's in `room`, after the `slots` bytes. +pub fn narrows(room: u64, slots: u64, larger: u64, smaller: u64, per: u64, want: u64) bool { + return @min(want, (room -| slots -| smaller) / per) > @min(want, (room -| slots -| larger) / per); } /// Bytes of the pinned staging a forward's uploads and n-gram rows go through. @@ -280,10 +280,14 @@ pub const Engine = struct { if (small >= e.o.chunk) return larger; const pool = try hip.admission.budget(e.gpa, e.io, e.ctx); const room = pool.room(hip.usage(false).device); + const slots: u64 = if (gdn.supported(e.weights.model.dims, e.cfg.layers)) + @intCast(gdn.Slots.bytes(e.weights.model.dims, @max(e.o.want, 1))) + else + 0; const asked = e.o.chunk; e.o.chunk = small; const smaller = try e.scratchBytes(); - if (!narrows(room, larger, smaller, e.streamBytes(e.o.capacity), e.o.want)) { + if (!narrows(room, slots, larger, smaller, e.streamBytes(e.o.capacity), e.o.want)) { e.o.chunk = asked; return larger; } @@ -527,13 +531,23 @@ fn weightMapOf(a: std.mem.Allocator, io: std.Io, dir: []const u8) !std.json.Obje test "a chunk narrows only when its scratch costs a stream the server asked for" { const gib: u64 = 1 << 30; // one stream asked, room for many either way: the larger chunk stays - try std.testing.expect(!narrows(40 * gib, 7 * gib, 2 * gib, 3 * gib, 1)); + try std.testing.expect(!narrows(40 * gib, 0, 7 * gib, 2 * gib, 3 * gib, 1)); // one stream fits only beside the smaller chunk's scratch - try std.testing.expect(narrows(9 * gib, 7 * gib, 2 * gib, 4 * gib, 1)); + try std.testing.expect(narrows(9 * gib, 0, 7 * gib, 2 * gib, 4 * gib, 1)); // four asked: the larger chunk leaves three, the smaller four - try std.testing.expect(narrows(20 * gib, 7 * gib, 2 * gib, 4 * gib, 4)); + try std.testing.expect(narrows(20 * gib, 0, 7 * gib, 2 * gib, 4 * gib, 4)); // four asked and four fit beside either - try std.testing.expect(!narrows(30 * gib, 7 * gib, 2 * gib, 4 * gib, 4)); + try std.testing.expect(!narrows(30 * gib, 0, 7 * gib, 2 * gib, 4 * gib, 4)); // neither fits one: nothing to gain - try std.testing.expect(!narrows(3 * gib, 7 * gib, 2 * gib, 4 * gib, 1)); + try std.testing.expect(!narrows(3 * gib, 0, 7 * gib, 2 * gib, 4 * gib, 1)); +} + +test "the chunk fallback leaves the window plan slots' bytes off the room" { + const gib: u64 = 1 << 30; + // one stream fits beside either chunk's scratch: the larger stays + try std.testing.expect(!narrows(13 * gib, 0, 7 * gib, 2 * gib, 4 * gib, 1)); + // the same room with the slots' bytes off it: one stream fits only beside the smaller chunk's scratch + try std.testing.expect(narrows(13 * gib, 4 * gib, 7 * gib, 2 * gib, 4 * gib, 1)); + // the room was already tight for four with no slots: the subtraction stays a narrowing + try std.testing.expect(narrows(20 * gib, 4 * gib, 7 * gib, 2 * gib, 4 * gib, 4)); } From ef059a506ed775c6220376c4796859a09c1c6542 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:24:52 +0000 Subject: [PATCH 25/25] changelog: #3419 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 048e5828eb8..ddf52ee9ca6 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 +- Flash Next on HIP: the prompt chunk fallback counts the window plan's slot bytes as used before deciding whether a smaller chunk admits more streams, where it counted them as free and could keep the larger chunk (#3419). Thanks to @gilby. + - DeepSeek-V4.1 on Metal: its GPU work goes through a Metal 4 command queue by default where the Mac has one (macOS 26 and later), with the same kernels in the same order and bit-identical outputs; `TF_METAL4=0` keeps Metal 3, `TF_METAL4_TIMELINE=n` logs per-stage GPU times for n rounds of each kind, and `TF_DSV41_ROUND_PROF=1` logs decode rounds' host and GPU milliseconds (#3374). - Flash Next on HIP: the verify window holds eight rows instead of four, so a stream alone in a round can land copy drafts of up to seven tokens a round; rounds shared by several streams keep three-token copies, MTP still drafts at most three, and each stream's window snapshots take more device memory, which admission counts (#2730). Thanks to @gilby.