Repository navigation
Preserve aspect ratio in Gemma4 image preprocessing - #325
Penrose0v0 wants to merge 2 commits into
Conversation
| gemma4VisionAspectPreservingTarget( | ||
| width: Double($0.extent.width), height: Double($0.extent.height), | ||
| imageSeqLength: config.imageSeqLength, fallback: config.fixedSize) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
3a8492c to
d716b67
Compare
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.
d716b67 to
6d73582
Compare
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>
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>
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 * poolingKernelSizeand kept within the existing pre-pooling patch budget derived fromimageSeqLength, 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
gemma4VisionAspectPreservingTarget