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
10 changes: 7 additions & 3 deletions benchmarks/api_server/maxtext_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ class GenerationStream:
tokens: np.ndarray
true_length: int
image: Optional[np.ndarray]
image_position_ids: Optional[np.ndarray] = None

# Output accumulators
generated_ids: List[int] = field(default_factory=list)
Expand Down Expand Up @@ -307,9 +308,11 @@ def _initialize_streams_and_state(self, prompts, image_paths, seed, is_chat=None
is_chat = [False] * len(prompts)
streams = []
for prompt, image_path, prompt_is_chat in zip(prompts, image_paths, is_chat):
toks, tlen, imgs = self._preprocess_inputs(prompt, prefill_length, image_path, is_chat=prompt_is_chat)
toks, tlen, imgs, image_position_ids = self._preprocess_inputs(
prompt, prefill_length, image_path, is_chat=prompt_is_chat
)
assert tlen <= prefill_length, f"Input token length {tlen} is > {prefill_length}"
streams.append(GenerationStream(tokens=toks, true_length=tlen, image=imgs))
streams.append(GenerationStream(tokens=toks, true_length=tlen, image=imgs, image_position_ids=image_position_ids))

if seed is not None:
rng = jax.random.PRNGKey(seed)
Expand Down Expand Up @@ -348,6 +351,7 @@ def _run_prefill_step(self, streams, decode_state, rng, logprobs, echo, temperat
padded_tokens=stream.tokens,
true_length=stream.true_length,
images=stream.image,
image_position_ids=stream.image_position_ids,
rng=rng_prefill,
slot=i,
return_prompt_logp=want_prompt_logp,
Expand Down Expand Up @@ -546,7 +550,7 @@ def _preprocess_inputs(self, text, prefill_length, image_path, is_chat=False):
tokens = mm_processor.prepare_text_for_image_fusion(tokens, config=self.config, processor_output=processor_output)
true_length += mm_processor.get_image_offsets(config=self.config, processor_output=processor_output)

return tokens, true_length, images
return tokens, true_length, images, processor_output.image_position_ids

def _validate_config(self, config):
"""Validates configuration."""
Expand Down
1 change: 1 addition & 0 deletions benchmarks/multimodal/multimodal_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ def main(config, local_args):
image_masks=getattr(processor_output, "pixel_mask", None)
if config.use_multimodal and "llama4" in config.model_name
else None,
image_position_ids=processor_output.image_position_ids if config.use_multimodal else None,
audio_values=getattr(processor_output, "audio_values", None) if config.use_audio else None,
audio_masks=getattr(processor_output, "audio_mask", None) if config.use_audio else None,
true_length=true_length,
Expand Down
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
10 changes: 9 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,10 @@ 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
# 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"
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,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,10 @@ 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
# 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"
ple_pad_token_id: 0
54 changes: 51 additions & 3 deletions src/maxtext/configs/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -4784,6 +4784,33 @@ 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_native_resolution_for_vit: bool = Field(
False,
description=(
"Gemma 4: 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="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."
),
)
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 +8658,37 @@ 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}."
)
Comment on lines +8661 to +8664

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two missing config guards for use_native_resolution_for_vit=True:

  1. vision_output_length defaults to -1 (L4917), so a custom config without it hits ZeroDivisionError in get_max_num_images (image_offset = 0). Please validate self.vision_output_length > 0.
  2. When max_target_length <= vision_output_length + 1 (e.g. <= 281 on default E2B/E4B), mm_utils.get_max_num_images returns 0, yielding 0-sized (B, 0, 2520, 768) tensors in get_dummy_patch_shape_for_init_gemma4 (processor_gemma4.py:285-292) and hitting jnp.clip(cumsum_mask - 1, 0, -1) in merge_mm_embeddings (utils.py:224). Please fail fast with a clear ValueError when max_num_images < 1.

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 and 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
1 change: 1 addition & 0 deletions src/maxtext/inference/decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,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