Skip to content

Add UntrainableParam for weights that are never trained - #6224

Open
nuinashco-ks wants to merge 4 commits into
AI-Hypercomputer:mainfrom
KyivstarDMP:pr/untrainable-param
Open

nuinashco-ks wants to merge 4 commits into
AI-Hypercomputer:mainfrom
KyivstarDMP:pr/untrainable-param

Conversation

@nuinashco-ks

@nuinashco-ks nuinashco-ks commented Nov 10, 2026 •

Copy link
Copy Markdown

Description

Adds UntrainableParam, an nnx.Param subclass for weights that belong to the model and its checkpoints but must never be changed by training, such as fixed clip bounds or lookup tables. The first one is Gemma-4's layer_scalar, so this PR also changes Gemma-4 training: layer_scalar is no longer trained, and a Gemma-4 run started before this change cannot resume its optimizer state.

Problem

Whether a weight is an nnx.Param decides two things at once: it is stored in the params collection, and the optimizer updates it, weight decay included. A weight that should be stored but not trained has two options today, and each has a cost:

  • Keep it an nnx.Param and freeze it in the optimizer by a name pattern. That stops working silently when a weight is renamed or a new one is added.
  • Make it a custom nnx.Variable class. That keeps the optimizer away but moves the weight to another collection, which is the mismatch _alias_legacy_collections in checkpointing.py works around.

Change

UntrainableParam is still a Param, so saving, resuming, conversion and sharding treat it like any other param. Two things differ:

  • Reading it returns a stop_gradient value.
  • get_optimizer reads the model's UntrainableParam paths and routes them to optax.set_to_zero(), so they get no update, no weight decay and no optimizer state. The RL and distillation optimizers do the same.

Flax names a collection by exact class, so a small helper, variable_collection_name, maps UntrainableParam to params in the three places that use the name lookup: the weights-only loader, the Hugging Face converter and the Linen bridge.

If an optimizer is built without the model and then initialised on a model that has UntrainableParam weights, init raises instead of silently applying weight decay to them.

First user: Gemma-4 layer_scalar

Every Gemma-4 decoder layer multiplies its output by a layer_scalar. HF stores it as a fixed buffer (nn.Buffer), and the Gemma 4 report (section 2.5) describes a per-block scalar that bounds activation ranges for fp16 inference. MaxText created it as a trainable nnx.Param; it is now UntrainableParam. With bfloat16 weights its updates at usual learning rates round away anyway; with float32 weights it would drift away from the checkpoint values (0.018 to 0.87 in E2B).

Impact on existing models

Only Gemma-4: its optimizer state no longer holds layer_scalar, so a Gemma-4 run started before this change cannot resume its optimizer state, while its weights load unchanged. Gemma-4 loss curves also change: layer_scalar no longer moves, and with gradient clipping its gradient no longer counts toward the global norm that scales every update. Other models are unaffected: without an UntrainableParam the optimizer state tree is unchanged (covered by a test). trainable_parameters_mask keeps working as before and cannot unfreeze an UntrainableParam.

Next users

#6621 adds image support for Gemma-4 E2B/E4B and is stacked on this PR: the vision clip bounds and the vision tower's std_bias/std_scale are UntrainableParam there.

Not in this PR

The existing custom variable classes (MoEBiasVar, Tid2EidVar and others) are unchanged. Tid2EidVar is a fixed table and could move to this class later if you want that. The routing biases are advanced every step by load balancing, so they are a different case.

Tests

Unit tests:

  • tests/unit/untrainable_param_test.py (new): zero gradient for every way of reading the value, saved in params, resume restores type and value, a missing weight raises, weights-only load, collection naming, stacked-layer sharding, Linen bridge, round trip through ToNNX for a weight that has metadata.
  • tests/unit/optimizers_test.py: weight decay does not move an UntrainableParam under AdamW, adam_pax and Muon; trainable_parameters_mask cannot unfreeze it; inject_hyperparams factories; the "model not passed" error; unchanged optimizer state when the class is not used; a frozen weight whose value is a pytree gets no update and no optimizer state.
  • tests/post_training/unit/rl_utils_test.py and tests/post_training/unit/train_distill_test.py: one weight-decay test each.
  • tests/unit/gemma4_small_test.py: layer_scalar is untrainable in the E2B and 26B decoder layers; fails without the change.

