cifar10_multi_gpu_train.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """A binary to train CIFAR-10 using multiple GPU's with synchronous updates.
  16. Accuracy:
  17. cifar10_multi_gpu_train.py achieves ~86% accuracy after 100K steps (256
  18. epochs of data) as judged by cifar10_eval.py.
  19. Speed: With batch_size 128.
  20. System | Step Time (sec/batch) | Accuracy
  21. --------------------------------------------------------------------
  22. 1 Tesla K20m | 0.35-0.60 | ~86% at 60K steps (5 hours)
  23. 1 Tesla K40m | 0.25-0.35 | ~86% at 100K steps (4 hours)
  24. 2 Tesla K20m | 0.13-0.20 | ~84% at 30K steps (2.5 hours)
  25. 3 Tesla K20m | 0.13-0.18 | ~84% at 30K steps
  26. 4 Tesla K20m | ~0.10 | ~84% at 30K steps
  27. Usage:
  28. Please see the tutorial and website for how to download the CIFAR-10
  29. data set, compile the program and train the model.
  30. http://tensorflow.org/tutorials/deep_cnn/
  31. """
  32. from __future__ import absolute_import
  33. from __future__ import division
  34. from __future__ import print_function
  35. from datetime import datetime
  36. import os.path
  37. import re
  38. import time
  39. import numpy as np
  40. from six.moves import xrange # pylint: disable=redefined-builtin
  41. import tensorflow as tf
  42. import cifar10
  43. FLAGS = tf.app.flags.FLAGS
  44. tf.app.flags.DEFINE_string('train_dir', '/tmp/cifar10_train',
  45. """Directory where to write event logs """
  46. """and checkpoint.""")
  47. tf.app.flags.DEFINE_integer('max_steps', 1000000,
  48. """Number of batches to run.""")
  49. tf.app.flags.DEFINE_integer('num_gpus', 1,
  50. """How many GPUs to use.""")
  51. tf.app.flags.DEFINE_boolean('log_device_placement', False,
  52. """Whether to log device placement.""")
  53. def tower_loss(scope):
  54. """Calculate the total loss on a single tower running the CIFAR model.
  55. Args:
  56. scope: unique prefix string identifying the CIFAR tower, e.g. 'tower_0'
  57. Returns:
  58. Tensor of shape [] containing the total loss for a batch of data
  59. """
  60. # Get images and labels for CIFAR-10.
  61. images, labels = cifar10.distorted_inputs()
  62. # Build inference Graph.
  63. logits = cifar10.inference(images)
  64. # Build the portion of the Graph calculating the losses. Note that we will
  65. # assemble the total_loss using a custom function below.
  66. _ = cifar10.loss(logits, labels)
  67. # Assemble all of the losses for the current tower only.
  68. losses = tf.get_collection('losses', scope)
  69. # Calculate the total loss for the current tower.
  70. total_loss = tf.add_n(losses, name='total_loss')
  71. # Attach a scalar summary to all individual losses and the total loss; do the
  72. # same for the averaged version of the losses.
  73. for l in losses + [total_loss]:
  74. # Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training
  75. # session. This helps the clarity of presentation on tensorboard.
  76. loss_name = re.sub('%s_[0-9]*/' % cifar10.TOWER_NAME, '', l.op.name)
  77. tf.summary.scalar(loss_name, l)
  78. return total_loss
  79. def average_gradients(tower_grads):
  80. """Calculate the average gradient for each shared variable across all towers.
  81. Note that this function provides a synchronization point across all towers.
  82. Args:
  83. tower_grads: List of lists of (gradient, variable) tuples. The outer list
  84. is over individual gradients. The inner list is over the gradient
  85. calculation for each tower.
  86. Returns:
  87. List of pairs of (gradient, variable) where the gradient has been averaged
  88. across all towers.
  89. """
  90. average_grads = []
  91. for grad_and_vars in zip(*tower_grads):
  92. # Note that each grad_and_vars looks like the following:
  93. # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))
  94. grads = []
  95. for g, _ in grad_and_vars:
  96. # Add 0 dimension to the gradients to represent the tower.
  97. expanded_g = tf.expand_dims(g, 0)
  98. # Append on a 'tower' dimension which we will average over below.
  99. grads.append(expanded_g)
  100. # Average over the 'tower' dimension.
  101. grad = tf.concat(axis=grads, values=0)
  102. grad = tf.reduce_mean(grad, 0)
  103. # Keep in mind that the Variables are redundant because they are shared
  104. # across towers. So .. we will just return the first tower's pointer to
  105. # the Variable.
  106. v = grad_and_vars[0][1]
  107. grad_and_var = (grad, v)
  108. average_grads.append(grad_and_var)
  109. return average_grads
  110. def train():
  111. """Train CIFAR-10 for a number of steps."""
  112. with tf.Graph().as_default(), tf.device('/cpu:0'):
  113. # Create a variable to count the number of train() calls. This equals the
  114. # number of batches processed * FLAGS.num_gpus.
  115. global_step = tf.get_variable(
  116. 'global_step', [],
  117. initializer=tf.constant_initializer(0), trainable=False)
  118. # Calculate the learning rate schedule.
  119. num_batches_per_epoch = (cifar10.NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN /
  120. FLAGS.batch_size)
  121. decay_steps = int(num_batches_per_epoch * cifar10.NUM_EPOCHS_PER_DECAY)
  122. # Decay the learning rate exponentially based on the number of steps.
  123. lr = tf.train.exponential_decay(cifar10.INITIAL_LEARNING_RATE,
  124. global_step,
  125. decay_steps,
  126. cifar10.LEARNING_RATE_DECAY_FACTOR,
  127. staircase=True)
  128. # Create an optimizer that performs gradient descent.
  129. opt = tf.train.GradientDescentOptimizer(lr)
  130. # Calculate the gradients for each model tower.
  131. tower_grads = []
  132. with tf.variable_scope(tf.get_variable_scope()):
  133. for i in xrange(FLAGS.num_gpus):
  134. with tf.device('/gpu:%d' % i):
  135. with tf.name_scope('%s_%d' % (cifar10.TOWER_NAME, i)) as scope:
  136. # Calculate the loss for one tower of the CIFAR model. This function
  137. # constructs the entire CIFAR model but shares the variables across
  138. # all towers.
  139. loss = tower_loss(scope)
  140. # Reuse variables for the next tower.
  141. tf.get_variable_scope().reuse_variables()
  142. # Retain the summaries from the final tower.
  143. summaries = tf.get_collection(tf.GraphKeys.SUMMARIES, scope)
  144. # Calculate the gradients for the batch of data on this CIFAR tower.
  145. grads = opt.compute_gradients(loss)
  146. # Keep track of the gradients across all towers.
  147. tower_grads.append(grads)
  148. # We must calculate the mean of each gradient. Note that this is the
  149. # synchronization point across all towers.
  150. grads = average_gradients(tower_grads)
  151. # Add a summary to track the learning rate.
  152. summaries.append(tf.summary.scalar('learning_rate', lr))
  153. # Add histograms for gradients.
  154. for grad, var in grads:
  155. if grad is not None:
  156. summaries.append(tf.summary.histogram(var.op.name + '/gradients', grad))
  157. # Apply the gradients to adjust the shared variables.
  158. apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)
  159. # Add histograms for trainable variables.
  160. for var in tf.trainable_variables():
  161. summaries.append(tf.summary.histogram(var.op.name, var))
  162. # Track the moving averages of all trainable variables.
  163. variable_averages = tf.train.ExponentialMovingAverage(
  164. cifar10.MOVING_AVERAGE_DECAY, global_step)
  165. variables_averages_op = variable_averages.apply(tf.trainable_variables())
  166. # Group all updates to into a single train op.
  167. train_op = tf.group(apply_gradient_op, variables_averages_op)
  168. # Create a saver.
  169. saver = tf.train.Saver(tf.global_variables())
  170. # Build the summary operation from the last tower summaries.
  171. summary_op = tf.summary.merge(summaries)
  172. # Build an initialization operation to run below.
  173. init = tf.global_variables_initializer()
  174. # Start running operations on the Graph. allow_soft_placement must be set to
  175. # True to build towers on GPU, as some of the ops do not have GPU
  176. # implementations.
  177. sess = tf.Session(config=tf.ConfigProto(
  178. allow_soft_placement=True,
  179. log_device_placement=FLAGS.log_device_placement))
  180. sess.run(init)
  181. # Start the queue runners.
  182. tf.train.start_queue_runners(sess=sess)
  183. summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph)
  184. for step in xrange(FLAGS.max_steps):
  185. start_time = time.time()
  186. _, loss_value = sess.run([train_op, loss])
  187. duration = time.time() - start_time
  188. assert not np.isnan(loss_value), 'Model diverged with loss = NaN'
  189. if step % 10 == 0:
  190. num_examples_per_step = FLAGS.batch_size * FLAGS.num_gpus
  191. examples_per_sec = num_examples_per_step / duration
  192. sec_per_batch = duration / FLAGS.num_gpus
  193. format_str = ('%s: step %d, loss = %.2f (%.1f examples/sec; %.3f '
  194. 'sec/batch)')
  195. print (format_str % (datetime.now(), step, loss_value,
  196. examples_per_sec, sec_per_batch))
  197. if step % 100 == 0:
  198. summary_str = sess.run(summary_op)
  199. summary_writer.add_summary(summary_str, step)
  200. # Save the model checkpoint periodically.
  201. if step % 1000 == 0 or (step + 1) == FLAGS.max_steps:
  202. checkpoint_path = os.path.join(FLAGS.train_dir, 'model.ckpt')
  203. saver.save(sess, checkpoint_path, global_step=step)
  204. def main(argv=None): # pylint: disable=unused-argument
  205. cifar10.maybe_download_and_extract()
  206. if tf.gfile.Exists(FLAGS.train_dir):
  207. tf.gfile.DeleteRecursively(FLAGS.train_dir)
  208. tf.gfile.MakeDirs(FLAGS.train_dir)
  209. train()
  210. if __name__ == '__main__':
  211. tf.app.run()