Skip to content

Keep weight decay off frozen vision and audio encoders - #6235

Open
nuinashco-ks wants to merge 6 commits into
AI-Hypercomputer:mainfrom
KyivstarDMP:pr/freeze-vision-encoder
Open

nuinashco-ks wants to merge 6 commits into
AI-Hypercomputer:mainfrom
KyivstarDMP:pr/freeze-vision-encoder

Conversation

@nuinashco-ks

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

Copy link
Copy Markdown

Description

freeze_vision_encoder_params and freeze_audio_encoder_params now also keep weight decay off the frozen encoder towers, and the optimizer no longer allocates state for them.

Stacked on #6224 (UntrainableParam), which adds the freeze_params wrapper this PR reuses. Until #6224 lands, this diff includes its commits; this PR's own commits: compare.

Problem

Both flags default to true, and both only apply stop_gradient to the encoder output in VisionEncoder.__call__ and AudioEncoder.__call__. The tower then gets a zero gradient, but AdamW's decoupled weight decay still shrinks every tower weight each step, and the optimizer keeps mu/nu for weights that never learn. To make the effect visible, a Gemma-4 E2B run (vision from #4790) took 3 AdamW steps with adam_weight_decay=2.0, the flag on and trainable_parameters_mask=['vision_encoder']. The flag stops the tower's gradient, so weight decay was the only force on it, and 212 of the tower's 213 regular weights changed. At usual settings (lr 2e-5, weight decay 0.1) the shrink is 2e-6 per step: it rounds away with bfloat16 weights, and with float32 weights it adds up to about 0.2% per 1000 steps.

Change

A new frozen_param_paths(model, config) in optimizers.py returns the paths the optimizer must not change: the UntrainableParam weights from #6224, plus, for each encoder whose flag is on, the weights under its encoder_name child. get_optimizer, the distillation optimizer and the RL optimizer route these paths to optax.set_to_zero(), so they get no update, no weight decay and no optimizer state.

  • The projector stays trainable, which matches what the stop_gradient already cuts off.
  • Encoders are found anywhere in the model, so RL's TunixMaxTextAdapter, which keeps the model under base, is covered.
  • A small table, _ENCODER_FREEZE_FLAGS, ties vision_encoder and audio_encoder to their flags, so each flag freezes only its own encoder.

The stop_gradient stays: it skips the backward pass through the tower and keeps the tower out of gradient clipping and grad_norm.

Impact

Multimodal runs with a frozen encoder, which is the default, no longer hold that tower in the optimizer state: less memory, and a run started before this change cannot resume its optimizer state, while its weights load unchanged. Text-only models are unaffected, since their optimizer is built exactly as before. The optimizer in m3/train/loop.py is built without the model and is not covered by this change.

Tests

Unit tests:

  • tests/unit/optimizers_test.py: new FreezeEncodersTest, 10 cases.
    • 8 cases with test encoders (vision flag × audio flag × model wrapped like RL). With zero gradients and weight decay as the only force, a frozen tower does not move and gets no optimizer state, while the projectors and the text weights do. Both test encoders use the same tower name, so each flag must freeze only its own encoder.
    • 2 cases build the real VisionEncoder and AudioEncoder of Qwen3-Omni with nnx.eval_shape and check that exactly the tower's weights are frozen.
  • tests/post_training/unit/rl_utils_test.py and tests/post_training/unit/train_distill_test.py: the existing weight-decay tests now include a vision encoder with the flag on.
  • Mutation check: each of these mistakes, planted one at a time, makes at least one test fail: no fix, flag ignored, projector frozen too, tower name matched outside its own encoder, only the top level of the model searched, get_optimizer not using the paths, the RL change reverted, the distillation change reverted, optimizer state still allocated for a frozen tower, the tower attribute renamed in the real encoders.

To reproduce:

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

Run locally on main (f8dfb87), on the #6224 branch and on this branch. Nothing that passes on #6224 fails on this branch:

Model Vision flag Audio flag Vision tower Audio tower
Gemma-3 4B on – 437 frozen –
Gemma-3 4B off – 437 trained –
Gemma-4 26B on – 355 frozen –
Gemma-4 26B off – 355 trained –
Qwen3-Omni 30B-A3B on off 453 frozen 521 trained
Qwen3-Omni 30B-A3B off on 453 trained 521 frozen
Qwen3-Omni 30B-A3B on on 453 frozen 521 frozen
Qwen3-Omni 30B-A3B off off 453 trained 521 trained

Projectors and text weights are trained in every row (apart from Gemma-4's layer_scalar, frozen by #6224), and wrapping the model in TunixMaxTextAdapter, as the RL trainer does, gives the same frozen set. Without this change, the same check shows the Gemma-3 and Gemma-4 towers trained with the flag on.

  • pyink 24.10.1 and pylint with the repository settings: nothing new.

Local failures are the same on main, on #6224 and on this branch: 79 tests and 4 files that cannot be imported in the first CPU run (106 tests in the second), and 118 tests in the TPU run. The TPU failures need more devices, or library versions and packages that the local setup does not have. The 4 files need tunix.dist_rl, which is missing locally, so they 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.

@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.

@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 optimizes memory usage and training stability for multimodal models by ensuring that frozen vision and audio encoders are fully excluded from the optimizer's state and weight decay updates. By introducing an UntrainableParam wrapper and a path-based freezing mechanism, the changes prevent the optimizer from applying updates to weights that are intended to remain static, while maintaining compatibility with existing model structures and training configurations.

Highlights

  • Frozen Encoder Weight Decay: Updated the optimizer to ensure that frozen vision and audio encoders are excluded from weight decay and optimizer state updates, preventing unnecessary parameter shrinkage.
  • UntrainableParam Implementation: Introduced UntrainableParam to explicitly mark model weights that should not be updated, ensuring they are excluded from gradients and optimizer state.
  • Optimizer Routing: Updated get_optimizer and related training loops to route frozen parameter paths to optax.set_to_zero(), effectively freezing them during training.
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 94.59459% 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 #6235 (freeze vision/audio encoder weight decay) — the encoder-vs-projector split across encoders.py looks accurate. A few substantive items to address:

  1. Inherits the #6224 bugs (and squash-merge rebase requirement):

    • Please pick up the nnx_wrappers.py and _leaf_path (composite PyTree / quantized weight) fixes from #6224 — the _leaf_path bug is directly relevant here if a frozen vision or audio encoder is quantized (QTensor / QArray).
    • Because this repo is squash-merge only, once #6224 lands this PR will need a rebase onto main (keeping only 49d1ffbea765) to avoid conflicts across the 6 shared files.
  2. Test coverage gaps in tests/unit/optimizers_test.py (FreezeEncodersTest):

    • FreezeEncodersTest doesn't assert that nnx.state(optimizer) has no mu/nu slots allocated for frozen tower params (unlike #6224's _assert_untrainable_unchanged), so the zero-optimizer-state guarantee isn't verified by tests.
    • All tests use synthetic _Encoder mocks; adding a lightweight nnx.eval_shape test against a real VisionEncoder / AudioEncoder would ensure an encoder_name or tower-attribute refactor can't silently re-enable weight decay.

— Review assisted by Jetski agent

@nuinashco-ks
nuinashco-ks force-pushed the pr/freeze-vision-encoder branch from 49d1ffb to 773d80c Compare November 26, 2026 02:01
@nuinashco-ks

Copy link
Copy Markdown
Author

Both points are addressed, and the branch is rebased onto the updated #6224.

  1. Add UntrainableParam for weights that are never trained #6224 fixes: included through the rebase. This PR's own commits are the last two; they go onto main once Add UntrainableParam for weights that are never trained #6224 lands.
  2. Tests (773d80c): FreezeEncodersTest now checks that a frozen tower gets no optimizer state. A new test builds the real VisionEncoder and AudioEncoder of Qwen3-Omni with nnx.eval_shape and checks that exactly the tower is frozen.

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