GPU or CPU

xiaoxiao2021-02-27  179

使用 GPUs

支持的设备

在一套标准的系统上通常有多个计算设备. 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 .

记录设备指派情况

为了获取你的 operations 和 Tensor 被指派到哪个设备上运行, 用 log_device_placement 新建一个session, 并设置为True.

# 新建一个 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)

你应该能看见以下输出:

Device mapping: /job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: Tesla K40c, pci bus id: 0000:05:00.0 b: /job:localhost/replica:0/task:0/gpu:0 a: /job:localhost/replica:0/task:0/gpu:0 MatMul: /job:localhost/replica:0/task:0/gpu:0 [[ 22. 28.] [ 49. 64.]]

手工指派设备

如果你不想使用系统来为 operation 指派设备, 而是手工指派设备, 你可以用 with tf.device创建一个设备环境, 这个环境下的 operation 都统一运行在环境指定的设备上.

# 新建一个graph. 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)

你会发现现在 a 和 b 操作都被指派给了 cpu:0.

Device mapping: /job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: Tesla K40c, pci bus id: 0000:05:00.0 b: /job:localhost/replica:0/task:0/cpu:0 a: /job:localhost/replica:0/task:0/cpu:0 MatMul: /job:localhost/replica:0/task:0/gpu:0 [[ 22. 28.] [ 49. 64.]]

在多GPU系统里使用单一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(log_device_placement=True)) # 运行这个 op. print sess.run(c)

如果你指定的设备不存在, 你会收到 InvalidArgumentError 错误提示:

InvalidArgumentError: Invalid argument: Cannot assign a device to node 'b': Could not satisfy explicit device specification '/gpu:2' [[Node: b = Const[dtype=DT_FLOAT, value=Tensor<type: float shape: [3,2] values: 1 2 3...>, _device="/gpu:2"]()]]

为了避免出现你指定的设备不存在这种情况, 你可以在创建的 session 里把参数 allow_soft_placement 设置为True, 这样 tensorFlow 会自动选择一个存在并且支持的设备来运行 operation.

# 新建一个 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)

使用多个 GPU

如果你想让 TensorFlow 在多个 GPU 上运行, 你可以建立 multi-tower 结构, 在这个结构里每个 tower 分别被指配给不同的 GPU 运行. 比如:

# 新建一个 graph. c = [] for d in ['/gpu:2', '/gpu:3']: with tf.device(d): a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3]) b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2]) c.append(tf.matmul(a, b)) with tf.device('/cpu:0'): sum = tf.add_n(c) # 新建session with log_device_placement并设置为True. sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) # 运行这个op. print sess.run(sum)

你会看到如下输出:

Device mapping: /job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: Tesla K20m, pci bus id: 0000:02:00.0 /job:localhost/replica:0/task:0/gpu:1 -> device: 1, name: Tesla K20m, pci bus id: 0000:03:00.0 /job:localhost/replica:0/task:0/gpu:2 -> device: 2, name: Tesla K20m, pci bus id: 0000:83:00.0 /job:localhost/replica:0/task:0/gpu:3 -> device: 3, name: Tesla K20m, pci bus id: 0000:84:00.0 Const_3: /job:localhost/replica:0/task:0/gpu:3 Const_2: /job:localhost/replica:0/task:0/gpu:3 MatMul_1: /job:localhost/replica:0/task:0/gpu:3 Const_1: /job:localhost/replica:0/task:0/gpu:2 Const: /job:localhost/replica:0/task:0/gpu:2 MatMul: /job:localhost/replica:0/task:0/gpu:2 AddN: /job:localhost/replica:0/task:0/cpu:0 [[ 44. 56.] [ 98. 128.]]

cifar10 tutorial 这个例子很好的演示了怎样用GPU集群训练.

==============programe with GPU==================

下面是带GPU的Minist程序代码:

# encoding=utf8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for storing data') global mnist mnist = input_data.read_data_sets('/home/yuan/testMinist', one_hot=True) # mnist = input_data.read_data_sets('/home/yuan/Xia', one_hot=True) #远程下载MNIST数据,建议先下载好并保存在MNIST_data目录下 def DownloadData():     global mnist     #mnist = input_data.read_data_sets('/home/yuan/testMinist', one_hot=True)  #编码格式:one-hot     #print(mnist.train.images.shape, mnist.train.labels.shape)     #print(mnist.test.images.shape, mnist.test.labels.shape)     #print(mnist.validation.images.shape, mnist.validation.labels.shape) def weight_variable(shape):       initial = tf.truncated_normal(shape, stddev=0.1)       return tf.Variable(initial)   def bias_variable(shape):       initial = tf.constant(0.1, shape=shape)       return tf.Variable(initial) def conv2d(x, W):       return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x):       return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def Train():     with tf.device('/cpu:0'):         x = tf.placeholder("float", shape=[None, 784])            #构建占位符,代表输入的图像,None表示样本的数量可以是任意的         W = tf.Variable(tf.zeros([784,10]))                    #构建一个变量,代表训练目标weights,初始化为0         b = tf.Variable(tf.zeros([10]))         y_ = tf.placeholder("float", shape=[None, 10])         config = tf.ConfigProto()         config.gpu_options.allow_growth = True         gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)         #sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True))         #sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))         #sess = tf.InteractiveSession(config=tf.ConfigProto(gpu_options=gpu_options))         sess = tf.InteractiveSession(config=config)         #sess = tf.Session(config=config)     with tf.device('/gpu:0'):     #with tf.device('/cpu:0'):        #sess = tf.InteractiveSession()         #Step 1         #定义算法公式Softmax Regression         # = tf.placeholder("float", shape=[None, 784])            #构建占位符,代表输入的图像,None表示样本的数量可以是任意的         # = tf.Variable(tf.zeros([784,10]))                    #构建一个变量,代表训练目标weights,初始化为0        #b = tf.Variable(tf.zeros([10]))                        #构建一个变量,代表训练目标biases,初始化为0         #y = tf.nn.softmax(tf.matmul(x, W) + b)                 #构建了一个softmax的模型:y = softmax(Wx + b),y指样本标签的预测值         W_conv1 = weight_variable([5, 5, 1, 32])           b_conv1 = bias_variable([32])                      x_image = tf.reshape(x, [-1, 28, 28, 1])                      h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)           h_pool1 = max_pool_2x2(h_conv1)                      W_conv2 = weight_variable([5, 5, 32, 64])           b_conv2 = bias_variable([64])                      h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)           h_pool2 = max_pool_2x2(h_conv2)                      # Now image size is reduced to 7*7           W_fc1 = weight_variable([7 * 7 * 64, 1024])           b_fc1 = bias_variable([1024])                      h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])           h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)                      keep_prob = tf.placeholder("float")           h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)                      W_fc2 = weight_variable([1024, 10])           b_fc2 = bias_variable([10])           y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)         #Step 2         #定义损失函数,选定优化器,并指定优化器优化损失函数         #y_ = tf.placeholder(tf.float32, [None, 10])             # 构建占位符,代表样本标签的真实值        #y_ = tf.placeholder("float", shape=[None, 10])         # 交叉熵损失函数     with tf.device('/cpu:0'):         cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))         #y = tf.matmul(x, W) + b         #cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))         # 使用梯度下降法(0.01的学习率)来最小化这个交叉熵损失函数         #train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)         train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)         #Step 3         #使用随机梯度下降训练数据         #tf.global_variables_initializer().run() #when the comple enviroment is python3, changing global_variables_initializer         #tf.initialize_all_variables().run()  #when the comple enviroment is python2, changing initialize_all_variables()         #for i in range(10000):                                                  #迭代次数为1000         #    batch_xs, batch_ys = mnist.train.next_batch(100)                   #使用minibatch的训练数据,一个batch的大小为100         #   sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})        #用训练数据替代占位符来执行训练         #Step 4         #在测试集上对准确率进行评测         correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))          #tf.argmax()返回的是某一维度上其数据最大所在的索引值,在这里即代表预测值和真值         #accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))      #用平均值来统计测试准确率         accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))      #用平均值来统计测试准确率         #sess.run(tf.initialize_all_variables()) # when compile in python2,changing this.         sess.run(tf.global_variables_initializer()) # when compile in python3,changing this.                           #print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))  #打印测试信息                  for i in range(2000):                                                  #迭代次数为1000             #batch_xs, batch_ys = mnist.train.next_batch(50)                   #使用minibatch的训练数据,一个batch的大小为100           batch = mnist.train.next_batch(50)             #sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})        #用训练数据替代占位符来执行训练           if i0 == 0:  # this step is conducted when the condition needs             train_accuracy = accuracy.eval(feed_dict={                  x:batch[0], y_: batch[1], keep_prob: 1.0})               print ("step %d, training accuracy %.3f" %(i, train_accuracy))  # the output the training accuracy when the condition needs           train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})  # this step is used to get an trained model                    #sess.close()         print ("Training finished")         print ("test accuracy %.3f" % accuracy.eval(feed_dict={               x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) if __name__ == '__main__':     DownloadData();     Train();    

