Repository navigation
fix(vision): turn pictures upright by their EXIF orientation - #2993
Conversation
A camera stores the sensor's rows and records how the device was held in the EXIF `Orientation` tag. mlx-vlm's and transformers' `load_image` turn the picture by it (`PIL.ImageOps.exif_transpose`); mlxcel decoded the stored pixels and stopped, so a portrait photo from a phone reached the model lying on its side. On a tagged picture Qwen3-VL-4B and Gemma 3 4B answered exactly as for the same pixels without the tag. `multimodal::image_orientation` reads the tag (JPEG, PNG `eXIf`, WebP) and applies it after the decode. It is used by - `decode_request_image_with_limits`, the one decode every server family, the diffusion, Florence-2 and Nemotron-parse workers, the OpenXLA preprocessors and `mlxcel generate` share; - the Kimi K3 image prompts, which are sized from the header before the pixels are decoded and have to agree with the upright grid; - the commands that open a picture themselves: `embed`, `rerank`, `generate-image`, the diffusion path of `generate`, and the YOLO11 and RT-DETRv2 predictors. A picture without the tag, or with one that cannot be read, is used as stored. The decode limits still apply to the stored pixels.
The orientation tests built PNG eXIf and JPEG APP1 pictures but no WebP, which the change and the issue both list. A lossless WebP written with the encoder's EXIF chunk now goes through every tag from 1 to 8, checking that the decode alone returns the stored pixels and the upright load returns the upright picture pixel for pixel. Refs lablup#2992
|
Thank you for the thorough fix and the evidence tables. Maintainer review and hardening summary: Coverage. Every entry point the issue lists goes through the fix. Chat Dependencies. No manifest or lockfile change; Security and performance. The decode limits path is unchanged and the tag is read only after a successful decode. Known costs, acceptable: a second header parse per picture (for JPEG, image 0.25.10 copies the input once more), and a transient second buffer on quarter turns that Pushed.
Validated on macOS M3 Ultra (Metal). Targeted lib tests (120 passed, including all orientation, model_worker, chat_request and kimi_k3 tests), |
Summary
mlxcel handed a model the pixels a picture stores and ignored its EXIF
Orientationtag, so a portrait photo from a phone reached the model on its side. mlx-vlm's and transformers'load_imageturn the picture by that tag (PIL.ImageOps.exif_transpose). This applies the tag where pictures are decoded: the one decode every server family andmlxcel generateshare, the Kimi K3 prompt sizing that reads the header ahead of it, and the commands that open a picture themselves.Related issues
Closes #2992.
#2717 lists this under "Deferred" for its edit source.
Type of change
fix— bug fixCause
decode_request_image_with_limitsinsrc/server/model_worker.rswasImageReader::new(..).with_guessed_format()?.decode(). Theimagecrate decodes the stored pixels and leaves the tag to the caller (ImageDecoder::orientation,DynamicImage::apply_orientation). Every server family, the diffusion, Florence-2 and Nemotron-parse workers and the OpenXLA preprocessors decode through that function, andmlxcel generatereaches it throughserver::local_media.embed,rerank,generate-imageand the detection predictors calledimage::open/image::load_from_memorydirectly.Change
src/multimodal/image_orientation.rs(new).exif_orientation(bytes)reads the tag from the header and metadata (JPEGAPP1, PNGeXIf, WebP).turn_upright,load_upright_from_memoryandopen_uprightapply it after the decode;upright_dimensionsanswers for a header-only caller. No tag, a value the tag does not define, and metadata that cannot be read all leave the picture as stored: an unreadable tag is no reason to refuse a picture that decodes.turn_uprightafterreader.decode(). The limits are untouched: width, height and allocation are still checked by the decoder on the stored pixels, and a decode that is refused today is refused the same way.planned_image_size(the header probe, moved out ofkimi_k3_image_promptsso it can be tested without a renderer) returns the upright size, so the planned<|media_pad|>run still matches the grid the decoded picture produces after a quarter turn.mlxcel embed,mlxcel rerank,mlxcel generate-imagereferences, the diffusion path ofmlxcel generate,Yolo11Predictor::predict_path_with_sizeand the RT-DETRv2process_path.docs/llama-server-compat.md, and a sentence indocs/embeddings.md.Before / after
GB10 (sm_121, CUDA 13.0), release builds of
ce6855bc8(main) and of this PR, greedy. The pictures are the shapes fixture (red square top left, blue circle top right, green triangle at the bottom) and a white picture with the textHELLO 739, stored turned and tagged with PIL as in the issue; PIL'sexif_transposegives the upright picture back for each.mlxcel generate --image <picture> -n 40 --temp 0 -p "Which shape is at the bottom of the image, and which shapes are at the top? Answer briefly."(the text rows:-n 24 -p "Read the text in the image. Reply with the text only."):maineXIf), tag 6eXIf) and WebP, tag 6Those are the 12 of 28 replies that change. The other 16 are word for word the same on both builds: the 14 for pictures without a tag (the upright pictures, and the turned pixels saved without the tag, which stay turned), and Gemma 3's two for the tagged text pictures, which it reads as
HELLO 739in any orientation.The server.
mlxcel-server -m Qwen3-VL-4B-Instruct-4bit,POST /v1/chat/completionswith the picture as a base64image_url,temperature: 0, the same question:maineXIf), tag 6A picture without a tag, across the families.
tests/fixtures/test_image_shapes.png(chunksIHDR,IDAT,IEND: noeXIf),-p "Describe the image." -n 48 --temp 0(<CAPTION>for Florence-2), both builds, on 35 checkpoints: Bunny-Llama-3-8B-V, Florence-2-base-ft, GLM-4.1V-9B-Thinking, Idefics2-8B, Idefics3-8B-Llama3, InternVL3-1B and -2B, Kimi-VL-A3B-Thinking, LFM2-VL-450M and -1.6B, Llama-3.2-11B-Vision, Molmo-7B-D-0924, Molmo2-4B and -8B (6 and 8 bit), Phi-3.5-vision, Qwen2-VL-2B, Qwen2.5-VL-3B, Qwen3-VL-4B, SmolVLM-Instruct, aya-vision-8b, deepseek-vl2-small, fastvlm-0.5b, gemma-3-4b, gemma-3n-E2B, gemma-4-e2b, granite-vision-3.2-2b, llava-1.5-7b, llava-interleave-qwen-0.5b, llava-v1.6-mistral-7b, MiniCPM-V-4.6, nanoLLaVA-1.5, PaliGemma 2 (two conversions), pixtral-12b.maingave two texts for granite-vision (18 and 2 runs) and two for nanoLLaVA (17 and 3), and this PR's binary gave the same two (15 and 5, 17 and 3). Qwen3-VL-4B, run the same way as a control, gave one text in all 40 runs. It is the default one-row decode SDPA of fix(cuda): Qwen3 greedy decoding is not reproducible run to run on GB10 #2128, not this change: withMLXCEL_SDPA_DETERMINISTIC=1each of the two checkpoints gave one text in 20 of 20 runs onmainand the same text in 20 of 20 on this PR.!(fix(vision): Molmo2-8B float16 checkpoints emit only "!" on image prompts (unclamped vision features overflow to NaN) #2968).Test plan
Run on this PR's commit (
23edeeb40, one commit once6855bc8) on a DGX Spark (GB10).cargo fmt --all -- --checkcargo clippy --workspace --all-targets --features cuda -- -D warnings(the Linux spelling of the template's line)cargo build --release --features cudacargo test --profile test-fast --features cuda --lib multimodal::image_orientation -- --test-threads=1: 6 passed. All eight tag values come back pixel for pixel through a PNG whoseeXIfchunk the test writes by hand, and through a JPEGAPP1segment; the stored pixels are computed from the tag's definition, not with the crate's own transformsserver::model_provider::model_worker(41 passed),server::chat_request(131 passed),kimi_k3(109 passed) andvision::detection(110 passed)turn_uprightcall taken out of the shared decode,decode_request_images_turns_a_picture_upright_by_its_exif_orientationfails (a 4 x 6 picture for the 6 x 4 one). With the stored size back in the Kimi K3 planning,an_image_prompt_is_sized_for_the_upright_picturefails at tag 5 ((4, 6)for(6, 4))make verify-test-cuda(cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1): 186 of 187 test binaries pass (15494 tests passed, 1 failed, 496 ignored). The one failure isnative_env_tests::the_cuda_cache_defaults_reach_mlx, which fails the same way on a cleanmain(it is order-dependent; described in the notes of perf(cuda): fuse the f32 tanh GELU into one bit-exact kernel (#2780) #2967)ci.ymljobs a pull request from a fork does not get, run by hand:clippy(cargo clippy -p mlxcel --lib --tests -- -D warnings, default features),cpu-link(the build and its 13 tests) andxla-compile(cargo check --features cuda,xla-iree --all-targets,cargo check --no-default-features --features xla-diagnostics --all-targets), pluscargo check --features cuda,xla-reference-diagnostics --all-targets: all passmake verify-python-tooling(219 tests OK), license headers, cross-repo refs, env-var docs, native-env writes, the llama-compat manifest (the new paragraph is in that document) and the binary-asset budget (the tests build their pictures in memory and add no file)a_picture_without_a_readable_tag_is_left_as_it_is), and 27 of the 29 checkpoints that describe such a picture give the same reply word for word; the two that do not vary between runs onmainas well, and give one text on both builds withMLXCEL_SDPA_DETERMINISTIC=1cargo deny check: not run and not applicable (no manifest, lockfile ordeny.tomlchange;imageis already a dependency)make verifyNotes for reviewers
exif_transposeremoves the tag when it turns a picture). A picture whose pixels are upright but whose tag still says otherwise is turned, as it is in mlx-vlm, transformers and any viewer.ImageReader::decodereserves the output buffer againstmax_allocbefore it hands the limits to the decoder, andinto_decoderdoes not; reading the tag from a separate header parse keeps the limit path exactly as it was.embed,rerank,generate-imageand the two detectors on a real checkpoint (I have none of those here; the call sites are one-line swaps to the tested helper). A real phone photo: the pictures are synthetic, built with PIL and, in the unit tests, by hand. TheWebUI installed artifactjob, whichsrc/server/**triggers and a fork PR does not get: it needs pnpm and Playwright, which this host does not have. Metal.Checklist
docs/:docs/llama-server-compat.md,docs/embeddings.md// Used by: ...comments: on the new functions; no existing shared function changes its contract.envfiles committed