Skip to content

Add native-resolution image preprocessing for Gemma-4 - #6262

Open
nuinashco-ks wants to merge 10 commits into
AI-Hypercomputer:mainfrom
KyivstarDMP:pr/native-resolution
Open

nuinashco-ks wants to merge 10 commits into
AI-Hypercomputer:mainfrom
KyivstarDMP:pr/native-resolution

Conversation

@nuinashco-ks

@nuinashco-ks nuinashco-ks commented Nov 11, 2026 •

Copy link
Copy Markdown

Description

Adds native-resolution image preprocessing for Gemma-4, like the Hugging Face processor: each image keeps its aspect ratio and is resized to at most vision_output_length soft tokens, instead of being stretched to 672x960 (height x width). It is behind a new flag, use_native_resolution_for_vit, which gemma4-e2b.yml and gemma4-e4b.yml turn on. 26B and 31B keep the 672x960 path.

It also lets an image SFT dataset contain rows without an image. Such a row trains as plain text: it gets no image tokens, and its image slot is all padding, which the encoder masks.

Stacked on #6621 (image support for E2B / E4B), which is stacked on #6224. Until they land, this diff includes their commits; this PR's own three commits: compare.

Why

With #6621 the Gemma-4 vision encoder takes patches with per-patch (x, y) positions and masks padded patches, as Hugging Face does, but nothing in MaxText produces such input. Preprocessing stretches every image to 672x960 and always gives it 280 soft tokens, so an image of any other shape reaches the model distorted. For eight test images of other shapes Hugging Face uses 256 to 270 tokens, not 280.

The existing comparison cannot see this, because generate_hf_golden_logits.py also forces 672x960 before it calls Hugging Face.

A row without an image fails in preprocessing, so one dataset cannot mix image rows with text-only rows, and with several image columns every row needs an image in each column.

What changes

The budget is Hugging Face's max_soft_tokens, read from vision_output_length (280 in the model files). Hugging Face accepts 70, 140, 280, 560 and 1120. Changing vision_output_length changes the resize, the per-image token cost and the shaped batch together.

Each image is padded to vision_output_length * 9 patches with pad positions -1, so batch shapes do not depend on the aspect ratio and the train step compiles once. Each image's placeholder run has its own length, for example 256 tokens for a square image.

A row without an image needs no new model code. Native-resolution preprocessing returns a valid output for zero images, and the row's image slots are filled with masked patches, like any unused slot.

Commits

  1. feat(multimodal): pass per-patch image positions through the input pipeline and inference: not Gemma-specific. PadOrTrimToMaxLength pads image_position_ids with the pad value, so unused image slots are masked, and charges every slot the full budget. ExtractImagesAndMasks emits image_position_ids. MaxEngine.prefill takes them, and decode.py, benchmarks/multimodal/multimodal_eval.py and benchmarks/api_server/maxtext_generator.py pass them. Models without positions are unchanged.
  2. feat(gemma4): native-resolution image preprocessing:
    • the flag, with a config check that it is used only with the Gemma-4 vision encoder; on in the E2B and E4B model files;
    • a port of Hugging Face's get_aspect_ratio_preserving_size;
    • preprocess_mm_data_gemma4_native: bicubic resize, patches, positions, padding to the budget;
    • placeholder expansion and token offsets per image;
    • the shaped batch for AOT and init;
    • --native-resolution in generate_hf_golden_logits.py, used by test_gemma4_multimodal.sh;
    • positions in forward_pass_logit_checker.py.
  3. feat(multimodal): allow rows without an image in image SFT datasets:
    • one helper returns the images of a row as a list without the missing ones; reformat_prompt, merge_image_columns and pre_process_image_sft use it. So a row can have no image, fewer images than image columns, or a list with a missing element;
    • the helper also takes a list column the way Grain reads it from parquet, as a numpy object array. Before, the Grain loader treated such a column as one image and failed;
    • the fixed-size Gemma-4 path cannot hold zero images, so it raises an error that names the flag.

Impact

  • gemma4-e2b, gemma4-e4b: image runs, which are new with Add image support for Gemma-4 E2B and E4B #6621, use native resolution by default. use_native_resolution_for_vit=false override_model_config=true gives the 672x960 path.
  • gemma4-26b, gemma4-31b: unchanged.
  • Image SFT datasets, every model: a missing image inside a list or in one of several image columns is skipped; before, it failed. A list-of-images column in parquet now also works with the Grain loader.
  • MaxEngine.prefill has a new optional argument, image_position_ids.

Limits

Every image costs the full budget in the batch shape, whatever its own size, so smaller images do not save compute. A row without an image also runs the vision tower over its padded slot.

Only Gemma-4 with native resolution accepts a row without an image. Other vision models still fail on one.

The flag is off for 26B and 31B. With the flag passed on the command line, 31B matches Hugging Face on CPU in float32 (max KL 1.9e-3 with the chat-template prompt, 8.7e-3 with the prompt of 31b/convert_gemma4.sh).

No docs page is updated here: docs/tutorials/posttraining/multimodal.md lists only Gemma-4 26B / 31B today.

Tests

Unit tests, in tests/unit/multimodal_utils_test.py, tests/unit/input_pipeline_utils_test.py and tests/unit/maxengine_nnx_test.py:

  • Preprocessing against Hugging Face's Gemma4ImageProcessorPil: pixels within 1e-6, identical positions and token counts, for 4:1 and 9:16 images.
  • Positions through padding, extraction, the shaped batch, the API server, decode.py and the engine's prefill; rows without an image, a missing image in a list, a list column as Grain reads it.
  • Mutation check: 32 mistakes planted in the code of the three commits, one at a time. 31 make at least one test fail. The one that does not is multimodal_eval.py dropping the positions; that one-line change was made by reading.

To reproduce:

  • CPU: JAX_PLATFORMS=cpu python3 -m pytest tests/unit/multimodal_utils_test.py tests/unit/input_pipeline_utils_test.py tests/unit/maxengine_nnx_test.py
  • Hugging Face comparison, needs a chip and the E2B checkpoint: bash tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh

Run locally on the #6621 branch and on this branch. Nothing that passes on #6621 fails on this branch:

  • CPU, the 137 unit test files of Add image support for Gemma-4 E2B and E4B #6621's description, with jax 0.11.1, flax 0.12.12 and optax 0.2.8: 3353 passed on Add image support for Gemma-4 E2B and E4B #6621, 3379 on this branch.
  • The same CPU run with flax 0.12.8 and optax 0.2.6: 3274 and 3322 passed.
  • Preprocessing against the Hugging Face processor on nine images of different shapes, no model: pixels equal to its PIL backend, and identical positions and prompt tokens. Hugging Face's default torchvision backend differs from its own PIL backend by at most 0.008 per pixel.
  • Hugging Face comparison with real weights, float32, limit 0.03, the test image with "Describe this image". In each run MaxText's tokens and patch positions equal those of the Hugging Face processor.
Run Max KL
E2B on one v6e chip, budget 280 3.6e-4
E2B, flag off, against the 672x960 golden 4.3e-4, as in #6621
E4B on CPU, budget 280 1.0e-4
E2B, budget 70 / 140 / 560 / 1120 1.3e-4 / 1.7e-4 / 2.5e-4 / 1.3e-3
E2B, two images of different shapes plus an empty slot (square and 4:1; 9:16 and 16:9) 4.4e-3; 3.9e-3
E2B, an image at budget 70 inside a 280 slot; 140 inside 560 1.3e-4; 1.7e-4
  • decode.py on the chip describes the test image correctly.
  • SFT on the chip, converted E2B checkpoint: 6 steps through train_sft_native with checkpoints saved at steps 0 and 5, loss 0.47 to 0.64; 8 steps through train.py on real ChartQA rows, loss finite (3.7 to 15.8: the labels are one word and the base model answers at length).
  • Rows without an image:
    • the SFT pipeline on a dataset where every other row has no image, with the hf and the grain loader: a text-only row gets 0 image tokens and 0 valid patches, and its tokens equal the output of the Hugging Face chat template;
    • real E2B weights on CPU in float32, vision tower not frozen: a text-only row has the same loss with its padded image slot as with no image inputs at all (2.7131488 both), and its gradient for the vision tower is exactly 0; a batch of one image row and one text-only row has a finite loss (0.8168) and finite gradients, with a non-zero tower gradient;
    • SFT through train.py on the chip: 6 steps on batches of one image row and one text-only row, loss 0.71 to 0.92.
  • A list-of-images column in parquet (2 images, 1 image) and a bare image column, native and fixed size, through the trainer's data loader: all six cases load with Grain, and each Grain batch equals the Hugging Face loader's batch exactly.
  • pyink 24.10.1 and pylint with the repository settings: nothing new.

