Skip to content

fix(models): mistral4-VLM image+text path aborts in multimodal prefill (reshape size 12480512 into (1,1,1)) #425

Closed

Description

@inureyes

Problem

After #423 / PR #424 wired the Mistral3-VLM mistral4 (MLA + MoE) text backbone into the loader and exposed embed_tokens, text-only generation on mlx-community/Mistral-Small-4-119B-2603-4bit works (loads ~22s, coherent). But an image+text request (/v1/chat/completions with an image_url) aborts during multimodal prefill:

libc++abi: terminating due to uncaught exception of type std::invalid_argument: [reshape] Cannot reshape array of size 12480512 into shape (1,1,1).

12480512 = 3047 x 4096 is the merged text+image embedding sequence at hidden_size 4096 (3047 * 4096 = 12480512). The plain text path (forward(input_ids)) does not hit this; only the image-bearing path (forward_with_embeddings) does.

What the code shows (verified)

  • Mistral3-VLM routes its text tower through mistral4 and merges images with MergeStrategy::LLaVA (src/loading/vlm_pixtral.rs:245,320), i.e. merge_llava -> masked_scatter (src/vision/merge.rs:175,224).

  • get_input_embeddings (src/vision/mod.rs:167) calls text_model.embed_tokens(input_ids) (now provided by mistral4 after fix(loading): Mistral3-VLM with mistral4 (MLA) text backbone fails to load (routes to Llama q_proj loader) #423/fix(loading): route Mistral3-VLM mistral4 (MLA) text backbone to the Mistral4 loader (#423) #424), encodes pixels, projects through the connector, and scatters image features into the text embedding via merge_llava.

  • The merged embeddings reach Mistral4::forward_with_embeddings (src/models/mistral4.rs:923-937), which copies them and runs the same transformer_body (:629-678) as the text path. transformer_body derives l = array_shape(&h)[1] and builds the Llama-4-style position scale from l.

  • Mistral4Attention is MLA with a Llama-4-style position-dependent scale (get_llama4_attn_scale, :173-186), applied at :303-307:

    let scale_shape = vec![1, 1, l, 1];
    let scale_arr = mlxcel_core::from_slice_f32(attn_scale, &[l]);
    let scale_arr = mlxcel_core::reshape(&scale_arr, &scale_shape);
    let queries = mlxcel_core::multiply(&queries, &scale_arr);

Correction to the original hypothesis

The first guess was that a per-position scale tensor is reshaped to a scalar-ish (1,1,1). That does not match the literal code: the scale reshape target at mistral4.rs:304 is [1, 1, l, 1] (4-dim, sized to the sequence), and masked_scatter reshapes back to the embedding's own final_shape (merge.rs:267). Neither is (1,1,1). So static reading does not pin a literal (1,1,1) reshape on the verified mistral4 / merge path. The (1,1,1) target with the full-embedding source size (12480512) points at a rank/shape mismatch that only surfaces when input_embeddings is supplied, but the exact origin still needs runtime tracing.

Proposed direction

  • Reproduce on the 119B checkpoint with a real image and capture which op aborts (eager eval, or eval()/shape prints around the merge output, transformer_body entry, and the attention scale build).
  • Confirm the rank/shape of the merged embeddings returned by get_input_embeddings for mistral4 (expected [batch, seq, hidden] = [1, 3047, 4096]); an unexpected rank would propagate a bad l and a degenerate scale tensor.
  • Compare against the Llama text backbone that already works as a Mistral3 VLM text tower, and against mistral4's text-only forward.
  • Fix so an image-bearing merged [batch, seq, hidden] sequence flows through prefill without the degenerate reshape (scale/position tensors must be sized to the actual sequence, not collapsed).

Acceptance criteria

  • An image+text request on Mistral-Small-4-119B-2603-4bit returns a coherent description without aborting.
  • Text-only generation and non-mistral4 Mistral3 VLMs (Llama / ministral3 text towers) remain unaffected.
  • Validated on the real 119B checkpoint with an actual image.

References

Activity

  1. added
    type:bug
    area:models
    area:inference
    priority:medium
    status:backlog
    on Jun 24, 2026
  2. inureyes commented on Jun 24, 2026

    @inureyes
    MemberAuthor

    Broader than the image path: also reachable text-only under chunked prefill (--max-kv-size)

    Validating the #421 mistral4 mask fix surfaced the SAME reshape ... into (1,1,1) abort on a TEXT-ONLY request (no image) under --max-kv-size 1024 --prefill-chunk-size 512 on the real Mistral-Small-4-119B-2603-4bit: [reshape] Cannot reshape array of size 2097152 into shape (1,1,1) (2097152 = 512 x 4096, chunk_len x hidden). It aborts identically with and without the #421 mask fix, so it is independent of #421 and fires before the prefill mask is even applied.

    So the root cause is mistral4's offset>0 / continuation forward in general (any prefill where cache.offset > 0), not the multimodal merge specifically. Both triggers (image tokens, and chunked-prefill continuation) share it: a [seq, hidden] tensor is being reshaped to a scalar-ish (1,1,1) somewhere in the mistral4 forward when offset > 0. mistral4 text-only WITHOUT chunked prefill / --max-kv-size (single-pass, offset == 0) works fine (validated: coherent generation), which is why this was not seen until an offset>0 path was exercised.

    Consequence for #421: mistral4's dense-prefill mask fix (offset→live_len) is byte-identical when untrimmed and correct, but its crash→fix cannot be demonstrated on mistral4 because this reshape bug aborts every offset>0 mistral4 forward first. The other four #421 models are unaffected by this. Suggest broadening this issue's title/scope from "image+text" to "mistral4 offset>0 forward reshape-to-(1,1,1) (image tokens AND chunked prefill)".

  3. inureyes commented on Jun 24, 2026

    @inureyes
    MemberAuthor

    Trace progress (root cause not yet pinned; ruled out the obvious spots)

    Static trace through the mistral4 forward did NOT find a literal reshape(..., [1,1,1]), so the (1,1,1) target is a runtime-computed shape that collapses under the offset>0 path. Ruled out:

    • Mistral4Attention::forward (mistral4.rs:220-327): all reshapes are 4D [b,l,heads,dim]; the Llama-4 scale is from_slice_f32(attn_scale, [l]) reshaped to [1,1,l,1] (mistral4.rs:304-306), correct for any l.
    • Mistral4MoE::forward (mistral4.rs:449-494) and transformer_body (mistral4.rs:629-686): no (1,1,1) reshape; SwitchGLU::forward (switch_layers.rs:324) handles multi-token via expand_dims/squeeze.
    • Repo-wide grep for literal reshape(.., [1,1,1]) in the model/MoE/server prefill paths: none on this path.

    Key discriminator: mistral4 text-only SINGLE-PASS prefill (offset==0, even a long 2632-token prompt in one forward) generates coherently; the abort only appears once a forward runs with offset>0 (a chunked-prefill continuation chunk, or an image-bearing prefill). So the failing reshape is reachable only when cache.offset > 0 at forward entry. The crashing tensor is [seq, hidden] (seq x 4096): 512x4096 for a 512-token continuation chunk, 3047x4096 for the image+text prefill.

    Next step (needs runtime instrumentation on the 119B, orchestrator-driven since a rebuild+reload exceeds a subagent watchdog): add shape logging through the mistral4 offset>0 forward (entry h, per-op shapes in attention/MoE, and the server chunked-prefill continuation call) to catch which op receives [seq,4096] and targets (1,1,1). Candidate areas to instrument first: the server's chunked-prefill continuation hidden-state handling for mistral4, and forward_with_embeddings/transformer_body entry shapes on a continuation chunk.

  4. added
    status:in-progress
    status:review
    and removed
    status:backlog
    status:in-progress
    on Jun 24, 2026
  5. added
    status:done
    and removed
    status:review
    on Jun 24, 2026
  6. self-assigned this
    on Jun 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:inferencearea:modelspriority:mediumstatus:donetype:bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions