Repository navigation
Gemma 4: aspect-preserving image resize with per-image dynamic token counts; fix multi-image requests - #405
Conversation
| 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]) |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
| // 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 |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
See what you think about the two items I suggested. This looks good!
|
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. |
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>
016e798 to
8028f43
Compare
|
Rebased onto On the rebased branch: builds clean, On the lint saga — looks like #404 landed 603 conformance rather than pinning 602, so |
davidkoski
left a comment
There was a problem hiding this comment.
Change looks good, thank you!
…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.
Backports upstream PR ml-explore#405, commit 60bd0d7. Required for assessment windows containing multiple frames; preserves the 3.31.4 preparation API.
…ents-follow-schema Gemma: read an unmarked scalar by its parameter's schema, so `zip:01000` stays "01000" (provider 0.10.13)
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>
What
Ports the Python mlx-vlm
Gemma4ImageProcessorresize behavior to the Swift Gemma 4 port, replacing the fixed-size square preprocessing, and makes multi-image requests work.max_soft_tokens × pooling_kernel_size²while leaving both sides divisible bypooling_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.numPatches / kernel²soft tokens instead of a fixedimage_seq_length. The processor decodesmax_soft_tokens/patch_size/pooling_kernel_sizefrom either a flatpreprocessor_config.jsonor theimage_processorobject nested inprocessor_config.json.LMInput.ProcessedImage: smaller images are zero-padded onto the request's largest canvas, real sizes ride inframes, 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 threwimageTokenCountMismatch(N × 280placeholders vsdim(1) == 280); mixed portrait+landscape requests crashed on concat. Both work now.-1positions, encoder attention mask, pooler valid-count trimming) is deleted; the encoder runs dense attention and the pooler pools the full grid. This also removesgemma4VisionPoolingKernelfrom Fix Gemma 4 vision pooler kernel derivation #290 — the kernel no longer needs to be recovered from a padded length because the resize guaranteesnumPatches = outputLength × kernel²exactly. The Fix Gemma 4 vision pooler kernel derivation #290 regression tests are replaced byGemma4ResizeTests, which pin the resize invariants that make that bug class impossible (side alignment, patch budget, exact pooling coverage, aspect preservation, extreme-aspect clamps).sizeconfig entry is now ignored, matching the Python reference (models ship 224×224 there, which was never used by the Python processor).The
gemma4_unifiedpath (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-Packagepasses (the pre-existingGemma4ChunkedPrefillTests/chunkSizeInvariancefailure reproduces identically on currentmainwithout this change).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).mlx-vlmformula over 100k random sizes with zero mismatches.🤖 Generated with Claude Code