Curious Minds

Clear answers to science and history questions

Why TensorFlow Hangs with Multiple GPUs

· 5 min read · Science

TensorFlow hangs with multiple GPUs most often because of GPU memory exhaustion, improper device placement, or a deadlock in the CUDA context initialization when multiple processes or threads compete for the same GPU resources. The hang usually appears as a stalled training loop, a frozen session, or a process that never completes even though the CPU is idle.

Background: How TensorFlow Uses Multiple GPUs

TensorFlow was designed to distribute computation across devices, but it does not automatically use all available GPUs unless you explicitly configure it. By default, TensorFlow will allocate memory on every visible GPU at startup, even if you only intend to use one. This eager allocation is a common source of hangs because if another process (like a second TensorFlow job) has already reserved memory on that GPU, the new process will block waiting for memory that never becomes available.

In addition, TensorFlow's device placement logic decides which operations run on which GPU. If you do not specify placement, TensorFlow may place an operation on a GPU that is already occupied, or it may try to copy tensors between GPUs in a way that creates a circular wait. The CUDA driver itself can also hang if the GPU is in an unstable state, for example after a failed kernel launch or a driver timeout.

Common Causes of Hangs

Below are the most frequently reported reasons for a TensorFlow hang with multiple GPUs, based on developer forums and official documentation.

  • GPU memory exhaustion: The default setting allow_growth=False makes TensorFlow reserve nearly all available memory on each GPU at start. If two processes try to use the same GPU, the second one waits forever.
  • Missing CUDA_VISIBLE_DEVICES: Without this environment variable, TensorFlow sees all GPUs and tries to allocate on each, even if you only want one. This can cause conflicts with other users on a shared machine.
  • Improper device placement: Using with tf.device('/gpu:0') for some ops and '/gpu:1' for others can create a dependency cycle if the ops are not independent.
  • Inter-process communication deadlock: When using tf.distribute.MirroredStrategy or Horovod, all processes must synchronize. If one process crashes or stalls, the others hang waiting for its gradient.
  • Driver or CUDA version mismatch: An incompatible CUDA runtime can cause a kernel to hang silently, especially when multiple GPUs are accessed concurrently.

How to Diagnose the Hang

Before changing code, you need to confirm where the hang occurs. Use these steps:

  1. Run your script with strace -p (Linux) to see if the process is stuck on a CUDA call.
  2. Check GPU memory with nvidia-smi – if one GPU shows 100% memory usage but 0% compute, it's likely a memory allocation block.
  3. Add tf.debugging.set_log_device_placement(True) to log which device each op runs on. This reveals unintended placement.
  4. Set CUDA_LAUNCH_BLOCKING=1 to force synchronous kernel execution. This makes the hang reproducible and shows the exact op that stalls.
  5. If using multiple processes, check that all processes have the same CUDA_VISIBLE_DEVICES and that no process is using a GPU that another expects.

Solutions and Best Practices

Once you identify the cause, apply the corresponding fix. Here are proven solutions:

  • Set memory growth: Use gpus = tf.config.experimental.list_physical_devices('GPU') and then tf.config.experimental.set_memory_growth(gpu, True) for each GPU. This prevents pre-allocation and allows dynamic growth.
  • Limit visible GPUs: Set os.environ['CUDA_VISIBLE_DEVICES']='0' before importing TensorFlow to use only one GPU, or specify a subset like '0,1'.
  • Use tf.distribute.MirroredStrategy correctly: Wrap your model and training loop inside the strategy scope, and ensure all processes use the same strategy. Do not mix manual device placement with the strategy.
  • Add timeouts: In distributed training, set a timeout for the collective ops, e.g., tf.distribute.experimental.CommunicationOptions(timeout_seconds=30) to avoid indefinite hangs.
  • Update drivers and CUDA: Ensure your NVIDIA driver supports the CUDA version TensorFlow expects. Check TensorFlow's official GPU support matrix.

Multi-Process vs. Multi-Thread Hangs

Hangs differ depending on whether you run multiple processes (e.g., with mpirun for Horovod) or multiple threads (e.g., with a single Python process using tf.distribute). In multi-process, the hang often stems from a mismatch in the number of processes and the number of GPUs. For example, if you launch 4 processes but only 2 GPUs, two processes will try to share a GPU and may deadlock. In multi-thread, the hang is often due to a race condition in the graph construction phase, especially when using tf.function with side effects.

A common misconception is that adding more GPUs automatically speeds up training. In reality, if your model is small or your batch size is too small, the communication overhead can dominate, and the system may appear to hang because the GPU utilization is low. This is not a true hang but a performance issue. Always profile with nvidia-smi to see if GPUs are actually computing.

Comparison: TensorFlow vs. PyTorch Multi-GPU Behavior

PyTorch has a similar issue with CUDA memory allocation, but it uses a different default: PyTorch allocates memory on demand, not eagerly. This makes PyTorch less prone to startup hangs when multiple processes share a GPU. However, PyTorch can still hang if you use DataParallel incorrectly or if you have a deadlock in the dataloader. TensorFlow's eager allocation is a deliberate design choice to reduce runtime overhead, but it requires careful configuration in multi-GPU environments.

Frequently Asked Questions

Why does TensorFlow hang even with only one GPU?

If you have one GPU but still hang, it's usually because another process (like a display server or another TensorFlow job) is holding memory. Use nvidia-smi to check memory usage. Also, ensure your CUDA and cuDNN versions match TensorFlow's requirements.

How do I stop TensorFlow from using all GPUs?

Set the environment variable CUDA_VISIBLE_DEVICES to a comma-separated list of GPU indices before importing TensorFlow. For example, os.environ['CUDA_VISIBLE_DEVICES']='0' uses only GPU 0.

What is the difference between allow_growth=True and set_memory_growth?

They are the same thing. set_memory_growth is the newer API that sets the same option. It allows TensorFlow to allocate memory incrementally as needed, rather than reserving all memory upfront.

Can a hang damage my GPU?

No, a software hang does not damage hardware. However, if the GPU is stuck at high temperature due to a long hang, it could theoretically overheat, but most GPUs have thermal protection that shuts down before damage.

Does using tf.distribute.MirroredStrategy automatically avoid hangs?

No. You must still set memory growth and ensure that the strategy is used consistently across all processes. Also, you need to make sure that the number of GPUs matches the number of processes, or the strategy will hang.

In this article
  1. Background: How TensorFlow Uses Multiple GPUs
  2. Common Causes of Hangs
  3. How to Diagnose the Hang
  4. Solutions and Best Practices
  5. Multi-Process vs. Multi-Thread Hangs
  6. Comparison: TensorFlow vs. PyTorch Multi-GPU Behavior
  7. Frequently Asked Questions