+1 (415) 366-1364

Debugging TensorFlow: tf.function Retracing, NaN Losses, and Reproducible Runs

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=True to let TensorFlow generalize shapes automatically.
  • In tf.data, pad or bucket batches so shapes are stable, and use drop_remainder=True when 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:

  1. Check the data first. Run a pass over the dataset with tf.debugging.check_numerics or simply tf.reduce_any(tf.math.is_nan(x)). One corrupt record is a common culprit.
  2. 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.

  1. 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.
  2. Make losses safe. Clamp inputs to logs (tf.math.log(tf.maximum(p, 1e-7))), prefer from_logits=True in cross-entropy losses, and add clipnorm or global_clipnorm to the optimizer to contain exploding gradients.
  3. Mixed precision. If you train with mixed_float16, make sure loss scaling is active (Keras handles it with its standard optimizers) or switch to bfloat16 where 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.data shuffles explicitly (shuffle(buffer, seed=42)), and be careful with parallel map calls that use randomness; with determinism enabled, TensorFlow forces deterministic ordering in tf.data options.
  • 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.