Customizing fit() with train_step

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

fit() is convenient but assumes the standard supervised recipe: one forward pass, one loss, one gradient step. Many models need something else: two optimizers (GANs), an extra loss term, gradient clipping done by hand, a self-supervised objective, or per-sample masking. Overriding train_step replaces what happens in one batch and keeps everything else that fit() provides: the epoch loop, progress bar, callbacks, validation, distribution strategies and History. If you need full control of the loop itself, go to Writing a Training Loop from Scratch; the standard behaviour is on compile, fit, evaluate & predict, the hooks that surround steps on Callbacks, and the lower-level gradient mechanics on Automatic Differentiation with GradientTape and A Training Loop with TF Core.

It targets Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming and not covered) 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. Snippets that continue an earlier example, or use names such as model and train_ds defined elsewhere, were run with small synthetic stand-ins. The examples set KERAS_BACKEND to tensorflow because the gradient code uses tf.GradientTape; the same ideas on other backends are summarised near the end.

When to override train_step

Use it when the standard loop is almost right. Compare the options:

Need Choice

Different loss weighting, per-sample masks, extra regularizer

compile(loss=...), sample_weight, add_loss() or a custom loss function. No override needed.

Different metric

A custom Metric passed to compile().

Different update rule, several optimizers, extra forward passes, gradient surgery, adversarial training

Override train_step (this page).

Different data handling per epoch, bespoke evaluation schedule, non-standard iteration

A full custom loop.

Related: Losses and Metrics cover the cheaper options, and Backpropagation and Autodiff explains the mathematics behind the gradient step.

The minimal override

fit() calls train_step(data) once per batch. data is whatever the input pipeline yields: a tuple (x, y) for NumPy arrays or datasets, or (x, y, sample_weight) when weights are supplied. The method must return a dictionary of metric names to current values, which feeds the progress bar, the logs and the callbacks.

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

import numpy as np
import tensorflow as tf
import keras
from keras import layers


class CustomModel(keras.Model):
    def train_step(self, data):
        x, y = data

        with tf.GradientTape() as tape:
            y_pred = self(x, training=True)                  # forward pass
            loss = self.compute_loss(y=y, y_pred=y_pred)     # loss given to compile()

        trainable_vars = self.trainable_variables
        gradients = tape.gradient(loss, trainable_vars)
        self.optimizer.apply(gradients, trainable_vars)      # update weights

        for metric in self.metrics:
            if metric.name == "loss":
                metric.update_state(loss)
            else:
                metric.update_state(y, y_pred)

        return {m.name: m.result() for m in self.metrics}


inputs = keras.Input(shape=(32,))
outputs = layers.Dense(1)(inputs)
model = CustomModel(inputs, outputs)

model.compile(optimizer="adam", loss="mse", metrics=["mae"])

x = np.random.random((1000, 32)).astype("float32")
y = np.random.random((1000, 1)).astype("float32")
model.fit(x, y, epochs=3, batch_size=64)

What each piece does:

  • self(x, training=True) calls the model in training mode, so dropout and batch normalization behave as during training. A frequent bug is to omit training=True.

  • self.compute_loss(y=y, y_pred=y_pred) wraps the loss (or losses) given to compile(). It also includes the regularization losses of layers. You may skip it and call your own loss object instead.

  • self.optimizer.apply(grads, vars) applies the update and increments the optimizer’s iteration counter. It is the Keras 3 spelling of Keras 2’s apply_gradients(zip(grads, vars)), which Keras 3.15 still accepts; see Migrating from Keras 2 to Keras 3.

  • Metrics are updated by hand, and the loss entry in self.metrics is the built-in loss tracker.

  • The returned dictionary should contain scalars, either tensors or Python numbers. Names become keys in History and in logs, so they define what EarlyStopping(monitor=...) can watch.

The model must be built from the subclass so that Keras knows the overridden method; the example uses the Functional constructor CustomModel(inputs, outputs), which also works for Sequential-like use. Subclassed-model details are in Subclassing & Custom Layers.

