更改TensorF中的默认GPU

2024-04-25 09:38:33 发布

您现在位置:Python中文网/ 问答频道 /正文

根据文档,默认GPU是具有最低id的GPU:

If you have more than one GPU in your system, the GPU with the lowest ID will be selected by default.

是否可以从命令行或一行代码更改此默认值?


Tags: thein文档youidyourifgpu
3条回答

in the documentation所述,可以使用tf.device('/gpu:id')指定默认设备以外的设备。

# This will use the second GPU on your system
with tf.device('/gpu:1'):
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
    b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')

c = tf.matmul(a, b)
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print sess.run(c)

只是想清楚环境变量CUDA_VISIBLE_DEVICES的用法:

要仅在GPU 1上运行脚本my_script.py,在Linux终端中可以使用以下命令:

username@server:/scratch/coding/src$ CUDA_VISIBLE_DEVICES=1 python my_script.py 

More演示语法的示例:

Environment Variable Syntax      Results
CUDA_VISIBLE_DEVICES=1           Only device 1 will be seen
CUDA_VISIBLE_DEVICES=0,1         Devices 0 and 1 will be visible
CUDA_VISIBLE_DEVICES="0,1"       Same as above, quotation marks are optional
CUDA_VISIBLE_DEVICES=0,2,3       Devices 0, 2, 3 will be visible; device 1 is masked
CUDA_VISIBLE_DEVICES=""          No GPU will be visible

仅供参考:

Suever's answer正确地显示了如何将操作固定到特定的GPU。但是,如果在同一台计算机上运行多个TensorFlow程序,建议在启动进程之前设置^{}环境变量以公开不同的gpu。否则,TensorFlow将尝试在所有可用gpu上分配几乎整个内存,这将阻止其他进程使用这些gpu(即使当前进程不使用它们)。

请注意,如果使用CUDA_VISIBLE_DEVICES,则设备名"/gpu:0""/gpu:1"等是指当前进程中第0个和第1个可见的设备。

相关问题 更多 >