Training ShapeMask on Cloud TPU (TF 2.x)

This document demonstrates how to run the ShapeMask model using Cloud TPU with the COCO dataset.

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

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

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

Set up your resources

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

  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 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 virtual machine (VM) and your TPU node. VMs and TPU nodes are located in specific zones, which are subdivisions within a region.

  6. Launch a Compute Engine VM instance.

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

    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.

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

  7. The configuration you specified appears. Enter y to approve or n to cancel.

    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 shapemask-tutorial --zone=europe-west4-a
    

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

  8. Create an environment variable to store your Cloud Storage bucket location.

    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    
  9. Create an environment variable for the data directory.

    (vm)$ export DATA_DIR=${STORAGE_BUCKET}/coco
    
  10. Clone the tpu repository.

    (vm)$ git clone -b shapemask https://github.com/tensorflow/tpu/
    
  11. 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"
    

Prepare the COCO dataset

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

  2. 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 and start the Cloud TPU

  1. Launch a Cloud TPU resource using the gcloud command.

    (vm)$ gcloud compute tpus execution-groups create \
     --tpu-only \
     --accelerator-type=v3-8  \
     --name=shapemask-tutorial \
     --zone=europe-west4-a \
     --tf-version=2.4.1
    

    Command flag descriptions

    tpu-only
    Creates the Cloud TPU without creating a VM. By default the gcloud compute tpus execution-groups command creates a VM and a Cloud TPU.
    tpu-size
    The type of the Cloud TPU to create.
    name
    The name of the Cloud TPU to create.
    zone
    The zone where you plan to create your Cloud TPU.
    tf-version
    The version of Tensorflow gcloud compute tpus execution-groups installs on the VM.
  2. Add an environment variable for your Cloud TPU's name.

    (vm)$ export TPU_NAME=shapemask-tutorial
    
  3. The configuration you specified appears. Enter y to approve or n to cancel.

    You will see a message: Operation success; not ssh-ing to Compute Engine VM due to --tpu-only flag. Since you previously completed SSH key propagation, you can ignore this message.

  4. Add an environment variable for your Cloud TPU's name.

    (vm)$ export TPU_NAME=shapemask-tutorial
    

Run the training and evaluation

The following script runs a sample training that trains for just 100 steps and takes approxiately 6 minutes to complete on a v3-8 TPU. To train to convergence takes about 22,500 steps and approximately 6 hours on a v3-8 TPU.

  1. Add some required environment variables:

    (vm)$ export PYTHONPATH="${PYTHONPATH}:/usr/share/models"
    (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
    (vm)$ export SHAPE_PRIOR_PATH=gs://cloud-tpu-checkpoints/shapemask/kmeans_class_priors_91x20x32x32.npy
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/shapemask
    
  2. Run the following script to train the ShapeMask model:

    (vm)$ python3 /usr/share/models/official/vision/detection/main.py \
    --strategy_type=tpu \
    --tpu=${TPU_NAME} \
    --model_dir=${MODEL_DIR} \
    --mode=train \
    --model=shapemask \
    --params_override="{train: {total_steps: 100, learning_rate: {init_learning_rate: 0.08, learning_rate_levels: [0.008, 0.0008], learning_rate_steps: [15000, 20000], }, checkpoint: { path: ${RESNET_CHECKPOINT},prefix: resnet50}, train_file_pattern: ${TRAIN_FILE_PATTERN}}, shapemask_head: {use_category_for_mask: true, shape_prior_path: ${SHAPE_PRIOR_PATH}}, shapemask_parser: {output_size: [640, 640]}}"
    

    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
    One of train, eval, or train_and_eval.
    model
    The model to train.
    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 training script output should look like this:

    Train Step: 100/100  / loss = {
     'total_loss': 10.152124404907227,
     'loss': 10.152124404907227,
     'retinanet_cls_loss': 1.3409545421600342,
     'l2_regularization_loss': 4.6183762550354,
     'retinanet_box_loss': 0.012389584444463253,
     'shapemask_prior_loss': 0.183448925614357,
     'shapemask_coarse_mask_loss': 1.7648673057556152,
     'shapemask_fine_mask_loss': 1.790102243423462,
     'model_loss': 5.533748626708984,
     'learning_rate': 0.021359999
    }
    / training metric = {
    'total_loss': 10.152124404907227,
    'loss': 10.152124404907227,
    'retinanet_cls_loss': 1.3409545421600342,
    'l2_regularization_loss': 4.6183762550354,
    'retinanet_box_loss': 0.012389584444463253,
    'shapemask_prior_loss': 0.183448925614357,
    'shapemask_coarse_mask_loss': 1.7648673057556152,
    'shapemask_fine_mask_loss': 1.790102243423462,
    'model_loss': 5.533748626708984,
    'learning_rate': 0.021359999
    }
  3. Run the script to evaluate the ShapeMask model:

    (vm)$ python3 /usr/share/models/official/vision/detection/main.py \
    --strategy_type=tpu \
    --tpu=${TPU_NAME} \
    --model_dir=${MODEL_DIR} \
    --checkpoint_path=${MODEL_DIR} \
    --mode=eval_once \
    --model=shapemask \
    --params_override="{eval: { val_json_file: ${VAL_JSON_FILE}, eval_file_pattern: ${EVAL_FILE_PATTERN}, eval_samples: 5000 }, shapemask_head: {use_category_for_mask: true, shape_prior_path: ${SHAPE_PRIOR_PATH}}, shapemask_parser: {output_size: [640, 640]}}"
    

    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
    One of train, eval, or train_and_eval.
    model
    The model to train.
    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 evaluation script output should look like this:

756s 62ms/step
- loss: 0.4864
- accuracy: 0.8055
- val_loss: 0.3832
- val_accuracy: 0.8546

From here, you can either conclude this tutorial and clean up your GCP resources, or you can further explore running the model on a Cloud TPU Pod.

Scaling your model with Cloud TPU Pods

You can get results faster by scaling your model with Cloud TPU Pods. The fully supported Mask RCNN model can work with the following Pod slices:

  • v2-32
  • v3-32

When working with Cloud TPU Pods, you first train the model using a Pod, then use a single Cloud TPU device to evaluate the model.

Training with Cloud TPU Pods

If you have already deleted your Compute Engine instance, create a new one following the steps in Set up your resources.

The sample training below runs for just 20 steps and takes approximately 10 minutes to complete on a v3-32 TPU node. To train to convergence takes about 11,250 steps and approximately 2 hours on a v3-32 TPU Pod.

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

    (vm)$ gcloud compute tpus execution-groups delete shapemask-tutorial \
      --zone=europe-west4-a \
      --tpu-only
  2. 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.

    (vm)$ gcloud compute tpus execution-groups  create --name=shapemask-tutorial \
      --accelerator-type=v3-32  \
      --zone=europe-west4-a \
      --tf-version=2.4.1 \
      --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. Update the TPU_NAME and MODEL_DIR environment variables.

    (vm)$ export TPU_NAME=shapemask-tutorial
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/shapemask-pods
    
  4. Start 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 \
    --model=shapemask \
    --params_override="{train: { batch_size: 128, iterations_per_loop: 500, total_steps: 20, learning_rate: {'learning_rate_levels': [0.008, 0.0008],'learning_rate_steps': [10000, 13000]}, 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}},shapemask_head: {use_category_for_mask: true, shape_prior_path: ${SHAPE_PRIOR_PATH}}}"
    

    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
    One of train, eval, or train_and_eval.
    model
    The model to train.
    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 training script output should look like the following:

Train Step: 20/20  / loss = {
  'total_loss': 12.213006973266602,
  'loss': 12.213006973266602,
  'retinanet_cls_loss': 1.9299328327178955,
  'l2_regularization_loss': 4.628948211669922,
  'retinanet_box_loss': 0.016126759350299835,
  'shapemask_prior_loss': 0.16990719735622406,
  'shapemask_coarse_mask_loss': 3.688129425048828,
  'shapemask_fine_mask_loss': 1.1426670551300049,
  'model_loss': 7.584057807922363,
  'learning_rate': 0.009632
}
/ training metric = {
  'total_loss': 12.213006973266602,
  'loss': 12.213006973266602,
  'retinanet_cls_loss': 1.9299328327178955,
  'l2_regularization_loss': 4.628948211669922,
  'retinanet_box_loss': 0.016126759350299835,
  'shapemask_prior_loss': 0.16990719735622406,
  'shapemask_coarse_mask_loss': 3.688129425048828,
  'shapemask_fine_mask_loss': 1.1426670551300049,
  'model_loss': 7.584057807922363,
  'learning_rate': 0.009632
}

Evaluating the model

In this step, you use a single Cloud TPU node to evaluate the above trained model against the COCO dataset. The evaluation takes about 20 minutes.

  1. Delete the Cloud TPU resource you created to train the model on a Pod.

    (vm)$ gcloud compute tpus execution-groups delete shapemask-tutorial \
      --zone=europe-west4-a \
      --tpu-only
  2. Launch a new TPU device to run evaluation.

    (vm)$ gcloud compute tpus execution-groups create --tpu-only \
      --name=shapemask-tutorial \
      --accelerator-type=v3-8 \
      --zone=europe-west4-a \
      --tf-version=2.4.1 \
    
    

    Command flag descriptions

    tpu-only
    Create a Cloud TPU only. By default the gcloud command creates a VM and a Cloud TPU.
    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.
  3. Update the TPU_NAME environment variable.

    (vm)$ export TPU_NAME=shapemask-tutorial
    
  4. Start the evaluation.

    (vm)$ python3 /usr/share/models/official/vision/detection/main.py \
    --strategy_type=tpu \
    --tpu=shapemask-tutorial \
    --model_dir=${MODEL_DIR} \
    --checkpoint_path=${MODEL_DIR} \
    --mode=eval_once \
    --model=shapemask \
    --params_override="{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
    One of train, eval, or train_and_eval.
    model
    The model to train.
    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.

Cleaning 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 shapemask-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

Train with different image sizes

You can explore using a larger neural network (for example, ResNet-101 instead of ResNet-50). A larger input image and a more powerful neural network 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 ShapeMask model. With some more work, you can also swap in an alternative neural 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.