2016-12-23 5 views
8

저는 분산 텐서 흐름을 처음 사용하며 CPU에서 동기식 교육을 수행하는 좋은 예를 찾고 있습니다.Distributed Tensorflow : CPU의 동기식 교육에 대한 좋은 예

나는 이미 Distributed Tensorflow Example을 시도했으며 1 개의 매개 변수 서버 (1 개의 CPU가있는 1 대의 컴퓨터)와 3 명의 작업자 (각 작업자 = 1 개의 CPU가있는 1 대의 컴퓨터)에서 성공적으로 비동기 교육을 수행 할 수 있습니다. 그러나 동기 훈련에 관해서는 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") 

내 코드에 문제가 있습니까? 아니면 내가 따라야 할 좋은 모범이 될 수 있는가?

+0

코드는 피상적으로 올바른 보이는, 당신이 동 기적으로 실행하는 데 최소화 방법에 aggregation_method를 지정해야한다는 것입니다,하지만'tf.train.SyncReplicasOptimizer' 인터페이스는 매우 복잡하다, 그래서 여전히 버그가있을 수 있습니다. "훈련 과정이 여전히 비동기"라고 말하면 어떻게 관찰 했습니까? – mrry

+0

답장을 보내 주셔서 감사합니다. @mrry. 이상적인 syn-training에서 우리는 "Epoch #i"가 모든 근로자에게 같은 시간에 거의 동시에 인쇄 될 것이라고 기대하지만, 내가 관찰 한 것은 근로자 0의 "Epoch 1"(3 분 후) 작업자 1 - (3 분 후) -> 작업자 2의 "에포크 1"- 작업자 3의 "에포크 2"-> (3 분 후) -> 작업자 1의 "Epoch 2"- 작업자 0의 "Epoch 2"- 작업자 0의 "Epoch 3"-> 종료 3 분 후 (3 분 후) -> 루프. 그렇다면 tensorflow syn-training에서 정확히 무엇이 진행되고 있습니까? 주문 신기원 훈련이있는 이유는 무엇입니까? –

+0

나는 이것에 대해서도 궁금합니다. 때로는 하나의 CPU가 뒤질 수 있고 한 CPU에서 두 개의 일괄 처리를 집계하여 다른 CPU 중 하나가 뒤질 수 있는지 궁금합니다. – Aaron

답변

0

백엔드에서 MPI를 사용하는 사용자 투명 분산 텐서 흐름에 관심이 있는지 확실하지 않습니다. 우리는 최근에 MaTEx로 이러한 버전을 개발했습니다 : https://github.com/matex-org/matex.

따라서 분산 된 TensorFlow의 경우 모든 변경 사항이 사용자로부터 추출되므로 SyncReplicaOptimizer 코드를 작성할 필요가 없습니다.

희망이 도움이됩니다.

0

나는 귀하의 질문에 텐서 흐름의 문제 #9596의 의견으로 대답 할 수 있다고 생각합니다. 이 문제는 새 버전의 tf.train.SyncReplicasOptimizer() 버그로 인해 발생합니다. 이 API의 이전 버전을 사용하면이 문제를 피할 수 있습니다.

다른 해결책은 Tensorflow Distributed Benchmarks입니다. 소스 코드를 살펴보면 텐서 흐름의 대기열을 통해 수동으로 작업자를 동기화한다는 것을 알 수 있습니다. 실험을 통해이 벤치 마크는 예상대로 정확하게 실행됩니다.

이 주석과 리소스가 문제를 해결하는 데 도움이되기를 바랍니다. 감사!

0

한 가지 문제가

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