Skip to content
Closed
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` takes PaddleX's request contract (step 6 of #2440): page results with reading-order blocks, lines and optional word boxes, the whole document's page count kept when processing stops early, and a repeated query refused (#2575).

- Qwen3.8 on CUDA: `TF_QWEN_PDL` is now on by default on sm_12x GPUs (GB10, RTX 50 series), so the ModelOpt NVFP4 lanes and the qwen35 glue kernels use programmatic dependent launch with tokens unchanged; other GPUs keep plain launches, `TF_QWEN_PDL=1` still turns it on from sm_90 and `TF_QWEN_PDL=0` turns it off (#4881).

- Tests: the prose benchmark's two concurrency cases hold their mock streams long enough that a busy CI host can no longer fail them (#4930).
Expand Down
89 changes: 60 additions & 29 deletions docs/api.md
Original file line number Diff line number Diff line change
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 three OCR contracts when it serves a model with an OCR reader and
`--vision`. One route answers Mistral's contract; `/ocr` (and `/ocr/`) answers two more, chosen from the request.
The native HIP engine reads pages through four OCR contracts when it serves a model with an OCR reader and
`--vision`. One route answers Mistral's contract; `/ocr` (and `/ocr/`) answers three more, chosen from the request.

| 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` | PaddleX OCR serving | JSON `{"file", "fileType", ...}` | `{"logId", "errorCode", "errorMsg", "result"}` | the PaddleX serving clients |
| `POST /ocr` | docTR API | multipart, one or more `files` parts, options in the query | one `OCROut` a page | the docTR API template's client |
| `POST /ocr` | LiteParse HTTP OCR | multipart, one `file` part | `{"results": [...]}` | `lit parse --ocr-server-url http://HOST:PORT/ocr` |