In the parallel CPU runs, 3 tests failed on this branch and not on #6621: 2 compile tests that collide on a libtpu lock file under parallel workers, and the new API-server test, because that run did not mount benchmarks/. Run alone, with benchmarks/ mounted, all 3 pass.

Not run: multimodal_eval.py and the API server against a real model.

Checklist

Before submitting this PR, please make sure (put X in square brackets):

  • I have performed a self-review of my code. For an optional AI review, add the gemini-review label.
  • I have necessary comments in my code, particularly in hard-to-understand areas.
  • I have run end-to-end tests and provided workload links above if applicable. (Note: New PRs get skip-ci-tests so only CPU/lint/docs checks run during review; a bot removes it after 2 approvals on a 1-commit PR to run TPU/GPU suites, or remove it yourself / ask a maintainer on fork PRs to run them sooner. On TPU7X, only the TPU tests that the PR adds or modifies run; add the run-tpu7x label to run the full TPU7X suite.)
  • I have made or will make corresponding changes to the doc if needed, including adding new documentation pages to the relevant Table of Contents (toctree directive) as explained in our documentation.

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enables native-resolution image preprocessing for Gemma-4 models, aligning MaxText's vision pipeline with Hugging Face's implementation. It introduces critical infrastructure for handling vision encoder activation clipping, adds support for padded-patch masking to maintain fixed batch shapes, and implements robust validation for model contracts. These changes are gated behind new configuration flags, ensuring existing models remain unaffected while providing a path for Gemma-4 E2B/E4B parity.

