Skip to content

Preserve aspect ratio in Gemma4 image preprocessing - #325

Closed
Penrose0v0 wants to merge 2 commits into
ml-explore:mainfrom
Penrose0v0:gemma4-aspect-resize
Closed

Penrose0v0 wants to merge 2 commits into
ml-explore:mainfrom
Penrose0v0:gemma4-aspect-resize

Conversation

@Penrose0v0

Copy link
Copy Markdown

Summary

This updates Gemma4 image preprocessing to choose an aspect-ratio-preserving target size instead of resizing every image to the fixed square config.fixedSize.

The target size is aligned to patchSize * poolingKernelSize and kept within the existing pre-pooling patch budget derived from imageSeqLength, so the model still receives the same fixed number of vision soft tokens.

This better matches the Gemma4 / mlx-vlm preprocessing behavior and avoids distorting non-square screenshots, dashboards, and tall images.

Testing

  • Added unit tests for gemma4VisionAspectPreservingTarget
    • verifies target sizes align to the pooling stride
    • verifies patch count stays within budget
    • verifies non-square images are not forced to square
    • verifies degenerate extents fall back

Comment on lines +1890 to +1892
gemma4VisionAspectPreservingTarget(
width: Double($0.extent.width), height: Double($0.extent.height),
imageSeqLength: config.imageSeqLength, fallback: config.fixedSize)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good, but there is one potential flaw: if you have multiple input images with different aspect ratios this will resize them independently and will later fail in concatenating them (probably with a failure to broadcast is my guess).

A few things I could think of:

  • multiple images use the old path
  • it finds a fit-in size and resizes everything to fit in that with padding (not sure how well this works)
  • cropping to fit the aspect ratio

I am not sure how often this case will come up. Portrait vs landscape. Screenshots.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pointing this out! You're right that the previous version could produce different H x W tensors for multiple images and then try to concatenate them directly.

I've updated the code so each image is preprocessed independently, flattened, and paired with its THW metadata. The model side then reconstructs each image from the flattened buffer using those frame sizes before running the vision tower. This avoids the shape mismatch while preserving the aspect-ratio resize path for both single-image and multi-image inputs.

I also reproduced the same shape issue in my own downstream test project, and this update fixes it there.

Gemma4Processor.preprocess resized every image to a square fixedSize
(800x800), distorting non-square inputs: a wide screenshot is squashed
horizontally, a tall one vertically. Gemma 4's vision tower is
NaViT-style — it patchifies at the input's real aspect ratio and pools
to a fixed soft-token budget regardless of shape (see Gemma4VisionModel
/ Gemma4VisionPooler) — so the square resize buys nothing on token count
while feeding the model off-distribution, distorted images.

Compute the largest aspect-preserving size within the patch budget,
aligned to poolingKernelSize * patchSize, mirroring mlx-vlm's
Gemma4ImageProcessor.aspect_ratio_preserving_resize. Extracted as the
internal gemma4VisionAspectPreservingTarget so it is unit-testable; tests
cover the patch budget, pooling-stride alignment, non-square preservation,
and degenerate extents.
@Penrose0v0
Penrose0v0 force-pushed the gemma4-aspect-resize branch from 3a8492c to d716b67 Compare July 4, 2026 07:43
Gemma4Processor now preserves each image's aspect ratio, so a multi-image
input produces per-image pixel tensors of different shapes. The old path
stacked them into one dense batch and ran the vision tower once, which
(a) failed to concatenate different-sized images and (b) even for equal
sizes mismatched the per-image soft-token count, so multi-image never
actually worked.

Run the vision tower per image instead. The tower pools every image to a
fixed imageSeqLength soft tokens, so the per-image outputs are equal length
and concatenate cleanly into one (1, numImages * imageSeqLength, hidden)
sequence — matching the expanded image tokens in the prompt. Pixels are
flattened and concatenated in the processor, with each image's (height,
width) carried in `frames` (mirroring the Qwen2-VL pixels+frames handling)
so the model can slice the buffer back apart. Vision tower, pooler, and
weights are unchanged; single-image behavior is identical.

Add Gemma4MultiImagePackingTests covering the flatten -> concat -> slice ->
reshape round-trip for a mix of sizes and aspect ratios.
@Penrose0v0
Penrose0v0 force-pushed the gemma4-aspect-resize branch from d716b67 to 6d73582 Compare July 4, 2026 07:50
@davidkoski

Copy link
Copy Markdown
Member

Thank you for the work on this but let's go with #405 -- this uses the same path with the Gemma4Unified and the python reference and removes the padding item from #290.

@davidkoski davidkoski closed this Jul 10, 2026
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
mlx-swift#58 is squash-merged; pin its main commit instead of the PR branch's c2cbef34, so resolution does not depend on that branch. 67dc7528 has the tree of d80124e (c2cbef34 with mlx and mlx-c pinned to their merged main, identical trees). No source change.

Co-authored-by: jonathan308 <5055076+jonathan308@users.noreply.github.com>
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
Brings ml-explore#322 (Flint), ml-explore#324, ml-explore#326-ml-explore#330 (CBv2 paged/MTP/SDPA, GPT-OSS), ml-explore#325 and the
Nemotron Super fused MTP verify window: SDK main up to the commit d-inference
master pins (889fe3c). Main's later ml-explore#331/ml-explore#332 are left out until the provider
adopts ml-explore#332's streamed tool-call type. Package.swift pins the cluster
mlx-swift 9fe34405 instead of main's 67dc7528; that was the only conflict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants