Skip to content

fix: guard conv-weight PyTorch→MLX transpose with layout detection (Gemma4 audio crash + same-pattern loaders) #428

Closed

Description

@inureyes

Summary

Loading mlx-community/gemma-4-e4b-it-qat-4bit and sending audio crashes the server with an uncaught MLX conv exception. Root cause: the Gemma 4 audio weight sanitizer transposes the subsampling conv weights from PyTorch to MLX layout unconditionally, but the mlx-community checkpoint already stores them channel-last, so the transpose double-converts and corrupts the shape. The same unconditional anti-pattern exists in three other loaders. The codebase already has the correct guarded pattern (layout detection) in six other places; this issue makes the unguarded sites use it too.

Reproduction and crash

Calling mlxcel-server (via backend.ai-go) with this model and an audio input:

mlxcel::server::model_provider::model_worker: Audio input: 1600 samples at 16000 Hz (0.1s)
libc++abi: terminating due to uncaught exception of type std::invalid_argument: [conv] Expect the input channels in the input and weight array to match but got shapes - input: (1,12,130,1) and weight: (128,3,1,3)

Root cause (confirmed via checkpoint inspection, no build needed)

  1. The checkpoint stores the audio subsample conv weights already in MLX channel-last [C_out, kH, kW, C_in] layout (read from the safetensors header):
    • audio_tower.subsample_conv_projection.layer0.conv.weight = [128, 3, 3, 1] (C_in=1)
    • audio_tower.subsample_conv_projection.layer1.conv.weight = [32, 3, 3, 128]
    • audio_tower.layers.*.lconv1d.depthwise_conv1d.weight = [1024, 5, 1] (MLX [C_out, kW, C_in])
  2. config.json has model_type: gemma4 and a vision_config, so the model loads via load_gemma4_vlm (src/loading/mod.rs:127), the encoder-based VLM path (not Gemma4Unified).
  3. load_gemma4_vlm calls sanitize_gemma4_audio_weights (src/loading/vlm_gemma.rs:316), which unconditionally transposes:
    • src/loading/vlm_gemma.rs:289: transpose_axes(w, &[0, 2, 3, 1]) on subsample_conv_projection.*.conv.weight (gated only by key.contains("conv.weight") && shape.len() == 4, no layout check).
    • src/loading/vlm_gemma.rs:295: transpose_axes(w, &[0, 2, 1]) on depthwise_conv1d.weight (gated only by shape.len() == 3).
  4. Applying [0,2,3,1] to the already-channel-last [128, 3, 3, 1] yields [128, 3, 1, 3], exactly the crash weight. conv2d (src/audio/encoder.rs:125) then sees weight C_in=3 vs input C_in=1 and MLX throws std::invalid_argument.
  5. conv2d is declared in the cxx bridge as -> UniquePtr<MlxArray> (src/lib/mlxcel-core/src/lib.rs:953), not Result, so cxx turns the throw into std::terminate (the libc++abi: terminating abort). The process-abort half is tracked separately as the conv2d-fallibility follow-up (companion issue).

The function's only commit is its original implementation (86ce520); recent commits did not change it. This reproduces on current main (v0.3.3).

The correct pattern already exists in the codebase

Guarded sites detect PyTorch-vs-MLX layout before transposing and only transpose PyTorch-layout weights. The reusable heuristic (true = already MLX layout, skip transpose) is:

// already channel-last [C_out, kH, kW, C_in] when out >= kH, out >= kW, kH == kW
out_ch >= dim1 && out_ch >= dim2 && dim1 == dim2

Used by should_transpose_phi3_patch_embedding (src/loading/vlm_special.rs:1179), and inline in siglip.rs:295, pixtral.rs:476, internvl.rs:298, minicpmo.rs:317. Gemma 3n uses an equivalent shape[1] > shape[2] check via gemma3n_needs_conv_transpose (src/loading/vlm_gemma.rs:80).

Audit: all unconditional (unguarded) conv-transpose sites

