Training ResNet on Cloud TPU

This tutorial shows you how to train the Tensorflow ResNet-50 model on Cloud TPU. You can apply the same pattern to other TPU-optimised image classification models that use TensorFlow and the ImageNet dataset.

Disclaimer

This tutorial uses a third-party dataset. Google provides no representation, warranty, or other guarantees about the validity, or any other aspects of, this dataset.

Model description

The model in this tutorial is based on Deep Residual Learning for Image Recognition, which first introduces the residual network (ResNet) architecture. This tutorial uses the 50-layer variant, known as ResNet-50.

This tutorial uses tf.estimator to train the model. tf.estimator is a high-level TensorFlow API and is the recommended way to build and run a machine learning model on Cloud TPU. The API simplifies the model development process by hiding most of the low-level implementation, making it easier to switch between TPU and other platforms such as GPU or CPU.

Before you begin

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

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Select or create a GCP project.

    Go to the Manage resources page

  3. Make sure that billing is enabled for your project.

    Learn how to enable billing

  4. This walkthrough uses billable components of Google Cloud Platform. Check the Cloud TPU pricing page to estimate your costs, and follow the instructions to clean up resources when you've finished with them.

Create a Cloud Storage bucket

You need a Cloud Storage bucket to store the data that you use to train your machine learning model and the results of the training.

  1. Go to the Cloud Storage page on the GCP Console.

    Go to the Cloud Storage page

  2. Create a new bucket, specifying the following options:

    • A unique name of your choosing.
    • Default storage class: Regional
    • Location: us-central1

Open Cloud Shell and use the ctpu tool

This guide uses the Cloud TPU Provisioning Utility (ctpu) as a simple tool for setting up and managing your Cloud TPU. The guide runs ctpu from a Cloud Shell. For more advanced setup options, see the custom setup.

The ctpu tool is pre-installed in your Cloud Shell. Follow these steps to check your ctpu configuration:

  1. Open a Cloud Shell window.

    Open Cloud Shell

  2. Type the following into your Cloud Shell, to check your ctpu configuration:

    $ ctpu print-config
    

    You should see a message like this:

    2018/04/29 05:23:03 WARNING: Setting zone to "us-central1-b"
    ctpu configuration:
            name: [your TPU's name]
            project: [your-project-name]
            zone: us-central1-b
    If you would like to change the configuration for a single command invocation, please use the command line flags.
    

    In the output message, the name is the name of your TPU resource (defaults to your username) and zone is the default geographic zone for your Compute Engine. You can change these when you run ctpu up to create a Compute Engine VM and a Cloud TPU.

  3. Take a look at the ctpu commands:

    $ ctpu

    You should see a usage guide, including a list of subcommands and flags with a brief description of each one.

Create a Compute Engine VM and a Cloud TPU

Run the following command to set up a Compute Engine virtual machine (VM) and a Cloud TPU with associated services. The combination of resources and services is called a Cloud TPU flock. The --tpu-size parameter is an optional parameter that you can use to specify the size of your Cloud TPU configuration, a single Cloud TPU device or slices from a Cloud TPU Pod (alpha).

$ ctpu up [optional: --name --zone --tpu-size] 

You should see a message like this:

ctpu will use the following configuration:

   Name: [your TPU's name]
   Zone: [your project's zone]
   GCP Project: [your project's name]
   TensorFlow Version: 1.12
   VM:
     Machine Type: [your machine type]
     Disk Size: [your disk size]
     Preemptible: [true or false]
   Cloud TPU:
     Size: [your TPU size]
     Preemptible: [true or false]

OK to create your Cloud TPU resources with the above configuration? [Yn]:

Press y to create your Cloud TPU resources.

The ctpu up command performs the following tasks:

  • Enables the Compute Engine and Cloud TPU services.
  • Creates a Compute Engine VM with the latest stable TensorFlow version pre-installed. The default zone is us-central1-b. For reference, Cloud TPU is available in the following zones:

    US

    Cloud TPU v2 and Preemptible v2 us-central1-b
    us-central1-c
    us-central1-f ( TFRC program only)
    Cloud TPU v3 (beta) and Preemptible v3 (beta) us-central1-b
    us-central1-f
    ( TFRC program only)
    Cloud TPU v2 Pod (alpha) us-central1-a

    Europe

    Cloud TPU v2 and Preemptible v2 europe-west4-a
    Cloud TPU v3 (beta) and Preemptible v3 (beta) europe-west4-a
    Cloud TPU v2 Pod (alpha) europe-west4-a

    Asia Pacific

    Cloud TPU v2 and Preemptible v2 asia-east1-c
  • Creates a Cloud TPU with the corresponding version of TensorFlow, and passes the name of the Cloud TPU to the Compute Engine VM as an environment variable (TPU_NAME).

  • Ensures your Cloud TPU has access to resources it needs from your GCP project, by granting specific IAM roles to your Cloud TPU service account.

  • Performs a number of other checks.

  • Logs you in to your new Compute Engine VM.

You can run ctpu up as often as you like. For example, if you lose the SSH connection to the Compute Engine VM, run ctpu up to restore the connection, specifying --name and --zone if you changed the default values. See the ctpu documentation for details.

From this point on, a prefix of (vm)$ means you should run the command on the Compute Engine VM instance.

Verify your Compute Engine VM

When the ctpu up command has finished executing, verify that your shell prompt has changed from username@project to username@tpuname. This change shows that you are now logged into your Compute Engine VM.

Use the default or change the Cloud Storage access permissions

The ctpu up command set up default permissions for your Cloud TPU service account. If you want finer-grain permissions, review and update the access level permissions.

Prepare the data

Set up the following environment variable, replacing YOUR-BUCKET-NAME with the name of your Cloud Storage bucket:

(vm)$ export STORAGE_BUCKET=gs://YOUR-BUCKET-NAME

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.

Below are the instructions for using a randomly generated fake dataset to test the model. Alternatively, you can use the full ImageNet dataset.

The fake dataset is at this location on Cloud Storage:

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

Note that the fake 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.

(Optional) Set up TensorBoard

TensorBoard offers a suite of tools designed to present TensorFlow data visually. When used for monitoring, TensorBoard can help identify bottlenecks in processing and suggest ways to improve performance.

If you don't need to monitor the model's output at this time, you can skip the TensorBoard setup steps.

If you want to monitor the model's output and performance, follow the guide to setting up TensorBoard.

Run the ResNet-50 model

You are now ready to train and evaluate the ResNet-50 model on your Cloud TPU. In the following steps, a prefix of (vm)$ means you should run the command on your Compute Engine VM:

  1. Set up a DATA_DIR environment variable, if necessary. The data directory used within the ResNet Python module that is specified by DATA_DIR defaults to the fake dataset, so you only need to set DATA_DIR if you are using the full ImageNet dataset.

  2. Add the top-level /models folder to the Python path with the command

    (vm)$ export PYTHONPATH="$PYTHONPATH:/usr/share/tpu/models"
    
  3. The ResNet-50 model is pre-installed on your Compute Engine VM. Navigate to the directory:

    (vm)$ cd /usr/share/tpu/models/official/resnet/
    
  4. Run the training script:

    (vm)$ python resnet_main.py \
      --tpu=$TPU_NAME \
      --data_dir=$DATA_DIR \
      --model_dir=${STORAGE_BUCKET}/resnet
    
    • --tpu specifies the name of the Cloud TPU. Note that ctpu passes this name to the Compute Engine VM as an environment variable (TPU_NAME).
    • --data_dir specifies the Cloud Storage path for training input. This parameter is only needed if you are using the full ImageNet dataset. The Python program will use the fake dataset if it is not set.
    • --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.

What to expect

The above procedure trains the ResNet-50 model for 90 epochs and evaluates every fixed number of steps. With the default flags, the model should train to above 76% accuracy.

TPU-specific modifications to the ResNet-50 model

The ResNet code in this tutorial uses TPUEstimator which is based on the high-level Estimator API. There are a few code changes that are required in order to convert an Estimator-based model to a TPUEstimator-based model for training.

Import the following libraries:

from tensorflow.contrib.tpu.python.tpu import tpu_config
from tensorflow.contrib.tpu.python.tpu import tpu_estimator
from tensorflow.contrib.tpu.python.tpu import tpu_optimizer

Use the CrossShardOptimizer function to wrap the optimizer, such as:

if FLAGS.use_tpu:
  optimizer = tpu_optimizer.CrossShardOptimizer(optimizer)

Define the model_fn and return a TPUEstimator specification using:

return tpu_estimator.TPUEstimatorSpec(
    mode=mode,
    loss=loss,
    train_op=train_op)

To run the model on Cloud TPU, you need the TPU gRPC address, which you can get using tf.contrib.cluster_resolver.python.training.TPUClusterResolver. Define an Estimator compatible configuration using:

config = tpu_config.RunConfig(
    master=tpu_grpc_addr,
    model_dir=FLAGS.model_dir,
    tpu_config=tpu_config.TPUConfig(
        iterations_per_loop=FLAGS.iterations_per_loop,
        num_shards=FLAGS.num_cores))

Creating the Estimator object using configuration and model data:

estimator = tpu_estimator.TPUEstimator(
    use_tpu=FLAGS.use_tpu,
    model_fn=model_fn,
    config=config,
    train_batch_size=FLAGS.batch_size)

The Python program runs the estimator.train function for the number of iterations defined in the configuration:

estimator.train(input_fn=input_fn, max_steps=FLAGS.train_steps)

Clean up

  1. Disconnect from the Compute Engine VM:

    (vm)$ exit
    

    Your prompt should now be user@projectname, showing you are in your Cloud Shell.

  2. In your Cloud Shell, run the following command to delete your Compute Engine VM and your Cloud TPU:

    $ ctpu delete
    
  3. Run ctpu status to make sure you have no instances allocated to avoid unnecessary charges for TPU usage. The deletion might take several minutes. A response like the one below indicates there are no more allocated instances:

    2018/04/28 16:16:23 WARNING: Setting zone to "us-central1-b"
    No instances currently exist.
            Compute Engine VM:     --
            Cloud TPU:             --
    
  4. When you no longer need the Cloud Storage bucket you created during this tutorial, use the gsutil command to delete it. Replace YOUR-BUCKET-NAME with the name of your Cloud Storage bucket:

    $ gsutil rm -r gs://YOUR-BUCKET-NAME
    

    See the Cloud Storage pricing guide for free storage limits and other pricing information.

Using the full ImageNet dataset

You need about 300GB of space available on your local machine or VM to run the script used in this section.

If you decide to process the data on your Compute Engine VM, follow these steps to add disk space to the VM:

  • Follow the Compute Engine guide to add a disk to your VM.
  • Set the disk size to 300GB or more.
  • Set When deleting instance to Delete disk to ensure that the disk is removed when you remove the VM.
  • Make a note of the path to your new disk. For example: /mnt/disks/mnt-dir.

Download and convert the ImageNet data:

  1. Sign up for an ImageNet account. Remember the username and password you used to create the account.

  2. Set up a DATA_DIR environment variable pointing to a path on your Cloud Storage bucket:

    (vm)$ export DATA_DIR=${STORAGE_BUCKET}/data
    
  3. Download the imagenet_to_gcs.py script from GitHub:

    $ wget https://raw.githubusercontent.com/tensorflow/tpu/master/tools/datasets/imagenet_to_gcs.py
    
  4. Set a SCRATCH_DIR variable to contain the script's working files. The variable must specify a location on your local machine or on your Compute Engine VM. For example, on your local machine:

    $ SCRATCH_DIR=./imagenet_tmp_files
    

    Or if you're processing the data on the VM:

    (vm)$ SCRATCH_DIR=/mnt/disks/mnt-dir/imagenet_tmp_files
    
  5. Run the imagenet_to_gcs.py script to download, format, and upload the ImageNet data to the bucket. Replace YOUR-USERNAME and YOUR-PASSWORD with the username and password you used to create your ImageNet account.

    $ pip install google-cloud-storage
    $ python imagenet_to_gcs.py \
      --project=$PROJECT \
      --gcs_output_path=$DATA_DIR \
      --local_scratch_dir=$SCRATCH_DIR \
      --imagenet_username=YOUR-USERNAME \
      --imagenet_access_key=YOUR-PASSWORD
    

Optionally if the raw data, in JPEG format, has already been downloaded, you can provide a direct raw_data_directory path. If a raw data directory for training or validation data is provided, it should be in the format:

The training subdirectory names (for example, n03062245) are "WordNet IDs" (wnid). The ImageNet API shows the mapping of WordNet IDs to their associated validation labels in the synset_labels.txt file. A synset in this context is a visually-similar group of images.

Note: Downloading and preprocessing the data can take up to half a day, depending on your network and computer speed. Do not interrupt the script.

When the script finishes processing, a message like the following appears:

2018-02-17 14:30:17.287989: Finished writing all 1281167 images in data set.

The script produces a series of directories (for both training and validation) of the form:

${DATA_DIR}/train-00000-of-01024
${DATA_DIR}/train-00001-of-01024
 ...
${DATA_DIR}/train-01023-of-01024

and

${DATA_DIR}/validation-00000-of-00128
S{DATA_DIR}/validation-00001-of-00128
 ...
${DATA_DIR}/validation-00127-of-00128

What's next

Was this page helpful? Let us know how we did:

Send feedback about...