tensorflow:Multiple GPUs

深度学习theano/tensorflow多显卡多人使用问题集

tensorflow中使用指定的GPU及GPU显存

Using GPUs

petewarden/tensorflow_makefile

tf_gpu_manager/manager.py

多GPU运行Deep Learning 和 并行Deep Learning(待续)


Multiple GPUs


这里写图片描述


1. 终端执行程序时设置使用的GPU


如果电脑有多个GPU,tensorflow默认全部使用。如果想只使用部分GPU,可以设置CUDA_VISIBLE_DEVICES。在调用python程序时,可以使用

CUDA_VISIBLE_DEVICES=1 python my_script.py #只使用GPU1
CUDA_VISIBLE_DEVICES=0,1 python my_script.py #使用GPU0,GPU1
Environment Variable Syntax      ResultsCUDA_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

2. python代码中设置使用的GPU


如果要在python代码中设置使用的GPU,可以使用下面的代码

import os
os.environ["CUDA_VISIBLE_DEVICES"] = "2"

3. 设置tensorflow使用的显存大小


定量设置显存

默认tensorflow是使用GPU尽可能多的显存。可以通过下面的方式,来设置使用的GPU显存:

gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.7)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))    

上面分配给tensorflow的GPU显存大小为:GPU实际显存*0.7。
可以按照需要,设置不同的值,来分配显存。

按需设置显存

上面的只能设置固定的大小。如果想按需分配,可以使用allow_growth参数(参考网址:http://blog.csdn.net/cq361106306/article/details/52950081):

gpu_options = tf.GPUOptions(allow_growth=True)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))   

4. 使用多个 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.]]

5. 如何实现multi_gpu_model函数


def multi_gpu_model(num_gpus=1):grads = []for i in range(num_gpus):with tf.device("/gpu:%d"%i):with tf.name_scope("tower_%d"%i):model = Model(is_training, config, scope)# 放到collection中,方便feed的时候取tf.add_to_collection("train_model", model)grads.append(model.grad) #grad 是通过tf.gradients(loss, vars)求得#以下这些add_to_collection可以直接在模型内部完成。# 将loss放到 collection中, 方便以后操作tf.add_to_collection("loss",model.loss)#将predict放到collection中,方便操作tf.add_to_collection("predict", model.predict)#将 summary.merge op放到collection中,方便操作tf.add_to_collection("merge_summary", model.merge_summary)# ...with tf.device("cpu:0"):averaged_gradients = average_gradients(grads)# average_gradients后面说明opt = tf.train.GradientDescentOptimizer(learning_rate)train_op=opt.apply_gradients(zip(average_gradients,tf.trainable_variables()))return train_op

6. cifar10 tutorial-cifar10_multi_gpu_train.py


code 见 models/tutorials/image/cifar10/

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================="""A binary to train CIFAR-10 using multiple GPUs with synchronous updates.
Accuracy:
cifar10_multi_gpu_train.py achieves ~86% accuracy after 100K steps (256
epochs of data) as judged by cifar10_eval.py.
Speed: With batch_size 128.
System        | Step Time (sec/batch)  |     Accuracy
--------------------------------------------------------------------
1 Tesla K20m  | 0.35-0.60              | ~86% at 60K steps  (5 hours)
1 Tesla K40m  | 0.25-0.35              | ~86% at 100K steps (4 hours)
2 Tesla K20m  | 0.13-0.20              | ~84% at 30K steps  (2.5 hours)
3 Tesla K20m  | 0.13-0.18              | ~84% at 30K steps
4 Tesla K20m  | ~0.10                  | ~84% at 30K steps
Usage:
Please see the tutorial and website for how to download the CIFAR-10
data set, compile the program and train the model.
http://tensorflow.org/tutorials/deep_cnn/
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_functionfrom datetime import datetime
import os.path
import re
import timeimport numpy as np
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf
import cifar10FLAGS = tf.app.flags.FLAGStf.app.flags.DEFINE_string('train_dir', '/tmp/cifar10_train',"""Directory where to write event logs """"""and checkpoint.""")
tf.app.flags.DEFINE_integer('max_steps', 1000000,"""Number of batches to run.""")
tf.app.flags.DEFINE_integer('num_gpus', 1,"""How many GPUs to use.""")
tf.app.flags.DEFINE_boolean('log_device_placement', False,"""Whether to log device placement.""")def tower_loss(scope, images, labels):"""Calculate the total loss on a single tower running the CIFAR model.Args:scope: unique prefix string identifying the CIFAR tower, e.g. 'tower_0'images: Images. 4D tensor of shape [batch_size, height, width, 3].labels: Labels. 1D tensor of shape [batch_size].Returns:Tensor of shape [] containing the total loss for a batch of data"""# Build inference Graph.logits = cifar10.inference(images)# Build the portion of the Graph calculating the losses. Note that we will# assemble the total_loss using a custom function below._ = cifar10.loss(logits, labels)# Assemble all of the losses for the current tower only.losses = tf.get_collection('losses', scope)# Calculate the total loss for the current tower.total_loss = tf.add_n(losses, name='total_loss')# Attach a scalar summary to all individual losses and the total loss; do the# same for the averaged version of the losses.for l in losses + [total_loss]:# Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training# session. This helps the clarity of presentation on tensorboard.loss_name = re.sub('%s_[0-9]*/' % cifar10.TOWER_NAME, '', l.op.name)tf.summary.scalar(loss_name, l)return total_lossdef average_gradients(tower_grads):"""Calculate the average gradient for each shared variable across all towers.Note that this function provides a synchronization point across all towers.Args:tower_grads: List of lists of (gradient, variable) tuples. The outer listis over individual gradients. The inner list is over the gradientcalculation for each tower.Returns:List of pairs of (gradient, variable) where the gradient has been averagedacross all towers."""average_grads = []for grad_and_vars in zip(*tower_grads):# Note that each grad_and_vars looks like the following:#   ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))grads = []for g, _ in grad_and_vars:# Add 0 dimension to the gradients to represent the tower.expanded_g = tf.expand_dims(g, 0)# Append on a 'tower' dimension which we will average over below.grads.append(expanded_g)# Average over the 'tower' dimension.grad = tf.concat(axis=0, values=grads)grad = tf.reduce_mean(grad, 0)# Keep in mind that the Variables are redundant because they are shared# across towers. So .. we will just return the first tower's pointer to# the Variable.v = grad_and_vars[0][1]grad_and_var = (grad, v)average_grads.append(grad_and_var)return average_gradsdef train():"""Train CIFAR-10 for a number of steps."""with tf.Graph().as_default(), tf.device('/cpu:0'):# Create a variable to count the number of train() calls. This equals the# number of batches processed * FLAGS.num_gpus.global_step = tf.get_variable('global_step', [],initializer=tf.constant_initializer(0), trainable=False)# Calculate the learning rate schedule.num_batches_per_epoch = (cifar10.NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN /FLAGS.batch_size)decay_steps = int(num_batches_per_epoch * cifar10.NUM_EPOCHS_PER_DECAY)# Decay the learning rate exponentially based on the number of steps.lr = tf.train.exponential_decay(cifar10.INITIAL_LEARNING_RATE,global_step,decay_steps,cifar10.LEARNING_RATE_DECAY_FACTOR,staircase=True)# Create an optimizer that performs gradient descent.opt = tf.train.GradientDescentOptimizer(lr)# Get images and labels for CIFAR-10.images, labels = cifar10.distorted_inputs()batch_queue = tf.contrib.slim.prefetch_queue.prefetch_queue([images, labels], capacity=2 * FLAGS.num_gpus)# Calculate the gradients for each model tower.tower_grads = []with tf.variable_scope(tf.get_variable_scope()):for i in xrange(FLAGS.num_gpus):with tf.device('/gpu:%d' % i):with tf.name_scope('%s_%d' % (cifar10.TOWER_NAME, i)) as scope:# Dequeues one batch for the GPUimage_batch, label_batch = batch_queue.dequeue()# Calculate the loss for one tower of the CIFAR model. This function# constructs the entire CIFAR model but shares the variables across# all towers.loss = tower_loss(scope, image_batch, label_batch)# Reuse variables for the next tower.tf.get_variable_scope().reuse_variables()# Retain the summaries from the final tower.summaries = tf.get_collection(tf.GraphKeys.SUMMARIES, scope)# Calculate the gradients for the batch of data on this CIFAR tower.grads = opt.compute_gradients(loss)# Keep track of the gradients across all towers.tower_grads.append(grads)# We must calculate the mean of each gradient. Note that this is the# synchronization point across all towers.grads = average_gradients(tower_grads)# Add a summary to track the learning rate.summaries.append(tf.summary.scalar('learning_rate', lr))# Add histograms for gradients.for grad, var in grads:if grad is not None:summaries.append(tf.summary.histogram(var.op.name + '/gradients', grad))# Apply the gradients to adjust the shared variables.apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)# Add histograms for trainable variables.for var in tf.trainable_variables():summaries.append(tf.summary.histogram(var.op.name, var))# Track the moving averages of all trainable variables.variable_averages = tf.train.ExponentialMovingAverage(cifar10.MOVING_AVERAGE_DECAY, global_step)variables_averages_op = variable_averages.apply(tf.trainable_variables())# Group all updates to into a single train op.train_op = tf.group(apply_gradient_op, variables_averages_op)# Create a saver.saver = tf.train.Saver(tf.global_variables())# Build the summary operation from the last tower summaries.summary_op = tf.summary.merge(summaries)# Build an initialization operation to run below.init = tf.global_variables_initializer()# Start running operations on the Graph. allow_soft_placement must be set to# True to build towers on GPU, as some of the ops do not have GPU# implementations.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,log_device_placement=FLAGS.log_device_placement))sess.run(init)# Start the queue runners.tf.train.start_queue_runners(sess=sess)summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph)for step in xrange(FLAGS.max_steps):start_time = time.time()_, loss_value = sess.run([train_op, loss])duration = time.time() - start_timeassert not np.isnan(loss_value), 'Model diverged with loss = NaN'if step % 10 == 0:num_examples_per_step = FLAGS.batch_size * FLAGS.num_gpusexamples_per_sec = num_examples_per_step / durationsec_per_batch = duration / FLAGS.num_gpusformat_str = ('%s: step %d, loss = %.2f (%.1f examples/sec; %.3f ''sec/batch)')print (format_str % (datetime.now(), step, loss_value,examples_per_sec, sec_per_batch))if step % 100 == 0:summary_str = sess.run(summary_op)summary_writer.add_summary(summary_str, step)# Save the model checkpoint periodically.if step % 1000 == 0 or (step + 1) == FLAGS.max_steps:checkpoint_path = os.path.join(FLAGS.train_dir, 'model.ckpt')saver.save(sess, checkpoint_path, global_step=step)def main(argv=None):  # pylint: disable=unused-argumentcifar10.maybe_download_and_extract()if tf.gfile.Exists(FLAGS.train_dir):tf.gfile.DeleteRecursively(FLAGS.train_dir)tf.gfile.MakeDirs(FLAGS.train_dir)train()if __name__ == '__main__':
tf.app.run()
python cifar10_multi_gpu_train.py --num_gpus=2

参考文献


http://stackoverflow.com/questions/36668467/change-default-gpu-in-tensorflow
http://stackoverflow.com/questions/37893755/tensorflow-set-cuda-visible-devices-within-jupyter
(原)tensorflow中使用指定的GPU及GPU显存
Using GPUs
TensorFlow官方文档中文版 » 运作方式 » 使用gpu
tensorflow学习笔记(三十一):构建多GPU代码
cifar10 tutorial
CIFAR10 多 GPU 版本例程源码分析
tensorflow cifar_10 代码阅读与理解

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/246809.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Tensorflow一些常用基本概念与函数

参考文献 Tensorflow一些常用基本概念与函数 http://www.cnblogs.com/wuzhitj/archive/2017/03.html Tensorflow笔记:常用函数说明: http://blog.csdn.net/u014595019/article/details/52805444 Tensorflow一些常用基本概念与函数(1&#…

ubuntu16.04 Nvidia 显卡的风扇调速及startx的后果

问题描述 #查看nvdia GPU 显卡状态 watch -n 10 nvidia-smi 发现显卡Tesla k40c的温度已经达到74,转速仅仅只有49%。 查看Tesla产品资料,Tesla K40 工作站加速卡规格 ,可知 所以需要调整风扇速度来降温。 然而官方驱动面板里也没有了风扇调…

Python函数式编程-map()、zip()、filter()、reduce()、lambda()

三个函数比较类似,都是应用于序列的内置函数。常见的序列包括list、tuple、str map函数 map函数会根据提供的函数对指定序列做映射。 map函数的定义: map(function, sequence[, sequence, ...]) -> list map()函数接收两个参数,一个是函…

Kaggle : Using a Convolutional Neural Network for classifying Cats vs Dogs

数据下载 https://www.kaggle.com/c/dogs-vs-cats-redux-kernels-edition/data Part 1 - Preprocessing #Package Requirements #!/usr/bin/python2 # -*- coding: UTF-8 -*- import cv2 # working with, mainly resizing, images import numpy as np …

李宏毅机器学习课程1~~~Introduction Regression

机器学习介绍 机器学习就是要找一个函数。 机器学习的三大要素框架:训练集,函数集(模型集),损失函数集。 机器学习图谱 AI训练师的成长之路。 1. 梯度下降法的理解Gradient Descent 参数变化的方向就是损失函数减少的方…

李宏毅机器学习课程2~~~误差从哪里来?

Stanford机器学习—第六讲. 怎样选择机器学习方法、系统 误差来源 误差主要来自于偏差和方差。 数学上定义: 通过covariate X 预测 Y ,我们假设存在如下关系: Y f(X) ϵ 满足正态分布均值为0 方差σϵ 模型预测错误定义为: …

李宏毅机器学习课程3~~~梯度下降法

梯度下降法描述 梯度下降法是为了找到最优的目标函数,寻找的过程就是沿着损失函数下降的方向来确定参数变化的方向。参数更新的过程就是一个不断迭代的过程,每次更新参数学到的函数都会使得误差损失越来越小,也就是说学习到的参数函数越来越逼…

李宏毅机器学习课程4~~~分类:概率生成模型

分类问题用回归来解决? 当有右图所示的点时,这些点会大幅改变分类线的位置。这时候就会导致整体的回归结果变差。当把多分类当成回归问题,类别分别为1,2,3,4……,因为回归的问题是预测具体的值,这样定义类别…

李宏毅机器学习课程5~~~分类:逻辑回归

Function Set 不同的w,b来确定不同的函数,这样就组成了函数集合,不同的w,b可以来表达不同的分布函数。 Good of a Function 变换表达形式 两个Bernoulli distribution的交叉熵。所谓交叉熵,是用来刻画两个分布的相似性…

李宏毅机器学习课程6~~~深度学习入门

深度学习历史 深度学习经典步骤 神经网络的符合标记含义 Wij 代表的是从神经元j到神经元i,这样写的目的是便于表达,否则最后的表达式子就是Wij的转置,细节见下面。 每个神经元的偏执值组成一个向量b 单个神…

李宏毅机器学习课程7~~~反向传播

到底为什么基于反向传播的纯监督学习在过去表现不佳?Geoffrey Hinton总结了目前发现的四个方面问题: 带标签的数据集很小,只有现在的千分之一. 计算性能很慢,只有现在的百万分之一. 权重的初始化方式笨拙. 使用了错误的非线性模型…

李宏毅机器学习课程8~~~keras

keras keras示例 确定网络结构 确定损失函数 确定训练网络参数 batchsize与运算时间,平行运算,可以缩简运算时间。batchsize不能太大,这是由于内存的关系。此外,batchsize太大容易陷入局部极值点或者鞍点。batchsize=&…

李宏毅机器学习课程9~~~深度学习技巧

Recipe of Deep Learning Overfitting overfitting的判断是要训练误差与测试误差做比较。这个56-layer的网络在训练集上都没有训练好,说白了就是有点欠拟合。所以仅仅依靠测试集上的结果来判断56-layer比20-layer overfitting是不合理的。 更多理解见 Overfitting…

Liner(分段线性插值)

第一次写微博,记录自己的学习历程~~~~欢迎大家一起探讨~~~~ 分段线性插值故名思议就是说把给定样本点的区间分成多个不同区间,记为[xi,xi1],在每个区间上的一次线性方程为: 关于其证明: 分段线性插值在速度和误差取得…

在linux设置回收站 - 防止失误操作造成数据清空,并定期清理

安装trash sudo apt-get install trash-chi 原理 执行trash命令后,是将文件移动了用户的回收站,每个用户的回收站路径为$HOME/.local/share/Trash,比如用户asin的回收站位于/home/asin/.local/share/Trash,用户root的回收站位于…

Spline(三次样条插值)

关于三次样条插值,计算方法比较复杂,但是静下心来仔细研究也是可以理解的。 本文借鉴文章来源:http://www.cnki.com.cn/Article/CJFDTotal-BGZD200611035.htm 定义: 简单来说就是给定了一些在区间[a,b]的数据点{x1,x2,x3.....xn…

李宏毅机器学习课程10~~~卷积神经网络

卷积的意义 数字图像是一个二维的离散信号,对数字图像做卷积操作其实就是利用卷积核(卷积模板)在图像上滑动,将图像点上的像素灰度值与对应的卷积核上的数值相乘,然后将所有相乘后的值相加作为卷积核中间像素对应的图像…

matlab自带的插值函数interp1的四种插值方法

x0:2*pi; ysin(x); xx0:0.5:2*pi;%interp1对sin函数进行分段线性插值,调用interp1的时候,默认的是分段线性插值 y1interp1(x,y,xx); figure plot(x,y,o,xx,y1,r) title(分段线性插值)%临近插值 y2interp1(x,y,xx,nearest); figure plot(x,y,o,xx,y2,r); …

拉格朗日插值法(Lagrange)

拉格朗日插值法是基于基函数的插值方法,插值多项式可以表示为: 其中称为 i 次基函数 Matlab中拉格朗日插值法函数为:Language 功能:求已知点数据点的拉格朗日多项式 调用格式:fLagrange(x,y) 或者 f ’Lagrange(x,y,x0) 其中&a…

当你在应用机器学习时你应该想什么

如今, 机器学习变得十分诱人, 它已在网页搜索, 商品推荐, 垃圾邮件检测, 语音识别, 图像识别, 自然语言处理等诸多领域发挥重要作用. 和以往我们显式地通过编程告诉计算机如何进行计算不同, 机器学习是一种数据驱动方法(data-driven approach). 然而, 有时候机器学习像是一种”…