DeepSeek-OCR / code /PYTHON.md
changh95's picture
tt-model push deepseek-ocr (container)
b8b3105 verified
|
Raw History Blame Contribute Delete
5.99 kB

DeepSeek-OCR on Tenstorrent p150: Python API

from tt_dsocr import config as C
from tt_dsocr.api import DeepSeekOcr

with DeepSeekOcr.from_config(C.resolve_config()) as m:  # opens the p150, loads the weights, captures the traces
    r = m.ocr("page.png")                               # task "markdown", 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 boxes: label + boxes in pixels
        print(ref["label"], ref["boxes"])
    r = m.ocr("line.png", task="free", mode="tiny")     # plain text from one 512 x 512 view (73 image tokens)
    r = m.ocr("page.png", task="ocr", mode="base")      # text with boxes
    r = m.ocr("chart.png", task="figure")
    r = m.ocr("page.png", task="locate", ref="the signature")    # r.json = {"text", "refs", "image"}
    r = m.ocr("page.png", prompt="<image>\nWhat is the total?")  # a free prompt
    r = m.ocr("page.png", ngram_preset="vllm", max_crops=6)      # the official vLLM n-gram rule, fewer tiles
    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, *, ref=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: markdown (default; <image>\n<|grounding|>Convert the document to markdown.), ocr (<image>\n<|grounding|>OCR this image.), free (<image>\nFree OCR.), figure (<image>\nParse the figure.), describe (<image>\nDescribe this image in detail.), locate (<image>\nLocate <|ref|>{ref}<|/ref|> in the image., needs ref). prompt replaces the task's prompt (<image>\n is added in front when it has no <image>; the model is trained on the official prompts).
  • mode: tiny (512), small (640), base (1024), large (1280), gundam (default: a 1024 global view + 2 .. 9 tiles of 640 for images larger than 640 x 640); min_crops / max_crops bound the Gundam tile grid (official 2 / 9, at most DSOCR_MAX_CROPS). Only the modes enabled by DSOCR_MODES are accepted.
  • output_format: raw (the model's output; grounding tags kept), markdown (the official post-processing: tags removed, image regions as ![](images/<i>.jpg) placeholders; default for markdown / ocr), json ({"text", "refs", "image"}; default for locate). refs (every <|ref|>label<|/ref|><|det|>boxes<|/det|> group, boxes in pixels of the original image and as the model's 0..999 values) is filled whatever the format.
  • max_new_tokens: default DSOCR_DEFAULT_MAX_NEW_TOKENS (8192, the official value), at most DSOCR_MAX_NEW_TOKENS, 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).
  • The no-repeat n-gram rule: ngram_preset hf (default: the official infer, size 20 over the whole sequence, prompt included), vllm (the official vLLM recipe: size 30, window 90, <td> / </td> never banned) or off; no_repeat_ngram_size (0 = off, 2 .. 64), ngram_window (0 = whole sequence), ngram_whitelist (token ids) replace the preset's values.
  • 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 (deepseek-ocr here).

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 deepseek-ai/DeepSeek-OCR 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; mk_moe/ the decode megakernel; model.py the pipeline), reference/ (the CPU reference), server/ (HTTP server, stdlib client, smoke test), samples/, licenses/.