Repository navigation
feat(got): port GOT-OCR 2.0 (SAM ViT-B + Qwen2-0.5B) - #1744
Merged
Merged
Conversation
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
8 of 9 tasks
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds
model_type: "GOT", the 0.58B document-OCR VLM released asstepfun-ai/GOT-OCR2_0and converted asmlx-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 singleLinear(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.rschose the special-token table by hardcoding HunYuan's. GOT ships a bareqwen.tiktokenwith an emptyadded_tokens_decoder, so that table gave<|im_end|>and<imgpad>no id at all. The table is now selected from the checkpoint'stokenizer_class(or itsauto_map), and the QWen one followstokenization_qwen.pyorder. Verified against the real file: 151643 ranks + 217 specials = the 151860vocab_sizethe config declares, with<|im_end|>151645 and<imgpad>151859.src/loading/vlm_got_ocr.rsfolds both released key layouts onto one naming, including the neck'sconv1/norm1/conv2/norm2rename back to theneck.0..3indicesSamEncoderreads, and drops the tiedlm_headcopy the original ships. It is idempotent, so a converted checkpoint passes through unchanged.[151643, 151645].config.jsondeclares only<|endoftext|>, which an OCR answer never emits; upstream stops on the<|im_end|>turn separator through aKeywordsStoppingCriteriainstead.src/server/chat_template.rs, andbuild_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.rsdelegatessequence_state_layoutand 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 annn.Linear, a transformersQwen2Modelwith the tied head, spliced asmodeling_GOT.py::forwardsplices, tokenized by thetokenization_qwen.pycontract) 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-templatepaths 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/completionswith an image part returns the same 287 prompt tokens, the same 7-token completion andfinish_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.rscompares every id of the server render against the CLI instruction, not just the counts.cargo clippy --lib --tests --features cuda -- -D warningsandcargo fmt --allcleancargo check --lib --tests --features cudaclean--profile test-fast --features cuda:multimodal::got_ocr_prompt12/12,loading::vlm::got_ocr7/7,vision::got_ocr2/2,vision::processors::got_ocr5/5,server::got_chat_template_tests5/5,tokenizer::tiktoken4/4, detection 1/1tests/got_ocr_real_model.rs1/1 andtests/got_ocr_prompt_parity.rs3/3, both-- --ignoredserver::chat_template154/154,loading::vlm216/216,multimodal::vlm_runtime50/50,models::detection_tests61/61,execution::memory_estimate43/43,models::registry9/9,model_metadata8/8,vision::merge4/4,cli_help_consistency27/27cargo test --workspace --profile test-fast --features metal,accelerateis not runnable on this host (Linux/CUDA, no Metal and no Accelerate); unrun, left to the merge gateOut 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