To reproduce:

  • CPU: JAX_PLATFORMS=cpu python3 -m pytest tests/unit/untrainable_param_test.py tests/unit/optimizers_test.py tests/unit/gemma4_small_test.py tests/post_training/unit/rl_utils_test.py
  • TPU: python3 -m pytest -m tpu_only tests/post_training/unit/train_distill_test.py tests/post_training/unit/rl_utils_test.py tests/unit/optimizers_test.py

Run locally with jax 0.11.1, flax 0.12.12, optax 0.2.8, on main (f8dfb87) and on this branch. Nothing that passes on main fails on this branch:

  • CPU, the 57 unit test files that touch the changed modules: 1221 passed on main, 1242 passed on this branch.
  • The same CPU run with flax 0.12.8 and optax 0.2.6: 1194 passed on main, 1215 passed on this branch.
  • TPU-only tests in 11 of those files, on one v6e chip: 113 passed on main, 114 passed on this branch.
  • With and without the layer_scalar commit, gemma4_small_test.py, gemma4_small_layers_test.py, nnx_decoders_test.py, hf_checkpoint_conversion_test.py, optimizers_test.py, untrainable_param_test.py and flop_calculation_test.py on CPU: 296 and 297 passed.
  • pyink 24.10.1 and pylint with the repository settings: nothing new.

End to end, on one v6e chip, on main and on this branch: Gemma-4 E2B trained from scratch on synthetic data for 10 steps, saved, and resumed to 15 steps. The run uses bfloat16 weights and SGD, because AdamW at this size does not fit one chip, so it does not cover weight decay or optimizer state. The resume works on both. With gradient clipping off, 12 of the 35 layer_scalar weights change on main within 9 steps (the lowest reaches 0.87), and all 35 stay at 1.0 on this branch. With the default clipping they stay at 1.0 on both in this bfloat16 run.

Local failures are the same with and without the change: 79 tests and 4 files that cannot be imported in the first run (106 tests in the second), 118 tests in the TPU run, and 5 in the layer_scalar comparison. The TPU failures need more devices, or library versions and packages that the local setup does not have. The 4 files are maxtext_engine_test.py, maxtext_engine_constructor_test.py, prepare_weight_sync_test.py and train_rl_test.py: tunix.dist_rl is missing locally, so they did not run and rely on CI.

Checklist

Before submitting this PR, please make sure (put X in square brackets):

  • I have performed a self-review of my code. For an optional AI review, add the gemini-review label.
  • I have necessary comments in my code, particularly in hard-to-understand areas.
  • I have run end-to-end tests and provided workload links above if applicable. (Note: New PRs get skip-ci-tests so only CPU/lint/docs checks run during review; a bot removes it after 2 approvals on a 1-commit PR to run TPU/GPU suites, or remove it yourself / ask a maintainer on fork PRs to run them sooner. On TPU7X, only the TPU tests that the PR adds or modifies run; add the run-tpu7x label to run the full TPU7X suite.)
  • I have made or will make corresponding changes to the doc if needed, including adding new documentation pages to the relevant Table of Contents (toctree directive) as explained in our documentation.

@gemini-code-assist

Copy link
Copy Markdown

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@github-actions github-actions Bot added the skip-ci-tests Add this label to the PR to skip running CI tests label Nov 10, 2026
@google-cla

google-cla Bot commented Nov 10, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@nuinashco-ks nuinashco-ks changed the title feat(nnx): add UntrainableParam for weights that are never trained Add UntrainableParam for weights that are never trained Nov 10, 2026
@nuinashco-ks
nuinashco-ks marked this pull request as ready for review November 12, 2026 22:42
@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces UntrainableParam to address the challenge of managing model weights that must be saved and loaded but never updated by the optimizer. By subclassing nnx.Param, these weights retain standard checkpointing behavior while being explicitly routed to zero-gradient updates. This change improves training stability for specific components like the Gemma-4 layer_scalar and provides a robust mechanism for handling fixed parameters without requiring custom variable collections or fragile name-based freezing patterns.

