How to Limit TensorFlow GPU Memory Usage
In this article
To limit TensorFlow GPU memory, set the GPU memory growth option before any TensorFlow operation runs, or cap the memory with a per-process limit. The most reliable approach is to call tf.config.experimental.set_memory_growth(gpu, True) for each GPU, or set tf.config.set_logical_device_configuration with a hard memory limit. Do this at the very start of your script, before importing or initializing any TensorFlow graph. If you skip this, TensorFlow will grab nearly all available GPU memory by default, which can starve other processes or cause out-of-memory errors when multiple jobs share a GPU.
What You'll Need
- A working TensorFlow installation (2.x recommended; the configuration API is stable in 2.x).
- A CUDA-capable NVIDIA GPU with a compatible driver and CUDA toolkit installed.
- Basic familiarity with Python and running scripts from a terminal or IDE.
- Access to the machine's GPU settings (no root required for memory growth, but some container setups may restrict device visibility).
Step-by-Step
- Check which GPUs TensorFlow sees. Run a short Python snippet:
import tensorflow as tf; print(tf.config.list_physical_devices('GPU')). If the list is empty, fix your driver/CUDA setup first; memory settings won't help if no GPU is detected. The exact output format can differ slightly by TensorFlow version, but the device list is the key part. - Set memory growth before any model or tensor is created. Place this code at the top of your script, right after importing TensorFlow and before building any model:
Memory growth tells TensorFlow to allocate GPU memory incrementally as needed instead of reserving a large block upfront. This is the simplest way to share a GPU between processes.gpus = tf.config.list_physical_devices('GPU') for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) - Alternatively, set a hard memory limit. If you need a strict cap (for example, to leave room for another job), configure a logical device with a memory limit:
The value is in megabytes. This creates a logical GPU that TensorFlow will not exceed. Note that this must also be done before any GPU operation.gpus = tf.config.list_physical_devices('GPU') if gpus: tf.config.set_logical_device_configuration( gpus[0], [tf.config.LogicalDeviceConfiguration(memory_limit=4096)]) - Verify the setting took effect. After configuration, run a small operation and check memory usage with
nvidia-smiin a terminal. You should see TensorFlow's process using only a fraction of total memory initially, growing as needed (with growth enabled) or capped at your limit (with a hard limit). - Apply the same pattern in Jupyter notebooks. Because notebooks keep the kernel alive between cells, you must run the configuration cell before any cell that imports TensorFlow or creates tensors. If you already ran a model cell, restart the kernel and run the configuration first. The menu path to restart is Kernel > Restart in Jupyter; in JupyterLab it is Kernel > Restart Kernel. Labels can differ slightly by version.
- For multi-GPU systems, configure each GPU individually. Loop over
tf.config.list_physical_devices('GPU')and apply growth or a limit to each device. You can also restrict visibility to specific GPUs with the environment variableCUDA_VISIBLE_DEVICESset before launching Python (for example,CUDA_VISIBLE_DEVICES=0 python train.py). This is an environment variable, not a TensorFlow setting, and must be set in the shell or script environment before TensorFlow initializes. - Persist the setting in your project. Put the configuration in a small module (for example,
gpu_config.py) and import it first in every entry point. This avoids forgetting the step in new scripts. Keep it before any other TensorFlow import that might initialize the runtime.
Common Mistakes
- Setting memory growth after creating a model or tensor. TensorFlow initializes the GPU context on first use; later calls raise a RuntimeError saying the virtual devices must be configured before initialization. Move the configuration to the very top.
- Confusing memory growth with a hard cap. Growth still allows TensorFlow to use all free memory eventually; it only avoids reserving it upfront. If you need a strict ceiling, use
memory_limit. - Using the wrong API name. In TensorFlow 2.x the function is
tf.config.experimental.set_memory_growth. Older 1.x code usedtf.ConfigProtoand session configs, which do not apply to eager execution in 2.x. - Forgetting that notebooks retain state. Running the configuration in a later cell after a model cell has already run will fail. Restart the kernel.
- Assuming the setting affects other processes. Memory growth and limits apply only to the current Python process. Other TensorFlow jobs need their own configuration.
Tips
- Use
nvidia-smito watch memory in real time while training; it shows per-process usage and helps confirm your cap is working. - If you run many small experiments, memory growth is usually enough and simpler than hard limits.
- For production services, a hard memory limit plus a batch-size check prevents one request from exhausting the GPU.
- When using Docker, pass
--gpusflags and setCUDA_VISIBLE_DEVICESinside the container to control which GPUs are visible before TensorFlow starts. - Keep a single configuration helper and import it first; this is the most reliable way to avoid the initialization-order error.
Troubleshooting
If you see a RuntimeError about virtual devices being configured after initialization, restart the Python process or notebook kernel and move the configuration to the top of the script. If tf.config.list_physical_devices('GPU') returns an empty list, the problem is driver or CUDA compatibility, not memory settings; verify the NVIDIA driver and CUDA version match your TensorFlow build. If memory usage still spikes to near total GPU memory, confirm you are not using a hard limit that is too high, and check that no other process is already holding memory. If a hard limit causes out-of-memory errors during training, increase the limit or reduce batch size. If settings seem ignored in a notebook, ensure you restarted the kernel after adding the configuration cell. In containerized environments, confirm the GPU is actually exposed to the container; otherwise TensorFlow falls back to CPU and memory settings have no effect.
Frequently Asked Questions
Does setting memory growth slow down training?
It can add minor overhead because memory is allocated incrementally, but for most workloads the difference is small. A hard limit avoids growth overhead but may cause out-of-memory errors if set too low.
Can I change the memory limit after TensorFlow has started?
No. Logical device configuration must be set before the GPU is initialized. After that, you must restart the process to apply a new limit.
What is the difference between memory growth and memory limit?
Memory growth lets TensorFlow allocate memory as needed without reserving it all upfront. A memory limit sets a hard ceiling in megabytes that TensorFlow will not exceed.
Does this work on TensorFlow 1.x?
The configuration API described here is for TensorFlow 2.x. TensorFlow 1.x used session-based ConfigProto settings, which are different and not covered by these calls.
Will limiting GPU memory affect model accuracy?
No. Memory settings control allocation only; they do not change computations or model results, though an overly tight limit can cause out-of-memory errors during training.
Can I limit memory for only one GPU in a multi-GPU setup?
Yes. Apply the configuration to the specific physical device you want to limit, or hide other GPUs with CUDA_VISIBLE_DEVICES before starting Python.