flowchart LR A[fit loop: next batch] --> B[train_step data] B --> C[unpack x, y, sample_weight] C --> D[forward pass under GradientTape] D --> E[compute_loss] E --> F[gradients] F --> G[optimizer.apply] G --> H[update metrics] H --> I[return dict of results] I --> J[progress bar and callbacks]

Tracking your own metrics

Metrics held by the model must be reset at the start of every epoch, otherwise the printed numbers are running averages across the entire run. Keras resets the objects it knows about at the start of each fit() epoch and of evaluate(). The standard way to make it know about yours is to override the metrics property.

class CustomModel(keras.Model):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.loss_tracker = keras.metrics.Mean(name="loss")
        self.mae_metric = keras.metrics.MeanAbsoluteError(name="mae")

    def train_step(self, data):
        x, y = data
        with tf.GradientTape() as tape:
            y_pred = self(x, training=True)
            loss = keras.losses.mean_squared_error(y, y_pred)
        grads = tape.gradient(loss, self.trainable_variables)
        self.optimizer.apply(grads, self.trainable_variables)

        self.loss_tracker.update_state(loss)
        self.mae_metric.update_state(y, y_pred)
        return {"loss": self.loss_tracker.result(),
                "mae": self.mae_metric.result()}

    @property
    def metrics(self):
        # Listing the metrics here lets Keras call reset_state() on them
        # at the start of each epoch and of evaluate().
        return [self.loss_tracker, self.mae_metric]


model = CustomModel(inputs, outputs)
model.compile(optimizer="adam")          # no loss: train_step computes it
model.fit(x, y, epochs=3)

Notes:

  • Here the loss comes from keras.losses.mean_squared_error, so compile() has no loss argument. That is allowed because train_step never asks the compiled loss.

  • Returning {m.name: m.result() for m in self.metrics} is equivalent to listing the entries by hand and keeps the dictionary in sync with the metrics.

  • loss from mean_squared_error has shape (batch,); the Mean metric averages it. For optimization, tape.gradient of a vector sums its entries; use a scalar loss (ops.mean) when the scale matters to the optimizer.

  • If you also want the metrics passed to compile(metrics=[...]) to be updated, call compute_metrics (see below) or iterate self.metrics as in the first example.

Sample weights

data can have three elements. Unpack them with the helper keras.utils.unpack_x_y_sample_weight(data), or manually, and pass the weights to the loss and to every metric.

class WeightedModel(keras.Model):
    def train_step(self, data):
        x, y, sample_weight = keras.utils.unpack_x_y_sample_weight(data)

        with tf.GradientTape() as tape:
            y_pred = self(x, training=True)
            loss = self.compute_loss(y=y, y_pred=y_pred,
                                     sample_weight=sample_weight)

        grads = tape.gradient(loss, self.trainable_variables)
        self.optimizer.apply(grads, self.trainable_variables)

        for metric in self.metrics:
            if metric.name == "loss":
                metric.update_state(loss)
            else:
                metric.update_state(y, y_pred, sample_weight=sample_weight)
        return {m.name: m.result() for m in self.metrics}

When fit() receives class_weight, Keras converts it into per-sample weights before train_step sees the data, so handling sample_weight covers both. With a tf.data.Dataset, return (x, y, w) from the pipeline. The unpack_x_y_sample_weight helper appears in the official JAX version of this guide; it works regardless of backend because it only inspects the structure.

Customizing evaluate() with test_step

evaluate() and the validation phase of fit() call test_step. If you override train_step but not test_step, the default is used, which can disagree with your training metrics (for example different loss, missing metrics). Override it too:

class CustomModel(keras.Model):
    def test_step(self, data):
        x, y = data
        y_pred = self(x, training=False)                 # inference mode
        loss = self.compute_loss(y=y, y_pred=y_pred)

        for metric in self.metrics:
            if metric.name == "loss":
                metric.update_state(loss)
            else:
                metric.update_state(y, y_pred)
        return {m.name: m.result() for m in self.metrics}

No gradient tape is needed, and training=False is essential. predict() has the matching predict_step(data), whose result is what predict() collects; override it to post-process outputs or to accept (x,) and (x, y) structures.

