Training RetinaNet on Cloud TPU

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 haven't already done so, review the instructions for running the ResNet model on Cloud TPU.

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.

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. Be sure to clean up resources you create when you've finished with them to avoid unecessary charges.

Set up your resources

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

Create a Cloud Storage bucket

You need a Cloud Storage bucket to store 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. If you want finer-grain permissions, review the access level permissions.

The bucket you create must reside in the same region as your virtual machine (VM) and your Cloud TPU device or Cloud TPU slice (multiple TPU devices) do.

  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: If you want to use a Cloud TPU device, accept the default presented. If you want to use a Cloud TPU Pod slice, you must specify a region where Cloud TPU Pods are available.

Use the ctpu tool

This section demonstrates using the Cloud TPU provisioning tool (ctpu) for creating and managing Cloud TPU project resources. The resources are comprised of a virtual machine (VM) and a Cloud TPU resource that have the same name. These resources must reside in the same region/zone as the bucket you just created.

Run ctpu up to create resources

  1. Open a Cloud Shell window.

    Open Cloud Shell

  2. Run ctpu up and specify options for either a Cloud TPU device or Pod slice:

    You can use flags to change the following options:

    • --name - name of your Cloud TPU resource and your VM.
    • --zone - region and zone of the physical assets. The zone must be the same for the VM and Cloud TPU. The bucket must be in the same region.
    • --project name - name of an existing project.
    • --tpu_size - version and size of the Cloud TPU. The default is one device with 8 cores.
    • --disk-size-gb - disk size. Use only if your dataset requires more than the default 250GB.
    • --machine-type - virtual machine (VM) memory per CPU.
    • --preemptible - interruptable, but lower cost Cloud TPU.
  3. Set up either a Cloud TPU device or a Pod slice:

TPU Device

Set up a Cloud TPU device:

$ ctpu up

The following configuration message appears:

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.

TPU Pod

Set up a Cloud TPU slice with 32 Cloud TPU cores, 8 CPUs, a 500GB disk on the VM and the zone you are working in:

$ ctpu up --zone=us-central1-a --tpu-size=v2-32 --disk-size-gb=500 --machine-type n1-standard-8 --preemptible

The following configuration message appears:

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 creates a virtual machine (VM) and Cloud TPU services.

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.

Check for the RetinaNet model

If you are running on the prepared Compute Engine VM, the RetinaNet model files are in the following location:

(vm)$ ls /usr/share/tpu/models/official/retinanet/

You can also get the latest version from GitHub:

(vm)$ git clone https://github.com/tensorflow/tpu/
(vm)$ ls tpu/models/official/retinanet

Prepare the COCO dataset

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

Before you can train, you need to prepare the training data. The RetinaNet model has been configured to train on the COCO dataset.

The tpu/tools/datasets/download_and_preprocess_coco.sh script converts the COCO dataset into a set of TFRecords that the training application expects.

This requires at least 100GB of disk space for the target directory, and takes approximately 1 hour to complete. You can use the nohup command to keep the command running even if your terminal disconnects (for example if your laptop goes to sleep). If you don't have 100GB of space on your VM, you need to attach a data drive to your VM.

When you have a data directory available, you can run the preprocessing script:

(vm)$ cd tpu/tools/datasets
(vm)$ bash download_and_preprocess_coco.sh ./data/dir/coco

This installs the required libraries and then run the preprocessing script. It outputs a number of *.tfrecord files in your data directory. The script might take up to an hour to run.

You need to copy these files to Cloud Storage so they are accessible to the for training. You can use gsutil to copy the files over. You also need to save the annotation files: they are used to validate the model performance:

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

Install extra packages

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

(vm)$ sudo apt-get install -y python-tk
(vm)$ pip install Cython matplotlib
(vm)$ pip install 'git+https://github.com/cocodataset/cocoapi#egg=pycocotools&subdirectory=PythonAPI'

Run the model

  1. Run the training application for 100 steps to make sure everything is working and you can successfully write out checkpoints:

    (vm)$ RESNET_CHECKPOINT=gs://cloud-tpu-artifacts/resnet/resnet-nhwc-2018-10-14/model.ckpt-112602
    (vm)$ MODEL_DIR=${STORAGE_BUCKET}/retinanet-model
    
    (vm)$ python tpu/models/official/retinanet/retinanet_main.py \
     --tpu=$TPU_NAME \
     --train_batch_size=64 \
     --training_file_pattern=${STORAGE_BUCKET}/coco/train-* \
     --resnet_checkpoint=${RESNET_CHECKPOINT} \
     --model_dir=${MODEL_DIR} \
     --hparams=image_size=640 \
     --num_examples_per_epoch=100 \
     --num_epochs=1
     
    • --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).
    • --resnet_checkpoint specifies a pretrained checkpoint. RetinaNet requires a pre-trained image classification model (like ResNet) as a backbone network. This example uses a pretrained checkpoint created with the ResNet demonstration model. You can instead train your own ResNet model if desired, and specify a checkpoint from your ResNet model directory.

Evaluate the model while you train (optional)

You can measure the progress of the model on a validation set as it trains. As the evaluation code for RetinaNet does not currently run on the Cloud TPU VM, you need to run it on a CPU VM. Running through all of the validation images is time-consuming, so you might not want to stop the training to let the validation run. Instead, you can run the validation in parallel on a different VM. The validation runner scans the model directory for new checkpoints, and when it finds one, computes new evaluation metrics.

Evaluate on a CPU VM

Set up an evaluation CPU VM:

$ gcloud compute instances create \
 retinanet-eval-vm \
  --machine-type=n1-highcpu-64 \
  --image-project=ml-images \
  --image-family=tf-1-12 \
  --scopes=cloud-platform

You can now connect to the evaluation VM and start the evaluation loop.

Installing packages and checking the RetinaNet model

On your CPU VM, you need to install the following packages:

(vm)$ sudo apt-get install -y python-tk
(vm)$ pip install Cython matplotlib
(vm)$ pip install 'git+https://github.com/pdollar/coco.git#egg=pycocotools&subdirectory=PythonAPI'

You then need to grab the RetinaNet model code so you can evaluate:

(vm)$ git clone https://github.com/tensorflow/tpu

Running the evaluation

You can now run the evaluation script. First try a quick evaluation to test that you can read the model directory and validation files.

Set up a variable containing your Cloud Storage bucket and copy the annotation file created during preprocessing. Then run the model:

(vm)$ export STORAGE_BUCKET=gs://YOUR-BUCKET-NAME
(vm)$ gsutil cp ${STORAGE_BUCKET}/coco/instances_val2017.json .

(vm)$ python tpu/models/official/retinanet/retinanet_main.py  \
 --use_tpu=False \
 --validation_file_pattern=${STORAGE_BUCKET}/coco/val-* \
 --val_json_file=./instances_val2017.json \
 --model_dir=${STORAGE_BUCKET}/retinanet-model/ \
 --hparams=image_size=640 \
 --mode=eval \
 --num_epochs=1 \
 --eval_samples=10

The parameters num_epochs=1 and eval_samples=10 are used to ensure the script finishes quickly. Increase those to run over the full evaluation dataset, and to keep the evaluation script running until training is finished (15 epochs).

(vm)$ python tpu/models/official/retinanet/retinanet_main.py  \
 --use_tpu=False \
 --validation_file_pattern=${STORAGE_BUCKET}/coco/val-* \
 --val_json_file=./instances_val2017.json \
 --model_dir=${STORAGE_BUCKET}/retinanet-model/ \
 --hparams=image_size=640 \
 --num_epochs=15 \
 --mode=eval \
 --eval_samples=5000

It takes about 10 minutes to run through the 5000 evaluation steps. After finishing, the evaluator continues waiting for new checkpoints from the training application for up to 1 hour. You don't have to wait for the evaluation to finish though: you can go ahead and kick off a full training run now.

Run the training application again

Back on your original VM, you are now ready to run the model on preprocessed COCO data. Complete training takes less than 4 hours.

(vm)$ python tpu/models/official/retinanet/retinanet_main.py \
 --tpu=$TPU_NAME \
 --train_batch_size=64 \
 --training_file_pattern=${STORAGE_BUCKET}/coco/train-* \
 --resnet_checkpoint=${RESNET_CHECKPOINT} \
 --model_dir=${STORAGE_BUCKET}/retinanet-model/ \
 --hparams=image_size=640 \
 --num_epochs=15

Check the status of your training

Use TensorBoard to visualize the progress of your training.

If you set up an evaluation VM, it continually reads new checkpoints and output the evaluation events to the model_dir directory. You can view the current status of the training and evaluation in TensorBoard.

Follow the guide to setting up TensorBoard, then explore the Cloud TPU tools in TensorBoard.

Clean up

To avoid incurring charges to your GCP account for the resources used in this tutorial:

  1. Disconnect from the Compute Engine VM:

    (vm)$ exit
    

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

  2. In your Cloud Shell, run ctpu delete with the --zone flag you used when you set up the Cloud TPU to delete your Compute Engine VM and your Cloud TPU:

    $ ctpu delete [optional: --zone]
    

    The operation may take a few moments. A message 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:             --
    
  3. Run ctpu status with the --zone flag you used when you set up the Cloud TPU. This checks that your instance was deleted so you can avoid unnecessary charges for TPU usage.

  4. Run gsutil as shown, replacing YOUR-BUCKET-NAME with the name of the Cloud Storage bucket you created for this tutorial:

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

If you used any additional Compute Engine VMs for the evaluation step, delete those instances too.

$ gcloud compute instances delete YOUR-INSTANCE-NAME

What's next

Train with different image sizes

The instructions in this tutorial assume you want to train on a 640x640 pixel image. You can try changing the image_size hparam to train on a smaller image, resulting in a faster but less precise model.

In addition, 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. You can specify the image_size hparam to be 768, 896, or 1024; also, the resnet_depth parameter can be one of 50 or 101.

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.

Larger batch sizes on TPU Pods

When using a Cloud TPU v2 Pod, you can reduce the training time by specifying a larger batch size. For example, use the batch size 64 on Cloud TPU v2-8 and batch size 256 on Cloud TPU v2-32. The model linearly scales the learning rate for a given batch size. See retinanet_model.py for more details.

(vm)$ python tpu/models/official/retinanet/retinanet_main.py \
 --tpu=${TPU_NAME} \
 --train_batch_size=256 \
 --num_cores=32 \
 --training_file_pattern=${GCS_BUCKET}/coco/train-* \
 --resnet_checkpoint=${RESNET_CHECKPOINT} \
 --model_dir=${GCS_BUCKET}/retinanet-model/ \
 --hparams=image_size=640 \
 --num_epochs=15

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

Send feedback about...