Unlimited-OCR-2 / code /PYTHON.md
changh95's picture
tt-model push unlimited-ocr-2 (container)
9b1a077 verified
|
Raw History Blame Contribute Delete
6.75 kB
# Unlimited-OCR-2 on Tenstorrent p150: Python API
```python
from tt_dsocr import config as C
from tt_dsocr.api import DeepSeekOcr
cfg = C.resolve_config({"DSOCR_VARIANT": "unlimited-ocr-2"}) # or C.resolve_config() with DSOCR_VARIANT in the env
with DeepSeekOcr.from_config(cfg) as m: # opens the p150, loads the weights, builds the engines
r = m.ocr(["page1.png", "page2.png", "page3.png"]) # one document: the pages in order (Base mode: one 1024 view
print(r.text) # each); Markdown per page, "<!-- page k -->" between pages
for page in m.ocr(["page1.png", "page2.png"], output_format="json").json["pages"]:
for b in page["blocks"]: # layout blocks: label, box in pixels of that page, content
print(page["page"], b["label"], b["box"], b["text"][:60])
r = m.ocr("page.png") # one page: Gundam (1024 global view + up to 16 tiles of 640)
r = m.ocr("page.png", output_format="raw") # the model's output: <PAGE><BLOCK>label[x1, y1, x2, y2]<FORK>...
r = m.ocr(["p1.png", "p2.png"], ngram_preset="sglang") # the official SGLang client's n-gram rule
s = m.ocr_stream(["p1.png", "p2.png"]) # text deltas as tokens are decoded
for delta in s:
print(delta, end="", flush=True)
print(s.result.usage, s.result.image["n_pages"])
```
`ocr(image, task=None, prompt=None, *, images=None, mode=None, min_crops=None, max_crops=None, max_new_tokens=None,
temperature=None, top_k=None, top_p=None, repetition_penalty=None, seed=None, no_repeat_ngram_size=None,
ngram_window=None, ngram_whitelist=None, ngram_preset=None, output_format=None, on_delta=None, cancel=None)` returns an
`OcrResult(text, raw_text, tokens, finish_reason, task, mode, output_format, usage, timings, image, refs, json,
sampling)`; `ocr_stream(...)` is the same as an iterator of text deltas (the result is `stream.result` afterwards).
`image` is one image (path, bytes, PIL image, uint8 array or data URL) or a list of page images; `images=` takes the
list too. The parameters are those of `POST /ocr` (the model card's table):
- 1 .. `DSOCR_MAX_PAGES` (8) pages per call, in document order. The prompt is the official layout: `<PAGE><image>`
per page, then the instruction.
- `task`: `parse` (default: the official instruction `Multi page parsing.`). `prompt` replaces the instruction (the
`<PAGE><image>` runs are added in front when it has no `<image>`; one `<image>` is expanded per page; every page
needs its `<PAGE><image>`, prompts without the markers raise `InputError`; the model is trained on the default
instruction).
- `mode`: default `gundam` for one page (a 1024 global view + 2 .. 16 tiles of 640 for pages larger than 640 x 640),
`base` for several (one 1024 x 1024 view per page: 273 image tokens + the `<PAGE>` marker) -- the official auto
policy; `min_crops` / `max_crops` bound the Gundam tile grid of each page (official 2 / 16, at most
`DSOCR_MAX_CROPS`). Only the modes enabled by `DSOCR_MODES` are accepted.
- `output_format`: `raw` (the model's output, every tag kept), `markdown` (default: per page the block contents
without the tags, image blocks as `![](images/page_<p>_<i>.jpg)` placeholders, pages separated by `<!-- page <k> -->`
lines), `json` (`{"text", "pages": [{"page", "width", "height", "text", "blocks": [{"label", "kind", "box",
"box_norm", "text"}]}], "refs"}`). `refs` (every block with a box: label, boxes in pixels of its page and as the
model's 0..999 values, page number) is filled whatever the format.
- `max_new_tokens`: default `DSOCR_DEFAULT_MAX_NEW_TOKENS` (16384: the official default runs until the context is
full), clipped to the KV capacity left after the prompt; `finish_reason` is `stop` (the EOS token), `length` or
`cancelled` (`cancel`, a `threading.Event`, was set).
- Generation follows the official `infer`: greedy, the page-count guard always on (EOS is held back until the output
has one `<PAGE>` per input page; a page longer than 20000 tokens is closed; fixed), no n-gram rule (`ngram_preset`
`off`); `ngram_preset` `sglang` is the official SGLang client's rule (size 35, window 128 for one page, 1024 for
several); `no_repeat_ngram_size` (0 = off, 2 .. 64), `ngram_window` (0 = whole sequence), `ngram_whitelist`
(token ids) set any rule.
- `temperature` 0 (default) = greedy, the official decoding; `top_k` <= `DSOCR_K_MAX` (64); `repetition_penalty`
1 .. 2; `seed` makes sampling reproducible.
The two halves of a request can be called separately: `prepare(image, ...)` (validation, image decoding, views and
tiles, prompt ids: CPU only, thread-safe) and `run(prepared, on_delta=None, cancel=None)` (the device; one at a time).
The server prepares the next request while the device serves the current one.
The compile-time configuration is `config.ServeConfig` (the `DSOCR_*` environment variables of the model card;
`C.resolve_config({...})` takes a dict). `DSOCR_BACKEND=cpu` runs the clean-room CPU reference instead of the device
(float32; slow: development and checks), `DSOCR_BACKEND=fake` a deterministic stand-in without weights (tests).
`DeepSeekOcr.from_config(cfg, device=dev)` uses an already opened p150 (the caller keeps it); without `device` the
p150 is opened with ETH dispatch and closed by `close()`. `DSOCR_VARIANT` selects the model of the package family
(`unlimited-ocr-2` here; the package's server reads it from its environment).
Requirements: tt-metal at `44d66500520fda9f2c7060c0f6b41ec48f7ab37e` with the package's two tt-metal patches (`patches/` of the package repository: ETH
dispatch: the 12 x 10 grid; the row-major reshape fix), and `numpy<2 safetensors huggingface_hub tokenizers pillow`
(+ `fastapi uvicorn` for the server). The weights are fetched from
[baidu/Unlimited-OCR-2](https://huggingface.co/baidu/Unlimited-OCR-2) at the pinned commit (`DSOCR_MODEL_DIR` points at
a local copy instead); the repository's Python files, `wheel/` and PDF are never downloaded, and its code is never
executed.
Package layout (`tt_dsocr/`): `frontend.py` (the official views, tiles, multi-page prompt ids, tokenizer), `api.py`
(this API), `backends.py` (device / CPU / fake), `postprocess.py` (output formats), `config.py` (configuration), `tt/`
(the device engines: `ttnn_vision.py` the DeepEncoder, one trace per view size; `ttnn_dash.py` the DASH decoder with
`dash_host.py` the host block router; `model.py` the pipeline and the page-count guard), `reference/` (the CPU
references: `model.py`, `uocr2.py`), `server/` (HTTP server, stdlib client, smoke test), `samples/`, `licenses/`. The
same package serves DeepSeek-OCR and DeepSeek-OCR-2 (their own packages).