Writing the loss in the model

When the model owns the loss (as in the earlier example without loss= in compile()), remember that:

  • compute_loss accounts for layer regularizers and add_loss() terms; a hand-written loss does not. Use self.losses (the list of regularization losses) and add tf.add_n(self.losses) or sum(self.losses) yourself if you bypass compute_loss.

  • Gradient clipping is a one-liner at construction (clipnorm= and clipvalue= on the optimizer) or done manually with tf.clip_by_global_norm(gradients, 1.0) between tape.gradient and apply.

  • Mixed precision with compile() wraps the optimizer for loss scaling when auto_scale_loss=True; a manual train_step that scales the loss itself must not scale twice. See Mixed Precision.

A GAN: two optimizers in one train_step

A generative adversarial network trains a discriminator and a generator with different objectives, which compile() alone cannot express. The model overrides compile() to receive extra arguments, then runs two tapes in train_step. The full pattern in the official guide uses keras.random.SeedGenerator for reproducible noise; this reduced version keeps the structure.

class GAN(keras.Model):
    def __init__(self, discriminator, generator, latent_dim):
        super().__init__()
        self.discriminator = discriminator
        self.generator = generator
        self.latent_dim = latent_dim
        self.seed_generator = keras.random.SeedGenerator(1337)
        self.d_loss_tracker = keras.metrics.Mean(name="d_loss")
        self.g_loss_tracker = keras.metrics.Mean(name="g_loss")

    @property
    def metrics(self):
        return [self.d_loss_tracker, self.g_loss_tracker]

    def compile(self, d_optimizer, g_optimizer, loss_fn):
        super().compile()                     # no loss/optimizer for the base class
        self.d_optimizer = d_optimizer
        self.g_optimizer = g_optimizer
        self.loss_fn = loss_fn

    def train_step(self, real_images):
        if isinstance(real_images, tuple):    # (images, labels): ignore labels
            real_images = real_images[0]
        batch_size = tf.shape(real_images)[0]

        # 1. Train the discriminator on fake and real images.
        z = keras.random.normal((batch_size, self.latent_dim),
                                seed=self.seed_generator)
        fake_images = self.generator(z)
        combined = tf.concat([fake_images, real_images], axis=0)
        labels = tf.concat([tf.ones((batch_size, 1)),
                            tf.zeros((batch_size, 1))], axis=0)
        labels += 0.05 * keras.random.uniform(tf.shape(labels),
                                              seed=self.seed_generator)

        with tf.GradientTape() as tape:
            d_loss = self.loss_fn(labels, self.discriminator(combined))
        grads = tape.gradient(d_loss, self.discriminator.trainable_weights)
        self.d_optimizer.apply(grads, self.discriminator.trainable_weights)

        # 2. Train the generator to make the discriminator say "real".
        z = keras.random.normal((batch_size, self.latent_dim),
                                seed=self.seed_generator)
        misleading = tf.zeros((batch_size, 1))
        with tf.GradientTape() as tape:
            g_loss = self.loss_fn(misleading, self.discriminator(self.generator(z)))
        grads = tape.gradient(g_loss, self.generator.trainable_weights)
        self.g_optimizer.apply(grads, self.generator.trainable_weights)

        self.d_loss_tracker.update_state(d_loss)
        self.g_loss_tracker.update_state(g_loss)
        return {"d_loss": self.d_loss_tracker.result(),
                "g_loss": self.g_loss_tracker.result()}


gan = GAN(discriminator, generator, latent_dim=128)
gan.compile(d_optimizer=keras.optimizers.Adam(1e-4),
            g_optimizer=keras.optimizers.Adam(1e-4),
            loss_fn=keras.losses.BinaryCrossentropy(from_logits=True))
gan.fit(dataset, epochs=1)

discriminator and generator are ordinary Keras models you define. Because each tape differentiates only with respect to one network’s weights, the other network is effectively frozen for that update. Generative models in general, including diffusion and VAEs, are discussed in Generative Models.

Execution model and pitfalls on the TensorFlow backend

