Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

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

## Unreleased

- OCR: `POST /ocr` now answers LiteParse's OCR server contract, with one text item per line and its box in page pixels (#2573). Thanks @laudney.

- H3 on Metal: transformer products run on the `h3_gemm_32x64` kernel in 64-row bands and the decoder decodes 64 tiles a pass, with sums unchanged (#4641).

- Hy4-flash: host-side weight map, TP=1/2/4 partition and Engram FP8 row codec for the official W8A16 FP8 checkpoint, with refusal tests; serving follows in later PRs (#4827). Thanks @GrgaPalcic.
Expand Down
66 changes: 52 additions & 14 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ different scopes, or scopes a key the flags or environment already give, is refu

| Scope | Routes |
| --- | --- |
| `inference` | POST `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/tokenize`, `/v1/detokenize`, `/v1/apply-template`, `/v1/audio/speech`, `/v1/images/generations`, `/v1/embeddings`, `/v1/decisions`, `/v1/systemone`, `/score`, `/v1/score`, `/v2/rerank`, `/v1/rerank` (also by PUT), `/v1/ocr`, and the same paths without `/v1` where the server has them; GET `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices`; a WebSocket upgrade on GET `/v1/responses` or `/responses` |
| `inference` | POST `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/tokenize`, `/v1/detokenize`, `/v1/apply-template`, `/v1/audio/speech`, `/v1/images/generations`, `/v1/embeddings`, `/v1/decisions`, `/v1/systemone`, `/score`, `/v1/score`, `/v2/rerank`, `/v1/rerank` (also by PUT), `/v1/ocr`, `/ocr`, and the same paths without `/v1` where the server has them; GET `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices`; a WebSocket upgrade on GET `/v1/responses` or `/responses` |
| `read` | GET `/metrics`, `/v1/metrics`, `/v1/load`, `/memory`, `/v1/memory`, `/stats`, `/dashboard`, `/v1/benchmark/manifest`, `/v1/execution/witness`, `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices` |

A scoped key reaches nothing else: not the stored Responses (GET or DELETE `/v1/responses/ID`), Recall, Sliding Weights,
Expand Down Expand Up @@ -275,12 +275,13 @@ context-window check still applies. Cohere-style requests retain the reranker's

## OCR

The native HIP engine reads pages through Mistral's OCR contract when it serves a model with an OCR reader
and `--vision`.
The native HIP engine reads pages through two OCR contracts when it serves a model with an OCR reader and
`--vision`. One route answers Mistral's contract; `/ocr` (and `/ocr/`) answers LiteParse's.

| Route | Contract | Request | Reply | Written for |
| --- | --- | --- | --- | --- |
| `POST /v1/ocr` | Mistral OCR | JSON `{"model", "document", ...}` | `{"pages", "model", "document_annotation", "usage_info"}` | the `mistralai` Python and `@mistralai/mistralai` TypeScript SDKs, with `server_url` set to the server root |
| `POST /ocr` | LiteParse HTTP OCR | multipart, one `file` part | `{"results": [...]}` | `lit parse --ocr-server-url http://HOST:PORT/ocr` |

Two families have a reader. A reader gives Markdown blocks in pixels of the page the client sent (after EXIF
orientation), never in the model's resized frame.
Expand All @@ -290,10 +291,23 @@ orientation), never in the model's resized frame.
| dots.mocr | one block a layout region (title, text, table, formula, picture, header, footer, ...), tables as pipe tables or, when cells span, HTML | a box a block |
| GLM-OCR | the page's Markdown as one block, tables as pipe tables or spanned HTML | none |

Any other model answers the route with HTTP 400 "this model has no OCR reader; use POST /v1/chat/completions",
Any other model answers both routes with HTTP 400 "this model has no OCR reader; use POST /v1/chat/completions",
and a server started without `--vision` answers "OCR needs image input; start the server with --vision".
Embedding, reranker and readout engines refuse the OCR route as they refuse chat. The route takes the `inference`
key scope.
Embedding, reranker and readout engines refuse the OCR routes as they refuse chat. The routes take the
`inference` key scope.

`POST /ocr` picks its contract in this order:

1. `?format=liteparse`. A query parameter sent twice is HTTP 400 ("the format query parameter is repeated; send
it once"), because servers differ on which copy wins.
2. `multipart/form-data`: exactly one part named `file` is LiteParse; any other set of parts is HTTP 400, and so
is a body with any `files` part ("a multipart OCR request has files parts, which this server does not read;
LiteParse sends one file part"), even when `?format=` names the contract.
3. Any other content type, or none, is HTTP 415.

Refusals made before the contract is known (415, those 400s, a drain's 503 and an admission 429 with
`Retry-After`) use the server's `{"error": {"message", "type"}}` envelope. On a model without a reader, or a
server without `--vision`, a request no contract takes gets the 400 above instead of its 415 or 400.

### Reader Markdown

Expand All @@ -304,7 +318,7 @@ Both readers write block text in one Markdown flavour, the one Mistral's page Ma
block holds exactly one table.
- Display math as `$$…$$` and inline math as `$…$`, the LaTeX kept as the model wrote it.
- Lists with `-` or `1.` markers, and code in fenced blocks.
- No images: a picture block has empty text, and its caption, if any, is its own block. The contract writes its
- No images: a picture block has empty text, and its caption, if any, is its own block. Each contract writes its
own image references.
- GLM-OCR's single block holds the whole page's Markdown, headings, tables and math included.

Expand Down Expand Up @@ -335,19 +349,29 @@ 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, 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, out of memory, PDF renderer crash or deadline | 500 |
| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` |
| Failure | Mistral | LiteParse |
| --- | --- | --- |
| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | 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 | 422 |
| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | 503, `Retry-After: 1` |
| Engine fault, out of memory, PDF renderer crash or deadline | 500 | 500 |
| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | `{"error": "..."}` |

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.

### Estimates

dots.mocr gives one box a block and GLM-OCR none, so LiteParse's lines estimate what the models do not give:

- **Lines.** A block's plain-text lines (Markdown markup removed, a table one line a row with tab-separated
cells, math without its `$`) divide the block's box into equal bands along its left and right edges, first
line at the top. A paragraph written without line breaks stays one line covering the block.
- **Scores.** Every score is `1.0`: LiteParse `confidence`. Mistral replies leave `confidence_scores` out.
- **No geometry.** With GLM-OCR, Mistral returns `blocks: []` and LiteParse is refused.

### Mistral: `POST /v1/ocr`

| Field | Meaning |
Expand All @@ -370,6 +394,20 @@ stops the request before its next page or PDF render.
`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.

### LiteParse: `POST /ocr`

The contract is LiteParse's published
[OCR API specification](https://github.com/run-llama/liteparse/blob/main/OCR_API_SPEC.md). One `file` part holds a PNG,
JPEG or WebP page image; `language` and other parts are ignored, but a `files` part is HTTP 400 (above). A PDF is
HTTP 400: the specification sends an image.
Each line is one result `{"text", "bbox", "confidence"}`: `bbox` is the line's axis-aligned `[x1, y1, x2, y2]` in
pixels of the image received, and `confidence` is `1.0`, the value the specification asks for when the engine gives
none. The specification's optional `polygon` is not sent: it gives the point order, but not how LiteParse turns a
polygon into a text rotation, so a rotated line is sent as its axis-aligned box. GLM-OCR gives no boxes, so
LiteParse requests to it are HTTP 400 "this model gives no text boxes; LiteParse needs them". With dots.mocr a
paragraph written without line breaks is one result covering its block. Errors use the specification's
`{"error": "..."}` body.

### GLM-OCR context

GLM-OCR's default 8192-token window leaves about 2000 tokens for the reply after a full image budget (6144
Expand Down
2 changes: 1 addition & 1 deletion zig/src/core/engine_api.zig
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ pub const Info = struct {
pictures: bool = false,
/// Image input (--vision); null: text only.
vision: ?Vision = null,
ocr: ?ocr.Ocr = null, // OCR reader for /v1/ocr; null: no OCR route
ocr: ?ocr.Ocr = null, // OCR reader for /v1/ocr and /ocr; null: no OCR routes
/// The engine decodes greedily only: the server refuses a request with a temperature before admitting it.
greedy_only: bool = false,
/// The learner reads conversation prompts at any length through taps.
Expand Down
24 changes: 24 additions & 0 deletions zig/src/core/ocr_html.zig
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,30 @@ pub fn normalized(a: Allocator, t: Table) Allocator.Error![]const u8 {
return out.toOwnedSlice(a);
}

/// One line a grid row, its cells joined by '\t'; a spanned cell's text at its top-left only, trailing cells kept.
pub fn rowsText(a: Allocator, t: Table) Allocator.Error![][]const u8 {
const lines = try a.alloc([]const u8, t.rows);
var done: usize = 0;
errdefer {
for (lines[0..done]) |l| a.free(l);
a.free(lines);
}
var line: std.ArrayList(u8) = .empty;
defer line.deinit(a);
var k: usize = 0;
for (lines, 0..) |*l, r| {
line.clearRetainingCapacity();
for (0..t.cols) |c| {
if (c > 0) try line.append(a, '\t');
const text = if (topLeft(t, &k, r, c)) |cell| cell.text else "";
for (text) |ch| try line.append(a, if (ch == '\n') ' ' else ch);
}
l.* = try a.dupe(u8, line.items);
done += 1;
}
return lines;
}

/// A cell's text in a pipe row: math as written (only `|` escaped), markup escaped elsewhere, to read back literally.
fn cellText(a: Allocator, out: *std.ArrayList(u8), text: []const u8) Allocator.Error!void {
var no_close = false; // a `$` found no closer, so no later `$` in the cell can (markdown.zig's rule)
Expand Down
21 changes: 19 additions & 2 deletions zig/src/core/ocr_html_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ fn expectCell(got: html.Cell, text: []const u8, row: u32, col: u32, rows: u32, c
try t.expectEqualDeep(want, got);
}

fn expectRows(a: std.mem.Allocator, table: html.Table, want: []const []const u8) !void {
const got = try html.rowsText(a, table);
try t.expectEqual(want.len, got.len);
for (want, got) |w, g| try t.expectEqualStrings(w, g);
}

test "ocr html: the dots.mocr table keeps its spans" {
var arena = std.heap.ArenaAllocator.init(t.allocator);
defer arena.deinit();
Expand All @@ -34,6 +40,12 @@ test "ocr html: the dots.mocr table keeps its spans" {
try t.expectEqualDeep(nhl, table.cells[3]);
try expectCell(table.cells[4], "Cases", 1, 2, 1, 1, true);
try t.expect(!table.cells[10].head);
try expectRows(a, table, &.{
"\tControls\tHodgkin lymphoma\t\t\tNon-Hodgkin lymphoma\t\t",
"\t\tCases\tOR\t95% CI\tCases\tOR\t95% CI",
"Never Exposed (reference group)\t2,273\t315\t1.00\t—\t1,823\t1.00\t—",
">1 year\t90\t7\t0.84\t0.37-1.91\t86\t1.17\t0.87-1.59",
});
}

test "ocr html: the GLM-OCR table has no header row and becomes a pipe table with its first row the header" {
Expand Down Expand Up @@ -73,14 +85,15 @@ test "ocr html: other tags drop and keep their text; names and attributes in any
try expectCell(table.cells[2], "y", 1, 1, 1, 2, false);
}

test "ocr html: <br> is a line break in the cell and a space in pipe cells" {
test "ocr html: <br> is a line break in the cell and a space in pipe cells and text rows" {
var arena = std.heap.ArenaAllocator.init(t.allocator);
defer arena.deinit();
const a = arena.allocator();
const src = "<table><tr><td><br>line one<br>line two <br/>\n three <BR /> </td><td>b</td></tr></table>";
const table = try html.parse(a, src);
try t.expectEqualStrings("line one\nline two\nthree", table.cells[0].text);
try t.expectEqualStrings("| line one line two three | b |\n| --- | --- |", try html.pipe(a, table));
try expectRows(a, table, &.{"line one line two three\tb"});
const clean = "<table><tr><td>line one<br>line two<br>three</td><td>b</td></tr></table>";
try t.expectEqualStrings(clean, try html.normalized(a, table));
}
Expand Down Expand Up @@ -179,14 +192,15 @@ test "ocr html: spans clip to the grid and to columns earlier rows cover" {
try t.expect(!lone.spanned and lone.rows == 1 and lone.cols == 1);
}

test "ocr html: pipe rows place a spanned cell's text once and keep trailing cells" {
test "ocr html: text rows place a spanned cell's text once and keep trailing cells" {
var arena = std.heap.ArenaAllocator.init(t.allocator);
defer arena.deinit();
const a = arena.allocator();
const src = "<table><tr><td rowspan=\"2\">A</td><td colspan=\"2\">B</td></tr><tr><td>c</td><td>d</td></tr>" ++
"<tr><td>e</td></tr></table>";
const table = try html.parse(a, src);
try t.expectEqual(@as(u32, 3), table.cols);
try expectRows(a, table, &.{ "A\tB\t", "\tc\td", "e\t\t" });
try t.expectEqualStrings("| A | B | |\n| --- | --- | --- |\n| | c | d |\n| e | | |", try html.pipe(a, table));
}

Expand All @@ -213,6 +227,9 @@ fn everyWriter(a: std.mem.Allocator, src: []const u8) !void {
defer table.deinit(a);
a.free(try html.pipe(a, table));
a.free(try html.normalized(a, table));
const rows = try html.rowsText(a, table);
for (rows) |r| a.free(r);
a.free(rows);
}

test "ocr html: every allocation failure is returned and nothing leaks" {
Expand Down
2 changes: 1 addition & 1 deletion zig/src/hip_serve/offer.zig
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub const Offer = struct {
window: ?usize = null,
/// Built by the family; null: text only.
vision: ?api.Vision = null,
/// The family's OCR reader (/v1/ocr); null: no OCR route.
/// The family's OCR reader (/v1/ocr and /ocr); null: no OCR routes.
ocr: ?api.ocr.Ocr = null,
/// The family's own store; null whenever its cache is off (no budget or no slots).
cache: ?*api.prompt_cache.Store = null,
Expand Down
8 changes: 4 additions & 4 deletions zig/src/server/auth_scope.zig
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,10 @@ const inferring = [_][]const u8{
"/responses", "/v1/responses", "/tokenize", "/v1/tokenize",
"/detokenize", "/v1/detokenize", "/v1/audio/speech", "/v1/embeddings",
"/v1/images/generations", "/decisions", "/v1/decisions", "/systemone",
"/v1/systemone", "/rerank", "/v1/rerank", "/v1/ocr",
"/v2/rerank", "/score", "/v1/score", "/api/chat",
"/api/generate", "/api/embed", "/api/show", "/apply-template",
"/v1/apply-template",
"/v1/systemone", "/rerank", "/v1/rerank", "/ocr",
"/v1/ocr", "/v2/rerank", "/score", "/v1/score",
"/api/chat", "/api/generate", "/api/embed", "/api/show",
"/apply-template", "/v1/apply-template",
};

/// A gated request a key may make: the route as the dispatcher reads it, matched exactly, never by suffix.
Expand Down
2 changes: 1 addition & 1 deletion zig/src/server/cache_salt_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@ test "cache salt isolation: two keys OCR pages never resume each other and each
var wire: harness.Wire = .{ .a = a };
const conn = try harness.request(a, &wire, "/v1/ocr", "application/json", body);
conn.key_digest = @as([32]u8, @splat(key));
@import("ocr/route.zig").post(srv, conn, a);
@import("ocr/route.zig").post(srv, conn, a, "/v1/ocr");
try std.testing.expectEqual(@as(u16, 200), wire.status());
try isolated(&cache, from, 1, resumed);
const reply = try wire.parsed();
Expand Down
Loading
Loading