From bb0c359975e8944c2da0c7ae38e47e11b014be59 Mon Sep 17 00:00:00 2001 From: dengcchi Date: Fri, 7 Aug 2026 20:07:24 -0700 Subject: [PATCH 01/26] Gemma-4 vision: add per-projection clipped-linears (E2B/E4B parity prerequisite) 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. --- .../utils/param_mapping.py | 21 +- src/maxtext/configs/base.yml | 6 + src/maxtext/configs/types.py | 9 + src/maxtext/models/gemma4_vision.py | 234 +++++++++++++++++- 4 files changed, 267 insertions(+), 3 deletions(-) diff --git a/src/maxtext/checkpoint_conversion/utils/param_mapping.py b/src/maxtext/checkpoint_conversion/utils/param_mapping.py index 94e96173f1..3ddac7fd6b 100644 --- a/src/maxtext/checkpoint_conversion/utils/param_mapping.py +++ b/src/maxtext/checkpoint_conversion/utils/param_mapping.py @@ -3123,7 +3123,9 @@ def GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(config, maxtext_config, scan_layers } ) - # TODO: gemma4-small multimodal not yet supported — vision-encoder mappings below are dead. + # Gemma-4 E2B/E4B vision-encoder param mapping. Active when use_multimodal is set; + # the clipped-linears activation clip bounds are additionally mapped when + # use_clipped_linears_for_vit is enabled (required for image parity on E2B/E4B). if maxtext_config.use_multimodal and vcfg: nvis = vcfg.get("num_hidden_layers", 0) mapping.update( @@ -3179,6 +3181,23 @@ def GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(config, maxtext_config, scan_layers f"{prefix}-mlp-wo-kernel": f"{hf_prefix}.mlp.down_proj.linear.weight", } ) + # Gemma-4 vision clipped-linears: per-projection activation clip bounds + # (scalar {input,output}_{min,max}) carried in the reference checkpoint. + # Only mapped when the clipped-linears path is enabled; the nnx leaves live + # at _clip.{input,output}_{min,max} under attention/mlp. + if getattr(maxtext_config, "use_clipped_linears_for_vit", False): + _clip_proj = { + "attention-q_clip": f"{hf_prefix}.self_attn.q_proj", + "attention-k_clip": f"{hf_prefix}.self_attn.k_proj", + "attention-v_clip": f"{hf_prefix}.self_attn.v_proj", + "attention-o_clip": f"{hf_prefix}.self_attn.o_proj", + "mlp-gate_clip": f"{hf_prefix}.mlp.gate_proj", + "mlp-up_clip": f"{hf_prefix}.mlp.up_proj", + "mlp-down_clip": f"{hf_prefix}.mlp.down_proj", + } + for mt_sub, hf_proj in _clip_proj.items(): + for bound in ("input_min", "input_max", "output_min", "output_max"): + mapping[f"{prefix}-{mt_sub}-{bound}"] = f"{hf_proj}.{bound}" return {k: v for k, v in mapping.items() if v is not None} diff --git a/src/maxtext/configs/base.yml b/src/maxtext/configs/base.yml index f3341ce211..cf359a8aef 100644 --- a/src/maxtext/configs/base.yml +++ b/src/maxtext/configs/base.yml @@ -1244,6 +1244,12 @@ freeze_vision_encoder_params: true freeze_audio_encoder_params: true dtype_mm: "float32" # Data type for multimodal model's vision encoder remat_policy_for_vit: "minimal" # Remat policy for multimodal model's vision encoder. Check `remat_policy` for options. +# Gemma-4 vision only: apply the per-projection activation clip bounds carried in the +# reference checkpoint (self_attn.{q,k,v,o}_proj and mlp.{gate,up,down}_proj each have +# scalar {input,output}_{min,max}). A prerequisite for Gemma-4 E2B/E4B image parity +# (necessary but not on its own sufficient); no-op for other vision encoders. Bounds are +# checkpoint-resident, non-trainable scalars. +use_clipped_linears_for_vit: false image_size_for_vit: 896 # Default for Gemma3, and should be overwritten by model's config image_path: "" # Local image path used for decoding, can be multiple paths separated by comma, exp "/path/image1.jpg,/path/image2.jpg" video_path: "" # Local video path used for decoding, can be multiple paths separated by comma, exp "/path/video1.mp4,/path/video2.mp4" diff --git a/src/maxtext/configs/types.py b/src/maxtext/configs/types.py index 2ec9de0028..d945b7bffe 100644 --- a/src/maxtext/configs/types.py +++ b/src/maxtext/configs/types.py @@ -2321,6 +2321,15 @@ class MultimodalGeneral(BaseModel): use_multimodal: bool = Field(False, description="Enable multimodal capabilities.") attention_for_vit: str = Field("dot_product", description="The attention algorithm to use for vision encoder.") + use_clipped_linears_for_vit: bool = Field( + False, + description=( + "Gemma-4 vision only: apply the per-projection activation clip bounds carried in the reference " + "checkpoint (self_attn.{q,k,v,o}_proj and mlp.{gate,up,down}_proj each have scalar " + "{input,output}_{min,max}). A prerequisite for Gemma-4 E2B/E4B image parity (necessary but not " + "on its own sufficient); no-op for other encoders." + ), + ) vision_encoder_block: VisionEncoderBlockType = Field( VisionEncoderBlockType.NONE, description="The style of VisionEncoderBlock to use (e.g., 'gemma3', 'llama4').", diff --git a/src/maxtext/models/gemma4_vision.py b/src/maxtext/models/gemma4_vision.py index 72cd841f81..d6fcbb5ad4 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -16,6 +16,8 @@ """Vision transformer implementation for Gemma4.""" from typing import cast +import functools +import operator import jax import jax.numpy as jnp from flax import linen as nn @@ -30,6 +32,108 @@ from maxtext.layers import normalizations +# ============================================================================= +# Gemma-4 vision clipped-linears (Navi upstream contribution) +# ----------------------------------------------------------------------------- +# The Gemma-4 E2B/E4B vision tower ships per-projection activation clip bounds in +# the reference (HF) checkpoint: for each of the 7 vision projections +# (self_attn.{q,k,v,o}_proj and mlp.{gate,up,down}_proj) in each of the 16 encoder +# blocks, a scalar {input_min,input_max,output_min,output_max} = 16*7*4 = 448 +# checkpoint tensors. The reference forward clamps each projection's input by +# [input_min,input_max] and its output by [output_min,output_max]. Omitting the +# clamps produces large activation drift in the image span (empirically KL 4-17 +# on a 340-token teacher-forced parity harness), because a handful of vision +# activations blow up without the trained saturation. Upstream MaxText marks +# E2B/E4B multimodal "not yet supported" and does not model these bounds. +# +# This module adds them as OPT-IN, checkpoint-resident, NON-TRAINABLE scalars, +# gated on ``config.use_clipped_linears_for_vit`` (exact no-op when False). +# Design: plain ``nnx.Param`` bounds (so they map to the canonical ``params`` +# collection and round-trip through the nnx->linen->orbax checkpoint path), plus +# a leaf-PATH optimizer-freeze mask so the 448 bounds are excluded from optimizer +# updates and weight decay without a custom nnx.Variable subclass (subclasses are +# renamed by the linen bridge and silently dropped from the saved checkpoint). +# A NaN sentinel + ``validate_clip_bounds`` hard-fails on a missing/non-finite +# bound rather than silently degrading to an identity clamp. + +# Leaf-name tokens that identify a clip-bound scalar in a flattened params tree. +_CLIP_LEAF_TOKENS = ("q_clip", "k_clip", "v_clip", "o_clip", "gate_clip", "up_clip", "down_clip") +_CLIP_BOUND_NAMES = ("input_min", "input_max", "output_min", "output_max") + + +def _mk_clip_bound(init_val=jnp.nan): + """A checkpoint-resident scalar clip bound as a plain ``nnx.Param`` (maps to the + canonical ``params`` collection; NaN sentinel marks an unloaded bound).""" + return nnx.Param(jnp.asarray(init_val, dtype=jnp.float32)) + + +def _is_clip_bound_path(path) -> bool: + """True iff a flattened-params key path addresses a clip-bound scalar.""" + s = "/".join(str(getattr(p, "key", p)) for p in path) if not isinstance(path, str) else path + return any(tok in s for tok in _CLIP_LEAF_TOKENS) and any(b in s for b in _CLIP_BOUND_NAMES) + + +def clip_optimizer_freeze_mask(params_tree): + """Bool pytree (same structure as ``params_tree``): True for TRAINABLE leaves, + False for the immutable clip bounds. Feed to ``optax.masked``/``multi_transform`` + so the bounds get ``set_to_zero()`` updates. Path-based, so it survives the + nnx->linen->orbax round-trip regardless of leaf type erasure.""" + flat = jax.tree_util.tree_flatten_with_path(params_tree)[0] + leaves_mask = [not _is_clip_bound_path(path) for path, _ in flat] + treedef = jax.tree_util.tree_structure(params_tree) + return jax.tree_util.tree_unflatten(treedef, leaves_mask) + + +def _clip_in(x, cb): + """clamp(x, input_min, input_max) in x's dtype; no-op if ``cb`` is None.""" + if cb is None: + return x + xd = x.dtype + return jnp.clip(x, cb.input_min.value.astype(xd), cb.input_max.value.astype(xd)) + + +def _clip_out(y, cb): + """clamp(y, output_min, output_max) in y's dtype; no-op if ``cb`` is None.""" + if cb is None: + return y + yd = y.dtype + return jnp.clip(y, cb.output_min.value.astype(yd), cb.output_max.value.astype(yd)) + + +class _ClipBounds(nnx.Module): + """Holds the four checkpoint-resident scalar clip bounds as ``nnx.Param`` leaves.""" + + def __init__(self): + self.input_min = _mk_clip_bound() + self.input_max = _mk_clip_bound() + self.output_min = _mk_clip_bound() + self.output_max = _mk_clip_bound() + + +def _make_clip_state(): + """Four NaN-sentinel scalar bounds (checkpoint-resident, non-trainable).""" + return _ClipBounds() + + +def validate_clip_bounds(cb, where=""): + """Hard-fail: every bound finite + scalar. Raises ValueError otherwise. No-op if ``cb`` is None.""" + if cb is None: + return + for nm in ("input_min", "input_max", "output_min", "output_max"): + v = getattr(cb, nm).value + if getattr(v, "shape", ()) not in ((), (1,)): + raise ValueError(f"Gemma4 vision clip bound '{nm}'{(' @ '+where) if where else ''} has non-scalar " + f"shape {v.shape}; expected scalar.") + fv = float(jnp.reshape(v, (-1,))[0]) + if not bool(jnp.isfinite(jnp.asarray(fv))): + raise ValueError(f"Gemma4 vision clip bound '{nm}'{(' @ '+where) if where else ''} = {fv} is non-finite " + f"(missing/NaN/Inf). use_clipped_linears_for_vit=True declares a FINITE clipped model; " + f"refusing to fall back to an identity clamp.") + + + + + def factorized_posemb(posemb: jax.Array, positions_xy: jax.Array, precision) -> jax.Array: """Computes factorized position embedding from (x, y) coordinates. @@ -409,7 +513,15 @@ def __call__(self, inputs: jax.Array, positions: jax.Array) -> jax.Array: class Gemma4Attention(attentions.Attention): - """Gemma 4 specific Attention module.""" + """Gemma 4 specific Attention module. + + When ``use_clipped_linears`` is enabled, the q/k/v/o projections apply the + per-projection activation clip bounds carried in the Gemma-4 vision checkpoint + (input clamp before the matmul, output clamp after). The clamps are wired by + overriding the base ``Attention`` projection methods, so the underlying + ``DenseGeneral`` weights and their checkpoint key paths are unchanged. When the + flag is off, every override is an exact delegate to the base implementation. + """ def init_rotary_embedding(self) -> Gemma4VisionRotaryEmbedding: """Initializes the rotary position embedding module for Gemma 4 vision.""" @@ -418,6 +530,116 @@ def init_rotary_embedding(self) -> Gemma4VisionRotaryEmbedding: rotary_fraction=None, # Or assume it from config if available ) + def enable_vision_clip_bounds(self): + """Attach the four checkpoint-resident clip-bound scalars for each of q/k/v/o. + + Called once by ``Gemma4EncoderBlock`` after construction when + ``config.use_clipped_linears_for_vit`` is set. Idempotent. + """ + if getattr(self, "_use_clipped_linears", False): + return + self._use_clipped_linears = True + self.q_clip = _make_clip_state() + self.k_clip = _make_clip_state() + self.v_clip = _make_clip_state() + self.o_clip = _make_clip_state() + + def validate_clip_bounds(self): + if not getattr(self, "_use_clipped_linears", False): + return + validate_clip_bounds(self.q_clip, "q_proj") + validate_clip_bounds(self.k_clip, "k_proj") + validate_clip_bounds(self.v_clip, "v_proj") + validate_clip_bounds(self.o_clip, "o_proj") + + # --- projection overrides: clamp(input) -> DenseGeneral -> clamp(output) --- + def query_projection(self, inputs_q, out_sharding=None): + if not getattr(self, "_use_clipped_linears", False): + return super().query_projection(inputs_q, out_sharding=out_sharding) + x = _clip_in(inputs_q, self.q_clip) + y = self.query(x, out_sharding=out_sharding) + return _clip_out(y, self.q_clip) + + def kv_projection(self, inputs_kv, proj_name, out_sharding=None): + if not getattr(self, "_use_clipped_linears", False): + return super().kv_projection(inputs_kv, proj_name=proj_name, out_sharding=out_sharding) + if proj_name == "key": + cb, module = self.k_clip, self.key + elif proj_name == "value": + cb, module = self.v_clip, self.value + else: + raise ValueError(f"proj_name must be 'key' or 'value', but got {proj_name}") + x = _clip_in(inputs_kv, cb) + y = module(x, out_sharding=out_sharding) + return _clip_out(y, cb) + + def out_projection(self, out, out_sharding=None): + if not getattr(self, "_use_clipped_linears", False): + return super().out_projection(out, out_sharding=out_sharding) + x = _clip_in(out, self.o_clip) + y = self.out(x, out_sharding=out_sharding) + return _clip_out(y, self.o_clip) + + +class Gemma4ClippedMlpBlock(linears.MlpBlock): + """MlpBlock that applies the Gemma-4 vision per-projection activation clip bounds + to the gate (wi_0), up (wi_1) and down (wo) projections. + + Only the non-fused activation path is supported (E2B/E4B use + ``activations=("gelu", "linear")`` with ``fused_mlp=False``), because gate and up + carry distinct clip bounds. When ``use_clipped_linears`` is off, this delegates to + the base ``MlpBlock`` unchanged. + """ + + def __init__(self, *args, use_clipped_linears=False, **kwargs): + super().__init__(*args, **kwargs) + self._use_clipped_linears = bool(use_clipped_linears) + if self._use_clipped_linears: + self.gate_clip = _make_clip_state() # wi_0 + self.up_clip = _make_clip_state() # wi_1 + self.down_clip = _make_clip_state() # wo + + def validate_clip_bounds(self): + if not self._use_clipped_linears: + return + validate_clip_bounds(self.gate_clip, "gate_proj") + validate_clip_bounds(self.up_clip, "up_proj") + validate_clip_bounds(self.down_clip, "down_proj") + + def __call__(self, inputs, decode=False, deterministic=False, + intermediate_sharding=None, out_sharding=None): + if not self._use_clipped_linears: + return super().__call__(inputs, decode=decode, deterministic=deterministic, + intermediate_sharding=intermediate_sharding, out_sharding=out_sharding) + cfg = self.config + if getattr(cfg, "fused_mlp", False): + # Clipped vision MLP requires the unfused path so gate/up get their own output clamps. + raise ValueError("Gemma4ClippedMlpBlock requires fused_mlp=False (per-projection clip bounds).") + if self.mlp_layer_norm is not None: + inputs = self.mlp_layer_norm(inputs) + clips = [self.gate_clip, self.up_clip] # order matches activations ("gelu", "linear") == (gate, up) + activations = [] + for idx, act_fn in enumerate(self.activations): + dense_name = "wi" if len(self.activations) == 1 else f"wi_{idx}" + module = getattr(self, dense_name) + x = _clip_in(inputs, clips[idx]) + x = module(x, out_sharding=intermediate_sharding) + x = _clip_out(x, clips[idx]) + x = linears.checkpoint_name(x, "mlp" + dense_name) + if cfg.activations_in_float32: + x = x.astype(jnp.float32) + x = linears._convert_to_activation_function(act_fn)(x) + activations.append(x) + x = functools.reduce(operator.mul, activations).astype(self.dtype) + x = self.dropout(x, deterministic=deterministic) + x = self._maybe_shard_with_logical(x, self.intermediate_logical) + x = _clip_in(x, self.down_clip) + output = self.wo(x, out_sharding=out_sharding) + output = _clip_out(output, self.down_clip) + output = linears.checkpoint_name(output, "mlpwo") + return output + + class Gemma4EncoderBlock(nnx.Module): """Single transformer encoder block (MHSA + MLP).""" @@ -487,6 +709,11 @@ def __init__( is_vision=True, rngs=self.rngs, ) + # Opt-in Gemma-4 vision clipped-linears: attach the q/k/v/o checkpoint-resident + # clip bounds and route the projections through the clamp-in/clamp-out overrides. + self._use_clipped_linears = bool(getattr(config, "use_clipped_linears_for_vit", False)) + if self._use_clipped_linears: + self.attention.enable_vision_clip_bounds() self.pre_ffw_norm = normalizations.RMSNorm( num_features=config.hidden_size_for_vit, @@ -506,7 +733,9 @@ def __init__( rngs=self.rngs, ) - self.mlp = linears.MlpBlock( + mlp_cls = Gemma4ClippedMlpBlock if self._use_clipped_linears else linears.MlpBlock + mlp_kwargs = {"use_clipped_linears": True} if self._use_clipped_linears else {} + self.mlp = mlp_cls( config=config, mesh=mesh, in_features=config.hidden_size_for_vit, @@ -516,6 +745,7 @@ def __init__( weight_dtype=config.weight_dtype, intermediate_dropout_rate=config.dropout_rate, rngs=self.rngs, + **mlp_kwargs, ) def __call__(self, x: jax.Array, positions: jax.Array | None = None, deterministic: bool = False) -> jax.Array: From 7734eee7131690897561b3be8b25454c6c054dfd Mon Sep 17 00:00:00 2001 From: dengcchi Date: Sat, 8 Aug 2026 03:12:57 -0700 Subject: [PATCH 02/26] Gemma-4 E2B/E4B: close image parity (padded-patch masking + PLE image-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. --- src/maxtext/configs/base.yml | 6 ++ src/maxtext/configs/types.py | 42 +++++++++- src/maxtext/layers/encoders.py | 12 ++- src/maxtext/layers/nnx_decoders.py | 23 ++++- src/maxtext/models/gemma4_vision.py | 126 ++++++++++++++++++++++++---- src/maxtext/models/models.py | 22 +++-- 6 files changed, 198 insertions(+), 33 deletions(-) diff --git a/src/maxtext/configs/base.yml b/src/maxtext/configs/base.yml index cf359a8aef..69faac69d5 100644 --- a/src/maxtext/configs/base.yml +++ b/src/maxtext/configs/base.yml @@ -1250,6 +1250,12 @@ remat_policy_for_vit: "minimal" # Remat policy for multimodal model's vision en # (necessary but not on its own sufficient); no-op for other vision encoders. Bounds are # checkpoint-resident, non-trainable scalars. use_clipped_linears_for_vit: false +# Gemma-4 E2B/E4B decoder image-handling (defaults preserve behavior for other models): +use_bidirectional_image_attn: false # E2B/E4B image spans are causal +ple_pad_substitute_image_rows: false # substitute pad id for image rows in the per-layer-embedding path (HF gemma4) +ple_pad_mode: "identity" # 'identity' (token-id path) or 'both' (also context/embedding path) +image_placeholder_token_id: 258880 # GEMMA4_TOKEN_PLACEHOLDER +ple_pad_token_id: 0 # E2B text_config.pad_token_id image_size_for_vit: 896 # Default for Gemma3, and should be overwritten by model's config image_path: "" # Local image path used for decoding, can be multiple paths separated by comma, exp "/path/image1.jpg,/path/image2.jpg" video_path: "" # Local video path used for decoding, can be multiple paths separated by comma, exp "/path/video1.mp4,/path/video2.mp4" diff --git a/src/maxtext/configs/types.py b/src/maxtext/configs/types.py index d945b7bffe..0607419737 100644 --- a/src/maxtext/configs/types.py +++ b/src/maxtext/configs/types.py @@ -2330,6 +2330,34 @@ class MultimodalGeneral(BaseModel): "on its own sufficient); no-op for other encoders." ), ) + use_bidirectional_image_attn: bool = Field( + False, + description=( + "Whether image placeholder tokens attend bidirectionally in the text decoder. Gemma-4 E2B/E4B " + "use causal image spans (False); bidirectional-image models (Gemma-3, gemma4-26b/31b) use True." + ), + ) + ple_pad_substitute_image_rows: bool = Field( + False, + description=( + "Gemma-4 E2B/E4B per-layer-embedding (PLE) path: substitute ple_pad_token_id for image placeholder " + "rows before the per-layer embedder, matching HF modeling_gemma4 (llm_input_ids pad substitution). " + "Default False preserves the native PLE for other models." + ), + ) + ple_pad_mode: str = Field( + "identity", + description=( + "PLE pad-substitution scope when ple_pad_substitute_image_rows=True: 'identity' (token-id path only) " + "or 'both' (also substitute the pad embedding in the context path)." + ), + ) + image_placeholder_token_id: int = Field( + 258880, description="Gemma-4 image placeholder token id (GEMMA4_TOKEN_PLACEHOLDER)." + ) + ple_pad_token_id: int = Field( + 0, description="Pad token id used for PLE image-row substitution (Gemma-4 E2B text_config.pad_token_id=0)." + ) vision_encoder_block: VisionEncoderBlockType = Field( VisionEncoderBlockType.NONE, description="The style of VisionEncoderBlock to use (e.g., 'gemma3', 'llama4').", @@ -3994,16 +4022,22 @@ def calculate_global_batch_sizes(per_device_batch_size, expansion_factor, num_de f"{self.model_name} requires scan_layers=False (per-layer KV sharing is incompatible with nn.scan)." ) if self.use_multimodal: - # Gemma 4 small (E2B / E4B) only supports text for now; multimodal - # support is pending clipped-linears in the vision encoder. - if self.model_name in ("gemma4-e2b", "gemma4-e4b"): - raise ValueError(f"Multimodal is not yet supported for {self.model_name}; only text inputs are supported.") + # Gemma 4 small (E2B / E4B) multimodal requires the vision-encoder clipped-linears AND the + # padded-patch masking / position-threading path; gate on the clipped-linears flag. + if self.model_name in ("gemma4-e2b", "gemma4-e4b") and not self.use_clipped_linears_for_vit: + raise ValueError( + f"Multimodal for {self.model_name} requires use_clipped_linears_for_vit=True " + "(the vision encoder ships per-projection activation clip bounds; without them the " + "image span diverges). Set use_clipped_linears_for_vit=True to enable image inputs." + ) valid_mm_models = ( "gemma3-4b", "gemma3-12b", "gemma3-27b", "gemma4-26b", "gemma4-31b", + "gemma4-e2b", + "gemma4-e4b", "llama4-17b-16e", "llama4-17b-128e", "qwen3-omni-30b-a3b", diff --git a/src/maxtext/layers/encoders.py b/src/maxtext/layers/encoders.py index e5e32d044a..a5a0c38ff8 100644 --- a/src/maxtext/layers/encoders.py +++ b/src/maxtext/layers/encoders.py @@ -106,13 +106,21 @@ def _setup_vision_encoder_layers(self): return encoder_name, projector_name - def __call__(self, input_images, input_masks=None, video_grid_thw=None, deterministic=False): + def __call__(self, input_images, input_masks=None, video_grid_thw=None, deterministic=False, + image_position_ids=None): # vision encoder output, frozen params in many cases encoder = getattr(self, self.encoder_name) + vision_image_masks = None if self.vision_encoder_block.value.startswith("qwen3") and input_masks is not None: encoder_output = encoder( input_images, video_mask=input_masks, video_grid_thw=video_grid_thw, deterministic=deterministic ) + elif self.vision_encoder_block == VisionEncoderBlockType.GEMMA4 and image_position_ids is not None: + # Gemma-4 padded-patch path: pre-patchified patches + per-patch positions (-1 = pad). The + # encoder returns (embeddings, image_masks); the mask marks the valid pooled tokens. + encoder_output = encoder(input_images, deterministic=deterministic, image_position_ids=image_position_ids) + embeddings, vision_image_masks = encoder_output + encoder_output = embeddings else: encoder_output = encoder(input_images, deterministic=deterministic) deep_feats = None @@ -131,7 +139,7 @@ def __call__(self, input_images, input_masks=None, video_grid_thw=None, determin projector = getattr(self, self.projector_name) embeddings = projector(embeddings) - return embeddings, deep_feats + return embeddings, deep_feats, vision_image_masks class MultimodalMLPProjector(nnx.Module): diff --git a/src/maxtext/layers/nnx_decoders.py b/src/maxtext/layers/nnx_decoders.py index a545a80822..e95083f7e5 100644 --- a/src/maxtext/layers/nnx_decoders.py +++ b/src/maxtext/layers/nnx_decoders.py @@ -2258,10 +2258,31 @@ def _apply_gemma4_small_layers( """Apply Gemma 4 small (E2B/E4B) decoder layers (pure-NNX).""" cfg = self.config bidirectional_mask_value = multimodal_input.bidirectional_mask if multimodal_input is not None else None + # Gemma-4 E2B/E4B image spans are causal (text_config.use_bidirectional_attention is unset), unlike + # the bidirectional-image Gemma-3 / 26B / 31B models. Suppress the bidirectional attention carve-out + # unless explicitly enabled via config (gate on a flag, not the model name). + if not bool(getattr(cfg, "use_bidirectional_image_attn", False)): + bidirectional_mask_value = None per_layer_inputs = None if cfg.hidden_size_per_layer_input > 0 and cfg.vocab_size_per_layer_input > 0: - per_layer_inputs = self.per_layer_embedder(decoder_input_tokens, y) + ple_tokens = decoder_input_tokens + ple_context = y + # Gemma-4 E2B/E4B build the per-layer inputs from llm_input_ids with the image placeholder + # tokens mapped to pad_token_id (HF modeling_gemma4.py), rather than feeding the image + # placeholder id / merged image features into the PLE path. Without this substitution the + # per-layer embeddings at the image placeholder positions diverge from the reference, which + # corrupts the image-span and post-image logits. Gated on ple_pad_substitute_image_rows + # (default False preserves the native PLE for other models). + if bool(getattr(cfg, "ple_pad_substitute_image_rows", False)) and multimodal_input is not None: + _img_id = int(getattr(cfg, "image_placeholder_token_id", 258880)) + _pad_id = int(getattr(cfg, "ple_pad_token_id", 0)) + _img_row = decoder_input_tokens.astype(jnp.int32) == _img_id + ple_tokens = jnp.where(_img_row, _pad_id, decoder_input_tokens.astype(jnp.int32)) + if str(getattr(cfg, "ple_pad_mode", "identity")) == "both" and hasattr(self, "shared_embedding"): + _pad_vec = self.shared_embedding(jnp.full_like(decoder_input_tokens, _pad_id).astype(jnp.int32)) + ple_context = jnp.where(_img_row[..., None], _pad_vec, y) + per_layer_inputs = self.per_layer_embedder(ple_tokens, ple_context) layer_types = gemma4_small.build_layer_types(cfg.num_decoder_layers, cfg.model_name) num_kv_shared = cfg.num_kv_shared_layers diff --git a/src/maxtext/models/gemma4_vision.py b/src/maxtext/models/gemma4_vision.py index d6fcbb5ad4..60ab571f85 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -748,11 +748,29 @@ def __init__( **mlp_kwargs, ) - def __call__(self, x: jax.Array, positions: jax.Array | None = None, deterministic: bool = False) -> jax.Array: - """Applies the encoder block (MHSA + MLP) to the inputs.""" + def __call__( + self, + x: jax.Array, + positions: jax.Array | None = None, + deterministic: bool = False, + decoder_segment_ids: jax.Array | None = None, + ) -> jax.Array: + """Applies the encoder block (MHSA + MLP) to the inputs. + + When ``decoder_segment_ids`` is provided, patches carrying distinct segment + ids cannot attend to each other. This is used by the padded-patch path + (valid patches = segment 1, padded/sentinel patches = segment 2) so that the + phantom pad patches are masked out of vision self-attention. + """ x_normed = self.pre_attention_norm(x) - # Pass positions to attention for RoPE - x_attn, _ = self.attention(x_normed, x_normed, inputs_positions=positions, deterministic=deterministic) + # Pass positions to attention for RoPE (+ optional segment mask for padded patches). + x_attn, _ = self.attention( + x_normed, + x_normed, + inputs_positions=positions, + decoder_segment_ids=decoder_segment_ids, + deterministic=deterministic, + ) x_attn = self.post_attention_norm(x_attn) x_after_attn = x_attn + x @@ -803,34 +821,106 @@ def __init__(self, config: Config, mesh: Mesh, *, rngs: nnx.Rngs): nnx.initializers.ones(self.rngs.params(), (config.hidden_size_for_vit,), config.weight_dtype), sharding=(None,) ) - def __call__(self, inputs: jax.Array, deterministic: bool = False) -> jax.Array: - """Applies the vision encoder layer.""" + def __call__( + self, + inputs: jax.Array, + deterministic: bool = False, + image_position_ids: jax.Array | None = None, + ): + """Applies the vision encoder layer. + + Two contracts: + + (A) Legacy all-valid (``image_position_ids is None``): ``inputs`` are raw images + [B, N, H, W, C] (or [B, H, W, C]); patchify -> full unmasked attention -> pool by the + derived positions -> return embeddings only (4D array [B, N, K, D]). + + (B) Padded-patch dynamic-N (``image_position_ids is not None``): ``inputs`` are ALREADY + patchified pixel_values with shape [B, L, P*P*C] (or [B, N, L, P*P*C]) and + ``image_position_ids`` is [B, L, 2] (or [B, N, L, 2]) with -1 sentinel rows marking padded + patches. The pre-patchified patches + REAL positions are fed to VisionEntry, per-patch + ``decoder_segment_ids`` (valid=1, pad=2) mask the phantom pad patches out of self-attention, + pooling uses the real positions (``avg_pool_by_positions`` maps a -1 patch to a zero-weight + bucket), and the VisionExit validity mask is returned. Returns a 2-tuple + ``(embeddings[B, N, K, D], image_masks[B*N, K])`` where ``image_masks.sum()`` is the number + of valid pooled tokens, threaded to ``merge_mm_embeddings.token_masks`` so exactly the valid + pooled tokens land in the image placeholders. + """ + if image_position_ids is None: + # ---- Legacy path: raw images -> patchify -> full (unmasked) attention ---- + if inputs.ndim == 4: + inputs = jnp.expand_dims(inputs, 1) + b, n, h, w, c = inputs.shape + inputs_flat = jnp.reshape(inputs, (b * n, h, w, c)) + + x, positions_xy = self.vision_entry(inputs_flat) + + for i in range(self.config.num_hidden_layers_for_vit): + layer = getattr(self, f"layer_{i}") + x = layer(x, positions=positions_xy, deterministic=deterministic) + + vision_exit_results = self.vision_exit(x, positions_xy=positions_xy) + (embeddings, _) = vision_exit_results[0] + + embeddings = (embeddings - self.std_bias.value.astype(embeddings.dtype)) * self.std_scale.value.astype( + embeddings.dtype + ) + + # Unflatten batch and num_images + final_x = jnp.reshape(embeddings, (b, n, embeddings.shape[1], embeddings.shape[2])) + return final_x + + # ---- Padded-patch dynamic-N path: pre-patchified patches + sentinel positions ---- + # inputs: [B, L, P*P*C] pre-patchified pixel_values. Support an optional per-image N dim + # [B, N, L, F] -> flatten to [B*N, L, F] to match positions. if inputs.ndim == 4: - inputs = jnp.expand_dims(inputs, 1) - b, n, h, w, c = inputs.shape - inputs_flat = jnp.reshape(inputs, (b * n, h, w, c)) + b, n, l, f = inputs.shape + patches = jnp.reshape(inputs, (b * n, l, f)) + pos = jnp.reshape(image_position_ids, (b * n, l, 2)) + else: + assert inputs.ndim == 3, f"padded-patch path expects pre-patchified [B, L, F] patches, got {inputs.shape}" + b, l, f = inputs.shape + n = 1 + patches = inputs + pos = image_position_ids + if pos.ndim == 2: + pos = jnp.broadcast_to(pos, (b, l, 2)) - x, positions_xy = self.vision_entry(inputs_flat) + pos = pos.astype(jnp.int32) + + # VisionEntry consumes pre-patchified patches + REAL positions (incl -1 sentinels). + x, positions_xy = self.vision_entry(patches, positions_xy=pos) + + # Segment ids: valid patch (any coord != -1) -> 1, padded sentinel patch -> 2. Distinct segments + # cannot attend to each other, masking the phantom pad patches out of self-attention. + is_pad = (positions_xy == -1).all(axis=-1) # [B*N, L] + decoder_segment_ids = jnp.where(is_pad, 2, 1).astype(jnp.int32) for i in range(self.config.num_hidden_layers_for_vit): layer = getattr(self, f"layer_{i}") - x = layer(x, positions=positions_xy, deterministic=deterministic) + x = layer( + x, + positions=positions_xy, + deterministic=deterministic, + decoder_segment_ids=decoder_segment_ids, + ) + # Pool with REAL positions; avg_pool_by_positions returns (embeddings, validity_mask). vision_exit_results = self.vision_exit(x, positions_xy=positions_xy) - - # Return embeddings from VisionExit tuple - # vision_exit_results is a tuple of (embeddings, mask) tuples, one for each output length. - # We take the first result. - (embeddings, _) = vision_exit_results[0] + (embeddings, image_masks) = vision_exit_results[0] # embeddings [B*N, K, D], mask [B*N, K] embeddings = (embeddings - self.std_bias.value.astype(embeddings.dtype)) * self.std_scale.value.astype( embeddings.dtype ) - # Unflatten batch and num_images final_x = jnp.reshape(embeddings, (b, n, embeddings.shape[1], embeddings.shape[2])) + if image_masks is None: + image_masks = jnp.ones((b * n, embeddings.shape[1]), dtype=jnp.int32) + else: + # merge_mm_embeddings does argsort(-token_mask); use int32 so negation/sort is well-defined. + image_masks = image_masks.astype(jnp.int32) - return final_x + return final_x, image_masks class Gemma4VisionProjector(nnx.Module): diff --git a/src/maxtext/models/models.py b/src/maxtext/models/models.py index a70ad780a3..aab8f1bdab 100644 --- a/src/maxtext/models/models.py +++ b/src/maxtext/models/models.py @@ -129,6 +129,7 @@ def __call__( decoder_segment_ids=None, encoder_images: None | jnp.ndarray = None, encoder_image_masks: None | jnp.ndarray = None, + encoder_image_position_ids: None | jnp.ndarray = None, encoder_videos: None | jnp.ndarray = None, encoder_video_masks: None | jnp.ndarray = None, encoder_video_grid_thw: None | jnp.ndarray = None, @@ -164,17 +165,19 @@ def __call__( video_embeddings = None audio_embeddings = None deepstack_visual_embeds = None + vision_image_masks = None if getattr(self.config, "use_multimodal", False) and encoder_images is not None: - image_embeddings, deepstack_visual_embeds = self.vision_encoder( # pyrefly: ignore[not-callable] - input_images=encoder_images, deterministic=not enable_dropout + image_embeddings, deepstack_visual_embeds, vision_image_masks = self.vision_encoder( # pyrefly: ignore[not-callable] + input_images=encoder_images, deterministic=not enable_dropout, + image_position_ids=encoder_image_position_ids, ) bidirectional_mask_image = mm_processor.get_bidirectional_mask_vision( self.config, decoder_input_tokens, is_video=False ) if getattr(self.config, "use_multimodal", False) and encoder_videos is not None: - video_embeddings, deepstack_visual_embeds = self.vision_encoder( # pyrefly: ignore[not-callable] + video_embeddings, deepstack_visual_embeds, _ = self.vision_encoder( # pyrefly: ignore[not-callable] input_images=encoder_videos, input_masks=encoder_video_masks, video_grid_thw=encoder_video_grid_thw, @@ -197,7 +200,7 @@ def __call__( if image_embeddings is not None or video_embeddings is not None or audio_embeddings is not None: multimodal_input = MultimodalInput( image_embeddings=image_embeddings, - image_masks=encoder_image_masks, + image_masks=vision_image_masks if vision_image_masks is not None else encoder_image_masks, video_embeddings=video_embeddings, video_masks=encoder_video_masks, audio_embeddings=audio_embeddings, @@ -449,6 +452,7 @@ def __call__( cache=None, encoder_images: jax.Array | None = None, encoder_image_masks: jax.Array | None = None, + encoder_image_position_ids: jax.Array | None = None, encoder_videos: jax.Array | None = None, encoder_video_masks: jax.Array | None = None, encoder_video_grid_thw: jax.Array | None = None, @@ -499,16 +503,18 @@ def __call__( video_embeddings = None audio_embeddings = None deepstack_visual_embeds = None + vision_image_masks = None if getattr(self.config, "use_multimodal", False) and encoder_images is not None: - image_embeddings, deepstack_visual_embeds = self.vision_encoder( # pyrefly: ignore[not-callable] - input_images=encoder_images, deterministic=not enable_dropout + image_embeddings, deepstack_visual_embeds, vision_image_masks = self.vision_encoder( # pyrefly: ignore[not-callable] + input_images=encoder_images, deterministic=not enable_dropout, + image_position_ids=encoder_image_position_ids, ) bidirectional_mask_image = mm_processor.get_bidirectional_mask_vision( self.config, decoder_input_tokens, is_video=False ) if getattr(self.config, "use_multimodal", False) and encoder_videos is not None: - video_embeddings, deepstack_visual_embeds = self.vision_encoder( # pyrefly: ignore[not-callable] + video_embeddings, deepstack_visual_embeds, _ = self.vision_encoder( # pyrefly: ignore[not-callable] input_images=encoder_videos, input_masks=encoder_video_masks, video_grid_thw=encoder_video_grid_thw, @@ -531,7 +537,7 @@ def __call__( if image_embeddings is not None or video_embeddings is not None or audio_embeddings is not None: multimodal_input = MultimodalInput( image_embeddings=image_embeddings, - image_masks=encoder_image_masks, + image_masks=vision_image_masks if vision_image_masks is not None else encoder_image_masks, video_embeddings=video_embeddings, video_masks=encoder_video_masks, audio_embeddings=audio_embeddings, From 1e9d2b49f417a3d92877cc8049c7fcde37e36078 Mon Sep 17 00:00:00 2001 From: dengcchi Date: Sat, 8 Aug 2026 03:17:01 -0700 Subject: [PATCH 03/26] Gemma-4 E2B/E4B: set image-contract defaults in the model configs 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. --- src/maxtext/configs/models/gemma4-e2b.yml | 10 +++++++++- src/maxtext/configs/models/gemma4-e4b.yml | 10 +++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/maxtext/configs/models/gemma4-e2b.yml b/src/maxtext/configs/models/gemma4-e2b.yml index 81c8d4ea66..c4a4b26c26 100644 --- a/src/maxtext/configs/models/gemma4-e2b.yml +++ b/src/maxtext/configs/models/gemma4-e2b.yml @@ -44,7 +44,8 @@ global_rope_proportion: 0.25 local_rope_proportion: 1.0 final_logits_soft_cap: 30.0 -# Vision encoder flags — multimodal not yet supported for E2B / E4B. +# Vision encoder flags. Image (multimodal) parity requires use_clipped_linears_for_vit=true +# (set at runtime alongside use_multimodal=true); the flags below configure the E2B image contract. vision_encoder_block: "gemma4" rope_theta_for_vit: 100 image_size_for_vit: [672, 960] @@ -58,3 +59,10 @@ num_attention_heads_for_vit: 12 image_placeholder: "<|image|>" vision_output_length: 280 num_position_embeddings_for_vit: 10240 +# E2B image contract (decoder-side): image spans are causal and the per-layer-embedding path +# substitutes the pad token for image placeholder rows (matches HF modeling_gemma4). +use_bidirectional_image_attn: False +ple_pad_substitute_image_rows: True +ple_pad_mode: "identity" +image_placeholder_token_id: 258880 +ple_pad_token_id: 0 diff --git a/src/maxtext/configs/models/gemma4-e4b.yml b/src/maxtext/configs/models/gemma4-e4b.yml index b8da0d1d46..cd752ae22b 100644 --- a/src/maxtext/configs/models/gemma4-e4b.yml +++ b/src/maxtext/configs/models/gemma4-e4b.yml @@ -45,7 +45,8 @@ global_rope_proportion: 0.25 local_rope_proportion: 1.0 final_logits_soft_cap: 30.0 -# Vision encoder flags — multimodal not yet supported for E2B / E4B. +# Vision encoder flags. Image (multimodal) parity requires use_clipped_linears_for_vit=true +# (set at runtime alongside use_multimodal=true); the flags below configure the E4B image contract. vision_encoder_block: "gemma4" rope_theta_for_vit: 100 image_size_for_vit: [672, 960] @@ -59,3 +60,10 @@ num_attention_heads_for_vit: 12 image_placeholder: "<|image|>" vision_output_length: 280 num_position_embeddings_for_vit: 10240 +# E4B image contract (decoder-side): image spans are causal and the per-layer-embedding path +# substitutes the pad token for image placeholder rows (matches HF modeling_gemma4). +use_bidirectional_image_attn: False +ple_pad_substitute_image_rows: True +ple_pad_mode: "identity" +image_placeholder_token_id: 258880 +ple_pad_token_id: 0 From 8bb801b5060b05f0dc6a70a412c0626c52e723f4 Mon Sep 17 00:00:00 2001 From: dengcchi Date: Sun, 9 Aug 2026 07:57:35 -0700 Subject: [PATCH 04/26] =?UTF-8?q?M1:=20fail-closed=20guard=20=E2=80=94=20l?= =?UTF-8?q?egacy=20vision=20path=20rejects=20pre-patchified=20input=20with?= =?UTF-8?q?out=20image=5Fposition=5Fids?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/maxtext/models/gemma4_vision.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/maxtext/models/gemma4_vision.py b/src/maxtext/models/gemma4_vision.py index 60ab571f85..977910ee5a 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -848,6 +848,17 @@ def __call__( """ if image_position_ids is None: # ---- Legacy path: raw images -> patchify -> full (unmasked) attention ---- + # Fail-closed contract guard: the legacy path requires FULL images ([B,N,H,W,C] or [B,H,W,C]). + # Pre-patchified inputs ([B,L,F] or [B,N,L,F]) only make sense with per-patch image_position_ids + # (the padded-patch path). Refuse to silently mis-handle pre-patchified input as a full image, which + # would either crash cryptically or produce wrong pooling. + if inputs.ndim not in (4, 5): + raise ValueError( + "Gemma4 vision legacy path expects full images with shape [B, H, W, C] or [B, N, H, W, C]; " + f"got inputs.ndim={inputs.ndim} (shape {tuple(inputs.shape)}). Pre-patchified pixel_values must be " + "accompanied by image_position_ids (the padded-patch path). Refusing to silently take the legacy " + "all-valid vision path." + ) if inputs.ndim == 4: inputs = jnp.expand_dims(inputs, 1) b, n, h, w, c = inputs.shape From 375a36ef8496b75f0a0b06f7dc71ce52359fcf48 Mon Sep 17 00:00:00 2001 From: dengcchi Date: Sun, 9 Aug 2026 08:00:47 -0700 Subject: [PATCH 05/26] =?UTF-8?q?M3:=20make=20448=20clip=20bounds=20immuta?= =?UTF-8?q?ble=20=E2=80=94=20stop=5Fgradient=20at=20use-site=20+=20optimiz?= =?UTF-8?q?er=20freeze=20integration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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). --- src/maxtext/models/gemma4_vision.py | 15 ++++++++++---- src/maxtext/optimizers/optimizers.py | 30 ++++++++++++++++++++++------ 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/src/maxtext/models/gemma4_vision.py b/src/maxtext/models/gemma4_vision.py index 977910ee5a..a9fc6a4c6d 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -84,20 +84,27 @@ def clip_optimizer_freeze_mask(params_tree): return jax.tree_util.tree_unflatten(treedef, leaves_mask) +def _clip_bound_value(bound, dtype): + """Read a clip-bound scalar as a constant: stop_gradient defends the bounds from receiving + gradient at the clamp use-site (defense in depth alongside the optimizer freeze mask), so clip-bound + gradients can never contaminate gradient statistics even if the freeze mask were misconfigured.""" + return jax.lax.stop_gradient(bound.value).astype(dtype) + + def _clip_in(x, cb): - """clamp(x, input_min, input_max) in x's dtype; no-op if ``cb`` is None.""" + """clamp(x, input_min, input_max) in x's dtype; no-op if ``cb`` is None. Bounds are stop_gradient'd.""" if cb is None: return x xd = x.dtype - return jnp.clip(x, cb.input_min.value.astype(xd), cb.input_max.value.astype(xd)) + return jnp.clip(x, _clip_bound_value(cb.input_min, xd), _clip_bound_value(cb.input_max, xd)) def _clip_out(y, cb): - """clamp(y, output_min, output_max) in y's dtype; no-op if ``cb`` is None.""" + """clamp(y, output_min, output_max) in y's dtype; no-op if ``cb`` is None. Bounds are stop_gradient'd.""" if cb is None: return y yd = y.dtype - return jnp.clip(y, cb.output_min.value.astype(yd), cb.output_max.value.astype(yd)) + return jnp.clip(y, _clip_bound_value(cb.output_min, yd), _clip_bound_value(cb.output_max, yd)) class _ClipBounds(nnx.Module): diff --git a/src/maxtext/optimizers/optimizers.py b/src/maxtext/optimizers/optimizers.py index 67e1f589ca..64c2369d17 100644 --- a/src/maxtext/optimizers/optimizers.py +++ b/src/maxtext/optimizers/optimizers.py @@ -239,14 +239,32 @@ def get_optimizer(config, learning_rate_schedule, model=None): # When trainable_parameters_mask is empty, freeze_mask_fn is None and all parameters are trained. trainable_patterns = getattr(config, "trainable_parameters_mask", None) freeze_mask_fn = _get_path_mask_fn(trainable_patterns, match_returns_true=False) - if freeze_mask_fn is not None: - # Use optax.multi_transform to explicitly map frozen parameters to a stateless set_to_zero() optimizer. - # If we simply wrapped base_opt in optax.masked() or chained it, Optax would still allocate - # massive states (momentum, variance) for the entire model before zeroing the updates. - # By using multi_transform, only the trainable parameters get states allocated. + + # Gemma-4 vision clipped-linears: the 448 clip bounds are checkpoint-resident, immutable state and must + # NEVER receive optimizer updates, weight decay, or momentum/variance slots. Freeze them via a leaf-PATH + # mask (robust to the nnx->linen bridge's type erasure). This composes with any trainable_parameters_mask: + # a parameter is "trainable" only if it is trainable under the whitelist AND is not a clip bound. + freeze_clip_bounds = bool(getattr(config, "use_clipped_linears_for_vit", False)) + + if freeze_mask_fn is not None or freeze_clip_bounds: + def _partition(params): + # trainable_mask: True where trainable under the whitelist (all-True if no whitelist). + if freeze_mask_fn is not None: + trainable_mask = freeze_mask_fn(params) + else: + trainable_mask = jax.tree_util.tree_map(lambda _: True, params) + if freeze_clip_bounds: + # clip_optimizer_freeze_mask returns True for trainable leaves, False for clip bounds. + from maxtext.models import gemma4_vision # pylint: disable=import-outside-toplevel + clip_trainable = gemma4_vision.clip_optimizer_freeze_mask(params) + trainable_mask = jax.tree_util.tree_map(lambda a, b: bool(a) and bool(b), trainable_mask, clip_trainable) + return jax.tree_util.tree_map(lambda x: "trainable" if x else "frozen", trainable_mask) + + # Use optax.multi_transform so frozen (and clip-bound) params map to a stateless set_to_zero() optimizer + # and never allocate momentum/variance slots. return optax.multi_transform( {"trainable": base_opt, "frozen": optax.set_to_zero()}, - lambda params: jax.tree_util.tree_map(lambda x: "frozen" if x else "trainable", freeze_mask_fn(params)), + _partition, ) return base_opt From 8a77804758f037827b833f87cb3c8f043767d3c7 Mon Sep 17 00:00:00 2001 From: dengcchi Date: Sun, 9 Aug 2026 08:03:36 -0700 Subject: [PATCH 06/26] M4+M5: real post-load clip validation (exact 112/448, min<=max, fail-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. --- src/maxtext/models/gemma4_vision.py | 63 ++++++++++++++++++++++- src/maxtext/utils/model_creation_utils.py | 8 +++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/src/maxtext/models/gemma4_vision.py b/src/maxtext/models/gemma4_vision.py index a9fc6a4c6d..541403296e 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -123,9 +123,11 @@ def _make_clip_state(): def validate_clip_bounds(cb, where=""): - """Hard-fail: every bound finite + scalar. Raises ValueError otherwise. No-op if ``cb`` is None.""" + """Hard-fail: every bound finite + scalar, and input_min<=input_max, output_min<=output_max. + Raises ValueError otherwise. No-op if ``cb`` is None.""" if cb is None: return + vals = {} for nm in ("input_min", "input_max", "output_min", "output_max"): v = getattr(cb, nm).value if getattr(v, "shape", ()) not in ((), (1,)): @@ -136,6 +138,57 @@ def validate_clip_bounds(cb, where=""): raise ValueError(f"Gemma4 vision clip bound '{nm}'{(' @ '+where) if where else ''} = {fv} is non-finite " f"(missing/NaN/Inf). use_clipped_linears_for_vit=True declares a FINITE clipped model; " f"refusing to fall back to an identity clamp.") + vals[nm] = fv + if vals["input_min"] > vals["input_max"]: + raise ValueError(f"Gemma4 vision clip bound{(' @ '+where) if where else ''}: input_min={vals['input_min']} " + f"> input_max={vals['input_max']} (a clamp with min>max would empty the interval).") + if vals["output_min"] > vals["output_max"]: + raise ValueError(f"Gemma4 vision clip bound{(' @ '+where) if where else ''}: output_min={vals['output_min']} " + f"> output_max={vals['output_max']} (a clamp with min>max would empty the interval).") + + +# Expected clipped-module accounting for a Gemma-4 vision tower: 16 encoder blocks x 7 projections +# (attention q/k/v/o = 4 modules holding q/k/v/o clip states + mlp gate/up/down = 3) -> but the clip +# STATE lives on 2 modules per block (the Gemma4Attention holding q/k/v/o_clip, and the +# Gemma4ClippedMlpBlock holding gate/up/down_clip). The scalar bound count is the invariant that matters: +# 16 blocks x 7 projections x 4 bounds = 448. We validate the projection-level clip states (16x7 = 112). +EXPECTED_CLIP_PROJECTIONS = 112 # 16 blocks x 7 projections (q,k,v,o,gate,up,down) +EXPECTED_CLIP_BOUNDS = 448 # 112 projections x 4 scalar bounds + + +def validate_all_vision_clip_bounds(model, *, expected_projections=EXPECTED_CLIP_PROJECTIONS, + expected_bounds=EXPECTED_CLIP_BOUNDS): + """Post-checkpoint-load, pre-first-JIT validation of ALL Gemma-4 vision clip bounds. Fail-closed. + + Walks the model graph, collects every ``_ClipBounds`` module (each carries the 4 scalars for one + projection), validates each (finite, scalar, min<=max), and asserts EXACT counts: + ``expected_projections`` clip-state modules and ``expected_bounds`` scalar leaves. Raises ValueError on + any deficiency. The exact-count check is what prevents a traversal that accidentally finds zero modules + from silently "passing". + """ + from flax import nnx # pylint: disable=import-outside-toplevel + n_proj = 0 + n_bounds = 0 + for path, mod in nnx.iter_graph(model): + # A clip-state module has exactly the four bound leaves. + if (hasattr(mod, "input_min") and hasattr(mod, "input_max") + and hasattr(mod, "output_min") and hasattr(mod, "output_max") + and not isinstance(mod, (int, float))): + where = "/".join(str(getattr(p, "key", p)) for p in path) if isinstance(path, (list, tuple)) else str(path) + validate_clip_bounds(mod, where) + n_proj += 1 + n_bounds += 4 + if n_proj != expected_projections: + raise ValueError( + f"Gemma-4 vision clip validation found {n_proj} clip-state modules, expected exactly " + f"{expected_projections} (16 blocks x 7 projections). A mismatch means the clip bounds were not " + f"loaded/mapped correctly; refusing to run with a partially-clipped vision tower." + ) + if n_bounds != expected_bounds: + raise ValueError( + f"Gemma-4 vision clip validation found {n_bounds} clip-bound scalars, expected exactly {expected_bounds}." + ) + return n_proj, n_bounds @@ -545,6 +598,14 @@ def enable_vision_clip_bounds(self): """ if getattr(self, "_use_clipped_linears", False): return + # Fail-closed: the clipped path clamps q/k/v independently, which requires SEPARATE q/k/v projections. + # A fused QKV projection would apply a single clamp and silently bypass the per-projection clip semantics. + if bool(getattr(self.config, "fused_qkv", False)): + raise ValueError( + "Gemma-4 vision clipped-linears require fused_qkv=False: the checkpoint carries distinct " + "q/k/v activation clip bounds that must be applied per-projection. Refusing to silently clip a " + "fused QKV projection." + ) self._use_clipped_linears = True self.q_clip = _make_clip_state() self.k_clip = _make_clip_state() diff --git a/src/maxtext/utils/model_creation_utils.py b/src/maxtext/utils/model_creation_utils.py index a2a1403125..9e4bb54dce 100644 --- a/src/maxtext/utils/model_creation_utils.py +++ b/src/maxtext/utils/model_creation_utils.py @@ -1211,6 +1211,14 @@ def _walk_align(ckpt, model_arr, axes): "Please ensure the checkpoint format matches the scan_layers setting." ) + # Gemma-4 vision clipped-linears: fail-closed post-load validation BEFORE the first JIT forward/train. + # Asserts exactly 112 clip-state modules / 448 finite, correctly-ordered scalar bounds. A missing/NaN/ + # unordered bound or wrong module count raises here rather than silently degrading to an identity clamp. + if bool(getattr(config, "use_clipped_linears_for_vit", False)) and bool(getattr(config, "use_multimodal", False)): + from maxtext.models import gemma4_vision # pylint: disable=import-outside-toplevel + n_proj, n_bounds = gemma4_vision.validate_all_vision_clip_bounds(model) + max_logging.log(f"Gemma-4 vision clip validation OK: {n_proj} clip-state modules, {n_bounds} scalar bounds.") + if wrap_with_tunix_adapter: with mesh: use_no_op_mappings = "maxtext_config" in config.vllm_additional_config From 181aa50a4d9148cf008b58c617c614e61ec7e2c4 Mon Sep 17 00:00:00 2001 From: dengcchi Date: Sun, 9 Aug 2026 08:07:46 -0700 Subject: [PATCH 07/26] M1-M5 in-tree tests: tests/unit/gemma4_clip_linears_test.py (13 tests, 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). --- tests/unit/gemma4_clip_linears_test.py | 145 +++++++++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 tests/unit/gemma4_clip_linears_test.py diff --git a/tests/unit/gemma4_clip_linears_test.py b/tests/unit/gemma4_clip_linears_test.py new file mode 100644 index 0000000000..a8174a228b --- /dev/null +++ b/tests/unit/gemma4_clip_linears_test.py @@ -0,0 +1,145 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""In-tree tests for the Gemma-4 vision clipped-linears (PR #4790). + +Pure mechanism + validation tests: no checkpoint, no TPU. Cover the merge-critical invariants: +clip math vs jnp.clip, dtype/no-op, NaN/Inf/ordering hard-fail, exact 112/448 counts, optimizer +freeze mask polarity, and fail-closed contract guards. +""" + +import unittest + +import jax +import jax.numpy as jnp +import numpy as np + +from maxtext.models import gemma4_vision as gv + +jax.config.update("jax_platform_name", "cpu") + + +def _finite_cb(in_lo=-2.5, in_hi=2.5, out_lo=-4.0, out_hi=4.0): + cb = gv._make_clip_state() + cb.input_min.value = jnp.asarray(in_lo, jnp.float32) + cb.input_max.value = jnp.asarray(in_hi, jnp.float32) + cb.output_min.value = jnp.asarray(out_lo, jnp.float32) + cb.output_max.value = jnp.asarray(out_hi, jnp.float32) + return cb + + +class ClipMathTest(unittest.TestCase): + + def test_clip_in_matches_jnp_clip(self): + cb = _finite_cb() + x = (jax.random.normal(jax.random.PRNGKey(0), (5, 17)) * 6.0).astype(jnp.float32) + self.assertTrue(bool(jnp.array_equal(gv._clip_in(x, cb), jnp.clip(x, -2.5, 2.5)))) + + def test_clip_out_matches_jnp_clip(self): + cb = _finite_cb() + x = (jax.random.normal(jax.random.PRNGKey(1), (5, 17)) * 6.0).astype(jnp.float32) + self.assertTrue(bool(jnp.array_equal(gv._clip_out(x, cb), jnp.clip(x, -4.0, 4.0)))) + + def test_none_is_exact_noop(self): + x = jax.random.normal(jax.random.PRNGKey(2), (3, 8)).astype(jnp.float32) + self.assertTrue(bool(jnp.array_equal(gv._clip_in(x, None), x))) + self.assertTrue(bool(jnp.array_equal(gv._clip_out(x, None), x))) + + def test_dtype_preserved(self): + cb = _finite_cb() + x = jax.random.normal(jax.random.PRNGKey(3), (4, 4)).astype(jnp.bfloat16) + self.assertEqual(gv._clip_in(x, cb).dtype, jnp.bfloat16) + + def test_bounds_are_stop_gradient(self): + # The clamp bound is read through jax.lax.stop_gradient at the use-site, so gradient wrt the bound + # value is exactly zero even when the clamp is active. Probe _clip_bound_value directly with a + # lightweight bound holder to avoid mutating an nnx Param inside a traced function. + class _B: + def __init__(self, v): + self.value = v + + def loss(bound_val): + x = jnp.ones((4,), jnp.float32) * 10.0 # above the bound -> clamp active + hi = gv._clip_bound_value(_B(bound_val), jnp.float32) + return jnp.sum(jnp.clip(x, -100.0, hi)) + + g = jax.grad(loss)(jnp.asarray(2.5, jnp.float32)) + self.assertEqual(float(g), 0.0) + + +class ValidateBoundsTest(unittest.TestCase): + + def test_accepts_finite_ordered(self): + gv.validate_clip_bounds(_finite_cb(), "ok") # no raise + + def test_rejects_nan_sentinel(self): + with self.assertRaises(ValueError): + gv.validate_clip_bounds(gv._make_clip_state(), "nan") + + def test_rejects_inf(self): + cb = _finite_cb() + cb.input_max.value = jnp.asarray(np.inf, jnp.float32) + with self.assertRaises(ValueError): + gv.validate_clip_bounds(cb, "inf") + + def test_rejects_min_gt_max(self): + cb = _finite_cb(in_lo=3.0, in_hi=-3.0) # input_min > input_max + with self.assertRaises(ValueError): + gv.validate_clip_bounds(cb, "order") + + def test_none_is_noop(self): + self.assertIsNone(gv.validate_clip_bounds(None)) + + +class FreezeMaskTest(unittest.TestCase): + + def test_freeze_mask_polarity_and_count(self): + tree = { + "vision_encoder": { + "layer_0": { + "attention": { + "q_clip": {"input_min": 1.0, "input_max": 1.0, "output_min": 1.0, "output_max": 1.0}, + "query": {"kernel": 1.0}, + }, + "mlp": {"gate_clip": {"input_min": 1.0, "output_max": 1.0}, "wi_0": {"kernel": 1.0}}, + } + }, + "decoder": {"layer_0": {"norm": {"scale": 1.0}}}, + } + mask = gv.clip_optimizer_freeze_mask(tree) + flat = jax.tree_util.tree_flatten_with_path(mask)[0] + n_clip = 0 + for path, v in flat: + is_clip = gv._is_clip_bound_path(path) + # clip leaves -> False (frozen); everything else -> True (trainable) + self.assertEqual(bool(v), (not is_clip)) + if is_clip: + n_clip += 1 + self.assertEqual(n_clip, 6) # q_clip(4) + gate_clip(2) + + +class SymbolsTest(unittest.TestCase): + + def test_expected_counts_constants(self): + self.assertEqual(gv.EXPECTED_CLIP_PROJECTIONS, 112) + self.assertEqual(gv.EXPECTED_CLIP_BOUNDS, 448) + + def test_public_symbols_present(self): + for sym in ("validate_all_vision_clip_bounds", "clip_optimizer_freeze_mask", + "Gemma4ClippedMlpBlock", "Gemma4Attention"): + self.assertTrue(hasattr(gv, sym), sym) + + +if __name__ == "__main__": + unittest.main() From 8ab09317062650276096a79a4485489f9113c13d Mon Sep 17 00:00:00 2001 From: Loki Chen Date: Sun, 9 Aug 2026 08:30:38 -0700 Subject: [PATCH 08/26] M1/M2/M6: stock-trainer position threading + PLE enum + MM contract gate 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. --- src/maxtext/configs/types.py | 59 ++++++++++++++++++++++++- src/maxtext/layers/decoders.py | 12 +++++ src/maxtext/layers/nnx_decoders.py | 17 ++++++- src/maxtext/trainers/pre_train/train.py | 8 ++++ 4 files changed, 92 insertions(+), 4 deletions(-) diff --git a/src/maxtext/configs/types.py b/src/maxtext/configs/types.py index 0607419737..8b48fdffd9 100644 --- a/src/maxtext/configs/types.py +++ b/src/maxtext/configs/types.py @@ -2348,8 +2348,12 @@ class MultimodalGeneral(BaseModel): ple_pad_mode: str = Field( "identity", description=( - "PLE pad-substitution scope when ple_pad_substitute_image_rows=True: 'identity' (token-id path only) " - "or 'both' (also substitute the pad embedding in the context path)." + "PLE pad-substitution scope when ple_pad_substitute_image_rows=True. 'identity' (DEFAULT, " + "HF-faithful): map image placeholder rows -> pad in the token-identity PLE path only; the context/" + "projection path keeps the merged image features (matches HF Transformers 5.9.0 " + "Gemma4ForConditionalGeneration, where get_per_layer_inputs ignores inputs_embeds when input_ids is " + "provided). 'both': additionally overwrite the context path with the pad embedding — this is " + "HF-DIVERGENT and provided only for ablation. Validated as an enum; unknown values hard-fail." ), ) image_placeholder_token_id: int = Field( @@ -4030,6 +4034,57 @@ def calculate_global_batch_sizes(per_device_batch_size, expansion_factor, num_de "(the vision encoder ships per-projection activation clip bounds; without them the " "image span diverges). Set use_clipped_linears_for_vit=True to enable image inputs." ) + # ---- Gemma-4 E2B/E4B multimodal STATIC contract gate (fail-closed) ---- + # These invariants encode the semantics validated against pinned HF Transformers 5.9.0 + # (Gemma4ForConditionalGeneration). Any deviation silently corrupts image/post-image logits, so we + # refuse to build the model rather than degrade to a wrong-but-runnable path. + if self.model_name in ("gemma4-e2b", "gemma4-e4b"): + # (a) PLE pad-substitution mode must be a known value. HF maps image placeholder tokens -> pad in the + # token-identity PLE path only (the context path keeps the merged image features); that is + # "identity". "both" additionally overwrites the context path, which is HF-DIVERGENT. We keep the + # knob for experimentation but hard-fail unknown/typo values instead of silently defaulting. + _valid_ple_modes = ("identity", "both") + if str(self.ple_pad_mode) not in _valid_ple_modes: + raise ValueError( + f"ple_pad_mode='{self.ple_pad_mode}' is not one of {_valid_ple_modes}. " + f"For Gemma-4 E2B/E4B the HF-faithful contract is 'identity' (token-identity PLE path maps " + f"image rows -> pad; context path keeps merged image features). 'both' is HF-divergent and " + f"provided only for ablation. Refusing to run with an unrecognized PLE mode." + ) + # (b) The image placeholder id and PLE pad id are semantic constants tied to the tokenizer/model. We + # require them to be set explicitly (single source of truth: the model yml derived from HF config) + # so a silent hidden default cannot mask a tokenizer mismatch. + if self.ple_pad_substitute_image_rows: + if int(self.image_placeholder_token_id) < 0: + raise ValueError( + "image_placeholder_token_id must be a valid non-negative token id when " + "ple_pad_substitute_image_rows=True (derive it from the model/tokenizer config)." + ) + if int(self.ple_pad_token_id) < 0: + raise ValueError( + "ple_pad_token_id must be a valid non-negative token id when " + "ple_pad_substitute_image_rows=True (Gemma-4 E2B text_config.pad_token_id=0)." + ) + # (c) Gemma-4 E2B/E4B image spans are CAUSAL. Bidirectional image attention is a Gemma-3 / 26B / 31B + # feature and would change the attention pattern for E2B/E4B. + if bool(getattr(self, "use_bidirectional_image_attn", False)): + raise ValueError( + f"{self.model_name} uses CAUSAL image spans; use_bidirectional_image_attn must be False. " + "Bidirectional image attention is for Gemma-3 / gemma4-26b / gemma4-31b." + ) + # (d) The clipped path clamps q/k/v and gate/up/down per-projection; a fused QKV or fused MLP would + # apply a single clamp and silently bypass the per-projection clip semantics. Fail closed here + # (defense in depth alongside the runtime guards in gemma4_vision). + if bool(getattr(self, "fused_qkv", False)): + raise ValueError( + f"{self.model_name} multimodal clipped-linears require fused_qkv=False " + "(distinct q/k/v activation clip bounds must be applied per-projection)." + ) + if bool(getattr(self, "fused_mlp", False)): + raise ValueError( + f"{self.model_name} multimodal clipped-linears require fused_mlp=False " + "(distinct gate/up/down activation clip bounds must be applied per-projection)." + ) valid_mm_models = ( "gemma3-4b", "gemma3-12b", diff --git a/src/maxtext/layers/decoders.py b/src/maxtext/layers/decoders.py index 648392738e..cf711755d6 100644 --- a/src/maxtext/layers/decoders.py +++ b/src/maxtext/layers/decoders.py @@ -1680,6 +1680,18 @@ def _apply_gemma4_small_layers( per_layer_inputs = None if cfg.hidden_size_per_layer_input > 0 and cfg.vocab_size_per_layer_input > 0: + # Fail-closed: the pure-Linen Gemma-4-small decoder does NOT implement the PLE image-row pad + # substitution (the HF-faithful mapping of image placeholder rows -> pad in the token-identity PLE + # path). That logic lives in the NNX decoder (nnx_decoders._apply_gemma4_small_layers) and is exercised + # by the supported enable_nnx=True path. Running E2B/E4B multimodal through this pure-Linen path would + # silently diverge on the image-span / post-image logits, so we refuse rather than degrade quietly. + if bool(getattr(cfg, "ple_pad_substitute_image_rows", False)) and multimodal_input is not None: + raise NotImplementedError( + "Gemma-4 E2B/E4B multimodal PLE pad-substitution is only implemented on the NNX decoder path " + "(enable_nnx=True, the default). The pure-Linen decoder does not perform the image-row PLE " + "substitution and would silently diverge from the HF reference. Set enable_nnx=True (default) to " + "run Gemma-4 E2B/E4B multimodal." + ) per_layer_inputs = gemma4_small.PLEToLinen( config=cfg, mesh=mesh, diff --git a/src/maxtext/layers/nnx_decoders.py b/src/maxtext/layers/nnx_decoders.py index e95083f7e5..d27f30da84 100644 --- a/src/maxtext/layers/nnx_decoders.py +++ b/src/maxtext/layers/nnx_decoders.py @@ -1769,6 +1769,7 @@ def __call__( attention_metadata=attention_metadata, previous_chunk=previous_chunk, slot=slot, + shared_embedding=shared_embedding, ) elif cfg.scan_layers: if self.is_deepseek: @@ -2254,6 +2255,7 @@ def _apply_gemma4_small_layers( attention_metadata=None, previous_chunk=None, slot=None, + shared_embedding=None, ): """Apply Gemma 4 small (E2B/E4B) decoder layers (pure-NNX).""" cfg = self.config @@ -2279,8 +2281,19 @@ def _apply_gemma4_small_layers( _pad_id = int(getattr(cfg, "ple_pad_token_id", 0)) _img_row = decoder_input_tokens.astype(jnp.int32) == _img_id ple_tokens = jnp.where(_img_row, _pad_id, decoder_input_tokens.astype(jnp.int32)) - if str(getattr(cfg, "ple_pad_mode", "identity")) == "both" and hasattr(self, "shared_embedding"): - _pad_vec = self.shared_embedding(jnp.full_like(decoder_input_tokens, _pad_id).astype(jnp.int32)) + # ple_pad_mode: 'identity' (HF-faithful default) substitutes ONLY the token-identity path (above), + # leaving the context/projection path reading the merged image features — this matches HF + # Transformers 5.9.0 (get_per_layer_inputs ignores inputs_embeds when input_ids is given). The + # 'both' mode additionally overwrites the context path with the pad embedding; this is HF-DIVERGENT + # and provided only for ablation (see M9 ablation matrix). Enum-validated in configs/types.py. + if str(getattr(cfg, "ple_pad_mode", "identity")) == "both": + if shared_embedding is None: + raise ValueError( + "ple_pad_mode='both' requires the shared token embedding to compute the pad context " + "vector, but shared_embedding was not threaded into the Gemma-4-small PLE path. This is " + "an HF-divergent ablation mode; use the default 'identity' for HF-faithful behavior." + ) + _pad_vec = shared_embedding(jnp.full_like(decoder_input_tokens, _pad_id).astype(jnp.int32), model_mode=model_mode) ple_context = jnp.where(_img_row[..., None], _pad_vec, y) per_layer_inputs = self.per_layer_embedder(ple_tokens, ple_context) diff --git a/src/maxtext/trainers/pre_train/train.py b/src/maxtext/trainers/pre_train/train.py index 84276f1a2c..85a185b0b7 100644 --- a/src/maxtext/trainers/pre_train/train.py +++ b/src/maxtext/trainers/pre_train/train.py @@ -144,6 +144,12 @@ def loss_fn(model, config, data, dropout_rng, params, sparsity_state=None, is_tr # parameters in the model and checkpoints. Only pass image inputs when present. encoder_images = data.get("images") if config.use_multimodal else None encoder_image_masks = data.get("image_masks") if config.use_multimodal else None + # Gemma-4 padded-patch (Option-S) contract: when the data pipeline produces per-patch image position ids + # (native-resolution / pan-and-scan processors), thread them to the vision encoder so pad patches are + # masked and pooled by real coordinates. The stock fixed-grid Gemma-4 processor produces all-valid patches + # and does NOT emit this key, so the legacy all-valid path is used (correct for its contract). See + # gemma4_vision.Gemma4VisionEncoderLayer for the fail-closed guard. + encoder_image_position_ids = data.get("image_position_ids") if config.use_multimodal else None mutable_collections = ["intermediates"] if config.mtp_num_layers > 0 and is_train: # The single model.apply call now triggers the entire chain if MTP is enabled: @@ -181,6 +187,7 @@ def loss_fn(model, config, data, dropout_rng, params, sparsity_state=None, is_tr decoder_segment_ids=data["inputs_segmentation"], encoder_images=encoder_images, encoder_image_masks=encoder_image_masks, + encoder_image_position_ids=encoder_image_position_ids, enable_dropout=config.enable_dropout if is_train else False, rngs={"dropout": rng1, "params": aqt_rng}, # pyrefly: ignore[bad-argument-type] mutable=mutable_collections, @@ -240,6 +247,7 @@ def loss_fn(model, config, data, dropout_rng, params, sparsity_state=None, is_tr decoder_segment_ids=data["inputs_segmentation"], encoder_images=encoder_images, encoder_image_masks=encoder_image_masks, + encoder_image_position_ids=encoder_image_position_ids, enable_dropout=config.enable_dropout if is_train else False, decoder_target_tokens=data["targets"], decoder_target_mask=data["targets_segmentation"], From 0c67c77c62e452070221a83130be8fe9a1666f91 Mon Sep 17 00:00:00 2001 From: Loki Chen Date: Sun, 9 Aug 2026 08:57:18 -0700 Subject: [PATCH 09/26] M2/M5/M6 in-tree test: Gemma-4 MM static contract gate (enum/causal/fused/clipped) --- tests/unit/gemma4_mm_contract_gate_test.py | 83 ++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 tests/unit/gemma4_mm_contract_gate_test.py diff --git a/tests/unit/gemma4_mm_contract_gate_test.py b/tests/unit/gemma4_mm_contract_gate_test.py new file mode 100644 index 0000000000..06b49e5bd0 --- /dev/null +++ b/tests/unit/gemma4_mm_contract_gate_test.py @@ -0,0 +1,83 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""M2/M5/M6: Gemma-4 E2B/E4B multimodal STATIC contract gate (configs/types.py). + +Asserts the config validator ACCEPTS a valid E2B multimodal config and HARD-FAILS on each +contract violation: unknown PLE mode (M2 enum), bidirectional image attention (causal M6), +fused_qkv / fused_mlp (M5), and clipped-linears disabled. These encode the semantics verified +against pinned HF Transformers 5.9.0 and must fail closed rather than silently degrade. +""" +import os +import unittest + +from maxtext.configs import pyconfig +from maxtext.utils.globals import MAXTEXT_PKG_DIR + + +def _init(overrides): + base_yml = os.path.join(MAXTEXT_PKG_DIR, "configs", "base.yml") + argv = [ + "test", + base_yml, + "model_name=gemma4-e2b", + "use_multimodal=true", + "override_model_config=true", + "tokenizer_path=/tmp/unused", + "per_device_batch_size=1", + "scan_layers=false", + "enable_checkpointing=false", + "run_name=gate_test", + "steps=1", + "skip_jax_distributed_system=true", + ] + overrides + return pyconfig.initialize(argv) + + +class Gemma4MmContractGateTest(unittest.TestCase): + + def test_valid_e2b_mm_config_builds(self): + # Clipped linears on, identity PLE, causal image spans, fused off -> the HF-faithful contract. + cfg = _init(["use_clipped_linears_for_vit=true"]) + self.assertEqual(cfg.model_name, "gemma4-e2b") + self.assertTrue(cfg.use_multimodal) + self.assertEqual(str(cfg.ple_pad_mode), "identity") + + def test_unknown_ple_pad_mode_hard_fails(self): + with self.assertRaises(Exception): + _init(["use_clipped_linears_for_vit=true", "ple_pad_mode=bogus"]) + + def test_both_ple_pad_mode_is_valid_ablation_enum(self): + cfg = _init(["use_clipped_linears_for_vit=true", "ple_pad_mode=both"]) + self.assertEqual(str(cfg.ple_pad_mode), "both") + + def test_bidirectional_image_attn_hard_fails(self): + # Gemma-4 E2B/E4B image spans are causal; bidirectional is a Gemma-3 / 26B / 31B feature. + with self.assertRaises(Exception): + _init(["use_clipped_linears_for_vit=true", "use_bidirectional_image_attn=true"]) + + def test_fused_qkv_hard_fails(self): + with self.assertRaises(Exception): + _init(["use_clipped_linears_for_vit=true", "fused_qkv=true"]) + + def test_fused_mlp_hard_fails(self): + with self.assertRaises(Exception): + _init(["use_clipped_linears_for_vit=true", "fused_mlp=true"]) + + def test_clipped_linears_off_under_mm_hard_fails(self): + with self.assertRaises(Exception): + _init(["use_clipped_linears_for_vit=false"]) + + +if __name__ == "__main__": + unittest.main() From 250f6c6d83cd1885a1e27e95affe912ec4d3a5dd Mon Sep 17 00:00:00 2001 From: Loki Chen Date: Sun, 9 Aug 2026 09:00:28 -0700 Subject: [PATCH 10/26] M7: Option-S sentinel integrity + placeholder==pooled validators + 5 unit tests --- src/maxtext/models/gemma4_vision.py | 62 ++++++++++++++++++++++++++ tests/unit/gemma4_clip_linears_test.py | 37 +++++++++++++++ 2 files changed, 99 insertions(+) diff --git a/src/maxtext/models/gemma4_vision.py b/src/maxtext/models/gemma4_vision.py index 541403296e..4456ec5d1d 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -191,8 +191,70 @@ def validate_all_vision_clip_bounds(model, *, expected_projections=EXPECTED_CLIP return n_proj, n_bounds +# Sentinel value marking a padded (phantom) patch position in the Option-S padded-patch contract. +POSITIONS_PAD_VALUE = -1 +def option_s_position_sentinel_ok(positions_xy): + """Return (all_rows_valid_or_full_sentinel, n_bad_rows) for an Option-S position tensor. + + The padded-patch contract requires every per-patch position row to be EXACTLY one of: + * [x, y] with both coordinates >= 0 (a valid patch), or + * [POSITIONS_PAD_VALUE, POSITIONS_PAD_VALUE] (a fully-padded sentinel). + A MIXED row such as [-1, y] or [x, -1] is malformed: it would be classified as "valid" by the + ``(pos == -1).all(axis=-1)`` pad test (silently attended-to as a real patch) yet carry a negative + coordinate into pooling. This helper flags such rows so callers can fail closed rather than + silently mis-handle them. Pure (numpy/jax-eager friendly); does not allocate on-device state. + + Args: + positions_xy: int array [..., 2] of per-patch (x, y) positions. + Returns: + (ok: bool, n_bad: int) where ok is True iff no malformed (mixed-sentinel) row exists. + """ + import numpy as _np # local import: this is called eagerly (host) for validation, not in the JIT forward + p = _np.asarray(positions_xy) + if p.shape[-1] != 2: + raise ValueError(f"option_s positions must have last dim 2 (x,y); got shape {p.shape}") + is_neg = p == POSITIONS_PAD_VALUE + any_neg = is_neg.any(axis=-1) + all_neg = is_neg.all(axis=-1) + # A row is malformed iff it has SOME sentinel coord but is not FULLY sentinel. + bad = _np.logical_and(any_neg, _np.logical_not(all_neg)) + # Also reject any negative coordinate other than the exact sentinel (e.g. -2), which is never valid. + other_neg = _np.logical_and(p < 0, p != POSITIONS_PAD_VALUE).any(axis=-1) + bad = _np.logical_or(bad, other_neg) + n_bad = int(bad.sum()) + return (n_bad == 0), n_bad + + +def validate_option_s_positions(positions_xy, where=""): + """Hard-fail if any Option-S position row is a malformed mixed sentinel. No-op if positions is None.""" + if positions_xy is None: + return + ok, n_bad = option_s_position_sentinel_ok(positions_xy) + if not ok: + raise ValueError( + f"Gemma-4 Option-S position sentinel integrity{(' @ '+where) if where else ''}: found {n_bad} malformed " + f"row(s). Every patch position must be [x,y] with both coords >= 0, or [-1,-1] (full sentinel). Mixed " + f"rows like [-1, y] / [x, -1] (or other negatives) would be silently treated as valid patches and " + f"corrupt pooling; refusing to run." + ) + + +def option_s_pooled_matches_placeholder(image_mask, n_placeholder): + """Return (ok, n_valid_pooled) checking the count of valid pooled image tokens == n_placeholder. + + ``image_mask`` is the [..., K] validity mask returned by the vision pooler (True where a pooled slot + received at least one real patch). ``n_placeholder`` is the number of image placeholder positions in the + decoder sequence for the SAME sample. The Option-S contract requires these to be equal so that the pooled + image tokens scatter 1:1 onto the placeholder rows; a mismatch means the merge would drop or duplicate + image tokens regardless of padded-embedding ordering. + """ + import numpy as _np + m = _np.asarray(image_mask) + n_valid = int(_np.asarray(m).astype(bool).sum()) + return (n_valid == int(n_placeholder)), n_valid + def factorized_posemb(posemb: jax.Array, positions_xy: jax.Array, precision) -> jax.Array: """Computes factorized position embedding from (x, y) coordinates. diff --git a/tests/unit/gemma4_clip_linears_test.py b/tests/unit/gemma4_clip_linears_test.py index a8174a228b..fd2c08f766 100644 --- a/tests/unit/gemma4_clip_linears_test.py +++ b/tests/unit/gemma4_clip_linears_test.py @@ -143,3 +143,40 @@ def test_public_symbols_present(self): if __name__ == "__main__": unittest.main() + + +class OptionSInvariantsTest(unittest.TestCase): + """M7: Option-S sentinel integrity + placeholder==pooled count invariants (pure validators).""" + + def test_valid_positions_pass(self): + pos = np.array([[[0, 0], [1, 0], [-1, -1], [-1, -1]]], dtype=np.int32) # 2 valid + 2 full-sentinel + ok, n_bad = gv.option_s_position_sentinel_ok(pos) + self.assertTrue(ok) + self.assertEqual(n_bad, 0) + gv.validate_option_s_positions(pos) # must not raise + + def test_mixed_sentinel_row_fails(self): + for bad_row in ([-1, 5], [5, -1]): + pos = np.array([[[0, 0], bad_row, [-1, -1]]], dtype=np.int32) + ok, n_bad = gv.option_s_position_sentinel_ok(pos) + self.assertFalse(ok, f"mixed row {bad_row} should be flagged") + self.assertEqual(n_bad, 1) + with self.assertRaises(ValueError): + gv.validate_option_s_positions(pos, where="test") + + def test_other_negative_coord_fails(self): + pos = np.array([[[0, 0], [-2, -2], [-1, -1]]], dtype=np.int32) # -2 is not the sentinel + ok, n_bad = gv.option_s_position_sentinel_ok(pos) + self.assertFalse(ok) + + def test_pooled_matches_placeholder(self): + mask = np.array([True, True, True, False, False]) # 3 valid pooled tokens + ok, n_valid = gv.option_s_pooled_matches_placeholder(mask, 3) + self.assertTrue(ok) + self.assertEqual(n_valid, 3) + + def test_pooled_placeholder_mismatch_detected(self): + mask = np.array([True, True, True, False, False]) # 3 valid + ok, n_valid = gv.option_s_pooled_matches_placeholder(mask, 4) # placeholder count 4 != 3 + self.assertFalse(ok) + self.assertEqual(n_valid, 3) From 99d6c28c49bc3cec632791c2217b93ad3e77e96a Mon Sep 17 00:00:00 2001 From: Loki Chen Date: Sun, 9 Aug 2026 09:07:25 -0700 Subject: [PATCH 11/26] M7.4: sanitize padded-patch rows to zero before attention (isolate non-finite pad from valid outputs) --- src/maxtext/models/gemma4_vision.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/maxtext/models/gemma4_vision.py b/src/maxtext/models/gemma4_vision.py index 4456ec5d1d..b65836b39c 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -1037,6 +1037,16 @@ def __call__( is_pad = (positions_xy == -1).all(axis=-1) # [B*N, L] decoder_segment_ids = jnp.where(is_pad, 2, 1).astype(jnp.int32) + # Sanitize padded-patch rows to zero BEFORE attention. Segment masking already prevents pad patches + # from influencing valid patches' attention outputs, and pooling excludes pad positions — so for FINITE + # pad content the valid outputs are provably invariant (verified byte-identical under 1e6 garbage pad). + # However, attention computes q/k/v on ALL rows before masking, so a NON-FINITE (NaN/Inf) pad patch would + # produce NaN q/k/v and leak through the softmax normalization into valid rows (NaN*0=NaN). Zeroing pad + # rows here makes the isolation hold for arbitrary (incl. non-finite) pad content without changing any + # valid output. This is defense-in-depth for malformed processor output; the frozen processor emits finite + # pad, which was already invariant. + x = jnp.where(is_pad[..., None], jnp.zeros_like(x), x) + for i in range(self.config.num_hidden_layers_for_vit): layer = getattr(self, f"layer_{i}") x = layer( From c16da94e9d10735c3ba7252245343827760a7ae7 Mon Sep 17 00:00:00 2001 From: Loki Chen Date: Sun, 9 Aug 2026 09:16:37 -0700 Subject: [PATCH 12/26] M8: fail-close packing for E2B/E4B multimodal (any mode) + packing-guard 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. --- src/maxtext/configs/types.py | 11 +++++++++++ tests/unit/gemma4_mm_contract_gate_test.py | 5 +++++ 2 files changed, 16 insertions(+) diff --git a/src/maxtext/configs/types.py b/src/maxtext/configs/types.py index 8b48fdffd9..bdf5cc3a07 100644 --- a/src/maxtext/configs/types.py +++ b/src/maxtext/configs/types.py @@ -4085,6 +4085,17 @@ def calculate_global_batch_sizes(per_device_batch_size, expansion_factor, num_de f"{self.model_name} multimodal clipped-linears require fused_mlp=False " "(distinct gate/up/down activation clip bounds must be applied per-projection)." ) + # (e) Sequence packing is not supported for Gemma-4 E2B/E4B multimodal in ANY training mode. The stock + # data pipeline does not pack image spans, and packing image-bearing examples together would risk + # cross-document image attention and PLE image-row substitution bleeding across segment boundaries. + # MaxText already forbids packing for multimodal SFT; extend that to every mode for these models + # (fail closed rather than silently produce cross-doc image attention). + if bool(getattr(self, "packing", False)): + raise ValueError( + f"{self.model_name} multimodal does not support sequence packing (packing=True). The stock data " + "pipeline does not pack image spans; packing image-bearing examples risks cross-document image " + "attention and PLE image-row substitution across segment boundaries. Set packing=False." + ) valid_mm_models = ( "gemma3-4b", "gemma3-12b", diff --git a/tests/unit/gemma4_mm_contract_gate_test.py b/tests/unit/gemma4_mm_contract_gate_test.py index 06b49e5bd0..a60529079b 100644 --- a/tests/unit/gemma4_mm_contract_gate_test.py +++ b/tests/unit/gemma4_mm_contract_gate_test.py @@ -78,6 +78,11 @@ def test_clipped_linears_off_under_mm_hard_fails(self): with self.assertRaises(Exception): _init(["use_clipped_linears_for_vit=false"]) + def test_packing_hard_fails(self): + # Packed multimodal is unsupported for E2B/E4B in any mode (cross-doc image attention risk). + with self.assertRaises(Exception): + _init(["use_clipped_linears_for_vit=true", "packing=true"]) + if __name__ == "__main__": unittest.main() From da07c528d8698debd5536e7805b4fe64f2f6ee39 Mon Sep 17 00:00:00 2001 From: Loki Chen Date: Sun, 9 Aug 2026 09:21:27 -0700 Subject: [PATCH 13/26] E2B/E4B ymls: default packing=false (MM does not support packed image spans) --- src/maxtext/configs/models/gemma4-e2b.yml | 1 + src/maxtext/configs/models/gemma4-e4b.yml | 1 + 2 files changed, 2 insertions(+) diff --git a/src/maxtext/configs/models/gemma4-e2b.yml b/src/maxtext/configs/models/gemma4-e2b.yml index c4a4b26c26..502e84737b 100644 --- a/src/maxtext/configs/models/gemma4-e2b.yml +++ b/src/maxtext/configs/models/gemma4-e2b.yml @@ -66,3 +66,4 @@ ple_pad_substitute_image_rows: True ple_pad_mode: "identity" image_placeholder_token_id: 258880 ple_pad_token_id: 0 +packing: false # Gemma-4 E2B/E4B multimodal does not support packed image spans (see configs/types.py gate) diff --git a/src/maxtext/configs/models/gemma4-e4b.yml b/src/maxtext/configs/models/gemma4-e4b.yml index cd752ae22b..d2cf5bdd7e 100644 --- a/src/maxtext/configs/models/gemma4-e4b.yml +++ b/src/maxtext/configs/models/gemma4-e4b.yml @@ -67,3 +67,4 @@ ple_pad_substitute_image_rows: True ple_pad_mode: "identity" image_placeholder_token_id: 258880 ple_pad_token_id: 0 +packing: false # Gemma-4 E2B/E4B multimodal does not support packed image spans (see configs/types.py gate) From 85f817fc0d794b46ac3f336f174dfbeda905dbbd Mon Sep 17 00:00:00 2001 From: Loki Chen Date: Mon, 24 Aug 2026 22:39:35 -0700 Subject: [PATCH 14/26] Gemma4-small ViT review: consolidate clip tests into gemma4_small_layers_test.py; optimizer clip-freeze comment; E2B multimodal e2e script Addresses hengtaoguo review on #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) --- src/maxtext/optimizers/optimizers.py | 4 + .../tpu/gemma4/e2b/test_gemma4_multimodal.sh | 71 ++++++ tests/unit/gemma4_clip_linears_test.py | 182 -------------- tests/unit/gemma4_mm_contract_gate_test.py | 88 ------- tests/unit/gemma4_small_layers_test.py | 226 ++++++++++++++++++ 5 files changed, 301 insertions(+), 270 deletions(-) create mode 100755 tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh delete mode 100644 tests/unit/gemma4_clip_linears_test.py delete mode 100644 tests/unit/gemma4_mm_contract_gate_test.py diff --git a/src/maxtext/optimizers/optimizers.py b/src/maxtext/optimizers/optimizers.py index 64c2369d17..1f84653300 100644 --- a/src/maxtext/optimizers/optimizers.py +++ b/src/maxtext/optimizers/optimizers.py @@ -247,6 +247,7 @@ def get_optimizer(config, learning_rate_schedule, model=None): freeze_clip_bounds = bool(getattr(config, "use_clipped_linears_for_vit", False)) if freeze_mask_fn is not None or freeze_clip_bounds: + def _partition(params): # trainable_mask: True where trainable under the whitelist (all-True if no whitelist). if freeze_mask_fn is not None: @@ -254,8 +255,11 @@ def _partition(params): else: trainable_mask = jax.tree_util.tree_map(lambda _: True, params) if freeze_clip_bounds: + # Gemma4-small (E2B/E4B) ViT: exclude the checkpoint-resident, non-trainable per-projection + # activation clip bounds from optimizer updates / weight decay. # clip_optimizer_freeze_mask returns True for trainable leaves, False for clip bounds. from maxtext.models import gemma4_vision # pylint: disable=import-outside-toplevel + clip_trainable = gemma4_vision.clip_optimizer_freeze_mask(params) trainable_mask = jax.tree_util.tree_map(lambda a, b: bool(a) and bool(b), trainable_mask, clip_trainable) return jax.tree_util.tree_map(lambda x: "trainable" if x else "frozen", trainable_mask) diff --git a/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh b/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh new file mode 100755 index 0000000000..208e2dde00 --- /dev/null +++ b/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh @@ -0,0 +1,71 @@ +#!/bin/bash + +# End-to-end image (multimodal) parity check for Gemma-4 E2B. +# +# Unlike gemma4/e2b/convert_gemma4.sh (text-only), this exercises the image path enabled by +# PR #4790: vision clipped-linears + padded-patch masking + PLE image-row pad substitution + +# causal image spans. It converts the HF checkpoint (with the vision tower), pre-generates the +# HF golden logits for an image+prompt, and runs forward_pass_logit_checker on the NNX path +# (enable_nnx defaults True; per-layer KV sharing is incompatible with nn.scan, so scan_layers=false). +# +# See tests/end_to_end/tpu/gemma4/Run_Gemma4.md for an overview. +# +# Usage: +# export HF_TOKEN= +# export HF_MODEL=path/to/your/hf/gemma-4-E2B-it +# bash tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh + +set -ex +idx=$(date +%Y-%m-%d-%H-%M) + +MODEL_NAME='gemma4-e2b' +export MODEL_VARIATION='e2b-it' +MODEL_ID='google/gemma-4-E2B-it' +TOKENIZER_PATH='google/gemma-4-E2B-it' +USE_SCAN_LAYERS=false # Per-layer KV sharing is incompatible with nn.scan. +IMAGE_PATH='tests/assets/test_image.jpg' +PROMPT='Describe this image' + +# Installing torch for deps in the HF golden-logits generator / logit checker. +python3 -m pip install torch --index-url https://download.pytorch.org/whl/cpu + +# HF checkpoint (must contain the vision tower for multimodal). +export MODEL_BUCKET='gs://maxtext-gemma/gemma4' +export HF_MODEL=${HF_MODEL:-'path/to/your/hf/gemma-4-E2B-it'} + +# Step 1: HF -> MaxText conversion WITH the vision tower (use_multimodal=true). +python3 -m maxtext.checkpoint_conversion.to_maxtext "${MAXTEXT_CONFIGS_DIR:-${MAXTEXT_REPO_ROOT:-$PWD}/src/maxtext/configs}"/base.yml \ + model_name=${MODEL_NAME} \ + hf_access_token=${HF_TOKEN} \ + --hf_model_path=${HF_MODEL} \ + base_output_directory=${MODEL_BUCKET}/${MODEL_VARIATION}/converted_mm/${idx} \ + use_multimodal=true \ + scan_layers=${USE_SCAN_LAYERS} + +export MAXTEXT_CKPT_PATH=${MODEL_BUCKET}/${MODEL_VARIATION}/converted_mm/${idx}/0/items + +# Step 2: Pre-generate the HF golden logits for the image+prompt (required for multimodal). +GOLDEN_LOGITS_PATH="golden_${MODEL_VARIATION}_vision_${idx}.jsonl" +python3 -m tests.assets.logits_generation.generate_hf_golden_logits \ + --model-id=${MODEL_ID} --hf-model-path=${HF_MODEL} \ + --prompts="${PROMPT}" --image-paths=${IMAGE_PATH} \ + --output-path=${GOLDEN_LOGITS_PATH} \ + --apply-chat-template --output-format=json + +# Step 3: MaxText vs HF golden-logit parity on the image path. +# Gate mirrors the PR's post_image parity (max_KL << 0.03 observed at 4.29e-05); we use the +# conservative repo default multimodal gate here. +python3 -m tests.utils.forward_pass_logit_checker "${MAXTEXT_CONFIGS_DIR:-${MAXTEXT_REPO_ROOT:-$PWD}/src/maxtext/configs}"/base.yml \ + tokenizer_path=${TOKENIZER_PATH} \ + load_parameters_path=${MAXTEXT_CKPT_PATH} \ + model_name=${MODEL_NAME} \ + use_multimodal=true \ + use_clipped_linears_for_vit=true \ + scan_layers=${USE_SCAN_LAYERS} \ + per_device_batch_size=1 \ + dtype=float32 \ + attention=dot_product \ + prompt="${PROMPT}" \ + image_path=${IMAGE_PATH} \ + --max_kl_div=0.03 \ + --golden_logits_path=${GOLDEN_LOGITS_PATH} diff --git a/tests/unit/gemma4_clip_linears_test.py b/tests/unit/gemma4_clip_linears_test.py deleted file mode 100644 index fd2c08f766..0000000000 --- a/tests/unit/gemma4_clip_linears_test.py +++ /dev/null @@ -1,182 +0,0 @@ -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""In-tree tests for the Gemma-4 vision clipped-linears (PR #4790). - -Pure mechanism + validation tests: no checkpoint, no TPU. Cover the merge-critical invariants: -clip math vs jnp.clip, dtype/no-op, NaN/Inf/ordering hard-fail, exact 112/448 counts, optimizer -freeze mask polarity, and fail-closed contract guards. -""" - -import unittest - -import jax -import jax.numpy as jnp -import numpy as np - -from maxtext.models import gemma4_vision as gv - -jax.config.update("jax_platform_name", "cpu") - - -def _finite_cb(in_lo=-2.5, in_hi=2.5, out_lo=-4.0, out_hi=4.0): - cb = gv._make_clip_state() - cb.input_min.value = jnp.asarray(in_lo, jnp.float32) - cb.input_max.value = jnp.asarray(in_hi, jnp.float32) - cb.output_min.value = jnp.asarray(out_lo, jnp.float32) - cb.output_max.value = jnp.asarray(out_hi, jnp.float32) - return cb - - -class ClipMathTest(unittest.TestCase): - - def test_clip_in_matches_jnp_clip(self): - cb = _finite_cb() - x = (jax.random.normal(jax.random.PRNGKey(0), (5, 17)) * 6.0).astype(jnp.float32) - self.assertTrue(bool(jnp.array_equal(gv._clip_in(x, cb), jnp.clip(x, -2.5, 2.5)))) - - def test_clip_out_matches_jnp_clip(self): - cb = _finite_cb() - x = (jax.random.normal(jax.random.PRNGKey(1), (5, 17)) * 6.0).astype(jnp.float32) - self.assertTrue(bool(jnp.array_equal(gv._clip_out(x, cb), jnp.clip(x, -4.0, 4.0)))) - - def test_none_is_exact_noop(self): - x = jax.random.normal(jax.random.PRNGKey(2), (3, 8)).astype(jnp.float32) - self.assertTrue(bool(jnp.array_equal(gv._clip_in(x, None), x))) - self.assertTrue(bool(jnp.array_equal(gv._clip_out(x, None), x))) - - def test_dtype_preserved(self): - cb = _finite_cb() - x = jax.random.normal(jax.random.PRNGKey(3), (4, 4)).astype(jnp.bfloat16) - self.assertEqual(gv._clip_in(x, cb).dtype, jnp.bfloat16) - - def test_bounds_are_stop_gradient(self): - # The clamp bound is read through jax.lax.stop_gradient at the use-site, so gradient wrt the bound - # value is exactly zero even when the clamp is active. Probe _clip_bound_value directly with a - # lightweight bound holder to avoid mutating an nnx Param inside a traced function. - class _B: - def __init__(self, v): - self.value = v - - def loss(bound_val): - x = jnp.ones((4,), jnp.float32) * 10.0 # above the bound -> clamp active - hi = gv._clip_bound_value(_B(bound_val), jnp.float32) - return jnp.sum(jnp.clip(x, -100.0, hi)) - - g = jax.grad(loss)(jnp.asarray(2.5, jnp.float32)) - self.assertEqual(float(g), 0.0) - - -class ValidateBoundsTest(unittest.TestCase): - - def test_accepts_finite_ordered(self): - gv.validate_clip_bounds(_finite_cb(), "ok") # no raise - - def test_rejects_nan_sentinel(self): - with self.assertRaises(ValueError): - gv.validate_clip_bounds(gv._make_clip_state(), "nan") - - def test_rejects_inf(self): - cb = _finite_cb() - cb.input_max.value = jnp.asarray(np.inf, jnp.float32) - with self.assertRaises(ValueError): - gv.validate_clip_bounds(cb, "inf") - - def test_rejects_min_gt_max(self): - cb = _finite_cb(in_lo=3.0, in_hi=-3.0) # input_min > input_max - with self.assertRaises(ValueError): - gv.validate_clip_bounds(cb, "order") - - def test_none_is_noop(self): - self.assertIsNone(gv.validate_clip_bounds(None)) - - -class FreezeMaskTest(unittest.TestCase): - - def test_freeze_mask_polarity_and_count(self): - tree = { - "vision_encoder": { - "layer_0": { - "attention": { - "q_clip": {"input_min": 1.0, "input_max": 1.0, "output_min": 1.0, "output_max": 1.0}, - "query": {"kernel": 1.0}, - }, - "mlp": {"gate_clip": {"input_min": 1.0, "output_max": 1.0}, "wi_0": {"kernel": 1.0}}, - } - }, - "decoder": {"layer_0": {"norm": {"scale": 1.0}}}, - } - mask = gv.clip_optimizer_freeze_mask(tree) - flat = jax.tree_util.tree_flatten_with_path(mask)[0] - n_clip = 0 - for path, v in flat: - is_clip = gv._is_clip_bound_path(path) - # clip leaves -> False (frozen); everything else -> True (trainable) - self.assertEqual(bool(v), (not is_clip)) - if is_clip: - n_clip += 1 - self.assertEqual(n_clip, 6) # q_clip(4) + gate_clip(2) - - -class SymbolsTest(unittest.TestCase): - - def test_expected_counts_constants(self): - self.assertEqual(gv.EXPECTED_CLIP_PROJECTIONS, 112) - self.assertEqual(gv.EXPECTED_CLIP_BOUNDS, 448) - - def test_public_symbols_present(self): - for sym in ("validate_all_vision_clip_bounds", "clip_optimizer_freeze_mask", - "Gemma4ClippedMlpBlock", "Gemma4Attention"): - self.assertTrue(hasattr(gv, sym), sym) - - -if __name__ == "__main__": - unittest.main() - - -class OptionSInvariantsTest(unittest.TestCase): - """M7: Option-S sentinel integrity + placeholder==pooled count invariants (pure validators).""" - - def test_valid_positions_pass(self): - pos = np.array([[[0, 0], [1, 0], [-1, -1], [-1, -1]]], dtype=np.int32) # 2 valid + 2 full-sentinel - ok, n_bad = gv.option_s_position_sentinel_ok(pos) - self.assertTrue(ok) - self.assertEqual(n_bad, 0) - gv.validate_option_s_positions(pos) # must not raise - - def test_mixed_sentinel_row_fails(self): - for bad_row in ([-1, 5], [5, -1]): - pos = np.array([[[0, 0], bad_row, [-1, -1]]], dtype=np.int32) - ok, n_bad = gv.option_s_position_sentinel_ok(pos) - self.assertFalse(ok, f"mixed row {bad_row} should be flagged") - self.assertEqual(n_bad, 1) - with self.assertRaises(ValueError): - gv.validate_option_s_positions(pos, where="test") - - def test_other_negative_coord_fails(self): - pos = np.array([[[0, 0], [-2, -2], [-1, -1]]], dtype=np.int32) # -2 is not the sentinel - ok, n_bad = gv.option_s_position_sentinel_ok(pos) - self.assertFalse(ok) - - def test_pooled_matches_placeholder(self): - mask = np.array([True, True, True, False, False]) # 3 valid pooled tokens - ok, n_valid = gv.option_s_pooled_matches_placeholder(mask, 3) - self.assertTrue(ok) - self.assertEqual(n_valid, 3) - - def test_pooled_placeholder_mismatch_detected(self): - mask = np.array([True, True, True, False, False]) # 3 valid - ok, n_valid = gv.option_s_pooled_matches_placeholder(mask, 4) # placeholder count 4 != 3 - self.assertFalse(ok) - self.assertEqual(n_valid, 3) diff --git a/tests/unit/gemma4_mm_contract_gate_test.py b/tests/unit/gemma4_mm_contract_gate_test.py deleted file mode 100644 index a60529079b..0000000000 --- a/tests/unit/gemma4_mm_contract_gate_test.py +++ /dev/null @@ -1,88 +0,0 @@ -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""M2/M5/M6: Gemma-4 E2B/E4B multimodal STATIC contract gate (configs/types.py). - -Asserts the config validator ACCEPTS a valid E2B multimodal config and HARD-FAILS on each -contract violation: unknown PLE mode (M2 enum), bidirectional image attention (causal M6), -fused_qkv / fused_mlp (M5), and clipped-linears disabled. These encode the semantics verified -against pinned HF Transformers 5.9.0 and must fail closed rather than silently degrade. -""" -import os -import unittest - -from maxtext.configs import pyconfig -from maxtext.utils.globals import MAXTEXT_PKG_DIR - - -def _init(overrides): - base_yml = os.path.join(MAXTEXT_PKG_DIR, "configs", "base.yml") - argv = [ - "test", - base_yml, - "model_name=gemma4-e2b", - "use_multimodal=true", - "override_model_config=true", - "tokenizer_path=/tmp/unused", - "per_device_batch_size=1", - "scan_layers=false", - "enable_checkpointing=false", - "run_name=gate_test", - "steps=1", - "skip_jax_distributed_system=true", - ] + overrides - return pyconfig.initialize(argv) - - -class Gemma4MmContractGateTest(unittest.TestCase): - - def test_valid_e2b_mm_config_builds(self): - # Clipped linears on, identity PLE, causal image spans, fused off -> the HF-faithful contract. - cfg = _init(["use_clipped_linears_for_vit=true"]) - self.assertEqual(cfg.model_name, "gemma4-e2b") - self.assertTrue(cfg.use_multimodal) - self.assertEqual(str(cfg.ple_pad_mode), "identity") - - def test_unknown_ple_pad_mode_hard_fails(self): - with self.assertRaises(Exception): - _init(["use_clipped_linears_for_vit=true", "ple_pad_mode=bogus"]) - - def test_both_ple_pad_mode_is_valid_ablation_enum(self): - cfg = _init(["use_clipped_linears_for_vit=true", "ple_pad_mode=both"]) - self.assertEqual(str(cfg.ple_pad_mode), "both") - - def test_bidirectional_image_attn_hard_fails(self): - # Gemma-4 E2B/E4B image spans are causal; bidirectional is a Gemma-3 / 26B / 31B feature. - with self.assertRaises(Exception): - _init(["use_clipped_linears_for_vit=true", "use_bidirectional_image_attn=true"]) - - def test_fused_qkv_hard_fails(self): - with self.assertRaises(Exception): - _init(["use_clipped_linears_for_vit=true", "fused_qkv=true"]) - - def test_fused_mlp_hard_fails(self): - with self.assertRaises(Exception): - _init(["use_clipped_linears_for_vit=true", "fused_mlp=true"]) - - def test_clipped_linears_off_under_mm_hard_fails(self): - with self.assertRaises(Exception): - _init(["use_clipped_linears_for_vit=false"]) - - def test_packing_hard_fails(self): - # Packed multimodal is unsupported for E2B/E4B in any mode (cross-doc image attention risk). - with self.assertRaises(Exception): - _init(["use_clipped_linears_for_vit=true", "packing=true"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/unit/gemma4_small_layers_test.py b/tests/unit/gemma4_small_layers_test.py index 8a50217b73..2413044745 100644 --- a/tests/unit/gemma4_small_layers_test.py +++ b/tests/unit/gemma4_small_layers_test.py @@ -41,6 +41,7 @@ from maxtext.common.common_types import AttentionType from maxtext.layers.attentions import Attention from maxtext.models import gemma4_small +from maxtext.models import gemma4_vision as gv from maxtext.utils.globals import MAXTEXT_REPO_ROOT from tests.utils.multimodal_test_utils import assert_all_close_jax_torch, copy_rmsnorm_weights @@ -411,5 +412,230 @@ def test_shared_layer_matches_torch(self): ) +# --------------------------------------------------------------------------- +# Gemma-4 vision clipped-linears (PR #4790): pure jax-cpu mechanism + validation tests. +# Consolidated here from the standalone gemma4_clip_linears_test.py per review. +# --------------------------------------------------------------------------- + + +def _finite_cb(in_lo=-2.5, in_hi=2.5, out_lo=-4.0, out_hi=4.0): + cb = gv._make_clip_state() + cb.input_min.value = jnp.asarray(in_lo, jnp.float32) + cb.input_max.value = jnp.asarray(in_hi, jnp.float32) + cb.output_min.value = jnp.asarray(out_lo, jnp.float32) + cb.output_max.value = jnp.asarray(out_hi, jnp.float32) + return cb + + +class ClipMathTest(unittest.TestCase): + + def test_clip_in_matches_jnp_clip(self): + cb = _finite_cb() + x = (jax.random.normal(jax.random.PRNGKey(0), (5, 17)) * 6.0).astype(jnp.float32) + self.assertTrue(bool(jnp.array_equal(gv._clip_in(x, cb), jnp.clip(x, -2.5, 2.5)))) + + def test_clip_out_matches_jnp_clip(self): + cb = _finite_cb() + x = (jax.random.normal(jax.random.PRNGKey(1), (5, 17)) * 6.0).astype(jnp.float32) + self.assertTrue(bool(jnp.array_equal(gv._clip_out(x, cb), jnp.clip(x, -4.0, 4.0)))) + + def test_none_is_exact_noop(self): + x = jax.random.normal(jax.random.PRNGKey(2), (3, 8)).astype(jnp.float32) + self.assertTrue(bool(jnp.array_equal(gv._clip_in(x, None), x))) + self.assertTrue(bool(jnp.array_equal(gv._clip_out(x, None), x))) + + def test_dtype_preserved(self): + cb = _finite_cb() + x = jax.random.normal(jax.random.PRNGKey(3), (4, 4)).astype(jnp.bfloat16) + self.assertEqual(gv._clip_in(x, cb).dtype, jnp.bfloat16) + + def test_bounds_are_stop_gradient(self): + # The clamp bound is read through jax.lax.stop_gradient at the use-site, so gradient wrt the bound + # value is exactly zero even when the clamp is active. Probe _clip_bound_value directly with a + # lightweight bound holder to avoid mutating an nnx Param inside a traced function. + class _B: + + def __init__(self, v): + self.value = v + + def loss(bound_val): + x = jnp.ones((4,), jnp.float32) * 10.0 # above the bound -> clamp active + hi = gv._clip_bound_value(_B(bound_val), jnp.float32) + return jnp.sum(jnp.clip(x, -100.0, hi)) + + g = jax.grad(loss)(jnp.asarray(2.5, jnp.float32)) + self.assertEqual(float(g), 0.0) + + +class ValidateBoundsTest(unittest.TestCase): + + def test_accepts_finite_ordered(self): + gv.validate_clip_bounds(_finite_cb(), "ok") # no raise + + def test_rejects_nan_sentinel(self): + with self.assertRaises(ValueError): + gv.validate_clip_bounds(gv._make_clip_state(), "nan") + + def test_rejects_inf(self): + cb = _finite_cb() + cb.input_max.value = jnp.asarray(np.inf, jnp.float32) + with self.assertRaises(ValueError): + gv.validate_clip_bounds(cb, "inf") + + def test_rejects_min_gt_max(self): + cb = _finite_cb(in_lo=3.0, in_hi=-3.0) # input_min > input_max + with self.assertRaises(ValueError): + gv.validate_clip_bounds(cb, "order") + + def test_none_is_noop(self): + self.assertIsNone(gv.validate_clip_bounds(None)) + + +class FreezeMaskTest(unittest.TestCase): + + def test_freeze_mask_polarity_and_count(self): + tree = { + "vision_encoder": { + "layer_0": { + "attention": { + "q_clip": {"input_min": 1.0, "input_max": 1.0, "output_min": 1.0, "output_max": 1.0}, + "query": {"kernel": 1.0}, + }, + "mlp": {"gate_clip": {"input_min": 1.0, "output_max": 1.0}, "wi_0": {"kernel": 1.0}}, + } + }, + "decoder": {"layer_0": {"norm": {"scale": 1.0}}}, + } + mask = gv.clip_optimizer_freeze_mask(tree) + flat = jax.tree_util.tree_flatten_with_path(mask)[0] + n_clip = 0 + for path, v in flat: + is_clip = gv._is_clip_bound_path(path) + # clip leaves -> False (frozen); everything else -> True (trainable) + self.assertEqual(bool(v), (not is_clip)) + if is_clip: + n_clip += 1 + self.assertEqual(n_clip, 6) # q_clip(4) + gate_clip(2) + + +class SymbolsTest(unittest.TestCase): + + def test_expected_counts_constants(self): + self.assertEqual(gv.EXPECTED_CLIP_PROJECTIONS, 112) + self.assertEqual(gv.EXPECTED_CLIP_BOUNDS, 448) + + def test_public_symbols_present(self): + for sym in ( + "validate_all_vision_clip_bounds", + "clip_optimizer_freeze_mask", + "Gemma4ClippedMlpBlock", + "Gemma4Attention", + ): + self.assertTrue(hasattr(gv, sym), sym) + + +class OptionSInvariantsTest(unittest.TestCase): + """M7: Option-S sentinel integrity + placeholder==pooled count invariants (pure validators).""" + + def test_valid_positions_pass(self): + pos = np.array([[[0, 0], [1, 0], [-1, -1], [-1, -1]]], dtype=np.int32) # 2 valid + 2 full-sentinel + ok, n_bad = gv.option_s_position_sentinel_ok(pos) + self.assertTrue(ok) + self.assertEqual(n_bad, 0) + gv.validate_option_s_positions(pos) # must not raise + + def test_mixed_sentinel_row_fails(self): + for bad_row in ([-1, 5], [5, -1]): + pos = np.array([[[0, 0], bad_row, [-1, -1]]], dtype=np.int32) + ok, n_bad = gv.option_s_position_sentinel_ok(pos) + self.assertFalse(ok, f"mixed row {bad_row} should be flagged") + self.assertEqual(n_bad, 1) + with self.assertRaises(ValueError): + gv.validate_option_s_positions(pos, where="test") + + def test_other_negative_coord_fails(self): + pos = np.array([[[0, 0], [-2, -2], [-1, -1]]], dtype=np.int32) # -2 is not the sentinel + ok, _n_bad = gv.option_s_position_sentinel_ok(pos) + self.assertFalse(ok) + + def test_pooled_matches_placeholder(self): + mask = np.array([True, True, True, False, False]) # 3 valid pooled tokens + ok, n_valid = gv.option_s_pooled_matches_placeholder(mask, 3) + self.assertTrue(ok) + self.assertEqual(n_valid, 3) + + def test_pooled_placeholder_mismatch_detected(self): + mask = np.array([True, True, True, False, False]) # 3 valid + ok, n_valid = gv.option_s_pooled_matches_placeholder(mask, 4) # placeholder count 4 != 3 + self.assertFalse(ok) + self.assertEqual(n_valid, 3) + + +# --------------------------------------------------------------------------- +# Gemma-4 E2B/E4B multimodal STATIC contract gate (configs/types.py). +# Consolidated here from the standalone gemma4_mm_contract_gate_test.py per review. +# --------------------------------------------------------------------------- + + +def _init_gate_config(overrides): + """Initialize a gemma4-e2b multimodal MaxTextConfig for the contract-gate tests.""" + base_yml = os.path.join(MAXTEXT_REPO_ROOT, "src", "maxtext", "configs", "base.yml") + argv = [ + "test", + base_yml, + "model_name=gemma4-e2b", + "use_multimodal=true", + "override_model_config=true", + "tokenizer_path=/tmp/unused", + "per_device_batch_size=1", + "scan_layers=false", + "enable_checkpointing=false", + "run_name=gate_test", + "steps=1", + "skip_jax_distributed_system=true", + ] + overrides + return pyconfig.initialize(argv) + + +class Gemma4MmContractGateTest(unittest.TestCase): + + def test_valid_e2b_mm_config_builds(self): + # Clipped linears on, identity PLE, causal image spans, fused off -> the HF-faithful contract. + cfg = _init_gate_config(["use_clipped_linears_for_vit=true"]) + self.assertEqual(cfg.model_name, "gemma4-e2b") + self.assertTrue(cfg.use_multimodal) + self.assertEqual(str(cfg.ple_pad_mode), "identity") + + def test_unknown_ple_pad_mode_hard_fails(self): + with self.assertRaises(Exception): + _init_gate_config(["use_clipped_linears_for_vit=true", "ple_pad_mode=bogus"]) + + def test_both_ple_pad_mode_is_valid_ablation_enum(self): + cfg = _init_gate_config(["use_clipped_linears_for_vit=true", "ple_pad_mode=both"]) + self.assertEqual(str(cfg.ple_pad_mode), "both") + + def test_bidirectional_image_attn_hard_fails(self): + # Gemma-4 E2B/E4B image spans are causal; bidirectional is a Gemma-3 / 26B / 31B feature. + with self.assertRaises(Exception): + _init_gate_config(["use_clipped_linears_for_vit=true", "use_bidirectional_image_attn=true"]) + + def test_fused_qkv_hard_fails(self): + with self.assertRaises(Exception): + _init_gate_config(["use_clipped_linears_for_vit=true", "fused_qkv=true"]) + + def test_fused_mlp_hard_fails(self): + with self.assertRaises(Exception): + _init_gate_config(["use_clipped_linears_for_vit=true", "fused_mlp=true"]) + + def test_clipped_linears_off_under_mm_hard_fails(self): + with self.assertRaises(Exception): + _init_gate_config(["use_clipped_linears_for_vit=false"]) + + def test_packing_hard_fails(self): + # Packed multimodal is unsupported for E2B/E4B in any mode (cross-doc image attention risk). + with self.assertRaises(Exception): + _init_gate_config(["use_clipped_linears_for_vit=true", "packing=true"]) + + if __name__ == "__main__": unittest.main() From 99e51a960d4b07d99b038247c2078968f5d8d1f5 Mon Sep 17 00:00:00 2001 From: lokic233 Date: Sat, 24 Oct 2026 21:40:50 -0700 Subject: [PATCH 15/26] Fix trainable_parameters_mask polarity in get_optimizer 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. --- src/maxtext/optimizers/optimizers.py | 11 +- tests/unit/optimizers_test.py | 145 +++++++++++++++++++++++++++ 2 files changed, 151 insertions(+), 5 deletions(-) diff --git a/src/maxtext/optimizers/optimizers.py b/src/maxtext/optimizers/optimizers.py index 1f84653300..b0bedf2712 100644 --- a/src/maxtext/optimizers/optimizers.py +++ b/src/maxtext/optimizers/optimizers.py @@ -236,9 +236,10 @@ def get_optimizer(config, learning_rate_schedule, model=None): ) # If a whitelist of trainable parameters is provided, freeze everything else. - # When trainable_parameters_mask is empty, freeze_mask_fn is None and all parameters are trained. + # When trainable_parameters_mask is empty, trainable_mask_fn is None and all parameters are trained. + # trainable_mask_fn returns True for leaves whose path matches the whitelist (trainable), False otherwise. trainable_patterns = getattr(config, "trainable_parameters_mask", None) - freeze_mask_fn = _get_path_mask_fn(trainable_patterns, match_returns_true=False) + trainable_mask_fn = _get_path_mask_fn(trainable_patterns, match_returns_true=True) # Gemma-4 vision clipped-linears: the 448 clip bounds are checkpoint-resident, immutable state and must # NEVER receive optimizer updates, weight decay, or momentum/variance slots. Freeze them via a leaf-PATH @@ -246,12 +247,12 @@ def get_optimizer(config, learning_rate_schedule, model=None): # a parameter is "trainable" only if it is trainable under the whitelist AND is not a clip bound. freeze_clip_bounds = bool(getattr(config, "use_clipped_linears_for_vit", False)) - if freeze_mask_fn is not None or freeze_clip_bounds: + if trainable_mask_fn is not None or freeze_clip_bounds: def _partition(params): # trainable_mask: True where trainable under the whitelist (all-True if no whitelist). - if freeze_mask_fn is not None: - trainable_mask = freeze_mask_fn(params) + if trainable_mask_fn is not None: + trainable_mask = trainable_mask_fn(params) else: trainable_mask = jax.tree_util.tree_map(lambda _: True, params) if freeze_clip_bounds: diff --git a/tests/unit/optimizers_test.py b/tests/unit/optimizers_test.py index 0057dab45c..19048fec5d 100644 --- a/tests/unit/optimizers_test.py +++ b/tests/unit/optimizers_test.py @@ -804,6 +804,151 @@ def learning_rate_schedule(step): self.assertFalse(jax.numpy.all(updates["layer1"]["kernel"] == 0)) +_ADAPTER = "adapter/kernel" +_BACKBONE = "backbone/kernel" +_VIT_QUERY = "vision_encoder/layer_0/attention/query/kernel" +_VIT_WI_0 = "vision_encoder/layer_0/mlp/wi_0/kernel" +_CLIP_BOUND_NAMES = ("input_min", "input_max", "output_min", "output_max") +_CLIP_BOUNDS = frozenset( + f"vision_encoder/layer_0/{block}/{name}" + for block in ("attention/q_clip", "mlp/gate_clip") + for name in _CLIP_BOUND_NAMES +) +_NON_CLIP = frozenset({_ADAPTER, _BACKBONE, _VIT_QUERY, _VIT_WI_0}) + + +def _adapter_backbone_vit_params(): + """Small params tree: an adapter, a backbone and two Gemma-4 ViT projections carrying scalar clip bounds.""" + + def clip(): + return {n: jnp.asarray(v, jnp.float32) for n, v in zip(_CLIP_BOUND_NAMES, (-2.0, 2.0, -3.0, 3.0))} + + return { + "adapter": {"kernel": jnp.ones((2, 2))}, + "backbone": {"kernel": jnp.ones((2, 2))}, + "vision_encoder": { + "layer_0": { + "attention": {"query": {"kernel": jnp.ones((2, 2))}, "q_clip": clip()}, + "mlp": {"wi_0": {"kernel": jnp.ones((2, 2))}, "gate_clip": clip()}, + } + }, + } + + +def _leaf_paths(tree): + return {jax.tree_util.keystr(p, simple=True, separator="/"): v for p, v in jax.tree_util.tree_leaves_with_path(tree)} + + +def _run_jitted_steps(opt, params, num_steps=2): + """Applies `num_steps` jitted optimizer steps with a constant non-zero gradient; returns (params, opt_state).""" + grads = jax.tree_util.tree_map(lambda x: jnp.full_like(x, 0.5), params) + opt_state = opt.init(params) + + @jax.jit + def step(p, s): + updates, s = opt.update(grads, s, p) + return optax.apply_updates(p, updates), s + + for _ in range(num_steps): + params, opt_state = step(params, opt_state) + return params, opt_state + + +def _adam_mu_slots(opt_state): + """Returns (allocated, masked): param paths with an allocated AdamW `mu` slot vs. an optax.MaskedNode slot.""" + allocated, masked = set(), set() + flat = jax.tree_util.tree_flatten_with_path(opt_state, is_leaf=lambda x: isinstance(x, optax.MaskedNode))[0] + for path, leaf in flat: + names = [getattr(k, "name", getattr(k, "key", None)) for k in path] + if "mu" not in names: + continue + param_path = "/".join(str(n) for n in names[names.index("mu") + 1 :]) + (masked if isinstance(leaf, optax.MaskedNode) else allocated).add(param_path) + return allocated, masked + + +class TrainableMaskAndClipBoundFreezeTest(parameterized.TestCase): + """trainable_parameters_mask (a whitelist) composed with the Gemma-4 ViT clip-bound freeze in get_optimizer. + + Checks the parameters actually updated by jitted AdamW steps (weight decay > 0, so any leaf that is not frozen + moves) and the optimizer-state allocation: frozen leaves are routed to optax.set_to_zero() through + optax.multi_transform, so they get zero updates and no AdamW moment slots (optax.MaskedNode), while trainable + leaves get allocated slots. + """ + + def _get_optimizer(self, trainable_mask, use_clipped_linears_for_vit): + """Builds (config, get_optimizer(config)) for AdamW with weight decay and a constant learning rate of 1.0.""" + argv = [ + "", + get_test_config_path(), + "run_name=test_trainable_mask_clip_freeze", + "opt_type=adamw", + "adam_weight_decay=0.1", + f"trainable_parameters_mask={trainable_mask}", + f"use_clipped_linears_for_vit={use_clipped_linears_for_vit}", + ] + config = pyconfig.initialize(argv) + return config, optimizers.get_optimizer(config, lambda step: 1.0) + + def _assert_trained_exactly(self, opt, expected_trainable): + params = _adapter_backbone_vit_params() + new_params, opt_state = _run_jitted_steps(opt, params) + before, after = _leaf_paths(params), _leaf_paths(new_params) + self.assertEqual(set(before), _NON_CLIP | _CLIP_BOUNDS) + changed = {k for k in before if not jnp.array_equal(before[k], after[k])} + self.assertEqual(changed, set(expected_trainable)) + allocated, masked = _adam_mu_slots(opt_state) + self.assertEqual(allocated, set(expected_trainable)) + self.assertEqual(masked, set(before) - set(expected_trainable)) + + def test_whitelist_trains_only_matching_params(self): + """use_clipped_linears_for_vit=False: only whitelisted leaves train (the pre-existing whitelist contract).""" + _, opt = self._get_optimizer(["adapter"], False) + self._assert_trained_exactly(opt, {_ADAPTER}) + + @parameterized.named_parameters( + ("adapter_only", ["adapter"], {_ADAPTER}), + ("whitelist_covers_vit", ["adapter", "vision_encoder"], {_ADAPTER, _VIT_QUERY, _VIT_WI_0}), + ("whitelist_names_clip_bounds", ["adapter", "_clip"], {_ADAPTER}), + ) + def test_whitelist_with_clip_freeze(self, trainable_mask, expected_trainable): + """Whitelisted leaves train, the rest stay frozen, and clip bounds stay frozen even when whitelisted.""" + _, opt = self._get_optimizer(trainable_mask, True) + self._assert_trained_exactly(opt, expected_trainable) + + def test_clip_freeze_without_whitelist(self): + """No whitelist: everything trains except the clip bounds.""" + _, opt = self._get_optimizer([], True) + self._assert_trained_exactly(opt, _NON_CLIP) + + def test_both_flags_off_returns_unwrapped_optimizer(self): + """No whitelist and no clip freeze: get_optimizer returns the base optimizer unwrapped; every leaf trains.""" + _, opt = self._get_optimizer([], False) + params = _adapter_backbone_vit_params() + self.assertNotIsInstance(opt.init(params), optax.PartitionState) + new_params, _ = _run_jitted_steps(opt, params) + before, after = _leaf_paths(params), _leaf_paths(new_params) + self.assertTrue(all(not jnp.array_equal(before[k], after[k]) for k in before)) + + def test_whitelist_without_clip_freeze_matches_original_composition(self): + """use_clipped_linears_for_vit=False: the whitelist-only optimizer equals its definition prior to the clip freeze.""" + patterns = ["adapter"] + config, opt = self._get_optimizer(patterns, False) + _, base_opt = self._get_optimizer([], False) + self.assertFalse(config.use_clipped_linears_for_vit) + freeze_mask_fn = optimizers._get_path_mask_fn(patterns, match_returns_true=False) # pylint: disable=protected-access + reference = optax.multi_transform( + {"trainable": base_opt, "frozen": optax.set_to_zero()}, + lambda p: jax.tree_util.tree_map(lambda x: "frozen" if x else "trainable", freeze_mask_fn(p)), + ) + params = _adapter_backbone_vit_params() + got = _run_jitted_steps(opt, params) + ref = _run_jitted_steps(reference, params) + self.assertEqual(jax.tree_util.tree_structure(got), jax.tree_util.tree_structure(ref)) + for got_leaf, ref_leaf in zip(jax.tree_util.tree_leaves(got), jax.tree_util.tree_leaves(ref)): + self.assertTrue(jnp.array_equal(got_leaf, ref_leaf)) + + class SkipStepOnSpikesTest(parameterized.TestCase): """Tests for the skip_step_on_spikes optimizer wrapper.""" From 19e4d9be7ed639597ee8eda38cda5897e2b13bc2 Mon Sep 17 00:00:00 2001 From: lokic233 Date: Sat, 24 Oct 2026 22:48:17 -0700 Subject: [PATCH 16/26] Gemma-4 vision: neutral wording in clipped-linears comments 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. --- src/maxtext/layers/nnx_decoders.py | 2 +- src/maxtext/models/gemma4_vision.py | 7 +++---- tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh | 3 +-- tests/unit/gemma4_small_layers_test.py | 2 +- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/maxtext/layers/nnx_decoders.py b/src/maxtext/layers/nnx_decoders.py index d27f30da84..939e88c1c5 100644 --- a/src/maxtext/layers/nnx_decoders.py +++ b/src/maxtext/layers/nnx_decoders.py @@ -2285,7 +2285,7 @@ def _apply_gemma4_small_layers( # leaving the context/projection path reading the merged image features — this matches HF # Transformers 5.9.0 (get_per_layer_inputs ignores inputs_embeds when input_ids is given). The # 'both' mode additionally overwrites the context path with the pad embedding; this is HF-DIVERGENT - # and provided only for ablation (see M9 ablation matrix). Enum-validated in configs/types.py. + # and provided only for ablation. Enum-validated in configs/types.py. if str(getattr(cfg, "ple_pad_mode", "identity")) == "both": if shared_embedding is None: raise ValueError( diff --git a/src/maxtext/models/gemma4_vision.py b/src/maxtext/models/gemma4_vision.py index b65836b39c..4c0a7382a7 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -33,7 +33,7 @@ # ============================================================================= -# Gemma-4 vision clipped-linears (Navi upstream contribution) +# Gemma-4 vision clipped-linears # ----------------------------------------------------------------------------- # The Gemma-4 E2B/E4B vision tower ships per-projection activation clip bounds in # the reference (HF) checkpoint: for each of the 7 vision projections @@ -41,9 +41,8 @@ # blocks, a scalar {input_min,input_max,output_min,output_max} = 16*7*4 = 448 # checkpoint tensors. The reference forward clamps each projection's input by # [input_min,input_max] and its output by [output_min,output_max]. Omitting the -# clamps produces large activation drift in the image span (empirically KL 4-17 -# on a 340-token teacher-forced parity harness), because a handful of vision -# activations blow up without the trained saturation. Upstream MaxText marks +# clamps produces large activation drift in the image span, because a handful of +# vision activations blow up without the trained saturation. Upstream MaxText marks # E2B/E4B multimodal "not yet supported" and does not model these bounds. # # This module adds them as OPT-IN, checkpoint-resident, NON-TRAINABLE scalars, diff --git a/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh b/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh index 208e2dde00..e19bdab609 100755 --- a/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh +++ b/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh @@ -53,8 +53,7 @@ python3 -m tests.assets.logits_generation.generate_hf_golden_logits \ --apply-chat-template --output-format=json # Step 3: MaxText vs HF golden-logit parity on the image path. -# Gate mirrors the PR's post_image parity (max_KL << 0.03 observed at 4.29e-05); we use the -# conservative repo default multimodal gate here. +# Gated on the conservative repo default multimodal KL threshold. python3 -m tests.utils.forward_pass_logit_checker "${MAXTEXT_CONFIGS_DIR:-${MAXTEXT_REPO_ROOT:-$PWD}/src/maxtext/configs}"/base.yml \ tokenizer_path=${TOKENIZER_PATH} \ load_parameters_path=${MAXTEXT_CKPT_PATH} \ diff --git a/tests/unit/gemma4_small_layers_test.py b/tests/unit/gemma4_small_layers_test.py index 2413044745..199b6069ee 100644 --- a/tests/unit/gemma4_small_layers_test.py +++ b/tests/unit/gemma4_small_layers_test.py @@ -535,7 +535,7 @@ def test_public_symbols_present(self): class OptionSInvariantsTest(unittest.TestCase): - """M7: Option-S sentinel integrity + placeholder==pooled count invariants (pure validators).""" + """Option-S sentinel integrity + placeholder==pooled count invariants (pure validators).""" def test_valid_positions_pass(self): pos = np.array([[[0, 0], [1, 0], [-1, -1], [-1, -1]]], dtype=np.int32) # 2 valid + 2 full-sentinel From 0aecb7a217ce23d7e4b20fcfe02372d1b1f7ede3 Mon Sep 17 00:00:00 2001 From: lokic233 Date: Sun, 25 Oct 2026 00:14:58 -0700 Subject: [PATCH 17/26] Gemma-4 vision: describe pad-row zeroing as design intent 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. --- src/maxtext/models/gemma4_vision.py | 14 ++++++-------- .../tpu/gemma4/e2b/test_gemma4_multimodal.sh | 2 +- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/maxtext/models/gemma4_vision.py b/src/maxtext/models/gemma4_vision.py index 4c0a7382a7..0e03126827 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -1036,14 +1036,12 @@ def __call__( is_pad = (positions_xy == -1).all(axis=-1) # [B*N, L] decoder_segment_ids = jnp.where(is_pad, 2, 1).astype(jnp.int32) - # Sanitize padded-patch rows to zero BEFORE attention. Segment masking already prevents pad patches - # from influencing valid patches' attention outputs, and pooling excludes pad positions — so for FINITE - # pad content the valid outputs are provably invariant (verified byte-identical under 1e6 garbage pad). - # However, attention computes q/k/v on ALL rows before masking, so a NON-FINITE (NaN/Inf) pad patch would - # produce NaN q/k/v and leak through the softmax normalization into valid rows (NaN*0=NaN). Zeroing pad - # rows here makes the isolation hold for arbitrary (incl. non-finite) pad content without changing any - # valid output. This is defense-in-depth for malformed processor output; the frozen processor emits finite - # pad, which was already invariant. + # Sanitize padded-patch rows to zero BEFORE attention. By design, segment masking keeps pad patches out + # of the valid patches' attention outputs and pooling excludes pad positions, so the valid outputs are + # not meant to depend on finite pad content. Attention still computes q/k/v on ALL rows before masking, + # though, so a NON-FINITE (NaN/Inf) pad patch would produce NaN q/k/v that can leak through the softmax + # normalization into valid rows (NaN*0=NaN). Zeroing pad rows here extends that isolation to arbitrary + # pad content, including non-finite values. This is a defensive guard against malformed processor output. x = jnp.where(is_pad[..., None], jnp.zeros_like(x), x) for i in range(self.config.num_hidden_layers_for_vit): diff --git a/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh b/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh index e19bdab609..d65668446a 100755 --- a/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh +++ b/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh @@ -53,7 +53,7 @@ python3 -m tests.assets.logits_generation.generate_hf_golden_logits \ --apply-chat-template --output-format=json # Step 3: MaxText vs HF golden-logit parity on the image path. -# Gated on the conservative repo default multimodal KL threshold. +# Uses the same --max_kl_div threshold as the Gemma-4 convert_gemma4.sh checks. python3 -m tests.utils.forward_pass_logit_checker "${MAXTEXT_CONFIGS_DIR:-${MAXTEXT_REPO_ROOT:-$PWD}/src/maxtext/configs}"/base.yml \ tokenizer_path=${TOKENIZER_PATH} \ load_parameters_path=${MAXTEXT_CKPT_PATH} \ From d52f968207d283bd22912448c5ed745301c199ed Mon Sep 17 00:00:00 2001 From: nuinashco Date: Fri, 6 Nov 2026 00:32:10 +0000 Subject: [PATCH 18/26] fix(testing): convert with clip bounds in the E2B multimodal E2E script --- tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh b/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh index d65668446a..9d9289d476 100755 --- a/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh +++ b/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh @@ -40,6 +40,7 @@ python3 -m maxtext.checkpoint_conversion.to_maxtext "${MAXTEXT_CONFIGS_DIR:-${MA --hf_model_path=${HF_MODEL} \ base_output_directory=${MODEL_BUCKET}/${MODEL_VARIATION}/converted_mm/${idx} \ use_multimodal=true \ + use_clipped_linears_for_vit=true \ scan_layers=${USE_SCAN_LAYERS} export MAXTEXT_CKPT_PATH=${MODEL_BUCKET}/${MODEL_VARIATION}/converted_mm/${idx}/0/items From 9a4b2efbe7289c062e93c46408e4fc553ff76276 Mon Sep 17 00:00:00 2001 From: nuinashco Date: Fri, 6 Nov 2026 01:37:35 +0000 Subject: [PATCH 19/26] fix(config): keep packing on for text-only Gemma-4 E2B/E4B runs --- src/maxtext/configs/models/gemma4-e2b.yml | 1 - src/maxtext/configs/models/gemma4-e4b.yml | 1 - src/maxtext/configs/types.py | 11 ----------- tests/unit/gemma4_small_layers_test.py | 14 +++++++++++--- 4 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/maxtext/configs/models/gemma4-e2b.yml b/src/maxtext/configs/models/gemma4-e2b.yml index 502e84737b..c4a4b26c26 100644 --- a/src/maxtext/configs/models/gemma4-e2b.yml +++ b/src/maxtext/configs/models/gemma4-e2b.yml @@ -66,4 +66,3 @@ ple_pad_substitute_image_rows: True ple_pad_mode: "identity" image_placeholder_token_id: 258880 ple_pad_token_id: 0 -packing: false # Gemma-4 E2B/E4B multimodal does not support packed image spans (see configs/types.py gate) diff --git a/src/maxtext/configs/models/gemma4-e4b.yml b/src/maxtext/configs/models/gemma4-e4b.yml index d2cf5bdd7e..cd752ae22b 100644 --- a/src/maxtext/configs/models/gemma4-e4b.yml +++ b/src/maxtext/configs/models/gemma4-e4b.yml @@ -67,4 +67,3 @@ ple_pad_substitute_image_rows: True ple_pad_mode: "identity" image_placeholder_token_id: 258880 ple_pad_token_id: 0 -packing: false # Gemma-4 E2B/E4B multimodal does not support packed image spans (see configs/types.py gate) diff --git a/src/maxtext/configs/types.py b/src/maxtext/configs/types.py index dafea22dbb..361c675f54 100644 --- a/src/maxtext/configs/types.py +++ b/src/maxtext/configs/types.py @@ -6381,17 +6381,6 @@ def _non_batch_devices(num_devices: int, num_slices: int) -> int: f"{self.model_name} multimodal clipped-linears require fused_mlp=False " "(distinct gate/up/down activation clip bounds must be applied per-projection)." ) - # (e) Sequence packing is not supported for Gemma-4 E2B/E4B multimodal in ANY training mode. The stock - # data pipeline does not pack image spans, and packing image-bearing examples together would risk - # cross-document image attention and PLE image-row substitution bleeding across segment boundaries. - # MaxText already forbids packing for multimodal SFT; extend that to every mode for these models - # (fail closed rather than silently produce cross-doc image attention). - if bool(getattr(self, "packing", False)): - raise ValueError( - f"{self.model_name} multimodal does not support sequence packing (packing=True). The stock data " - "pipeline does not pack image spans; packing image-bearing examples risks cross-document image " - "attention and PLE image-row substitution across segment boundaries. Set packing=False." - ) valid_mm_models = ( "gemma3-4b", "gemma3-12b", diff --git a/tests/unit/gemma4_small_layers_test.py b/tests/unit/gemma4_small_layers_test.py index d1d7b408dd..e2a19df894 100644 --- a/tests/unit/gemma4_small_layers_test.py +++ b/tests/unit/gemma4_small_layers_test.py @@ -634,9 +634,17 @@ def test_clipped_linears_off_under_mm_hard_fails(self): _init_gate_config(["use_clipped_linears_for_vit=false"]) def test_packing_hard_fails(self): - # Packed multimodal is unsupported for E2B/E4B in any mode (cross-doc image attention risk). - with self.assertRaises(Exception): - _init_gate_config(["use_clipped_linears_for_vit=true", "packing=true"]) + # Only multimodal SFT loads images; packing there is rejected, as for every multimodal model. + with self.assertRaisesRegex(Exception, "packing"): + _init_gate_config( + ["use_clipped_linears_for_vit=true", "use_sft=true", "sft_train_on_completion_only=true", "packing=true"] + ) + + def test_text_only_keeps_packing(self): + for model in ("gemma4-e2b", "gemma4-e4b"): + for packing in ({}, {"packing": True}): + config = pyconfig.initialize(["", _BASE_CONFIG_PATH], model_name=model, scan_layers=False, **packing) + self.assertTrue(config.packing, msg=f"{model} {packing}") if __name__ == "__main__": From 525518eb8560024035987c1460930293d4f8ca05 Mon Sep 17 00:00:00 2001 From: nuinashco Date: Tue, 10 Nov 2026 02:07:07 +0000 Subject: [PATCH 20/26] feat(nnx): add UntrainableParam for weights that are never trained --- .../checkpoint_conversion/to_maxtext.py | 4 +- src/maxtext/common/checkpointing.py | 4 +- src/maxtext/common/common_types.py | 18 ++ src/maxtext/layers/initializers.py | 4 +- src/maxtext/layers/nnx_wrappers.py | 4 +- src/maxtext/optimizers/optimizers.py | 46 ++++- .../post_train/distillation/train_distill.py | 14 +- .../trainers/post_train/rl/train_rl.py | 2 +- .../trainers/post_train/rl/utils_rl.py | 10 +- tests/post_training/unit/rl_utils_test.py | 17 ++ .../post_training/unit/train_distill_test.py | 23 +++ tests/unit/optimizers_test.py | 83 ++++++++ tests/unit/untrainable_param_test.py | 177 ++++++++++++++++++ 13 files changed, 388 insertions(+), 18 deletions(-) create mode 100644 tests/unit/untrainable_param_test.py diff --git a/src/maxtext/checkpoint_conversion/to_maxtext.py b/src/maxtext/checkpoint_conversion/to_maxtext.py index 8b321f9e71..71f585bcc9 100644 --- a/src/maxtext/checkpoint_conversion/to_maxtext.py +++ b/src/maxtext/checkpoint_conversion/to_maxtext.py @@ -60,9 +60,9 @@ import absl import ml_dtypes from flax import nnx -from flax.nnx import variablelib from huggingface_hub import hf_hub_download, list_repo_files import jax +from maxtext.common.common_types import variable_collection_name from maxtext.configs import pyconfig from maxtext.configs.types import DType from maxtext.checkpoint_conversion.utils.hf_model_configs import HF_MODEL_CONFIGS @@ -419,7 +419,7 @@ def get_maxtext_model_info(config): for path, variable in nnx.to_flat_state(nnx.state(abstract_model)): if isinstance(variable, nnx.RngState): continue - node = abstract_params_tree.setdefault(variablelib.variable_name_from_type(type(variable), allow_register=True), {}) + node = abstract_params_tree.setdefault(variable_collection_name(type(variable)), {}) *parents, name = param_key_parts_from_path(path) for part in parents: node = node.setdefault(part, {}) diff --git a/src/maxtext/common/checkpointing.py b/src/maxtext/common/checkpointing.py index 881df23425..de382223e6 100644 --- a/src/maxtext/common/checkpointing.py +++ b/src/maxtext/common/checkpointing.py @@ -24,7 +24,6 @@ from etils import epath from flax import nnx -from flax.nnx import variablelib from flax import struct @@ -39,6 +38,7 @@ from maxtext.common import grain_utility from maxtext.common import snapshotting from maxtext.common import train_state_nnx +from maxtext.common.common_types import variable_collection_name from maxtext.input_pipeline import multihost_dataloading from maxtext.input_pipeline import synthetic_data_processing from maxtext.layers import quantizations @@ -1176,7 +1176,7 @@ def load_params_from_path( collection_leaves = collections.defaultdict(dict) for path_tuple, leaf in nnx.to_flat_state(abstract_unboxed_params): if isinstance(leaf, nnx.Variable): - col = variablelib.variable_name_from_type(leaf.type, allow_register=True) + col = variable_collection_name(leaf.type) val = leaf.get_value() if hasattr(leaf, "get_value") else leaf else: col = "params" diff --git a/src/maxtext/common/common_types.py b/src/maxtext/common/common_types.py index dca5c3bc33..f885c09356 100644 --- a/src/maxtext/common/common_types.py +++ b/src/maxtext/common/common_types.py @@ -19,8 +19,11 @@ import numpy as np +import jax import jax.numpy as jnp +from flax import nnx from flax import struct +from flax.nnx import variablelib Config = Any @@ -30,6 +33,21 @@ Shape = Sequence[int] +class UntrainableParam(nnx.Param): # pylint: disable=abstract-method + """A model weight saved and loaded like `nnx.Param`, with no gradient, optimizer update or weight decay.""" + + def get_value(self, **kwargs): + value = super().get_value(**kwargs) + return jax.lax.stop_gradient(value) if isinstance(value, jax.Array) else value + + +def variable_collection_name(variable_type: type[nnx.Variable]) -> str: + """Returns the checkpoint collection of a Variable type; UntrainableParam is stored with the regular params.""" + if issubclass(variable_type, UntrainableParam): + return "params" + return variablelib.variable_name_from_type(variable_type, allow_register=True) + + def is_fp8_dtype(dtype: Any) -> bool: """Checks whether a dtype is FP8.""" return dtype in ( diff --git a/src/maxtext/layers/initializers.py b/src/maxtext/layers/initializers.py index 83674225d2..b44bad1698 100644 --- a/src/maxtext/layers/initializers.py +++ b/src/maxtext/layers/initializers.py @@ -23,7 +23,7 @@ from flax import nnx from aqt.jax.v2 import aqt_tensor -from maxtext.common.common_types import Array, DType, Shape, PRNGKey, is_fp8_dtype +from maxtext.common.common_types import Array, DType, Shape, PRNGKey, UntrainableParam, is_fp8_dtype Initializer = Callable[[PRNGKey, Shape, DType], Array] InitializerAxis = int | tuple[int, ...] @@ -108,7 +108,7 @@ def variable_to_logically_partitioned(variable: nnx.Variable): if out_sharding is not None: if nnx.PARTITION_NAME in metadata: partition_name = metadata[nnx.PARTITION_NAME] - scan_axis = metadata.get("param_scan_axis", 0) if variable.type == nnx.Param else 0 + scan_axis = metadata.get("param_scan_axis", 0) if variable.type in (nnx.Param, UntrainableParam) else 0 sharding_list = [out_sharding] if isinstance(out_sharding, str) else list(out_sharding) if partition_name not in sharding_list: diff --git a/src/maxtext/layers/nnx_wrappers.py b/src/maxtext/layers/nnx_wrappers.py index 584e34c3e9..05b416ff85 100644 --- a/src/maxtext/layers/nnx_wrappers.py +++ b/src/maxtext/layers/nnx_wrappers.py @@ -35,6 +35,8 @@ from jax import tree_util as jtu import qwix +from maxtext.common.common_types import variable_collection_name + M = tp.TypeVar("M", bound=Module) @@ -624,7 +626,7 @@ def _update_variables(self, module): # group state by collection for path, leaf in nnx.to_flat_state(state): type_ = leaf.type if isinstance(leaf, nnx.Variable) else type(leaf) - collection = variablelib.variable_name_from_type(type_, allow_register=True) + collection = variable_collection_name(type_) if collection not in collection_flat_state: collection_flat_state[collection] = [] collection_flat_state[collection].append((path, leaf)) diff --git a/src/maxtext/optimizers/optimizers.py b/src/maxtext/optimizers/optimizers.py index 7a9d0e07ad..da4c906477 100644 --- a/src/maxtext/optimizers/optimizers.py +++ b/src/maxtext/optimizers/optimizers.py @@ -16,12 +16,13 @@ """Utils that are only interesting to MaxText.""" import re +from flax import nnx import jax import jax.numpy as jnp import optax from optax.contrib._muon import muon as optax_muon -from maxtext.common.common_types import DecoderBlockType +from maxtext.common.common_types import DecoderBlockType, UntrainableParam from maxtext.optimizers.muon import muon as maxtext_muon from maxtext.utils import max_logging from maxtext.utils.muon_utils import get_muon_weight_dimension_numbers @@ -52,6 +53,43 @@ def get_adamw_mask(config): return get_path_mask_fn(config.adamw_mask, match_returns_true=False) +def untrainable_paths(model): + """Paths ("a/b/c") of `model`'s UntrainableParam weights; empty unless `model` is an NNX module.""" + if not isinstance(model, nnx.Module): + return frozenset() + untrainable = nnx.to_flat_state(nnx.state(model, UntrainableParam)) + return frozenset("/".join(str(key) for key in path) for path, _ in untrainable) + + +def _leaf_path(path): + """Path as "a/b/c". At init a leaf is still inside its nnx.Variable, which adds a trailing `value` key.""" + if path and isinstance(path[-1], jax.tree_util.GetAttrKey) and path[-1].name == "value": + path = path[:-1] + return jax.tree_util.keystr(path, simple=True, separator="/") + + +def freeze_params(tx, frozen_paths): + """Wraps `tx` so the weights at `frozen_paths` get no update, weight decay or optimizer state.""" + if frozen_paths: + + def labels(params): + return jax.tree_util.tree_map_with_path( + lambda path, _: "frozen" if _leaf_path(path) in frozen_paths else "trainable", params + ) + + tx = optax.multi_transform({"trainable": tx, "frozen": optax.set_to_zero()}, labels) + + def init(params): + # An optimizer built without the model would otherwise apply weight decay to these weights. + for path, variable in jax.tree_util.tree_leaves_with_path(params, is_leaf=lambda x: isinstance(x, nnx.Variable)): + name = _leaf_path(path) + if isinstance(variable, UntrainableParam) and name not in frozen_paths: + raise ValueError(f"UntrainableParam weights would be trained: {name}. Pass the model to get_optimizer.") + return tx.init(params) + + return tx._replace(init=init) + + def _compute_rolling_stats(arr: jax.Array, count: jax.Array, interval: int): """Computes mean and unbiased std (Bessel's correction) over a rolling window.""" valid_elements = jnp.minimum(count, interval) @@ -177,8 +215,8 @@ def skip_update(): return optax.GradientTransformationExtraArgs(init_fn, update_fn) -def get_optimizer(config, learning_rate_schedule, model=None, mesh=None): - """Create optimizer.""" +def get_optimizer(config, learning_rate_schedule, model=None, mesh=None, frozen_paths=None): + """Create optimizer. `frozen_paths` overrides `untrainable_paths(model)`, for callers that run under jit.""" if config.opt_type == "adamw": # Create AdamW Optimizer following Llama2's training details, see https://arxiv.org/pdf/2307.09288.pdf section 2.2 base_opt = optax.adamw( @@ -259,6 +297,8 @@ def get_optimizer(config, learning_rate_schedule, model=None, mesh=None): else: raise ValueError(f"{config.opt_type=} is not a supported.") + base_opt = freeze_params(base_opt, untrainable_paths(model) if frozen_paths is None else frozen_paths) + # Apply `trainable_parameters_mask` before `skip_step_on_spikes` so `skip_step_on_spikes` # stays the outermost transformation: callers expect `opt_state` to be a top-level dict # exposing `opt_state["is_skipped"]` (whereas `optax.multi_transform` wraps state in diff --git a/src/maxtext/trainers/post_train/distillation/train_distill.py b/src/maxtext/trainers/post_train/distillation/train_distill.py index efcdefa7fc..63e0e35c83 100644 --- a/src/maxtext/trainers/post_train/distillation/train_distill.py +++ b/src/maxtext/trainers/post_train/distillation/train_distill.py @@ -82,7 +82,7 @@ # ----------------------------------------------------------------------------- -def get_distillation_optimizer(config, max_train_steps): +def get_distillation_optimizer(config, max_train_steps, model=None): """Creates a custom optimizer for distillation that enables Learning Rate logging. This function constructs an optax optimizer using standard MaxText settings but @@ -95,6 +95,7 @@ def get_distillation_optimizer(config, max_train_steps): `learning_rate`, `adam_b1`, `opt_type`, `gradient_clipping_threshold`). max_train_steps: The total number of training steps, used to calculate the warmup and cosine decay schedule. + model: The student model, whose UntrainableParam weights are frozen. Returns: An optax optimizer that: @@ -116,11 +117,14 @@ def get_distillation_optimizer(config, max_train_steps): end_value=config.learning_rate_final_fraction * config.learning_rate, ) + # inject_hyperparams reruns the factory inside jit, so read the model once here. + frozen_paths = optimizers.untrainable_paths(model) + # 2. Define Factory (Required for inject_hyperparams) def optimizer_factory(learning_rate): # Reuse MaxText's standard logic to create the base optimizer. # We pass 'learning_rate' (which is the injected schedule) directly. - opt = optimizers.get_optimizer(config, learning_rate, model=None) + opt = optimizers.get_optimizer(config, learning_rate, model=None, frozen_paths=frozen_paths) # Apply Gradient Clipping if config.gradient_clipping_threshold > 0: @@ -595,12 +599,14 @@ def build_training_components( teacher_config: pyconfig.HyperParameters, is_offline: bool = False, offline_data_dir: str | None = None, + student_model: nnx.Module | None = None, ): """Builds and returns the strategy, optimizer, and training config objects. Args: student_config: Configuration object for the Student model. teacher_config: Configuration object for the Teacher model. + student_model: The Student model, whose UntrainableParam weights the optimizer freezes. Returns: A tuple of (DistillationStrategy, Optimizer, TrainingConfig). @@ -642,7 +648,7 @@ def build_training_components( ) # Prepare optimizer - optimizer = get_distillation_optimizer(student_config, student_config.steps) + optimizer = get_distillation_optimizer(student_config, student_config.steps, model=student_model) checkpointing_options = checkpoint.CheckpointManagerOptions( save_interval_steps=student_config.checkpoint_period, @@ -769,7 +775,7 @@ def student_freeze_param_fn(path) -> bool: with maybe_record_goodput(goodput_recorder, GoodputEvent.TRAINING_PREPARATION): # Build Training Components strategy, optimizer, train_config = build_training_components( - student_config, teacher_config, is_offline, offline_data_dir + student_config, teacher_config, is_offline, offline_data_dir, student_model=student_model ) # 3. Initialize Trainer diff --git a/src/maxtext/trainers/post_train/rl/train_rl.py b/src/maxtext/trainers/post_train/rl/train_rl.py index 573c4b2deb..6df384ac7c 100644 --- a/src/maxtext/trainers/post_train/rl/train_rl.py +++ b/src/maxtext/trainers/post_train/rl/train_rl.py @@ -434,7 +434,7 @@ def create_rl_components( # pylint: disable=too-many-positional-arguments ): """Setup RL cluster, trainer, and optimizer.""" # Setup optimizer - optimizer = utils_rl.get_optimizer(trainer_config) + optimizer = utils_rl.get_optimizer(trainer_config, actor_model) # Setup checkpointing if trainer_config.enable_checkpointing: diff --git a/src/maxtext/trainers/post_train/rl/utils_rl.py b/src/maxtext/trainers/post_train/rl/utils_rl.py index b66eca1c3a..534e91c296 100644 --- a/src/maxtext/trainers/post_train/rl/utils_rl.py +++ b/src/maxtext/trainers/post_train/rl/utils_rl.py @@ -31,6 +31,7 @@ from tunix.rl.agentic.parser.chat_template_parser import parser as agentic_chat_template_parser +from maxtext.optimizers import optimizers from maxtext.trainers.post_train.rl.math_verify_pool import math_verify_pool, verify_math_worker from maxtext.utils import max_logging @@ -606,8 +607,8 @@ def check_correctness(extracted_response: str, acceptable_answers: list[str], tm return False, is_partially_correct -def get_optimizer(tmvp_config: Any) -> optax.GradientTransformation: - """Function to obtain an optax optimizer, currently we use adamw. +def get_optimizer(tmvp_config: Any, model: Any = None) -> optax.GradientTransformation: + """Function to obtain an optax optimizer, currently we use adamw. `model`'s UntrainableParam weights are frozen. The LR schedule length defaults to the actual RL run length (`max_train_steps` = num_batches * num_iterations * train_fraction * @@ -642,6 +643,9 @@ def get_optimizer(tmvp_config: Any) -> optax.GradientTransformation: end_value=0.0, ) + # inject_hyperparams reruns make_optimizer inside jit, so read the model once here. + frozen_paths = optimizers.untrainable_paths(model) + # TODO: @mazumdera: try optimizer offloading with adamw # Add gradient clipping if specified # Grad clipping to prevent large gradients. We find this @@ -658,7 +662,7 @@ def make_optimizer(learning_rate): weight_decay=tmvp_config.adam_weight_decay, ) ) - return optax.chain(*transforms) + return optimizers.freeze_params(optax.chain(*transforms), frozen_paths) # Wrap the entire optimizer (including gradient clipping) with # inject_hyperparams so opt_state.hyperparams['learning_rate'] is at the diff --git a/tests/post_training/unit/rl_utils_test.py b/tests/post_training/unit/rl_utils_test.py index 1d4b477ae1..8bcba2d2ee 100644 --- a/tests/post_training/unit/rl_utils_test.py +++ b/tests/post_training/unit/rl_utils_test.py @@ -331,6 +331,23 @@ def test_returns_optimizer_with_clipping(self): state = opt.init(params) self.assertIn("learning_rate", state.hyperparams) + def test_weight_decay_skips_untrainable_params(self): + """Zero gradients leave weight decay as the only force, which must not reach an UntrainableParam.""" + import jax # pylint: disable=import-outside-toplevel + import jax.numpy as jnp # pylint: disable=import-outside-toplevel + from flax import nnx # pylint: disable=import-outside-toplevel + from maxtext.common.common_types import UntrainableParam # pylint: disable=import-outside-toplevel + + config = self._make_optimizer_config() + config.learning_rate, config.adam_weight_decay, config.warmup_steps_fraction = 1.0, 0.5, 0.0 + model = nnx.Dict(kernel=nnx.Param(jnp.ones(3)), bound=UntrainableParam(jnp.ones(3))) + optimizer = nnx.Optimizer(model, utils_rl.get_optimizer(config, model), wrt=nnx.Param) + + optimizer.update(model, jax.tree_util.tree_map(jnp.zeros_like, nnx.state(model, nnx.Param))) + + self.assertFalse(jnp.array_equal(model.kernel[...], jnp.ones(3))) + self.assertTrue(jnp.array_equal(model.bound[...], jnp.ones(3))) + class TestFormatMaxTextMessages(unittest.TestCase): """Tests for utils_rl.format_maxtext_messages.""" diff --git a/tests/post_training/unit/train_distill_test.py b/tests/post_training/unit/train_distill_test.py index 8f76eae6f3..4fca75add4 100644 --- a/tests/post_training/unit/train_distill_test.py +++ b/tests/post_training/unit/train_distill_test.py @@ -35,6 +35,7 @@ from absl.testing import absltest # Import the module under test +from maxtext.common.common_types import UntrainableParam from maxtext.trainers.post_train.distillation import train_distill from maxtext.trainers.post_train.distillation import distillation_utils from maxtext.configs import pyconfig @@ -431,6 +432,28 @@ def test_optimizer_factory(self): with self.assertRaisesRegex(ValueError, "Muon optimizer is not currently supported"): train_distill.get_distillation_optimizer(muon_config, max_train_steps=100) + def test_optimizer_weight_decay_skips_untrainable_params(self): + """Zero gradients leave weight decay as the only force, which must not reach an UntrainableParam.""" + config = pyconfig.initialize( + ["", get_test_config_path()], + base_output_directory=self.test_dir, + run_name="optimizer_untrainable_test", + learning_rate=1.0, + opt_type="adamw", + adam_weight_decay=0.5, + gradient_clipping_threshold=0.0, + warmup_steps_fraction=0.0, + learning_rate_final_fraction=0.1, + ) + model = nnx.Dict(kernel=nnx.Param(jnp.ones(3)), bound=UntrainableParam(jnp.ones(3))) + tx = train_distill.get_distillation_optimizer(config, max_train_steps=100, model=model) + optimizer = nnx.Optimizer(model, tx, wrt=nnx.Param) + + optimizer.update(model, jax.tree_util.tree_map(jnp.zeros_like, nnx.state(model, nnx.Param))) + + self.assertFalse(jnp.array_equal(model.kernel[...], jnp.ones(3))) + self.assertTrue(jnp.array_equal(model.bound[...], jnp.ones(3))) + def test_monitored_strategy(self): self._test_monitored_strategy(sft_mode=False, feature_loss_type="cosine") self._test_monitored_strategy(sft_mode=False, feature_loss_type="l2") diff --git a/tests/unit/optimizers_test.py b/tests/unit/optimizers_test.py index 2dfc24305f..07cf3c3e2c 100644 --- a/tests/unit/optimizers_test.py +++ b/tests/unit/optimizers_test.py @@ -23,6 +23,7 @@ from flax import nnx import jax import jax.numpy as jnp +from maxtext.common.common_types import UntrainableParam from maxtext.configs import pyconfig from maxtext.optimizers import optimizers from maxtext.optimizers.muon import ShardedMuonDimensionNumbers as smdn @@ -1041,6 +1042,88 @@ def test_whitelist_without_clip_freeze_matches_original_composition(self): self.assertTrue(jnp.array_equal(got_leaf, ref_leaf)) +class _WeightDecayModel(nnx.Module): + """Names follow the Muon rules: `kernel` is a matrix, `scale` is excluded from Muon.""" + + def __init__(self): + layer = nnx.Dict(kernel=nnx.Param(jnp.ones((2, 2))), frozen_kernel=UntrainableParam(jnp.ones((2, 2)))) + self.decoder = nnx.Dict(layer=layer) + self.bound_scale = UntrainableParam(jnp.asarray(3.0, jnp.float32)) + + +class UntrainableParamWeightDecayTest(parameterized.TestCase): + """Zero gradients leave weight decay as the only force on a weight, so only a real freeze holds it in place.""" + + def _config(self, *extra): + argv = ["", get_test_config_path(), "run_name=test_untrainable_decay", "adam_weight_decay=0.5", *extra] + return pyconfig.initialize(argv) + + def _apply_zero_grads(self, model, tx): + optimizer = nnx.Optimizer(model, tx, wrt=nnx.Param) + optimizer.update(model, jax.tree_util.tree_map(jnp.zeros_like, nnx.state(model, nnx.Param))) + return optimizer + + def _assert_untrainable_unchanged(self, model, optimizer, kernel_moved=True): + self.assertEqual(kernel_moved, not jnp.array_equal(model.decoder.layer.kernel[...], jnp.ones((2, 2)))) + self.assertTrue(jnp.array_equal(model.decoder.layer.frozen_kernel[...], jnp.ones((2, 2)))) + self.assertEqual(float(model.bound_scale[...]), 3.0) + slots = [jax.tree_util.keystr(path) for path, _ in jax.tree_util.tree_leaves_with_path(nnx.state(optimizer))] + self.assertEqual(kernel_moved, bool([s for s in slots if "'kernel'" in s]), slots) + self.assertFalse([s for s in slots if "frozen_kernel" in s or "bound_scale" in s], slots) + + @parameterized.named_parameters( + ("adamw", "opt_type=adamw"), + ("adam_pax", "opt_type=adam_pax"), + ) + def test_adam_weight_decay_skips_untrainable(self, opt_type): + model = _WeightDecayModel() + tx = optimizers.get_optimizer(self._config(opt_type), lambda step: 1.0, model) + self._assert_untrainable_unchanged(model, self._apply_zero_grads(model, tx)) + + def test_muon_weight_decay_skips_untrainable(self): + model = _WeightDecayModel() + config = self._config("opt_type=muon", "muon_type=maxtext_muon", "muon_weight_decay=0.5") + tx = optimizers.get_optimizer(config, lambda step: 1.0, model) + self._assert_untrainable_unchanged(model, self._apply_zero_grads(model, tx)) + + @parameterized.named_parameters( + ("whitelist_names_untrainable", "trainable_parameters_mask=['kernel','bound_scale']", True), + ("whitelist_excludes_everything_else", "trainable_parameters_mask=['bound_scale']", False), + ) + def test_trainable_parameters_mask_cannot_unfreeze(self, mask, kernel_moved): + model = _WeightDecayModel() + tx = optimizers.get_optimizer(self._config("opt_type=adamw", mask), lambda step: 1.0, model) + self._assert_untrainable_unchanged(model, self._apply_zero_grads(model, tx), kernel_moved) + + def test_frozen_paths_survive_inject_hyperparams(self): + model = _WeightDecayModel() + config = self._config("opt_type=adamw") + frozen_paths = optimizers.untrainable_paths(model) + + def factory(learning_rate): + return optimizers.get_optimizer(config, learning_rate, frozen_paths=frozen_paths) + + tx = optax.inject_hyperparams(factory)(learning_rate=1.0) + self._assert_untrainable_unchanged(model, self._apply_zero_grads(model, tx)) + + def test_no_untrainable_params_leaves_optimizer_state_unchanged(self): + params = {"kernel": jnp.ones((2, 2))} + config = self._config("opt_type=adamw") + wrapped = optimizers.get_optimizer(config, lambda step: 1.0, nnx.Dict(kernel=nnx.Param(jnp.ones((2, 2))))) + plain = optimizers.get_optimizer(config, lambda step: 1.0) + self.assertEqual(jax.tree_util.tree_structure(wrapped.init(params)), jax.tree_util.tree_structure(plain.init(params))) + + def test_untrainable_param_without_freeze_raises_at_init(self): + model = _WeightDecayModel() + tx = optimizers.get_optimizer(self._config("opt_type=adamw"), lambda step: 1.0) + with self.assertRaisesRegex(ValueError, "UntrainableParam weights would be trained"): + nnx.Optimizer(model, tx, wrt=nnx.Param) + + def test_untrainable_paths_is_empty_for_none_and_models_without_them(self): + self.assertEqual(optimizers.untrainable_paths(None), frozenset()) + self.assertEqual(optimizers.untrainable_paths(nnx.Dict(kernel=nnx.Param(jnp.ones(1)))), frozenset()) + + class SkipStepOnSpikesTest(parameterized.TestCase): """Tests for the skip_step_on_spikes optimizer wrapper.""" diff --git a/tests/unit/untrainable_param_test.py b/tests/unit/untrainable_param_test.py new file mode 100644 index 0000000000..948600edb6 --- /dev/null +++ b/tests/unit/untrainable_param_test.py @@ -0,0 +1,177 @@ +# Copyright 2025-2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""UntrainableParam is stored and loaded like nnx.Param, but never trained. Drives the real save and restore on CPU.""" +# This suite unit-tests private restore helpers directly, by design. +# pylint: disable=protected-access + +import shutil +import tempfile +import unittest +from unittest import mock + +from flax import nnx +import jax +import jax.numpy as jnp +import numpy as np +import optax + +from maxtext.common import checkpointing +from maxtext.common import train_state_nnx +from maxtext.common.common_types import UntrainableParam, variable_collection_name +from maxtext.layers import nnx_wrappers +from maxtext.layers.initializers import variable_to_logically_partitioned +from maxtext.optimizers import optimizers + +_BOUND = np.asarray([1.5, 2.5, 3.5], np.float32) + + +class _Model(nnx.Module): + """A Param, an untrainable weight, and RNG state.""" + + def __init__(self, rngs: nnx.Rngs): + self.linear = nnx.Linear(2, 3, rngs=rngs) + self.bound = UntrainableParam(jnp.asarray(_BOUND)) + self.dropout = nnx.Dropout(rate=0.5, rngs=rngs) + + +class _Clipped(nnx.Module): + """A Param and an untrainable weight, callable so the Linen bridge can wrap it.""" + + def __init__(self): + self.kernel = nnx.Param(jnp.ones(3)) + self.bound = UntrainableParam(jnp.asarray(_BOUND)) + + def __call__(self, x): + return jnp.minimum(x * self.kernel[...], self.bound[...]) + + +def _train_state(model): + tx = optimizers.freeze_params(optax.adamw(1e-2, weight_decay=0.5), optimizers.untrainable_paths(model)) + return nnx.state(train_state_nnx.TrainStateNNX(model, nnx.Optimizer(model, tx, wrt=nnx.Param))) + + +def _abstract_train_state(): + return nnx.eval_shape(lambda: _train_state(_Model(nnx.Rngs(9)))) + + +def _checkpoint(): + return train_state_nnx.to_checkpoint_dict(_train_state(_Model(nnx.Rngs(0)))) + + +class UntrainableParamGradientTest(unittest.TestCase): + + def test_gradient_is_zero_however_the_value_is_read(self): + reads = { + "index": lambda v: v[...], + "get_value": lambda v: v.get_value(), + "value": lambda v: v.value, + "asarray": jnp.asarray, + "arithmetic": lambda v: v + 0.0, + } + for name, read in reads.items(): + with self.subTest(name): + self.assertEqual(float(jax.grad(lambda x, r=read: r(UntrainableParam(x)) ** 2)(2.0)), 0.0) + self.assertEqual(float(jax.grad(lambda x, r=read: r(nnx.Param(x)) ** 2)(2.0)), 4.0) + + def test_reads_an_abstract_value_without_failing(self): + abstract = nnx.eval_shape(lambda: UntrainableParam(jnp.ones(2))) + self.assertEqual(abstract.get_value().shape, (2,)) + + +class UntrainableParamCheckpointTest(unittest.TestCase): + + def setUp(self): + self._dir = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self._dir, ignore_errors=True) + + def _save(self, checkpoint): + root = self._dir + "/ckpt" + checkpointing.ocp.save(root, checkpoint, checkpointable_name="items") + return root + "/items" + + def _resume(self, path): + return checkpointing._load_linen_checkpoint_into_nnx(path, _abstract_train_state(), 8, True, True) + + def test_saved_with_the_regular_params(self): + checkpoint = _checkpoint() + + self.assertEqual(set(checkpoint["params"]), {"params"}) + self.assertEqual(set(checkpoint["params"]["params"]), {"linear", "bound"}) + self.assertEqual(set(checkpoint["nnx_aux"]["model"]), {"dropout"}) + + def test_resume_restores_type_and_value(self): + checkpoint = _checkpoint() + + restored = self._resume(self._save(checkpoint)) + + self.assertIsInstance(restored.model.bound, UntrainableParam) + np.testing.assert_array_equal(np.asarray(restored.model.bound[...]), _BOUND) + np.testing.assert_array_equal( + np.asarray(restored.model.linear.kernel[...]), np.asarray(checkpoint["params"]["params"]["linear"]["kernel"]) + ) + + def test_resume_raises_when_weight_is_missing(self): + checkpoint = _checkpoint() + del checkpoint["params"]["params"]["bound"] + + with self.assertRaisesRegex(ValueError, "bound"): + self._resume(self._save(checkpoint)) + + def test_weights_only_load_reads_the_params_collection(self): + path = self._save(_checkpoint()) + abstract = checkpointing._abstract_params(_abstract_train_state()) + + with mock.patch.object(checkpointing.max_logging, "log") as log: + restored = checkpointing.load_params_from_path(path, abstract, 8).to_pure_dict() + + np.testing.assert_array_equal(np.asarray(restored["bound"]), _BOUND) + self.assertNotIn("predates", " ".join(str(c) for c in log.call_args_list)) + + +class UntrainableParamNamingTest(unittest.TestCase): + + def test_collection_name_matches_regular_params(self): + class _Custom(nnx.Variable): # pylint: disable=abstract-method + pass + + self.assertEqual(variable_collection_name(UntrainableParam), "params") + self.assertEqual(variable_collection_name(nnx.Param), "params") + self.assertEqual(variable_collection_name(_Custom), "_Custom") + + def test_scanned_sharding_matches_regular_params(self): + metadata = {"out_sharding": ("x",), "param_scan_axis": 1, nnx.PARTITION_NAME: "layers"} + regular = variable_to_logically_partitioned(nnx.Param(jnp.ones((2, 3)), **metadata)) + untrainable = variable_to_logically_partitioned(UntrainableParam(jnp.ones((2, 3)), **metadata)) + + self.assertEqual(untrainable.names, ("x", "layers")) + self.assertEqual(untrainable.names, regular.names) + + +class UntrainableParamLinenBridgeTest(unittest.TestCase): + + def test_bridge_keeps_it_in_the_params_collection(self): + model = nnx_wrappers.to_linen(_Clipped, skip_rng=True) + x = jnp.full(3, 10.0) + variables = model.init(jax.random.key(0), x) + self.assertEqual(set(variables), {"params"}) + + loaded = {"params": {**variables["params"], "bound": jnp.asarray(_BOUND + 1)}} + np.testing.assert_array_equal(model.apply(loaded, x), _BOUND + 1) + grads = jax.grad(lambda variables: model.apply(variables, x).sum())(loaded) + np.testing.assert_array_equal(grads["params"]["bound"], np.zeros(3)) + + +if __name__ == "__main__": + unittest.main() From 3a2de92b8a4ea43252836f31f5e75805fed02077 Mon Sep 17 00:00:00 2001 From: nuinashco Date: Tue, 10 Nov 2026 02:14:29 +0000 Subject: [PATCH 21/26] refactor(gemma4): make the vision clip bounds UntrainableParam --- src/maxtext/models/gemma4_vision.py | 48 ++------ src/maxtext/optimizers/optimizers.py | 16 +-- tests/unit/gemma4_small_layers_test.py | 48 ++------ tests/unit/optimizers_test.py | 145 ------------------------- 4 files changed, 20 insertions(+), 237 deletions(-) diff --git a/src/maxtext/models/gemma4_vision.py b/src/maxtext/models/gemma4_vision.py index 34d7fd7b75..2cf9ae45ec 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -23,7 +23,7 @@ from flax import nnx from jax.sharding import Mesh -from maxtext.common.common_types import Config, AttentionType +from maxtext.common.common_types import Config, AttentionType, UntrainableParam from maxtext.layers import attentions from maxtext.layers import linears from maxtext.layers import normalizations @@ -44,47 +44,15 @@ # # This module adds them as OPT-IN, checkpoint-resident, NON-TRAINABLE scalars, # gated on ``config.use_clipped_linears_for_vit`` (exact no-op when False). -# Design: plain ``nnx.Param`` bounds (so they map to the canonical ``params`` -# collection and round-trip through the nnx->linen->orbax checkpoint path), plus -# a leaf-PATH optimizer-freeze mask so the 448 bounds are excluded from optimizer -# updates and weight decay without a custom nnx.Variable subclass (subclasses are -# renamed by the linen bridge and silently dropped from the saved checkpoint). +# Design: the bounds are ``UntrainableParam``, so they are stored and loaded like any +# ``nnx.Param`` but get no gradient, optimizer update or weight decay. # A NaN sentinel + ``validate_clip_bounds`` hard-fails on a missing/non-finite # bound rather than silently degrading to an identity clamp. -# Leaf-name tokens that identify a clip-bound scalar in a flattened params tree. -_CLIP_LEAF_TOKENS = ("q_clip", "k_clip", "v_clip", "o_clip", "gate_clip", "up_clip", "down_clip") -_CLIP_BOUND_NAMES = ("input_min", "input_max", "output_min", "output_max") - def _mk_clip_bound(init_val=jnp.nan): - """A checkpoint-resident scalar clip bound as a plain ``nnx.Param`` (maps to the - canonical ``params`` collection; NaN sentinel marks an unloaded bound).""" - return nnx.Param(jnp.asarray(init_val, dtype=jnp.float32)) - - -def _is_clip_bound_path(path) -> bool: - """True iff a flattened-params key path addresses a clip-bound scalar.""" - s = "/".join(str(getattr(p, "key", p)) for p in path) if not isinstance(path, str) else path - return any(tok in s for tok in _CLIP_LEAF_TOKENS) and any(b in s for b in _CLIP_BOUND_NAMES) - - -def clip_optimizer_freeze_mask(params_tree): - """Bool pytree (same structure as ``params_tree``): True for TRAINABLE leaves, - False for the immutable clip bounds. Feed to ``optax.masked``/``multi_transform`` - so the bounds get ``set_to_zero()`` updates. Path-based, so it survives the - nnx->linen->orbax round-trip regardless of leaf type erasure.""" - flat = jax.tree_util.tree_flatten_with_path(params_tree)[0] - leaves_mask = [not _is_clip_bound_path(path) for path, _ in flat] - treedef = jax.tree_util.tree_structure(params_tree) - return jax.tree_util.tree_unflatten(treedef, leaves_mask) - - -def _clip_bound_value(bound, dtype): - """Read a clip-bound scalar as a constant: stop_gradient defends the bounds from receiving - gradient at the clamp use-site (defense in depth alongside the optimizer freeze mask), so clip-bound - gradients can never contaminate gradient statistics even if the freeze mask were misconfigured.""" - return jax.lax.stop_gradient(bound.value).astype(dtype) + """A checkpoint-resident scalar clip bound (NaN sentinel marks an unloaded bound).""" + return UntrainableParam(jnp.asarray(init_val, dtype=jnp.float32)) def _clip_in(x, cb): @@ -92,7 +60,7 @@ def _clip_in(x, cb): if cb is None: return x xd = x.dtype - return jnp.clip(x, _clip_bound_value(cb.input_min, xd), _clip_bound_value(cb.input_max, xd)) + return jnp.clip(x, cb.input_min.value.astype(xd), cb.input_max.value.astype(xd)) def _clip_out(y, cb): @@ -100,11 +68,11 @@ def _clip_out(y, cb): if cb is None: return y yd = y.dtype - return jnp.clip(y, _clip_bound_value(cb.output_min, yd), _clip_bound_value(cb.output_max, yd)) + return jnp.clip(y, cb.output_min.value.astype(yd), cb.output_max.value.astype(yd)) class _ClipBounds(nnx.Module): - """Holds the four checkpoint-resident scalar clip bounds as ``nnx.Param`` leaves.""" + """Holds the four checkpoint-resident scalar clip bounds as ``UntrainableParam`` leaves.""" def __init__(self): self.input_min = _mk_clip_bound() diff --git a/src/maxtext/optimizers/optimizers.py b/src/maxtext/optimizers/optimizers.py index da4c906477..ba6077602f 100644 --- a/src/maxtext/optimizers/optimizers.py +++ b/src/maxtext/optimizers/optimizers.py @@ -330,12 +330,7 @@ def apply_trainable_parameters_mask(base_opt, config): # When trainable_parameters_mask is empty, freeze_mask_fn is None and all parameters are trained. trainable_patterns = config.trainable_parameters_mask freeze_mask_fn = get_path_mask_fn(trainable_patterns, match_returns_true=False) - # Gemma-4 vision clipped-linears: the 448 clip bounds are checkpoint-resident, immutable state and must - # NEVER receive optimizer updates, weight decay, or momentum/variance slots. Freeze them via a leaf-PATH - # mask (robust to the nnx->linen bridge's type erasure). This composes with any trainable_parameters_mask: - # a parameter is "trainable" only if it is trainable under the whitelist AND is not a clip bound. - freeze_clip_bounds = bool(getattr(config, "use_clipped_linears_for_vit", False)) - if freeze_mask_fn is None and not freeze_clip_bounds: + if freeze_mask_fn is None: return base_opt has_logged = False @@ -351,14 +346,7 @@ def _label_params(params): up front. Log the counts once so the intent is checkable against the run log. """ nonlocal has_logged - frozen_mask = freeze_mask_fn(params) if freeze_mask_fn else jax.tree_util.tree_map(lambda _: False, params) - if freeze_clip_bounds: - # clip_optimizer_freeze_mask returns True for trainable leaves, False for clip bounds. - from maxtext.models import gemma4_vision # pylint: disable=import-outside-toplevel - - clip_trainable = gemma4_vision.clip_optimizer_freeze_mask(params) - frozen_mask = jax.tree_util.tree_map(lambda f, t: bool(f) or not bool(t), frozen_mask, clip_trainable) - labels = jax.tree_util.tree_map(lambda x: "frozen" if x else "trainable", frozen_mask) + labels = jax.tree_util.tree_map(lambda x: "frozen" if x else "trainable", freeze_mask_fn(params)) if not has_logged: has_logged = True leaves = jax.tree_util.tree_flatten_with_path(labels)[0] diff --git a/tests/unit/gemma4_small_layers_test.py b/tests/unit/gemma4_small_layers_test.py index e2a19df894..1bc503fc0f 100644 --- a/tests/unit/gemma4_small_layers_test.py +++ b/tests/unit/gemma4_small_layers_test.py @@ -42,6 +42,7 @@ from maxtext.layers.attentions import Attention from maxtext.models import gemma4_small from maxtext.models import gemma4_vision as gv +from maxtext.optimizers import optimizers from maxtext.utils.globals import MAXTEXT_REPO_ROOT from tests.utils.multimodal_test_utils import assert_all_close_jax_torch, copy_rmsnorm_weights @@ -431,6 +432,10 @@ def _finite_cb(in_lo=-2.5, in_hi=2.5, out_lo=-4.0, out_hi=4.0): class ClipMathTest(unittest.TestCase): + def test_clip_bounds_are_untrainable_params(self): + cb = gv._make_clip_state() # pylint: disable=protected-access + self.assertEqual(optimizers.untrainable_paths(cb), {"input_min", "input_max", "output_min", "output_max"}) + def test_clip_in_matches_jnp_clip(self): cb = _finite_cb() x = (jax.random.normal(jax.random.PRNGKey(0), (5, 17)) * 6.0).astype(jnp.float32) @@ -452,18 +457,13 @@ def test_dtype_preserved(self): self.assertEqual(gv._clip_in(x, cb).dtype, jnp.bfloat16) def test_bounds_are_stop_gradient(self): - # The clamp bound is read through jax.lax.stop_gradient at the use-site, so gradient wrt the bound - # value is exactly zero even when the clamp is active. Probe _clip_bound_value directly with a - # lightweight bound holder to avoid mutating an nnx Param inside a traced function. - class _B: - - def __init__(self, v): - self.value = v - + # The bounds are UntrainableParam, so the gradient wrt a bound is zero even when the clamp is active. + # pylint: disable=protected-access def loss(bound_val): + cb = gv._make_clip_state() + cb.input_min, cb.input_max = gv._mk_clip_bound(-100.0), gv._mk_clip_bound(bound_val) x = jnp.ones((4,), jnp.float32) * 10.0 # above the bound -> clamp active - hi = gv._clip_bound_value(_B(bound_val), jnp.float32) - return jnp.sum(jnp.clip(x, -100.0, hi)) + return jnp.sum(gv._clip_in(x, cb)) g = jax.grad(loss)(jnp.asarray(2.5, jnp.float32)) self.assertEqual(float(g), 0.0) @@ -493,33 +493,6 @@ def test_none_is_noop(self): self.assertIsNone(gv.validate_clip_bounds(None)) -class FreezeMaskTest(unittest.TestCase): - - def test_freeze_mask_polarity_and_count(self): - tree = { - "vision_encoder": { - "layer_0": { - "attention": { - "q_clip": {"input_min": 1.0, "input_max": 1.0, "output_min": 1.0, "output_max": 1.0}, - "query": {"kernel": 1.0}, - }, - "mlp": {"gate_clip": {"input_min": 1.0, "output_max": 1.0}, "wi_0": {"kernel": 1.0}}, - } - }, - "decoder": {"layer_0": {"norm": {"scale": 1.0}}}, - } - mask = gv.clip_optimizer_freeze_mask(tree) - flat = jax.tree_util.tree_flatten_with_path(mask)[0] - n_clip = 0 - for path, v in flat: - is_clip = gv._is_clip_bound_path(path) - # clip leaves -> False (frozen); everything else -> True (trainable) - self.assertEqual(bool(v), (not is_clip)) - if is_clip: - n_clip += 1 - self.assertEqual(n_clip, 6) # q_clip(4) + gate_clip(2) - - class SymbolsTest(unittest.TestCase): def test_expected_counts_constants(self): @@ -529,7 +502,6 @@ def test_expected_counts_constants(self): def test_public_symbols_present(self): for sym in ( "validate_all_vision_clip_bounds", - "clip_optimizer_freeze_mask", "Gemma4ClippedMlpBlock", "Gemma4Attention", ): diff --git a/tests/unit/optimizers_test.py b/tests/unit/optimizers_test.py index 07cf3c3e2c..a6e359c3c0 100644 --- a/tests/unit/optimizers_test.py +++ b/tests/unit/optimizers_test.py @@ -897,151 +897,6 @@ def test_apply_trainable_parameters_mask_warns_on_empty_or_full_freeze(self): self.assertIn("froze EVERY parameter", mock_warning.call_args[0][0]) -_ADAPTER = "adapter/kernel" -_BACKBONE = "backbone/kernel" -_VIT_QUERY = "vision_encoder/layer_0/attention/query/kernel" -_VIT_WI_0 = "vision_encoder/layer_0/mlp/wi_0/kernel" -_CLIP_BOUND_NAMES = ("input_min", "input_max", "output_min", "output_max") -_CLIP_BOUNDS = frozenset( - f"vision_encoder/layer_0/{block}/{name}" - for block in ("attention/q_clip", "mlp/gate_clip") - for name in _CLIP_BOUND_NAMES -) -_NON_CLIP = frozenset({_ADAPTER, _BACKBONE, _VIT_QUERY, _VIT_WI_0}) - - -def _adapter_backbone_vit_params(): - """Small params tree: an adapter, a backbone and two Gemma-4 ViT projections carrying scalar clip bounds.""" - - def clip(): - return {n: jnp.asarray(v, jnp.float32) for n, v in zip(_CLIP_BOUND_NAMES, (-2.0, 2.0, -3.0, 3.0))} - - return { - "adapter": {"kernel": jnp.ones((2, 2))}, - "backbone": {"kernel": jnp.ones((2, 2))}, - "vision_encoder": { - "layer_0": { - "attention": {"query": {"kernel": jnp.ones((2, 2))}, "q_clip": clip()}, - "mlp": {"wi_0": {"kernel": jnp.ones((2, 2))}, "gate_clip": clip()}, - } - }, - } - - -def _leaf_paths(tree): - return {jax.tree_util.keystr(p, simple=True, separator="/"): v for p, v in jax.tree_util.tree_leaves_with_path(tree)} - - -def _run_jitted_steps(opt, params, num_steps=2): - """Applies `num_steps` jitted optimizer steps with a constant non-zero gradient; returns (params, opt_state).""" - grads = jax.tree_util.tree_map(lambda x: jnp.full_like(x, 0.5), params) - opt_state = opt.init(params) - - @jax.jit - def step(p, s): - updates, s = opt.update(grads, s, p) - return optax.apply_updates(p, updates), s - - for _ in range(num_steps): - params, opt_state = step(params, opt_state) - return params, opt_state - - -def _adam_mu_slots(opt_state): - """Returns (allocated, masked): param paths with an allocated AdamW `mu` slot vs. an optax.MaskedNode slot.""" - allocated, masked = set(), set() - flat = jax.tree_util.tree_flatten_with_path(opt_state, is_leaf=lambda x: isinstance(x, optax.MaskedNode))[0] - for path, leaf in flat: - names = [getattr(k, "name", getattr(k, "key", None)) for k in path] - if "mu" not in names: - continue - param_path = "/".join(str(n) for n in names[names.index("mu") + 1 :]) - (masked if isinstance(leaf, optax.MaskedNode) else allocated).add(param_path) - return allocated, masked - - -class TrainableMaskAndClipBoundFreezeTest(parameterized.TestCase): - """trainable_parameters_mask (a whitelist) composed with the Gemma-4 ViT clip-bound freeze in get_optimizer. - - Checks the parameters actually updated by jitted AdamW steps (weight decay > 0, so any leaf that is not frozen - moves) and the optimizer-state allocation: frozen leaves are routed to optax.set_to_zero() through - optax.multi_transform, so they get zero updates and no AdamW moment slots (optax.MaskedNode), while trainable - leaves get allocated slots. - """ - - def _get_optimizer(self, trainable_mask, use_clipped_linears_for_vit): - """Builds (config, get_optimizer(config)) for AdamW with weight decay and a constant learning rate of 1.0.""" - argv = [ - "", - get_test_config_path(), - "run_name=test_trainable_mask_clip_freeze", - "opt_type=adamw", - "adam_weight_decay=0.1", - f"trainable_parameters_mask={trainable_mask}", - f"use_clipped_linears_for_vit={use_clipped_linears_for_vit}", - ] - config = pyconfig.initialize(argv) - return config, optimizers.get_optimizer(config, lambda step: 1.0) - - def _assert_trained_exactly(self, opt, expected_trainable): - params = _adapter_backbone_vit_params() - new_params, opt_state = _run_jitted_steps(opt, params) - before, after = _leaf_paths(params), _leaf_paths(new_params) - self.assertEqual(set(before), _NON_CLIP | _CLIP_BOUNDS) - changed = {k for k in before if not jnp.array_equal(before[k], after[k])} - self.assertEqual(changed, set(expected_trainable)) - allocated, masked = _adam_mu_slots(opt_state) - self.assertEqual(allocated, set(expected_trainable)) - self.assertEqual(masked, set(before) - set(expected_trainable)) - - def test_whitelist_trains_only_matching_params(self): - """use_clipped_linears_for_vit=False: only whitelisted leaves train (the pre-existing whitelist contract).""" - _, opt = self._get_optimizer(["adapter"], False) - self._assert_trained_exactly(opt, {_ADAPTER}) - - @parameterized.named_parameters( - ("adapter_only", ["adapter"], {_ADAPTER}), - ("whitelist_covers_vit", ["adapter", "vision_encoder"], {_ADAPTER, _VIT_QUERY, _VIT_WI_0}), - ("whitelist_names_clip_bounds", ["adapter", "_clip"], {_ADAPTER}), - ) - def test_whitelist_with_clip_freeze(self, trainable_mask, expected_trainable): - """Whitelisted leaves train, the rest stay frozen, and clip bounds stay frozen even when whitelisted.""" - _, opt = self._get_optimizer(trainable_mask, True) - self._assert_trained_exactly(opt, expected_trainable) - - def test_clip_freeze_without_whitelist(self): - """No whitelist: everything trains except the clip bounds.""" - _, opt = self._get_optimizer([], True) - self._assert_trained_exactly(opt, _NON_CLIP) - - def test_both_flags_off_returns_unwrapped_optimizer(self): - """No whitelist and no clip freeze: get_optimizer returns the base optimizer unwrapped; every leaf trains.""" - _, opt = self._get_optimizer([], False) - params = _adapter_backbone_vit_params() - self.assertNotIsInstance(opt.init(params), optax.PartitionState) - new_params, _ = _run_jitted_steps(opt, params) - before, after = _leaf_paths(params), _leaf_paths(new_params) - self.assertTrue(all(not jnp.array_equal(before[k], after[k]) for k in before)) - - def test_whitelist_without_clip_freeze_matches_original_composition(self): - """use_clipped_linears_for_vit=False: the whitelist-only optimizer equals its definition prior to the clip freeze.""" - patterns = ["adapter"] - config, opt = self._get_optimizer(patterns, False) - _, base_opt = self._get_optimizer([], False) - self.assertFalse(config.use_clipped_linears_for_vit) - freeze_mask_fn = optimizers.get_path_mask_fn(patterns, match_returns_true=False) - reference = optax.multi_transform( - {"trainable": base_opt, "frozen": optax.set_to_zero()}, - lambda p: jax.tree_util.tree_map(lambda x: "frozen" if x else "trainable", freeze_mask_fn(p)), - ) - params = _adapter_backbone_vit_params() - got = _run_jitted_steps(opt, params) - ref = _run_jitted_steps(reference, params) - self.assertEqual(jax.tree_util.tree_structure(got), jax.tree_util.tree_structure(ref)) - for got_leaf, ref_leaf in zip(jax.tree_util.tree_leaves(got), jax.tree_util.tree_leaves(ref)): - self.assertTrue(jnp.array_equal(got_leaf, ref_leaf)) - - class _WeightDecayModel(nnx.Module): """Names follow the Muon rules: `kernel` is a matrix, `scale` is excluded from Muon.""" From 180969296d763e8f38c05e2fac7526a408398a4e Mon Sep 17 00:00:00 2001 From: nuinashco Date: Tue, 10 Nov 2026 04:21:58 +0000 Subject: [PATCH 22/26] fix(gemma4): make std_bias and std_scale UntrainableParam --- src/maxtext/models/gemma4_vision.py | 4 ++-- tests/unit/gemma4_small_layers_test.py | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/maxtext/models/gemma4_vision.py b/src/maxtext/models/gemma4_vision.py index 2cf9ae45ec..02dbfb6ed7 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -908,10 +908,10 @@ def __init__(self, config: Config, mesh: Mesh, *, rngs: nnx.Rngs): rngs=self.rngs, precision=config.matmul_precision, ) - self.std_bias = nnx.Param( + self.std_bias = UntrainableParam( nnx.initializers.zeros(self.rngs.params(), (config.hidden_size_for_vit,), config.weight_dtype), sharding=(None,) ) - self.std_scale = nnx.Param( + self.std_scale = UntrainableParam( nnx.initializers.ones(self.rngs.params(), (config.hidden_size_for_vit,), config.weight_dtype), sharding=(None,) ) diff --git a/tests/unit/gemma4_small_layers_test.py b/tests/unit/gemma4_small_layers_test.py index 1bc503fc0f..d1537f447c 100644 --- a/tests/unit/gemma4_small_layers_test.py +++ b/tests/unit/gemma4_small_layers_test.py @@ -469,6 +469,15 @@ def loss(bound_val): self.assertEqual(float(g), 0.0) +class VisionStdTest(unittest.TestCase): + + def test_std_bias_and_std_scale_are_untrainable(self): + config = _init_gate_config(["use_clipped_linears_for_vit=true"]) + mesh = Mesh(np.array(jax.devices()[:1]), axis_names=("data",)) + encoder = nnx.eval_shape(lambda: gv.Gemma4VisionEncoderLayer(config, mesh, rngs=nnx.Rngs(0))) + self.assertLessEqual({"std_bias", "std_scale"}, optimizers.untrainable_paths(encoder)) + + class ValidateBoundsTest(unittest.TestCase): def test_accepts_finite_ordered(self): From 0a523cd3646f37f2c2c7cc8d6408e504a2f0672d Mon Sep 17 00:00:00 2001 From: nuinashco Date: Tue, 10 Nov 2026 05:03:50 +0000 Subject: [PATCH 23/26] fix(gemma4): make layer_scalar UntrainableParam --- src/maxtext/models/gemma4.py | 4 ++-- src/maxtext/models/gemma4_small.py | 4 ++-- tests/unit/gemma4_small_test.py | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/maxtext/models/gemma4.py b/src/maxtext/models/gemma4.py index bc133aff2c..ed01c2f90e 100644 --- a/src/maxtext/models/gemma4.py +++ b/src/maxtext/models/gemma4.py @@ -25,7 +25,7 @@ from flax import nnx from typing import Optional, Any -from maxtext.common.common_types import Config, AttentionType, MODEL_MODE_PREFILL, ShardMode +from maxtext.common.common_types import Config, AttentionType, MODEL_MODE_PREFILL, ShardMode, UntrainableParam from maxtext.layers import initializers from maxtext.layers import moe from maxtext.layers import nnx_scan @@ -344,7 +344,7 @@ def __init__( else: self.post_ffw_norm = None - self.layer_scalar = nnx.Param(jnp.ones((1,), dtype=config.weight_dtype), sharding=(None,)) + self.layer_scalar = UntrainableParam(jnp.ones((1,), dtype=config.weight_dtype), sharding=(None,)) def __call__( self, diff --git a/src/maxtext/models/gemma4_small.py b/src/maxtext/models/gemma4_small.py index 4929dfaf83..36d7095802 100644 --- a/src/maxtext/models/gemma4_small.py +++ b/src/maxtext/models/gemma4_small.py @@ -23,7 +23,7 @@ from flax import nnx -from maxtext.common.common_types import Config, AttentionType, MODEL_MODE_PREFILL, ShardMode +from maxtext.common.common_types import Config, AttentionType, MODEL_MODE_PREFILL, ShardMode, UntrainableParam from maxtext.layers import quantizations from maxtext.layers.attentions import Attention from maxtext.layers.linears import DenseGeneral, MlpBlock @@ -427,7 +427,7 @@ def __init__( self.per_layer_projection = None self.post_per_layer_input_norm = None - self.layer_scalar = nnx.Param(jnp.ones((1,), dtype=config.weight_dtype), sharding=(None,)) + self.layer_scalar = UntrainableParam(jnp.ones((1,), dtype=config.weight_dtype), sharding=(None,)) def compute_shared_kv(self, inputs: jax.Array, decoder_positions: jax.Array) -> tuple[jax.Array, jax.Array]: """Returns the rotated, normed K / V for this (non-shared) layer. diff --git a/tests/unit/gemma4_small_test.py b/tests/unit/gemma4_small_test.py index 0de35e25ad..2c41424b6c 100644 --- a/tests/unit/gemma4_small_test.py +++ b/tests/unit/gemma4_small_test.py @@ -29,7 +29,9 @@ from maxtext.configs import pyconfig from maxtext.layers import embeddings from maxtext.layers import nnx_decoders +from maxtext.models import gemma4 from maxtext.models import gemma4_small +from maxtext.optimizers import optimizers from maxtext.utils.globals import MAXTEXT_CONFIGS_DIR @@ -254,5 +256,21 @@ def loss_fn(model): ) +class Gemma4LayerScalarTest(unittest.TestCase): + """`layer_scalar` is a fixed buffer in the HF checkpoints, so the optimizer must not train it.""" + + def _untrainable_paths(self, model_name, layer_cls): + config = pyconfig.initialize( + ["", os.path.join(MAXTEXT_CONFIGS_DIR, "base.yml")], model_name=model_name, scan_layers=False + ) + mesh = Mesh(np.array(jax.devices()[:1]), axis_names=("data",)) + layer = nnx.eval_shape(lambda: layer_cls(config, mesh, common_types.MODEL_MODE_TRAIN, rngs=nnx.Rngs(0))) + return optimizers.untrainable_paths(layer) + + def test_layer_scalar_is_untrainable(self): + self.assertIn("layer_scalar", self._untrainable_paths("gemma4-e2b", gemma4_small.Gemma4SmallDecoderLayer)) + self.assertIn("layer_scalar", self._untrainable_paths("gemma4-26b", gemma4.Gemma4DecoderLayer)) + + if __name__ == "__main__": unittest.main() From 5509b927dfc22e8e179a93972eea50a3f24bd0f2 Mon Sep 17 00:00:00 2001 From: nuinashco Date: Tue, 10 Nov 2026 22:59:33 +0000 Subject: [PATCH 24/26] feat(multimodal): pass per-patch image positions through the input pipeline and inference --- src/maxtext/inference/decode.py | 1 + src/maxtext/inference/maxengine/maxengine.py | 13 ++++- .../input_pipeline/input_pipeline_utils.py | 30 +++++++----- src/maxtext/multimodal/utils.py | 14 ++++++ tests/unit/input_pipeline_utils_test.py | 47 +++++++++++++++++++ 5 files changed, 93 insertions(+), 12 deletions(-) diff --git a/src/maxtext/inference/decode.py b/src/maxtext/inference/decode.py index a4ab17f904..355b5f0a33 100644 --- a/src/maxtext/inference/decode.py +++ b/src/maxtext/inference/decode.py @@ -192,6 +192,7 @@ def main(argv: Sequence[str]) -> None: image_masks=processor_outputs.pixel_mask # pyrefly: ignore[bad-argument-type] if config.use_multimodal and "llama4" in config.model_name else None, # pyrefly: ignore[bad-argument-type] + image_position_ids=processor_outputs.image_position_ids, videos=getattr(processor_outputs, "video_values", None) if config.use_multimodal else None, video_masks=getattr(processor_outputs, "video_mask", None) if config.use_multimodal else None, video_grid_thw=getattr(processor_outputs, "video_grid_thw", None) if config.use_multimodal else None, diff --git a/src/maxtext/inference/maxengine/maxengine.py b/src/maxtext/inference/maxengine/maxengine.py index ab04d7a614..fbd860c059 100644 --- a/src/maxtext/inference/maxengine/maxengine.py +++ b/src/maxtext/inference/maxengine/maxengine.py @@ -217,6 +217,7 @@ def _nnx_run_model( slot=None, encoder_images=None, encoder_image_masks=None, + encoder_image_position_ids=None, encoder_videos=None, encoder_video_masks=None, encoder_video_grid_thw=None, @@ -240,6 +241,7 @@ def _nnx_run_model( decoder_segment_ids=decoder_segment_ids, encoder_images=encoder_images, encoder_image_masks=encoder_image_masks, + encoder_image_position_ids=encoder_image_position_ids, encoder_videos=encoder_videos, encoder_video_masks=encoder_video_masks, encoder_video_grid_thw=encoder_video_grid_thw, @@ -594,6 +596,7 @@ def _prefill_jit( mrope_deltas: jax.Array | None = None, images: jax.Array | None = None, image_masks: jax.Array | None = None, + image_position_ids: jax.Array | None = None, videos: jax.Array | None = None, video_masks: jax.Array | None = None, video_grid_thw: tuple[int, int, int] | None = None, @@ -624,6 +627,7 @@ def _prefill_jit( padded_tokens: The input token sequence, padded to a fixed length. images: Optional input images for multimodal models. image_masks: Optional image masks for multimodal models with tiled images. + image_position_ids: Optional per-patch (x, y) positions [N, L, 2] for images given as patches [N, L, F]. audio_values: Optional input audio for multimodal models. audio_masks: Optional audio masks for multimodal models (currently unused). true_length: The actual length of `padded_tokens` before padding. @@ -669,7 +673,11 @@ def _prefill_jit( positions = jnp.expand_dims(jnp.arange(start_position, start_position + input_tokens.shape[1]), 0) if self.config.use_multimodal and images is not None: - if images.ndim == 3: + if image_position_ids is not None: + # [N, L, F] patches with [N, L, 2] positions: add the batch dimension. + images = images[jnp.newaxis, ...] + image_position_ids = image_position_ids[jnp.newaxis, ...] + elif images.ndim == 3: # For Gemma3 single image, add batch and image count dimensions images = images[jnp.newaxis, jnp.newaxis, ...] image_masks = image_masks[jnp.newaxis, jnp.newaxis, ...] if image_masks is not None else None @@ -698,6 +706,7 @@ def _prefill_jit( decoder_segment_ids=sequence_indicator, encoder_images=images, encoder_image_masks=image_masks, + encoder_image_position_ids=image_position_ids, encoder_videos=videos, encoder_video_masks=video_masks, encoder_video_grid_thw=video_grid_thw, @@ -781,6 +790,7 @@ def prefill( mrope_deltas: jax.Array | None = None, images: jax.Array | None = None, image_masks: jax.Array | None = None, + image_position_ids: jax.Array | None = None, videos: jax.Array | None = None, video_masks: jax.Array | None = None, video_grid_thw: jax.Array | None = None, @@ -821,6 +831,7 @@ def prefill( mrope_deltas=mrope_deltas, images=images, image_masks=image_masks, + image_position_ids=image_position_ids, videos=videos, video_masks=video_masks, video_grid_thw=video_grid_thw, diff --git a/src/maxtext/input_pipeline/input_pipeline_utils.py b/src/maxtext/input_pipeline/input_pipeline_utils.py index ac2e6cf93c..89f7e445d5 100644 --- a/src/maxtext/input_pipeline/input_pipeline_utils.py +++ b/src/maxtext/input_pipeline/input_pipeline_utils.py @@ -1004,26 +1004,28 @@ def _pad_image_and_mask(self, preprocessed_image: mm_utils.PreprocessorOutput) - ) # Determine the maximum number of images/masks allowed. - image_offsets = mm_processor.get_image_offsets(self.config, preprocessed_image) - single_image_offset = image_offsets // preprocessed_image.pixel_values.shape[0] - - # Reserve space for at least one text token. - max_num_items = (self.max_length - 1) // single_image_offset - if self.max_num_images_per_example > 0: - max_num_items = min(self.max_num_images_per_example, max_num_items) + positions_tensor = preprocessed_image.image_position_ids + if positions_tensor is not None: + # Patches are padded to the largest image, so every slot costs as much as the largest image. + single_image_offset = mm_processor.get_image_offsets(self.config, None) + else: + image_offsets = mm_processor.get_image_offsets(self.config, preprocessed_image) + single_image_offset = image_offsets // preprocessed_image.pixel_values.shape[0] + max_num_items = mm_utils.get_max_num_images(self.max_length, single_image_offset, self.max_num_images_per_example) image_tensor = preprocessed_image.pixel_values mask_tensor = preprocessed_image.pixel_mask - def _pad(tensor: np.ndarray) -> np.ndarray: + def _pad(tensor: np.ndarray, fill_value: int = 0) -> np.ndarray: # Validate tensor dimensions. - if tensor.ndim in (4, 5): # Standard or Tiled Image + if tensor.ndim in (4, 5) or (positions_tensor is not None and tensor.ndim == 3): # Image, tiles or patches tensor_type = "images" elif tensor.ndim == 2: # Mask tensor_type = "masks" else: raise ValueError( - "Input tensor must be 2D (mask), 4D (image), or 5D (tiled image), " f"but got {tensor.ndim} dimensions." + "Input tensor must be 2D (mask), 3D (patches with positions), 4D (image), or 5D (tiled image), " + f"but got {tensor.ndim} dimensions." ) # Assert that the input tensor does not exceed the maximum size. @@ -1035,7 +1037,7 @@ def _pad(tensor: np.ndarray) -> np.ndarray: pad_size = max_num_items - tensor.shape[0] pad_shape_suffix = tensor.shape[1:] pad_shape = (pad_size,) + pad_shape_suffix - pad_tensor = np.zeros(pad_shape, dtype=tensor.dtype) + pad_tensor = np.full(pad_shape, fill_value, dtype=tensor.dtype) if tensor.size > 0: tensor = np.concatenate([tensor, pad_tensor], axis=0) @@ -1050,6 +1052,10 @@ def _pad(tensor: np.ndarray) -> np.ndarray: if mask_tensor is not None: preprocessed_image.pixel_mask = _pad(mask_tensor) + if positions_tensor is not None: + # Unused image slots get pad positions, so the encoder masks them. + preprocessed_image.image_position_ids = _pad(positions_tensor, fill_value=mm_utils.IMAGE_POSITION_PAD_VALUE) + return preprocessed_image def map( @@ -1139,6 +1145,8 @@ def map(self, element: dict[str, np.ndarray]) -> dict[str, np.ndarray]: output["images"] = preprocessed_image.pixel_values # pyrefly: ignore[unsupported-operation] if preprocessed_image.pixel_mask is not None: output["image_masks"] = preprocessed_image.pixel_mask + if preprocessed_image.image_position_ids is not None: + output["image_position_ids"] = preprocessed_image.image_position_ids # Qwen MRoPE needs per-image (t, h, w) grids to build 3D positions. pixel_grid_thw = getattr(preprocessed_image, "pixel_grid_thw", None) if pixel_grid_thw is not None: diff --git a/src/maxtext/multimodal/utils.py b/src/maxtext/multimodal/utils.py index 9d1b193c21..273c3db3f4 100644 --- a/src/maxtext/multimodal/utils.py +++ b/src/maxtext/multimodal/utils.py @@ -30,6 +30,8 @@ librosa = None NUM_IMAGE_CHANNELS = 3 # RGB +# Position of a padded patch in `PreprocessorOutput.image_position_ids`. +IMAGE_POSITION_PAD_VALUE = -1 @dataclass @@ -48,6 +50,8 @@ class PreprocessorOutput: This is particularly relevant for models like Llama4 that handle images by tiling. num_images: Number of images in the output. + image_position_ids: Optional per-patch (x, y) positions [N, L, 2] for images given as patches + [N, L, F]; padded patches hold IMAGE_POSITION_PAD_VALUE. audio_values: An optional array containing processed audio features. audio_mask: An optional array indicating valid audio segments. """ @@ -56,11 +60,21 @@ class PreprocessorOutput: pixel_mask: None | np.ndarray = None aspect_ratios: None | np.ndarray = None num_images: int = 0 + image_position_ids: None | np.ndarray = None # Audio attributes. audio_values: None | np.ndarray = None audio_mask: None | np.ndarray = None +def get_max_num_images(max_length: int, image_offset: int, max_num_images_per_example: int) -> int: + """Image slots per example when each image adds `image_offset` tokens.""" + # Reserve space for at least one text token. + max_num_images = (max_length - 1) // image_offset + if max_num_images_per_example > 0: + max_num_images = min(max_num_images_per_example, max_num_images) + return max_num_images + + def convert_to_RGB(image): """Convert image to RGB format.""" if isinstance(image, dict) and "bytes" in image and image["bytes"] is not None: diff --git a/tests/unit/input_pipeline_utils_test.py b/tests/unit/input_pipeline_utils_test.py index 2580cfa0f1..49658743b8 100644 --- a/tests/unit/input_pipeline_utils_test.py +++ b/tests/unit/input_pipeline_utils_test.py @@ -552,6 +552,53 @@ def test_qwen_vision_padding_bypass_and_validation(self): with self.assertRaisesRegex(ValueError, "must have pixel_values"): unreg_transform._pad_image_and_mask(mm_utils.PreprocessorOutput(pixel_values=None)) # pylint: disable=protected-access + def test_patches_with_positions_are_padded_per_slot(self): + patches = np.ones((2, 6, 4), dtype=np.float32) + positions = np.arange(24, dtype=np.int32).reshape(2, 6, 2) + output = mm_utils.PreprocessorOutput(pixel_values=patches, image_position_ids=positions, num_images=2) + config = SimpleNamespace(vision_encoder_block="gemma4", use_multimodal=True) + transform = PadOrTrimToMaxLength(max_length=45, pad_id=0, config=config) + with mock.patch.object(input_pipeline_utils.mm_processor, "get_image_offsets", return_value=11) as offsets: + out = transform._pad_image_and_mask(output) # pylint: disable=protected-access + # Slots are costed at the largest image (no sample passed), so every sample gets the same count. + offsets.assert_called_once_with(config, None) + self.assertEqual(out.pixel_values.shape, (4, 6, 4)) # (45 - 1) // 11 + np.testing.assert_array_equal(out.pixel_values[:2], patches) + np.testing.assert_array_equal(out.pixel_values[2:], 0) + self.assertEqual(out.image_position_ids.shape, (4, 6, 2)) + np.testing.assert_array_equal(out.image_position_ids[:2], positions) + np.testing.assert_array_equal(out.image_position_ids[2:], mm_utils.IMAGE_POSITION_PAD_VALUE) + + def test_patches_respect_max_num_images_per_example(self): + output = mm_utils.PreprocessorOutput( + pixel_values=np.ones((1, 6, 4)), image_position_ids=np.zeros((1, 6, 2), dtype=np.int32), num_images=1 + ) + transform = PadOrTrimToMaxLength( + max_length=45, + pad_id=0, + config=SimpleNamespace(vision_encoder_block="gemma4", use_multimodal=True), + max_num_images_per_example=2, + ) + with mock.patch.object(input_pipeline_utils.mm_processor, "get_image_offsets", return_value=11): + out = transform._pad_image_and_mask(output) # pylint: disable=protected-access + self.assertEqual(out.pixel_values.shape[0], 2) + self.assertEqual(out.image_position_ids.shape[0], 2) + + +class ExtractImagesAndMasksTest(unittest.TestCase): + """ExtractImagesAndMasks passes per-patch positions on to the model.""" + + def test_emits_image_position_ids(self): + positions = np.zeros((1, 6, 2), dtype=np.int32) + output = mm_utils.PreprocessorOutput(pixel_values=np.ones((1, 6, 4)), image_position_ids=positions) + element = input_pipeline_utils.ExtractImagesAndMasks().map({"images": output}) + self.assertIs(element["image_position_ids"], positions) + + def test_no_positions_no_key(self): + output = mm_utils.PreprocessorOutput(pixel_values=np.ones((1, 4, 4, 3))) + element = input_pipeline_utils.ExtractImagesAndMasks().map({"images": output}) + self.assertNotIn("image_position_ids", element) + class FixPadTokenIfNeededTest(unittest.TestCase): """Tests for fix_pad_token_if_needed and SFT completion EOS loss masking.""" From 273722e0801cf788e90776d9d18f65c461045df1 Mon Sep 17 00:00:00 2001 From: nuinashco Date: Wed, 11 Nov 2026 00:14:43 +0000 Subject: [PATCH 25/26] feat(gemma4): native-resolution image preprocessing --- src/maxtext/configs/models/gemma4-e2b.yml | 2 + src/maxtext/configs/types.py | 11 + src/maxtext/multimodal/processor.py | 19 +- src/maxtext/multimodal/processor_gemma4.py | 121 +++++++++- src/maxtext/utils/maxtext_utils.py | 5 + .../generate_hf_golden_logits.py | 10 +- .../tpu/gemma4/e2b/test_gemma4_multimodal.sh | 2 +- tests/unit/multimodal_utils_test.py | 212 ++++++++++++++++++ tests/utils/forward_pass_logit_checker.py | 22 +- 9 files changed, 381 insertions(+), 23 deletions(-) diff --git a/src/maxtext/configs/models/gemma4-e2b.yml b/src/maxtext/configs/models/gemma4-e2b.yml index c4a4b26c26..2723b4a40a 100644 --- a/src/maxtext/configs/models/gemma4-e2b.yml +++ b/src/maxtext/configs/models/gemma4-e2b.yml @@ -59,6 +59,8 @@ num_attention_heads_for_vit: 12 image_placeholder: "<|image|>" vision_output_length: 280 num_position_embeddings_for_vit: 10240 +# Like the HF processor: keep the aspect ratio, up to vision_output_length soft tokens per image. +use_native_resolution_for_vit: True # E2B image contract (decoder-side): image spans are causal and the per-layer-embedding path # substitutes the pad token for image placeholder rows (matches HF modeling_gemma4). use_bidirectional_image_attn: False diff --git a/src/maxtext/configs/types.py b/src/maxtext/configs/types.py index 361c675f54..d71ba4f480 100644 --- a/src/maxtext/configs/types.py +++ b/src/maxtext/configs/types.py @@ -3638,6 +3638,13 @@ class MultimodalGeneral(BaseModel): "on its own sufficient); no-op for other encoders." ), ) + use_native_resolution_for_vit: bool = Field( + False, + description=( + "Gemma-4 vision only: resize each image like the HF processor, keeping its aspect ratio, to at most " + "vision_output_length soft tokens. When False, every image is stretched to 672x960 (280 soft tokens)." + ), + ) use_bidirectional_image_attn: bool = Field( False, description=( @@ -6322,6 +6329,10 @@ def _non_batch_devices(num_devices: int, num_slices: int) -> int: f"{self.model_name} requires scan_layers=False (per-layer KV sharing is incompatible with scanned layers)." ) if self.use_multimodal: + 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}." + ) # Gemma 4 small (E2B / E4B) multimodal requires the vision-encoder clipped-linears AND the # padded-patch masking / position-threading path; gate on the clipped-linears flag. if self.model_name in ("gemma4-e2b", "gemma4-e4b") and not self.use_clipped_linears_for_vit: diff --git a/src/maxtext/multimodal/processor.py b/src/maxtext/multimodal/processor.py index 430e031b84..fef00b463e 100644 --- a/src/maxtext/multimodal/processor.py +++ b/src/maxtext/multimodal/processor.py @@ -105,7 +105,7 @@ def preprocess_mm_data(config): from maxtext.multimodal.processor_gemma4 import preprocess_mm_data_gemma4 # pylint: disable=import-outside-toplevel images = [mm_utils.load_image_from_path(p) for p in config.image_path.split(",")] - processor_outputs = preprocess_mm_data_gemma4(images) + processor_outputs = preprocess_mm_data_gemma4(images, config) elif vision_block in ["llama4"]: from maxtext.multimodal.processor_llama4 import preprocess_mm_data_llama4 # pylint: disable=import-outside-toplevel @@ -137,7 +137,7 @@ def preprocess_image_for_training(image, config): elif vision_block in ["gemma4"]: from maxtext.multimodal.processor_gemma4 import preprocess_mm_data_gemma4 # pylint: disable=import-outside-toplevel - return preprocess_mm_data_gemma4(image) + return preprocess_mm_data_gemma4(image, config) elif vision_block in ["llama4"]: from maxtext.multimodal.processor_llama4 import preprocess_mm_data_llama4 # pylint: disable=import-outside-toplevel @@ -166,7 +166,7 @@ def get_image_offsets(config, processor_output: mm_utils.PreprocessorOutput | No elif vision_block in ["gemma4"]: from maxtext.multimodal.processor_gemma4 import get_image_offsets_gemma4 # pylint: disable=import-outside-toplevel - return get_image_offsets_gemma4(processor_output) + return get_image_offsets_gemma4(processor_output, config) elif vision_block in ["llama4"]: from maxtext.multimodal.processor_llama4 import get_image_offsets_llama4 # pylint: disable=import-outside-toplevel @@ -276,7 +276,9 @@ def prepare_text_for_image_fusion(tokens, config, processor_output=None): from maxtext.multimodal.processor_gemma4 import add_extra_tokens_for_images_gemma4 # pylint: disable=import-outside-toplevel return add_extra_tokens_for_images_gemma4( - tokens, max_num_images=processor_output.num_images # pyrefly: ignore[missing-attribute] + tokens, + max_num_images=processor_output.num_images, # pyrefly: ignore[missing-attribute] + num_soft_tokens_per_image=getattr(processor_output, "num_soft_tokens_per_image", None), ) # pyrefly: ignore[missing-attribute] elif vision_block in ["llama4"]: from maxtext.multimodal.processor_llama4 import add_extra_tokens_for_images_llama4 # pylint: disable=import-outside-toplevel @@ -317,6 +319,15 @@ def get_dummy_image_shape_for_init(model_name, batch_size=1, num_image_per_seque return image_shape +def get_dummy_patch_shape_for_init(config, batch_size=1): + """Shape [B, N, L, F] of images given as patches with per-patch positions; None for models that take whole images.""" + if _get_vision_block(config) in ["gemma4"]: + from maxtext.multimodal.processor_gemma4 import get_dummy_patch_shape_for_init_gemma4 # pylint: disable=import-outside-toplevel + + return get_dummy_patch_shape_for_init_gemma4(config, batch_size) + return None + + def get_dummy_audio_shape_for_init(config): """Return the shape of the dummy audio for specific model's initialization. diff --git a/src/maxtext/multimodal/processor_gemma4.py b/src/maxtext/multimodal/processor_gemma4.py index e261eb8223..eb3a6d32e5 100644 --- a/src/maxtext/multimodal/processor_gemma4.py +++ b/src/maxtext/multimodal/processor_gemma4.py @@ -16,6 +16,7 @@ """Gemma4-specific utilities for multimodal features.""" from dataclasses import dataclass +import math import numpy as np from PIL import Image @@ -45,13 +46,20 @@ class Gemma4PreprocessorOutput(mm_utils.PreprocessorOutput): num_images: int = 0 pixel_values: None | np.ndarray = None pixel_mask: None | np.ndarray = None - positions_xy: None | np.ndarray = None + num_soft_tokens_per_image: None | np.ndarray = None -def preprocess_mm_data_gemma4(images): - """Preprocesses multimodal data for Gemma4 models.""" +def _resize_and_rescale(img: np.ndarray, height: int, width: int) -> np.ndarray: + """Bicubic resize to (height, width), scaled to the [0, 1] range Gemma 4 expects.""" # PIL resize expects (width, height) - target_size = (GEMMA4_IMAGE_WIDTH, GEMMA4_IMAGE_HEIGHT) + resized_pil_img = Image.fromarray(img).resize((width, height), resample=Image.Resampling.BICUBIC) + return np.asarray(resized_pil_img, dtype=np.float32) / 255.0 + + +def preprocess_mm_data_gemma4(images, config=None): + """Preprocesses multimodal data for Gemma4 models.""" + if config is not None and config.use_native_resolution_for_vit: + return preprocess_mm_data_gemma4_native(images, max_soft_tokens=config.vision_output_length) images_in, images_out = [], [] if isinstance(images, np.ndarray): @@ -60,12 +68,7 @@ def preprocess_mm_data_gemma4(images): images_in.extend(images) for img in images_in: - pil_img = Image.fromarray(img) - resized_pil_img = pil_img.resize(target_size, resample=Image.Resampling.BICUBIC) - - # Gemma 4 expects inputs strictly in the [0, 1] range. - img = np.asarray(resized_pil_img, dtype=np.float32) / 255.0 - images_out.append(img) + images_out.append(_resize_and_rescale(img, GEMMA4_IMAGE_HEIGHT, GEMMA4_IMAGE_WIDTH)) stacked_images = np.stack(images_out, axis=0).astype(np.float32) @@ -75,8 +78,73 @@ def preprocess_mm_data_gemma4(images): ) -def get_image_offsets_gemma4(processor_output: mm_utils.PreprocessorOutput | None): +def get_aspect_ratio_preserving_size_gemma4(height: int, width: int, max_soft_tokens: int) -> tuple[int, int]: + """Port of HF `get_aspect_ratio_preserving_size` with the Gemma-4 patch and pooling sizes; returns (height, width).""" + max_patches = max_soft_tokens * GEMMA4_POOLING_KERNEL**2 + side_mult = GEMMA4_PATCH_SIZE * GEMMA4_POOLING_KERNEL + factor = math.sqrt(max_patches * GEMMA4_PATCH_SIZE**2 / (height * width)) + target_height = int(math.floor(factor * height / side_mult)) * side_mult + target_width = int(math.floor(factor * width / side_mult)) * side_mult + + if target_height == 0 and target_width == 0: + raise ValueError(f"Cannot resize a {height}x{width} image to a non-empty Gemma-4 patch grid.") + # An extreme aspect ratio can round one side down to zero: keep one row or column of pooled tokens. + max_side_length = max_soft_tokens * side_mult + if target_height == 0: + target_height = side_mult + target_width = min(int(math.floor(width / height)) * side_mult, max_side_length) + elif target_width == 0: + target_width = side_mult + target_height = min(int(math.floor(height / width)) * side_mult, max_side_length) + return target_height, target_width + + +def preprocess_mm_data_gemma4_native(images, max_soft_tokens: int): + """Preprocesses images like the HF Gemma-4 processor: aspect ratio kept, patches padded to the token budget. + + Returns: + A Gemma4PreprocessorOutput with pixel_values [N, L, P*P*C], image_position_ids [N, L, 2] holding (x, y), and + num_soft_tokens_per_image [N], where L = max_soft_tokens * GEMMA4_POOLING_KERNEL**2. + """ + images_in = [images] if isinstance(images, np.ndarray) else list(images) + num_images = len(images_in) + patch = GEMMA4_PATCH_SIZE + max_patches = max_soft_tokens * GEMMA4_POOLING_KERNEL**2 + + pixel_values = np.zeros((num_images, max_patches, patch * patch * mm_utils.NUM_IMAGE_CHANNELS), dtype=np.float32) + image_position_ids = np.full((num_images, max_patches, 2), mm_utils.IMAGE_POSITION_PAD_VALUE, dtype=np.int32) + num_soft_tokens_per_image = np.zeros(num_images, dtype=np.int32) + + for i, img in enumerate(images_in): + height, width = get_aspect_ratio_preserving_size_gemma4(img.shape[0], img.shape[1], max_soft_tokens) + pixels = _resize_and_rescale(img, height, width) + + grid_h, grid_w = height // patch, width // patch + num_patches = grid_h * grid_w + pixel_values[i, :num_patches] = ( + pixels.reshape(grid_h, patch, grid_w, patch, -1).transpose(0, 2, 1, 3, 4).reshape(num_patches, -1) + ) + xs, ys = np.meshgrid(np.arange(grid_w), np.arange(grid_h)) + image_position_ids[i, :num_patches] = np.stack([xs, ys], axis=-1).reshape(num_patches, 2) + num_soft_tokens_per_image[i] = num_patches // GEMMA4_POOLING_KERNEL**2 + + return Gemma4PreprocessorOutput( + num_images=num_images, + pixel_values=pixel_values, + image_position_ids=image_position_ids, + num_soft_tokens_per_image=num_soft_tokens_per_image, + ) + + +def get_image_offsets_gemma4(processor_output: mm_utils.PreprocessorOutput | None, config=None): """Gets the increase in total token count after inserting image token placeholders.""" + num_soft_tokens_per_image = getattr(processor_output, "num_soft_tokens_per_image", None) + if num_soft_tokens_per_image is not None: + return int(np.sum(np.asarray(num_soft_tokens_per_image) + GEMMA4_NUM_EXTRA_TOKENS_PER_MEDIA - 1)) + if processor_output is None and config is not None and config.use_native_resolution_for_vit: + # One image at the full token budget. + return config.vision_output_length + GEMMA4_NUM_EXTRA_TOKENS_PER_MEDIA - 1 + has_images = processor_output is not None and processor_output.pixel_values is not None num_images = processor_output.pixel_values.shape[0] if has_images else 1 # pyrefly: ignore[missing-attribute] @@ -154,12 +222,33 @@ def insert_sequence( return new_tokens +def _expand_image_tokens_native(tokens: np.ndarray, num_soft_tokens_per_image: np.ndarray) -> np.ndarray: + """Replaces each placeholder in a 1D token array with its image's own soft token run.""" + if tokens.ndim != 1: + raise ValueError(f"Native-resolution token expansion expects 1D tokens, got shape {tokens.shape}.") + starts = np.flatnonzero(tokens == GEMMA4_TOKEN_PLACEHOLDER) + if starts.size != len(num_soft_tokens_per_image): + raise ValueError( + f"Found {starts.size} image placeholder(s) in the prompt for {len(num_soft_tokens_per_image)} image(s)." + ) + pieces = np.split(tokens, starts) + out = [pieces[0]] + for piece, num_soft_tokens in zip(pieces[1:], num_soft_tokens_per_image): + image_tokens = [GEMMA4_BEGIN_IMAGE_TOKEN, *[GEMMA4_TOKEN_PLACEHOLDER] * int(num_soft_tokens), GEMMA4_END_IMAGE_TOKEN] + out += [image_tokens, piece[1:]] + return np.concatenate(out).astype(tokens.dtype) + + def add_extra_tokens_for_images_gemma4( tokens: np.ndarray | list, *, max_num_images: int = 1, + num_soft_tokens_per_image: np.ndarray | None = None, ): """Replaces image placeholder tokens with the full sequence of Gemma 4 image tokens.""" + if num_soft_tokens_per_image is not None: + return _expand_image_tokens_native(np.asarray(tokens), num_soft_tokens_per_image) + # New tokens which will be inserted for each image (accounting for pooling) num_patches = (GEMMA4_IMAGE_HEIGHT // GEMMA4_PATCH_SIZE) * (GEMMA4_IMAGE_WIDTH // GEMMA4_PATCH_SIZE) num_soft_tokens = num_patches // (GEMMA4_POOLING_KERNEL**2) @@ -189,3 +278,13 @@ def get_dummy_image_shape_for_init_gemma4(batch_size=1, num_image_per_sequence=1 mm_utils.NUM_IMAGE_CHANNELS, ) return image_shape + + +def get_dummy_patch_shape_for_init_gemma4(config, batch_size=1): + """Shape [B, N, L, P*P*C] of native-resolution images, as the input pipeline pads them; None when off.""" + if not config.use_native_resolution_for_vit: + return None + image_offset = get_image_offsets_gemma4(None, config) + num_images = mm_utils.get_max_num_images(config.max_target_length, image_offset, config.max_num_images_per_example) + max_patches = config.vision_output_length * GEMMA4_POOLING_KERNEL**2 + return (batch_size, num_images, max_patches, GEMMA4_PATCH_SIZE**2 * mm_utils.NUM_IMAGE_CHANNELS) diff --git a/src/maxtext/utils/maxtext_utils.py b/src/maxtext/utils/maxtext_utils.py index 14860b13e6..1ba02740fa 100644 --- a/src/maxtext/utils/maxtext_utils.py +++ b/src/maxtext/utils/maxtext_utils.py @@ -177,6 +177,11 @@ def get_shaped_batch(config, batch_sharding=None, is_eval=False): shaped_batch["images"] = jax.ShapeDtypeStruct(video_shape, jnp.float32, sharding=batch_sharding) shaped_batch["image_masks"] = jax.ShapeDtypeStruct(video_mask_shape, jnp.int32, sharding=batch_sharding) shaped_batch["video_grid_thw"] = jax.ShapeDtypeStruct((batch_size, 3), jnp.int32, sharding=batch_sharding) + 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) else: image_shape = mm_processor.get_dummy_image_shape_for_init(config.model_name, batch_size=batch_size) shaped_batch["images"] = jax.ShapeDtypeStruct(image_shape, jnp.int32, sharding=batch_sharding) diff --git a/tests/assets/logits_generation/generate_hf_golden_logits.py b/tests/assets/logits_generation/generate_hf_golden_logits.py index 5b59214d62..12fe3c2398 100644 --- a/tests/assets/logits_generation/generate_hf_golden_logits.py +++ b/tests/assets/logits_generation/generate_hf_golden_logits.py @@ -71,6 +71,7 @@ def save_golden_logits( trust_remote_code, image_paths, output_format, + native_resolution=False, ): """save golden logits""" if hf_model_path is None: @@ -119,7 +120,7 @@ def save_golden_logits( image = image_file.convert("RGB") if model_id.startswith("meta-llama/Llama-4"): image = image.resize((336, 336)) - elif "gemma-4" in model_id.lower(): + elif "gemma-4" in model_id.lower() and not native_resolution: # Force exact dimensions to prevent HF from dynamically padding # PIL resize expects (Width, Height). Matches MaxText's [672, 960] image = image.resize((960, 672), resample=Image.Resampling.BICUBIC) @@ -227,6 +228,12 @@ def main(raw_args=None) -> None: default="json", help="The output format for the golden logits. (json, pickle)", ) + parser.add_argument( + "--native-resolution", + action="store_true", + help="Gemma-4: let the HF processor size the image itself instead of forcing 960x672. " + "Pair with use_native_resolution_for_vit=true in MaxText.", + ) args = parser.parse_args(raw_args) prompts = args.prompts.split(";") image_paths = args.image_paths.split(";") if args.image_paths else [] @@ -247,6 +254,7 @@ def main(raw_args=None) -> None: args.trust_remote_code, image_paths, args.output_format, + native_resolution=args.native_resolution, ) diff --git a/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh b/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh index 9d9289d476..c0f2a87fd6 100755 --- a/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh +++ b/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh @@ -51,7 +51,7 @@ python3 -m tests.assets.logits_generation.generate_hf_golden_logits \ --model-id=${MODEL_ID} --hf-model-path=${HF_MODEL} \ --prompts="${PROMPT}" --image-paths=${IMAGE_PATH} \ --output-path=${GOLDEN_LOGITS_PATH} \ - --apply-chat-template --output-format=json + --apply-chat-template --output-format=json --native-resolution # Step 3: MaxText vs HF golden-logit parity on the image path. # Uses the same --max_kl_div threshold as the Gemma-4 convert_gemma4.sh checks. diff --git a/tests/unit/multimodal_utils_test.py b/tests/unit/multimodal_utils_test.py index 71adc98615..b297b1490f 100644 --- a/tests/unit/multimodal_utils_test.py +++ b/tests/unit/multimodal_utils_test.py @@ -16,10 +16,15 @@ import os import types import unittest +from flax import nnx +import jax +from jax.sharding import Mesh +import jax.numpy as jnp import numpy as np from maxtext.common.common_types import DecoderBlockType, VisionEncoderBlockType from maxtext.configs import pyconfig +from maxtext.models.gemma4_vision import Gemma4VisionEncoderLayer from maxtext.utils.globals import MAXTEXT_REPO_ROOT from maxtext.input_pipeline import input_pipeline_utils from maxtext.multimodal import processor as mm_processor @@ -27,6 +32,8 @@ from maxtext.multimodal import processor_gemma3 from maxtext.multimodal import processor_gemma4 from maxtext.multimodal import processor_llama4 +from maxtext.utils import maxtext_utils +from tests.utils.test_helpers import get_test_config_path class TestTextImageFusionGemma3(unittest.TestCase): @@ -561,5 +568,210 @@ def test_omni_gemma3_qwen3_processor_routing(self): mm_processor.get_image_offsets(unsupported_omni, None) +class TestGemma4NativeResolution(unittest.TestCase): + """Gemma-4 native-resolution preprocessing.""" + + def _native_config(self, vision_output_length=280): + return types.SimpleNamespace( + model_name="gemma4-e2b", + use_multimodal=True, + vision_encoder_block=VisionEncoderBlockType.GEMMA4, + use_native_resolution_for_vit=True, + vision_output_length=vision_output_length, + ) + + def _native(self, *images): + return processor_gemma4.preprocess_mm_data_gemma4(list(images), self._native_config()) + + def _pad(self, output, max_length): + pad = input_pipeline_utils.PadOrTrimToMaxLength(max_length, 0, config=self._native_config()) + return pad._pad_image_and_mask(output) # pylint: disable=protected-access + + def _pyconfig(self, model_name="gemma4-e2b", **kwargs): + return pyconfig.initialize( + ["", get_test_config_path()], model_name=model_name, scan_layers=False, skip_jax_distributed_system=True, **kwargs + ) + + def test_size_matches_hf_grids(self): + # Source (height, width) -> HF Gemma4ImageProcessor size, transformers 5.12.1. + cases = { + (672, 960): (672, 960), + (536, 640): (720, 864), + (536, 536): (768, 768), + (160, 640): (384, 1584), + (341, 512): (624, 960), + (341, 191): (1056, 576), + (48, 64): (672, 912), + (360, 640): (576, 1056), + (10, 100000): (48, 13440), + (100000, 10): (13440, 48), + } + for source, expected in cases.items(): + size = processor_gemma4.get_aspect_ratio_preserving_size_gemma4(*source, max_soft_tokens=280) + self.assertEqual(size, expected, msg=f"source {source}") + + def test_matches_hf_pil_processor(self): + try: + from transformers.models.gemma4.image_processing_pil_gemma4 import Gemma4ImageProcessorPil # pylint: disable=import-outside-toplevel + except ImportError: + self.skipTest("transformers without Gemma-4") + hf = Gemma4ImageProcessorPil(patch_size=16, max_soft_tokens=280, pooling_kernel_size=3) + rng = np.random.default_rng(0) + images = [rng.integers(0, 255, size=shape, dtype=np.uint8) for shape in ((160, 640, 3), (341, 191, 3))] + for image in images: + out = self._native(image) + expected = hf([image], return_tensors="np") + np.testing.assert_allclose(out.pixel_values, expected["pixel_values"], atol=1e-6) + np.testing.assert_array_equal(out.image_position_ids, expected["image_position_ids"]) + self.assertEqual(out.num_soft_tokens_per_image.tolist(), expected["num_soft_tokens_per_image"].tolist()) + + def test_patches_positions_and_padding(self): + # 160x640 resizes to 384x1584: a 24x99 patch grid, 264 soft tokens. + out = self._native(np.zeros((160, 640, 3), dtype=np.uint8)) + self.assertEqual(out.pixel_values.shape, (1, 2520, 768)) + self.assertEqual(out.num_soft_tokens_per_image.tolist(), [264]) + positions = out.image_position_ids[0] + self.assertEqual(positions[1].tolist(), [1, 0]) + self.assertEqual(positions[99].tolist(), [0, 1]) + self.assertEqual(positions[2375].tolist(), [98, 23]) + np.testing.assert_array_equal(positions[2376:], mm_utils.IMAGE_POSITION_PAD_VALUE) + + def test_resize_keeps_the_image_layout(self): + image = np.zeros((160, 640, 3), dtype=np.uint8) + image[:, 320:] = 255 + out = self._native(image) + # Mean brightness per patch on the 24x99 grid: left half dark, right half bright. + brightness = out.pixel_values[0, :2376].mean(axis=-1).reshape(24, 99) + self.assertTrue((brightness[:, :48] < 0.05).all()) + self.assertTrue((brightness[:, 51:] > 0.95).all()) + + def test_patch_layout_is_row_major_pixels(self): + # 672x960 is already on the grid, so patches equal the raw pixels. + image = np.random.default_rng(1).integers(0, 255, size=(672, 960, 3), dtype=np.uint8) + out = self._native(image) + expected_second_patch = (image[0:16, 16:32] / 255.0).astype(np.float32).reshape(-1) + np.testing.assert_array_equal(out.pixel_values[0, 1], expected_second_patch) + + def test_budget_comes_from_vision_output_length(self): + out = processor_gemma4.preprocess_mm_data_gemma4(np.zeros((536, 536, 3), dtype=np.uint8), self._native_config(560)) + self.assertEqual(out.pixel_values.shape, (1, 560 * 9, 768)) + self.assertEqual(out.num_soft_tokens_per_image.tolist(), [529]) # 1104x1104: a 23x23 pooled grid + + def test_tokens_expand_per_image(self): + placeholder = processor_gemma4.GEMMA4_TOKEN_PLACEHOLDER + begin, end = processor_gemma4.GEMMA4_BEGIN_IMAGE_TOKEN, processor_gemma4.GEMMA4_END_IMAGE_TOKEN + tokens = np.array([1, placeholder, 2, placeholder, 3, 0, 0], dtype=np.int32) + out = processor_gemma4.add_extra_tokens_for_images_gemma4(tokens, num_soft_tokens_per_image=np.array([2, 3])) + expected = [1, begin, placeholder, placeholder, end, 2, begin, placeholder, placeholder, placeholder, end, 3, 0, 0] + self.assertEqual(out.tolist(), expected) + self.assertEqual(out.dtype, np.int32) + + def test_placeholder_count_mismatch_raises(self): + tokens = np.array([1, processor_gemma4.GEMMA4_TOKEN_PLACEHOLDER, 2], dtype=np.int32) + with self.assertRaises(ValueError): + processor_gemma4.add_extra_tokens_for_images_gemma4(tokens, num_soft_tokens_per_image=np.array([2, 3])) + + def test_text_fusion_uses_each_image_token_count(self): + placeholder = processor_gemma4.GEMMA4_TOKEN_PLACEHOLDER + output = self._native(np.zeros((536, 536, 3), dtype=np.uint8)) + tokens = mm_processor.prepare_text_for_image_fusion( + np.array([1, placeholder, 2]), config=self._native_config(), processor_output=output + ) + self.assertEqual(int((tokens == placeholder).sum()), 256) + + def test_offsets_per_image_and_largest_image(self): + output = processor_gemma4.Gemma4PreprocessorOutput(num_soft_tokens_per_image=np.array([256, 264])) + self.assertEqual(mm_processor.get_image_offsets(self._native_config(), output), (256 + 1) + (264 + 1)) + self.assertEqual(mm_processor.get_image_offsets(self._native_config(), None), 281) + self.assertEqual(mm_processor.get_image_offsets(self._native_config(560), None), 561) + + def test_two_images_are_padded_per_image(self): + out = self._pad(self._native(np.zeros((536, 536, 3), np.uint8), np.zeros((160, 640, 3), np.uint8)), 1024) + self.assertEqual(out.pixel_values.shape, (3, 2520, 768)) # (1024 - 1) // 281 slots + self.assertEqual(out.image_position_ids.shape, (3, 2520, 2)) + for slot, num_patches in enumerate((2304, 2376)): + self.assertTrue((out.image_position_ids[slot, :num_patches] >= 0).all(), msg=f"slot {slot}") + np.testing.assert_array_equal(out.image_position_ids[slot, num_patches:], mm_utils.IMAGE_POSITION_PAD_VALUE) + np.testing.assert_array_equal(out.image_position_ids[2], mm_utils.IMAGE_POSITION_PAD_VALUE) + + def test_two_images_reach_their_own_placeholders(self): + # 26B's encoder has no clip bounds, which stay NaN until a checkpoint is loaded. + config = self._pyconfig( + model_name="gemma4-26b", + use_multimodal=True, + use_native_resolution_for_vit=True, + override_model_config=True, + vision_output_length=12, + hidden_size_for_vit=32, + intermediate_size_for_vit=64, + num_hidden_layers_for_vit=1, + num_attention_heads_for_vit=2, + attention="dot_product", + dtype="float32", + dtype_mm="float32", + weight_dtype="float32", + matmul_precision="highest", + ) + encoder = Gemma4VisionEncoderLayer(config, Mesh(np.array(jax.devices()[:1]), ("data",)), rngs=nnx.Rngs(0)) + + def encode(output): + return encoder(output.pixel_values[None], deterministic=True, image_position_ids=output.image_position_ids[None]) + + rng = np.random.default_rng(0) + images = [rng.integers(0, 256, (100, width, 3), dtype=np.uint8) for width in (100, 400)] + output = processor_gemma4.preprocess_mm_data_gemma4(images, config) + counts = output.num_soft_tokens_per_image.tolist() + self.assertEqual(counts, [9, 6]) + placeholder = processor_gemma4.GEMMA4_TOKEN_PLACEHOLDER + tokens = mm_processor.prepare_text_for_image_fusion(np.array([1, placeholder, 2, placeholder, 3]), config, output) + mask = mm_processor.get_bidirectional_mask_vision(config, tokens[None]) + self.assertEqual(mask[0, : np.flatnonzero(tokens == 2)[0]].sum(), counts[0]) + + # (40 - 1) // 13 == 3 slots, so the third one stays empty. + pad = input_pipeline_utils.PadOrTrimToMaxLength(40, 0, config=config) + embeddings, image_masks = encode(pad._pad_image_and_mask(output)) # pylint: disable=protected-access + self.assertEqual(embeddings.shape[1], 3) + text = jnp.full((1, len(tokens), embeddings.shape[-1]), 7.0) + merged = np.asarray(mm_utils.merge_mm_embeddings(text, embeddings, mask, token_masks=image_masks))[0] + + alone = [ + np.asarray(encode(processor_gemma4.preprocess_mm_data_gemma4([image], config))[0])[0, 0, :count] + for image, count in zip(images, counts) + ] + np.testing.assert_allclose(merged[mask[0]], np.concatenate(alone), rtol=1e-4, atol=1e-5, equal_nan=False) + np.testing.assert_array_equal(merged[~mask[0]], 7.0) + + def test_batch_shape_does_not_depend_on_aspect_ratio(self): + # Per-sample counts would give 1099 // 257 == 4 slots (square) vs 1099 // 281 == 3 (full). + square = self._native(np.zeros((536, 536, 3), dtype=np.uint8)) + full = self._native(np.zeros((672, 960, 3), dtype=np.uint8)) + self.assertEqual(self._pad(square, 1100).pixel_values.shape, self._pad(full, 1100).pixel_values.shape) + + def test_training_preprocess_follows_the_flag(self): + image = np.zeros((536, 536, 3), dtype=np.uint8) + native = mm_processor.preprocess_image_for_training(image, self._native_config()) + self.assertEqual(native.num_soft_tokens_per_image.tolist(), [256]) + fixed_config = self._native_config() + fixed_config.use_native_resolution_for_vit = False + fixed = mm_processor.preprocess_image_for_training(image, fixed_config) + self.assertIsNone(fixed.image_position_ids) + self.assertEqual(fixed.pixel_values.shape, (1, 1, 672, 960, 3)) + + def test_native_resolution_is_on_for_e2b(self): + self.assertTrue(self._pyconfig().use_native_resolution_for_vit) + + def test_rejected_for_other_vision_encoders(self): + with self.assertRaisesRegex(ValueError, "use_native_resolution_for_vit requires"): + self._pyconfig("gemma3-4b", use_multimodal=True, use_native_resolution_for_vit=True) + + def test_shaped_batch_matches_the_pipeline(self): + config = self._pyconfig(use_multimodal=True, use_clipped_linears_for_vit=True, max_target_length=1024) + batch = maxtext_utils.get_shaped_batch(config) + padded = self._pad(self._native(np.zeros((536, 536, 3), dtype=np.uint8)), config.max_target_length) + for key, value in (("images", padded.pixel_values), ("image_position_ids", padded.image_position_ids)): + self.assertEqual(batch[key].shape[1:], value.shape, msg=key) + self.assertEqual(batch[key].dtype, value.dtype, msg=key) + + if __name__ == "__main__": unittest.main() diff --git a/tests/utils/forward_pass_logit_checker.py b/tests/utils/forward_pass_logit_checker.py index 04985ebe1f..1ee38c420f 100644 --- a/tests/utils/forward_pass_logit_checker.py +++ b/tests/utils/forward_pass_logit_checker.py @@ -281,12 +281,15 @@ def get_data(golden_data_point, config): if config.use_multimodal and audio_values is None: assert "pixel_values" in golden_data_point, "no image found in golden data while use_multimodal=True" + image_position_ids = None if config.use_multimodal and "pixel_values" in golden_data_point: pixel_values = np.asarray(golden_data_point["pixel_values"], dtype=np.float32) max_logging.log(f"pixel_values.shape = {pixel_values.shape}") - # Gemma3 and Gemma4 models expect (num_images, height, width, channels) + # Gemma3 and Gemma4 models expect (num_images, height, width, channels), or Gemma4 [L, F] patches with positions if model_prefix in ["gemma3", "gemma4"]: - if pixel_values.ndim == 2: + if config.use_native_resolution_for_vit: + image_position_ids = np.asarray(golden_data_point["image_position_ids"], dtype=np.int32) + elif pixel_values.ndim == 2: h, w = config.image_size_for_vit p = config.patch_size_for_vit c = pixel_values.shape[-1] // (p * p) @@ -308,6 +311,8 @@ def get_data(golden_data_point, config): c = config.num_channels_for_vit pixel_values = np.reshape(pixel_values, (c, int(grid_t * tps), int(grid_h * p), int(grid_w * p))) pixel_values = np.stack([pixel_values for _ in range(config.global_batch_size_to_train_on)]) + if image_position_ids is not None: + image_position_ids = np.stack([image_position_ids for _ in range(config.global_batch_size_to_train_on)]) else: pixel_values = None @@ -359,7 +364,7 @@ def get_data(golden_data_point, config): decoder_positions = np.stack( [np.arange(config.max_target_length, dtype=np.int32) for _ in range(config.global_batch_size_to_train_on)] ) - return ids, decoder_segment_ids, decoder_positions, logits, seq_len, pixel_values, audio_values + return ids, decoder_segment_ids, decoder_positions, logits, seq_len, pixel_values, audio_values, image_position_ids def main(config, test_args): # pylint: disable=W0621 @@ -412,7 +417,9 @@ def main(config, test_args): # pylint: disable=W0621 nnx_graphdef, nnx_state = nnx.split(model) @jax.jit - def eval_step_nnx(step_state, ids, decoder_positions, decoder_segment_ids, images=None, audios=None): + def eval_step_nnx( + step_state, ids, decoder_positions, decoder_segment_ids, images=None, audios=None, image_position_ids=None + ): """Fused NNX forward pass. Without jit the decoder runs op-by-op and every layer's intermediates stay @@ -428,6 +435,7 @@ def eval_step_nnx(step_state, ids, decoder_positions, decoder_segment_ids, image decoder_segment_ids=decoder_segment_ids, encoder_images=images, encoder_audios=audios, + encoder_image_position_ids=image_position_ids, enable_dropout=False, ) @@ -465,11 +473,13 @@ def eval_step_nnx(step_state, ids, decoder_positions, decoder_segment_ids, image all_data_to_save = [] for golden_data_index, golden_data_point in enumerate(golden_data): max_logging.log(f"\n--- Comparing forward pass for golden data index: {golden_data_index} ---") - ids, decoder_segment_ids, decoder_positions, golden_logits, seq_len, images, audios = get_data( + ids, decoder_segment_ids, decoder_positions, golden_logits, seq_len, images, audios, image_position_ids = get_data( golden_data_point, config ) max_logging.log("maxtext forward pass") - full_train_logits = eval_step_nnx(nnx_state, ids, decoder_positions, decoder_segment_ids, images, audios) + full_train_logits = eval_step_nnx( + nnx_state, ids, decoder_positions, decoder_segment_ids, images, audios, image_position_ids + ) # Only batch element 0 is compared; slice before the allgather so the # full [batch, seq, vocab] logits are never materialized per host. From 458db3c08bbeca408571b586352ccee86cae5ea0 Mon Sep 17 00:00:00 2001 From: nuinashco Date: Fri, 13 Nov 2026 01:15:44 +0000 Subject: [PATCH 26/26] feat(multimodal): allow rows without an image in image SFT datasets --- .../input_pipeline/input_pipeline_utils.py | 3 +++ src/maxtext/multimodal/processor_gemma4.py | 2 ++ tests/unit/multimodal_utils_test.py | 22 +++++++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/src/maxtext/input_pipeline/input_pipeline_utils.py b/src/maxtext/input_pipeline/input_pipeline_utils.py index 89f7e445d5..1a04cb15c6 100644 --- a/src/maxtext/input_pipeline/input_pipeline_utils.py +++ b/src/maxtext/input_pipeline/input_pipeline_utils.py @@ -151,6 +151,7 @@ def merge_image_columns(example, image_columns, max_num_images_per_example): images.extend(example[col]) else: images.append(example[col]) + images = [image for image in images if image is not None] example["images"] = images[:max_num_images_per_example] if max_num_images_per_example > 0 else images return example @@ -160,6 +161,8 @@ def pre_process_image_sft(example, image_column, config): """pre-process image for multimodal SFT""" def _process_image_fn(image): + if image is None: # A row without an image. + image = [] is_video = is_video_file(image) or (isinstance(image, list) and image and is_video_file(image[0])) if is_video: return mm_processor.preprocess_image_for_training(image, config) diff --git a/src/maxtext/multimodal/processor_gemma4.py b/src/maxtext/multimodal/processor_gemma4.py index eb3a6d32e5..b89f9ba226 100644 --- a/src/maxtext/multimodal/processor_gemma4.py +++ b/src/maxtext/multimodal/processor_gemma4.py @@ -66,6 +66,8 @@ def preprocess_mm_data_gemma4(images, config=None): images_in.append(images) else: images_in.extend(images) + if not images_in: + raise ValueError("A row without an image needs use_native_resolution_for_vit=True.") for img in images_in: images_out.append(_resize_and_rescale(img, GEMMA4_IMAGE_HEIGHT, GEMMA4_IMAGE_WIDTH)) diff --git a/tests/unit/multimodal_utils_test.py b/tests/unit/multimodal_utils_test.py index b297b1490f..fb54640bf5 100644 --- a/tests/unit/multimodal_utils_test.py +++ b/tests/unit/multimodal_utils_test.py @@ -428,6 +428,12 @@ def test_reformat_prompt_text_only_fallback(self): mm_processor.reformat_prompt("Tell me a story", "", "llama2-7b", num_images=0), "Tell me a story" ) + def test_merge_image_columns_skips_missing_images(self): + example = {"first": "a", "second": None, "third": ["b", None]} + merged = input_pipeline_utils.merge_image_columns(example, ["first", "second", "third"], 0) + self.assertEqual(merged["images"], ["a", "b"]) + self.assertEqual(input_pipeline_utils.merge_image_columns({"first": None}, ["first"], 2)["images"], []) + def test_get_vision_and_decoder_block_routing(self): # pylint: disable=protected-access # Multimodal Qwen3-VL @@ -757,6 +763,22 @@ def test_training_preprocess_follows_the_flag(self): self.assertIsNone(fixed.image_position_ids) self.assertEqual(fixed.pixel_values.shape, (1, 1, 672, 960, 3)) + def test_row_without_image_gets_only_empty_slots(self): + for missing in (None, []): + output = input_pipeline_utils.pre_process_image_sft({"images": missing}, "images", self._native_config())["images"] + self.assertEqual(output.pixel_values.shape, (0, 2520, 768)) + tokens = mm_processor.prepare_text_for_image_fusion(np.array([1, 2, 3]), self._native_config(), output) + self.assertEqual(tokens.tolist(), [1, 2, 3]) + padded = self._pad(output, 1024) + self.assertEqual(padded.pixel_values.shape, (3, 2520, 768)) + np.testing.assert_array_equal(padded.image_position_ids, mm_utils.IMAGE_POSITION_PAD_VALUE) + + def test_row_without_image_needs_native_resolution(self): + config = self._native_config() + config.use_native_resolution_for_vit = False + with self.assertRaisesRegex(ValueError, "use_native_resolution_for_vit"): + input_pipeline_utils.pre_process_image_sft({"images": None}, "images", config) + def test_native_resolution_is_on_for_e2b(self): self.assertTrue(self._pyconfig().use_native_resolution_for_vit)