Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Run Multiple TensorFlow Codes on One GPU

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Running several TensorFlow programs on a single GPU is possible, but the GPU's memory is shared, so each program must be configured to use only a fraction of the available memory. By default, TensorFlow grabs all GPU memory, which causes the second program to fail with an out-of-memory error. This guide shows you how to set memory limits, use virtual devices, and run multiple scripts concurrently.

What You'll Need

  • A machine with one NVIDIA GPU and the NVIDIA driver installed.
  • CUDA and cuDNN installed (matching your TensorFlow version).
  • TensorFlow 2.x installed (the examples use TF2).
  • Python 3.6 or later.
  • Basic command-line knowledge.

Step-by-Step

  1. Check your GPU memory – Run nvidia-smi in the terminal. Note the total memory (e.g., 8 GB). You'll allocate fractions of this to each script.
  2. Set memory growth in each script – At the very top of each TensorFlow script, before any model creation, add:
    import tensorflow as tf
    physical_devices = tf.config.list_physical_devices('GPU')
    tf.config.experimental.set_memory_growth(physical_devices[0], True)
    This makes TensorFlow allocate memory only as needed, not all at once. However, memory growth alone may still cause OOM if two scripts grow to the full memory.
  3. Limit memory per process – Instead of growth, set a hard limit. For example, to use 2 GB out of 8 GB:
    import tensorflow as tf
    gpus = tf.config.list_physical_devices('GPU')
    if gpus:
        tf.config.set_logical_device_configuration(
            gpus[0],
            [tf.config.LogicalDeviceConfiguration(memory_limit=2048)])
    
    Use memory_limit in MB. Adjust the number based on your GPU's total memory and how many scripts you plan to run.
  4. Run your scripts in parallel – Open separate terminal windows (or use screen/tmux) and run each script with python script1.py and python script2.py. Each will see only its allocated memory.
  5. Use virtual devices for finer control (optional) – If you want to run two different models in the same script, you can split the GPU into virtual devices:
    gpus = tf.config.list_physical_devices('GPU')
    tf.config.set_logical_device_configuration(
        gpus[0],
        [tf.config.LogicalDeviceConfiguration(memory_limit=4096),
         tf.config.LogicalDeviceConfiguration(memory_limit=4096)])
    
    Then assign operations to /GPU:0 and /GPU:1 using tf.device().
  6. Monitor usage – While running, use nvidia-smi to see how much memory each process uses. If one is close to its limit, reduce its batch size or model size.
  7. Adjust batch sizes – If you get OOM errors, reduce the batch size in your model's training or inference loop. Smaller batches use less memory.

Common Mistakes

  • Forgetting to set memory limits – If you only use memory growth, two scripts can still exceed the GPU's total memory because growth allows each to expand until the GPU is full.
  • Setting limits that sum to more than the GPU's total – For example, setting 6 GB + 3 GB on an 8 GB GPU will cause OOM when the second script starts. Always leave a small buffer (e.g., 10% of total memory) for CUDA context and driver overhead.
  • Using the same script with different limits – If you copy-paste the memory limit code, make sure you change the number for each script. Forgetting to change 2048 to 4096 will underutilize the GPU.
  • Ignoring the CUDA context – Each TensorFlow process creates a CUDA context that consumes a small amount of memory (typically 200–500 MB). Account for that in your limits.
  • Running scripts that use all CPU cores – While not GPU memory, CPU contention can slow down data loading and preprocessing, making training slower overall.

Tips

  • Use nvidia-smi to check the actual memory usage before setting limits. Run a simple TensorFlow script that prints the available memory.
  • If you have multiple GPUs, you can assign each script to a different GPU by setting CUDA_VISIBLE_DEVICES=0 for the first and CUDA_VISIBLE_DEVICES=1 for the second.
  • For quick tests, use tf.config.experimental.set_memory_growth and run scripts one at a time to see how much memory they actually need. Then set hard limits accordingly.
  • Consider using Docker with --gpus '"device=0"' and --shm-size to isolate environments, but that adds complexity.
  • If you're training large models, prefer running them sequentially rather than in parallel to avoid memory fragmentation and performance degradation.

Troubleshooting

  • Out of memory (OOM) when starting the second script – Reduce the memory limit in the second script, or reduce the first script's limit. Also check if the first script is actually using its full allocation (it may not if the model is small).
  • Both scripts run but training is very slow – The GPU may be thrashing due to memory swapping. Reduce batch sizes or use mixed precision (if supported) to lower memory usage.
  • Script fails with 'CUDA_ERROR_OUT_OF_MEMORY' even with limits – Ensure that the sum of your limits plus the CUDA context (about 200-500 MB) is less than the total GPU memory. Also check if other processes (like a desktop GUI) are using GPU memory.
  • Memory growth setting has no effect – In TensorFlow 2.x, set_memory_growth must be called before any GPU operations. If you call it after creating a model, it may not apply. Place it at the very top of your script.
  • One script crashes with a segmentation fault – This can happen if you set memory limits too low and TensorFlow tries to allocate more. Increase the limit or reduce the model size.

Frequently Asked Questions

Can I run two TensorFlow scripts on one GPU without any changes?

No. By default, TensorFlow allocates all available GPU memory, so the second script will fail with OOM. You must set memory limits or memory growth.

What is the difference between memory growth and memory limit?

Memory growth starts with a small allocation and increases as needed, up to the full GPU memory. A memory limit caps the maximum amount the process can use. For running multiple scripts, hard limits are safer because they prevent one script from consuming everything.

Will running two scripts on one GPU double the training time?

Not necessarily. If the GPU has enough memory and compute resources, two smaller models can run concurrently with little slowdown. However, if they compete for compute, each may take longer than running alone.

Can I use virtual devices to run multiple models in the same script?

Yes. You can split the GPU into multiple logical devices and assign different operations to each. This is useful for running different models concurrently within one Python process.

What is the minimum memory I should leave for the system?

Leave at least 500 MB to 1 GB of GPU memory free for the CUDA driver and other system processes. If you have an 8 GB GPU, you can allocate up to 7 GB total across scripts.

Does this work with TensorFlow 1.x?

Yes, but the API is different. In TF1, use tf.ConfigProto(gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.5)) or allow_growth=True.