Skip to content

feat(models): add LocateAnything (locateanything) VLM support - #1070

Merged
inureyes merged 7 commits into
mainfrom
feature/issue-847-locateanything-vlm
Aug 7, 2026
Merged

inureyes merged 7 commits into
mainfrom
feature/issue-847-locateanything-vlm

Conversation

@inureyes

@inureyes inureyes commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds native support for LocateAnything (model_type: locateanything), NVIDIA's ~3B generative grounding VLM: a MoonViT vision tower and an MLP connector feeding a Qwen2 text decoder whose output interleaves <ref>/<box> markers and the 1001 coordinate tokens <0>..<1000> (ids 151677..152677). Plain autoregressive decode already produces those, so no special detokenization is involved. Validated end to end on mlx-community/LocateAnything-3B-4bit, where the first emitted box is byte-identical to the output the model card documents for its own example image.

What changed

Reuse over duplication. The tower is the same MoonShot MoonViT-SO-400M that Kimi-VL embeds, so src/vision/encoders/kimi_vl.rs is reused rather than copied. Its upstream LocateAnything implementation diverges in exactly two places, both numeric: the LayerNorm epsilon is 1e-5 rather than 1e-6 (already a config field) and the block MLP uses nn.GELU(approx="precise"), MLX's tanh approximation, rather than the exact erf form. The activation becomes MoonViTMlpActivation on the vision config, defaulting to the erf form, so Kimi-VL and Kimi-VL 2.5 are byte-unchanged. mlxcel_core exposes no elementwise tanh GELU (both gelu and, despite its name, gelu_approx are erf-based), so it is synthesised from primitives the way models::kokoro::ops::gelu_new does. The text side is models::Qwen2Model verbatim.

New files. src/vision/locateanything.rs (VLM runtime + multi_modal_projector connector), src/vision/processors/locateanything.rs (native-resolution processor), src/multimodal/locateanything_prompt.rs (image-marker expansion), src/loading/vlm_locateanything.rs and src/loading/vlm_locateanything_quant.rs (loader), each with a _tests.rs beside it.

Where LocateAnything is genuinely not Kimi-VL. The connector normalizes over the flattened merged patch (vision_hidden * merge_h * merge_w, 4608 in the released checkpoint, which its layer_norm.weight shape confirms) rather than over the 1152-wide vision hidden dim. The processor resizes each side UP to the next multiple of merge * patch where Kimi-VL centre-crops DOWN, and normalizes with mean = std = 0.5 rather than the CLIP statistics. Neither is shared.

Image-token splice. <image-N> is what the chat template renders, and it is plain text rather than a vocabulary token, so the rewrite into <img> + <IMG_CONTEXT> * (grid_h * grid_w / merge_length) + </img> happens on the rendered prompt and is re-encoded, matching upstream's re.sub. A token-level splice covers --no-chat-template runs. The runtime then verifies the encoded stream carries exactly as many <IMG_CONTEXT> ids as the tower will emit feature rows, so a drift cannot silently scatter image features into text positions.

