Skip to content

feat(vision): add the Kimi K3 MoonViT3D tower and navit image path - #1768

Merged
inureyes merged 3 commits into
mainfrom
feature/issue-1342-kimi-k3-moonvit3d
Sep 10, 2026
Merged

inureyes merged 3 commits into
mainfrom
feature/issue-1342-kimi-k3-moonvit3d

Conversation

@inureyes

@inureyes inureyes commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

Adds the Kimi K3 vision path on top of the #1741 text backbone and the #1743 XTML renderer: the MoonViT3D tower, the sd2_tpool merger, the patchmergerv2 projector, the navit image preprocessor, detection of the VLM layout, the loader, and the prompt placement on both fronts.

What changed

  • Tower, merger, projector and preprocessor as specified: encoders/moonvit3d (RMSNorm at 2^-7, fused wqkv over a 1536-wide qkv space, the MoonViT 2D rotary table reused from kimi_vl::rope, bilinear half-pixel position resampling, sincos time table for t > 1, per-image attention through the fast SDPA kernel, tpool_merge), vision/kimi_k3_vl (projector, count-checked merge at id 163605, LanguageModel delegation to the K3 backbone, which gains an embeddings-injection forward with the token-id path's state-reset rule), processors/kimi_k3 (navit rule in f64 like the reference, chessboard alpha fill after the resize, padding to multiples of 28, patchify in either layout, preprocessor_config.json parsing with the geometry bounded the way processors::locateanything bounds its own).
  • Loader loading/vlm_kimi_k3: index-filtered read so a truncated copy never opens the shards it drops, vision keys split off before the unchanged text sanitize, the Axis A surgery hook run as the text and common VLM routes run it, a load-time check that vision_config and preprocessor_config.json agree on the patch size and the merge kernel, and the dtype policy from config_has_quantization_metadata, so the checkpoint counts as quantized and the bf16 tower is not promoted to f16, matching the text-only route.
  • Detection: kimi_k3 with vision_config and vision_tower.* tensors is ModelType::KimiK3VLM, otherwise the text backbone; inkling_has_vision_weights now shares a checkpoint_has_weight_prefix helper.
  • Prompts: the XTML renderer emits <|media_begin|>image {w}x{h}<|media_content|> + <|media_pad|> x gh*gw/4 + <|media_end|> per image_url part (sized from the image header, navit parameters read from the checkpoint on every server construction path including the router front-end); multimodal/kimi_k3_prompt verifies the pre-rendered runs on the worker and splices the same block in front of a raw mlxcel generate --image prompt. A run that disagrees with the processor's grid is refused rather than scattered, and so is an image_url part with no prompt behind it or on a tool message.
  • Resource bounds: one request's images may ask for at most 32,768 merged media tokens (MLXCEL_KIMI_K3_MAX_MEDIA_TOKENS overrides), checked at the render boundary and again on the worker; images are preprocessed, run and projected one at a time rather than as one batch tensor.
  • docs/supported-models.md: Kimi K3 VLM entry; the text-backbone sentence about vision keys now describes the split.

Review findings fixed

Two review passes ran over the branch (implementation, then security and performance). Fixed here, highest severity first:

  • Graph SDPA in the tower. scaled_dot_product_attention materializes the [1, heads, L, L] score matrix, and L is one image's whole patch count; at the navit ceiling of about 67,000 patches that is hundreds of gigabytes. Switched to fast_scaled_dot_product_attention.
  • No per-request media bound. The image count, the pixel dimensions and the decode allocation were each capped and their product was not: sixteen 4000x3000 photos ask for 247,104 media tokens and 988,416 tower tokens from one POST. check_media_token_budget bounds the sum, and geometry is now planned before any pixel work so the budget and the placeholder check both decide before the tower runs.
  • Whole-request batch tensor. The path built one host Vec<f32> of every image, copied it into MLX, cast and transposed it, and the tower sliced it apart per image anyway. project_image_stream streams one image at a time and evaluates each before the next starts.
  • f32 promotion at block 0. The rotary tables are f32 and nothing cast q and k back, so wo and the residual add promoted the stream and all 27 blocks ran bf16 weights against f32 activations. The harness now asserts the tower returns the dtype it was given.
  • Images on reordered tool results. A run of tool messages is sorted into the assistant's tool-call order while images stay in wire order, so two same-grid images on tool results would swap features with every count check passing. Refused.
  • --surgery a silent no-op on this route, which reads the shards directly and never reached the hook load_text_weights and finish_vlm_weights_common run.
  • A degenerate oracle fixture. The real-weights harness ran on a flat single-colour square where all 256 patches are identical, so patch order, intra-patch layout and padding were unobservable. It now runs on navit_probe.png, a 303x181 crop with 230 colours that pads on both axes, and the bf16 arm is compared against the same run's f32 arm as well as the numpy dump.
  • Smaller: an image_url part with no prompt supplied emitted placeholder text and no ids; the router front-end attached the renderer without the model directory; the projector indexed shape[0] before checking the rank; the navit grid arithmetic ran in u32 over checkpoint-supplied values; fixed_output_tokens was silently ignored; merge_llava and temporal_sinusoid gained their Used by: entries; the fixture docs pointed at the wrong test file.

Reported and not fixed:

  • The tower re-runs in full every turn: the Kimi K3 branch discards the active_caches and image_cache_keys other families use for an opportunistic vision cache.
  • Preprocessing is per pixel (get_pixel plus push, and a per-pixel chessboard composite), flatten() and resized_rgb() clone whole images, and the padding path fills a whole new image for a border of at most 27 pixels.
  • memory_estimate.rs has no term for the vision working set. That gap is shared by every VLM family in the tree.
  • decode_request_images_with_limits warns and skips an image it cannot decode, so the K3 path sees fewer images than the prompt was rendered for. The mismatch error now names that as a cause; refusing at the decode boundary is cross-family behavior and belongs in its own change.
  • checkpoint_has_weight_prefix trusts a parsed index and does not fall back to the shard headers when it finds no match, so a truncated index would downgrade a real VLM to text-only. Adding the fallback makes every text checkpoint scan every shard header at detection time, which wants a measurement first.
  • The rope and position tables are rebuilt per image inside one forward, and the patch-embedding conv over [N, 14, 14, 3] with stride 14 is a matmul in disguise. Both want a measurement before a change, per docs/benchmarks.md.
  • The published layout has no flag to force the text-only route, and the VLM route skips LoRA and sanitize_tied_embeddings.
  • init_pos_emb_time is unused, so t > 4 extrapolates the time table rather than being refused; video is out of scope for this issue.

Validation

Unit tests (cargo test --profile test-fast --features metal,accelerate --lib <module>) over vision::encoders::moonvit3d, vision::processors::kimi_k3, vision::kimi_k3_vl, models::detection, server::kimi_k3_chat, server::chat_request, multimodal::kimi_k3_prompt and loading::vlm: all pass, including the seven tests the issue names (navit_resize_rule, chessboard_fill, pos_emb_bilinear_matches_half_pixel_formula, time_embedding_sincos, rope2d_angle_layout, tpool_merge_averages_over_time_and_groups_2x2, projector_shapes_and_merge_count_mismatch_errors), the three detection-table tests, the prompt splice and verify tests, the renderer image-prompt and refusal tests, the media-budget and patch-layout tests, and a synthetic two-image tower test.

Real weights (cargo test --profile test-fast --features metal,accelerate --lib vision::encoders::moonvit3d -- --ignored kimi_k3_tower_real_weights --nocapture): the tower and projector on shards 00095 and 00096 of models/kimi-k3-8l-mxfp4 over tests/fixtures/kimi_k3_vision/navit_probe.png (303x181, padded to 308x196, grid (1, 14, 22), 77 tokens, 230 distinct colours so no two patches are alike), compared with tests/fixtures/kimi_k3_vision/reference.json, which generate_reference.py computes in numpy float32 from the same shards, parsing the safetensors headers itself with no torch, transformers or mlx. With the weights cast to f32 the relative mean-abs error over 8,624 sampled projected values is 7.3e-6 (per-token statistic 9.3e-7, final-norm 2.0e-7), so the port and the independent transcription agree to float32 rounding. In the checkpoint's own bf16, which is what the loader runs, the sampled values sit at 3.0e-2 relative and 3.0e-2 against the f32 arm of the same run, while the per-token statistic is within 2.9e-4 and the final norm within 2.0e-3. The harness gates the f32 arm at 1e-2, the bf16 arm at 5e-2 against the dump and at 5e-2 against the f32 arm, and asserts the tower does not change the activation dtype. The preprocessed pixels match the dump over all 181,104 values.

The checkpoint's own Python (media_utils.py from models/kimi-k3-tokenizer, which needs only numpy and pillow) was run directly out of band: navit_resize_image reproduces the Rust plan on 4000x3000 (15,444 tokens), 10000x100 (side-capped, 6x512 grid), 100x100 (16), 8000x8000 (129x129) and 303x181 (77), and its image_to_np / navit_patchify / normalize pixel tensor matches reference.json in shape, grid, mean absolute value and its first sixteen values. The tower half has no vendor equivalent to run: the checkpoint ships no modeling file and torch is not installed, which is why the numpy transcription exists.

End to end (./target/release/mlxcel generate -m models/kimi-k3-8l-mxfp4 --image tests/fixtures/kimi_k3_vision/navit_probe.png -p "What is in this picture?" -n 64; the issue names tests/fixtures/cat.jpg, which is not in the repository): detected as KimiK3VLM, loaded in 5.1 s (45.4 GB resident), Kimi K3: spliced 1 image block(s) (77 <|media_pad|> tokens) for the (1, 14, 22) grid, 64 tokens at 34.4 tok/s, exit 0. On mlxcel-server at port 20342 a /v1/chat/completions request with a base64 image_url part is 179 prompt tokens against 94 for the same text alone (the 77 pads plus the block framing and the image 303x181 label), 8 completion tokens, no error; the same image attached to a tool message is refused at the HTTP boundary with a named error. This is a load, placeholder-count and finite-logits gate only. The copy runs 4 of the published 93 layers, so the generated text is meaningless and is not a correctness result. The full model (about 1.4 TB at 4 bits, a pipeline over at least three 512 GB hosts with no stage executor yet) is not reachable on one machine; #1734 tracks it.

cargo fmt --all -- --check and cargo clippy --lib --tests --features metal,accelerate -- -D warnings pass. The workspace gate was not run as one command on this shared machine; the affected suites were run per module as listed above.

Deviations from the issue text: attention runs per image rather than through a block-diagonal mask (the issue allows either); the loader reads the four media control ids from tokenizer_config.json so the CLI can splice a block without a tokenizer; Pillow resizes palette images with nearest-neighbour sampling before the alpha fill while the image crate decodes palettes to RGB(A) first, noted in the processor docs.

Closes #1342

Refs #1331

@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:low Low priority area:models Model architectures, weights, loading, metadata area:inference Generation, sampling, decoding (incl. speculative, DRY) area:cli Command-line interface / CLI flags modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware modeltype:vlm Vision-language model arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) status:review Under review labels Sep 10, 2026
Kimi K3 loaded as its text backbone only; the checkpoint's `vision_tower.*` and `mm_projector.*` tensors were dropped at sanitize and an image request had nowhere to go. This adds the MoonViT3D tower, the sd2_tpool merger, the patchmergerv2 projector, the navit preprocessor and a loader that splits the vision keys off before the unchanged text sanitize and keeps the bf16 tower unpromoted, since the checkpoint counts as quantized for the dtype policy.