Site Code Op Status
src/loading/vlm_gemma.rs:289 sanitize_gemma4_audio_weights conv2d [0,2,3,1] CONFIRMED crash (gemma4 audio)
src/loading/vlm_gemma.rs:295 sanitize_gemma4_audio_weights depthwise conv1d [0,2,1] same fn, unguarded (would corrupt next)
src/loading/vlm_nemotron_h_nano_omni.rs:112 sanitize_audio_weights conv1d [0,2,1] unguarded: transposes any 3D sound_encoder.encoder.*.weight by shape.len() only
src/loading/vlm_nemotron_h_nano_omni.rs:117 sanitize_audio_weights conv2d [0,2,3,1] unguarded: any 4D under that prefix
src/loading/vlm_special.rs:736 flatten_phi4mm_patch_embedding conv2d [0,2,3,1] then flatten unguarded: only shape.len() == 4 check
src/vision/detection/rt_detr_v2/sanitize.rs:186 maybe_transpose_conv conv2d [0,2,3,1] unguarded: any 4D *.conv.weight

Only the Gemma 4 audio site is reproduced with a local checkpoint. The other three are the same anti-pattern and would corrupt any channel-last checkpoint for those models; they should be fixed defensively. Adding the layout guard is safe in both directions: it still transposes genuine PyTorch-layout weights and only skips already-MLX ones.

Fix plan

  • Extract a shared helper, for example conv2d_weight_is_channel_last(shape) -> bool (the out_ch >= dim1 && out_ch >= dim2 && dim1 == dim2 heuristic) plus a conv1d variant, in a common loader module, and replace the duplicated inline heuristics with it.
  • Gate every unconditional site above on the helper (transpose only when PyTorch layout is detected).
  • Handle conv1d detection separately from conv2d. Note the predicate differs: for depthwise conv1d, PyTorch [C_out, C_in=1, kW] has shape[1] < shape[2] while MLX [C_out, kW, C_in=1] has shape[1] > shape[2], so the conv2d heuristic does not transfer directly. The checkpoint here ([1024, 5, 1]) is MLX layout and must be left as-is.

Tests

  • Idempotency: running each sanitizer twice equals running it once (a channel-last input is unchanged).
  • A synthetic PyTorch-layout conv weight is transposed; a synthetic MLX-layout one is left unchanged, for conv2d (4D) and depthwise conv1d (3D).
  • Regression for the Gemma 4 audio shapes: [128,3,3,1], [32,3,3,128], and [1024,5,1] are preserved (not transposed).

Acceptance criteria

  • Loading mlx-community/gemma-4-e4b-it-qat-4bit and running an audio request no longer crashes (the audio subsample conv receives a [128,3,3,1] weight matching the C_in=1 input).
  • All six unguarded sites in the table are gated by the shared layout-detection helper; the duplicated inline heuristics are consolidated where reasonable.
  • Existing sanitize tests still pass; new idempotency/layout tests added.
  • No change to the Rust inference core ops beyond the loaders/sanitizers.

Validation note

The fix is device-independent weight-sanitize shape logic. Full runtime validation of the audio generation path needs a working MLX runtime (Apple Silicon / Metal); the current dev host is Linux + CUDA (GB10), where the cold MLX build and quantized audio path may not be runnable, so runtime confirmation may be deferred to an Apple Silicon machine.

Related

Companion follow-up: make conv2d fallible at the FFI boundary so a conv shape fault degrades to a per-request error instead of aborting the whole server (separate issue).

Activity

  1. added
    type:bug
    status:ready
    priority:high
    area:models
    on Jun 24, 2026
  2. inureyes commented on Jun 24, 2026

    @inureyes
    MemberAuthor

    Companion follow-up for crash isolation: #427 (make conv2d/conv1d fallible at the FFI boundary, so a conv shape fault degrades to a per-request error instead of a process abort).

  3. added
    status:in-progress
    status:review
    and removed
    status:ready
    status:in-progress
    on Jun 24, 2026
  4. added
    status:done
    and removed
    status:review
    on Jun 24, 2026
  5. self-assigned this
    on Jun 25, 2026
  6. added a commit that references this issue on Jul 30, 2026
    22002d1
  7. added a commit that references this issue on Oct 27, 2026
    a19005d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:modelspriority:highstatus:donetype:bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions