A Training Loop with TF Core
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Every training framework reduces to the same cycle: compute predictions, compute a loss, differentiate, update parameters. This page writes that cycle with nothing but TensorFlow core: a tf.Module as the model, tf.GradientTape for gradients, in-place updates, and then the same loop with an optimizer, mini-batches from tf.data and tf.function. It finishes by showing the equivalent Keras fit call, so you can see exactly what that method automates. Pieces used here are explained on Modules, Variables, Automatic Differentiation and Graphs and tf.function. Customising Keras itself is on Customizing fit() with train_step and Writing a Training Loop from Scratch.
It targets Python 3.13 and TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is labelled "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 mathematics of the update rule is in Gradient Descent and Optimization and of differentiation in Backpropagation and Autodiff; the PyTorch version of the same loop is Training Loop.
The problem
The task is a one-feature linear regression on synthetic data, small enough that the whole dataset is a single batch and the answer is known: \( y = 3x + 2 + \varepsilon \). The goal is to recover a weight near 3 and a bias near 2. Because the optimum is known, any bug in the loop shows up as parameters that do not approach those values.
import tensorflow as tf
tf.random.set_seed(0)
x = tf.linspace(-2.0, 2.0, 201)
noise = tf.random.normal(shape=[201], stddev=0.3)
y = 3.0 * x + 2.0 + noise
Step 1: a model made of variables
class LinearModel(tf.Module):
def __init__(self, name=None):
super().__init__(name=name)
self.w = tf.Variable(5.0, name="w") # deliberately far from 3
self.b = tf.Variable(0.0, name="b")
def __call__(self, x):
return self.w * x + self.b
model = LinearModel()
print(model.variables) # (b, w) variables
Subclassing tf.Module buys tracking: model.variables and model.trainable_variables are available with no bookkeeping. Plain Python scalars would not train, because gradients flow only to variables (and to tensors explicitly watched).
Step 2: a loss
def mse(target, pred):
return tf.reduce_mean(tf.square(target - pred))
The mean squared error is a scalar, which is what GradientTape.gradient expects as its target by default. If you return a vector, TensorFlow sums it, which silently changes the effective loss. Other losses and their reduction options are on Losses, with the theory in Information Theory and Losses.
Step 3: one step by hand
def train_step(model, x, y, learning_rate):
with tf.GradientTape() as tape:
pred = model(x)
loss = mse(y, pred)
dw, db = tape.gradient(loss, [model.w, model.b])
model.w.assign_sub(learning_rate * dw)
model.b.assign_sub(learning_rate * db)
return loss
for epoch in range(10):
loss = train_step(model, x, y, learning_rate=0.1)
print(f"epoch {epoch}: loss={loss.numpy():.4f} w={model.w.numpy():.3f} b={model.b.numpy():.3f}")
# epoch 0: loss=9.3820 w=4.463 b=0.396
# epoch 1: loss=5.4698 w=4.070 b=0.713
# ...
# epoch 9: loss=0.1847 w=3.091 b=1.769
Reading it line by line:
-
The forward pass and the loss both run inside the tape context, which is when TensorFlow records operations on watched variables.
-
tape.gradient(loss, sources)returns one gradient per source, in the same structure. The tape is released after one call unless created withpersistent=True. -
assign_submutates the variable in place, implementing \( \theta \leftarrow \theta - \eta \nabla_\theta L \). Writingmodel.w = model.w - lr * dwwould instead rebind the attribute to a plain tensor and break training and saving. -
The printed loss is the value before the update of that step, so each line reports the pre-update loss.
If a gradient comes back as None, the variable did not take part in the computation under the tape (a cast to NumPy, a tf.stop_gradient, or a computation outside the with block). Fixing that is covered on the autodiff page.
Step 4: use an optimizer
Hand-written updates stop scaling at momentum, Adam and schedules. The optimizer classes keep their own state (moments, step counts) and apply updates in one call.
model = LinearModel()
opt = tf.keras.optimizers.SGD(learning_rate=0.1)
def train_step(model, x, y):
with tf.GradientTape() as tape:
loss = mse(y, model(x))
grads = tape.gradient(loss, model.trainable_variables)
opt.apply_gradients(zip(grads, model.trainable_variables))
return loss
for epoch in range(10):
loss = train_step(model, x, y)
opt.apply_gradients takes an iterable of gradient and variable pairs. In TensorFlow 2.21 tf.keras.optimizers resolves to the Keras 3 optimizers, which are the single implementation shared by all backends; the old tf.keras.optimizers.legacy namespace belongs to Keras 2 and is only reachable through the tf_keras package (see Keras 3 Overview). Catalogue and schedules: Optimizers and Learning-Rate Schedules.
Step 5: mini-batches with tf.data
Real datasets do not fit in one tensor and need shuffling. A tf.data.Dataset supplies batches and the loop iterates over it per epoch.
ds = (tf.data.Dataset.from_tensor_slices((x, y))
.shuffle(buffer_size=201, seed=0, reshuffle_each_iteration=True)
.batch(32)
.prefetch(tf.data.AUTOTUNE))
model = LinearModel()
opt = tf.keras.optimizers.SGD(learning_rate=0.05)
for epoch in range(20):
total, n = 0.0, 0
for xb, yb in ds:
loss = train_step(model, xb, yb)
total += float(loss) * xb.shape[0]
n += xb.shape[0]
print(epoch, total / n) # 0 5.37, 1 1.13, 2 0.31, ... levels off near 0.095 (the noise variance)
The epoch loss is a sample-weighted average, because the last batch is smaller (201 is not a multiple of 32). Averaging raw batch losses would over-weight it. Input pipeline details are on Input Pipelines with tf.data and speed tuning on tf.data Performance.
Step 6: compile the step with tf.function
Eager execution is easy to debug but pays Python overhead per operation. Wrapping the step in tf.function traces it into a graph once and reuses it.
@tf.function
def train_step(model, x, y):
with tf.GradientTape() as tape:
loss = mse(y, model(x))
grads = tape.gradient(loss, model.trainable_variables)
opt.apply_gradients(zip(grads, model.trainable_variables))
return loss
Rules that bite here:
-
Create the optimizer and the model’s variables before the first call, or on the first trace only. Variables created on a later trace raise an error. With Keras 3 optimizers you can call
opt.build(model.trainable_variables)ahead of time. -
The last batch has a different static shape, which triggers a second trace. Use
.batch(32, drop_remainder=True)for training, or declare aninput_signaturewith aNonebatch dimension. -
Passing a Python float as an argument bakes it into the trace and retraces when it changes. Pass a tensor or keep the value in an optimizer or
tf.Variable(for a learning rate schedule, use a schedule object). -
A Python
printinside the step runs at trace time only; usetf.print. -
Return tensors, and call
.numpy()outside the function.
Step 7: evaluation and metrics
Keep evaluation separate from training: no tape, no update, and any stochastic layers in inference mode. Metric objects accumulate across batches and are reset between epochs.
val_x = tf.linspace(-2.0, 2.0, 50)
val_y = 3.0 * val_x + 2.0
mae = tf.keras.metrics.MeanAbsoluteError()
mae.update_state(val_y, model(val_x))
print(mae.result().numpy()) # 0.016: near the noise-free error of the fit
mae.reset_state()
Source: https://keras.io/api/metrics/
Metrics are explained on Metrics. The usual evaluation rules (a held-out split, no tuning on the test set) are in Generalization and Regularization.
The same task with Keras fit
The Keras version is a handful of lines because fit implements Steps 3 to 7: batching, the tape, the optimizer call, compilation into a graph and metric tracking.
import keras
class KerasLinear(keras.Model):
def __init__(self):
super().__init__()
self.w = self.add_weight(shape=(), initializer=keras.initializers.Constant(5.0), name="w")
self.b = self.add_weight(shape=(), initializer="zeros", name="b")
def call(self, x):
return self.w * x + self.b
km = KerasLinear()
km.compile(optimizer=keras.optimizers.SGD(learning_rate=0.1), loss="mse")
km.fit(x, y, epochs=10, batch_size=201, verbose=2)
Source: https://www.tensorflow.org/guide/basic_training_loops and https://keras.io/api/models/model_training_apis/
A batch size equal to the dataset size mirrors the single-batch hand loop. Without it Keras defaults to a batch size of 32, so the loss curves differ for reasons that have nothing to do with correctness. With one batch per epoch, each epoch makes a single update and fit reports the loss computed before it, so the log (loss: 9.3820, 5.4698, 3.2312, …) matches the hand loop line for line. With several batches per epoch the reported value is the running average over the epoch’s updates instead. Details of compile and fit are on compile, fit, evaluate and predict.
When to leave fit
fit is the right default. Write the loop yourself when you need something it does not express: several optimizers (GANs), gradient accumulation, custom gradient clipping across models, per-step logic that depends on the previous step, or research code that mixes frameworks. Two intermediate options keep most of Keras: overriding train_step (the loop is still driven by fit, so callbacks and distribution still work) or writing the full loop against a Keras model, as on the pages linked in the introduction.
Loop checklist
| Concern | Rule |
|---|---|
Gradients |
compute under the tape; differentiate a scalar; check for |
Updates |
|
Batching |
|
Compilation |
|
Validation |
separate pass, no tape, metrics reset per epoch |
Saving |
|
Reproducibility |
set seeds, see the hardware and determinism notes in Performance, XLA and Profiling |
References
-
Basic training loops: https://www.tensorflow.org/guide/basic_training_loops
-
TensorFlow Core guides: https://www.tensorflow.org/guide/core
-
Introduction to gradients and automatic differentiation: https://www.tensorflow.org/guide/autodiff
-
Better performance with tf.function: https://www.tensorflow.org/guide/function
-
tf.data guide: https://www.tensorflow.org/guide/data
-
Keras optimizers API: https://keras.io/api/optimizers/
-
Keras model training APIs: https://keras.io/api/models/model_training_apis/