Training on Cloud TPU (TF 2.x)


This tutorial shows you how to train a Keras ResNet-RS model on Cloud TPU using tf.distribute.TPUStrategy. For more information about ResNet-RS, see Revisiting ResNets: Improved Training and Scaling Strategies.

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

In this document, you use the following billable components of Google Cloud:

  • Compute Engine
  • Cloud TPU
  • Cloud Storage

To generate a cost estimate based on your projected usage, use the pricing calculator. 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 Google Cloud project.

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  5. Make sure that billing is enabled for your Google Cloud project.

  6. 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

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

  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 Google Cloud CLI 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 Google Cloud 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 gs://bucket-name
    

    This Cloud Storage bucket stores the data you use to train your model and the training results. The gcloud compute tpus execution-groups tool 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 Compute Engine (VM) and your Cloud TPU node.

  6. Launch a Compute Engine VM using the gcloud command.

    $ gcloud compute tpus execution-groups create \
     --vm-only \
     --name=resnet-rs-tutorial \
     --zone=europe-west4-a \
     --disk-size=300 \
     --machine-type=n1-standard-16 \
     --tf-version=2.12.0
     

    Command flag descriptions

    vm-only
    Create a VM only, do not create a TPU.
    name
    The name of the TPU to create.
    zone
    The zone in which to create your Cloud TPU.
    disk-size
    The size of the hard disk in GB of the VM created by the gcloud compute tpus execution-groups command.
    machine-type
    The machine type of the Compute Engine VM to create.

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

  7. When prompted, press y to create your Cloud TPU resources.

    When the gcloud compute tpus execution-groups 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.

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

    As you continue these instructions, run each command that begins with (vm)$ in your Compute Engine instance.

  8. Install necessary packages.

    $ pip3 install tensorflow-text==2.8.1 --no-deps

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-rs-2x
(vm)$ export IMAGENET_DIR=gs://cloud-tpu-test-datasets/fake_imagenet
(vm)$ export PYTHONPATH=/usr/share/models
(vm)$ export TPU_NAME=resnet-rs-tutorial

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.

Cloud TPU single device training and evaluation

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.

For information on how to download and process the full ImageNet dataset, see Downloading, preprocessing, and uploading the ImageNet dataset.

  1. Create a Cloud TPU using the gcloud command.

    $ gcloud compute tpus execution-groups create \
     --tpu-only \
     --accelerator-type=v3-8  \
     --name=resnet-rs-tutorial \
     --zone=europe-west4-a \
     --tf-version=2.12.0

    Command flag descriptions

    tpu-only
    Create a TPU only, do not create a VM.
    accelerator-type
    The type of the Cloud TPU to create.
    name
    The name of the TPU to create.
    zone
    The zone in which to create your Cloud TPU.
    tf-version
    The Tensorflow version installed on the VM.
  2. Set the TPU_NAME name variable.

    (vm)$ export TPU_NAME=resnet-rs-tutorial
    
  3. Run the training script.

    (vm)$ python3 /usr/share/models/official/vision/beta/train.py \
    --experiment=resnet_rs_imagenet \
    --mode=train_and_eval \
    --model_dir=$MODEL_DIR \
    --tpu=$TPU_NAME \
    --config_file=/usr/share/models/official/vision/beta/configs/experiments/image_classification/imagenet_resnetrs50_i160.yaml \
    --params_override="task.train_data.input_path=$IMAGENET_DIR/train*, task.validation_data.input_path=$IMAGENET_DIR/valid*, trainer.train_steps=100"
    

    Command flag descriptions

    experiment
    The name of experiment to run.
    mode
    The mode in which to run the script. Valid values are: `train`, `eval` , or `train_and_eval`.
    model_dir
    The Cloud Storage bucket where checkpoints and summaries are stored during training. You can use an existing folder to load previously generated checkpoints created on a TPU of the same size and TensorFlow version.
    tpu
    The name of the TPU to use.
    config_file
    The path to a script configuration file.
    params_override
    Override settings set in the script configuration file.

This will train ResNet-RS for 100 training steps and will complete on a v3-8 TPU node in less than 5 minutes. The training script output should include text like:

{
  'train_loss': 1.435225,
  'train_accuracy': 0.00084427913
}

The training script also performs evaluation. The evaluation output should contain text like this:

Run stats:
{
  'eval_loss': 0.861013,
  'eval_acc': 0.001,
  'train_loss': 1.435225,
  'train_acc': 0.00084427913,
  'step_timestamp_log': [
    'BatchTimestamp<batch_index: 0,
    timestamp: 1606330585.7613473>',
    'BatchTimestamp<batch_index: 500,
    timestamp: 1606330883.8486104>',
    'BatchTimestamp<batch_index: 1000,
    timestamp: 1606331119.515312>',
    'BatchTimestamp<batch_index: 1251,
    timestamp: 1606331240.7516596>'
  ],
  'train_finish_time': 1606331296.395158,
  'avg_exp_per_second': 1951.6983246161021
}

To train the ResNet-RS model to convergence, omit the trainer.train_steps=100 argument as shown in the following script. Training and evaluation are done together.

(vm)$ python3 /usr/share/models/official/vision/beta/train.py \
  --experiment=resnet_rs_imagenet \
  --mode=train_and_eval \
  --model_dir=$MODEL_DIR \
  --tpu=$TPU_NAME \
  --config_file=/usr/share/models/official/vision/beta/configs/experiments/image_classification/imagenet_resnetrs50_i160.yaml \
  --params_override="task.train_data.input_path=$IMAGENET_DIR/train*, task.validation_data.input_path=$IMAGENET_DIR/valid*"

Command flag descriptions

