Skip to content
C.W.K.
Lesson 04 of 05 · published

The Complete Training Loop

~9 min · training, jax, tutorial

Level 0Curious
0 XP0/73 lessons0/17 achievements
0/100 XP to next level100 XP to go0% complete

This small Flax NNX and Optax loop is self-contained. It generates synthetic images in NHWC format with shape (batch, 28, 28, 1), float32 values and integer labels from 0 to 9. The random labels make it a wiring check, not an accuracy benchmark. Replace the synthetic batches with a real dataset before drawing conclusions about learning.

from flax import nnx
import jax
import jax.numpy as jnp
import optax


class Classifier(nnx.Module):
    def __init__(self, *, rngs):
        self.conv1 = nnx.Conv(1, 32, (3, 3), padding="SAME", rngs=rngs)
        self.conv2 = nnx.Conv(32, 64, (3, 3), padding="SAME", rngs=rngs)
        # NHWC: 28x28 -> 14x14 -> 7x7 after two pooling layers.
        self.linear1 = nnx.Linear(64 * 7 * 7, 256, rngs=rngs)
        self.linear2 = nnx.Linear(256, 10, rngs=rngs)
        self.dropout = nnx.Dropout(rate=0.5, rngs=rngs)

    def __call__(self, x):
        x = nnx.relu(self.conv1(x))
        x = nnx.max_pool(x, (2, 2), strides=(2, 2))
        x = nnx.relu(self.conv2(x))
        x = nnx.max_pool(x, (2, 2), strides=(2, 2))
        x = x.reshape(x.shape[0], -1)
        x = self.dropout(nnx.relu(self.linear1(x)))
        return self.linear2(x)


model = Classifier(rngs=nnx.Rngs(0))
schedule = optax.warmup_cosine_decay_schedule(
    init_value=1e-4, peak_value=1e-3, warmup_steps=2, decay_steps=12,
)
tx = optax.chain(
    optax.clip_by_global_norm(1.0),
    optax.adamw(learning_rate=schedule),
)
optimizer = nnx.Optimizer(model, tx, wrt=nnx.Param)


@nnx.jit
def train_step(model, optimizer, x, y):
    def loss_fn(model):
        logits = model(x)
        return optax.softmax_cross_entropy_with_integer_labels(logits, y).mean()

    loss, grads = nnx.value_and_grad(loss_fn)(model)
    optimizer.update(model, grads)
    return loss


@nnx.jit
def eval_step(model, x, y):
    logits = model(x)
    return jnp.sum(jnp.argmax(logits, axis=-1) == y)


def make_batch(key, size=8):
    image_key, label_key = jax.random.split(key)
    x = jax.random.uniform(image_key, (size, 28, 28, 1), dtype=jnp.float32)
    y = jax.random.randint(label_key, (size,), 0, 10)
    return x, y


# Synthetic data checks the wiring; it is not an accuracy benchmark.
train_batches = [make_batch(jax.random.key(i)) for i in range(2)]
val_batches = [make_batch(jax.random.key(100)), make_batch(jax.random.key(101), 3)]

for epoch in range(2):
    model.train()  # Enable dropout before tracing the training step.
    total_loss, train_count = 0.0, 0
    for x, y in train_batches:
        loss = train_step(model, optimizer, x, y)
        total_loss += loss * x.shape[0]
        train_count += x.shape[0]

    model.eval()  # Disable dropout before tracing the evaluation step.
    correct, val_count = 0, 0
    for x, y in val_batches:
        correct += eval_step(model, x, y)
        val_count += x.shape[0]

    print(f"Epoch {epoch}: loss={float(total_loss / train_count):.4f}, "
          f"val_acc={float(correct / val_count):.4f}")

Follow One Update

Two SAME convolutions preserve spatial sizes, while two stride-2 pooling layers reduce 28 to 14 to 7. The dense layer therefore receives 64 * 7 * 7 features. The optimizer explicitly selects nnx.Param, and update(model, grads) applies the gradients to that model. The warm-up schedule is deliberately short for this two-epoch demonstration.

