Skip to content

Gemma 4: aspect-preserving image resize with per-image dynamic token counts; fix multi-image requests - #405

Merged
davidkoski merged 2 commits into
ml-explore:mainfrom
prbme:gemma4-aspect-resize
Jul 16, 2026
Merged

davidkoski merged 2 commits into
ml-explore:mainfrom
prbme:gemma4-aspect-resize

Conversation

@prbme

@prbme prbme commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

What

Ports the Python mlx-vlm Gemma4ImageProcessor resize behavior to the Swift Gemma 4 port, replacing the fixed-size square preprocessing, and makes multi-image requests work.

  • Aspect-preserving resize. Each image is resized to the largest dimensions that keep the patch count within max_soft_tokens × pooling_kernel_size² while leaving both sides divisible by pooling_kernel_size × patch_size. The pooling kernel is then exact for every aspect ratio and the pooled grid covers the image fully. Degenerate extreme-aspect inputs (e.g. an 8000×20 panorama) clamp to one pooling cell on the short side, capped at the token budget on the long side.
  • Per-image dynamic soft-token counts. Prompt placeholders expand per image to numPatches / kernel² soft tokens instead of a fixed image_seq_length. The processor decodes max_soft_tokens / patch_size / pooling_kernel_size from either a flat preprocessor_config.json or the image_processor object nested in processor_config.json.
  • Multi-image requests. Images keep their own sizes through LMInput.ProcessedImage: smaller images are zero-padded onto the request's largest canvas, real sizes ride in frames, and the model slices each image back out and runs the vision tower on it alone, concatenating pooled tokens in placeholder order. Previously any request with more than one image threw imageTokenCountMismatch (N × 280 placeholders vs dim(1) == 280); mixed portrait+landscape requests crashed on concat. Both work now.
  • Padded-path machinery removed. With every patch real, the padded/masked path (-1 positions, encoder attention mask, pooler valid-count trimming) is deleted; the encoder runs dense attention and the pooler pools the full grid. This also removes gemma4VisionPoolingKernel from Fix Gemma 4 vision pooler kernel derivation #290 — the kernel no longer needs to be recovered from a padded length because the resize guarantees numPatches = outputLength × kernel² exactly. The Fix Gemma 4 vision pooler kernel derivation #290 regression tests are replaced by Gemma4ResizeTests, which pin the resize invariants that make that bug class impossible (side alignment, patch budget, exact pooling coverage, aspect preservation, extreme-aspect clamps).
  • The vestigial size config entry is now ignored, matching the Python reference (models ship 224×224 there, which was never used by the Python processor).

The gemma4_unified path (Gemma4Unified, its embedder and processor) is untouched.

Why

The fixed-size square resize distorts every non-square image (a phone screenshot is squashed ~2:1) and diverges from the reference implementation in Python mlx-vlm / HF transformers, which resize aspect-preserving with dynamic token counts. And multi-image prompts — which the chat template and processor placeholder expansion already support — currently throw before generation starts.

Verification

  • xcodebuild test -scheme mlx-swift-lm-Package passes (the pre-existing Gemma4ChunkedPrefillTests/chunkSizeInvariance failure reproduces identically on current main without this change).
  • Runtime-verified against mlx-community/gemma-4-26b-a4b-it-4bit: single portrait, single landscape, and portrait+landscape in one message all produce correct spatial color descriptions (half-and-half color test images; the model names both halves correctly, including the bottom half).
  • Target-size math cross-checked against the Python mlx-vlm formula over 100k random sizes with zero mismatches.

🤖 Generated with Claude Code

Comment thread Libraries/MLXVLM/Models/Gemma4.swift Outdated
Comment on lines +1870 to +1877
values.reserveCapacity(patchesH * patchesW * 2)
for y in 0 ..< patchesH {
for x in 0 ..< patchesW {
values.append(Int32(x))
values.append(Int32(y))
}
}

let count = realCount + paddedCount
return (MLXArray(values, [batch, count, 2]), realCount)
let positions = MLXArray(values, [1, patchesH * patchesW, 2])

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 could potentially be done with meshGrid. Something like this:

let xs = MLXArray.arange(0, patchesW)
let ys = MLXArray.arange(0, patchesH)
let (gx, gy) = meshGrid([xs, ys])
let positions = stacked([gx.flattened(), gy.flattened], axis: 1).reshaped(1, -1, 2)

That all runs on the GPU and the larger array is never realized on the CPU

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 8028f43 — used your snippet almost verbatim. Two small deltas: meshGrid returns [MLXArray] rather than a tuple, so it's grids[0]/grids[1], and I passed dtype: .int32 to arange to keep the positions integral. Left the default indexing: .xy (x varies fastest), which matches the row-major patch order the embedder and pooler expect — added a comment noting that, since correctness depends on it.

Comment thread Libraries/MLXVLM/Models/Gemma4.swift Outdated
// divisible by kernel * patchSize, so the pooled grid covers the
// image exactly.
let positions = patchPositions[0]
let maxX = Int(positions[0..., 0].max().item(Int32.self)) + 1

@davidkoski davidkoski Jul 10, 2026 •

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.

The 0 column in positions is 0 ..< patchesW, so maxX = patchesW - 1 + 1 = patchesW

I think this is only done once per image, but avoiding item/eval in inference is a key to good performance.

(I note this is the same code as before, just different indentation, but since we are in here anyway)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 8028f43 — maxX is gone. The pooler now takes patchesW: Int from the caller and uses it directly. You're right on both counts: it was pre-existing and my diff only reindented it, and the arithmetic checks out — x runs 0 ..< patchesW, so max + 1 == patchesW exactly. No .item() left in the vision path.

@davidkoski davidkoski left a comment

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.

See what you think about the two items I suggested. This looks good!

@davidkoski

davidkoski commented Jul 10, 2026 •

Copy link
Copy Markdown
Member

Also, please rebase -- the lint issue is #416 (and others). You may not have been following that saga -- the short version is that it will pin the version of swift-format to 602.0.0, which is what we have all been using. 603 came out recently but we can't configure it to behave like 602, so waiting for 604.

prbme and others added 2 commits July 16, 2026 05:59
Port the Python mlx-vlm Gemma4ImageProcessor resize to the Swift port,
replacing the fixed-size square preprocessing:

- Each image is resized to the largest dimensions that keep the patch
  count within max_soft_tokens * pooling_kernel_size^2 while leaving both
  sides divisible by pooling_kernel_size * patch_size. The pooling kernel
  is then exact for every aspect ratio and the pooled grid covers the
  image fully. Degenerate extreme-aspect inputs clamp to one pooling cell
  on the short side, capped at the token budget on the long side.
- Prompt placeholders expand per image to numPatches / kernel^2 soft
  tokens instead of a fixed image_seq_length, and the processor decodes
  max_soft_tokens / patch_size / pooling_kernel_size from either a flat
  preprocessor_config.json or the image_processor object nested in
  processor_config.json.
- Images keep their own sizes through LMInput.ProcessedImage: smaller
  images are zero-padded onto the request's largest canvas, real sizes
  ride in frames, and the model slices each image back out and runs the
  vision tower on it alone, concatenating pooled tokens in placeholder
  order. Multi-image requests (previously imageTokenCountMismatch, and
  an MLX concat crash for mixed orientations) now work.
