Performance, XLA & Profiling

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Training that feels slow is rarely slow for the reason you first suspect. The reliable method is to measure: find out whether the accelerator is waiting for input, executing many tiny kernels, or limited by arithmetic or memory, and only then change something. This page covers the TensorFlow Profiler (programmatic APIs, Keras callback, remote capture and the analysis tools), reading the input pipeline analyzer, XLA compilation through jit_compile, and a short checklist. The data-loading details are on tf.data Performance, graph behaviour on Graphs, tf.function, AutoGraph and Retracing, reduced precision on Mixed Precision, multi-device scaling on Distributed Training and visualisation on TensorBoard. The PyTorch equivalents are Profiling with torch.profiler and torch.compile; the general method is in Deep Learning Tuning Playbook.

It targets Python 3.13 and TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is "upcoming" and not covered), and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21, Keras 3.15 and TensorBoard 2.21 (CPU) on 2026-10-31. Snippets that use names such as model, train_ds, train_step and run_some_steps defined elsewhere were run with small synthetic stand-ins. GPU kernel statistics, Tensor Core eligibility and TPU or multi-worker profiling need that hardware and were not executed.

A measure-first workflow

flowchart TD A["Training is slow"] --> B["Capture a profile of about 10 steps after warm-up"] B --> C{"Input pipeline analyzer: device waiting for input?"} C -- yes --> D["Fix tf.data: prefetch, parallel map, cache, interleave"] C -- no --> E{"Many tiny ops or large host gaps?"} E -- yes --> F["tf.function, larger batch, jit_compile or XLA fusion"] E -- no --> G{"Compute or memory bound?"} G -- compute --> H["Mixed precision, Tensor Core friendly shapes"] G -- memory --> I["Smaller activations, mixed precision, checkpointing"] D --> B F --> B H --> B I --> B

Change one thing at a time and re-profile; warm-up steps (tracing, XLA compilation, autotuning) distort the first batches, so skip them.

Capturing a profile

The TensorFlow Profiler writes trace data into a TensorBoard log directory and is viewed in the Profile tab of TensorBoard (install the tensorboard-plugin-profile package, see TensorBoard). There are five ways to capture:

import tensorflow as tf
import keras

# 1. Keras callback: profile batches 10 to 15 of the first epoch
tb = keras.callbacks.TensorBoard(log_dir="logs/prof", profile_batch=(10, 15))
model.fit(train_ds, epochs=2, callbacks=[tb])

# 2. Programmatic start and stop
tf.profiler.experimental.start("logs/prof")
run_some_steps()
tf.profiler.experimental.stop()

# 3. Context manager
with tf.profiler.experimental.Profile("logs/prof"):
    run_some_steps()

# 4. Sampling mode: start a server in the training job, trigger from outside
tf.profiler.experimental.server.start(6009)
# elsewhere (or from the TensorBoard "Capture profile" button):
tf.profiler.experimental.client.trace("grpc://localhost:6009", "gs://my-bucket/logs", 2000)

Captures 1 to 3 write an xplane.pb file under logs/prof/plugins/profile/<timestamp>/ (the callback under logs/prof/train/plugins/profile/). Option 4 needs the profiler server to run inside a training process that is busy while the client traces; triggered from the same idle process, as in this snippet, client.trace raises RuntimeError: UNAVAILABLE: No trace event was collected. Option 4 is the one that works for remote machines, multiple workers (pass a comma-separated list of grpc:// addresses) and TPUs. Profile about 10 steps at a time and avoid the very first batches. When you start the profiler programmatically you can pass options=tf.profiler.experimental.ProfilerOptions(...). Its fields in TensorFlow 2.21 are host_tracer_level (default 2), python_tracer_level (default 0; set 1 to trace Python function calls), device_tracer_level (default 1) and delay_ms.

Marking steps in a custom loop

The profiler needs step boundaries to produce per-step statistics. Keras fit marks them automatically; in a custom loop wrap each step in tf.profiler.experimental.Trace.

import tensorflow as tf

iterator = iter(train_ds)
tf.profiler.experimental.start("logs/prof")
for step in range(20):
    with tf.profiler.experimental.Trace("train", step_num=step, _r=1):
        batch = next(iterator)        # fetch INSIDE the trace so input time is attributed
        train_step(batch)
tf.profiler.experimental.stop()

name is the step-name prefix, step_num is appended to it and _r=1 marks the event as a step event. Writing for step, batch in enumerate(dataset) outside the Trace block is an anti-pattern: the time spent fetching the next element is then missing from the step and the input-pipeline analysis is inaccurate.

The profiler tools

Tool What it tells you

Overview page

step time summary, device precision use, top device operations and recommendations

Input pipeline analyzer

whether the program is input bound and where input time goes

TensorFlow Stats

self and cumulative time per operation on host and device, with CSV export

Trace viewer

a timeline of operations on host and device, limited to 1 million events per device

GPU kernel stats

per-kernel statistics and the originating operation, including Tensor Core eligibility

Memory profile

memory use over time, peak, fragmentation and allocations by operation, for out-of-memory debugging

Pod viewer

per-step time breakdown across all workers

tf.data bottleneck analysis

an experimental analysis of the slowest tf.data stage

Reading the input pipeline analyzer

Open Profile, choose input_pipeline_analyzer in the Tools menu. It has three parts:

  1. Summary: the percentage of device time spent waiting for input from the host. A large figure means the program is input bound.

  2. Device-side analysis: a step-time graph in which red is device idle time waiting for input and green is active device work.

  3. Host-side analysis: input processing time split into reading files on demand (no caching, prefetching or interleaving), reading files in advance, preprocessing such as image decoding, and enqueuing data to the device. Expanding Input Op Statistics shows a per-operation table.

If most time is "reading data on demand", add prefetch, interleave and parallel reads; if it is preprocessing, add num_parallel_calls=tf.data.AUTOTUNE or move work offline; see tf.data Performance and Input Pipelines with tf.data.

Typical symptoms and the usual response:

  • Device idle between steps, big host gaps in the trace: input bound, or Python overhead in an eager loop. Wrap the step in tf.function and increase prefetching.

  • Thousands of very short kernels: fuse them with XLA (below) or restructure the model.

  • Kernels not eligible for Tensor Cores: use float16 or bfloat16 and dimensions that are multiples of 8, see Mixed Precision.

  • Memory profile near the device limit: shrink the batch, use mixed precision, or recompute activations.

A quick wall-clock benchmark for a dataset alone separates the input pipeline from the model:

import time
import tensorflow as tf

def benchmark(dataset, steps=200):
    it = iter(dataset.repeat())               # repeat so short datasets do not run out
    next(it)                                  # warm-up
    start = time.perf_counter()
    for _ in range(steps):
        next(it)
    elapsed = time.perf_counter() - start
    print(f"{steps / elapsed:.1f} batches/s")

benchmark(train_ds)

If the dataset alone cannot deliver more batches per second than the model consumes, the input pipeline is the bottleneck.

XLA and jit_compile

XLA (Accelerated Linear Algebra) is a compiler that turns a TensorFlow graph into fused, device-specific code. Fusing element-wise operations avoids writing intermediate tensors to memory, which often helps memory-bound models and models with many small operations. There are three ways to turn it on.

import tensorflow as tf
import keras

# 1. Per function: compile this tf.function with XLA
@tf.function(jit_compile=True)
def dense_step(x, w, b):
    return tf.nn.relu(tf.matmul(x, w) + b)

# 2. Per Keras model: compile the train/test/predict steps with XLA
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", jit_compile=True)
# jit_compile="auto" is the Keras 3 default; False disables compilation

# 3. Whole-process auto-clustering (no code change)
#    TF_XLA_FLAGS=--tf_xla_auto_jit=2 python train.py

Behavioural points:

  • With jit_compile=True the function must be fully compilable by XLA. Shapes must be known when tracing; ragged tensors, data-dependent output shapes and unsupported operations make compilation fail with an error instead of silently falling back.

  • XLA recompiles for each new input shape, so variable batch or sequence lengths cause repeated compilation. Pad to a few fixed sizes, or use drop_remainder=True when batching.

  • Compilation adds start-up time; XLA pays off for long runs. Always compare against the non-XLA run with the same profiler capture.

  • The auto-clustering flag --tf_xla_auto_jit=2 goes in the TF_XLA_FLAGS environment variable, and XLA debug options such as --xla_dump_to=<dir> (which writes the HLO and lowered code of every compiled cluster) go in XLA_FLAGS; both are described in the XLA documentation at openxla.org. TensorFlow 2.21 aborts at start-up on an unknown flag in TF_XLA_FLAGS. On the CPU, auto-clustering only compiles plain tf.function code when --tf_xla_cpu_global_jit is added to TF_XLA_FLAGS; functions with jit_compile=True are compiled either way.

  • In Keras 3 the default for compile(jit_compile=...) is "auto", which enables XLA when the active backend and model support it. On the JAX backend everything is compiled through XLA by default; see Keras Multi-Backend.

XLA is complementary to tf.function: tf.function removes Python overhead, XLA optimises the graph itself. The PyTorch compiler plays a similar role, see torch.compile.

A tuning checklist

  1. Run on a representative number of steps after warm-up and capture a profile before changing anything.

  2. Make sure the input pipeline overlaps with training: prefetch(tf.data.AUTOTUNE), parallel map, interleave for many files, and caching small datasets after decoding.

  3. Use tf.function (Keras fit already does) and avoid Python side effects and retracing in the step.

  4. Increase the batch size until memory or generalisation limits you, re-tuning the learning rate (Gradient Descent and Optimization).

  5. Enable mixed precision on Tensor Core or TPU hardware.

  6. Try jit_compile=True and keep it only if the profiled step time improves.

  7. Distribute only after one device is saturated, see Distributed Training.

  8. For deterministic runs use tf.config.experimental.enable_op_determinism(), which may slow some operations; see Tensors, Dtypes and Random Numbers for seeding.

Also consider TensorFlow’s GPU memory behaviour: by default it reserves most of the GPU memory at start-up; tf.config.experimental.set_memory_growth(gpu, True) makes it grow on demand (see Devices).

References