liveBook · Manning

Training step

As explained in Deep Learning with Python, Third Edition

A single update of a model on one batch, consisting of prediction, loss computation, gradient computation, and weight adjustment.

A training step updates a model’s weights using one batch of data. It makes predictions, measures their loss against the targets, computes gradients, and adjusts the weights to reduce that loss. section 2.5.2

One batch of image labels

For a batch of images, the model predicts class probabilities. Sparse categorical crossentropy compares them with the labels; the average loss supplies the scalar used to compute gradients. An optimizer then updates the weights. section 2.5.2

def one_training_step(model, images_batch, labels_batch):
    with tf.GradientTape() as tape:
        predictions = model(images_batch)
        loss = ops.sparse_categorical_crossentropy(labels_batch, predictions)
        average_loss = ops.mean(loss)
    gradients = tape.gradient(average_loss, model.weights)
    update_weights(gradients, model.weights)
    return average_loss

This TensorFlow step records the prediction and loss computation with GradientTape, then uses the resulting gradients to update the weights. section 2.5.2

The four operations are:

  • Predict: run the batch through the model. section 2.5.2
  • Compute loss: compare predictions with the batch’s targets. section 2.5.2
  • Compute gradients: find how the loss changes with the weights, typically using automatic differentiation. section 2.5.2
  • Update weights: move them against the gradients. A simple update subtracts gradient × learning rate from each weight; in practice, use an optimizer. section 2.5.2

An epoch repeats the step for each training batch; a training loop repeats epochs. The step is the reusable unit inside that loop. section 2.5.3

Gradient handling depends on the backend. TensorFlow records operations in GradientTape. In PyTorch, loss.backward() populates gradients on trainable parameters; apply the update under torch.no_grad() and clear gradients with model.zero_grad(). section 7.4.2

import torch

model = get_mnist_model()
loss_fn = keras.losses.SparseCategoricalCrossentropy()
optimizer = keras.optimizers.Adam()

def train_step(inputs, targets):
    predictions = model(inputs, training=True)                    #1
    loss = loss_fn(targets, predictions)                           #1
    loss.backward()                                               #2
    gradients = [weight.value.grad for weight in model.trainable_weights] #3
    with torch.no_grad():                                         #4
        optimizer.apply(gradients, model.trainable_weights)        #4
    model.zero_grad()                                             #5
    return loss

The PyTorch version collects parameter gradients, applies them, and clears them before the next step. section 7.4.2

JAX steps are stateless: pass the current state in and return its updated values. For a Keras model, that state can include trainable weights, non-trainable weights, and optimizer variables. section 3.5.4 section 7.4.2

learning_rate = 0.1

@jax.jit                                                                #1
def training_step(inputs, targets, W, b):
    loss, grads = grad_fn((W, b), inputs, targets)                    #2
    grad_wrt_W, grad_wrt_b = grads
    W = W - grad_wrt_W * learning_rate                                #3
    b = b - grad_wrt_b * learning_rate                                 #3
    return loss, W, b                                                 #4

This JAX linear-classifier step uses value_and_grad and returns the updated weight and bias alongside the loss. section 3.5.4

To customize the learning algorithm without writing the whole loop, subclass keras.Model and override train_step(); fit() calls it for each batch. Return a dictionary of metric names and values. After compile(), self.compute_loss combines the configured loss with regularization losses, while self.metrics provides the configured metrics and a loss tracker. section 7.4.4 section 7.4.5

import keras
from keras import layers

class CustomModel(keras.Model):
    def train_step(self, data):
        inputs, targets = data
        with tf.GradientTape() as tape:
            predictions = self(inputs, training=True)
            loss = self.compute_loss(y=targets, y_pred=predictions)    #1

        gradients = tape.gradient(loss, self.trainable_weights)
        self.optimizer.apply(gradients, self.trainable_weights)

        for metric in self.metrics:                                    #2
            if metric.name == "loss":                                   #2
                metric.update_state(loss)                               #2
            else:                                                       #2
                metric.update_state(targets, predictions)               #2
 #2
        return {m.name: m.result() for m in self.metrics}              #3

This custom TensorFlow step uses the compiled loss and updates each metric before returning its result. section 7.4.5

How Deep Learning with Python, Third Edition covers it

How deep it goes
Works through prediction, loss, gradients, and updates, then implements backend-specific steps and custom metric handling.
Examples
Uses MNIST image classification and a JAX linear classifier to demonstrate training steps.
What it assumes
Assumes familiarity with Keras training APIs and backend gradient APIs in the custom-loop treatment.
What you can do after
Apply it via TensorFlow, PyTorch, or JAX, including by overriding Keras train_step().
How it connects
Connects automatic differentiation, gradient descent, optimizers, epochs, and training metrics.

Also explained in

Compare how 2 books explain training step →

Related concepts

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