Skip to content

Fast, accurate OCR with correctness assessment.

sdk: support SGLang, llama.cpp, and Ollama for Jev scoring

LuMingcongdf21f1050daa
diff --git a/docs/minicpm_ocr_jev_tutorial_en.md b/docs/minicpm_ocr_jev_tutorial_en.md
index ed5673a..dd41f6e 100644
--- a/docs/minicpm_ocr_jev_tutorial_en.md
+++ b/docs/minicpm_ocr_jev_tutorial_en.md
@@ -39,7 +39,7 @@ cd scripts/minicpm-ocr-jev
docker build -f serve/Dockerfile -t minicpm-ocr-jev-1-0:latest .
```
-On a slow network you need two mirror arguments; see [`scripts/minicpm-ocr-jev/README.md`](../scripts/minicpm-ocr-jev/README.md).
+On a slow network add `--build-arg PIP_INDEX_URL=https://<mirror>/simple` and `--build-arg PLAYWRIGHT_DOWNLOAD_HOST=https://<mirror>`.
Run (mount the weights, map the port):
@@ -80,7 +80,7 @@ curl -s http://127.0.0.1:8030/v1/rm/score -H 'Content-Type: application/json' -d
`image` takes a `data:image/png;base64,` or `data:image/jpeg;base64,` prefix followed by the base64 body. `category` must match the real type of the block (`text` / `formula` / `table`); getting it wrong raises no error but skews the score. **Always read** `verdict` **before using a score** — `0.0` and `-1.0` are the fixed values returned when scoring failed, not low scores.
-For the other endpoints (`/v1/rm/score_best`, `/v1/rm/score_best_batch`) and the full field definitions, see the [Docker image API reference](./minicpm_ocr_jev_docker_api_en.md). For the directory layout and build details, see [`scripts/minicpm-ocr-jev/README.md`](../scripts/minicpm-ocr-jev/README.md).
+For the other endpoints (`/v1/rm/score_best`, `/v1/rm/score_best_batch`) and the full field definitions, see the [Docker image API reference](./minicpm_ocr_jev_docker_api_en.md).
### Option 2: SDK deployment
diff --git a/docs/minicpm_ocr_jev_tutorial_zh.md b/docs/minicpm_ocr_jev_tutorial_zh.md
index 483fd0e..72b51e4 100644
--- a/docs/minicpm_ocr_jev_tutorial_zh.md
+++ b/docs/minicpm_ocr_jev_tutorial_zh.md
@@ -39,7 +39,7 @@ cd scripts/minicpm-ocr-jev
docker build -f serve/Dockerfile -t minicpm-ocr-jev-1-0:latest .
```
-慢网下需要加两个镜像源参数,详见 [`scripts/minicpm-ocr-jev/README.md`](../scripts/minicpm-ocr-jev/README.md)。
+慢网下加上 `--build-arg PIP_INDEX_URL=https://<mirror>/simple` 和 `--build-arg PLAYWRIGHT_DOWNLOAD_HOST=https://<mirror>`。
运行(挂载权重、映射端口):
@@ -80,7 +80,7 @@ curl -s http://127.0.0.1:8030/v1/rm/score -H 'Content-Type: application/json' -d
`image` 传 `data:image/png;base64,` 或 `data:image/jpeg;base64,` 前缀加 base64 正文。`category` 必须与块真实类型一致(`text` / `formula` / `table`),填错不报错但分数会偏。**用分数前必须先看** `verdict`——`0.0` 与 `-1.0` 是打分失败时的固定返回值,不是低分。
-更多端点(`/v1/rm/score_best`、`/v1/rm/score_best_batch`)与完整字段定义见 [Docker 镜像 API 参考](./minicpm_ocr_jev_docker_api_zh.md)。目录结构与构建细节见 [`scripts/minicpm-ocr-jev/README.md`](../scripts/minicpm-ocr-jev/README.md)。
+更多端点(`/v1/rm/score_best`、`/v1/rm/score_best_batch`)与完整字段定义见 [Docker 镜像 API 参考](./minicpm_ocr_jev_docker_api_zh.md)。
### 方式二:SDK 本地部署
diff --git a/scripts/minicpm-ocr-jev/README.md b/scripts/minicpm-ocr-jev/README.md
deleted file mode 100644
index 19e7d4b..0000000
--- a/scripts/minicpm-ocr-jev/README.md
+++ /dev/null
@@ -1,797 +0,0 @@
-# MiniCPM-OCR Jev local deployment
-
-A vision-language reward model that judges whether a piece of OCR output actually
-matches the document image it came from. Given a document block and several candidate
-transcriptions, it scores each one, so you can pick the best, filter the bad, or rank
-several OCR engines against each other.
-
-It is a 2-class sequence-classification head (a "value head") on a Qwen3.5-VL 2B
-backbone. The output is `prob_yes`: the probability that a candidate is consistent
-with the original image.
-
-What makes this model different from a text-similarity metric is that **it does not
-read the candidate as text alone**. It looks at two images:
-
-```
- image 1 the original document block
- image 2 the candidate text, rendered back into an image
- + text the candidate text itself
-```
-
-Three inputs, hence *ternary*. Scoring therefore has three stages, and this repo ships
-all of them:
-
-```
- precheck → render → forward
- (Node + (Chromium + (vLLM)
- KaTeX) KaTeX)
-```
-
-Rendering is what lets the model catch errors that text comparison misses: a formula
-written with different LaTeX but identical meaning should score *high*, while a
-transcription that keeps every word but scrambles the layout should score *low*. Both
-of those are in [`examples/`](examples/).
-
-The same model appears under three spellings, one per place it has to be named:
-weights `openbmb/MiniCPM-OCR-1.0-Jev` on the Hub, the container image
-`minicpm-ocr-jev-1-0` this repo builds, and `minicpm-ocr-jev` as the model id the
-service serves it under.
-
----
-
-## Contents
-
-```
-infer_vllm.py end-to-end scoring: precheck → render → forward
-rm_render.py precheck + render only, if you just want the images
-requirements.txt
-renderer/
- setup_renderer.sh install Chromium; check Node, fonts and the font pin
- check_renderer.py compare your renders against the bundled references
- render_triple_rm_labels.py render driver
- render_module/ HTML generation and page layout
- precheck/ KaTeX parse screen (Node)
- assets/katex-0.16.47/ pinned KaTeX, with its own fonts
-serve/
- setup_backend.sh install vLLM into its own venv, and check it can serve this
- start_vllm.sh the forward pass, as a stock `vllm serve`
- app.py the HTTP service: precheck, render, call the backend
- start_app.sh
- start_all.sh both halves together, as one container's entrypoint
- render_pool.py browsers kept open for the life of the process
- chat_template_passthrough.jinja
- requirements-serve.txt
- Dockerfile both halves in one image, two processes, no weights
- check_server.py is the backend reproducing our prompt and scores?
- check_service.py does the service honour its contract?
- check_render_parity.py does the pool render the same bytes as a fresh browser?
- bench_service.py throughput and the stage breakdown, under load
- bench_backend.py the forward pass alone — where the GPU flattens out
- bench_render.py the renderer alone — how it scales with workers
-examples/
- 01_text_putnam/ layout scrambled but wording preserved
- 02_formula_putnam/ same formula, very different LaTeX
- 03_table_gb_standard/ unit and character errors inside a table
-```
-
----
-
-## Install
-
-The renderer and the forward pass go into **two separate virtual environments**. That
-is deliberate: the renderer pins Pillow to the exact version it was calibrated on,
-while vLLM asks only for `pillow>=12.3.0`. Share one environment and a later
-`pip install -U vllm` moves Pillow forward and changes every score — silently, with
-no error anywhere. Two environments make that impossible instead of merely
-discouraged.
-
-### 0. System packages
-
-```bash
-sudo apt-get install -y python3 python3-pip python3-venv python3-dev \
- gcc g++ nodejs fonts-noto-cjk fontconfig ca-certificates curl
-```
-
-`gcc` and `python3-dev` are needed **at run time, on every cold start** — not just to
-install. Triton compiles a small CPython extension on the first forward pass, so
-without them the backend loads the weights, runs for two minutes, and then dies on a
-bare `CalledProcessError` whose real cause (`fatal error: Python.h: No such file`) is
-sixty lines further up. `nodejs` drives the KaTeX precheck; `fonts-noto-cjk` is what
-makes Chinese render as text rather than empty boxes. Both setup scripts below check
-for all of this and name what is missing.
-
-If pypi.org is slow from where you are, point pip at a nearer mirror first. This
-install pulls vLLM, torch and a dozen CUDA wheels — several gigabytes — and the
-difference is minutes versus hours:
-
-```bash
-export PIP_INDEX_URL=https://<your-nearest-mirror>/simple
-```
-
-Playwright downloads its browser from its own CDN, which `PIP_INDEX_URL` does not
-cover, so set that separately or step 1 will sit for an hour on a 180 MB file:
-
-```bash
-export PLAYWRIGHT_DOWNLOAD_HOST=https://<your-nearest-mirror>
-```
-
-Both are plain mirrors of the same artefacts; neither changes what gets installed.
-Measured from one machine in China: pypi.org 19 KB/s against a local mirror's
-15 MB/s, and Playwright's CDN 28 KB/s against a local mirror's 11 MB/s.
-
-### 1. The renderer
-
-```bash
-git clone <this repo>
-cd <this repo>
-python3 -m venv .venv-render && . .venv-render/bin/activate
-bash renderer/setup_renderer.sh
-```
-
-This installs the Python packages, downloads the pinned Chromium through Playwright,
-and then **checks** two things it cannot install for you: Node.js (needed by the
-precheck stage) and a CJK font (needed to render Chinese at all). It tells you exactly
-what to install if either is missing.
-
-The virtualenv is not optional on Debian 12 / Ubuntu 23.04 and newer: their system
-Python is marked externally managed (PEP 668) and pip refuses to install into it. The
-script stops with that instruction rather than letting pip suggest
-`--break-system-packages`, which would push the renderer's Pillow pin onto the system
-Python for every other program on the machine.
-
-**Then pin the font environment.** The step above installs Chromium through
-Playwright's `--with-deps`, which also drags in several fonts of its own — and
-fontconfig prefers some of them over the faces this renderer's CSS actually names.
-Rendered text is model input here, so a different face is a different score. Four
-commands fix the face set and the rasteriser to the ones the reference deployment
-uses:
-
-```bash
-sudo apt-get install -y fonts-droid-fallback
-sudo apt-get purge -y fonts-wqy-zenhei fonts-unifont fonts-ipafont-gothic
-sudo rm -f /etc/fonts/conf.d/10-sub-pixel-rgb.conf
-sudo fc-cache -f
-```
-
-`fonts-droid-fallback` supplies DroidSansFallbackFull, one of the three faces the CSS
-stack names (the other two come from `fonts-noto-cjk` in §0). The three purged
-packages are never named by the stack, but they outrank the named faces in
-fontconfig's substitution for characters Noto does not cover. The removed config turns
-on RGB sub-pixel rendering, which tints glyph edges per channel — same shapes,
-different pixels.
-
-Run these **after** `setup_renderer.sh`, never before: `--with-deps` would reinstall
-what you just purged. On a distro without these package names the requirement is the
-same — the three named faces present, nothing fontconfig prefers over them, sub-pixel
-rendering off. "Matching the reference renderer" below measures what skipping this
-costs, which is less than you might expect for some uses and not negligible for
-others.
-
-Then verify the renderer reproduces the bundled reference images:
-
-```bash
-python3 renderer/check_renderer.py
-```
-
-See [Matching the reference renderer](#matching-the-reference-renderer) for how to
-read the result.
-
-### 2. vLLM
-
-```bash
-bash serve/setup_backend.sh .venv-vllm
-```
-
-That creates a second virtualenv, installs vLLM from PyPI, and then checks the thing
-that actually matters: that this build registers `Qwen3_5ForConditionalGeneration` and
-can therefore serve the model.
-
-**A second environment, not the renderer's.** This is a requirement, not tidiness.
-vLLM requires only `pillow>=12.3.0`, while the renderer pins the exact version —
-because Pillow decides the pixels the model is scored on. Install both into one
-environment and a single later `pip install -U vllm` moves Pillow to the next major
-version, changes every score, and reports no error at all. Two environments make that
-impossible rather than unlikely. If you then start the service from this environment,
-tell it where the renderer lives with `RM_RENDER_PYTHON` (see "Tuning").
-
-vLLM itself is **not pinned** — the reward model is an
-ordinary 2-class sequence classifier on a Qwen3.5-VL backbone, so any build with that
-architecture and vLLM's `runner="pooling"` + `convert="classify"` path will serve it.
-
-Verified combinations:
-
-| | built from upstream (earlier) | plain `pip install vllm` (what we now run) |
-|---|---|---|
-| vLLM | `0.1.dev21951+g5ff3bbfb0` | **`0.32.0`** (PyPI wheel) |
-| torch | `2.13.0+cu130` | `2.13.0+cu130` |
-| transformers | `5.17.0` | `5.19.0` |
-
-Scored against each other on identical images and identical prompt bytes, the six
-bundled candidates agree to within 6e-4, except the table ground-truth candidate
-(4.7e-3) — which is the one example whose absolute score is already known to be
-unreliable, see [Reading the scores](#reading-the-scores). Candidate ordering is
-identical. Earlier revisions of this document told you to build from commit
-`5ff3bbfb0`; that is no longer necessary and the release is the better choice.
-
-### 3. Weights
-
-```bash
-huggingface-cli download openbmb/MiniCPM-OCR-1.0-Jev --local-dir ./weights
-```
-
-Then pass `--model ./weights`.
-
-<https://huggingface.co/openbmb/MiniCPM-OCR-1.0-Jev>
-
-Any other checkpoint works too, as long as it is a 2-class sequence-classification
-model on a Qwen3.5-VL backbone: point `--model` at a directory holding
-`config.json` and the safetensors shards. Note that the scores a different
-checkpoint produces are its own — the prompt below is part of *this* model, and
-the reference scores in `examples/` are too.
-
----
-
-## Quickstart
-
-Score the bundled examples:
-
-```bash
-python3 infer_vllm.py --model ./weights --examples
-```
-
-Score your own block:
-
-```bash
-python3 infer_vllm.py --model ./weights \
- --image my_block.png --category text \
- --candidate "first transcription" \
- --candidate "second transcription"
-```
-
-Score a batch — one block per line, several candidates each:
-
-```bash
-python3 infer_vllm.py --model ./weights --input-jsonl blocks.jsonl
-```
-
-```json
-{"case_id": "p1_b3", "image_path": "crops/p1_b3.png", "category": "table", "candidates": ["<table>…</table>", "<table>…</table>"]}
-```
-
-From Python:
-
-```python
-from rm_render import Candidate
-from infer_vllm import RMScorer
-
-scorer = RMScorer("./weights") # loads once, reuse it
-results = scorer.score([
- Candidate(case_id="b1#0", image_path="crops/b1.png", text="…", category="text"),
- Candidate(case_id="b1#1", image_path="crops/b1.png", text="…", category="text"),
-])
-for r in results:
- print(r.case_id, r.prob_yes, r.verdict)
-```
-
-Loading the engine takes a few minutes (weights, graph capture, multi-modal warmup),
-so build one `RMScorer` and keep it alive. `vllm.LLM` batches internally: hand it all
-your prompts at once rather than calling it in a loop.
-
-If you only want the rendered images, skip the model entirely:
-
-```bash
-python3 rm_render.py --image my_block.png --candidate "…" --out-dir ./renders
-```
-
----
-
-## Running it as a service
-
-Everything above loads the model into your own process. To serve it over HTTP
-instead, run the two halves separately:
-
-```
- your client ──> serve/app.py ────HTTP────> vllm serve
- precheck forward pass
- render
-```
-
-The split is not ceremony. Scoring one candidate costs about 0.2s of precheck,
-0.9s of rendering and 0.1s of forward pass — measured, like every figure in this
-document, on the machine named under "Where the ceiling is" — so nine tenths of
-the work is a browser and one tenth is the GPU. In one process they compete for one
-interpreter, and the only way to add rendering capacity is to add GPUs. Apart,
-`app.py` is stateless and you can run several against one backend, while vLLM's
-own scheduler — continuous batching, prefix caching — handles the GPU side
-without any engine code in this repo.
-
-A second consequence: because the backend batches across HTTP requests,
-candidates from unrelated requests end up in the same GPU batch on their own.
-
-### Start the backend
-
-```bash
-bash serve/start_vllm.sh 0 8026 ./weights # GPU index, port, checkpoint
-```
-
-Three environment variables adjust it, and none of them are arguments: `GPU_MEM_UTIL`
-(default 0.80 — the fraction of VRAM vLLM reserves; lower it to share the card),
-`MAX_MODEL_LEN` (16384) and `SERVED_NAME` (`minicpm-ocr-jev`, the id the backend
-answers to). The service asks the backend for that last one rather than assuming it,
-so changing it needs no matching change in `app.py`.
-
-This is a stock `vllm serve` in classification mode. The one non-obvious flag is
-`--chat-template serve/chat_template_passthrough.jinja`: the `/classify` endpoint
-accepts images only in the chat form, and the chat form always runs a template,
-so the template here is one that hands our prompt back unchanged rather than
-assembling one. The prompt bytes stay where they belong, in `build_prompt()`
-under its fingerprint check. See [The prompt is part of the
-model](#the-prompt-is-part-of-the-model).
-
-### Start the service
-
-```bash
-python3 -m pip install -r serve/requirements-serve.txt
-bash serve/start_app.sh 8030 http://127.0.0.1:8026
-```
-
-It answers 503 until the backend is up, so either half can be restarted without
-the other.
-
-### Or both at once
-
-```bash
-bash serve/start_all.sh 8030 ./weights # app port, checkpoint
-```
-
-This starts the backend, waits for it to answer — loading weights and capturing
-CUDA graphs takes a few minutes, so it asks rather than sleeps — then starts the
-service, and exits if either half dies afterwards. That last part is the point: a
-container whose backend has died but whose HTTP layer still answers, correctly,
-with 503 forever, looks alive to every probe except a caller reading the response
-body. It is also the entrypoint of the image described in "As images".
-
-Two environments need naming here, and `start_all.sh` reads them from
-`VLLM_PYTHON_BIN` and `RENDER_PYTHON_BIN`; the defaults are the paths the
-container uses. Running it outside a container, set both.
-
-### Endpoints
-
-| | |
-|---|---|
-| `GET /healthz` | readiness, plus the identity of everything that decides a score: backend model, prompt fingerprint, renderer version |
-| `POST /v1/rm/score` | score a batch of candidates; returns per-item scores and a summary with the throughput rate |
-| `POST /v1/rm/score_best` | N candidates for one block; returns the best one |
-| `POST /v1/rm/score_best_batch` | several blocks in one request |
-
-```bash
-curl -s localhost:8030/v1/rm/score_best -H 'Content-Type: application/json' -d '{
- "input_form": "ternary",
- "image": "'"$(base64 -w0 examples/01_text_putnam/block.png)"'",
- "candidates": ["first transcription", "second transcription"],
- "category": "text"
-}'
-```
-
-Supply `render_image` (or `render_images`) if you have already rendered the
-candidates; the service then skips precheck and rendering entirely.
-
-Read `verdict` before `prob_yes`. Items that never reached the model carry a
-sentinel score — `0.0` when the candidate was judged unusable, `-1.0` when we
-could not find out — so a caller that ignores `verdict` degrades safely, but
-reads a number that is not a probability.
-
-### Checking it
-
-```bash
-python3 serve/check_server.py --base-url http://127.0.0.1:8026 # backend: prompt and scores
-python3 serve/check_service.py --base-url http://127.0.0.1:8030 # service: the contract
-python3 serve/check_render_parity.py # pool renders == fresh browser
-python3 serve/bench_service.py --base-url http://127.0.0.1:8030 # throughput and stage split
-```
-
-### Tuning
-
-The service keeps Chromium open rather than starting one per batch, which
-removes 1.2s from every request on that same machine. The defaults are already the fast
-configuration; this section is for when they are not right for your machine.
-
-| variable | default | what it changes |
-|---|---|---|
-| `RM_WORKERS` | cores ÷ 8, capped at 16 | uvicorn worker processes. **The throughput knob** — see below. Set it explicitly inside a CPU-limited container, where `nproc` reports the host's cores rather than your share. |
-| `RM_RENDER_BROWSERS` | 2 | Chromiums per worker. Keep it small and add workers instead. |
-| `RM_BROWSER_CONCURRENCY` | 8 | pages rendering at once inside one browser. The per-request latency knob: a request with twenty candidates renders them this many at a time. |
-| `RM_FORWARD_CONCURRENCY` | 32 | in-flight requests to the backend. Rarely the limit; the GPU side saturates around 16 and queues past it. |
-| `RM_RENDER_MODE` | `persistent` | `subprocess` starts a fresh browser per batch. A fallback for environments where the pool will not start, not a tuning choice. |
-| `RM_VLLM_MODEL` | unset — ask the backend | the model id sent to the backend. Unset, the service reads it from the backend's `/v1/models`, so the two halves cannot disagree. Set it only when the backend serves more than one model. |
-| `RM_RENDER_PYTHON` | unset — use `app.py`'s own interpreter | which interpreter runs the render subprocess. Needed when the renderer and vLLM are installed in *different* environments — see below. |
-
-**On `RM_RENDER_PYTHON`.** The renderer draws each candidate in a subprocess, and by
-default that subprocess is started with the same interpreter that runs `app.py`. That
-is right only when the renderer's packages are installed there. Two common cases
-where they are not:
-
-- **Two environments on purpose.** §1 and §2 install the renderer and vLLM
- separately, and §2 explains why that separation is load-bearing rather than tidy:
- vLLM requires only `pillow>=12.3.0` while the renderer pins the exact version that
- decides its pixels, so one `pip install -U vllm` in a shared environment moves
- Pillow and silently changes every score. If you start `app.py` from the vLLM
- environment, point `RM_RENDER_PYTHON` at the renderer's
- (`/path/to/.venv-render/bin/python`). The container built by `serve/Dockerfile`
- handles this through `PATH` instead — see `start_all.sh`.
-- **A wrapper script.** Where you cannot install system libraries, the same variable
- takes an interpreter wrapper that sets `LD_LIBRARY_PATH` for the render subprocess
- alone — see Troubleshooting.
-
-The command-line tools take the same thing as `--render-python`
-(`infer_vllm.py`, `rm_render.py`, `renderer/check_renderer.py`). Get it wrong and the
-failure is loud and immediate — the subprocess dies on `ModuleNotFoundError` for
-`playwright` — so this is not a silent-wrong-answer risk, unlike the Pillow version
-it exists to protect.
-
-Workers rather than browsers, because every browser a process owns is driven
-over one Playwright connection by one asyncio loop, and rendered screenshots
-come back through it. That pipe saturates well before the browsers do. Measured
-on 128 cores, four candidates per request, 32-way concurrency:
-
-```
- 1 worker x 8 browsers 11.5 candidates/s p50 5.5s
- 8 workers x 2 browsers 45.5 candidates/s p50 2.5s
-```
-
-Sixteen Chromiums in the second row against eight in the first, and it is four
-times the throughput at half the latency. Add workers first.
-
-### Where the ceiling is
-
-Both halves were measured separately, because a single end-to-end number cannot
-tell you which one to spend money on. On one RTX 5090 and 128 cores, four
-candidates per request:
-
-```
- backend (bench_backend.py) 52 candidates/s, flat from ~32-way concurrency
- renderer (bench_render.py) 35 candidates/s at 4 workers
- 80 candidates/s at 8 workers
- 142 candidates/s at 16 workers, still linear
- end to end (bench_service.py) 56 candidates/s at the defaults, 64-way, p50 3.2s
- 32 candidates/s at the defaults, 16-way, p50 1.8s
- 2.7 candidates/s for a lone request, p50 1.4s
-```
-
-The renderer scales with cores and had not bent at 32 Chromiums; the GPU is flat
-by 32-way concurrency and stays flat to 128. **So the ceiling is the GPU, and the
-renderer's job is to stay ahead of it** — which at the default 16 workers it
-does, the whole chain landing at or above what the backend measured alone.
-
-That is what the defaults aim at, and it also says what to do when it is too
-slow. More renderer capacity — workers, or another machine running `app.py`
-against the same backend — helps only while the renderer is behind the GPU, and
-`stage_sec` on any `score_best` response says whether it is. Past that, another
-GPU is the only thing that moves the number.
-
-Two cautions about these figures. The backend's 52 is a floor, not a ceiling:
-`bench_backend.py` makes every image unique, so nothing is ever cached, while
-real traffic sends one original image with several candidates and the backend
-caches its encoding — end to end at 96-way the chain reached 60 candidates/s,
-above the "ceiling", for exactly that reason. And throughput past 64-way buys
-little while costing a lot of latency (p50 3.6s to 5.7s), so the useful operating
-range is narrower than the peak suggests.
-
-### As images
-
-`serve/Dockerfile` builds **one image holding both halves** — `vllm serve` for the
-forward pass, and the renderer, precheck and HTTP layer in front of it. It carries
-CUDA wheels, Chromium and CJK fonts, so it is not small (about 24 GB). What it does
-not carry is the weights: the checkpoint is a run-time argument, so one image serves
-any compatible checkpoint and the build context stays small.
-
-```bash
-docker build -f serve/Dockerfile -t minicpm-ocr-jev-1-0:latest .
-
-docker run -d --name minicpm-ocr-jev --gpus '"device=0"' \
- -p 127.0.0.1:8030:8030 \
- -v /path/to/weights:/weights:ro \
- minicpm-ocr-jev-1-0:latest 8030 /weights
-```
-
-Behind a slow link, pass `--build-arg PIP_INDEX_URL=…` and
-`--build-arg PLAYWRIGHT_DOWNLOAD_HOST=…` — see §0 above; without them the build
-takes hours rather than minutes.
-
-Two things about this image are deliberate, and both are worth knowing before you
-modify it.
-
-**It starts from a bare `ubuntu:24.04` and installs through this material's own
-scripts** — the same commands §0 through §2 give a reader with a fresh machine. So
-if the image builds, the documented install works; there is no second, image-only
-path that can drift out of step with these instructions.
-
-**The two halves stay two processes.** `start_all.sh` runs them side by side and
-exits if either dies. One container is about giving callers one address, not about
-merging the two workloads: a browser pool and a vLLM engine in one Python process
-share one asyncio loop, and that loop saturates at roughly a quarter of the
-throughput — measured on one machine, four candidates per request, same GPU and
-checkpoint, 13.0 candidates/s against 54.3. So: one container if you need one
-address, never one process.
-
-If you do want the renderer to scale on its own, you do not need a second image for
-it — run `start_app.sh` on another machine against this one's backend, as
-"Where the ceiling is" describes.
-
----
-
-## Input requirements
-
-**Category.** Every block is `text`, `formula`, or `table`. The category selects the
-render mode, and getting it wrong quietly ruins the score — a formula sent as `text`
-renders as literal LaTeX source rather than typeset math, and will not match the
-original image.
-
-**Tables must be HTML.** The renderer accepts `<table>…</table>`. If your OCR engine
-emits some other table markup, convert it before scoring; anything unrecognised is
-rendered as literal text.
-
-**The original image must be a readable file on disk.** The renderer derives the
-render width from the original image's width, so it reads the file, not just its
-pixels-in-memory.
-
-**Formula blocks render at a higher device scale factor** (3.0, versus 1.0 for text
-and tables). This is why a formula's rendered image comes out much larger than its
-source crop — that is expected, not a bug.
-
----
-
-## The prompt is part of the model
-
-The checkpoint was trained with one exact prompt. The wording, the whitespace, and the
-order of the two images are all fixed:
-
-```
-<|im_start|>user
-{image}
-OCR文本:
-{candidate text}
-{image}
-第一张图是原图,第二张图是上述 OCR 文本渲染得到的图片。
-请判断该 OCR 文本及其对应渲染图是否与原图内容一致。
-这是一个二分类任务:一致标为 1,不一致标为 0。<|im_end|>
-<|im_start|>assistant
-<think>
-
-</think>
-
-```
-
-The first image is the original, the second is the render. Swapping them, translating
-the instruction, or adding a system message changes what the scores mean.
-
-Two parts of that look like padding and are not:
-
-**The newline after each image placeholder.** Dropping it is the easiest way to get
-this wrong, because assembling the prompt through a chat template's content list
-renders the placeholder without one.
-
-**The empty assistant turn at the end**, including the empty `<think>` block. The
-model was trained as a sequence classifier, where the training framework appends that
-turn; vLLM's classify path pools the **last** token, so the value head reads the hidden
-state of the final newline inside it. Cut the turn off and you are pooling a position
-the model never saw pooled during training. It still returns plausible-looking
-probabilities, which is exactly what makes this mistake hard to catch.
-
-`infer_vllm.py` fingerprints the template at import time and refuses to run if it has
-been edited (`PROMPT_TEMPLATE_MD5`). That guard exists because a modified prompt does
-not fail — it silently produces numbers that look fine and are comparable to nothing.
-
----
-
-## Reading the scores
-
-`prob_yes` is `softmax(logits)[1]`, between 0 and 1. Higher means more consistent with
-the original image. Each candidate's score is computed independently, so candidates
-within a block do not compete and scores do not sum to 1.
-
-Every result also carries a `verdict`:
-
-| verdict | `prob_yes` | meaning |
-|---|---|---|
-| `scored` | model output | reached the model normally |
-| `precheck_reject` | `0.0` | KaTeX could not parse the candidate's LaTeX |
-| `render_error` | `0.0` | the candidate could not be rendered |
-| `missing_original_image` | `0.0` | the block image was unreadable |
-
-Rejected candidates are assigned `0.0` rather than dropped: a transcription whose LaTeX
-does not even parse is not a plausible reading of the page, so treating it as "wrong"
-is the useful behaviour. If you would rather see those cases scored anyway, run with
-`--no-precheck` (which also removes the Node dependency).
-
-A `scored` result can still carry `katex_errors`. That means the page rendered, but
-with an error message where the formula should be — the model sees that error text and
-will score it as wrong. The field is there so you can tell this apart from a genuine
-low score.
-
-**Scores are not bitwise reproducible.** vLLM batches requests continuously, so the
-same candidate may be computed alongside different neighbours from one run to the next
-and differ in the last few decimal places. Practically:
-
-- compare rankings within a block, not absolute values across runs
-- keep one engine instance for a whole experiment
-- do not hard-code a threshold calibrated on a single run
-
----
-
-## Matching the reference renderer
-
-The model learned what "correct" looks like from images produced by one specific
-renderer. The closer your renders are to that renderer, the closer your scores are to
-the ones the model was trained to produce.
-
-Three things are pinned in this repo and need no attention from you:
-
-| | | |
-|---|---|---|
-| KaTeX | 0.16.47 | bundled in `renderer/assets/`, ships its own math fonts |
-| Chromium | pinned by `playwright==1.62.0` | pinning Playwright is how the browser gets pinned |
-| Render pipeline | v8.5 | the code in `renderer/`, including the per-category scale factor |
-
-A fourth thing is pinned, but not by the repo — by you, in §1: **body-text fonts come
-from your operating system**. KaTeX bundles its own fonts, so formulas are reproducible
-anywhere. Latin and especially CJK body text is drawn with whatever faces your OS
-provides, and different font builds produce different pixels. §1's four font commands
-are what hold that fixed on Debian and Ubuntu; skip them, or run a distro where those
-package names do not exist, and this is the part of the pipeline that drifts.
-
-`renderer/check_renderer.py` measures this for you. It renders the bundled examples and
-compares against the reference PNGs shipped beside them:
-
-- `identical` — byte-for-byte equal.
-- `close` — a few percent of pixels differ. Normal: anti-aliasing and hinting differ
- between builds of the same font.
-- `drifted` — noticeably different, layout still intact. Expected when your fonts or
- browser build differ from the reference environment.
-- `different` — large differences at nearly the same size. Almost always a missing
- font: text is falling back to another face, or drawing as empty boxes.
-- `mismatched` — the geometry does not match. Something structural: check that KaTeX
- under `renderer/assets/` is intact and that Playwright is pinned.
-
-Only the last two are failures. Some drift is unavoidable, and the bundled references
-make that concrete. They were produced by this same pipeline version, but earlier and
-on another machine, with an older Chromium build. Re-rendering them under the pinned
-environment gives:
-
-| example | result |
-|---|---|
-| formula | `identical`, byte for byte |
-| table | `close` — 2.3% of pixels differ |
-| text | `drifted` — 10px narrower, which shifts the line and surfaces as 10% of pixels |
-
-Two things are worth knowing about those numbers, because both were measured rather
-than assumed.
-
-**The text drift is not local to one machine.** The same 10px narrower render came out
-of two unrelated environments — a purpose-built image and a bare Ubuntu container that
-installed everything from scratch. Two independent environments agreeing on the same
-output points at the references, not at the local setup: they predate the pinned
-Chromium. So this particular drift is the pin doing its job, and you should expect to
-reproduce it too.
-
-**The font set changes which candidate wins; it does not change how well the model
-separates good from bad.** These are two different questions and they have two
-different answers, so both are worth stating. Pixel-wise the effect is small: swapping
-the font set entirely — from whatever Playwright's `--with-deps` pulls in, to the face
-set §1 pins — moved the Chinese table example by less than half a percent of pixels.
-Score-wise it is small but not nothing: across 200 blocks with four candidates each,
-the same swap moved `prob_yes` by a mean of 0.017 and changed the **top-ranked
-candidate on 16.5% of blocks**, against a 1% floor from re-running one identical
-container. And yet ranking quality is untouched: on a held-out set of 2,267 blocks,
-AUROC ×100 came out 93.7 with the pinned fonts and 93.8 without — a paired difference
-of +0.08 points with a bootstrap interval of [−0.07, +0.23] points (computed before
-rounding), i.e. indistinguishable,
-and measured tightly enough to mean "no difference" rather than "no power".
-
-The practical reading: if you are **measuring** the model, the font set is not what
-decides your number and you can skip §1's font step. If you are using the model to
-**pick** the best of several OCR outputs and want the same picks as the reference
-deployment, pin it — a sixth of close blocks go the other way otherwise. With *no* CJK
-font at all it is a different story again: text renders as empty boxes and the score is
-meaningless.
-
-Formulas are the exception to all of this: they came out byte-identical in every
-environment tested, because KaTeX carries its own fonts. If a *formula* example reports
-worse than `close`, suspect your KaTeX or browser pin rather than your fonts.
-
-If `fc-list :lang=zh | wc -l` reports 0, install a CJK font before anything else —
-any of them will do:
-
-```bash
-sudo apt-get install fonts-noto-cjk # Debian/Ubuntu
-sudo dnf install google-noto-sans-cjk-fonts # Fedora
-```
-
-Two stages run as subprocesses rather than in-process, on purpose: that is what keeps
-the rendered bytes identical to the pipeline the model was trained against.
-Reimplementing either stage would change the pixels, and therefore the scores.
-
----
-
-## Examples
-
-Each directory in [`examples/`](examples/) holds a document block, two candidate
-transcriptions with their labels, and the reference render of one of them.
-
-Running `python3 infer_vllm.py --model ./weights --examples` on the reference setup
-produced these scores, which your run should land near:
-
-| | reference transcription | OCR output | what it shows |
-|---|---|---|---|
-| `01_text_putnam` | 0.995 | 0.007 | The OCR output keeps nearly every token but merges list items (a) and (b) and re-emits the content out of order. Order-insensitive text metrics score this highly; the rendered image makes it obvious. |
-| `02_formula_putnam` | 0.968 | 0.966 | Both candidates are labelled consistent despite very different LaTeX — `$$…$$` vs `\[…\]`, `'` vs `\prime`, extra spacing. Rendering collapses the difference; string comparison would not. |
-| `03_table_gb_standard` | **0.041** | 0.001 | Three real OCR errors in one table: the unit `s` read as `a` in three cells, 电压切断 read as 电压倒落, and a rebuilt row structure. |
-
-The third row is the one worth sitting with. Its reference transcription is faithful —
-it matches the block — and still scores 0.04. The *ranking* is right, by a factor of 35,
-but the absolute number does not mean "this transcription is wrong". If you were
-filtering on `prob_yes > 0.5`, you would throw away a correct transcription here.
-
-We have not established why. The renderer lays tables out at a fixed width, so a small
-source crop and its render differ considerably in scale, which is a plausible cause
-but not a demonstrated one. Either way it is the concrete reason for the advice above:
-**compare candidates against each other, not against a threshold.**
-
-Only the OCR candidate in each example carries a label from the source dataset. The
-reference transcription is the dataset's ground-truth text, which that dataset does
-not itself label or score — so do not read it as "the answer the model should return
-1.0 for".
-
-The document blocks come from [OmniDocBench](https://github.com/opendatalab/OmniDocBench)
-v1.6 — specifically pages from the Putnam Competition archive and from a published
-Chinese national standard. They are included to make the examples runnable; the
-identity of the OCR engine that produced each erroneous candidate is withheld, since
-the point is the error pattern, not the engine.
-
----
-
-## Troubleshooting
-
-**`libgbm.so.1: cannot open shared object file`** (or another missing library at
-browser launch). Chromium downloaded, but its system libraries did not. This is the
-most common first-run failure:
-
-```bash
-python3 -m playwright install --with-deps chromium
-```
-
-If you cannot install system packages — a shared cluster, no root — put the missing
-libraries somewhere you control and pass an interpreter wrapper that sets
-`LD_LIBRARY_PATH` for the render subprocess only:
-
-```bash
-python3 infer_vllm.py --render-python /path/to/wrapper.sh ...
-```
-
-Under the service, the same wrapper goes in `RM_RENDER_PYTHON` instead — see
-"Tuning", which also covers the other reason to set it: a renderer and a vLLM
-installed in two different environments.
-
-Setting `LD_LIBRARY_PATH` globally instead is a bad idea: it also lands in front of
-the loader path for the inference process.
-
-**Rendered images are blank or full of boxes.** Missing fonts. Run
-`renderer/check_renderer.py`; if it reports `different` or `mismatched`, start with
-`fc-list :lang=zh | wc -l`.
-
-**`node not found`.** The precheck stage needs Node; it has been tested on Node 12,
-18 and 22, so your distribution's default is almost certainly fine. Install it, or
-run with `--no-precheck` and accept that unparsable candidates get scored instead of
-rejected.
-
-**Engine fails to load with an out-of-memory error.** Lower `GPU_MEM_UTIL`, which
-`start_vllm.sh` passes to vLLM as `--gpu-memory-utilization` and defaults to **0.80**.
-The engine reserves that fraction of VRAM at startup, so another process on the same
-GPU will collide with it: `GPU_MEM_UTIL=0.6 bash serve/start_vllm.sh 0 8026 ./weights`.
-
-**`expected 2 class logits from the value head`.** The checkpoint is not a 2-class
-sequence-classification model, or vLLM loaded it in a different mode. Check that your
-build supports `runner="pooling"` with `convert="classify"`.
-
-**Every candidate scores near 0.** Check the category first — a formula or table scored
-as `text` renders as literal markup and will not match anything.
diff --git a/scripts/minicpm-ocr-jev/renderer/setup_renderer.sh b/scripts/minicpm-ocr-jev/renderer/setup_renderer.sh
index 759b646..c53f758 100644
--- a/scripts/minicpm-ocr-jev/renderer/setup_renderer.sh
+++ b/scripts/minicpm-ocr-jev/renderer/setup_renderer.sh
@@ -6,7 +6,7 @@
# images produced by one specific combination of browser, KaTeX and fonts, so this
# script pins the browser and KaTeX, and then reports on the fonts, which are the
# one part it cannot install for you: fonts come from your operating system. The
-# README's font step pins those; this script tells you whether they are pinned.
+# The Docker image pins those; this script tells you whether they are pinned.
#
# Run from anywhere: bash renderer/setup_renderer.sh
#
@@ -111,7 +111,7 @@ if command -v fc-list >/dev/null 2>&1; then
With none at all, Chinese blocks render as empty boxes and score meaninglessly.
Which CJK font you install matters much less for pixels -- swapping font sets
moved the bundled references by under half a percent -- but it does decide which
- candidate wins a close block; see the font step in README \"1. The renderer\"."
+ candidate wins a close block."
problems=$((problems + 1))
fi
@@ -133,7 +133,7 @@ if command -v fc-list >/dev/null 2>&1; then
printf 'Font environment differs from the reference deployment:\n'
printf "$pin_notes"
printf ' Fine for measuring the model; pin it if you need the reference bytes\n'
- printf ' or the same best-of-N picks. Four commands, in README "1. The renderer".\n'
+ printf ' or the same best-of-N picks. Pin it with sdk/setup_render.sh or serve/Dockerfile.\n'
fi
elif [ "$(uname -s)" = "Darwin" ]; then
printf 'macOS: system CJK fonts are present by default (fc-list not installed).\n'
diff --git a/scripts/minicpm-ocr-jev/requirements.txt b/scripts/minicpm-ocr-jev/requirements.txt
index e067af1..ffd9132 100644
--- a/scripts/minicpm-ocr-jev/requirements.txt
+++ b/scripts/minicpm-ocr-jev/requirements.txt
@@ -1,6 +1,6 @@
# Renderer. These three decide what the rendered image looks like, pixel for pixel,
# so they are pinned to the versions the model was trained and served with.
-# Changing them changes the scores. See README, "Matching the reference renderer".
+# Changing them changes the scores.
playwright==1.62.0
Pillow==12.3.0
Markdown==3.10.3
@@ -13,7 +13,7 @@ Markdown==3.10.3
#
# bash serve/setup_backend.sh <venv dir>
#
-# See README, "Install / 2. vLLM". Any build that registers
+# Any build that registers
# Qwen3_5ForConditionalGeneration serves this model; setup_backend.sh checks for
# that rather than for a version number. Verified with:
#
diff --git a/scripts/minicpm-ocr-jev/sdk/README.md b/scripts/minicpm-ocr-jev/sdk/README.md
deleted file mode 100644
index 52717f4..0000000
--- a/scripts/minicpm-ocr-jev/sdk/README.md
+++ /dev/null
@@ -1,158 +0,0 @@
-# Local deployment without our image
-
-`sdk/` is the second way to run this model. The first is the published image,
-built from `serve/`, which carries a browser, a font set and a pinned Chromium so
-that it reproduces the reference scores byte for byte. This one installs onto a
-host you already have.
-
-The trade is explicit: **you get your own renderer, and your own renderer draws
-slightly different pixels.** Rendered text is model input here, so different
-pixels mean different scores. On the machine this was built on, the three bundled
-examples came out one byte-identical, one within 2.3% of pixels, one within
-10.2% — and the end-to-end scores landed within 0.009 of the image's, with the
-best candidate unchanged in all three blocks. Rankings are what this model is
-for; the third decimal place is not promised. Run `renderer/check_renderer.py`
-after installing and quote the number it gives you.
-
-Use the image when you need the published numbers. Use this when you need the
-model on a host of your own.
-
-## Layers
-
-```
-render+score sdk/app.py original image + candidate text -> render -> prob_yes
-score sdk/jev_score/ original + rendered image + text -> prob_1
-engine vllm serve logits
-```
-
-Pick the layer by what you already have:
-
-* **Renders made elsewhere, or no browser on the host** — run the engine and the
- score service. It needs `sdk/requirements-score.txt` and nothing else: no
- Chromium, no Node, no fonts.
-* **Text in, score out** — run the engine and the render+score service. It
- imports the score layer in its own process; there is no socket between them,
- and you do not start the score service separately.
-
-The score layer returns `prob_1` and only `prob_1`: no threshold, no label, no
-logits. A probability is comparable across runs, a label is a probability plus
-somebody's threshold, and a threshold shipped inside a library ends up applied to
-runs it was never calibrated on. The render+score service keeps the published
-field name `prob_yes` and the same endpoints as the image, so callers move
-between the two without edits.
-
-## Install
-
-Two virtual environments, and that is a requirement rather than tidiness: the
-renderer pins `Pillow==12.3.0` because that version decides what the rendered
-image looks like, while vLLM asks only for `pillow>=12.3.0`. In one shared
-environment a later `pip install -U vllm` moves Pillow forward and changes every
-score, silently and with no error.
-
-```bash
-# 1. the forward pass
-bash serve/setup_backend.sh /opt/venv-vllm
-
-# 2. the renderer -- only if you want render+score
-bash sdk/setup_render.sh /opt/venv-render
-```
-
-Behind a slow link, set both mirrors. `PLAYWRIGHT_DOWNLOAD_HOST` is not covered
-by `PIP_INDEX_URL`, and Playwright's own CDN is where this install usually
-stalls:
-
-```bash
-PIP_INDEX_URL=https://<mirror>/simple \
-PLAYWRIGHT_DOWNLOAD_HOST=https://<mirror>/playwright \
- bash sdk/setup_render.sh /opt/venv-render
-```
-
-`gcc`, `g++` and `python3-dev` are run-time dependencies, not build-time ones:
-Triton compiles a CPython extension on the first forward pass of every fresh
-process. Removing them after installing produces a backend that loads the
-weights, runs for two minutes and dies on a bare `CalledProcessError`.
-
-## Run
-
-```bash
-# the engine -- note there is no --chat-template
-PATH=/opt/venv-vllm/bin:$PATH bash sdk/start_engine.sh 0 18499 /path/to/weights
-
-# then one of:
-PATH=/opt/venv-render/bin:$PATH bash sdk/start_score.sh 18501 http://127.0.0.1:18499
-PATH=/opt/venv-render/bin:$PATH bash sdk/start_render_score.sh 18500 http://127.0.0.1:18499
-```
-
-The render+score service renders in its own process, so it must run with the
-renderer's interpreter.
-
-### score
-
-```
-POST /v1/score {"items": [{"original_image": <b64>,
- "render_image": <b64>,
- "ocr_text": "..."}]}
- -> {"results": [{"prob_1": 0.00227, "error": null}]}
-```
-
-`ocr_text` goes to the model exactly as given. It is not stripped: whitespace is
-in the rendered image too, and the model is being asked to compare the two.
-
-### render+score
-
-`/healthz`, `/v1/rm/score`, `/v1/rm/score_best`, `/v1/rm/score_best_batch` —
-same request and response shapes as the image serves, including `stage_sec` and
-the `throughput_rate` summary. `RM_THRESHOLD` (default 0.5) affects the summary
-only; no item's `prob_yes` is ever rounded or decided for you.
-
-## The startup check, and what it does not cover
-
-Both services refuse to start if the engine does not assemble the prompt this
-checkpoint was trained on. This matters more than it sounds, because the failure
-has no symptom: a wrong prompt still returns 200, still returns a number in
-range, still ranks candidates plausibly, and is on a different scale.
-
-Three request keys are load-bearing, and `sdk/` sends all three explicitly rather
-than relying on any default:
-
-```python
-"add_generation_prompt": True # /classify defaults to False
-"chat_template_kwargs": {"enable_thinking": False} # at top level it is ignored
-"use_activation": False # we softmax the two logits ourselves
-```
-
-Measured on vLLM 0.32.0, `/classify` and `/tokenize` **disagree** about
-`add_generation_prompt`: the scoring endpoint defaults it to `False`, the
-endpoint the check interrogates defaults it to `True`. That is why the check has
-a half that reads the outgoing request rather than the engine's reply.
-
-What the check covers depends on what is installed:
-
-| | needs | catches |
-|---|---|---|
-| pooled position | engine only | the assistant turn being cut off (last token 198 instead of 271) |
-| outgoing request | nothing | the adapter not sending the three keys above |
-| token-for-token | `transformers` + the weights on this host | everything else: image/text ordering, a missing newline, any template change |
-
-Without the weights reachable from the service, the third row is skipped and the
-check keeps roughly half its discriminating power. Set `JEV_WEIGHTS` to the
-checkpoint directory to get all of it.
-
-`JEV_ALLOW_UNVERIFIED=1` starts anyway. It is for bringing up a new engine, where
-the check failing is the thing being worked on. Scores produced that way are not
-comparable to any published number.
-
-## Backends
-
-`sdk/backends/vllm.yaml` selects the engine and says where to reach it. Only vLLM
-is implemented: SGLang and llama.cpp both need upstream work that has not landed,
-so their adapters would be untested code shipped as if it worked. The interface
-they will implement is `sdk/jev_score/backends/base.py`, and naming either engine
-in the config gives you that message rather than a vague failure.
-
-## What is not here
-
-`serve/` is unchanged and stays the image's source. This directory is excluded
-from the image build context (`.dockerignore`), so editing it cannot move the
-image's digest — the two routes are meant to be independently verifiable, which
-they stop being the moment one rebuilds when the other changes.
diff --git a/scripts/minicpm-ocr-jev/sdk/backends/llamacpp.yaml b/scripts/minicpm-ocr-jev/sdk/backends/llamacpp.yaml
new file mode 100644
index 0000000..4541f12
--- /dev/null
+++ b/scripts/minicpm-ocr-jev/sdk/backends/llamacpp.yaml
@@ -0,0 +1,27 @@
+# Which engine runs the forward pass, and where to reach it.
+#
+# Start the engine with llama-server; the deployment guide is
+# docs/llamacpp_deploy_jev_zh.md. Two things differ from the vLLM path:
+# the prompt comes from a template baked into the GGUF and cannot be read back,
+# so the startup gate reports it as unverifiable rather than green; and
+# /v1/systemone answers with class probabilities instead of raw logits, which
+# the adapter declares so the score layer does not softmax them a second time.
+
+engine: llamacpp
+
+# Where llama-server is listening. Host and port only; the adapter appends the
+# endpoint paths (/v1/systemone, /v1/models).
+base_url: http://127.0.0.1:18499
+
+# What the engine calls the model. Leave it unset: llama-server serves the one
+# GGUF it was started with and the scoring endpoint takes no model name, so the
+# adapter asks /v1/models only to report an identity in /healthz.
+# model: MiniCPM-OCR-Jev-bf16
+
+# Seconds to wait on one forward pass.
+timeout_sec: 120
+
+# Requests in flight toward the engine. llama-server serves -np slots sharing one
+# context window and queues the rest; this bounds our sockets and memory rather
+# than the engine's throughput.
+max_in_flight: 32
diff --git a/scripts/minicpm-ocr-jev/sdk/backends/ollama.yaml b/scripts/minicpm-ocr-jev/sdk/backends/ollama.yaml
new file mode 100644
index 0000000..d62a3cd
--- /dev/null
+++ b/scripts/minicpm-ocr-jev/sdk/backends/ollama.yaml
@@ -0,0 +1,28 @@
+# Which engine runs the forward pass, and where to reach it.
+#
+# Start the engine with `ollama serve`; the deployment guide is
+# docs/ollama_deploy_jev_zh.md. Ollama runs llama.cpp underneath, so it shares
+# that path's two differences from vLLM: the prompt comes from a template baked
+# into the GGUF and cannot be read back, so the startup gate reports it as
+# unverifiable rather than green; and /v1/systemone answers with class
+# probabilities instead of raw logits, which the adapter declares so the score
+# layer does not softmax them a second time.
+
+engine: ollama
+
+# Where `ollama serve` is listening. 11434 is its default, not 18499.
+base_url: http://127.0.0.1:11434
+
+# ⭐ Required here, unlike every other engine: Ollama hosts many models and
+# routes by name. This must be the name `ollama create` registered -- change it
+# in both places or requests go to a model that does not exist. Startup fails
+# with a message saying so rather than defaulting to anything.
+model: ocr-jev
+
+# Seconds to wait on one forward pass.
+timeout_sec: 120
+
+# Requests in flight toward the engine. Ollama starts llama-server with parallel
+# slots sharing one KV cache and queues past that; this bounds our sockets and
+# memory rather than the engine's throughput.
+max_in_flight: 32
diff --git a/scripts/minicpm-ocr-jev/sdk/backends/sglang.yaml b/scripts/minicpm-ocr-jev/sdk/backends/sglang.yaml
new file mode 100644
index 0000000..ed23e0a
--- /dev/null
+++ b/scripts/minicpm-ocr-jev/sdk/backends/sglang.yaml
@@ -0,0 +1,25 @@
+# Which engine runs the forward pass, and where to reach it.
+#
+# Start the engine with sdk/start_engine_sglang.sh. Unlike the vLLM path, this
+# one applies no chat template: the SDK sends the finished prompt string and
+# SGLang runs it as given. What the startup gate checks therefore moves to our
+# side of the wire -- see the `client` branch in sdk/jev_score/selfcheck.py.
+
+engine: sglang
+
+# Where sglang.launch_server is listening. Host and port only; the adapter
+# appends the endpoint paths (/classify, /get_model_info).
+base_url: http://127.0.0.1:18499
+
+# What the engine calls the model. Leave it unset: the adapter asks
+# /get_model_info, which reports the checkpoint path the server was started
+# with. Set it only to pin a name in a log.
+# model: minicpm-ocr-jev
+
+# Seconds to wait on one forward pass. Generous because a cold engine spends its
+# first request capturing CUDA graphs.
+timeout_sec: 120
+
+# Requests in flight toward the engine. SGLang queues past its own capacity, so
+# this bounds our sockets and memory rather than the engine's throughput.
+max_in_flight: 32
diff --git a/scripts/minicpm-ocr-jev/sdk/jev_score/backends/__init__.py b/scripts/minicpm-ocr-jev/sdk/jev_score/backends/__init__.py
index 65e70c5..9130c4d 100644
--- a/scripts/minicpm-ocr-jev/sdk/jev_score/backends/__init__.py
+++ b/scripts/minicpm-ocr-jev/sdk/jev_score/backends/__init__.py
@@ -1,9 +1,8 @@
"""Backend selection.
Which engine runs the forward pass is a deployment choice, not a code change, so
-it is read from a file: `sdk/backends/<engine>.yaml`. The shipped one is
-`vllm.yaml`; SGLang and llama.cpp get their own once the upstream work they
-depend on lands.
+it is read from a file: `sdk/backends/<engine>.yaml`. One ships per engine;
+`vllm.yaml` is the default, and `JEV_BACKEND_CONFIG` picks another.
"""
from __future__ import annotations
@@ -20,15 +19,17 @@ __all__ = ["Backend", "BackendError", "load_backend", "load_config", "DEFAULT_CO
CONFIG_DIR = Path(__file__).resolve().parents[2] / "backends"
DEFAULT_CONFIG = CONFIG_DIR / "vllm.yaml"
-#: Engines that are implemented *and* have been run against the model. The two
-#: absent ones are listed here rather than silently missing, because "not
-#: supported yet" and "you spelled it wrong" are different problems for whoever
-#: is reading the error.
-KNOWN_ENGINES = {"vllm"}
-PLANNED_ENGINES = {
- "sglang": "the classify path needs an upstream PR that is not merged yet",
- "llamacpp": "the classify path needs an upstream PR that is not merged yet",
-}
+#: Engines this SDK has an adapter for. Each has a shipped config of the same
+#: name in `sdk/backends/`, and the error for anything else names them all,
+#: because "not supported" and "you spelled it wrong" are different problems for
+#: whoever is reading it.
+#:
+#: What they do *not* all share is how the scores come back. vLLM and SGLang hand
+#: over the two raw logits; llama.cpp and Ollama answer with the probabilities
+#: already activated. Each adapter declares which via `output_kind`, and
+#: `scorer.py` branches on that -- see `base.py` for why that distinction is
+#: worth a field rather than a convention.
+KNOWN_ENGINES = {"vllm", "sglang", "llamacpp", "ollama"}
def load_config(path: str | Path | None = None) -> dict[str, Any]:
@@ -36,6 +37,19 @@ def load_config(path: str | Path | None = None) -> dict[str, Any]:
import yaml
chosen = Path(path or os.environ.get("JEV_BACKEND_CONFIG") or DEFAULT_CONFIG)
+ if not chosen.is_file() and not chosen.is_absolute():
+ # A relative path is resolved against the cwd of *this process*, which is
+ # not where the operator typed the command: start_score.sh and
+ # start_render_score.sh both `cd` into sdk/ before exec'ing uvicorn. So
+ # `JEV_BACKEND_CONFIG=sdk/backends/sglang.yaml` -- the spelling the deploy
+ # docs use, correct relative to the directory they tell you to stand in --
+ # would otherwise never resolve. Try it against the SDK root, then against
+ # the shipped config directory, so `sglang.yaml` works too.
+ for base in (CONFIG_DIR.parent.parent, CONFIG_DIR):
+ candidate = base / chosen
+ if candidate.is_file():
+ chosen = candidate
+ break
if not chosen.is_file():
raise FileNotFoundError(
f"backend config not found: {chosen}\n"
@@ -59,12 +73,6 @@ def load_backend(path: str | Path | None = None, **overrides: Any) -> Backend:
engine = str(config.get("engine", "")).strip().lower()
if engine not in KNOWN_ENGINES:
- if engine in PLANNED_ENGINES:
- raise NotImplementedError(
- f"backend '{engine}' is not implemented yet: {PLANNED_ENGINES[engine]}.\n"
- f"The adapter interface it will implement is in "
- f"{Path(__file__).parent / 'base.py'}."
- )
raise ValueError(
f"{config.get('_source')}: unknown engine {engine!r}. "
f"Known: {', '.join(sorted(KNOWN_ENGINES))}."
@@ -74,11 +82,29 @@ def load_backend(path: str | Path | None = None, **overrides: Any) -> Backend:
if not base_url:
raise ValueError(f"{config.get('_source')}: 'base_url' is required")
+ # Same four arguments for every engine: the adapters differ in what they put
+ # on the wire, not in how they are configured.
+ kwargs: dict[str, Any] = {
+ "model": config.get("model") or None,
+ "timeout": float(config.get("timeout_sec", 120.0)),
+ "max_in_flight": int(config.get("max_in_flight", 32)),
+ }
+
+ if engine == "sglang":
+ from .sglang_backend import SGLangBackend
+
+ return SGLangBackend(str(base_url), **kwargs)
+
+ if engine == "llamacpp":
+ from .llamacpp_backend import LlamaCppBackend
+
+ return LlamaCppBackend(str(base_url), **kwargs)
+
+ if engine == "ollama":
+ from .ollama_backend import OllamaBackend
+
+ return OllamaBackend(str(base_url), **kwargs)
+
from .vllm_backend import VLLMBackend
- return VLLMBackend(
- str(base_url),
- model=config.get("model") or None,
- timeout=float(config.get("timeout_sec", 120.0)),
- max_in_flight=int(config.get("max_in_flight", 32)),
- )
+ return VLLMBackend(str(base_url), **kwargs)
diff --git a/scripts/minicpm-ocr-jev/sdk/jev_score/backends/llamacpp_backend.py b/scripts/minicpm-ocr-jev/sdk/jev_score/backends/llamacpp_backend.py
new file mode 100644
index 0000000..9bfb490
--- /dev/null
+++ b/scripts/minicpm-ocr-jev/sdk/jev_score/backends/llamacpp_backend.py
@@ -0,0 +1,192 @@
+"""llama.cpp adapter: `llama-server` with the decision-model endpoint.
+
+This engine is the far end of the spectrum the other two adapters sit on. vLLM
+holds the model's `chat_template.jinja` and assembles the prompt from a content
+list; SGLang holds no template and runs the finished string we send. llama.cpp
+holds a template too -- `systemone`, baked into the GGUF at conversion time --
+but unlike vLLM's it cannot be read back out over HTTP. So `/v1/systemone` takes
+only the parts that vary: the candidate text in `state`, the two images in
+`files`.
+
+Two consequences, both of which the rest of the SDK has to be told about rather
+than left to discover:
+
+ the prompt cannot be verified There is no endpoint that returns what the
+ server will build. `selfcheck.py` reports that as a fact instead of
+ pretending to check it -- the `server_template` branch there. What still
+ gets checked is the forward pass itself.
+
+ the scores arrive activated `/v1/systemone` answers with the class
+ probabilities, not the two raw logits. `output_kind` says so, and
+ `scorer.py` takes the number rather than softmaxing it twice. The scale is
+ the published one because this softmax is the same one -- temperature 1
+ over the same value head -- which is the only reason this is acceptable;
+ see `base.py`.
+
+`type: "choice"` rather than `"noul"`: both ask the same question, but `choice`
+with an empty criterion per class returns the whole distribution, and two
+numbers are what the startup shape check needs in order to be a check at all.
+A single number cannot distinguish a decision model from anything else that
+returns a float.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import httpx
+
+from ..prompt import PromptParts
+from .base import BackendError
+
+__all__ = ["LlamaCppBackend"]
+
+
+class LlamaCppBackend:
+ """Talks to one `llama-server` process over HTTP."""
+
+ #: The engine builds the prompt from a template we cannot read. `selfcheck.py`
+ #: branches on this and reports the prompt as unverifiable rather than green.
+ prompt_source = "server_template"
+
+ #: `/v1/systemone` has already applied the softmax. See `base.py`.
+ output_kind = "probabilities"
+
+ #: The question this model answers. One question per request, named so the
+ #: answer can be found again in the response.
+ QUESTION = "consistency"
+
+ def __init__(
+ self,
+ base_url: str,
+ *,
+ model: str | None = None,
+ timeout: float = 120.0,
+ max_in_flight: int = 32,
+ ) -> None:
+ self.base_url = base_url.rstrip("/")
+ self._model_override = model
+ self._model: str | None = model
+ self._client = httpx.AsyncClient(timeout=timeout)
+ import asyncio
+
+ self._gate = asyncio.Semaphore(max_in_flight)
+
+ # ── identity ─────────────────────────────────────────────────────────────
+
+ async def served_name(self) -> str | None:
+ """What `llama-server` was started with, via the OpenAI-shaped listing.
+
+ `/v1/models` is the one endpoint of that family this server implements
+ usefully here: it reports the GGUF it loaded. The scoring endpoint itself
+ is not OpenAI-shaped and takes no model name.
+ """
+ if self._model:
+ return self._model
+ try:
+ resp = await self._client.get(f"{self.base_url}/v1/models", timeout=5.0)
+ except httpx.HTTPError:
+ return None
+ if resp.status_code != 200:
+ return None
+ try:
+ entries = resp.json().get("data") or []
+ name = entries[0].get("id")
+ except (AttributeError, IndexError, TypeError, ValueError):
+ return None
+ if name:
+ self._model = str(name)
+ return self._model
+
+ # ── request shape ────────────────────────────────────────────────────────
+
+ def _systemone_body(
+ self, parts: PromptParts, original_data_url: str, render_data_url: str
+ ) -> dict[str, Any]:
+ """The exact body `forward` posts. Separate so the self-check can read it.
+
+ Image order is load-bearing and silent when wrong: the baked template
+ puts the first image before the OCR text and the second after it, and
+ says so in words. Swapping them asks the model a different question and
+ still returns a number in range.
+
+ No `instructions`: the task is fixed by the model, and the template has
+ it. Sending one here would put a second copy of the task in the prompt.
+ """
+ return {
+ "state": parts.ocr_text,
+ "files": [original_data_url, render_data_url],
+ "questions": {
+ self.QUESTION: {"type": "choice", "criteria": {"0": None, "1": None}}
+ },
+ }
+
+ def describe_scoring_request(self, parts: PromptParts) -> dict[str, Any]:
+ """`_systemone_body` with the image payloads elided, for the self-check."""
+ return self._systemone_body(parts, "<original>", "<render>")
+
+ def _read_probabilities(self, payload: Any, raw: str) -> list[float]:
+ """The two class probabilities out of the `systemone` answer shape.
+
+ Reads the classes by name rather than by position: the response holds a
+ mapping, and a mapping has no order to rely on. Getting this backwards
+ would invert every score while every score stayed in range.
+ """
+ try:
+ answer = payload["answers"][self.QUESTION]
+ except (KeyError, TypeError):
+ raise BackendError(
+ f"the response carries no answer named {self.QUESTION!r}: {raw[:300]}"
+ ) from None
+ probs = answer.get("probabilities") if isinstance(answer, dict) else None
+ if not isinstance(probs, dict):
+ raise BackendError(
+ "the answer carries no 'probabilities' mapping. A server that "
+ "answers with a single number was asked a different question "
+ f"type than 'choice': {raw[:300]}"
+ )
+ missing = [k for k in ("0", "1") if k not in probs]
+ if missing:
+ raise BackendError(
+ f"the answer is missing class {', '.join(missing)}. Ask with "
+ "criteria {\"0\": null, \"1\": null} to get both classes."
+ )
+ try:
+ return [float(probs["0"]), float(probs["1"])]
+ except (TypeError, ValueError) as exc:
+ raise BackendError(f"unreadable class probabilities: {raw[:300]}") from exc
+
+ # ── the two calls ────────────────────────────────────────────────────────
+
+ async def forward(
+ self,
+ parts: PromptParts,
+ original_data_url: str,
+ render_data_url: str,
+ ) -> list[float]:
+ body = self._systemone_body(parts, original_data_url, render_data_url)
+ try:
+ async with self._gate:
+ resp = await self._client.post(f"{self.base_url}/v1/systemone", json=body)
+ except httpx.HTTPError as exc:
+ raise BackendError(f"backend unreachable: {exc}") from exc
+ if resp.status_code != 200:
+ raise BackendError(f"backend HTTP {resp.status_code}: {resp.text[:300]}")
+
+ try:
+ payload = resp.json()
+ except ValueError as exc:
+ raise BackendError(f"unreadable response: {resp.text[:300]}") from exc
+ return self._read_probabilities(payload, resp.text)
+
+ async def tokenize(self, parts: PromptParts) -> list[int] | None:
+ """Not available: the prompt is assembled inside the server.
+
+ `llama-server` does expose a tokenizer, but tokenizing anything we could
+ send it would describe our string rather than the one the baked template
+ produces -- the gap between the two is precisely what a prompt check
+ would be for. None is the honest answer; `selfcheck.py` surfaces it.
+ """
+ return None
+
+ async def aclose(self) -> None:
+ await self._client.aclose()
diff --git a/scripts/minicpm-ocr-jev/sdk/jev_score/backends/ollama_backend.py b/scripts/minicpm-ocr-jev/sdk/jev_score/backends/ollama_backend.py
new file mode 100644
index 0000000..af537aa
--- /dev/null
+++ b/scripts/minicpm-ocr-jev/sdk/jev_score/backends/ollama_backend.py
@@ -0,0 +1,89 @@
+"""Ollama adapter: `ollama serve`, the same decision-model endpoint.
+
+Ollama runs `llama-server` underneath, so everything that makes llama.cpp
+different from the other two engines is true here as well: the `systemone`
+template is baked into the GGUF and cannot be read back, and `/v1/systemone`
+answers with class probabilities rather than raw logits. That is why this adapter
+inherits rather than repeats -- the response shape, the two guards on it, and
+both facts the rest of the SDK branches on live in one place.
+
+What Ollama changes is the envelope, in two ways that are easy to get wrong
+because each fails as an error rather than as a wrong number:
+
+ the model is named Ollama hosts many models and routes by name, so the
+ name from `ollama create` has to travel in every request. llama.cpp serves
+ the one GGUF it was started with and takes no name at all.
+
+ images are bare base64 Ollama's field is `images` and wants the base64 on its
+ own; llama.cpp's is `files` and wants a `data:` URL. The SDK produces data
+ URLs, so this adapter strips the prefix on the way out.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+from ..prompt import PromptParts
+from .base import BackendError
+from .llamacpp_backend import LlamaCppBackend
+
+__all__ = ["OllamaBackend"]
+
+
+def _bare_base64(data_url: str) -> str:
+ """The payload of a `data:` URL, or the string unchanged if it is already bare.
+
+ Tolerant on the way in and strict on the way out: callers inside this SDK
+ always pass a data URL, but a caller that had the base64 to begin with should
+ not have to wrap it just to have it unwrapped.
+ """
+ marker = ";base64,"
+ at = data_url.find(marker)
+ return data_url[at + len(marker):] if at != -1 else data_url
+
+
+class OllamaBackend(LlamaCppBackend):
+ """Talks to one `ollama serve` process over HTTP."""
+
+ def __init__(
+ self,
+ base_url: str,
+ *,
+ model: str | None = None,
+ timeout: float = 120.0,
+ max_in_flight: int = 32,
+ ) -> None:
+ if not model:
+ raise BackendError(
+ "the Ollama backend needs the model name: set 'model' in "
+ "sdk/backends/ollama.yaml to whatever `ollama create` registered "
+ "(e.g. ocr-jev). Ollama routes by name, and it has no default."
+ )
+ super().__init__(
+ base_url, model=model, timeout=timeout, max_in_flight=max_in_flight
+ )
+
+ # ── identity ─────────────────────────────────────────────────────────────
+
+ async def served_name(self) -> str | None:
+ """The configured name, which for this engine is the whole of its identity.
+
+ Not asked over HTTP, unlike every other adapter here: Ollama would list
+ every model it hosts, and which of them answers our requests is decided
+ by the name we send, not by anything the server reports. The name is
+ required in the constructor, so this cannot be None.
+ """
+ return self._model
+
+ # ── request shape ────────────────────────────────────────────────────────
+
+ def _systemone_body(
+ self, parts: PromptParts, original_data_url: str, render_data_url: str
+ ) -> dict[str, Any]:
+ """llama.cpp's body with Ollama's envelope: named model, bare base64."""
+ body = super()._systemone_body(parts, original_data_url, render_data_url)
+ files = body.pop("files")
+ return {
+ "model": self._model,
+ **body,
+ "images": [_bare_base64(f) for f in files],
+ }
diff --git a/scripts/minicpm-ocr-jev/sdk/jev_score/backends/sglang_backend.py b/scripts/minicpm-ocr-jev/sdk/jev_score/backends/sglang_backend.py
new file mode 100644
index 0000000..e7ef6ed
--- /dev/null
+++ b/scripts/minicpm-ocr-jev/sdk/jev_score/backends/sglang_backend.py
@@ -0,0 +1,148 @@
+"""SGLang adapter: `python -m sglang.launch_server --is-embedding`.
+
+The division of labour is the mirror image of the vLLM path. There, the engine
+holds the model's `chat_template.jinja` and assembles the prompt from a content
+list we hand it; the whole self-check exists to prove the engine still assembles
+the right one. Here the engine applies no template at all: `/classify` takes a
+finished prompt string in `text` and the two images in `image_data`, and renders
+nothing. `PromptParts.raw` is that string.
+
+So the failure this adapter can have is a different one, and it moves to our
+side of the wire: nothing downstream can mangle the prompt, but this file could
+build the wrong one. `build_prompt()` is fingerprinted at import
+(`PROMPT_TEMPLATE_MD5`), and `selfcheck.py` compares what `describe_scoring_request`
+would send against it before the service takes traffic -- see the `client` branch
+there.
+
+The other way to get this wrong is the engine, not the prompt: without the model
+class from PR #45829, SGLang loads the generative class and `/classify` answers
+with a 2048-dim hidden state instead of two logits. That is caught by shape, on
+a real forward pass, at startup.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import httpx
+
+from ..prompt import PromptParts
+from .base import BackendError
+
+__all__ = ["SGLangBackend"]
+
+
+class SGLangBackend:
+ """Talks to one `sglang.launch_server` process over HTTP."""
+
+ #: Who assembles the prompt. `selfcheck.py` branches on this: an engine that
+ #: templates for us has to be interrogated, one that does not has to be
+ #: checked on our own side instead. Neither check substitutes for the other.
+ prompt_source = "client"
+
+ #: `/classify` returns the value head's two raw logits; `scorer.py` applies
+ #: the softmax. Spelled out rather than left to the default, so the two
+ #: families stay visible side by side in `sdk/backends/`.
+ output_kind = "logits"
+
+ def __init__(
+ self,
+ base_url: str,
+ *,
+ model: str | None = None,
+ timeout: float = 120.0,
+ max_in_flight: int = 32,
+ ) -> None:
+ self.base_url = base_url.rstrip("/")
+ self._model_override = model
+ self._model: str | None = model
+ self._client = httpx.AsyncClient(timeout=timeout)
+ import asyncio
+
+ self._gate = asyncio.Semaphore(max_in_flight)
+
+ # ── identity ─────────────────────────────────────────────────────────────
+
+ async def served_name(self) -> str | None:
+ """The model path SGLang was started with.
+
+ `/get_model_info` rather than `/v1/models`: SGLang serves one model per
+ process and reports it by path, which is what identifies the checkpoint.
+ """
+ if self._model:
+ return self._model
+ try:
+ resp = await self._client.get(f"{self.base_url}/get_model_info", timeout=5.0)
+ except httpx.HTTPError:
+ return None
+ if resp.status_code != 200:
+ return None
+ path = resp.json().get("model_path")
+ if path:
+ self._model = str(path)
+ return self._model
+
+ # ── request shape ────────────────────────────────────────────────────────
+
+ def _classify_body(
+ self, parts: PromptParts, original_data_url: str, render_data_url: str
+ ) -> dict[str, Any]:
+ """The exact body `forward` posts. Separate so the self-check can read it.
+
+ Image order is load-bearing and silent when wrong: the prompt says the
+ first image is the original and the second is the render, and the
+ placeholders in `raw` are positional. Swapping them asks the model a
+ different question and still returns a number in range.
+ """
+ return {
+ "text": parts.raw,
+ "image_data": [original_data_url, render_data_url],
+ }
+
+ def describe_scoring_request(self, parts: PromptParts) -> dict[str, Any]:
+ """`_classify_body` with the image payloads elided, for the self-check."""
+ return self._classify_body(parts, "<original>", "<render>")
+
+ # ── the two calls ────────────────────────────────────────────────────────
+
+ async def forward(
+ self,
+ parts: PromptParts,
+ original_data_url: str,
+ render_data_url: str,
+ ) -> list[float]:
+ body = self._classify_body(parts, original_data_url, render_data_url)
+ try:
+ async with self._gate:
+ resp = await self._client.post(f"{self.base_url}/classify", json=body)
+ except httpx.HTTPError as exc:
+ raise BackendError(f"backend unreachable: {exc}") from exc
+ if resp.status_code != 200:
+ raise BackendError(f"backend HTTP {resp.status_code}: {resp.text[:300]}")
+
+ try:
+ logits = resp.json()["embedding"]
+ except (KeyError, TypeError, ValueError) as exc:
+ raise BackendError(f"unreadable response: {resp.text[:300]}") from exc
+ if not isinstance(logits, list) or len(logits) != 2:
+ got = len(logits) if isinstance(logits, list) else type(logits).__name__
+ raise BackendError(
+ f"expected 2 class logits, got {got}. A hidden state of a few "
+ "thousand dimensions means the server loaded the generative class: "
+ "start it with --json-model-override-args "
+ '\'{"architectures": ["Qwen3_5VLForSequenceClassification"]}\'.'
+ )
+ return [float(logits[0]), float(logits[1])]
+
+ async def tokenize(self, parts: PromptParts) -> list[int] | None:
+ """Not applicable: this engine never assembles a prompt of its own.
+
+ None is the honest answer rather than a gap. Asking SGLang to tokenize
+ `raw` would only confirm that it can tokenize a string we handed it --
+ it would prove nothing about the prompt, because the prompt did not come
+ from the engine. The check that does carry weight for this backend runs
+ against `describe_scoring_request` in `selfcheck.py`.
+ """
+ return None
+
+ async def aclose(self) -> None:
+ await self._client.aclose()
diff --git a/scripts/minicpm-ocr-jev/sdk/jev_score/prompt.py b/scripts/minicpm-ocr-jev/sdk/jev_score/prompt.py
index f29acfe..f39e112 100644
--- a/scripts/minicpm-ocr-jev/sdk/jev_score/prompt.py
+++ b/scripts/minicpm-ocr-jev/sdk/jev_score/prompt.py
@@ -15,6 +15,11 @@ chat template:
raw SGLang's /classify takes the finished prompt string and applies no
template at all. That is what `build_prompt()` already returns.
+ ocr_text llama.cpp's and Ollama's /v1/systemone take the candidate text bare
+ and wrap it in a template baked into the GGUF. Neither of the two
+ arrangements above fits: `raw` would be wrapped a second time, and
+ the segments carry the prompt's own punctuation around the text.
+
Both are built from the same source, so they cannot disagree about the words.
What they *can* disagree about is the handful of tokens a template adds at the
end, which is why `selfcheck.py` exists.
@@ -53,12 +58,15 @@ class PromptParts:
`text_after_original` and `text_after_render` are the two text segments that
sit between and after the two image placeholders. `raw` is the same prompt as
- a finished string, for engines that do not apply a template.
+ a finished string, for engines that do not apply a template. `ocr_text` is the
+ candidate text with nothing around it, for engines that hold the template
+ themselves and want only the part that varies.
"""
text_after_original: str
text_after_render: str
raw: str
+ ocr_text: str
def build_parts(ocr_text: str) -> PromptParts:
@@ -79,4 +87,5 @@ def build_parts(ocr_text: str) -> PromptParts:
text_after_original=f"\nOCR文本:\n{ocr_text}\n",
text_after_render="\n" + INSTRUCTION,
raw=build_prompt(ocr_text),
+ ocr_text=ocr_text,
)
diff --git a/scripts/minicpm-ocr-jev/sdk/jev_score/scorer.py b/scripts/minicpm-ocr-jev/sdk/jev_score/scorer.py
index 04800e3..74ed218 100644
--- a/scripts/minicpm-ocr-jev/sdk/jev_score/scorer.py
+++ b/scripts/minicpm-ocr-jev/sdk/jev_score/scorer.py
@@ -26,7 +26,14 @@ from .backends import Backend, BackendError, load_backend
from .images import to_data_url
from .prompt import PROMPT_TEMPLATE_MD5, build_parts
-__all__ = ["Scorer", "ScoreInput", "BackendError", "PROMPT_TEMPLATE_MD5", "softmax_prob_1"]
+__all__ = [
+ "Scorer",
+ "ScoreInput",
+ "BackendError",
+ "PROMPT_TEMPLATE_MD5",
+ "softmax_prob_1",
+ "prob_1_from_probabilities",
+]
@dataclass(frozen=True)
@@ -62,6 +69,45 @@ def softmax_prob_1(logits: Sequence[float]) -> float:
return exp_b / (exp_a + exp_b)
+#: How far a declared probability pair may stray from summing to 1 before we stop
+#: believing it is one. Loose enough for float32 round-trips through JSON, far
+#: tighter than any logit pair would land by accident.
+_PROB_SUM_TOLERANCE = 1e-3
+
+
+def prob_1_from_probabilities(scores: Sequence[float]) -> float:
+ """P(class 1) from a pair the engine already softmaxed.
+
+ Takes the number rather than recomputing it: a softmax applied twice is a
+ different, flatter function, and it fails silently -- every score still lands
+ in (0, 1) and the ranking survives, so no smoke test notices.
+
+ The pair is checked rather than trusted. An adapter that declared
+ `output_kind = "probabilities"` while handing over raw logits is the one
+ mistake this path makes possible, and it is visible here: logits do not lie
+ in [0, 1] and sum to 1.
+ """
+ if len(scores) != 2:
+ raise ValueError(
+ f"expected 2 class probabilities from the engine, got {len(scores)}. "
+ "This checkpoint may not be a 2-class decision model."
+ )
+ p0, p1 = float(scores[0]), float(scores[1])
+ if not (0.0 <= p0 <= 1.0 and 0.0 <= p1 <= 1.0):
+ raise ValueError(
+ f"the engine's two class scores are {p0!r} and {p1!r}, which are not "
+ "probabilities. The adapter declares output_kind='probabilities'; if "
+ "this engine returns raw logits, that declaration is what is wrong."
+ )
+ if abs(p0 + p1 - 1.0) > _PROB_SUM_TOLERANCE:
+ raise ValueError(
+ f"the engine's two class probabilities sum to {p0 + p1!r}, not 1. "
+ "Either a class is missing from the response or these are not a "
+ "distribution over the two classes."
+ )
+ return p1
+
+
class Scorer:
"""The score layer, as a library. `sdk/jev_score/server.py` is the thin HTTP shell over it."""
@@ -76,12 +122,18 @@ class Scorer:
and "the engine was down" are different facts, and a library that
conflates them hands its caller a number that looks like a judgement.
"""
- logits = await self.backend.forward(
+ scores = await self.backend.forward(
build_parts(item.ocr_text),
to_data_url(item.original),
to_data_url(item.render),
)
- return softmax_prob_1(logits)
+ # Which of the two families this engine belongs to is the adapter's to
+ # declare, not ours to guess -- and getting it wrong is the one failure
+ # here that returns a plausible number instead of an error. See
+ # backends/base.py for why the second family exists at all.
+ if getattr(self.backend, "output_kind", "logits") == "probabilities":
+ return prob_1_from_probabilities(scores)
+ return softmax_prob_1(scores)
async def score_many(self, items: Sequence[ScoreInput]) -> list[float]:
"""`score` over a batch, concurrently, results in input order.
diff --git a/scripts/minicpm-ocr-jev/sdk/jev_score/selfcheck.py b/scripts/minicpm-ocr-jev/sdk/jev_score/selfcheck.py
index c88987b..8443b6c 100644
--- a/scripts/minicpm-ocr-jev/sdk/jev_score/selfcheck.py
+++ b/scripts/minicpm-ocr-jev/sdk/jev_score/selfcheck.py
@@ -1,29 +1,35 @@
-"""Startup gate: does this engine still assemble the training prompt?
+"""Startup gate: is this engine going to score the prompt this model was trained on?
-The shipped image answers this by construction -- it carries a pass-through chat
+The shipped image answers that by construction -- it carries a pass-through chat
template whose fingerprint is asserted at import. A self-installed deployment
-cannot: the prompt is assembled by the engine, from the model's own
-`chat_template.jinja`, under request flags that this SDK sets. Any of those three
-can change without this code changing.
-
-And when they do change, nothing breaks. The engine answers 200. The number is
-in range, the ranking across candidates still looks sane, and it is not the
-scale the checkpoint was trained on, because the value head pooled a different
-position. The failure has no symptom, so it needs a test rather than a reader.
-
-Hence this gate, which runs before the service accepts traffic and refuses to
-start if it fails. Two assertions:
-
- tail the last token id is 271 -- the final newline of the empty assistant
- turn, which is the position the classify path pools.
- whole the engine's token sequence equals the local tokenizer's rendering of
- `build_prompt()`, token for token.
-
-`tail` is the cheap one and catches the two documented ways to get this wrong
-(`add_generation_prompt` defaulting to False, `enable_thinking` at the wrong
-level), both of which land on 198. `whole` is stricter and needs `transformers`
-and the weights on the same host, so it is optional and skipped with a loud note
-when they are absent.
+cannot, and *how* it cannot depends on which engine runs it, because the engines
+do not divide the work the same way:
+
+ vLLM we hand it a content list; its copy of the model's
+ chat_template.jinja assembles the prompt -> prompt_source "engine"
+ SGLang we hand it a finished prompt string; it
+ applies no template at all -> prompt_source "client"
+ llama.cpp the template is baked into the GGUF and runs
+ Ollama server-side, where we cannot read it -> prompt_source "server_template"
+
+The failure is the same in all three cases and has no symptom: the engine answers
+200, the number is in range, the ranking across candidates still looks sane, and
+it is not the scale the checkpoint was trained on. So each one needs a test
+rather than a reader -- but not the same test, because what can go wrong moves:
+
+ * With "engine" the prompt is assembled out of our sight, so the engine is the
+ one that has to be interrogated: tokenize the probe and compare.
+ * With "client" nothing downstream can touch the prompt, so interrogating the
+ engine proves nothing -- it would only confirm it can tokenize a string we
+ just handed it. What can go wrong is on our side, so the check reads the
+ outgoing request and compares it against `build_prompt()`.
+ * With "server_template" neither is possible. That is a fact to report rather
+ than paper over: the gate says so, and the service starts knowing the scale
+ of its scores is established only by comparison against a known backend.
+
+One check does apply to all three, and it is the only one that catches an engine
+serving the wrong model class: ask for one real forward pass and count the
+numbers that come back. Two is a classifier; two thousand is a hidden state.
"""
from __future__ import annotations
@@ -46,6 +52,25 @@ EXPECTED_LAST_TOKEN = 271
#: markup, a newline inside the text, and non-ASCII.
PROBE_TEXT = "<table><tr><td>参考</td><td>Accuracy (%)</td></tr></table>\nE = mc^2"
+#: 1x1 white PNG. The forward-shape check needs two images of *some* size, and
+#: the pixels are irrelevant to what it asserts, so one pixel keeps startup fast.
+PIXEL_PNG = (
+ "data:image/png;base64,"
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
+)
+
+#: What the two numbers are called, per `Backend.output_kind`. Only wording --
+#: the check itself is the same one either way, because what it rules out
+#: (an engine serving the generative class) looks the same in both families.
+_OUTPUT_NOUN = {"logits": "logits", "probabilities": "probabilities"}
+
+#: What `scoring_request` reports once the per-source check passes.
+_SCORING_OK = {
+ "engine": "carries the template keys",
+ "client": "carries the finished prompt",
+ "server_template": "skipped",
+}
+
class SelfCheckFailed(RuntimeError):
"""The engine does not assemble the prompt this checkpoint was trained on."""
@@ -54,11 +79,13 @@ class SelfCheckFailed(RuntimeError):
@dataclass
class SelfCheckResult:
passed: bool
+ prompt_source: str = "engine" # "engine" | "client" | "server_template"
last_token: int | None = None
expected_last_token: int = EXPECTED_LAST_TOKEN
n_tokens: int | None = None
token_equality: str = "skipped" # "equal" | "differs" | "skipped"
- scoring_request: str = "skipped" # "carries the template keys" | "differs" | "skipped"
+ scoring_request: str = "skipped" # see _SCORING_OK, or "differs"
+ forward_shape: str = "skipped" # "2 logits" | "2 probabilities" | "differs" | "skipped"
notes: list[str] = field(default_factory=list)
def raise_for_status(self) -> "SelfCheckResult":
@@ -76,18 +103,196 @@ async def run_selfcheck(
"""Run the gate against a live engine.
`weights` is a local checkpoint directory, used only for the stricter
- token-for-token comparison; `JEV_WEIGHTS` is read when it is not passed.
+ token-level comparison; `JEV_WEIGHTS` is read when it is not passed.
"""
parts: PromptParts = build_parts(probe_text)
- result = SelfCheckResult(passed=False)
+ source = str(getattr(backend, "prompt_source", "engine"))
+ kind = str(getattr(backend, "output_kind", "logits"))
+ result = SelfCheckResult(passed=False, prompt_source=source)
- scoring_note = _check_scoring_request(backend, parts)
+ # ── 1. what goes out on the wire ─────────────────────────────────────────
+ scoring_note = _check_scoring_request(backend, parts, source, probe_text)
if scoring_note is not None:
result.scoring_request = "differs"
result.notes.append(scoring_note)
return result
- result.scoring_request = "carries the template keys"
+ result.scoring_request = _SCORING_OK.get(source, "skipped")
+
+ # ── 2. does this engine answer like a classifier at all ──────────────────
+ shape_note = await _check_forward_shape(backend, parts)
+ if shape_note is not None:
+ result.forward_shape = "differs"
+ result.notes.append(shape_note)
+ return result
+ # Named after what this engine actually returned, not after the one family the
+ # check was first written for: a reader comparing /healthz across two legs is
+ # entitled to see which side of that difference each one is on.
+ result.forward_shape = f"2 {_OUTPUT_NOUN.get(kind, 'numbers')}"
+
+ # ── 3. is the prompt the training prompt ─────────────────────────────────
+ if source == "engine":
+ return await _check_engine_prompt(backend, parts, result, weights, probe_text)
+ if source == "client":
+ return _check_local_prompt(result, weights, probe_text)
+
+ result.notes.append(
+ "this engine builds the prompt from a template of its own that cannot be "
+ "read from here, so the prompt itself is not checked before traffic "
+ "arrives. The forward-shape check above passed; the scale of the scores "
+ "has to be established by comparing against a known backend on the same "
+ "inputs."
+ )
+ result.passed = True
+ return result
+
+# ── 1. the outgoing request ──────────────────────────────────────────────────
+
+#: What a templating engine's scoring request must say out loud rather than
+#: leave to a default. `use_activation` is here for the same reason as the other
+#: two: its default returns activated probabilities, which rank identically and
+#: are on a different scale -- the one kind of wrongness that every smoke test
+#: passes.
+REQUIRED_SCORING_KEYS: dict[str, object] = {
+ "add_generation_prompt": True,
+ "chat_template_kwargs": {"enable_thinking": False},
+ "use_activation": False,
+}
+
+
+def _check_scoring_request(
+ backend: Backend, parts: PromptParts, source: str, probe_text: str
+) -> str | None:
+ """Does the body `forward` sends carry what it must? None if it does."""
+ describe = getattr(backend, "describe_scoring_request", None)
+ if describe is None:
+ return None # an adapter that cannot show its request is not checked here
+
+ body = describe(parts)
+ if source == "client":
+ return _check_client_body(body, probe_text)
+ if source == "engine":
+ return _check_template_keys(body)
+ return None
+
+
+def _check_template_keys(body: dict) -> str | None:
+ """The engine assembles the prompt, so the flags that steer it must be sent.
+
+ This is the half of the check that the engine cannot answer. /classify
+ replies with two numbers, so no amount of interrogating it reveals which
+ prompt produced them; and the endpoint the token check *can* interrogate,
+ /tokenize, defaults `add_generation_prompt` the other way. An adapter that
+ quietly stopped sending the key would leave the token check green and every
+ score wrong. So this one reads the outgoing request instead of the reply.
+ """
+ wrong = {
+ key: (body.get(key, "<missing>"), expected)
+ for key, expected in REQUIRED_SCORING_KEYS.items()
+ if body.get(key, "<missing>") != expected
+ }
+ if not wrong:
+ return None
+ lines = [
+ "the scoring request does not carry the keys it must:",
+ *(f" {key}: sends {got!r}, must send {want!r}" for key, (got, want) in wrong.items()),
+ " These cannot be left to the endpoint's default. On vLLM 0.32.0 /classify",
+ " defaults add_generation_prompt to False while /tokenize defaults it to",
+ " True, so the prompt check below would pass while the scores came from a",
+ " prompt with the assistant turn cut off.",
+ ]
+ return "\n".join(lines)
+
+
+def _check_client_body(body: dict, probe_text: str) -> str | None:
+ """We assemble the prompt, so what gets checked is what we assembled.
+
+ For such a backend this is the prompt check, not a preliminary to it -- and
+ it is the stricter of the two kinds: it compares the exact string that will
+ be sent, rather than a tokenization of a probe that resembles it.
+ """
+ expected = build_prompt(probe_text)
+ sent = body.get("text")
+ if sent != expected:
+ if not isinstance(sent, str):
+ return (
+ "the scoring request carries no prompt string: 'text' is "
+ f"{type(sent).__name__}, expected the output of build_prompt()"
+ )
+ first = next(
+ (i for i in range(min(len(sent), len(expected))) if sent[i] != expected[i]),
+ min(len(sent), len(expected)),
+ )
+ return (
+ "the prompt this adapter sends is not build_prompt():\n"
+ f" first difference at character {first} of "
+ f"{len(sent)} (sent) / {len(expected)} (expected)\n"
+ f" sent {sent[max(0, first - 30):first + 30]!r}\n"
+ f" expected {expected[max(0, first - 30):first + 30]!r}"
+ )
+
+ images = body.get("image_data")
+ if not isinstance(images, list) or len(images) != IMAGES_PER_PROMPT:
+ got = len(images) if isinstance(images, list) else type(images).__name__
+ return (
+ f"the scoring request carries {got} images, expected {IMAGES_PER_PROMPT}. "
+ "Ternary input is original + render, always two, in that order."
+ )
+ return None
+
+
+# ── 2. the forward pass ──────────────────────────────────────────────────────
+
+
+async def _check_forward_shape(backend: Backend, parts: PromptParts) -> str | None:
+ """Ask for one real score and count the numbers. None if two came back.
+
+ The only check here that runs the model, and the only one that catches an
+ engine serving the wrong class: a checkpoint loaded as its generative self
+ answers the same endpoint with a hidden state of a few thousand dimensions.
+ Two numbers is the whole assertion -- their values mean nothing, because the
+ images are one white pixel.
+ """
+ try:
+ logits = await backend.forward(parts, PIXEL_PNG, PIXEL_PNG)
+ except BackendError as exc:
+ return (
+ f"the engine could not score the startup probe: {exc}\n"
+ " Nothing can be verified about an engine that does not answer."
+ )
+ if len(logits) != 2:
+ noun = _OUTPUT_NOUN.get(str(getattr(backend, "output_kind", "logits")), "numbers")
+ return (
+ f"the engine returned {len(logits)} numbers for one candidate, expected "
+ f"2 class {noun}. This checkpoint may not be loaded as a 2-class "
+ "sequence-classification model."
+ )
+ return None
+
+
+# ── 3a. the prompt, when the engine assembles it ─────────────────────────────
+
+
+async def _check_engine_prompt(
+ backend: Backend,
+ parts: PromptParts,
+ result: SelfCheckResult,
+ weights: str | Path | None,
+ probe_text: str,
+) -> SelfCheckResult:
+ """Two assertions against the engine's own assembly.
+
+ tail the last token id is 271 -- the final newline of the empty
+ assistant turn, which is the position the classify path pools.
+ whole the engine's token sequence equals the local tokenizer's
+ rendering of `build_prompt()`, token for token.
+
+ `tail` is the cheap one and catches the two documented ways to get this wrong
+ (`add_generation_prompt` defaulting to False, `enable_thinking` at the wrong
+ level), both of which land on 198. `whole` is stricter and needs
+ `transformers` and the weights on the same host, so it is optional and
+ skipped with a loud note when they are absent.
+ """
try:
tokens = await backend.tokenize(parts)
except BackendError as exc:
@@ -118,28 +323,11 @@ async def run_selfcheck(
)
return result
- # ── stricter half ────────────────────────────────────────────────────────
- weights = weights or os.environ.get("JEV_WEIGHTS")
- if not weights:
- result.notes.append(
- "token-for-token comparison skipped: no weights path given "
- "(pass weights=... or set JEV_WEIGHTS). The tail check above passed."
- )
- result.passed = True
- return result
-
- try:
- from transformers import AutoTokenizer
- except ImportError:
- result.notes.append(
- "token-for-token comparison skipped: transformers is not installed in "
- "this environment. The tail check above passed."
- )
- result.passed = True
+ reference = _local_reference_tokens(result, weights, probe_text)
+ if reference is None:
+ result.passed = True # the note explaining the skip is already in place
return result
-
- tok = AutoTokenizer.from_pretrained(str(weights))
- reference = tok(build_prompt(probe_text), add_special_tokens=False)["input_ids"]
+ tok, reference_ids = reference
# The two sequences cannot be compared element by element, and the reason is
# not a defect in either of them. The engine has already expanded each image
@@ -154,7 +342,7 @@ async def run_selfcheck(
vision_end = tok.convert_tokens_to_ids("<|vision_end|>")
engine_text, engine_images = _strip_image_spans(tokens, vision_start, vision_end)
- reference_text, reference_images = _strip_image_spans(reference, vision_start, vision_end)
+ reference_text, reference_images = _strip_image_spans(reference_ids, vision_start, vision_end)
if engine_images != IMAGES_PER_PROMPT or reference_images != IMAGES_PER_PROMPT:
result.token_equality = "differs"
@@ -179,7 +367,6 @@ async def run_selfcheck(
if engine_text[i] != reference_text[i]),
min(len(engine_text), len(reference_text)),
)
- result.token_equality = "differs"
result.notes.append(
"the text the engine assembles differs from build_prompt():\n"
f" first difference at text token {first} of "
@@ -194,48 +381,77 @@ async def run_selfcheck(
return result
-#: What the scoring request must say out loud rather than leave to a default.
-#: `use_activation` is here for the same reason as the other two: its default
-#: returns activated probabilities, which rank identically and are on a different
-#: scale -- the one kind of wrongness that every smoke test passes.
-REQUIRED_SCORING_KEYS: dict[str, object] = {
- "add_generation_prompt": True,
- "chat_template_kwargs": {"enable_thinking": False},
- "use_activation": False,
-}
+# ── 3b. the prompt, when we assemble it ──────────────────────────────────────
-def _check_scoring_request(backend: Backend, parts: PromptParts) -> str | None:
- """Does the body `forward` sends carry the keys it must? None if it does.
+def _check_local_prompt(
+ result: SelfCheckResult, weights: str | Path | None, probe_text: str
+) -> SelfCheckResult:
+ """Tokenize our own prompt and confirm it pools where training pooled.
+
+ The string itself was already compared against `build_prompt()` in step 1,
+ which is the assertion that carries the weight for this backend. This adds
+ the one thing a string comparison cannot show: that the string tokenizes to a
+ sequence ending on token 271, the position the value head reads. It needs the
+ local tokenizer, so it is skipped -- not failed -- when the weights are not
+ on this host.
+ """
+ reference = _local_reference_tokens(result, weights, probe_text)
+ if reference is None:
+ result.passed = True # the note explaining the skip is already in place
+ return result
+ _, reference_ids = reference
- This is the half of the check that the engine cannot answer. /classify
- replies with two numbers, so no amount of interrogating it reveals which
- prompt produced them; and the endpoint the token check *can* interrogate,
- /tokenize, defaults `add_generation_prompt` the other way. An adapter that
- quietly stopped sending the key would leave the token check green and every
- score wrong. So this one reads the outgoing request instead of the reply.
+ result.n_tokens = len(reference_ids)
+ result.last_token = reference_ids[-1] if reference_ids else None
+ if result.last_token != EXPECTED_LAST_TOKEN:
+ result.token_equality = "differs"
+ result.notes.append(
+ f"build_prompt() tokenizes to a sequence ending on {result.last_token}, "
+ f"expected {EXPECTED_LAST_TOKEN}.\n"
+ " The classify path pools the LAST token. The prompt string itself\n"
+ " matches its fingerprint, so this points at the tokenizer in the\n"
+ " weights directory rather than at the prompt."
+ )
+ return result
+
+ result.token_equality = "equal"
+ result.passed = True
+ result.notes.append(
+ f"the prompt we send matches build_prompt() character for character and "
+ f"tokenizes to {len(reference_ids)} tokens ending on {EXPECTED_LAST_TOKEN}"
+ )
+ return result
+
+
+def _local_reference_tokens(
+ result: SelfCheckResult, weights: str | Path | None, probe_text: str
+) -> tuple[object, list[int]] | None:
+ """The local tokenizer's ids for `build_prompt(probe_text)`, if available.
+
+ Returns None and appends the reason when `transformers` or the weights are
+ missing, which is a skip rather than a failure in both callers.
"""
- describe = getattr(backend, "describe_scoring_request", None)
- if describe is None:
- return None # an adapter that cannot show its request is not checked here
+ weights = weights or os.environ.get("JEV_WEIGHTS")
+ if not weights:
+ result.notes.append(
+ "token-for-token comparison skipped: no weights path given "
+ "(pass weights=... or set JEV_WEIGHTS). The checks above passed."
+ )
+ return None
- body = describe(parts)
- wrong = {
- key: (body.get(key, "<missing>"), expected)
- for key, expected in REQUIRED_SCORING_KEYS.items()
- if body.get(key, "<missing>") != expected
- }
- if not wrong:
+ try:
+ from transformers import AutoTokenizer
+ except ImportError:
+ result.notes.append(
+ "token-for-token comparison skipped: transformers is not installed in "
+ "this environment. The checks above passed."
+ )
return None
- lines = [
- "the scoring request does not carry the keys it must:",
- *(f" {key}: sends {got!r}, must send {want!r}" for key, (got, want) in wrong.items()),
- " These cannot be left to the endpoint's default. On vLLM 0.32.0 /classify",
- " defaults add_generation_prompt to False while /tokenize defaults it to",
- " True, so the prompt check below would pass while the scores came from a",
- " prompt with the assistant turn cut off.",
- ]
- return "\n".join(lines)
+
+ tok = AutoTokenizer.from_pretrained(str(weights))
+ ids = tok(build_prompt(probe_text), add_special_tokens=False)["input_ids"]
+ return tok, list(ids)
def _strip_image_spans(
diff --git a/scripts/minicpm-ocr-jev/sdk/setup_render.sh b/scripts/minicpm-ocr-jev/sdk/setup_render.sh
index 64bc81e..8e8733b 100644
--- a/scripts/minicpm-ocr-jev/sdk/setup_render.sh
+++ b/scripts/minicpm-ocr-jev/sdk/setup_render.sh
@@ -23,8 +23,7 @@
# is the bare-metal equivalent of that Dockerfile, so it does too -- and that
# is the whole difference between the two files.
#
-# ⚠ Expect a different score here than from the published image, and read
-# "Matching the reference renderer" in the README before comparing numbers. Even
+# ⚠ Expect a different score here than from the published image. Even
# with the font environment pinned, a self-installed Chromium on a different
# kernel and GPU draws subtly different pixels, and rendered text is model input.
# Rankings hold; the digits after the second decimal place are not promised.
diff --git a/scripts/minicpm-ocr-jev/sdk/start_engine_sglang.sh b/scripts/minicpm-ocr-jev/sdk/start_engine_sglang.sh
new file mode 100644
index 0000000..09b2427
--- /dev/null
+++ b/scripts/minicpm-ocr-jev/sdk/start_engine_sglang.sh
@@ -0,0 +1,54 @@
+#!/usr/bin/env bash
+# Start the forward-pass engine for the SDK path on SGLang.
+#
+# usage: ./start_engine_sglang.sh <GPU index> <port> <model path>
+#
+# The three arguments have no defaults. Picking the wrong GPU means evicting
+# whatever already runs on it, so a missing argument stops the script instead of
+# quietly falling back to card 0.
+#
+# How this differs from the vLLM script, and why it matters:
+#
+# start_engine.sh the engine applies the model's chat_template.jinja
+# this script the engine applies no template at all
+#
+# SGLang's /classify takes a finished prompt string. The SDK sends one, built by
+# `build_prompt()`, whose fingerprint is asserted at import. So the prompt cannot
+# be mangled downstream -- and the startup gate checks our side of the wire
+# instead of the engine's (`prompt_source: client` in jev_score/selfcheck.py).
+#
+# What can still go wrong here is the model class, not the prompt. Without
+# --json-model-override-args the server loads the generative class and answers
+# /classify with a hidden state of a few thousand dimensions instead of two
+# logits; the gate catches that on a real forward pass before traffic arrives.
+set -euo pipefail
+
+GPU="${1:?GPU index required (check nvidia-smi first)}"
+PORT="${2:?port required}"
+MODEL="${3:?path to the checkpoint directory required}"
+
+MEM_FRACTION="${MEM_FRACTION:-0.45}"
+HOST="${HOST:-127.0.0.1}"
+
+[ -d "$MODEL" ] || { echo "[error] model directory not found: $MODEL" >&2; exit 1; }
+
+echo "model=$MODEL gpu=$GPU port=$PORT mem-fraction=$MEM_FRACTION (no chat template)"
+
+# --is-embedding -- run the model through the pooling path rather than as a text
+# generator. Without it there is no /classify to call.
+# --json-model-override-args -- the checkpoint's config.json lists
+# Qwen3_5ForConditionalGeneration, which is the generative class. Overriding it
+# to the sequence-classification class is what makes the server return the two
+# logits of the value head. This is a load-time override; the checkpoint on
+# disk is not touched.
+# --mem-fraction-static -- SGLang otherwise reserves most of the free memory on
+# the card for its cache pools. The model itself needs about 8 GB. Below ~0.25
+# of a 24 GB card the hybrid state cache is too small to serve anything.
+exec env CUDA_VISIBLE_DEVICES="$GPU" \
+ python -m sglang.launch_server \
+ --model-path "$MODEL" \
+ --is-embedding \
+ --json-model-override-args '{"architectures": ["Qwen3_5VLForSequenceClassification"]}' \
+ --mem-fraction-static "$MEM_FRACTION" \
+ --host "$HOST" \
+ --port "$PORT"
diff --git a/scripts/minicpm-ocr-jev/serve/Dockerfile b/scripts/minicpm-ocr-jev/serve/Dockerfile
index 43d3c53..731510c 100644
--- a/scripts/minicpm-ocr-jev/serve/Dockerfile
+++ b/scripts/minicpm-ocr-jev/serve/Dockerfile
@@ -2,10 +2,10 @@
# app.py for precheck, rendering and the HTTP contract.
#
# It builds from a bare `ubuntu:24.04` and installs everything through the
-# material's own scripts -- the same commands the README gives a reader with a
-# fresh machine. That is deliberate: if this image builds, the documented install
-# works, and there is no second, image-only path to drift out of step with the
-# instructions.
+# material's own scripts -- the same commands the deployment tutorial gives a
+# reader with a fresh machine. That is deliberate: if this image builds, the
+# documented install works, and there is no second, image-only path to drift
+# out of step with the instructions.
#
# No weights. The checkpoint is a run-time argument, so one image serves any
# compatible checkpoint and the image itself stays something you can rebuild
@@ -39,7 +39,7 @@ ENV DEBIAN_FRONTEND=noninteractive \
PIP_INDEX_URL=${PIP_INDEX_URL} \
PIP_DISABLE_PIP_VERSION_CHECK=1
-# README, "Install / 0. System packages", verbatim.
+# System packages, matching the documented install.
#
# gcc and python3-dev are not build-time conveniences to be removed afterwards:
# Triton compiles a CPython extension on the first forward pass of every fresh
@@ -77,7 +77,7 @@ RUN python3 -m venv /opt/venv-render \
/opt/venv-render/bin/python -m playwright install --with-deps chromium \
&& rm -rf /var/lib/apt/lists/*
-# README, "Install / 1. The renderer / Pin the font environment", verbatim.
+# Pin the font environment, matching the documented install.
#
# This has to come after the playwright install above, not before: --with-deps
# pulls in its own set of fonts, and would put the purged packages back.
diff --git a/scripts/minicpm-ocr-jev/serve/requirements-serve.txt b/scripts/minicpm-ocr-jev/serve/requirements-serve.txt
index 0f46288..9452754 100644
--- a/scripts/minicpm-ocr-jev/serve/requirements-serve.txt
+++ b/scripts/minicpm-ocr-jev/serve/requirements-serve.txt
@@ -1,8 +1,7 @@
# Extra dependencies for the HTTP service in this directory. The renderer's own
-# dependencies are in ../requirements.txt, and vLLM is installed separately
-# (see README, "Install / 2. vLLM") -- it runs as its own process and must not
-# share an environment with this service, because it would move the renderer's
-# Pillow pin.
+# dependencies are in ../requirements.txt, and vLLM is installed separately --
+# it runs as its own process and must not share an environment with this
+# service, because it would move the renderer's Pillow pin.
#
# These are lower bounds, not pins. Nothing here touches an image or a prompt, so
# none of it can move a score; pinning it would only make the service harder to
diff --git a/scripts/minicpm-ocr-jev/serve/setup_backend.sh b/scripts/minicpm-ocr-jev/serve/setup_backend.sh
index e53af0b..12c9970 100644
--- a/scripts/minicpm-ocr-jev/serve/setup_backend.sh
+++ b/scripts/minicpm-ocr-jev/serve/setup_backend.sh
@@ -86,7 +86,7 @@ if arch not in archs:
print(f"\n!! {arch} is not registered in this vLLM build.", file=sys.stderr)
print(" This release cannot serve the model. Install a newer vLLM, or build",
file=sys.stderr)
- print(" from upstream (see README, 'Install / 2. vLLM').", file=sys.stderr)
+ print(" from upstream.", file=sys.stderr)
raise SystemExit(1)
print(f"{arch} registered")
PY