When Do You Need It?
model.fit() covers most cases. A custom loop is useful for GANs, reinforcement learning, special loss combinations or research ideas where you must control every step.
Backend note: The tf.GradientTape code in this lesson works with the TensorFlow backend. If you use JAX or PyTorch backends, the way of computing gradients is different.
A Complete Manual Loop
python
import tensorflow as tf
import keras
from keras import layers
(x_train, y_train), _ = keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 784).astype("float32") / 255.0
train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(10000).batch(64)
model = keras.Sequential([
keras.Input(shape=(784,)),
layers.Dense(128, activation="relu"),
layers.Dense(10), # logits
])
loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True)
optimizer = keras.optimizers.Adam(1e-3)
acc_metric = keras.metrics.SparseCategoricalAccuracy()
for epoch in range(3):
acc_metric.reset_state()
for x_batch, y_batch in train_ds:
with tf.GradientTape() as tape:
logits = model(x_batch, training=True) # forward pass
loss = loss_fn(y_batch, logits) # compute loss
grads = tape.gradient(loss, model.trainable_variables) # backward
optimizer.apply_gradients(zip(grads, model.trainable_variables)) # update
acc_metric.update_state(y_batch, logits)
print(f"Epoch {epoch + 1}: loss={float(loss):.4f} acc={float(acc_metric.result()):.4f}")
- Open
GradientTape to record the forward pass
- Compute the loss
- Ask the tape for gradients
- Apply the gradients with the optimizer
- Update the metrics
Faster with tf.function
python
@tf.function
def train_step(x, y):
with tf.GradientTape() as tape:
logits = model(x, training=True)
loss = loss_fn(y, logits)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
acc_metric.update_state(y, logits)
return loss
@tf.function compiles the Python function into a TensorFlow graph, which usually runs much faster.
Better: Override train_step
You can keep the convenience of fit(), callbacks and progress bars while customizing the step itself.
python
class CustomModel(keras.Model):
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)
grads = tape.gradient(loss, self.trainable_variables)
self.optimizer.apply_gradients(zip(grads, self.trainable_variables))
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=(784,))
x = layers.Dense(128, activation="relu")(inputs)
outputs = layers.Dense(10, activation="softmax")(x)
model = CustomModel(inputs, outputs)
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(x_train, y_train, epochs=2, batch_size=64)
Tip: Start with the built-in fit(). Move to train_step when you need custom logic, and use a full manual loop only as a last resort.
Conclusion
GradientTape exposes what fit() does behind the scenes. Overriding train_step gives you control without losing Keras features.
Quick Summary: Record the forward pass in GradientTape, get gradients, apply them with the optimizer and update metrics.