Training ResNet on Cloud TPU (TF 2.x)

This tutorial shows you how to train a Keras ResNet model on Cloud TPU using tf.distribute.TPUStrategy.

If you are not familiar with Cloud TPU, it is strongly recommended that you go through the quickstart to learn how to create a TPU and a Compute Engine VM.

Objectives

  • Create a Cloud Storage bucket to hold your dataset and model output.
  • Prepare a fake imagenet dataset that is similar to the ImageNet dataset.
  • Run the training job.
  • Verify the output results.

Costs

This tutorial uses billable components of Google Cloud, including:

  • Compute Engine
  • Cloud TPU
  • Cloud Storage

Use the pricing calculator to generate a cost estimate based on your projected usage. New Google Cloud users might be eligible for a free trial.

Before you begin

Before starting this tutorial, check that your Google Cloud project is correctly set up.

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Cloud project. Learn how to confirm that billing is enabled for your project.

  4. This walkthrough uses billable components of Google Cloud. Check the Cloud TPU pricing page to estimate your costs. Be sure to clean up resources you create when you've finished with them to avoid unnecessary charges.

Set up your resources for single device training

This section provides information on setting up Cloud Storage bucket, VM, and Cloud TPU resources for single device training.

  1. Open a Cloud Shell window.

    Open Cloud Shell

  2. Create a variable for your project's ID.

    export PROJECT_ID=project-id
    
  3. Configure the gcloud command-line tool to use the project where you want to create Cloud TPU.

    gcloud config set project ${PROJECT_ID}
    

    The first time you run this command in a new Cloud Shell VM, an Authorize Cloud Shell page is displayed. Click Authorize at the bottom of the page to allow gcloud to make GCP API calls with your credentials.

  4. Create a Service Account for the Cloud TPU project.

    gcloud beta services identity create --service tpu.googleapis.com --project $PROJECT_ID
    

    The command returns a Cloud TPU Service Account with following format:

    service-PROJECT_NUMBER@cloud-tpu.iam.gserviceaccount.com
    

  5. Create a Cloud Storage bucket using the following command:

    gsutil mb -p ${PROJECT_ID} -c standard -l europe-west4 -b on gs://bucket-name
    

    This Cloud Storage bucket stores the data you use to train your model and the training results. The gcloud command used in this tutorial to set up the TPU also sets up default permissions for the Cloud TPU Service Account you set up in the previous step. If you want finer-grain permissions, review the access level permissions.

  6. Prepare your dataset or use fake_imagenet

    ImageNet is an image database. The images in the database are organized into a hierarchy, with each node of the hierarchy depicted by hundreds and thousands of images.

    This tutorial uses a demonstration version of the full ImageNet dataset, referred to as fake_imagenet. This demonstration version allows you to test the tutorial, while reducing the storage and time requirements typically associated with running a model against the full ImageNet database.

    The fake_imagenet dataset is at this location on Cloud Storage:

    gs://cloud-tpu-test-datasets/fake_imagenet

    The fake_imagenet dataset is only useful for understanding how to use a Cloud TPU and validating end-to-end performance. The accuracy numbers and saved model will not be meaningful.

    If you want to use the full ImageNet dataset, see Downloading, preprocessing, and uploading the ImageNet dataset.

  7. Launch a Compute Engine VM and Cloud TPU using the gcloud command. The command you use depends on whether you are using TPU VMs or TPU nodes. For more information on the two VM architecture, see System Architecture.

    TPU VM

    $ gcloud alpha compute tpus tpu-vm create resnet-tutorial \
    --zone=europe-west4-a \
    --accelerator-type=v3-8 \
    --version=v2-alpha
    

    Command flag descriptions

    zone
    The zone where you plan to create your Cloud TPU.
    accelerator-type
    The type of the Cloud TPU to create.
    version
    The Cloud TPU runtime version.

    TPU Node

    gcloud compute tpus execution-groups create \
    --project=${PROJECT_ID} \
    --zone=europe-west4-a \
    --name=resnet-tutorial \
    --disk-size=300 \
    --machine-type=n1-standard-16 \
    --tf-version=2.5.0

    Command flag descriptions

    project
    Your GCP project ID
    zone
    The zone where you plan to create your Cloud TPU.
    name
    The name of the Cloud TPU to create.
    disk-size
    The size of the hard disk in GB of the VM created by the gcloud command.
    machine-type
    The machine type of the Compute Engine VM to create.
    tf-version
    The version of Tensorflow gcloud installs on the VM.

    For more information on the gcloud command, see the gcloud Reference.

  8. If you are not automatically logged in to the Compute Engine instance, log in by running the following ssh command. When you are logged into the VM, your shell prompt changes from username@projectname to username@vm-name:

    TPU VM

    gcloud alpha compute tpus tpu-vm ssh resnet-tutorial --zone=europe-west4-a
    

    TPU Node

    gcloud compute ssh resnet-tutorial --zone=europe-west4-a
    

    As you continue these instructions, run each command that begins with (vm)$ in your VM session window.

  9. Set the Cloud TPU name variable.

    TPU VM

    (vm)$ export TPU_NAME=local
    

    TPU Node

    (vm)$ export TPU_NAME=resnet-tutorial
    
  10. Set Cloud Storage bucket variables

    Set up the following environment variables, replacing bucket-name with the name of your Cloud Storage bucket:

    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/resnet-2x
    (vm)$ export DATA_DIR=gs://cloud-tpu-test-datasets/fake_imagenet
    

    The training application expects your training data to be accessible in Cloud Storage. The training application also uses your Cloud Storage bucket to store checkpoints during training.

  11. Install TensorFlow requirements.

    The command you use depends on whether you are using TPU VMs or TPU Nodes.

    TPU VM

    (vm)$ git clone https://github.com/tensorflow/models.git
    (vm)$ pip3 install -r models/official/requirements.txt
    

    TPU Node

    (vm)$ sudo pip3 install -r /usr/share/models/official/requirements.txt
    
  12. The ResNet training script requires an extra package. Install it now:

    (vm)$ sudo pip3 install tensorflow-model-optimization>=0.1.3
    
  13. Set the PYTHONPATH environment variable:

    TPU VM

    (vm)$ export PYTHONPATH="${PWD}/models:${PYTHONPATH}"
    

    TPU Node

    (vm)$ export PYTHONPATH="${PYTHONPATH}:/usr/share/models"
    
  14. Change to directory that stores the model:

    TPU VM

    (vm)$ cd ~/models/official/vision/image_classification/resnet
    

    TPU Node

    (vm)$ cd /usr/share/models/official/vision/image_classification/resnet
    

Train the model

  1. Run the training script. This uses a fake_imagenet dataset and trains ResNet for one epoch.

    (vm)$ python3 resnet_ctl_imagenet_main.py \
     --tpu=${TPU_NAME} \
     --model_dir=${MODEL_DIR} \
     --data_dir=${DATA_DIR} \
     --batch_size=1024 \
     --steps_per_loop=500 \
     --train_epochs=1 \
     --use_synthetic_data=false \
     --dtype=fp32 \
     --enable_eager=true \
     --enable_tensorboard=true \
     --distribution_strategy=tpu \
     --log_steps=50 \
     --single_l2_loss_op=true \
     --use_tf_function=true
    

    Command flag descriptions

    tpu
    The name of your TPU.
    model_dir
    Specifies the directory where checkpoints and summaries are stored during model training. If the folder is missing, the program creates one. When using a Cloud TPU, the model_dir must be a Cloud Storage path (gs://...). You can reuse an existing folder to load current checkpoint data and to store additional checkpoints as long as the previous checkpoints were created using TPU of the same size and TensorFlow version.
    data_dir
    The Cloud Storage path of training input. It is set to the fake_imagenet dataset in this example.
    batch_size
    The training batch size.
    steps_per_loop
    The number of training steps to run before saving state to the CPU. A training step is the processing of one batch of examples. This includes both a forward pass and back propagation.
    train_epochs
    The number of times to train the model using the entire dataset.
    use_synthetic_data
    Whether to use synthetic data for training.
    dtype
    The data type to use for training.
    enable_eager
    Enable TensorFlow eager execution.
    enable_tensorboard
    Enable TensorBoard.
    distribution_strategy
    To train the ResNet model on a TPU, set distribution_strategy to tpu.
    log_steps
    The number of training steps to take before logging timing information such as examples per second.
    single_l2_loss_op
    Calculate L2_loss on concatenated weights, instead of using Keras per-layer L2 loss.
    use_tf_function
    Wrap the train and test steps inside a tf.function.

This will train ResNet for 1 epoch and will complete on a v3-8 TPU node in approximately 10 minutes. At the end of the training, output similar to the following appears:

I1107 20:28:57.561836 140033625347520 resnet_ctl_imagenet_main.py:222] Training 1 epochs, each epoch has 1251 steps, total steps: 1251; Eval 48 steps
I1107 20:34:09.638025 140033625347520 resnet_ctl_imagenet_main.py:358] Training loss: 0.6292637, accuracy: 0.99680257 at epoch 1
I1107 20:34:21.682796 140033625347520 resnet_ctl_imagenet_main.py:372] Test loss: 3.8977659, accuracy: 0.0% at epoch: 1
I1107 20:34:22.028973 140033625347520 resnet_ctl_imagenet_main.py:392]
Run stats:
{'train_loss': 0.6292637, 'train_acc': 0.99680257, 'eval_acc': 0.0, 'step_timestamp_log':
['BatchTimestamp <batch_index: 1, timestamp: 1573158554.11>'],
'train_finish_time': 1573158861.683073, 'eval_loss': 3.8977659>}

To train the ResNet to convergence, run it for 90 epochs as shown in the following script. Training and evaluation are done together. Each epoch has 1251 steps for a total of 112590 training steps and 48 evaluation steps.

(vm)$ python3 resnet_ctl_imagenet_main.py \
    --tpu=${TPU_NAME} \
    --model_dir=${MODEL_DIR} \
    --data_dir=${DATA_DIR} \
    --batch_size=1024 \
    --steps_per_loop=500 \
    --train_epochs=90 \
    --use_synthetic_data=false \
    --dtype=fp32 \
    --enable_eager=true \
    --enable_tensorboard=true \
    --distribution_strategy=tpu \
    --log_steps=50 \
    --single_l2_loss_op=true \
    --use_tf_function=true

Command flag descriptions

tpu
The name of your TPU.
model_dir
Specifies the directory where checkpoints and summaries are stored during model training. If the folder is missing, the program creates one. When using a Cloud TPU, the model_dir must be a Cloud Storage path (gs://...). You can reuse an existing folder to load current checkpoint data and to store additional checkpoints as long as the previous checkpoints were created using a Cloud TPU of the same size and TensorFlow version.
data_dir
The Cloud Storage path of training input. It is set to the fake_imagenet dataset in this example.
batch_size
The training batch size.
steps_per_loop
The number of training steps to run before saving state to the CPU. A training step is the processing of one batch of examples. This includes both a forward pass and back propagation.
train_epochs
The number of times to train the model using the entire dataset.
use_synthetic_data
Whether to use synthetic data for training.
dtype
The data type to use for training.
enable_eager
Enable TensorFlow eager execution.
enable_tensorboard
Enable TensorBoard.
distribution_strategy
To train the ResNet model on a TPU, set distribution_strategy to tpu.
log_steps
The number of training steps to take before logging timing information such as examples per second.
single_l2_loss_op
Calculate L2_loss on concatenated weights, instead of using Keras per-layer L2 loss.
use_tf_function
Wrap the train and test steps inside a tf.function.

Since the training and evaluation were done on the fake_imagenet dataset, the output results do not reflect actual output that would appear if the training and evaluation were performed on a real dataset.

You have now completed single-device training. Use the following steps to delete the current single-device TPU resources.

  1. Disconnect from the Compute Engine instance:

    (vm)$ exit
    

    Your prompt should now be username@projectname, showing you are in the Cloud Shell.

  2. Delete the TPU resource.

    TPU VM

    $ gcloud alpha compute tpus tpu-vm delete resnet-tutorial \
    --zone=europe-west4-a
    

    Command flag descriptions

    zone
    The zone where your Cloud TPU resided.

    TPU Node

    $ gcloud compute tpus execution-groups delete resnet-tutorial \
    --tpu-only \
    --zone=europe-west4-a
    

    Command flag descriptions

    tpu-only
    Deletes only the Cloud TPU. The VM remains available.
    zone
    The zone that contains the TPU to delete.

At this point, you can either conclude this tutorial and clean up, or you can continue and explore running the model on Cloud TPU Pods.

Scaling your model with Cloud TPU Pods

TPU VM Pod training

This section provides information on setting up a Cloud Storage bucket and Cloud TPU resources for Pod training.

  1. Open a Cloud Shell window.

    Open Cloud Shell

  2. Create a variable for your project's ID.

    export PROJECT_ID=project-id
    
  3. Configure gcloud command-line tool to use the project where you want to create Cloud TPU.

    gcloud config set project ${PROJECT_ID}
    

    The first time you run this command in a new Cloud Shell VM, an Authorize Cloud Shell page is displayed. Click Authorize at the bottom of the page to allow gcloud to make GCP API calls with your credentials.

  4. Create a Service Account for the Cloud TPU project.

    gcloud beta services identity create --service tpu.googleapis.com --project $PROJECT_ID
    

    The command returns a Cloud TPU Service Account with following format:

    service-PROJECT_NUMBER@cloud-tpu.iam.gserviceaccount.com
    

  5. Create a Cloud Storage bucket using the following command or use a bucket you created earlier for your project:

    gsutil mb -p ${PROJECT_ID} -c standard -l europe-west4 -b on gs://bucket-name
    

    This Cloud Storage bucket stores the data you use to train your model and the training results. The gcloud command used in this tutorial sets up default permissions for the Cloud TPU Service Account you set up in the previous step. If you want finer-grain permissions, review the access level permissions.

    The bucket location must be in the same region as your TPU VM.

  6. Prepare your dataset or use fake_imagenet

    ImageNet is an image database. The images in the database are organized into a hierarchy, with each node of the hierarchy depicted by hundreds and thousands of images.

    The default Pod training accesses a demonstration version of the full ImageNet dataset, referred to as fake_imagenet. This demonstration version allows you to test Pod training, while reducing the storage and time requirements typically associated with training a model against the full ImageNet database.

    The fake_imagenet dataset is only useful for understanding how to use a Cloud TPU and validating end-to-end performance. The accuracy numbers and saved model will not be meaningful.

    If you want to use the full ImageNet dataset, see Downloading, preprocessing, and uploading the ImageNet dataset.

  7. Launch a TPU VM Pod using the gcloud alpha compute tpus tpu-vm command. This tutorial specifies a v3-32 Pod. For other Pod options, see the available TPU types page.

    $ gcloud alpha compute tpus tpu-vm create resnet-tutorial \
    --zone=europe-west4-a \
    --accelerator-type=v3-32 \
    --version=v2-alpha-pod
    

    Command flag descriptions

    zone
    The zone where you plan to create your Cloud TPU.
    accelerator-type
    The type of the Cloud TPU to create.
    version
    The Cloud TPU runtime version.
  8. Run the following ssh command to log into the VM. When you are logged into the VM, your shell prompt changes from username@projectname to username@vm-name:

      gcloud alpha compute tpus tpu-vm ssh resnet-tutorial --zone=europe-west4-a
      

  9. Set the Cloud TPU name variable.

    (vm)$ export TPU_NAME=resnet-tutorial
    
  10. Set Cloud Storage bucket variables

    Set up the following environment variables, replacing bucket-name with the name of your Cloud Storage bucket:

    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/resnet-2x-pod
    (vm)$ export DATA_DIR=gs://cloud-tpu-test-datasets/fake_imagenet
    

    The training application expects your training data to be accessible in Cloud Storage. The training application also uses your Cloud Storage bucket to store checkpoints during training.

  11. The ResNet training script requires an extra package. Install it now:

    (vm)$ sudo pip3 install tensorflow-model-optimization>=0.1.3
    
  12. Install TensorFlow requirements.

    The command you use depends on whether you are using TPU VMs or TPU Nodes.

    TPU VM

    (vm)$ git clone https://github.com/tensorflow/models.git
    (vm)$ pip3 install -r models/official/requirements.txt
    

    TPU Node

    (vm)$ sudo pip3 install -r /usr/share/models/official/requirements.txt
    
  13. Set some required environment variables:

    (vm)$ export TPU_LOAD_LIBRARY=0
    
  14. Set the PYTHONPATH environment variable:

    TPU VM

    (vm)$ export PYTHONPATH="${PWD}/models:${PYTHONPATH}"
    (vm)$ export TPU_LOAD_LIBRARY=0
    

    TPU Node

    (vm)$ export PYTHONPATH="${PYTHONPATH}:/usr/share/models"
    
  15. Change to directory that stores the model:

    TPU VM

    (vm)$ cd ~/models/official/vision/image_classification/resnet
    

    TPU Node

    (vm)$ cd /usr/share/models/official/vision/image_classification/resnet
    
  16. Train the model.

    (vm)$ python3 resnet_ctl_imagenet_main.py \
      --tpu=${TPU_NAME} \
      --model_dir=${MODEL_DIR} \
      --data_dir=${DATA_DIR} \
      --batch_size=4096 \
      --steps_per_loop=500 \
      --train_epochs=1 \
      --use_synthetic_data=false \
      --dtype=fp32 \
      --enable_eager=true \
      --enable_tensorboard=true \
      --distribution_strategy=tpu \
      --log_steps=50 \
      --single_l2_loss_op=true \
      --use_tf_function=true
     

    Command flag descriptions

    tpu
    The name of your TPU.

      <dt><code>model_dir</code></dt>
      <dd>Specifies the directory where checkpoints and summaries are stored
        during model training. If the folder is missing, the program creates
        one. When using a Cloud TPU, the <code>model_dir</code>
        must be a Cloud Storage path (<code>gs://...</code>). You can
        reuse an existing folder to load current checkpoint data and to store
        additional checkpoints as long as the previous checkpoints were
        created using Cloud TPU of the same size and TensorFlow version.</dd>
    
      <dt><code>data_dir</code></dt>
      <dd>The Cloud Storage path of training input. It is set to the
        fake_imagenet dataset in this example.</dd>
    
      <dt><code>batch_size</code></dt>
      <dd>The training batch size.</dd>
    
      <dt><code>steps_per_loop</code></dt>
      <dd>The number of training steps to run before saving state to the CPU.
        A training step is the processing of one batch of examples. This
        includes both a forward pass and back propagation.</dd>
    
      <dt><code>train_epochs</code></dt>
      <dd>The number of times to train the model using the entire dataset.</dd>
    
      <dt><code>use_synthetic_data</code></dt>
      <dd>Whether to use synthetic data for training.</dd>
    
      <dt><code>dtype</code></dt>
      <dd>The data type to use for training.</dd>
    
      <dt><code>enable_eager</code></dt>
      <dd>Enables TensorFlow <a href="https://www.tensorflow.org/guide/eager">eager execution</a>.</dd>
    
      <dt><code>enable_tensorboard</code></dt>
      <dd>Enables <a href="https://www.tensorflow.org/tensorboardTensorBoard">TensorBoard</a>.</dd>
    
      <dt><code>distribution_strategy</code></dt>
      <dd>To train the ResNet model on a TPU, set <code>distribution_strategy</code>
        to <code>tpu</code>.</dd>
    
      <dt><code>log_steps</code></dt>
      <dd>The number of training steps to take before logging timing
        information such as <code>examples per second</code>.</dd>
    
      <dt><code>single_l2_loss_op</code></dt>
      <dd>Calculate L2_loss on concatenated weights, instead of using Keras
        per-layer L2 loss.</dd>
    
      <dt><code>use_tf_function</code></dt>
      <dd>Wrap the train and test steps inside a <code>tf.function</code>.</dd>
    </dl>
    

This procedure trains the model on the fake_imagenet dataset to 1 epoch (312 total training steps and 12 evaluation steps). This training takes approximately 2 minutes on a v3-32 Cloud TPU. When the training and evaluation complete, a message similar to the following appears:

1107 22:45:19.821746 140317155378624 resnet_ctl_imagenet_main.py:358] Training loss: 0.22576721, accuracy: 0.838141 at epoch 1
I1107 22:45:33.892045 140317155378624 resnet_ctl_imagenet_main.py:372] Test loss: 0.26673648, accuracy: 0.0% at epoch: 1
I1107 22:45:34.851322 140317155378624 resnet_ctl_imagenet_main.py:392] Run stats:
{'train_loss': 0.22576721, 'train_acc': 0.838141, 'eval_acc': 0.0, 'step_timestamp_log': ['BatchTimestamp<batch_index: 1, timestamp: 1573166574.67>'], 'train_finish_time': 1573166733.892282, 'eval_loss': 0.26673648}

