Repository navigation
Preserve aspect ratio in Gemma4 image preprocessing #325
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| // Copyright © 2026 Apple Inc. | ||
|
|
||
| import CoreGraphics | ||
| import Foundation | ||
| import Testing | ||
|
|
||
| @testable import MLXVLM | ||
|
|
||
| /// Unit tests for `gemma4VisionAspectPreservingTarget`. Verifies the resize | ||
| /// target avoids square distortion, stays within the patch budget, and aligns | ||
| /// to `patch_size * pooling_kernel_size`. | ||
| struct Gemma4AspectResizeTests { | ||
| private static let patchSize = 16 | ||
| private static let poolingKernelSize = 3 | ||
| private static let sideMultiple = patchSize * poolingKernelSize | ||
| private static let imageSeqLength = 280 | ||
| private static let fallback = CGSize(width: 800, height: 800) | ||
| private static var maxPatches: Int { imageSeqLength * poolingKernelSize * poolingKernelSize } | ||
|
|
||
| private func target(_ width: Double, _ height: Double) -> CGSize { | ||
| gemma4VisionAspectPreservingTarget( | ||
| width: width, | ||
| height: height, | ||
| imageSeqLength: Self.imageSeqLength, | ||
| fallback: Self.fallback | ||
| ) | ||
| } | ||
|
|
||
| @Test( | ||
| "Target stays within budget and aligns to pooling stride", | ||
| arguments: [ | ||
| (1280.0, 800.0), // wide dashboard | ||
| (800.0, 1280.0), // tall page | ||
| (1000.0, 1000.0), // square | ||
| (1920.0, 1080.0), // 16:9 | ||
| (2560.0, 900.0), // ultra-wide | ||
| ]) | ||
| func targetIsAlignedAndBounded(size: (Double, Double)) { | ||
| let target = target(size.0, size.1) | ||
| let width = Int(target.width) | ||
| let height = Int(target.height) | ||
|
|
||
| #expect(width % Self.sideMultiple == 0) | ||
| #expect(height % Self.sideMultiple == 0) | ||
| #expect(width >= Self.sideMultiple) | ||
| #expect(height >= Self.sideMultiple) | ||
|
|
||
| let patchCount = (width / Self.patchSize) * (height / Self.patchSize) | ||
| #expect(patchCount <= Self.maxPatches) | ||
| } | ||
|
|
||
| @Test("Non-square images are not forced to square") | ||
| func nonSquareImagesAreNotForcedToSquare() { | ||
| let wideTarget = target(1280, 800) | ||
| let wideAspectRatio = Double(wideTarget.width) / Double(wideTarget.height) | ||
| #expect(wideAspectRatio > 1.5) | ||
|
|
||
| let tallTarget = target(800, 1280) | ||
| let tallAspectRatio = Double(tallTarget.width) / Double(tallTarget.height) | ||
| #expect(tallAspectRatio < 0.67) | ||
| } | ||
|
|
||
| @Test("Degenerate extents fall back") | ||
| func degenerateExtentsFallBack() { | ||
| #expect(target(0, 0) == Self.fallback) | ||
| #expect(target(-10, 100) == Self.fallback) | ||
| #expect(target(100, 0) == Self.fallback) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| // Copyright © 2026 Apple Inc. | ||
|
|
||
| import Foundation | ||
| import MLX | ||
| import Testing | ||
|
|
||
| @testable import MLXVLM | ||
|
|
||
| /// Guards the multi-image pixel packing used by the Gemma4 (non-unified) vision | ||
| /// path. Each image is aspect-ratio-preserved to its own `(height, width)`, so | ||
| /// the images cannot be stacked into one dense batch: `Gemma4Processor.prepare` | ||
| /// flattens every image to 1D and concatenates them, and `Gemma4.getInputEmbeddings` | ||
| /// slices that buffer back apart using each image's `(height, width)` from | ||
| /// `frames`. This verifies the flatten → concat → slice → reshape round-trip | ||
| /// recovers every image exactly for a mix of different sizes and aspect ratios. | ||
| struct Gemma4MultiImagePackingTests { | ||
| private static let channels = 3 | ||
|
|
||
| // (height, width) — deliberately different sizes and aspect ratios, each a | ||
| // multiple of `patch_size * pooling_kernel_size` (48) like real targets. | ||
| private static let sizes: [(h: Int, w: Int)] = [ | ||
| (48, 96), // wide | ||
| (96, 48), // tall | ||
| (144, 144), // square, larger | ||
| ] | ||
|
|
||
| @Test("Flatten/concat then slice/reshape recovers each image exactly") | ||
| func packingRoundTrips() { | ||
| // Pure data movement (flatten/concat/slice/reshape); scope to the CPU | ||
| // backend so it runs under `swift test` without the Metal library. | ||
| Device.withDefaultDevice(.cpu) { | ||
| // One distinct dense image per size, mirroring the (1, C, H, W) | ||
| // layout that MediaProcessing.asMLXArray produces. Globally unique | ||
| // values catch any ordering or off-by-one error in the pack/unpack. | ||
| var originals: [MLXArray] = [] | ||
| var base = 0 | ||
| for size in Self.sizes { | ||
| let count = Self.channels * size.h * size.w | ||
| let image = MLXArray(base ..< (base + count)) | ||
| .reshaped(1, Self.channels, size.h, size.w) | ||
| originals.append(image) | ||
| base += count | ||
| } | ||
|
|
||
| // Processor side (Gemma4Processor.prepare): flatten each to 1D, concat. | ||
| let packed = concatenated(originals.map { $0.flattened() }) | ||
|
|
||
| let expectedLength = Self.sizes.reduce(0) { $0 + Self.channels * $1.h * $1.w } | ||
| #expect(packed.ndim == 1) | ||
| #expect(packed.dim(0) == expectedLength) | ||
|
|
||
| // Model side (Gemma4.getInputEmbeddings): slice by count, reshape back. | ||
| var offset = 0 | ||
| for (index, size) in Self.sizes.enumerated() { | ||
| let count = Self.channels * size.h * size.w | ||
| let recovered = packed[offset ..< (offset + count)] | ||
| .reshaped(1, Self.channels, size.h, size.w) | ||
| offset += count | ||
|
|
||
| #expect(recovered.shape == [1, Self.channels, size.h, size.w]) | ||
| #expect((recovered .== originals[index]).all().item(Bool.self)) | ||
| } | ||
|
|
||
| // The model consumes exactly the whole buffer, in order. | ||
| #expect(offset == expectedLength) | ||
| } | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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:
I am not sure how often this case will come up. Portrait vs landscape. Screenshots.
There was a problem hiding this comment.
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 Wtensors 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
THWmetadata. 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.