MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Tensorsflow Lab4 – Tensorsflow function

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.

AspectEager executiontf.function (graph)
When ops runImmediately, line by lineGraph built once per input signature, then executed
Python print()Runs every callRuns only while tracing
tf.print()Runs every callRuns every call (it is a graph op)
DebuggingNormal Python debugger worksNeeds tf.print or run_functions_eagerly
PerformancePython overhead per opLess overhead; graph optimizations apply
ExportNot directly serializableCan be saved with tf.saved_model

Running the lab

  1. Create a virtual environment and install TensorFlow: python -m venv tf-env && source tf-env/bin/activate && pip install tensorflow jupyter.
  2. 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.
  3. Open the notebook with jupyter notebook and run the cells in order from a fresh kernel. Several cells change tf.Variable state, so running a cell twice changes later results.
  4. 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) with num = tf.Variable(7) adds 5 five times. On a fresh kernel print(num) shows numpy=32, not 42.
  • f(1, 2) with a = 1.0 and b = 2.0 sets a = 2 * 2 = 4 and then b = 2 + 1 * 4 = 6, so the first call returns 10.0. The recorded 30.0 is the second call, after the first call had already set a = 4 and b = 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

SymptomCauseFix
ValueError: tf.function only supports singleton tf.VariablesA tf.Variable is created on every callCreate it outside the function or guard creation with an is None check
print() output appears only oncePython side effects run only during tracingUse tf.print for run-time output
Python list holds symbolic Tensor('strided_slice:0') objectslist.append ran at trace time and stored graph tensorsUse tf.TensorArray and return .stack(), as in the notebook
Retracing warnings and slow callsPython scalars or changing shapes in the argumentsPass tensors, set input_signature, or use reduce_retracing=True
OperatorNotAllowedInGraphError: using a tf.Tensor as a Python boolTensor used in Python control flow that AutoGraph did not convertKeep the condition inside the decorated function, or use tf.cond / tf.while_loop directly
Concrete function rejects inputDtype or shape does not match the traced signatureCast 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 linear calling add and matmul above, 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.Variable objects created once, and change it with assign, assign_add or assign_sub.
  • Treat tf.py_function as 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Tensorsflow Lab8 – Tensorsflow FunctionalModel

This lab uses the UCI heart disease dataset (303 patients, 13 features, a binary target) to build a binary classifier with the Keras Functional API in TensorFlow….

Read More

Tensorsflow Lab7 – Tensorsflow SequentialModel

This lab uses the WHO life expectancy dataset to build a regression model with the TensorFlow Keras Sequential API. The notebook above covers loading the data, inspecting…

Read More

Tensorsflow Lab6 – Tensorsflow SimpleLinearRegression

This lab builds simple linear regression (y = Wx + b) from scratch in TensorFlow 2. It creates the weight and bias with tf.Variable, computes gradients of…

Read More

Tensorsflow Lab5 – Tensorsflow GradientTape

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….

Read More

Tensorsflow Lab3 – Tensorsflow EagerExecution

In eager execution, TensorFlow runs each operation as soon as Python calls it and gives you a concrete value back, with no graph to build first. It…

Read More

Tensorsflow Lab2 – Tensorsflow V1Sessions

This lab shows how TensorFlow 1.x style graphs and sessions still work in TensorFlow 2 through the tf.compat.v1 API. You will see why Session.run() fails while eager…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x