

# docs/model-onboarding-refactor.md
# Refactor proposal: make adding a model architecture a recipe, not a project

Written after onboarding `LlamaForCausalLM` (MiniCPM5-1B) end-to-end on
the post-2026-05-28 leaner registry. The adapter itself was small — the
friction was everything *around* it. This proposal targets that friction
so the next arch is a 20-minute recipe.

Each item lists: the friction observed, the fix, and status.

---

## What actually happened onboarding MiniCPM5-1B

Six distinct issues surfaced; only three were the adapter. The rest were
pre-existing engine/image gaps that adding a fresh model exposed:

| # | Symptom | Root cause | Adapter's fault? |
|---|---|---|---|
| 1 | `Unsupported architecture ['LlamaForCausalLM']` | not registered | yes — but the registration is a 4-edit dance |
| 2 | `No flash_attn_varlen_func resolver succeeded` | slim image omits flash-attn; default bf16 backend needs it | no — image gap |
| 3 | `AttributeError: 'SafetensorsCollection' has no attribute key_to_file` | guessed the loader API | yes — no discoverable contract |
| 4 | generation returns `finish_reason:error`, empty body, HTTP 200 | engine error swallowed into a 200 | no — error handling gap |
| 5 | `CUDA OOM, tried to allocate 12.1 GiB` regardless of `--gpu-memory-utilization` | KV pool sized to `max_batch × max_context` floor, overriding the VRAM budget | no — engine sizing bug |
| 6 | restart-loop GPU contention | `--restart unless-stopped` on a crashing boot | no — ops |

The adapter (`llama.py`) loads weights correctly and runs to the
attention call; the same checkpoint serves fine on the vLLM fork. The
*serving* blockers were #2/#4/#5 — engine/image robustness, not the model.

---

## Fixes

### 1. flash-attn in the slim image — DONE, AND SINCE UNDONE

SUPERSEDED: there is no `Dockerfile.slim` (one `Dockerfile`, target `slim`),
`pyproject.toml` pins `torch>=2.12,<2.13` rather than 2.9.1, the `Dockerfile`
records flash-attn as DROPPED on that stack, and `paged_kv:bf16-fa` is not a
registered backend. A bf16-FA2 parity arm — the natural correctness control
when onboarding a model — cannot be run as described. The production bf16
default is `paged_kv:tkv-bypass`, which has no flash-attn dependency.

As written at the time: `Dockerfile.slim` installs the **prebuilt** flash-attn
2.8.3 wheel (same one the full `Dockerfile` uses), not a source build. The
`torch==2.9.1` pin exists precisely so this wheel's ABI matches — they move in
lockstep.

Policy preserved: "never build flash-attn from source" — honoured by
pinning the wheel URL, not by omitting flash-attn.

### 2. KV pool sizing: VRAM budget is authoritative — DONE

`engine/active.py` previously did:

```python
target_pages = max(profiled_budget, max_batch * (per_seq_pages + 1) + 1)
```

The second term ("hold max_batch sequences each at full max_context") is
a *comfort* target, not a constraint. At default `max_batch=32` /
`max_context=32768` it is ~24 GB of bf16 KV — larger than what fits on a
24 GB card — so `max()` discarded the profiled budget (which DID fit) and
OOM'd at boot. Lowering `--gpu-memory-utilization` couldn't help because
`max()` ignored it.

Fixed: when a profiled budget exists it is used verbatim; the batch floor
is only a fallback for unit-test stubs with no budget. `max_context` does
not consume VRAM — only the page budget does — so the scheduler simply
admits fewer concurrent full-context sequences when pages are scarce, and
logs that it did. This is the general fix the user asked for ("you just
specify gpu util and it tells you how much KV you can actually fit").

### 3. One-line architecture registration — DONE

Registering an arch was **four** edits in `models/__init__.py`
(TYPE_CHECKING import, `_build_architectures` dict entry, `__all__`,
`_LAZY_NAMES`). The declarative table (`_ARCH_TABLE`) collapsed it to one
row — see `models/__init__.py` ("Adding a model is one table row"):

```python
# models/_registry_table.py  (torch-clean — just strings)
ARCH_TABLE: dict[str, tuple[str, str]] = {
    # config arch string         (module path,                     class name)
    "LlamaForCausalLM":  ("arbi_serve.models.llama",       "LlamaModel"),
    "Qwen3ForCausalLM":  ("arbi_serve.models.qwen3",       "Qwen3Model"),
    "DeepseekV3ForCausalLM": ("arbi_serve.models.deepseek_v3", "DeepseekV3Model"),
    # ... one line per arch; aliases just repeat the (module, class)
}
```

`_build_architectures()` becomes a loop that imports lazily on first
`load_model`. `__all__` / `_LAZY_NAMES` are derived from the table, not
hand-maintained. Adding an arch = one table row + the arch file. Keeps
the torch-tax lazy-import guard (the table is strings only).

### 4. A `DenseDecoderConfig` base — PROPOSED

`Qwen3Config`, `LlamaConfig`, `GraniteConfig` are ~95% the same dataclass
(11 shared fields + identical `from_hf_config` / `to_model_dims` /
`to_layer_specs`). Lift the shared shape into one base; subclasses declare
only their deltas (Qwen3: qk-norm flag; Granite: the three multipliers;
Llama: nothing). A new plain-dense arch then becomes ~15 lines, not ~395.

Not done yet — it touches three existing files, so it wants its own PR
with the arch-parity tests green, separate from the MiniCPM enablement.

### 5. Fail loud, not into a 200 — PROPOSED

The empty-body `finish_reason:error` cost a debug cycle: the
real `key_to_file` traceback only appeared in the container log, while the
HTTP client got a clean 200 with empty text. A build/forward exception
should surface as a 500 with the error class, or crash boot — never a
silent empty completion. (Matches the repo-wide "no silent fallback" rule
already applied to the codec paths.)

---

## The recipe (what a newcomer should follow)

See [adding-a-model.md](adding-a-model.md). Short version once #3/#4 land:

1. Read `config.json`; if it's an existing arch, add one `ARCH_TABLE` row
   and stop.
2. Else copy the nearest sibling arch file; subclass `DenseDecoderConfig`,
   declare the deltas, set `use_qk_norm` / `with_qk_norm` to match.
3. Add one `ARCH_TABLE` row.
4. `ruff check` + `pytest -k "model or registry"`.
5. Mount-test on a real checkpoint (bf16 first, then `--kv-cache-dtype
   tkv TKV_BITS=4`). No image rebuild for the test loop.

---

## Status summary

- DONE: flash-attn wheel in slim image (#1); KV budget authority (#2);
  generic `llama.py` + registry wiring + `adding-a-model.md`;
  registration table (#3); `DenseDecoderConfig` base (#4).
- PROPOSED (own PRs): fail-loud generation errors (#5).


# docs/multi-turn-reasoning-replay-2026-09-08.md
# Multi-turn reasoning replay: what the seam costs, and what closing it costs

Issue #2286. Measured 2026-09-08 on the live Qwen3.8-27B-exl3-4.0bpw
(box 105, TP=1, `--kv-cache-dtype=tkv --enable-mtp`) and offline over every
chat template on `/mnt/k8scache/models`.

This is a **trade**, not a fix. `replay_reasoning` ships OFF, and on the
configuration measured here turning it on is a LOSS today. The numbers
below are the ones to re-run before anyone changes that default.

## The seam

A thinking model's generation prompt opens the think block itself —
Qwen3.8's ends `<|im_start|>assistant\n<think>\n`. Everything the model
then emits, trace included, is committed at `finished()` under
`cache_token_ids() + output_token_ids`.

The next turn re-renders that same assistant turn from `messages`. With
no trace in the message, the template closes an EMPTY block, and the
re-rendered prompt diverges from the committed path **at the previous
prompt's last token** — before a single generated token. Measured over a
real three-turn conversation (`prev_committed` / first divergence):

| turn | prev committed ids | first divergence | previous prompt |
|---|---|---|---|
| 2 | 886 | 115 | 116 |
| 3 | 1120 | 435 | 436 |
| 4 | 1936 | 839 | 840 |

With the trace replayed through the template's own `reasoning_content`
slot, the same three comparisons return **no divergence**: the committed
ids are a strict prefix of the next turn's rendered ids. That is the
acceptance property, and it is what makes the replay sound — the tokens
and the KV genuinely correspond. Re-keying committed pages under the
re-rendered path would force the same `cached_tokens` while being false
about the KV; `commit_full_pages` says so in its own docstring, and it is
not what this does.

## Scope: which templates have the seam

`tools/chat/turn2_seam_survey.py` sweeps every checkpoint on the box
through arbi-serve's own render path. Three messages (user, assistant,
user), not two — a template that keeps a historical think block only for
the turn after the last user query looks clean on a two-message probe and
is not. 21 distinct templates over 47 checkpoints:

**RECOVERABLE** — a seam, and the template's own slot to close it:

* Qwen3.8-27B (+ AWQ-INT4, FP8, exl3-4.0bpw) — the production model
* Qwen3.6-27B-AWQ-INT4 — needs `preserve_thinking` too, which
  `replay_reasoning` turns on where the template declares it
* LFM2.5-2.6B

**STRUCTURAL** — a seam the template keeps even with the trace replayed,
because it rewrites a completed turn rather than appending to it. Not
addressable from our side; closing these would mean rewriting a published
artefact:

* Gemma-4-31B-IT (NVFP4, AWQ-4bit) — `strip_thinking()` deletes the
  thought channel from history outright
* Nemotron-3.5-Lightning-30B-A3B, Nemotron-3-Nano-4B
* Qwen3-4B-Thinking-2507 — no `preserve_thinking`; history keeps no block
* Qwen3.5-0.8B — its generation prompt appends an empty think block that
  history never reproduces, with or without a trace
* NemotronLabs-VoiceChat-11B

**CLEAN** — no seam either way: DeepSeek-V2-Lite, LFM2.5-8B-A1B,
Ling-3.0-tiny, MiniCPM5-1B, Muse-Glimmer-30B, Qwen3-0.6B/1.7B/4B,
Qwen3-4B-Instruct-2507, Step-Audio-2-mini (both), Unlimited-OCR,
gemma-4-E2B-it, gpt-oss-20b, granite-4.1.

## What the status quo actually costs

Two self-consistent conversations, same three questions, greedy, each
driven turn by turn so every turn's prompt is the one its own arm would
have sent. Final turn measured with `max_tokens=1`.

| | prompt | cached | uncached | TTFT |
|---|---|---|---|---|
| A — status quo (trace dropped) | 1169 | 768 | 401 | 129 ms |
| B — `replay_reasoning=true` | 3071 | 2048 | 1023 | 219 ms |

**Replay is slower today, by 90 ms and 1902 tokens of context.** The
reason is the second finding below.

Note what arm A does NOT pay for: the trace is not re-prefilled, because
it is never sent. The status quo re-prefills the previous reply's
**content** only — here ~330 tokens of a ~1100-token reply. The issue's
framing ("every turn re-prefills the previous reply", the reply being
mostly trace) overstates it: the trace is neither cached nor prefilled,
it is absent, and that absence is the whole of what the model loses.

## Why replay cannot pay yet: decode-written pages are unreachable

On this engine the radix match never reaches past the previous turn's
prompt end **even when the ids match exactly**. Isolated, with an output
whose re-tokenization is certainly canonical (the model copying a line
verbatim out of its own prompt, 900 completion tokens re-tokenizing to
exactly 900):

```
prompt=85  completion=900  cached=0
continuation with prompt+output: prompt=985  cached=0
                                 (full committed pages would be 768)
```

In every arm above, `cached` is exactly `floor(previous PROMPT / 256) *
256` — the previous turn's prefill pages, never its decode pages.

Qwen3.8-27B is hybrid (64 layers, `full_attention_interval=4`: 48 linear
+ 16 full attention), so the match is capped at what a recurrent
savepoint covers — `savepoint_admission.py:252-263`,
`max_match_len=min(recurrent_cap, page_budget_cap)`, with the force-disable
at `:305-313`. Savepoints are written across prefill; a decode-written
page has none behind it. This is #2272, and it is the same cap the issue
saw as `radix_reach=2560` against `stored_desc=[3328, 3072, 2816, 2560]`.

**The two defects are complementary and neither pays alone.**

* Fix #2272 without the seam: arm A still diverges at the previous
  prompt's last token, so no decode page is reachable. Buys nothing on
  multi-turn chat.
* Fix the seam without #2272 (today): arm B's ids match, but the pages
  behind them are not matchable, and the replayed trace lands in the
  uncached region. Costs 90 ms and 2x the context.

Projected for both landed, from the two arms' prefill slope
(0.145 ms/token, 71 ms fixed): arm B's uncached region falls from 1023 to
~255 tokens, ~108 ms against arm A's 129 ms — a **~20 ms / 16% TTFT win
at 2.6x the transcript**. Re-measure rather than trusting that
projection; it is arithmetic on two points, not a measurement.

## The trade, stated plainly

* **Prefill saved** scales with the previous reply's *content* — the part
  arm A re-prefills. Measured: 33-38% of each reply.
* **Context spent** scales with the previous replies' *traces* — the part
  arm B carries forever. Measured: 62-69% of each reply. Those tokens are
  cached, so they cost context window rather than prefill time, but they
  cost it cumulatively.
* **What the model conditions on changes.** It sees its own prior
  reasoning. Anthropic's API mandates replaying thinking blocks precisely
  to keep the cache valid; Qwen's template offers the slot and does not
  require it. Neither is wrong, and this is the choice being made.

Roughly two tokens of permanent context per one token of prefill saved,
per turn.

## Default OFF, and why the field is not enough on its own

`ChatMessage.reasoning_content` is accepted under both wire names the
response emits, and dropped unless `replay_reasoning` rides with it. Many
OpenAI-style clients echo a whole response message back; honoring the
field unconditionally would silently start feeding traces to models for
callers that never asked, which is a behavior change wearing a bug fix's
clothes.

## Reproducing

```
python tools/chat/turn2_seam_survey.py            # scope, offline, no GPU
pytest tests/test_reasoning_replay_prefix_seam.py # token identity
```


# docs/native-kokoro-serving.md
# Native Kokoro serving

Kokoro runs as `ArbiKokoroSpeech`, a scheduled `MediaForwardModel` with the
`speech_synthesis` binding. The ordinary engine owns admission, batching,
cancellation, output copies and weight migration. The HTTP process exposes
`POST /v1/audio/speech` through serialized binding metadata; it performs local
English pronunciation before submitting phoneme segments to the engine.

Provision the published Kokoro checkpoint locally (`config.json`,
`kokoro-v1_0.pth`, and `voices/*.pt`) and the English spaCy model directory
containing `config.cfg`. Serving never downloads models or executes remote code.
The model and selected voice packs retain their upstream licenses. The English
processor uses the pinned Misaki recipe and local Espeak assets.

```sh
python scripts/prepare_kokoro_deployment.py \
  --checkpoint /path/to/kokoro --phonemizer /path/to/english-spacy-model \
  --output /path/to/deployment --voices af_heart am_adam bf_emma
```

This creates the small engine config and an operator credential at
`deployment/auth-tokens` without printing its value. Existing credentials are
preserved; a conflicting existing config is refused. Mount the same asset
directories used for provisioning:

```sh
export ARBI_IMAGE=registry.arbi.work/arbi-serve:test-latest
export ARBI_KOKORO_SOURCE="$PWD"
export ARBI_KOKORO_CHECKPOINT=/path/to/kokoro
export ARBI_KOKORO_PHONEMIZER=/path/to/english-spacy-model
export ARBI_KOKORO_DEPLOYMENT=/path/to/deployment
export ARBI_KOKORO_CACHE=/path/to/persistent-cache
export ARBI_KOKORO_EXTRA_DEPS=/path/to/empty-directory
mkdir -p "$ARBI_KOKORO_CACHE" "$ARBI_KOKORO_EXTRA_DEPS"
sudo chown -R 10001:10001 "$ARBI_KOKORO_DEPLOYMENT" "$ARBI_KOKORO_CACHE"
bash scripts/ci/gpu_lock.sh 0 -- docker compose \
  -p arbi-kokoro -f compose.kokoro-serving.yaml up --no-build
```

The serving recipes use the image account, UID/GID 10001, drop all capabilities,
and forbid privilege escalation. The deployment credential must remain private
and readable by that account; its cache directory must be writable by it.
A local development override may match a host-owned development account.

Use a freshly built image for its declared runtime dependencies. An older
published image requires a separately prepared dependency overlay at
`ARBI_KOKORO_EXTRA_DEPS`; that is a local development aid, not an image closure
validation. CUDA 13.1 is mounted by the recipe. The shared GPU lease must cover
the entire service lifetime. The persistent `/cache` mount retains boot caches.
The default host address is `127.0.0.1:17892`; set `ARBI_KOKORO_BIND=0.0.0.0`
when a Docker worker connects through `host.docker.internal`.

Readiness includes required CPU preparation in the API process: the offline
English phonemizer is loaded before admitting speech, and audio-animation
deployments prepare all configured facial processors and their fitting library.
This preparation runs alongside engine boot, including separate API processes.
`/health/ready` returns 503 until both are ready; preparation failures keep the
service unready. Startup preparation time and first-request latency are separate
measurements. Existing checkpoint caches can still shorten subsequent boots.

A standard request uses model `kokoro`, a configured voice such as `af_heart`,
text in `input`, and optional `speed`. Kokoro produces 24 kHz speech. It accepts
American and British English voices; emotion/style instructions are not a
capability of this model. The generic speech route owns response formats and
stream delivery.

The outer config declares checkpoint and phonemizer assets, a voice-name/path
mapping, `default_voice`, `max_batch`, `max_phonemes`, speed bounds, and
`max_audio_seconds`. Asset roles are `checkpoint`, `phonemizer`, and
`voices.<name>`, so ordinary hosted bundles can relocate them. Defaults admit
four requests, 510 phonemes per segment, speeds 0.5–2, and 120 seconds of audio
per segment. Longer input is segmented without dropping text. A predicted
segment beyond the duration bound is rejected before vocoder allocation.

Exact token lengths and speeds share acoustic prediction batches. The vocoder
decodes each member separately and preserves its voice and owned output. Boot
measures the admitted maximum prediction and vocoder allocation, retaining prior
batch outputs while decoding later members. This measurement participates in
ordinary engine memory budgeting; no fixed memory reserve substitutes for it.

## ARBI calls through LiteLLM

The native endpoint accepts standard OpenAI-compatible
`POST /v1/audio/speech` requests. ARBI's backend repository contains the local
preview gateway recipe at `tools/avatar/kokoro-gateway.compose.yml` and its model
mapping at `tools/avatar/kokoro-litellm.yaml` (application integration is reviewed
in [ARBI #4072](https://github.com/arbicity/ARBI/pull/4072)). That recipe declares
LiteLLM alias `arbi-kokoro` for `openai/kokoro` and forwards to this deployment's
`/v1` URL. Keep its authentication values in the private environment file the
recipe names.

Configure the assistant worker with `TTS_MODEL=arbi-kokoro` and
`TTS_BACKEND=kokoro`. `TTS_GATEWAY_URL` can select that separate local gateway for
the preview; production can use the ordinary configured gateway. The Kokoro
profile omits unsupported expressive instructions and uses voice IDs such as
male `am_adam` and female `af_heart`, matching the selected avatar's voice
profile. The native deployment must include each selected voice pack.

For raw audio, request `response_format: "pcm"`; no `stream` parameter is
required. The native endpoint returns segment chunks and reports its 24 kHz
rate in `X-Audio-Sample-Rate`. This is segmentation-based streaming: each
phoneme segment is synthesized before that segment is returned. The tested
LiteLLM 1.103.2 proxy awaits `audio.speech.create`, buffers the response and does
not preserve that rate header. Consequently segment streaming is a native
endpoint capability; do not assume the preview proxy preserves its timing or
headers. ARBI's Kokoro profile uses the known 24 kHz rate when the header is
absent.

For phrase-by-phrase calls, optionally set `trim_pcm16_edge_padding: true` in
this Kokoro component's deployment config (or pass
`--trim-pcm16-edge-padding` to `scripts/prepare_kokoro_deployment.py`). The
public default remains disabled. Completed waveform edges that encode as zero
PCM16 are reduced to 10ms guards before audio is published or handed to facial
animation. Interior pauses and every nonzero PCM16 sample are preserved.
The helper returns a view on the original device; only boundary/finite-status
metadata is read on CPU. All-silent output is rejected explicitly. Boot's
maximum-duration activation probe includes this optional processing. Trimming
final external audio after animation would invalidate their shared clock and
must not be used instead.


# docs/nebius-6036-preflight.md
# #6036 Nebius preflight

This entry point is scoped to the landed #6036 first-parent A/B, on one Nebius UK RTX PRO 6000 with 188 SMs. The plan fixes TP1, Qwen3.8-27B vision6 4bpw and DSpine K=15 with k4v4. Allow for an exact-device cold boot and census on each tree. The required CuTe AOT package covers historical compile misses.

Run this from the repository containing the gate.

```bash
python3 scripts/ci/nebius_6036_gate.py fingerprint /private/6036/plan.json
python3 scripts/ci/nebius_6036_gate.py preflight /private/6036/plan.json --audit /private/6036/audit.json
```

Preflight checks files and evidence offline. Success here is a preparation result. Use the authorized wall-time and budget for the run. The paid path requires a compatible controller tested against this handoff.

For a standalone payload verification before the controller is staged, use only the `PAYLOAD_ARTIFACTS` roles and `PAYLOAD_CHECKS` evidence in a separate plan and audit with the same schemas.

```bash
python3 scripts/ci/nebius_6036_gate.py fingerprint /private/6036/payload.json
python3 scripts/ci/nebius_6036_gate.py payload /private/6036/payload.json --audit /private/6036/payload-audit.json
```

This verifies the runtime, two exact source archives, their native extensions, the model manifest, the target and drafter TKV evidence, and the required CuTe AOT package. A payload-only plan is refused by `launch`.

## Plan and evidence

Use the `CONFIG`, `RUNTIME` and `ARTIFACTS` constants in the gate for the exact names and pinned values. `plan.json` contains:

- `schema` set to `arbi.nebius-6036.plan/1`.
- `config` equal to the gate's `CONFIG`, including both full source SHAs.
- `runtime` equal to `RUNTIME` plus `image`, an OCI ref pinned by SHA-256.
- `wall_minutes` set to the approved positive integer limit, at most 90.
- `cache_policy` set to `cold`.
- `artifacts` mapping each required role to `{"path": "relative/file", "sha256": "lowercase SHA-256"}`. Separate the two extension archives. Use `git archive REV | zstd` for the baseline and candidate so the archive contains the Git PAX commit ID. Use the exact model bundle manifest with object digests.

`audit.json` contains `schema: "arbi.nebius-6036.audit/1"`, `result: "PASS"`, `inputs_sha256` from `fingerprint`, and `checks`. For each check use `subjects` to map the expected artifact roles to the actual SHA-256 values tested. Use `output` to identify the raw report by path and SHA-256 relative to `audit.json`. The gate reads and validates the report content.

| Check | Offline evidence |
| --- | --- |
| `baseline_native_ext`, `candidate_native_ext` | Verify each extracted native extension share under that tree and runtime. Keep a JSONL row per GEMV, activation-prep and served int8 GEMM with `name`, `arch: "120"`, `tier: "share"`, the exact loader `key`, and the positive `cubins_sm120` count from `cuobjdump`. |
| `target_tkv_no_jit` | Capture `tkv.kernels.bake_manifest verify` output for the extracted target archive, with GPUs and network disabled, when all served kernels are found and none compiled or were refused. |
| `drafter_tkv_no_jit` | Capture `scripts/ci/tkv_drafter_preflight.py verify` output for the extracted, same TKV archive. The device-fatbin lines and the final success count must agree. |
| `cute_aot_no_jit` | Use the offline coverage JSON for all 23 CuTe dispatcher keys observed on the exact K15 configuration, including the bypass kernels. Package the same JSON as `coverage.json`, the exported objects under `aot/`, and SM120a device images under `cubin/sm_120a/`. Include each object digest as `object_sha256`. The gate verifies every archive member against the report. |
| `guest_adapter` | Keep verbose dry-run results for `test_exact_verified_plan_handoff` in the actual controller/adapter suite. Test that the launch consumes the supplied paths and exact plan. |
| `deadline_and_teardown` | Keep verbose dry-run results for `test_deadline_and_scoped_teardown` in the actual controller suite, with provider operations stubbed out. Test the owner-approved cap and exact-name cleanup. |

This is an integrity and wiring check. Obtain reports from trusted offline runs on the actual extracted inputs. The gate checks evidence format and bindings and does not certify live GPU execution or the identity of the evidence producer.

## Launch using the authorized limits

```bash
python3 scripts/ci/nebius_6036_gate.py launch /private/6036/plan.json --audit /private/6036/audit.json
```

Before starting a controller the gate checks the evidence, stages private copies, verifies their SHA-256, and checks the two source archive revisions. It invokes only the bound standalone Python `controller` with `--verified-plan FILE`. Use that file's absolute artifact paths, settings and deadline parameters. The controller owns spot-only provisioning, the provider and guest deadlines, hardware verification, and scoped deletion. Its foreground lifetime must cover all use of the temporary verified files.

This entry point applies only to #6036. It does not wrap the general Nebius or RunPod tooling.


# docs/nebius-run.md
# Renting one Nebius GPU for a measurement (the routine path)

`scripts/cloud/nebius_run.sh` rents one RTX PRO 6000 (sm_120, 96 GB), runs a job on it, brings the results back and
deletes the machine. It uses the Nebius engine's own bench tool (arbicity/ansible
`k8s/playbooks/nebius-ephemeral-hold.yml`, run through Semaphore) and nothing of the queue's cloud burst: no bundle, no
plan gate, no approval file, no controller dry-run flag.

    RECIPE=recipe.json scripts/cloud/nebius_run.sh --on-demand --ref origin/<branch> \
        [--job tools/.../job.sh] [--minutes 150] -- KS="1 2 3 7" OFFICIAL=0

What it does:

1. `hold`: a fresh VM from the ephemeral image (driver 580, pinned nvcc 13.1, uv), spot unless `--on-demand`, with a
   guest poweroff timer. No public IP: it is reached over the office WireGuard (10.0.242.x). Needs `ANSIBLE_DIR`, a
   clone of arbicity/ansible with `.vault_pass` (Semaphore's token comes from it).
2. Ships `git archive REF` over ssh (the repo is private and the VM holds no credential) and starts
   `scripts/cloud/vm_run.sh` there (through `scripts/cloud/ssh_run.sh`, see the last section): `uv sync --frozen --extra server` from the tree's lock, checkpoints from
   Hugging Face (`MODELS="repo=dir ..."`, public repos), then the job with `ARBI_ENGINE_RECIPE` set.
3. Fetches `results.tgz` and `extshare.tgz` (the kernels this card compiled) into `$OUT`, then deletes the VM, its
   WireGuard peer and its disk (`nebius-ephemeral-absent.yml`) on every exit path.

Traps measured on the first run (2026-11-23):

- The image's nvcc root lacks the cusparse/cublas headers and an unversioned `libcudart.so`; `vm_run.sh` points
  `CPATH`/`LIBRARY_PATH` at the venv's `nvidia/cu13` and links it. Without that the int8 GEMM JIT fails and every boot
  refuses the EXL3 experts.
- No kernel store holds sm_120 entries here, so the first boot compiles gemv, a_prep, int8 and tkv kernels on the card
  (minutes, billed). Keep `extshare.tgz` and bank it on the 203 mirror's ext-cache for the next run.
- The tkv codec (`--kv-cache-dtype=tkv`) refuses to boot without the calibration corpus, which cannot be fetched from
  upstream here: copy `/mnt/k8scache-mirror/calibration-corpus` to `/mnt/k8scache/calibration-corpus` on the VM.
- A spot VM can vanish with its disk (one did, with no log). Use `--on-demand` for a run that matters.
- A job variable set to the empty string reads as unset in scripts that use `${VAR:-default}`.

## Any other ssh-reachable GPU box (packet.ai, a RunPod pod with sshd, your own)

`scripts/cloud/ssh_run.sh` is the provider-agnostic half of the above: it rents and deletes nothing. Steps 2 and 3 run
unchanged on any machine with the NVIDIA driver, where the login is root or has passwordless sudo.

    TARGET=root@HOST SSH_PORT=22 SSH_KEY=~/.ssh/id_ed25519 RECIPE=recipe.json OUT=./packet-out \
        scripts/cloud/ssh_run.sh --ref <full-sha-or-ref> [--job tools/.../job.sh] -- KS="1 2 3 7" OFFICIAL=0

- `vm_run.sh` uses the image's pinned nvcc when `/opt/nvcc-13.1/nvidia/cu13` exists (Nebius), else the venv's
  `nvidia/cu13` wheel; `NVCC_ROOT` overrides. It installs `uv` when missing.
- A box that bills while idle is yours to stop: the script neither deletes nor powers it off. Stop it once the
  results are in `$OUT`.
- This is a direct ssh run, not the cloud-burst controller: no bundle, no plan gate. Making packet.ai a third provider
  of `gpu-cloud-burst` needs its instance API (create, quote, delete).


# docs/nemotron-transcribe-exl3-conversion.md
# NVIDIA-Nemotron-3.5-Transcribe-30B-A4B: EXL3 4-bit conversion runbook

How to turn the published BF16 checkpoint into an EXL3 4bpw directory that one
24 GB card can serve with `--kv-cache-dtype tkv` (k4v4) and the DFlash2 drafter.
Status: the prepare step is implemented and tested; **the conversion itself has not been run**.

## What the model is, for conversion purposes

`model.safetensors` (≈65 GB) is a NeMo SALM bundle: `llm.*` (language model + MTP head),
`perception.*` (32-layer ASR encoder, 31-layer Sortformer diarizer, projector, mel
filterbank), `ctc_timestamp.*` (word-timestamp head). Only the language model is a
quantization target. It is **the same backbone as Nemotron-3.5-Lightning-30B-A3B**
(52 layers, `hybrid_override_pattern` `MEMEM*EMEMEM*EMEMEM*EMEMEM*EMEMEM*EMEMEMEM*EMEMEMEME`,
byte-identical to the Lightning config's), plus a one-layer MTP head (`*E`: attention +
MoE, reused for depth 2). Perception and CTC stay BF16 (≈1.4 + 0.2 GiB).

## How Lightning's 4bpw checkpoint was made (what this reuses)

`NVIDIA-Nemotron-3.5-Lightning-30B-A3B-exl3-4bpw` carries exllamav3's native
`quantization_config.json` (`version 1.4.2`, `bits 4.09`, `head_bits 6`, calibration
250 rows × 2048 cols, `codebook mul1`, `out_scales always`, with a `tensor_storage` map),
so it came from **exllamav3's own converter**, not from `scripts/exl3_convert_mamba_hybrid.py`:

- exllamav3 (arbi-dev fork, pinned in `uv.lock` / `scripts/exl3-pinned-rev.sh`, rev `e903316`)
  ships `architecture/nemotronh.py` (`NemotronHForCausalLM`: Mamba2, NoPE attention, relu² MLP,
  `BlockSparseMLP` with per-expert `experts.{i}.up_proj/down_proj`, `router_type="dots"`,
  shared expert, `calibration_all_experts = True`) and `architecture/nemotronh_mtp.py`
  (`mtp.layers.N.*`, `qbits_key="mtp_bits"`, default 4 bits). It is layer-by-layer with
  checkpoint/resume in a work directory; the bf16 model is never resident (that is the
  correction the docstring of `exl3_convert_mamba_hybrid.py` does not reflect).
- The entry point in this repo is `arbi-serve convert` (`arbi_serve/convert/convert_to_exl3.py`),
  a wrapper over `exllamav3.conversion.convert_model` (`-i/-o/-w/-b/-hb/-mb/-cr/-cc/-cb/-hq/-d`).
- Input layout it expects: HF `NemotronHForCausalLM`, `backbone.*` + `lm_head`, `hybrid_override_pattern`
  in `config.json`, **per-expert** MoE keys, Mamba `A_log/D/dt_bias` directly under `mixer`.
  The Transcribe checkpoint has none of that (NeMo `llm.model.*`, fused `[E, in, out]` experts,
  `mixer._fp32_params.*`), hence `scripts/prepare_nemotron_transcribe.py`.
- Output tensors per quantized Linear: `.trellis`, `.suh`, `.svh`, `.mul1`; embeddings, norms,
  `gate.*`, `conv1d`, `A_log/D/dt_bias`, `mixer.norm` stay dense. The loader needs no per-arch change
  (`NemotronHModel` swaps a Linear for its EXL3 mirror by the presence of `.trellis`).

Unverified: the `4.09` in Lightning's config. It is not `--bits 4` exactly; the likely cause is
`--hq` (MoE high-quality bumps) raising the average. Use `--hq` and read the achieved bpw from the
resulting `quantization_config.json`.

## Step 1: prepare (CPU, any host with the checkpoint mounted; ~15 min, I/O bound)

```bash
M=/mnt/k8scache/models
python scripts/prepare_nemotron_transcribe.py \
    --src $M/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B \
    --out $M/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-arbi-bf16 --dry-run   # headers only, validates every key
python scripts/prepare_nemotron_transcribe.py --src ... --out ...          # writes ≈62 GiB
```

Output: Lightning-compatible LLM directory (`backbone.*`, `lm_head`, per-expert experts,
`mtp.layers.*` in separate `model-mtp-*.safetensors`), `config.json` (`NemotronHForCausalLM`,
`mtp_hybrid_override_pattern: "*E"`, `num_nextn_predict_layers: 1`), tokenizer files, and
`sidecars/{perception,ctc}.safetensors`, `sidecars/transcribe_config.json`,
`sidecars/alignment_tokenizer/`. The sidecars sit in a subdirectory on purpose: exllamav3's
`*.safetensors` glob and arbi-serve's shard glob only look at the top level. Peak host RAM is
≈2 GiB shard + 1.3 GiB (one layer's fused experts) + the 1.4 GiB perception sidecar.
Dry-run on the real header: 6513 LLM tensors (trunk 58.8 GiB, MTP 2.5 GiB), 85 `_extra_state`
dropped, 852 perception, 41 CTC.

**The tokenizer is split on purpose.** The checkpoint's tokenizer appends `<|audio|>` as id 131072, one past
the 131072-row embedding table (the model looks the placeholder up as row 0 and overwrites it). exllamav3
takes its vocabulary from the tokenizer (`actual_vocab_size = 1 + max id` = 131073), and its default
calibration set includes 20 % rows of `torch.randint(0, actual_vocab_size)` (seed 0, so deterministic): the
first embedding forward fails with `IndexError: index out of range in self`. The prepared directory therefore
carries a conversion tokenizer *without* the out-of-table token at the top level (vocabulary = 131072 =
`config.vocab_size`) and the real one in `sidecars/tokenizer.json`; `--stamp` copies it back, and refuses to
stamp a tokenizer that lacks `<|audio|>`. Nothing is clamped. A directory prepared before this split is
fixed in place (no rerun) with `prepare_nemotron_transcribe.py --retrofit-tokenizer <prepared dir>`.

Key map (full contract in the script docstring): `llm.model.embed_tokens` → `backbone.embeddings`,
`llm.model.norm` → `backbone.norm_f`, `llm.lm_head` → `lm_head`, `llm.model.layers.N.*` →
`backbone.layers.N.*`, `mixer._fp32_params.X` → `mixer.X`, `experts.gate_and_up_projs[e].T` →
`experts.e.up_proj.weight`, `experts.down_projs[e].T` → `experts.e.down_proj.weight`,
`llm.mtp.*` → `mtp.*`, `*._extra_state` dropped.

The `[E, in, out]` transpose is shape-checked (hidden ≠ moe_intermediate: 2688 vs 1856), but
the **direction was inferred from NeMo Automodel's `x @ W` convention, not run against the BF16
model**. Check it once on GPU before trusting the 4-bit result (see Validation, check 1).

## Step 2: quantize (GPU host, NOT box 201)

Candidates:

- **k8s-gpu-206-w1** (dual 4090, 54 GB RAM, `/mnt/k8scache` mounted; `ssh -i ~/.ssh/k8s_rsa arbi-admin@10.2.0.204`,
  then `export KUBECONFIG=~/cluster-config/kubeconfig`; run as a Job on the node, see the `k8s-cluster` skill).
  Preferred. `--devices 0,1` uses both cards.
- 5090 VM `10.1.103.200`: unreachable when last probed (no route to host), and its GPU can drop off the bus.
- 202/203 are busy CI hosts; 201 hosts the CI VMs (no GPU work).

Run inside the arbi-serve image so the pinned exllamav3 fork and `arbi-serve convert` match
(`scripts/run-in-image.sh` or an image with `/mnt/k8scache` bind-mounted):

```bash
M=/mnt/k8scache/models
arbi-serve convert \
    --model $M/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-arbi-bf16 \
    --out   $M/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-exl3-4bpw \
    --work-dir /mnt/k8scache/exl3-conversions/Nemotron-3.5-Transcribe-30B-A4B \
    --bits 4 --head-bits 6 --codebook mul1 --hq \
    --cal-rows 250 --cal-cols 2048 \
    --devices 0,1 --preserve-mtp --no-validate --verbose
# interrupted? same command with --resume --work-dir <same>
cp -r $M/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-arbi-bf16/sidecars \
      $M/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-exl3-4bpw/
# exllamav3 converted it as NemotronH; serve it as the Transcribe model (also restores the real tokenizer
# from sidecars/tokenizer.json, so the served directory knows <|audio|> = 131072):
python scripts/prepare_nemotron_transcribe.py \
    --stamp $M/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-exl3-4bpw
```

Notes on the flags:

- `--codebook mul1`: the wrapper defaults to `mcg`; Lightning is `mul1`, and the served Lightning
  and Transcribe packs are `mul1` (the native MoE legs read either codebook).
- `--head-bits 6` on a 131072×2688 head needs host RAM for its Hessian; the wrapper refuses up front
  (`head_memory_refusal`) rather than dying at the last module. 54 GB is ample; otherwise `--head-bits 16`.
- `--no-validate` because the post-convert `load_model()` smoke test is better run deliberately (Step 3).
- `--preserve-mtp` currently looks for `mtp.fc.*` (the Qwen naming) and logs "no bundled MTP — nothing to
  preserve" for this checkpoint; it is a no-op here, not a failure. The converter itself still quantizes
  `mtp.*` natively at `mtp_bits` (default 4) because exllamav3's `NemotronHConfig` enables its MTP model when
  `mtp.layers.0.eh_proj.weight` exists. Verify `mtp.layers.*.trellis` is in the output index (Step 3, check 0).
  The wrapper should learn the `eh_proj` key (follow-up, not edited here).
- Calibration is the exllamav3 bundled text mix (the same as Lightning). `/mnt/k8scache/calibration-corpus/real-corpus-v2`
  exists if a different corpus is wanted (`--cal-data`, packed rows). **Caveat:** nothing in this calibration
  exercises the `<|audio|>` embedding path; the LLM's input distribution on real requests is
  audio-embedding + instruction text, so the quantization error on those activations is unmeasured. If WER
  regresses (check 3) the principled fix is an audio-conditioned `--cal-data`: encode ~250 mixed-language clips
  with the perception tower, run the BF16 trunk over `[prompt + audio embeds + reference transcript]` rows, pack
  into the safetensors format `sc_trace.py` writes.

Expected cost (estimates, not measurements): output ≈17 GB trunk + ≈0.6 GB MTP (Lightning's checkpoint is 17 GB
with MTP absent), work dir ≈ the output size again, several hours on two 4090s (128 experts × 2 projections × 23 MoE layers
dominate; all experts are activated for the Hessian pass). Disk: the prepared BF16 copy needs 62 GiB on `/mnt/k8scache`
(287 GB free when checked); delete it after the 4-bit result is validated if space is needed
(`prepare` re-creates it in minutes).

## Step 3: validate

Memory budget for a single 24 GB card: trunk ≈17 GB + MTP 0.6 + perception 1.4 + CTC 0.2 + DFlash2 drafter
1.1 (BF16) ≈ 20.3 GB, leaving ≈3 GB for KV (six attention layers, 2 KV heads, tkv k4v4 is tiny), Mamba state
and activations. It fits only if the vocabulary-sized buffers stay small; measure, do not assume.

0. **Structure**: the output index has `backbone.*` trellis tensors for every Linear and expert (23×128×2 expert
   linears + 23 shared + attention + in/out_proj), `mtp.layers.0.{eh_proj,mixer.*_proj}` and
   `mtp.layers.1.mixer.experts.*` trellis tensors, `lm_head` trellis, and
   `quantization_config.json` with `bits ≈ 4.0-4.1`, `codebook mul1`. Load check (GPU, one card):
   `NemotronHModel.from_safetensors(<out>, ...)` binds with no missing/unexpected keys.
1. **Transpose check (do this first, before the long run if possible)**: on the prepared BF16 dir, run one MoE layer
   (layer 1: `experts.0` up → relu² → down) on a random normal hidden state of norm like the model's and confirm
   the output magnitude is sane (relu² of a mis-transposed matrix gives garbage of the wrong scale), or simply
   diff `prepared experts.0.up_proj` against Lightning's published BF16 expert statistics (row-norm histogram).
   The real proof is teacher-forced loss in check 2: a wrong transpose gives NLL ≈ ln(131072).
2. **Teacher-forced reference (text, LLM only)**: score 50 held-out transcripts' tokens with (a) the BF16 prepared dir
   and (b) the EXL3 dir, same prompts, and compare mean NLL and top-1 agreement / KL. BF16 is 63 GB, so (a) needs
   ≥2×40 GB GPUs, or HF `device_map="auto"` with CPU offload on a ≥96 GB-RAM host, or TP2 across two cards plus
   offload; it cannot run on 2×24 GB. Acceptance: ΔNLL ≤ 0.05 nats/token and top-1 agreement ≥ 95%
   (no Lightning-vs-BF16 number is recorded in this repo to anchor these; they are proposals).
3. **Task level (the check that matters)**: WER on ≥100 English clips (LibriSpeech test-other slice) and ≥100 clips
   from three other languages (FLEURS), EXL3-served-by-arbi vs the model card's Open ASR numbers (README
   "Benchmark Results"); BF16 reference runs are not needed for this one. Also the speaker-tagged prompt
   (`<spk:N>` output) and one translation prompt.
4. **Spec decode**: acceptance rate with MTP depth 2 and with DFlash2 (K=7) on the same clips; the drafter is
   `DFlash2DraftModel`, `target_layer_ids [1,5,19,29,41,51]`, borrows `embed_tokens`/`lm_head` from the target.

## Open issues

- Transpose direction unverified against real weights (check 1/2).
- `--preserve-mtp` does not recognise `mtp.layers.0.eh_proj`; silent no-op.
- Achieved bits (4.09 for Lightning) and conversion wall time are unmeasured for this model.
- Audio-conditioned calibration is not available in the converter; quality on real audio prompts is the risk.
- `config.json` `eos_token_id` is 2 in `llm_backbone/config.json` but `generation_config.json` says `[11]`
  (the prompt format's end token); the serving side must use the generation config.

## Speculative decoding on a 24 GB card: MTP or DFlash2

Both drafters work on the composite (`tests/test_nemotron_transcribe_spec_decode.py`): `mtp_enabled` is forwarded,
the marker layer is last, the head ties the model's own embedding and `lm_head`, the DFlash driver finds the
embedding at `backbone.embeddings`, and the drafter's taps `[1,5,19,29,41,51]` and `num_target_layers: 52` match
the 52-layer stack. They are alternatives, not a pair: with a DFlash drafter selected `mtp_enabled` is false and the
bundled head is neither loaded nor given a KV slab.

One defect was fixed on the way: the MTP KV-fill pairs each hidden state with the NEXT position's embedding, and at
an `<|audio|>` position it used embedding row 0 (the placeholder id 131072 is past the table). It now uses the
tower's row, as the verifier saw it (`NemotronHModel._mtp_fill_embeds`, overridden by the composite). DFlash needs
no equivalent: it taps hidden states, and the ids it embeds (anchor token, mask token 990) are generated tokens.

**Memory arithmetic (estimates, one 24 GB card, about 23.3 GB usable at `--gpu-memory-utilization 0.99`).**

| item | size | note |
|---|---|---|
| EXL3 4bpw trunk | about 17.0 GB | Lightning's 4bpw checkpoint is 17 GB |
| perception tower (bf16, replicated) | 1.4 GB | 733.6M parameters; the CTC head (0.2 GB) is not loaded |
| graphs, activations, JIT reserve | about 1 to 1.5 GB | |
| recurrent state | about 49 MB per sequence | 23 Mamba layers, fp32 SSM state |
| KV | 1584 B per token at k4v4 | 6 attention layers x 2 KV heads x 128; 65k tokens x 8 sequences is 0.8 GB (3.2 GB at bf16) |
| verify-rollback snapshots | (K+1) x batch x 49 MB | needed by ANY drafter on a hybrid target: K=2, batch 8 is 1.2 GB; K=7, batch 8 is 3.1 GB |
| MTP head | 2.7 GB if left bf16; about 0.7 GB if the converter quantizes `mtp.*` | check for `mtp.layers.*.trellis` in the output |
| DFlash2 drafter | 1.1 GB bf16 (570.6M parameters) | its own small draft KV on top |

What is left for speculation after weights and reserve is about 3.5 GB at batch 8. MTP at bf16 head weights plus K=2
snapshots is 3.9 GB: it does not fit at batch 8, and it fits at batch 4. DFlash2 at K=7 is 1.1 + 3.1 = 4.2 GB at
batch 8 and fits at batch 4 (2.7 GB). With a quantized MTP head the picture reverses: 0.7 + 1.2 = 1.9 GB.

**Default recommendation (before any measurement):** MTP, K=2, provided the converted checkpoint carries a quantized
head; it is the cheapest verify (3 tokens per sequence through the MoE), and NVIDIA's own H100 numbers rank it first
(RTFx 410 for MTP2 against 340 for DFlash2 K=7, 270 for MTP8). If the head stays bf16, serve DFlash2 K=7 at batch 4
instead: the smaller drafter leaves room for the K=7 snapshots. Neither number is measured on this stack; the
decision rule is accept length and RTFx on `tools/transcribe_eval.py` (LibriSpeech and FLEURS, prefix cache off).
Note that Lightning's DSpark drafter was slower than no drafter at c1 on open-ended chat text (accept 1.08 to 1.36);
transcription output is predictable from the audio, so expect a different regime, but do not assume it.


# docs/nemotron-voicechat-exl3-conversion.md
# NemotronVoiceChat-11B EXL3 backbone conversion

How the STT backbone of `NVIDIA-NemotronLabs-VoiceChat-11B` (a Mamba-2 +
attention + standalone-MLP hybrid, see `arbi_serve/models/nemotron_h.py` /
`nemotron_voicechat.py`) was EXL3-quantized to fit the whole composite
model — backbone + perception tower + TTS backbone + audio codec — on a
single 24 GB GPU. Companion to
[quant-support-matrix.md](quant-support-matrix.md); for the general EXL3
reference see [exl3-5120x17408-family-2026-08-31.md](exl3-5120x17408-family-2026-08-31.md),
[exl3-wide-shape-family-2026-08-31.md](exl3-wide-shape-family-2026-08-31.md)
and [prefill-gemm-precision-2026-08-30.md](prefill-gemm-precision-2026-08-30.md).
This doc is the Mamba-hybrid-specific detail.

## Why the ordinary `arbi-serve convert` path doesn't work here

`arbi_serve/convert/convert_to_exl3.py` wraps
`exllamav3.conversion.convert_model`, which builds exllamav3's OWN
reference `Model` (from `exllamav3/architecture/*.py`) to drive the
calibration forward pass. `exllamav3.model.config.Config.from_directory`
hard-asserts the checkpoint's `architectures[]` string is a registered
`exllamav3.architecture.*` entry — and **exllamav3 ships zero Mamba-2 SSM
architectures** (verified: no `mamba`/`ssm`/`nemotron` hits anywhere in the
installed package; its "hybrid" archs, `olmohybrid.py` / `qwen3_next.py`,
are GatedDeltaNet linear-attention, not real Mamba-2 recurrence). This is a
genuine, verified gap in exllamav3 itself, not "nobody validated it yet."

`scripts/exl3_convert_mamba_hybrid.py` routes around it: it calls
exllamav3's low-level, architecture-agnostic trellis quantizer
(`exllamav3.modules.quant.exl3_lib.quantize.quantize_exl3` — the exact
LDLQ + Hadamard-rotation routine `exllamav3.modules.linear.Linear
.convert_exl3` calls per-tensor) directly, per target `nn.Linear`-shaped
weight, sourcing calibration Hessians (`H += X^T @ X`, mirroring
`Linear.capture_H`) via forward hooks on arbi-serve's OWN already-correct
`NemotronVoiceChatBackboneModel` forward — real Mamba-2 recurrence, real
GQA attention, no reimplementation needed.

## The loader side needed ZERO new code

`NemotronVoiceChatBackboneModel.from_safetensors` already routes through
the generic, architecture-agnostic `prepare_dims_for_quant` /
`_apply_quant_and_materialize` / `apply_quant_if_present` /
`_filter_for_quant` machinery — the SAME code path Qwen3.5's GDN-hybrid
EXL3 checkpoints use. It swaps each Linear-shaped module for its EXL3
mirror purely by checking whether that module's checkpoint path carries a
`.trellis` tensor, so a MIXED checkpoint (some linears quantized, some left
dense) loads with no per-arch change. `weight_quants_supported` in the
recipe yaml (`arbi_serve/recipes/*.yaml`) is **documentation, not
enforcement** — `recipes/loader.py` parses it and nothing else reads it
(see `unlimited-ocr.yaml`'s identical caveat on this same field) — so the
old `nemotron-h.yaml: weight_quants_supported: [bf16]` undersold what the
loader already supported. Updated to `[bf16, exl3]`.

## One real geometry constraint: 128-alignment, not Mamba

The task's a-priori hypothesis was that Mamba-2's fused `in_proj`/
`out_proj` might violate trellis-format assumptions. They don't — both are
plain `ColumnParallelLinear`/`RowParallelLinear` 2-D GEMM weights (see
`nemotron_h.py`'s `_add_mamba2_keys` docstring), and EVERY dimension in
this backbone's attention + Mamba projections lands on a multiple of 16
(the trellis packing granularity).

The REAL constraint, found live: EXL3's Hadamard-rotation preprocessing
(`exllamav3...quantize.py`: `had_k = had_n = 128`, applied on BOTH axes via
`blockwise_preapply_had_l_`/`_r_`) needs a *stricter* 128-divisibility on
both `in_features` and `out_features` (`AssertionError: n % had_dim == 0`
when violated). NemotronVoiceChat-11B's `intermediate_size=15680`
(15680 / 128 = 122.5) violates this for the MLP-only layers' `up_proj`
(out=15680) / `down_proj` (in=15680) — every OTHER target in this backbone
(`hidden_size=4480`, Mamba's fused projections, `vocab_size=131072`)
already lands on a 128 multiple. **Nemotron-3-Nano-4B's own
`intermediate_size=12544` (=128×98) clears this on every layer** — so this
is a per-checkpoint geometry fact about VoiceChat-11B's specific dims, not
a NemotronH-architecture-wide limitation. `_target_linears()` in the
conversion script computes this generically (both axes rounded up to the
next 128 multiple) and logs exactly which tensors it zero-pads.

**Update (2026-08-08)**: zero-padding `up_proj`'s output / `down_proj`'s
input to the next 128 multiple (15744) before quantizing is now
implemented — relu² maps the padded zero rows to zero, so it's lossless —
and the EXL3 loader now supports a trellis whose padded dim differs from
the dense module's declared in/out_features (the `EXL3Backend` lm_head-
padding comment below described this as refused; it now works for the
MLP case). See "Follow-up: closing the MLP 128-alignment gap" below for
the full design + measured results.

## VRAM ceiling for the two heads (a box limitation, not a format one)

`lm_head`/`function_head` (`131072 × 4480`, the single biggest tensors in
the backbone) failed to quantize even with a dedicated retry pass on an
otherwise-idle GPU1: materializing their fp32 working copy (2.19 GB) plus
`ldlq`'s internal buffers alongside the ~18 GB resident bf16 backbone
pushed this process to ~22 GB against the 23.52 GB this box's GPU1
actually reports usable — a real ceiling on THIS box for THIS
combination, confirmed by retrying with zero other GPU1 tenants present
and still OOMing. Both heads shipped bf16 in the final checkpoint (dense
passthrough — no loader change needed, see "mixed checkpoint" above). A
follow-up on a box with more free VRAM at conversion time (or a version of
this script that frees more of the resident model before the head tensors)
should close this.

## What actually got quantized

**(Historical — the FIRST pass, before the 2026-08-08 padding follow-up
below closed the 128-alignment gap; kept for the record. See "Follow-up:
closing the MLP 128-alignment gap" for the current 120/122 state.)**

Of 122 `nn.Linear`-shaped weights in the backbone:

- **50 skipped (128-alignment)**: `up_proj`/`down_proj` in the 25 MLP-only
  layers — left bf16.
- **2 skipped (OOM ceiling)**: `lm_head`, `function_head` — left bf16.
- **70 quantized to EXL3** (4 bpw, `mcg` codebook): every attention
  `q_proj`/`k_proj`/`v_proj`/`o_proj` (4 attention layers) and every Mamba-2
  `in_proj`/`out_proj` (27 Mamba layers) — **97% of the backbone's total
  Linear-shaped param count** by the accounting that matters (Mamba's
  fused projections dominate: ~4.2 B of the ~8.9 B target params).

## Reproducing the conversion

> **Note added 2026-09-13 (`integ/flag-cull`).** `ARBI_COMPILE_OFF` no longer
> exists as an env var: `b05697441` turned it into the engine-owned eager
> window `force_compile_off()` / `compile_forced_off()` in
> `arbi_serve/runtime_flags.py`. The conversions recorded in this document were RUN under
> `ARBI_COMPILE_OFF=1` and the spellings are left as they were run.
> `ARBI_COMPILE_ON=0` is NOT a re-spelling of them — it is a different boot:
> it skips the trampoline install altogether, is an axis of
> `_compile_cache_key` (`compile/cache.py`), and hard-refuses
> `prefill_capture=piecewise` (`config_server.py`). Reproducing these numbers
> today means opening the eager window from inside the process, not setting an
> env var.

```bash
# GPU1 only — GPU0 on this box runs another tenant's production workload,
# never touch it. flash_attn on this box is installed but ABI-broken
# (undefined symbol in flash_attn_2_cuda against the resident torch build)
# — the driver stubs it automatically (see its _stub_and_import_exllamav3),
# same class of issue as mamba_ssm elsewhere this session. ARBI_COMPILE_OFF
# forces eager execution so the forward-hook Hessian capture reliably fires
# (a torch.compile'd block can otherwise dodge module-level hooks). HF_HOME
# must point at a cache that already has allenai/c4 (never downloads).
# NOTE: `.venv/bin/python` below is what the original run used. The host venv
# is not maintained (CLAUDE.md), and this script imports
# `exllamav3.modules.quant.exl3_lib` — the arbi fork, pinned by SHA in
# pyproject.toml. Run it in the image so the fork is the pinned one; a host
# venv carries whatever was last installed there, which is the wrong-fork
# failure the boot guard exists to catch.
CUDA_VISIBLE_DEVICES=1 ARBI_COMPILE_OFF=1 HF_HOME=/mnt/k8scache/hf \
  .venv/bin/python scripts/exl3_convert_mamba_hybrid.py \
  --model /mnt/k8scache/models/NVIDIA-NemotronLabs-VoiceChat-11B-arbi \
  --out /mnt/k8scache/models/NVIDIA-NemotronLabs-VoiceChat-11B-exl3-4bpw \
  --bits 4.0 --head-bits 6.0 --cal-rows 16 --cal-cols 1024 --codebook mcg \
  --batch-h-budget-gb 4 --device cuda:0
```

(As of the 2026-08-08 follow-up below, this same command now also
zero-pads and quantizes the 25 MLP layers automatically — no new flag —
producing 120/122 quantized linears instead of 70/122; use a different
`--out` dir to keep both checkpoints around.)

Calibration: c4, 16 rows × 1024 tokens (16K tokens total) — a deliberately
small/fast first pass per this task's own "prove the pipeline end-to-end,
document a higher-quality follow-up" allowance, not exllamav3's own
250-row/2048-col default. `--batch-h-budget-gb` bin-packs targets into
calibration passes bounded by simultaneously-resident fp32 Hessian size
(all 122 targets' Hessians at once would need ~42 GB host RAM — more than
this box's spare capacity under the resident bf16 model).

Took **~38 minutes** end to end (model load ~45 s, calibration + quantize
~15 min across 4 passes, safetensors write ~22 min — the write phase is
slow because the OUTPUT directory is a drop-in replacement for the full
44 GB composite checkpoint, not just the backbone: `NemotronVoiceChatModel
.weight_map()` loads the backbone's linears from THIS file and the
perception/TTS/codec pieces from the SAME file, so everything not
quantized here is copied through dense unchanged).

### Real bugs this surfaced (fixed in the script, worth knowing if extending it)

1. `quant_args["K"]` must be a plain `int` — `exllamav3`'s
   `get_temp_buffers` does `65536 >> K` (bit-shift), and the top-level
   `--bits` float (e.g. `4.0`) raises `TypeError` unshifted.
2. `quantize_exl3`'s `swap_to_device` parameter looks like a ready-made
   CPU-offload OOM fallback but isn't one — `ext.quantize_tiles` (the
   compiled CUDA extension op) is CUDA-only; passing
   `swap_to_device=torch.device("cpu")` crashes with `RuntimeError:
   CUDAGuardImpl initialized with non-CUDA DeviceType: cpu`. The only real
   OOM lever is reclaim-and-retry ON the GPU, with a per-tensor skip
   (leave bf16) as the last resort so one contended tensor doesn't crash a
   72-tensor job.
3. The retry must wrap the fp32 weight materialization too, not just the
   `quantize_exl3()` call — a 2.19 GB `lm_head` fp32 copy can itself OOM
   under contention; an earlier version only wrapped the quantize call and
   crashed the whole job on exactly that.
4. `flash_attn` on this box is installed but ABI-broken, not absent —
   `arbi_serve.convert.convert_to_exl3`'s own stub detection uses
   `importlib.util.find_spec` (package-installed check), which doesn't
   catch this; the driver attempts a real import first and stubs on
   failure.

## Results (measured, 2026-08-08 — first pass, 70/122 quantized)

**(Historical — see "Follow-up: closing the MLP 128-alignment gap" for the
current 120/122 numbers; kept here for the before/after comparison.)**

**Coherence** — teacher-forced top-1 next-token agreement vs the bf16
source, 5 prompts × 32 tokens (160 positions total), same methodology as
`arbi_serve/convert/_convert_validate_forward.py`'s bf16-agreement gate:

| Prompt | Agreement |
|---|---|
| "The capital of France is" | 31/32 = 96.9% |
| "Explain how photosynthesis works…" | 31/32 = 96.9% |
| "def fibonacci(n):" | 31/32 = 96.9% |
| "Once upon a time, in a small village," | 32/32 = 100.0% |
| "The three laws of thermodynamics are" | 30/32 = 93.8% |
| **Overall** | **155/160 = 96.9%** |

Free-running greedy continuations from both models are fluent and
semantically on-topic (e.g. EXL3: *"...Paris is the most populated city in
France and has been the capital of the country for centuries..."* vs bf16's
near-identical phrasing) — comfortably clears "still coherent," the bar
this check is for (EXL3 is not, and isn't expected to be, bit-identical to
bf16).

**VRAM** (`nvidia-smi`/`torch.cuda.mem_get_info` on GPU1, 24564 MiB card,
idle before each load):

| Configuration | VRAM used | Free |
|---|---|---|
| bf16 backbone alone | 21.77 GB | 3.48 GB |
| **EXL3 backbone alone** (70/72 linears quantized) | **15.57 GB** | 9.68 GB |
| **Full composite** (EXL3 backbone + perception tower + TTS backbone + audio codec, `ARBI_ENABLE_AUDIO=1`) | **18.32 GB** | **6.94 GB** |

Backbone-alone saving: **6.2 GB** (~28%) — short of the ~9-10 GB backbone
target hoped for going in, because the 25 MLP layers (~3.5 B params, ~7 GB
bf16) and the two heads (~1.2 B params, ~2.35 GB bf16) stayed dense for the
reasons above; closing either gap (128-alignment padding, or converting on
a box with more spare VRAM for the heads) would recover most of the
shortfall. **The actual point of the exercise is still satisfied**: the
full composite model that matters for serving loads in 18.32 GB, leaving
6.94 GB of real, measured headroom on a 24 GB card for activations/KV —
this was a live load of `NemotronVoiceChatModel.from_safetensors(...,
device="cuda:0")` with the audio path on, not an estimate.

## Follow-up: closing the MLP 128-alignment gap (2026-08-08, issue #1308 item 3)

The "zero-pad MLP `up_proj`/`down_proj`" follow-up below is now DONE — all
122 Linear-shaped weights except the two OOM'd heads are quantized (120/122).

**Where the padding lives** — split cleanly across two layers, neither of
which needed `arbi_serve/models/nemotron_h.py` / `nemotron_voicechat.py` (or
`ModelDims.intermediate_size`) to change at all:

- **Conversion time** (`scripts/exl3_convert_mamba_hybrid.py`): `_target_linears`
  no longer skips a misaligned target — it computes `padded_in`/`padded_out`
  (real dim rounded up to the next 128 multiple: 15680 → **15744** = 123×128,
  *not* 15872/124×128 — 15680/128 = 122.5, ceil is 123) and `_quantize_one`
  zero-pads the transposed weight on the misaligned axis/axes before calling
  `quantize_exl3`, plus — only when `in_features` is the padded axis (`down_proj`)
  — embeds the REAL captured Hessian into the top-left block of a zero
  `(padded_in, padded_in)` matrix (exact, not approximate: the padded input
  channels are always identically zero in the real forward, so their true
  covariance with everything is exactly zero). The resulting trellis/suh/svh
  ship at the padded width.
- **Load time** (`arbi_serve/weight_quant/exl3/linear.py`): `EXL3LinearBase`
  now tracks a `_kernel_in_features`/`_kernel_out_features` pair alongside the
  declared (real) `in_features`/`out_features`. `exl3_load`'s shape asserts
  (`_resolve_kernel_dim`) accept a trellis whose block-rounded dim is EXACTLY
  the declared dim rounded up to the next 128 — nothing else — and only at
  `tp_size == 1` (this backbone is TP=1-only anyway; a padded+TP>1 combination
  raises `NotImplementedError` rather than silently mis-slicing, since the TP
  subclasses derive block ranges from the declared global dim). `_exl3_forward`
  zero-pads the input activation up to the kernel width before the trellis GEMM
  (down_proj) and truncates the kernel's output back to the declared width
  after it (up_proj) — both correctness arguments are exact, not
  quantization-noise-dependent: a zero-padded activation column contributes
  exactly zero regardless of what garbage the padded weight rows decode to,
  and a truncated output column is simply never read. `dequantized_weight()`
  slices the same way. `EXL3Backend.register_for_direct_slab` (`backend.py`)
  now sources the cold-boot direct-slab buffer size from the trellis's own
  on-disk header shape at `tp_size == 1` (previously always `lin.in_features`/
  `out_features`) so the slab is sized for what `bind()` actually writes; a
  no-op for every existing unpadded checkpoint.

**Re-running the conversion**: same command as below, new `--out` dir
(`...-exl3-4bpw-padded`) — the tool doesn't support incremental/resume
conversion (a fresh full pass), and the padded-MLP path is exercised for
every target uniformly (a no-op for the 70 already-aligned ones). Took
**~30 minutes** end to end on 10.2.0.206 GPU1 (quantize phase 1721 s across
11 calibration batches + a ~30 s safetensors write — much faster than the
original run's ~22 min write, likely warm page cache on the second pass).
One operational note: **a concurrent tenant on that shared box killed the
first attempt** (`sudo kill -9`) while reclaiming both GPUs' clocks for its
own benchmark — not a bug in this pipeline; the retry on the same command
succeeded cleanly and deterministically reproduced the first attempt's
per-tensor `proxy_err` values up to the point of the kill.

**Tensor inventory** (`quantization_config.json`): `quantized_linears`: 120
(was 70), `quantized_linears_had_padded`: 50 (all 25 MLP layers'
`up_proj`+`down_proj`), `dense_bf16_128_alignment`: `[]` (was the 50 MLP
linears), `dense_bf16_oom`: `["stt_model.function_head", "stt_model.lm_head"]`
(unchanged — still out of scope, see the VRAM-ceiling section above).

**Coherence** (same teacher-forced top-1 methodology as below, 5 prompts × 32
tokens, 160 positions total — bf16 greedy continuation as reference, EXL3
re-evaluated over the same fixed sequence):

| Prompt | Agreement |
|---|---|
| "The capital of France is" | 31/32 = 96.9% |
| "Explain how photosynthesis works…" | 30/32 = 93.8% |
| "def fibonacci(n):" | 32/32 = 100.0% |
| "Once upon a time, in a small village," | 29/32 = 90.6% |
| "The three laws of thermodynamics are" | 30/32 = 93.8% |
| **Overall** | **152/160 = 95.0%** |

A ~2-point drop from the pre-padding run's 96.9% (155/160), consistent with
50 more linears now carrying real quantization noise instead of being exact
bf16 — still comfortably clears "coherent," the bar this check is for.

**VRAM** (`torch.cuda.mem_get_info` cross-checked against an independent
`nvidia-smi` poll — both agreed exactly, GPU1 on 10.2.0.206, 23.54 GB usable,
idle before each load):

| Configuration | VRAM used |
|---|---|
| bf16 backbone alone (unchanged) | 21.77 GB |
| EXL3 backbone alone, 70/122 quantized (pre-padding) | 15.57 GB |
| **EXL3 backbone alone, 120/122 quantized (padded MLP)** | **9.53 GB** |
| Full composite, 70/122 EXL3 (pre-padding, `ARBI_ENABLE_AUDIO=1`) | 18.32 GB |
| **Full composite, 120/122 EXL3 (padded MLP, `ARBI_ENABLE_AUDIO=1`)** | **11.69 GB** |

**6.63 GB** additional saving on the full composite figure that actually
matters for serving (18.32 → 11.69 GB) — almost exactly the "~7 GB more"
this doc's own follow-up section estimated. The full composite model now
loads in under 12 GB, leaving **~11.8 GB** of headroom on a 24 GB card for
activations/KV, roughly double the pre-padding figure.

Reproduction scripts (removed from the tree with the non-public material in
#1799; not re-executable here):
`_exl3_padded_mlp_load_smoke.py` (load + one forward, asserts every padded
MLP linear reports its real declared shape), `_exl3_padded_mlp_coherence_check.py`
(the table above), `_exl3_padded_mlp_vram_check.py` (the table above — loads
once, holds the process so `nvidia-smi` can cross-check).

A combined EXL3+TKV real-turn crash first suspected this padding path
(the 2026-08-08 perf-baseline notes, since removed in #1799) — root-caused and
fixed as an unrelated arbi-serve dispatch-registry bug in
`nemotron_voicechat_stt_step.py`, not this padding logic; see that note's
update for the full story and re-verification of the coherence/VRAM
numbers above against the fix.

## What's left (follow-ups, not blocking)

- Quantize `lm_head`/`function_head` on a box with more free VRAM at
  conversion time (or restructure the driver to release more of the
  resident bf16 model before materializing the head's fp32 copy) — would
  recover ~1-1.5 GB more (6 bpw vs their bf16 size). Unaffected by the
  padding follow-up above — same OOM, same root cause, still open.
- A higher-quality calibration pass (more rows/cols, closer to
  exllamav3's own 250×2048 default) once the pipeline's correctness is
  trusted — this run used a deliberately small 16×1024 corpus to keep the
  first end-to-end pass fast.
- TP>1 support for a Hadamard-alignment-padded EXL3 linear
  (`EXL3ColumnParallelLinear`/`EXL3RowParallelLinear`'s TP block-range math
  derives offsets from the declared, unpadded global dim — see
  `EXL3LinearBase._resolve_kernel_dim`'s `NotImplementedError`) — not needed
  for this backbone (TP=1-only already, per its own `from_safetensors`), but
  would matter for a future padded checkpoint served at TP>1.

## Bit-width comparison: 4bpw vs 6bpw (2026-08-08)

Coherence at a fixed 4 bits/weight got measured three times as backbone
coverage increased — 70/122: 96.9%, 120/122 (padded MLP): 95.0%, +TKV
KV-cache quant on top: 94.6% — a real degradation trend, not noise. That's
evidence 4bpw itself was too aggressive for this checkpoint, not that lower
coverage was better. This section re-runs the SAME 120/122-coverage
conversion at 6 bits/weight — everything else identical (codebook `mcg`,
`--cal-rows 16 --cal-cols 1024`, `--head-bits 6.0`, only `--bits` changed)
— to test whether more bits per weight is the right lever, with real
measured numbers rather than an assumption.

**Command** (GPU1 on `10.2.0.206`, the same box+GPU this doc's own
padded-MLP follow-up used — GPU0 there runs another tenant's live
workload, confirmed busy at conversion time, never touched):

```bash
CUDA_VISIBLE_DEVICES=1 ARBI_COMPILE_OFF=1 HF_HOME=/mnt/k8scache/hf \
  .venv/bin/python scripts/exl3_convert_mamba_hybrid.py \
  --model /mnt/k8scache/models/NVIDIA-NemotronLabs-VoiceChat-11B-arbi \
  --out /mnt/k8scache/models/NVIDIA-NemotronLabs-VoiceChat-11B-exl3-6bpw \
  --bits 6.0 --head-bits 6.0 --cal-rows 16 --cal-cols 1024 --codebook mcg \
  --batch-h-budget-gb 4 --device cuda:0
```

Same 120/122 coverage as the padded 4bpw run — `lm_head`/`function_head`
hit the identical fp32-workspace OOM ceiling and stayed bf16 (identical
`dense_bf16_oom` entries in `quantization_config.json`). Took **~30
minutes** end to end: quantization phase 1661.9 s across 11 calibration
passes, safetensors write ~1m40s (bigger trellis payload than 4bpw but a
fast write — likely warm page cache).

**Coherence** — same methodology, same harness, same 5 prompts × 32 tokens
(160 positions), unmodified coherence-check harness:

| Prompt | 4bpw (120/122) | 6bpw (120/122) |
|---|---|---|
| "The capital of France is" | 31/32 = 96.9% | 32/32 = 100.0% |
| "Explain how photosynthesis works…" | 30/32 = 93.8% | 32/32 = 100.0% |
| "def fibonacci(n):" | 32/32 = 100.0% | 32/32 = 100.0% |
| "Once upon a time, in a small village," | 29/32 = 90.6% | 32/32 = 100.0% |
| "The three laws of thermodynamics are" | 30/32 = 93.8% | 31/32 = 96.9% |
| **Overall** | **152/160 = 95.0%** | **159/160 = 99.4%** |

**VRAM** (`torch.cuda
.mem_get_info` cross-checked against an independent `nvidia-smi` poll
during the hold window — both agreed exactly, GPU1 on `10.2.0.206`, 23.54
GB usable, idle before each load):

| Configuration | 4bpw (120/122) | 6bpw (120/122) | Delta |
|---|---|---|---|
| EXL3 backbone alone | 9.53 GB | 11.43 GB | +1.90 GB |
| Full composite (`ARBI_ENABLE_AUDIO=1`) | 11.69 GB | 13.57 GB | +1.88 GB |

Full composite at 6bpw leaves **~9.97 GB** of headroom on the 24 GB card
(23.54 GB usable) for activations/KV — comfortably inside the budget this
whole effort targets (see "VRAM ceiling" above), and still noticeably more
headroom than the ORIGINAL pre-padding 4bpw pass had at less than half the
coverage (6.94 GB free, 70/122 quantized).

**5bpw**: attempted as a middle point (same command, `--bits 5.0`) — the
conversion was progressing normally (batch 10/11 of 11 calibration passes,
~26 minutes in, on pace with the 6bpw run's own ~28-minute quantize phase)
when it was deliberately stopped before completion: the 4bpw/6bpw
comparison had already produced a decisive, unambiguous result, and
finishing a third data point wasn't worth the extra GPU time it would have
burned. No 5bpw coherence/VRAM numbers exist. The partial output directory
was removed and GPU1 confirmed idle afterward (`nvidia-smi`: 1 MiB used,
0% util, process confirmed killed).

**Recommendation**: ship **6bpw** as the default for this backbone, not
4bpw. The 4bpw degradation trend (96.9% → 95.0% → 94.6% as coverage/KV-quant
increased) was a real signal that 4 bits/weight left too little error
margin once combined with full MLP coverage and (separately) TKV KV-cache
quantization — 6bpw's 99.4% teacher-forced agreement is within noise of
"exact" and gives much more headroom before those additional error sources
erode it further. The cost is small and easily affordable inside the 24 GB
budget: +1.88 GB on the full composite (11.69 → 13.57 GB), still leaving
~10 GB free for activations/KV. There's no real quality/VRAM tension here
that would argue for 4bpw — its only advantage is VRAM headroom the budget
doesn't actually need.


# docs/ocr-models.md
# The OCR models

Status: served by `python -m arbi_serve ocr` since 2026-10-20, and the only model family:
the Surya 0.17-era family, its code and its dependencies were removed afterwards. The parser
pins these models' ids (ARBI `ocr_client.py`); a mismatch fails its identity check
at the first request.

## Why

`ocr` used to serve the Surya 0.17-era checkpoints. Their licence is the Datalab
modified OpenRAIL-M: commercial use under $2M revenue/funding only, plus a non-compete clause.
The table checkpoint `table_recognition/2025_02_18` is CC-BY-NC-SA-4.0. We cannot ship these
weights to clients. The replacement is a stack of Apache-2.0 code and weights behind the same parser wire contract:

| Phase | Model | Weights | Licence |
|---|---|---|---|
| layout | PP-DocLayoutV3 + `list_item` fine-tune r4 (ARBI #2883) | `/mnt/k8scache/paddle/pp-doclayoutv3-listitem/r4` (sha256 ad7cfcf2…) | Apache-2.0 base; fine-tune data DocLayNet CDLA-Permissive-1.0 |
| line detection | PP-OCRv6 medium det | `PaddlePaddle/PP-OCRv6_medium_det_safetensors` | Apache-2.0 |
| recognition | PP-OCRv6 medium rec (CTC) | `PaddlePaddle/PP-OCRv6_medium_rec_safetensors` | Apache-2.0 |
| tables | PP-LCNet table cls, RT-DETR-L wired/wireless cell det, SLANeXt wired/wireless | `PaddlePaddle/*_safetensors` | Apache-2.0 |
| formulas | none | – | – |

All of these run as arbi-serve's own forward-only torch modules (`arbi_serve/models/paddle`,
ported from the Apache-2.0 `transformers` implementations), loaded from the HF-format
checkpoints with a strict key match. Their outputs are bit-identical to transformers' in fp32
(`tests/ocr/test_native_*`, which import transformers as the reference; it is a dev
dependency only). No Paddle runtime, no transformers at serving time, no GPL, no Datalab
weights. There is no formula model: an Equation block is read by the text recognizer
line by line, and one that holds no text stays an image (the parser already does this,
`parser_equations.equation_html`).

The behaviour is ARBI's reference server (ARBI #2998, since removed; its parity scorers stay in
`parser-service/tools/ocr_parity`), run as `--formula 0`, XY-cut off, layout fp32 one page per forward, ported; its
tables were PaddleOCR's `TableRecognitionPipelineV2` on the Paddle runtime, reimplemented here on
the HF torch models.

## How it plugs into arbi-serve

### 1. The `forward` task (engine, generic)

The family runs on the engine's own continuous batching: the scheduler, its admission and its
steps, the same path the LLMs take. Nothing in the engine batches for
it alone.

* **`--task forward`** (`engine/serving_tasks.py`) joins the prefill-only tasks (`embed`,
  `rerank`, `decide`). A request is a prompt that is prefilled once and answered from that
  prefill, so it gets their boot sizing (a bf16 `tkv-bypass` pool sized for one in-flight
  batch, no decode loop, no sampler, no decode capture), their admission fan-out allowance and
  their step (`run_step/embed.embed_step`). Its tap (`hidden_tap.ForwardTap`) reads nothing:
  the model answers.
* **Media.** A request carries its pixels as `multimodal.inputs.TensorFeatures` (named host
  tensors plus str meta), which cross the process boundary as zero-copy tensor frames
  (`engine/proc/media.py`). Its prompt is one placeholder token per item.
* **The batched forward is the media encoder.** The batch build hands every prefill row of a
  step that carries one modality to that modality's `MediaBinding.encode_batch` in one call
  (`runtime/multimodal_merge._encode_batched`). Each task is a modality, so each step runs one
  forward per task over the rows of every client in it. The forward leaves the request's raw
  outputs on its features (`TensorFeatures.outputs`).
* **The answer leaves on the finish record.** `finish_extras` (`engine/finish_extras.py`)
  copies the outputs to pinned host memory on a side stream and sends them on
  `FinishOut.extras`; the API child turns them into the result.
* **Weightless.** The task models load from their own HF dirs; the model binds nothing through
  the generic loader (`weightless = True`, held to its own row in
  `tests/test_arch_conformance.py`). One attention `LayerSpec` gives the scheduler the paged pool
  its page table needs (one page per request); the forward never attends.

### 2. The family (`arbi_serve/ocr/`)

| Module | What |
|---|---|
| `model.py` | `OcrModel` (arch row `ArbiOcrLanes`, `routes=arbi_serve.ocr.routes:register`) and `OcrConfig` |
| `tasks.py` | the four tasks (`layout` also runs `task_orientation.py`'s classifier when configured), each split where the scheduler batches it: `prepare` (API child), `forward` (engine, one call per step), `finish` (API child) |
| `engine_tasks.py` | the tasks as `MediaBinding`s, warmed at load; `finish_extras`; the `model_stats` counters |
| `layout.py` | PaddleX layout post-processing (score 0.3, class-aware NMS 0.6/0.98, page-sized image dropped, large merge), container regions flattened, nested duplicate visual boxes dropped, margin paragraph numbers joined to their paragraph, visual boxes trimmed off captions |
| `orientation.py` | the page's turn: the classifier's decision, the four-angle trial's pick, `turn` |
| `lines.py` | detection floor 0.6 (0.3 on formula regions), same-baseline merging inside one layout region, line order, notched-polygon mask (the crops are cut on the device: `models/paddle/rec_crops.py`) |
| `textfix.py` | pilcrow look-alike rule, seam spaces, dropped word gaps from blank columns, raised footnote digits as `<sup>` |
| `table.py` | PaddleX `table_recognition_v2` (non-end-to-end path, cells-split OCR) |
| `kmeans.py` | scikit-learn's `KMeans(random_state=0, n_init="auto")`, numpy only (label-identical on 400 random inputs) |
| `pipeline.py` | the three API tasks over the model tasks (`TaskRunner`: prepare, one engine request per item, finish), the page registry between the lowres layout page and the highres OCR page (exact `page_key`, else thumbnail within the affinity key) |
| `working_set.py` | how many requests an API process decodes at once: a count and the container's memory watermark |
| `routes.py` | `register`: `server.register_routes` with the `ocr_lines` item handler and `EngineForward` |
| `server.py` | the tasks, envelopes and errors of `register_routes` |
| `unit.py` | `python -m arbi_serve ocr`: the engine process, its API processes and the page router (`PageRouter`) |
| `model_dir/` | the deployed config dir (`config.json`, `tokenizer_config.json`). A boot bundle (`docs/fast-boot-bundle.md`, section H) carries the checkpoint directories it names under `assets/` and resolves them through `host_assets.resolve_asset`; the config is not rewritten |

The split keeps the reference's arithmetic. `prepare` is the processor's own resize on the host
(the page the API child already decoded; no PNG crosses again), the device finishes it with the
processor's own `rescale_and_normalize` (a true division: the same bits on either side), and
`finish` runs the reference's host steps on the copied outputs. `tests/ocr/test_tasks_cpu.py`
holds the split to the processor's tensor. A task that runs out of memory on a shared card
retries its forward one item at a time, waiting for memory, instead of failing the request.

| Task | Per step | What |
|---|---|---|
| `layout` | forwards of <= `OCR_LAYOUT_BATCH` pages (default 8), each forward size replayed from a CUDA graph (`OCR_LAYOUT_GRAPHS=0`: eager) | PP-DocLayoutV3 fp32; one label per query (argmax, score >= 0.5; a page with none at 0.5 keeps those above 0.3, `OCR_LAYOUT_LOW_SCORE`, `0` off, counted as `layout.low_score_pages`: handwriting on ruled paper scored 0.34-0.48 and came back with no block at all) in `order_seq` order, each page's reading order on its own slice |
| `detection` | forwards of <= `OCR_DET_FORWARD_PAGES` pages of one input shape (default 4; deployed 1), never padded | the page detector as the reference ran it (processor size rule, box score 0.3); its DB post-processing on the device (`db_postprocess.db_device`: row-run union-find, minimum-area rectangles, box scores; fixed shapes, no host sync, a CUDA graph per highres page shape `OCR_DB_GRAPHS`); with one-page forwards, a whole page's detection (normalisation, CNN and device DB) replays one CUDA graph per map shape in `OCR_DET_GRAPHS` (default the 192 and 96 DPI Letter/A4 maps 2112x1632, 2240x1600, 1056x832, 1120x800; empty: none), and any other shape runs eager at its own size (`ocr/stage_graphs.py`), only candidate rectangles leave and the API child runs the unclip tail; within a pixel of the processor, holes' contours not listed; a page whose device pass reports a capacity miss is detected again with its map (`mode="page_map"`, host post-processing); `mode="table"`: PaddleX's general-OCR detection on a table crop (cv2 `DetResizeForTest` limit 960 max, PaddleX normalisation; thresh 0.3, box 0.4, unclip 1.5, 3000 candidates) |
| `recognition` | every line of the step's pages, padded widths under a 64k-frame budget per forward; each forward of a width class in the smallest captured row bucket (1, 2, 4, 8, up to the class's cap: 8 to 704 px, 4 to 1536, 2 to 2176, then 1) that holds its lines, the spare rows zero; the recognizer's convolutions and linears are row-invariant kernels (`models/paddle/invariant_triton.py`) | `mode="lines"`: the page plus its lines' quads; crops cut on the device as OpenCV's cubic warp and resized to height 48 as PIL's bilinear, bit for bit (`rec_crops`), each line's ink components and inked columns (`rec_crops.ink_stats`, OpenCV's `connectedComponentsWithStats` boxes) returned for the text fixes (the grey crops only after a capacity miss); greedy CTC with per-character confidence, x-centre and pilcrow weight; `mode="paddle"`: PaddleX's batch-1 input (cv2 resize, own padded width) for table cell text |
| `table` | the crops in flight together, up to `OCR_TABLE_BATCH` (default 8) a step: the classifier over all of them, then per kind the structure encoder one crop per forward (a batch costs as much per crop in fp32 and holds its activations per crop), one decode over its crops, and the cell detector in pairs; the classifier and the cell detector run row-invariant kernels and replay the smallest captured bucket (1, 2, 4, 8; cells 1 or 2) that holds their crops, the encoder one crop per forward (`table_graph.stage_buckets`; inputs fixed at 224, 512 and 640 px; `OCR_TABLE_GRAPHS=0`: eager at the crops' own count); the decode in the smallest batch bucket (1, 2, 4, 8) holding its crops, from a 32-token graph between stop checks and a one-token graph for the tail, the spare rows zero and finished from the start, its attention and linears row-invariant kernels (`models/paddle/slanext_decode_triton.py`, `ocr/table_graph.py`) | PP-LCNet wired/wireless, then that kind's SLANeXt (fp32: the HF snapshots are fp16 weights) and RT-DETR-L cells (> 0.3); the models start while the crop's general OCR runs, which reads none of their outputs. A crop's result is the same bits alone or beside any crops (see **Batch invariance**) |

**Page orientation** (`OCR_PAGE_ORIENTATION=0` turns it off). A scan can arrive turned a quarter or
upside down (a PDF `/Rotate`, a scanner), and every later model reads upright text: a hostile-ingest
page set read 0.66 of its words upright and 0.24 / 0.10 / 0.09 turned 90 / 180 / 270, with no flag.
The service turns each page upright before layout and detection (`ocr/orientation.py`) and returns
the turn as `page_rotation` (0, 90, 180 or 270, degrees clockwise; **only with `OCR_RESULT_EXTRAS=1`**, off by default, because the deployed parser's decode accepts exactly the keys it knows: a default result has exactly the old keys, and the page is turned upright either way) on every `layout` result and
every `ocr_lines` result, next to `image_bbox`. Everything in the result (layout boxes, lines,
polygon reads, `image_bbox`) is in the **upright** frame; a caller that cuts regions from its own
copy of the page turns that copy clockwise by `page_rotation` first, and keeps sending its page as
it has it: the service turns it again by the stored angle.

The classifier (PP-LCNet_x1_0_doc_ori, Apache-2.0, 6.8 MB: the table classifier's network and
PaddleX preprocessing with four classes) is part of the `layout` task, not a task of its own: the
page's 224x224 input (host: short side 256, centre crop, one 150 KB tensor) travels in the layout
request, and the classifier runs in the layout's step on the layout's stream, replayed from captured
graphs of its row buckets 1, 2, 4, 8 (`OCR_ORIENTATION_GRAPHS=0`: eager) in the layout's capture
pool, with the softmax on the device; four probabilities per page leave with the layout's outputs.
So an upright page costs one extra input and a replay of a few small kernels: no request, step,
stream or host synchronisation, and no second layout pass. The class is the turn the page's content
has (a page that arrives turned 90 degrees clockwise is class 90), so `page_rotation` is its
complement. The layout call decides: a page laid out as it arrived and found turned is laid out
again upright (`orientation.layout_redone`). A page whose top class is below
`OCR_ORIENTATION_CONFIDENCE` (0.5: the checkpoint is label-smoothed, a clear page tops out near 0.92)
(and above `OCR_ORIENTATION_NO_SIGNAL`, 0.3: a blank page's classifier output is uniform, 0.256, and nothing can orient it: it keeps its angle and costs no trial; no page of the 3,500-page corpus set lay between) is decided by a trial of the four angles on that page alone (the lines detected at each angle times
the mean recognition confidence of the `OCR_ORIENTATION_TRIAL_LINES` (24) longest, all four reads in
one recognition request); the trial's angle must score `OCR_ORIENTATION_TRIAL_MARGIN` (1.5) times
the classifier's, and a page that reads at no angle keeps the classifier's. The angle is stored
with the page in the registry (`PageState.rot`), so its keyed or thumbnail-matched OCR calls turn
the page the same way without classifying again; a page with no stored layout (an unkeyed call that
no layout matched, at least 256 px on a side) is classified by a layout request of its own.
`/v1/stats` `pipeline`: `orientation.pages`, `.rot<angle>`, `.trials`, `.trial_changed`,
`.layout_redone`; the engine's `orientation.graph_replays`. The classifier is optional: served when
the config dir's `checkpoints` has `page_orientation`.

Memory: the weights are 6.8 MB fp32 (registered with the layout task's modules), the classifier's
input and a forward of it are part of the layout row of the forward arena (`_prepare_layout`
measures the layout forward with the classifier input), its graphs' scratch and inputs live in
`capture.cudagraphs.ocr_layout` and `capture.io_buffers`, and the page registry holds one more int
per page (`PageState.rot`). A rotated highres page is a transient copy in the API process (PIL
`transpose`), priced like any decoded page by the working set's measured growth per decoded byte.

**The engine's step thread never waits for the GPU.** It runs every forward, so a host
synchronisation inside one makes it wait for the work already queued instead of preparing the
next step. Inputs go up through `runtime/pinned_h2d.stack_to_device`: staged straight into a
pinned ring and copied on a side stream, so reusing a staging arena waits only for earlier
copies, never for a forward. The native models cache their constants (frozen batch-norm
factors, anchors, position tables, spatial shapes) per device and shape, so a forward copies
nothing from pageable memory, and SLANeXt's structure decode reads its stop condition once every
few steps rather than every step. Outputs leave
as host tensors on `FinishOut.extras_tensors`, zero-copy frames, so nothing is packed into a
blob on the step thread. Line recognition batches take their padded width and row count
from a short ladder (`REC_WIDTHS`, `rec_rows_bucket`): cuDNN plans each new input shape on the
host for about as long as the forward runs, and with every batch a new shape that planning was
most of the step thread's time. `tests/ocr/test_sync_free_live_gpu.py` runs the
forwards with synchronisation set to raise.

**Live-row recognition** (on by default; `OCR_REC_NATIVE=0` turns it off). The recognition row
graphs record the recognizer's whole forward on the row-invariant family kernels
(`models/paddle/invariant_recognizer.py`: the dense convolutions and linears of
`invariant_triton`, the depthwise convolutions, squeeze-excitation, pools, layer norms,
attention and the CTC head of `invariant_glue_triton`), half-precision activations and
products with float32 accumulation, normalisations and the softmax in float32. One graph per
width class, at its row cap; a forward of fewer lines binds its live row count
(`invariant.set_live_rows`) and every kernel computes and writes only those rows, so a lone
line costs about one row. With it off, the graphs record the compiled program below.

**Compiled recognition** (on by default; `OCR_REC_COMPILE=0` turns it off). The recognition row graphs record the recognizer and its greedy CTC
as one `torch.compile` program (`ocr/recognition_compile.py`): each batch norm fuses with the
activation after it, the glue around the convolutions fuses, and the CTC outputs
are fused reductions over the logits, under float16 autocast (layer norms and the softmax stay
float32). Width and row count are symbolic, so the whole ladder shares one program for one row
and one for several; the compile runs at warm-up, in the Inductor cache under `/cache`, and
nothing compiles after it. The row caps are the eager forward's
(`recognition_graph.graph_row_limit`).
It is off by default. Its graphs are captured on a thread of their own that stays parked for
the engine's life (`recognition_graph.capture`): a recorded cuDNN v8 convolution runs kernels
owned by a plan in torch's per-thread plan cache, and on the step thread the engine's eager
convolutions (detection and layout on every new page shape) would evict them, after which the
graphs read NaN for every line (garbage or empty text) and later fault. `OCR_REC_DTYPE=float32`
keeps float32 (fused only). Batch-invariant mode and every uncaptured shape stay eager.

**Table cells on the width ladder** (`OCR_REC_CELL_LADDER`, on by default). PaddleX pads each
table-cell crop (`paddle` mode) only to its own width, so nearly every cell is an input shape of
its own: eager, float32, and planned by cuDNN afresh. On the ladder a cell is padded on with zeros
to its width class (`REC_WIDTHS`, as a line is) and a batch is topped up with zero rows to a
captured row count, so the cells replay the recognition row graphs that already exist; no graph is
added. The read's own width and pixels are unchanged; only the zero padding the recognizer's
attention sees grows. `0` keeps PaddleX's own-width input.

**Compiled detection in float16** (`OCR_DET_DTYPE`, `float16` by default; `float32` keeps every
op in float32). The page and crop graphs record the compiled detector
(`models/paddle/ppocr_det_compiled.py`) with its convolutions under float16 autocast; the head's
logits are cast to float32 before the sigmoid, so the DB threshold and box scores read a float32
probability. Uncaptured shapes stay on the eager float32 forward. The same plan-cache hazard as
recognition applies, and one parked thread is not enough here: every captured shape is a plan
per convolution, and the crop ladder alone holds more plans than one thread's cache
(`TORCH_CUDNN_V8_API_LRU_CACHE_LIMIT`), so a single capture thread evicts its own first graphs'
plans while capturing its last, and those graphs fault on their first replay. The captures are
split into chunks the cache holds, each on a parked thread of its own
(`stage_graphs.shapes_per_thread`, `ocr/parked_capture.py`). Choosing a float16 plan for each new
shape costs more host time than a float32 one, which the engine pays once, at warm-up.

**Page identity.** Layout items accept `{image, page_key}` as well as legacy base64
image strings. OCR items accept `{image, page_key}` or `{image, polygons, page_key}`.
Use a unique nonempty string (at most 256 characters) per document page and send the same
key for its lowres layout and every highres OCR request. Submit layout before OCR.
Each API process keeps layouts in a registry (`ocr/page_registry.py`) that evicts the least
recently used page, never one stored or looked up within `OCR_PAGE_PIN_S` (900 s) while its
memory stays under `OCR_PAGE_REGISTRY_MIB` (256 per API process); `/v1/stats` `pages` reports
its slots, pinned pages, evictions and bytes. A keyed OCR call whose layout is missing (never
stored on that process, or evicted) returns HTTP 409 with `code` `layout_missing`: resubmit
the page's layout under the same key, then retry. Keep these calls on the same API
process using the existing affinity routing. A reused key replaces its layout and clears
its cached lines. Keys are caller identities, so callers must not reuse them for other pages.
An unkeyed OCR request (every parser released before `page_key`) finds its page's layout
by thumbnail (48x64 grey, mean absolute difference at most 6, aspect within 1%), because its
highres page is a separate render from the lowres one layout saw. It searches only unkeyed
pages stored under its own `X-Arbi-Affinity` key (the parser's key per layout request, which
the unit forwards to the API process) and unkeyed pages stored without one. So two similar
pages of different documents never share state, and a keyed page is never matched by
thumbnail. Deploy the server's additive protocol support before upgrading the parser client.

**Working set.** An API process starts at most 128 requests at once, and a started request
decodes nothing until the container can hold what is already running will grow to, plus its
own growth, under its memory limit. Both are measured: the container's unreclaimable memory
(cgroup `anon` + `shmem` + `kernel`), each process's reserve in the unit's memory ledger (the
engine's: the peak of its live memory over the last two minutes less now; an API process's:
what its running requests have yet to grow by), and the growth per decoded byte each API
process observes in its own live memory, which charges every request (`ocr/memory_ledger.py`,
`ocr/working_set.py`). Free memory a process's allocator keeps for reuse is taken off, since
a request can be given it without the container growing (`ocr/malloc_retention.py`), and
those pages are returned once they stand in the way of growth the ledger has promised.
`OCR_MEMORY_HIGH_FRACTION`, when set, replaces the measurement with a fixed watermark of the
limit (0 turns the memory bound off). One request always runs, and a process runs one at a
time until it has measured one. The rest wait at their compressed size behind the door, whose
queue-wait bound refuses with a measured `Retry-After`, so more documents in flight queue
instead of ending in an OOM kill (`ocr/working_set.py`; `/v1/stats` → `working_set`). The
unit lifts its soft open-files limit to the hard limit for every process it spawns: each
request in flight holds sockets in the proxy and the API process.

**Faulted in at boot.** What a first pass of real traffic would otherwise fault in one page at
a time on its requests is set up when each process starts serving. Each process fills the free
memory its allocator keeps for reuse to a fixed amount (`OCR_MALLOC_KEEP_ENGINE_MIB`,
`OCR_MALLOC_KEEP_API_MIB`, `OCR_MALLOC_KEEP_PROXY_MIB`; 0 turns it off), as far as the container
has room for it short of a purge, one process at a time under the ledger's lock. The fill is
held free memory in the ledger, so the gate counts it as reusable rather than in use. An idle
process returns only what its heap grew past that amount and fills it back while idle; memory
returned under pressure is not filled back. Each API process also starts every worker thread
of its pools, makes its shared-memory arena and has the engine map it (the engine lane
`ocr.shm_map`). The engine page-locks one pinned segment for its outputs' copies to the host
before its warm-up pins anything (`OCR_PINNED_RESERVE_MIB`, booked in the host ledger as
`ocr.output_staging`), which torch's caching host allocator carves its blocks from instead of
page-locking new ones mid-traffic (`ocr/malloc_retention.py`, `ocr/pinned_outputs.py`,
`ocr/routes.py`; `/v1/stats` → `malloc.keep_bytes` / `malloc.filled_bytes`, and the engine's
`pinned.*` under `lanes`). Two allocator settings keep later requests on those pages: jemalloc
may carve any request from a retained extent (`lg_extent_max_active_fit` in the image's
`MALLOC_CONF`), and the image preloads a `calloc` that zeroes in place
(`scripts/packaging/ocr_calloc_memset.c`) where jemalloc would hand the pages back to the kernel
to be zeroed on their next fault.

**One shared-memory arena for every API process.** The unit makes the arena the API processes
decode their pages into and stage their large engine inputs in, before the engine starts
(`OCR_SHM_UNIT_ARENA_MIB`, default 1792; `ocr/shm_payloads.py`). The router spreads pages over
the API processes by key, so their pages in flight do not peak together: one arena any of them
may fill holds what one per process would only if each were sized to its own peak, and an
input that fits none goes inline over ZMQ, which the engine then faults in. Each API process
faults the arena in when it opens it and `mlock`s it where the container allows that
(`/v1/stats` → `shm.locked`: `locked`, or the refusal's errno). `shm.unit_high_water_bytes` is
what the API processes had in it at once; `shm.inline` counts inputs that did not fit.
`OCR_SHM_UNIT_ARENA_MIB=0` gives each API process an arena of its own
(`OCR_SHM_ARENA_MIB`, 512).

`GET /v1/stats` shows each task's busy time, items, forwards, widest step and the GPU
peak (`model_stats` admin RPC), and which device path ran: `detection.db_graph_replays` /
`detection.db_eager` (a page's DB post-processing replayed from a captured graph, or kernel by
kernel for an uncaptured map shape), `detection.page_graph_replays` and `layout.graph_replays` (a whole-stage replay, `ocr/stage_graphs.py`) and `recognition.crops_triton` / `recognition.crops_torch`
(line canvases cut by the Triton kernels, or by torch ops off CUDA). The host fallbacks are
the API process's `pipeline` counters `det.device_db.<flag>` (a page detected again on the host
after a DB capacity miss) and `ocr.ink_host_lines` (lines whose text fixes read the grey crop
after a line-statistics capacity miss). The `tasks` counters are per API process: with
`OCR_API_PROCESSES=N` a document's pages spread over all N, so one process's `ocr_detect` /
`ocr_polygons` show about 1/N of its pages (sum `?api=0` .. `?api=N-1`).

**Batch invariance.** A table's HTML and a line's read do not depend on what else shares
the step. cuDNN and cuBLAS choose a kernel, and with it a reduction order, by shape: on an RTX
4090 nearly every recognition row count from 1 to 8 gave a row other bits (the first
divergence is the backbone's stem convolution), and a crop's cells moved between the cell
detector's one- and two-crop forwards, so about 1% of the 665-table corpus changed HTML at
c=8/16 against c=1. The OCR convolution networks (the recognizer, the table classifier and
the cell detector) therefore run their dense convolutions and linears in row-invariant kernels
(`models/paddle/invariant_triton.py`, marked per model by `models/paddle/invariant.enable`):
implicit-GEMM convolutions and GEMMs whose every output element reduces in an order fixed by the
layer's per-image geometry (one chunk width, a split count chosen by the layer, partial sums
added in split order), never by the batch, with the batch norm, activation and learnable affine
fused into the epilogue. Every other op (depthwise convolutions, normalisations, attention,
sampling, the elementwise glue) already reads only its own row through a kernel chosen without
the batch. The compiled recognizer has one symbolic row count (`recognition_compile`: an
unbacked size, so no one-row specialization). So each stage and width class runs the smallest
captured bucket that holds its rows, and a row's bits are the same in every bucket, at any
position and beside any neighbours (`tests/ocr/test_invariant_kernels_live_gpu.py`; the same
checks fail on cuDNN). The structure encoder runs one crop per forward. The structure decoder
keeps its batch ladder: its attention and linears are kernels whose reductions are fixed by the
model's geometry alone (`models/paddle/slanext_decode_triton.py`), so a table's tokens are the
same bits in any bucket. Each line also keeps its own padded
width class; neighbouring lines cannot promote it into a wider class.

`OCR_BATCH_INVARIANT=1` additionally pins layout and detection forwards to one page (the
deployment already runs `OCR_LAYOUT_BATCH=1` and `OCR_DET_FORWARD_PAGES=1`) and recognition to
one row in the eager float32 program. Its October cost
([receipt](receipts/ocr-batch-invariance-2026-10-24.md): 56.6–84.8% lower recognition
throughput) was the singleton recognition this default path no longer needs. The mode addresses
model batch composition and still requires correct page keys and layout-before-OCR ordering.

Table preprocessing (`config.json` `table_preprocess`): `structure` and `cells` use the PaddleX
runner's own cv2 resize/normalise (`paddle`, the only value served); `cls` the HF processor's
arithmetic (`hf`, run on the device by `pp_lcnet.ClsPreprocessor`, bit-identical) or PaddleX's
(`paddle`). The flow on one crop: general OCR (detect, sort, min-area crops, recognise), classify,
structure + cells, cell NMS 0.3, cells reconciled with the structure's cell count and the OCR
boxes (KMeans merges), OCR boxes spanning >= 2 cells split and re-read, cells sorted into rows,
OCR boxes matched into cells (> 70% inside), HTML. Cell text is always the recognizer's read of
the crop, never generated.

### 3. The unit

`python -m arbi_serve ocr --root /models` starts ONE engine
(`--model={root}/ocr --task=forward --kv-cache-dtype=auto`) that answers every
task of `POST /v1/infer`. `OCR_MAX_BATCH` (default 256) bounds the rows of one step. The
API process does the host work (resize, post-processing, the text fixes) on its request threads,
with `OMP_NUM_THREADS=OCR_THREADS` (default: the container's CPUs over its processes, `ocr/cpu_budget.py`) and torch on one thread in each API process.

**API processes.** `OCR_API_PROCESSES=N` gives the engine N API processes, `api-0` ..
`api-<N-1>` (ports `--recognition-port + 1 + j`; the engine process itself is `engine`). A page's
OCR calls must reach the API process whose page registry holds its layout. The parser names the
page of every request in an `X-Arbi-Affinity` header (one key per page and conversion), and the
router (`unit.PageRouter`) sends a keyed request to the API process the key hashes to (BLAKE2b):
one page's requests share an API process, and one document's pages are served by all of them at
once. A request without the header keeps its client on one API process (a new client takes the
least-loaded one). A request that holds no page state (`/v1/ocr/table` without a key) goes to the
API process with the fewest requests in flight, so one host's tables use every API process. The
console's OCR service probe (`admin_console/ocr_service_measure.py`) sends a key per page like the
parser, so its pages spread the same way. `GET /v1/stats?api=k` reads API process `k`.

### 4. Identity

`GET /v1/models` lists them per task (the model entry's `tasks`):

| Task | Ids |
|---|---|
| `layout` | `layout/pp-doclayoutv3-listitem-r4` |
| `ocr_lines` | `text_recognition/pp-ocrv6-medium-rec`, `text_detection/pp-ocrv6-medium-det` |
| `table` | `text_recognition/pp-ocrv6-medium-rec`, `table_recognition/slanext`, `text_detection/pp-ocrv6-medium-det` |

These are the parser's pins (ARBI #2998, `parser-service/ocr_client.py`), so a
parser and an OCR unit that serve other models fail the identity check at the first request.

## Config dir

`/mnt/k8scache/paddle/ocr/` (mounted at `/models/ocr` with
`/mnt/k8scache/paddle` at `/models`) holds a copy of `arbi_serve/ocr/model_dir/`:

* `config.json`: `architectures: ["ArbiOcrLanes"]`, `model_type: arbi_ocr_lanes`, the eight checkpoints (and the optional ninth, `page_orientation`: `../hf/PP-LCNet_x1_0_doc_ori_safetensors`) relative to the
  dir (`../pp-doclayoutv3-listitem/r4`, `../hf/PP-OCRv6_medium_det_safetensors`, ...),
  `model_ids`, `table_preprocess`;
* `tokenizer_config.json`: the file the engine fingerprints (the model has no tokenizer).

## Parser side

The parser needs no logic change: it talks the same contract and pins these model ids
(above). Its garbled-text check is the model-free `parser_text_quality.garbled` (ARBI #2998),
which replaced `OCRErrorPredictor` (Datalab `ocr_error_detection` weights).

## Validation (10.2.0.106, one RTX 4090 shared with other tenants)

The unit ran from this branch's source over the OCR image built from f2e4859b2
( torch 2.12.1, transformers 5.15.0; the reference ran torch
2.14.1, transformers 5.20.1). On CPU the two transformers versions give bit-identical outputs
for all eight models; on the card layout boxes differ from the reference by <= 0.01 px (torch
kernels), labels identical.

The parser was the unchanged parser image with the ARBI #2998 source, pinned to these models;
CUR is the then-production (Surya) model server, REF the reference server.

Legal scan set (15 documents, 346 pages; truth: 1153 paragraph numbers, 230 footnotes, 236
markers):

| | CUR | REF | this family |
|---|---|---|---|
| paragraph numbers correct | 1135 | 1142 | 1142 |
| single wrong numbers | 4 | 6 | 7 |
| shift runs (scorer artefact on sc4, see the reference README) | 0 | 1 | 1 |
| numbers lost | 8 | 2 | 2 |
| glued to the previous paragraph | 0 | 3 | 2 |
| footnote bodies numbered | 215 | 218 | 221 |
| in-text footnote markers | 158 | 180 | 181 |
| duplicated 8-grams (strict) | 641 | 613 | 619 |
| duplicated words / loops / invented lines / novel numbers | 0/0/0/0 | 0/0/0/0 | 0/0/0/0 |
| doc words lost / numbers lost | 180 / 12 | 99 / 3 | 102 / 3 |
| parse wall time | 144 s | 130 s | 130.5 s |

The per-document differences against REF are single recognizer reads at pilcrow look-alikes
("914." for ¶ 14, which REF read "9 14.") and footnotes numbered that REF missed: the same class
of error, flipped by float noise (two runs of this family differ by as much). The 9 table crops:
structure identical to the Paddle pipeline on 9/9, cell text identical on 6/9 (one character
each in the other three).

100-document corpus (5,000 pages):

| metric | CUR | REF | this family |
|---|---|---|---|
| words lost | 4,175 | 2,569 | 2,499 |
| numbers lost | 919 | 312 | 324 |
| wrong digits | 169 | 126 | 128 |
| missing line-start labels | 797 | 656 | 653 |
| invented lines | 4,139 | 2,966 | 2,990 |
| list items | 17,764 | 18,677 | 18,677 |
| tables | 621 | 526 | 526 |
| word order (mono) | 97.15% | 97.25% | 97.25% |
| strict 8-gram duplication / unsupported excess | 812 / 402 | 1,151 / 590 | 1,183 / 612 |
| loops / uncorroborated inventions | 0 / 0 | 0 / 0 | 0 / 0 |
| pages clearly worse / better ordered than CUR | – | 54 / 34 | 54 / 35 |

The differences against REF are spread over a dozen documents in both directions (block order
on one equation page, spacing in reference lists). Every one of the 141 table crops was also
sent to the reference's own Paddle table service: structure identical on 140/141, HTML
byte-identical on 99/141, cell text identical in 4,565 of 4,691 cells (about 1% of characters
differ: recognizer numerics, Paddle vs torch).

Speed and memory, 100 documents on the shared 4090: wall 557 s (REF 598 s, CUR 627 s); card
busy (utilisation-weighted) 260 s vs REF 248 s; lane busy layout 273 s, detection 267 s,
recognition 238 s, table 19 s (REF layout 385 s, detection 259 s, recognition 297 s, Paddle
tables separate). torch peak allocated 8.3 GiB in one process (REF 7.9 GiB plus the Paddle table
process). The engine caps itself at `OCR_MEM_FRACTION` (default 0.45 of the card,
as the reference did): without the cap the caching allocator held 13.6 GiB; with it the
legal-set run peaked at 11.2 GB on the card.

## Not done / known gaps

* Two-column reading order uses the layout model's own order (no commercial-use human
  reading-order data exists; Surya/Datalab outputs must not be used as labels). Recursive
  XY-cut was measured and is worse overall; it is not ported.
* A pilcrow glyph that the recognizer reads as an extra leading digit ("¶ 112" for ¶ 12) is
  left as read; the fix needs the paragraph sequence, which only the parser has.
* Tables are the Paddle structure models; question/option lists are no longer turned into
  tables. When the cell detector finds no cells at all, PaddleX's NMS fails on the empty array
  (a 500); this port takes PaddleX's own reconciliation from zero cells instead (the OCR boxes
  stand in for the cells).

## Served config and boot

`k8s/served-configs.json` lists it as `ocr`, the image's default command
(`ocr --root /models`, `/models` = the NFS share's `paddle/`). The `forward` engine builds a bf16 `tkv-bypass` pool of
one tiny layer and the prefill-only step's kernels; the Inductor/Triton codegen it derives
(sampler and step kernels) ships in the Dockerfile's `BOOT_STORE`, recorded on a fresh volume
(RTX 4090; ready in about 66 s).


# docs/ocr-robustness-design.md
# OCR robustness: the smallest thing that works, found by measurement

Status: 2026-11-10. Owner rule: **experiment, and find a non-overengineered, non-brittle solution.**
An earlier version of this document listed many stages (a dense warp field, a multi-rung ladder,
three verifier roles, several candidate models). That is not built by default. Nothing below is added
until a measurement says it pays. The acceptance principle stays: **a page a human can read must be
readable by our OCR**, and one document must never kill or delay the engine.

## 1. What is shipped and proven (kept as is)

| change | fixes | state |
|---|---|---|
| layout rescue (#4909) | a page with no layout region at 0.5 lost every line (handwriting on ruled paper) | merged |
| page orientation (#4900) | a scan turned 90/180/270 lost 63-86% of its words, unflagged | merged |
| result extras are opt-in (#4924) | `page_rotation` broke the deployed parser's strict decode | merged |
| separate overlapping line boxes (#4913), read a one-line block at its detected line's height (#4914) | recognition crop height: neighbours' ascenders garble a line; found by the rig agent on the letter | rig's PRs, in review |
| skew estimate and turn (#4919) | unmeasured: the rig finds main's letter losses are line-level, not only skew | open, **does not merge without numbers** |

## 2. Rules (few, and each is a test)

1. **Never make a page worse.** Any mechanism that changes pixels is kept only if its own result is
   better by our existing score (lines x mean recognition confidence) on that page, else the page is
   left as it was. One retry, never a loop.
2. **No magic thresholds.** A threshold is set on one set of pages and reported on a held-out set, with
   the margin. A threshold that only fits the set it was tuned on is deleted.
3. **Clean pages pay nothing** (p50/p99, VRAM, host RAM, ABAB on the same card) and results for the
   deployed parser keep exactly the old keys unless the operator opts in.
4. **Bounded and flagged.** Bounded time and memory per page; an internal error returns a flagged page,
   not a failed document.
5. **A kill switch per mechanism**, and no coupling to the parser beyond additive, opt-in fields.

## 3. Method: measure first, add one thing at a time

1. **Baseline = main plus the proven fixes.** Run the degrade set (rig's `degrade_gen.py`: rotation,
   skew, perspective, aspect, lens, waves/curl and folds, shadow, grain, faint, blur, resolution,
   handwriting, partial page and background) and the letter variants. For every factor, record the
   strength at which a human still reads the page and we do not.
2. **Rank the remaining failures by recall lost on realistic inputs** (phone photos, rescans, rotated
   pages, faint, handwriting), not by how many distortion types exist. Only the top of that list is
   worked on.
3. **One mechanism at a time.** For a candidate: recall gain on the factors it targets, on the held-out
   pages and on clean pages (must not move), latency, lines of code, failure modes. Kept only if the
   gain justifies those. If two mechanisms give the same recall, the one with fewer moving parts wins.
   Prefer one general mechanism to several special cases (for example one local rectification driven by
   the detected lines, or one learned unwarper if it clearly beats it, instead of separate
   homography, lens, wave and curl estimators; one cheap retry on low-confidence pages instead of a
   multi-rung ladder).
4. **Brittleness test for every mechanism:** run it on inputs it was not designed for and on clean
   pages; it must never worsen a page. Delete what does not pay.

Candidate mechanisms, in the order the baseline is likely to rank them, **each only if the baseline
shows it matters**: (a) the proven line-crop fixes (done); (b) skew (#4919) and any rotation left; (c)
one local rectification for oblique and curled photos; (d) one cheap retry for low-confidence pages
(contrast or resolution); (e) a verifier (section 4). Everything else in the earlier catalogue
(binarisation, de-halftoning, bleed-through, a vision-model reader, tiling for very large images,
a learned corner finder) is **not built** until a measured failure asks for it.

## 4. The verifier: cheapest version first

One second model, run after the document is ready, on a sample or on low-confidence pages, **flag
only**: it never supplies text and is never primary (our output stays the stored text; a disagreement
is a cause to investigate and the trigger for a re-read, not a replacement). A flag records page,
region and both readings in the page metadata. Measure on the degrade set and the letter whether it
catches real losses: detection rate on real losses, false-alarm rate on pages we read correctly,
and whether its errors are independent of ours. **Build nothing more until those numbers say so.**
Candidate for the first test: **Unlimited-OCR v1**, already served by arbi-serve
(`UnlimitedOCRForCausalLM`, bf16 KV only). Verified at the official sources (2026-11-10): code and
weights both MIT (repo LICENSE, model card), 3B total / 0.5B active, built on DeepSeek-OCR with its
frozen DeepEncoder (256 vision tokens per 1024 px page); R-SWA bounds the decoder cache to the vision
prefix plus a 128-token window (our model file already reproduces that ring). Its "40+ pages" is a test
bucket of the paper, not a limit, and "100 pages in one pass" is not an official number for v1. Not
published: expert layout, a handwriting or olmOCR score, a throughput GPU. A v2 exists
(`baidu/Unlimited-OCR-2`, SR-SWA, MIT); our architecture serves v1 only and v2 would need its own
check. Independence from our PaddleOCR-family recogniser is a hypothesis to measure, not a given:
its single-page training labels were produced with PaddleOCR, which may correlate its errors with
ours. PaddleOCR-VL-1.5 (Apache-2.0, 0.9B dense decoder, strong on the vendor's skew and warp tables,
needs transformers 5 or its own stack, not served here) is a second candidate only if the first does
not catch real losses. The letter is kept on the isolated host.

## 5. Report this plan produces

The experiments run; a table of mechanism against recall gain, latency, lines of code and failure
modes; what was cut and why; the minimal pipeline recommended. Numbers are added as they exist.


# docs/ocr.md
# ocr: layout, OCR lines and tables for the ARBI parser

arbi-serve serves the ARBI parser's `ocr` API (one `POST /v1/infer` with the tasks
`layout`, `ocr_lines` and `table`) on its own engine. The models are PP-DocLayoutV3 + `list_item`,
PP-OCRv6 detection and recognition, SLANeXt tables, all Apache-2.0 weights run as arbi-serve's
own torch modules (`arbi_serve/models/paddle`). [ocr-models.md](ocr-models.md) covers the family:
the `forward` task, the per-task split, the post-processing, identity and validation.

One OCR unit runs per GPU. Use the slim serving image and pass these container arguments:

```
ocr --root /models --port 18093
```

Mount `/models` from the NFS share's `paddle/` (it holds `ocr/`, the config dir, and the
checkpoints it names). The unit (`arbi_serve/ocr/unit.py`) supervises
one `forward`-task engine process (and its API processes) on internal ports and serves its one
API on one port:

| Route | What |
|---|---|
| `POST /v1/infer` | `{"task", "items", "params"}`, forwarded to the API process of the request's `X-Arbi-Affinity` key |
| `POST /v1/ocr/layout`, `/v1/ocr/detect`, `/v1/ocr/recognize`, `/v1/ocr/table` | the same request for one kind of work: `layout`, `ocr_lines` detections (`{image}`), `ocr_lines` reads (`{image, polygons}`), `table`; a body of another kind is a 400. LiteLLM maps one endpoint onto each, so spend logs name the work |
| `GET /v1/models` | the engine's model list; its entry names the tasks (`capabilities`) and each task's checkpoint ids (`tasks`) |
| `GET /v1/stats` | one API process's stats (`?api=k`, default 0): per task, the family's counters, admission |
| `GET /health` | 200 only when the engine and its API processes are ready, 503 before that; `engines` lists `engine` and `api-0` .. `api-<N-1>` |

Without hosted pooling models these are the unit’s routes. `tests/ocr/test_unit_router.py` holds the unit to that contract.

* **Booting:** every route but `/health` is 503 `{"status": "booting"}` until the engine is
  ready, then the engine's answer.
* **`/v1/models`:** identity, not traffic: the unit reads the engine's list once when it turns
  ready and answers from that, so a saturated engine (its own requests 429) never fails the
  parser's identity check. It is 503 only while the engine boots or after it exits.
* **API processes:** a request that names its page (`X-Arbi-Affinity`) goes to that page's API
  process; any other client stays on one (`unit.PageRouter`, ocr-models.md). A table crop holds
  no page state, so an unkeyed `/v1/ocr/table` goes to the API process with the fewest requests
  in flight.
* **Shutdown:** SIGTERM and SIGINT are forwarded to the engine.
* **Crash:** if the engine exits, the unit exits non-zero, so the container or pod restarts.
* **Proxy:** forwards bodies, statuses and `Retry-After` unchanged; it does not batch, queue
  or retry.

The engine is a plain `arbi-serve --model={root}/ocr --task=forward`: the
`ArbiOcrLanes` architecture row mounts the OCR API
(`arbi_serve/ocr/routes.py`, over `ocr/server.register_routes`) into the
arbi-serve app, so nothing else changes for other models. `docker/ocr/compose.yaml` is an
example deployment.

## The preconfigured OCR engine

`uvx arbi-serve` and the admin console carry the OCR host as a ready-made engine, so a machine with one card
serves it without a model root laid out by hand:

```
arbi-serve prepare ocr                  # once: fetch the checkpoints, build the deployment
arbi-serve run --preset "OCR engine"    # start it (also: the first menu's "a ready-made engine")
```

`prepare ocr` builds exactly what production's `ocr` unit serves: `arbi_serve/ocr/model_dir/config.json`
copied unchanged, and its nine checkpoints laid out where that file's relative paths point (`hf/<name>` for
eight, `pp-doclayoutv3-listitem/r4` for the layout fine-tune) under the launcher's cache
(`~/.cache/arbi-serve/engines/ocr`). Every checkpoint is a Hub repo at a pinned revision with the sha256 of each
file, declared once in `_arbi_serve_launcher/engine_assets.py` (the table the console, the launcher and
`scripts/publish_engine_assets.py` all read), and a download that does not hash to its pin is refused by file
name. It is resumable, fetches nothing twice, never runs downloaded code, and no start downloads anything. The
engine boots as the `forward` task (the `ArbiOcrLanes` row's own task) on one card, with the engine
environment this unit gives its own engine, and prints the curl for `/v1/ocr/{layout,detect,recognize,table}`.
Hosts need about 32 GiB of host memory for the engine's sleep staging and a 2 GiB `/dev/shm` when it runs in a
container.

**The layout model is the production fine-tune.** The `list_item` fine-tune of PP-DocLayoutV3 ([ocr-models.md](ocr-models.md), run r4) is published by `scripts/publish_engine_assets.py` to the public-read bucket `arbi-engine-assets` (`https://arbi-engine-assets.s3.uk.io.cloud.ovh.net/pp-doclayoutv3-listitem/r4/`, fetched over plain https and checked against the pinned sha256, no Hub c