Skip to content

Fast, accurate OCR with correctness assessment.

add transformer backend support

taitoushiyuneede5f053f9a
diff --git a/docs/SKILL_jev.md b/docs/SKILL_jev.md
index c731002..b09c4f5 100644
--- a/docs/SKILL_jev.md
+++ b/docs/SKILL_jev.md
@@ -1,6 +1,6 @@
---
name: minicpm-ocr-jev-deploy
-description: 安装、部署和验证 MiniCPM-OCR Jev 打分服务,两条路径——Docker 镜像,或 SDK 本地部署(vLLM / SGLang / llama.cpp / Ollama 四个推理后端)。在用户要起 Jev 打分服务、部署 Jev 镜像或 SDK、给 OCR 结果打一致性分数或在多个候选里选优、排查起服与打分报错时使用。
+description: 安装、部署和验证 MiniCPM-OCR Jev 打分服务,两条路径——Docker 镜像,或 SDK 本地部署(vLLM / SGLang / llama.cpp / Ollama / PyTorch Transformers 五个推理后端)。在用户要起 Jev 打分服务、部署 Jev 镜像或 SDK、给 OCR 结果打一致性分数或在多个候选里选优、排查起服与打分报错时使用。
---
# MiniCPM-OCR Jev 本地部署
@@ -9,7 +9,7 @@ Jev 判断一段 OCR 文本与原图是否一致:送原图与候选文本,
部署有两条路径,用同一个模型、同一套打分逻辑:**Docker 镜像**一个容器里装齐引擎、打分服务与渲染环境;**SDK** 把渲染器与模型服务分开装在主机上——引擎做前向,服务层做打分,两者必须在不同的虚拟环境里。
-本文的命令与 `docs/minicpm_ocr_jev_tutorial_zh.md`、`docs/minicpm_ocr_jev_docker_api_zh.md`、`docs/{vllm,sglang,llamacpp,ollama}_deploy_jev_zh.md` 同源,每节都标了对应文档的小节;改任一方需同步。
+本文的命令与 `docs/minicpm_ocr_jev_tutorial_zh.md`、`docs/minicpm_ocr_jev_docker_api_zh.md`、`docs/{vllm,sglang,llamacpp,ollama,transformers}_deploy_jev_zh.md` 同源,每节都标了对应文档的小节;改任一方需同步。
## 1. 确定方案
@@ -20,7 +20,7 @@ Jev 判断一段 OCR 文本与原图是否一致:送原图与候选文本,
| 渲染环境 | 镜像内置固定版本的 Chromium 与 CJK 字体 | 自己装(6.2),或由调用方提供渲染图(6.1) |
| 分数口径 | 与云端 API 同一套渲染环境,可直接与发布数字对照 | 排序稳定,绝对值可能差在小数点后第三位 |
| 要装什么 | Docker + NVIDIA Container Toolkit | 两个虚拟环境:引擎 + 服务层 |
-| 推理后端 | 镜像内固定 vLLM | vLLM / SGLang / llama.cpp / Ollama 四选一 |
+| 推理后端 | 镜像内固定 vLLM | vLLM / SGLang / llama.cpp / Ollama / PyTorch Transformers 五选一 |
| 平台 | 仅 Linux + NVIDIA | Linux + NVIDIA/macOS(见 1.3) |
| 适合 | 要与发布数字对照、不想自己装渲染环境 | 没有 Docker、在 macOS 上、已有渲染图、或要指定后端 |
@@ -81,7 +81,7 @@ curl -s http://127.0.0.1:8030/v1/rm/score -H 'Content-Type: application/json' -d
| 功能 | 逐条打分 | 逐条打分、块内选优、批量选优,带 precheck |
| 启动脚本 | `sdk/start_score.sh` | `sdk/start_render_score.sh` |
-四个后端的环境成本相差很大,按用户的约束选:
+五个后端的环境成本相差很大,按用户的约束选:
| 后端 | 系统 CUDA toolkit | 要编译 | 引擎环境体积 | 可用平台 | 适合 |
|---|---|---|---|---|---|
@@ -89,10 +89,12 @@ curl -s http://127.0.0.1:8030/v1/rm/score -H 'Content-Type: application/json' -d
| SGLang | **需要** | 否 | 9.5 GB | 仅 Linux + NVIDIA | 已有 SGLang 技术栈 |
| llama.cpp | **需要**(仅 Linux) | **是** | 214 MB(build) | Linux + NVIDIA/macOS | 显存小、不想装 torch |
| Ollama | 不需要 | 否 | 无(引擎在安装包里) | Linux + NVIDIA/macOS | 要求最轻,已有 Ollama |
+| PyTorch Transformers | 不需要 | 否 | 无(不起引擎,权重在服务进程里) | Linux + NVIDIA/macOS | 不想起引擎、要在 mac 上用原始权重、小批量 |
- llama.cpp 与 Ollama 用 GGUF 权重,**官方已发布,默认直接下**(见 5.3),不必下 HF 原始权重、也不必装转换环境。只在要换转换参数、或权重是用户自己微调的时候才自己转,那时需要一个 4.8 GB 的转换环境(CPU 版 torch),转完可删。
- Ollama 跑的就是 llama.cpp 的 runner,两者分数同源,**不要拿它们互相验证**。
-- ⭐ **用户在 macOS(Apple Silicon)上时只有 llama.cpp 与 Ollama 两条路**:vLLM 与 SGLang 依赖 CUDA 栈,mac 上起不来,不要建议。两者在 mac 上都走 Metal,命令与 Linux 的差别见 5.3/5.4。
+- ⭐ **PyTorch Transformers 不单独起引擎**:权重加载进服务进程,第 5 节对它只是填一份配置(见 5.5),服务层那个虚拟环境要装 torch。它默认一次只做一次前向,没有跨请求的连续批处理;要吞吐靠调 `max_batch_size` 加宽单次前向(实测批 4 有 2.3×),**但天花板仍低于引擎**,单机高吞吐选 vLLM 或 SGLang。用它的理由是不想装引擎、或要在 macOS 上直接用原始权重。
+- ⭐ **用户在 macOS(Apple Silicon)上时有三条路**:llama.cpp、Ollama 与 PyTorch Transformers。前两者用 GGUF 权重、走 Metal(命令与 Linux 的差别见 5.3/5.4);Transformers 直接读原始 bfloat16 权重,`device: auto` 自动选 Metal(MPS)。vLLM 与 SGLang 依赖 CUDA 栈,mac 上起不来,不要建议。
- ⭐ **macOS 上只做不带渲染器服务**:内置渲染器服务要固定字体环境,那一步依赖 apt,mac 上做不到(见 6.2)。
## 2. 安装前检查
@@ -202,6 +204,8 @@ grep -rq COMMON_DECISION_TYPE_MINICPM_OCR_JEV tools/server/ && echo supported ||
四个引擎的端口都用 18499(文档默认值)。一台机器上同时起多个后端时错开端口,并把服务层的引擎地址跟着改。
+**选 PyTorch Transformers 时本节只做 5.5 那一份配置**:它不起引擎,没有端口,权重由第 6 节的服务进程加载。
+
### 5.1 vLLM(对应 `vllm_deploy_jev_zh.md` 一)
```bash
@@ -335,9 +339,33 @@ ollama show minicpm-ocr-jev
通过标准:**只有起服自检能确认这个后端可用**(见[第 7 节](#7-验证))。`ollama show` 报 `decision, vision` 只说明 GGUF 转对了,runner 认不认它不负责。两个平台同此标准,macOS 上的 Ollama 也走 llama.cpp + Metal。
+### 5.5 PyTorch Transformers(对应 `transformers_deploy_jev_zh.md` 一)
+
+本后端不装引擎、不起进程、没有端口,本节只写一份配置;权重由第 6 节的服务进程加载,**那个虚拟环境要装 torch**(见 6.1)。用第 3 节取的 HF 原始权重,不要 GGUF。
+
+`sdk/backends/transformers.yaml` 指向权重目录:
+
+```yaml
+engine: transformers
+model_path: <WEIGHTS>
+device: auto
+dtype: auto
+attn_implementation: sdpa
+max_in_flight: 1
+max_batch_size: 1
+```
+
+- `model_path` 必填,与 `base_url` 互斥:同时给出会在启动时报错。
+- `device: auto` 依次尝试 `cuda:0`、`mps`、`cpu`;mac 上自动走 Metal。
+- `dtype` 与 `attn_implementation` 保持原值。实测:mac 上一次前向 bfloat16 耗时 0.3 秒、float32 耗时 38 秒且与参考分数偏差更大;`sdpa` 与参考分数相差 4.4e-3、`flash_attention_2` 为 7.6e-3。
+- `max_in_flight` 是同时进行的前向次数,保持 1;填大于 1 会在启动时降回 1 并在 `/healthz` 留一条 note。
+- `max_batch_size` 是**一次前向里的候选数**,与上一项不同轴(上一项是跑几次,这一项是一次多宽)。默认 1;要吞吐就调它。实测 24 候选(RTX 5090,bf16):批 1→2.17 秒,批 4→0.94 秒(2.3×),批 8→0.89 秒已趋平;峰值显存 4347→4962 MiB。⚠ 调大后分数不再逐位可复现(同候选跨批大小概率差 ≤3.3e-4,远在 4.4e-3 内)——根因是 GPU 归约次序随批形状变,与补齐无关(等长不补齐的批同样会动)。要逐位复现就保持 1。
+
+通过标准:**只有起服自检加打分能确认这个后端可用**(见[第 7 节](#7-验证))。
+
## 6. 装服务层并启动
-两种形态二选一,不要都起。引擎地址按第 5 节实际用的端口填。
+两种形态二选一,不要都起。引擎地址按第 5 节实际用的端口填;**PyTorch Transformers 不填这个参数**(它没有引擎),见 6.3。
### 6.1 不带渲染器服务(对应各文档 二)
@@ -350,6 +378,18 @@ pip install "fastapi>=0.110" "uvicorn>=0.27" "httpx>=0.27" "pydantic>=2.6" "PyYA
PATH=/opt/venv-score/bin:$PATH bash sdk/start_score.sh 18501 http://127.0.0.1:18499
```
+PyTorch Transformers 后端的服务进程要加载权重,依赖另装一份,启动时不带引擎地址:
+
+```bash
+python3 -m venv /opt/venv-transformers && source /opt/venv-transformers/bin/activate
+pip install -r sdk/requirements-transformers.txt
+```
+
+```bash
+JEV_BACKEND_CONFIG=sdk/backends/transformers.yaml \
+PATH=/opt/venv-transformers/bin:$PATH bash sdk/start_score.sh 18501
+```
+
### 6.2 内置渲染器服务(对应各文档 三)
```bash
@@ -375,7 +415,16 @@ JEV_BACKEND_CONFIG=sdk/backends/sglang.yaml \
PATH=/opt/venv-score/bin:$PATH bash sdk/start_score.sh 18501 http://127.0.0.1:18499
```
-把 `sglang.yaml` 换成 `llamacpp.yaml` / `ollama.yaml`。**不设这个变量时服务按 vLLM 协议发请求**:SGLang 那边连得上但分数不可用,llama.cpp 与 Ollama 那边端点对不上、起服即失败。
+把 `sglang.yaml` 换成 `llamacpp.yaml` / `ollama.yaml` / `transformers.yaml`。**不设这个变量时服务按 vLLM 协议发请求**:SGLang 那边连得上但分数不可用,llama.cpp 与 Ollama 那边端点对不上、起服即失败。
+
+`transformers.yaml` 还有一处不同:**两个启动脚本的引擎地址参数要整个省掉**,权重路径由配置里的 `model_path` 给。多给一个引擎地址会在启动时报错,而不是被忽略。
+
+```bash
+JEV_BACKEND_CONFIG=sdk/backends/transformers.yaml \
+PATH=/opt/venv-transformers/bin:$PATH bash sdk/start_render_score.sh 18500
+```
+
+内置渲染器服务用这个后端时,渲染器与权重在同一个进程里,所以 6.2 的渲染依赖要装进 `/opt/venv-transformers` 这同一个环境(`pip install "playwright==1.62.0" "Markdown==3.10.3"` + `playwright install chromium`),装完核对 `Pillow` 仍是 12.3.0。
## 7. 验证
@@ -394,8 +443,9 @@ curl -s http://127.0.0.1:18501/healthz
| vLLM | `engine` | `2 logits` | 引擎拼的 prompt 被逐项校过 |
| SGLang | `client` | `2 logits` | prompt 由 SDK 拼,校的是即将发出的字符串 |
| llama.cpp / Ollama | `server_template` | `2 probabilities` | 模板内置在 GGUF 里,读不回来,prompt 不校 |
+| PyTorch Transformers | `client` | `2 logits` | 同 SGLang,另加逐 token 比对(下行) |
-`token_equality` 为 `skipped` 是跳过不是失败。`status` 不是 `ok` 时读 `prompt.notes` 或 `error`——它会带上引擎的原话。
+`token_equality` 为 `skipped` 是跳过不是失败。**PyTorch Transformers 后端这一项是 `equal`**:逐 token 比对要本机有 tokenizer,而这个后端的环境必然装了 transformers,所以这一项真的跑了。`served_model` 在这个后端上是权重目录而不是模型名。`status` 不是 `ok` 时读 `prompt.notes` 或 `error`——它会带上引擎的原话。
### 7.2 用自带用例打分
@@ -544,6 +594,7 @@ ln -sfn $L/libggml-cuda.so $O/cuda_v13/libggml-cuda.so
| SGLang | 稳定版 0.5.22 **无本模型支持**;PR #45829 源码树可用,venv 9.5 GB |
| llama.cpp | release **v0.8.0**(含 PR #30980,2026-10-27 合入 master),build 214 MB |
| Ollama | v0.40.11 原装 **无本模型支持**,换 runner 后可用 |
+| PyTorch Transformers | Linux:torch 2.13.0+cu130 + transformers 5.19.0 + torchvision 0.29.2;macOS:torch 2.15.0 + transformers 5.22.2 + torchvision 0.29.2(2026-11-09 两端各实测一遍)。⚠ transformers 4.57.6 **没有** `Qwen3_5ForSequenceClassification` 这个类 |
| Docker 镜像 | 由 `serve/Dockerfile` 自建,引擎、打分服务与渲染环境都在镜像里;镜像内各件的实际版本以 `/healthz` 的 `scorer` 与 `render` 字段为准 |
| 服务层 | Python 3.12.3,fastapi 0.162.0,uvicorn 0.54.0,httpx 0.28.1,pydantic 2.14.1,Pillow 12.3.0,venv 59 MB |
| 渲染环境 | playwright 1.62.0,KaTeX 0.16.47,渲染流水线 v8.5,venv 205 MB |
diff --git a/docs/SKILL_jev_en.md b/docs/SKILL_jev_en.md
index ccf55aa..d8e269a 100644
--- a/docs/SKILL_jev_en.md
+++ b/docs/SKILL_jev_en.md
@@ -1,6 +1,6 @@
---
name: minicpm-ocr-jev-deploy
-description: Install, deploy and verify the MiniCPM-OCR Jev scoring service by either of two paths — the Docker image, or the SDK local deployment (four inference backends: vLLM / SGLang / llama.cpp / Ollama). Use when the user wants to start a Jev scoring service, deploy the Jev image or SDK, score OCR output for consistency or pick the best of several candidates, or troubleshoot startup and scoring errors.
+description: Install, deploy and verify the MiniCPM-OCR Jev scoring service by either of two paths — the Docker image, or the SDK local deployment (five inference backends: vLLM / SGLang / llama.cpp / Ollama / PyTorch Transformers). Use when the user wants to start a Jev scoring service, deploy the Jev image or SDK, score OCR output for consistency or pick the best of several candidates, or troubleshoot startup and scoring errors.
---
# MiniCPM-OCR Jev local deployment
@@ -9,7 +9,7 @@ Jev judges whether a piece of OCR text matches the original image: send the orig
There are two deployment paths, using the same model and the same scoring logic: the **Docker image** carries the engine, the scoring service and the render environment in one container; the **SDK** installs the renderer and the model service separately on the host — the engine does the forward pass, the service layer does the scoring, and the two must live in different virtual environments.
-The commands here come from the same source as `docs/minicpm_ocr_jev_tutorial_en.md`, `docs/minicpm_ocr_jev_docker_api_en.md` and `docs/{vllm,sglang,llamacpp,ollama}_deploy_jev_en.md`, and every section names the section of those documents it mirrors; change one side and the other must follow.
+The commands here come from the same source as `docs/minicpm_ocr_jev_tutorial_en.md`, `docs/minicpm_ocr_jev_docker_api_en.md` and `docs/{vllm,sglang,llamacpp,ollama,transformers}_deploy_jev_en.md`, and every section names the section of those documents it mirrors; change one side and the other must follow.
## 1. Determine the plan
@@ -20,7 +20,7 @@ The commands here come from the same source as `docs/minicpm_ocr_jev_tutorial_en
| Render environment | Pinned Chromium and CJK fonts, built into the image | Installed by you (6.2), or the caller provides the render image (6.1) |
| What the scores mean | Same render environment as the cloud API, so they can be compared against the published numbers directly | Ranking is stable; absolute values may differ in the third decimal |
| What to install | Docker + NVIDIA Container Toolkit | Two virtual environments: engine + service layer |
-| Inference backend | vLLM, fixed inside the image | One of vLLM / SGLang / llama.cpp / Ollama |
+| Inference backend | vLLM, fixed inside the image | One of vLLM / SGLang / llama.cpp / Ollama / PyTorch Transformers |
| Platforms | Linux + NVIDIA only | Linux + NVIDIA / macOS (see 1.3) |
| Suited to | Comparing against the published numbers, not installing a render environment yourself | No Docker, macOS, render images already in hand, or a specific backend wanted |
@@ -81,7 +81,7 @@ There are two service shapes, split by where the render image comes from; both u
| Features | Scoring only | Scoring, best-of-N within a block, batched best-of-N, with precheck |
| Start script | `sdk/start_score.sh` | `sdk/start_render_score.sh` |
-The four backends differ a lot in what they cost to set up; pick by the user's constraints:
+The five backends differ a lot in what they cost to set up; pick by the user's constraints:
| Backend | System CUDA toolkit | Compiles | Engine environment size | Platforms | Suited to |
|---|---|---|---|---|---|
@@ -89,10 +89,12 @@ The four backends differ a lot in what they cost to set up; pick by the user's c
| SGLang | **Needed** | No | 9.5 GB | Linux + NVIDIA only | An existing SGLang stack |
| llama.cpp | **Needed** (Linux only) | **Yes** | 214 MB (build) | Linux + NVIDIA / macOS | Small VRAM, no torch wanted |
| Ollama | Not needed | No | None (the engine ships with Ollama) | Linux + NVIDIA / macOS | Lightest requirements, an existing Ollama |
+| PyTorch Transformers | Not needed | No | None (no engine; the weights live in the service process) | Linux + NVIDIA / macOS | No engine wanted, original weights on a mac, small batches |
- llama.cpp and Ollama use GGUF weights, which are **published officially and downloaded directly by default** (see 5.3) — no HF weights and no conversion environment. Convert them yourself only when the user wants different conversion settings or the weights are their own fine-tune; that needs a 4.8 GB conversion environment (CPU torch), which can be deleted afterwards.
- Ollama runs llama.cpp's own runner, so their scores share one source — **do not use one to verify the other**.
-- ⭐ **On macOS (Apple Silicon) only llama.cpp and Ollama are available**: vLLM and SGLang depend on the CUDA stack and will not start on a mac, so do not suggest them. Both macOS paths go through Metal; where the commands differ from Linux is covered in 5.3 / 5.4.
+- ⭐ **PyTorch Transformers starts no engine of its own**: the weights load into the service process, section 5 is only a config file for it (see 5.5), and the service layer's virtual environment is the one that needs torch. It runs one forward pass at a time by default and has no cross-request continuous batching; for throughput, widen the pass with `max_batch_size` (2.3x measured at batch 4), **but the ceiling is still below an engine's** — pick vLLM or SGLang for single-host throughput. Pick this one to avoid installing an engine, or to use the original weights on macOS.
+- ⭐ **On macOS (Apple Silicon) there are three paths**: llama.cpp, Ollama and PyTorch Transformers. The first two use GGUF weights over Metal (where the commands differ from Linux is covered in 5.3 / 5.4); Transformers reads the original bfloat16 weights directly, and `device: auto` selects Metal (MPS). vLLM and SGLang depend on the CUDA stack and will not start on a mac, so do not suggest them.
- ⭐ **On macOS only run the score service**: the render+score service needs a pinned font environment, and that step depends on apt, which is not available on a mac (see 6.2).
## 2. Pre-installation checks
@@ -203,6 +205,8 @@ grep -rq COMMON_DECISION_TYPE_MINICPM_OCR_JEV tools/server/ && echo supported ||
All four engines use port 18499 (the documents' default). When several backends run on one machine, stagger the ports and change the engine address in the service layer to match.
+**With PyTorch Transformers this section is only the config in 5.5**: it starts no engine and has no port, and the weights are loaded by the service process in section 6.
+
### 5.1 vLLM (mirrors `vllm_deploy_jev_en.md` §1)
```bash
@@ -336,9 +340,33 @@ The model name `minicpm-ocr-jev` has to match `model` in `sdk/backends/ollama.ya
Pass criteria: **only the startup self-check can confirm this backend works** (see [section 7](#7-verification)). `ollama show` reporting `decision, vision` only says the GGUF conversion was right; it says nothing about whether the runner knows the model. Same criteria on both platforms — Ollama on macOS also runs llama.cpp plus Metal.
+### 5.5 PyTorch Transformers (mirrors `transformers_deploy_jev_en.md` §1)
+
+This backend installs no engine, starts no process and has no port; this section is only a config file. The weights are loaded by the service process in section 6, so **that virtual environment is the one that needs torch** (see 6.1). Use the HF weights from section 3, not GGUF.
+
+`sdk/backends/transformers.yaml` points at the weights directory:
+
+```yaml
+engine: transformers
+model_path: <WEIGHTS>
+device: auto
+dtype: auto
+attn_implementation: sdpa
+max_in_flight: 1
+max_batch_size: 1
+```
+
+- `model_path` is required and mutually exclusive with `base_url`: supplying both fails at startup.
+- `device: auto` tries `cuda:0`, then `mps`, then `cpu`; on a mac it selects Metal.
+- Leave `dtype` and `attn_implementation` as they are. Measured: on a mac one forward pass takes 0.3 s in bfloat16 and 38 s in float32, with float32 also landing further from the reference scores; `sdpa` lands within 4.4e-3 of the reference scores and `flash_attention_2` within 7.6e-3.
+- `max_in_flight` means concurrent forward passes; leave it at 1. A larger value is lowered back to 1 at startup with a note in `/healthz`.
+- `max_batch_size` is **how many candidates share one forward pass** — a different axis from the line above (that one is how many passes, this one is how wide a pass is). Default 1; raise it for throughput. Measured on 24 candidates (RTX 5090, bf16): batch 1 → 2.17 s, batch 4 → 0.94 s (2.3x), batch 8 → 0.89 s and flattening; peak memory 4347 → 4962 MiB. ⚠ Above 1 the scores are no longer bit-reproducible (the same candidate's probability varies by ≤3.3e-4 across batch sizes, well inside the 4.4e-3 band) — the cause is the GPU's reduction order changing with batch shape, not padding (an equal-length batch with no padding moves too). Keep it at 1 where bit-reproducibility matters.
+
+Pass criteria: **only the startup self-check plus a real score can confirm this backend works** (see [section 7](#7-verification)).
+
## 6. Install and start the service layer
-Pick one of the two shapes; do not start both. Fill in the engine address with the port actually used in section 5.
+Pick one of the two shapes; do not start both. Fill in the engine address with the port actually used in section 5; **PyTorch Transformers takes no such argument** (it has no engine) — see 6.3.
### 6.1 Score service (mirrors §2 of each document)
@@ -351,6 +379,18 @@ pip install "fastapi>=0.110" "uvicorn>=0.27" "httpx>=0.27" "pydantic>=2.6" "PyYA
PATH=/opt/venv-score/bin:$PATH bash sdk/start_score.sh 18501 http://127.0.0.1:18499
```
+With the PyTorch Transformers backend the service process loads the weights, so its dependencies are a separate install and it starts without an engine address:
+
+```bash
+python3 -m venv /opt/venv-transformers && source /opt/venv-transformers/bin/activate
+pip install -r sdk/requirements-transformers.txt
+```
+
+```bash
+JEV_BACKEND_CONFIG=sdk/backends/transformers.yaml \
+PATH=/opt/venv-transformers/bin:$PATH bash sdk/start_score.sh 18501
+```
+
### 6.2 Render+score service (mirrors §3 of each document)
```bash
@@ -379,7 +419,16 @@ JEV_BACKEND_CONFIG=sdk/backends/sglang.yaml \
PATH=/opt/venv-score/bin:$PATH bash sdk/start_score.sh 18501 http://127.0.0.1:18499
```
-Replace `sglang.yaml` with `llamacpp.yaml` / `ollama.yaml`. **Without that variable the service speaks the vLLM protocol**: SGLang will connect but the scores are unusable, while llama.cpp and Ollama expose different endpoints and the service fails to start.
+Replace `sglang.yaml` with `llamacpp.yaml` / `ollama.yaml` / `transformers.yaml`. **Without that variable the service speaks the vLLM protocol**: SGLang will connect but the scores are unusable, while llama.cpp and Ollama expose different endpoints and the service fails to start.
+
+`transformers.yaml` differs in one more way: **drop the engine-address argument from both start scripts entirely**, since the config's `model_path` supplies the weights. Passing an engine address as well fails at startup rather than being ignored.
+
+```bash
+JEV_BACKEND_CONFIG=sdk/backends/transformers.yaml \
+PATH=/opt/venv-transformers/bin:$PATH bash sdk/start_render_score.sh 18500
+```
+
+For the render+score service on this backend, the renderer and the weights share one process, so 6.2's render dependencies go into that same `/opt/venv-transformers` environment (`pip install "playwright==1.62.0" "Markdown==3.10.3"` plus `playwright install chromium`); afterwards confirm `Pillow` is still 12.3.0.
## 7. Verification
@@ -398,8 +447,9 @@ Look at `status` only; `ok` means it passed. The other fields are details, and w
| vLLM | `engine` | `2 logits` | The prompt the engine assembled was checked field by field |
| SGLang | `client` | `2 logits` | The SDK assembles the prompt; what is checked is the string about to be sent |
| llama.cpp / Ollama | `server_template` | `2 probabilities` | The template is baked into the GGUF and cannot be read back, so the prompt is not checked |
+| PyTorch Transformers | `client` | `2 logits` | As SGLang, plus the token-for-token comparison (next paragraph) |
-`token_equality` being `skipped` means skipped, not failed. When `status` is not `ok`, read `prompt.notes` or `error` — it carries the engine's own words.
+`token_equality` being `skipped` means skipped, not failed. **On the PyTorch Transformers backend it reads `equal`**: the token-for-token comparison needs a local tokenizer, and that backend's environment necessarily has transformers installed, so the check actually runs. `served_model` on that backend is the weights directory rather than a model name. When `status` is not `ok`, read `prompt.notes` or `error` — it carries the engine's own words.
### 7.2 Score the bundled cases
@@ -548,6 +598,7 @@ ln -sfn $L/libggml-cuda.so $O/cuda_v13/libggml-cuda.so
| SGLang | Stable 0.5.22 has **no support for this model**; the PR #45829 source tree works, venv 9.5 GB |
| llama.cpp | Release **v0.8.0** (includes PR #30980, merged into master on 2026-10-27), build 214 MB |
| Ollama | Stock v0.40.11 has **no support for this model**; works after the runner swap |
+| PyTorch Transformers | Linux: torch 2.13.0+cu130 + transformers 5.19.0 + torchvision 0.29.2; macOS: torch 2.15.0 + transformers 5.22.2 + torchvision 0.29.2 (both measured on 2026-11-09). ⚠ transformers 4.57.6 does **not** have the `Qwen3_5ForSequenceClassification` class |
| Docker image | Built from `serve/Dockerfile`, with the engine, the scoring service and the render environment all inside it; for the versions actually in the image, read the `scorer` and `render` fields of `/healthz` |
| Service layer | Python 3.12.3, fastapi 0.162.0, uvicorn 0.54.0, httpx 0.28.1, pydantic 2.14.1, Pillow 12.3.0, venv 59 MB |
| Render environment | playwright 1.62.0, KaTeX 0.16.47, render pipeline v8.5, venv 205 MB |
diff --git a/docs/minicpm_ocr_jev_tutorial_en.md b/docs/minicpm_ocr_jev_tutorial_en.md
index 833cd1e..81883e1 100644
--- a/docs/minicpm_ocr_jev_tutorial_en.md
+++ b/docs/minicpm_ocr_jev_tutorial_en.md
@@ -96,7 +96,7 @@ Both shapes use the same model and the same scoring code; they differ only in th
#### Inference scoring
-Scoring can use several inference engines: [vLLM](./vllm_deploy_jev_en.md), [SGLang](./sglang_deploy_jev_en.md), [llama.cpp](./llamacpp_deploy_jev_en.md), [Ollama](./ollama_deploy_jev_en.md)
+Scoring can use several inference engines: [vLLM](./vllm_deploy_jev_en.md), [SGLang](./sglang_deploy_jev_en.md), [llama.cpp](./llamacpp_deploy_jev_en.md), [Ollama](./ollama_deploy_jev_en.md), [PyTorch Transformers](./transformers_deploy_jev_en.md)
#### Requirements
diff --git a/docs/minicpm_ocr_jev_tutorial_zh.md b/docs/minicpm_ocr_jev_tutorial_zh.md
index 437bd61..5e3554f 100644
--- a/docs/minicpm_ocr_jev_tutorial_zh.md
+++ b/docs/minicpm_ocr_jev_tutorial_zh.md
@@ -96,7 +96,7 @@ curl -s http://127.0.0.1:8030/v1/rm/score -H 'Content-Type: application/json' -d
#### 推理打分
-支持多种推理引擎进行打分:[vLLM](./vllm_deploy_jev_zh.md),[SGLang](./sglang_deploy_jev_zh.md),[llama.cpp](./llamacpp_deploy_jev_zh.md),[Ollama](./ollama_deploy_jev_zh.md)
+支持多种推理引擎进行打分:[vLLM](./vllm_deploy_jev_zh.md),[SGLang](./sglang_deploy_jev_zh.md),[llama.cpp](./llamacpp_deploy_jev_zh.md),[Ollama](./ollama_deploy_jev_zh.md),[PyTorch Transformers](./transformers_deploy_jev_zh.md)
#### 环境要求
diff --git a/docs/transformers_deploy_jev_en.md b/docs/transformers_deploy_jev_en.md
new file mode 100644
index 0000000..05dba5a
--- /dev/null
+++ b/docs/transformers_deploy_jev_en.md
@@ -0,0 +1,313 @@
+# SDK Local Deployment: PyTorch Transformers Backend
+
+[中文版](transformers_deploy_jev_zh.md)
+
+[← Back to the deployment guide](./minicpm_ocr_jev_tutorial_en.md)
+
+This document covers the SDK deployment path with PyTorch Transformers as the forward backend: how to install, start, and call the **score service** and the **render+score service**.
+
+The only difference between the two services is where the render image comes from:
+
+| | Score service | Render+score service |
+| ---- | -------------------------------------- | ---------------------------------------------------- |
+| Render image | You provide it | The service renders it by default (you may also provide it) |
+| Render environment | **Not needed** — no Chromium, Node or fonts | Needed |
+| Endpoint | `/v1/score`, returns `prob_1` | `/v1/rm/score*`, returns `prob_yes`, identical to the Docker image |
+| Features | Scoring only | Scoring, best-of-N within a block, batched best-of-N, with precheck |
+| Start script | `sdk/start_score.sh` | `sdk/start_render_score.sh` |
+
+## Deployment steps
+
+1. Install the environment (model dependencies included)
+2. Pick one:
+ - **Score service** → start the service
+ - **Render+score service** → add the render dependencies → start the service
+
+**This backend does not start a separate forward engine.** That is the only difference in deployment steps between it and the vLLM, SGLang, llama.cpp and Ollama backends — see [1. No separate forward engine](#1-no-separate-forward-engine).
+
+## Requirements
+
+| | Linux | macOS |
+| ------------ | ------------------------------------- | ------------------------------------------- |
+| Accelerator | NVIDIA GPU, ≥8GB VRAM | Apple Silicon (M series), ≥16GB unified memory |
+| Driver | ≥535 | Ships with the OS |
+| Python | ≥3.10 | ≥3.10 |
+| Compute backend | CUDA (torch ships its own runtime) | Metal (MPS, ships with torch) |
+
+- **transformers**: ≥5.19
+- **torch**: ≥2.13 (verified with 2.13.0+cu130 on Linux and 2.15.0 on macOS)
+- **torchvision**: required — see the note under [Install](#install)
+- **CUDA toolkit**: **not needed** — torch ships its own GPU runtime
+- **Pinned versions**: `Pillow` 12.3.0, `playwright` 1.62.0 (render+score service only)
+
+The weights occupy about 4.2 GB of accelerator memory (bfloat16) for the life of the process.
+
+**System packages**:
+
+```bash
+sudo apt-get install -y python3 python3-venv python3-pip curl
+```
+
+On a slow network point pip at a nearby mirror first:
+
+```bash
+export PIP_INDEX_URL=https://<your-mirror>/simple
+# in mainland China, for example: https://mirrors.ustc.edu.cn/pypi/simple
+```
+
+---
+
+## 1. No separate forward engine
+
+The other four backends are separate processes: you start an engine, then start a service, and the service sends images and text to the engine over HTTP. This backend loads the weights directly into the service process. There is no second process and no engine port.
+
+Four consequences follow, and together they decide where this backend fits:
+
+- **One forward pass at a time, by default.** This is a deliberate trade: the weights and the service share one process and one card, so concurrent forward passes compete for memory rather than queueing, and going over means running out of it. Fixing the number at one also means the service never has to implement its own batching or memory budget, which is what keeps it simple to run as a service. Concurrent requests queue inside the service and are executed in turn.
+- **For throughput, widen the pass rather than add concurrency.** `max_batch_size` scores several candidates in one forward pass. Measured on 24 candidates (RTX 5090, bfloat16): 2.17 s at batch 1, 0.94 s at batch 4 (2.3x), 0.89 s at batch 8 where the gain has flattened; peak memory rises from 4347 MiB to 4962 MiB. This backend still has no cross-request continuous batching the way an engine does, so **for single-host throughput, use the vLLM or SGLang backend**.
+- **The service process is the model process.** Running out of accelerator memory ends the whole service, not just an engine.
+- **It runs on Apple Silicon**, where `device: auto` selects Metal (MPS). Of the other four backends only llama.cpp and Ollama run on macOS, and both need GGUF weights; this backend reads the original bfloat16 weights directly.
+
+The config file `sdk/backends/transformers.yaml` points at a weights directory rather than at an engine address:
+
+```yaml
+engine: transformers
+model_path: /path/to/weights
+device: auto # auto tries cuda:0, then mps, then cpu
+dtype: auto # auto is bfloat16 on cuda and mps, float32 on cpu
+attn_implementation: sdpa
+max_in_flight: 1
+max_batch_size: 1
+```
+
+- `model_path` is required, and mutually exclusive with `base_url`: this backend has no engine address to point at, so supplying `base_url` as well fails at startup.
+- Keep `dtype` at `auto`. Measured on Apple Silicon, one forward pass takes 0.3 s in bfloat16 and 38 s in float32 — and float32 also lands further from the reference scores, not closer.
+- Keep `attn_implementation` at `sdpa`. Measured on 12 samples, `sdpa` lands within 4.4e-3 of the reference scores and `flash_attention_2` within 7.6e-3, the latter outside the 5e-3 band these published scores were measured in.
+- Keep `max_in_flight` at 1. It means concurrent forward passes. A larger value is lowered back to 1 at startup, with a note in `prompt.notes` under `/healthz`.
+- `max_batch_size` It defaults to 1; raise it for throughput — the measurements above are this setting going from 1 to 8. Candidates beyond it in a request are not dropped, they go in the next pass.
+
+---
+
+## 2. Score service
+
+You already have the render images and only need scores.
+
+### Install
+
+```bash
+cd scripts/minicpm-ocr-jev/
+python3 -m venv /opt/venv-transformers
+source /opt/venv-transformers/bin/activate
+pip install -r sdk/requirements-transformers.txt
+```
+
+The equivalent package-by-package command:
+
+```bash
+pip install "Pillow==12.3.0" "transformers>=5.19" "torch>=2.13" torchvision \
+ "fastapi>=0.110" "uvicorn>=0.27" "httpx>=0.27" "pydantic>=2.6" "PyYAML>=6.0"
+```
+
+- `Pillow` comes first and is pinned exactly. It decides the pixels of the white padding added to block crops longer than 199:1, so a different version changes the scores. `transformers` and `torch` are given lower bounds only; installed together in one environment, pip does not move `Pillow` forward.
+- `torchvision` has nothing to do with video here: `AutoProcessor` builds a video processor from the `processor_config.json` in the weights directory, and that class imports torchvision when constructed. Without it the service fails at startup reporting Torchvision as missing.
+- `accelerate` is **not needed**: this backend places the model with `.to(device)` and never shards across devices.
+- `causal_conv1d` and `flash-linear-attention` are **not needed**: without these two optional kernel libraries, transformers reports at every start that it is falling back to its reference implementation ("correct but much slower"). Every score in this document was measured without them; install them for speed.
+
+**Reference dependency versions**
+
+```text
+python 3.12.3
+torch 2.13.0+cu130
+transformers 5.19.0
+torchvision 0.29.2
+fastapi 0.162.0
+uvicorn 0.54.0
+httpx 0.28.1
+pydantic 2.14.1
+PyYAML 6.0.3
+Pillow 12.3.0
+```
+
+### Start
+
+The only argument is the service port; there is no engine address:
+
+```bash
+cd scripts/minicpm-ocr-jev/
+PATH=/opt/venv-transformers/bin:$PATH \
+JEV_BACKEND_CONFIG=sdk/backends/transformers.yaml \
+ bash sdk/start_score.sh 18501
+```
+
+Start it with the interpreter that has torch, since this process loads the weights. The service runs a single worker: each worker would load its own copy of the weights.
+
+The service runs a prompt self-check at startup — see [4. Startup self-check](#4-startup-self-check).
+
+### Endpoints
+
+| Method | Path | Purpose |
+|---|---|---|
+| GET | `/healthz` | Service status, the loaded weights directory, the prompt template fingerprint and the self-check result |
+| POST | `/v1/score` | Score a batch of already-rendered candidates |
+
+### Request
+
+```bash
+curl -s http://127.0.0.1:18501/v1/score -H 'Content-Type: application/json' -d '{
+ "items": [{"original_image": "<base64>", "render_image": "<base64>", "ocr_text": "..."}]
+}'
+```
+
+```json
+{"results": [{"prob_1": 0.00280, "error": null}]}
+```
+
+All three fields are required: `original_image` is the base64 of the original block crop, `render_image` is the base64 of that candidate rendered back into an image, and `ocr_text` is the candidate text itself. The base64 carries **no** `data:image/png;base64,` prefix, matching the image API.
+
+### Fields and limits
+
+- `ocr_text` goes into the model as given, with no cleanup.
+- `prob_1` is `softmax(logits)[1]`: no threshold, no label, and the logits are not returned.
+- Up to 64 items per request (`JEV_MAX_ITEMS` adjusts it); above that the service returns 413, and an empty batch returns an empty result. This number is an upper guard against one request carrying too many images, not a recommended batch size.
+- If a base64 payload cannot be decoded the whole batch returns 422, naming the item index and the field. A failure during scoring affects only that item, which carries its own `error` with `prob_1` set to `null`.
+
+---
+
+## 3. Render+score service
+
+You only have candidate text and want the service to render it before scoring. Precheck, render and forward all happen in this one process.
+
+### Install
+
+With this backend the weights and the renderer live in the same process, so both sets of dependencies go into the **same** virtual environment. Add the render dependencies to the environment from the previous section:
+
+```bash
+cd scripts/minicpm-ocr-jev/
+source /opt/venv-transformers/bin/activate
+pip install "playwright==1.62.0" "Markdown==3.10.3"
+playwright install chromium
+sudo apt-get install -y nodejs fonts-noto-cjk
+```
+
+On a slow network, fetch Chromium from a mirror:
+
+```bash
+PLAYWRIGHT_DOWNLOAD_HOST=https://<your-mirror>/playwright \
+ playwright install chromium
+# in mainland China, for example:
+# PLAYWRIGHT_DOWNLOAD_HOST=https://cdn.npmmirror.com/binaries/playwright
+```
+
+Afterwards, confirm `Pillow` is still 12.3.0:
+
+```bash
+python3 -c "import PIL; print(PIL.__version__)"
+```
+
+When the renderer and the model share one environment, that exact version is yours to keep. It decides the pixels of the render image, and the render image is one of the model's inputs.
+
+### Start
+
+The only argument is the service port; there is no engine address:
+
+```bash
+cd scripts/minicpm-ocr-jev/
+PATH=/opt/venv-transformers/bin:$PATH \
+JEV_BACKEND_CONFIG=sdk/backends/transformers.yaml \
+ bash sdk/start_render_score.sh 18500
+```
+
+`RM_RENDER_BROWSERS` controls how many render processes run. The service runs a single worker; raise that variable rather than adding workers.
+
+### Endpoints
+
+The paths and field names are identical to the Docker image, so callers moving between the image and the SDK change nothing:
+
+| Method | Path | Purpose |
+|---|---|---|
+| GET | `/healthz` | As above, plus the supported `input_form` and the render pool status |
+| POST | `/v1/rm/score` | Score a batch of "original image + candidate text" pairs, with a summary |
+| POST | `/v1/rm/score_best` | Several candidates for one block; pick the best |
+| POST | `/v1/rm/score_best_batch` | Several blocks, each picking its own best, in one request |
+
+Full field definitions are in the [Docker image API reference](./minicpm_ocr_jev_docker_api_en.md), which describes the same endpoints this service exposes.
+
+### Request
+
+Best-of-N within one block:
+
+```bash
+curl -s http://127.0.0.1:18500/v1/rm/score_best -H 'Content-Type: application/json' -d '{
+ "input_form": "ternary",
+ "case_id": "block_01",
+ "image": "<base64 of the original block crop>",
+ "category": "text",
+ "candidates": ["candidate A", "candidate B"]
+}'
+```
+
+```json
+{"best_index": 0, "best_text": "candidate A", "scores": [0.99524, 0.00610],
+ "verdicts": ["scored", "scored"],
+ "stage_sec": {"render_sec": 0.33, "forward_sec": 0.31, "total_sec": 0.65},
+ "batch_size": 2}
+```
+
+- `input_form` currently takes one value, `ternary`, and must be sent explicitly.
+- `category` must match the block's real type (`text` / `formula` / `table`). A wrong value is not an error, but the score will be off.
+- Sending `render_images` skips server-side rendering; its length must equal that of `candidates`.
+- Up to 64 candidates per request (`RM_MAX_ITEMS` adjusts it), again an upper guard rather than a recommended batch size. All three endpoints count **candidates**, not blocks: `score_best_batch` counts the candidates of every block together, so at 3 candidates per block, 64 covers 21 blocks.
+
+### The two rates in the summary
+
+`pass_rate` and `throughput_rate` are different things. The first is the scoring success rate (`scored / total`, independent of any threshold); the second is the pass-threshold rate (items with `prob_yes >= RM_THRESHOLD` over total, threshold 0.5 by default and configurable). The threshold only enters that second rate; every item's `prob_yes` is returned as produced.
+
+---
+
+## 4. Startup self-check
+
+Both services verify the prompt going into the model before accepting the first request.
+
+After starting, query `/healthz`; `status` of `ok` means everything is in order:
+
+```bash
+curl -s http://127.0.0.1:18501/healthz
+```
+
+```json
+{"status": "ok", "served_model": "/path/to/weights",
+ "prompt": {"template_md5": "9aab68e8ba8ab4da17ba9752bddb199c",
+ "source": "client",
+ "last_token": 271, "expected_last_token": 271,
+ "token_equality": "equal",
+ "forward_shape": "2 logits",
+ "notes": ["the prompt we send matches build_prompt() ..."]}}
+```
+
+Read `status` alone: `ok` means the self-check passed and the service is usable, and the remaining fields under `prompt` are the detail it left behind — matching the shape above is normal. When `status` is not `ok`, `prompt.notes` says which check did not pass.
+
+`token_equality` reads `equal` on this backend, where it reads `skipped` on the vLLM, SGLang, llama.cpp and Ollama backends: the token-for-token comparison needs a local tokenizer, and this backend's environment necessarily has transformers installed, so that check can actually run.
+
+### Verify with the bundled cases
+
+The self-check only confirms the service starts. To confirm the scores as well, run the three cases under `examples/` and compare against the reference scores in `observed_prob_yes` in each `case.json`:
+
+```bash
+cd scripts/minicpm-ocr-jev
+python3 - <<'EOF'
+import base64, json, urllib.request
+for name in ("01_text_putnam", "02_formula_putnam", "03_table_gb_standard"):
+ c = json.load(open(f"examples/{name}/case.json"))
+ role = c["reference_render_of"]
+ text = next(x["text"] for x in c["candidates"] if x["role"] == role)
+ b64 = lambda f: base64.b64encode(open(f"examples/{name}/{f}", "rb").read()).decode()
+ body = {"items": [{"original_image": b64(c["block_image"]),
+ "render_image": b64(c["reference_render"]), "ocr_text": text}]}
+ req = urllib.request.Request("http://127.0.0.1:18501/v1/score",
+ data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
+ got = json.load(urllib.request.urlopen(req))["results"][0]["prob_1"]
+ print(f"{name:24} got {got:.5f} reference {c['observed_prob_yes'][role]:.5f}")
+EOF
+```
+
+All three scores within 0.02 of the reference is normal. For the render+score service, change the endpoint to `/v1/rm/score_best` and the body to `image` plus `candidates` (see [3. Render+score service · Request](#request-1)); the service renders for you.
diff --git a/docs/transformers_deploy_jev_zh.md b/docs/transformers_deploy_jev_zh.md
new file mode 100644
index 0000000..8756e0f
--- /dev/null
+++ b/docs/transformers_deploy_jev_zh.md
@@ -0,0 +1,310 @@
+# SDK 本地部署:PyTorch Transformers 后端
+
+[English](transformers_deploy_jev_en.md)
+
+[← 返回使用教程](./minicpm_ocr_jev_tutorial_zh.md)
+
+本文介绍SDK部署模式下,以 PyTorch Transformers 作为前向后端时,**不带渲染器服务**与**内置渲染器服务**的安装、启动、接口与请求格式。
+
+两种服务区别只在渲染图从哪里来:
+
+| | 不带渲染器服务 | 内置渲染器服务 |
+| ---- | -------------------------- | ------------------------------------------- |
+| 渲染图 | 由你提供 | 服务默认自己渲染(也可由你提供) |
+| 渲染环境 | **不需要**,无 Chromium、Node、字体 | 需要 |
+| 接口 | `/v1/score`,返回 `prob_1` | `/v1/rm/score*`,返回 `prob_yes`,与 Docker 镜像同构 |
+| 功能 | 逐条打分 | 逐条打分、块内选优、批量选优,带 precheck |
+| 启动脚本 | `sdk/start_score.sh` | `sdk/start_render_score.sh` |
+
+## 部署流程
+
+1. 装环境(含模型依赖)
+2. 二选一:
+ - **不带渲染器服务** → 起服务
+ - **内置渲染器服务** → 追加渲染依赖 → 起服务
+
+**本后端不单独启动前向引擎**,这是它与 vLLM、SGLang、llama.cpp、Ollama 四种后端在部署步骤上唯一的区别,详见[一、没有单独的前向引擎](#一没有单独的前向引擎)。
+
+## 环境要求
+
+| | Linux | macOS |
+| -------- | ------------------------------------- | ---------------------------------- |
+| 加速器 | NVIDIA GPU,显存 ≥8GB | Apple Silicon(M 系列),统一内存 ≥16GB |
+| 驱动 | ≥535 | 随系统 |
+| Python | ≥3.10 | ≥3.10 |
+| 计算后端 | CUDA(torch 自带运行时) | Metal(MPS,torch 自带) |
+
+- **transformers**:≥5.19
+- **torch**:≥2.13(Linux 实测 2.13.0+cu130,macOS 实测 2.15.0)
+- **torchvision**:必装,见[安装](#安装)小节说明
+- **CUDA toolkit**:**不需要**,torch 自带 GPU 运行时
+- **固定版本**:`Pillow` 12.3.0、`playwright` 1.62.0(仅内置渲染器服务)
+
+模型权重常驻显存约 4.2 GB(bfloat16)。
+
+**系统包**:
+
+```bash
+sudo apt-get install -y python3 python3-venv python3-pip curl
+```
+
+慢网下先给 pip 指一个就近镜像:
+
+```bash
+export PIP_INDEX_URL=https://mirrors.ustc.edu.cn/pypi/simple
+```
+
+---
+
+## 一、没有单独的前向引擎
+
+另外四种后端都是独立进程:先起引擎,再起服务,服务通过 HTTP 把图文发给引擎。本后端把权重直接加载进服务进程,没有第二个进程、也没有引擎端口。
+
+由此带来四点,决定了它适合用在什么地方:
+
+- **默认一次只做一次前向**。这是有意的取舍:权重与服务在同一进程、同一张卡上,并发的前向竞争的是显存,超出不是排队等待而是显存耗尽;固定成一次,服务端就不必自己实现攒批与显存预算,起成服务的形态也最简单。并发请求在服务内排队逐个执行。
+- **要吞吐就加宽单次前向,而不是加并发**。`max_batch_size` 让一次前向算多个候选。实测 24 个候选(RTX 5090,bfloat16):批 1 耗时 2.17 秒,批 4 降到 0.94 秒(2.3 倍),批 8 为 0.89 秒、收益已趋平;峰值显存从 4347 MiB 升到 4962 MiB。本后端仍然没有引擎那样的跨请求连续批处理,**单机高吞吐场景请用 vLLM 或 SGLang 后端**。
+- **服务进程即模型进程**。显存不足会终止整个服务,而不只是引擎。
+- **可在 Apple Silicon 上运行**,`device: auto` 会自动选用 Metal(MPS)。另外四种后端里只有 llama.cpp 与 Ollama 能在 macOS 上运行,且需要 GGUF 格式权重;本后端直接读取原始 bfloat16 权重。
+
+配置文件 `sdk/backends/transformers.yaml` 指向权重目录,而不是引擎地址:
+
+```yaml
+engine: transformers
+model_path: /path/to/weights
+device: auto # auto 依次尝试 cuda:0、mps、cpu
+dtype: auto # auto 在 cuda 与 mps 上为 bfloat16,cpu 上为 float32
+attn_implementation: sdpa
+max_in_flight: 1
+max_batch_size: 1
+```
+
+- `model_path` 必填,且与 `base_url` 互斥:本后端没有可指向的引擎地址,同时给出 `base_url` 会在启动时报错。
+- `dtype` 保持 `auto`。在 Apple Silicon 上实测,一次前向 bfloat16 耗时 0.3 秒、float32 耗时 38 秒,而 float32 与参考分数的偏差反而更大。
+- `attn_implementation` 保持 `sdpa`。实测 12 个样例,`sdpa` 与参考分数相差在 4.4e-3 以内、`flash_attention_2` 为 7.6e-3,后者超出本权重发布分数所在的 5e-3 区间。
+- `max_in_flight` 保持 1,含义是同时进行的前向次数。填大于 1 的值会在启动时降回 1,并在 `/healthz` 的 `prompt.notes` 里留一条说明。
+- `max_batch_size` 是**一次前向里的候选数**,默认 1,调大即可提吞吐,上面那组实测就是这一项从 1 改到 8 的结果。一次请求里超出的候选不会被丢弃,排进下一次前向。
+
+---
+
+## 二、不带渲染器服务
+
+你已经有渲染图,只要分数。
+
+### 安装
+
+```bash
+cd scripts/minicpm-ocr-jev/
+python3 -m venv /opt/venv-transformers
+source /opt/venv-transformers/bin/activate
+pip install -r sdk/requirements-transformers.txt
+```
+
+等价的逐包命令:
+
+```bash
+pip install "Pillow==12.3.0" "transformers>=5.19" "torch>=2.13" torchvision \
+ "fastapi>=0.110" "uvicorn>=0.27" "httpx>=0.27" "pydantic>=2.6" "PyYAML>=6.0"
+```
+
+- `Pillow` 写在最前且为精确版本。它决定了超过 199:1 的长条块图补白后的像素,版本变化会改变分数。`transformers` 与 `torch` 只给下界,装在同一环境时 pip 不会把 `Pillow` 推高。
+- `torchvision` 与视频无关:`AutoProcessor` 会按权重目录里的 `processor_config.json` 构建一个视频处理器,该类在构建时导入 torchvision。缺它会在启动阶段报 Torchvision 缺失。
+- **不需要** `accelerate`:本后端用 `.to(device)` 放置模型,不做跨卡切分。
+- **不需要** `causal_conv1d`、`flash-linear-attention`:缺少这两个可选算子库时,transformers 会在每次启动时提示回落到参考实现("correct but much slower")。本文给出的全部分数即在不装它们的环境下测得,装它们是为了提速。
+
+**依赖版本参考**
+
+```text
+python 3.12.3
+torch 2.13.0+cu130
+transformers 5.19.0
+torchvision 0.29.2
+fastapi 0.162.0
+uvicorn 0.54.0
+httpx 0.28.1
+pydantic 2.14.1
+PyYAML 6.0.3
+Pillow 12.3.0
+```
+
+### 启动
+
+参数只有服务端口,不带引擎地址:
+
+```bash
+cd scripts/minicpm-ocr-jev/
+PATH=/opt/venv-transformers/bin:$PATH \
+JEV_BACKEND_CONFIG=sdk/backends/transformers.yaml \
+ bash sdk/start_score.sh 18501
+```
+
+必须用装了 torch 的那个解释器启动,权重由本进程加载。服务只起一个 worker:每个 worker 都会各加载一份权重。
+
+服务启动时会自检一遍 prompt,见 [四、启动自检](#四启动自检)。
+
+### 接口
+
+| 方法 | 路径 | 用途 |
+|---|---|---|
+| GET | `/healthz` | 服务状态、所加载的权重目录、prompt 模板指纹与自检结论 |
+| POST | `/v1/score` | 给一批已渲染好的候选打分 |
+
+### 请求
+
+```bash
+curl -s http://127.0.0.1:18501/v1/score -H 'Content-Type: application/json' -d '{
+ "items": [{"original_image": "<base64>", "render_image": "<base64>", "ocr_text": "..."}]
+}'
+```
+
+```json
+{"results": [{"prob_1": 0.00280, "error": null}]}
+```
+
+三个字段都是必填:`original_image` 是原始块图的 base64,`render_image` 是该候选渲染回图片后的 base64,`ocr_text` 是候选文本本身。base64 **不带** `data:image/png;base64,` 前缀,与镜像接口一致。
+
+### 字段与限额
+
+- `ocr_text` 原样送进模型,不做任何清洗。
+- `prob_1` 是 `softmax(logits)[1]`,不带阈值、不带标签、不回 logits。
+- 一次最多 64 条(`JEV_MAX_ITEMS` 可调),超限返回 413;空批返回空结果。这个数是防止单请求塞进过多图片的保护上限,不是推荐批大小。
+- 图片 base64 解不开时整批返回 422,并指出是第几条的哪个字段;打分阶段的失败只影响那一条,它在自己那一格里带上 `error`、`prob_1` 为 `null`。
+
+---
+
+## 三、内置渲染器服务
+
+你只有候选文本,让服务渲染完再打分。precheck、render、forward 三个阶段都在这个进程里完成。
+
+### 安装
+
+本后端的权重与渲染器在同一个进程里,所以两套依赖要装进**同一个**虚拟环境。在上一节那个环境里追加渲染依赖:
+
+```bash
+cd scripts/minicpm-ocr-jev/
+source /opt/venv-transformers/bin/activate
+pip install "playwright==1.62.0" "Markdown==3.10.3"
+playwright install chromium
+sudo apt-get install -y nodejs fonts-noto-cjk
+```
+
+慢网下 Chromium 走镜像:
+
+```bash
+PLAYWRIGHT_DOWNLOAD_HOST=https://cdn.npmmirror.com/binaries/playwright \
+ playwright install chromium
+```
+
+装完核对一次 `Pillow` 仍是 12.3.0:
+
+```bash
+python3 -c "import PIL; print(PIL.__version__)"
+```
+
+渲染器与模型共用一个环境时,`Pillow` 的精确版本要由你守住。它决定渲染图的像素,而渲染图是模型的输入之一。
+
+### 启动
+
+参数只有服务端口,不带引擎地址:
+
+```bash
+cd scripts/minicpm-ocr-jev/
+PATH=/opt/venv-transformers/bin:$PATH \
+JEV_BACKEND_CONFIG=sdk/backends/transformers.yaml \
+ bash sdk/start_render_score.sh 18500
+```
+
+渲染进程数量由 `RM_RENDER_BROWSERS` 控制;服务只起一个 worker,要提吞吐请调这个变量而不是加 worker。
+
+### 接口
+
+端点与字段名与 Docker 镜像完全一致,调用方在镜像与 SDK 之间切换时不必改任何字段:
+
+| 方法 | 路径 | 用途 |
+|---|---|---|
+| GET | `/healthz` | 同上,另报支持的 `input_form` 与渲染池状态 |
+| POST | `/v1/rm/score` | 给一批「原图 + 候选文本」逐条打分,返回分数与汇总 |
+| POST | `/v1/rm/score_best` | 一个块内多个候选,选出最优 |
+| POST | `/v1/rm/score_best_batch` | 多个块各自选优,一次提交 |
+
+完整字段定义见 [Docker 镜像 API 参考](./minicpm_ocr_jev_docker_api_zh.md),那份文档描述的就是本服务的同名端点。
+
+### 请求
+
+块内选优:
+
+```bash
+curl -s http://127.0.0.1:18500/v1/rm/score_best -H 'Content-Type: application/json' -d '{
+ "input_form": "ternary",
+ "case_id": "block_01",
+ "image": "<base64 原始块图>",
+ "category": "text",
+ "candidates": ["候选 A", "候选 B"]
+}'
+```
+
+```json
+{"best_index": 0, "best_text": "候选 A", "scores": [0.99524, 0.00610],
+ "verdicts": ["scored", "scored"],
+ "stage_sec": {"render_sec": 0.33, "forward_sec": 0.31, "total_sec": 0.65},
+ "batch_size": 2}
+```
+
+- `input_form` 目前只有 `ternary` 一个取值,必须显式传。
+- `category` 必须与块真实类型一致(`text` / `formula` / `table`),填错不报错但分数会偏。
+- 传 `render_images` 则跳过服务端渲染,其长度必须与 `candidates` 一致。
+- 一次最多 64 个候选(`RM_MAX_ITEMS` 可调),同样是保护上限而非推荐批大小。三个端点都按**候选数**算、不按块数:`score_best_batch` 数的是所有块的候选总和,每块 3 个候选时 64 只够 21 个块。
+
+### 汇总里的两个比率
+
+`pass_rate` 与 `throughput_rate` 是两件事:前者是打分成功率(`scored / total`,与阈值无关),后者是过阈率(`prob_yes >= RM_THRESHOLD` 的条数 / total,阈值默认 0.5,可配)。阈值只参与这个比率的计算,任何一条的 `prob_yes` 都按原值返回。
+
+---
+
+## 四、启动自检
+
+两种服务在接第一个请求之前都会校一遍送进模型的 prompt。
+
+起服后查 `/healthz`,`status` 为 `ok` 即正常:
+
+```bash
+curl -s http://127.0.0.1:18501/healthz
+```
+
+```json
+{"status": "ok", "served_model": "/path/to/weights",
+ "prompt": {"template_md5": "9aab68e8ba8ab4da17ba9752bddb199c",
+ "source": "client",
+ "last_token": 271, "expected_last_token": 271,
+ "token_equality": "equal",
+ "forward_shape": "2 logits",
+ "notes": ["the prompt we send matches build_prompt() ..."]}}
+```
+
+只看 `status`:`ok` 就是自检通过、服务可用,`prompt` 下的其余字段是自检留下的明细,照上面的样子即为正常。`status` 不是 `ok` 时,`prompt.notes` 写明是哪一项没过。
+
+本后端的 `token_equality` 为 `equal`,而以 vLLM、SGLang、llama.cpp、Ollama 为后端时该字段为 `skipped`:逐 token 比对需要本机有 tokenizer,而本后端的运行环境必然装了 transformers,这一项因此可以真正执行。
+
+### 用自带用例验证
+
+自检只确认服务起得来。要确认分数也对,用 `examples/` 下三个用例打一遍,与 `case.json` 里的参考分数 `observed_prob_yes` 对照:
+
+```bash
+cd scripts/minicpm-ocr-jev
+python3 - <<'EOF'
+import base64, json, urllib.request
+for name in ("01_text_putnam", "02_formula_putnam", "03_table_gb_standard"):
+ c = json.load(open(f"examples/{name}/case.json"))
+ role = c["reference_render_of"]
+ text = next(x["text"] for x in c["candidates"] if x["role"] == role)
+ b64 = lambda f: base64.b64encode(open(f"examples/{name}/{f}", "rb").read()).decode()
+ body = {"items": [{"original_image": b64(c["block_image"]),
+ "render_image": b64(c["reference_render"]), "ocr_text": text}]}
+ req = urllib.request.Request("http://127.0.0.1:18501/v1/score",
+ data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
+ got = json.load(urllib.request.urlopen(req))["results"][0]["prob_1"]
+ print(f"{name:24} got {got:.5f} reference {c['observed_prob_yes'][role]:.5f}")
+EOF
+```
+
+三行分数与参考值相差都在 0.02 以内即为正常。内置渲染器服务把端点换成 `/v1/rm/score_best`、请求体换成 `image` + `candidates`(见[三、内置渲染器服务 · 请求](#请求-1)),服务会自己渲染。
diff --git a/scripts/minicpm-ocr-jev/sdk/backends/transformers.yaml b/scripts/minicpm-ocr-jev/sdk/backends/transformers.yaml
new file mode 100644
index 0000000..449e5ce
--- /dev/null
+++ b/scripts/minicpm-ocr-jev/sdk/backends/transformers.yaml
@@ -0,0 +1,75 @@
+# Which engine runs the forward pass, and -- for this one alone -- where the
+# weights are.
+#
+# This is the only backend with no engine to start. The other four configs point
+# at a server that was launched separately and holds the model; this one names a
+# checkpoint directory, and the service process loads it at startup and keeps it
+# in its own memory. There is no second process and no port to reach it on.
+#
+# What that buys: nothing to install beyond torch and transformers, no CUDA-only
+# engine, and the service runs anywhere the weights fit -- including a laptop.
+# What it costs: no continuous batching -- requests queue in the service and are
+# served in turn -- and an out-of-memory error takes the service down with it
+# rather than just the engine. So this is the reference and small-batch route,
+# not the throughput one.
+
+engine: transformers
+
+# ⭐ Required here, and required *instead of* base_url: the local checkpoint
+# directory. Replace the placeholder -- it is checked for existence before the
+# model loads, so an unedited config fails naming this file rather than failing
+# somewhere inside the loader. Starting with a base_url set is an error rather
+# than an ignored key, because the two describe incompatible deployments.
+model_path: /path/to/weights
+
+# Where to run it. "auto" tries cuda:0, then Apple's mps, then cpu. Pin it
+# (cuda:1, mps, cpu, …) when the host has more than one GPU and this service
+# should not take the first.
+#
+# mps is a real option, not a fallback: measured on an M-series machine, this
+# checkpoint runs on Metal with no unimplemented operators and lands within
+# 4.1e-3 of the reference scores -- marginally closer than the CUDA leg's 4.2e-3.
+device: auto
+
+# "auto" means bfloat16 on any accelerator (cuda or mps) and float32 only on cpu.
+#
+# ⚠ Do not widen this to float32 on mps "to be safe". One forward pass there
+# takes 0.3 s in bfloat16 and 38 s in float32 -- a factor of ~100 -- and float32
+# also lands *further* from the reference scores (4.9e-3 against 4.1e-3). The
+# published numbers were measured in bfloat16; float16 is a different thing again,
+# same width and a much smaller exponent range.
+dtype: auto
+
+# ⚠ Leave this at sdpa. Measured against the reference scores on 12 samples,
+# sdpa lands within 4.4e-3 and flash_attention_2 within 7.6e-3. Both rank
+# candidates identically and neither looks wrong; only sdpa stays inside the
+# 5e-3 band the published numbers were measured in. "auto" also resolves to sdpa
+# rather than to whatever is installed, for that reason.
+attn_implementation: sdpa
+
+# Concurrent forward passes. ⚠ Not the same quantity as the other configs'
+# max_in_flight: there it bounds sockets toward an engine that queues, here it
+# would bound passes competing for one GPU's memory, which does not queue. Values
+# above 1 are lowered to 1 with a note.
+max_in_flight: 1
+
+# How many candidates share one forward pass. A different axis from the line
+# above: that one is how many passes run at once (one), this one is how wide a
+# single pass is.
+#
+# 1 is the default so that an unedited config scores exactly what it scored
+# before this option existed. Raise it to get throughput out of this backend --
+# it is the only way to, since there is no engine doing continuous batching
+# underneath. A scoring prompt measures 304-590 tokens on the shipped examples,
+# which does not fill a modern GPU, so a wider pass is mostly free compute.
+#
+# What it costs is memory, and the cost is not linear in the number you write
+# here: rows are padded to the longest in the pass, and a batch mixing a short
+# text block with a wide table pays for the table on every row. Raise it in
+# steps and watch peak memory; an out-of-memory here takes the service with it.
+# Candidates beyond this number are not dropped, they go in the next pass.
+max_batch_size: 1
+
+# Optional, for logs only: what to call this model in /healthz. The default is
+# the checkpoint directory, which is what actually identifies the weights.
+# model: minicpm-ocr-jev
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 9130c4d..e9be0b9 100644
--- a/scripts/minicpm-ocr-jev/sdk/jev_score/backends/__init__.py
+++ b/scripts/minicpm-ocr-jev/sdk/jev_score/backends/__init__.py
@@ -29,7 +29,15 @@ DEFAULT_CONFIG = CONFIG_DIR / "vllm.yaml"
#: 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"}
+KNOWN_ENGINES = {"vllm", "sglang", "llamacpp", "ollama", "transformers"}
+
+#: Engines that are not a separate process. There is one, and it is the reason
+#: this set exists rather than an `if engine == "transformers"`: the distinction
+#: it draws is "is there a server to point at", and that question decides which
+#: key the config must carry. An HTTP engine needs `base_url` and a local one
+#: needs `model_path`; requiring both, or neither, would let a config that names
+#: no weights start a service that cannot score.
+LOCAL_ENGINES = {"transformers"}
def load_config(path: str | Path | None = None) -> dict[str, Any]:
@@ -78,6 +86,9 @@ def load_backend(path: str | Path | None = None, **overrides: Any) -> Backend:
f"Known: {', '.join(sorted(KNOWN_ENGINES))}."
)
+ if engine in LOCAL_ENGINES:
+ return _load_local_backend(engine, config)
+
base_url = config.get("base_url")
if not base_url:
raise ValueError(f"{config.get('_source')}: 'base_url' is required")
@@ -108,3 +119,54 @@ def load_backend(path: str | Path | None = None, **overrides: Any) -> Backend:
from .vllm_backend import VLLMBackend
return VLLMBackend(str(base_url), **kwargs)
+
+
+def _load_local_backend(engine: str, config: dict[str, Any]) -> Backend:
+ """Build a backend that runs the forward pass in this process.
+
+ Split out rather than folded into the chain above because the four arguments
+ the HTTP adapters share -- a URL, a timeout, a socket budget -- are the wrong
+ four here. What this one needs instead is where the weights are and what to
+ run them as.
+ """
+ source = config.get("_source")
+
+ if config.get("base_url"):
+ raise ValueError(
+ f"{source}: engine {engine!r} runs in this process, so 'base_url' "
+ f"({config['base_url']!r}) has nothing to point at.\n"
+ " If this came from start_score.sh, that script's second argument is "
+ "an engine URL and does not apply to a local engine -- start the "
+ "service without it (see the deployment guide for this engine)."
+ )
+
+ model_path = config.get("model_path")
+ if not model_path:
+ raise ValueError(
+ f"{source}: 'model_path' is required for engine {engine!r} -- the "
+ "local checkpoint directory to load. There is no engine to ask."
+ )
+ if not Path(str(model_path)).is_dir():
+ raise ValueError(
+ f"{source}: model_path {str(model_path)!r} is not a directory. "
+ "This is checked before loading so the failure names the config "
+ "rather than surfacing from inside the model loader."
+ )
+
+ from .transformers_backend import TransformersBackend
+
+ return TransformersBackend(
+ str(model_path),
+ device=str(config.get("device", "auto")),
+ dtype=str(config.get("dtype", "auto")),
+ attn_implementation=str(config.get("attn_implementation", "sdpa")),
+ # Default 1, not 32: the HTTP default bounds sockets, this one bounds
+ # concurrent forward passes on one GPU. See transformers_backend.py.
+ max_in_flight=int(config.get("max_in_flight", 1)),
+ # Also 1, for a different reason. This one is how many candidates share a
+ # pass, and raising it is the supported way to get throughput out of this
+ # backend -- but the default stays at 1 so an unchanged config scores
+ # exactly what it scored before this option existed.
+ max_batch_size=int(config.get("max_batch_size", 1)),
+ model=config.get("model") or None,
+ )
diff --git a/scripts/minicpm-ocr-jev/sdk/jev_score/backends/transformers_backend.py b/scripts/minicpm-ocr-jev/sdk/jev_score/backends/transformers_backend.py
new file mode 100644
index 0000000..63597d7
--- /dev/null
+++ b/scripts/minicpm-ocr-jev/sdk/jev_score/backends/transformers_backend.py
@@ -0,0 +1,473 @@
+"""Transformers adapter: no engine at all -- the weights live in this process.
+
+Every other adapter here is an HTTP client. An engine was started separately, it
+holds the weights, and the adapter's whole job is to put a request on the wire.
+This one has no wire. `from_pretrained` runs inside the service process, the
+model sits in its memory, and `forward` is a function call.
+
+That difference is worth stating plainly because it changes what can go wrong,
+not just how fast it is:
+
+ configuration There is no `base_url` to point at. What this adapter needs is
+ `model_path`, a local checkpoint directory, and `sdk/jev_score/backends/__init__.py`
+ asks for one instead -- see the `LOCAL_ENGINES` branch there.
+
+ concurrency Two axes, and keeping them apart is the whole design here.
+
+ `max_in_flight` is how many forward passes run *at once*. An HTTP engine
+ queues past its own capacity, so there the name bounds this process's
+ sockets. Here it would bound concurrent passes on one GPU, where exceeding
+ it does not queue, it runs out of memory. So that gate stays at one: the
+ forward runs on a worker thread (`asyncio.to_thread`, because it is
+ synchronous and would otherwise block the event loop for its whole
+ duration), and a config asking for more gets a note, not a silent OOM.
+
+ `max_batch_size` is how many candidates go through *one* pass. That is a
+ different question with a different answer, because the four HTTP engines
+ get their batching from the engine's own continuous batching and this one
+ has none. Measured on the shipped examples, a scoring prompt is 304-590
+ tokens -- nowhere near enough to saturate the GEMMs -- so widening the
+ batch buys real throughput rather than just latency. It defaults to 1, so
+ the shipped configuration runs exactly the code path it always did.
+
+ What a wider pass does to the numbers, measured rather than assumed. On
+ CUDA the logits move by 2-5 bf16 ulps (one ulp near 2.9 is 0.015625) when
+ the batch changes, which is 3.3e-4 or less once softmaxed -- an order of
+ magnitude inside the 4.4e-3 the published scores were measured in, but
+ not bit-identical. The cause is the reduction order in a wider GEMM, not
+ padding: a batch of the *same* candidate repeated, every row equal length
+ and zero pad tokens, moves further (7.8e-2) than any mixed-length batch
+ here does. Left and right padding move the logits alike, so the 18
+ recurrent layers (`layer_types` is 18 linear_attention + 6 full_attention)
+ are not leaking pad steps into their state either way.
+
+ Padding is still on the right. Not for a measured reason -- there isn't
+ one -- but because right padding is the shape where "the value head reads
+ the last real token" needs nothing to be true of the pad handling, and
+ this gets no cheaper to reason about later. The per-row pooled-position
+ assert below is what actually holds the line.
+
+ blast radius An engine that dies is a connection error this process can
+ report. A model that dies takes the service with it.
+
+ worker count `uvicorn --workers N` loads the model N times, once per
+ process. For the HTTP adapters N is N thin clients; here it is N times
+ 4.1 GiB. The start script pins it to 1.
+
+What does *not* change is the contract: two raw class logits, in class order,
+and `scorer.py` applies the same softmax it applies to vLLM's. The value head is
+the same tensor either way.
+
+Two things this adapter can check that no HTTP adapter can, because the
+tokenizer is right here rather than behind an engine:
+
+ * `tokenize()` answers for real, so `selfcheck.py` never has to report the
+ prompt as unverifiable.
+ * every scoring call asserts the pooled position itself. The classify path
+ pools the last token, this model class pools the last non-pad token, and
+ with one sequence and no padding those are the same token -- but that is a
+ property worth asserting per request rather than assuming, because when it
+ breaks it breaks silently. 271 is the final newline of the empty assistant
+ turn; 198 is the near-miss.
+"""
+from __future__ import annotations
+
+import base64
+import binascii
+import io
+from pathlib import Path
+from typing import Any
+
+from ..prompt import PromptParts
+from .base import BackendError
+
+__all__ = ["TransformersBackend", "POOLED_TOKEN_ID"]
+
+#: The token the value head reads. Same constant as `selfcheck.EXPECTED_LAST_TOKEN`,
+#: restated here rather than imported: importing it would make this module depend
+#: on the self-check, when the relationship is the other way round -- the gate
+#: below has to hold on every request, including deployments that never run a
+#: startup check.
+POOLED_TOKEN_ID = 271
+
+
+def _decode_data_url(data_url: str) -> bytes:
+ """The bytes behind a `data:` URL, or of bare base64.
+
+ `scorer.py` hands every adapter data URLs because the HTTP engines want them
+ on the wire. This one has to undo that, which costs a base64 round trip and
+ buys the one thing that matters: the padding decision in `images.py` --
+ whether this crop is too long and thin for the preprocessor -- is made in
+ exactly one place for all five backends.
+ """
+ marker = ";base64,"
+ at = data_url.find(marker)
+ payload = data_url[at + len(marker):] if at != -1 else data_url
+ try:
+ return base64.b64decode(payload, validate=True)
+ except (binascii.Error, ValueError) as exc:
+ raise BackendError(f"image payload is not valid base64: {exc}") from exc
+
+
+class TransformersBackend:
+ """Runs the forward pass in this process, on weights it loaded itself."""
+
+ #: We assemble the prompt and nothing downstream can touch it, exactly as on
+ #: the SGLang path. `selfcheck.py` therefore checks our outgoing request
+ #: against `build_prompt()` rather than interrogating an engine.
+ prompt_source = "client"
+
+ #: The value head's two raw logits. `scorer.py` applies the softmax.
+ output_kind = "logits"
+
+ def __init__(
+ self,
+ model_path: str,
+ *,
+ device: str = "auto",
+ dtype: str = "auto",
+ attn_implementation: str = "sdpa",
+ max_in_flight: int = 1,
+ max_batch_size: int = 1,
+ model: str | None = None,
+ timeout: float | None = None,
+ ) -> None:
+ import asyncio
+
+ # Imported here, not at module scope, so that `load_backend` for any of
+ # the four HTTP engines never pays for -- or requires -- the model stack.
+ try:
+ import torch
+ from transformers import AutoProcessor, Qwen3_5ForSequenceClassification
+ except ImportError as exc:
+ raise BackendError(
+ f"the transformers backend needs the model stack in *this* "
+ f"interpreter, and {exc.name!r} is not importable from it.\n"
+ " Install sdk/requirements-transformers.txt and start the service\n"
+ " with that interpreter, e.g.\n"
+ " PATH=/opt/venv-transformers/bin:$PATH bash sdk/start_score.sh 18501\n"
+ " Unlike the four HTTP engines, this backend has no separate "
+ "process to hold the weights."
+ ) from exc
+
+ self.model_path = str(model_path)
+ self._name = model or self.model_path
+ # `timeout` is accepted and ignored: there is no request to time out. It
+ # is in the signature so that one backend config schema covers every
+ # engine, rather than a local-only config that rejects a key the others
+ # require.
+ self._timeout = timeout
+
+ self.device, self.dtype, self.attn_implementation = _resolve_runtime(
+ device, dtype, attn_implementation
+ )
+
+ self.notes: list[str] = []
+ if max_in_flight > 1:
+ self.notes.append(
+ f"max_in_flight={max_in_flight} was lowered to 1: this backend runs "
+ "the forward pass in this process, where concurrent passes compete "
+ "for one GPU's memory instead of queueing."
+ )
+ self._gate = asyncio.Semaphore(1)
+
+ self.max_batch_size = max(1, int(max_batch_size))
+
+ self.processor = AutoProcessor.from_pretrained(self.model_path)
+
+ # Right padding, set rather than assumed -- it is the HF default, but a
+ # checkpoint's tokenizer_config.json is free to override it. Right is the
+ # side on which "pool the last real token" holds without depending on how
+ # any layer treats pad positions; measured, this checkpoint is indifferent
+ # (see `concurrency` in the module docstring), so this is the conservative
+ # choice rather than a required one. Asserted after setting, so a future
+ # tokenizer that ignores the attribute fails loudly instead of padding the
+ # other way in silence.
+ self._pad_token_id = self.processor.tokenizer.pad_token_id
+ if self.max_batch_size > 1 and self._pad_token_id is None:
+ raise BackendError(
+ "max_batch_size > 1 needs a pad token to batch with, and this "
+ "tokenizer defines none. The pooled-position rule that picks the "
+ "value head's token is 'rightmost id != pad_token_id'; without a "
+ "pad id there is nothing for it to exclude."
+ )
+ self.processor.tokenizer.padding_side = "right"
+ if self.processor.tokenizer.padding_side != "right":
+ raise BackendError(
+ "the tokenizer would not accept padding_side='right'. This backend "
+ "batches by right-padding only, so that the token the value head "
+ "pools is the last real one on every row."
+ )
+
+ # The class is named, not resolved from the checkpoint's `architectures`.
+ # That field says `Qwen3_5ForConditionalGeneration`, and the weights do
+ # not contain an `lm_head` -- they contain `score.weight`, shape [2, 2048].
+ # Loading the generative class therefore initialises a head at random,
+ # drops the one that was trained, and warns about both rather than
+ # failing. The result scores every candidate in range and means nothing.
+ self.model, loading_info = Qwen3_5ForSequenceClassification.from_pretrained(
+ self.model_path,
+ dtype=self.dtype,
+ attn_implementation=self.attn_implementation,
+ output_loading_info=True,
+ )
+ # Deliberately `.to(device)` rather than `device_map=`: the latter pulls
+ # in `accelerate` for a placement this adapter does not need, since it
+ # never shards across devices.
+ self.model = self.model.to(self.device)
+ self.model.eval()
+
+ missing = set(loading_info.get("missing_keys") or ())
+ unexpected = set(loading_info.get("unexpected_keys") or ())
+ if missing or unexpected:
+ raise BackendError(
+ "the checkpoint did not load cleanly into the sequence-classification "
+ f"class.\n missing: {sorted(missing)}\n unexpected: {sorted(unexpected)}\n"
+ " A missing 'score.weight' means the value head was initialised at "
+ "random and every score is noise; an unexpected one means it was "
+ "loaded into a class that has no use for it."
+ )
+ if self.model.config.num_labels != 2:
+ raise BackendError(
+ f"expected a 2-class head, got num_labels={self.model.config.num_labels}"
+ )
+
+ # Two pad ids, and batching is only correct when they agree. The tokenizer's
+ # is what gets *written* into the padded rows; the config's is what
+ # `GenericForSequenceClassification` excludes when it picks the token to
+ # pool. If they differ, the head pools a pad and every padded row scores
+ # noise -- silently, since a pad position still produces two finite logits.
+ # Harmless at batch size 1, which is why it is only fatal above it.
+ config_pad = self.model.config.get_text_config().pad_token_id
+ if self.max_batch_size > 1 and config_pad != self._pad_token_id:
+ raise BackendError(
+ f"the tokenizer pads with id {self._pad_token_id} but the model "
+ f"config calls {config_pad} the pad token. Batching pads rows with "
+ "the former and the value head skips the latter when choosing what "
+ "to read, so padded rows would be pooled at a pad position."
+ )
+
+ self._torch = torch
+
+ # ── identity ─────────────────────────────────────────────────────────────
+
+ async def served_name(self) -> str | None:
+ """The checkpoint directory, which is what identifies this model.
+
+ A path rather than a name, like the SGLang adapter's `/get_model_info`:
+ there is no server to have been started with a name, and the directory is
+ the only thing that says which weights answered.
+ """
+ return self._name
+
+ # ── request shape ────────────────────────────────────────────────────────
+
+ def _scoring_request(
+ self, parts: PromptParts, original_data_url: str, render_data_url: str
+ ) -> dict[str, Any]:
+ """What this adapter would put on the wire, if it had one.
+
+ It has no wire, but `selfcheck.py` checks `client`-source adapters by
+ reading this -- `text` against `build_prompt()`, `image_data` for two
+ images in order -- and that check is just as meaningful here: the prompt
+ and the image order are still ours to get wrong, and both fail silently.
+ So the shape is kept identical to SGLang's rather than invented.
+ """
+ return {
+ "text": parts.raw,
+ "image_data": [original_data_url, render_data_url],
+ }
+
+ def describe_scoring_request(self, parts: PromptParts) -> dict[str, Any]:
+ """`_scoring_request` with the image payloads elided, for the self-check."""
+ return self._scoring_request(parts, "<original>", "<render>")
+
+ # ── the two calls ────────────────────────────────────────────────────────
+
+ def _pooled_positions(self, input_ids: Any) -> Any:
+ """Which token the value head will read, per row.
+
+ This is `GenericForSequenceClassification.forward`'s rule restated, not a
+ rule of our own: the rightmost id that is not `pad_token_id`. It has to be
+ the same rule, because the point of the assert below is to check the
+ position the model is *actually* about to pool -- a second, independent
+ notion of "last token" would check something else and pass while the head
+ read a pad.
+ """
+ torch = self._torch
+ non_pad = (input_ids != self._pad_token_id).to(torch.int32)
+ indices = torch.arange(input_ids.shape[-1], dtype=torch.int32)
+ return (indices * non_pad).argmax(-1)
+
+ def _forward_sync(
+ self, batch: list[tuple[PromptParts, str, str]]
+ ) -> list[list[float]]:
+ """One forward pass over `batch`. Synchronous, GPU-bound, not re-entrant.
+
+ A batch of one is not a special case with its own code path, but it does
+ skip `padding`: with nothing to pad to, asking for it would be a no-op
+ that still changes which kwargs the processor sees. The default config
+ therefore runs byte-for-byte what it ran before batching existed.
+ """
+ from PIL import Image
+
+ torch = self._torch
+ texts: list[str] = []
+ images = []
+ # Flat, in candidate order: this processor consumes the image list in the
+ # order the placeholders appear across the whole batch, two per prompt.
+ # Nesting per row is the shape another VL processor wants and is silently
+ # wrong here -- it would pair row 0's prompt with both of row 0's images
+ # only by accident of the flattening.
+ for parts, original_data_url, render_data_url in batch:
+ texts.append(parts.raw)
+ for data_url in (original_data_url, render_data_url):
+ with Image.open(io.BytesIO(_decode_data_url(data_url))) as img:
+ images.append(img.convert("RGB"))
+
+ extra: dict[str, Any] = {}
+ if len(batch) > 1:
+ extra = {"padding": True, "padding_side": "right"}
+ inputs = self.processor(
+ text=texts, images=images, return_tensors="pt", **extra
+ )
+
+ input_ids = inputs["input_ids"]
+ pooled_at = self._pooled_positions(input_ids)
+ for row in range(input_ids.shape[0]):
+ pooled = int(input_ids[row][int(pooled_at[row])])
+ if pooled != POOLED_TOKEN_ID:
+ hint = " (198 is the assistant turn cut short)" if pooled == 198 else ""
+ where = f" (row {row} of {input_ids.shape[0]})" if len(batch) > 1 else ""
+ raise BackendError(
+ f"the token this forward pass would pool is {pooled}, expected "
+ f"{POOLED_TOKEN_ID}{hint}{where}. The value head would read a "
+ "position it never read during training, and the score would be "
+ "off scale."
+ )
+
+ inputs = {
+ key: (value.to(self.model.device) if hasattr(value, "to") else value)
+ for key, value in inputs.items()
+ }
+ with torch.inference_mode():
+ logits = self.model(**inputs).logits
+ # float() before leaving the GPU dtype: bfloat16 has ~3 decimal digits,
+ # and the softmax upstream is where the published score comes from.
+ logits = logits.float()
+ if logits.shape[0] != len(batch):
+ raise BackendError(
+ f"asked the value head for {len(batch)} rows, got {logits.shape[0]}."
+ )
+ if logits.shape[-1] != 2:
+ raise BackendError(
+ f"expected 2 class logits from the value head, got {logits.shape[-1]}."
+ )
+ return [[float(row[0]), float(row[1])] for row in logits]
+
+ async def forward(
+ self,
+ parts: PromptParts,
+ original_data_url: str,
+ render_data_url: str,
+ ) -> list[float]:
+ return (await self.forward_batch([(parts, original_data_url, render_data_url)]))[0]
+
+ async def forward_batch(
+ self, batch: list[tuple[PromptParts, str, str]]
+ ) -> list[list[float]]:
+ """Score several candidates in one pass, in input order.
+
+ The gate is still one: `max_batch_size` widens the pass, it does not add
+ a second concurrent one. Callers are expected to have split to
+ `max_batch_size` already -- this does not re-split, because a caller that
+ hands over more than it configured should hear about it rather than have
+ the limit quietly applied twice in different places.
+ """
+ import asyncio
+
+ if not batch:
+ return []
+ if len(batch) > self.max_batch_size:
+ raise BackendError(
+ f"asked for a batch of {len(batch)} with max_batch_size="
+ f"{self.max_batch_size}. Split before calling."
+ )
+
+ async with self._gate:
+ try:
+ return await asyncio.to_thread(self._forward_sync, batch)
+ except BackendError:
+ raise
+ except Exception as exc: # torch raises its own hierarchy
+ raise BackendError(f"forward pass failed: {type(exc).__name__}: {exc}") from exc
+
+ async def tokenize(self, parts: PromptParts) -> list[int] | None:
+ """The prompt's token ids, from the tokenizer in this process.
+
+ Answered rather than declined. The SGLang adapter returns None here on
+ the grounds that asking an engine to tokenize a string we just handed it
+ proves nothing -- true for an engine, but this is the same tokenizer the
+ forward pass will use, loaded from the same directory, so its answer is
+ the one that counts.
+ """
+ ids = self.processor.tokenizer(parts.raw, add_special_tokens=False)["input_ids"]
+ return list(ids)
+
+ async def aclose(self) -> None:
+ """Drop the model and give the memory back.
+
+ The HTTP adapters close sockets here. This one is holding several GiB of
+ device memory, and a caller that builds a second Scorer in the same
+ process -- a test, a notebook -- would otherwise be holding two copies.
+ """
+ model = getattr(self, "model", None)
+ self.model = None
+ del model
+ try:
+ if self._torch.cuda.is_available():
+ self._torch.cuda.empty_cache()
+ except Exception: # noqa: BLE001 -- releasing memory must not raise
+ pass
+
+
+def _resolve_runtime(device: str, dtype: str, attn_implementation: str) -> tuple[str, Any, str]:
+ """Turn the three `auto`s in the config into what torch wants.
+
+ `attn_implementation` defaults to sdpa and `auto` resolves to it, rather than
+ to flash_attention_2 where that is installed. Measured against the reference
+ scores on 12 samples: sdpa lands within 4.4e-3, flash_attention_2 within
+ 7.6e-3. Both rank identically and both look fine; only the first stays inside
+ the 5e-3 band this checkpoint's published numbers were measured in.
+ """
+ import torch
+
+ if device == "auto":
+ # Apple's Metal backend is checked, not skipped. This checkpoint runs on
+ # it: 18 of the 24 layers are linear attention, which is where an
+ # unimplemented operator would have surfaced, and none did -- no
+ # PYTORCH_ENABLE_MPS_FALLBACK required. Falling through to "cpu" on a
+ # machine that has mps would cost a factor of ~100 for nothing.
+ if torch.cuda.is_available():
+ device = "cuda:0"
+ elif getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available():
+ device = "mps"
+ else:
+ device = "cpu"
+ if dtype == "auto":
+ # bfloat16 on every accelerator, float32 only on CPU.
+ #
+ # The CPU exception is the usual one: bfloat16 is emulated there, and a
+ # CPU deployment is not the one being compared against published scores
+ # anyway. What is *not* an exception, and was wrong here until mps was
+ # measured, is treating mps like the CPU. On an M-series GPU, one forward
+ # pass of this model takes 0.3 s in bfloat16 and 38 s in float32 -- a
+ # factor of ~100 -- and float32 also lands slightly further from the
+ # reference scores (4.9e-3 against 4.1e-3), not closer. So the wider dtype
+ # buys nothing on this device and costs two orders of magnitude.
+ torch_dtype = torch.float32 if device.startswith("cpu") else torch.bfloat16
+ else:
+ torch_dtype = getattr(torch, dtype)
+ if attn_implementation == "auto":
+ attn_implementation = "sdpa"
+ return device, torch_dtype, attn_implementation
diff --git a/scripts/minicpm-ocr-jev/sdk/jev_score/scorer.py b/scripts/minicpm-ocr-jev/sdk/jev_score/scorer.py
index 74ed218..93287b1 100644
--- a/scripts/minicpm-ocr-jev/sdk/jev_score/scorer.py
+++ b/scripts/minicpm-ocr-jev/sdk/jev_score/scorer.py
@@ -135,18 +135,93 @@ class Scorer:
return prob_1_from_probabilities(scores)
return softmax_prob_1(scores)
+ def _batch_size(self) -> int:
+ """How many candidates this backend wants in one forward pass.
+
+ Asked of the adapter rather than configured here, and absent on the four
+ HTTP adapters: their batching happens inside the engine, where requests
+ from every client meet. Reading it with a default of 1 is what keeps this
+ method unchanged for them.
+ """
+ if not hasattr(self.backend, "forward_batch"):
+ return 1
+ return max(1, int(getattr(self.backend, "max_batch_size", 1) or 1))
+
async def score_many(self, items: Sequence[ScoreInput]) -> list[float]:
- """`score` over a batch, concurrently, results in input order.
+ """`score` over a batch, results in input order.
+
+ Two paths. For an engine-backed adapter, and for any adapter at batch
+ size 1, the candidates go out concurrently and the engine's own queue
+ sets throughput -- a second limit above it would only make the real one
+ harder to find. For an in-process adapter configured to batch, they are
+ split into passes of `max_batch_size` instead: there is no engine queue
+ to feed, so the width of the pass is the only throughput there is.
+ """
+ import asyncio
- Concurrency is bounded by the backend adapter, not here: the engine's own
- queue is what actually sets throughput, and a second limit above it would
- only make the real one harder to find.
+ if not items:
+ return []
+ size = self._batch_size()
+ if size <= 1:
+ return list(await asyncio.gather(*(self.score(i) for i in items)))
+
+ out: list[float] = []
+ for start in range(0, len(items), size):
+ chunk = items[start : start + size]
+ raw = await self.backend.forward_batch(
+ [
+ (build_parts(i.ocr_text), to_data_url(i.original), to_data_url(i.render))
+ for i in chunk
+ ]
+ )
+ if len(raw) != len(chunk):
+ raise BackendError(
+ f"asked for {len(chunk)} scores in one pass and got {len(raw)}."
+ )
+ # The same two families as `score`, applied per row. Chunks run one
+ # after another rather than concurrently on purpose: the adapter
+ # admits one pass at a time, so gathering them here would queue on
+ # its semaphore and only make the ordering harder to read.
+ probabilities = getattr(self.backend, "output_kind", "logits") == "probabilities"
+ out.extend(
+ prob_1_from_probabilities(row) if probabilities else softmax_prob_1(row)
+ for row in raw
+ )
+ return out
+
+ async def score_many_settled(
+ self, items: Sequence[ScoreInput]
+ ) -> list[float | BaseException]:
+ """`score_many`, but a failure is a value in the list rather than a raise.
+
+ This is the shape a server wants: one bad candidate out of twenty should
+ cost its own cell, not the other nineteen.
+
+ What a failure costs differs by path, and the difference is honest rather
+ than papered over. One candidate at a time, only that candidate fails.
+ In a batched pass, the pass is what succeeded or failed -- so every
+ candidate in it carries the error. Re-running the chunk one by one to
+ narrow it down would turn a configuration chosen for throughput into its
+ worst case exactly when things are already going wrong.
"""
import asyncio
if not items:
return []
- return list(await asyncio.gather(*(self.score(i) for i in items)))
+ size = self._batch_size()
+ if size <= 1:
+ return list(
+ await asyncio.gather(*(self.score(i) for i in items), return_exceptions=True)
+ )
+
+ out: list[float | BaseException] = []
+ for start in range(0, len(items), size):
+ chunk = items[start : start + size]
+ try:
+ out.extend(await self.score_many(chunk))
+ except (BackendError, ValueError, OSError) as exc:
+ out.extend([exc] * len(chunk))
+ return out
async def aclose(self) -> None:
await self.backend.aclose()
diff --git a/scripts/minicpm-ocr-jev/sdk/jev_score/server.py b/scripts/minicpm-ocr-jev/sdk/jev_score/server.py
index 6845c58..c4caabc 100644
--- a/scripts/minicpm-ocr-jev/sdk/jev_score/server.py
+++ b/scripts/minicpm-ocr-jev/sdk/jev_score/server.py
@@ -144,13 +144,12 @@ def create_app() -> FastAPI:
)
for i, it in enumerate(req.items)
]
- # One bad item must not take the batch down with it: a caller that sent
- # twenty candidates and one unreadable PNG wants the nineteen scores.
- import asyncio
-
- settled = await asyncio.gather(
- *(scorer.score(i) for i in inputs), return_exceptions=True
- )
+ # One bad item must not take the whole request down with it: a caller
+ # that sent twenty candidates and one unreadable PNG wants the nineteen
+ # scores. Which unit "one" means depends on whether the backend is
+ # scoring candidates singly or several to a forward pass -- see
+ # `Scorer.score_many_settled`.
+ settled = await scorer.score_many_settled(inputs)
results = []
for outcome in settled:
if isinstance(outcome, BaseException):
diff --git a/scripts/minicpm-ocr-jev/sdk/requirements-transformers.txt b/scripts/minicpm-ocr-jev/sdk/requirements-transformers.txt
new file mode 100644
index 0000000..09904f5
--- /dev/null
+++ b/scripts/minicpm-ocr-jev/sdk/requirements-transformers.txt
@@ -0,0 +1,89 @@
+# The transformers backend: the forward pass runs in the service process.
+#
+# This file exists because that one sentence breaks an assumption the other
+# requirements files are built on. There, the engine lives in its own virtual
+# environment and the warning in requirements.txt holds: vLLM asks only for
+# "pillow>=12.3.0" while the renderer pins it exactly, so a shared environment
+# lets `pip install -U vllm` move Pillow forward and change every score, silently.
+# The answer there is separation -- two environments, two resolvers, no contact.
+#
+# That answer is unavailable here. There is no second process to separate into:
+# this backend loads the weights into the process that is also rendering. So the
+# pin has to be defended inside one environment instead, which is what the
+# `Pillow==12.3.0` below is doing. It is listed before the model stack on purpose:
+# whatever torch and transformers would accept, this is the version the model was
+# calibrated against, and it is not negotiable by a later `pip install -U`.
+#
+# Install into a virtual environment of its own and run the service with that
+# interpreter:
+#
+# python3 -m venv /opt/venv-transformers
+# /opt/venv-transformers/bin/pip install -r sdk/requirements-transformers.txt
+# PATH=/opt/venv-transformers/bin:$PATH \
+# JEV_BACKEND_CONFIG=sdk/backends/transformers.yaml bash sdk/start_score.sh 18501
+
+# ── pinned: these decide what the model sees ─────────────────────────────────
+# Exactly the renderer's pin, for exactly the renderer's reason -- see above, and
+# the same line in requirements.txt. Pillow runs on the scoring path for images
+# past 199:1, which are padded and re-encoded.
+Pillow==12.3.0
+
+# ── the model stack ──────────────────────────────────────────────────────────
+# transformers must be new enough to register Qwen3_5ForSequenceClassification.
+# The checkpoint's config.json reports transformers_version 5.10.4; verified
+# with 5.19.0 (Linux/CUDA) and 5.22.2 (macOS/mps). 4.57.6 does *not* have the
+# class -- it imports fine and then cannot build the model.
+transformers>=5.19
+torch>=2.13
+
+# Required, and not for anything this service does with video. AutoProcessor
+# builds a Qwen3VLVideoProcessor because processor_config.json carries a
+# video_processor section, and that class imports torchvision at construction
+# time. Without it the service fails at startup with an ImportError naming
+# Torchvision, which reads like a missing feature rather than a missing
+# dependency of a feature nobody asked for.
+torchvision
+
+# ── the HTTP shell ───────────────────────────────────────────────────────────
+# Same lower bounds as requirements-score.txt. Nothing here touches a prompt.
+fastapi>=0.110
+uvicorn>=0.27
+httpx>=0.27
+pydantic>=2.6
+PyYAML>=6.0
+
+# ── deliberately absent ──────────────────────────────────────────────────────
+#
+# accelerate Only `device_map=` needs it, and this backend places the model
+# with `.to(device)` instead. It never shards across devices, so
+# the dependency would buy nothing.
+#
+# causal_conv1d Both are optional kernels for this architecture. Without them
+# flash-linear- transformers prints that it is "falling back to its reference
+# attention PyTorch implementation ... correct but much slower", on every
+# start, for each one. Correct is the operative word: the
+# reference scores below are what this environment produces
+# without either of them. Install them for speed, not for
+# agreement.
+#
+# flash-attn The adapter pins attn_implementation to sdpa. Measured against
+# the reference scores on 12 samples, sdpa lands within 4.4e-3 and
+# flash_attention_2 within 7.6e-3 -- the second one is outside the
+# 5e-3 band the published numbers were measured in. Installing it
+# does not change the default, but do not then switch to it.
+#
+# vllm It is a different backend, with its own config and its own
+# environment (serve/setup_backend.sh). Installing both here is
+# how Pillow moves.
+#
+# ── if this service should also render ───────────────────────────────────────
+# sdk/start_render_score.sh renders in-process, so that deployment needs the
+# renderer's dependencies in this same environment as well:
+#
+# playwright==1.62.0
+# Markdown==3.10.3
+#
+# They are not listed above because the score-only deployment must not install
+# them -- it needs no browser, no Node and no fonts. Add them (and
+# `playwright install chromium`) only for the render+score entry point; the pins
+# are the renderer's and are not independent of the scores either.
diff --git a/scripts/minicpm-ocr-jev/sdk/start_render_score.sh b/scripts/minicpm-ocr-jev/sdk/start_render_score.sh
index 02add67..0459938 100644
--- a/scripts/minicpm-ocr-jev/sdk/start_render_score.sh
+++ b/scripts/minicpm-ocr-jev/sdk/start_render_score.sh
@@ -2,7 +2,7 @@
# Start the render+score service -- built-in renderer. Renders candidates, then
# scores them.
#
-# usage: ./start_render_score.sh <port> <engine base url>
+# usage: ./start_render_score.sh <port> [engine base url]
#
# Run it with the renderer's interpreter -- the environment sdk/setup_render.sh
# built -- because this process renders in-process through serve/render_pool.py.
@@ -11,16 +11,34 @@
#
# PATH=/opt/venv-render/bin:$PATH bash sdk/start_render_score.sh 18500 http://127.0.0.1:18499
#
-# Neither argument has a default: pointing this at the wrong engine produces
-# scores rather than an error.
+# The engine URL is omitted -- not defaulted -- for the one backend that has no
+# URL to give:
+#
+# ./start_render_score.sh 18500 http://127.0.0.1:18499 vllm, sglang, llamacpp, ollama
+# ./start_render_score.sh 18500 transformers (runs in process)
+#
+# A *default* URL would point this service at some other engine and produce
+# scores rather than an error; omitting the argument introduces no default, and a
+# config for an HTTP engine that names no base_url fails at startup saying so.
+#
+# ⚠ With the transformers backend the two environments described above become
+# one: this process renders *and* holds the weights, so it needs the renderer's
+# pinned Pillow and torch in the same interpreter. That is what
+# sdk/requirements-transformers.txt is for, and why it pins Pillow itself rather
+# than leaving it to the model stack to resolve.
+#
+# PATH=/opt/venv-transformers/bin:$PATH \
+# JEV_BACKEND_CONFIG=sdk/backends/transformers.yaml bash sdk/start_render_score.sh 18500
set -euo pipefail
PORT="${1:?port required}"
-BACKEND="${2:?engine base url required, e.g. http://127.0.0.1:18499}"
+BACKEND="${2-}"
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-export JEV_BACKEND_URL="$BACKEND"
+if [ -n "$BACKEND" ]; then
+ export JEV_BACKEND_URL="$BACKEND"
+fi
export JEV_WEIGHTS="${JEV_WEIGHTS:-}"
# This service imports rm_render.py and serve/render_pool.py, and Python writes a
@@ -41,7 +59,7 @@ python3 -c 'import playwright' 2>/dev/null || {
echo " PATH=/opt/venv-render/bin:\$PATH bash sdk/start_render_score.sh $PORT $BACKEND" >&2
exit 1; }
-echo "render+score service on $HOST:$PORT -> engine $BACKEND (render mode ${RM_RENDER_MODE:-persistent})"
+echo "render+score service on $HOST:$PORT -> engine ${BACKEND:-from ${JEV_BACKEND_CONFIG:-sdk/backends/vllm.yaml} (no URL given)} (render mode ${RM_RENDER_MODE:-persistent})"
cd "$HERE"
exec python3 -m uvicorn app:app --host "$HOST" --port "$PORT" --no-access-log
diff --git a/scripts/minicpm-ocr-jev/sdk/start_score.sh b/scripts/minicpm-ocr-jev/sdk/start_score.sh
index ea49564..ace1122 100644
--- a/scripts/minicpm-ocr-jev/sdk/start_score.sh
+++ b/scripts/minicpm-ocr-jev/sdk/start_score.sh
@@ -2,24 +2,47 @@
# Start the score service -- bring your own render image. Scores candidates that
# have already been rendered.
#
-# usage: ./start_score.sh <port> <engine base url>
+# usage: ./start_score.sh <port> [engine base url]
#
-# Neither argument has a default. Pointing this at the wrong engine produces
-# scores rather than an error, so a missing argument stops the script.
+# The port has no default. Neither does the engine URL -- for the one backend
+# that has no URL to give, it is *omitted* rather than defaulted:
+#
+# ./start_score.sh 18501 http://127.0.0.1:18499 vllm, sglang, llamacpp, ollama
+# ./start_score.sh 18501 transformers (runs in process)
+#
+# That distinction is the whole of what the original check protected. The danger
+# was never a missing argument as such: a *default* URL would silently point a
+# service at some other engine and produce scores rather than an error. Omitting
+# the argument introduces no default -- it leaves JEV_BACKEND_URL unset, the
+# backend config decides, and a config for an HTTP engine that names no base_url
+# fails at startup saying exactly that. Neither path can end in a service scoring
+# against an engine nobody chose.
+#
+# ⚠ With the transformers backend this process loads the weights itself, so run
+# it with an interpreter that has torch and transformers
+# (sdk/requirements-transformers.txt):
+#
+# PATH=/opt/venv-transformers/bin:$PATH \
+# JEV_BACKEND_CONFIG=sdk/backends/transformers.yaml bash sdk/start_score.sh 18501
#
# This is the entry point for a deployment that renders elsewhere. It needs no
-# browser, no Node and no fonts -- only sdk/requirements-score.txt. If you want
-# the service to render for you, start sdk/app.py instead
-# (sdk/start_render_score.sh); it imports this layer directly and does not talk
-# to this port.
+# browser, no Node and no fonts -- only sdk/requirements-score.txt, plus the model
+# stack when the backend is the local one. If you want the service to render for
+# you, start sdk/app.py instead (sdk/start_render_score.sh); it imports this layer
+# directly and does not talk to this port.
set -euo pipefail
PORT="${1:?port required}"
-BACKEND="${2:?engine base url required, e.g. http://127.0.0.1:18499}"
+BACKEND="${2-}"
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-export JEV_BACKEND_URL="$BACKEND"
+# Exported only when given. Exporting it empty would read the same to this script
+# and differently to the config loader, which treats a blank base_url as one that
+# was asked for and left blank.
+if [ -n "$BACKEND" ]; then
+ export JEV_BACKEND_URL="$BACKEND"
+fi
# Optional. With the weights reachable here, the startup gate also compares the
# engine's prompt against the local tokenizer token for token; without them it
# can only check the pooled position. Both are described in jev_score/selfcheck.py.
@@ -28,7 +51,7 @@ export JEV_WEIGHTS="${JEV_WEIGHTS:-}"
WORKERS="${JEV_WORKERS:-1}"
HOST="${HOST:-0.0.0.0}"
-echo "score service on $HOST:$PORT -> engine $BACKEND"
+echo "score service on $HOST:$PORT -> engine ${BACKEND:-from ${JEV_BACKEND_CONFIG:-sdk/backends/vllm.yaml} (no URL given)}"
cd "$HERE"
exec python3 -m uvicorn jev_score.server:app \