Skip to content

feat(got): port GOT-OCR 2.0 (SAM ViT-B + Qwen2-0.5B) - #1744

Merged
inureyes merged 7 commits into
mainfrom
feature/issue-1359-got-ocr2
Sep 10, 2026
Merged

inureyes merged 7 commits into
mainfrom
feature/issue-1359-got-ocr2

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

Adds model_type: "GOT", the 0.58B document-OCR VLM released as stepfun-ai/GOT-OCR2_0 and converted as mlx-community/GOT-OCR2_0-{bf16,8bit,4bit}. A SAM ViT-B tower on a fixed 1024x1024 canvas emits exactly 256 feature rows of width 1024, a single Linear(1024, 1024) projects them, and a Qwen2-0.5B decoder reads them. The tower is the DeepSeek-OCR one reused unchanged (SamEncoder) and the decoder is the Llama-family backbone, so the port is mostly the five things that are genuinely new.

What changed

  • src/tokenizer/tiktoken.rs chose the special-token table by hardcoding HunYuan's. GOT ships a bare qwen.tiktoken with an empty added_tokens_decoder, so that table gave <|im_end|> and <imgpad> no id at all. The table is now selected from the checkpoint's tokenizer_class (or its auto_map), and the QWen one follows tokenization_qwen.py order. Verified against the real file: 151643 ranks + 217 specials = the 151860 vocab_size the config declares, with <|im_end|> 151645 and <imgpad> 151859.
  • src/loading/vlm_got_ocr.rs folds both released key layouts onto one naming, including the neck's conv1/norm1/conv2/norm2 rename back to the neck.0..3 indices SamEncoder reads, and drops the tied lm_head copy the original ships. It is idempotent, so a converted checkpoint passes through unchanged.
  • Stop ids are [151643, 151645]. config.json declares only <|endoftext|>, which an OCR answer never emits; upstream stops on the <|im_end|> turn separator through a KeywordsStoppingCriteria instead.
  • The checkpoint ships no chat template, so the fixed conversation lives in two places that agree byte for byte: a builtin server template in src/server/chat_template.rs, and build_got_prompt, which wraps a bare instruction and leaves already-framed text alone. A client system message is replaced by the fixed one, because the features are scattered into a prompt whose prefix the model saw on every training example.
  • src/vision/got_ocr.rs delegates sequence_state_layout and the batching predicates to the decoder rather than leaving them to the trait default, which would hand the server scheduler an empty cache vector.

Validation

Linux aarch64 / GB10 / CUDA sm_121, --profile test-fast --features cuda, on all three downloaded checkpoints (models/mlx/got-ocr2_0-{bf16,4bit,original}).

Greedy token-exact against a reference assembled from the checkpoint's own files (got_vision_b.py::build_GOT_vit_b(), model.mm_projector_vary.* as an nn.Linear, a transformers Qwen2Model with the tied head, spliced as modeling_GOT.py::forward splices, tokenized by the tokenization_qwen.py contract) under torch 2.14.0 fp32 on CPU. On the committed fixture page both the bf16 conversion and the original layout reproduce the reference's 287 prompt tokens and all 11 generated ids, then stop on 151645. All three checkpoints transcribe the rendered page verbatim from the CLI, and the CLI's templated and --no-chat-template paths produce the identical 287-token prompt.

Termination is proven, not inferred. A differential build with 151645 removed from the stop set emits <|im_end|> at exactly the position where the shipped build stops, then repeats it until the token cap; the probe was reverted and the shipped behavior re-confirmed.

Server: /v1/chat/completions with an image part returns the same 287 prompt tokens, the same 7-token completion and finish_reason: "stop" as the CLI, and two concurrent requests both transcribe correctly through the batched decode path. That the two front ends render the same prompt is pinned rather than argued: tests/got_ocr_prompt_parity.rs compares every id of the server render against the CLI instruction, not just the counts.

  • cargo clippy --lib --tests --features cuda -- -D warnings and cargo fmt --all clean
  • cargo check --lib --tests --features cuda clean
  • New tests --profile test-fast --features cuda: multimodal::got_ocr_prompt 12/12, loading::vlm::got_ocr 7/7, vision::got_ocr 2/2, vision::processors::got_ocr 5/5, server::got_chat_template_tests 5/5, tokenizer::tiktoken 4/4, detection 1/1
  • Real-checkpoint gates: tests/got_ocr_real_model.rs 1/1 and tests/got_ocr_prompt_parity.rs 3/3, both -- --ignored
  • Regression scopes for the shared files touched: server::chat_template 154/154, loading::vlm 216/216, multimodal::vlm_runtime 50/50, models::detection_tests 61/61, execution::memory_estimate 43/43, models::registry 9/9, model_metadata 8/8, vision::merge 4/4, cli_help_consistency 27/27
  • cargo test --workspace --profile test-fast --features metal,accelerate is not runnable on this host (Linux/CUDA, no Metal and no Accelerate); unrun, left to the merge gate

Out of scope

Multi-crop OCR, the model card's rendered-HTML helpers, and multi-image prompts (the decoder was trained with a single 256-token block; a second image is refused at prompt build).

Closes #1359