==============programe without GPU, only using CPU==================

下面是带CPU的Minist程序代码:

#!/usr/bin/python   # -*- coding: utf-8 -*- import input_data mnist = input_data.read_data_sets('/home/yuan/testMinist', one_hot=True) import tensorflow as tf   import sys   #from tensorflow.examples.tutorials.mnist import input_data   from tensorflow.examples.tutorials.mnist import input_data #print("step",mnist) #print("step",mnist.train) #print("step",mnist)   def weight_variable(shape):     initial = tf.truncated_normal(shape, stddev=0.1)     return tf.Variable(initial)     def bias_variable(shape):     initial = tf.constant(0.1, shape=shape)     return tf.Variable(initial)     def conv2d(x, W):     return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')     def max_pool_2x2(x):     return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')     #mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)     sess = tf.InteractiveSession()     x = tf.placeholder("float", shape=[None, 784])   y_ = tf.placeholder("float", shape=[None, 10])     W = tf.Variable(tf.zeros([784,10]))   b = tf.Variable(tf.zeros([10]))     W_conv1 = weight_variable([5, 5, 1, 32])   b_conv1 = bias_variable([32])     x_image = tf.reshape(x, [-1, 28, 28, 1])     h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)   h_pool1 = max_pool_2x2(h_conv1)     W_conv2 = weight_variable([5, 5, 32, 64])   b_conv2 = bias_variable([64])     h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)   h_pool2 = max_pool_2x2(h_conv2)     # Now image size is reduced to 7*7   W_fc1 = weight_variable([7 * 7 * 64, 1024])   b_fc1 = bias_variable([1024])     h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])   h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)     keep_prob = tf.placeholder("float")   h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)     W_fc2 = weight_variable([1024, 10])   b_fc2 = bias_variable([10])   y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)       cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))   train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)   correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))   accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))   sess.run(tf.initialize_all_variables())     for i in range(2000):  # the iterate steps for array   batch = mnist.train.next_batch(50)     #print("the format shape is:",batch[0].shape)   #print("the format size is:",batch[0].size)   #print("the format 2 is:",batch[0])   #print("the format 2 is:",batch[0].length)   #print("the format 2 is:",batch.size)   if i0 == 0:  # this step is conducted when the condition needs     train_accuracy = accuracy.eval(feed_dict={           x:batch[0], y_: batch[1], keep_prob: 1.0})       print "step %d, training accuracy %.3f"%(i, train_accuracy)  # the output the training accuracy when the condition needs   train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})  # this step is used to get an trained model     print "Training finished"     print "test accuracy %.3f" % accuracy.eval(feed_dict={       x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}) 

转载请注明原文地址: https://www.6miu.com/read-13804.html

最新回复(0)