<jupyter_start><jupyter_text>Copyright 2019 The TensorFlow Authors.<jupyter_code>#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.<jupyter_output><empty_output><jupyter_text>Distributed training in TensorFlow       View on TensorFlow.org        Run in Google Colab        View source on GitHub    OverviewThe `tf.distribute.Strategy` API provides an abstraction for distributing your trainingacross 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`, whichdoes 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](http://mpitutorial.com/tutorials/mpi-reduce-and-allreduce/) 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](../../guide/distribute_strategy.ipynb).  Keras APIThis example uses the `tf.keras` API to build the model and training loop. For custom training loops, see [this tutorial](training_loops.ipynb).  Import Dependencies<jupyter_code>from __future__ import absolute_import, division, print_function
# Import TensorFlow
!pip install tensorflow-gpu==2.0.0-alpha0 
import tensorflow_datasets as tfds
import tensorflow as tf

import os<jupyter_output><empty_output><jupyter_text>Download the dataset Download the MNIST dataset and load it from [TensorFlow Datasets](https://www.tensorflow.org/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.<jupyter_code>datasets, ds_info = tfds.load(name='mnist', with_info=True, as_supervised=True)
mnist_train, mnist_test = datasets['train'], datasets['test']<jupyter_output><empty_output><jupyter_text>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.<jupyter_code>strategy = tf.distribute.MirroredStrategy()
print ('Number of devices: {}'.format(strategy.num_replicas_in_sync))<jupyter_output><empty_output><jupyter_text>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.<jupyter_code># 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<jupyter_output><empty_output><jupyter_text>Pixel values, which are 0-255, [have to be normalized to the 0-1 range](https://en.wikipedia.org/wiki/Feature_scaling). Define this scale in a function.<jupyter_code>def scale(image, label):
  image = tf.cast(image, tf.float32)
  image /= 255
  
  return image, label<jupyter_output><empty_output><jupyter_text>Apply this function to the training and test data, shuffle the training data, and [batch it for training](https://www.tensorflow.org/api_docs/python/tf/data/Datasetbatch).<jupyter_code>train_dataset = mnist_train.map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
eval_dataset = mnist_test.map(scale).batch(BATCH_SIZE)<jupyter_output><empty_output><jupyter_text>Create the model Create and compile the Keras model in the context of `strategy.scope`.<jupyter_code>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'])<jupyter_output><empty_output><jupyter_text>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.<jupyter_code># 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, 
                                                       model.optimizer.lr.numpy()))
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()
]<jupyter_output><empty_output><jupyter_text>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.<jupyter_code>model.fit(train_dataset, epochs=10, callbacks=callbacks)<jupyter_output><empty_output><jupyter_text>As you can see below, the checkpoints are getting saved.<jupyter_code># check the checkpoint directory
!ls {checkpoint_dir}<jupyter_output><empty_output><jupyter_text>To see how the model perform, load the latest checkpoint and call `evaluate` on the test data.Call `evaluate` as before using appropriate datasets.<jupyter_code>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))<jupyter_output><empty_output><jupyter_text>To see the output, you can download and view the TensorBoard logs at the terminal.```$ tensorboard --logdir=path/to/log-directory```<jupyter_code>!ls -sh ./logs<jupyter_output><empty_output><jupyter_text>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.<jupyter_code>path = 'saved_model/'
tf.keras.experimental.export_saved_model(model, path)<jupyter_output><empty_output><jupyter_text>Load the model without `strategy.scope`.<jupyter_code>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))<jupyter_output><empty_output><jupyter_text>Load the model with `strategy.scope`.<jupyter_code>with strategy.scope():
  replicated_model = tf.keras.experimental.load_from_saved_model(path)
  replicated_model.compile(loss='sparse_categorical_crossentropy',
                           optimizer=tf.keras.optimizers.Adam(),
                           metrics=['accuracy'])

  eval_loss, eval_acc = replicated_model.evaluate(eval_dataset)
  print ('Eval loss: {}, Eval Accuracy: {}'.format(eval_loss, eval_acc))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0911060433295325, 'fraction_numerical': 0.0063854047890535915, 'mean_word_length': 5.2739628040057225, 'pattern_counts': {'":': 0, '<': 67, '<?xml version=': 0, '>': 66, 'https://': 4, 'lorem ipsum': 0, 'www.': 3, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '5928', 'license': 'Apache-2.0', 'n_tokens_mistral': 2651, 'n_tokens_neox': 2534, 'n_words': 796, 'path': 'site/en/r2/tutorials/distribute/keras.ipynb', 'repo_name': 'shawnkoon/docs', 'size': '8770'}