Skip to content

fix(vision): turn pictures upright by their EXIF orientation - #2993

Merged
inureyes merged 4 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/exif-orientation-image-input
Nov 14, 2026
Merged

inureyes merged 4 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/exif-orientation-image-input

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

Summary

mlxcel handed a model the pixels a picture stores and ignored its EXIF Orientation tag, so a portrait photo from a phone reached the model on its side. mlx-vlm's and transformers' load_image turn the picture by that tag (PIL.ImageOps.exif_transpose). This applies the tag where pictures are decoded: the one decode every server family and mlxcel generate share, 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 fix

Cause

decode_request_image_with_limits in src/server/model_worker.rs was ImageReader::new(..).with_guessed_format()?.decode(). The image crate 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, and mlxcel generate reaches it through server::local_media. embed, rerank, generate-image and the detection predictors called image::open / image::load_from_memory directly.

Change

  • src/multimodal/image_orientation.rs (new). exif_orientation(bytes) reads the tag from the header and metadata (JPEG APP1, PNG eXIf, WebP). turn_upright, load_upright_from_memory and open_upright apply it after the decode; upright_dimensions answers 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.
  • The shared decode calls turn_upright after reader.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.
  • Kimi K3 image prompts are sized from the header before the worker decodes. planned_image_size (the header probe, moved out of kimi_k3_image_prompts so 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.
  • Direct opens: mlxcel embed, mlxcel rerank, mlxcel generate-image references, the diffusion path of mlxcel generate, Yolo11Predictor::predict_path_with_size and the RT-DETRv2 process_path.
  • Docs: a paragraph under "Multimodal projectors and request media" in docs/llama-server-compat.md, and a sentence in docs/embeddings.md.
  • Not changed: the benchmark binaries and diagnostics, which read repository fixtures, and video frames, which are decoded from frames without an EXIF tag.

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 text HELLO 739, stored turned and tagged with PIL as in the issue; PIL's exif_transpose gives 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."):

Picture Model main This PR
JPEG, tag 6 Qwen3-VL-4B-Instruct-4bit The red square is at the bottom. The blue circle and green triangle are at the top. The green triangle is at the bottom. The red square and blue circle are at the top.
JPEG, tag 3 same Bottom: circle and square. Top: triangle. Shape at bottom: triangle. Shapes at top: square and circle.
JPEG, tag 8 same Shape at bottom: blue circle. Shapes at top: red square and green triangle. The green triangle is at the bottom. The red square and blue circle are at the top.
PNG (eXIf), tag 6 same Shape at bottom: red square. Shapes at top: blue circle, green triangle Triangle is at the bottom. Square and circle are at the top. (the upright PNG's reply, word for word)
WebP, tag 6 same the same as the PNG the same as the PNG
text, JPEG tag 6 same 30 30 30 30 30 30 30 30 Hello 73 (the upright picture's reply)
text, JPEG tag 3 same 631007122222222222222222 Hello 73
JPEG, tag 6 gemma-3-4b-it-4bit Bottom: Square. Top: Circle and triangle Bottom: Triangle. Top: Square and Circle (the upright reply, word for word)
JPEG, tag 3 same Bottom: Square. Top: Triangle, Circle the upright reply
JPEG, tag 8 same Bottom: Circle. Top: Triangle and Square the upright reply
PNG (eXIf) and WebP, tag 6 same Bottom: Square. Top: Circle and triangle the upright reply

Those 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 739 in any orientation.

The server. mlxcel-server -m Qwen3-VL-4B-Instruct-4bit, POST /v1/chat/completions with the picture as a base64 image_url, temperature: 0, the same question:

Picture main This PR
upright JPEG Shape at bottom: triangle. Shapes at top: square and circle identical
JPEG, tag 6 The red square is at the bottom. The blue circle and green triangle are at the top. The green triangle is at the bottom. The red square and blue circle are at the top.
the same pixels, no tag The red square is at the bottom. The blue circle and green triangle are at the top. identical
JPEG, tag 3 Bottom: circle and square. Top: triangle. Shape at bottom: triangle. Shapes at top: square and circle.
PNG (eXIf), tag 6 Shape at bottom: red square. Shapes at top: blue circle, green triangle Triangle is at the bottom. Square and circle are at the top.
WebP, tag 6 the same as the PNG the same as the PNG

A picture without a tag, across the families. tests/fixtures/test_image_shapes.png (chunks IHDR, IDAT, IEND: no eXIf), -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.

  • 29 describe the picture. 27 of them give the same reply on both builds, word for word.
  • The other two, granite-vision-3.2-2b-4bit and nanoLLaVA-1.5-4bit, gave a different text, and they do that between two runs of one binary: over 20 alternating runs each, main gave 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: with MLXCEL_SDPA_DETERMINISTIC=1 each of the two checkpoints gave one text in 20 of 20 runs on main and the same text in 20 of 20 on this PR.
  • Six show no reply to compare, the same on both builds: GLM-4.1V, Kimi-VL, gemma-4-e2b and MiniCPM-V-4.6 spend the 48 tokens in the reasoning channel, and the two Molmo2-8B conversions print ! (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 on ce6855bc8) on a DGX Spark (GB10).

  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets --features cuda -- -D warnings (the Linux spelling of the template's line)
  • cargo build --release --features cuda
  • cargo 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 whose eXIf chunk the test writes by hand, and through a JPEG APP1 segment; the stored pixels are computed from the tag's definition, not with the crate's own transforms
  • The same command for server::model_provider::model_worker (41 passed), server::chat_request (131 passed), kimi_k3 (109 passed) and vision::detection (110 passed)
  • Mutations. With the turn_upright call taken out of the shared decode, decode_request_images_turns_a_picture_upright_by_its_exif_orientation fails (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_picture fails at tag 5 ((4, 6) for (6, 4))
  • Evidence identity audit (2026-11-12): all eight newly added test names are present and passing in the targeted logs and in the full CUDA gate; the two removed-call controls fail by name, and the recorded final tree matches this commit. This is a read-only audit of the retained runs, not a rerun.
  • 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 is native_env_tests::the_cuda_cache_defaults_reach_mlx, which fails the same way on a clean main (it is order-dependent; described in the notes of perf(cuda): fuse the f32 tanh GELU into one bit-exact kernel (#2780) #2967)
  • The self-hosted ci.yml jobs 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) and xla-compile (cargo check --features cuda,xla-iree --all-targets, cargo check --no-default-features --features xla-diagnostics --all-targets), plus cargo check --features cuda,xla-reference-diagnostics --all-targets: all pass
  • make 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)
  • Validated with real checkpoints: the tables above
  • Traced per "Judging a change that moves the numbers": a reply moves only for a picture whose tag is 2 to 8. A picture without a tag decodes to the same pixels (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 on main as well, and give one text on both builds with MLXCEL_SDPA_DETERMINISTIC=1
  • cargo deny check: not run and not applicable (no manifest, lockfile or deny.toml change; image is already a dependency)
  • Metal: not built or run here. The change is in the decode, before any array exists; the new tests first run on Metal in the nightly make verify

Notes for reviewers

  • This changes what a model sees for a tagged picture, on purpose. A client that already sends upright pixels without the tag is not affected (PIL's exif_transpose removes 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.
  • Detection boxes are in upright coordinates now, the picture the user looks at. Before, a tagged picture gave boxes in the stored frame.
  • Memory. A quarter turn makes a second buffer of the same size for a moment. The decode allocation limit bounds the first; the copy is the same size and is not counted against it.
  • The tag is read in a second pass over the header, not from the decoder that produces the pixels. ImageReader::decode reserves the output buffer against max_alloc before it hands the limits to the decoder, and into_decoder does not; reading the tag from a separate header parse keeps the limit path exactly as it was.
  • Not run: embed, rerank, generate-image and 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. The WebUI installed artifact job, which src/server/** triggers and a fork PR does not get: it needs pnpm and Playwright, which this host does not have. Metal.
  • Implemented and validated with AI assistance (Claude) driving the GB10 host. Every number above comes from the logs of those runs.

Checklist

  • PR title uses a Conventional Commits prefix
  • One logical change per PR
  • Updated docs/: docs/llama-server-compat.md, docs/embeddings.md
  • Updated // Used by: ... comments: on the new functions; no existing shared function changes its contract
  • No secrets, credentials, or .env files committed

Jaeyeong-CHOI and others added 4 commits November 12, 2026 01:53
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
@inureyes

Copy link
Copy Markdown
Member

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 image_url, /v1/embeddings, /v1/rerank and /v1/images/edits all reach decode_request_image_with_limits through media::fetch_labeled_image; mlxcel generate --image, the OCR commands, RF-DETR and PP-DocLayoutV3 reach it through decode_image_payloads_with_limits; embed, rerank, generate-image, the diffusion path, YOLO11 and RT-DETRv2 use the new helpers. The only remaining direct image::open calls are in bench binaries and diagnostics. Kimi K3 is the only header-based sizer, and it now returns the upright size.

Dependencies. No manifest or lockfile change; image 0.25.10 was already a dependency, so cargo-deny and license policy are unaffected.

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 max_alloc does not count.

Pushed.

  • Merged origin/main into the branch.
  • Added a_webp_exif_chunk_is_read_as_well: all eight tags through a lossless WebP EXIF chunk, pixel exact. PNG and JPEG were covered; WebP was only checked by hand.
  • Added the bilingual technical report.

Validated on macOS M3 Ultra (Metal). Targeted lib tests (120 passed, including all orientation, model_worker, chat_request and kimi_k3 tests), cargo clippy --lib --tests -- -D warnings, release build. gemma-3n-e2b-it-4bit greedy on the shapes fixture: upright and tag 3, 6, 8 JPEGs all answer triangle at the bottom, square and circle at the top; the untagged tag 6 pixels answer square at the bottom. The server image_url path gives the same split.

@inureyes
inureyes merged commit ff4ed7f into lablup:main Nov 14, 2026
31 checks passed
@inureyes inureyes added the status:done Completed label Nov 14, 2026
@inureyes inureyes added type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:inference Generation, sampling, decoding (incl. speculative, DRY) modeltype:vlm Vision-language model labels Nov 30, 2026
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) modeltype:vlm Vision-language model priority:medium Medium priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(vision): apply EXIF orientation to image inputs before preprocessing

2 participants