Repository navigation
Add image support for Gemma-4 E2B and E4B - #6621
Open
nuinashco-ks wants to merge 7 commits into
Open
nuinashco-ks wants to merge 7 commits into
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>
nuinashco-ks
requested review from
A9isha,
NuojCheng,
RissyRan,
SurbhiJainUSC,
abhinavclemson,
aireenmei,
bvandermoon,
darisoy,
dipannita08,
gagika,
gobbleturk,
hengtaoguo,
igorts-git,
jiangjy1982,
khatwanimohit,
parambole,
shralex,
shuningjin and
xibinliu
as code owners
November 29, 2026 22:17
This was referenced Nov 29, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.use_clipped_linears_for_vitand the five decoder settings (use_bidirectional_image_attn,ple_pad_substitute_image_rows,ple_pad_mode,image_placeholder_token_id,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 fieldtypes.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, 22 new: the clamp, the bounds andstd_*being untrainable, the config checks, text-only runs keeping packing, 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, 19 tests failed on this branch and not on #6224: 16 compile tests that collide on a libtpu lock file under parallel workers, and 3 whose worker was killed for memory. Run alone, the 16 compile tests and 2 of the 3 pass; the third 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.)