TPU Node Pod training

  1. Create a new Cloud TPU Pod. Run the gcloud compute tpus execution-groups command, using the accelerator-type parameter to specify the Pod slice you want to use. For example, the following command uses a v3-32 Pod slice.

    (vm)$ gcloud compute tpus execution-groups create \
      --zone=europe-west4-a \
      --tpu-only \
      --name=resnet-tutorial \
      --accelerator-type=v3-32 \
      --tf-version=2.5.0

    Command flag descriptions

    zone
    The zone where you plan to create your Cloud TPU.
    tpu-only
    Creates the Cloud TPU only. By default the gcloud compute tpus execution-groups command creates both a VM and a Cloud TPU.
    name
    The name of the Cloud TPU to create.
    accelerator-type
    The type of the Cloud TPU to create.
    tf-version
    The version of Tensorflow gcloud installs on the VM.
  2. When the gcloud alpha compute tpus command has finished executing, verify that your shell prompt has changed from username@projectname to username@vm-name. This change shows that you are now logged into your Compute Engine VM.

    If you are not connected to the Compute Engine instance, you can connect by running the following commands:

       gcloud compute ssh resnet-tutorial --zone=europe-west4-a
      

  3. Set some required environment variables:

    (vm)$ export TPU_NAME=resnet-tutorial
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/resnet-2x-pod
    
  4. Navigate to the script directory:

    (vm)$ cd /usr/share/models/official/vision/image_classification/resnet
    
  5. Train the model.

    (vm)$ python3 resnet_ctl_imagenet_main.py \
      --tpu=${TPU_NAME} \
      --model_dir=${MODEL_DIR} \
      --data_dir=${DATA_DIR} \
      --batch_size=4096 \
      --steps_per_loop=500 \
      --train_epochs=1 \
      --use_synthetic_data=false \
      --dtype=fp32 \
      --enable_eager=true \
      --enable_tensorboard=true \
      --distribution_strategy=tpu \
      --log_steps=50 \
      --single_l2_loss_op=true \
      --use_tf_function=true
     

    Command flag descriptions

    tpu
    The name of your TPU.

      <dt><code>model_dir</code></dt>
      <dd>Specifies the directory where checkpoints and summaries are stored
        during model training. If the folder is missing, the program creates
        one. When using a Cloud TPU, the <code>model_dir</code>
        must be a Cloud Storage path (<code>gs://...</code>). You can
        reuse an existing folder to load current checkpoint data and to store
        additional checkpoints as long as the previous checkpoints were
        created using Cloud TPU of the same size and TensorFlow version.</dd>
    
      <dt><code>data_dir</code></dt>
      <dd>The Cloud Storage path to the training dataset.</dd>
    
      <dt><code>batch_size</code></dt>
      <dd>The training batch size.</dd>
    
      <dt><code>steps_per_loop</code></dt>
      <dd>The number of training steps to run before saving state to the CPU.
        A training step is the processing of one batch of examples. This
        includes both a forward pass and back propagation.</dd>
    
      <dt><code>train_epochs</code></dt>
      <dd>The number of times to train the model using the entire dataset.</dd>
    
      <dt><code>use_synthetic_data</code></dt>
      <dd>Whether to use synthetic data for training.</dd>
    
      <dt><code>dtype</code></dt>
      <dd>The data type to use for training.</dd>
    
      <dt><code>enable_eager</code></dt>
      <dd>Enables TensorFlow <a href="https://www.tensorflow.org/guide/eager">eager execution</a>.</dd>
    
      <dt><code>enable_tensorboard</code></dt>
      <dd>Enables <a href="https://www.tensorflow.org/tensorboardTensorBoard">TensorBoard</a>.</dd>
    
      <dt><code>distribution_strategy</code></dt>
      <dd>To train the ResNet model on a TPU, set <code>distribution_strategy</code>
        to <code>tpu</code>.</dd>
    
      <dt><code>log_steps</code></dt>
      <dd>The number of training steps to take before logging timing
        information such as <code>examples per second</code>.</dd>
    
      <dt><code>single_l2_loss_op</code></dt>
      <dd>Calculate L2_loss on concatenated weights, instead of using Keras
        per-layer L2 loss.</dd>
    
      <dt><code>use_tf_function</code></dt>
      <dd>Wrap the train and test steps inside a <code>tf.function</code>.</dd>
    </dl>
    

This procedure trains the model on the fake_imagenet dataset to 1 epoch (312 total training steps and 12 evaluation steps). This training takes approximately 2 minutes on a v3-32 Cloud TPU. When the training and evaluation complete, a message similar to the following appears:

1107 22:45:19.821746 140317155378624 resnet_ctl_imagenet_main.py:358] Training loss: 0.22576721, accuracy: 0.838141 at epoch 1
I1107 22:45:33.892045 140317155378624 resnet_ctl_imagenet_main.py:372] Test loss: 0.26673648, accuracy: 0.0% at epoch: 1
I1107 22:45:34.851322 140317155378624 resnet_ctl_imagenet_main.py:392] Run stats:
{'train_loss': 0.22576721, 'train_acc': 0.838141, 'eval_acc': 0.0, 'step_timestamp_log': ['BatchTimestamp<batch_index: 1, timestamp: 1573166574.67>'], 'train_finish_time': 1573166733.892282, 'eval_loss': 0.26673648}