Control-plane wiring. ModelType::LocateAnythingVLM with the "locateanything" detection arm (which has to win at the top level, because the text sub-config also says "qwen2"), for_each_model_registration! entry, LoadedModel variant, VlmRuntimeRef::LocateAnything, the try_load_vlm_model_from_dir route, a generate_vlm summary line, and the TP arch-string table (LocateAnything's backbone is llama-family; TP is refused for VLM-kind models earlier, this just keeps the dispatch total).

Two real-checkpoint gaps the Python reference did not show

Both were found by running the actual checkpoint, not by reading mlx_vlm.

The conversion is mixed_4_8, not uniform 4-bit. The model card explains why: pure 4-bit on the tied embed_tokens destroys coordinate-token precision. 18 of the 36 layers store v_proj at 8 bits while q_proj and k_proj stay at 4. Every per-tensor loader reconciles its own width from tensor shapes and is fine, but FusedQKVLinear::from_weights_separate concatenates the three packed planes along axis 0 and infers one width from q_proj, which is a hard shape error inside MLX for a mixed layer ([2048, 256] against [256, 512]). The loader dequantizes the three planes of an affected layer, which is exact. It deliberately does not requantize the narrow planes up to the wider width: MLX's affine quantizer snaps the group scale onto the larger-magnitude edge rather than using a plain (max - min) / (2^bits - 1), so a 4-bit group does not land on the 8-bit grid and a round trip perturbs the weights by up to half an 8-bit step (measured 3.7e-3 on a synthetic plane before switching approaches). The cost is roughly 190 MB on the released 3B checkpoint. Note this is not LocateAnything-specific: any family on the shared fused-QKV loader would hit the same wall on an mlx_lm --quant-predicate mixed_4_8 conversion. Fixing it properly needs a FusedQKVLinear that can hold per-projection widths, which is a shared-layer change and is left as a follow-up.

The checkpoint ships no tokenizer.json. Neither nvidia/LocateAnything-3B nor its MLX conversions exported a fast tokenizer, only vocab.json + merges.txt + added_tokens.json + tokenizer_config.json, so load_tokenizer had nothing to read and the model could not load at all. A new last-resort fallback reconstructs the tokenizer the way transformers' Qwen2Converter does, component for component: byte-level BPE with no unk token and no subword prefix or suffix, NFC normalizer, Sequence[Split(PRETOKENIZE_REGEX, isolated), ByteLevel(add_prefix_space, use_regex=false)], ByteLevel decoder, ByteLevel post-processor with trim_offsets = false. It is gated on tokenizer_class naming the Qwen2 tokenizer as well as on both files being present, because vocab.json + merges.txt is the generic GPT-2 slow-tokenizer pair and another family shipping it must not be tokenized with Qwen2's rules. Added tokens are registered in ascending id order and then verified against the ids the checkpoint declares, since tokenizers assigns them sequentially from the base vocab size and a gap would shift every later token silently; LocateAnything's 1038 added tokens include the 1001 coordinate tokens that carry its box output, where an off-by-one would corrupt every box rather than fail loudly.

Real-checkpoint validation

GB10, CUDA (sm_121), release build, mlx-community/LocateAnything-3B-4bit, on the COCO image the model card's own usage example uses (http://images.cocodataset.org/val2017/000000039769.jpg).

$ ./target/release/mlxcel generate -m models/mlx/locateanything-3b-4bit \
    --image 000000039769.jpg -p "Detect all objects in the image." -n 128 --temp 0.0
LocateAnything: inserted 1 image block(s) (414 total image tokens)
<ref>object</ref><box><64><152><273><244></box><box><520><160><580><392></box>
[Generated 15 tokens in 1.68s = 8.91 tok/s]

The first box <64><152><273><244> is byte-identical to the <ref>remote</ref><box><64><152><273><244></box> the model card documents for this image, and the object label instead of remote is exactly the semantic generalization the card documents for this 4-bit conversion. The second box is 333,77,371,188 in pixels against a COCO ground-truth remote of 333,72,368,187.

Referring and multi-object queries on the same image:

-p "...the region this sentence describes: the cat on the right."
-> <ref>the cat on the right</ref><box><541><49><1000><778></box>     (346,24,640,373 px; GT 345,23,640,368)

-p "Detect all the cats in the image."
-> <ref>the cats in the image</ref><box><9><112><494><989></box><box><541><52><1000><775></box>
                                    (6,54,316,475 px; GT 13,52,314,470)  (346,25,640,372 px; GT 345,23,640,368)

./target/release/mlxcel arch lists LocateAnything (MoonViT + MLP connector + Qwen2, grounding).

The tokenizer was separately validated against a transformers Qwen2Tokenizer oracle built from the same checkpoint directory: 7 cases covering the rendered ChatML prompt, a <ref>/<box> grounding string, repeated whitespace and newline runs, tabs, CJK and accented Latin text, and the apostrophe contractions the pre-tokenize regex special-cases. All 7 encode token-exact and decode round-trip exactly. That harness was a throwaway and is not part of the diff.

Finalization pass

One review-fix seam had no regression test: the bf16-ordering fix (densify the mixed-precision QKV planes before the Apple Silicon bf16 -> f16 pass, not after) was previously validated only by reading the diff, because the host that landed it could not run its own test suite in that session. load_locateanything_vlm's two inline passes are now reconcile_mixed_precision_weights, a private function that takes the Apple Silicon gate as a convert_bf16: bool parameter instead of reading hardware::get_hardware() internally, so a test can force the conversion branch independent of the host it runs on (this GB10 box is CUDA, not Apple Silicon, and would otherwise never execute that branch). Two new tests in src/loading/vlm_locateanything_tests.rs quantize a bf16-sourced dense plane the way the released checkpoint's mixed-precision layers do (confirming the scales stay bf16, which is the premise of the whole bug), densify it, and assert the densified planes land on f16 only when the conversion flag is set; the control test proves the f16 dtype comes from the conversion pass and not from densification itself. No behavior changed, only the call composition became a named, independently testable unit.

Test plan

  • cargo test --release --features cuda --lib locateanything -- --test-threads=1 (53 passed, 0 failed)
  • cargo test --release --features cuda --lib tokenizer -- --test-threads=1 (75 passed, 0 failed, 5 ignored)
  • cargo test --release --features cuda --lib kimi_vl -- --test-threads=1 (25 passed, 0 failed)
  • cargo test --release --features cuda --lib detection -- --test-threads=1 (80 passed, 0 failed)
  • cargo test --release --features cuda --lib model_metadata -- --test-threads=1 (8 passed, 0 failed)
  • cargo test --release --features cuda --lib loading:: -- --test-threads=1 (255 passed, 0 failed)
  • cargo test --release --features cuda --lib vision:: -- --test-threads=1 (314 passed, 0 failed, 17 ignored)
  • cargo test --release --features cuda --lib multimodal:: -- --test-threads=1 (187 passed, 0 failed, 17 ignored)
  • cargo test --release --features cuda --test kimi_vl_parity -- --test-threads=1 (3 passed, 0 failed)
  • cargo clippy --features cuda --lib --tests -- -D warnings (clean)
  • cargo fmt --all
  • Real-checkpoint generation above

Not run here, left to the broader gate: the full cargo test --workspace and any non-CUDA / Apple Silicon path. The Apple Silicon bf16-to-f16 branch in the loader mirrors the InternVL one line for line but was not exercised on this Linux box.

Follow-up (explicitly out of scope for #847)

  • The pbd parallel box-decoding path with its multi-token-prediction heads (n_future_tokens = 6), and coordinate-token-to-box post-processing. Plain autoregressive decode emitting coordinate tokens as text was the target here.
  • A FusedQKVLinear that holds per-projection quantization widths, which would remove the dequantize-on-mixed-precision workaround for every family, not just this one.

Closes #847

LocateAnything (#847) embeds the same MoonShot MoonViT-SO-400M tower Kimi-VL uses, so its port reuses this encoder rather than duplicating 600 lines. Its upstream implementation diverges in exactly two places, and both are numeric rather than structural: the block/final LayerNorm epsilon is 1e-5 rather than 1e-6, and the block MLP applies `nn.GELU(approx="precise")` (MLX's tanh approximation) rather than `nn.GELU()` (exact erf).

The epsilon was already a config field. The activation was hardcoded, so it becomes `MoonViTMlpActivation` on the vision config, defaulting to the exact erf form. Kimi-VL and Kimi-VL 2.5 keep the activation they had; only a config that opts in gets the tanh form.

`mlxcel_core` exposes no elementwise tanh-approximate GELU (both `gelu` and, despite its name, `gelu_approx` are erf-based), so the tanh form is synthesised from primitives the way `models::kokoro::ops::gelu_new` does.

Refs #847
`nvidia/LocateAnything-3B` and its MLX conversions ship only the slow-tokenizer files: `vocab.json`, `merges.txt`, `added_tokens.json`, `tokenizer_config.json`. There is no exported `tokenizer.json`, no SentencePiece model, no tiktoken vocab and no `tokenizer.jsonl`, so `load_tokenizer` had nothing to read and the checkpoint could not load at all. Transformers handles this by running `Qwen2Converter` at load time; this is the same construction.

The new fallback sits last, after every existing format, and is gated on `tokenizer_class` naming the Qwen2 tokenizer as well as on both files being present. `vocab.json` + `merges.txt` is the generic GPT-2 slow-tokenizer pair, and a different family shipping it (with another normalizer, pre-tokenize regex, or prefix-space convention) must not be silently tokenized with Qwen2's rules.

Components mirror `transformers/convert_slow_tokenizer.py::Qwen2Converter` one for one: byte-level BPE with no unk token and no subword prefix or suffix, an NFC normalizer, `Sequence[Split(PRETOKENIZE_REGEX, isolated), ByteLevel(add_prefix_space, use_regex=false)]` as the pre-tokenizer, a ByteLevel decoder, and a ByteLevel post-processor with `trim_offsets = false`.

Added tokens are registered in ascending id order and then verified against the ids the checkpoint declares. `tokenizers` assigns added-token ids sequentially from the base vocab size, so a gap or an out-of-order entry would shift every later token silently. LocateAnything's 1038 added tokens include the 1001 coordinate tokens `<0>`..`<1000>` that carry its box output, where an off-by-one would corrupt every box rather than fail loudly.

Validated against a `transformers` `Qwen2Tokenizer` oracle on the real `mlx-community/LocateAnything-3B-4bit` directory: 7 cases covering the rendered ChatML prompt, a `<ref>`/`<box>` grounding string, repeated whitespace and newline runs, tabs, CJK and accented Latin text, and the apostrophe contractions the regex special-cases. All 7 encode token-exact and decode round-trip exactly.

Refs #847
LocateAnything is NVIDIA's ~3B generative grounding VLM: a MoonViT vision tower and an MLP connector feeding a Qwen2 text decoder whose output interleaves `<ref>`/`<box>` markers and the 1001 coordinate tokens `<0>`..`<1000>` (ids 151677..152677). Plain autoregressive decode is enough to produce those, so the port needs no special detokenization.

The tower is the same MoonShot MoonViT-SO-400M Kimi-VL embeds, so `vision::encoders::kimi_vl` is reused and only the two deltas its upstream implementation actually carries are expressed through the config (LayerNorm eps 1e-5, tanh-approximate GELU in the block MLP). The text side is `models::Qwen2Model` verbatim.

New pieces:

- `vision/locateanything.rs` — the VLM runtime and the `multi_modal_projector` connector. The connector normalizes over the flattened merged patch (`vision_hidden * merge_h * merge_w`, 4608 in the released checkpoint, which is what its `layer_norm.weight` shape confirms) rather than over the 1152-wide vision hidden dim, which is where it differs from the Kimi-VL projector.
- `vision/processors/locateanything.rs` — a native-resolution processor that is deliberately not shared with the Kimi-VL one: LocateAnything resizes each side UP to the next multiple of `merge * patch` where Kimi-VL centre-crops DOWN, and normalizes with `mean = std = 0.5` rather than the CLIP statistics.
- `multimodal/locateanything_prompt.rs` — the `<image-N>` expansion. That marker is plain text, not a vocabulary token, so the rewrite into `<img> + <IMG_CONTEXT> * (grid_h * grid_w / merge_length) + </img>` happens on the rendered prompt and is re-encoded, matching upstream's `re.sub`. A token-level splice covers `--no-chat-template` runs. The runtime then checks the encoded stream carries exactly as many `<IMG_CONTEXT>` ids as the tower will emit feature rows, so a drift cannot silently scatter image features into text positions.
- `loading/vlm_locateanything.rs` plus `_quant.rs` — config normalization, weight-key remapping, and the mixed-precision reconciliation described below.

Two properties of the released conversion needed handling beyond the model graph, and neither was visible from the Python reference.

It is a `mixed_4_8` quantization rather than uniform 4-bit (the model card explains why: pure 4-bit on the tied `embed_tokens` destroys coordinate-token precision). 18 of the 36 layers store `v_proj` at 8 bits while `q_proj` and `k_proj` stay at 4. Every per-tensor loader reconciles its own width from the tensor shapes and is fine, but `FusedQKVLinear::from_weights_separate` concatenates the three packed planes along axis 0 and infers one width from `q_proj`, which is a hard shape error inside MLX for a mixed layer (`[2048, 256]` against `[256, 512]`). The loader therefore dequantizes the three planes of an affected layer, which is exact, and does not requantize the narrow ones up: MLX's affine quantizer snaps the group scale onto the larger-magnitude edge rather than using a plain `(max - min) / (2^bits - 1)`, so a 4-bit group does not land on the 8-bit grid and a round trip perturbs the weights by up to half an 8-bit step (measured 3.7e-3 on a synthetic plane). The cost is about 190 MB on the released 3B checkpoint; removing it needs a `FusedQKVLinear` that can hold per-projection widths, which is a shared-layer change.

The weight-key remapping is also a no-op on the released MLX conversion, which already ships the post-sanitize names. It reproduces upstream `Model.sanitize` plus `VisionModel.sanitize` anyway so an unconverted `nvidia/LocateAnything-3B` checkpoint loads through the same path, and it drops `language_model.lm_head.weight` only when the text config ties embeddings rather than unconditionally as upstream does.

Real-checkpoint validation on `mlx-community/LocateAnything-3B-4bit` (GB10, CUDA, release build), against the COCO image the model card's own usage example uses:

    mlxcel generate -m models/mlx/locateanything-3b-4bit --image 000000039769.jpg \
      -p "Detect all objects in the image." -n 128 --temp 0.0
    -> <ref>object</ref><box><64><152><273><244></box><box><520><160><580><392></box>

The first box is byte-identical to the output the model card documents for that image, and the `object` label instead of `remote` is the generalization the card documents for this 4-bit conversion. A referring query ("the cat on the right") returns `<541><49><1000><778>`, which is 346,24,640,373 in pixels against a COCO ground-truth box of 345,23,640,368.

Out of scope, noted as a follow-up: the checkpoint's parallel box-decoding path (`pbd`, `n_future_tokens = 6`) and coordinate-token-to-box post-processing.

Closes #847
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata labels Aug 7, 2026
The Apple Silicon bf16 to f16 pass in `load_locateanything_vlm` ran before `densify_mixed_precision_qkv`, but MLX's `dequantize` returns an array carrying the scales' dtype and the conversion deliberately keeps `.scales` / `.biases` at bf16. Every dense q/k/v plane the densification inserted was therefore a fresh bf16 tensor created after the only pass that would have converted it: 54 tensors (18 mixed layers x 3 projections) on the released 3B checkpoint, which is exactly the M5 JIT crash the loader exists to avoid. Densification now runs first, so its output is converted along with the MoonViT tower and the connector, and the densified planes no longer carry `.scales` / `.biases` so the keep-predicate does not exempt them. `vlm_locateanything_quant.rs` is unchanged; only the call ordering was wrong.

`read_added_tokens_sorted` defaulted an added token's `special` flag to true in both branches, inverting HuggingFace's `AddedToken` default. The `added_tokens.json` fallback was worse: that file is a flat content-to-id map carrying no flags at all, so every entry was forced special. Because `AddedVocabulary`'s `special_tokens_set` is insert-only (the same property already documented for `demote_tool_parser_markers` in #778), a content-bearing token registered special can never be demoted and is stripped from every `decode` with `skip_special_tokens`. Both defaults are now false, so a Qwen2-family checkpoint shipping only `added_tokens.json` keeps its added tokens. LocateAnything is unaffected either way: its `added_tokens_decoder` carries an explicit `special` on all 1038 entries, so neither default is reachable for it.

`LocateAnythingProcessor::merged_token_count` reimplemented `multimodal::locateanything_prompt::merged_token_count` rather than calling it. It now delegates, so the processor and the `<IMG_CONTEXT>` run builder cannot drift apart.

Two new unit tests in `src/tokenizer/mod.rs` cover the added-token defaults through both branches, asserting the parsed flags and the resulting `skip_special_tokens` decode. Validated with `cargo fmt --all` (no changes) and by review; the test suite was not run in this session because a CUDA gate held the workspace target directory.

Refs #847
@inureyes

inureyes commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Add native locateanything VLM support (MoonViT tower reused from Kimi-VL + MLP connector + Qwen2 text decoder), plain autoregressive grounding decode only, with pbd and coordinate-to-box post-processing explicitly deferred.

Findings Addressed

  • (HIGH) src/loading/vlm_locateanything.rs: the Apple Silicon bf16 to f16 pass ran before densify_mixed_precision_qkv. MLX's dequantize returns an array carrying the scales' dtype, and the keep-predicate deliberately holds .scales / .biases at bf16, so every dense q/k/v plane the densification inserted was a fresh bf16 tensor created after the only pass that would have converted it: 54 tensors (18 mixed layers x 3 projections) on the released 3B checkpoint, defeating the exact M5 JIT-crash mitigation the loader's own module doc says it exists to apply. Densification now runs first. Independently confirmed by the Codex reviewer as its sole P1.
  • (MEDIUM) src/tokenizer/mod.rs read_added_tokens_sorted: special defaulted to true in both branches, inverting HuggingFace's AddedToken default. The added_tokens.json branch was worse, forcing every entry special although that file carries no flags at all. Since AddedVocabulary's special_tokens_set is insert-only (already documented in this file for fix(diffusion_gemma): demote tool-parser markers from special tokens at load #778), a content-bearing token registered special can never be demoted and is stripped from every skip_special_tokens decode. Both defaults are now false, with two new unit tests covering both branches. LocateAnything is unaffected either way: its added_tokens_decoder carries an explicit special on all 1038 entries.
  • (LOW) src/vision/processors/locateanything.rs: merged_token_count reimplemented multimodal::locateanything_prompt::merged_token_count and was reachable only from its own unit test. It now delegates, per the reuse direction in feat(models): add LocateAnything (locateanything) VLM support #847.

Fixed in 5ad34371.

Remaining Items

  • (MEDIUM, pre-existing, deliberately not fixed here) The no-placeholder fallback in locateanything_prompt.rs:216-220 splices the image block after prompt_tokens[0], which under --no-chat-template is an ordinary BPE token rather than a ChatML framing token, so the block can land inside the first word. Raised by the Codex reviewer. This is not introduced by this PR: internvl_prompt.rs:118, smolvlm_prompt.rs:133, and kimi_vl_prompt.rs:134 all use the identical let head = prompt_tokens[0] splice. Changing it for LocateAnything alone would make it inconsistent with three sibling families, so it belongs in a follow-up against the shared pattern.
  • (LOW) The new tokenizer path does not call ensure_bos_post_processor, unlike the tokenizer.json branch. Only reachable for a Qwen2 slow-tokenizer checkpoint declaring add_bos_token: true; no regression, since the path cannot run when tokenizer.json exists.

Notes on the three regression-risk areas

1. Tokenizer gating (src/tokenizer/mod.rs): verified safe. The fallback cannot preempt any checkpoint that previously loaded a real tokenizer. load_tokenizer returns unconditionally from the tokenizer.json branch at line 1236, and the new is_qwen2_slow_tokenizer_dir check sits at line 1284, after tokenizer.model, *.tiktoken, and tokenizer.jsonl. It additionally requires tokenizer_class to be exactly Qwen2Tokenizer or Qwen2TokenizerFast, so an absent or Qwen2-adjacent class falls through unchanged rather than being tokenized with Qwen2's rules. Checked against a real local checkpoint: moondream2 ships vocab.json + merges.txt (the generic GPT-2 pair) but declares CodeGenTokenizer, so it is excluded by the class gate and by the tokenizer.json early return. The one theoretical ordering interaction, preempting the moondream3 remote-tokenizer fallback, requires a moondream3 checkpoint with no tokenizer.json that declares a Qwen2 class; moondream3 is CodeGen-family, so this is unreachable in practice. The reconstruction itself matches transformers Qwen2Converter component for component (BPE with no unk / no prefix / no suffix, NFC, Sequence[Split(regex, isolated, invert=false), ByteLevel(add_prefix_space, use_regex=false)], ByteLevel decoder, ByteLevel post-processor with trim_offsets=false).

2. Mixed 4/8-bit handling (vlm_locateanything_quant.rs): logic correct, one ordering bug (fixed). Dequantization is exact by construction and the unit tests assert max_abs_diff == 0.0 on all three planes. Scoping is right: only prefixes ending .self_attn that carry q_proj.scales are considered, per-projection layouts are reconciled from actual tensor shapes, and a layer is skipped when all three agree on both bits and group_size, so uniform-4-bit and uniform-8-bit layers stay packed (both covered by positive-control tests). The unsafe block is correctly scoped with a SAFETY comment; the raw biases pointer is null or borrowed from a live entry in the same map for the call's duration. The roughly 190 MB cost is documented in the module doc and logged via tracing::info!. The only defect was the loader-side call ordering above.

3. Kimi-VL MoonViT refactor: byte-unchanged. MoonViTMlpActivation derives Default with #[default] on Gelu (the erf form) and the config field carries #[serde(default)], so a Kimi-VL config.json, which has no mlp_activation key, deserializes to the exact prior behavior at vlm_kimi_vl.rs:60. GeluTanh is set only in LocateAnythingVisionConfig::to_moonvit_config, from a struct literal, never from Kimi-VL's deserialization path. tests/kimi_vl_parity.rs was not weakened: the only change is adding mlp_activation: MoonViTMlpActivation::Gelu to the tiny_config struct literal (mandatory once the field exists) plus the import; every assertion is unchanged. Same for kimi_vl_tests.rs.

Verification

  • All stated requirements implemented (every acceptance criterion in feat(models): add LocateAnything (locateanything) VLM support #847 except the two it explicitly defers)
  • No placeholder/mock code remaining (no TODO / FIXME / todo! / unimplemented! in the diff; pbd appears only in doc comments marking it out of scope)
  • Integrated into project code flow (detection arm, for_each_model_registration!, LoadedModel, VlmRuntimeRef, loader route, vlm_runtime dispatch, generate_vlm summary, TP arch string, docs/supported-models.md; the only sites where an analogous VLM is registered and LocateAnything is not are the two video paths in server/startup.rs and server/model_worker.rs, which is correct since LocateAnything is image-only, and InternVL is likewise absent there)
  • Project conventions followed
  • Existing modules reused where applicable (Kimi-VL MoonViT encoder, models::Qwen2Model, vision::merge::merge_llava, load_vlm_weights_common, reconcile_quantization_layout)
  • No unintended structural changes
  • Tests pass (not run in this review; CUDA test execution is owned by the merge gate running concurrently)

A model directory is semi-trusted, but a malformed `config.json` or `preprocessor_config.json` must produce a clean `Err`, never a panic or an unbounded allocation. Four paths in the new LocateAnything support failed that bar.

`merged_token_count` divided by `(merge_h * merge_w) as i32`. A `usize` product of `65536 * 65536` is exactly `2^32`, so the narrowing cast truncated it to 0 and the next line panicked with "attempt to divide by zero". That pair is square and non-zero, so it survived both existing guards: `merge_kernel()`'s `.max(1)` floor and `to_moonvit_config()`'s square-kernel check. The merge product is now formed with `saturating_mul` and clamped into `1..=i32::MAX` before the cast, and the patch product is formed in `i64` so two `i32` grid sides cannot overflow either.

The connector width had the same shape of bug one layer up: `(hidden_size * merge_h * merge_w) as i32` could overflow the `usize` multiply and then truncate. With the released `hidden_size: 1152` and that same merge pair the result was `input_dim == 0`, which reaches `LocateAnythingConnector::forward`'s `reshape(image_features, &[-1, 0])` and throws inside MLX, and a C++ throw across the cxx boundary aborts the process instead of unwinding into a `Result`. The computation moves into a `connector_input_dim` helper that uses `checked_mul` plus `i32::try_from` and returns a descriptive error naming the offending config values.

Two unbounded-allocation vectors are now capped. `patch_size` drives the resize quadratically: step 2 rounds each side up to a multiple of `merge * patch` and the only ceiling was the 511-patch grid envelope, so a declared `patch_size: 100000` asked `resize_exact` for a ~200000x200000 RGB buffer (over 100 GB) and OOM-aborted the process. The `in_token_limit` downscale could not save it, because `(w / p) * (h / p)` is 0 once `p` exceeds the image and the downscale never engages. Separately, `in_token_limit` is read from `preprocessor_config.json` and is the only thing that engages that downscale at all, so an unbounded value left a single image bounded only by the grid envelope, roughly 614 MB of f32 patch data at `patch_size: 14` plus the resized RGB image and the MLX array copy.

`patch_size` and `merge_kernel_size` are rejected rather than clamped at the loader (`to_moonvit_config`), because each is consumed twice and the two consumers have to agree: the processor derives the patch grid from them, while the MoonViT conv patch-embed and patch merger are sized from the `KimiVLVisionConfig` built alongside. Clamping only the processor side would turn a loud failure into a quiet mis-computation. `LocateAnythingProcessor::new` still clamps as a backstop for its `pub` constructor, against constants kept equal to the loader's and pinned by a test. `in_token_limit` is clamped rather than rejected, since the tower never sees it and nothing can desync.

Valid checkpoints are unaffected: the released geometry (`patch_size: 14`, `merge_kernel_size: [2, 2]`, `in_token_limit: 25600`, vision `hidden_size: 1152`) sits well inside every bound and passes through unchanged, which a test asserts directly. The ceilings are 128 for `patch_size` (every ViT/MoonViT patch size in this tree is 14 or 16, with a single 48), 16 per merge axis (real spatial merges are 1, 2, or 4), and 102400 for `in_token_limit` (4x upstream's 25600).

Validated on Linux aarch64 with the CUDA feature: `cargo check --features cuda --lib --tests` and `cargo clippy --features cuda --lib --tests -- -D warnings` both clean, `cargo fmt --check` clean, and the three affected suites green at `--test-threads=1` with `MLX_ENABLE_TF32=0` (13 in `multimodal::locateanything_prompt`, 12 in `vision::processors::locateanything`, 23 in `loading::vlm::locateanything`). New regression tests cover the confirmed division by zero, the `i64` grid widening, the connector-width overflow and zero-width rejection, the loader range checks at and past each boundary, the processor clamps, and the released-config passthrough.

Refs #847
`build_qwen2_bpe_tokenizer` registered added tokens one at a time. Every `Tokenizer::add_tokens` / `add_special_tokens` call ends in `AddedVocabulary::refresh_added_tokens`, which rebuilds both Aho-Corasick automatons over every token accumulated so far, and `add_tokens` additionally clones the whole existing token set first, so N entries cost N full rebuilds. Measured against the pinned tokenizers 0.22.2 in a release build, the loop is cleanly quadratic at 4x per doubling: 500 entries 46.9 ms, 1000 162 ms, 2000 609 ms, 4000 2.42 s, 8000 10.1 s, 16000 46.1 s. A checkpoint with a large `added_tokens_decoder` therefore wedged the loader with no error and no timeout, and LocateAnything's own 1038 added tokens paid 175 ms instead of 0.5 ms. This was a regression against main, where added tokens only arrived through `tokenizer.json`, whose deserializer makes a single batched call.

Adds are now batched. End to end through the loader on synthetic checkpoints: 1038 added tokens 197.6 ms to 1.5 ms, 4000 2.54 s to 4.8 ms, 16000 44.0 s to 23.3 ms, with the resulting added-token tables and encodings identical in every case.

The batches are consecutive runs of the same `special` flag, not one specials group plus one normals group. `tokenizers` hands out ids in the order tokens are passed, so regrouping is not id-preserving: measured directly, `[A(special), B(normal), C(special)]` declared as 7, 8, 9 comes back as A=7, C=8, B=9 under a two-group split, silently mis-mapping the vocabulary. Runs keep the sorted order intact. A uniformly special checkpoint (LocateAnything, and the common case generally) collapses to a single call, and a perfectly alternating one degrades to the previous per-token cost without moving an id, measured at 179 ms before and 180 ms after for 1038 alternating tokens. Run-batching was verified id-identical against the per-token loop across 33 flag patterns covering all-special, all-plain, both alternations, the `[special, normal, special]` trap, mixed runs, the 1038-token LocateAnything shape, and 24 seeded random sequences, comparing the full id to (content, special) table plus encode and decode output.

`vocab.json` is now rejected unless its ids are exactly `0..len`, with the gap or the duplicated id named in the error. The file is a `content -> id` map and nothing in the format forces dense ids, but `BPE::get_vocab_size()` reports `vocab.len()` and `AddedVocabulary` starts assigning added-token ids from that number regardless of which ids are actually occupied. Measured with `{"Ġ":0,"h":1,"Ġh":2,"i":3,"COLLIDE":5}` plus an added token declaring id 5: before the add, `token_to_id("COLLIDE")` is 5 and `decode([5])` is `COLLIDE`; after it, `token_to_id` returns 5 for both `COLLIDE` and the added token, `decode([5])` yields the added token instead, and the existing contiguity check still passes because the assigned id equals the declared one. Recomputing our own base vocab size would not fix this because the library still starts from `vocab.len()` and the starting id cannot be overridden, so refusing the input is the only sound response, and it is what the function's doc comment already claimed; that comment is updated to describe what the code now actually guarantees. All 65 `vocab.json` files in the local model set are dense, so no real checkpoint is turned away.

Tests added to `src/tokenizer/mod.rs`:

- a gapped `vocab.json` is rejected, and the error names both the unused id and the entry that overshot
- a `vocab.json` that assigns one id twice is rejected, and the error names both colliding contents
- a dense `vocab.json` with six added tokens still builds, with every declared id resolving to its declared content in both directions and the base vocab left untouched
- a nine-token sequence that alternates `special` six times keeps every declared id, content, and flag, which is the regression guard for the run-batching change

Validated with `cargo check --features cuda --lib --tests`, a clean `cargo clippy --features cuda --lib --tests -- -D warnings`, `cargo fmt`, and `MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib tokenizer -- --test-threads=1` at 75 passed, 0 failed.

Refs #847
@inureyes

inureyes commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Security and performance review

Reviewed for security vulnerabilities and performance issues. Two fixes pushed (9f65b9d4, b082ed26). Details below, including what was checked and found safe, since that constrains the severity of what remains.

unsafe block: SOUND

src/loading/vlm_locateanything_quant.rs:152 is the standard cxx nullable-biases bridge pattern already used at 17+ call sites (for example src/lib/mlxcel-core/src/layers.rs:514).

  • b.as_ref() correctly yields None for a null UniquePtr, so a missing biases becomes a null pointer rather than a dangling one. The C++ side (mlx_cxx_bridge.cpp:2968) dereferences only when non-null, copies into std::optional<array>, and never retains the pointer.
  • The raw pointer derives from a shared borrow of weights that is still live at the call, and the map is not mutated until the insert after the block ends. No aliasing or use-after-free. A null UniquePtr in w/s panics in Deref rather than causing UB.
  • Attacker-influenced values cannot reach it unvalidated: reconcile_quantization_layout runs first and validates group_size, bits, and the mode string, propagating Err before dequantize is called. A malformed checkpoint yields a clean error.

Fixed

Division by zero, src/multimodal/locateanything_prompt.rs:137. merge_kernel_size: [65536, 65536] gives a usize product of exactly 2^32; .max(1) left it and as i32 truncated it to 0, so the next line divided by zero. That pair is square and non-zero, so it passed both existing guards. Confirmed by running it at -O. Now uses saturating_mul plus clamp(1, i32::MAX) before the cast, with the patch product widened to i64.

Truncating input_dim, src/loading/vlm_locateanything.rs:363. (hidden_size * merge_h * merge_w) as i32 could overflow and truncate; with the released hidden_size: 1152 and that same merge pair it produced input_dim == 0, reaching reshape(image_features, &[-1, 0]) and throwing inside MLX, which aborts across the cxx boundary instead of unwinding. Now a connector_input_dim helper using checked_mul plus i32::try_from.

Unbounded allocation from patch_size and in_token_limit. The only ceiling on the resize was the 511-patch grid envelope, so the resized side scaled as 511 * patch_size and the f32 patch buffer as patch_size^2. A declared patch_size: 100000 asked resize_exact for a ~200000x200000 RGB buffer. The in_token_limit downscale could not save it, since (w / p) * (h / p) is 0 once p exceeds the image. Separately an unbounded in_token_limit from preprocessor_config.json left one image bounded only by that envelope, roughly 614 MB of f32 patch data. patch_size and merge_kernel_size are now rejected at to_moonvit_config rather than clamped, because both are consumed twice and clamping only the processor would desync the emitted patch grid from the MoonViT tower sized from the unclamped config. in_token_limit is clamped, since the tower never sees it.

Quadratic tokenizer DoS, src/tokenizer/mod.rs. The added-token loop registered one token per call, and each call rebuilds both Aho-Corasick automatons over everything accumulated so far. Measured release timings: 4000 tokens 2.51 s, 8000 10.3 s, 16000 42.9 s, extrapolating to about 28 minutes for 100k entries with no error and no timeout. This was also a regression against the tokenizer.json path on main, which batches: 10.2 ms versus 42.9 s at 16k. Now batches consecutive runs of the same special flag. Runs rather than a two-group split, because add_tokens assigns ids in slice order, so grouping all specials first reorders them (verified: a naive split maps declared 8 and 9 onto assigned 9 and 8). Id preservation was checked across 33 flag patterns including the 1038-token LocateAnything shape, all identical. Measured after: 1038 tokens 197.6 ms to 1.5 ms, 16000 tokens 44.05 s to 23.3 ms, with no regression in the alternating worst case.

Silent token-id aliasing, src/tokenizer/mod.rs. base_vocab_size came from vocab.len(), but vocab.json ids need not be dense and tokenizers also assigns from len(). With a 5-entry vocab whose max id is 5 plus an added token declaring id 5, the build returned Ok and decode([5]) flipped from "COLLIDE" to "<x>", with two tokens sharing id 5. Recomputing the base size does not help, since the library still assigns from len(), so a non-dense vocab.json is now rejected. All 65 real vocab.json files checked locally are dense.

Checked and safe

  • Path handling in the tokenizer is clean. Every join uses a hardcoded literal, so no path component originates from file content and ../ escape is not possible.
  • No unwrap, expect, indexing, or with_capacity in the new tokenizer non-test code. All 16 malformed-input cases return Err rather than panicking. No UTF-8 boundary hazard, since the empty continuing_subword_prefix makes the one boundary-sensitive BPE slice a no-op.
  • With a valid config, image-driven allocation is bounded at roughly 61 MB of f32 per image. The in_token_limit downscale and the grid clamp together make a 510x510 grid unreachable, so adversarial aspect ratios cannot escape the budget.
  • The densification path is load-time only (single call site), engaged only when the three planes genuinely disagree on bits or group size, and bounded by model size. The decode hot path delegates straight to the Qwen2 backbone with no per-token allocation.

Not fixed, for maintainer judgement

  • language_weights_subset (src/loading/vlm_locateanything.rs:373) copies every language_model.* tensor via mlxcel_core::copy, which is a real array copy, transiently duplicating the whole text stack (roughly 1.8 GB for the 3B checkpoint) until the drop after Qwen2Model::from_weights. This stacks with the 190 MB densification. It is the identical pattern in vlm_internvl.rs:247 and vlm_lfm2_vl.rs:81, so it is a family convention rather than a regression here. Since the language keys are disjoint from the vision and connector keys, draining instead of copying would remove the peak, but that is a shared-pattern change.
  • Unbounded u32 ids from vocab.json reach encode() output. The samplers bounds-check (sampling.rs:222, :786, :1047, :1382), but the prompt-embedding gather was not traced to a bounds check. Not new in kind: main's tokenizer.json path accepts the same range.
  • tokenizer_config.json is read and parsed three times per load (roughly 1.3 s on a large file). Measured RSS amplification is 1.0x, so this is cost rather than risk.
  • An empty prompt combined with an image skips the placeholder-count guard in vlm_runtime.rs and reaches merge_llava with feature rows but no matching positions. Niche, needs --no-chat-template with an empty prompt, and produces a confusing MLX-level failure rather than a clean error.

Verification

Linux aarch64, CUDA feature, --test-threads=1, MLX_ENABLE_TF32=0. Re-run independently rather than taken from the fix runs: 51 passed across the four locateanything suites, 75 passed in tokenizer (5 ignored). cargo clippy --features cuda -p mlxcel --lib --tests -- -D warnings clean, cargo fmt --check clean. None of the 5 pre-existing failures on origin/main are affected.

One testing note worth carrying forward: the filter --lib loading::vlm_locateanything matches zero tests and prints test result: ok, a false green. The module path is loading::vlm::locateanything, declared under a vlm parent rather than by filename.

…ssion test

The bf16-ordering fix in commit 5ad3437 (densify mixed-precision QKV before the Apple Silicon bf16 -> f16 pass, not after) had no regression test: the host that landed it could not run the suite in that session, and this GB10 box is CUDA, not Apple Silicon, so the hardware-gated conversion branch never executes here regardless of test placement.

`load_locateanything_vlm`'s two inline passes are now `reconcile_mixed_precision_weights`, a private function in `src/loading/vlm_locateanything.rs` that takes the Apple Silicon gate as a `convert_bf16: bool` parameter instead of reading `hardware::get_hardware()` internally. This is a pure extraction with no behavior change at the real call site, but it lets a test force the conversion branch independent of the hardware it runs on.

Two new tests in `src/loading/vlm_locateanything_tests.rs` quantize a bf16-sourced dense plane the way the released checkpoint's mixed-precision layers do, which confirms MLX's quantizer keeps the scales at bf16 (the premise the whole bug rests on), then densify it and assert the densified planes land on f16 only when `convert_bf16` is set. The control test with the flag off proves the f16 dtype in the first test comes from the conversion pass and not from densification itself.

Validation:
- `cargo fmt --all` and `cargo clippy --features cuda --lib --tests -- -D warnings` both clean
- `MLX_ENABLE_TF32=0 cargo test --release --features cuda --lib locateanything -- --test-threads=1`: 53 passed, 0 failed (was 39)
- `MLX_ENABLE_TF32=0 cargo test --release --features cuda --lib loading:: -- --test-threads=1`: 255 passed, 0 failed

Refs #847
@inureyes inureyes added status:done Completed and removed status:review Under review labels Aug 7, 2026
@inureyes
inureyes merged commit 8309a3b into main Aug 7, 2026
7 checks passed
@inureyes
inureyes deleted the feature/issue-847-locateanything-vlm branch August 7, 2026 09:09
inureyes added a commit that referenced this pull request Aug 7, 2026
…chain (#1081)

Bilingual technical reports for the three VLM ports merged on 2026-08-07, following the existing `TECHNICAL_REPORTS/` convention. Each report is dated by its PR's merge date rather than the authoring date, and each Korean file mirrors its English counterpart section for section.

- `1070-locateanything-vlm-20260807.{en,ko}.md` for PR #1070 (issue #847), LocateAnything grounding VLM.
- `1075-falcon-ocr-early-fusion-20260807.{en,ko}.md` for PR #1075 (issue #848), Falcon-OCR early-fusion VLM.
- `1076-jina-vlm-20260807.{en,ko}.md` for PR #1076 (issue #849), Jina VLM.

The reports concentrate on what real-checkpoint validation caught and synthetic parity would have missed. The LocateAnything report records that the released checkpoint is `mixed_4_8` rather than uniform 4-bit, which hard-errors in `FusedQKVLinear::from_weights_separate`, and that this breaks any family loading an `mlx_lm --quant-predicate mixed_4_8` conversion rather than LocateAnything alone. The Falcon-OCR report records the `sequence_state_layout()` trait default that let the scheduler allocate an empty cache vector, so the server ran zero of 22 decoder layers with no panic and no log line while the CLI stayed correct because it builds its own caches. The Jina VLM report records that the checkpoint declares `model_type: jvlm` rather than the `jina_vlm` the issue assumed, and that the chat-template fallback's matching 824 prompt-token count across CLI and server was coincidence rather than evidence that the two front ends rendered the same prompt.

Each report also carries an explicit section for what was not verified, so the gaps are on the record: no numeric oracle parity for Jina VLM, the Apple Silicon bf16 branch that cannot be exercised on the Linux CUDA box, absent layout detection for Falcon-OCR, and the pre-existing failures on `main` that were control-run before being attributed anywhere.

Documentation only. No source, test, or build changes.
@inureyes inureyes self-assigned this Aug 27, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…#1070)

## Summary

Adds native support for LocateAnything (`model_type: locateanything`), NVIDIA's ~3B generative grounding VLM: a MoonViT vision tower and an MLP connector feeding a Qwen2 text decoder whose output interleaves `<ref>`/`<box>` markers and the 1001 coordinate tokens `<0>`..`<1000>` (ids 151677..152677). Plain autoregressive decode already produces those, so no special detokenization is involved. Validated end to end on `mlx-community/LocateAnything-3B-4bit`, where the first emitted box is byte-identical to the output the model card documents for its own example image.

## What changed

**Reuse over duplication.** The tower is the same MoonShot MoonViT-SO-400M that Kimi-VL embeds, so `src/vision/encoders/kimi_vl.rs` is reused rather than copied. Its upstream LocateAnything implementation diverges in exactly two places, both numeric: the LayerNorm epsilon is `1e-5` rather than `1e-6` (already a config field) and the block MLP uses `nn.GELU(approx="precise")`, MLX's tanh approximation, rather than the exact erf form. The activation becomes `MoonViTMlpActivation` on the vision config, defaulting to the erf form, so Kimi-VL and Kimi-VL 2.5 are byte-unchanged. `mlxcel_core` exposes no elementwise tanh GELU (both `gelu` and, despite its name, `gelu_approx` are erf-based), so it is synthesised from primitives the way `models::kokoro::ops::gelu_new` does. The text side is `models::Qwen2Model` verbatim.

**New files.** `src/vision/locateanything.rs` (VLM runtime + `multi_modal_projector` connector), `src/vision/processors/locateanything.rs` (native-resolution processor), `src/multimodal/locateanything_prompt.rs` (image-marker expansion), `src/loading/vlm_locateanything.rs` and `src/loading/vlm_locateanything_quant.rs` (loader), each with a `_tests.rs` beside it.

**Where LocateAnything is genuinely not Kimi-VL.** The connector normalizes over the flattened merged patch (`vision_hidden * merge_h * merge_w`, 4608 in the released checkpoint, which its `layer_norm.weight` shape confirms) rather than over the 1152-wide vision hidden dim. The processor resizes each side UP to the next multiple of `merge * patch` where Kimi-VL centre-crops DOWN, and normalizes with `mean = std = 0.5` rather than the CLIP statistics. Neither is shared.

**Image-token splice.** `<image-N>` is what the chat template renders, and it is plain text rather than a vocabulary token, so the rewrite into `<img> + <IMG_CONTEXT> * (grid_h * grid_w / merge_length) + </img>` happens on the rendered prompt and is re-encoded, matching upstream's `re.sub`. A token-level splice covers `--no-chat-template` runs. The runtime then verifies the encoded stream carries exactly as many `<IMG_CONTEXT>` ids as the tower will emit feature rows, so a drift cannot silently scatter image features into text positions.

**Control-plane wiring.** `ModelType::LocateAnythingVLM` with the `"locateanything"` detection arm (which has to win at the top level, because the text sub-config also says `"qwen2"`), `for_each_model_registration!` entry, `LoadedModel` variant, `VlmRuntimeRef::LocateAnything`, the `try_load_vlm_model_from_dir` route, a `generate_vlm` summary line, and the TP arch-string table (LocateAnything's backbone is `llama`-family; TP is refused for VLM-kind models earlier, this just keeps the dispatch total).

## Two real-checkpoint gaps the Python reference did not show

Both were found by running the actual checkpoint, not by reading `mlx_vlm`.

**The conversion is `mixed_4_8`, not uniform 4-bit.** The model card explains why: pure 4-bit on the tied `embed_tokens` destroys coordinate-token precision. 18 of the 36 layers store `v_proj` at 8 bits while `q_proj` and `k_proj` stay at 4. Every per-tensor loader reconciles its own width from tensor shapes and is fine, but `FusedQKVLinear::from_weights_separate` concatenates the three packed planes along axis 0 and infers one width from `q_proj`, which is a hard shape error inside MLX for a mixed layer (`[2048, 256]` against `[256, 512]`). The loader dequantizes the three planes of an affected layer, which is exact. It deliberately does not requantize the narrow planes up to the wider width: MLX's affine quantizer snaps the group scale onto the larger-magnitude edge rather than using a plain `(max - min) / (2^bits - 1)`, so a 4-bit group does not land on the 8-bit grid and a round trip perturbs the weights by up to half an 8-bit step (measured 3.7e-3 on a synthetic plane before switching approaches). The cost is roughly 190 MB on the released 3B checkpoint. Note this is not LocateAnything-specific: any family on the shared fused-QKV loader would hit the same wall on an `mlx_lm --quant-predicate mixed_4_8` conversion. Fixing it properly needs a `FusedQKVLinear` that can hold per-projection widths, which is a shared-layer change and is left as a follow-up.

**The checkpoint ships no `tokenizer.json`.** Neither `nvidia/LocateAnything-3B` nor its MLX conversions exported a fast tokenizer, only `vocab.json` + `merges.txt` + `added_tokens.json` + `tokenizer_config.json`, so `load_tokenizer` had nothing to read and the model could not load at all. A new last-resort fallback reconstructs the tokenizer the way `transformers`' `Qwen2Converter` does, component for component: byte-level BPE with no unk token and no subword prefix or suffix, NFC normalizer, `Sequence[Split(PRETOKENIZE_REGEX, isolated), ByteLevel(add_prefix_space, use_regex=false)]`, ByteLevel decoder, ByteLevel post-processor with `trim_offsets = false`. It is gated on `tokenizer_class` naming the Qwen2 tokenizer as well as on both files being present, because `vocab.json` + `merges.txt` is the generic GPT-2 slow-tokenizer pair and another family shipping it must not be tokenized with Qwen2's rules. Added tokens are registered in ascending id order and then verified against the ids the checkpoint declares, since `tokenizers` assigns them sequentially from the base vocab size and a gap would shift every later token silently; LocateAnything's 1038 added tokens include the 1001 coordinate tokens that carry its box output, where an off-by-one would corrupt every box rather than fail loudly.

## Real-checkpoint validation

GB10, CUDA (sm_121), release build, `mlx-community/LocateAnything-3B-4bit`, on the COCO image the model card's own usage example uses (`http://images.cocodataset.org/val2017/000000039769.jpg`).

```
$ ./target/release/mlxcel generate -m models/mlx/locateanything-3b-4bit \
    --image 000000039769.jpg -p "Detect all objects in the image." -n 128 --temp 0.0
LocateAnything: inserted 1 image block(s) (414 total image tokens)
<ref>object</ref><box><64><152><273><244></box><box><520><160><580><392></box>
[Generated 15 tokens in 1.68s = 8.91 tok/s]
```

The first box `<64><152><273><244>` is byte-identical to the `<ref>remote</ref><box><64><152><273><244></box>` the model card documents for this image, and the `object` label instead of `remote` is exactly the semantic generalization the card documents for this 4-bit conversion. The second box is 333,77,371,188 in pixels against a COCO ground-truth remote of 333,72,368,187.

Referring and multi-object queries on the same image:

```
-p "...the region this sentence describes: the cat on the right."
-> <ref>the cat on the right</ref><box><541><49><1000><778></box>     (346,24,640,373 px; GT 345,23,640,368)

-p "Detect all the cats in the image."
-> <ref>the cats in the image</ref><box><9><112><494><989></box><box><541><52><1000><775></box>
                                    (6,54,316,475 px; GT 13,52,314,470)  (346,25,640,372 px; GT 345,23,640,368)
```

`./target/release/mlxcel arch` lists `LocateAnything (MoonViT + MLP connector + Qwen2, grounding)`.

The tokenizer was separately validated against a `transformers` `Qwen2Tokenizer` oracle built from the same checkpoint directory: 7 cases covering the rendered ChatML prompt, a `<ref>`/`<box>` grounding string, repeated whitespace and newline runs, tabs, CJK and accented Latin text, and the apostrophe contractions the pre-tokenize regex special-cases. All 7 encode token-exact and decode round-trip exactly. That harness was a throwaway and is not part of the diff.

## Finalization pass

One review-fix seam had no regression test: the bf16-ordering fix (densify the mixed-precision QKV planes before the Apple Silicon bf16 -> f16 pass, not after) was previously validated only by reading the diff, because the host that landed it could not run its own test suite in that session. `load_locateanything_vlm`'s two inline passes are now `reconcile_mixed_precision_weights`, a private function that takes the Apple Silicon gate as a `convert_bf16: bool` parameter instead of reading `hardware::get_hardware()` internally, so a test can force the conversion branch independent of the host it runs on (this GB10 box is CUDA, not Apple Silicon, and would otherwise never execute that branch). Two new tests in `src/loading/vlm_locateanything_tests.rs` quantize a bf16-sourced dense plane the way the released checkpoint's mixed-precision layers do (confirming the scales stay bf16, which is the premise of the whole bug), densify it, and assert the densified planes land on f16 only when the conversion flag is set; the control test proves the f16 dtype comes from the conversion pass and not from densification itself. No behavior changed, only the call composition became a named, independently testable unit.

## Test plan

- [x] `cargo test --release --features cuda --lib locateanything -- --test-threads=1` (53 passed, 0 failed)
- [x] `cargo test --release --features cuda --lib tokenizer -- --test-threads=1` (75 passed, 0 failed, 5 ignored)
- [x] `cargo test --release --features cuda --lib kimi_vl -- --test-threads=1` (25 passed, 0 failed)
- [x] `cargo test --release --features cuda --lib detection -- --test-threads=1` (80 passed, 0 failed)
- [x] `cargo test --release --features cuda --lib model_metadata -- --test-threads=1` (8 passed, 0 failed)
- [x] `cargo test --release --features cuda --lib loading:: -- --test-threads=1` (255 passed, 0 failed)
- [x] `cargo test --release --features cuda --lib vision:: -- --test-threads=1` (314 passed, 0 failed, 17 ignored)
- [x] `cargo test --release --features cuda --lib multimodal:: -- --test-threads=1` (187 passed, 0 failed, 17 ignored)
- [x] `cargo test --release --features cuda --test kimi_vl_parity -- --test-threads=1` (3 passed, 0 failed)
- [x] `cargo clippy --features cuda --lib --tests -- -D warnings` (clean)
- [x] `cargo fmt --all`
- [x] Real-checkpoint generation above

Not run here, left to the broader gate: the full `cargo test --workspace` and any non-CUDA / Apple Silicon path. The Apple Silicon bf16-to-f16 branch in the loader mirrors the InternVL one line for line but was not exercised on this Linux box.

## Follow-up (explicitly out of scope for lablup#847)

- The `pbd` parallel box-decoding path with its multi-token-prediction heads (`n_future_tokens = 6`), and coordinate-token-to-box post-processing. Plain autoregressive decode emitting coordinate tokens as text was the target here.
- A `FusedQKVLinear` that holds per-projection quantization widths, which would remove the dequantize-on-mixed-precision workaround for every family, not just this one.

Closes lablup#847
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…blup#849 VLM port chain (lablup#1081)

Bilingual technical reports for the three VLM ports merged on 2026-08-07, following the existing `TECHNICAL_REPORTS/` convention. Each report is dated by its PR's merge date rather than the authoring date, and each Korean file mirrors its English counterpart section for section.

- `1070-locateanything-vlm-20260807.{en,ko}.md` for PR lablup#1070 (issue lablup#847), LocateAnything grounding VLM.
- `1075-falcon-ocr-early-fusion-20260807.{en,ko}.md` for PR lablup#1075 (issue lablup#848), Falcon-OCR early-fusion VLM.
- `1076-jina-vlm-20260807.{en,ko}.md` for PR lablup#1076 (issue lablup#849), Jina VLM.

The reports concentrate on what real-checkpoint validation caught and synthetic parity would have missed. The LocateAnything report records that the released checkpoint is `mixed_4_8` rather than uniform 4-bit, which hard-errors in `FusedQKVLinear::from_weights_separate`, and that this breaks any family loading an `mlx_lm --quant-predicate mixed_4_8` conversion rather than LocateAnything alone. The Falcon-OCR report records the `sequence_state_layout()` trait default that let the scheduler allocate an empty cache vector, so the server ran zero of 22 decoder layers with no panic and no log line while the CLI stayed correct because it builds its own caches. The Jina VLM report records that the checkpoint declares `model_type: jvlm` rather than the `jina_vlm` the issue assumed, and that the chat-template fallback's matching 824 prompt-token count across CLI and server was coincidence rather than evidence that the two front ends rendered the same prompt.

Each report also carries an explicit section for what was not verified, so the gaps are on the record: no numeric oracle parity for Jina VLM, the Apple Silicon bf16 branch that cannot be exercised on the Linux CUDA box, absent layout detection for Falcon-OCR, and the pre-existing failures on `main` that were control-run before being attributed anywhere.

Documentation only. No source, test, or build changes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata 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(models): add LocateAnything (locateanything) VLM support

1 participant