experiment
The name of experiment to run.
mode
The mode in which to run the script. Valid values are: `train`, `eval`, or `train_and_eval`.
model_dir
The Cloud Storage bucket where checkpoints and summaries are stored during training. You can use an existing folder to load previously generated checkpoints created on a TPU of the same size and TensorFlow version.
tpu
The name of the TPU to use.
config_file
The path to a script configuration file.
params_override
Override settings set in the script configuration file.

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

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

Use larger models

ResNet-RS provides a family of models of different sizes with larger models typically being more accurate at the cost of more compute. For more information, see Revisiting ResNets: Improved Training and Scaling Strategies.

You can choose the size of the model to train by changing the config_file in the following command.

(vm)$ python3 /usr/share/models/official/vision/beta/train.py \
  --experiment=resnet_rs_imagenet \
  --mode=train_and_eval \
  --model_dir=$MODEL_DIR \
  --tpu=$TPU_NAME \
  --config_file=/usr/share/models/official/vision/beta/configs/experiments/image_classification/imagenet_resnetrs200_i256.yaml \
  --params_override="task.train_data.input_path=$IMAGENET_DIR/train*, task.validation_data.input_path=$IMAGENET_DIR/valid*"

The available configs are in /usr/share/models/official/vision/beta/configs/experiments/ on your VM.

Scale your model with Cloud TPU Pods

Training your model on Cloud TPU Pods may require some changes to your training script. For information, see Training on TPU Pods.

You can get results faster by scaling your model with Cloud TPU Pods. The fully supported ResNet-RS-50 model can work with the following Pod slices:

  • v2-32
  • v3-32

With Cloud TPU Pods, training and evaluation are done together.

Training with Cloud TPU Pods

  1. Delete the Cloud TPU resource you created for training the model on a single device.

    (vm)$ gcloud compute tpus execution-groups delete resnet-rs-tutorial \
      --zone=europe-west4-a \
      --tpu-only
  2. Create a new Cloud TPU resource for the Pod, 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 --name=resnet-rs-tutorial \
      --accelerator-type=v3-32  \
      --zone=europe-west4-a \
      --tf-version=2.12.0 \
      --tpu-only
    

    Command flag descriptions

    name
    The name of the Cloud TPU to create.
    accelerator-type
    The type of the Cloud TPU to create.
    zone
    The zone where you plan to create your Cloud TPU.
    tf-version
    The version of Tensorflow gcloud installs on the VM.
    tpu-only
    Create a Cloud TPU only. By default the gcloud command creates a VM and a Cloud TPU.
  3. Run the training script.

    (vm)$ python3 /usr/share/models/official/vision/beta/train.py \
    --experiment=resnet_rs_imagenet \
    --mode=train_and_eval \
    --model_dir=$MODEL_DIR \
    --tpu=$TPU_NAME \
    --config_file=/usr/share/models/official/vision/beta/configs/experiments/image_classification/imagenet_resnetrs50_i160.yaml \
    --params_override="task.train_data.input_path=$IMAGENET_DIR/train*, task.validation_data.input_path=$IMAGENET_DIR/valid*, trainer.train_steps=100"
    

    Command flag descriptions

    experiment
    The name of experiment to run.
    mode
    The mode in which to run the script. Valid values are: `train`, `eval`, or `train_and_eval`.
    model_dir
    The Cloud Storage bucket where checkpoints and summaries are stored during training. You can use an existing folder to load previously generated checkpoints created on a TPU of the same size and TensorFlow version.
    tpu
    The name of the TPU to use.
    config_file
    The path to a script configuration file.
    params_override
    Override settings set in the script configuration file.

This will train ResNet-RS for 100 training steps and will complete on a v3-8 TPU node in less than 5 minutes. The training script output should include text like:

{
  'train_loss': 1.435225,
  'train_accuracy': 0.00084427913
}

The training script also performs evaluation. The evaluation output should contain text like this:

Run stats:
{
  'eval_loss': 0.861013,
  'eval_acc': 0.001,
  'train_loss': 1.435225,
  'train_acc': 0.00084427913,
  'step_timestamp_log': [
    'BatchTimestamp<batch_index: 0,
    timestamp: 1606330585.7613473>',
    'BatchTimestamp<batch_index: 500,
    timestamp: 1606330883.8486104>',
    'BatchTimestamp<batch_index: 1000,
    timestamp: 1606331119.515312>',
    'BatchTimestamp<batch_index: 1251,
    timestamp: 1606331240.7516596>'
  ],
  'train_finish_time': 1606331296.395158,
  'avg_exp_per_second': 1951.6983246161021
}

Training and evaluation are done together. Each epoch has 1251 steps for a total of 112590 training steps and 48 evaluation steps.

Clean 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. In your Cloud Shell, use the following command to delete your Compute Engine VM and Cloud TPU:

    $ gcloud compute tpus execution-groups delete resnet-rs-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
    

    You should see an empty list of TPUs like the following:

       NAME             STATUS
    
  4. Delete your Cloud Storage bucket using gsutil as shown below. Replace bucket-name with the name of your Cloud Storage bucket.

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

What's next

The TensorFlow Cloud TPU tutorials generally train the model using a sample dataset. The results of this training are not usable for inference. To use a model for inference, you can train the data on a publicly available dataset or your own dataset. TensorFlow models trained on Cloud TPUs generally 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 and Tune hyperparameters.

Inference

Once you have trained your model, you can use it for inference (also called prediction). You can use the Cloud TPU inference converter tool to prepare and optimize a TensorFlow model for inference on Cloud TPU v5e. For more information about inference on Cloud TPU v5e, see Cloud TPU v5e inference introduction.