【问题标题】:Distributed Tensorflow: good example for synchronous training on CPUs分布式 Tensorflow:在 CPU 上同步训练的好例子
【发布时间】:2017-05-08 16:40:45
【问题描述】:

我是分布式 tensorflow 的新手,正在寻找一个在 CPU 上执行同步训练的好例子。

我已经尝试过Distributed Tensorflow Example,它可以在 1 台参数服务器(1 台机器,1 个 CPU)和 3 个工作人员(每个工作人员 = 1 台机器,1 个 CPU)上成功执行异步训练。但是,当涉及到同步训练时,我无法正确运行它,虽然我已经按照教程 SyncReplicasOptimizer(V1.0 and V2.0)

我已将官方 SyncReplicasOptimizer 代码插入到工作异步训练示例中,但训练过程仍然是异步的。我的详细代码如下。任何与同步训练相关的代码都在******块内。

import tensorflow as tf
import sys
import time

# cluster specification ----------------------------------------------------------------------
parameter_servers = ["xx1.edu:2222"]
workers = ["xx2.edu:2222", "xx3.edu:2222", "xx4.edu:2222"]
cluster = tf.train.ClusterSpec({"ps":parameter_servers, "worker":workers})

# input flags
tf.app.flags.DEFINE_string("job_name", "", "Either 'ps' or 'worker'")
tf.app.flags.DEFINE_integer("task_index", 0, "Index of task within the job")
FLAGS = tf.app.flags.FLAGS

# start a server for a specific task
server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index)

# Parameters  ----------------------------------------------------------------------
N = 3 # number of replicas
learning_rate = 0.001
training_epochs = int(21/N)
batch_size = 100

# Network Parameters
n_input = 784 # MNIST data input (img shape: 28*28)
n_hidden_1 = 256 # 1st layer number of features
n_hidden_2 = 256 # 2nd layer number of features
n_classes = 10 # MNIST total classes (0-9 digits)

if FLAGS.job_name == "ps":
    server.join()
    print("--- Parameter Server Ready ---")
elif FLAGS.job_name == "worker":
    # Import MNIST data
    from tensorflow.examples.tutorials.mnist import input_data
    mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
    # Between-graph replication
    with tf.device(tf.train.replica_device_setter(
        worker_device="/job:worker/task:%d" % FLAGS.task_index,
        cluster=cluster)):
        # count the number of updates
        global_step = tf.get_variable('global_step', [], 
                                      initializer = tf.constant_initializer(0), 
                                      trainable = False,
                                      dtype = tf.int32)
        # tf Graph input
        x = tf.placeholder("float", [None, n_input])
        y = tf.placeholder("float", [None, n_classes])

        # Create model
        def multilayer_perceptron(x, weights, biases):
            # Hidden layer with RELU activation
            layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
            layer_1 = tf.nn.relu(layer_1)
            # Hidden layer with RELU activation
            layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
            layer_2 = tf.nn.relu(layer_2)
            # Output layer with linear activation
            out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
            return out_layer

        # Store layers weight & bias
        weights = {
            'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
            'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
            'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
        }
        biases = {
            'b1': tf.Variable(tf.random_normal([n_hidden_1])),
            'b2': tf.Variable(tf.random_normal([n_hidden_2])),
            'out': tf.Variable(tf.random_normal([n_classes]))
        }

        # Construct model
        pred = multilayer_perceptron(x, weights, biases)

        # Define loss and optimizer
        cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))

        # ************************* SyncReplicasOpt Version 1.0 *****************************************************
        ''' This optimizer collects gradients from all replicas, "summing" them, 
        then applying them to the variables in one shot, after which replicas can fetch the new variables and continue. '''
        # Create any optimizer to update the variables, say a simple SGD
        opt = tf.train.AdamOptimizer(learning_rate=learning_rate)

        # Wrap the optimizer with sync_replicas_optimizer with N replicas: at each step the optimizer collects N gradients before applying to variables.
        opt = tf.train.SyncReplicasOptimizer(opt, replicas_to_aggregate=N,
                                        replica_id=FLAGS.task_index, total_num_replicas=N)

        # Now you can call `minimize()` or `compute_gradients()` and `apply_gradients()` normally
        train = opt.minimize(cost, global_step=global_step)

        # You can now call get_init_tokens_op() and get_chief_queue_runner().
        # Note that get_init_tokens_op() must be called before creating session
        # because it modifies the graph.
        init_token_op = opt.get_init_tokens_op()
        chief_queue_runner = opt.get_chief_queue_runner()
        # **************************************************************************************

        # Test model
        correct = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct, "float"))

        # Initializing the variables
        init_op = tf.initialize_all_variables()
        print("---Variables initialized---")

    # **************************************************************************************
    is_chief = (FLAGS.task_index == 0)
    # Create a "supervisor", which oversees the training process.
    sv = tf.train.Supervisor(is_chief=is_chief,
                             logdir="/tmp/train_logs",
                             init_op=init_op,
                             global_step=global_step,
                             save_model_secs=600)
    # **************************************************************************************

    with sv.prepare_or_wait_for_session(server.target) as sess:
        # **************************************************************************************        
        # After the session is created by the Supervisor and before the main while loop:
        if is_chief:
            sv.start_queue_runners(sess, [chief_queue_runner])
            # Insert initial tokens to the queue.
            sess.run(init_token_op)
        # **************************************************************************************
        # Statistics
        net_train_t = 0
        # Training
        for epoch in range(training_epochs):
            total_batch = int(mnist.train.num_examples/batch_size)
            # Loop over all batches
            for i in range(total_batch):
                batch_x, batch_y = mnist.train.next_batch(batch_size)
                # ======== net training time ========
                begin_t = time.time()
                sess.run(train, feed_dict={x: batch_x, y: batch_y})
                end_t = time.time()
                net_train_t += (end_t - begin_t)
                # ===================================
            # Calculate training accuracy
            # acc = sess.run(accuracy, feed_dict={x: mnist.train.images, y: mnist.train.labels})
            # print("Epoch:", '%04d' % (epoch+1), " Train Accuracy =", acc)
            print("Epoch:", '%04d' % (epoch+1))
        print("Training Finished!")
        print("Net Training Time: ", net_train_t, "second")
        # Testing
        print("Testing Accuracy = ", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

    sv.stop()
    print("done")

我的代码有什么问题吗?或者我可以举一个好榜样吗?

【问题讨论】:

  • 代码表面上看起来是正确的,但是tf.train.SyncReplicasOptimizer的接口相当复杂,所以可能还是有bug。当您说“训练过程仍然是异步的”时,您是如何观察到这一点的?
  • 感谢您的回复,@mrry。在理想的同步训练中,我们希望看到“Epoch #i”在每个工人身上几乎同时打印出来,但我观察到的是:工人 0 上的“Epoch 1”--(3 分钟后)-->“工人 1 上的“时代 1”--(3 分钟后)--> 工人 2 上的“时代 1”--(3 分钟后)--> 工人 0 上的“时代 2”--(3 分钟后)-->工人 1 上的“时代 2”--(3 分钟后)--> 工人 2 上的“时代 2”--(3 分钟后)--> 工人 0 上的“时代 3” .... 循环直到结束。那么张量流同步训练到底发生了什么?为什么会有一个有序的epoch训练?
  • 我也很好奇这个。我想知道有时一个 CPU 是否会落后,它会从一个 CPU 聚合两个批次并让其他 CPU 之一落后。
  • @leonardo_zz 你有运气解决这个问题吗?
  • @volatile 不。对此感到抱歉。

标签: tensorflow distributed synchronous


【解决方案1】:

一个问题是你需要在最小化方法中指定一个aggregation_method,让它同步运行,

train = opt.minimize(cost, global_step=global_step, aggregation_method=tf.AggregationMethod.ADD_N)

【讨论】:

    【解决方案2】:

    我认为您的问题可以作为 tensorflow 的 issue #9596 中的 cmets 来回答。 这个问题是由新版本的 tf.train.SyncReplicasOptimizer() 的 bug 引起的。您可以使用该 API 的旧版本来避免此问题。

    另一个解决方案来自Tensorflow Distributed Benchmarks。看一下源码,可以发现他们是通过tensorflow中的队列手动同步worker的。通过实验,该基准测试完全符合您的预期。

    希望这些 cmets 和资源可以帮助您解决问题。谢谢!

    【讨论】:

      【解决方案3】:

      我不确定您是否会对在后端使用 MPI 的用户透明分布式张量流感兴趣。我们最近使用 MaTEx 开发了一个这样的版本:https://github.com/matex-org/matex

      因此,对于分布式 TensorFlow,您不需要编写 SyncReplicaOptimizer 代码,因为所有更改都是从用户那里抽象出来的。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-26
        • 2017-03-30
        • 2021-01-08
        • 1970-01-01
        • 2020-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多