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 effects such as print 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.
What tf.function actually does
TensorFlow 2 runs eagerly by default: each op runs as soon as Python reaches it. Wrapping a function with @tf.function changes this. On the first call with a new kind of input, TensorFlow traces 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.
During tracing, AutoGraph rewrites Python control flow that depends on tensors into graph ops. An if on a tensor becomes tf.cond. A for over tf.range or a while on a tensor condition becomes tf.while_loop. This is why pos_neg_check and some_tanh_fn in the example above work without any changes.
| Aspect | Eager execution | tf.function (graph) |
|---|---|---|
| When ops run | Immediately, line by line | Graph built once per input signature, then executed |
| Python print() | Runs every call | Runs only while tracing |
| tf.print() | Runs every call | Runs every call (it is a graph op) |
| Debugging | Normal Python debugger works | Needs tf.print or run_functions_eagerly |
| Performance | Python overhead per op | Less overhead; graph optimizations apply |
| Export | Not directly serializable | Can be saved with tf.saved_model |
Running the lab
- Create a virtual environment and install TensorFlow:
python -m venv tf-env && source tf-env/bin/activate && pip install tensorflow jupyter. - 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.
- Open the notebook with
jupyter notebookand run the cells in order from a fresh kernel. Several cells changetf.Variablestate, so running a cell twice changes later results. - Use Kernel > Restart & Run All if your output stops matching the comments in the sections below.
import tensorflow as tf
print(tf.__version__)
print(tf.executing_eagerly()) # True: eager mode is the defaultCode language: PHP (php)
Note: The time, warnings and logging imports in the first cell are never used. They are harmless, and you can delete them.
Corrections to the notebook
Variables created inside a tf.function. The cell that calls fn_with_variable_init_autograph() has no output because it fails. That function creates tf.Variable(12.) on every call, and tf.function refuses this with ValueError: tf.function only supports singleton tf.Variables created on the first call. The fix is to create the variable once, outside the function:
b = tf.Variable(12.0)
@tf.function
def fn_with_variable_outside():
a = tf.constant([[10., 10.], [11., 1.]])
x = tf.constant([[1., 0.], [0., 1.]])
y = tf.matmul(a, x) + b
tf.print("tf_print:", y)
return y
fn_with_variable_outside()
# tf_print: [[22 22]
# [23 13]]
If a variable really has to be created lazily, for example inside a tf.Module or Keras layer, guard it so that it is created only once: if self.v is None: self.v = tf.Variable(...).
tf.Variable dtype argument. tf.Variable([[100.0], [100.0], [100.0]], tf.float32) passes tf.float32 as the second positional argument, and for tf.Variable that argument is trainable, not dtype. It works only because the values are already floats. Pass the dtype by keyword instead: tf.Variable([[100.0], [100.0], [100.0]], dtype=tf.float32). For tf.constant, the second positional argument really is dtype, so those cells are correct.
Stale outputs. Two recorded outputs come from cells that were run more than once:
add_times(5)withnum = tf.Variable(7)adds 5 five times. On a fresh kernelprint(num)showsnumpy=32, not 42.f(1, 2)witha = 1.0andb = 2.0setsa = 2 * 2 = 4and thenb = 2 + 1 * 4 = 6, so the first call returns10.0. The recorded30.0is the second call, after the first call had already seta = 4andb = 6.
Concrete function error. Calling concrete_float_square_fn with an int32 tensor still fails on current releases, but the exception type and message are different from the old InvalidArgumentError traceback. Newer versions raise a TypeError about the input not matching the function signature. The ConcreteFunction object also prints with a different module path.
Tracing and retracing in practice
A new trace is created for each distinct input signature. For tensors, the signature is the dtype and shape. For plain Python values, it is the value itself. This is the most common reason graph code runs slower than expected. You can count traces with experimental_get_tracing_count():
@tf.function
def double(x):
print("Tracing with", x)
return x * 2
double(tf.constant(1)) # traces (int32 scalar)
double(tf.constant(2)) # reuses the graph, no print
double(1) # traces: Python int 1 is baked in as a constant
double(2) # traces again for the value 2
print(double.experimental_get_tracing_count()) # 3Code language: PHP (php)
To fix the signature up front and prevent extra traces, pass an input_signature. A None dimension accepts any length:
@tf.function(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.float32)])
def scale(v):
return v * 2.0
scale(tf.constant([1.0, 2.0]))
scale(tf.constant([1.0, 2.0, 3.0]))
print(scale.experimental_get_tracing_count()) # 1
# scale(tf.constant([1, 2])) -> error: int32 does not match float32Code language: PHP (php)
Calling get_concrete_function(), as in the example above, returns the graph for one specific signature. Calling the generic square would retrace for an unseen dtype. A concrete function never retraces. It rejects any input that does not match, which is why the last concrete_float_square_fn call fails.
Note: If TensorFlow warns that several recent calls 'triggered tf.function retracing', look for Python numbers, changing tensor shapes or new Python objects passed as arguments. Convert scalars with tf.constant, or relax shapes with input_signature or reduce_retracing=True (named experimental_relax_shapes in older releases).
Debugging graph functions
Breakpoints and print do not behave normally inside a traced function. These three tools help:
# 1. Run every tf.function eagerly so pdb and print work normally
tf.config.run_functions_eagerly(True)
pos_neg_check(tf.constant([1, -5]))
tf.config.run_functions_eagerly(False) # turn it back off
# 2. See the Python code AutoGraph generated
print(tf.autograph.to_code(pos_neg_check.python_function))
# 3. Print tensor values at run time, on every call
@tf.function
def debug_me(x):
tf.print("x =", x, "sum =", tf.reduce_sum(x))
return x * 2Code language: PHP (php)
The output of tf.autograph.to_code shows the if in pos_neg_check 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.
Measuring whether tf.function helps
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:
import timeit
x = tf.random.uniform([100, 100])
def many_small_ops(x):
for _ in range(100):
x = tf.tanh(x) + 0.01
return x
graph_fn = tf.function(many_small_ops)
graph_fn(x) # warm-up call: pays the tracing cost once
print("eager:", timeit.timeit(lambda: many_small_ops(x), number=100))
print("graph:", timeit.timeit(lambda: graph_fn(x), number=100))Code language: PHP (php)
Here the Python for _ in range(100) loop is unrolled 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 tf.range so AutoGraph builds a single tf.while_loop instead.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
| ValueError: tf.function only supports singleton tf.Variables | A tf.Variable is created on every call | Create it outside the function or guard creation with an is None check |
| print() output appears only once | Python side effects run only during tracing | Use tf.print for run-time output |
| Python list holds symbolic Tensor('strided_slice:0') objects | list.append ran at trace time and stored graph tensors | Use tf.TensorArray and return .stack(), as in the notebook |
| Retracing warnings and slow calls | Python scalars or changing shapes in the arguments | Pass tensors, set input_signature, or use reduce_retracing=True |
| OperatorNotAllowedInGraphError: using a tf.Tensor as a Python bool | Tensor used in Python control flow that AutoGraph did not convert | Keep the condition inside the decorated function, or use tf.cond / tf.while_loop directly |
| Concrete function rejects input | Dtype or shape does not match the traced signature | Cast with tf.cast or get another concrete function for that signature |
Best practices
- Write and debug the function in eager mode first, then add
@tf.function. - Decorate the outer function, such as a training step. Nested calls, like
linearcallingaddandmatmulabove, are inlined into one graph, so the inner functions do not need their own decorators. - Pass tensors, not Python numbers, for values that change between calls.
- Keep state in
tf.Variableobjects created once, and change it withassign,assign_addorassign_sub. - Treat
tf.py_functionas an escape hatch. It runs arbitrary Python, blocks graph optimizations, and is not saved when you export a SavedModel. - Restart the kernel before trusting notebook results that depend on variable state.
Frequently asked questions
What is the difference between tf.function and eager execution?
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.
Why does print() inside a tf.function only run once?
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.
Does tf.function always make code faster?
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.
Can I create a tf.Variable inside a tf.function?
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.
How do I stop tf.function from retracing?
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.
Related tutorials
- More Machine Learning tutorials
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- Lead Machine Learning 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