A kimi_k3 config with vision_config and vision_tower.* tensors now detects as ModelType::KimiK3VLM. Each image renders as <|media_begin|>image {w}x{h}<|media_content|> followed by gh*gw/4 <|media_pad|> control ids and <|media_end|>: the XTML renderer emits the block per image_url part on the server (sized from the image header, navit parameters read from preprocessor_config.json) and the runtime verifies the pre-rendered runs on the worker or splices the block in front of a raw `mlxcel generate --image` prompt; a run that disagrees with the processor's grid is refused rather than scattered. The K3 backbone gains an embeddings-injection forward with the same state-reset rule as the token-id path.

Validated with the seven unit tests named in the issue plus detection, prompt and renderer tests; an ignored kimi_k3_tower_real_weights harness compares the real bf16 tower and projector shards against tests/fixtures/kimi_k3_vision/reference.json, a numpy dump generate_reference.py computes independently from the same shards (6.9e-6 relative mean-abs on the sampled projected values with the weights in f32, 1.6e-2 in the checkpoint's bf16); and mlxcel generate --image on the 4-layer local copy as a load, placeholder-count and finite-logits gate only (64 <|media_pad|> ids for the 16x16 grid of tests/fixtures/test_image.png, 64 finite tokens). The full 93-layer model needs a multi-host pipeline that #1734 tracks.

Closes #1342
Review follow-up on the MoonViT3D vision path. The correctness and resource findings, in the order they bite:

The tower attended through the graph SDPA, which materializes the `[1, heads, L, L]` score matrix over one image's whole patch grid. At the navit ceiling of about 67,000 patches that is hundreds of gigabytes for a single image, so the fast kernel is used instead. The rotary tables are f32, and nothing cast q and k back afterwards, so the attention output, `wo` and the residual add all promoted: every one of the 27 blocks ran its bf16 weights against f32 activations. The harness now asserts the tower returns the dtype it was given.

Nothing bounded what one request's images add up to. The image count, the pixel dimensions and the decode allocation are each capped, and sixteen 4000x3000 photos still ask for 247,104 media tokens and 988,416 tower tokens. `check_media_token_budget` bounds the sum at 32,768 merged tokens by default, `MLXCEL_KIMI_K3_MAX_MEDIA_TOKENS` overrides it, and it is checked at the render boundary where the header dimensions are first known and again on the worker before any pixel is normalized. Geometry is planned before pixel work now, so the placeholder placement and the budget both decide before the tower runs.

The request path built one host `Vec<f32>` of every image's pixels, copied it into one MLX array, cast and transposed the whole batch, and then let the tower slice it back apart per image, because attention is per image regardless. `project_image_stream` preprocesses, runs and projects one image at a time, writes the channels-last layout the conv wants directly, and evaluates each image before the next starts.

A run of tool results is reordered to the assistant's tool-call order while images stay in wire order, so an image on a tool message would be described by another tool result's prompt, and two same-grid images would swap features with every count check passing. Tool-message images are refused. An `image_url` part rendered with no image prompt supplied used to put the placeholder in the text and nothing in the ids, dropping the image silently; also refused.

`--surgery` was a silent no-op on this route, which reads the shards directly and never reached the hook that `load_text_weights` and `finish_vlm_weights_common` run. The router front-end attached the chat renderer without the model directory, so it sized pad runs with the published navit defaults instead of the checkpoint's own. `vision_config` and `preprocessor_config.json` must now agree on the patch size and the merge kernel at load, rather than disagreeing later as a count mismatch. `media_proc_cfg` geometry is bounded the way `processors::locateanything` bounds its own, `fixed_output_tokens` is refused rather than ignored, the grid arithmetic runs in u64 with a named error when the patch tensor would not fit an i32 shape, and the projector checks the rank before indexing it.

The real-weights oracle ran on a flat single-colour square, where every patch is identical and the patch order, the intra-patch layout and the padding are all unobservable. It now runs on `navit_probe.png`, a 303x181 crop with 230 colours that pads on both axes, and the bf16 arm is compared against the same run's f32 arm as well as against the numpy dump, because that comparison does not drift when MLX changes a kernel.

Validation:
- `cargo test --profile test-fast --features metal,accelerate --lib` over `vision::encoders::moonvit3d`, `vision::processors::kimi_k3`, `vision::kimi_k3_vl`, `models::detection`, `server::kimi_k3_chat`, `server::chat_request`, `multimodal::kimi_k3_prompt`, `loading::vlm`: all pass.
- `cargo clippy --lib --tests --features metal,accelerate -- -D warnings` and `cargo fmt --all -- --check`: clean.
- `kimi_k3_tower_real_weights` on shards 00095 / 00096 of `models/kimi-k3-8l-mxfp4`: f32 arm 7.3e-6 relative mean-abs against the numpy oracle over 8,624 sampled values, per-token 9.3e-7; bf16 arm 3.0e-2 against the oracle and 3.0e-2 against the f32 arm of the same run, per-token 2.9e-4; preprocessed pixels identical to the oracle over 181,104 values.
- The checkpoint's own `media_utils.py` reproduces the plan on 4000x3000, 10000x100, 100x100, 8000x8000 and 303x181, and its pixel tensor matches the oracle value for value.
- `mlxcel generate -m models/kimi-k3-8l-mxfp4 --image tests/fixtures/kimi_k3_vision/navit_probe.png -n 64`: detected as `KimiK3VLM`, 77 `<|media_pad|>` tokens for the (1, 14, 22) grid, 64 finite tokens at 34.4 tok/s, exit 0.
- `mlxcel-server` on port 20342: an `image_url` request is 179 prompt tokens against 94 for the same text alone, and an image on a tool message is refused at the HTTP boundary.

Refs #1342
@inureyes
inureyes force-pushed the feature/issue-1342-kimi-k3-moonvit3d branch from 7183acb to 6dd3585 Compare September 10, 2026 15:03
Bilingual pre-merge report for the Kimi K3 MoonViT3D vision path: where MoonViT3D departs from the MoonViT already in the tree and why each difference is a silent-wrong-answer risk, the navit rule with the per-image ceiling that was written down nowhere, the two prompt fronts and the count-checked merge at id 163605, the detection and loader decisions including the dtype policy, what the implementation and security reviews changed, and the validation chain from the numpy oracle through the checkpoint's own preprocessing Python to the truncated-copy end-to-end gate.

Refs #1768, #1342
@inureyes inureyes added status:done Completed and removed status:review Under review labels Sep 10, 2026
@inureyes
inureyes merged commit 58dc969 into main Sep 10, 2026
13 checks passed
@inureyes
inureyes deleted the feature/issue-1342-kimi-k3-moonvit3d branch September 10, 2026 15:13
@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:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) area:cli Command-line interface / CLI flags area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware modeltype:vlm Vision-language model priority:low Low 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(vision): Kimi K3 MoonViT3D tower, temporal-pool patch merger and navit image preprocessing

1 participant