EMA#
- class flax.nnx.EMA(self, params, decay, *, warmup_steps=0, only=Ellipsis, graph=None)[source]#
Exponential Moving Average (EMA) of parameters.
Maintains a shadow copy of model Variables that is updated as an exponentially weighted moving average on each call to
update(). This is commonly used to stabilize training and improve evaluation performance by applying the averaged parameters at inference time.Example usage:
>>> from flax import nnx >>> import jax, jax.numpy as jnp >>> import optax ... >>> model = nnx.Linear(2, 2, rngs=nnx.Rngs(0)) >>> optimizer = nnx.Optimizer(model, optax.sgd(0.1), wrt=nnx.Param) >>> ema = nnx.EMA(model, decay=0.9) >>> ema_model = ema.apply_to(model) ... >>> def loss_fn(model, x, y): ... return jnp.mean((model(x) - y) ** 2) ... >>> @nnx.jit ... def train_step(model, optimizer, ema, x, y): ... grads = nnx.grad(loss_fn)(model, x, y) ... optimizer.update(model, grads) ... ema.update(model) ... >>> @nnx.jit ... def eval_step(model, x, y): ... return loss_fn(model, x, y) ... >>> x, y = jnp.ones((1, 2)), jnp.ones((1, 2)) >>> train_step(model, optimizer, ema, x, y) >>> loss = eval_step(ema_model, x, y)
In this example,
ema.updatecomputes the moving average and updates the internal state ofema.ema.apply_tocreates a new model instance (ema_model) that shares its Variables withema. Therefore,ema_modelwill automatically reflect the updates performed byema.updateand can be used directly ineval_step.- decay#
The decay rate for the exponential moving average, either a float in
[0, 1)or a callable mapping the 0-based update count to a decay rate (e.g. anoptax.Schedule).
- warmup_steps#
The number of updates over which the update rate is warmed up to
1 - decay.0means no warmup.
- count#
A
Variablethat tracks the number of updates, orNoneifdecayis a float andwarmup_stepsis0.
- filter#
The filter used to select which variables to track.
- params#
A pytree of variables holding the current moving average values.
- __init__(params, decay, *, warmup_steps=0, only=Ellipsis, graph=None)[source]#
Initializes the EMA module.
- Parameters:
params – Any object, typically an NNX module/node, whose parameters will be tracked.
decay – The decay rate for the moving average. Either a float in
[0, 1), or a callable mapping the 0-based update count (a scalarint32jax.Array) to a decay rate (e.g. anoptax.Schedule).warmup_steps – If positive, the update rate starts higher and decreases to
1 - decayover the firstwarmup_stepsupdates, so that the average is less dominated by the initial parameters early in training. Cannot be combined with a callabledecay. Seeupdate()for the exact schedule. Defaults to0, which disables warmup.only – A filter indicating which variables should be included in the EMA tracking. Defaults to matching everything. Note that EMA only tracks
nnx.Variableinstances.graph – If
True, uses graph-mode which supports the full NNX feature set including shared references. IfFalse, uses tree-mode which treats Modules as regular JAX pytrees, avoiding the overhead of the graph protocol. IfNone(default), the value is determined by the currentnnx.set_graph_modecontext.
- Raises:
ValueError – If
decayis a float not in[0, 1),warmup_stepsis negative, or bothwarmup_steps != 0and a callabledecayare provided.TypeError – If
paramscontains non-Variable leaves.
- update(updates)[source]#
Updates the EMA parameters towards the given new parameters.
The update rule for each parameter is:
ema = decay * ema + (1 - decay) * update
If
decayis callable,decay = decay(count)is evaluated using the 0-based update count before incrementingcount.If
warmup_steps > 0, the rate1 - decayis replaced by:max(1 - decay, 1 / (1 + count * k))
where
countis the number of updates so far, including the current one, andk = decay / ((1 - decay) * warmup_steps), so that the rate reaches1 - decayatcount == warmup_steps.- Parameters:
updates – The new parameters or module to blend into the current EMA. This should have the same structure as the
paramsobject passed during initialization.