Expand All @@ -293,18 +294,21 @@ orientation), never in the model's resized frame.
| GLM-OCR | the page's Markdown as one block, tables as pipe tables or spanned HTML | none |

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 routes as they refuse chat. The routes take the
`inference` key scope.
and a server started without `--vision` answers "OCR needs image input; start the server with --vision" (PaddleX
answers both with 422). 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=doctr` or `?format=liteparse`. A query parameter sent twice is HTTP 400 ("the format query parameter is
repeated; send it once", and the same for docTR's parameters), because servers differ on which copy wins.
2. `multipart/form-data`: one or more parts named `files` is docTR; exactly one part named `file` is LiteParse;
1. `?format=paddlex`, `?format=doctr` or `?format=liteparse`. A query parameter sent twice is HTTP 400 ("the format
query parameter is repeated; send it once", and the same for docTR's parameters), because servers differ on
which copy wins.
2. `Content-Type` `application/json` or `application/*+json` (parameters such as `charset` ignored), or no
`Content-Type` with a body whose first non-space byte is `{`: PaddleX.
3. `multipart/form-data`: one or more parts named `files` is docTR; exactly one part named `file` is LiteParse;
any other set of parts is HTTP 400, and so is a body with both `files` and `file` parts, even when `?format=`
names the contract.
3. Any other content type, or none, is HTTP 415.
4. Any other content type 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
Expand Down Expand Up @@ -334,29 +338,34 @@ Both readers write block text in one Markdown flavour, the one Mistral's page Ma
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.
- `https://` URLs (Mistral `document_url` and `image_url`, PaddleX `file`) 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.
apply. Over the budget, a request is refused before any inference, except in PaddleX, which reads the first
pages of a PDF up to the budget, as [PaddleX's OCR serving API](https://paddlepaddle.github.io/PaddleX/latest/en/pipeline_usage/tutorials/ocr_pipelines/OCR.html)
reads the first `max_num_input_imgs` pages. `ocrResults` and `dataInfo.pages` list the pages read, and
`dataInfo.numPages` is the document's page count, so a client can see the cut.
- Image budget, for Mistral crops (`include_image_base64`) and PaddleX's `ocrImage` and `inputImage`: 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". Both encodes need libjpeg-turbo
3.1.4.1 (`TENSORFOLD_LIBTURBOJPEG` names its file); without it `include_image_base64` is HTTP 400 and PaddleX's
default `visualize` is HTTP 500 "visualize needs libjpeg-turbo, which this server cannot load; send visualize:
false".

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 | docTR | LiteParse |
| --- | --- | --- | --- |
| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | 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 | 422 |
| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | 503, `Retry-After: 1` | 503, `Retry-After: 1` |
| Engine fault, out of memory, PDF renderer crash or deadline | 500 | 500 | 500 |
| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | `{"detail": "..."}` | `{"error": "..."}` |
| Failure | Mistral | PaddleX | docTR | LiteParse |
| --- | --- | --- | --- | --- |
| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | 422 | 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 | 422 | 422 |
| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | 503, `Retry-After: 1` | 503, `Retry-After: 1` | 503, `Retry-After: 1` |
| Engine fault, out of memory, PDF renderer crash or deadline | 500 | 500 | 500 | 500 |
| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | `{"logId", "errorCode", "errorMsg"}`, `errorCode` equal to the status | `{"detail": "..."}` | `{"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
Expand All @@ -370,12 +379,12 @@ dots.mocr gives one box a block and GLM-OCR none, so the line contracts estimate
- **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.
- **Words.** docTR's words divide a line's box along its reading direction in proportion to each word's character
count.
- **Scores.** Every score is `1.0`: docTR `confidence` and `objectness_score`, LiteParse `confidence`. Mistral
replies leave `confidence_scores` out.
- **No geometry.** With GLM-OCR, Mistral returns `blocks: []`, docTR gives each line the whole page as its box, and
LiteParse is refused.
- **Words.** docTR's words and PaddleX's `returnWordBox` divide a line's box along its reading direction in
proportion to each word's character count.
- **Scores.** Every score is `1.0`: PaddleX `rec_scores`, docTR `confidence` and `objectness_score`, LiteParse
`confidence`. Mistral replies leave `confidence_scores` out.
- **No geometry.** With GLM-OCR, Mistral returns `blocks: []`, PaddleX and docTR give each line the whole page as
its box, and LiteParse is refused.

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

Expand All @@ -399,6 +408,28 @@ dots.mocr gives one box a block and GLM-OCR none, so the line contracts estimate
`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.

### PaddleX: `POST /ocr`

`file` is base64 (bytes outside the alphabet are skipped and the padding is repaired, as Python's `b64decode`
does), a `data:` URL or an `https://` URL. `fileType` is `0` for a PDF and `1` for an image; when it is absent the
bytes decide. TIFF is not read. `logId` is echoed by every reply once the body parses; an absent or empty one gets
a new UUID. Each field converts as pydantic's lax mode converts the type PaddleX's serving reference gives it (`"0.5"` is a
number, `"off"` and `0` are false), and a number must be finite.

| Field | Meaning |
| --- | --- |
| `textRecScoreThresh` | Keep lines with a score at or above it in `rec_*`; `dt_polys` keeps every line. Default `0.0` |
| `returnWordBox` | Add `text_word_boxes` and `text_word`, each line's estimated words |
| `visualize` | Default `true`: `inputImage` (the page) and `ocrImage` (the page with each `rec_polys` polygon outlined), base64 JPEG without a data-URL prefix. `false` leaves both out |
| `useDocOrientationClassify`, `useDocUnwarping`, `useTextlineOrientation` | Accepted when null or false; `true` is 422 |
| `textDetLimitSideLen`, `textDetLimitType`, `textDetThresh`, `textDetBoxThresh`, `textDetUnclipRatio` | Accepted when null; any value is 422, since TensorFold has no text detector to apply it to |

`prunedResult` leaves out `text_det_params` and `doc_preprocessor_res`. Polygons
round each corner half to even, as Python does; `rec_boxes` is each polygon's min/max. `dataInfo` is
`{"width", "height", "type": "image"}` or `{"numPages", "pages": [{"width", "height"}], "type": "pdf"}`, where
`numPages` is the document's page count and `pages`, like `ocrResults`, lists the pages read. A schema error's
`errorMsg` is the JSON list `[{"type", "loc", "msg"}]` with `loc` dot-joined (`body.file`).

### docTR: `POST /ocr`

Each `files` part's type must be exactly `image/jpeg`, `image/png` or `application/pdf` (the types docTR's API README names),
Expand Down
9 changes: 1 addition & 8 deletions zig/src/server/benchmark_receipt.zig
Original file line number Diff line number Diff line change
Expand Up @@ -316,14 +316,7 @@ fn indented(w: *std.Io.Writer, v: Value, depth: usize) std.Io.Writer.Error!void

/// A random lowercase UUID v4, as ``str(uuid.uuid4())``.
pub fn runId(io: std.Io) [36]u8 {
var b: [16]u8 = undefined;
io.random(&b);
b[6] = (b[6] & 0x0f) | 0x40;
b[8] = (b[8] & 0x3f) | 0x80;
const hex = std.fmt.bytesToHex(b, .lower);
var out: [36]u8 = undefined;
_ = std.fmt.bufPrint(&out, "{s}-{s}-{s}-{s}-{s}", .{ hex[0..8], hex[8..12], hex[12..16], hex[16..20], hex[20..32] }) catch unreachable;
return out;
return @import("ids.zig").uuid4(io);
}

/// UTC wall time as ``datetime.isoformat()`` with Z: microseconds only when not zero.
Expand Down
12 changes: 12 additions & 0 deletions zig/src/server/ids.zig
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,18 @@ pub fn make(a: Allocator, prefix: []const u8, n: usize) Allocator.Error![]const
return out;
}

/// A random lowercase UUID v4, as ``str(uuid.uuid4())``.
pub fn uuid4(io: std.Io) [36]u8 {
var b: [16]u8 = undefined;
io.random(&b);
b[6] = (b[6] & 0x0f) | 0x40;
b[8] = (b[8] & 0x3f) | 0x80;
const hex = std.fmt.bytesToHex(b, .lower);
var out: [36]u8 = undefined;
_ = std.fmt.bufPrint(&out, "{s}-{s}-{s}-{s}-{s}", .{ hex[0..8], hex[8..12], hex[12..16], hex[16..20], hex[20..32] }) catch unreachable;
return out;
}

/// ``prefix`` then the first ``n`` (at most 64) lowercase hex digits of ``digest``.
fn hexed(a: Allocator, prefix: []const u8, n: usize, digest: [32]u8) Allocator.Error![]const u8 {
const hex = std.fmt.bytesToHex(digest, .lower);
Expand Down
2 changes: 1 addition & 1 deletion zig/src/server/ocr/budget.zig
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub const Pages = struct {
}
};

/// The crops a request has encoded, against its limits.
/// The crops and visualisations a request has encoded, against its limits.
pub const Encodes = struct {
count: u32 = 0,
pixels: u64 = 0,
Expand Down
81 changes: 81 additions & 0 deletions zig/src/server/ocr/draw.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
//! Region outlines on a page's RGB pixels for the visualisation images (PaddleX ``ocrImage``).
const std = @import("std");

/// The one outline colour the visualisations use.
pub const red: [3]u8 = .{ 255, 0, 0 };

/// Draws the closed polygon ``poly`` on ``w`` x ``h`` RGB rows, lines ``width_px`` thick, every pixel clipped.
pub fn outline(rgb: []u8, w: u32, h: u32, poly: [4][2]i32, rgb_color: [3]u8, width_px: u32) void {
std.debug.assert(rgb.len >= @as(usize, w) * h * 3);
if (w == 0 or h == 0 or width_px == 0) return;
for (0..4) |i| segment(rgb, w, h, poly[i], poly[(i + 1) % 4], rgb_color, width_px);
}

/// One Bresenham line, first clipped to the image grown by the line width so a far-off corner costs no steps.
fn segment(rgb: []u8, w: u32, h: u32, from: [2]i32, to: [2]i32, color: [3]u8, n: u32) void {
const pad: f64 = @floatFromInt(n);
var p0: [2]f64 = .{ @floatFromInt(from[0]), @floatFromInt(from[1]) };
var p1: [2]f64 = .{ @floatFromInt(to[0]), @floatFromInt(to[1]) };
if (!clip(&p0, &p1, .{ -pad, -pad, @as(f64, @floatFromInt(w)) + pad, @as(f64, @floatFromInt(h)) + pad })) return;
var x: i64 = @intFromFloat(@round(p0[0]));
var y: i64 = @intFromFloat(@round(p0[1]));
const x1: i64 = @intFromFloat(@round(p1[0]));
const y1: i64 = @intFromFloat(@round(p1[1]));
const dx: i64 = @intCast(@abs(x1 - x));
const dy: i64 = -@as(i64, @intCast(@abs(y1 - y)));
const sx: i64 = if (x < x1) 1 else -1;
const sy: i64 = if (y < y1) 1 else -1;
var err = dx + dy;
while (true) {
dot(rgb, w, h, x, y, color, n);
if (x == x1 and y == y1) break;
const e2 = 2 * err;
if (e2 >= dy) {
err += dy;
x += sx;
}
if (e2 <= dx) {
err += dx;
y += sy;
}
}
}

/// An ``n`` x ``n`` square centred on (x, y) (2 px: x-1..x), so an edge on the image border stays visible.
fn dot(rgb: []u8, w: u32, h: u32, x: i64, y: i64, color: [3]u8, n: u32) void {
const back: i64 = @intCast(n / 2);
for (0..n) |j| for (0..n) |i| {
const px = x - back + @as(i64, @intCast(i));
const py = y - back + @as(i64, @intCast(j));
if (px < 0 or py < 0 or px >= w or py >= h) continue;
const at: usize = (@as(usize, @intCast(py)) * w + @as(usize, @intCast(px))) * 3;
rgb[at..][0..3].* = color;
};
}

/// Liang-Barsky: trims the segment to the box ``[xmin, ymin, xmax, ymax]``; false when nothing is left.
fn clip(p0: *[2]f64, p1: *[2]f64, b: [4]f64) bool {
const d: [2]f64 = .{ p1[0] - p0[0], p1[1] - p0[1] };
const ps = [4]f64{ -d[0], d[0], -d[1], d[1] };
const qs = [4]f64{ p0[0] - b[0], b[2] - p0[0], p0[1] - b[1], b[3] - p0[1] };
var t0: f64 = 0;
var t1: f64 = 1;
for (ps, qs) |p, q| {
if (p == 0) {
if (q < 0) return false;
continue;
}
const r = q / p;
if (p < 0) {
if (r > t1) return false;
t0 = @max(t0, r);
} else {
if (r < t0) return false;
t1 = @min(t1, r);
}
}
const start = p0.*;
p0.* = .{ start[0] + t0 * d[0], start[1] + t0 * d[1] };
p1.* = .{ start[0] + t1 * d[0], start[1] + t1 * d[1] };
return true;
}
34 changes: 34 additions & 0 deletions zig/src/server/ocr/draw_test.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//! The region outline PaddleX's ocrImage draws: its thickness along the edges and its clipping to the image.
const std = @import("std");
const draw = @import("draw.zig");
const t = std.testing;

fn isRed(rgb: []const u8, w: u32, x: u32, y: u32) bool {
const at = (y * w + x) * 3;
return std.mem.eql(u8, rgb[at..][0..3], &draw.red);
}

test "ocr draw: an outline is 2 px thick along the polygon's edges" {
const w = 12;
const h = 10;
var rgb: [w * h * 3]u8 = @splat(0);
draw.outline(&rgb, w, h, .{ .{ 2, 2 }, .{ 8, 2 }, .{ 8, 7 }, .{ 2, 7 } }, draw.red, 2);
for ([_][2]u32{ .{ 2, 2 }, .{ 5, 2 }, .{ 5, 1 }, .{ 8, 4 }, .{ 7, 4 }, .{ 2, 7 }, .{ 1, 5 }, .{ 8, 7 } }) |p| try t.expect(isRed(&rgb, w, p[0], p[1]));
for ([_][2]u32{ .{ 5, 5 }, .{ 0, 0 }, .{ 11, 9 }, .{ 5, 3 }, .{ 3, 5 }, .{ 9, 4 }, .{ 5, 8 } }) |p| try t.expect(!isRed(&rgb, w, p[0], p[1]));
}

test "ocr draw: an outline is clipped to the image" {
const w = 8;
const h = 6;
var rgb: [w * h * 3]u8 = @splat(0);
draw.outline(&rgb, w, h, .{ .{ -5, -5 }, .{ 20, -5 }, .{ 20, 3 }, .{ -5, 3 } }, draw.red, 2);
for (0..w) |x| try t.expect(isRed(&rgb, w, @intCast(x), 3));
try t.expect(!isRed(&rgb, w, 3, 0));
// corners far outside cost no work and write nothing out of bounds
var far: [w * h * 3]u8 = @splat(0);
const big = std.math.maxInt(i32);
draw.outline(&far, w, h, .{ .{ -big, -big }, .{ big, -big }, .{ big, -big + 1 }, .{ -big, -big + 1 } }, draw.red, 2);
for (far) |b| try t.expectEqual(@as(u8, 0), b);
draw.outline(&far, w, h, .{ .{ 0, 0 }, .{ w, 0 }, .{ w, h }, .{ 0, h } }, draw.red, 2);
try t.expect(isRed(&far, w, 0, 0) and isRed(&far, w, w - 1, h - 1) and !isRed(&far, w, 3, 3));
}
2 changes: 1 addition & 1 deletion zig/src/server/ocr/fetch.zig
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! A document's bytes from a public HTTPS URL, for POST /v1/ocr's document URLs.
//! A document's bytes from a public HTTPS URL, for the OCR dialects that take URLs (Mistral, PaddleX).
const std = @import("std");
const Allocator = std.mem.Allocator;
const images = @import("../images.zig");
Expand Down
Loading
Loading