Skip to content

Fix Gemma 4 vision pooler kernel derivation - #290

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
joshuaejackson:fix/gemma4-pooling-kernel
May 22, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
joshuaejackson:fix/gemma4-pooling-kernel

Conversation

@joshuaejackson

Copy link
Copy Markdown
Contributor

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 = 3 at every supported soft-token budget.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

@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.

Nice find and fix!

@davidkoski

Copy link
Copy Markdown
Member

Waiting on CI -- infrastructure issue

@joshuaejackson

Copy link
Copy Markdown
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
davidkoski force-pushed the fix/gemma4-pooling-kernel branch from 1080007 to 2b32be5 Compare May 22, 2026 16:53
@davidkoski

Copy link
Copy Markdown
Member

rebase to pick up CI fix

@davidkoski
davidkoski merged commit 4f1bbaf into ml-explore:main May 22, 2026
2 checks passed
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gemma 4 vision pooler derives kernel from unpadded patch count

2 participants