Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
c213141
feat(server): measure and render selected PDF pages per call
laudney Nov 13, 2026
018d904
feat(ocr): read PDF documents and pages on POST /v1/ocr
laudney Nov 13, 2026
9096e89
docs(ocr): document PDF documents and pages on POST /v1/ocr
laudney Nov 13, 2026
1ea013c
changelog: #2571 under Unreleased
ashhart Nov 19, 2026
b84ad64
flashnext hip: a verify window holds eight rows, so a copy lands up t…
gilby Nov 10, 2026
9a9975c
flashnext hip: shared rounds keep three-token copies; a lone stream's…
gilby Nov 10, 2026
41ca621
changelog: the HIP Flash Next eight-row window under Unreleased
gilby Nov 10, 2026
56c78e4
flashnext hip: a host test drives the facts' copy widths through the …
gilby Nov 10, 2026
f8dd5d1
changelog: the eight-row window's line ends with its number and the t…
gilby Nov 10, 2026
ac9591c
flashnext hip: the MTP head's three-draft cap is a named constant the…
gilby Nov 10, 2026
18d1478
native hip: a host test refuses --mtp-drafts 4 by name, so the head's…
gilby Nov 12, 2026
8c52ce5
changelog: #2730's line once, under Unreleased (rebase onto main)
ashhart Nov 13, 2026
431f7a4
flashnext hip: the MTP draft cap lives in facts.zig, so lanes.zig sta…
ashhart Nov 13, 2026
052577b
flashnext hip: one refusal test for --drafter and --mtp-drafts, so hi…
ashhart Nov 14, 2026
c84f088
flashnext hip: preserve drafting facts and leave #2730 changelog to l…
ashhart Nov 19, 2026
52792e9
changelog: #2730 under Unreleased
ashhart Nov 19, 2026
1c8c8da
metal: a Metal 4 backend under the queue, command buffer and encoder …
ashhart Nov 14, 2026
a09abfa
dsv41 metal: TF_METAL4=1 runs the family on a Metal 4 queue, decode r…
ashhart Nov 14, 2026
d52b7aa
dsv41 metal: Metal 4 by default where the Mac has it, TF_METAL4=0 kee…
ashhart Nov 14, 2026
009de59
changelog: #3374's line names its PR
ashhart Nov 14, 2026
7cce8ce
metal 4: a closing queue keeps its memory while a feedback is owed, a…
ashhart Nov 14, 2026
d4e33d0
metal: Metal 4 compiled in only for a binary whose engines use it, an…
ashhart Nov 15, 2026
22ef341
changelog: #3374 under Unreleased
ashhart Nov 19, 2026
0d172c6
flashnext hip: the chunk fallback measures room after the window plan…
gilby Nov 15, 2026
ef059a5
changelog: #3419 under Unreleased
ashhart Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- Flash Next on HIP: the prompt chunk fallback counts the window plan's slot bytes as used before deciding whether a smaller chunk admits more streams, where it counted them as free and could keep the larger chunk (#3419). Thanks to @gilby.

- DeepSeek-V4.1 on Metal: its GPU work goes through a Metal 4 command queue by default where the Mac has one (macOS 26 and later), with the same kernels in the same order and bit-identical outputs; `TF_METAL4=0` keeps Metal 3, `TF_METAL4_TIMELINE=n` logs per-stage GPU times for n rounds of each kind, and `TF_DSV41_ROUND_PROF=1` logs decode rounds' host and GPU milliseconds (#3374).

- Flash Next on HIP: the verify window holds eight rows instead of four, so a stream alone in a round can land copy drafts of up to seven tokens a round; rounds shared by several streams keep three-token copies, MTP still drafts at most three, and each stream's window snapshots take more device memory, which admission counts (#2730). Thanks to @gilby.

- OCR: the native HIP engine reads documents through `POST /v1/ocr` in Mistral's OCR contract (its Python and TypeScript SDKs), with dots.mocr's reader (a box for each layout block). Images and PDFs (`--vision-pdf`) share one page budget per request (`TENSORFOLD_MAX_PDF_PAGES`, default 16), each PDF measured before any inference and each page rendered just before it is read, and Mistral crops share one image budget (256 images, 4 times the page pixels, 16 MiB plus 2 MiB a page). An option that changes content and that TensorFold cannot apply, such as annotations, is refused. A page cut at the context limit or out of its model's format fails the whole request with HTTP 422; `docs/api.md` lists the contract's fields, statuses and limits (#2570, #2571, #2440). Thanks to @laudney.

- Core prompt cache: the radix store can keep a checkpoint inside a page as a writable tail, a store-held copy of that page's rows that is never written again; no family turns tails on yet, so every current store behaves as before (#3329, part of #2444). Thanks to @laudney.

- CUDA: on a GB10, the one-launch path for two to four affine-4 prompt projections (`tf_qmm_prefill_many`) works out each thread's copy addresses once, before the K loop, instead of at every stage; the copies, their order and the math are unchanged (#2825). Thanks to @GumbiiDigital.
Expand Down
42 changes: 24 additions & 18 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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 |
Expand All @@ -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

Expand Down
3 changes: 3 additions & 0 deletions docs/environment.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
14 changes: 13 additions & 1 deletion zig/src/families/deepseek_v41/metal/boot.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const dspark = @import("dspark.zig");
const rope = @import("rope.zig");
const scratch = @import("scratch.zig");
const forward = @import("forward.zig");
const round_prof = @import("round_prof.zig");
const serve = @import("serve.zig");
const target_ = @import("target.zig");

Expand Down Expand Up @@ -36,6 +37,16 @@ pub const Options = struct {
decode_share: ?f64 = null,
};

/// 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,
Expand Down Expand Up @@ -65,7 +76,7 @@ pub const Boot = struct {
const limit: u32 = @intCast(@min(o.context orelse 262144, c.rope.max_positions));
b.device = try mtl.Device.init();
errdefer b.device.deinit();
b.queue = try b.device.queue();
b.queue = try openQueue(b.device, b.device.hasMetal4());
errdefer b.queue.deinit();
b.p = try pipelines.Pipelines.load(a, b.device, c);
errdefer b.p.deinit();
Expand Down Expand Up @@ -157,6 +168,7 @@ pub const Boot = struct {
if (b.ds) |*w| w.deinit();
b.w.deinit();
b.p.deinit();
round_prof.forget();
b.queue.deinit();
b.device.deinit();
b.a.destroy(b);
Expand Down
2 changes: 2 additions & 0 deletions zig/src/families/deepseek_v41/metal/entry.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
6 changes: 6 additions & 0 deletions zig/src/families/deepseek_v41/metal/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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;
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/deepseek_v41/metal/metal.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
66 changes: 66 additions & 0 deletions zig/src/families/deepseek_v41/metal/round_prof.zig
Original file line number Diff line number Diff line change
@@ -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() });
}
17 changes: 15 additions & 2 deletions zig/src/families/flashnext/hip/cache.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down Expand Up @@ -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());
}
Loading