Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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 @@ -61,9 +61,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 @@ -442,7 +442,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
48 changes: 48 additions & 0 deletions src/maxtext/checkpoint_conversion/utils/hf_shape.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,54 @@ def GEMMA4_SMALL_HF_WEIGHTS_TO_SHAPE(config):
shapes[f"{hf_prefix}.per_layer_projection.weight"] = [hidden_size, ple_dim]
shapes[f"{hf_prefix}.post_per_layer_input_norm.weight"] = [hidden_size]

# The vision tower of GEMMA4_HF_WEIGHTS_TO_SHAPE; E2B / E4B store no std weights and add clip bounds.
if vision_cfg:
vis_hidden = vision_cfg["hidden_size"]
vis_intermediate = vision_cfg["intermediate_size"]
vis_num_layers = vision_cfg["num_hidden_layers"]
vis_num_heads = vision_cfg["num_attention_heads"]
vis_head_dim = vision_cfg["head_dim"]
vis_q_dim = vis_num_heads * vis_head_dim
vis_kv_heads = vision_cfg.get("num_key_value_heads", vis_num_heads)
vis_kv_dim = vis_kv_heads * vis_head_dim
vis_pos_emb_size = vision_cfg.get("position_embedding_size", 10240)
vis_patch_size = vision_cfg.get("patch_size", 16)
num_channels = vision_cfg.get("num_channels", 3) # RGB
patch_flat = num_channels * vis_patch_size * vis_patch_size

# VisionEntry: input_proj is a linear [patch_flat, vis_hidden] transposed to [vis_hidden, patch_flat]
shapes["model.vision_tower.patch_embedder.input_proj.weight"] = [vis_hidden, patch_flat]
# pos_emb_param MaxText shape (N, 2, D) -> transpose(1, 0, 2) -> HF (2, N, D)
shapes["model.vision_tower.patch_embedder.position_embedding_table"] = [2, vis_pos_emb_size, vis_hidden]
if vision_cfg.get("standardize", False):
shapes["model.vision_tower.std_scale"] = [vis_hidden]
shapes["model.vision_tower.std_bias"] = [vis_hidden]
# Vision projector: [vis_hidden, hidden_size] -> reshape_kernel -> [hidden_size, vis_hidden]
shapes["model.embed_vision.embedding_projection.weight"] = [hidden_size, vis_hidden]

for i in range(vis_num_layers):
vis_prefix = f"model.vision_tower.encoder.layers.{i}"
shapes[f"{vis_prefix}.self_attn.q_proj.linear.weight"] = [vis_q_dim, vis_hidden]
shapes[f"{vis_prefix}.self_attn.k_proj.linear.weight"] = [vis_kv_dim, vis_hidden]
shapes[f"{vis_prefix}.self_attn.v_proj.linear.weight"] = [vis_kv_dim, vis_hidden]
shapes[f"{vis_prefix}.self_attn.o_proj.linear.weight"] = [vis_hidden, vis_q_dim]
shapes[f"{vis_prefix}.self_attn.q_norm.weight"] = [vis_head_dim]
shapes[f"{vis_prefix}.self_attn.k_norm.weight"] = [vis_head_dim]
shapes[f"{vis_prefix}.input_layernorm.weight"] = [vis_hidden]
shapes[f"{vis_prefix}.post_attention_layernorm.weight"] = [vis_hidden]
shapes[f"{vis_prefix}.pre_feedforward_layernorm.weight"] = [vis_hidden]
shapes[f"{vis_prefix}.post_feedforward_layernorm.weight"] = [vis_hidden]
shapes[f"{vis_prefix}.mlp.gate_proj.linear.weight"] = [vis_intermediate, vis_hidden]
shapes[f"{vis_prefix}.mlp.up_proj.linear.weight"] = [vis_intermediate, vis_hidden]
shapes[f"{vis_prefix}.mlp.down_proj.linear.weight"] = [vis_hidden, vis_intermediate]

if vision_cfg.get("use_clipped_linears", False):
projections = ("self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj")
projections += ("mlp.gate_proj", "mlp.up_proj", "mlp.down_proj")
for projection in projections:
for bound in ("input_min", "input_max", "output_min", "output_max"):
shapes[f"{vis_prefix}.{projection}.{bound}"] = [] # a scalar

return shapes


