GLM-OCR / README.md
changh95's picture
Card: add Example output demo (media/)
c14ba15 verified
|
Raw History Blame Contribute Delete
18.8 kB
---
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.
![GLM-OCR on a Tenstorrent p150: a table with merged header cells and the HTML table it returned, drawn as a grid](media/demo_table.png)
![GLM-OCR on a Tenstorrent p150: the attention formula and the LaTeX it returned](media/demo_formula.png)
![GLM-OCR on a Tenstorrent p150: a simplified-Chinese notice and the text it returned](media/demo_chinese.png)
The table's answer (`text` of the response, `"task": "table"`), as returned:
```html
<table border="1"><tr><td rowspan="2">Station</td><td colspan="4">Rainfall(mm)</td><td rowspan="2">Total</td></tr><tr><td>Jan</td><td>Feb</td><td>Mar</td><td>Apr</td></tr><tr><td>Harbor</td><td>81.2</td><td>64.5</td><td>70.3</td><td>52.8</td><td>268.8</td></tr><tr><td>Hillside</td><td>95.0</td><td>77.4</td><td>88.1</td><td>60.2</td><td>320.7</td></tr><tr><td>Airport</td><td>58.6</td><td>49.9</td><td>55.0</td><td>41.3</td><td>204.8</td></tr><tr><td>Valley</td><td>72.4</td><td>61.0</td><td>66.7</td><td>47.5</td><td>247.6</td></tr></table>
```
| input | task | image tokens | output tokens | first token | decoding | whole request (server) | client round trip |
| --- | --- | --- | --- | --- | --- | --- | --- |
| table, 788 x 324 | `table` | 336 | 303 | 226 ms | 359 tokens/s | 1.07 s | 1.08 s |
| formula, 820 x 160 | `formula` | 174 | 62 | 255 ms | 369 tokens/s | 0.42 s | 0.43 s |
| Chinese notice, 1130 x 442 | `text` | 640 | 61 | 322 ms | 343 tokens/s | 0.50 s | 0.51 s |
The second request of each input on a warm server (the first gave the same answer); the server times are the
answer's `timings` (first token includes the vision encoder and the prefill), the round trip is on loopback. All
three answers are identical to the greedy answers of the official float32 model on the CPU (the same weights in
transformers 5.24.1), including the missing space in "Rainfall(mm)".
## Expected performance
Agreement with Z.ai's own float32 model on the CPU (transformers
5.24.1 `GlmOcrForConditionalGeneration`, same weights and prompts, greedy) on synthetic test images (text lines,
a paragraph, an A4 page, a table, formulas, handwriting-style text, Chinese, Korean / Japanese / German, an
extraction form) and a public-domain manuscript scan:
| eval | this package | float32 CPU reference | images |
| --- | --- | --- | --- |
| Vision encoder output PCC | 0.9973 - 0.9999 on line / paragraph / table / formula; 0.9947 / 0.9968 on the two full pages (official bfloat16, emulated: 0.9961 - 0.9999; 0.9968 / 0.9991 on the pages: see the limitations) | 1 | 6 |
| Next-token distribution, total-variation distance per step, mean (teacher-forced, every step) | 0.00001 - 0.0017, top-1 agreement 100 % (official bfloat16: 0.00001 - 0.0023) | 0 | 11 |
| Outputs identical to the float32 outputs (greedy) | 11 / 11 (1,134 tokens) | – | 11 |
| Character error rate vs the float32 outputs | 0.0 | 0 | 11 |
| speed (batch 1, warm) | input | median | throughput |
| --- | --- | --- | --- |
| Vision encoder | 709 x 64 line (50 image tokens) / A4 page at 150 dpi (2772 tokens) / 6144 tokens | 18 ms / 615 ms / 1.73 s | – |
| Time to first token | line / paragraph (288 tokens) / A4 page | 30 ms / 100 ms / 718 ms | – |
| Decoder time per token | ~300 / ~1000 / ~3000 / ~6000 positions of context | 2.6 / 2.8 / 3.0 / 3.7 ms | 380 / 360 / 330 / 270 tokens/s |
| Whole page (A4 at 150 dpi, 280 output tokens) | image in, text out | 1.59 s | 0.63 pages/s |
| Served `POST /ocr`, client round trip | formula / line / table (273 tokens) | 138 ms / 156 ms / 949 ms | – |
| Server start (`tt-model serve` until ready) | first start with empty caches (kernel compilation on a busy 8-core host) / restart | about 25 min / 1.5-2 min | – |
## Limitations
- Not for decisions that need exact text without a human check (legal, medical, financial or identity
documents): OCR output can miss, misread or invent characters, on the CPU and the p150 alike.
- No layout analysis: the official SDK's full-document parsing (PP-DocLayoutV3 layout detection, one recognition
per region, Markdown assembly) is not included; an image is read as one region, so complex multi-column pages
read best as crops of their regions.
- One image per request, single-turn prompts, batch 1: requests are served one at a time in arrival order
(`GLMOCR_QUEUE_DEPTH` may wait). No PDF input.
- Images are resized to at most 6144 image tokens (about 4.8 megapixels; `max_pixels` lowers it): very small
print on a large page loses resolution. Aspect ratios of 200 or more are refused.
- The model is trained on the model card's prompts (text, table, formula, the extraction preface); other prompts
are accepted but untested.
- Sampling (`temperature` > 0) draws from at most the 64 most likely tokens (`GLMOCR_K_MAX`); greedy decoding,
the official default, is exact; sampling and `repetition_penalty` run on the device too (about 340 tokens/s, replays with the same `seed` are identical).
- One p150 only: device dispatch runs on the chip's Ethernet cores, so multi-chip meshes are not supported.
- Vision accuracy gate: this package's vision gate asks the image embeddings to stay within 0.001 PCC of the
official bfloat16 model. It is missed by up to 0.002 PCC on full pages (A4 at 150 dpi: 0.9947 vs the official
bfloat16 model's 0.9968, emulated on the CPU; the 1863 manuscript page 0.9968 vs 0.9991, emulated; a held-out A4
page 0.9969 vs 0.9987) and by 0.0007 on one small formula image (190 image tokens, exact exponential: 0.9934 vs
0.9951), with either attention setting. The decoded text still matched the float32 reference token for token on
all of these. Images above 512 image tokens use an approximate exponential in the vision attention by default
(1.8x faster vision on pages); `GLMOCR_PRECISION=vis_sdpa=exact` uses the exact one: page vision then takes about
1.0 s instead of 0.6 s for an A4 page at 150 dpi, for slightly higher embedding fidelity (the page misses shrink
to 0.0001-0.0007; one test page then flips a near-tie at token 57).
## Licensing
- Weights (not redistributed here; `tt serve` downloads them from the authors' repository at this commit):
[zai-org/GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) `2e85a628`, MIT License (the model card). Notices:
[`code/tt_glmocr/licenses/NOTICE.md`](code/tt_glmocr/licenses/NOTICE.md). The card's full pipeline also uses
PP-DocLayoutV3 (Apache-2.0), which is not part of this package.
- This package is a derivative work of GLM-OCR: the inference code is written anew (image preprocessing, prompt
and 3D positions follow transformers' `glm46v` / `glm_ocr` code, Apache-2.0), the networks run on the device in
tt-nn operations and a decoder megakernel, and the weights are loaded unmodified. The Markdown clean-up is
adapted from the official SDK ([zai-org/GLM-OCR](https://github.com/zai-org/GLM-OCR), Apache-2.0). The decoder
megakernel (`code/tt_glmocr/tt/mk_dec/`) is adapted from the same author's unpublished Qwen3-ASR and Qwen3-TTS
Tenstorrent ports (their decode megakernels and on-device sampler, Apache-2.0); the tt-nn decoder follows
patterns of tt-metal's demos (Tenstorrent, Apache-2.0). Related packages by the same author:
[changh95/DepthPro2](https://huggingface.co/changh95/DepthPro2),
[changh95/all-MiniLM-L6-v2](https://huggingface.co/changh95/all-MiniLM-L6-v2).
- Port, server and scripts (`code/`) and the tt-metal patches in [`patches/`](patches/): Apache-2.0.
- Samples: `code/tt_glmocr/samples/*/sample.png`, synthetic images made for this package (Apache-2.0);
provenance in their `PROVENANCE.md`.
- Demo images in `media/`: inputs rendered for this demo from text written for it, and this package's answers,
CC0 1.0 (fonts: DejaVu, Bitstream Vera licence; Noto Sans CJK SC, SIL OFL 1.1); attributions in
[`media/ATTRIBUTION.md`](media/ATTRIBUTION.md).
## Feedback
Questions or problems with this package: open a discussion at https://huggingface.co/changh95/GLM-OCR/discussions β€” that is what reaches its author. A problem with the `tt` tooling itself: `tt report issue` (collects your environment and opens a prefilled issue against tenstorrent/tt-cli). Product feedback: support@tenstorrent.com.
## Provenance
The exact sources the image was built from β€” `code/` in this repo is byte-identical to the model code inside the image:
| component | built from |
| --- | --- |
| tt-metal | [`44d66500520fda9f2c7060c0f6b41ec48f7ab37e`](https://github.com/tenstorrent/tt-metal/commit/44d66500520fda9f2c7060c0f6b41ec48f7ab37e) *(dirty tree β€” the image includes uncommitted changes)* |
| `code/` digest | `569ad3c1032021b8` (sha256, first 16 hex digits) |
| built | 2026-12-01T04:10:18+00:00 by tt-model 0.1.0 |