Highlights

  • Native-Resolution Image Preprocessing: Implemented native-resolution image preprocessing for Gemma-4, allowing images to maintain their aspect ratio and be resized to a soft token budget instead of being stretched to a fixed resolution.
  • Clipped-Linears for Vision Encoder: Added support for per-projection activation clip bounds in the Gemma-4 vision encoder, ensuring parity with HF implementations and preventing activation drift.
  • Untrainable Parameters: Introduced UntrainableParam to handle non-trainable checkpoint-resident scalars, ensuring they are preserved during training without being updated by the optimizer.
  • Input Pipeline Improvements: Updated the input pipeline to support per-patch position threading and masking for padded patches, enabling consistent batch shapes for compilation.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@csgoogle csgoogle left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review of #6262 (native-resolution preprocessing + bundled #4790 / lokic233#2–#4 changes) — the native-resolution resizing, patchification, (x, y) position IDs, and fixed-shape padding match HF Gemma4ImageProcessorPil accurately. Blocking issues to fix before merge:

  1. Broken gemma4-e2b inference in multimodal_eval.py and maxtext_generator.py (crash):

    • Commit 273722e0801c enables use_native_resolution_for_vit: True by default in src/maxtext/configs/models/gemma4-e2b.yml.
    • Both benchmarks/multimodal/multimodal_eval.py:215, 256-269 and benchmarks/api_server/maxtext_generator.py:335-340, 508-517 preprocess images into 3D patch arrays (N, 2520, 768) + image_position_ids, then call engine.prefill(..., images=...) without image_position_ids.
    • In src/maxtext/inference/maxengine/maxengine.py:676-683, image_position_ids is None with images.ndim == 3 falls into the Gemma-3 single-image branch ((1, 1, N, 2520, 768)), entering Gemma4VisionEncoderLayer's legacy raw-image path and crashing in patchify.
    • Fix: Pass image_position_ids into engine.prefill(...) in both callers (and store it on GenerationStream in maxtext_generator.py).
  2. Single-column list datasets with None elements crash (src/maxtext/input_pipeline/input_pipeline_utils.py:117-121, 170-171, commit 458db3c08bbe):

    • merge_image_columns strips None entries, but it only runs when image_column is a list of multiple columns. For a single list-typed column containing [img1, None] or [None], reformat_prompt (L117–121) counts None in len(media) (inserting extra <|image|> placeholders) and pre_process_image_sft (L171) crashes in mm_utils.convert_to_RGB(None).
    • Fix: Filter None elements inside lists in both reformat_prompt and pre_process_image_sft.
  3. Breaking VisionEncoder.__call__ 3-tuple return breaks existing callers (src/maxtext/layers/encoders.py:140):

    • Changing VisionEncoder.__call__ to return 3 values causes a guaranteed ValueError: too many values to unpack in:
      • src/maxtext/integration/vllm/maxtext_vllm_adapter/multimodal.py:97
      • tests/unit/qwen3_omni_layers_test.py:854-858
    • Please update all remaining 2-tuple callers (or preserve the 2-tuple contract when image_position_ids is unused).
  4. New pure-JAX vision/contract tests are excluded from CI (tests/unit/gemma4_small_layers_test.py):

    • pytest.ini:18 ignores tests/unit/gemma4_small_layers_test.py (due to its torch import), so none of the new pure-JAX contract/clip-bound/std tests execute in CI. Please move the torch-free tests into tests/unit/gemma4_small_test.py.
  5. validate_all_vision_clip_bounds gaps (src/maxtext/utils/model_creation_utils.py:1551-1554, src/maxtext/models/gemma4_vision.py:119-155):

    • Only runs in from_pretrained (bypassed by train.py / setup_training_state and setup_decode_state), runs even when config.load_parameters_path is empty (breaking random-init from_pretrained on jnp.nan sentinels), and hardcodes 112 projections / 448 bounds instead of deriving from config.num_hidden_layers_for_vit.
  6. Conflicts, stack alignment & CI gates:

    • Currently CONFLICTING with main in tests/unit/multimodal_utils_test.py:19, does not include #6235 (will conflict on 6 files once #6235 squash-merges) or #4860, and inherits the nnx_wrappers.py / _leaf_path fixes needed in #6224.
    • Two PR checklist boxes are unchecked and skip-ci-tests is set (and commit 458db3c08bbe was pushed after the feature/gemma4-e2b-vision run), so full CI will need to run after rebasing.

— Review assisted by Jetski agent

@nuinashco-ks

Copy link
Copy Markdown
Author

The branch is rebuilt on today's main as three commits on top of #6621.

  1. multimodal_eval.py and maxtext_generator.py pass image_position_ids to engine.prefill, and GenerationStream stores them. Tests cover the API server, decode.py and the engine's prefill.
  2. A missing image inside a list is skipped in reformat_prompt, merge_image_columns and pre_process_image_sft, through one helper, with tests.
  3. Fixed in Add image support for Gemma-4 E2B and E4B #6621: the vLLM adapter and the Qwen3-Omni test unpack three values.
  4. Fixed in Add image support for Gemma-4 E2B and E4B #6621: the torch-free tests are in tests/unit/gemma4_small_test.py.
  5. Fixed in Add image support for Gemma-4 E2B and E4B #6621: the clip-bound check is a hook that runs after a load in from_pretrained and in setup_train_loop, only when weights were loaded, and has no hard-coded counts.
  6. No conflict with main now. The stack is Add UntrainableParam for weights that are never trained #6224, then Add image support for Gemma-4 E2B and E4B #6621, then this PR. Keep weight decay off frozen vision and audio encoders #6235 changes none of this stack's files, and the two heads merge without conflict.

