Repository navigation
Add image support for Gemma-4 E2B and E4B - #6621
nuinashco-ks wants to merge 7 commits into
Conversation
…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>
bdc3919 to
88288d1
Compare
There was a problem hiding this comment.
Thanks for consolidating #4790 + #4860 cleanly onto #6224 (preserving Co-authored-by: Loki Chen) and addressing the earlier VisionEncoder callers, NaN gradient guard, validate_loaded_weights hook, and HF export fixes! No correctness blockers found; left 4 inline items below.
| ple_context = y | ||
|
|
||
| # As in Hugging Face, image placeholder rows look up the pad token in the per-layer embedding. | ||
| if cfg.ple_pad_substitute_image_rows and multimodal_input is not None: |
There was a problem hiding this comment.
Guard with and multimodal_input.bidirectional_mask is not None: models.py:298-308 constructs MultimodalInput whenever any of image_embeddings, video_embeddings, or audio_embeddings is non-None (leaving bidirectional_mask=None when images aren't present, e.g. audio-only input on Gemma-4 E2B/E4B), which will crash jnp.where(is_image_row, ...) with TypeError.
| use_bidirectional_image_attn: bool = Field( | ||
| False, | ||
| description="Gemma 4 E2B/E4B decoder: image tokens attend in both directions. These models require False.", | ||
| ) | ||
| ple_pad_substitute_image_rows: bool = Field( | ||
| False, | ||
| description="Gemma 4 E2B/E4B: image placeholder rows look up ple_pad_token_id in the per-layer embedding.", | ||
| ) | ||
| ple_pad_mode: str = Field( | ||
| "identity", | ||
| description=( | ||
| "With ple_pad_substitute_image_rows: 'identity' replaces the token ids only, as Hugging Face does; " | ||
| "'both' also replaces the embeddings given to the per-layer embedder." | ||
| ), | ||
| ) |
There was a problem hiding this comment.
Following up on @gagika's #4790 comment on avoiding unnecessary config flags:
use_bidirectional_image_attnis only read in_apply_gemma4_small_layers, yetL8664-8665raisesValueErrorif it isTrueforgemma4-e2b/gemma4-e4b— so it can never legally beTrueanywhere in MaxText.ple_pad_mode="both"is a known-wrong ablation (Max KL15.81vs4.3e-4for"identity"), has no runtime test coverage, and callsshared_embedding(...)directly atnnx_decoders.py:3598instead ofself.embed_tokens(...)(bypassingprefetch_fsdp_weightsunderShardMode.EXPLICIT).
Recommend dropping use_bidirectional_image_attn and ple_pad_mode (along with the shared_embedding plumbing) and implementing the verified HF reference behavior directly.
| if was_restored: # pyrefly: ignore[unbound-name] | ||
| model_creation_utils.validate_loaded_weights(model) |
There was a problem hiding this comment.
This only runs in the else: (not config.enable_diloco) branch, so restoring under enable_diloco=True bypasses validate_loaded_weights(model). Can we run it on both branches when was_restored is True?
| def test_nan_in_a_padded_patch_keeps_gradients_finite(self): | ||
| config, encoder = _tiny_vision_encoder() | ||
| _set_clip_bounds(encoder, 1e4) | ||
|
|
||
| # Three real patches and one padded patch that holds NaN. | ||
| patch_dim = config.patch_size_for_vit**2 * config.num_channels_for_vit | ||
| patches = jnp.full((1, 4, patch_dim), 0.5).at[0, 3].set(jnp.nan) | ||
| positions = jnp.array([[[0, 0], [1, 0], [0, 1], [-1, -1]]]) | ||
|
|
||
| def loss_fn(model): | ||
| image_embeddings, _ = model(patches, deterministic=True, image_position_ids=positions) | ||
| return image_embeddings.sum() | ||
|
|
||
| loss, grads = nnx.value_and_grad(loss_fn)(encoder) | ||
| self.assertTrue(jnp.isfinite(loss)) | ||
| for path, grad in nnx.to_flat_state(grads): | ||
| self.assertTrue(jnp.isfinite(grad.get_value()).all(), f"non-finite gradient at {path}") | ||
|
|
There was a problem hiding this comment.
This currently discards the returned mask (image_embeddings, _ = ...) and only checks jnp.isfinite. To cover the actual padded-patch and clipping behavior in CI, could we also assert:
- Changing a padded patch's value leaves valid output token embeddings bit-identical (verifies
decoder_segment_idsisolation). - Returned
image_maskshas shape[B * N, K],jnp.int32dtype (required bymerge_mm_embeddings), and exact valid/pad values. - Active clamping with tight clip bounds (currently
±1e4never saturates).
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Description
gemma4-e2bandgemma4-e4bnow acceptuse_multimodal=true: images work and the logits match Hugging Face. Until now the config validator rejected multimodal for these two models. Their text-only runs are unchanged.This PR continues #4790 by lokic233: the same feature on today's
main, with the review comments addressed. It also includes #4860 (Hugging Face export of the vision tower) with its review comments addressed, so it replaces both. lokic233 is co-author of the commits.Stacked on #6224 (
UntrainableParam), which this PR uses for the weights that are never trained. Until #6224 lands, this diff includes its commits; this PR's own commits: compare.What E2B / E4B need that 26B / 31B do not
std_scale/std_biasof the vision towerChange
Vision tower (
gemma4_vision.py):Gemma4Attentionand the newGemma4ClippedMlpBlockclamp the input and the output of every projection with bounds read from the checkpoint. The bounds areUntrainableParam, so they are saved and loaded like weights but get no gradient, no optimizer state and no weight decay.use_clipped_linears_for_vitturns this on; it is set in the two model files.Gemma4VisionEncoderLayeralso accepts patches that are already cut, with an (x, y) position for each, where (-1, -1) marks a padded patch. Padded patches are zeroed, kept out of attention and ignored by pooling, and the encoder returns a mask of the image tokens that hold real patches. Nothing onmainproduces such input yet; Add native-resolution image preprocessing for Gemma-4 #6262 adds the preprocessing. Without positions the encoder takes images as before, and that path gives bit-identical output.std_biasandstd_scaleareUntrainableParamfor every Gemma-4 size.Around it:
VisionEncoder.__call__returns the mask as a third value,Nonefor every other encoder.Transformerpassesencoder_image_position_idsdown and uses the returned mask.loss_fnpasses positions only when the batch has them. The two other callers, the vLLM adapter and a Qwen3-Omni test, unpack three values._apply_gemma4_small_layers): image tokens are causal, and the per-layer embedding looks up the pad token on image placeholder rows, as Hugging Face does. The rows come from the image-token mask thatTransformeralready builds.use_clipped_linears_for_vitand the four decoder settings (use_bidirectional_image_attn,ple_pad_substitute_image_rows,ple_pad_mode,ple_pad_token_id) are fields intypes.pywith their values ingemma4-e2b.ymlandgemma4-e4b.yml.base.ymlis not changed. The validator replaces "multimodal is not supported" with checks of these settings.model_creation_utils.validate_loaded_weights(model)callsvalidate_loaded_weights()on every submodule that defines it and puts the module path in front of an error. It runs infrom_pretrainedafter weights were loaded and insetup_train_loopwhen the state was restored, so it coverstrain.pyas well. The clip bounds define it: every bound must be finite and no range empty, so a checkpoint without bounds fails at load and not as NaN in the first step.to_huggingfacecovers the vision tower, andstd_scale/std_biasare no longer written on export. Before, both were written to the key of the first block's layernorm weight, and the export was correct only because the real weight was written after them.Impact
gemma4-e2b,gemma4-e4b: text-only runs and conversions are unchanged. Images need a checkpoint converted withuse_multimodal=true.gemma4-26b,gemma4-31b:std_biasandstd_scaleare no longer trained when the vision tower is unfrozen. They are fixed values in the Hugging Face checkpoint.validate_loaded_weights()are checked. Only the clip bounds define it today.VisionEncoderdirectly gets three values back.Review comments on #4790 and #4860
VisionEncoder; two callers still unpacked two valuesimage_placeholder_token_idis a config fieldimage_placeholder_token_idis removed: the decoder uses the image-token mask. The other settings are kept, but only in the two model files andtypes.py, like the per-layer embedding settings of Qwen3.8.base.ymlis untouchedpacking: falsechanges text-only runsconfig.x, notgetattr(config, ...)train.pybypassesfrom_pretrained; the check ran without a checkpoint; 112 and 448 were hard-codedvalidate_loaded_weightshook: both load paths, only after a load, no countsoptimizers.pywas invertedUntrainableParam; this PR does not changeoptimizers.pyfused_qkvuse_clipped_linears_for_vit=truetests/unit/gemma4_small_test.py, which CI runsmainstd_scale/std_biasexport relied on write orderTests
Unit tests:
tests/unit/gemma4_small_test.py, 23 new: the clamp, the bounds andstd_*being untrainable, the config checks, text-only runs keeping packing, the pad token on image rows of the per-layer embedding, finite gradients with NaN in a padded patch, and the clip-bound validation alone and through the hook.tests/unit/model_creation_utils_test.py, 4 new, andtests/unit/train_utils_test.py, 2 new: the hook, and each of its two call sites being called after a load and not called without one.tests/unit/hf_shape_test.py, new file, 9 cases: the vision shapes, the real E2B and E4B configs, the std weights on export and on import.tests/unit/train_nnx_test.py, 1 new: positions in the batch reach the model.To reproduce:
JAX_PLATFORMS=cpu python3 -m pytest tests/unit/gemma4_small_test.py tests/unit/hf_shape_test.py tests/unit/model_creation_utils_test.py tests/unit/train_utils_test.py tests/unit/train_nnx_test.pybash tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.shRun locally on the #6224 branch and on this branch. Nothing that passes on #6224 fails on this branch:
use_multimodal=true.ple_pad_substitute_image_rows=falseple_pad_mode=bothtrain.pyrun on one v6e chip: the converted E2B checkpoint, 6 steps of image SFT, AdamW withadam_weight_decay=2.0,learning_rate=0.01andtrainable_parameters_mask=['vision_encoder'], which is all that fits one chip and makes weight decay move every weight it is allowed to.validate_loaded_weightsran after the restore and checked 112 modules. Comparing the checkpoint before and after: 0 of 448 clip bounds changed, 0 of 2std_*, 0 of 35layer_scalar; all 210 regular weights of the vision tower and the projector changed. The loss stayed finite.to_huggingface use_multimodal=true, compared with the original Hugging Face file: all 659 vision tensors (210 weights, 448 clip bounds, the projector) are identical, there are no std keys, and the first block's layernorm weight equals the original. The exported files load intoGemma4ForConditionalGenerationwith no missing or unused weights; on the same image and prompt the exported and the original model give the same most likely token at all 294 positions (max KL 2.8e-4) and the same 40 generated tokens.pyink24.10.1 andpylintwith the repository settings: nothing new.In the parallel CPU runs, 31 tests failed on this branch and not on #6224, 30 of them only with the older libraries: 30 compile tests that collide on a libtpu lock file under parallel workers, and 1 whose worker was killed for memory. Run alone, the 30 compile tests pass; the other one needs 4 devices and is skipped on a one-device machine.
Not run: the export for E4B (covered by unit tests on its real config), and the vLLM adapter, whose one-line change was made by reading.
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.)