Adds `model_type: "GOT"`, the 0.58B OCR model released as `stepfun-ai/GOT-OCR2_0` and converted as `mlx-community/GOT-OCR2_0-{bf16,8bit,4bit}`. The SAM ViT-B tower is the DeepSeek-OCR one verbatim (`SamEncoder`), the decoder is Qwen2 on the Llama-family backbone, and the fusion is the LLaVA scatter, so the port is mostly the five things that are genuinely new.

The tiktoken loader hardcoded the HunYuan special table. GOT ships a bare `qwen.tiktoken` with an empty `added_tokens_decoder`, so that table silently gave `<|im_end|>` no id at all and left `<imgpad>` unresolvable. The table is now chosen from the checkpoint's `tokenizer_class` (or its `auto_map`), and the QWen one follows `tokenization_qwen.py` order: 151643 `<|endoftext|>`, 151645 `<|im_end|>`, 151859 `<imgpad>` on a 151643-rank vocabulary.

`canonicalize_got_keys` folds both released key layouts onto one naming, including the neck's `conv1/norm1/conv2/norm2` rename back to the `neck.0..3` indices `SamEncoder` reads, and drops the tied `lm_head` copy the original ships. It is idempotent, so a converted checkpoint passes through unchanged.

The stop set is `[151643, 151645]`. `config.json` declares only 151643, which an OCR answer never emits; upstream stops on the turn separator through a `KeywordsStoppingCriteria` instead, so without 151645 a run fills `max_tokens` rather than terminating.

The checkpoint ships no chat template, so the fixed MPT-style conversation lives in two places that agree: a builtin server template, and `build_got_prompt`, which wraps a bare instruction and leaves already-framed text alone. Both land on the same bytes, and `sequence_state_layout` is delegated to the decoder rather than left to the trait default so the server scheduler allocates real caches.

Refs #1359
`tests/got_ocr_prompt_parity.rs` compares every id of the assembled prompt against the checkpoint's own tokenizer contract (`tiktoken.Encoding` over the 151643 `qwen.tiktoken` ranks with `SPECIAL_TOKENS + IMAGE_ST` numbered from `len(mergeable_ranks)`), on a real checkpoint. It also asserts the server render and the bare CLI instruction tokenize to the identical vector, because matching prompt-token counts between two front ends is not evidence they rendered the same prompt.

`src/server/got_chat_template_tests.rs` covers the builtin template without a checkpoint: the rendered bytes, that a client system message is dropped for the fixed one, multi-turn history, that a shipped template still wins, and that the builtin does not leak onto a plain Qwen2 directory.

Refs #1359
Greedy-decodes a rendered page on both released key layouts and compares every token id against a reference assembled from the checkpoint's own files: `got_vision_b.py::build_GOT_vit_b()`, an `nn.Linear(1024, 1024)` loaded from `model.mm_projector_vary.*`, and a transformers `Qwen2Model` with the tied head, spliced the way `modeling_GOT.py::forward` splices. The reference ran fp32 on CPU under torch 2.14.0, so the claim is greedy token-exactness rather than bitwise agreement.

The test also asserts what a transcription alone would not: that the run ends on `<|im_end|>` strictly inside the 64-token cap and never on `<|endoftext|>`, that the prompt carries exactly 256 placeholders, and that `make_caches` returned a per-layer cache. This model fails quietly, so a dropped stride, a transposed feature grid or a wrong special table all produce fluent text; only the comparison against the page catches them.

The fixture is a committed rendered page with a generator script beside it, following `generate_test_image_shapes.py`.

Refs #1359
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata area:docs User and developer documentation area:inference Generation, sampling, decoding (incl. speculative, DRY) area:cli Command-line interface / CLI flags modelsize:small 4-bit checkpoint <= 10GB; fast iteration, safe for smoke tests modeltype:vlm Vision-language model arch:dense Dense transformer decoder status:review Under review labels Sep 10, 2026
@inureyes inureyes added status:done Completed and removed status:review Under review labels Sep 10, 2026
@inureyes
inureyes merged commit 92a7fae into main Sep 10, 2026
13 checks passed
inureyes added a commit that referenced this pull request Sep 10, 2026
Bilingual pre-merge report for the Kimi K3 tiktoken family and native XTML chat renderer. Covers the `TiktokenFamily` split (HunYuan keeping the QWen table from #1744, K3 adding the Han-first pre-tokenizer and the 256-entry control block), the id-level renderer and the injection fixture that measures it (118 ids with 14 control against 167 with none re-encoded as text and 99 with 19 re-encoded with special parsing on), the documented scope limit at `/v1/completions`, `/tokenize` and `generate -p`, the bounded-chunk guard and the linear special-token split that replaced a request-reachable quadratic, the think / response / tools stream markers and the 163586 stop id, the three `prompt_carries_bos` sites the #1347 rebase had to order, and the fixture validation against the checkpoint's own tokenizer.
@inureyes
inureyes deleted the feature/issue-1359-got-ocr2 branch September 14, 2026 11:59
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch:dense Dense transformer decoder area:cli Command-line interface / CLI flags area:docs User and developer documentation area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata modelsize:small 4-bit checkpoint <= 10GB; fast iteration, safe for smoke tests modeltype:vlm Vision-language model priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(got): port GOT-OCR 2.0 (SAM ViT-B tower reuse + linear projector + Qwen2-0.5B decoder, QWen tiktoken specials)

1 participant