Writing a Training Loop from Scratch

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

fit() covers most training jobs, but sometimes you need full control: two optimizers, a loss that depends on several models, a custom gradient transformation, an unusual schedule of updates, or simply a loop you can step through in a debugger. This page writes that loop by hand with tf.GradientTape, a Keras model, Keras losses and stateful Keras metrics. If you would rather keep fit() (callbacks, progress bar, distribution support) and only replace the body of one step, read Customizing fit() with train_step first. The lower-level, Keras-free version of the same loop is on A Training Loop with TF Core; gradient mechanics are on Automatic Differentiation with GradientTape and graph compilation on Graphs, tf.function, AutoGraph and Retracing.

It targets Python 3.13 and TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming), and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31. The same idea in PyTorch is on the PyTorch training loop page, and the theory of the update rule is on Gradient Descent and Optimization and Backpropagation and Autodiff. The loop here is TensorFlow-specific (it uses tf.GradientTape); a backend-neutral version is discussed on Keras Multi-Backend.

Anatomy of one training step

Every custom loop repeats the same five actions per batch: run the forward pass under a recording tape, compute the loss, ask the tape for gradients, hand the gradients to an optimizer, and update the metrics. Validation repeats only the forward pass and the metric updates, without a tape.

flowchart LR B["batch x, y"] --> F["forward pass: model(x, training=True)"] F --> L["loss_fn(y, logits) + sum(model.losses)"] L --> G["tape.gradient(loss, trainable_weights)"] G --> O["optimizer.apply(grads, trainable_weights)"] O --> M["metric.update_state(y, logits)"] M --> N["next batch"] N --> B

The pieces are:

  • A keras.Model (Sequential, Functional or subclassed) whose trainable weights are tracked in model.trainable_weights.

  • A loss callable such as keras.losses.SparseCategoricalCrossentropy(from_logits=True); see Losses.

  • An optimizer instance from keras.optimizers; see Optimizers and Learning-Rate Schedules.

  • Metric objects from keras.metrics, which keep running state in variables; see Metrics.

  • An iterable of batches, typically a tf.data.Dataset; see Input Pipelines with tf.data.

A minimal eager loop

The backend must be chosen before Keras is imported. Setting KERAS_BACKEND to tensorflow documents the intent even though TensorFlow is the default when it is installed.

import os
os.environ["KERAS_BACKEND"] = "tensorflow"

import tensorflow as tf
import keras

# Data: flatten MNIST and scale to [0, 1]
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 784).astype("float32") / 255.0
x_test = x_test.reshape(-1, 784).astype("float32") / 255.0

# Hold out the last 10,000 training samples for validation
x_val, y_val = x_train[-10000:], y_train[-10000:]
x_train, y_train = x_train[:-10000], y_train[:-10000]

batch_size = 64
train_ds = (
    tf.data.Dataset.from_tensor_slices((x_train, y_train))
    .shuffle(buffer_size=1024)
    .batch(batch_size)
)
val_ds = tf.data.Dataset.from_tensor_slices((x_val, y_val)).batch(batch_size)

# Model, loss, optimizer, metrics
model = keras.Sequential([
    keras.Input(shape=(784,)),
    keras.layers.Dense(128, activation="relu"),
    keras.layers.Dense(128, activation="relu"),
    keras.layers.Dense(10),                      # logits, no softmax
])
loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True)
optimizer = keras.optimizers.Adam(learning_rate=1e-3)
train_acc = keras.metrics.SparseCategoricalAccuracy()
val_acc = keras.metrics.SparseCategoricalAccuracy()

for epoch in range(2):
    for step, (x_batch, y_batch) in enumerate(train_ds):
        with tf.GradientTape() as tape:
            logits = model(x_batch, training=True)
            loss_value = loss_fn(y_batch, logits)
        grads = tape.gradient(loss_value, model.trainable_weights)
        optimizer.apply(grads, model.trainable_weights)
        train_acc.update_state(y_batch, logits)

        if step % 200 == 0:
            print(f"epoch {epoch} step {step}: loss {float(loss_value):.4f}")

    print(f"epoch {epoch}: train accuracy {float(train_acc.result()):.4f}")
    train_acc.reset_state()

    for x_batch, y_batch in val_ds:
        val_logits = model(x_batch, training=False)
        val_acc.update_state(y_batch, val_logits)
    print(f"epoch {epoch}: validation accuracy {float(val_acc.result()):.4f}")
    val_acc.reset_state()
