Most TensorFlow time sinks are not modelling problems. They are a training step that is mysteriously slow, a loss that turns into nan at step 8,000, or a result nobody can reproduce a week later. This tutorial covers the three we see most often on client projects, with the tools that find the cause quickly.
1. Silent retracing in tf.function
A tf.function is traced into a graph once per distinct input signature. If you keep passing Python scalars or tensors with changing shapes, TensorFlow retraces every call, and your "compiled" step runs slower than eager code.
import tensorflow as tf
@tf.function
def step(x, scale):
return tf.reduce_sum(x) * scale
for i in range(5):
step(tf.ones([i + 1]), i) # new shape AND new Python int each time
To see it, enable retracing logs:
tf.get_logger().setLevel("WARNING") # retracing warnings appear here
print(step.experimental_get_tracing_count())
Fixes, in order of preference:
- Pass tensors, not Python numbers:
step(x, tf.constant(i)). - Declare a signature with relaxed shapes:
@tf.function(input_signature=[tf.TensorSpec([None], tf.float32), tf.TensorSpec([], tf.float32)]). - Or use
reduce_retracing=Trueto let TensorFlow generalize shapes automatically. - In
tf.data, pad or bucket batches so shapes are stable, and usedrop_remainder=Truewhen a fixed batch size is acceptable.
A tracing count that grows with the number of steps is always a bug.
2. Finding the source of NaN losses
NaNs usually come from one of four places: a learning rate that is too high, log(0) or division by zero in a custom loss, bad values in the data, or overflow in float16.
Work through them cheaply:
- Check the data first. Run a pass over the dataset with
tf.debugging.check_numericsor simplytf.reduce_any(tf.math.is_nan(x)). One corrupt record is a common culprit. - Turn on numeric checks to fail at the first offending op rather than 5,000 steps later:
tf.debugging.enable_check_numerics()
This is slow, so use it on a short reproduction run only. The error names the op that produced the first inf or nan.
- Debug eagerly. Call
tf.config.run_functions_eagerly(True)so you can use ordinary Python breakpoints and prints inside the step. Turn it off afterward. - Make losses safe. Clamp inputs to logs (
tf.math.log(tf.maximum(p, 1e-7))), preferfrom_logits=Truein cross-entropy losses, and addclipnormorglobal_clipnormto the optimizer to contain exploding gradients. - Mixed precision. If you train with
mixed_float16, make sure loss scaling is active (Keras handles it with its standard optimizers) or switch tobfloat16where the hardware supports it.
3. Making runs reproducible
Full bit-for-bit reproducibility across different hardware is not realistic, but same-machine, same-software repeatability is achievable and is worth having for regression testing.
import keras, tensorflow as tf
keras.utils.set_random_seed(42) # seeds Python, NumPy and the backend
tf.config.experimental.enable_op_determinism()
Notes that save time:
enable_op_determinism()makes ops deterministic or raises an error if one has no deterministic implementation. It can reduce performance, so use it for debugging and CI rather than for every production training run.- Seed your
tf.datashuffles explicitly (shuffle(buffer, seed=42)), and be careful with parallelmapcalls that use randomness; with determinism enabled, TensorFlow forces deterministic ordering intf.dataoptions. - Record the library versions (
pip freeze), the seed, the git commit and the dataset version alongside every run. A seed alone is not a reproducible experiment. - When comparing two runs, compare metrics over several seeds. A difference smaller than the seed-to-seed spread is noise.
A short checklist
- Is the tracing count stable after the first few steps?
- Does a numerics check on one batch pass?
- Can you rerun with the same seed and get the same loss curve for the first 100 steps?
If all three are yes, you have removed the most common sources of wasted debugging time. If your team is stuck on a stubborn performance or stability problem in a TensorFlow system, our consultants can help; see our contact page.