Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
bb0c359
Gemma-4 vision: add per-projection clipped-linears (E2B/E4B parity pr…
lokic233 Aug 8, 2026
7734eee
Gemma-4 E2B/E4B: close image parity (padded-patch masking + PLE image…
lokic233 Aug 8, 2026
1e9d2b4
Gemma-4 E2B/E4B: set image-contract defaults in the model configs
lokic233 Aug 8, 2026
8bb801b
M1: fail-closed guard — legacy vision path rejects pre-patchified inp…
lokic233 Aug 9, 2026
375a36e
M3: make 448 clip bounds immutable — stop_gradient at use-site + opti…
lokic233 Aug 9, 2026
8a77804
M4+M5: real post-load clip validation (exact 112/448, min<=max, fail-…
lokic233 Aug 9, 2026
181aa50
M1-M5 in-tree tests: tests/unit/gemma4_clip_linears_test.py (13 tests…
lokic233 Aug 9, 2026
8ab0931
M1/M2/M6: stock-trainer position threading + PLE enum + MM contract gate
lokic233 Aug 9, 2026
0c67c77
M2/M5/M6 in-tree test: Gemma-4 MM static contract gate (enum/causal/f…
lokic233 Aug 9, 2026
250f6c6
M7: Option-S sentinel integrity + placeholder==pooled validators + 5 …
lokic233 Aug 9, 2026
99d6c28
M7.4: sanitize padded-patch rows to zero before attention (isolate no…
lokic233 Aug 9, 2026
c16da94
M8: fail-close packing for E2B/E4B multimodal (any mode) + packing-gu…
lokic233 Aug 9, 2026
da07c52
E2B/E4B ymls: default packing=false (MM does not support packed image…
lokic233 Aug 9, 2026
85f817f
Gemma4-small ViT review: consolidate clip tests into gemma4_small_lay…
lokic233 Aug 25, 2026
99e51a9
Fix trainable_parameters_mask polarity in get_optimizer
lokic233 Oct 25, 2026
19e4d9b
Gemma-4 vision: neutral wording in clipped-linears comments
lokic233 Oct 25, 2026
0aecb7a
Gemma-4 vision: describe pad-row zeroing as design intent
lokic233 Oct 25, 2026
f711ab3
Merge branch 'main' into gemma4-e2b-e4b-vision-clipped-linears
nuinashco Nov 10, 2026
d52f968
fix(testing): convert with clip bounds in the E2B multimodal E2E script
nuinashco Nov 6, 2026
9a4b2ef
fix(config): keep packing on for text-only Gemma-4 E2B/E4B runs
nuinashco Nov 6, 2026
525518e
feat(nnx): add UntrainableParam for weights that are never trained
nuinashco Nov 10, 2026
3a2de92
refactor(gemma4): make the vision clip bounds UntrainableParam
nuinashco Nov 10, 2026
1809692
fix(gemma4): make std_bias and std_scale UntrainableParam
nuinashco Nov 10, 2026
0a523cd
fix(gemma4): make layer_scalar UntrainableParam
nuinashco Nov 10, 2026
5509b92
feat(multimodal): pass per-patch image positions through the input pi…
nuinashco Nov 10, 2026
273722e
feat(gemma4): native-resolution image preprocessing
nuinashco Nov 11, 2026
458db3c
feat(multimodal): allow rows without an image in image SFT datasets
nuinashco Nov 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/maxtext/checkpoint_conversion/to_maxtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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, {})
Expand Down
21 changes: 20 additions & 1 deletion src/maxtext/checkpoint_conversion/utils/param_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -3385,7 +3385,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(
Expand Down Expand Up @@ -3441,6 +3443,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 <proj>_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}

Expand Down
4 changes: 2 additions & 2 deletions src/maxtext/common/checkpointing.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@

from etils import epath
from flax import nnx
from flax.nnx import variablelib
from flax import struct


Expand All @@ -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
Expand Down Expand Up @@ -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"
Expand Down
18 changes: 18 additions & 0 deletions src/maxtext/common/common_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 (
Expand Down
12 changes: 12 additions & 0 deletions src/maxtext/configs/base.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1572,6 +1572,18 @@ 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
# 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"
Expand Down
12 changes: 11 additions & 1 deletion src/maxtext/configs/models/gemma4-e2b.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -58,3 +59,12 @@ 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
ple_pad_substitute_image_rows: True
ple_pad_mode: "identity"
image_placeholder_token_id: 258880
ple_pad_token_id: 0
10 changes: 9 additions & 1 deletion src/maxtext/configs/models/gemma4-e4b.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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
115 changes: 112 additions & 3 deletions src/maxtext/configs/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3629,6 +3629,54 @@ 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."
),
)
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=(
"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' (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(
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').",
Expand Down Expand Up @@ -6281,16 +6329,77 @@ 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:
# Gemma 4 small (E2B / E4B) only supports text for now; multimodal
# support is pending clipped-linears in the vision encoder.
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:
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."
)
# ---- 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"):
raise ValueError(f"Multimodal is not yet supported for {self.model_name}; only text inputs are supported.")
# (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",
"gemma3-27b",
"gemma4-26b",
"gemma4-31b",
"gemma4-e2b",
"gemma4-e4b",
"llama4-17b-16e",
"llama4-17b-128e",
"qwen3-omni-30b-a3b",
Expand Down
1 change: 1 addition & 0 deletions src/maxtext/inference/decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading