Skip to content

Add image support for Gemma-4 E2B and E4B - #6621

Open
nuinashco-ks wants to merge 7 commits into
AI-Hypercomputer:mainfrom
KyivstarDMP:pr/gemma4-e2b-image-parity
Open

nuinashco-ks wants to merge 7 commits into
AI-Hypercomputer:mainfrom
KyivstarDMP:pr/gemma4-e2b-image-parity

Conversation

@nuinashco-ks

Copy link
Copy Markdown

Description

gemma4-e2b and gemma4-e4b now accept use_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

E2B / E4B 26B / 31B
Vision projections The checkpoint stores an input and an output clamp range for each of the 7 projections (q, k, v, o, gate, up, down) of every vision block, 448 scalars in total, and Hugging Face clamps with them No clamp ranges
Image tokens in the decoder Attend causally, like text Attend in both directions
Per-layer embedding (PLE) Present; image placeholder rows look up the pad token No PLE
std_scale / std_bias of the vision tower Not in the checkpoint In the checkpoint

Change

Vision tower (gemma4_vision.py):

  • Clip bounds. Gemma4Attention and the new Gemma4ClippedMlpBlock clamp the input and the output of every projection with bounds read from the checkpoint. The bounds are UntrainableParam, so they are saved and loaded like weights but get no gradient, no optimizer state and no weight decay. use_clipped_linears_for_vit turns this on; it is set in the two model files.
  • Padded patches. Gemma4VisionEncoderLayer also 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 on main produces 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_bias and std_scale are UntrainableParam for every Gemma-4 size.

Around it:

  • VisionEncoder.__call__ returns the mask as a third value, None for every other encoder. Transformer passes encoder_image_position_ids down and uses the returned mask. loss_fn passes positions only when the batch has them. The two other callers, the vLLM adapter and a Qwen3-Omni test, unpack three values.
  • Decoder (_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.
  • Config: use_clipped_linears_for_vit and 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 in types.py with their values in gemma4-e2b.yml and gemma4-e4b.yml. base.yml is not changed. The validator replaces "multimodal is not supported" with checks of these settings.
  • Loading: a new model_creation_utils.validate_loaded_weights(model) calls validate_loaded_weights() on every submodule that defines it and puts the module path in front of an error. It runs in from_pretrained after weights were loaded and in setup_train_loop when the state was restored, so it covers train.py as 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.
  • Conversion: the E2B / E4B mapping covers the clip bounds, the shape map used by to_huggingface covers the vision tower, and std_scale / std_bias are 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 with use_multimodal=true.
  • gemma4-26b, gemma4-31b: std_bias and std_scale are no longer trained when the vision tower is unfrozen. They are fixed values in the Hugging Face checkpoint.
  • Every model: after a checkpoint is loaded, modules that define validate_loaded_weights() are checked. Only the clip bounds define it today.
  • Code that calls VisionEncoder directly gets three values back.

Review comments on #4790 and #4860

Comment In this PR
Document how E2B / E4B differ from 26B / 31B The table above
Why the encoder needs positions and returns a mask "Padded patches" above: the positions say which patches are padding, the mask says which image tokens are real
The changed return value of VisionEncoder; two callers still unpacked two values Three values are kept; the vLLM adapter and the Qwen3-Omni test are updated
Are all the flags needed; why image_placeholder_token_id is a config field They are kept, but only in the two model files and types.py, like the per-layer embedding settings of Qwen3.8. base.yml is untouched
packing: false changes text-only runs Removed; packing stays on for text-only runs, with a test
Use config.x, not getattr(config, ...) Done in all new code
Clip-bound validation was never called; train.py bypasses from_pretrained; the check ran without a checkpoint; 112 and 448 were hard-coded The validate_loaded_weights hook: both load paths, only after a load, no counts
The freeze mask was not wired in; the mask in optimizers.py was inverted The bounds are UntrainableParam; this PR does not change optimizers.py
Guard for fused_qkv In the model and in the config validator
NaN gradients for NaN content in padded patches Padded patches are zeroed before the input projection, with a test
The E2E script must pass use_clipped_linears_for_vit=true The flag is set in the model files
New tests sat in a file that CI skips They are in tests/unit/gemma4_small_test.py, which CI runs
The Linen decoder path It no longer exists on main
#4860: shape tests only checked that keys exist, on equal dimensions Exact expected shapes on a config whose sizes all differ, and coverage on the real E2B and E4B configs
#4860: std_scale / std_bias export relied on write order Not exported; tests and a real export below

Tests

Unit tests:

  • tests/unit/gemma4_small_test.py, 22 new: the clamp, the bounds and std_* 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, and tests/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.
  • Mutation check: each of these mistakes, planted one at a time, makes at least one test fail: padded patches not zeroed before the projection, positions passed to every model, the hook never called, the hook always called, the std fix reverted, one shape transposed, one projection without bound shapes.

To reproduce:

  • CPU: 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.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 #6224 branch and on this branch. Nothing that passes on #6224 fails on this branch:

  • CPU, the 137 unit test files that touch the changed modules (136 of them exist on Add UntrainableParam for weights that are never trained #6224), with jax 0.11.1, flax 0.12.12 and optax 0.2.8: 3290 passed on Add UntrainableParam for weights that are never trained #6224, 3339 on this branch.
  • The same CPU run with flax 0.12.8 and optax 0.2.6: 3265 and 3295 passed.
  • Hugging Face comparison, the test image with the prompt "Describe this image", float32, against the limit of 0.03 that the Gemma-4 scripts use: E2B on one v6e chip, max KL 4.3e-4; E4B on CPU, max KL 1.2e-4. Each model was converted from its Hugging Face checkpoint with use_multimodal=true.
  • The same comparison for E2B with one piece switched off, to show that it can fail:
Run Max KL Result
This PR 4.3e-4 pass
Clamps off 12.99 fail
ple_pad_substitute_image_rows=false 23.68 fail
ple_pad_mode=both 15.81 fail
  • Real train.py run on one v6e chip: the converted E2B checkpoint, 6 steps of image SFT, AdamW with adam_weight_decay=2.0, learning_rate=0.01 and trainable_parameters_mask=['vision_encoder'], which is all that fits one chip and makes weight decay move every weight it is allowed to. validate_loaded_weights ran after the restore and checked 112 modules. Comparing the checkpoint before and after: 0 of 448 clip bounds changed, 0 of 2 std_*, 0 of 35 layer_scalar; all 210 regular weights of the vision tower and the projector changed. The loss stayed finite.
  • Export of the converted E2B checkpoint with 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 into Gemma4ForConditionalGeneration with 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.
  • The images path of the vision tower gives bit-identical output before and after the padded-patch change, for the E2B and the 26B configuration.
  • TPU-only tests in 18 of those files, on one v6e chip: 99 passed on Add UntrainableParam for weights that are never trained #6224 and on this branch.
  • pyink 24.10.1 and pylint with 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):

  • 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.

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.

2 participants