Repository navigation
Add native-resolution image preprocessing for Gemma-4 - #6262
nuinashco-ks wants to merge 10 commits into
Conversation
Summary of ChangesHello, 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
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 AssistThe 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
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 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
|
csgoogle
left a comment
There was a problem hiding this comment.
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:
-
Broken
gemma4-e2binference inmultimodal_eval.pyandmaxtext_generator.py(crash):- Commit
273722e0801cenablesuse_native_resolution_for_vit: Trueby default insrc/maxtext/configs/models/gemma4-e2b.yml. - Both
benchmarks/multimodal/multimodal_eval.py:215, 256-269andbenchmarks/api_server/maxtext_generator.py:335-340, 508-517preprocess images into 3D patch arrays(N, 2520, 768)+image_position_ids, then callengine.prefill(..., images=...)withoutimage_position_ids. - In
src/maxtext/inference/maxengine/maxengine.py:676-683,image_position_ids is Nonewithimages.ndim == 3falls into the Gemma-3 single-image branch ((1, 1, N, 2520, 768)), enteringGemma4VisionEncoderLayer's legacy raw-image path and crashing inpatchify. - Fix: Pass
image_position_idsintoengine.prefill(...)in both callers (and store it onGenerationStreaminmaxtext_generator.py).
- Commit
-
Single-column list datasets with
Noneelements crash (src/maxtext/input_pipeline/input_pipeline_utils.py:117-121, 170-171, commit458db3c08bbe):merge_image_columnsstripsNoneentries, but it only runs whenimage_columnis a list of multiple columns. For a single list-typed column containing[img1, None]or[None],reformat_prompt(L117–121) countsNoneinlen(media)(inserting extra<|image|>placeholders) andpre_process_image_sft(L171) crashes inmm_utils.convert_to_RGB(None).- Fix: Filter
Noneelements inside lists in bothreformat_promptandpre_process_image_sft.
-
Breaking
VisionEncoder.__call__3-tuple return breaks existing callers (src/maxtext/layers/encoders.py:140):- Changing
VisionEncoder.__call__to return 3 values causes a guaranteedValueError: too many values to unpackin:src/maxtext/integration/vllm/maxtext_vllm_adapter/multimodal.py:97tests/unit/qwen3_omni_layers_test.py:854-858
- Please update all remaining 2-tuple callers (or preserve the 2-tuple contract when
image_position_idsis unused).
- Changing
-
New pure-JAX vision/contract tests are excluded from CI (
tests/unit/gemma4_small_layers_test.py):pytest.ini:18ignorestests/unit/gemma4_small_layers_test.py(due to itstorchimport), so none of the new pure-JAX contract/clip-bound/std tests execute in CI. Please move the torch-free tests intotests/unit/gemma4_small_test.py.
-
validate_all_vision_clip_boundsgaps (src/maxtext/utils/model_creation_utils.py:1551-1554,src/maxtext/models/gemma4_vision.py:119-155):- Only runs in
from_pretrained(bypassed bytrain.py/setup_training_stateandsetup_decode_state), runs even whenconfig.load_parameters_pathis empty (breaking random-initfrom_pretrainedonjnp.nansentinels), and hardcodes112projections /448bounds instead of deriving fromconfig.num_hidden_layers_for_vit.
- Only runs in
-
Conflicts, stack alignment & CI gates:
- Currently
CONFLICTINGwithmainintests/unit/multimodal_utils_test.py:19, does not include#6235(will conflict on 6 files once#6235squash-merges) or#4860, and inherits thennx_wrappers.py/_leaf_pathfixes needed in#6224. - Two PR checklist boxes are unchecked and
skip-ci-testsis set (and commit458db3c08bbewas pushed after thefeature/gemma4-e2b-visionrun), so full CI will need to run after rebasing.
- Currently
— Review assisted by Jetski agent
…ed patches, pad token in PLE) Co-authored-by: Loki Chen <dengcchi@meta.com>
…a 4 vision clip bounds)
Co-authored-by: Loki Chen <dengcchi@meta.com>
…peline and inference
458db3c to
3e66156
Compare
|
The branch is rebuilt on today's
|
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| 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}." | ||
| ) |
There was a problem hiding this comment.
Two missing config guards for use_native_resolution_for_vit=True:
vision_output_lengthdefaults to-1(L4917), so a custom config without it hitsZeroDivisionErroringet_max_num_images(image_offset = 0). Please validateself.vision_output_length > 0.- When
max_target_length <= vision_output_length + 1(e.g.<= 281on default E2B/E4B),mm_utils.get_max_num_imagesreturns0, yielding 0-sized(B, 0, 2520, 768)tensors inget_dummy_patch_shape_for_init_gemma4(processor_gemma4.py:285-292) and hittingjnp.clip(cumsum_mask - 1, 0, -1)inmerge_mm_embeddings(utils.py:224). Please fail fast with a clearValueErrorwhenmax_num_images < 1.
| 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) |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
Nit: consider renaming _present_images -> _extract_image_list (or extract_image_list) for clarity.
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_lengthsoft tokens, instead of being stretched to 672x960 (height x width). It is behind a new flag,use_native_resolution_for_vit, whichgemma4-e2b.ymlandgemma4-e4b.ymlturn 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.pyalso 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 fromvision_output_length(280 in the model files). Hugging Face accepts 70, 140, 280, 560 and 1120. Changingvision_output_lengthchanges the resize, the per-image token cost and the shaped batch together.Each image is padded to
vision_output_length * 9patches 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
feat(multimodal): pass per-patch image positions through the input pipeline and inference: not Gemma-specific.PadOrTrimToMaxLengthpadsimage_position_idswith the pad value, so unused image slots are masked, and charges every slot the full budget.ExtractImagesAndMasksemitsimage_position_ids.MaxEngine.prefilltakes them, anddecode.py,benchmarks/multimodal/multimodal_eval.pyandbenchmarks/api_server/maxtext_generator.pypass them. Models without positions are unchanged.feat(gemma4): native-resolution image preprocessing:get_aspect_ratio_preserving_size;preprocess_mm_data_gemma4_native: bicubic resize, patches, positions, padding to the budget;--native-resolutioningenerate_hf_golden_logits.py, used bytest_gemma4_multimodal.sh;forward_pass_logit_checker.py.feat(multimodal): allow rows without an image in image SFT datasets:reformat_prompt,merge_image_columnsandpre_process_image_sftuse it. So a row can have no image, fewer images than image columns, or a list with a missing element;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=truegives the 672x960 path.gemma4-26b,gemma4-31b: unchanged.MaxEngine.prefillhas 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.mdlists only Gemma-4 26B / 31B today.Tests
Unit tests, in
tests/unit/multimodal_utils_test.py,tests/unit/input_pipeline_utils_test.pyandtests/unit/maxengine_nnx_test.py:Gemma4ImageProcessorPil: pixels within 1e-6, identical positions and token counts, for 4:1 and 9:16 images.decode.pyand the engine's prefill; rows without an image, a missing image in a list, a list column as Grain reads it.multimodal_eval.pydropping the positions; that one-line change was made by reading.To reproduce:
JAX_PLATFORMS=cpu python3 -m pytest tests/unit/multimodal_utils_test.py tests/unit/input_pipeline_utils_test.py tests/unit/maxengine_nnx_test.pybash tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.shRun locally on the #6621 branch and on this branch. Nothing that passes on #6621 fails on this branch:
decode.pyon the chip describes the test image correctly.train_sft_nativewith checkpoints saved at steps 0 and 5, loss 0.47 to 0.64; 8 steps throughtrain.pyon real ChartQA rows, loss finite (3.7 to 15.8: the labels are one word and the base model answers at length).hfand thegrainloader: a text-only row gets 0 image tokens and 0 valid patches, and its tokens equal the output of the Hugging Face chat template;train.pyon the chip: 6 steps on batches of one image row and one text-only row, loss 0.71 to 0.92.pyink24.10.1 andpylintwith 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, withbenchmarks/mounted, all 3 pass.Not run:
multimodal_eval.pyand the API server against a real model.Checklist
Before submitting this PR, please make sure (put X in square brackets):
gemini-reviewlabel.skip-ci-testsso 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 therun-tpu7xlabel to run the full TPU7X suite.)