# ... epoch 1: validation accuracy 0.9700 (varies from run to run)

Points worth understanding:

  • The tape only records operations executed inside the with block, so the forward pass and the loss belong inside it, while tape.gradient is called outside it. Calling gradient inside the block works but records the gradient computation itself and wastes memory. A non-persistent tape can be queried once.

  • optimizer.apply(grads, variables) is the Keras 3 call. The Keras 2 call apply_gradients(zip(grads, variables)), which you will meet in older tutorials, still works in Keras 3.15; the Keras 3 apply takes two parallel lists instead of pairs. See Migrating from Keras 2 to Keras 3.

  • The model ends in raw logits and the loss is built with from_logits=True, which is numerically more stable than a softmax layer followed by a probability-based loss.

  • Gradients for variables that do not influence the loss come back as None. Keras 3.15 apply skips those variables and warns Gradients do not exist for variables [...]; treat the warning as a bug and fix the graph (for example a layer that was defined but never called).

Training and inference modes

Layers such as Dropout and BatchNormalization behave differently while training and while evaluating: dropout zeroes activations only in training mode, and batch normalization uses batch statistics in training mode and moving averages in inference mode. Calling a model as model(x) does not by default switch it to training mode, so you pass the flag yourself:

logits = model(x_batch, training=True)    # dropout active, BN uses batch statistics, BN moving stats updated
val_logits = model(x_batch, training=False)  # dropout off, BN uses moving statistics

Forgetting training=True in the training step silently trains without dropout; forgetting training=False in validation makes the validation loss noisy and, for batch normalization, corrupts the moving statistics. The fit() method sets both correctly for you, which is one of the reasons to prefer it when you do not need the control.

Stateful metrics

A Keras metric accumulates state (a running sum and a count) in variables. The lifecycle is always the same:

  1. Create the metric once, before the loop.

  2. Call update_state(y_true, y_pred) after each batch.

  3. Call result() to read the current aggregate, for example once per epoch or every N steps.

  4. Call reset_state() when a new aggregation window begins, usually at the end of each epoch.

Use separate metric instances for training and validation so their statistics never mix. keras.metrics.Mean is the metric to use for aggregating a scalar such as the loss:

loss_tracker = keras.metrics.Mean(name="loss")

# inside the step
loss_tracker.update_state(loss_value)

# at the end of the epoch
print("mean loss:", float(loss_tracker.result()))
loss_tracker.reset_state()

Printing loss_value of the last batch only tells you about that batch; the tracker gives the epoch average that fit() reports. Metric names in Keras 3 use reset_state; the older reset_states spelling was removed.

Compiling the step with tf.function

An eager loop runs each operation through the Python interpreter. Wrapping the step in tf.function traces it once into a graph, which TensorFlow can optimise and run without returning to Python between operations. The step must take tensors as arguments and may update Keras metrics and optimizer variables, because those are held in variables.

@tf.function
def train_step(x, y):
    with tf.GradientTape() as tape:
        logits = model(x, training=True)
        loss_value = loss_fn(y, logits)
    grads = tape.gradient(loss_value, model.trainable_weights)
    optimizer.apply(grads, model.trainable_weights)
    train_acc.update_state(y, logits)
    return loss_value

@tf.function
def test_step(x, y):
    val_logits = model(x, training=False)
    val_acc.update_state(y, val_logits)

for epoch in range(2):
    for step, (x_batch, y_batch) in enumerate(train_ds):
        loss_value = train_step(x_batch, y_batch)
        if step % 200 == 0:
            print(f"epoch {epoch} step {step}: loss {float(loss_value):.4f}")
    print("train accuracy:", float(train_acc.result()))
    train_acc.reset_state()

    for x_batch, y_batch in val_ds:
        test_step(x_batch, y_batch)
    print("validation accuracy:", float(val_acc.result()))
    val_acc.reset_state()

