--- tags: - blackhole - p150 - tt-dit-server - tt-model-cache - tt-model-catalog - tt-model-container license: apache-2.0 pipeline_tag: image-to-text base_model: - zai-org/GLM-OCR --- # glm-ocr on Tenstorrent p150 > Derived from Z.ai's [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) ([technical report](https://arxiv.org/abs/2603.10910)), with unmodified weights downloaded from the authors' repository. Official SDK: [zai-org/GLM-OCR](https://github.com/zai-org/GLM-OCR). This is a third-party port, not affiliated with or endorsed by Z.ai / Zhipu AI. See the original model card for training details. GLM-OCR (0.9B parameters) reads documents: it returns the text of an image, tables as HTML, formulas as LaTeX, and fills a JSON schema with the information it finds ("information extraction"). It is a CogViT vision encoder (0.4B parameters, 24 transformer blocks over 14 x 14-pixel patches, 2 x 2 patches merged into one token) whose output enters a GLM-0.5B text decoder (16 layers, 3D rotary positions) as image tokens; the decoder writes the answer token by token. Images are resized with the official rule to at most 6144 image tokens (about 4.8 megapixels). The package includes the official image preprocessing, prompt template and stop tokens, the model card's task prompts and information-extraction prompt, and the Markdown clean-up of the official SDK. The vision encoder and the prefill run on the device as traced tt-nn graphs, one per size bucket, and the decoder writes every token as one launch of a decoder megakernel (bfp8 decoder weights, bf16 output head; on-device greedy decoding / sampling / repetition penalty and the stop rule); image decoding and resizing run on the host CPU. Runs on Tenstorrent **p150** (mesh `P150`). Packaged and published with [tt-model-manager](https://github.com/tenstorrent/tt-model-manager) 0.1.0 (manifest schema 5.1). ## At a glance | | | | --- | --- | | Hardware | p150 | | License | apache-2.0 | ## Intended use Document OCR on one Tenstorrent p150, one request at a time: the text, tables and formulas of a page or a crop, and structured fields from forms, invoices or receipts with a JSON schema; for research, prototyping and offline processing. ## Prerequisites - The [Tenstorrent CLI](https://github.com/tenstorrent/tt-cli/blob/main/docs/prerequisites.md), `tt`: `uv tool install tenstorrent` (or use tt-model alone, see the Quickstart) - Docker - Tenstorrent hardware: **p150** - About 2.7 GB of free disk for the checkpoint (fetched once into the Hugging Face cache), plus the container image - Images as PNG, JPEG, WebP, BMP, TIFF or GIF (the first frame); PDF pages must be rendered to images first ## Quickstart ```bash tt serve changh95/GLM-OCR ``` `tt serve` downloads the Docker image and the [`zai-org/GLM-OCR`](https://huggingface.co/zai-org/GLM-OCR) at `2e85a62840ccac27daa451df36c736c4636b8628` weights (into your HF cache; they are not in the image), then starts the model's own HTTP server on port 20000 (or the next free port, if that one is busy). The first start compiles kernels for your device, which takes several minutes; the server is ready when it logs `Application startup complete`. Without tt-cli: `tt-model serve changh95/GLM-OCR`. On the port `tt serve` reported: ```bash curl -sLO https://huggingface.co/changh95/GLM-OCR/resolve/main/code/tt_glmocr/samples/line_en/sample.png curl -s localhost:20000/ocr -F file=@sample.png # {"model": "glm-ocr", "text": "Invoice No. 2026-0417, due 15 December 2026.", "finish_reason": "stop", ...} (the p150 output; identical to the float32 reference) curl -s localhost:20000/ocr -F file=@sample.png -F task=extract -F format=json \ --form-string 'schema={"invoice_number": "", "due_date": ""}' curl -sN localhost:20000/ocr -F file=@sample.png -F stream=true # SSE text deltas ``` ## Capabilities This package exposes the model's own HTTP server on port 20000, **not** an OpenAI-compatible chat API — its request and response shapes are the model's own. See the author's notes for the payload it expects. `POST /v1/chat/completions` is OpenAI-compatible: the image goes in an `image_url` part as a data URL (base64), the task in a text part (`Text Recognition:` when empty); `stream`, `max_tokens`, `temperature`, `top_p`, `seed` and `stream_options.include_usage` work as in the OpenAI API, and the OpenAI Python client works against it: ```python import base64 from openai import OpenAI client = OpenAI(base_url="http://localhost:20000/v1", api_key="unused") image = "data:image/png;base64," + base64.b64encode(open("sample.png", "rb").read()).decode() r = client.chat.completions.create(model="glm-ocr", messages=[{"role": "user", "content": [ {"type": "image_url", "image_url": {"url": image}}, {"type": "text", "text": "Table Recognition:"}]}]) print(r.choices[0].message.content) ``` `POST /ocr` is the native route: multipart (`file` + fields), JSON (`{"image": base64 or data URL, ...}`) or the raw image as the body (`Content-Type: image/png`, fields as query parameters): | request field | default | meaning | | --- | --- | --- | | `file` / `image` | required | the image (one per request) | | `task` | `text` | `text` (`Text Recognition:`), `table` (`Table Recognition:`, HTML output), `formula` (`Formula Recognition:`, LaTeX output), `extract` (with `schema`) | | `schema` | - | `extract`: a JSON object of the fields to fill, values `""` (nested objects and lists allowed); sent after the model card's extraction preface | | `prompt` | the task's | a free prompt instead of the task's (up to `GLMOCR_MAX_PROMPT_TOKENS`; the model is trained on the card's prompts) | | `format` | `raw` | `raw` (the model's output), `markdown` (the SDK's clean-up: tables stay HTML, formulas a `$$` block), `json` (the output parsed: `json` field) | | `max_new_tokens` | 4096 | 1 .. `GLMOCR_MAX_NEW_TOKENS`; clipped to the KV capacity left after the prompt | | `temperature`, `top_k`, `top_p`, `repetition_penalty`, `seed` | 0, 0, 1, 1.0, random | 0 = greedy, the official decoding; `top_k` <= 64; `repetition_penalty` 1 .. 2 (the SDK uses 1.1) | | `max_pixels` / `max_image_tokens`, `min_pixels` | 9633792 / 6144, 12544 | the image budget in the official processor units (2 x height x width; 1568 per image token): smaller is faster, larger reads finer print | | `stream` | false | Server-Sent Events: `{"type": "delta", "text"}` as tokens are decoded, then `{"type": "done", ...}` | - The answer: `text` (in `format`), `raw_text`, `json` / `json_error`, `finish_reason` (`stop` | `length`), `usage` (`prompt_tokens`, `image_tokens`, `completion_tokens`), `image` (size before / after resizing, image tokens) and `timings` (preprocessing, vision, prefill, first token, decode tokens per second). - `GET /health` reports readiness, `GET /info` the weights and their commit, the device, the engines, the configuration, the limits, the buckets and the timings of the last request; `GET /v1/models` lists the model. - The chat route reads the last user message only (one image, its text parts); `temperature` defaults to 0, not OpenAI's 1; `n` other than 1, `stop`, `logprobs`, `tools`, presence / frequency penalties and JSON response formats are refused with 400. Image URLs (http / https) are fetched only when `GLMOCR_ALLOW_URLS=1`. - Errors: 400 with the reason, 413 body or image too large, 415 content type, 422 malformed body, 429 queue full (`Retry-After`), 503 while starting or after `GLMOCR_QUEUE_TIMEOUT_S`, 500 on a device failure. - A Python API with the same parameters (`tt_glmocr.api.GlmOcr`) is described in [`code/PYTHON.md`](code/PYTHON.md); it needs a tt-metal build with the patches in [`patches/`](patches/). ### Configuration The server builds its device programs for one configuration when it starts; change it with environment variables and start it again. `GET /info` reports it. | item | environment variable | values | default | | --- | --- | --- | --- | | largest image | `GLMOCR_MAX_IMAGE_TOKENS` | 256 .. 6144 image tokens (1568 pixels of `max_pixels` each) | 6144 | | longest prompt text | `GLMOCR_MAX_PROMPT_TOKENS` | 16 .. 4096 | 1024 | | KV capacity (prompt + output) | `GLMOCR_MAX_CONTEXT` | 1024 .. 32768 positions | 10240 | | largest / default `max_new_tokens` | `GLMOCR_MAX_NEW_TOKENS`, `GLMOCR_DEFAULT_MAX_NEW_TOKENS` | 16 .. 32768 | 8192, 4096 | | size buckets (one trace each) | `GLMOCR_VISION_BUCKETS` (patches, multiples of 256), `GLMOCR_PREFILL_BUCKETS` (rows, multiples of 128) | comma-separated | derived from the limits | | device engines | `GLMOCR_ENGINE` | `vis=ttnn,pre=ttnn,dec=mk` (decoder megakernel) or `dec=ttnn` (tt-nn decoder, 2.4x slower) | `vis=ttnn,pre=ttnn,dec=mk` | | weight formats | `GLMOCR_PRECISION` | `vis`, `attn`, `mlp`, `head` = `bf16` / `bfp8` (`vis`, `mlp` also `bfp4`); `vis_fid`, `pre_fid` = `HiFi4` / `HiFi2` / `LoFi`; `mk` (the decoder megakernel) = `bf16` / `bfp8` / `bfp8h8`; `vis_sdpa` = `approx` / `exact` (exponential of the vision attention for images above 512 image tokens, i.e. the vision buckets of 4096 patches and up: exact is 1.8x slower on pages) | `""` = vision bf16 HiFi4 with `vis_sdpa=approx`, prefill attention bf16 / MLP bfp8, `mk=bfp8` (bf16 head) | | largest `top_k` | `GLMOCR_K_MAX` | 1 .. 64 | 64 | | decode steps per launch | `GLMOCR_LOOP_STEPS` | 1 .. 64 (streaming granularity) | 8 | | queue | `GLMOCR_QUEUE_DEPTH`, `GLMOCR_QUEUE_TIMEOUT_S` | waiting requests, seconds | 8, 300 | | uploads | `GLMOCR_MAX_BODY_MB`, `GLMOCR_MAX_INPUT_MEGAPIXELS`, `GLMOCR_ALLOW_URLS` | MB, megapixels, 0 / 1 | 64, 50, 0 | ### Example output Three images rendered for this demo (a table with merged header cells, a formula, a simplified-Chinese notice), each sent to this package's container on a p150 as `POST /ocr` with the task shown and otherwise the defaults (greedy decoding). The right half of each image draws the answer as returned: the HTML table as a grid, the LaTeX as source and re-rendered with matplotlib, the text as is. [`media/demos.json`](media/demos.json) has the exact requests, the whole answers with their timings, and the official float32 model's answers.    The table's answer (`text` of the response, `"task": "table"`), as returned: ```html
| Station | Rainfall(mm) | Total | |||
| Jan | Feb | Mar | Apr | ||
| Harbor | 81.2 | 64.5 | 70.3 | 52.8 | 268.8 |
| Hillside | 95.0 | 77.4 | 88.1 | 60.2 | 320.7 |
| Airport | 58.6 | 49.9 | 55.0 | 41.3 | 204.8 |
| Valley | 72.4 | 61.0 | 66.7 | 47.5 | 247.6 |