Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 97 additions & 9 deletions Libraries/MLXVLM/Models/Gemma4.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import MLXNN
private enum Gemma4Error: LocalizedError {
case imageTokenCountMismatch(expectedVisionTokens: Int, actualPromptTokens: Int)
case multimodalTokenCountMismatch(kind: String, featureTokens: Int, promptTokens: Int)
case missingImageFrames

var errorDescription: String? {
switch self {
Expand All @@ -18,6 +19,9 @@ private enum Gemma4Error: LocalizedError {
case .multimodalTokenCountMismatch(let kind, let featureTokens, let promptTokens):
return
"Gemma4 \(kind) token count mismatch: encoder produced \(featureTokens) soft tokens, but the prompt contains \(promptTokens) \(kind) tokens."
case .missingImageFrames:
return
"Gemma4 received image pixels without per-image frames; the vision path needs each image's (height, width) to reconstruct the flattened pixels."
}
}
}
Expand Down Expand Up @@ -105,6 +109,55 @@ internal func gemma4VisionPoolingKernel(
return Int(sqrt(Double(ratio)))
}

/// Largest aspect-ratio-preserving size for a Gemma 4 vision input that stays
/// within the soft-token (patch) budget and aligns to
/// `patchSize * poolingKernelSize`. Mirrors mlx-vlm's
/// `Gemma4ImageProcessor.aspect_ratio_preserving_resize`.
///
/// 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, so
/// preserving aspect ratio (rather than forcing a square `fixedSize`) avoids
/// feeding the model distorted, off-distribution images at no token cost.
///
/// Returns `fallback` for degenerate (non-positive) extents.
internal func gemma4VisionAspectPreservingTarget(
width: Double, height: Double, imageSeqLength: Int, fallback: CGSize
) -> CGSize {
// Fixed by Gemma 4's SigLIP-style vision encoder.
let patchSize = 16
let poolingKernelSize = 3
let sideMultiple = patchSize * poolingKernelSize
let maxPatches = imageSeqLength * poolingKernelSize * poolingKernelSize

guard width > 0, height > 0 else { return fallback }

func alignedDown(_ value: Double) -> Int {
max((Int(value) / sideMultiple) * sideMultiple, sideMultiple)
}

let maxPixels = Double(maxPatches * patchSize * patchSize)
let scale = sqrt(maxPixels / (width * height))

var targetW = alignedDown(width * scale)
var targetH = alignedDown(height * scale)

// Flooring to `sideMultiple` already keeps the patch count within budget for
// normal aspect ratios; this loop only fires for extreme ratios where the
// short side is clamped up to a single block, trimming the long side until
// the budget holds.
while (targetW / patchSize) * (targetH / patchSize) > maxPatches {
if targetW >= targetH && targetW > sideMultiple {
targetW -= sideMultiple
} else if targetH > sideMultiple {
targetH -= sideMultiple
} else {
break
}
}

return CGSize(width: targetW, height: targetH)
}

private func gemma4RotateHalf(_ x: MLXArray) -> MLXArray {
let half = x.shape[x.shape.count - 1] / 2
let x1 = x[.ellipsis, ..<half]
Expand Down Expand Up @@ -2010,7 +2063,8 @@ public final class Gemma4: Module, VLMModel, KVCacheDimensionProvider {

private func getInputEmbeddings(
inputIds: MLXArray,
pixelValues: MLXArray? = nil
pixelValues: MLXArray? = nil,
frames: [THW]? = nil
) throws -> (MLXArray, MLXArray?) {
var inputsEmbeds = languageModel.model.embedTokens(inputIds)
inputsEmbeds =
Expand All @@ -2035,8 +2089,30 @@ public final class Gemma4: Module, VLMModel, KVCacheDimensionProvider {
guard let pixelValues else {
return (inputsEmbeds, perLayerInputs)
}

var imageFeatures = visionTower(pixelValues)
guard let frames, !frames.isEmpty else {
throw Gemma4Error.missingImageFrames
}

// Images are preprocessed at their own aspect-ratio-preserving sizes, so
// they cannot be stacked into a single dense batch; they arrive flattened
// and concatenated, with `frames` carrying each image's (height, width).
// Run the vision tower once per image — the tower pools every image to a
// fixed `imageSeqLength` soft tokens, so the per-image outputs are equal
// length — then concatenate them into one
// `(1, numImages * imageSeqLength, hidden)` sequence.
let channels = 3
var visionOutputs: [MLXArray] = []
visionOutputs.reserveCapacity(frames.count)
var offset = 0
for frame in frames {
let count = channels * frame.h * frame.w
let imagePixels = pixelValues[offset ..< (offset + count)]
.reshaped(1, channels, frame.h, frame.w)
offset += count
visionOutputs.append(visionTower(imagePixels))
}

var imageFeatures = concatenated(visionOutputs, axis: 1)
imageFeatures = embedVision(imageFeatures)
imageFeatures = imageFeatures.asType(inputsEmbeds.dtype)

Expand Down Expand Up @@ -2065,7 +2141,8 @@ public final class Gemma4: Module, VLMModel, KVCacheDimensionProvider {
let convertedCache = cache.map { $0 }
if let imagePixels = input.image?.pixels {
let (inputsEmbeds, perLayerInputs) = try getInputEmbeddings(
inputIds: input.text.tokens, pixelValues: imagePixels)
inputIds: input.text.tokens, pixelValues: imagePixels,
frames: input.image?.frames)
let result = languageModel(
nil,
cache: convertedCache,
Expand Down Expand Up @@ -2621,11 +2698,17 @@ public struct Gemma4Processor: UserInputProcessor {
public func preprocess(images: [CIImage], processing: UserInput.Processing?) throws -> (
MLXArray, THW
) {
var userProcessing = processing ?? UserInput.Processing()
let targetSize = config.fixedSize
userProcessing.resize = targetSize
let targetSize =
images.first.map {
gemma4VisionAspectPreservingTarget(
width: Double($0.extent.width), height: Double($0.extent.height),
imageSeqLength: config.imageSeqLength, fallback: config.fixedSize)
Comment on lines +2703 to +2705

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.

} ?? config.fixedSize

let processedImages = images.map { image in
var userProcessing = processing ?? UserInput.Processing()
userProcessing.resize = targetSize

let processedImage = MediaProcessing.apply(image, processing: userProcessing)
let srgbImage = MediaProcessing.inSRGBToneCurveSpace(processedImage)
let resizedImage = MediaProcessing.resampleBicubic(srgbImage, to: targetSize)
Expand Down Expand Up @@ -2656,9 +2739,14 @@ public struct Gemma4Processor: UserInputProcessor {
let imagePixelsAndFrames = try input.images.map {
try preprocess(images: [$0.asCIImage()], processing: input.processing)
}
let imagePixelsConcatenated = concatenated(imagePixelsAndFrames.map { $0.0 })
// Each image is aspect-ratio-preserved to its own (height, width), so
// the per-image pixel tensors have different shapes and cannot be
// stacked. Flatten each to 1D and concatenate; the paired `frames`
// carry every image's (height, width) so the model can slice this
// buffer back apart and run the vision tower per image.
let flattenedPixels = concatenated(imagePixelsAndFrames.map { $0.0.flattened() })
processedImage = LMInput.ProcessedImage(
pixels: imagePixelsConcatenated,
pixels: flattenedPixels,
frames: imagePixelsAndFrames.map { $0.1 }
)

Expand Down
69 changes: 69 additions & 0 deletions Tests/MLXLMTests/Gemma4AspectResizeTests.swift
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)
}
}
68 changes: 68 additions & 0 deletions Tests/MLXLMTests/Gemma4MultiImagePackingTests.swift
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)
}
}
}