- With every patch real, the padded machinery (-1 positions, attention
  mask, pooler valid-count trimming) is deleted; the encoder runs dense
  attention and the pooler pools the full grid. gemma4VisionPoolingKernel
  (ml-explore#290) is removed with it: the resize guarantees numPatches =
  outputLength * kernel^2, so the kernel no longer needs recovering from
  a padded length. Its regression tests are replaced by Gemma4ResizeTests
  pinning the resize invariants that make that bug class impossible.
- The vestigial 'size' config entry is now ignored, matching the Python
  reference (models ship 224x224 there, which was never used).

The gemma4_unified path is untouched.

Verified against mlx-community/gemma-4-26b-a4b-it-4bit: single portrait,
single landscape, and portrait+landscape in one message all produce
correct spatial color descriptions; target-size math cross-checked
against the Python formula over 100k random sizes with zero mismatches.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Address review feedback from ml-explore#405:
- patchPositions now uses arange + meshGrid + stacked, so the grid is
  built on the GPU instead of materializing a Swift array on the CPU.
- The pooler takes patchesW directly from the caller instead of
  recovering it from the positions array via max().item(), which forced
  a GPU sync per image.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@prbme
prbme force-pushed the gemma4-aspect-resize branch from 016e798 to 8028f43 Compare July 16, 2026 10:03
@prbme

prbme commented Jul 16, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (4ca25fd) and pushed — 8028f43. Both review comments addressed.

On the rebased branch: builds clean, Gemma4ResizeTests passes (5 tests, incl. 1×1 / 20×8000 / 4032×3024), and swift-format lint --strict is clean on the touched files.

On the lint saga — looks like #404 landed 603 conformance rather than pinning 602, so main pins 603.0.0 now. Lint's clean here at that version.

@davidkoski davidkoski left a comment

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.

Change looks good, thank you!

@davidkoski
davidkoski merged commit 60bd0d7 into ml-explore:main Jul 16, 2026
2 checks passed
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
…counts; fix multi-image requests (ml-explore#405)

Gemma4: aspect-preserving resize with per-image dynamic token counts
Port the Python mlx-vlm Gemma4ImageProcessor resize to the Swift port,
replacing the fixed-size square preprocessing.
- Resize each image to the largest dimensions that keep the patch count
  within max_soft_tokens * pooling_kernel_size^2 with both sides divisible
  by pooling_kernel_size * patch_size, so the pooling kernel is exact and
  the pooled grid covers the image at any aspect ratio. Extreme-aspect
  inputs clamp to one pooling cell on the short side, capped at the token
  budget on the long side.
- Expand prompt placeholders per image to numPatches / kernel^2 soft
  tokens instead of a fixed image_seq_length. The processor decodes
  max_soft_tokens / patch_size / pooling_kernel_size from a flat
  preprocessor_config.json or the nested image_processor object.
- Carry per-image sizes through LMInput.ProcessedImage: smaller images are
  zero-padded onto the request's largest canvas, real sizes ride in frames,
  and the model slices each image back out to run the vision tower alone,
  concatenating pooled tokens in placeholder order. Multi-image requests
  (previously imageTokenCountMismatch, plus an MLX concat crash for mixed
  orientations) now work.
- With every patch real, the padded machinery (-1 positions, attention
  mask, pooler valid-count trimming) is deleted: dense encoder attention,
  full-grid pooling. gemma4VisionPoolingKernel (ml-explore#290) goes with it, since
  the resize guarantees numPatches = outputLength * kernel^2. Its
  regression tests are replaced by Gemma4ResizeTests.
- The vestigial 'size' config entry is now ignored, matching the Python
  reference. gemma4_unified is untouched.
Also builds patch positions on the GPU with arange + meshGrid + stacked,
and passes patchesW into the pooler directly instead of recovering it via
max().item() (which forced a per-image GPU sync).
Verified against mlx-community/gemma-4-26b-a4b-it-4bit (single portrait,
single landscape, and portrait+landscape in one message); target-size math
cross-checked against the Python formula over 100k random sizes.
ngingric pushed a commit to TechnicallyInvalid/mlx-swift-lm that referenced this pull request Sep 15, 2026
Backports upstream PR ml-explore#405, commit 60bd0d7. Required for assessment windows containing multiple frames; preserves the 3.31.4 preparation API.
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…ents-follow-schema

Gemma: read an unmarked scalar by its parameter's schema, so `zip:01000` stays "01000" (provider 0.10.13)
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
Brings the branch onto current main so d-inference can pin one SDK commit
that carries both ml-explore#405 (d-inference#2050) and this PR (d-inference#2060).
No overlap: ml-explore#405 changes the Gemma tool parser, its tests and docs; the only
shared file is fork.yaml, in different sections (clean merge).

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