Custom Training Loops and Advanced Mechanics
8 min read
Welcome to the engine room. ๐ง
Up until now, you've likely been cruising in the comfort of model.fit(). Itโs like a self-driving car: you tell it where to go (epochs), give it fuel (data), and it drives you there. But what happens when you want to drift? Or drive off-road? Or build a car that drives sideways?
model.fit() is excellent for standard supervised learning. But in the industry, when you are building Generative Adversarial Networks (GANs), Reinforcement Learning agents, or models with complex, multi-modal loss functions, model.fit() forces you into a box you don't want to be in.
Today, we take the autopilot off. We are going to manually control the learning process, calculate our own gradients, and update weights by hand.
It sounds scary, but it's just a for loop. Seriously.
1. Eager Execution vs. Graph Mode
Before we write loops, we need to understand how TensorFlow runs your code.
๐ง The Concept
Eager Execution is an imperative programming environment that evaluates operations immediately, without building graphs. operations return concrete values instead of constructing a computational graph to run later.
Graph Execution involves building a symbolic graph of the computation first, optimizing it, and then executing it.
๐ง The Problem
In TensorFlow 1.x, you had to build a "Graph" (like writing a recipe), then open a "Session" to run it (cooking). It was fast but impossible to debug. If your code crashed, the error pointed to the graph engine, not your Python line.
- Problem: You can't use Python
ifstatements orprint()inside a graph easily to check values.
โ The Solution
TensorFlow 2.x defaults to Eager Execution. It runs like standard Python. You can inspect variables, use the debugger, and iterate quickly. However, for deployment, we still want the speed of Graph Mode. TensorFlow gives us the best of both worlds: Eager for dev, Graph for prod.
๐ป Industry Practice
You are in Eager mode by default. You don't need to do anything to enable it.
import tensorflow as tf
import time
# We are in Eager mode immediately
x = tf.constant([[1, 2], [3, 4]])
y = tf.add(x, 2)
# In Graph mode (TF 1.x), 'y' would be a Tensor placeholder.
# In Eager mode, 'y' actually holds the data right now.
print(f"Result:\n{y}")
# Result:
# [[3 4]
# [5 6]]2. Automatic Differentiation using tf.GradientTape
To train a neural network, we need to minimize a loss function. To minimize the loss, we need to change the weights. To know how to change the weights, we need the gradient (the slope) of the loss with respect to those weights.
Calculus is hard. Doing backpropagation by hand for a 100-layer network is impossible.
๐ง The Concept
Automatic Differentiation is a set of techniques to mathematically evaluate the derivative of a function specified by a computer program.
tf.GradientTape is the TensorFlow API that records operations for automatic differentiation.
๐ง The Problem
Manually deriving backpropagation formulas is error-prone and tedious. If you change one activation function, you have to re-calculate all the math from scratch.
โ The Solution
You wrap your computation inside a with tf.GradientTape() as tape: block. TensorFlow "watches" every variable involved in that block. When you exit the block, you ask the tape: "Hey, how much does y change if I wiggle x?"
๐งฎ How it works
Imagine a literal tape recorder. It records the forward pass (the math you do). Then, to get gradients, it plays the tape backward (reverse-mode differentiation).
# Create a variable (only Variables are watched by default, not constants)
x = tf.Variable(3.0)
with tf.GradientTape() as tape:
# Function: y = x^2
y = x ** 2
# Calculate gradient (dy/dx)
# The derivative of x^2 is 2x.
# If x=3, gradient should be 2*3 = 6.
dy_dx = tape.gradient(y, x)
print(f"The gradient of y=x^2 at x=3 is: {dy_dx.numpy()}")
# Output: 6.0๐ฅ Pro Tip: The tape expires after one use! If you need to calculate multiple gradients from the same computation (common in some advanced architectures), use
tf.GradientTape(persistent=True).
3. Writing a Custom Training Loop from Scratch
Now for the main event. We are going to replicate model.fit().
๐ง The Concept
A Training Loop consists of iterating over a dataset, performing a forward pass, calculating loss, calculating gradients, and applying those gradients to the model weights using an optimizer.
๐ง The Problem
model.fit() hides the state.
- What if you want to update weights only on even-numbered steps?
- What if you have two models (like a Generator and Discriminator) that fight each other?
- What if your loss depends on something other than the output?
โ The Solution
We write the loop explicitly using Python for loops and tf.GradientTape.
๐ The Setup (Boilerplate)
Let's prepare a simple MNIST model so we have something to train.
from tensorflow import keras
# 1. Prepare Data
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000, 784).astype("float32") / 255
dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
dataset = dataset.shuffle(buffer_size=1024).batch(64)
# 2. Define Model
model = keras.Sequential([
keras.layers.Dense(64, activation="relu", input_shape=(784,)),
keras.layers.Dense(64, activation="relu"),
keras.layers.Dense(10)
])
# 3. Define Optimizer and Loss Function
optimizer = keras.optimizers.Adam(learning_rate=1e-3)
loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True)
# Metric to track progress
train_acc_metric = keras.metrics.SparseCategoricalAccuracy()๐ The Manual Loop
Here is the anatomy of a single training step. This is what happens inside one batch of data.
def train_step(x, y):
# 1. Open the Tape
with tf.GradientTape() as tape:
# 2. Forward Pass: Run the model
logits = model(x, training=True)
# 3. Compute Loss: Compare prediction to actual label
loss_value = loss_fn(y, logits)
# 4. Calculate Gradients: "How do weights affect loss?"
grads = tape.gradient(loss_value, model.trainable_weights)
# 5. Apply Gradients: Update weights using the optimizer
optimizer.apply_gradients(zip(grads, model.trainable_weights))
# Track metrics
train_acc_metric.update_state(y, logits)
return loss_valueWait, training=True?
Yes! Some layers, like Dropout or BatchNormalization, behave differently during training vs. inference. You must explicitly tell the model which mode it's in.
๐ Putting it together
Now we wrap the step in a loop over epochs.
import time
epochs = 2
for epoch in range(epochs):
print(f"\nStart of epoch {epoch}")
start_time = time.time()
# Iterate over the batches of the dataset
for step, (x_batch_train, y_batch_train) in enumerate(dataset):
# Run the step
loss_value = train_step(x_batch_train, y_batch_train)
# Log every 200 batches
if step % 200 == 0:
print(f"Training loss (for one batch) at step {step}: {float(loss_value):.4f}")
print(f"Seen so far: {(step + 1) * 64} samples")
# Display metrics at the end of each epoch
train_acc = train_acc_metric.result()
print(f"Training acc over epoch: {float(train_acc):.4f}")
# Reset training metrics at the end of each epoch
train_acc_metric.reset_states()
print(f"Time taken: {time.time() - start_time:.2f}s")Congratulations! You just manually trained a Neural Network. ๐ฅณ
It feels like churning butter by hand, doesn't it? Hard work, but total control.
4. Optimizing Performance with the @tf.function Decorator
You might notice that the loop above runs a bit slower than model.fit().
Thatโs because we are running in Eager Execution. Every line of Python is interpreted, the C++ op is called, and results are returned to Python. The "Python-C++ ping-pong" overhead is real.
๐ง The Concept
@tf.function is a decorator that takes a regular Python function and compiles it into a TensorFlow Graph. It uses a system called AutoGraph to convert Python syntax (like while, if, for) into graph operations.
๐ง The Problem
Python is slow. GPU execution is fast. If the GPU has to wait for Python to tell it what to do next (bottleneck), you aren't getting your money's worth.
โ The Solution
We "compile" the training step. We trace it once, optimize it, and run the optimized C++ graph for all subsequent steps.
โก Applying the Boost
It is ridiculously easy to use. Just add the decorator to your training step.
@tf.function # <--- This is the magic line
def train_step_optimized(x, y):
with tf.GradientTape() as tape:
logits = model(x, training=True)
loss_value = loss_fn(y, logits)
grads = tape.gradient(loss_value, model.trainable_weights)
optimizer.apply_gradients(zip(grads, model.trainable_weights))
train_acc_metric.update_state(y, logits)
return loss_value๐ The "Gotcha" (Industry Standard Warning)
When you use @tf.function, Python code inside the function acts differently.
- Tracing: The first time you call the function, TF runs the Python code to build the graph.
- Execution: On subsequent calls, it skips the Python code and just runs the Graph.
Example of what goes wrong:
@tf.function
def buggy_function(x):
print("I am a Python print statement!")
tf.print("I am a TensorFlow print op!")
return x + 1
# Call 1: Tracing happens
buggy_function(1)
# Output:
# "I am a Python print statement!" (Python runs during trace)
# "I am a TensorFlow print op!" (Graph runs)
# Call 2: Execution only
buggy_function(2)
# Output:
# "I am a TensorFlow print op!"
# (The Python print is missing! Because the graph is already built and the Python function isn't re-read.)Lesson: Inside @tf.function, use tf.print() for debugging, not print(). Use tf.cond() for logic if standard if statements behave oddly (though AutoGraph handles simple ifs well).
Summary
- Eager Mode: Default, pythonic, easy to debug. Great for development.
- GradientTape: The recorder that enables backpropagation. It watches your math and calculates derivatives.
- Custom Loops: Iterate data ->
tapeforward pass ->tape.gradient->optimizer.apply_gradients. - @tf.function: The turbo button. Compiles your custom loop into a fast, portable graph.
You are now equipped to build models that don't fit in the standard box. Go forth and differentiate! ๐โก๏ธ๐
๐ References & Further Reading
- Official TF Guide on Custom Loops: Writing a training loop from scratch
- GradientTape Docs: tf.GradientTape API
- Performance with tf.function: Better performance with tf.function
- AutoGraph Details: Introduction to Graphs and tf.function
Challenge
Challenge: Implement a Custom TensorFlow Training Step
Your task is to implement a complete custom training step for a simple Keras model using TensorFlow. You will be provided with the boilerplate code for data loading, model definition, optimizer, and loss function. Your goal is to complete the train_step function.
Requirements:
- Decorate the
train_stepfunction with the appropriate decorator to compile it into a high-performance TensorFlow graph. - Inside the
train_stepfunction, implement the logic for a single training iteration. - Use a
tf.GradientTapecontext to record operations for automatic differentiation. - Perform a forward pass of the input
xthrough themodel. Ensure the model runs in training mode. - Calculate the loss between the true labels
yand the model's predictions using the providedloss_object. - Compute the gradients of the calculated loss with respect to the model's
trainable_variables. - Apply the computed gradients to update the model's weights using the provided
optimizer. - Return the calculated loss value from the function.
Expected result
Your solution should be a completed train_step function that correctly performs a single step of model training. The final function should look like this:
@tf.function
def train_step(x, y):
with tf.GradientTape() as tape:
predictions = model(x, training=True)
loss = loss_object(y, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
return lossKey points for a correct solution:
- The function must be decorated with
@tf.function. - It must use a
with tf.GradientTape() as tape:block. - The forward pass
model(x, training=True)and loss calculation must be inside thetapecontext. tape.gradient()must be called outside thewithblock to compute gradients.optimizer.apply_gradients()must be used to update the weights, taking a list of (gradient, variable) pairs.- The function must return the calculated
loss.