Repository navigation
Add UntrainableParam for weights that are never trained - #6224
nuinashco-ks wants to merge 4 commits into
Conversation
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
|
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. |
Summary of ChangesHello, 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 Highlights
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 AssistThe 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
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 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
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
Review of #6224 (UntrainableParam) — the core design and HF layer_scalar parity look solid, with two real bugs to fix before merge:
-
Missed
variable_collection_nameandNNXMetaassertion insrc/maxtext/layers/nnx_wrappers.py:ToLinen._update_variables(L629) was updated tovariable_collection_name(type_), butnnx_attrs_to_linen_varsat L136 (called byToNNX.__call__at L282) still callsvariablelib.variable_name_from_type(v.type)(withoutallow_register=True), which raisesValueError: Unknown variable type(or routes into"UntrainableParam"instead of"params").to_nnx_varat L83–85 assertsvtype == x.var_typewhen unpackingnnx.bridge.NNXMeta. For anyUntrainableParamcarrying metadata — such assharding=(None,)onGemma4DecoderLayer.layer_scalar(gemma4.py:347,gemma4_small.py:430) —to_linen_varwraps it inNNXMeta(UntrainableParam, ...)under"params", and round-tripping throughto_nnx_var("params", ...)resolvesvtype = nnx.Paramand trips the assertion. (UntrainableParamLinenBridgeTestdidn't hit this because itsUntrainableParamhas no metadata.)- Fix: Use
variable_collection_name(v.type)at L136, relax L84 toassert variable_collection_name(x.var_type) == col, and add asharding=(None,)+ToNNXround-trip test.
-
_leaf_pathinsrc/maxtext/optimizers/optimizers.py:66-68misses composite PyTree values (e.g., AQTQTensor/ QwixQArray):_leaf_pathonly strips a trailingGetAttrKey("value"). If a frozen parameter stores a composite PyTree value (e.g., quantized weight with.qvalue/.scale— especially relevant when#6235freezes vision/audio encoders),labels(params)sees(..., DictKey("kernel"), GetAttrKey("value"), GetAttrKey("qvalue")), returns".../kernel/value/qvalue", and silently labels it"trainable"whilefreeze_params.init'sis_leaf=isinstance(..., nnx.Variable)guard still passes.- Fix: Truncate at
GetAttrKey("value")(or matchnnx.Variable-level prefixes) instead of only checkingpath[-1].
— Review assisted by Jetski agent
edb301f to
1b53cb9
Compare
|
Both points are fixed, and the branch is rebased onto
The test results are in the updated description. |
Description
Adds
UntrainableParam, annnx.Paramsubclass 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'slayer_scalar, so this PR also changes Gemma-4 training:layer_scalaris no longer trained, and a Gemma-4 run started before this change cannot resume its optimizer state.Problem
Whether a weight is an
nnx.Paramdecides two things at once: it is stored in theparamscollection, 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:nnx.Paramand freeze it in the optimizer by a name pattern. That stops working silently when a weight is renamed or a new one is added.nnx.Variableclass. That keeps the optimizer away but moves the weight to another collection, which is the mismatch_alias_legacy_collectionsincheckpointing.pyworks around.Change
UntrainableParamis still a Param, so saving, resuming, conversion and sharding treat it like any other param. Two things differ:stop_gradientvalue.get_optimizerreads the model'sUntrainableParampaths and routes them tooptax.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, mapsUntrainableParamtoparamsin 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
UntrainableParamweights,initraises instead of silently applying weight decay to them.First user: Gemma-4
layer_scalarEvery 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 trainablennx.Param; it is nowUntrainableParam. 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_scalarno longer moves, and with gradient clipping its gradient no longer counts toward the global norm that scales every update. Other models are unaffected: without anUntrainableParamthe optimizer state tree is unchanged (covered by a test).trainable_parameters_maskkeeps working as before and cannot unfreeze anUntrainableParam.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_scaleareUntrainableParamthere.Not in this PR
The existing custom variable classes (
MoEBiasVar,Tid2EidVarand others) are unchanged.Tid2EidVaris 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 inparams, resume restores type and value, a missing weight raises, weights-only load, collection naming, stacked-layer sharding, Linen bridge, round trip throughToNNXfor a weight that has metadata.tests/unit/optimizers_test.py: weight decay does not move anUntrainableParamunder AdamW, adam_pax and Muon;trainable_parameters_maskcannot unfreeze it;inject_hyperparamsfactories; 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.pyandtests/post_training/unit/train_distill_test.py: one weight-decay test each.tests/unit/gemma4_small_test.py:layer_scalaris untrainable in the E2B and 26B decoder layers; fails without the change.To reproduce:
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.pypython3 -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.pyRun locally with jax 0.11.1, flax 0.12.12, optax 0.2.8, on
main(f8dfb87) and on this branch. Nothing that passes onmainfails on this branch:main, 1242 passed on this branch.main, 1215 passed on this branch.main, 114 passed on this branch.layer_scalarcommit,gemma4_small_test.py,gemma4_small_layers_test.py,nnx_decoders_test.py,hf_checkpoint_conversion_test.py,optimizers_test.py,untrainable_param_test.pyandflop_calculation_test.pyon CPU: 296 and 297 passed.pyink24.10.1 andpylintwith the repository settings: nothing new.End to end, on one v6e chip, on
mainand 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 35layer_scalarweights change onmainwithin 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_scalarcomparison. The TPU failures need more devices, or library versions and packages that the local setup does not have. The 4 files aremaxtext_engine_test.py,maxtext_engine_constructor_test.py,prepare_weight_sync_test.pyandtrain_rl_test.py:tunix.dist_rlis missing locally, so they did not run and rely on CI.Checklist
Before submitting this PR, please make sure (put X in square brackets):
gemini-reviewlabel.skip-ci-testsso 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 therun-tpu7xlabel to run the full TPU7X suite.)