103

I have two GPUs and would like to run two different networks via ipynb simultaneously, however the first notebook always allocates both GPUs.

Using CUDA_VISIBLE_DEVICES, I can hide devices for python files, however I am unsure of how to do so within a notebook.

Is there anyway to hide different GPUs in to notebooks running on the same server?

3 Answers 3

201

You can set environment variables in the notebook using os.environ. Do the following before initializing TensorFlow to limit TensorFlow to first GPU.

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"   # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0"

You can double check that you have the correct devices visible to TF

from tensorflow.python.client import device_lib
print device_lib.list_local_devices()

I tend to use it from utility module like notebook_util

import notebook_util
notebook_util.pick_gpu_lowest_memory()
import tensorflow as tf
4
  • 4
    for me it didn't work os.environ["CUDA_VISIBLE_DEVICES"]="0" ... I changed it to os.environ["CUDA_VISIBLE_DEVICES"]="" and then it worked. I'm using tensorflow 1.12 Commented Jun 23, 2019 at 15:44
  • I tried displaying tensorflow local devices as mentioned. My system outputs only device type: CPU. Does this mean that tensorflow is not running GPU. Commented Jul 2, 2019 at 13:12
  • This does not work for me after tensorflow imports.
    – rjurney
    Commented Oct 29, 2020 at 6:59
  • That has to be done at the very beginning of your notebook.
    – muammar
    Commented Oct 28, 2021 at 11:49
49

You can do it faster without any imports just by using magics:

%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0

Notice that all env variable are strings, so no need to use ". You can verify that env-variable is set up by running: %env <name_of_var>. Or check all of them with %env.

2
  • Does this env setting affect other python scripts? as it looks like changing the environment variable of os.
    – JenkinsY
    Commented May 16, 2018 at 11:21
  • 1
    @JenkinsY you can easily check it by setting the variable in one script and reading it in another. Commented May 23, 2018 at 7:35
15

You can also enable multiple GPU cores, like so:

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0,2,3,4"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.