人工智能 - TensorFlow 的 GPU [5]

欢迎Follow我的GitHub,关注我的简书

在含有GPU的服务器中,运行TensorFlow程序。

一般不需要显式指定使用CPU还是GPU,TensorFlow能自动检测。如果检测到GPU,TensorFlow会尽可能地利用找到的第一个GPU来执行操作。如果机器上有超过一个可用的GPU,除第一个外,其它GPU默认是不参与计算的。为了让TensorFlow使用这些 GPU,你必须将op明确指派给它们执行。with tf.device('/gpu:%d' % i)用来指派特定的CPU或GPU。

本文源码的GitHub地址,位于multi_gpu_train文件夹。

Cuda

查看当前服务器,满足TensorFlow的GPU数。

def get_available_gpus():
    """
    查看GPU的命令:nvidia-smi
    查看被占用的情况:ps aux | grep PID
    :return: GPU个数
    """
    local_device_protos = device_lib.list_local_devices()
    print "all: %s" % [x.name for x in local_device_protos]
    print "gpu: %s" % [x.name for x in local_device_protos if x.device_type == 'GPU']

默认的TensorFlow库,无法显示,需要下载TensorFlow的GPU版本。

pip install --upgrade tensorflow-gpu==1.2 -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com

查看GPU的库是否导入

echo $LD_LIBRARY_PATH

查看服务器的GPU

nvidia-smi

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 375.20                 Driver Version: 375.20                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla K40m          Off  | 0000:04:00.0     Off |                    0 |
| N/A   29C    P0    68W / 235W |      0MiB / 11471MiB |     85%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+

tensorflow-gpu==1.3.0报错,无法找到libcudnn.so.6,回退版本1.2即可。

ImportError: libcudnn.so.6: cannot open shared object file: No such file or directory

如果缺少libcudnn库,则登录Nvidia的官网下载cuDNN库,网址

cuDNN

最终显示设备

all: [u'/cpu:0', u'/gpu:0']
gpu: [u'/gpu:0']

显示tensorboard

tensorboard --logdir=/tmp/cifar10_train --port=8008

源码

使用tf.gfile模块,处理文件夹,执行核心方法train()。

def main(argv=None):  # pylint: disable=unused-argument
    cifar10.maybe_download_and_extract()  # 下载数据

    # 目录处理的标准流程,使用tf.gfile模块
    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()

创建global_step,训练步数,在训练时,自动增加,名称是global_step,shape是[],表示常数,初始值是0,非训练参数。

def train():
    """Train CIFAR-10 for a number of steps."""
    with tf.Graph().as_default(), tf.device('/cpu:0'):  # 默认使用默认CPU0
        # 参数: trainable是False,不用训练,全局步数就是global_step,默认设置。
        global_step = tf.get_variable(
            'global_step', [],
            initializer=tf.constant_initializer(0), trainable=False)

        # 每个批次的训练数,
        num_batches_per_epoch = (cifar10.NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN /
                                 FLAGS.batch_size)  # batch_size是128,50000 / 128=390.625
        decay_steps = int(num_batches_per_epoch * cifar10.NUM_EPOCHS_PER_DECAY)  # 每个批次需要衰减的次数

        lr = tf.train.exponential_decay(cifar10.INITIAL_LEARNING_RATE,
                                        global_step,
                                        decay_steps,
                                        cifar10.LEARNING_RATE_DECAY_FACTOR,
                                        staircase=True)  # 计算学习率,lr=Learning Rate

        opt = tf.train.GradientDescentOptimizer(lr)  # 参数是学习率

使用预加载队列,获取batch_queue

# 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)  # 使用预加载的队列

多个GPU执行,当GPU不足时,有几个执行几个。将全部梯度放置于tower_gradsreuse_variables()重用变量,使用summaries获取scope变量的数据。

tower_grads = []
with tf.variable_scope(tf.get_variable_scope()):  # 变量的名称
    for i in xrange(FLAGS.num_gpus):  # 创建GUP的循环
        with tf.device('/gpu:%d' % i):  # 指定GPU
            with tf.name_scope('%s_%d' % (cifar10.TOWER_NAME, i)) as scope:
                # 含有几个GPU执行几个,没有不执行
                print('running: %s_%d' % (cifar10.TOWER_NAME, i))
                # Dequeues one batch for the GPU
                image_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)  # 添加梯度,tower_grads是外部变量,会存储全部梯度信息

求平均的梯度,优化器opt使用梯度的平均值,存储输入进入summaries。

# 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))

求变量的均值操作

variable_averages = tf.train.ExponentialMovingAverage(
    cifar10.MOVING_AVERAGE_DECAY, global_step)  # 求变量的均值
variables_averages_op = variable_averages.apply(tf.trainable_variables())  # 将变量的均值应用于操作

训练操作,summary操作

# 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)  # 写入summary的地址

每10次显示一次,每100次总结一次,每1000次保存一次;

for step in xrange(FLAGS.max_steps):
    start_time = time.time()
    _, loss_value = sess.run([train_op, loss])
    duration = time.time() - start_time

    assert not np.isnan(loss_value), 'Model diverged with loss = NaN'

    if step % 10 == 0:
        num_examples_per_step = FLAGS.batch_size * FLAGS.num_gpus
        examples_per_sec = num_examples_per_step / duration
        sec_per_batch = duration / FLAGS.num_gpus

        format_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)

核心就是通过多CPU训练梯度,并且求平均梯度和平均均值。TensorBoard的效果

GPU

OK, that's all!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,012评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,589评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,819评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,652评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,954评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,381评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,687评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,404评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,082评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,355评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,880评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,249评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,864评论 3 232
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,007评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,760评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,394评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,281评论 2 259

推荐阅读更多精彩内容