The official guide reports roughly an order of magnitude speed-up on a small MNIST model going from eager to tf.function, but the factor depends on model size and hardware, so measure your own. Pitfalls of compiled steps, all covered on the graphs page:

  • Python side effects (print, appending to a list) run only while tracing. Use tf.print for per-call output, and return tensors instead of mutating Python objects.

  • A new Python value or tensor shape for an argument can trigger a retrace. The last batch of an epoch is usually smaller, which causes one extra trace; pass input_signature or reduce_retracing=True, or drop the remainder with batch(batch_size, drop_remainder=True).

  • Create variables (a new metric, a model that builds lazily) before the first call, not inside the traced function. Build the model with keras.Input or call it once on a sample batch.

  • The loss value returned is a tensor; convert with float(...) only outside the function.

Auxiliary losses from layers

A layer can contribute extra terms to the objective, such as an activity regulariser or a KL-divergence penalty, by calling self.add_loss(value) inside call. After a forward pass the model exposes them as model.losses, a list of scalar tensors. Weight regularisers (the kernel_regularizer argument) also appear there. A hand-written loop must add them itself, inside the tape:

class ActivityPenalty(keras.layers.Layer):
    def __init__(self, rate=1e-2, **kwargs):
        super().__init__(**kwargs)
        self.rate = rate

    def call(self, inputs):
        self.add_loss(self.rate * tf.reduce_sum(tf.abs(inputs)))
        return inputs

model = keras.Sequential([
    keras.Input(shape=(784,)),
    keras.layers.Dense(64, activation="relu",
                       kernel_regularizer=keras.regularizers.L2(1e-4)),
    ActivityPenalty(),
    keras.layers.Dense(10),
])

@tf.function
def train_step(x, y):
    with tf.GradientTape() as tape:
        logits = model(x, training=True)
        loss_value = loss_fn(y, logits)
        loss_value += sum(model.losses)          # regularisers and add_loss terms
    grads = tape.gradient(loss_value, model.trainable_weights)
    optimizer.apply(grads, model.trainable_weights)
    return loss_value

The list model.losses is rebuilt at every forward pass, so read it after calling the model and before leaving the tape. sum of an empty list is 0, so the same code works for models without extra losses. Writing the layer itself is covered on Subclassing and Custom Layers.

Freezing weights and choosing what to update

You choose which variables receive gradients by choosing the list passed to tape.gradient and optimizer.apply. Setting layer.trainable = False removes a layer’s weights from model.trainable_weights, which is how transfer learning freezes a backbone (see Transfer Learning and Fine-Tuning). With two networks that train against each other, each has its own tape and its own optimizer:

generator = keras.Sequential([keras.Input(shape=(64,)), keras.layers.Dense(784, activation="sigmoid")])
discriminator = keras.Sequential([keras.Input(shape=(784,)), keras.layers.Dense(1)])
g_opt = keras.optimizers.Adam(1e-4)
d_opt = keras.optimizers.Adam(1e-4)
bce = keras.losses.BinaryCrossentropy(from_logits=True)

@tf.function
def gan_step(real):
    n = tf.shape(real)[0]
    noise = tf.random.normal((n, 64))

    with tf.GradientTape() as d_tape:
        fake = generator(noise, training=True)
        d_real = discriminator(real, training=True)
        d_fake = discriminator(fake, training=True)
        d_loss = bce(tf.ones_like(d_real), d_real) + bce(tf.zeros_like(d_fake), d_fake)
    d_grads = d_tape.gradient(d_loss, discriminator.trainable_weights)
    d_opt.apply(d_grads, discriminator.trainable_weights)

    with tf.GradientTape() as g_tape:
        fake = generator(noise, training=True)
        g_loss = bce(tf.ones_like(fake[:, :1]), discriminator(fake, training=True))
    g_grads = g_tape.gradient(g_loss, generator.trainable_weights)
    g_opt.apply(g_grads, generator.trainable_weights)   # only generator weights move
    return d_loss, g_loss

