Download code/PYTHON.md from changh95/DeepSeek-OCR-2: direct link, hf CLI and curl.
- Browser
- Download file 6 kB
-
https://huggingface.co/changh95/DeepSeek-OCR-2/resolve/main/code/PYTHON.md
- Command line
-
hf download hf://changh95/DeepSeek-OCR-2/code/PYTHON.md
-
curl -L -o PYTHON.md https://huggingface.co/changh95/DeepSeek-OCR-2/resolve/main/code/PYTHON.md
DeepSeek-OCR-2 on Tenstorrent p150: Python API
from tt_dsocr import config as C
from tt_dsocr.api import DeepSeekOcr
cfg = C.resolve_config({"DSOCR_VARIANT": "deepseek-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, 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="base") # plain text from one 1024 x 1024 view (257 image tokens)
r = m.ocr("page.png", output_format="json") # r.json = {"text", "refs", "image"}
r = m.ocr("page.png", prompt="<image>\nWhat is the total?") # a free prompt (untested by the authors)
r = m.ocr("page.png", ngram_preset="vllm", max_crops=4) # DeepSeek-OCR's 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, *, 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.) orfree(<image>\nFree OCR.), the two prompts of the DeepSeek-OCR-2 model card; DeepSeek-OCR's other presets (ocr,figure,describe,locate) raiseInputError.promptreplaces the task's prompt (<image>\nis added in front when it has no<image>; the model is trained on the official prompts).mode:gundam(default: a 1024 global view + 2 .. 6 tiles of 768 for images larger than 768 x 768),base(1024),small(768);min_crops/max_cropsbound the Gundam tile grid (official 2 / 6, at mostDSOCR_MAX_CROPS). Only the modes enabled byDSOCR_MODESare accepted.output_format:raw(the model's output; grounding tags kept),markdown(the official post-processing: tags removed, image regions asplaceholders; default formarkdown),json({"text", "refs", "image"}).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: defaultDSOCR_DEFAULT_MAX_NEW_TOKENS(8192, the official value), at mostDSOCR_MAX_NEW_TOKENS, clipped to the KV capacity left after the prompt;finish_reasonisstop(the EOS token),lengthorcancelled(cancel, athreading.Event, was set).- The no-repeat n-gram rule:
ngram_presethf(default: the officialinfer, size 20 over the whole sequence, prompt included),vllm(DeepSeek-OCR's vLLM recipe: size 30, window 90,<td>/</td>never banned) oroff;no_repeat_ngram_size(0 = off, 2 .. 64),ngram_window(0 = whole sequence),ngram_whitelist(token ids) replace the preset's values. temperature0 (default) = greedy, the official decoding;top_k<=DSOCR_K_MAX(64);repetition_penalty1 .. 2;seedmakes 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-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
deepseek-ai/DeepSeek-OCR-2 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 V2, 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/. The same package serves DeepSeek-OCR and Unlimited-OCR-2
(their own packages).