Expand Down
38 changes: 28 additions & 10 deletions src/maxtext/checkpoint_conversion/utils/param_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -3439,7 +3439,7 @@ def _spec_active(gate):
return mapping


def GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(config, maxtext_config, scan_layers=False):
def GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(config, maxtext_config, scan_layers=False, saving_to_hf=False):
"""MaxText↔HF weight-path map for Gemma 4 small (E2B / E4B).

The small variants thread per-layer state (PLE input + donor K/V) through
Expand Down Expand Up @@ -3494,16 +3494,15 @@ def GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(config, maxtext_config, scan_layers
}
)
if not is_shared:
mapping.update( # pyrefly: ignore[no-matching-overload]
mapping.update(
{
f"{prefix}-self_attention-key-kernel": f"{hf_prefix}.self_attn.k_proj.weight",
f"{prefix}-self_attention-value-kernel": f"{hf_prefix}.self_attn.v_proj.weight",
f"{prefix}-self_attention-key_norm-scale": f"{hf_prefix}.self_attn.k_norm.weight",
f"{prefix}-self_attention-value_norm-scale": f"{hf_prefix}.self_attn.v_norm.weight"
if maxtext_config.v_norm_with_scale
else None,
}
)
if maxtext_config.v_norm_with_scale:
mapping[f"{prefix}-self_attention-value_norm-scale"] = f"{hf_prefix}.self_attn.v_norm.weight"
if ple_dim > 0:
mapping.update(
{
Expand All @@ -3513,7 +3512,6 @@ 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.
if maxtext_config.use_multimodal and vcfg:
nvis = vcfg.get("num_hidden_layers", 0)
mapping.update(
Expand All @@ -3536,6 +3534,14 @@ def GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(config, maxtext_config, scan_layers
"params-vision_encoder-Gemma4VisionEncoderLayer_0-std_bias": "model.vision_tower.std_bias",
}
)
elif saving_to_hf:
# E2B / E4B checkpoints have no std_scale / std_bias; None keeps them out of the export.
mapping.update( # pyrefly: ignore[no-matching-overload]
{
"params-vision_encoder-Gemma4VisionEncoderLayer_0-std_scale": None,
"params-vision_encoder-Gemma4VisionEncoderLayer_0-std_bias": None,
}
)
else:
# E2B / E4B ship with ``standardize=false`` and do not store
# ``std_scale`` / ``std_bias`` in the safetensors. Point at any
Expand Down Expand Up @@ -3570,7 +3576,21 @@ def GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(config, maxtext_config, scan_layers
}
)

return {k: v for k, v in mapping.items() if v is not None}
if maxtext_config.use_clipped_linears_for_vit:
_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 mapping


def GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_HOOK_FN(config, maxtext_config, scan_layers=False, saving_to_hf=False):
Expand Down Expand Up @@ -3646,9 +3666,7 @@ def reshape_to_target(input_tensor, target_shape):
hooks[f"{prefix}-{k}"] = reshape_kernel
hooks[f"{prefix}-post_per_layer_input_norm-scale"] = scale_rmsnorm_layer

# TODO: gemma4-small multimodal not yet supported — vision-encoder hooks below are dead.
# When it lands: standardize=false branch synthesizes ones/zeros so the standardize op is
# a no-op (E2B / E4B don't ship std_scale / std_bias in their safetensors).
# E2B / E4B don't ship std_scale / std_bias: the standardize=false branch synthesizes ones/zeros for them.
if maxtext_config.use_multimodal and vcfg:
big_hooks = GEMMA4_MAXTEXT_TO_HF_PARAM_HOOK_FN(config, maxtext_config, scan_layers=False, saving_to_hf=saving_to_hf)
for key, fn in big_hooks.items():
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 @@ -20,8 +20,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 @@ -40,6 +43,21 @@
DEEPSEEK_V3_ROUTING_MODEL_PREFIXES = ("deepseek3", "deepseek4", "kimi-k2", "ming", "hy4", "kimi-k3")


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
9 changes: 8 additions & 1 deletion src/maxtext/configs/models/gemma4-e2b.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@ 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.
vision_encoder_block: "gemma4"
use_clipped_linears_for_vit: true # The checkpoint stores clip bounds for the vision projections.
rope_theta_for_vit: 100
image_size_for_vit: [672, 960]
num_channels_for_vit: 3
Expand All @@ -58,3 +59,9 @@ num_attention_heads_for_vit: 12
image_placeholder: "<|image|>"
vision_output_length: 280
num_position_embeddings_for_vit: 10240
# Image handling in the decoder: causal image tokens, pad token in the per-layer embedding on image rows.
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
9 changes: 8 additions & 1 deletion src/maxtext/configs/models/gemma4-e4b.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ 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.
vision_encoder_block: "gemma4"
use_clipped_linears_for_vit: true # The checkpoint stores clip bounds for the vision projections.
rope_theta_for_vit: 100
image_size_for_vit: [672, 960]
num_channels_for_vit: 3
Expand All @@ -59,3 +60,9 @@ num_attention_heads_for_vit: 12
image_placeholder: "<|image|>"
vision_output_length: 280
num_position_embeddings_for_vit: 10240
# Image handling in the decoder: causal image tokens, pad token in the per-layer embedding on image rows.
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
47 changes: 44 additions & 3 deletions src/maxtext/configs/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -4784,6 +4784,27 @@ 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 E2B/E4B: clamp the vision projections with the clip bounds of the checkpoint.",
)
use_bidirectional_image_attn: bool = Field(
False,
description="Gemma 4 E2B/E4B decoder: image tokens attend in both directions. These models require False.",
)
ple_pad_substitute_image_rows: bool = Field(
False,
description="Gemma 4 E2B/E4B: image placeholder rows look up ple_pad_token_id in the per-layer embedding.",
)
ple_pad_mode: str = Field(
"identity",
description=(
"With ple_pad_substitute_image_rows: 'identity' replaces the token ids only, as Hugging Face does; "
"'both' also replaces the embeddings given to the per-layer embedder."
),
)
image_placeholder_token_id: int = Field(258880, description="Gemma 4 image placeholder token id.")
ple_pad_token_id: int = Field(0, description="Pad token id used by ple_pad_substitute_image_rows.")
vision_encoder_block: VisionEncoderBlockType = Field(
VisionEncoderBlockType.NONE,
description="The style of VisionEncoderBlock to use (e.g., 'gemma3', 'llama4').",
Expand Down Expand Up @@ -8631,16 +8652,36 @@ 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.model_name in ("gemma4-e2b", "gemma4-e4b"):
raise ValueError(f"Multimodal is not yet supported for {self.model_name}; only text inputs are supported.")
if not self.use_clipped_linears_for_vit:
raise ValueError(f"Multimodal for {self.model_name} requires use_clipped_linears_for_vit=True.")

if self.ple_pad_mode not in ("identity", "both"):
raise ValueError(f"ple_pad_mode must be 'identity' or 'both', got '{self.ple_pad_mode}'.")

if self.ple_pad_substitute_image_rows:
if self.image_placeholder_token_id < 0:
raise ValueError("image_placeholder_token_id must be non-negative.")
if self.ple_pad_token_id < 0:
raise ValueError("ple_pad_token_id must be non-negative.")

if self.use_bidirectional_image_attn:
raise ValueError(f"{self.model_name} image tokens are causal: use_bidirectional_image_attn must be False.")

# Every projection has its own clip bounds, so projections cannot be fused.
if self.fused_qkv:
raise ValueError(f"Multimodal for {self.model_name} requires fused_qkv=False.")
if self.fused_mlp:
raise ValueError(f"Multimodal for {self.model_name} requires fused_mlp=False.")

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
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def embed_multimodal(
)

with mesh, logical_axis_rules(maxtext_config.logical_axis_rules):
image_embeddings, _ = model.vision_encoder(input_images=input_images, deterministic=True)
image_embeddings, _, _ = model.vision_encoder(input_images=input_images, deterministic=True)
embeddings.append(image_embeddings.squeeze(0))
current_idx += image_size

Expand Down
10 changes: 8 additions & 2 deletions src/maxtext/layers/encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,19 @@ 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:
# Patches with their positions: the encoder also returns the mask of valid image tokens.
encoder_output, vision_image_masks = encoder(
input_images, deterministic=deterministic, image_position_ids=image_position_ids
)
else:
encoder_output = encoder(input_images, deterministic=deterministic)
deep_feats = None
Expand All @@ -129,7 +135,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):
Expand Down
4 changes: 2 additions & 2 deletions src/maxtext/layers/initializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, ...]
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading