contrib: add MARS optimizer (arXiv:2411.10438)#1697
Closed
irhyl wants to merge 6 commits into
Closed
Conversation
SOAP (Improving and Stabilizing Shampoo using Adam) combines Shampoo's
Kronecker-factored preconditioning with Adam's per-coordinate adaptivity.
For each 2-D weight matrix it maintains left/right Kronecker factors
whose eigenbases define a rotation; Adam's moment buffers are tracked in
that rotated space and the final update is unprojected back. Parameters
with fewer than two dimensions fall back to standard Adam.
New files:
optax/contrib/_soap.py – scale_by_soap and soap implementations
optax/contrib/_soap_test.py – 14 unit tests (shapes, orthogonality,
convergence, JIT stability, Adam fallback,
weight decay, mu_dtype, frequency control)
Modified files:
optax/contrib/__init__.py – export soap / scale_by_soap / ScaleBySOAPState
optax/contrib/_common_test.py – add soap to the shared optimizer test matrix
and mark precondition_frequency as static
MARS (Unleashing the Power of Variance Reduction for Training Large
Models) augments Adam with a scaled stochastic recursive momentum
correction that reduces gradient variance across steps. For each
parameter, the variance-reduced estimate
c_t = g_t + γ·(β₁/(1-β₁))·(g_t - g_{t-1})
replaces the raw gradient before the standard Adam moment updates.
c_t is optionally clipped to unit L2 norm to prevent the large
effective gradient on the first step (when last_grad=0) from
dominating. Setting γ=0 recovers Adam exactly.
This is the approximate-MARS variant: g_{t-1} is the gradient from
the previous step rather than a re-evaluation on the current mini-batch,
keeping cost identical to Adam at one gradient evaluation per step.
New files:
optax/contrib/_mars.py – scale_by_mars and mars implementations
optax/contrib/_mars_test.py – 13 unit tests (shapes, state tracking,
γ=0/Adam equivalence, clipping on/off,
variance-reduction direction check,
convergence on quadratic and mixed params,
JIT stability, weight decay, mu_dtype,
count increment)
Modified files:
optax/contrib/__init__.py – export mars / scale_by_mars / ScaleByMARSState
optax/contrib/_common_test.py – add mars to the shared optimizer test matrix
|
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. |
Move test_utils import to file top (C0415), fix dict iteration to use .items() (C0206), and wrap all lines that exceeded 80 chars (E501).
Move test_utils and transform imports to file top (C0415), fix dict iteration to use .items() (C0206), and wrap the 81-char docstring line in _soap.py (E501).
Change count field type from jax.Array to jax.typing.ArrayLike to match the established pattern in transform.py (ScaleByAdamState). Add pyrefly ignore comments for the GradientTransformation and add_decayed_weights calls, matching the pattern used in alias.py.
Change count field type from jax.Array to jax.typing.ArrayLike to match the established pattern in transform.py. Add pyrefly ignore comments for GradientTransformation and add_decayed_weights calls, matching the same pattern used in _soap.py and alias.py.
20d3ddd to
09987ea
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds MARS (Unleashing the Power of Variance Reduction for Training Large Models, Yuan et al. 2024 / ICML 2025) as a new optimizer in
optax.contrib.MARS augments Adam with a scaled stochastic recursive momentum correction. The key idea: instead of updating Adam's moments with the raw gradient$g_t$ , MARS first computes a variance-reduced estimate
which penalizes changes in gradient direction between consecutive steps. This acts as a low-cost variance reduction step without requiring an extra gradient evaluation. Adam's standard moment updates and bias correction then run on$c_t$ rather than $g_t$ .
Setting$\gamma = 0$ recovers Adam exactly, making MARS a strict generalization.
Reported gains (from the paper, on GPT-2 training):
Files changed
optax/contrib/_mars.py—scale_by_mars(primitive) andmars(full optimizer with weight decay and learning rate). Includes complete docstring with math, memory note, and usage example.optax/contrib/_mars_test.py— 13 unit tests covering: state shapes, last_grad tracking, γ=0/Adam equivalence, clipping (on/off), variance-reduction directional effect, quadratic convergence (2D and mixed params), JIT recompilation, weight decay, mu_dtype, count increment.optax/contrib/__init__.py— exportsmars,scale_by_mars,ScaleByMARSState.optax/contrib/_common_test.py— addsmarsto the shared optimizer test matrix (all 13 shared tests pass, includinginject_hyperparamsand dtype stability).Implementation notes
Approximate vs exact MARS. The paper describes an exact variant that evaluates$\nabla f(x_{t-1}, \xi_t)$ — the previous-parameter gradient on the current mini-batch — requiring two gradient evaluations per step. This implementation uses the approximate variant: $g_{t-1}$ is simply the gradient stored from the previous step (different mini-batch). This is standard in practice (the official PyTorch reference implementation does the same), costs one gradient evaluation per step, and retains most of the variance-reduction benefit.
Clipping. The$c_t$ to at most unit L2 norm before the moment updates. On the first step, $c_t = (1 + \gamma\beta_1/(1-\beta_1)) \cdot g_t$ , which can be ~1.5× larger than the raw gradient for typical $\gamma = 0.025$ , $\beta_1 = 0.95$ . Clipping keeps the first step well-behaved. Setting
clip_thresholdparameter (default 1.0) rescaleslast_gradis zero soclip_threshold=Nonedisables it entirely.inject_hyperparams compatibility.
b1,b2,eps, andgammaare normalised tofloat32at the top ofscale_by_mars. This is necessary becauseinject_hyperparamsreconstructs the inner optimizer from scratch each step with strongly-typedjnp.float32hyperparameters; without normalisation,(1 - b2)evaluates differently for a Python float vs a JAXfloat32, producing numerically different moment updates and breaking the inject test.Dtype stability. Moment buffers are cast back to their stored dtype after each float32 computation, following the same pattern as
scale_by_soap. This ensures the state dtype is invariant across steps when params are float16 or bfloat16.Test plan
python -m pytest optax/contrib/_mars_test.py— 13/13 passpython -m pytest optax/contrib/_common_test.py— 562 pass, 4 skippython -m pytest optax/contrib/— 697 pass, 7 skip🤖 Generated with Claude Code