4

i'm running some code with cudas, and I need to test the same code on CPU to compare running time. To decide between regular pytorch tensor and cuda float tensor, the library I use calls torch.cuda.is_available(). Is there an easy method to make this function return false? I tried changing the Cuda visible devices with

os.environ["CUDA_VISIBLE_DEVICES"]=""

but torch.cuda.is_available() still return True. I went into pytorch source code, and in my case, torch.cuda.is_avaible returns

torch._C._cuda_getDeviceCount() > 0

I assume I should be able to "hide" my GPU at the start of my notebook, so the device count is equal to zero, but i didn't get any success so far. Any help is appreciated :)

2 Answers 2

6

You can make torch.cuda.is_available() return False by overwriting it. Just run the following code as the first thing in your program:

import torch
torch.cuda.is_available = lambda : False
3

my code

Instead of trying to trick it, why not rewrite your code? For example,

use_gpu = torch.cuda.is_available() and not os.environ['USE_CPU']

Then you can start your program as python runme.py to run on GPU if available, and USE_CPU=1 python3 runme.py to force CPU execution (or make it semi-permanent by export USE_CPU=1).

I tried changing the Cuda visible devices with

You can also try running your code with CUDA_VISIBLE_DEVICES="" python3 runme.py; if you're setting the environment variable inside your code, it might be set later than PyTorch initialisation, and have no effect.

3
  • 1
    The answer is simple. I'm using a library on top of pytorch. Everytime this library creates a tensor, it does the test i mentionned. So it's way easier for me if I could "trick" pytorch as you say. Furthermore, i only need to run my code once, to compare the time taken on CPU and GPU, so i don't feel like it's worth the investment^^ Oct 24, 2018 at 9:34
  • 1
    Yeah, that's why I quoted "my code" - you didn't mention the check is not, in fact, in your code. See the edit for another possibility.
    – Amadan
    Oct 24, 2018 at 9:35
  • 1
    I work with jupyterlab, so I did CUDA_VISIBLE_DEVICES="" jupyter lab, and it worked. Thanks a lot. Oct 24, 2018 at 9:40

Your Answer

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

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