liveBook · Manning

TrainState

As explained in Deep Learning with JAX

A Flax dataclass-like container that bundles model parameters, optimizer state, step count, and an apply function for training.

How do you keep a JAX training loop’s moving parts together? Flax’s TrainState packages the model’s apply function, parameters, optimizer transformation, optimizer state, and step information into one functional training value. section 11.1.3 section 11.4

Create a state with TrainState.create(), supplying model.apply, initialized parameters, and an Optax transformation. Initialization of the optimizer state happens inside create(). During each update, call state.apply_fn to run the model and state.apply_gradients(grads=grads) to update parameters and optimizer state. Because the updated state is returned, the loop remains compatible with JAX’s functional transformations. section 11.1.3 section 11.4

A basic TrainState provides:

  • apply_fn, usually model.apply, for applying the network to variables and inputs. section 11.1.3
  • params for the trainable model parameters updated by the optimizer. section 11.1.3
  • tx for an Optax gradient transformation such as SGD with momentum. section 11.1.3
  • A single-optimizer design suited to the common case; add metrics or other state by subclassing TrainState. section 11.1.3

TrainState is extensible rather than universal. A metrics subclass can hold CLU collections and update them with replace(). Models with internal state, such as BatchNorm, require another field—often model_state—and explicit mutable collections during apply. section 11.2.1

How Deep Learning with JAX covers it

How deep it goes
Explains creation and gradient updates, then extends the pattern to metrics and mutable model state.
Examples
Demonstrates SGD with momentum, a jitted MNIST update loop, metric accumulation, and a ResNet state extension.
What it assumes
Assumes initialized Flax model parameters and familiarity with JAX gradients, while hiding Optax optimizer-state initialization.
What you can do after
Build it from scratch with TrainState.create, update it through apply_gradients, and extend it for metrics or model variables.
How it connects
Connects Flax Linen, JAX transformations, Optax gradient transformations, CLU metrics, and BatchNorm model state.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with JAX. The section links point to the parts of the book it draws on.