From 8115c2210b7f7c57920d904de863c6e3b7903efb Mon Sep 17 00:00:00 2001 From: nuinashco Date: Tue, 10 Nov 2026 02:07:07 +0000 Subject: [PATCH 1/7] 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 | 45 ++++- .../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, 387 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 af2f367983..3000234a82 100644 --- a/src/maxtext/checkpoint_conversion/to_maxtext.py +++ b/src/maxtext/checkpoint_conversion/to_maxtext.py @@ -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 @@ -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, {}) diff --git a/src/maxtext/common/checkpointing.py b/src/maxtext/common/checkpointing.py index e77af6b063..13ea1a3053 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 c5169ad4a8..d58f1197f7 100644 --- a/src/maxtext/common/common_types.py +++ b/src/maxtext/common/common_types.py @@ -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 @@ -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 ( 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 eed1618be1..b2723af5ca 100644 --- a/src/maxtext/optimizers/optimizers.py +++ b/src/maxtext/optimizers/optimizers.py @@ -23,7 +23,7 @@ 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 @@ -55,6 +55,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) @@ -317,8 +354,8 @@ def update_fn(updates, state, params=None): return optax.GradientTransformation(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( @@ -403,6 +440,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 bcb742f791..2529309f93 100644 --- a/src/maxtext/trainers/post_train/distillation/train_distill.py +++ b/src/maxtext/trainers/post_train/distillation/train_distill.py @@ -84,7 +84,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 @@ -97,6 +97,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: @@ -118,11 +119,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: @@ -605,12 +609,14 @@ def build_training_components( is_offline: bool = False, offline_data_dir: str | None = None, mesh=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). @@ -653,7 +659,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, @@ -785,7 +791,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, mesh=mesh + student_config, teacher_config, is_offline, offline_data_dir, mesh=mesh, 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 740d691e0f..6a2db8ec41 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 5aa6e501d4..ff59d67097 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 @@ -613,8 +614,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 * @@ -649,6 +650,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 @@ -665,7 +669,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 edbcfea0cc..d71b068c34 100644 --- a/tests/post_training/unit/rl_utils_test.py +++ b/tests/post_training/unit/rl_utils_test.py @@ -374,6 +374,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 c1dfab173d..c35bc9d35d 100644 --- a/tests/post_training/unit/train_distill_test.py +++ b/tests/post_training/unit/train_distill_test.py @@ -37,6 +37,7 @@ from jax.sharding import Mesh # 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 @@ -434,6 +435,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 c5634528fd..9730d8aea1 100644 --- a/tests/unit/optimizers_test.py +++ b/tests/unit/optimizers_test.py @@ -22,6 +22,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 @@ -916,6 +917,88 @@ def test_apply_trainable_parameters_mask_warns_on_empty_or_full_freeze(self): self.assertIn("froze EVERY parameter", mock_warning.call_args[0][0]) +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 38312047907862e60fc365215164d9ef578f0a5b Mon Sep 17 00:00:00 2001 From: nuinashco Date: Tue, 10 Nov 2026 05:03:50 +0000 Subject: [PATCH 2/7] 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 a27f90bc77..0f966caef7 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 @@ -347,7 +347,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 975348c4e9..af8af4fe1b 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 @@ -428,7 +428,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 bbce6d68524eea56098ef45136d6094467de6533 Mon Sep 17 00:00:00 2001 From: nuinashco Date: Wed, 25 Nov 2026 22:29:04 +0000 Subject: [PATCH 3/7] fix(nnx): keep UntrainableParam in params through the ToNNX bridge --- src/maxtext/layers/nnx_wrappers.py | 4 ++-- tests/unit/untrainable_param_test.py | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/maxtext/layers/nnx_wrappers.py b/src/maxtext/layers/nnx_wrappers.py index 05b416ff85..2169dcf1ff 100644 --- a/src/maxtext/layers/nnx_wrappers.py +++ b/src/maxtext/layers/nnx_wrappers.py @@ -81,7 +81,7 @@ def to_nnx_var(col: str, x: meta.AxisMetadata | Any) -> variablelib.Variable: """Convert a Linen variable to an NNX variable.""" vtype = variablelib.variable_type_from_name(col, allow_register=True) if isinstance(x, nnx.bridge.NNXMeta): - assert vtype == x.var_type, f"Type stored in NNXMeta {x.var_type} != type inferred from collection name {vtype}" + assert variable_collection_name(x.var_type) == col, f"Type stored in NNXMeta {x.var_type} is not in collection {col}" return x.to_nnx_variable() if isinstance(x, meta.AxisMetadata): x_metadata = vars(x) @@ -133,7 +133,7 @@ def nnx_attrs_to_linen_vars(nnx_attrs: dict) -> dict: # attaches bookkeeping attrs like qwix_path/qwix_rngs/disable_quant_stats_update # to the module during interception; leave them on the module and skip them here. continue - col_name = variablelib.variable_name_from_type(v.type) + col_name = variable_collection_name(v.type) v = to_linen_var(v) linen_structured[(col_name, *kp)] = v variables = nnx.traversals.unflatten_mapping(linen_structured) diff --git a/tests/unit/untrainable_param_test.py b/tests/unit/untrainable_param_test.py index 948600edb6..cd3384b7ff 100644 --- a/tests/unit/untrainable_param_test.py +++ b/tests/unit/untrainable_param_test.py @@ -57,6 +57,17 @@ def __call__(self, x): return jnp.minimum(x * self.kernel[...], self.bound[...]) +class _Scaled(nnx.Module): + """A Param and an untrainable weight that has metadata.""" + + def __init__(self): + self.kernel = nnx.Param(jnp.ones(1)) + self.scale = UntrainableParam(jnp.full(1, 2.0), sharding=(None,)) + + def __call__(self, x): + return x * self.kernel[...] * self.scale[...] + + 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))) @@ -172,6 +183,13 @@ def test_bridge_keeps_it_in_the_params_collection(self): grads = jax.grad(lambda variables: model.apply(variables, x).sum())(loaded) np.testing.assert_array_equal(grads["params"]["bound"], np.zeros(3)) + def test_round_trip_through_to_nnx_keeps_the_type(self): + x = jnp.ones(1) + model = nnx_wrappers.ToNNX(nnx_wrappers.to_linen(_Scaled, skip_rng=True), rngs=nnx.Rngs(0)).lazy_init(x) + + self.assertIsInstance(model.scale, UntrainableParam) + np.testing.assert_array_equal(model(x), [2.0]) + if __name__ == "__main__": unittest.main() From 1b53cb980ced3f0f28df937ab543b8d46431826f Mon Sep 17 00:00:00 2001 From: nuinashco Date: Wed, 25 Nov 2026 22:29:04 +0000 Subject: [PATCH 4/7] fix(optimizers): freeze weights whose value is a pytree --- src/maxtext/optimizers/optimizers.py | 15 +++++++++------ tests/unit/optimizers_test.py | 11 +++++++++++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/maxtext/optimizers/optimizers.py b/src/maxtext/optimizers/optimizers.py index b2723af5ca..f2b72fd619 100644 --- a/src/maxtext/optimizers/optimizers.py +++ b/src/maxtext/optimizers/optimizers.py @@ -63,20 +63,23 @@ def untrainable_paths(model): 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] +def _path_str(path): + """A pytree key path as "a/b/c".""" return jax.tree_util.keystr(path, simple=True, separator="/") +def _is_frozen(path, frozen_paths): + """True if the leaf at `path` is, or lies inside, a weight in `frozen_paths`.""" + return any(_path_str(path[:end]) in frozen_paths for end in range(1, len(path) + 1)) + + 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 + lambda path, _: "frozen" if _is_frozen(path, frozen_paths) else "trainable", params ) tx = optax.multi_transform({"trainable": tx, "frozen": optax.set_to_zero()}, labels) @@ -84,7 +87,7 @@ def labels(params): 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) + name = _path_str(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) diff --git a/tests/unit/optimizers_test.py b/tests/unit/optimizers_test.py index 9730d8aea1..4e868f992d 100644 --- a/tests/unit/optimizers_test.py +++ b/tests/unit/optimizers_test.py @@ -981,6 +981,17 @@ def factory(learning_rate): tx = optax.inject_hyperparams(factory)(learning_rate=1.0) self._assert_untrainable_unchanged(model, self._apply_zero_grads(model, tx)) + def test_freeze_covers_a_weight_whose_value_is_a_pytree(self): + model = nnx.Dict(quantized=nnx.Param({"qvalue": jnp.ones(2), "scale": jnp.ones(1)}), kernel=nnx.Param(jnp.ones(2))) + tx = optimizers.freeze_params(optax.adamw(1.0, weight_decay=0.5), frozenset({"quantized"})) + optimizer = self._apply_zero_grads(model, tx) + + self.assertTrue(jnp.array_equal(model.kernel[...], jnp.full(2, 0.5))) + for value in model.quantized.get_value().values(): + self.assertTrue(jnp.array_equal(value, jnp.ones_like(value))) + slots = [jax.tree_util.keystr(path) for path, _ in jax.tree_util.tree_leaves_with_path(nnx.state(optimizer))] + self.assertFalse([s for s in slots if "quantized" in s], slots) + def test_no_untrainable_params_leaves_optimizer_state_unchanged(self): params = {"kernel": jnp.ones((2, 2))} config = self._config("opt_type=adamw") From ea59b6da1149535c0536271344d6bc396f5d2042 Mon Sep 17 00:00:00 2001 From: nuinashco Date: Sat, 28 Nov 2026 05:54:32 +0000 Subject: [PATCH 5/7] feat(gemma4): add image support for E2B/E4B (vision clip bounds, padded patches, pad token in PLE) Co-authored-by: Loki Chen --- .../utils/param_mapping.py | 19 +- src/maxtext/configs/models/gemma4-e2b.yml | 9 +- src/maxtext/configs/models/gemma4-e4b.yml | 9 +- src/maxtext/configs/types.py | 47 +++- .../vllm/maxtext_vllm_adapter/multimodal.py | 2 +- src/maxtext/layers/encoders.py | 10 +- src/maxtext/layers/nnx_decoders.py | 22 +- src/maxtext/models/gemma4_vision.py | 242 ++++++++++++++++-- src/maxtext/models/models.py | 14 +- src/maxtext/trainers/pre_train/train.py | 4 + tests/end_to_end/tpu/gemma4/Run_Gemma4.md | 4 +- .../tpu/gemma4/e2b/convert_gemma4.sh | 5 +- .../tpu/gemma4/e2b/convert_gemma4_base.sh | 5 +- .../tpu/gemma4/e2b/test_gemma4_multimodal.sh | 63 +++++ .../tpu/gemma4/e4b/convert_gemma4.sh | 4 +- .../tpu/gemma4/e4b/convert_gemma4_base.sh | 4 +- tests/unit/gemma4_small_test.py | 163 ++++++++++++ tests/unit/qwen3_omni_layers_test.py | 6 +- tests/unit/train_nnx_test.py | 10 + 19 files changed, 588 insertions(+), 54 deletions(-) create mode 100755 tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh diff --git a/src/maxtext/checkpoint_conversion/utils/param_mapping.py b/src/maxtext/checkpoint_conversion/utils/param_mapping.py index 56e44c7d76..9f728462b1 100644 --- a/src/maxtext/checkpoint_conversion/utils/param_mapping.py +++ b/src/maxtext/checkpoint_conversion/utils/param_mapping.py @@ -3513,7 +3513,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( @@ -3570,6 +3569,20 @@ def GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(config, maxtext_config, scan_layers } ) + 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 {k: v for k, v in mapping.items() if v is not None} @@ -3646,9 +3659,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(): diff --git a/src/maxtext/configs/models/gemma4-e2b.yml b/src/maxtext/configs/models/gemma4-e2b.yml index 81c8d4ea66..a2c6ca4d1b 100644 --- a/src/maxtext/configs/models/gemma4-e2b.yml +++ b/src/maxtext/configs/models/gemma4-e2b.yml @@ -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 @@ -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 diff --git a/src/maxtext/configs/models/gemma4-e4b.yml b/src/maxtext/configs/models/gemma4-e4b.yml index b8da0d1d46..a7a1547a4b 100644 --- a/src/maxtext/configs/models/gemma4-e4b.yml +++ b/src/maxtext/configs/models/gemma4-e4b.yml @@ -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 @@ -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 diff --git a/src/maxtext/configs/types.py b/src/maxtext/configs/types.py index 19f18ce992..1721fdf4de 100644 --- a/src/maxtext/configs/types.py +++ b/src/maxtext/configs/types.py @@ -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').", @@ -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", diff --git a/src/maxtext/integration/vllm/maxtext_vllm_adapter/multimodal.py b/src/maxtext/integration/vllm/maxtext_vllm_adapter/multimodal.py index 6ade25d43b..a1dd93c0cc 100644 --- a/src/maxtext/integration/vllm/maxtext_vllm_adapter/multimodal.py +++ b/src/maxtext/integration/vllm/maxtext_vllm_adapter/multimodal.py @@ -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 diff --git a/src/maxtext/layers/encoders.py b/src/maxtext/layers/encoders.py index f43cc786bd..2681780625 100644 --- a/src/maxtext/layers/encoders.py +++ b/src/maxtext/layers/encoders.py @@ -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 @@ -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): diff --git a/src/maxtext/layers/nnx_decoders.py b/src/maxtext/layers/nnx_decoders.py index af217dff93..0607d1a922 100644 --- a/src/maxtext/layers/nnx_decoders.py +++ b/src/maxtext/layers/nnx_decoders.py @@ -2652,6 +2652,7 @@ def __call__( attention_metadata=attention_metadata, previous_chunk=previous_chunk, slot=slot, + shared_embedding=shared_embedding, ) elif cfg.scan_layers and not self.is_kimi_linear: # Kimi-K3 scans inside _apply_kimi_layers. if self.is_deepseek: @@ -3571,14 +3572,33 @@ 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 bidirectional_mask_value = multimodal_input.bidirectional_mask if multimodal_input is not None else None + if not cfg.use_bidirectional_image_attn: + 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 + + # As in Hugging Face, image placeholder rows look up the pad token in the per-layer embedding. + if cfg.ple_pad_substitute_image_rows and multimodal_input is not None: + tokens = decoder_input_tokens.astype(jnp.int32) + is_image_row = tokens == cfg.image_placeholder_token_id + ple_tokens = jnp.where(is_image_row, cfg.ple_pad_token_id, tokens) + + if cfg.ple_pad_mode == "both": + if shared_embedding is None: + raise ValueError("ple_pad_mode='both' requires shared_embedding.") + + pad_embeddings = shared_embedding(jnp.full_like(tokens, cfg.ple_pad_token_id), model_mode=model_mode) + ple_context = jnp.where(is_image_row[..., None], pad_embeddings, 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 f673488608..f0ca394b9c 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -16,17 +16,53 @@ """Vision transformer implementation for Gemma4.""" from typing import cast +import functools +import operator import jax import jax.numpy as jnp 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, MODEL_MODE_TRAIN, UntrainableParam from maxtext.layers import attentions from maxtext.layers import linears from maxtext.layers import normalizations +POSITIONS_PAD_VALUE = -1 + + +def _mk_clip_bound(init_val=jnp.nan): + """Scalar clip bound; NaN until a checkpoint is loaded.""" + return UntrainableParam(jnp.asarray(init_val, dtype=jnp.float32)) + + +class _ClipBounds(nnx.Module): + """Input and output clamp range of one vision projection, stored in the E2B/E4B checkpoint.""" + + 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 _clip_in(x, cb): + """Clamps a projection input; no-op if `cb` is None.""" + if cb is None: + return x + + return jnp.clip(x, cb.input_min.value.astype(x.dtype), cb.input_max.value.astype(x.dtype)) + + +def _clip_out(y, cb): + """Clamps a projection output; no-op if `cb` is None.""" + if cb is None: + return y + + return jnp.clip(y, cb.output_min.value.astype(y.dtype), cb.output_max.value.astype(y.dtype)) + + def factorized_posemb(posemb: jax.Array, positions_xy: jax.Array, precision) -> jax.Array: """Computes factorized position embedding from (x, y) coordinates. @@ -318,8 +354,6 @@ def _maybe_downsample( """Downsamples the vision features if required by the output length.""" cur_length = x.shape[1] - POSITIONS_PAD_VALUE = -1 - if cur_length == length: if positions_xy is None: mask = jnp.ones(x.shape[:-1], dtype=jnp.bool_) @@ -408,6 +442,8 @@ def __call__(self, inputs: jax.Array, positions: jax.Array) -> jax.Array: class Gemma4Attention(attentions.Attention): """Gemma 4 specific Attention module.""" + _use_clipped_linears = False + def init_rotary_embedding(self) -> Gemma4VisionRotaryEmbedding: """Initializes the rotary position embedding module for Gemma 4 vision.""" return Gemma4VisionRotaryEmbedding( @@ -415,6 +451,106 @@ def init_rotary_embedding(self) -> Gemma4VisionRotaryEmbedding: rotary_fraction=None, # Or assume it from config if available ) + def enable_vision_clip_bounds(self): + """Makes the q, k, v and o projections clamp their input and output.""" + if self.config.fused_qkv: + raise ValueError("Gemma 4 vision clip bounds require fused_qkv=False: q, k and v have separate bounds.") + + self._use_clipped_linears = True + self.q_clip = _ClipBounds() + self.k_clip = _ClipBounds() + self.v_clip = _ClipBounds() + self.o_clip = _ClipBounds() + + def query_projection(self, inputs_q, out_sharding=None, model_mode=MODEL_MODE_TRAIN): + if not self._use_clipped_linears: + return super().query_projection(inputs_q, out_sharding=out_sharding, model_mode=model_mode) + + x = _clip_in(inputs_q, self.q_clip) + y = super().query_projection(x, out_sharding=out_sharding, model_mode=model_mode) + return _clip_out(y, self.q_clip) + + def kv_projection(self, inputs_kv, proj_name, out_sharding=None): + if not self._use_clipped_linears: + 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, *, model_mode=None): + if not self._use_clipped_linears: + return super().out_projection(out, out_sharding=out_sharding, model_mode=model_mode) + + x = _clip_in(out, self.o_clip) + y = super().out_projection(x, out_sharding=out_sharding, model_mode=model_mode) + return _clip_out(y, self.o_clip) + + +class Gemma4ClippedMlpBlock(linears.MlpBlock): + """MlpBlock that clamps the input and output of the gate (wi_0), up (wi_1) and down (wo) projections.""" + + def __init__(self, *args, use_clipped_linears=False, **kwargs): + super().__init__(*args, **kwargs) + + self._use_clipped_linears = use_clipped_linears + if self._use_clipped_linears: + self.gate_clip = _ClipBounds() + self.up_clip = _ClipBounds() + self.down_clip = _ClipBounds() + + 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 cfg.fused_mlp: + raise ValueError("Gemma 4 vision clip bounds require fused_mlp=False: gate and up have separate bounds.") + + if self.mlp_layer_norm is not None: + inputs = self.mlp_layer_norm(inputs) + + # The unfused MlpBlock path with a clamp around every projection. + clips = [self.gate_clip, self.up_clip] + 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).""" @@ -484,7 +620,8 @@ def __init__( is_vision=True, rngs=self.rngs, ) - + if config.use_clipped_linears_for_vit: + self.attention.enable_vision_clip_bounds() self.pre_ffw_norm = normalizations.RMSNorm( num_features=config.hidden_size_for_vit, dtype=config.dtype_mm, @@ -503,7 +640,9 @@ def __init__( rngs=self.rngs, ) - self.mlp = linears.MlpBlock( + mlp_cls = Gemma4ClippedMlpBlock if config.use_clipped_linears_for_vit else linears.MlpBlock + mlp_kwargs = {"use_clipped_linears": True} if config.use_clipped_linears_for_vit else {} + self.mlp = mlp_cls( config=config, mesh=mesh, in_features=config.hidden_size_for_vit, @@ -513,13 +652,26 @@ 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: - """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); patches of different segments do not attend to each other.""" 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) + 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 @@ -563,32 +715,78 @@ 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,) ) - def __call__(self, inputs: jax.Array, deterministic: bool = False) -> jax.Array: - """Applies the vision encoder layer.""" - 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)) + def __call__( + self, + inputs: jax.Array, + deterministic: bool = False, + image_position_ids: jax.Array | None = None, + ): + """Applies the vision encoder layer. + + Args: + inputs: Images [B, N, H, W, C] or [B, H, W, C]. With `image_position_ids`: patches [B, N, L, F] or [B, L, F]. + deterministic: Disables dropout. + image_position_ids: (x, y) of every patch, [B, N, L, 2] or [B, L, 2]; (-1, -1) marks a padded patch. + + Returns: + Embeddings [B, N, K, D]. With `image_position_ids`: also the mask of valid image tokens, [B * N, K]. + """ + decoder_segment_ids = None + if image_position_ids is None: + if inputs.ndim not in (4, 5): + raise ValueError( + f"Expected images of shape [B, H, W, C] or [B, N, H, W, C], got {inputs.shape}; " + "patches need image_position_ids." + ) + + 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) + x, positions_xy = self.vision_entry(inputs_flat) + else: + if inputs.ndim == 4: + 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"Expected patches of shape [B, L, F], 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)) + + pos = pos.astype(jnp.int32) + is_pad = (pos == POSITIONS_PAD_VALUE).all(axis=-1) + + # Zero padded patches before and after the projection, so NaN in them reaches neither valid patches nor gradients. + patches = jnp.where(is_pad[..., None], jnp.zeros_like(patches), patches) + x, positions_xy = self.vision_entry(patches, positions_xy=pos) + x = jnp.where(is_pad[..., None], jnp.zeros_like(x), x) + + # Valid and padded patches are different segments, so they do not attend to each other. + 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) 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 = (embeddings - self.std_bias.value.astype(embeddings.dtype)) * self.std_scale.value.astype( embeddings.dtype @@ -597,7 +795,11 @@ def __call__(self, inputs: jax.Array, deterministic: bool = False) -> jax.Array: # Unflatten batch and num_images final_x = jnp.reshape(embeddings, (b, n, embeddings.shape[1], embeddings.shape[2])) - return final_x + if image_position_ids is None: + return final_x + + # merge_mm_embeddings sorts by -mask, which needs integers. + return final_x, image_masks.astype(jnp.int32) class Gemma4VisionProjector(nnx.Module): diff --git a/src/maxtext/models/models.py b/src/maxtext/models/models.py index 45c6790d1f..3afbf46ff0 100644 --- a/src/maxtext/models/models.py +++ b/src/maxtext/models/models.py @@ -206,6 +206,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, @@ -260,16 +261,21 @@ def __call__( video_embeddings = None audio_embeddings = None deepstack_visual_embeds = None + vision_image_masks = None if getattr(self.config, "use_multimodal", False) and self.vision_encoder is not None 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 self.vision_encoder is not None 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, @@ -292,7 +298,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, diff --git a/src/maxtext/trainers/pre_train/train.py b/src/maxtext/trainers/pre_train/train.py index 9066d0e6d1..fc9d1603d8 100644 --- a/src/maxtext/trainers/pre_train/train.py +++ b/src/maxtext/trainers/pre_train/train.py @@ -101,6 +101,7 @@ class EncoderKwargs(TypedDict, total=False): encoder_images: Any encoder_image_masks: Any + encoder_image_position_ids: Any encoder_videos: Any encoder_video_masks: Any encoder_video_grid_thw: Any @@ -226,6 +227,9 @@ def loss_fn(model, config, data, dropout_rng, params, sparsity_state=None, is_tr "encoder_images": encoder_images, "encoder_image_masks": encoder_image_masks, } + # Only Gemma 4 takes image positions, so they are passed only when the batch has them. + if config.use_multimodal and "image_position_ids" in data: + encoder_kwargs["encoder_image_position_ids"] = data["image_position_ids"] # Flax NNX model: forward pass, then pop Intermediates sown during it. logits = model( decoder_input_tokens=data["inputs"], diff --git a/tests/end_to_end/tpu/gemma4/Run_Gemma4.md b/tests/end_to_end/tpu/gemma4/Run_Gemma4.md index 3138444bf6..47d0d47be3 100644 --- a/tests/end_to_end/tpu/gemma4/Run_Gemma4.md +++ b/tests/end_to_end/tpu/gemma4/Run_Gemma4.md @@ -29,7 +29,7 @@ E2B and E4B are the **edge-device** ("E") variants — both **dense** (no MoE) - **Per-Layer Embedding (PLE).** Each decoder layer consumes a per-layer slice of an extra embedding tensor injected by `Gemma4SmallPLE`. Controlled by `hidden_size_per_layer_input` and `vocab_size_per_layer_input`. - **KV sharing.** The last `num_kv_shared_layers` layers reuse the K / V projections from the most recent non-shared layer of the same attention type (sliding↔sliding, full↔full). E2B additionally widens the MLP on shared layers (`use_double_wide_mlp: true`). -Both features are tied to per-layer state that is not expressible inside `nn.scan`, so E2B / E4B require `scan_layers=false`. Multimodal is currently gated off for these variants; the model validator raises a clear error if you try to enable `use_multimodal=true`. +Both features are tied to per-layer state that is not expressible inside `nn.scan`, so E2B / E4B require `scan_layers=false`. Image inputs are enabled with `use_multimodal=true`, as for the larger variants. ## Pre-training You can train from scratch to generate a new checkpoint. One example command to run pretraining Gemma4-26B model is as follows: @@ -64,7 +64,7 @@ This will convert the checkpoints and save them to a Google Cloud Storage (GCS) ### E2B / E4B conversion (text-only) -For the small variants, drop `use_multimodal=true` — multimodal is not supported. Conversion scripts live at `tests/end_to_end/tpu/gemma4/e2b/convert_gemma4.sh` (instruction-tuned) and `tests/end_to_end/tpu/gemma4/e2b/convert_gemma4_base.sh` (pre-trained base), and the same pair under `tests/end_to_end/tpu/gemma4/e4b/`. They follow the same shape as the larger Gemma 4 scripts. Example: +The scripts below convert the small variants without the vision tower (`use_multimodal=false`); `tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh` converts E2B with it and checks the logits for an image. Conversion scripts live at `tests/end_to_end/tpu/gemma4/e2b/convert_gemma4.sh` (instruction-tuned) and `tests/end_to_end/tpu/gemma4/e2b/convert_gemma4_base.sh` (pre-trained base), and the same pair under `tests/end_to_end/tpu/gemma4/e4b/`. They follow the same shape as the larger Gemma 4 scripts. Example: ```sh python3 -m maxtext.checkpoint_conversion.to_maxtext src/maxtext/configs/base.yml \ diff --git a/tests/end_to_end/tpu/gemma4/e2b/convert_gemma4.sh b/tests/end_to_end/tpu/gemma4/e2b/convert_gemma4.sh index 5b310d85b1..0703cf9165 100755 --- a/tests/end_to_end/tpu/gemma4/e2b/convert_gemma4.sh +++ b/tests/end_to_end/tpu/gemma4/e2b/convert_gemma4.sh @@ -2,9 +2,8 @@ # End-to-end conversion + forward-pass logit check for Gemma 4 E2B (text-only). # -# Multimodal is gated off for E2B / E4B by `MaxTextConfig.validate_model_size` -# and is not exercised here. See `tests/end_to_end/tpu/gemma4/Run_Gemma4.md` -# for an overview. +# Text only; images are checked by `test_gemma4_multimodal.sh`. See +# `tests/end_to_end/tpu/gemma4/Run_Gemma4.md` for an overview. set -ex idx=$(date +%Y-%m-%d-%H-%M) diff --git a/tests/end_to_end/tpu/gemma4/e2b/convert_gemma4_base.sh b/tests/end_to_end/tpu/gemma4/e2b/convert_gemma4_base.sh index 7a8b9c9cea..706165b94a 100755 --- a/tests/end_to_end/tpu/gemma4/e2b/convert_gemma4_base.sh +++ b/tests/end_to_end/tpu/gemma4/e2b/convert_gemma4_base.sh @@ -2,9 +2,8 @@ # End-to-end conversion + forward-pass logit check for Gemma 4 E2B (pre-trained). # -# Multimodal is gated off for E2B / E4B by `MaxTextConfig.validate_model_size` -# and is not exercised here. See `tests/end_to_end/tpu/gemma4/Run_Gemma4.md` -# for an overview. +# Text only; images are checked by `test_gemma4_multimodal.sh`. See +# `tests/end_to_end/tpu/gemma4/Run_Gemma4.md` for an overview. set -ex idx=$(date +%Y-%m-%d-%H-%M) 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..9ea88562ea --- /dev/null +++ b/tests/end_to_end/tpu/gemma4/e2b/test_gemma4_multimodal.sh @@ -0,0 +1,63 @@ +#!/bin/bash + +# End-to-end image parity check for Gemma 4 E2B: converts the Hugging Face checkpoint with the +# vision tower, generates Hugging Face golden logits for an image and a prompt, and compares the +# MaxText logits with them. 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. +# 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} \ + model_name=${MODEL_NAME} \ + use_multimodal=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/end_to_end/tpu/gemma4/e4b/convert_gemma4.sh b/tests/end_to_end/tpu/gemma4/e4b/convert_gemma4.sh index d88e9cd28c..b8eaf00866 100755 --- a/tests/end_to_end/tpu/gemma4/e4b/convert_gemma4.sh +++ b/tests/end_to_end/tpu/gemma4/e4b/convert_gemma4.sh @@ -2,9 +2,7 @@ # End-to-end conversion + forward-pass logit check for Gemma 4 E4B (instruction-tuned). # -# Multimodal is gated off for E2B / E4B by `MaxTextConfig.validate_model_size` -# and is not exercised here. See `tests/end_to_end/tpu/gemma4/Run_Gemma4.md` -# for an overview. +# Text only. See `tests/end_to_end/tpu/gemma4/Run_Gemma4.md` for an overview. set -ex idx=$(date +%Y-%m-%d-%H-%M) diff --git a/tests/end_to_end/tpu/gemma4/e4b/convert_gemma4_base.sh b/tests/end_to_end/tpu/gemma4/e4b/convert_gemma4_base.sh index 88f9219ab7..e86da68432 100755 --- a/tests/end_to_end/tpu/gemma4/e4b/convert_gemma4_base.sh +++ b/tests/end_to_end/tpu/gemma4/e4b/convert_gemma4_base.sh @@ -2,9 +2,7 @@ # End-to-end conversion + forward-pass logit check for Gemma 4 E4B (pre-trained). # -# Multimodal is gated off for E2B / E4B by `MaxTextConfig.validate_model_size` -# and is not exercised here. See `tests/end_to_end/tpu/gemma4/Run_Gemma4.md` -# for an overview. +# Text only. See `tests/end_to_end/tpu/gemma4/Run_Gemma4.md` for an overview. set -ex idx=$(date +%Y-%m-%d-%H-%M) diff --git a/tests/unit/gemma4_small_test.py b/tests/unit/gemma4_small_test.py index 2c41424b6c..f3a2051c03 100644 --- a/tests/unit/gemma4_small_test.py +++ b/tests/unit/gemma4_small_test.py @@ -31,10 +31,12 @@ from maxtext.layers import nnx_decoders from maxtext.models import gemma4 from maxtext.models import gemma4_small +from maxtext.models import gemma4_vision from maxtext.optimizers import optimizers from maxtext.utils.globals import MAXTEXT_CONFIGS_DIR +_BASE_CONFIG_PATH = os.path.join(MAXTEXT_CONFIGS_DIR, "base.yml") L = AttentionType.LOCAL_SLIDING G = AttentionType.GLOBAL @@ -272,5 +274,166 @@ def test_layer_scalar_is_untrainable(self): self.assertIn("layer_scalar", self._untrainable_paths("gemma4-26b", gemma4.Gemma4DecoderLayer)) +# The tests below call private helpers of gemma4_vision. +# pylint: disable=protected-access + + +def _finite_cb(in_lo=-2.5, in_hi=2.5, out_lo=-4.0, out_hi=4.0): + cb = gemma4_vision._ClipBounds() + 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_bounds_are_untrainable_params(self): + cb = gemma4_vision._ClipBounds() + 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) + self.assertTrue(bool(jnp.array_equal(gemma4_vision._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(gemma4_vision._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(gemma4_vision._clip_in(x, None), x))) + self.assertTrue(bool(jnp.array_equal(gemma4_vision._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(gemma4_vision._clip_in(x, cb).dtype, jnp.bfloat16) + + def test_bounds_are_stop_gradient(self): + # The bounds are UntrainableParam, so the gradient wrt a bound is zero even when the clamp is active. + def loss(bound_val): + cb = gemma4_vision._ClipBounds() + cb.input_min, cb.input_max = gemma4_vision._mk_clip_bound(-100.0), gemma4_vision._mk_clip_bound(bound_val) + x = jnp.ones((4,), jnp.float32) * 10.0 # above the bound, so the clamp is active + return jnp.sum(gemma4_vision._clip_in(x, cb)) + + g = jax.grad(loss)(jnp.asarray(2.5, jnp.float32)) + self.assertEqual(float(g), 0.0) + + +class VisionStdTest(unittest.TestCase): + + def test_std_bias_and_std_scale_are_untrainable(self): + config = _init_gate_config([]) + mesh = Mesh(np.array(jax.devices()[:1]), axis_names=("data",)) + encoder = nnx.eval_shape(lambda: gemma4_vision.Gemma4VisionEncoderLayer(config, mesh, rngs=nnx.Rngs(0))) + self.assertLessEqual({"std_bias", "std_scale"}, optimizers.untrainable_paths(encoder)) + + +def _init_gate_config(overrides): + """A gemma4-e2b multimodal config with the given overrides.""" + argv = [ + "test", + _BASE_CONFIG_PATH, + "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): + cfg = _init_gate_config([]) + self.assertEqual(cfg.model_name, "gemma4-e2b") + self.assertTrue(cfg.use_multimodal) + self.assertTrue(cfg.use_clipped_linears_for_vit) + self.assertEqual(str(cfg.ple_pad_mode), "identity") + + def test_unknown_ple_pad_mode_hard_fails(self): + with self.assertRaises(Exception): + _init_gate_config(["ple_pad_mode=bogus"]) + + def test_both_ple_pad_mode_is_valid_ablation_enum(self): + cfg = _init_gate_config(["ple_pad_mode=both"]) + self.assertEqual(str(cfg.ple_pad_mode), "both") + + def test_bidirectional_image_attn_hard_fails(self): + with self.assertRaises(Exception): + _init_gate_config(["use_bidirectional_image_attn=true"]) + + def test_fused_qkv_hard_fails(self): + with self.assertRaises(Exception): + _init_gate_config(["fused_qkv=true"]) + + def test_fused_mlp_hard_fails(self): + with self.assertRaises(Exception): + _init_gate_config(["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): + # Only multimodal SFT loads images; packing there is rejected, as for every multimodal model. + with self.assertRaisesRegex(Exception, "packing"): + _init_gate_config(["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}") + + +class Gemma4VisionPaddedPatchTest(unittest.TestCase): + """The padded-patch path of the vision tower.""" + + def test_nan_in_a_padded_patch_keeps_gradients_finite(self): + config = _init_gate_config( + [ + "hidden_size_for_vit=8", + "intermediate_size_for_vit=16", + "num_hidden_layers_for_vit=1", + "num_attention_heads_for_vit=2", + "patch_size_for_vit=2", + "vision_output_length=4", + "num_position_embeddings_for_vit=8", + ] + ) + mesh = Mesh(np.array(jax.devices()[:1]), axis_names=("data",)) + encoder = gemma4_vision.Gemma4VisionEncoderLayer(config, mesh, rngs=nnx.Rngs(0)) + for _, node in nnx.iter_graph(encoder): + if isinstance(node, gemma4_vision._ClipBounds): + node.input_min.value, node.input_max.value = jnp.float32(-1e4), jnp.float32(1e4) + node.output_min.value, node.output_max.value = jnp.float32(-1e4), jnp.float32(1e4) + + # Three real patches and one padded patch that holds NaN. + patch_dim = config.patch_size_for_vit**2 * config.num_channels_for_vit + patches = jnp.full((1, 4, patch_dim), 0.5).at[0, 3].set(jnp.nan) + positions = jnp.array([[[0, 0], [1, 0], [0, 1], [-1, -1]]]) + + def loss_fn(model): + image_embeddings, _ = model(patches, deterministic=True, image_position_ids=positions) + return image_embeddings.sum() + + loss, grads = nnx.value_and_grad(loss_fn)(encoder) + self.assertTrue(jnp.isfinite(loss)) + for path, grad in nnx.to_flat_state(grads): + self.assertTrue(jnp.isfinite(grad.get_value()).all(), f"non-finite gradient at {path}") + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/qwen3_omni_layers_test.py b/tests/unit/qwen3_omni_layers_test.py index 0258a4f308..a19007b01e 100644 --- a/tests/unit/qwen3_omni_layers_test.py +++ b/tests/unit/qwen3_omni_layers_test.py @@ -851,11 +851,11 @@ def test_padded_video_projected_outputs_match_unpadded_batched(self): vision_encoder = VisionEncoder(config=config, mesh=self.mesh, rngs=nnx.Rngs(42)) # Run individual unpadded - raw_output_1, _ = vision_encoder(raw_video_1) - raw_output_2, _ = vision_encoder(raw_video_2) + raw_output_1, _, _ = vision_encoder(raw_video_1) + raw_output_2, _, _ = vision_encoder(raw_video_2) # Run batched padded - batched_padded_output, _ = vision_encoder( + batched_padded_output, _, _ = vision_encoder( batched_padded_video, input_masks=batched_video_mask, video_grid_thw=batched_grid_thw, diff --git a/tests/unit/train_nnx_test.py b/tests/unit/train_nnx_test.py index 75ac5e3959..719c6ce84e 100644 --- a/tests/unit/train_nnx_test.py +++ b/tests/unit/train_nnx_test.py @@ -395,6 +395,16 @@ def test_multimodal_model_accepts_text_only_batch(self): self.assertTrue(jnp.isfinite(loss)) + def test_image_position_ids_in_the_batch_reach_the_model(self): + cfg, ts = _build_state() + cfg.use_multimodal = True + data = _make_data(batch=cfg.micro_batch_size_to_train_on, vocab=cfg.vocab_size) + data["image_position_ids"] = jnp.zeros((cfg.micro_batch_size_to_train_on, 4, 2), jnp.int32) + + # _TinyDecoder has no such argument, so the call fails exactly when the positions are passed. + with self.assertRaisesRegex(TypeError, "encoder_image_position_ids"): + pre_train.loss_fn(ts.model, cfg, data, None, None, is_train=True) + def test_indexer_dense_warmup_skips_xent(self): cfg, ts = _build_state() cfg.use_indexer = True From 8225a25ad895a1be7d1da0d20b777753ac0a0dae Mon Sep 17 00:00:00 2001 From: nuinashco Date: Sat, 28 Nov 2026 06:16:47 +0000 Subject: [PATCH 6/7] feat(checkpoint): validate loaded weights through a module hook (Gemma 4 vision clip bounds) --- src/maxtext/models/gemma4_vision.py | 12 ++++ src/maxtext/utils/model_creation_utils.py | 13 ++++ src/maxtext/utils/train_utils.py | 4 +- tests/unit/gemma4_small_test.py | 76 ++++++++++++++++++----- tests/unit/model_creation_utils_test.py | 43 +++++++++++++ tests/unit/train_utils_test.py | 44 +++++++++++++ 6 files changed, 174 insertions(+), 18 deletions(-) diff --git a/src/maxtext/models/gemma4_vision.py b/src/maxtext/models/gemma4_vision.py index f0ca394b9c..6ef72119fe 100644 --- a/src/maxtext/models/gemma4_vision.py +++ b/src/maxtext/models/gemma4_vision.py @@ -17,6 +17,7 @@ from typing import cast import functools +import math import operator import jax import jax.numpy as jnp @@ -46,6 +47,17 @@ def __init__(self): self.output_min = _mk_clip_bound() self.output_max = _mk_clip_bound() + def validate_loaded_weights(self): + """Raises if the checkpoint left a bound unset or a range empty.""" + bounds = {name: getattr(self, name).value.item() for name in ("input_min", "input_max", "output_min", "output_max")} + + not_finite = [name for name, value in bounds.items() if not math.isfinite(value)] + if not_finite: + raise ValueError(f"clip bounds {not_finite} are not finite") + + if bounds["input_min"] > bounds["input_max"] or bounds["output_min"] > bounds["output_max"]: + raise ValueError(f"clip range is empty: {bounds}") + def _clip_in(x, cb): """Clamps a projection input; no-op if `cb` is None.""" diff --git a/src/maxtext/utils/model_creation_utils.py b/src/maxtext/utils/model_creation_utils.py index a30f40f3b0..f902212e50 100644 --- a/src/maxtext/utils/model_creation_utils.py +++ b/src/maxtext/utils/model_creation_utils.py @@ -1192,6 +1192,16 @@ def _create_pathways_zarr2_registry( ) +def validate_loaded_weights(model: nnx.Module) -> None: + """Runs `validate_loaded_weights()` of every submodule that defines it; call it after weights were loaded.""" + for path, module in nnx.iter_graph(model): + if isinstance(module, nnx.Module) and hasattr(module, "validate_loaded_weights"): + try: + module.validate_loaded_weights() + except ValueError as e: + raise ValueError(f"{'/'.join(map(str, path))}: {e}") from e + + # pylint: disable=too-many-positional-arguments def from_pretrained( config, @@ -1591,6 +1601,9 @@ def _walk_align(ckpt, model_arr, axes): "Please ensure the checkpoint format matches the scan_layers setting." ) + if loads_safetensors_dynamic or config.load_parameters_path: + validate_loaded_weights(model) + if wrap_with_tunix_adapter: model = apply_tunix_adapter(model, config, tokenizer_pad_id) diff --git a/src/maxtext/utils/train_utils.py b/src/maxtext/utils/train_utils.py index 86941521be..e85f5627b5 100644 --- a/src/maxtext/utils/train_utils.py +++ b/src/maxtext/utils/train_utils.py @@ -483,7 +483,7 @@ def create_train_state_fn(): snapshotter = None else: snapshotter = elastic_retry_cache.snapshotter - state, _, state_mesh_shardings, data_iterator, _ = maxtext_utils.setup_training_state( + state, _, state_mesh_shardings, data_iterator, was_restored = maxtext_utils.setup_training_state( data_iterator, config, mesh, checkpoint_manager, init_state_fn, snapshotter=snapshotter ) if getattr(getattr(config, "lora", None), "enable_lora", False) and getattr(config.lora, "lora_restore_path", None): @@ -566,6 +566,8 @@ def create_train_state_fn(): else: train_state = nnx.merge(state_graphdef, state) # pyrefly: ignore[unbound-name] model = train_state.model + if was_restored: # pyrefly: ignore[unbound-name] + model_creation_utils.validate_loaded_weights(model) return ( init_rng, diff --git a/tests/unit/gemma4_small_test.py b/tests/unit/gemma4_small_test.py index f3a2051c03..c99c8ac874 100644 --- a/tests/unit/gemma4_small_test.py +++ b/tests/unit/gemma4_small_test.py @@ -33,6 +33,7 @@ from maxtext.models import gemma4_small from maxtext.models import gemma4_vision from maxtext.optimizers import optimizers +from maxtext.utils import model_creation_utils from maxtext.utils.globals import MAXTEXT_CONFIGS_DIR @@ -398,27 +399,36 @@ def test_text_only_keeps_packing(self): self.assertTrue(config.packing, msg=f"{model} {packing}") +def _tiny_vision_encoder(): + """A one-block E2B vision tower with unset clip bounds, and its config.""" + config = _init_gate_config( + [ + "hidden_size_for_vit=8", + "intermediate_size_for_vit=16", + "num_hidden_layers_for_vit=1", + "num_attention_heads_for_vit=2", + "patch_size_for_vit=2", + "vision_output_length=4", + "num_position_embeddings_for_vit=8", + ] + ) + mesh = Mesh(np.array(jax.devices()[:1]), axis_names=("data",)) + return config, gemma4_vision.Gemma4VisionEncoderLayer(config, mesh, rngs=nnx.Rngs(0)) + + +def _set_clip_bounds(module, limit): + for _, node in nnx.iter_graph(module): + if isinstance(node, gemma4_vision._ClipBounds): + node.input_min.value, node.input_max.value = jnp.float32(-limit), jnp.float32(limit) + node.output_min.value, node.output_max.value = jnp.float32(-limit), jnp.float32(limit) + + class Gemma4VisionPaddedPatchTest(unittest.TestCase): """The padded-patch path of the vision tower.""" def test_nan_in_a_padded_patch_keeps_gradients_finite(self): - config = _init_gate_config( - [ - "hidden_size_for_vit=8", - "intermediate_size_for_vit=16", - "num_hidden_layers_for_vit=1", - "num_attention_heads_for_vit=2", - "patch_size_for_vit=2", - "vision_output_length=4", - "num_position_embeddings_for_vit=8", - ] - ) - mesh = Mesh(np.array(jax.devices()[:1]), axis_names=("data",)) - encoder = gemma4_vision.Gemma4VisionEncoderLayer(config, mesh, rngs=nnx.Rngs(0)) - for _, node in nnx.iter_graph(encoder): - if isinstance(node, gemma4_vision._ClipBounds): - node.input_min.value, node.input_max.value = jnp.float32(-1e4), jnp.float32(1e4) - node.output_min.value, node.output_max.value = jnp.float32(-1e4), jnp.float32(1e4) + config, encoder = _tiny_vision_encoder() + _set_clip_bounds(encoder, 1e4) # Three real patches and one padded patch that holds NaN. patch_dim = config.patch_size_for_vit**2 * config.num_channels_for_vit @@ -435,5 +445,37 @@ def loss_fn(model): self.assertTrue(jnp.isfinite(grad.get_value()).all(), f"non-finite gradient at {path}") +class ClipBoundsValidationTest(unittest.TestCase): + + def test_loaded_bounds_pass(self): + _finite_cb().validate_loaded_weights() + + def test_unset_bound_fails(self): + with self.assertRaisesRegex(ValueError, "not finite"): + gemma4_vision._ClipBounds().validate_loaded_weights() + + def test_infinite_bound_fails(self): + cb = _finite_cb() + cb.input_max.value = jnp.asarray(np.inf, jnp.float32) + with self.assertRaisesRegex(ValueError, "input_max"): + cb.validate_loaded_weights() + + def test_empty_range_fails(self): + with self.assertRaisesRegex(ValueError, "empty"): + _finite_cb(in_lo=3.0, in_hi=-3.0).validate_loaded_weights() + + def test_hook_checks_every_bound_of_the_tower(self): + _, encoder = _tiny_vision_encoder() + with self.assertRaisesRegex(ValueError, "layer_0/.*_clip: clip bounds .* are not finite"): + model_creation_utils.validate_loaded_weights(encoder) + + _set_clip_bounds(encoder, 1e4) + model_creation_utils.validate_loaded_weights(encoder) + + encoder.layer_0.mlp.down_clip.output_max.value = jnp.float32(jnp.nan) + with self.assertRaisesRegex(ValueError, "layer_0/mlp/down_clip: clip bounds .'output_max'. are not finite"): + model_creation_utils.validate_loaded_weights(encoder) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/model_creation_utils_test.py b/tests/unit/model_creation_utils_test.py index ffa0072e5f..995ce1ff55 100644 --- a/tests/unit/model_creation_utils_test.py +++ b/tests/unit/model_creation_utils_test.py @@ -931,6 +931,22 @@ def fake_load(*args, **kwargs): for leaf in jax.tree.leaves(nnx.state(model, nnx.Param)): np.testing.assert_array_equal(leaf, np.full(leaf.shape, 0.5, leaf.dtype)) + @patch("maxtext.utils.model_creation_utils.checkpointing.load_state_if_possible") + def test_validates_weights_after_a_load(self, mock_load): + mock_load.side_effect = lambda *args, **kwargs: (None, jax.tree.map(lambda x: jnp.zeros(x.shape, x.dtype), args[5])) + cfg = _make_config(load_parameters_path="/fake/hf_repo", source_checkpoint_layout="safetensors_dynamic") + + with patch.object(model_creation_utils, "validate_loaded_weights") as mock_validate: + model = model_creation_utils.from_pretrained(cfg, self.mesh) + + mock_validate.assert_called_once_with(model) + + def test_does_not_validate_weights_without_a_load(self): + with patch.object(model_creation_utils, "validate_loaded_weights") as mock_validate: + model_creation_utils.from_pretrained(self.config, self.mesh) + + mock_validate.assert_not_called() + @patch("maxtext.utils.model_creation_utils.checkpointing.load_state_if_possible") def test_load_safetensors_dynamic_frees_initial_weights(self, mock_load): """The model's initial weights are deleted before the loader places its copy.""" @@ -1368,6 +1384,33 @@ def test_scan_layers_missing_metadata_no_error(self, mock_ocp, mock_load_meta): self.assertIsInstance(model, models.Transformer) +class _SelfChecking(nnx.Module): + + def __init__(self, ok): + self.ok = ok + + def validate_loaded_weights(self): + if not self.ok: + raise ValueError("bad weights") + + +class _Parent(nnx.Module): + + def __init__(self, ok): + self.plain = nnx.Linear(2, 2, rngs=nnx.Rngs(0)) + self.checked = _SelfChecking(ok) + + +class TestValidateLoadedWeights(unittest.TestCase): + + def test_passes_when_every_submodule_passes(self): + model_creation_utils.validate_loaded_weights(_Parent(ok=True)) + + def test_error_names_the_submodule(self): + with self.assertRaisesRegex(ValueError, "checked: bad weights"): + model_creation_utils.validate_loaded_weights(_Parent(ok=False)) + + class TestSetupDecodeStateFromNnx(unittest.TestCase): """Tests for setup_decode_state_from_nnx().""" diff --git a/tests/unit/train_utils_test.py b/tests/unit/train_utils_test.py index 0315544efd..4ea6da354f 100644 --- a/tests/unit/train_utils_test.py +++ b/tests/unit/train_utils_test.py @@ -34,10 +34,13 @@ import pytest from maxtext.common import grain_utility +from maxtext.configs import pyconfig from maxtext.input_pipeline import multihost_dataloading from maxtext.trainers.pre_train import train from maxtext.utils import elastic_utils from maxtext.utils import max_utils +from maxtext.utils import maxtext_utils +from maxtext.utils import model_creation_utils from maxtext.utils import sharding from maxtext.utils import train_utils from maxtext.utils.train_utils import ( @@ -45,6 +48,7 @@ create_training_optimizer, validate_completed_steps, ) +from tests.utils.test_helpers import get_test_config_path @dataclass @@ -642,5 +646,45 @@ def test_repeated_hbm_budget_exceeded_with_the_same_override_propagates(self): self.mocks["cleanup_iterators"].assert_called_once() +class TestSetupTrainLoopValidatesWeights(unittest.TestCase): + """setup_train_loop runs the weight validation hook only for a restored state.""" + + def _setup_train_loop(self, was_restored): + """Runs setup_train_loop on a tiny model whose state reports `was_restored`; returns the model and the hook mock.""" + config = pyconfig.initialize( + [sys.argv[0], get_test_config_path()], + run_name="test", + enable_checkpointing=False, + dataset_type="synthetic", + model_name="llama3.1-8b", + override_model_config=True, + base_emb_dim=32, + base_mlp_dim=64, + base_num_query_heads=2, + base_num_kv_heads=2, + base_num_decoder_layers=2, + vocab_size=64, + max_target_length=16, + ) + setup_training_state = maxtext_utils.setup_training_state + + def report(*args, **kwargs): + return (*setup_training_state(*args, **kwargs)[:4], was_restored) + + with mock.patch.object(maxtext_utils, "setup_training_state", side_effect=report): + with mock.patch.object(model_creation_utils, "validate_loaded_weights") as mock_validate: + model = train_utils.setup_train_loop(config, None)[3] + + return model, mock_validate + + def test_validates_weights_of_a_restored_state(self): + model, mock_validate = self._setup_train_loop(was_restored=True) + mock_validate.assert_called_once_with(model) + + def test_does_not_validate_a_fresh_state(self): + _, mock_validate = self._setup_train_loop(was_restored=False) + mock_validate.assert_not_called() + + if __name__ == "__main__": absltest.main() From bdc3919676ba4817937720d6e0ae7cefed1f1805 Mon Sep 17 00:00:00 2001 From: nuinashco Date: Sun, 29 Nov 2026 15:13:02 +0000 Subject: [PATCH 7/7] feat(gemma4): export the E2B/E4B vision tower to Hugging Face Co-authored-by: Loki Chen --- .../checkpoint_conversion/utils/hf_shape.py | 48 ++++++ .../utils/param_mapping.py | 19 +- tests/unit/hf_shape_test.py | 162 ++++++++++++++++++ 3 files changed, 223 insertions(+), 6 deletions(-) create mode 100644 tests/unit/hf_shape_test.py diff --git a/src/maxtext/checkpoint_conversion/utils/hf_shape.py b/src/maxtext/checkpoint_conversion/utils/hf_shape.py index 2a108d37aa..4dda70aa7f 100644 --- a/src/maxtext/checkpoint_conversion/utils/hf_shape.py +++ b/src/maxtext/checkpoint_conversion/utils/hf_shape.py @@ -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 diff --git a/src/maxtext/checkpoint_conversion/utils/param_mapping.py b/src/maxtext/checkpoint_conversion/utils/param_mapping.py index 9f728462b1..a53f4fb8f0 100644 --- a/src/maxtext/checkpoint_conversion/utils/param_mapping.py +++ b/src/maxtext/checkpoint_conversion/utils/param_mapping.py @@ -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 @@ -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( { @@ -3535,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 @@ -3583,7 +3590,7 @@ def GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(config, maxtext_config, scan_layers 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} + return mapping def GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_HOOK_FN(config, maxtext_config, scan_layers=False, saving_to_hf=False): diff --git a/tests/unit/hf_shape_test.py b/tests/unit/hf_shape_test.py new file mode 100644 index 0000000000..a9c8e1e354 --- /dev/null +++ b/tests/unit/hf_shape_test.py @@ -0,0 +1,162 @@ +# Copyright 2023–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. + +"""Tests for the Hugging Face export of Gemma 4 E2B / E4B: the shape map and the weights it covers.""" + +import unittest +from unittest import mock + +from absl.testing import parameterized +import numpy as np +import pytest + +from maxtext.checkpoint_conversion.utils import hf_model_configs +from maxtext.checkpoint_conversion.utils import hf_shape +from maxtext.checkpoint_conversion.utils import param_mapping +from maxtext.checkpoint_conversion.utils import utils + +pytestmark = [pytest.mark.decoupled_target] + +_STD_SCALE = "params-vision_encoder-Gemma4VisionEncoderLayer_0-std_scale" +_STD_BIAS = "params-vision_encoder-Gemma4VisionEncoderLayer_0-std_bias" +_BOUNDS = (".input_min", ".input_max", ".output_min", ".output_max") + + +def _tiny_config(**vision_overrides): + """A config shaped like the Hugging Face one of E2B, with small sizes that all differ from each other.""" + return { + "text_config": { + "num_hidden_layers": 2, + "hidden_size": 4, + "intermediate_size": 8, + "num_attention_heads": 2, + "num_key_value_heads": 1, + "num_global_key_value_heads": 1, + "head_dim": 3, + "global_head_dim": 9, + "vocab_size": 16, + "layer_types": ["sliding_attention", "full_attention"], + }, + "vision_config": { + "hidden_size": 6, + "intermediate_size": 14, + "num_hidden_layers": 2, + "num_attention_heads": 2, + "num_key_value_heads": 1, + "head_dim": 5, + "position_embedding_size": 7, + "patch_size": 2, + "standardize": False, + "use_clipped_linears": True, + } + | vision_overrides, + } + + +def _vision_shapes(config): + shapes = hf_shape.GEMMA4_SMALL_HF_WEIGHTS_TO_SHAPE(config) + return {key: shape for key, shape in shapes.items() if key.startswith(("model.vision_tower.", "model.embed_vision."))} + + +def _maxtext_config(): + return mock.Mock(use_multimodal=True, use_clipped_linears_for_vit=True, v_norm_with_scale=False) + + +class Gemma4SmallVisionShapeTest(parameterized.TestCase): + + def test_vision_shapes(self): + expected = { + "model.vision_tower.patch_embedder.input_proj.weight": [6, 12], + "model.vision_tower.patch_embedder.position_embedding_table": [2, 7, 6], + "model.embed_vision.embedding_projection.weight": [4, 6], + } + for i in range(2): + layer = f"model.vision_tower.encoder.layers.{i}" + expected |= { + f"{layer}.self_attn.q_proj.linear.weight": [10, 6], + f"{layer}.self_attn.k_proj.linear.weight": [5, 6], + f"{layer}.self_attn.v_proj.linear.weight": [5, 6], + f"{layer}.self_attn.o_proj.linear.weight": [6, 10], + f"{layer}.self_attn.q_norm.weight": [5], + f"{layer}.self_attn.k_norm.weight": [5], + f"{layer}.input_layernorm.weight": [6], + f"{layer}.post_attention_layernorm.weight": [6], + f"{layer}.pre_feedforward_layernorm.weight": [6], + f"{layer}.post_feedforward_layernorm.weight": [6], + f"{layer}.mlp.gate_proj.linear.weight": [14, 6], + f"{layer}.mlp.up_proj.linear.weight": [14, 6], + f"{layer}.mlp.down_proj.linear.weight": [6, 14], + } + for projection in ("self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj"): + expected |= {f"{layer}.{projection}{bound}": [] for bound in _BOUNDS} + for projection in ("mlp.gate_proj", "mlp.up_proj", "mlp.down_proj"): + expected |= {f"{layer}.{projection}{bound}": [] for bound in _BOUNDS} + + self.assertEqual(_vision_shapes(_tiny_config()), expected) + + def test_std_weights_only_with_standardize(self): + shapes = _vision_shapes(_tiny_config(standardize=True)) + + self.assertEqual(shapes["model.vision_tower.std_scale"], [6]) + self.assertEqual(shapes["model.vision_tower.std_bias"], [6]) + + def test_no_clip_bounds_without_clipped_linears(self): + shapes = _vision_shapes(_tiny_config(use_clipped_linears=False)) + + self.assertEmpty([key for key in shapes if key.endswith(_BOUNDS)]) + + def test_no_vision_shapes_without_vision_config(self): + config = _tiny_config() + del config["vision_config"] + + self.assertEmpty(_vision_shapes(config)) + + @parameterized.parameters("gemma4-e2b", "gemma4-e4b") + def test_every_exported_weight_of_the_real_config_has_a_shape(self, model_name): + config = hf_model_configs.HF_MODEL_CONFIGS[model_name].to_dict() + shapes = hf_shape.GEMMA4_SMALL_HF_WEIGHTS_TO_SHAPE(config) + mapping = param_mapping.GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(config, _maxtext_config(), saving_to_hf=True) + targets = [target for target in mapping.values() if target is not None] + + self.assertEmpty([target for target in targets if target not in shapes]) + self.assertLen([target for target in targets if target.endswith(_BOUNDS)], 16 * 7 * 4) + + +class Gemma4SmallStdExportTest(parameterized.TestCase): + """E2B / E4B checkpoints have no std_scale / std_bias.""" + + def test_export_skips_std_weights(self): + config = _tiny_config() + mapping = param_mapping.GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(config, _maxtext_config(), saving_to_hf=True) + hooks = param_mapping.GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_HOOK_FN(config, _maxtext_config(), saving_to_hf=True) + shapes = hf_shape.GEMMA4_SMALL_HF_WEIGHTS_TO_SHAPE(config) + + for key in (_STD_SCALE, _STD_BIAS): + self.assertEqual(utils.process_maxtext_param(key, np.ones(6), mapping, hooks, shapes, _maxtext_config()), []) + + def test_export_writes_every_hugging_face_weight_once(self): + mapping = param_mapping.GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(_tiny_config(), _maxtext_config(), saving_to_hf=True) + targets = [target for target in mapping.values() if target is not None] + + self.assertLen(set(targets), len(targets)) + + def test_import_fills_std_weights_from_a_placeholder(self): + mapping = param_mapping.GEMMA4_SMALL_MAXTEXT_TO_HF_PARAM_MAPPING(_tiny_config(), _maxtext_config()) + + self.assertEqual(mapping[_STD_SCALE], "model.vision_tower.encoder.layers.0.input_layernorm.weight") + self.assertEqual(mapping[_STD_BIAS], "model.vision_tower.encoder.layers.0.input_layernorm.weight") + + +if __name__ == "__main__": + unittest.main()