Repository navigation
Add native-resolution image preprocessing for Gemma-4 - #6262
nuinashco-ks wants to merge 27 commits into
Conversation
…erequisite)
The Gemma-4 E2B/E4B reference checkpoint ships per-projection activation clip
bounds for the vision tower: each of the 7 vision projections
(self_attn.{q,k,v,o}_proj and mlp.{gate,up,down}_proj) in every encoder block
carries a scalar {input,output}_{min,max} (16 blocks x 7 x 4 = 448 bounds), and
the reference forward clamps each projection's input and output by those bounds.
MaxText does not model them today, so the values are silently dropped on
conversion. They are one of the pieces required before E2B/E4B image inputs can
match the reference.
This adds the clip bounds as an opt-in, checkpoint-resident, non-trainable
feature gated on use_clipped_linears_for_vit (exact no-op when False):
- gemma4_vision.py: clip-bound helpers (_clip_in/_clip_out, _ClipBounds,
NaN-sentinel validate_clip_bounds, path-based clip_optimizer_freeze_mask).
Gemma4Attention overrides its q/k/v/o projection methods to clamp-in ->
DenseGeneral -> clamp-out; Gemma4ClippedMlpBlock does the same for
gate/up/down. The shared attentions.Attention / linears.MlpBlock are untouched,
and the underlying DenseGeneral weights and checkpoint key paths are unchanged
(the bounds are separate scalar leaves).
- param_mapping.py: maps the 448 clip-bound scalars from the HF checkpoint when
the flag is set.
- types.py / base.yml: adds the use_clipped_linears_for_vit flag (default False).
The bounds are plain nnx.Param leaves so they round-trip through the
nnx->linen->orbax checkpoint path and map to the canonical params collection;
clip_optimizer_freeze_mask keeps them out of optimizer updates and weight decay
via a leaf-path mask. A NaN sentinel + validate_clip_bounds hard-fails on a
missing/non-finite bound rather than silently degrading to an identity clamp.
Scope / status (deliberately conservative):
- This does NOT unblock E2B/E4B multimodal. The existing validator that gates
E2B/E4B image inputs is left in place, because clip-bounds are necessary but
NOT sufficient for image parity on their own.
- Verified: the 448 bounds convert and load with real finite values; the clamp
math is bit-exact vs jnp.clip, dtype-preserving, and an exact no-op when
disabled (checked at the helper level and on a real Gemma4EncoderBlock forward,
where wide bounds reproduce the disabled-path output exactly and tight bounds
bound the projected activations).
- End-to-end teacher-forced image parity is NOT yet achieved: with clip-bounds
loaded, the text path is exact but the image span still diverges from the HF
reference, because the current Gemma-4 vision forward is missing other pieces
of the reference contract (e.g. pad-patch attention masking and external image
position threading). Those are out of scope for this change and tracked
separately; this PR lands the clip-bounds building block on its own.
…-row substitution) Builds on the vision clipped-linears to make Gemma-4 E2B/E4B image inputs match the HF reference end to end. The clipped-linears alone are necessary but not sufficient; the reference contract also needs the vision padded-patch handling and a decoder-side per-layer embedding (PLE) fix. Vision (models/gemma4_vision.py): - Gemma4EncoderBlock threads decoder_segment_ids into attention (valid=1 / pad=2) so the phantom padded patches are masked out of vision self-attention. - Gemma4VisionEncoderLayer gains a padded-patch path (image_position_ids != None): consume pre-patchified patches + real per-patch positions (-1 = pad), build the segment ids, pool by the real positions, and return the pooled-token validity mask. image_position_ids is None -> byte-identical legacy path. Threading (layers/encoders.py, models/models.py): - VisionEncoder / the model forward thread encoder_image_position_ids to the Gemma-4 vision encoder and route the returned validity mask into MultimodalInput.image_masks, so exactly the valid pooled tokens land in the image placeholders (merge_mm_embeddings.token_masks). Decoder (layers/nnx_decoders.py): - ple_pad_substitute_image_rows: Gemma-4 E2B/E4B build the per-layer inputs from llm_input_ids with image placeholder tokens mapped to pad_token_id (HF modeling_gemma4), rather than feeding the placeholder id into the PLE path. Without this the per-layer embeddings at the image positions diverge, corrupting the image-span and post-image logits. - use_bidirectional_image_attn: E2B/E4B image spans are causal; suppress the bidirectional attention carve-out unless explicitly enabled (bidirectional-image models set it True). Config (configs/types.py, configs/base.yml): - Adds use_bidirectional_image_attn, ple_pad_substitute_image_rows, ple_pad_mode, image_placeholder_token_id, ple_pad_token_id (defaults preserve behavior for other models). - Allows E2B/E4B multimodal when use_clipped_linears_for_vit is set. Validation (CPU, teacher-forced 340-token forward vs HF reference logits, converted E2B checkpoint): with the full fix and clip-bounds enabled, pre_image max_KL 2.7e-5, argmax 1.0 image_span max_KL 9.0e-5, argmax 1.0 post_image max_KL 4.3e-5, argmax 1.0 (frozen gate: <= 1.26e-3 and argmax >= 0.995) matching the reference. With clip-bounds disabled the image span diverges, confirming the clip-bounds are required. Defaults keep all changes off for non-Gemma-4 models.
So enabling image inputs only requires use_multimodal=true + use_clipped_linears_for_vit=true; the E2B/E4B model configs supply the decoder image-contract flags (causal image spans, PLE image-row pad substitution, placeholder/pad token ids). Also drops the stale 'multimodal not yet supported' comment.
…ut without image_position_ids The legacy all-valid path expects full images ([B,H,W,C]/[B,N,H,W,C]). Pre-patchified pixel_values require image_position_ids (the padded-patch path). Previously a 3D pre-patchified input with no positions would crash cryptically on shape-unpack; now it raises a clear contract error instead of silently mis-handling it.
…mizer freeze integration
3.1 _clip_in/_clip_out now read bounds through jax.lax.stop_gradient (defense in depth: clip-bound
gradients can never contaminate gradient statistics even if the freeze mask were misconfigured).
3.2 get_optimizer() now wires clip_optimizer_freeze_mask into optax.multi_transform when
use_clipped_linears_for_vit is set: the 448 clip bounds map to set_to_zero() so they receive no
updates, no weight decay, and no momentum/variance slots. Composes with trainable_parameters_mask
(a leaf is trainable only if trainable under the whitelist AND not a clip bound).
…closed) + fused_qkv guard
M4: validate_all_vision_clip_bounds(model) walks the model graph, validates every clip-state module
(finite, scalar, input_min<=input_max, output_min<=output_max) and asserts EXACTLY 112 modules /
448 scalar bounds. Wired into from_pretrained AFTER restore, BEFORE first JIT, gated on
use_clipped_linears_for_vit + use_multimodal. Exact-count check prevents a zero-module traversal
from silently passing. Also strengthened validate_clip_bounds with the min<=max ordering check.
M5: Gemma4Attention.enable_vision_clip_bounds now hard-fails on fused_qkv=True (distinct q/k/v clip
bounds require separate projections); fused_mlp=True guard already present in Gemma4ClippedMlpBlock.
…, all pass) CI-grade unit tests covering the merge-critical invariants: clip math bit-exact vs jnp.clip, dtype-preserving, exact no-op when disabled, stop_gradient => zero grad wrt bound, NaN/Inf/min>max hard-fail, freeze-mask polarity+count, expected 112/448 count constants, public symbols present. Runs on CPU in grr-maxtext:latest (13 passed).
M1: thread image_position_ids through the stock loss_fn (train.py) for both
Linen and NNX paths, guarded on presence in the batch (the stock fixed-grid
Gemma-4 processor does not emit it -> legacy all-valid path, correct for its
contract; native-resolution/pan-and-scan processors do -> Option-S path).
M2: make ple_pad_mode a validated enum (hard-fail unknown); 'identity' documented
as the HF-faithful default (matches Transformers 5.9.0 get_per_layer_inputs,
which ignores inputs_embeds when input_ids is given); wire 'both' as a real
(HF-divergent, ablation-only) mode by threading shared_embedding into the
Gemma-4-small PLE path -- removing the previously-dead hasattr(self,...) branch.
M6: Gemma-4 E2B/E4B multimodal static contract gate in config validation:
enum PLE mode, non-negative token ids (single source of truth), causal image
spans (use_bidirectional_image_attn=False), fused_qkv/fused_mlp=False.
Pure-Linen Gemma-4-small MM path now fail-closed (PLE substitution is NNX-only).
No behavior change for non-Gemma-4 models or text-only Gemma-4.
…n-finite pad from valid outputs)
…ard test Packed multimodal is unsupported by the stock data pipeline; packing image spans risks cross-doc image attention + PLE image-row substitution across segment boundaries. MaxText forbade this for multimodal SFT only; extend to every training mode. + in-tree packing-guard test.
…ers_test.py; optimizer clip-freeze comment; E2B multimodal e2e script Addresses hengtaoguo review on AI-Hypercomputer#4790: - move gemma4_clip_linears_test.py + gemma4_mm_contract_gate_test.py into tests/unit/gemma4_small_layers_test.py (26 methods; fixes a stray mid-file main-guard that shadowed OptionSInvariantsTest; fixes unused-var + adds docstring) - optimizers.py: one-line callout for the Gemma4-small ViT clip-bound freeze - add tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh (image e2e on the NNX path)
trainable_parameters_mask is a whitelist of parameters to train. The mask was built with _get_path_mask_fn(..., match_returns_true=False), which is True for leaves that do NOT match the whitelist (freeze polarity), but the clip-bound composition in _partition() reads it as a trainable mask. As a result every whitelisted leaf was routed to set_to_zero() and every other leaf was trained, including when use_clipped_linears_for_vit is False. Build the mask with match_returns_true=True so it is True for whitelisted leaves, and AND it with the clip-bound mask as intended. With use_clipped_linears_for_vit=False the labels are again identical to the whitelist-only multi_transform used before the clip-bound freeze was added; with neither option set the base optimizer is still returned unwrapped. Add tests that run jitted AdamW steps (weight decay > 0) through get_optimizer and check which parameters change and which own AdamW moment slots: whitelisted leaves update and get slots, all other leaves and every Gemma-4 ViT clip bound (even when matched by the whitelist) keep their values and only hold optax.MaskedNode slots.
Comment and docstring cleanups only; no code or behavior change. - gemma4_vision.py: drop the attribution suffix from the clipped-linears section header, and drop the quoted measurement from the clamp rationale (it referenced a harness that is not part of the repo). - nnx_decoders.py: drop a reference to a planning document that is not part of the repo from the ple_pad_mode comment. - test_gemma4_multimodal.sh: describe the KL gate without quoting an observed value. - gemma4_small_layers_test.py: drop a planning label from a test class docstring.
Comment-only change; no code or behavior change. - gemma4_vision.py: reword the comment above the padded-patch zeroing so it states the design rationale (segment masking plus position-aware pooling keep finite pad content out of the valid outputs; zeroing pad rows also covers non-finite pad) instead of citing an out-of-tree measurement that no test in this change reproduces. - test_gemma4_multimodal.sh: state that the KL threshold is the same one the Gemma-4 convert_gemma4.sh scripts use, rather than calling it a repo default.
…peline and inference
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
Description
Adds native-resolution image preprocessing for Gemma-4, like the HF 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.ymlturns on. E4B, 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.
Depends on #4790 (Gemma-4 E2B vision), which is not in
mainyet. The branch is built on #4790 plus our three draft PRs into it: lokic233#2 merges currentmainin, lokic233#3 has two review fixes, and lokic233#4 makes the fixed HF buffersUntrainableParam(with #6224's commits). Until those land, this diff includes them; the three commits of this PR on their own: compare.Why
With #4790, the Gemma-4 vision encoder already takes patches with per-patch
(x, y)positions and masks pad patches, as HF does, but nothing in MaxText produced those positions. Preprocessing still stretched every image to 672x960 and always gave it 280 soft tokens.So any image that is not exactly 672x960 reached the model distorted. On six test images, the vision features' cosine similarity to HF's was 0.918 to 0.997, and 1.000 only for a 672x960 control. HF would use 256 to 270 tokens for these images, not 280.
The existing parity test could not see this, because
generate_hf_golden_logits.pyalso forced 672x960 before calling HF.A row with a missing image crashed preprocessing (
convert_to_RGB(None)), for every model. So one dataset could not mix image rows with text-only rows, and with several image columns every row needed an image in each column.What changes
The budget is HF's
max_soft_tokens, read fromvision_output_length(280 for E2B). HF 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 don't 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 already 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, andMaxEngine.prefillanddecode.pypass them to the encoder. 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:merge_image_columnsdrops missing images, so a row can have fewer images than image columns;pre_process_image_sftpasses a row without an image on as an empty image list;reformat_promptalready adds no image placeholder for such a row;Limits
Every image costs the full budget in the batch shape, whatever its own size, so smaller images don't save compute. A row without an image also runs the vision tower over its padded slot, so it saves no compute against an image row.
Only Gemma-4 with native resolution accepts a row without an image. Other vision models still fail on one.
Only E2B is checked against HF here, so only
gemma4-e2b.ymlturns the flag on. The flag itself works for any Gemma-4 vision encoder.No docs page is updated here:
docs/tutorials/posttraining/multimodal.mdlists only Gemma-4 26B/31B today. A docs update for E2B images and this flag will follow once #4790 lands.Tests
Gemma4ImageProcessorPil, in a unit test: pixels within 1e-6, and identical positions and token counts, for 4:1 and 9:16 images. HF's default torchvision backend differs from its own PIL backend by a mean of about 2e-5 per pixel.multimodal_utils_test.pyandinput_pipeline_utils_test.py. Mutation check: 25 bugs planted in the new code, one at a time, each made at least one test fail.main's dependency versions (jax 0.11.1, flax 0.12.12, optax 0.2.8) and with jax 0.11.0, flax 0.12.8, optax 0.2.6: no new failures. The 21 failures also happen without these commits; they need GCS test data.forward_pass_logit_checker.pywith threshold 0.03: max KL 3.6e-4 at budget 280; 1.4e-4 at 70; 1.7e-4 at 140; 2.5e-4 at 560; 1.3e-3 at 1120.decode.pyon TPU describes the test image correctly.train.pyon TPU: 6 steps with checkpoints, and 8 steps on real ChartQA rows.multimodal_utils_test.py; each of the commit's three source changes, reverted on its own, makes at least one of them fail;hfand thegrainloader: a text-only row gets 0 image tokens and 0 valid patches, and its tokens equal the output of the HF chat template;train.pyon TPU: 6 steps on batches of one image row and one text-only row, loss 0.71 to 0.92.decode.pyand the two SFT runs without text-only rows ran on our fork branchfeature/gemma4-e2b-vision, which carried cherry-picks of the first two commits; the rest ran on this branch.To reproduce:
JAX_PLATFORMS=cpu python3 -m pytest tests/unit/multimodal_utils_test.py tests/unit/input_pipeline_utils_test.pytests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh.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.)