TensorFlow 2.0 Beta is available Learn more

Distributed training in TensorFlow

View on TensorFlow.org Run in Google Colab View source on GitHub

Overview

The tf.distribute.Strategy API provides an abstraction for distributing your training across multiple processing units. The goal is to allow users to enable distributed training using existing models and training code, with minimal changes.

This tutorial uses the tf.distribute.MirroredStrategy, which does in-graph replication with synchronous training on many GPUs on one machine. Essentially, it copies all of the model's variables to each processor. Then, it uses all-reduce to combine the gradients from all processors and applies the combined value to all copies of the model.

MirroredStategy is one of several distribution strategy available in TensorFlow core. You can read about more strategies at distribution strategy guide.

Keras API

This example uses the tf.keras API to build the model and training loop. For custom training loops, see this tutorial.

Import Dependencies

from __future__ import absolute_import, division, print_function, unicode_literals
# Import TensorFlow
!pip install -q tf-nightly-gpu
import tensorflow as tf
import tensorflow_datasets as tfds

import os

Download the dataset

Download the MNIST dataset and load it from TensorFlow Datasets. This returns a dataset in tf.data format.

Setting with_info to True includes the metadata for the entire dataset, which is being saved here to ds_info. Among other things, this metadata object includes the number of train and test examples.

datasets, ds_info = tfds.load(name='mnist', with_info=True, as_supervised=True)
mnist_train, mnist_test = datasets['train'], datasets['test']
Downloading and preparing dataset mnist (11.06 MiB) to /home/kbuilder/tensorflow_datasets/mnist/1.0.0...

HBox(children=(IntProgress(value=1, bar_style='info', description='Dl Completed...', max=1, style=ProgressStyl…
HBox(children=(IntProgress(value=1, bar_style='info', description='Dl Size...', max=1, style=ProgressStyle(des…
HBox(children=(IntProgress(value=1, bar_style='info', description='Extraction completed...', max=1, style=Prog…
/home/kbuilder/.local/lib/python3.5/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
/home/kbuilder/.local/lib/python3.5/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
/home/kbuilder/.local/lib/python3.5/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
/home/kbuilder/.local/lib/python3.5/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)






HBox(children=(IntProgress(value=1, bar_style='info', max=1), HTML(value='')))


HBox(children=(IntProgress(value=0, description='Shuffling...', max=10, style=ProgressStyle(description_width=…
WARNING: Logging before flag parsing goes to stderr.
W0625 16:41:58.259716 140073879688960 deprecation.py:323] From /home/kbuilder/.local/lib/python3.5/site-packages/tensorflow_datasets/core/file_format_adapter.py:209: tf_record_iterator (from tensorflow.python.lib.io.tf_record) is deprecated and will be removed in a future version.
Instructions for updating:
Use eager execution and: 
`tf.data.TFRecordDataset(path)`

HBox(children=(IntProgress(value=1, bar_style='info', description='Reading...', max=1, style=ProgressStyle(des…
HBox(children=(IntProgress(value=0, description='Writing...', max=6000, style=ProgressStyle(description_width=…
HBox(children=(IntProgress(value=1, bar_style='info', description='Reading...', max=1, style=ProgressStyle(des…
HBox(children=(IntProgress(value=0, description='Writing...', max=6000, style=ProgressStyle(description_width=…
HBox(children=(IntProgress(value=1, bar_style='info', description='Reading...', max=1, style=ProgressStyle(des…
HBox(children=(IntProgress(value=0, description='Writing...', max=6000, style=ProgressStyle(description_width=…
HBox(children=(IntProgress(value=1, bar_style='info', description='Reading...', max=1, style=ProgressStyle(des…
HBox(children=(IntProgress(value=0, description='Writing...', max=6000, style=ProgressStyle(description_width=…
HBox(children=(IntProgress(value=1, bar_style='info', description='Reading...', max=1, style=ProgressStyle(des…
HBox(children=(IntProgress(value=0, description='Writing...', max=6000, style=ProgressStyle(description_width=…
HBox(children=(IntProgress(value=1, bar_style='info', description='Reading...', max=1, style=ProgressStyle(des…
HBox(children=(IntProgress(value=0, description='Writing...', max=6000, style=ProgressStyle(description_width=…
HBox(children=(IntProgress(value=1, bar_style='info', description='Reading...', max=1, style=ProgressStyle(des…
HBox(children=(IntProgress(value=0, description='Writing...', max=6000, style=ProgressStyle(description_width=…
HBox(children=(IntProgress(value=1, bar_style='info', description='Reading...', max=1, style=ProgressStyle(des…
HBox(children=(IntProgress(value=0, description='Writing...', max=6000, style=ProgressStyle(description_width=…
HBox(children=(IntProgress(value=1, bar_style='info', description='Reading...', max=1, style=ProgressStyle(des…
HBox(children=(IntProgress(value=0, description='Writing...', max=6000, style=ProgressStyle(description_width=…
HBox(children=(IntProgress(value=1, bar_style='info', description='Reading...', max=1, style=ProgressStyle(des…
HBox(children=(IntProgress(value=0, description='Writing...', max=6000, style=ProgressStyle(description_width=…


HBox(children=(IntProgress(value=1, bar_style='info', max=1), HTML(value='')))


HBox(children=(IntProgress(value=0, description='Shuffling...', max=1, style=ProgressStyle(description_width='…
HBox(children=(IntProgress(value=1, bar_style='info', description='Reading...', max=1, style=ProgressStyle(des…
HBox(children=(IntProgress(value=0, description='Writing...', max=10000, style=ProgressStyle(description_width…
Dataset mnist downloaded and prepared to /home/kbuilder/tensorflow_datasets/mnist/1.0.0. Subsequent calls will reuse this data.

Define Distribution Strategy

Create a MirroredStrategy object. This will handle distribution, and provides a context manager (tf.distribute.MirroredStrategy.scope) to build your model inside.

strategy = tf.distribute.MirroredStrategy()
print ('Number of devices: {}'.format(strategy.num_replicas_in_sync))
Number of devices: 1

Setup Input pipeline

If a model is trained on multiple GPUs, the batch size should be increased accordingly so as to make effective use of the extra computing power. Moreover, the learning rate should be tuned accordingly.

# You can also do ds_info.splits.total_num_examples to get the total
# number of examples in the dataset.

num_train_examples = ds_info.splits['train'].num_examples
num_test_examples = ds_info.splits['test'].num_examples

BUFFER_SIZE = 10000

BATCH_SIZE_PER_REPLICA = 64
BATCH_SIZE = BATCH_SIZE_PER_REPLICA * strategy.num_replicas_in_sync

Pixel values, which are 0-255, have to be normalized to the 0-1 range. Define this scale in a function.

def scale(image, label):
  image = tf.cast(image, tf.float32)
  image /= 255

  return image, label

Apply this function to the training and test data, shuffle the training data, and batch it for training.

train_dataset = mnist_train.map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
eval_dataset = mnist_test.map(scale).batch(BATCH_SIZE)
W0625 16:42:07.999913 140073879688960 deprecation_wrapper.py:118] From /tmpfs/src/tf_docs_env/lib/python3.5/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/__init__.py:10: The name tf.estimator.inputs is deprecated. Please use tf.compat.v1.estimator.inputs instead.

Create the model

Create and compile the Keras model in the context of strategy.scope.

with strategy.scope():
  model = tf.keras.Sequential([
      tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(28, 28, 1)),
      tf.keras.layers.MaxPooling2D(),
      tf.keras.layers.Flatten(),
      tf.keras.layers.Dense(64, activation='relu'),
      tf.keras.layers.Dense(10, activation='softmax')
  ])

  model.compile(loss='sparse_categorical_crossentropy',
                optimizer=tf.keras.optimizers.Adam(),
                metrics=['accuracy'])
W0625 16:42:08.103205 140073879688960 deprecation.py:506] From /tmpfs/src/tf_docs_env/lib/python3.5/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1624: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.

Define the callbacks.

The callbacks used here are:

  • Tensorboard: This callback writes a log for Tensorboard which allows you to visualize the graphs.
  • Model Checkpoint: This callback saves the model after every epoch.
  • Learning Rate Scheduler: Using this callback, you can schedule the learning rate to change after every epoch/batch.

For illustrative purposes, add a print callback to display the learning rate in the notebook.

# Define the checkpoint directory to store the checkpoints

checkpoint_dir = './training_checkpoints'
# Name of the checkpoint files
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}")
# Function for decaying the learning rate.
# You can define any decay function you need.
def decay(epoch):
  if epoch < 3:
    return 1e-3
  elif epoch >= 3 and epoch < 7:
    return 1e-4
  else:
    return 1e-5
# Callback for printing the LR at the end of each epoch.
class PrintLR(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs=None):
    print ('\nLearning rate for epoch {} is {}'.format(
        epoch + 1, tf.keras.backend.get_value(model.optimizer.lr)))
callbacks = [
    tf.keras.callbacks.TensorBoard(log_dir='./logs'),
    tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_prefix,
                                       save_weights_only=True),
    tf.keras.callbacks.LearningRateScheduler(decay),
    PrintLR()
]

Train and evaluate

Now, train the model in the usual way, calling fit on the model and passing in the dataset created at the beginning of the tutorial. This step is the same whether you are distributing the training or not.

model.fit(train_dataset, epochs=10, callbacks=callbacks)
W0625 16:42:10.020223 140073879688960 deprecation.py:323] From /tmpfs/src/tf_docs_env/lib/python3.5/site-packages/tensorflow_core/python/keras/optimizer_v2/optimizer_v2.py:460: BaseResourceVariable.constraint (from tensorflow.python.ops.resource_variable_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Apply a constraint manually following the optimizer update step.

Train on None steps
Epoch 1/10
    938/Unknown - 10s 11ms/step - loss: 0.1864 - acc: 0.9485
Learning rate for epoch 1 is 0.0010000000474974513
938/938 [==============================] - 10s 11ms/step - loss: 0.1864 - acc: 0.9485
Epoch 2/10
929/938 [============================>.] - ETA: 0s - loss: 0.0633 - acc: 0.9809
Learning rate for epoch 2 is 0.0010000000474974513
938/938 [==============================] - 8s 9ms/step - loss: 0.0632 - acc: 0.9809
Epoch 3/10
937/938 [============================>.] - ETA: 0s - loss: 0.0438 - acc: 0.9867
Learning rate for epoch 3 is 0.0010000000474974513
938/938 [==============================] - 8s 8ms/step - loss: 0.0438 - acc: 0.9867
Epoch 4/10
929/938 [============================>.] - ETA: 0s - loss: 0.0236 - acc: 0.9936
Learning rate for epoch 4 is 9.999999747378752e-05
938/938 [==============================] - 8s 9ms/step - loss: 0.0236 - acc: 0.9936
Epoch 5/10
919/938 [============================>.] - ETA: 0s - loss: 0.0200 - acc: 0.9950
Learning rate for epoch 5 is 9.999999747378752e-05
938/938 [==============================] - 8s 8ms/step - loss: 0.0200 - acc: 0.9949
Epoch 6/10
937/938 [============================>.] - ETA: 0s - loss: 0.0180 - acc: 0.9956
Learning rate for epoch 6 is 9.999999747378752e-05
938/938 [==============================] - 7s 8ms/step - loss: 0.0180 - acc: 0.9956
Epoch 7/10
931/938 [============================>.] - ETA: 0s - loss: 0.0165 - acc: 0.9960
Learning rate for epoch 7 is 9.999999747378752e-05
938/938 [==============================] - 8s 8ms/step - loss: 0.0165 - acc: 0.9960
Epoch 8/10
920/938 [============================>.] - ETA: 0s - loss: 0.0141 - acc: 0.9968
Learning rate for epoch 8 is 9.999999747378752e-06
938/938 [==============================] - 8s 9ms/step - loss: 0.0140 - acc: 0.9969
Epoch 9/10
922/938 [============================>.] - ETA: 0s - loss: 0.0138 - acc: 0.9970
Learning rate for epoch 9 is 9.999999747378752e-06
938/938 [==============================] - 8s 9ms/step - loss: 0.0137 - acc: 0.9970
Epoch 10/10
927/938 [============================>.] - ETA: 0s - loss: 0.0136 - acc: 0.9972
Learning rate for epoch 10 is 9.999999747378752e-06
938/938 [==============================] - 8s 9ms/step - loss: 0.0135 - acc: 0.9971

<tensorflow.python.keras.callbacks.History at 0x7f63c5b422b0>

As you can see below, the checkpoints are getting saved.

# check the checkpoint directory
!ls {checkpoint_dir}
checkpoint           ckpt_5.data-00000-of-00002
ckpt_10.data-00000-of-00002  ckpt_5.data-00001-of-00002
ckpt_10.data-00001-of-00002  ckpt_5.index
ckpt_10.index            ckpt_6.data-00000-of-00002
ckpt_1.data-00000-of-00002   ckpt_6.data-00001-of-00002
ckpt_1.data-00001-of-00002   ckpt_6.index
ckpt_1.index             ckpt_7.data-00000-of-00002
ckpt_2.data-00000-of-00002   ckpt_7.data-00001-of-00002
ckpt_2.data-00001-of-00002   ckpt_7.index
ckpt_2.index             ckpt_8.data-00000-of-00002
ckpt_3.data-00000-of-00002   ckpt_8.data-00001-of-00002
ckpt_3.data-00001-of-00002   ckpt_8.index
ckpt_3.index             ckpt_9.data-00000-of-00002
ckpt_4.data-00000-of-00002   ckpt_9.data-00001-of-00002
ckpt_4.data-00001-of-00002   ckpt_9.index
ckpt_4.index

To see how the model perform, load the latest checkpoint and call evaluate on the test data.

Call evaluate as before using appropriate datasets.

model.load_weights(tf.train.latest_checkpoint(checkpoint_dir))

eval_loss, eval_acc = model.evaluate(eval_dataset)
print ('Eval loss: {}, Eval Accuracy: {}'.format(eval_loss, eval_acc))
    157/Unknown - 2s 12ms/step - loss: 0.0374 - acc: 0.9874Eval loss: 0.0373838818465229, Eval Accuracy: 0.9873999953269958

To see the output, you can download and view the TensorBoard logs at the terminal.

$ tensorboard --logdir=path/to/log-directory
!ls -sh ./logs
total 320K
312K events.out.tfevents.1561480930.kokoro-image-debugging
4.0K events.out.tfevents.1561480933.kokoro-image-debugging.profile-empty
4.0K plugins

Export to SavedModel

If you want to export the graph and the variables, SavedModel is the best way of doing this. The model can be loaded back with or without the scope. Moreover, SavedModel is platform agnostic.

path = 'saved_model/'
tf.keras.experimental.export_saved_model(model, path)
W0625 16:43:39.476302 140073879688960 deprecation.py:323] From <ipython-input-20-7f22af6799f5>:1: export_saved_model (from tensorflow.python.keras.saving.saved_model_experimental) is deprecated and will be removed in a future version.
Instructions for updating:
Please use `model.save(..., save_format="tf")` or `tf.keras.models.save_model(..., save_format="tf")`.
W0625 16:43:39.498160 140073879688960 deprecation.py:506] From /tmpfs/src/tf_docs_env/lib/python3.5/site-packages/tensorflow_core/python/ops/init_ops.py:97: calling GlorotUniform.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
W0625 16:43:39.499724 140073879688960 deprecation.py:506] From /tmpfs/src/tf_docs_env/lib/python3.5/site-packages/tensorflow_core/python/ops/init_ops.py:97: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
W0625 16:43:40.520776 140073879688960 deprecation.py:323] From /tmpfs/src/tf_docs_env/lib/python3.5/site-packages/tensorflow_core/python/saved_model/signature_def_utils_impl.py:253: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.
W0625 16:43:40.522508 140073879688960 export_utils.py:182] Export includes no default signature!
W0625 16:43:40.854406 140073879688960 export_utils.py:182] Export includes no default signature!

Load the model without strategy.scope.

unreplicated_model = tf.keras.experimental.load_from_saved_model(path)

unreplicated_model.compile(
    loss='sparse_categorical_crossentropy',
    optimizer=tf.keras.optimizers.Adam(),
    metrics=['accuracy'])

eval_loss, eval_acc = unreplicated_model.evaluate(eval_dataset)
print ('Eval loss: {}, Eval Accuracy: {}'.format(eval_loss, eval_acc))
W0625 16:43:41.121877 140073879688960 deprecation.py:323] From <ipython-input-21-253c311d7fbe>:1: load_from_saved_model (from tensorflow.python.keras.saving.saved_model_experimental) is deprecated and will be removed in a future version.
Instructions for updating:
The experimental save and load functions have been  deprecated. Please switch to `tf.keras.models.load_model`.

    157/Unknown - 2s 13ms/step - loss: 0.0374 - acc: 0.9874Eval loss: 0.0373838818465229, Eval Accuracy: 0.9873999953269958

What's next?

Read the distribution strategy guide.