Repository navigation
Fix Gemma 4 vision pooler kernel derivation - #290
Merged
davidkoski merged 1 commit intoMay 22, 2026
Merged
Conversation
Member
|
Waiting on CI -- infrastructure issue |
Contributor
Author
|
Thanks! First PR here. Wide open to feedback on format. |
Gemma4VisionPooler.callAsFunction derived the kernel from the real
(un-padded) patch count rather than the padded sequence length. At
the default 280 soft-token budget, this can recover kernel=2 for
typical image sizes, while HuggingFace's reference implementation
and the model's pooling_kernel_size config both expect 3. Real-patch
positions whose flat-kernel bucket index exceeds pooledLength then
map to all-zero one-hot rows by gemma4OneHot and contribute nothing
to the einsum output.
Extract the formula into gemma4VisionPoolingKernel(paddedPatchCount:
outputLength:) and derive the kernel from pooledHiddenStates.dim(1)
(= outputLength * pool^2) so it returns pool=3 for every supported
budget.
Add Gemma4VisionPoolingTests asserting kernel=3 for all five
documented budgets {70, 140, 280, 560, 1120}, with a regression
test documenting the prior formula's behavior.
davidkoski
force-pushed
the
fix/gemma4-pooling-kernel
branch
from
May 22, 2026 16:53
1080007 to
2b32be5
Compare
Member
|
rebase to pick up CI fix |
prbme
added a commit
to prbme/mlx-swift-lm
that referenced
this pull request
Jul 16, 2026
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>
davidkoski
pushed a commit
that referenced
this pull request
Jul 16, 2026
…counts; fix multi-image requests (#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 (#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.
dkgv
pushed a commit
to dkgv/mlx-swift-lm
that referenced
this pull request
Jul 30, 2026
Fix Gemma4VisionPooler kernel derivation to use padded sequence length
Previously, the kernel was derived from the real patch count, which could yield kernel=2 at the 280-token budget instead of the expected 3, causing real patches to map to zero rows in the einsum output.
Extract gemma4VisionPoolingKernel(paddedPatchCount:outputLength:) and derive the kernel from pooledHiddenStates.dim(1) to consistently return pool=3 across all supported budgets. Add regression tests for all five budgets {70, 140, 280, 560, 1120}.
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.
davidtai
pushed a commit
to davidtai/mlx-swift-lm
that referenced
this pull request
Oct 6, 2026
…l-explore#290) * fix(cbv2): retire cancelled waiting requests before removing them * style(cbv2): format native engine files for CI
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Gemma4VisionPooler.callAsFunction derived the kernel from the real (un-padded) patch count rather than the padded sequence length. At the default 280 soft-token budget, this can recover kernel=2 for typical image sizes, while HuggingFace's reference implementation and the model's pooling_kernel_size config both expect 3. Real-patch positions whose flat-kernel bucket index exceeds pooledLength then map to all-zero one-hot rows by gemma4OneHot and contribute nothing to the einsum output.
Extract the formula into gemma4VisionPoolingKernel(paddedPatchCount: outputLength:) and derive the kernel from pooledHiddenStates.dim(1) (= outputLength * pool^2) so it returns pool=3 for every supported budget.
Add Gemma4VisionPoolingTests asserting kernel=3 for all five documented budgets {70, 140, 280, 560, 1120}, with a regression test documenting the prior formula's behavior.
Proposed changes
Fixes #289. Aligns the Gemma 4 vision pooler's kernel derivation with HuggingFace's reference image processor so the recovered kernel matches the model's
pooling_kernel_size = 3at every supported soft-token budget.Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes