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

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

Costs

This tutorial uses 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 Cloud project. Learn how to confirm that billing is enabled for your 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 Cloud project. Learn how to confirm that billing is enabled for your 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.

Prepare the COCO dataset

This tutorial uses the COCO dataset. The dataset needs to be in TFRecord format on a Cloud Storage bucket to be used for the training.

If you already have the COCO dataset prepared on a Cloud Storage bucket that is located in the zone you will be using to train the model, you can go directly to single device training. Otherwise, use the following steps to prepare the dataset.

  1. Open a Cloud Shell window.

    Open Cloud Shell

  2. In your Cloud Shell, create a Cloud Storage bucket using the following command:

    gsutil mb -p ${PROJECT_ID} -c standard -l europe-west4 gs://bucket-name
    
  3. Launch a Compute Engine VM instance.

    This VM instance will only be used to download and preprocess the COCO dataset. Fill in the instance-name with a name of your choosing.

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

    Command flag descriptions

    vm-only
    Create a VM only. By default the gcloud compute tpus execution-groups command creates a VM and a Cloud TPU.
    name
    The name of the Cloud TPU to create.
    zone
    The zone where you plan 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.
    tf-version
    The version of Tensorflow gcloud compute tpus execution-groups installs on the VM.
  4. 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:

      $ gcloud compute ssh instance-name --zone=europe-west4-a
      

  5. Set up two variables, one for the storage bucket you created earlier and one for the directory that holds the training data (DATA_DIR) on the storage bucket.

    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    
    (vm)$ export DATA_DIR=${STORAGE_BUCKET}/coco
  6. Install the packages needed to pre-process the data.

    (vm)$ sudo apt-get install -y python3-tk && \
      pip3 install --user Cython matplotlib opencv-python-headless pyyaml Pillow && \
      pip3 install --user "git+https://github.com/cocodataset/cocoapi#egg=pycocotools&subdirectory=PythonAPI"
    
  7. 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)$ git clone https://github.com/tensorflow/tpu.git
    (vm)$ sudo bash 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.

  8. 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}
    
  9. Clean up the VM resources

    Once the COCO dataset has been converted to TFRecords and copied to the DATA_DIR on your Cloud Storage bucket, you can delete the Compute Engine instance.

    Disconnect from the Compute Engine instance:

    (vm)$ exit
    

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

  10. Delete your Compute Engine instance.

      $ gcloud compute instances delete instance-name
        --zone=europe-west4-a
      

Training Retinanet on a single device TPU

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

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

Set up and start the Cloud TPU

  1. 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 retinanet-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  \
     --zone=europe-west4-a \
     --name=retinanet-tutorial \
     --accelerator-type=v3-8 \
     --machine-type=n1-standard-8 \
     --disk-size=300 \
     --tf-version=2.7.0
    

    Command flag descriptions

    zone
    The zone where you plan to create your Cloud TPU.
    accelerator-type
    The type of the Cloud TPU to create.
    machine-type
    The machine type of the Compute Engine VM to create.
    disk-size
    The root volume size of your Compute Engine VM (in GB).
    tf-version
    The version of TensorFlow gcloud installs on the VM.

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

  2. 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 retinanet-tutorial --zone=europe-west4-a
    

    TPU Node

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

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

  3. 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'
    
  4. Install TensorFlow requirements.

    TPU VM

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

    TPU Node

    (vm)$ pip3 install --user -r /usr/share/models/official/requirements.txt
    
  5. Set the Cloud TPU name variable.

    TPU VM

    (vm)$ export TPU_NAME=local
    

    TPU Node

    (vm)$ export TPU_NAME=retinanet-tutorial
    
  6. Add environment variables for the data and model directories.

    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    
    (vm)$ export DATA_DIR=${STORAGE_BUCKET}/coco
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/retinanet-train
    
  7. Set the PYTHONPATH environment variable:

    TPU VM

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

    TPU Node

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

    TPU VM

    (vm)$ cd ~/models/official/vision/detection
    

    TPU Node

    (vm)$ cd /usr/share/models/official/vision/detection
    

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

The model will train for 10 steps in about 5 minutes on a v3-8 TPU. When the training completes, you will see output similar to the following:

Train Step: 10/10  / loss = {
  'total_loss': 2.4581615924835205,
  'cls_loss': 1.4098565578460693,
  'box_loss': 0.012001709081232548,
  'model_loss': 2.0099422931671143,
  'l2_regularization_loss': 0.44821977615356445,
  'learning_rate': 0.008165999
}
/ training metric = {
  'total_loss': 2.4581615924835205,
  'cls_loss': 1.4098565578460693,
  'box_loss': 0.012001709081232548,
  'model_loss': 2.0099422931671143,
  'l2_regularization_loss': 0.44821977615356445,
 'learning_rate': 0.008165999
}

Single Cloud TPU device evaluation

The following procedure uses the COCO evaluation data. It takes about 10 minutes to run through the evaluation steps on a v3-8 TPU.

  1. Set up the following environment variables:

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

    (vm)$ python3 main.py \
          --strategy_type=tpu \
          --tpu=${TPU_NAME} \
          --model_dir=${MODEL_DIR} \
          --checkpoint_path=${MODEL_DIR} \
          --mode=eval_once \
          --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
    The distribution strategy to use. Either tpu or multi_worker_gpu.
    tpu
    The name of the Cloud TPU. This is set using the TPU_NAME environment variable.
    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.
    mode
    One of train, eval, or train_and_eval.
    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
    

You have now completed single-device training and evaluation. 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 retinanet-tutorial \
    --zone=europe-west4-a
    

    Command flag descriptions

    zone
    The zone where your Cloud TPU resided.

    TPU Node

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

Training Retinanet on a TPU Pod

  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.

    Service accounts allow the Cloud TPU service to access other Google Cloud Platform services.

    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.

    In the following command, replace europe-west4 with the name of the region you will use to run the training. Replace bucket-name with the name you want to assign to your bucket.

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

  6. If you previously prepared the COCO dataset and moved it to your storage bucket, you can use it again for Pod training. If you have not yet prepared the COCO dataset, prepare it now and return here to set up the training.

  7. Set up and launch a Cloud TPU Pod

    This tutorial specifies a v3-32 Pod. For other Pod options, see the available TPU types page.

    TPU VM

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

    TPU Node

    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.

    $ gcloud compute tpus execution-groups create  \
     --zone=europe-west4-a \
     --name=retinanet-tutorial \
     --accelerator-type=v3-32 \
     --machine-type=n1-standard-8 \
     --disk-size=300 \
     --tf-version=2.7.0 

    Command flag descriptions

    zone
    The zone where you plan to create your Cloud TPU.
    name
    The TPU name. If not specified, defaults to your username.
    accelerator-type
    The type of the Cloud TPU to create.
    machine-type
    The machine type of the Compute Engine VM to create.
    tf-version
    The version of Tensorflow gcloud installs on the VM.
  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 retinanet-tutorial --zone=europe-west4-a
    

    TPU Node

    gcloud compute ssh retinanet-tutorial --zone=europe-west4-a
    
  9. Set the Cloud TPU name variable.

    (vm)$ export TPU_NAME=retinanet-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}/retinanet-train
    (vm)$ export DATA_DIR=${STORAGE_BUCKET}/coco
    

    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 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' 
  12. Install TensorFlow requirements.

    TPU VM

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

    TPU Node

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

    (vm)$ export RESNET_PRETRAIN_DIR=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
    
  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/detection

    TPU Node

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

    TPU VM

    (vm)$ python3 main.py \
    --strategy_type=tpu \
    --tpu=${TPU_NAME} \
    --model_dir=${MODEL_DIR} \
    --mode=train \
    --model=retinanet \
    --params_override="{architecture: {use_bfloat16: true}, eval: {batch_size: 40, eval_file_pattern: ${EVAL_FILE_PATTERN}, val_json_file: ${VAL_JSON_FILE}}, postprocess: {pre_nms_num_boxes: 1000}, predict: {batch_size: 40}, train: {batch_size: 256, checkpoint: {path: ${RESNET_PRETRAIN_DIR}, prefix: resnet50/}, iterations_per_loop: 5000, total_steps: 5625, train_file_pattern: ${TRAIN_FILE_PATTERN}, } }" 

    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 Cloud TPU of the same size and TensorFlow version.
    params_override
    A JSON string that overrides default script parameters. For more information on script parameters, see ~/models/official/vision/detection/main.py.

    This procedure trains the model on the COCO dataset for 5625 training steps. This training takes approximately 20 minutes on a v3-32 Cloud TPU. When the training completes, a message similar to the following appears:

    TPU Node

    The following sample training script was run on a Cloud TPU v3-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 v3-32 TPU Pod.

    (vm)$  python3 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

    strategy_type
    The distribution strategy to use. Either tpu or multi_worker_gpu.
    tpu
    Specifies the name of the Cloud TPU. This is set using the TPU_NAME environment variable.
    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.
    mode
    One of train, eval, or train_and_eval.
    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.

When the training completes, a message similar to the following appears:

TPU VM

Train Step: 5625/5625  / loss = {'total_loss': 0.730501651763916,
'cls_loss': 0.3229793608188629, 'box_loss': 0.003082591574639082,
'model_loss': 0.4771089553833008, 'l2_regularization_loss': 0.2533927261829376,
'learning_rate': 0.08} / training metric = {'total_loss': 0.730501651763916,
'cls_loss': 0.3229793608188629, 'box_loss': 0.003082591574639082, 
'model_loss': 0.4771089553833008, 'l2_regularization_loss': 0.2533927261829376,
'learning_rate': 0.08} 

TPU Node

Train Step: 10/10  / loss = {'total_loss': 3.5455241203308105,
'cls_loss': 1.458828330039978, 'box_loss': 0.01220895815640688,
'model_loss': 2.0692763328552246, 'l2_regularization_loss': 1.4762479066848755,
'learning_rate': 0.008165999} / training metric = {'total_loss': 3.5455241203308105,
'cls_loss': 1.458828330039978, 'box_loss': 0.01220895815640688,
'model_loss': 2.0692763328552246, 'l2_regularization_loss': 1.4762479066848755,
'learning_rate': 0.008165999}

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 VM:

    (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 retinanet-tutorial \
    --zone=europe-west4-a
    

    TPU Node

    $ gcloud compute tpus execution-groups delete retinanet-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. 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 (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. 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, 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.