{"id":47529,"date":"2026-11-24T22:04:54","date_gmt":"2026-11-24T22:04:54","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=47529"},"modified":"2026-11-24T22:04:54","modified_gmt":"2026-11-24T22:04:54","slug":"tensorsflow-lab5-tensorsflow-gradienttape","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/tensorsflow-lab5-tensorsflow-gradienttape\/","title":{"rendered":"Tensorsflow Lab5 &#8211; Tensorsflow GradientTape"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><code>tf.GradientTape<\/code> is TensorFlow&#039;s automatic differentiation API. It records the operations you run inside a <code>with<\/code> 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 <code>None<\/code>, how persistent and nested tapes work, and how to use the tape in a real training loop.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/c10bcff02521c32537c86e9d47266d23.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How GradientTape works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In eager mode, TensorFlow runs each operation as soon as it is called. Nothing stores the computation unless you ask for it. A <code>tf.GradientTape<\/code> context records every operation that touches a *watched* value. When you call <code>tape.gradient(target, sources)<\/code>, TensorFlow walks the recorded operations backwards with the chain rule (reverse-mode autodiff) and returns one gradient for each source.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Watched automatically:<\/strong> any <code>tf.Variable<\/code> with <code>trainable=True<\/code> that is read inside the context.<\/li>\n\n\n<li><strong>Not watched by default:<\/strong> <code>tf.constant<\/code> values, plain tensors, and variables created with <code>trainable=False<\/code>.<\/li>\n\n\n<li><strong>Shape rule:<\/strong> the gradient for each source has the same shape as that source. That is why <code>dl_dw<\/code> above is <code>(4, 2)<\/code> like <code>w<\/code>, and <code>dl_db<\/code> is <code>(2,)<\/code> like <code>b<\/code>.<\/li>\n\n\n<li><strong>Lifetime:<\/strong> a default tape releases its resources after the first <code>gradient()<\/code> call.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Running the lab<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The notebook above needs only TensorFlow and Jupyter. The <code>numpy<\/code> and <code>matplotlib<\/code> 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.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">python3 -m venv tf-lab\nsource tf-lab\/bin\/activate\npip install --upgrade pip\npip install tensorflow jupyter\npython -c <span class=\"hljs-string\">\"import tensorflow as tf; print(tf.__version__)\"<\/span>\njupyter notebook<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Your random values for <code>w<\/code> and the <code>Dense<\/code> 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 <code>None<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Reading the results in the example above<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Cell<\/th><th>Result<\/th><th>Why<\/th><\/tr><\/thead><tbody><tr><td><code>y = x**2<\/code> with <code>x = 4.0<\/code><\/td><td><code>8.0<\/code><\/td><td>dy\/dx = 2x = 8.<\/td><\/tr><tr><td><code>loss = reduce_mean((x@w + b)**2)<\/code><\/td><td>Rows of <code>dl_dw<\/code> scale 1:2:3:4<\/td><td>dl\/dw = x\u1d40 \u00b7 y. The input row is <code>[10, 20, 30, 40]<\/code>, so each row of the gradient is that input value times the same vector. <code>dl_db<\/code> equals <code>y<\/code> itself.<\/td><\/tr><tr><td><code>Dense(2, activation=&#039;relu&#039;)<\/code><\/td><td>First column of the kernel gradient and first bias gradient are <code>0<\/code><\/td><td>The first unit&#039;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.<\/td><\/tr><tr><td><code>y = x1\u00b2 + x2\u00b2 + x3\u00b2 + x4\u00b2<\/code><\/td><td><code>[10.0, None, None, None]<\/code><\/td><td>Only <code>x1<\/code> is a trainable variable. <code>x2<\/code> is <code>trainable=False<\/code>, <code>x4<\/code> is a constant, and <code>x3<\/code> is a tensor computed <strong>before<\/strong> the tape opened, so there is no recorded path from <code>x3<\/code> back to <code>x1<\/code>.<\/td><\/tr><tr><td><code>tape.watch(x1)<\/code> on a constant<\/td><td><code>(10.0, 6.0)<\/code><\/td><td><code>watch()<\/code> makes the constant a source. <code>x2<\/code> is still watched automatically.<\/td><\/tr><tr><td><code>watch_accessed_variables=False<\/code><\/td><td><code>(10.0, None)<\/code><\/td><td>Automatic watching is turned off, so only the explicitly watched <code>x1<\/code> is tracked.<\/td><\/tr><tr><td><code>if x &gt; 0.0<\/code> branches<\/td><td>Gradient only for the branch taken<\/td><td>The tape records operations that actually ran, so Python control flow just works.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> In recent TensorFlow releases, which use Keras 3, the variable-name loop prints <code>kernel<\/code> and <code>bias<\/code> rather than <code>dense\/kernel:0<\/code> and <code>dense\/bias:0<\/code>. Use <code>var.path<\/code> if you need the layer-qualified name.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Persistent and nested tapes<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A default tape can answer only one <code>gradient()<\/code> call. A second call raises <code>RuntimeError: A non-persistent GradientTape can only be used to compute one set of gradients<\/code>. Pass <code>persistent=True<\/code> to make several calls on the same recording, then delete the tape to free its memory.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import tensorflow <span class=\"hljs-keyword\">as<\/span> tf\n\nx = tf.Variable(<span class=\"hljs-number\">3.0<\/span>)\n\nwith tf.GradientTape(persistent=<span class=\"hljs-keyword\">True<\/span>) <span class=\"hljs-keyword\">as<\/span> tape:\n    y = x ** <span class=\"hljs-number\">2<\/span>\n    z = y ** <span class=\"hljs-number\">2<\/span>          <span class=\"hljs-comment\"># z = x^4<\/span>\n\n<span class=\"hljs-keyword\">print<\/span>(tape.gradient(z, x).numpy())  <span class=\"hljs-comment\"># 4x^3 = 108.0<\/span>\n<span class=\"hljs-keyword\">print<\/span>(tape.gradient(y, x).numpy())  <span class=\"hljs-comment\"># 2x   = 6.0<\/span>\ndel tape                             <span class=\"hljs-comment\"># release recorded resources<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">x = tf.Variable(<span class=\"hljs-number\">3.0<\/span>)\n\nwith tf.GradientTape() <span class=\"hljs-keyword\">as<\/span> outer:\n    with tf.GradientTape() <span class=\"hljs-keyword\">as<\/span> inner:\n        y = x ** <span class=\"hljs-number\">3<\/span>\n    dy_dx = inner.gradient(y, x)      <span class=\"hljs-comment\"># 3x^2 = 27.0<\/span>\n\nd2y_dx2 = outer.gradient(dy_dx, x)    <span class=\"hljs-comment\"># 6x = 18.0<\/span>\n<span class=\"hljs-keyword\">print<\/span>(dy_dx.numpy(), d2y_dx2.numpy())<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Using GradientTape in a training loop<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This is the main reason the tape exists. The script below fits <code>y = 3x + 2<\/code> with manual gradient descent: run the forward pass under the tape, take gradients of the loss, then update the variables. <code>@tf.function<\/code> compiles the step into a graph for speed, and the tape works the same way inside it.<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">import tensorflow as tf\n\ntf.random.set_seed(42)\nX = tf.random.uniform((200, 1), -1.0, 1.0)\nY = 3.0 * X + 2.0 + tf.random.normal((200, 1), stddev=0.1)\n\nw = tf.Variable(tf.random.normal((1, 1)), name=\"w\")\nb = tf.Variable(tf.zeros((1,)), name=\"b\")\nlearning_rate = 0.1\n\n@tf.function\ndef train_step(x, y):\n    with tf.GradientTape() as tape:\n        y_pred = tf.matmul(x, w) + b\n        loss = tf.reduce_mean(tf.square(y - y_pred))\n    dw, db = tape.gradient(loss, &#91;w, b])   # called OUTSIDE the with block\n    w.assign_sub(learning_rate * dw)\n    b.assign_sub(learning_rate * db)\n    return loss\n\nfor epoch in range(200):\n    loss = train_step(X, Y)\n    if epoch % 50 == 0:\n        print(f\"epoch {epoch:3d}  loss {loss.numpy():.4f}\")\n\nprint(\"w =\", w.numpy().ravel(), \"b =\", b.numpy())<\/code><\/span><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The loss should fall towards the noise level, about 0.01, and the final values should come out close to <code>w = 3<\/code> and <code>b = 2<\/code>. With a Keras model, replace the manual updates with <code>grads = tape.gradient(loss, model.trainable_variables)<\/code> followed by <code>optimizer.apply_gradients(zip(grads, model.trainable_variables))<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Troubleshooting None gradients<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td>Source is a constant or tensor that was never watched<\/td><td>Call <code>tape.watch(t)<\/code> or make it a <code>tf.Variable<\/code>.<\/td><\/tr><tr><td>Variable created with <code>trainable=False<\/code><\/td><td>Set <code>trainable=True<\/code> or watch it explicitly.<\/td><\/tr><tr><td>Value computed before the tape opened (like <code>x3<\/code> above)<\/td><td>Move the computation inside the <code>with<\/code> block.<\/td><\/tr><tr><td>Target does not depend on the source at all<\/td><td>Check the math. To get zeros instead of <code>None<\/code>, pass <code>unconnected_gradients=tf.UnconnectedGradients.ZERO<\/code>.<\/td><\/tr><tr><td>Integer dtype source<\/td><td>Gradients need floating-point dtypes. Cast with <code>tf.cast(x, tf.float32)<\/code>.<\/td><\/tr><tr><td>Computation passed through NumPy (<code>.numpy()<\/code>, <code>np.*<\/code>)<\/td><td>Use TensorFlow ops only. NumPy calls are invisible to the tape.<\/td><\/tr><tr><td>Non-differentiable ops such as <code>tf.argmax<\/code>, <code>tf.round<\/code> or casting to int<\/td><td>Use a differentiable substitute, for example softmax instead of argmax.<\/td><\/tr><tr><td>Variable replaced with <code>x = x + 1<\/code> instead of <code>x.assign_add(1)<\/code><\/td><td>The name now points to a tensor, not the variable. Use <code>assign*<\/code> methods.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Check each gradient before you apply it. A silent <code>None<\/code> is the most common cause of a model that never learns. A quick <code>assert all(g is not None for g in grads)<\/code> during development catches it early.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Corrections to the original lab<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The title misspells the framework as &quot;Tensorsflow&quot;. The correct name is <strong>TensorFlow<\/strong>.<\/li>\n\n\n<li>The last cell calls <code>tape.gradient()<\/code> <strong>inside<\/strong> the <code>with<\/code> block. 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. Call <code>gradient()<\/code> after the block ends, as in the training loop above. The same cell names the result <code>dy_dx<\/code> even though it computes dz\/dx. It returns <code>None<\/code> because <code>z = y*y<\/code> never uses <code>x<\/code>.<\/li>\n\n\n<li>Several cells use <code>persistent=True<\/code> but call <code>gradient()<\/code> only once. A default tape is enough there. When you do need a persistent tape, <code>del tape<\/code> afterwards.<\/li>\n\n\n<li>In the conditional cells, <code>tape.watch(x)<\/code> is unnecessary because <code>x<\/code> is never a gradient source. It only controls which branch runs.<\/li>\n\n\n<li>The note &quot;Gradients are not calculated on Tensors&quot; is imprecise. Tensors are simply not watched by default, and <code>tape.watch()<\/code> enables gradients for them, as the next cell shows. <code>x3<\/code> gets <code>None<\/code> mainly because it was computed outside the tape.<\/li>\n\n\n<li>The <code>numpy<\/code> and <code>matplotlib<\/code> imports are unused, and the Python 3.7 kernel is not supported by current TensorFlow.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Why does tape.gradient return None in TensorFlow?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">When should I use persistent=True with GradientTape?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use it when you need more than one <code>gradient()<\/code> or <code>jacobian()<\/code> call on the same forward pass, such as gradients of two different losses. Delete the tape afterwards with <code>del tape<\/code>, because a persistent tape holds its resources until it is garbage collected.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between tape.watch and tf.Variable?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Trainable <code>tf.Variable<\/code> objects are watched automatically when they are read inside the tape. <code>tape.watch()<\/code> adds tracking for plain tensors or constants, which is useful for input gradients such as saliency maps or adversarial examples.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does GradientTape work inside tf.function?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. The tape works in graph mode inside <code>@tf.function<\/code>, and that is the standard way to write fast custom training steps. Python <code>if<\/code> statements on tensors are converted to graph control flow by AutoGraph.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I compute a second derivative with GradientTape?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Nest two tapes. Compute the first gradient with the inner tape while still inside the outer tape&#039;s context, then call the outer tape&#039;s <code>gradient()<\/code> on that result.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/artificial-intelligence\/machine-learning\/\">More Machine Learning tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/lead-machine-learning-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/staff-mlops-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>tf.GradientTape is TensorFlow&#039;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&#8230;. <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[6512],"tags":[7380],"class_list":["post-47529","post","type-post","status-publish","format-standard","hentry","category-machine-learning","tag-tensorflow"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47529","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=47529"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47529\/revisions"}],"predecessor-version":[{"id":80203,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47529\/revisions\/80203"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=47529"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=47529"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=47529"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}