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

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 or GPU machine. 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.

You first need to start a GPU to run the evaluation script. This requires the additional setup described in the following section.

GPU evaluation VM

Start the VM:

$ gcloud compute instances create eval-vm  \
 --machine-type=n1-highcpu-16  \
 --image-project=ubuntu-os-cloud  \
 --image-family=ubuntu-1604-lts  \
 --scopes=cloud-platform \
 --accelerator type=nvidia-tesla-p100 \
 --maintenance-policy TERMINATE \
 --restart-on-failure

After a minute, you should be able to connect:

$ gcloud compute ssh eval-vm

You need to setup CUDA (NVIDIA's parallel computing platform) so Tensorflow can use your image. The following commands, run on the evaluation VM. They install CUDA and Tensorflow on a GPU VM. After the installation finishes, restart the VM.

(vm)$ cat > /tmp/setup.sh <<HERE
(vm)$ wget http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/cuda-repo-ubuntu1604_9.0.176-1_amd64.deb
(vm)$ dpkg -i ./cuda-repo-ubuntu1604_9.0.176-1_amd64.deb
(vm)$ apt-key adv --fetch-keys http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/7fa2af80.pub
(vm)$ apt-get update
(vm)$ apt-get install -y cuda-9-0
(vm)$ bash -c 'echo "deb http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64 /" > /etc/apt/sources.list.d/nvidia-ml.list'
(vm)$ apt-get update
(vm)$ apt-get install -y --no-install-recommends libcudnn7=7.0.5.15-1+cuda9.0
(vm)$ apt install -y python-pip python-tk
(vm)$ pip install tensorflow-gpu==1.8
(vm)$ HERE

(vm)$ sudo bash /tmp/setup.sh

You can also use a CPU VM for evaluation, which requires less setup, but is significantly slower:

$ 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 either VM type, as before, 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

  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.

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