{"id":47527,"date":"2026-11-24T22:04:53","date_gmt":"2026-11-24T22:04:53","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=47527"},"modified":"2026-11-24T22:04:53","modified_gmt":"2026-11-24T22:04:53","slug":"tensorsflow-lab4-tensorsflow-function","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/tensorsflow-lab4-tensorsflow-function\/","title":{"rendered":"Tensorsflow Lab4 &#8211; Tensorsflow function"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This lab shows how <code>tf.function<\/code> turns ordinary Python functions into TensorFlow graphs. It covers how AutoGraph converts <code>if<\/code>, <code>for<\/code> and <code>while<\/code> into graph ops, why Python side effects such as <code>print<\/code> run only during tracing, and how concrete functions are tied to specific input types. Below the notebook you will find what happens under the hood, fixes for the cells that fail or show stale results, and practical rules for tracing, debugging and benchmarking.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/adac512ba8350b9b56bcec1216bb1124.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What tf.function actually does<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">TensorFlow 2 runs eagerly by default: each op runs as soon as Python reaches it. Wrapping a function with <code>@tf.function<\/code> changes this. On the first call with a new kind of input, TensorFlow <strong>traces<\/strong> the function. It runs the Python code once with symbolic tensors and records every TensorFlow op into a graph. Later calls with compatible inputs skip Python and run the stored graph directly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">During tracing, <strong>AutoGraph<\/strong> rewrites Python control flow that depends on tensors into graph ops. An <code>if<\/code> on a tensor becomes <code>tf.cond<\/code>. A <code>for<\/code> over <code>tf.range<\/code> or a <code>while<\/code> on a tensor condition becomes <code>tf.while_loop<\/code>. This is why <code>pos_neg_check<\/code> and <code>some_tanh_fn<\/code> in the example above work without any changes.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Aspect<\/th><th>Eager execution<\/th><th>tf.function (graph)<\/th><\/tr><\/thead><tbody><tr><td>When ops run<\/td><td>Immediately, line by line<\/td><td>Graph built once per input signature, then executed<\/td><\/tr><tr><td>Python print()<\/td><td>Runs every call<\/td><td>Runs only while tracing<\/td><\/tr><tr><td>tf.print()<\/td><td>Runs every call<\/td><td>Runs every call (it is a graph op)<\/td><\/tr><tr><td>Debugging<\/td><td>Normal Python debugger works<\/td><td>Needs tf.print or run_functions_eagerly<\/td><\/tr><tr><td>Performance<\/td><td>Python overhead per op<\/td><td>Less overhead; graph optimizations apply<\/td><\/tr><tr><td>Export<\/td><td>Not directly serializable<\/td><td>Can be saved with tf.saved_model<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Running the lab<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Create a virtual environment and install TensorFlow: <code>python -m venv tf-env &amp;&amp; source tf-env\/bin\/activate &amp;&amp; pip install tensorflow jupyter<\/code>.<\/li>\n\n\n<li>Check the installation with the snippet below. The notebook was recorded on an older TensorFlow 2.x release, so some object representations and error messages will look different on current versions.<\/li>\n\n\n<li>Open the notebook with <code>jupyter notebook<\/code> and run the cells <strong>in order from a fresh kernel<\/strong>. Several cells change <code>tf.Variable<\/code> state, so running a cell twice changes later results.<\/li>\n\n\n<li>Use <strong>Kernel &gt; Restart &amp; Run All<\/strong> if your output stops matching the comments in the sections below.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" 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<span class=\"hljs-keyword\">print<\/span>(tf.__version__)\n<span class=\"hljs-keyword\">print<\/span>(tf.executing_eagerly())   <span class=\"hljs-comment\"># True: eager mode is the default<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><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\"><strong>Note:<\/strong> The <code>time<\/code>, <code>warnings<\/code> and <code>logging<\/code> imports in the first cell are never used. They are harmless, and you can delete them.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Corrections to the notebook<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Variables created inside a tf.function.<\/strong> The cell that calls <code>fn_with_variable_init_autograph()<\/code> has no output because it fails. That function creates <code>tf.Variable(12.)<\/code> on every call, and <code>tf.function<\/code> refuses this with <code>ValueError: tf.function only supports singleton tf.Variables created on the first call<\/code>. The fix is to create the variable once, outside the function:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">b = tf.Variable(12.0)\n\n@tf.function\ndef fn_with_variable_outside():\n    a = tf.constant(&#91;&#91;10., 10.], &#91;11., 1.]])\n    x = tf.constant(&#91;&#91;1., 0.], &#91;0., 1.]])\n    y = tf.matmul(a, x) + b\n    tf.print(\"tf_print:\", y)\n    return y\n\nfn_with_variable_outside()\n# tf_print: &#91;&#91;22 22]\n#  &#91;23 13]]<\/code><\/span><\/pre>\n\n\n<p class=\"wp-block-paragraph\">If a variable really has to be created lazily, for example inside a <code>tf.Module<\/code> or Keras layer, guard it so that it is created only once: <code>if self.v is None: self.v = tf.Variable(...)<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>tf.Variable dtype argument.<\/strong> <code>tf.Variable([[100.0], [100.0], [100.0]], tf.float32)<\/code> passes <code>tf.float32<\/code> as the second positional argument, and for <code>tf.Variable<\/code> that argument is <code>trainable<\/code>, not <code>dtype<\/code>. It works only because the values are already floats. Pass the dtype by keyword instead: <code>tf.Variable([[100.0], [100.0], [100.0]], dtype=tf.float32)<\/code>. For <code>tf.constant<\/code>, the second positional argument really is <code>dtype<\/code>, so those cells are correct.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Stale outputs.<\/strong> Two recorded outputs come from cells that were run more than once:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>add_times(5)<\/code> with <code>num = tf.Variable(7)<\/code> adds 5 five times. On a fresh kernel <code>print(num)<\/code> shows <code>numpy=32<\/code>, not 42.<\/li>\n\n\n<li><code>f(1, 2)<\/code> with <code>a = 1.0<\/code> and <code>b = 2.0<\/code> sets <code>a = 2 * 2 = 4<\/code> and then <code>b = 2 + 1 * 4 = 6<\/code>, so the first call returns <code>10.0<\/code>. The recorded <code>30.0<\/code> is the second call, after the first call had already set <code>a = 4<\/code> and <code>b = 6<\/code>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Concrete function error.<\/strong> Calling <code>concrete_float_square_fn<\/code> with an <code>int32<\/code> tensor still fails on current releases, but the exception type and message are different from the old <code>InvalidArgumentError<\/code> traceback. Newer versions raise a <code>TypeError<\/code> about the input not matching the function signature. The <code>ConcreteFunction<\/code> object also prints with a different module path.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Tracing and retracing in practice<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A new trace is created for each distinct <strong>input signature<\/strong>. For tensors, the signature is the dtype and shape. For plain Python values, it is the <strong>value itself<\/strong>. This is the most common reason graph code runs slower than expected. You can count traces with <code>experimental_get_tracing_count()<\/code>:<\/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\">@tf<span class=\"hljs-function\">.<span class=\"hljs-keyword\">function<\/span>\n<span class=\"hljs-title\">def<\/span> <span class=\"hljs-title\">double<\/span><span class=\"hljs-params\">(x)<\/span>:\n    <span class=\"hljs-title\">print<\/span><span class=\"hljs-params\">(<span class=\"hljs-string\">\"Tracing with\"<\/span>, x)<\/span>\n    <span class=\"hljs-title\">return<\/span> <span class=\"hljs-title\">x<\/span> * 2\n\n<span class=\"hljs-title\">double<\/span><span class=\"hljs-params\">(tf.constant<span class=\"hljs-params\">(<span class=\"hljs-number\">1<\/span>)<\/span>)<\/span>   # <span class=\"hljs-title\">traces<\/span> <span class=\"hljs-params\">(int32 scalar)<\/span>\n<span class=\"hljs-title\">double<\/span><span class=\"hljs-params\">(tf.constant<span class=\"hljs-params\">(<span class=\"hljs-number\">2<\/span>)<\/span>)<\/span>   # <span class=\"hljs-title\">reuses<\/span> <span class=\"hljs-title\">the<\/span> <span class=\"hljs-title\">graph<\/span>, <span class=\"hljs-title\">no<\/span> <span class=\"hljs-title\">print<\/span>\n<span class=\"hljs-title\">double<\/span><span class=\"hljs-params\">(<span class=\"hljs-number\">1<\/span>)<\/span>                # <span class=\"hljs-title\">traces<\/span>: <span class=\"hljs-title\">Python<\/span> <span class=\"hljs-title\">int<\/span> 1 <span class=\"hljs-title\">is<\/span> <span class=\"hljs-title\">baked<\/span> <span class=\"hljs-title\">in<\/span> <span class=\"hljs-title\">as<\/span> <span class=\"hljs-title\">a<\/span> <span class=\"hljs-title\">constant<\/span>\n<span class=\"hljs-title\">double<\/span><span class=\"hljs-params\">(<span class=\"hljs-number\">2<\/span>)<\/span>                # <span class=\"hljs-title\">traces<\/span> <span class=\"hljs-title\">again<\/span> <span class=\"hljs-title\">for<\/span> <span class=\"hljs-title\">the<\/span> <span class=\"hljs-title\">value<\/span> 2\n\n<span class=\"hljs-title\">print<\/span><span class=\"hljs-params\">(double.experimental_get_tracing_count<span class=\"hljs-params\">()<\/span>)<\/span>   # 3<\/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 fix the signature up front and prevent extra traces, pass an <code>input_signature<\/code>. A <code>None<\/code> dimension accepts any length:<\/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\">@tf<span class=\"hljs-function\">.<span class=\"hljs-keyword\">function<\/span><span class=\"hljs-params\">(input_signature=&#91;tf.TensorSpec<span class=\"hljs-params\">(shape=&#91;None], dtype=tf.float32)<\/span>])<\/span>\n<span class=\"hljs-title\">def<\/span> <span class=\"hljs-title\">scale<\/span><span class=\"hljs-params\">(v)<\/span>:\n    <span class=\"hljs-title\">return<\/span> <span class=\"hljs-title\">v<\/span> * 2.0\n\n<span class=\"hljs-title\">scale<\/span><span class=\"hljs-params\">(tf.constant<span class=\"hljs-params\">(&#91;<span class=\"hljs-number\">1.0<\/span>, <span class=\"hljs-number\">2.0<\/span>])<\/span>)<\/span>\n<span class=\"hljs-title\">scale<\/span><span class=\"hljs-params\">(tf.constant<span class=\"hljs-params\">(&#91;<span class=\"hljs-number\">1.0<\/span>, <span class=\"hljs-number\">2.0<\/span>, <span class=\"hljs-number\">3.0<\/span>])<\/span>)<\/span>\n<span class=\"hljs-title\">print<\/span><span class=\"hljs-params\">(scale.experimental_get_tracing_count<span class=\"hljs-params\">()<\/span>)<\/span>   # 1\n\n# <span class=\"hljs-title\">scale<\/span><span class=\"hljs-params\">(tf.constant<span class=\"hljs-params\">(&#91;<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">2<\/span>])<\/span>)<\/span>  -&gt; <span class=\"hljs-title\">error<\/span>: <span class=\"hljs-title\">int32<\/span> <span class=\"hljs-title\">does<\/span> <span class=\"hljs-title\">not<\/span> <span class=\"hljs-title\">match<\/span> <span class=\"hljs-title\">float32<\/span><\/span><\/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<p class=\"wp-block-paragraph\">Calling <code>get_concrete_function()<\/code>, as in the example above, returns the graph for one specific signature. Calling the generic <code>square<\/code> would retrace for an unseen dtype. A concrete function never retraces. It rejects any input that does not match, which is why the last <code>concrete_float_square_fn<\/code> call fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> If TensorFlow warns that several recent calls &#039;triggered tf.function retracing&#039;, look for Python numbers, changing tensor shapes or new Python objects passed as arguments. Convert scalars with <code>tf.constant<\/code>, or relax shapes with <code>input_signature<\/code> or <code>reduce_retracing=True<\/code> (named <code>experimental_relax_shapes<\/code> in older releases).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Debugging graph functions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Breakpoints and <code>print<\/code> do not behave normally inside a traced function. These three tools help:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\"># 1. Run every tf.function eagerly so pdb and print work normally<\/span>\ntf.config.run_functions_eagerly(<span class=\"hljs-keyword\">True<\/span>)\npos_neg_check(tf.constant(&#91;<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">-5<\/span>]))\ntf.config.run_functions_eagerly(<span class=\"hljs-keyword\">False<\/span>)   <span class=\"hljs-comment\"># turn it back off<\/span>\n\n<span class=\"hljs-comment\"># 2. See the Python code AutoGraph generated<\/span>\n<span class=\"hljs-keyword\">print<\/span>(tf.autograph.to_code(pos_neg_check.python_function))\n\n<span class=\"hljs-comment\"># 3. Print tensor values at run time, on every call<\/span>\n@tf<span class=\"hljs-function\">.<span class=\"hljs-keyword\">function<\/span>\n<span class=\"hljs-title\">def<\/span> <span class=\"hljs-title\">debug_me<\/span><span class=\"hljs-params\">(x)<\/span>:\n    <span class=\"hljs-title\">tf<\/span>.<span class=\"hljs-title\">print<\/span><span class=\"hljs-params\">(<span class=\"hljs-string\">\"x =\"<\/span>, x, <span class=\"hljs-string\">\"sum =\"<\/span>, tf.reduce_sum<span class=\"hljs-params\">(x)<\/span>)<\/span>\n    <span class=\"hljs-title\">return<\/span> <span class=\"hljs-title\">x<\/span> * 2<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><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\">The output of <code>tf.autograph.to_code<\/code> shows the <code>if<\/code> in <code>pos_neg_check<\/code> rewritten into a call to an AutoGraph conditional helper. That makes it clear which code runs at trace time and which becomes part of the graph.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Measuring whether tf.function helps<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">As the notebook notes, the speedup is largest for functions made of many small ops and smallest for a few large ops such as big convolutions or matrix multiplications. Measure on your own hardware, and exclude the first call, because it includes tracing time:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import timeit\n\nx = tf.random.uniform(&#91;<span class=\"hljs-number\">100<\/span>, <span class=\"hljs-number\">100<\/span>])\n\ndef many_small_ops(x):\n    <span class=\"hljs-keyword\">for<\/span> _ in range(<span class=\"hljs-number\">100<\/span>):\n        x = tf.tanh(x) + <span class=\"hljs-number\">0.01<\/span>\n    <span class=\"hljs-keyword\">return<\/span> x\n\ngraph_fn = tf<span class=\"hljs-function\">.<span class=\"hljs-keyword\">function<\/span><span class=\"hljs-params\">(many_small_ops)<\/span>\n<span class=\"hljs-title\">graph_fn<\/span><span class=\"hljs-params\">(x)<\/span>   # <span class=\"hljs-title\">warm<\/span>-<span class=\"hljs-title\">up<\/span> <span class=\"hljs-title\">call<\/span>: <span class=\"hljs-title\">pays<\/span> <span class=\"hljs-title\">the<\/span> <span class=\"hljs-title\">tracing<\/span> <span class=\"hljs-title\">cost<\/span> <span class=\"hljs-title\">once<\/span>\n\n<span class=\"hljs-title\">print<\/span><span class=\"hljs-params\">(<span class=\"hljs-string\">\"eager:\"<\/span>, timeit.timeit<span class=\"hljs-params\">(lambda: many_small_ops<span class=\"hljs-params\">(x)<\/span>, number=<span class=\"hljs-number\">100<\/span>)<\/span>)<\/span>\n<span class=\"hljs-title\">print<\/span><span class=\"hljs-params\">(<span class=\"hljs-string\">\"graph:\"<\/span>, timeit.timeit<span class=\"hljs-params\">(lambda: graph_fn<span class=\"hljs-params\">(x)<\/span>, number=<span class=\"hljs-number\">100<\/span>)<\/span>)<\/span><\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><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\">Here the Python <code>for _ in range(100)<\/code> loop is <strong>unrolled<\/strong> during tracing, so the graph contains 100 copies of the ops. Unrolling suits a small, fixed loop count. For long or data-dependent loops, use <code>tf.range<\/code> so AutoGraph builds a single <code>tf.while_loop<\/code> instead.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Symptom<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td>ValueError: tf.function only supports singleton tf.Variables<\/td><td>A tf.Variable is created on every call<\/td><td>Create it outside the function or guard creation with an <code>is None<\/code> check<\/td><\/tr><tr><td>print() output appears only once<\/td><td>Python side effects run only during tracing<\/td><td>Use <code>tf.print<\/code> for run-time output<\/td><\/tr><tr><td>Python list holds symbolic Tensor(&#039;strided_slice:0&#039;) objects<\/td><td><code>list.append<\/code> ran at trace time and stored graph tensors<\/td><td>Use <code>tf.TensorArray<\/code> and return <code>.stack()<\/code>, as in the notebook<\/td><\/tr><tr><td>Retracing warnings and slow calls<\/td><td>Python scalars or changing shapes in the arguments<\/td><td>Pass tensors, set <code>input_signature<\/code>, or use <code>reduce_retracing=True<\/code><\/td><\/tr><tr><td>OperatorNotAllowedInGraphError: using a tf.Tensor as a Python bool<\/td><td>Tensor used in Python control flow that AutoGraph did not convert<\/td><td>Keep the condition inside the decorated function, or use <code>tf.cond<\/code> \/ <code>tf.while_loop<\/code> directly<\/td><\/tr><tr><td>Concrete function rejects input<\/td><td>Dtype or shape does not match the traced signature<\/td><td>Cast with <code>tf.cast<\/code> or get another concrete function for that signature<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Best practices<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Write and debug the function in eager mode first, then add <code>@tf.function<\/code>.<\/li>\n\n\n<li>Decorate the outer function, such as a training step. Nested calls, like <code>linear<\/code> calling <code>add<\/code> and <code>matmul<\/code> above, are inlined into one graph, so the inner functions do not need their own decorators.<\/li>\n\n\n<li>Pass tensors, not Python numbers, for values that change between calls.<\/li>\n\n\n<li>Keep state in <code>tf.Variable<\/code> objects created once, and change it with <code>assign<\/code>, <code>assign_add<\/code> or <code>assign_sub<\/code>.<\/li>\n\n\n<li>Treat <code>tf.py_function<\/code> as an escape hatch. It runs arbitrary Python, blocks graph optimizations, and is not saved when you export a SavedModel.<\/li>\n\n\n<li>Restart the kernel before trusting notebook results that depend on variable state.<\/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\">What is the difference between tf.function and eager execution?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Eager execution runs each operation immediately in Python. tf.function traces the Python code once per input signature into a graph and then runs that graph on later calls, which cuts Python overhead and makes the function exportable.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why does print() inside a tf.function only run once?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">print() is a Python side effect, so it runs only while the function is being traced. Use tf.print() to print values on every call, because it is a graph op.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does tf.function always make code faster?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. It helps most with many small ops, where Python overhead dominates. Functions built from a few expensive ops, such as large convolutions, may show little difference, and frequent retracing can make code slower.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I create a tf.Variable inside a tf.function?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Only if it is created once, on the first call. Creating a new variable on every call raises a ValueError, so create variables outside the function or guard their creation inside a tf.Module or Keras layer.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I stop tf.function from retracing?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Pass tensors instead of Python scalars and keep dtypes consistent. You can also declare an input_signature with tf.TensorSpec, using None for variable dimensions, so a single graph handles every call.<\/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\/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\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<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>This lab shows how tf.function turns ordinary Python functions into TensorFlow graphs. It covers how AutoGraph converts if, for and while into graph ops, why Python side&#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-47527","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\/47527","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=47527"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47527\/revisions"}],"predecessor-version":[{"id":80202,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47527\/revisions\/80202"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=47527"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=47527"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=47527"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}