Tensorflow之GPU和CPU

1.支持设备
在一套标准的系统上通常有多个计算设备. TensorFlow 支持 CPU 和 GPU 这两种设备. 我们用指定字符串 strings 来标识这些设备. 比如:

  • "/cpu:0": 机器中的 CPU
  • "/gpu:0": 机器中的 GPU, 如果你有一个的话.
  • "/gpu:1": 机器中的第二个 GPU, 以此类推…

如果一个 TensorFlow 的 operation 中兼有 CPU 和 GPU 的实现, 当这个算子被指派设备时, GPU 有优先权. 比如matmul中 CPU 和 GPU kernel 函数都存在. 那么在 cpu:0 和 gpu:0 中, matmul operation 会被指派给 gpu:0 .
2.设备指派情况

  • 自动指派设备
    为了获取你的operations和Tensor被指派到哪个设备上运行,用log_device_placement 新建一个 session, 并设置为 True.
import tensorflow as tf
#新建一个graph.
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)
#新建session with log_device_placement并设置为True.
sess=tf.Session(config=tf.ConfigProto(log_device_placement=True))
#运行这个op.
print(sess.run(c))
  • 手工指派设备
    可以用 with tf.device 创建一个设备环境, 这个环境下的 operation 都统一运行在环境指定的设备上.

**指派给CPU

# 新建一个graph.使得a和b的操作都指派给cpu:0
with tf.device('/cpu:0'):
  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)
# 新建session with log_device_placement并设置为True.
sess=tf.Session(config=tf.ConfigProto(log_device_placement=True))
# 运行这个op.
print (sess.run(c))

**指派给GPU
如果你的系统里有多个 GPU, 那么 ID 最小的 GPU 会默认使用. 如果你想用别的 GPU, 可以用下面的方法显式的声明你的偏好:

# 新建一个 graph.
with tf.device('/gpu:2'):
  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)
# 新建 session with log_device_placement 并设置为 True.
sess=tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True))
# 运行这个 op.
print(sess.run(c))

在这里,session 里参数 allow_soft_placement 设置为 True, 这是因为当指定的设备不存在时, 会收到 InvalidArgumentError 错误提示,这样可以避免这一情况发生,当其设置为true时, tensorFlow 会自动选择一个存在并且支持的设备来运行operation.
此外,还可以指派给多个GPU,下面举个例子说明这一点:

# 新建一个 graph.
x=3
y=4
z=2
with tf.device('/gpu:1'):
    a=tf.multiply(x,x)
    b=tf.multiply(a,y)
with tf.device('/gpu:2'):
    c=tf.add(y,z)
# 新建 session with log_device_placement 并设置为 True.
sess=tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True))
# 运行这个 op.
d=tf.add(b,c)
print(sess.run(d))

这里写图片描述

上述代码中,若不设置’allow_soft_placement=True’则会报错,是由于本机没有GPU1,GPU2

猜你喜欢

转载自blog.csdn.net/qq_33186949/article/details/79104659