Highlights

  • Introduction of UntrainableParam: Added UntrainableParam, a new nnx.Param subclass designed for model weights that should be persisted in checkpoints but remain excluded from training updates, weight decay, and optimizer state.
  • Optimizer Integration: Updated the optimizer logic to automatically detect and freeze UntrainableParam weights using optax.set_to_zero(), ensuring they remain static during training.
  • Gemma-4 Model Update: Converted the Gemma-4 layer_scalar from a standard nnx.Param to UntrainableParam to prevent unintended drift during training.
  • Checkpointing and Compatibility: Implemented helper utilities to ensure UntrainableParam is treated as a standard parameter for saving, loading, and sharding, maintaining compatibility with existing checkpoint formats.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@codecov

codecov Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.44262% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
.../trainers/post_train/distillation/train_distill.py 66.66% 2 Missing ⚠️
src/maxtext/checkpoint_conversion/to_maxtext.py 50.00% 1 Missing ⚠️
src/maxtext/trainers/post_train/rl/utils_rl.py 50.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@csgoogle csgoogle left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review of #6224 (UntrainableParam) — the core design and HF layer_scalar parity look solid, with two real bugs to fix before merge:

  1. Missed variable_collection_name and NNXMeta assertion in src/maxtext/layers/nnx_wrappers.py:

    • ToLinen._update_variables (L629) was updated to variable_collection_name(type_), but nnx_attrs_to_linen_vars at L136 (called by ToNNX.__call__ at L282) still calls variablelib.variable_name_from_type(v.type) (without allow_register=True), which raises ValueError: Unknown variable type (or routes into "UntrainableParam" instead of "params").
    • to_nnx_var at L83–85 asserts vtype == x.var_type when unpacking nnx.bridge.NNXMeta. For any UntrainableParam carrying metadata — such as sharding=(None,) on Gemma4DecoderLayer.layer_scalar (gemma4.py:347, gemma4_small.py:430) — to_linen_var wraps it in NNXMeta(UntrainableParam, ...) under "params", and round-tripping through to_nnx_var("params", ...) resolves vtype = nnx.Param and trips the assertion. (UntrainableParamLinenBridgeTest didn't hit this because its UntrainableParam has no metadata.)
    • Fix: Use variable_collection_name(v.type) at L136, relax L84 to assert variable_collection_name(x.var_type) == col, and add a sharding=(None,) + ToNNX round-trip test.
  2. _leaf_path in src/maxtext/optimizers/optimizers.py:66-68 misses composite PyTree values (e.g., AQT QTensor / Qwix QArray):

    • _leaf_path only strips a trailing GetAttrKey("value"). If a frozen parameter stores a composite PyTree value (e.g., quantized weight with .qvalue/.scale — especially relevant when #6235 freezes vision/audio encoders), labels(params) sees (..., DictKey("kernel"), GetAttrKey("value"), GetAttrKey("qvalue")), returns ".../kernel/value/qvalue", and silently labels it "trainable" while freeze_params.init's is_leaf=isinstance(..., nnx.Variable) guard still passes.
    • Fix: Truncate at GetAttrKey("value") (or match nnx.Variable-level prefixes) instead of only checking path[-1].

— Review assisted by Jetski agent

@nuinashco-ks

Copy link
Copy Markdown
Author

Both points are fixed, and the branch is rebased onto main, which had started to conflict with it.

  1. Linen bridge (bbce6d6): fixed, with a ToNNX round-trip test for a weight that has sharding metadata.
  2. Weights whose value is a pytree (1b53cb9): a leaf is now frozen when its path, or a prefix of it, is a frozen weight path. Cutting the path at value is not enough, because that key is in the path only at init and not at update. The new test uses a Param that holds {qvalue, scale}.

The test results are in the updated description.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gemini-review skip-ci-tests Add this label to the PR to skip running CI tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants