'Use CPU if GPU not present

self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

The code to check if there is a gpu or not, and if there isn't, to utilise the cpu, is described above, using Pytorch. How to implement this using tensorflow?



Solution 1:[1]

As long as you have all the necessary libraries installed (drivers, CUDA, etc.), Tensorflow will automatically run on the GPU, no changes required. You can use the following code to check if Tensorflow recognizes your GPU:

import tensorflow as tf

gpus = tf.config.list_physical_devices('GPU')
for gpu in gpus:
    print("Name:", gpu.name, "  Type:", gpu.device_type)

If there is no GPU available this code will simply print out nothing, so you know, that Tensorflow did not find a GPU to run your model on. In that case, Tensorflow will run normally on the CPU. There is no explicit code necessary to switch between GPU and CPU.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1