+1 (415) 366-1364

Custom Training Logic in Keras 3: Overriding train_step Without Giving Up fit()

Most TensorFlow projects hit the same wall: model.fit() is almost right, but you need a custom loss term, a two-optimizer setup, or gradient accumulation. The temptation is to rewrite everything as a hand-rolled loop and lose callbacks, checkpointing, and progress reporting. There is a better middle path: override train_step.

Why override train_step

fit() handles batching, callbacks, distribution strategy, and metric reset. train_step is only the part that computes one update. Overriding it keeps the rest of the machinery. Write a full custom loop only when you need control over the data loop itself.

A minimal override on the TensorFlow backend

import os
os.environ["KERAS_BACKEND"] = "tensorflow"
import keras
import tensorflow as tf

class RegularizedModel(keras.Model):
    def __init__(self, *args, aux_weight=0.1, **kwargs):
        super().__init__(*args, **kwargs)
        self.aux_weight = aux_weight
        self.loss_tracker = keras.metrics.Mean(name="loss")

    @property
    def metrics(self):
        return [self.loss_tracker] + super().metrics

    def train_step(self, data):
        x, y = data
        with tf.GradientTape() as tape:
            y_pred = self(x, training=True)
            loss = self.compute_loss(y=y, y_pred=y_pred)
            loss += self.aux_weight * tf.add_n(self.losses or [0.0])
        grads = tape.gradient(loss, self.trainable_variables)
        self.optimizer.apply(grads, self.trainable_variables)
        self.loss_tracker.update_state(loss)
        for m in super().metrics:
            m.update_state(y, y_pred)
        return {m.name: m.result() for m in self.metrics}

Three details matter. Pass training=True so dropout and batch norm behave. Use compute_loss so compiled losses and sample weights still work. Return metric results as a dict so callbacks see them.

Keeping metrics honest

Metrics listed in the metrics property are reset automatically each epoch. If you create a tracker and forget to expose it, it will average across epochs and report misleading numbers. Mirror the same logic in test_step, with training=False, so validation uses the same loss definition.

Gradient accumulation

When a batch will not fit in memory, accumulate gradients over N micro-batches. Keep one non-trainable variable per weight, add each micro-batch gradient divided by N, and call optimizer.apply only every Nth step using tf.cond. Remember that batch normalization statistics are still computed per micro-batch, so prefer layer normalization for these models. Recent Keras optimizers also expose a gradient_accumulation_steps argument. Try that first, and write your own only if you need custom behavior.

Two optimizers, one model

For GAN-style or fine-tuning setups, pass the extra optimizers to compile as keyword arguments or store them as attributes. Split variables by name or layer, take separate gradients from a persistent=True tape, and apply each set with its own optimizer.

Making it portable

If you may later move to JAX, train_step needs jax.value_and_grad and a stateless pattern instead of a tape. Keras 3 supports both, but they are separate implementations. Isolate backend-specific code in a small subclass so the model definition stays shared.

Testing the override

  • Overfit a tiny batch: loss should approach zero within a few hundred steps.
  • Compare against a plain fit() model with aux_weight=0; the loss curves should match closely.
  • Assert that every trainable variable receives a non-None gradient.
  • Run one epoch under tf.distribute.MirroredStrategy on CPU with two logical devices to catch strategy issues early.

Common pitfalls

  • Calling self.optimizer.apply_gradients from older code; Keras 3 uses apply.
  • Forgetting jit_compile compatibility: avoid Python side effects inside train_step.
  • Returning tensors that depend on the tape outside its scope.

When to bring in help

Custom training logic is where subtle bugs hide: silent gradient drops, wrong metric reductions, and distribution mismatches. If your team needs a second pair of eyes on a training pipeline, get in touch and we can match you with a senior TensorFlow engineer.