Cleaning up

To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.

  1. Disconnect from the Compute Engine instance, if you have not already done so:

    (vm)$ exit
    

    Your prompt should now be username@projectname, showing you are in the Cloud Shell.

  2. Delete your Cloud TPU and Compute Engine resources. The command you use to delete your resources depends upon whether you are using TPU VMs or TPU Nodes. For more information, see System Architecture.

    TPU VM

    $ gcloud alpha compute tpus tpu-vm delete resnet-tutorial \
    --zone=europe-west4-a
    

    TPU Node

    $ gcloud compute tpus execution-groups delete resnet-tutorial \
    --zone=europe-west4-a
    
  3. Verify the resources have been deleted by running gcloud compute tpus execution-groups list. The deletion might take several minutes. A response like the one below indicates your instances have been successfully deleted.

    $ gcloud compute tpus execution-groups list --zone=europe-west4-a
    
    Listed 0 items.
    
  4. Run gsutil as shown, replacing bucket-name with the name of the Cloud Storage bucket you created for this tutorial:

    $ gsutil rm -r gs://bucket-name
    

What's next

In this tutorial you have trained the RESNET model using a sample dataset. The results of this training are (in most cases) not usable for inference. To use a model for inference you can train the data on a publicly available dataset or your own data set. Models trained on Cloud TPUs require datasets to be in TFRecord format.

