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