Passing only generator.trainable_weights to g_opt.apply is what keeps the discriminator fixed during the generator update; no trainable = False toggling is needed. Generative training dynamics are discussed on Generative Models.

Gradient accumulation and clipping

Because the loop owns the gradients, transformations that fit() cannot express are a few lines. Clipping by global norm and accumulating over several micro-batches to simulate a larger batch look like this:

accum_steps = 4
optimizer = keras.optimizers.Adam(learning_rate=1e-3)   # a Keras 3 optimizer only updates the variables it was built with
accum = [tf.Variable(tf.zeros_like(w), trainable=False) for w in model.trainable_weights]

@tf.function
def micro_step(x, y):
    with tf.GradientTape() as tape:
        logits = model(x, training=True)
        loss_value = loss_fn(y, logits) / accum_steps     # scale so the sum is a mean
    grads = tape.gradient(loss_value, model.trainable_weights)
    for a, g in zip(accum, grads):
        a.assign_add(g)
    return loss_value

@tf.function
def apply_accumulated():
    clipped, _ = tf.clip_by_global_norm([tf.convert_to_tensor(a) for a in accum], 1.0)
    optimizer.apply(clipped, model.trainable_weights)
    for a in accum:
        a.assign(tf.zeros_like(a))

for i, (x_batch, y_batch) in enumerate(train_ds):
    micro_step(x_batch, y_batch)
    if (i + 1) % accum_steps == 0:
        apply_accumulated()

For simple clipping you do not need a custom loop: optimizers accept clipnorm, clipvalue and global_clipnorm arguments, and Keras 3 optimizers have a built-in gradient_accumulation_steps option. Check the optimizer page before writing this by hand. Layers that store batch statistics (batch normalization) still see each micro-batch separately, so accumulation is not exactly equivalent to a large batch for such models.

Reusing the loop with callbacks and checkpoints

A hand-written loop gives up the machinery of fit(). Some of it can be borrowed back:

  • Save and restore with model.save("model.keras"), model.save_weights("w.weights.h5") or a tf.train.Checkpoint; see Saving Keras Models and Training Checkpoints. Remember to checkpoint the optimizer too if you want to resume training exactly.

  • Write scalars with tf.summary for TensorBoard; see TensorBoard.

  • Run existing keras.callbacks objects manually through a keras.callbacks.CallbackList, calling its on_epoch_begin, on_train_batch_end and similar methods; see Callbacks.

  • For several devices wrap the step in strategy.run under a tf.distribute strategy and reduce the per-replica loss; see Distributed Training. Mixed precision needs a loss-scaling optimizer wrapper; see Mixed Precision.

When to choose which approach

Table 1. Choosing how much of the loop to write
Approach Use it when You give up

fit() with callbacks

Standard supervised training.

Nothing; this is the default.

train_step override (see custom train_step)

One non-standard update (adversarial, contrastive, multiple losses) but you still want callbacks, progress bar and distribution.

A little control over the order of operations.

Custom loop with GradientTape (this page)

Several optimizers, custom schedules of updates, research prototypes, debugging step by step.

fit() callbacks, automatic metric reset and logging, history object.

TF Core loop without Keras

Teaching, or models built from tf.Module and raw variables.

Keras layers, losses and optimizers.

Common mistakes

  • Using Keras 2 idioms: reset_states (gone from Keras 3 metrics), model.metrics_names assumptions, or tf_keras objects mixed with Keras 3 ones. Under Keras 3, import keras is the preferred entry point (tf.keras is the same Keras 3).

  • Updating metrics with probabilities when the metric expects logits, or the reverse. Match from_logits between the loss and the metrics.

  • Calling tape.gradient twice on a non-persistent tape; create tf.GradientTape(persistent=True) and delete it afterwards if you need several gradients.

  • Watching the wrong variables: only trainable variables are watched automatically. Constants need tape.watch(x) if you want gradients with respect to them.

References