Call model.train() before the training loop and model.eval() before evaluation so dropout has the correct mode when the corresponding JIT function is traced. Evaluation counts correct predictions and divides by the number of examples; a smaller final batch does not receive the weight of a full batch.

💡 Why This Matters

The example exercises initialization, a compiled gradient update and deterministic evaluation. JIT stages the training computation, but it does not promise that every operation becomes one fused hardware kernel. Production work still needs real data, checkpointing, recovery and validation in the intended runtime.

To turn this into the exercise below, use a repeatable data loader, extend the schedule to the intended update count, record package versions and save the final parameters. Keep validation data separate from training data and test loading the saved model.

Code

from flax import nnx
import jax
import jax.numpy as jnp
import optax


class Classifier(nnx.Module):
    def __init__(self, *, rngs):
        self.conv1 = nnx.Conv(1, 32, (3, 3), padding="SAME", rngs=rngs)
        self.conv2 = nnx.Conv(32, 64, (3, 3), padding="SAME", rngs=rngs)
        # NHWC: 28x28 -> 14x14 -> 7x7 after two pooling layers.
        self.linear1 = nnx.Linear(64 * 7 * 7, 256, rngs=rngs)
        self.linear2 = nnx.Linear(256, 10, rngs=rngs)
        self.dropout = nnx.Dropout(rate=0.5, rngs=rngs)

    def __call__(self, x):
        x = nnx.relu(self.conv1(x))
        x = nnx.max_pool(x, (2, 2), strides=(2, 2))
        x = nnx.relu(self.conv2(x))
        x = nnx.max_pool(x, (2, 2), strides=(2, 2))
        x = x.reshape(x.shape[0], -1)
        x = self.dropout(nnx.relu(self.linear1(x)))
        return self.linear2(x)


model = Classifier(rngs=nnx.Rngs(0))
schedule = optax.warmup_cosine_decay_schedule(
    init_value=1e-4, peak_value=1e-3, warmup_steps=2, decay_steps=12,
)
tx = optax.chain(
    optax.clip_by_global_norm(1.0),
    optax.adamw(learning_rate=schedule),
)
optimizer = nnx.Optimizer(model, tx, wrt=nnx.Param)


@nnx.jit
def train_step(model, optimizer, x, y):
    def loss_fn(model):
        logits = model(x)
        return optax.softmax_cross_entropy_with_integer_labels(logits, y).mean()

    loss, grads = nnx.value_and_grad(loss_fn)(model)
    optimizer.update(model, grads)
    return loss


@nnx.jit
def eval_step(model, x, y):
    logits = model(x)
    return jnp.sum(jnp.argmax(logits, axis=-1) == y)


def make_batch(key, size=8):
    image_key, label_key = jax.random.split(key)
    x = jax.random.uniform(image_key, (size, 28, 28, 1), dtype=jnp.float32)
    y = jax.random.randint(label_key, (size,), 0, 10)
    return x, y


# Synthetic data checks the wiring; it is not an accuracy benchmark.
train_batches = [make_batch(jax.random.key(i)) for i in range(2)]
val_batches = [make_batch(jax.random.key(100)), make_batch(jax.random.key(101), 3)]

for epoch in range(2):
    model.train()  # Enable dropout before tracing the training step.
    total_loss, train_count = 0.0, 0
    for x, y in train_batches:
        loss = train_step(model, optimizer, x, y)
        total_loss += loss * x.shape[0]
        train_count += x.shape[0]

    model.eval()  # Disable dropout before tracing the evaluation step.
    correct, val_count = 0, 0
    for x, y in val_batches:
        correct += eval_step(model, x, y)
        val_count += x.shape[0]

    print(f"Epoch {epoch}: loss={float(total_loss / train_count):.4f}, "
          f"val_acc={float(correct / val_count):.4f}")

External links

Exercise

Combine: model (Flax NNX or Equinox), loss, optax optimizer, jit'd train_step, simple data loader, 100-step loop. Print training loss every 10 steps. Save the final params. This is your minimum-viable JAX trainer template.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign in — Please sign in to comment.

No comments yet — be the first.