Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.LEGO for training
An optimizer is the rule that decides how to change a network’s parameters from their gradients. Instead of offering a fixed menu (SGD, Adam, …), Optax gives you small bricks (clip the gradient, average it over time, divide by its typical size, shrink the weights, multiply by the learning rate) that you snap together in a row. Flax and Equinox do the same for the network itself: layers are bricks, and the parameters are kept in a separate box you pass around explicitly. Because every brick is a pure function, JAX can differentiate, compile and parallelize the whole thing.
optax.chain(optax.add_decayed_weights(wd), optax.scale_by_adam(), optax.scale(-lr))
| chain | final w₁ | final w₂ |
|---|---|---|
| Adam | 0.996 | 0.992 |
| Adam + L2 | 0.949 | 0.437 |
| AdamW | 0.982 | 0.931 |
| SGD + L2 | 0.949 | 0.439 |
| ridge optimum | 0.952 | 0.444 |
Being able to see and change every step of the optimizer is what lets you reproduce a paper exactly, add gradient clipping for a flaky robotics dataset, freeze the pretrained part of a model, or exclude biases from weight decay, by editing one line instead of rewriting the training code.
- 1. Optax builds an optimizer by…
- 2. In Flax, where do the parameters live?
- 3. In the demo, what changes between Adam + L2 and AdamW?
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.Flax (Linen): init and apply
import jax, jax.numpy as jnp
import flax.linen as nn
import optax
class MLP(nn.Module):
features: tuple = (64, 64, 1)
@nn.compact
def __call__(self, x):
for f in self.features[:-1]:
x = nn.tanh(nn.Dense(f)(x))
return nn.Dense(self.features[-1])(x)
model = MLP()
params = model.init(jax.random.key(0), jnp.ones((1, 8))) # a pytree (nested dict) of arrays
tx = optax.chain(optax.clip_by_global_norm(1.0), optax.adamw(1e-3, weight_decay=1e-4))
opt_state = tx.init(params)
@jax.jit
def step(params, opt_state, x, y):
loss, grads = jax.value_and_grad(lambda p: jnp.mean((model.apply(p, x) - y) ** 2))(params)
updates, opt_state = tx.update(grads, opt_state, params)
return optax.apply_updates(params, updates), opt_state, lossThe model object holds only the architecture; init creates parameters from a random key and a sample input (shapes are inferred); apply(params, x) is a pure function. The optimizer state is another pytree. Everything flowing through step is an explicit input or output, so jit can compile it.
- 1. model.init(key, x) returns…
- 2. optax.apply_updates(params, updates) computes…
- 3. Why is the optimizer state returned from step?
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.Optax: gradient transformations
A GradientTransformation is a pair (init(params) → state, update(updates, state, params) → (updates, state)). Optimizers are chains:
optax.adam(lr)=chain(scale_by_adam(b1, b2, eps), scale_by_learning_rate(lr))optax.adamw(lr, wd)=chain(scale_by_adam(), add_decayed_weights(wd, mask), scale_by_learning_rate(lr))optax.sgd(lr, momentum)=chain(trace(momentum), scale_by_learning_rate(lr))
Other bricks: clip_by_global_norm, schedules (warmup_cosine_decay_schedule, piecewise_constant_schedule) passed as the learning rate, masked (apply a transformation to a subset of leaves, e.g. no decay on biases and norms), multi_transform (different optimizers for different parts), MultiSteps (gradient accumulation), inject_hyperparams (change the learning rate at run time), and contrib optimizers.
Pytrees
Parameters, gradients, optimizer states and updates are pytrees: nested containers with array leaves. jax.tree.map(f, *trees) applies f leaf-wise to trees of the same structure; jax.tree.leaves flattens; global norms, weight-decay masks and parameter counts are all short tree operations.
State beyond parameters
Batch-norm statistics live in a separate collection (model.apply(variables, x, mutable=["batch_stats"]) returns the new statistics); dropout needs a random key (rngs={"dropout": key}). Flax’s TrainState bundles step, params, optimizer and state. Orbax saves and restores these pytrees.
- 1. Which Optax brick excludes biases from weight decay?
- 2. Adam's first update has magnitude ≈ lr because…
- 3. Gradient accumulation in Optax is provided by…
Level 3: Advanced
★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.Equinox: modules are pytrees
In Equinox a model is a pytree: class MLP(eqx.Module) with array fields, constructed directly (MLP(key=...)), and called like a function. Since the model contains non-array fields (activation functions, sizes), Equinox provides filtered transformations: eqx.filter_jit, eqx.filter_grad and eqx.partition/combine treat array leaves as traced and everything else as static. Updates use eqx.apply_updates(model, updates) with Optax. Flax’s NNX API moves in the same direction, with mutable Python objects that are converted to and from pytrees at transformation boundaries.
Decoupled weight decay
With Adam, adding L2 to the loss (decay before scale_by_adam) makes the decay pass through the adaptive normalization: the stationary point of E[g] + λw = 0 is the ridge solution, which shrinks weights with small curvature (small-scale features) much more. AdamW (decay after normalization) shrinks all weights at a rate set by λ and the learning rate, independent of the gradient’s scale. In Optax the two optimizers are the same three bricks in a different order.
- 1. eqx.filter_jit treats non-array fields of a module as…
- 2. Adam + L2 converges to…
- 3. AdamW in Optax is…
Level 4: Expert
★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.Optimizers as chains, measured
Exercise 1. The pytree utilities preserve nested dict, list and tuple structure; the first Adam step has size exactly lr; a second step matches the hand-computed bias-corrected formula; masking skips biases; the warmup-cosine schedule gives 0, 0.5, 1, 0.5, 0 at steps 0, 5, 10, 60, 110. On sin(2x) with a 1-16-16-1 tanh MLP, 500 full-batch steps give MSE 0.0098 (SGD, lr 0.05), 0.0004 (momentum 0.9), 0.0002 (Adam, lr 0.01) and 0.0002 (clip + AdamW with warmup-cosine).
Exercise 2: Adam + L2 versus AdamW. Linear regression y = x₁ + x₂ + noise (σ = 0.5, batch 32, 4000 steps, lr 0.01, λ = 0.1); feature 1 has scale 1 and feature 2 a varying scale s₂. Final w₂ (averaged over the last 1000 steps):
| s₂ | Adam + L2 | ridge prediction 2s²/(2s² + λ) | AdamW |
|---|---|---|---|
| 1 | 0.952 | 0.952 | 0.990 |
| 0.3 | 0.644 | 0.643 | 0.968 |
| 0.1 | 0.167 | 0.167 | 0.910 |
Adam + L2 lands on the ridge solution to three decimals: its regularization strength relative to the data term depends on each feature’s scale. AdamW’s shrinkage varies 4× less across scales. With feature scales (10, 0.1) together, Adam + L2 gives (0.999, 0.167) and AdamW (0.995, 0.890).
Flax, Equinox and Optax in AI, robotics and aerospace
- Scientific ML: neural ODEs and physics-informed networks in Equinox with Diffrax (differential-equation solvers).
- Robot learning: policies in Flax trained with Brax simulators on accelerators.
- Large models: Flax and Optax power MaxText-style training at scale;
multi_transformand masking handle fine-tuning parts of a model. - Reproducibility: explicit keys, pure step functions and Orbax checkpoints of the full train state make runs reconstructible.
References
- J. Heek et al. (2023). Flax: a neural network library and ecosystem for JAX. github.com/google/flax.
- P. Kidger, C. Garcia (2021). “Equinox: neural networks in JAX via callable PyTrees and filtered transformations.” Differentiable Programming Workshop, NeurIPS.
- DeepMind et al. (2020). The DeepMind JAX Ecosystem (Optax). github.com/google-deepmind/optax.
- I. Loshchilov, F. Hutter (2019). “Decoupled weight decay regularization.” ICLR.
- D. P. Kingma, J. Ba (2015). “Adam: a method for stochastic optimization.” ICLR.