File size: 5,573 Bytes
ca1a504 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | # schift-ocr-1-beta 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": "schift-ocr-1-beta"})
with DeepSeekOcr.from_config(cfg) as m: # opens the p150, loads the weights, captures the traces
r = m.ocr("page.png") # task "parse", mode "gundam": path, bytes, PIL image,
print(r.text, r.finish_reason, r.usage, r.image) # uint8 array or data URL
for ref in r.refs: # the layout blocks: label + boxes in pixels
print(ref["label"], ref["boxes"])
r = m.ocr("page.png", output_format="json") # r.json["blocks"]: label, boxes, boxes_norm, text
r = m.ocr("page.png", output_format="raw") # the model's output: <|det|>label [x1, y1, x2, y2]<|/det|>...
r = m.ocr("page.png", max_crops=6) # fewer Gundam tiles (a faster, coarser read)
s = m.ocr_stream("page.png") # text deltas as tokens are decoded
for delta in s:
print(delta, end="", flush=True)
print(s.result.usage)
```
`ocr(image, task=None, prompt=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).
The parameters are those of `POST /ocr` (the model card's table):
- `task`: `parse` (default; `<image>document parsing.`, the only prompt the model card documents). `prompt`
replaces it (`<image>` is added in front, without a newline, when it has none, as in the model card's `<image>document parsing.`; other prompts are untested by the authors).
- `mode`: `gundam` (default: a 1024 global view + 2 .. 32 tiles of 640 for images larger than 640 x 640) or `base`
(one 1024 x 1024 view); `min_crops` / `max_crops` bound the Gundam tile grid (official 2 / 32, at most
`DSOCR_MAX_CROPS`). Only the modes enabled by `DSOCR_MODES` are accepted.
- `output_format`: `raw` (the model's output; block tags kept), `markdown` (default: the official post-processing,
tags removed, image blocks as `` placeholders), `json` (`{"text", "refs", "blocks", "image"}`:
every `<|det|>label [box]<|/det|>` block with its box in pixels of the original image, the 0..999 values the model
wrote, and its content). `refs` is filled whatever the format.
- `max_new_tokens`: default `DSOCR_DEFAULT_MAX_NEW_TOKENS` (16384), at most `DSOCR_MAX_NEW_TOKENS`; the decode
attention window (the prompt + the last 128 generated tokens) keeps the KV cache at a fixed size whatever the output
length; `finish_reason` is `stop` (the EOS token), `length` or `cancelled` (`cancel`, a `threading.Event`, was set).
- The no-repeat n-gram rule: off by default (the model card's setting); `ngram_preset` `hf` / `vllm` or the explicit
`no_repeat_ngram_size`, `ngram_window`, `ngram_whitelist` set one.
- `temperature` 0 (default) = greedy, the model card's 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
(`schift-ocr-1-beta` here; the package code is shared with the DeepSeek-OCR family ports).
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 [schift-io/schift-ocr-1-beta](https://huggingface.co/schift-io/schift-ocr-1-beta) at the pinned commit
(`DSOCR_MODEL_DIR` points at a local copy instead); the repository's Python files are never downloaded or executed.
Package layout (`tt_dsocr/`): `frontend.py` (the official views, tiles, 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_decoder.py` the prefill, one trace per row
bucket, and the traced decode step with the 128-token window; `model.py` the pipeline), `reference/` (the CPU
reference, with the window), `server/` (HTTP server, stdlib client, smoke test), `samples/`, `licenses/`.
|