On the TensorFlow backend fit() wraps train_step in a tf.function, and with jit_compile="auto" it may also be XLA-compiled. That has consequences:

  • The body is traced once and then replayed. Python side effects (print, appending to a list, incrementing a Python counter) happen only at trace time. Use tf.print or metrics for values that must update every step. See Graphs, tf.function, AutoGraph & Retracing.

  • Python control flow that depends on tensor values must use tf.cond / tf.while_loop or work through AutoGraph. Control flow on static Python values is fine.

  • New tf.Variable objects cannot be created on later calls. Create them in __init__ or build().

  • If the batch shape changes between calls (a final smaller batch), a retrace may happen; that is normal but can be slow if shapes vary a lot.

  • To debug, compile with run_eagerly=True so the step executes line by line, then switch it off for speed. Remember jit_compile interactions: an operation unsupported by XLA fails only when compiled; pass jit_compile=False to bypass.

  • self.optimizer.apply creates optimizer slot variables lazily the first time; the optimizer can be built automatically on first use in Keras 3, so manual build() is rarely needed.

Compute-metrics and the compiled metrics

Keras 3 models also carry a method compute_metrics(x, y, y_pred, sample_weight=None) that updates the metrics listed in compile() and returns their values, and compute_loss(x, y, y_pred, sample_weight, training). The official custom-train-step guide for TensorFlow writes the metric loop by hand as shown above; this page does the same, because the loop works identically on every backend. If you prefer compute_metrics, Keras 3.15 has it as compute_metrics(x, y, y_pred, sample_weight=None): it updates the metrics passed to compile() and returns all metric results as a dictionary. In a custom train_step it does not update the built-in loss tracker: a step that only returns self.compute_metrics(x, y, y_pred) logs loss: 0.0 in Keras 3.15, so the loss entry still has to be updated by hand. The Keras model API reference page does not document the method, so the hand-written loop is the more stable choice.

Other backends

Keras 3 can run on JAX and PyTorch as well as TensorFlow (see Keras Multi-Backend: JAX, PyTorch & keras.ops). The train_step contract is the same (consume a batch, return a dictionary of metric values) but the gradient mechanics differ, so there are separate official guides.

Backend Gradient and update Notes

TensorFlow

tf.GradientTape, tape.gradient, self.optimizer.apply

Stateful; variables are updated in place inside a tf.function.

JAX

Signature train_step(self, state, data); jax.value_and_grad over a loss function; self.stateless_call; self.optimizer.stateless_apply; returns (logs, state)

Fully functional: all variables (trainable, non-trainable, optimizer, metrics) are passed in and returned. No in-place mutation.

PyTorch

self.zero_grad(), loss.backward(), read v.value.grad of self.trainable_weights, then self.optimizer.apply(...) inside torch.no_grad()

Gradients accumulate in .grad, so clear them every step; the two-step GAN calls zero_grad() before each update.

A train_step written with backend-neutral keras.ops for the math but tf.GradientTape for gradients is not portable. To write one model that runs everywhere, keep the logic in layers and losses and avoid overriding train_step, or maintain one override per backend. Comparing with plain PyTorch, the hand-written loop is shown on the PyTorch training loop page.

Common mistakes

  • Forgetting training=True in the forward pass of train_step and training=False in test_step.

  • Returning tensors that are not scalars (a vector loss), which breaks the progress bar. Reduce first.

  • Using Keras 2 idioms: self.compiled_loss(...) or self.compiled_metrics.update_state(...). They are the Keras 2 interface (in Keras 3.15 compiled_metrics is a deprecated shim); Keras 3 uses compute_loss, self.optimizer.apply and the metric objects.

  • Not listing owned metrics in the metrics property, so they are never reset and the displayed values are running averages across epochs.

  • Updating a Python variable inside train_step and expecting it to change each step.

  • Overriding train_step but not test_step, giving validation numbers on a different basis.

  • Calling model.compile(loss=...) with a loss and then also computing a second loss by hand without realising the compiled one is ignored.

  • Overriding compile() with a new signature but forgetting super().compile().

  • Expecting steps_per_execution or jit_compile to behave the same on every backend; see compile, fit, evaluate & predict.