Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(examples): align document-ocr models with their image bundles (#654)
Yeonwoo Sung1fce5b5ad5f0
diff --git a/examples/document-ocr/README.md b/examples/document-ocr/README.mdindex 914ff4016..bc0aa1598 100644--- a/examples/document-ocr/README.md+++ b/examples/document-ocr/README.md@@ -2,11 +2,13 @@**Swap an OCR model with one identifier change. See what changes in the output.**-Three different model architectures, one inference server, one SDK call. This-demo is a working browser UI that runs document images through a recognition-model, a fine-tuned document model, and a zero-shot NER, all behind the same+Three different model architectures, one SDK call. This demo is a working+browser UI that runs document images through a recognition model, a+fine-tuned document model, and a zero-shot NER, all behind the same`client.extract(...)` API. Pick a model from any of the three dropdowns; watch-the pipeline run again with that one identifier swapped.+the pipeline run again with that one identifier swapped. The CPU compose+serves all three stages from the default image. The GPU compose is a separate+recognition path for LightOnOCR and GLM-OCR.<!-- Drop screenshots or a GIF here. Suggested:docs/cover.png (the browser UI mid-run)@@ -15,8 +17,8 @@ the pipeline run again with that one identifier swapped.> Built on [SIE](https://github.com/superlinked/sie), the open-source inference-> engine from Superlinked. Apache 2.0. Run it locally with `docker compose up`;-> a hosted Hugging Face Space is coming soon.+> engine from Superlinked. Apache 2.0. Run it locally with `docker compose up`,+> or open the hosted Space linked below.---@@ -24,8 +26,10 @@ the pipeline run again with that one identifier swapped.OCR is almost never a single-model problem. A real pipeline has three concerns:-1. **Recognition** (image to text). Modern VLM-OCRs like Florence-2 and- LightOnOCR take a whole document and emit Markdown.+1. **Recognition** (image to text). VLM-OCRs such as PaddleOCR-VL, LightOnOCR,+ and GLM-OCR take a whole document and emit Markdown. The CPU default image+ preloads PaddleOCR-VL-1.5's `transformers` profile. LightOnOCR and GLM-OCR+ stay on the GPU sglang-vision image.2. **Structured extraction** (image to JSON). End-to-end document models likeDonut on CORD skip the text intermediate entirely and emit nested JSONdirectly: `{ "total": { "total_price": "28.52" }, ... }`.@@ -34,14 +38,17 @@ OCR is almost never a single-model problem. A real pipeline has three concerns:"date"]`) instead of fine-tuning a new model.The SIE pitch this demo makes visceral: **all three are the same SDK call,-the same auth, the same rate-limit budget, the same Docker image.** Only the-model ID changes.+the same auth, the same rate-limit budget.** Only the model ID changes.+The CPU image (`latest-cpu-default`) serves PaddleOCR-VL, Donut, and GLiNER+together. LightOnOCR and GLM-OCR need the GPU `sglang-vision-extract` image,+which does not serve Donut or GLiNER.```python-# Recognition: VLM-OCR, returns Markdown+# Recognition on the CPU default image: transformers profile, returns Markdownclient.extract(- "lightonai/LightOnOCR-2-1B",+ "PaddlePaddle/PaddleOCR-VL-1.5:transformers",Item(images=[image_bytes]),+ options={"task": "ocr"},)# Structured: end-to-end Donut, returns JSON tree@@ -58,6 +65,10 @@ client.extract()```+Those three calls run on the CPU compose (`latest-cpu-default`). LightOnOCR+(`lightonai/LightOnOCR-2-1B`) and GLM-OCR need the GPU compose+(`latest-cuda12-sglang-vision-extract`).+Each cell in the demo's UI has a **"See the SIE call"** disclosure that showsthe exact line of code that just ran. Swap a dropdown, the snippet updates withthe one parameter that changed.@@ -79,26 +90,23 @@ npm installnpm start```-`npm start` runs `docker compose up -d` (boots `ghcr.io/superlinked/sie-server:latest-cpu-transformers5`,-preloads three small models), then starts a Node UI server and opens-http://localhost:3032.+`npm start` runs `docker compose up -d` (boots `ghcr.io/superlinked/sie-server:latest-cpu-default`,+preloads `PaddlePaddle/PaddleOCR-VL-1.5:transformers`, Donut on CORD, Donut on DocVQA, and+`urchade/gliner_multi-v2.1`), then starts a Node UI server and opens http://localhost:3032.+It does not preload LightOnOCR or GLM-OCR.-- **First start**: ~5-8 minutes on a typical home connection (~5 GB of- LightOnOCR + Donut + GLiNER weights download from Hugging Face into a- Docker volume; LightOnOCR is the big one at ~4 GB).-- **Subsequent restarts**: 30-60 seconds. Weights are cached in- `/app/.cache/huggingface` inside the `sie-cache` Docker volume.-- **Per-sample click**: ~20-30 s on Linux x86_64 native, ~60-90 s on Apple- Silicon (Rosetta tax on the amd64-only SIE image).+- **First start**: the image downloads the PaddleOCR-VL, Donut, and GLiNER weights from Hugging Face into a Docker volume.+- **Subsequent restarts**: weights are cached in `/app/.cache/huggingface` inside the `sie-cache` Docker volume.+- **Apple Silicon**: the image is `linux/amd64` and runs through Rosetta, so calls are slower than on native x86_64.```bashdocker compose down # when done```-**GPU variant** (Linux + NVIDIA, makes GLM-OCR / Paddle / LightOnOCR fast):+**GPU variant** (Linux + NVIDIA). Preloads only LightOnOCR-2-1B. GLM-OCR stays selectable and loads on demand; it is not preloaded with LightOnOCR because the two do not fit on one GPU. This image does not serve Donut, GLiNER, or the PaddleOCR-VL transformers profile.```bash-npm run start:gpu # uses compose.gpu.yml + latest-cuda12-default+npm run start:gpu # uses compose.gpu.yml + latest-cuda12-sglang-vision-extract```---@@ -109,22 +117,24 @@ The UI itself surfaces these as a "Try these moments" strip above the panels,so a visitor sees the prompts even without reading the README. The same fourmoments, with a little more context:-1. **Click any sample → open the "See the SIE call" disclosure under- "Recognition".** You'll see the actual `client.extract(...)` call with- the LightOnOCR-2-1B model ID. The disclosure updates when any dropdown- changes; only the model string changes between calls.+1. **On the CPU compose, click any sample.** Recognition, structured+ extraction, and NER all run. Open the Recognition disclosure: the call+ uses `PaddlePaddle/PaddleOCR-VL-1.5:transformers`. The Structured+ disclosure uses the Donut CORD model id.2. **Switch the Structured dropdown** from `donut-cord-v2` to- `donut-rvlcdip`. Same Donut architecture, different fine-tuning. The- output shape changes from a CORD-shaped JSON tree to a document-type- classification. Same model class, same SDK call, completely different- output category.-3. **Switch the NER dropdown** from `gliner_multi-v2.1` to `NuNER_Zero`.- Different model family entirely (NuMind vs urchade), same SDK call, same- labels. The architecture-swap-with-one-string-change pitch.-4. **Compare two samples back to back**: click `receipt.png` (Donut on CORD- dominates because that's exactly its fine-tuning distribution), then- click `letter.png` (the opposite: Donut produces garbage shaped like- CORD; recognition + GLiNER carry the pipeline).+ `donut-docvqa`. Same Donut architecture, different fine-tuning. The+ output shape changes from a CORD-shaped JSON tree to a DocVQA answer.+ Same model class, same SDK call, different output.+3. **Switch the NER dropdown** from `gliner_multi-v2.1` to `NuNER_Zero`+ on the CPU image. Different model family (NuMind vs urchade), same SDK+ call, same labels, same recognition Markdown from this image.+4. **On the GPU compose, open the Recognition disclosure.** The call uses+ `lightonai/LightOnOCR-2-1B` unless you switch to GLM-OCR. GLM-OCR stays+ in the dropdown and loads on demand; it is not preloaded with LightOnOCR+ because the two do not fit on one GPU. Donut, GLiNER, and the PaddleOCR-VL+ transformers profile are not registered on that image. Compare+ `receipt.png` with `letter.png` on the CPU image instead: Donut on CORD+ fits the receipt and emits a CORD-shaped tree for the letter too.Each of these illustrates a concrete SIE pitch: model swap, output-shapeswap, quality swap, document-type fit.@@ -170,8 +180,8 @@ SIE collapses that into one process:└─────────────┬─────────────┘│┌──────────────▼──────────────┐- │ one SIE server ││ client.extract(model_id) │+ │ (one CPU image, one call) │└──┬───────────┬───────────┬──┘│ │ │┌──────▼──┐ ┌─────▼─────┐ ┌──▼──────┐@@ -181,33 +191,35 @@ SIE collapses that into one process:└─────────┘ └───────────┘ └─────────┘```-The Node server in `web/server.ts` chains the three calls and streams progress-via Server-Sent Events. The browser renders each panel as the corresponding-event lands.+The Node server in `web/server.ts` chains the calls the running image can+serve and streams progress via Server-Sent Events. The browser renders each+panel as the corresponding event lands. The CPU image runs PaddleOCR-VL,+Donut, and GLiNER. The GPU image runs LightOnOCR and GLM-OCR.---## Model lineup-The dropdowns expose nine models across three categories. Models marked-"alternate" are listed in the UI but lazy-load on first click; the demo-auto-disables anything not in the running server's `/v1/models` catalog (so-GPU-only models show up disabled on the CPU compose).+The dropdowns expose nine models across three categories. The UI disables+anything the running server's `/v1/models` catalog does not list. A+`gpuRequired` model is disabled only when that response positively reports+that CUDA is unavailable — `/v1/models` has no device field, so an unknown+device does not hide LightOnOCR on the GPU compose. The CPU image serves+recognition, structured extraction, and NER. The GPU image serves the two+sglang recognition models and not the other stages.-| Stage | Default (preloaded) | Alternates |+| Stage | CPU compose `latest-cpu-default` | GPU compose `latest-cuda12-sglang-vision-extract` ||---|---|---|-| Recognition | `lightonai/LightOnOCR-2-1B` (2.1B, Markdown output) | `PaddlePaddle/PaddleOCR-VL-1.6` (GPU image); `zai-org/GLM-OCR` (9B, GPU only) |-| Structured | `naver-clova-ix/donut-base-finetuned-cord-v2` | `naver-clova-ix/donut-base-finetuned-docvqa`; `naver-clova-ix/donut-base-finetuned-rvlcdip` (16-class document classifier) |-| Zero-shot NER | `urchade/gliner_multi-v2.1` | `urchade/gliner_large-v2.1`; `urchade/gliner_multi_pii-v1`; `numind/NuNER_Zero` (different architecture, useful contrast against GLiNER) |--Defaults are pinned in [`src/config.ts`](src/config.ts). To add a new model,-add a `ModelOption` entry and a HuggingFace model ID; SIE handles the rest.-The demo runs on the `latest-cpu-transformers5` SIE image; this is the-bundle where `lighton_ocr` / `glm_ocr` / `paddle` adapters live. The-Florence-2 family ships in SIE's `default` bundle (which pins-`transformers<5`) and is not loadable from this image. This separation keeps-the incompatible tokenizer dependency sets reproducible; use the default-bundle when evaluating Florence-2.+| Recognition | preloaded: `PaddlePaddle/PaddleOCR-VL-1.5:transformers` | preloaded: `lightonai/LightOnOCR-2-1B`. On demand, not preloaded with LightOnOCR (they do not fit on one GPU): `zai-org/GLM-OCR` |+| Structured | preloaded: `naver-clova-ix/donut-base-finetuned-cord-v2` (default) and `naver-clova-ix/donut-base-finetuned-docvqa` | not served |+| Zero-shot NER | preloaded: `urchade/gliner_multi-v2.1`. Lazy-loaded alternates: `urchade/gliner_large-v2.1`, `urchade/gliner_multi_pii-v1`, `numind/NuNER_Zero` | not served |++Defaults are pinned in [`src/config.ts`](src/config.ts):+`PaddlePaddle/PaddleOCR-VL-1.5:transformers`, Donut on CORD, and+`urchade/gliner_multi-v2.1`. LightOnOCR and GLM-OCR are `gpuRequired`.+To add a model, add a `ModelOption` whose profile adapter is in the bundle+of the compose that should serve it. Profile-qualified preloads use+`model:profile`.---@@ -218,7 +230,7 @@ src/config.ts model lineup (defaults + alternates per category)types.ts SampleDoc, ExtractedField, TriageResultevents.ts typed SSE events streamed to the browser- ocr.ts VLM-OCR caller (Florence-2, LightOnOCR, etc.)+ ocr.ts VLM-OCR caller (LightOnOCR, GLM-OCR, PaddleOCR-VL)donut.ts image-to-JSON caller (Donut variants)extract.ts GLiNER caller for zero-shot NER on textpipeline.ts recognition → structured + NER orchestrator@@ -255,8 +267,8 @@ HTML + CSS + JavaScript driven by `EventSource` for the SSE stream from SIE.call is the same; the model ID picks an embedding model from SIE's catalog of 100+catalog.- **Fine-tune for your schema.** If your documents look like one of the- Donut training corpora (CORD, RVL-CDIP, DocVQA), pick the matching- variant and skip the GLiNER step entirely.+ Donut checkpoints this demo serves (CORD, DocVQA), pick the matching+ variant on the CPU image and skip the GLiNER step entirely.- **Add a reranker after retrieval.** `client.score(reranker_id, query,documents)` does cross-encoder reranking; many real-world OCR pipelinesneed a "did we extract the right field" verification pass.@@ -265,12 +277,15 @@ HTML + CSS + JavaScript driven by `EventSource` for the SSE stream from SIE.## Honest scope and known limits-- **Apple Silicon performance is poor** because the SIE Docker image is- `linux/amd64` only and runs through Rosetta. Per-call latency on a Mac- is ~60-90 s for LightOnOCR; on Linux x86_64 it is ~20 s.-- **GLM-OCR and Paddle are GPU-only in practice.** They need CUDA, so the- CPU compose lists them but auto-disables them in the dropdown. The CUDA- image variant (used by `compose.gpu.yml`) loads them.+- **Apple Silicon runs the CPU image through Rosetta.** That image is+ `linux/amd64` only, so PaddleOCR-VL, Donut, and GLiNER are slower than on+ native x86_64. The transformers profile runs, using fp32 off CUDA.+- **LightOnOCR and GLM-OCR are the GPU-only sglang choices.** Their default+ profile is `sglang_vision_extract`, which the CPU image does not ship.+ `compose.gpu.yml` uses `latest-cuda12-sglang-vision-extract` and does not+ load Donut, GLiNER, or `PaddleOCR-VL-1.5:transformers`. It preloads only+ LightOnOCR-2-1B. GLM-OCR loads on demand and is not preloaded with+ LightOnOCR because the two do not fit on one GPU.- **This is a demo, not a production OCR pipeline.** The bundled sampleimages are synthetic; production OCR needs real-world layout coverage,per-merchant tuning, and human review hooks.@@ -281,6 +296,8 @@ HTML + CSS + JavaScript driven by `EventSource` for the SSE stream from SIE.- [SIE](https://github.com/superlinked/sie) (Apache 2.0): the inferenceengine that hosts all three model classes+- [PaddleOCR-VL-1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5):+ Paddle's 0.9B OCR VLM, `transformers` profile on the CPU image- [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B)(Apache 2.0): LightOn's Pixtral+Qwen3 OCR-VLM- [Donut](https://huggingface.co/naver-clova-ix/donut-base-finetuned-cord-v2)diff --git a/examples/document-ocr/compose.gpu.yml b/examples/document-ocr/compose.gpu.ymlindex 2a9f2480f..bdd070142 100644--- a/examples/document-ocr/compose.gpu.yml+++ b/examples/document-ocr/compose.gpu.yml@@ -1,17 +1,18 @@services:sie:- # GPU compose uses the transformers5 bundle so we can serve LightOnOCR /- # GLM-OCR / Paddle (their adapters need transformers>=5). Florence-2 is- # in the catalog but its tokenizer relies on a transformers<5 API and is- # therefore unavailable on this image. The CPU compose covers Florence-2- # through the default bundle.- image: ghcr.io/superlinked/sie-server:latest-cuda12-transformers5+ # GPU compose uses the sglang-vision-extract bundle. LightOnOCR-2-1B and+ # GLM-OCR use that adapter. Donut, GLiNER, and PaddleOCR-VL's transformers+ # profile are not in this bundle — use compose.yml for those.+ # Preload only LightOnOCR-2-1B. GLM-OCR stays selectable and loads on+ # demand; it is not preloaded with LightOnOCR because the two do not fit+ # on one GPU.+ image: ghcr.io/superlinked/sie-server:latest-cuda12-sglang-vision-extractcommand:- serve- --port- "8080"- --preload- - lightonai/LightOnOCR-2-1B,naver-clova-ix/donut-base-finetuned-cord-v2,urchade/gliner_multi-v2.1,zai-org/GLM-OCR,PaddlePaddle/PaddleOCR-VL-1.6+ - lightonai/LightOnOCR-2-1Bports:- "8080:8080"restart: unless-stoppeddiff --git a/examples/document-ocr/compose.yml b/examples/document-ocr/compose.ymlindex 4e1c99e01..e52d19ab2 100644--- a/examples/document-ocr/compose.yml+++ b/examples/document-ocr/compose.yml@@ -1,10 +1,10 @@services:sie:- # transformers5 bundle so LightOnOCR-2-1B (the recognition default) loads.- # Florence-2 family is incompatible with transformers>=5 (tokenizer API- # change), so the UI auto-disables those entries on this image. Use the- # default bundle when testing Florence-2 models.- image: ghcr.io/superlinked/sie-server:latest-cpu-transformers5+ # CPU default bundle includes donut, gliner, and paddleocr_vl. Preload+ # Donut, GLiNER, and PaddleOCR-VL-1.5:transformers so recognition,+ # structured extraction, and NER all come from this image. LightOnOCR and+ # GLM-OCR use sglang_vision_extract — see compose.gpu.yml.+ image: ghcr.io/superlinked/sie-server:latest-cpu-default# linux/amd64 is a no-op on x86_64 Linux hosts; on Apple Silicon it forces# Rosetta translation (slower but works for local testing).platform: linux/amd64@@ -13,7 +13,7 @@ services:- --port- "8080"- --preload- - lightonai/LightOnOCR-2-1B,naver-clova-ix/donut-base-finetuned-cord-v2,urchade/gliner_multi-v2.1+ - naver-clova-ix/donut-base-finetuned-cord-v2,naver-clova-ix/donut-base-finetuned-docvqa,urchade/gliner_multi-v2.1,PaddlePaddle/PaddleOCR-VL-1.5:transformersports:- "8080:8080"restart: unless-stoppeddiff --git a/examples/document-ocr/package-lock.json b/examples/document-ocr/package-lock.jsonindex 6e2cebd79..30baaddb0 100644--- a/examples/document-ocr/package-lock.json+++ b/examples/document-ocr/package-lock.json@@ -8,7 +8,7 @@"name": "document-ocr","version": "0.1.0","dependencies": {- "@superlinked/sie-sdk": "^0.3.1"+ "@superlinked/sie-sdk": "^0.9.0"},"devDependencies": {"@types/node": "^22.10.0",@@ -471,12 +471,12 @@}},"node_modules/@superlinked/sie-sdk": {- "version": "0.3.2",- "resolved": "https://registry.npmjs.org/@superlinked/sie-sdk/-/sie-sdk-0.3.2.tgz",- "integrity": "sha512-SqNXHzBLsXHjvrZRyLm/RCia3jqLkf1fMMRmQFS9URllROgTvSSRazccHwUQovHiytHfGdIqNZCwDShFikjwKg==",+ "version": "0.9.0",+ "resolved": "https://registry.npmjs.org/@superlinked/sie-sdk/-/sie-sdk-0.9.0.tgz",+ "integrity": "sha512-MSh5Px0QtU9hUNL9NUUo7ic5wYpo+9SVUamHN0sX9gxslCOSH1p8LOJEl0nL+jCT/ta0lRj7LS/9rfqrpTpYiQ==","license": "MIT","dependencies": {- "@msgpack/msgpack": "^3.0.0"+ "@msgpack/msgpack": "^3.1.3"},"engines": {"node": ">=22.0.0"diff --git a/examples/document-ocr/package.json b/examples/document-ocr/package.jsonindex bdd1ee93a..eb80be9b8 100644--- a/examples/document-ocr/package.json+++ b/examples/document-ocr/package.json@@ -14,7 +14,7 @@"regen-samples": "python3 scripts/generate_samples.py"},"dependencies": {- "@superlinked/sie-sdk": "^0.3.1"+ "@superlinked/sie-sdk": "^0.9.0"},"devDependencies": {"@types/node": "^22.10.0",diff --git a/examples/document-ocr/src/config.ts b/examples/document-ocr/src/config.tsindex 6dce2432a..2d7679cf5 100644--- a/examples/document-ocr/src/config.ts+++ b/examples/document-ocr/src/config.ts@@ -9,21 +9,24 @@ export type ModelOption = {export const RECOGNITION_MODELS: ModelOption[] = [{- id: "lightonai/LightOnOCR-2-1B",- label: "LightOnOCR-2-1B (default)",- description: "Pixtral encoder + Qwen3 decoder, 2.1B. Strong Markdown output across dense layouts. ~4 GB to download on first call.",+ id: "PaddlePaddle/PaddleOCR-VL-1.5:transformers",+ label: "PaddleOCR-VL-1.5",+ description:+ "Paddle's VLM-OCR, 0.9B, transformers profile. Preloaded on the CPU default image with Donut and GLiNER. Six task modes. Falls back to fp32 off CUDA.",+ options: { task: "ocr" },},{- id: "PaddlePaddle/PaddleOCR-VL-1.6",- label: "PaddleOCR-VL-1.6 (GPU image)",- description: "Paddle's VLM-OCR, 0.9B. Six task modes. Available on the CUDA image (compose.gpu.yml).",- options: { task: "ocr" },+ id: "lightonai/LightOnOCR-2-1B",+ label: "LightOnOCR-2-1B",+ description:+ "Pixtral encoder + Qwen3 decoder, 2.1B. Strong Markdown output across dense layouts. GPU sglang-vision image only.",gpuRequired: true,},{id: "zai-org/GLM-OCR",- label: "GLM-OCR (GPU only)",- description: "CogViT + GLM-0.5B decoder, 9B in bfloat16. Premium quality, needs ~18 GB VRAM (compose.gpu.yml).",+ label: "GLM-OCR",+ description:+ "CogViT + GLM-0.5B decoder, 9B in bfloat16. Premium quality, needs ~18 GB VRAM. GPU sglang-vision image only; not preloaded with LightOnOCR.",gpuRequired: true,},];@@ -32,17 +35,14 @@ export const STRUCTURED_MODELS: ModelOption[] = [{id: "naver-clova-ix/donut-base-finetuned-cord-v2",label: "Donut on CORD (receipts)",- description: "Fine-tuned for the CORD receipt schema. Pixels in, nested JSON out.",+ description:+ "Fine-tuned for the CORD receipt schema. Pixels in, nested JSON out. Preloaded by the CPU compose (default image); not on the GPU sglang vision image.",},{id: "naver-clova-ix/donut-base-finetuned-docvqa",label: "Donut on DocVQA",- description: "Same Donut architecture, fine-tuned for visual question answering. Returns text answers.",- },- {- id: "naver-clova-ix/donut-base-finetuned-rvlcdip",- label: "Donut on RVL-CDIP (doc classification)",- description: "Same Donut architecture, fine-tuned for document-type classification across 16 classes (invoice, receipt, form, ...).",+ description:+ "Same Donut architecture, fine-tuned for visual question answering. Returns text answers. Preloaded by the CPU compose (default image); not on the GPU sglang vision image.",},];@@ -50,22 +50,26 @@ export const NER_MODELS: ModelOption[] = [{id: "urchade/gliner_multi-v2.1",label: "GLiNER multi (multilingual)",- description: "280M, zero-shot NER, 100+ languages. Good default.",+ description:+ "280M, zero-shot NER, 100+ languages. CPU default. Served by the CPU compose (default image); not on the GPU sglang vision image.",},{id: "urchade/gliner_large-v2.1",label: "GLiNER large (English)",- description: "440M, English-focused, higher quality on English text.",+ description:+ "440M, English-focused, higher quality on English text. Served by the CPU compose (default image); not on the GPU sglang vision image.",},{id: "urchade/gliner_multi_pii-v1",label: "GLiNER multi PII",- description: "GLiNER fine-tuned for PII extraction. Good for redaction-style pipelines on documents.",+ description:+ "GLiNER fine-tuned for PII extraction. Good for redaction-style pipelines on documents. Served by the CPU compose (default image); not on the GPU sglang vision image.",},{id: "numind/NuNER_Zero",label: "NuNER Zero",- description: "NuMind's zero-shot NER. Different architecture from GLiNER; useful for comparing zero-shot NER families on the same input text.",+ description:+ "NuMind's zero-shot NER. Different architecture from GLiNER; useful for comparing zero-shot NER families on the same input text. Served by the CPU compose (default image); not on the GPU sglang vision image.",},];diff --git a/examples/document-ocr/src/donut.ts b/examples/document-ocr/src/donut.tsindex f52108fec..835ad8695 100644--- a/examples/document-ocr/src/donut.ts+++ b/examples/document-ocr/src/donut.ts@@ -10,16 +10,14 @@ export async function structuredExtract(): Promise<{ entities: DonutEntity[]; data: unknown }> {const format = detectImageFormat(imageBytes);if (format === "unknown") throw new Error("could not detect image format");- const wire = { data: imageBytes, format };const result = await client.extract(model,- { images: [wire] as unknown as Uint8Array[] },- { labels: [], options } as unknown as Parameters<typeof client.extract>[2],+ { images: [{ data: imageBytes, format }] },+ { labels: [], adapterOptions: options },);const entities = (result.entities ?? []).map((e) => ({label: e.label,text: e.text,}));- const data = (result as unknown as { data?: unknown }).data;- return { entities, data };+ return { entities, data: result.data };}diff --git a/examples/document-ocr/src/ocr.ts b/examples/document-ocr/src/ocr.tsindex 9d66823fe..45ce6265f 100644--- a/examples/document-ocr/src/ocr.ts+++ b/examples/document-ocr/src/ocr.ts@@ -8,15 +8,10 @@ export async function recognize(): Promise<string> {const format = detectImageFormat(imageBytes);if (format === "unknown") throw new Error("could not detect image format");- const wire = { data: imageBytes, format };- // The TS SDK types declare images as Uint8Array[], but the wire format- // expects {data, format} dicts. Cast around the typing gap.const result = await client.extract(model,- { images: [wire] as unknown as Uint8Array[] },- // The TS SDK's ExtractOptions doesn't declare `options`, but the wire- // protocol forwards it to the adapter. Cast to bridge the typing gap.- { labels: [], options } as unknown as Parameters<typeof client.extract>[2],+ { images: [{ data: imageBytes, format }] },+ { labels: [], adapterOptions: options },);if (!result.entities || result.entities.length === 0) return "";const text = result.entities[0]?.text;diff --git a/examples/document-ocr/src/pipeline.ts b/examples/document-ocr/src/pipeline.tsindex 6bca3cc9b..851dc1071 100644--- a/examples/document-ocr/src/pipeline.ts+++ b/examples/document-ocr/src/pipeline.ts@@ -38,53 +38,66 @@ export async function runPipeline({data: { extractor: nerModel, recognition: recognitionModel, structured: structuredModel },});- // Recognition- const recOpt = lookup(RECOGNITION_MODELS, recognitionModel);- emit({ type: "recognition_start", data: { model: recognitionModel } });- const tRec = Date.now();let markdown = "";- try {- markdown = await recognize(client, recOpt.id, imageBytes, recOpt.options);- } catch (err) {- emit({- type: "error",- data: { stage: "recognition", message: `${recognitionModel} failed: ${(err as Error).message}` },- });- throw err;+ let recognitionMs = 0;+ if (recognitionModel) {+ const recOpt = lookup(RECOGNITION_MODELS, recognitionModel);+ emit({ type: "recognition_start", data: { model: recognitionModel } });+ const tRec = Date.now();+ try {+ markdown = await recognize(client, recOpt.id, imageBytes, recOpt.options);+ } catch (err) {+ emit({+ type: "error",+ data: { stage: "recognition", message: `${recognitionModel} failed: ${(err as Error).message}` },+ });+ throw err;+ }+ recognitionMs = Date.now() - tRec;}- const recognitionMs = Date.now() - tRec;- emit({ type: "recognition_done", data: { markdown, ms: recognitionMs } });+ emit({+ type: "recognition_done",+ data: {+ markdown: recognitionModel ? markdown : "No recognition model selected.",+ ms: recognitionMs,+ },+ });// Structured (Donut variants, etc.)- const strOpt = lookup(STRUCTURED_MODELS, structuredModel);- emit({ type: "donut_start" });- const tDon = Date.now();let donut = { entities: [] as { label: string; text: string }[], data: undefined as unknown };- try {- donut = await structuredExtract(client, strOpt.id, imageBytes, strOpt.options);- } catch (err) {- emit({- type: "error",- data: { stage: "donut", message: `${structuredModel} failed: ${(err as Error).message}` },- });+ let donutMs = 0;+ if (structuredModel) {+ const strOpt = lookup(STRUCTURED_MODELS, structuredModel);+ emit({ type: "donut_start" });+ const tDon = Date.now();+ try {+ donut = await structuredExtract(client, strOpt.id, imageBytes, strOpt.options);+ } catch (err) {+ emit({+ type: "error",+ data: { stage: "donut", message: `${structuredModel} failed: ${(err as Error).message}` },+ });+ }+ donutMs = Date.now() - tDon;}- const donutMs = Date.now() - tDon;emit({ type: "donut_done", data: { entities: donut.entities, rawData: donut.data, ms: donutMs } });- // NER (GLiNER variants)- const nerOpt = lookup(NER_MODELS, nerModel);- emit({ type: "gliner_start", data: { labels: sample.labels } });- const tGli = Date.now();let fields: { label: string; text: string; score: number }[] = [];- try {- fields = await extractFields(client, nerOpt.id, markdown, sample.labels);- } catch (err) {- emit({- type: "error",- data: { stage: "gliner", message: `${nerModel} failed: ${(err as Error).message}` },- });+ let glinerMs = 0;+ if (nerModel) {+ const nerOpt = lookup(NER_MODELS, nerModel);+ emit({ type: "gliner_start", data: { labels: sample.labels } });+ const tGli = Date.now();+ try {+ fields = await extractFields(client, nerOpt.id, markdown, sample.labels);+ } catch (err) {+ emit({+ type: "error",+ data: { stage: "gliner", message: `${nerModel} failed: ${(err as Error).message}` },+ });+ }+ glinerMs = Date.now() - tGli;}- const glinerMs = Date.now() - tGli;emit({ type: "gliner_done", data: { fields, ms: glinerMs } });const totalMs = Date.now() - t0;diff --git a/examples/document-ocr/web/public/app.js b/examples/document-ocr/web/public/app.jsindex 5024ca095..bb13dbff2 100644--- a/examples/document-ocr/web/public/app.js+++ b/examples/document-ocr/web/public/app.js@@ -25,7 +25,9 @@ let donutBuf = { entities: [], data: null };let glinerBuf = [];let modelConfig = null;let registeredSet = new Set();-let cudaAvailable = false;+let cudaAvailable = null;+let catalogKnown = false;+let availabilityUnavailable = false;function setBadge(text, cls) {els.badge.textContent = text;@@ -94,28 +96,60 @@ function updateSnippets() {els.snippetNer.innerHTML = snippetNer(els.selectNer.value, activeSample);}+function clearAvailability() {+ registeredSet = new Set();+ cudaAvailable = null;+ catalogKnown = false;+ availabilityUnavailable = true;+}++function optionAvailable(opt) {+ if (availabilityUnavailable) {+ return { inCatalog: false, blockedByCuda: false, available: false };+ }+ // Empty successful catalogs are known. A failed fetch leaves catalogKnown false.+ const serverKnown = catalogKnown;+ const inCatalog = !serverKnown || registeredSet.has(opt.id);+ const blockedByCuda = Boolean(opt.gpuRequired) && cudaAvailable === false;+ return { inCatalog, blockedByCuda, available: inCatalog && !blockedByCuda };+}++function enabledValue(selectEl) {+ const option = selectEl.selectedOptions && selectEl.selectedOptions[0];+ if (!option || option.disabled) return "";+ return option.value;+}+function populateDropdown(selectEl, options, defaultId) {+ const previous = selectEl.value;selectEl.innerHTML = "";+ const entries = [];for (const opt of options) {const node = document.createElement("option");node.value = opt.id;- const inCatalog = registeredSet.size === 0 || registeredSet.has(opt.id);- const blockedByCuda = opt.gpuRequired && !cudaAvailable;- const available = inCatalog && !blockedByCuda;+ const { blockedByCuda, available } = optionAvailable(opt);const labelSuffix = !available- ? blockedByCuda+ ? blockedByCuda || opt.gpuRequired? " (GPU image needed)"- : opt.gpuRequired- ? " (GPU image needed)"- : " (not registered)"+ : " (not registered)": "";node.textContent = opt.label + labelSuffix;if (!available) node.disabled = true;- if (opt.id === defaultId) node.selected = true;node.title = opt.description;selectEl.appendChild(node);+ entries.push({ node, available, id: opt.id });+ }+ const preferred = previous || defaultId;+ const pick =+ entries.find((entry) => entry.available && entry.id === preferred) ||+ entries.find((entry) => entry.available && entry.id === defaultId) ||+ entries.find((entry) => entry.available);+ if (pick) pick.node.selected = true;+ else selectEl.selectedIndex = -1;+ if (!selectEl.dataset.bound) {+ selectEl.addEventListener("change", updateSnippets);+ selectEl.dataset.bound = "1";}- selectEl.addEventListener("change", updateSnippets);}function renderSamples(samples, onClick) {@@ -179,11 +213,51 @@ function renderExtraction() {html += "</div>";}- if (!html) html = '<p class="hint">running...</p>';+ if (!html) html = '<p class="hint">nothing extracted on this image</p>';els.extraction.innerHTML = html;}-function runSample(sampleId) {+async function syncAvailability() {+ try {+ const r = await fetch("/api/health");+ const j = await r.json();+ els.sieUrl.textContent = j.sieUrl;+ if (j.catalogKnown !== true) {+ clearAvailability();+ els.sieState.textContent =+ j.sie === true+ ? "model catalog unavailable"+ : "SIE not reachable yet (still preloading models?)";+ return false;+ }+ registeredSet = new Set(j.registered ?? []);+ cudaAvailable = j.cuda === true ? true : j.cuda === false ? false : null;+ catalogKnown = true;+ availabilityUnavailable = false;+ els.sieState.textContent = `SIE healthy · ${j.registeredModels} models registered`;+ return true;+ } catch {+ clearAvailability();+ els.sieState.textContent = "could not reach the local server";+ return false;+ }+}++function applyModelMenus() {+ if (!modelConfig) return;+ populateDropdown(els.selectRecognition, modelConfig.recognition, modelConfig.defaults.recognition);+ populateDropdown(els.selectStructured, modelConfig.structured, modelConfig.defaults.structured);+ populateDropdown(els.selectNer, modelConfig.ner, modelConfig.defaults.ner);+ updateSnippets();+}++async function runSample(sampleId) {+ const availabilityOk = await syncAvailability();+ applyModelMenus();+ if (!availabilityOk) {+ setBadge("error", "red");+ return;+ }activeSampleId = sampleId;setBadge("running", "running");els.recognition.innerHTML = '<p class="hint">running recognition...</p>';@@ -195,9 +269,9 @@ function runSample(sampleId) {glinerBuf = [];updateTimings();- const recognition = els.selectRecognition.value;- const structured = els.selectStructured.value;- const ner = els.selectNer.value;+ const recognition = enabledValue(els.selectRecognition);+ const structured = enabledValue(els.selectStructured);+ const ner = enabledValue(els.selectNer);const url = `/api/run?id=${encodeURIComponent(sampleId)}&recognition=${encodeURIComponent(recognition)}&structured=${encodeURIComponent(structured)}&ner=${encodeURIComponent(ner)}`;const es = new EventSource(url);@@ -257,32 +331,13 @@ function runSample(sampleId) {}async function init() {- // Fetch SIE health (and registered models)- let registered = [];- try {- const r = await fetch("/api/health");- const j = await r.json();- els.sieUrl.textContent = j.sieUrl;- if (!j.sie) {- els.sieState.textContent = "SIE not reachable yet (still preloading models?)";- } else {- els.sieState.textContent = `SIE healthy · ${j.registeredModels} models registered`;- registered = j.registered ?? [];- cudaAvailable = !!j.cuda;- }- } catch {- els.sieState.textContent = "could not reach the local server";- }- registeredSet = new Set(registered);+ await syncAvailability();// Fetch model menus (config-side)try {const r = await fetch("/api/models");modelConfig = await r.json();- populateDropdown(els.selectRecognition, modelConfig.recognition, modelConfig.defaults.recognition);- populateDropdown(els.selectStructured, modelConfig.structured, modelConfig.defaults.structured);- populateDropdown(els.selectNer, modelConfig.ner, modelConfig.defaults.ner);- updateSnippets();+ applyModelMenus();} catch (e) {console.error("failed to load model config", e);}diff --git a/examples/document-ocr/web/public/index.html b/examples/document-ocr/web/public/index.htmlindex 7b862fe8e..4c19e1fef 100644--- a/examples/document-ocr/web/public/index.html+++ b/examples/document-ocr/web/public/index.html@@ -29,24 +29,23 @@<div class="hero-text"><p>OCR is rarely a single-model problem. This demo runs three model- classes through <strong>one SIE server</strong>: a VLM-OCR recognizes- the document into Markdown, a fine-tuned Donut emits a JSON tree- directly, and a zero-shot NER (GLiNER) pulls typed fields out of- the recognition output. Pick a sample on the left, swap any of the- three models in the dropdowns, watch SIE hot-swap them with- <em>one identifier change</em>.+ classes through the <strong>same SIE call</strong>. The CPU default+ image serves PaddleOCR-VL (transformers profile), Donut, and GLiNER+ together. LightOnOCR and GLM-OCR load on the GPU sglang-vision+ image, which does not serve Donut or GLiNER. Pick a sample on the+ left and swap a model with <em>one identifier change</em>.</p></div><div class="hero-diagram"><div class="diagram"><div class="diagram-input">image</div><div class="diagram-arrow">↓</div>- <div class="diagram-server">one SIE server · <code>client.extract(model_id, item)</code></div>+ <div class="diagram-server">one SIE call · <code>client.extract(model_id, item)</code></div><div class="diagram-arrows"><span>↓</span><span>↓</span><span>↓</span></div><div class="diagram-models">- <div class="diagram-box diagram-recognition">VLM-OCR<br><span>(LightOnOCR-2-1B, PaddleOCR-VL, GLM-OCR)</span></div>+ <div class="diagram-box diagram-recognition">VLM-OCR<br><span>(PaddleOCR-VL, LightOnOCR, GLM-OCR)</span></div><div class="diagram-box diagram-structured">Donut<br><span>(end-to-end JSON)</span></div><div class="diagram-box diagram-ner">GLiNER<br><span>(zero-shot NER)</span></div></div>@@ -70,9 +69,9 @@<h3>Try these moments</h3><ol class="tour-list"><li>- <strong>Click any sample on the left.</strong> All three models run- in one pipeline. The footer prints per-stage timings as each one- lands.+ <strong>Click any sample on the left.</strong> The stages that this+ image can serve run, and the others stay disabled. The footer prints+ per-stage timings as each one lands.</li><li><strong>Open "See the SIE call"</strong> in any panel, then swap thediff --git a/examples/document-ocr/web/server.ts b/examples/document-ocr/web/server.tsindex 6d50e1797..be1cc951e 100644--- a/examples/document-ocr/web/server.ts+++ b/examples/document-ocr/web/server.ts@@ -49,20 +49,19 @@ function setupSse(res: http.ServerResponse) {};}-async function fetchModels(): Promise<{ ok: boolean; names: string[]; cuda: boolean }> {+async function fetchModels(): Promise<{ ok: boolean; names: string[]; cuda: boolean | null }> {try {const r = await fetch(`${config.sieUrl}/v1/models`, { signal: AbortSignal.timeout(3000) });- if (!r.ok) return { ok: false, names: [], cuda: false };- const json = (await r.json()) as {- models?: { name: string; device?: string; state?: string }[];- };- const models = json.models ?? [];- // GPU compose preloads GPU-only models. If any catalog entry is currently- // loaded on a non-cpu device, treat this server as GPU-capable.- const cuda = models.some((m) => (m.device ?? "").toLowerCase().includes("cuda"));- return { ok: true, names: models.map((m) => m.name), cuda };+ if (!r.ok) return { ok: false, names: [], cuda: null };+ const json = (await r.json()) as { models?: { name?: string }[] };+ const names = (json.models ?? [])+ .map((model) => model.name)+ .filter((name): name is string => typeof name === "string" && name.length > 0);+ // ModelInfo and the health probes do not report a device. null is unknown,+ // not "CUDA unavailable"; only an explicit false blocks a gpuRequired model.+ return { ok: true, names, cuda: null };} catch {- return { ok: false, names: [], cuda: false };+ return { ok: false, names: [], cuda: null };}}@@ -145,6 +144,9 @@ const server = http.createServer(async (req, res) => {registeredModels: names.length,registered: names,cuda,+ // True only when /v1/models succeeded, including an empty list.+ // The page must not infer this from sie; that flag can be another probe.+ catalogKnown: ok,}),"application/json",);diff --git a/packages/sie_server/tests/test_document_ocr_example_bundles.py b/packages/sie_server/tests/test_document_ocr_example_bundles.pynew file mode 100644index 000000000..a1d7bf3f8--- /dev/null+++ b/packages/sie_server/tests/test_document_ocr_example_bundles.py@@ -0,0 +1,147 @@+from __future__ import annotations++import re+from pathlib import Path++import yaml+from sie_sdk.bundle_utils import match_bundle_models++_REPO_ROOT = Path(__file__).resolve().parents[3]+_EXAMPLE = _REPO_ROOT / "examples" / "document-ocr"+_COMPOSE_FILES = (_EXAMPLE / "compose.yml", _EXAMPLE / "compose.gpu.yml")+_EXPECTED_PRELOADS = {+ "compose.yml": [+ "naver-clova-ix/donut-base-finetuned-cord-v2",+ "naver-clova-ix/donut-base-finetuned-docvqa",+ "urchade/gliner_multi-v2.1",+ "PaddlePaddle/PaddleOCR-VL-1.5:transformers",+ ],+ "compose.gpu.yml": ["lightonai/LightOnOCR-2-1B"],+}+_CONFIG_TS = _EXAMPLE / "src" / "config.ts"+_BUNDLES_DIR = _REPO_ROOT / "packages" / "sie_server" / "bundles"+_MODELS_DIR = _REPO_ROOT / "packages" / "sie_server" / "models"++# Longest suffix first so a tag cannot match a shorter sibling by accident.+_IMAGE_BUNDLE_SUFFIXES = (+ ("-sglang-vision-extract", "sglang-vision-extract.yaml"),+ ("-transformers5", "transformers5.yaml"),+ ("-default", "default.yaml"),+)++# Quoted org/name ids, optionally ``model:profile``. A path like "data/samples"+# has neither a digit nor a hyphen/underscore, which every catalog id here does.+_QUOTED_MODEL_ID = re.compile(+ r"""["']([A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*(?::[A-Za-z0-9][A-Za-z0-9_.-]*)?)["']"""+)+_MODEL_ID_MARK = re.compile(r"[-_0-9]")+++def _models_by_id() -> dict[str, dict[str, object]]:+ found: dict[str, dict[str, object]] = {}+ for path in sorted(_MODELS_DIR.glob("*.yaml")):+ data = yaml.safe_load(path.read_text()) or {}+ if not isinstance(data, dict):+ continue+ sie_id = data.get("sie_id")+ if isinstance(sie_id, str):+ found[sie_id] = data+ return found+++def _bundle_filename_for_image(image: str) -> str:+ tag = image.rsplit(":", 1)[-1]+ for suffix, filename in _IMAGE_BUNDLE_SUFFIXES:+ if tag.endswith(suffix):+ return filename+ msg = f"no bundle mapping for image {image!r}"+ raise AssertionError(msg)+++def _preload_ids(command: object) -> list[str]:+ if isinstance(command, str):+ parts = command.split()+ elif isinstance(command, list):+ parts = [str(item) for item in command]+ else:+ return []+ found: list[str] = []+ for index, part in enumerate(parts):+ if part == "--preload" and index + 1 < len(parts):+ found.extend(item.strip() for item in parts[index + 1].split(",") if item.strip())+ elif part.startswith("--preload="):+ found.extend(item.strip() for item in part.split("=", 1)[1].split(",") if item.strip())+ return found+++def _bundle_model_ids(bundle_filename: str) -> set[str]:+ return set(match_bundle_models(_BUNDLES_DIR / bundle_filename, _MODELS_DIR))+++def _compose_image_and_preloads(path: Path) -> tuple[str, list[str]]:+ data = yaml.safe_load(path.read_text()) or {}+ services = data.get("services") if isinstance(data, dict) else None+ service = services.get("sie") if isinstance(services, dict) else None+ if not isinstance(service, dict):+ msg = f"{path} has no services.sie"+ raise AssertionError(msg)+ image = service.get("image")+ if not isinstance(image, str) or not image:+ msg = f"{path} has no image"+ raise AssertionError(msg)+ preloads = _preload_ids(service.get("command"))+ if not preloads:+ msg = f"{path} preloads no models"+ raise AssertionError(msg)+ return image, preloads+++def test_document_ocr_preloaded_models_match_image_bundles() -> None:+ assert _CONFIG_TS.is_file()+ config_text = _CONFIG_TS.read_text()++ problems: list[str] = []+ for compose in _COMPOSE_FILES:+ assert compose.is_file(), compose+ image, preloads = _compose_image_and_preloads(compose)+ expected = _EXPECTED_PRELOADS[compose.name]+ if preloads != expected:+ problems.append(f"{compose.name} preloads {preloads!r}, expected {expected!r}")+ bundle_name = _bundle_filename_for_image(image)+ matched = _bundle_model_ids(bundle_name)+ assert matched, f"{bundle_name} matches no models"+ for preload_id in preloads:+ if preload_id not in config_text:+ problems.append(f"{compose.name} preloads {preload_id!r}, which src/config.ts does not list")+ if preload_id not in matched:+ problems.append(+ f"{compose.name} image {image} ({bundle_name}) preloads {preload_id!r}, "+ "which match_bundle_models does not return for that bundle"+ )++ assert not problems, "document-ocr preloads models its image cannot load:\n " + "\n ".join(problems)+++def test_document_ocr_config_model_ids_exist() -> None:+ models = _models_by_id()+ assert models, f"No model YAML files found in {_MODELS_DIR}"+ served: set[str] = set()+ for compose in _COMPOSE_FILES:+ image, _preloads = _compose_image_and_preloads(compose)+ served.update(_bundle_model_ids(_bundle_filename_for_image(image)))+ text = _CONFIG_TS.read_text()+ config_ids = [model_id for model_id in _QUOTED_MODEL_ID.findall(text) if _MODEL_ID_MARK.search(model_id)]+ assert len(config_ids) >= 5, "config.ts scanner found too few model ids — the pattern has rotted"++ unknown: list[str] = []+ for model_id in sorted(set(config_ids)):+ base, separator, profile = model_id.partition(":")+ if separator and profile and profile != "default":+ if base not in models or model_id not in served:+ unknown.append(model_id)+ elif model_id not in models:+ unknown.append(model_id)+ assert not unknown, (+ "document-ocr config.ts ids that are not catalog sie_ids "+ "or bundle-matched profile ids:\n " + "\n ".join(unknown)+ )