You can use the dataset conversion tool sample to convert an image classification dataset into TFRecord format. If you are not using an image classification model, you will have to convert your dataset to TFRecord format yourself. For more information, see TFRecord and tf.Example

Hyperparameter tuning

To improve the model's performance with your dataset, you can tune the model's hyperparameters. You can find information about hyperparameters common to all TPU supported models on GitHub. Information about model-specific hyperparameters can be found in the source code for each model. For more information on hyperparameter tuning, see Overview of hyperparameter tuning, Using the Hyperparameter tuning service and Tune hyperparameters.

Inference

Once you have trained your model you can use it for inference (also called prediction). AI Platform is a cloud-based solution for developing, training, and deploying machine learning models. Once a model is deployed, you can use the AI Platform Prediction service.

  • Learn how to train and evaluate using your own data in place of the fake_imagenet or ImageNet datasets by following the dataset conversion tutorial. The tutorial explains how to use the image classification data converter example script to convert a raw dataset for image classification into TFRecords usable by Cloud TPU Tensorflow models.
  • Run a Cloud TPU colab that demonstrates how to run an image classification model using your own image data.
  • Explore the other Cloud TPU tutorials.
  • Learn to use the TPU monitoring tools in TensorBoard.
  • See how to train ResNet with Cloud TPU and GKE.