{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "Tce3stUlHN0L" }, "source": [ "##### Copyright 2019 The TensorFlow Authors.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "tuOe1ymfHZPu" }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "id": "MfBg1C5NB3X0" }, "source": [ "# Distributed training with Keras" ] }, { "cell_type": "markdown", "metadata": { "id": "r6P32iYYV27b" }, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " View on TensorFlow.org\n", " \n", " Run in Google Colab\n", " \n", " View source on GitHub\n", " \n", " Download notebook\n", "
" ] }, { "cell_type": "markdown", "metadata": { "id": "xHxb-dlhMIzW" }, "source": [ "## Overview\n", "\n", "The `tf.distribute.Strategy` API provides an abstraction for distributing your training\n", "across multiple processing units. The goal is to allow users to enable distributed training using existing models and training code, with minimal changes.\n", "\n", "This tutorial uses the `tf.distribute.MirroredStrategy`, which\n", "does in-graph replication with synchronous training on many GPUs on one machine.\n", "Essentially, it copies all of the model's variables to each processor.\n", "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.\n", "\n", "`MirroredStrategy` is one of several distribution strategy available in TensorFlow core. You can read about more strategies at [distribution strategy guide](../../guide/distributed_training.ipynb).\n" ] }, { "cell_type": "markdown", "metadata": { "id": "MUXex9ctTuDB" }, "source": [ "### Keras API\n", "\n", "This example uses the `tf.keras` API to build the model and training loop. For custom training loops, see the [tf.distribute.Strategy with training loops](training_loops.ipynb) tutorial." ] }, { "cell_type": "markdown", "metadata": { "id": "Dney9v7BsJij" }, "source": [ "## Import dependencies" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "r8S3ublR7Ay8" }, "outputs": [], "source": [ "# Import TensorFlow and TensorFlow Datasets\n", "\n", "import tensorflow_datasets as tfds\n", "import tensorflow as tf\n", "\n", "import os" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "SkocY8tgRd3H" }, "outputs": [], "source": [ "print(tf.__version__)" ] }, { "cell_type": "markdown", "metadata": { "id": "hXhefksNKk2I" }, "source": [ "## Download the dataset" ] }, { "cell_type": "markdown", "metadata": { "id": "OtnnUwvmB3X5" }, "source": [ "Download the MNIST dataset and load it from [TensorFlow Datasets](https://www.tensorflow.org/datasets). This returns a dataset in `tf.data` format." ] }, { "cell_type": "markdown", "metadata": { "id": "lHAPqG8MtS8M" }, "source": [ "Setting `with_info` to `True` includes the metadata for the entire dataset, which is being saved here to `info`.\n", "Among other things, this metadata object includes the number of train and test examples. \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "iXMJ3G9NB3X6" }, "outputs": [], "source": [ "datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True)\n", "\n", "mnist_train, mnist_test = datasets['train'], datasets['test']" ] }, { "cell_type": "markdown", "metadata": { "id": "GrjVhv-eKuHD" }, "source": [ "## Define distribution strategy" ] }, { "cell_type": "markdown", "metadata": { "id": "TlH8vx6BB3X9" }, "source": [ "Create a `MirroredStrategy` object. This will handle distribution, and provides a context manager (`tf.distribute.MirroredStrategy.scope`) to build your model inside." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "4j0tdf4YB3X9" }, "outputs": [], "source": [ "strategy = tf.distribute.MirroredStrategy()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "cY3KA_h2iVfN" }, "outputs": [], "source": [ "print('Number of devices: {}'.format(strategy.num_replicas_in_sync))" ] }, { "cell_type": "markdown", "metadata": { "id": "lNbPv0yAleW8" }, "source": [ "## Setup input pipeline" ] }, { "cell_type": "markdown", "metadata": { "id": "psozqcuptXhK" }, "source": [ "When training a model with multiple GPUs, you can use the extra computing power effectively by increasing the batch size. In general, use the largest batch size that fits the GPU memory, and tune the learning rate accordingly." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "p1xWxKcnhar9" }, "outputs": [], "source": [ "# You can also do info.splits.total_num_examples to get the total\n", "# number of examples in the dataset.\n", "\n", "num_train_examples = info.splits['train'].num_examples\n", "num_test_examples = info.splits['test'].num_examples\n", "\n", "BUFFER_SIZE = 10000\n", "\n", "BATCH_SIZE_PER_REPLICA = 64\n", "BATCH_SIZE = BATCH_SIZE_PER_REPLICA * strategy.num_replicas_in_sync" ] }, { "cell_type": "markdown", "metadata": { "id": "0Wm5rsL2KoDF" }, "source": [ "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Eo9a46ZeJCkm" }, "outputs": [], "source": [ "def scale(image, label):\n", " image = tf.cast(image, tf.float32)\n", " image /= 255\n", "\n", " return image, label" ] }, { "cell_type": "markdown", "metadata": { "id": "WZCa5RLc5A91" }, "source": [ "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/Dataset#batch). Notice we are also keeping an in-memory cache of the training data to improve performance.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "gRZu2maChwdT" }, "outputs": [], "source": [ "train_dataset = mnist_train.map(scale).cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE)\n", "eval_dataset = mnist_test.map(scale).batch(BATCH_SIZE)" ] }, { "cell_type": "markdown", "metadata": { "id": "4xsComp8Kz5H" }, "source": [ "## Create the model" ] }, { "cell_type": "markdown", "metadata": { "id": "1BnQYQTpB3YA" }, "source": [ "Create and compile the Keras model in the context of `strategy.scope`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "IexhL_vIB3YA" }, "outputs": [], "source": [ "with strategy.scope():\n", " model = tf.keras.Sequential([\n", " tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(28, 28, 1)),\n", " tf.keras.layers.MaxPooling2D(),\n", " tf.keras.layers.Flatten(),\n", " tf.keras.layers.Dense(64, activation='relu'),\n", " tf.keras.layers.Dense(10)\n", " ])\n", "\n", " model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n", " optimizer=tf.keras.optimizers.Adam(),\n", " metrics=['accuracy'])" ] }, { "cell_type": "markdown", "metadata": { "id": "8i6OU5W9Vy2u" }, "source": [ "## Define the callbacks\n" ] }, { "cell_type": "markdown", "metadata": { "id": "YOXO5nvvK3US" }, "source": [ "The callbacks used here are:\n", "\n", "* *TensorBoard*: This callback writes a log for TensorBoard which allows you to visualize the graphs.\n", "* *Model Checkpoint*: This callback saves the model after every epoch.\n", "* *Learning Rate Scheduler*: Using this callback, you can schedule the learning rate to change after every epoch/batch.\n", "\n", "For illustrative purposes, add a print callback to display the *learning rate* in the notebook." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "A9bwLCcXzSgy" }, "outputs": [], "source": [ "# Define the checkpoint directory to store the checkpoints\n", "\n", "checkpoint_dir = './training_checkpoints'\n", "# Name of the checkpoint files\n", "checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt_{epoch}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "wpU-BEdzJDbK" }, "outputs": [], "source": [ "# Function for decaying the learning rate.\n", "# You can define any decay function you need.\n", "def decay(epoch):\n", " if epoch < 3:\n", " return 1e-3\n", " elif epoch >= 3 and epoch < 7:\n", " return 1e-4\n", " else:\n", " return 1e-5" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "jKhiMgXtKq2w" }, "outputs": [], "source": [ "# Callback for printing the LR at the end of each epoch.\n", "class PrintLR(tf.keras.callbacks.Callback):\n", " def on_epoch_end(self, epoch, logs=None):\n", " print('\\nLearning rate for epoch {} is {}'.format(epoch + 1,\n", " model.optimizer.lr.numpy()))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "YVqAbR6YyNQh" }, "outputs": [], "source": [ "callbacks = [\n", " tf.keras.callbacks.TensorBoard(log_dir='./logs'),\n", " tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_prefix,\n", " save_weights_only=True),\n", " tf.keras.callbacks.LearningRateScheduler(decay),\n", " PrintLR()\n", "]" ] }, { "cell_type": "markdown", "metadata": { "id": "70HXgDQmK46q" }, "source": [ "## Train and evaluate" ] }, { "cell_type": "markdown", "metadata": { "id": "6EophnOAB3YD" }, "source": [ "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.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "7MVw_6CqB3YD" }, "outputs": [], "source": [ "model.fit(train_dataset, epochs=12, callbacks=callbacks)" ] }, { "cell_type": "markdown", "metadata": { "id": "NUcWAUUupIvG" }, "source": [ "As you can see below, the checkpoints are getting saved." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "JQ4zeSTxKEhB" }, "outputs": [], "source": [ "# check the checkpoint directory\n", "!ls {checkpoint_dir}" ] }, { "cell_type": "markdown", "metadata": { "id": "qor53h7FpMke" }, "source": [ "To see how the model perform, load the latest checkpoint and call `evaluate` on the test data.\n", "\n", "Call `evaluate` as before using appropriate datasets." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "JtEwxiTgpQoP" }, "outputs": [], "source": [ "model.load_weights(tf.train.latest_checkpoint(checkpoint_dir))\n", "\n", "eval_loss, eval_acc = model.evaluate(eval_dataset)\n", "\n", "print('Eval loss: {}, Eval Accuracy: {}'.format(eval_loss, eval_acc))" ] }, { "cell_type": "markdown", "metadata": { "id": "IIeF2RWfYu4N" }, "source": [ "To see the output, you can download and view the TensorBoard logs at the terminal.\n", "\n", "```\n", "$ tensorboard --logdir=path/to/log-directory\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "LnyscOkvKKBR" }, "outputs": [], "source": [ "!ls -sh ./logs" ] }, { "cell_type": "markdown", "metadata": { "id": "kBLlogrDvMgg" }, "source": [ "## Export to SavedModel" ] }, { "cell_type": "markdown", "metadata": { "id": "Xa87y_A0vRma" }, "source": [ "Export the graph and the variables to the platform-agnostic SavedModel format. After your model is saved, you can load it with or without the scope.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "h8Q4MKOLwG7K" }, "outputs": [], "source": [ "path = 'saved_model/'" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "4HvcDmVsvQoa" }, "outputs": [], "source": [ "model.save(path, save_format='tf')" ] }, { "cell_type": "markdown", "metadata": { "id": "vKJT4w5JwVPI" }, "source": [ "Load the model without `strategy.scope`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "T_gT0RbRvQ3o" }, "outputs": [], "source": [ "unreplicated_model = tf.keras.models.load_model(path)\n", "\n", "unreplicated_model.compile(\n", " loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n", " optimizer=tf.keras.optimizers.Adam(),\n", " metrics=['accuracy'])\n", "\n", "eval_loss, eval_acc = unreplicated_model.evaluate(eval_dataset)\n", "\n", "print('Eval loss: {}, Eval Accuracy: {}'.format(eval_loss, eval_acc))" ] }, { "cell_type": "markdown", "metadata": { "id": "YBLzcRF0wbDe" }, "source": [ "Load the model with `strategy.scope`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "BBVo3WGGwd9a" }, "outputs": [], "source": [ "with strategy.scope():\n", " replicated_model = tf.keras.models.load_model(path)\n", " replicated_model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n", " optimizer=tf.keras.optimizers.Adam(),\n", " metrics=['accuracy'])\n", "\n", " eval_loss, eval_acc = replicated_model.evaluate(eval_dataset)\n", " print ('Eval loss: {}, Eval Accuracy: {}'.format(eval_loss, eval_acc))" ] }, { "cell_type": "markdown", "metadata": { "id": "MUZwaz4AKjtD" }, "source": [ "### Examples and Tutorials\n", "Here are some examples for using distribution strategy with keras fit/compile:\n", "1. [Transformer](https://github.com/tensorflow/models/blob/master/official/nlp/transformer/transformer_main.py) example trained using `tf.distribute.MirroredStrategy`\n", "2. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) example trained using `tf.distribute.MirroredStrategy`.\n", "\n", "More examples listed in the [Distribution strategy guide](../../guide/distributed_training.ipynb#examples_and_tutorials)" ] }, { "cell_type": "markdown", "metadata": { "id": "8uNqWRdDMl5S" }, "source": [ "## Next steps\n", "\n", "* Read the [distribution strategy guide](../../guide/distributed_training.ipynb).\n", "* Read the [Distributed Training with Custom Training Loops](training_loops.ipynb) tutorial.\n", "* Visit the [Performance section](../../guide/function.ipynb) in the guide to learn more about other strategies and [tools](../../guide/profiler.md) you can use to optimize the performance of your TensorFlow models.\n", "\n", "Note: `tf.distribute.Strategy` is actively under development and we will be adding more examples and tutorials in the near future. Please give it a try. We welcome your feedback via [issues on GitHub](https://github.com/tensorflow/tensorflow/issues/new)." ] } ], "metadata": { "accelerator": "GPU", "colab": { "collapsed_sections": [], "name": "keras.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }