Training RetinaNet on Cloud TPU (TF 2.x)

This document describes an implementation of the RetinaNet object detection model. The code is available on GitHub.

The instructions below assume you are already familiar with running a model on Cloud TPU. If you are new to Cloud TPU, you can refer to the Quickstart for a basic introduction.

If you plan to train on a TPU Pod slice, review Training on TPU Pods to understand parameter changes required for Pod slices.

Objectives

  • Create a Cloud Storage bucket to hold your dataset and model output
  • Prepare the COCO dataset
  • Set up a Compute Engine VM and Cloud TPU node for training and evaluation
  • Run training and evaluation on a single Cloud TPU or a Cloud TPU Pod

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

This section provides information on setting up Cloud Storage bucket and a Compute Engine VM.

  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:

    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 ctpu up 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.

  6. Launch a Compute Engine VM using the ctpu up command.

    $ ctpu up --project=${PROJECT_ID} \
     --vm-only \
     --name=retinanet-tutorial \
     --disk-size-gb=300 \
     --machine-type=n1-standard-8 \
     --zone=europe-west4-a \
     --tf-version=2.3.1
    

    Command flag descriptions

    project
    Your GCP project ID
    vm-only
    Creates the VM without creating a Cloud TPU. By default the ctpu up command creates a VM and a Cloud TPU.
    name
    The name of the Cloud TPU to create.
    disk-size-gb
    The size of the hard disk in GB of the VM created by the ctpu up command.
    machine-type
    The machine type of the Compute Engine VM to create.
    zone
    The zone where you plan to create your Cloud TPU.
    tf-version
    The version of Tensorflow ctpu installs on the VM.

    For more information on the CTPU utility, see the CTPU Reference.

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

    When the ctpu up 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 retinanet-tutorial --zone=europe-west4-a
    

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

  8. Install extra packages

    The RetinaNet training application requires several extra packages. Install them now:

    (vm)$ sudo apt-get install -y python3-tk
    (vm)$ pip3 install --user Cython matplotlib opencv-python-headless pyyaml Pillow
    
    (vm)$ pip3 install --user 'git+https://github.com/cocodataset/cocoapi#egg=pycocotools&subdirectory=PythonAPI'
    
    (vm)$ sudo pip3 install --user -r /usr/share/models/official/requirements.txt
    

Prepare the COCO dataset

The COCO dataset will be stored on your Cloud Storage, so set a storage bucket variable specifying the name of the bucket you created:

(vm)$ export STORAGE_BUCKET=gs://bucket-name
(vm)$ export DATA_DIR=${STORAGE_BUCKET}/coco

Run the download_and_preprocess_coco.sh script to convert the COCO dataset into a set of TFRecords (*.tfrecord) that the training application expects.

(vm)$ sudo bash /usr/share/tpu/tools/datasets/download_and_preprocess_coco.sh ./data/dir/coco

This installs the required libraries and then runs the preprocessing script. It outputs a number of *.tfrecord files in your local data directory. The COCO download and conversion script takes approximately 1 hour to complete.

Copy the data to your Cloud Storage bucket

After you convert the data into TFRecords, copy them from local storage to your Cloud Storage bucket using the gsutil command. You must also copy the annotation files. These files help validate the model's performance.

(vm)$ gsutil -m cp ./data/dir/coco/*.tfrecord ${DATA_DIR}
(vm)$ gsutil cp ./data/dir/coco/raw-data/annotations/*.json ${DATA_DIR}

Set up the training environment

  1. Create a Cloud TPU using the ctpu up command.

    (vm)$ ctpu up --project=${PROJECT_ID} \
      --tpu-only \
      --tpu-size=v3-8 \
      --zone=europe-west4-a \
      --name=retinanet-tutorial \
      --tf-version=2.3.1
    

    For more information on the CTPU utility, see the CTPU Reference.

    Command flag descriptions

    project
    Your GCP project ID
    tpu-only
    Create a Cloud TPU only. By default the ctpu up command creates a VM and a Cloud TPU.
    tpu-size
    The type of the Cloud TPU to create.
    zone
    The zone where you plan to create your Cloud TPU.
    name
    The name of the Cloud TPU to create.
    tf-version
    The version of Tensorflow ctpu installs on the VM.

    For more information on the CTPU utility, see the CTPU Reference.

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

    When the ctpu up 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 retinanet-tutorial --zone=europe-west4-a
    

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

  3. Create an environment variable for the TPU name.

    (vm)$ export TPU_NAME=retinanet-tutorial
    
  4. Add the top-level /models folder to the Python path with the command:

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

Single Cloud TPU device training

The following training scripts were run on a Cloud TPU v3-8. It will take more time, but you can also run them on a Cloud TPU v2-8.

This sample script below trains for only 10 steps and takes less than 5 minutes to run on a v3-8 TPU Node. To train to convergence takes about 22,500 steps and approximately 1 1/2 hours on a Cloud TPU v3-8 TPU.

  1. Set up the following environment variables:

    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/retinanet-train
    (vm)$ export RESNET_CHECKPOINT=gs://cloud-tpu-checkpoints/retinanet/resnet50-checkpoint-2018-02-07
    (vm)$ export TRAIN_FILE_PATTERN=${DATA_DIR}/train-*
    (vm)$ export EVAL_FILE_PATTERN=${DATA_DIR}/val-*
    (vm)$ export VAL_JSON_FILE=${DATA_DIR}/instances_val2017.json
    
  2. Run the training script:

    (vm)$ python3 /usr/share/models/official/vision/detection/main.py \
         --strategy_type=tpu \
         --tpu=${TPU_NAME} \
         --model_dir=${MODEL_DIR} \
         --mode="train" \
         --params_override="{ type: retinanet, train: { total_steps: 10, checkpoint: { path: ${RESNET_CHECKPOINT}, prefix: resnet50/ }, train_file_pattern: ${TRAIN_FILE_PATTERN} }, eval: { val_json_file: ${VAL_JSON_FILE}, eval_file_pattern: ${EVAL_FILE_PATTERN}, eval_samples: 5000 } }"
    

    Command flag descriptions

    strategy_type
    To train the RetinaNet model on a TPU, you must set the distribution_strategy to tpu.
    tpu
    The name of the Cloud TPU. This is set using the TPU_NAME environment variable.
    model_dir
    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.
    mode
    Set this to train to train the model or eval to evaluate the model.
    params_override
    A JSON string that overrides default script parameters. For more information on script parameters, see /usr/share/models/official/vision/detection/main.py.

While the model is training, you can see the progress by viewing the log output. Output similar to the following shows the training is progressing normally:

31517803669, 'learning_rate': 0.08, 'box_loss': 0.0006472870009019971,
'l2_regularization_loss': 0.09328179806470871}
I0210 21:59:19.888985 139927795508992 distributed_executor.py:49]
Saving model as TF checkpoint: gs://bucket-eu/retinanet-model/ctl_step_2500.ckpt-5
I0210 22:01:07.714749 139927795508992 distributed_executor.py:446]
Train Step: 3000/22500  / loss = {'model_loss': 0.08362223953008652,
'total_loss': 0.17120523750782013, 'cls_loss': 0.057121846824884415,
'learning_rate': 0.08, 'box_loss': 0.0005300078773871064,
'l2_regularization_loss': 0.08758299797773361} / training metric =
{'model_loss': 0.08362223953008652, 'total_loss': 0.17120523750782013, 'cls_loss': 0.0
57121846824884415, 'learning_rate': 0.08, 'box_loss': 0.0005300078773871064,
'l2_regularization_loss': 0.08758299797773361}
I0210 22:01:15.813422 139927795508992 distributed_executor.py:49]
Saving model as TF checkpoint: gs://bucket-eu/retinanet-model/ctl_step_3000.ckpt-6

Single Cloud TPU device evaluation

The following procedure uses the COCO evaluation data. It takes about 10 minutes to run through the evaluation steps.

  1. Set up the following environment variables:

    (vm)$ export EVAL_SAMPLES=5000
    
  2. Run the evaluation script:

    (vm)$ python3 /usr/share/models/official/vision/detection/main.py \
          --strategy_type=tpu \
          --tpu=${TPU_NAME} \
          --model_dir=${MODEL_DIR} \
          --mode="eval" \
          --params_override="{ type: retinanet, eval: { val_json_file: ${VAL_JSON_FILE}, eval_file_pattern: ${EVAL_FILE_PATTERN}, eval_samples: ${EVAL_SAMPLES} } }"
    

    Command flag descriptions

    strategy_type
    To train the RetinaNet model on a TPU, you must set the distribution_strategy to tpu.
    tpu
    The name of the Cloud TPU. This is set using the TPU_NAME environment variable.
    model_dir
    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.
    mode
    Set model to eval to evaluate the model.
    params_override
    A JSON string that overrides default script parameters. For more information on script parameters, see /usr/share/models/official/vision/detection/main.py.

    At the end of the evaluation, you will see messages similar to the following on the console:

    Accumulating evaluation results...
    DONE (t=7.66s).
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.000
     Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.000
     Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.000
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.000
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.000
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.000
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.000
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.000
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.000
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.000
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.000
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.000
    

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

Scaling your model with Cloud TPU Pods

You can get results faster by scaling your model with Cloud TPU Pods. The fully supported RetinaNet model can work with the v2-32 Pod slice:

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

    (vm)$ ctpu delete --project=${PROJECT_ID} \
     --tpu-only \
     --zone=europe-west4-a \
     --name=retinanet-tutorial
  2. Run the ctpu up command, using the tpu-size parameter to specify the Pod slice you want to use. For example, the following command uses a v2-32 Pod slice.

    (vm)$ ctpu up --project=${PROJECT_ID} \
      --tpu-only \
      --tpu-size=v2-32  \
      --zone=europe-west4-a \
      --name=retinanet-tutorial \
      --tf-version=2.3.1

    Command flag descriptions

    project
    Your GCP project ID
    tpu-only
    Creates the Cloud TPU only. By default the ctpu up command creates both a VM and a Cloud TPU.
    tpu-size
    The type of the Cloud TPU to create.
    zone
    The zone where you plan to create your Cloud TPU.
    name
    The name of the Cloud TPU to create.
    tf-version
    The version of Tensorflow ctpu installs on the VM.

    For more information on the CTPU utility, see the CTPU Reference.

  3. Set the Cloud TPU name variable. This will either be a name you set with the --name parameter or the default, your username:

    (vm)$ export TPU_NAME=retinanet-tutorial
    
  4. Set up the following environment variable:

    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/retinanet-pod
    
  5. Run the Pod training script on a v2-32 TPU node

    The following sample training script was run on a Cloud TPU v2-32 Pod. It trains for only 10 steps and takes less than 5 minutes to run. To train to convergence requires 2109 steps and takes approximately 50 minutes on a v2-32 TPU Pod.

    (vm)$  python3 /usr/share/models/official/vision/detection/main.py \
        --strategy_type=tpu \
        --tpu=${TPU_NAME} \
        --model_dir=${MODEL_DIR} \
        --mode="train" \
        --params_override="{ type: retinanet, train: { total_steps: 10, batch_size: 256, checkpoint: { path: ${RESNET_CHECKPOINT}, prefix: resnet50/ }, train_file_pattern: ${TRAIN_FILE_PATTERN} }, eval: { val_json_file: ${VAL_JSON_FILE}, eval_file_pattern: ${EVAL_FILE_PATTERN}, eval_samples: 5000 } }"
    

    Command flag descriptions

    tpu
    Specifies the name of the Cloud TPU. This is set using the TPU_NAME environment variable.
    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.

Cleaning up

To avoid incurring charges to your Google Cloud Platform account for the resources used in this tutorial:

  1. Disconnect from the Compute Engine VM:

    (vm)$ exit
    

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

  2. In your VM or the Cloud Shell, use the following command to delete your VM and Cloud TPU:

    $ ctpu delete --project=${PROJECT_ID} \
      --name=retinanet-tutorial \
      --zone=europe-west4-a
    
  3. Run ctpu status specifying your zone 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:

    $ ctpu status --project=${PROJECT_ID} \
      --name=retinanet-tutorial \
      --zone=europe-west4-a
    
    2018/04/28 16:16:23 WARNING: Setting zone to "europe-west4-a"
    No instances currently exist.
        Compute Engine VM:     --
        Cloud TPU:             --
    
  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 RetinaNet 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.

Train with different image sizes

You can explore using a larger backbone network (for example, ResNet-101 instead of ResNet-50). A larger input image and a more powerful backbone will yield a slower but more precise model.

Use a different basis

Alternatively, you can explore pre-training a ResNet model on your own dataset and using it as a basis for your RetinaNet model. With some more work, you can also swap in an alternative backbone network in place of ResNet. Finally, if you are interested in implementing your own object detection models, this network may be a good basis for further experimentation.