Foundations to Frontier
Tests
C. Programming, Tools and HPC › C3 Deep Learning Frameworks

Flax, Equinox and Optax

JAX itself has no layers or optimizers; libraries built on its functional style provide them. Flax (Linen and the newer NNX API) and Equinox define neural-network modules whose parameters are pytrees passed explicitly through pure functions; Optax defines optimizers as chains of small gradient transformations, each a pair of pure functions init and update. This topic covers the init/apply pattern, mutable state (batch statistics, dropout keys), Equinox's modules-as-pytrees and filtered transformations, Optax's building blocks (scale_by_adam, add_decayed_weights, clip_by_global_norm, schedules, masking, chain) and the train-state pattern. In the exercises you implement pytrees, a mini-Optax and a Flax-style functional MLP in NumPy, then show that Adam + L2 and AdamW differ only in the order of two chained transformations, and measure the consequence.

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 chains: the order of transformations is the algorithm
optax.chain(optax.add_decayed_weights(wd), optax.scale_by_adam(), optax.scale(-lr))
w₁w₂true (1, 1)ridge
chainfinal w₁final w₂
Adam0.9960.992
Adam + L20.9490.437
AdamW0.9820.931
SGD + L20.9490.439
ridge optimum0.9520.444
Data: y = x₁ + x₂ + noise, so both true weights are 1, but feature 2 has a smaller scale. Adam + L2 and SGD + L2 both converge to the ridge solution, which shrinks the small-scale weight hard (its curvature 2s² is small next to wd). AdamW decays after normalization, so its shrinkage barely depends on the feature's scale (Loshchilov and Hutter, 2019). Same blocks, different order, different optimizer.
Why engineers care

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.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Optax builds an optimizer by…
  2. 2. In Flax, where do the parameters live?
  3. 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, loss

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

📝 Quick check (Level 1)
0/3 answered
  1. 1. model.init(key, x) returns…
  2. 2. optax.apply_updates(params, updates) computes…
  3. 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.

🐍 Exercise 1: pytrees, a mini-Optax and a functional MLP
Implement tree_map, tree_leaves and global_norm for nested dicts, lists and tuples; GradientTransformation; scale, scale_by_schedule, trace (momentum), scale_by_adam (with bias correction), add_decayed_weights (with a mask), clip_by_global_norm, chain, apply_updates, sgd, adam, adamw and a warmup-cosine schedule; and a Flax-style MLP with init(seed, sizes) and apply(params, x) plus its gradient. Compare optimizers on sin(2x).
📝 Quick check (Level 2)
0/3 answered
  1. 1. Which Optax brick excludes biases from weight decay?
  2. 2. Adam's first update has magnitude ≈ lr because…
  3. 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.

📝 Quick check (Level 3)
0/3 answered
  1. 1. eqx.filter_jit treats non-array fields of a module as…
  2. 2. Adam + L2 converges to…
  3. 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).

🐍 Exercise 2 (research): Adam + L2 versus AdamW as a chain order
Build Adam + L2 as chain(add_decayed_weights, scale_by_adam, scale(−lr)) and AdamW as chain(scale_by_adam, add_decayed_weights, scale(−lr)); train both on a noisy two-feature regression with different feature scales; compare the time-averaged final weights with the ridge prediction 2s²/(2s² + λ) across a sweep of feature scales.

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_transform and 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

  1. J. Heek et al. (2023). Flax: a neural network library and ecosystem for JAX. github.com/google/flax.
  2. P. Kidger, C. Garcia (2021). “Equinox: neural networks in JAX via callable PyTrees and filtered transformations.” Differentiable Programming Workshop, NeurIPS.
  3. DeepMind et al. (2020). The DeepMind JAX Ecosystem (Optax). github.com/google-deepmind/optax.
  4. I. Loshchilov, F. Hutter (2019). “Decoupled weight decay regularization.” ICLR.
  5. D. P. Kingma, J. Ba (2015). “Adam: a method for stochastic optimization.” ICLR.