tf.GradientTape is TensorFlow's automatic differentiation API. It records the operations you run inside a with block, then plays them back in reverse to compute gradients for training. This lab covers how the tape decides what to watch, why some gradients come back as None, how persistent and nested tapes work, and how to use the tape in a real training loop.
How GradientTape works
In eager mode, TensorFlow runs each operation as soon as it is called. Nothing stores the computation unless you ask for it. A tf.GradientTape context records every operation that touches a *watched* value. When you call tape.gradient(target, sources), TensorFlow walks the recorded operations backwards with the chain rule (reverse-mode autodiff) and returns one gradient for each source.
- Watched automatically: any
tf.Variablewithtrainable=Truethat is read inside the context. - Not watched by default:
tf.constantvalues, plain tensors, and variables created withtrainable=False. - Shape rule: the gradient for each source has the same shape as that source. That is why
dl_dwabove is(4, 2)likew, anddl_dbis(2,)likeb. - Lifetime: a default tape releases its resources after the first
gradient()call.
Running the lab
The notebook above needs only TensorFlow and Jupyter. The numpy and matplotlib imports in its first cell are never used, so you can drop them. The original notebook kernel is Python 3.7, which current TensorFlow releases no longer support. Use a recent Python 3 version in a fresh virtual environment.
python3 -m venv tf-lab
source tf-lab/bin/activate
pip install --upgrade pip
pip install tensorflow jupyter
python -c "import tensorflow as tf; print(tf.__version__)"
jupyter notebookCode language: JavaScript (javascript)
Your random values for w and the Dense layer will differ from the outputs shown in the notebook, so the numbers will not match. The patterns will: the shapes, which entries are zero, and which gradients are None.
Reading the results in the example above
| Cell | Result | Why |
|---|---|---|
y = x**2 with x = 4.0 | 8.0 | dy/dx = 2x = 8. |
loss = reduce_mean((x@w + b)**2) | Rows of dl_dw scale 1:2:3:4 | dl/dw = xแต ยท y. The input row is [10, 20, 30, 40], so each row of the gradient is that input value times the same vector. dl_db equals y itself. |
Dense(2, activation='relu') | First column of the kernel gradient and first bias gradient are 0 | The first unit's pre-activation was negative, so ReLU output 0 and its gradient is 0. With a different random init, the other unit may be the dead one. |
y = x1ยฒ + x2ยฒ + x3ยฒ + x4ยฒ | [10.0, None, None, None] | Only x1 is a trainable variable. x2 is trainable=False, x4 is a constant, and x3 is a tensor computed before the tape opened, so there is no recorded path from x3 back to x1. |
tape.watch(x1) on a constant | (10.0, 6.0) | watch() makes the constant a source. x2 is still watched automatically. |
watch_accessed_variables=False | (10.0, None) | Automatic watching is turned off, so only the explicitly watched x1 is tracked. |
if x > 0.0 branches | Gradient only for the branch taken | The tape records operations that actually ran, so Python control flow just works. |
Note: In recent TensorFlow releases, which use Keras 3, the variable-name loop prints kernel and bias rather than dense/kernel:0 and dense/bias:0. Use var.path if you need the layer-qualified name.
Persistent and nested tapes
A default tape can answer only one gradient() call. A second call raises RuntimeError: A non-persistent GradientTape can only be used to compute one set of gradients. Pass persistent=True to make several calls on the same recording, then delete the tape to free its memory.
import tensorflow as tf
x = tf.Variable(3.0)
with tf.GradientTape(persistent=True) as tape:
y = x ** 2
z = y ** 2 # z = x^4
print(tape.gradient(z, x).numpy()) # 4x^3 = 108.0
print(tape.gradient(y, x).numpy()) # 2x = 6.0
del tape # release recorded resourcesCode language: PHP (php)
To get second derivatives, nest the tapes. The inner gradient is computed inside the outer tape, so the outer tape records it and can differentiate it again.
x = tf.Variable(3.0)
with tf.GradientTape() as outer:
with tf.GradientTape() as inner:
y = x ** 3
dy_dx = inner.gradient(y, x) # 3x^2 = 27.0
d2y_dx2 = outer.gradient(dy_dx, x) # 6x = 18.0
print(dy_dx.numpy(), d2y_dx2.numpy())Code language: PHP (php)
Using GradientTape in a training loop
This is the main reason the tape exists. The script below fits y = 3x + 2 with manual gradient descent: run the forward pass under the tape, take gradients of the loss, then update the variables. @tf.function compiles the step into a graph for speed, and the tape works the same way inside it.
import tensorflow as tf
tf.random.set_seed(42)
X = tf.random.uniform((200, 1), -1.0, 1.0)
Y = 3.0 * X + 2.0 + tf.random.normal((200, 1), stddev=0.1)
w = tf.Variable(tf.random.normal((1, 1)), name="w")
b = tf.Variable(tf.zeros((1,)), name="b")
learning_rate = 0.1
@tf.function
def train_step(x, y):
with tf.GradientTape() as tape:
y_pred = tf.matmul(x, w) + b
loss = tf.reduce_mean(tf.square(y - y_pred))
dw, db = tape.gradient(loss, [w, b]) # called OUTSIDE the with block
w.assign_sub(learning_rate * dw)
b.assign_sub(learning_rate * db)
return loss
for epoch in range(200):
loss = train_step(X, Y)
if epoch % 50 == 0:
print(f"epoch {epoch:3d} loss {loss.numpy():.4f}")
print("w =", w.numpy().ravel(), "b =", b.numpy())
The loss should fall towards the noise level, about 0.01, and the final values should come out close to w = 3 and b = 2. With a Keras model, replace the manual updates with grads = tape.gradient(loss, model.trainable_variables) followed by optimizer.apply_gradients(zip(grads, model.trainable_variables)).
Troubleshooting None gradients
| Cause | Fix |
|---|---|
| Source is a constant or tensor that was never watched | Call tape.watch(t) or make it a tf.Variable. |
Variable created with trainable=False | Set trainable=True or watch it explicitly. |
Value computed before the tape opened (like x3 above) | Move the computation inside the with block. |
| Target does not depend on the source at all | Check the math. To get zeros instead of None, pass unconnected_gradients=tf.UnconnectedGradients.ZERO. |
| Integer dtype source | Gradients need floating-point dtypes. Cast with tf.cast(x, tf.float32). |
Computation passed through NumPy (.numpy(), np.*) | Use TensorFlow ops only. NumPy calls are invisible to the tape. |
Non-differentiable ops such as tf.argmax, tf.round or casting to int | Use a differentiable substitute, for example softmax instead of argmax. |
Variable replaced with x = x + 1 instead of x.assign_add(1) | The name now points to a tensor, not the variable. Use assign* methods. |
Note: Check each gradient before you apply it. A silent None is the most common cause of a model that never learns. A quick assert all(g is not None for g in grads) during development catches it early.
Corrections to the original lab
- The title misspells the framework as "Tensorsflow". The correct name is TensorFlow.
- The last cell calls
tape.gradient()inside thewithblock. That still works, but the tape records the gradient computation itself, which wastes memory. TensorFlow also warns when this is done on a persistent tape. Callgradient()after the block ends, as in the training loop above. The same cell names the resultdy_dxeven though it computes dz/dx. It returnsNonebecausez = y*ynever usesx. - Several cells use
persistent=Truebut callgradient()only once. A default tape is enough there. When you do need a persistent tape,del tapeafterwards. - In the conditional cells,
tape.watch(x)is unnecessary becausexis never a gradient source. It only controls which branch runs. - The note "Gradients are not calculated on Tensors" is imprecise. Tensors are simply not watched by default, and
tape.watch()enables gradients for them, as the next cell shows.x3getsNonemainly because it was computed outside the tape. - The
numpyandmatplotlibimports are unused, and the Python 3.7 kernel is not supported by current TensorFlow.
Frequently asked questions
Why does tape.gradient return None in TensorFlow?
The tape found no recorded path from the target to that source. Usually the source was not watched (a constant or non-trainable variable), was computed outside the tape, went through NumPy, or does not affect the target.
When should I use persistent=True with GradientTape?
Use it when you need more than one gradient() or jacobian() call on the same forward pass, such as gradients of two different losses. Delete the tape afterwards with del tape, because a persistent tape holds its resources until it is garbage collected.
What is the difference between tape.watch and tf.Variable?
Trainable tf.Variable objects are watched automatically when they are read inside the tape. tape.watch() adds tracking for plain tensors or constants, which is useful for input gradients such as saliency maps or adversarial examples.
Does GradientTape work inside tf.function?
Yes. The tape works in graph mode inside @tf.function, and that is the standard way to write fast custom training steps. Python if statements on tensors are converted to graph control flow by AutoGraph.
How do I compute a second derivative with GradientTape?
Nest two tapes. Compute the first gradient with the inner tape while still inside the outer tape's context, then call the outer tape's gradient() on that result.
Related tutorials
- More Machine Learning tutorials
- Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals