问题:如何在CPU上运行Tensorflow
我已经在Ubuntu 14.04上安装了GPU版本的tensorflow。
我在GPU服务器上,张量流可以访问可用的GPU。
我想在CPU上运行tensorflow。
通常我可以env CUDA_VISIBLE_DEVICES=0在GPU号上运行。0。
我该如何在CPU之间进行选择?
我不喜欢重新编写我的代码 with tf.device("/cpu:0"):
回答 0
您可以device_count按tf.Session以下方式应用参数:
config = tf.ConfigProto(
        device_count = {'GPU': 0}
    )
sess = tf.Session(config=config)另请参阅protobuf配置文件:
回答 1
您还可以将环境变量设置为
CUDA_VISIBLE_DEVICES=""无需修改源代码。
回答 2
如果以上答案不起作用,请尝试:
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'回答 3
对我来说,只有CUDA_VISIBLE_DEVICES精确设置才行-1:
作品:
import os
import tensorflow as tf
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
if tf.test.gpu_device_name():
    print('GPU found')
else:
    print("No GPU found")
# No GPU found难道不工作:
import os
import tensorflow as tf
os.environ['CUDA_VISIBLE_DEVICES'] = ''    
if tf.test.gpu_device_name():
    print('GPU found')
else:
    print("No GPU found")
# GPU found回答 4
只需使用下面的代码。
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'回答 5
在某些系统中,必须指定:
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]=""  # or even "-1"在导入张量流之前。
回答 6
您可以使用tf.config.set_visible_devices。一种可能的功能,它允许您设置是否使用以及使用哪些GPU:
import tensorflow as tf
def set_gpu(gpu_ids_list):
    gpus = tf.config.list_physical_devices('GPU')
    if gpus:
        try:
            gpus_used = [gpus[i] for i in gpu_ids_list]
            tf.config.set_visible_devices(gpus_used, 'GPU')
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
        except RuntimeError as e:
            # Visible devices must be set before GPUs have been initialized
            print(e)假设你是用4个GPU的系统上,你希望只使用两个GPU,在一个具有id = 0和一个有id = 2,那么你的代码的第一个命令,导入库后,将是:
set_gpu([0, 2])对于您的情况,仅使用CPU,可以使用一个空列表调用该函数:
set_gpu([])为了完整起见,如果要避免运行时初始化将分配设备上的所有内存,可以使用tf.config.experimental.set_memory_growth。最后,用于管理要使用的设备的功能(动态占用GPU的内存)变为:
import tensorflow as tf
def set_gpu(gpu_ids_list):
    gpus = tf.config.list_physical_devices('GPU')
    if gpus:
        try:
            gpus_used = [gpus[i] for i in gpu_ids_list]
            tf.config.set_visible_devices(gpus_used, 'GPU')
            for gpu in gpus_used:
                tf.config.experimental.set_memory_growth(gpu, True)
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
        except RuntimeError as e:
            # Visible devices must be set before GPUs have been initialized
            print(e)回答 7
在安装级别上的另一种可能的解决方案是寻找仅CPU的变体:https : //www.tensorflow.org/install/pip#package-location
就我而言,这给出了:
pip3 install https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow_cpu-2.2.0-cp38-cp38-win_amd64.whl只需选择正确的版本。如在此答案中说明的使用venv的奖励积分。
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