@csgoogle csgoogle left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for fixing the multimodal_eval.py / maxtext_generator.py image_position_ids forwarding, unifying None handling for single-column/multi-column image lists, and rebasing cleanly onto #6621! Left 1 AOT-compilation blocker, 2 substantive edge cases, and 1 naming nit inline below.

Comment on lines +182 to +186
elif (patch_shape := mm_processor.get_dummy_patch_shape_for_init(config, batch_size)) is not None:
# Images given as patches, with an (x, y) position per patch.
shaped_batch["images"] = jax.ShapeDtypeStruct(patch_shape, jnp.float32, sharding=batch_sharding)
positions_shape = patch_shape[:-1] + (2,)
shaped_batch["image_position_ids"] = jax.ShapeDtypeStruct(positions_shape, jnp.int32, sharding=batch_sharding)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocker: shaped_batch["inputs"] uses global_batch_size = config.global_batch_size_to_load (L146), while batch_size here (L168) is config.micro_batch_size_to_train_on.

Because gemma4-e2b/gemma4-e4b default use_native_resolution_for_vit: True, native SFT (train.py / train_compile.py) AOT-compiles train_step against shaped_batch. Under gradient_accumulation_steps > 1, gradient_accumulation_loss_and_grad (gradient_accumulation.py:160-167) divides axis 0 of every batch leaf by gradient_accumulation_steps, which crashes AOT compile in merge_mm_embeddings (src/maxtext/multimodal/utils.py:173-180: ValueError: Batch dimension of token_masks must be a multiple of the text batch size), and even for even N mismatches the HF/Grain dataloader's global_batch_size_to_load (same mismatch under per_device_batch_size < 1.0). (test_shaped_batch_matches_the_pipeline missed this because it uses GA=1 and slices off axis 0 with shape[1:].)

Fix: Pass global_batch_size (matching shaped_batch["inputs"].shape[0], or batch_shape[:-1] under DiLoCo) to get_dummy_patch_shape_for_init(config, ...) and add a test asserting batch["images"].shape[0] == batch["inputs"].shape[0] and batch["image_position_ids"].shape[0] == batch["inputs"].shape[0] with gradient_accumulation_steps=2 and per_device_batch_size=0.5.

Comment on lines +8661 to +8664
if self.use_native_resolution_for_vit and self.vision_encoder_block != VisionEncoderBlockType.GEMMA4:
raise ValueError(
f"use_native_resolution_for_vit requires the Gemma-4 vision encoder, got {self.vision_encoder_block}."
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Two missing config guards for use_native_resolution_for_vit=True:

  1. vision_output_length defaults to -1 (L4917), so a custom config without it hits ZeroDivisionError in get_max_num_images (image_offset = 0). Please validate self.vision_output_length > 0.
  2. When max_target_length <= vision_output_length + 1 (e.g. <= 281 on default E2B/E4B), mm_utils.get_max_num_images returns 0, yielding 0-sized (B, 0, 2520, 768) tensors in get_dummy_patch_shape_for_init_gemma4 (processor_gemma4.py:285-292) and hitting jnp.clip(cumsum_mask - 1, 0, -1) in merge_mm_embeddings (utils.py:224). Please fail fast with a clear ValueError when max_num_images < 1.

Comment on lines +111 to +113
def _is_image_list(media):
"""True for a list of images. Grain reads a parquet list column as a numpy object array."""
return isinstance(media, list) or (isinstance(media, np.ndarray) and media.dtype == object)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

isinstance(media, np.ndarray) and media.dtype == object matches 0-d object arrays (e.g. np.array(None, dtype=object) or np.array(img, dtype=object)), which will crash _present_images on L122 with TypeError: iteration over a 0-d array. Please require media.ndim > 0 here and unwrap 0-d object arrays with media.item() before the None check.

return isinstance(media, list) or (isinstance(media, np.ndarray) and media.dtype == object)


def _present_images(media):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit: consider renaming _present_images -> _extract_image_list (or extract_image_list) for clarity.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-ci-tests Add this label to the PR to skip running CI tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants