Repository navigation
feat(vision): add the Kimi K3 MoonViT3D tower and navit image path - #1768
Merged
Merged
Conversation
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
force-pushed
the
feature/issue-1342-kimi-k3-moonvit3d
branch
from
September 10, 2026 15:03
7183acb to
6dd3585
Compare
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
5 tasks
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.
Adds the Kimi K3 vision path on top of the #1741 text backbone and the #1743 XTML renderer: the MoonViT3D tower, the
sd2_tpoolmerger, thepatchmergerv2projector, the navit image preprocessor, detection of the VLM layout, the loader, and the prompt placement on both fronts.What changed
encoders/moonvit3d(RMSNorm at2^-7, fusedwqkvover a 1536-wide qkv space, the MoonViT 2D rotary table reused fromkimi_vl::rope, bilinear half-pixel position resampling, sincos time table fort > 1, per-image attention through the fast SDPA kernel,tpool_merge),vision/kimi_k3_vl(projector, count-checked merge at id 163605,LanguageModeldelegation 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.jsonparsing with the geometry bounded the wayprocessors::locateanythingbounds its own).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 thatvision_configandpreprocessor_config.jsonagree on the patch size and the merge kernel, and the dtype policy fromconfig_has_quantization_metadata, so the checkpoint counts as quantized and the bf16 tower is not promoted to f16, matching the text-only route.kimi_k3withvision_configandvision_tower.*tensors isModelType::KimiK3VLM, otherwise the text backbone;inkling_has_vision_weightsnow shares acheckpoint_has_weight_prefixhelper.<|media_begin|>image {w}x{h}<|media_content|>+<|media_pad|>xgh*gw/4+<|media_end|>perimage_urlpart (sized from the image header, navit parameters read from the checkpoint on every server construction path including the router front-end);multimodal/kimi_k3_promptverifies the pre-rendered runs on the worker and splices the same block in front of a rawmlxcel generate --imageprompt. A run that disagrees with the processor's grid is refused rather than scattered, and so is animage_urlpart with no prompt behind it or on atoolmessage.MLXCEL_KIMI_K3_MAX_MEDIA_TOKENSoverrides), 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:
scaled_dot_product_attentionmaterializes the[1, heads, L, L]score matrix, andLis one image's whole patch count; at the navit ceiling of about 67,000 patches that is hundreds of gigabytes. Switched tofast_scaled_dot_product_attention.check_media_token_budgetbounds the sum, and geometry is now planned before any pixel work so the budget and the placeholder check both decide before the tower runs.Vec<f32>of every image, copied it into MLX, cast and transposed it, and the tower sliced it apart per image anyway.project_image_streamstreams one image at a time and evaluates each before the next starts.woand 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.--surgerya silent no-op on this route, which reads the shards directly and never reached the hookload_text_weightsandfinish_vlm_weights_commonrun.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.image_urlpart with no prompt supplied emitted placeholder text and no ids; the router front-end attached the renderer without the model directory; the projector indexedshape[0]before checking the rank; the navit grid arithmetic ran in u32 over checkpoint-supplied values;fixed_output_tokenswas silently ignored;merge_llavaandtemporal_sinusoidgained theirUsed by:entries; the fixture docs pointed at the wrong test file.Reported and not fixed:
active_cachesandimage_cache_keysother families use for an opportunistic vision cache.get_pixelpluspush, and a per-pixel chessboard composite),flatten()andresized_rgb()clone whole images, and the padding path fills a whole new image for a border of at most 27 pixels.memory_estimate.rshas no term for the vision working set. That gap is shared by every VLM family in the tree.decode_request_images_with_limitswarns 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_prefixtrusts 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.[N, 14, 14, 3]with stride 14 is a matmul in disguise. Both want a measurement before a change, perdocs/benchmarks.md.sanitize_tied_embeddings.init_pos_emb_timeis unused, sot > 4extrapolates 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>) overvision::encoders::moonvit3d,vision::processors::kimi_k3,vision::kimi_k3_vl,models::detection,server::kimi_k3_chat,server::chat_request,multimodal::kimi_k3_promptandloading::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 ofmodels/kimi-k3-8l-mxfp4overtests/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 withtests/fixtures/kimi_k3_vision/reference.json, whichgenerate_reference.pycomputes 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.pyfrommodels/kimi-k3-tokenizer, which needs only numpy and pillow) was run directly out of band:navit_resize_imagereproduces the Rust plan on 4000x3000 (15,444 tokens), 10000x100 (side-capped, 6x512 grid), 100x100 (16), 8000x8000 (129x129) and 303x181 (77), and itsimage_to_np/navit_patchify/normalizepixel tensor matchesreference.jsonin 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 namestests/fixtures/cat.jpg, which is not in the repository): detected asKimiK3VLM, 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. Onmlxcel-serverat port 20342 a/v1/chat/completionsrequest with a base64image_urlpart is 179 prompt tokens against 94 for the same text alone (the 77 pads plus the block framing and theimage 303x181label), 8 completion tokens, no error; the same image attached to atoolmessage 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 -- --checkandcargo clippy --lib --tests --features metal,accelerate -- -D warningspass. 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.jsonso the CLI can splice a block without a tokenizer; Pillow resizes palette images with nearest-neighbour sampling before the alpha fill while theimagecrate decodes palettes to RGB(A) first, noted in the processor docs.Closes #1342
Refs #1331