Training Mask RCNN on Cloud TPU (TF 2.x)


Overview

This tutorial demonstrates how to run the Mask RCNN model using Cloud TPU with the COCO dataset.

Mask RCNN is a deep neural network designed to address object detection and image segmentation, one of the more difficult computer vision challenges.

The Mask RCNN model generates bounding boxes and segmentation masks for each instance of an object in the image. The model is based on the Feature Pyramid Network (FPN) and a ResNet50 backbone.

This tutorial uses Tensorflow Keras APIs to train the model. The Keras API is a high-level TensorFlow API that can be used to build and run a machine learning model on Cloud TPU. The API simplifies the model development process by hiding most of the low-level implementation, which makes it easier to switch between TPU and other platforms such as GPU or CPU.

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

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

In this document, you use 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 Google Cloud 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 Google Cloud 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, configure gcloud with your project ID.

    export PROJECT_ID=project-id
    gcloud config set project ${PROJECT_ID}
    
  3. 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
    
  4. 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.12.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.
  5. 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
      

  6. 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
  7. 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"
    
  8. 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.

  9. 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}
    
  10. 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.

  11. Delete your Compute Engine instance.

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

Cloud TPU single device training

  1. Open a Cloud Shell window.

    Open Cloud Shell

  2. Create an environment variable for your project's ID.

    export PROJECT_ID=project-id
  3. Configure Google Cloud CLI to use the project where you want to create the 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 Google Cloud 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. Export TPU setup variables

    Export your project ID, the name you want to use for your TPU resources, and the zone where you will train the model and store any training-related data.

    $ export TPU_NAME=mask-rcnn-tutorial
    $ export ZONE=europe-west4-a
    
  6. 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 architectures, see System Architecture.

    TPU VM

    $ gcloud compute tpus tpu-vm create mask-rcnn-tutorial \
    --zone=europe-west4-a \
    --accelerator-type=v3-8 \
    --version=tpu-vm-tf-2.16.1-pjrt
    

    Command flag descriptions

    zone
    The zone where you plan to create your Cloud TPU.
    accelerator-type
    The accelerator type specifies the version and size of the Cloud TPU you want to create. For more information about supported accelerator types for each TPU version, see TPU versions.
    version
    The Cloud TPU software version.

    TPU Node

    $ gcloud compute tpus execution-groups create  \
     --zone=europe-west4-a \
     --name=mask-rcnn-tutorial \
     --accelerator-type=v3-8 \
     --machine-type=n1-standard-8 \
     --disk-size=300 \
     --tf-version=2.12.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.
    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.

  7. 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 compute tpus tpu-vm ssh mask-rcnn-tutorial --zone=europe-west4-a
    

    TPU Node

    gcloud compute tpus execution-groups ssh mask-rcnn-tutorial --zone=europe-west4-a
    
  8. Install TensorFlow requirements.

    The command you use depends on whether you are using TPU VMs or TPU Nodes.

    TPU VM

    (vm)$ pip3 install -r /usr/share/tpu/models/official/requirements.txt 

    TPU Node

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

    TPU VM

    (vm)$ export TPU_NAME=local
    

    TPU Node

    (vm)$ export TPU_NAME=mask-rcnn-tutorial
    
  10. Set up the following environment variables, replacing bucket-name with the name of the Cloud Storage bucket that stores the COCO dataset:

    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    
  11. Add environment variables for the data and model directories.

    (vm)$ export DATA_DIR=${STORAGE_BUCKET}/coco
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/mask-rcnn
    
  12. Add some additional required 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
    
  13. Set the PYTHONPATH environment variable:

    TPU VM

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

    TPU Node

    (vm)$ export PYTHONPATH="${PYTHONPATH}:/usr/share/models"
    
  14. When creating your TPU, if you set the --version parameter to a version ending with -pjrt, set the following environment variables to enable the PJRT runtime:

      (vm)$ export NEXT_PLUGGABLE_DEVICE_USE_C_API=true
      (vm)$ export TF_PLUGGABLE_DEVICE_LIBRARY_PATH=/lib/libtpu.so
    
  15. Change to directory that stores the model:

    TPU VM

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

    TPU Node

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

The following script runs a sample training that trains for 10 training steps and 10 evaluation steps. It takes approximately 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. Run the following command to train Mask-RCNN model:

    (vm)$ python3 train.py \
      --tpu=${TPU_NAME} \
      --experiment=maskrcnn_resnetfpn_coco \
      --mode=train_and_eval \
      --config_file=configs/experiments/maskrcnn/r50fpn_640_coco_scratch_tpu4x4.yaml \
      --model_dir=${MODEL_DIR} \
      --params_override="task.train_data.input_path=${TRAIN_FILE_PATTERN},task.validation_data.input_path=${EVAL_FILE_PATTERN},task.annotation_file=${VAL_JSON_FILE},runtime.distribution_strategy=tpu,trainer.train_steps=10,trainer.validation_steps=10,task.train_data.global_batch_size=8,task.validation_data.global_batch_size=8"
    

    Command flag descriptions

    strategy_type
    The distribution strategy.
    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 TPU of the same size and TensorFlow version.

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

    {'frcnn_box_loss': 0.033865165,
     'frcnn_cls_loss': 1.2535654,
     'learning_rate': 0.008266499,
     'mask_loss': 1.2039567,
     'model_loss': 2.821458,
     'rpn_box_loss': 0.034982488,
     'rpn_score_loss': 0.2950886,
     'total_loss': 4.340171,
     'training_loss': 4.340171}
    train | step:     10 | steps/sec:    0.1 | output: 
    {'frcnn_box_loss': 0.033865165,
     'frcnn_cls_loss': 1.2535654,
     'learning_rate': 0.008266499,
     'mask_loss': 1.2039567,
     'model_loss': 2.821458,
     'rpn_box_loss': 0.034982488,
     'rpn_score_loss': 0.2950886,
     'total_loss': 4.340171,
     'training_loss': 4.340171}
    

    This is followed by output from the evaluation steps.

    You have now completed single-device training and evaluation. Use the following steps to delete the current single-device TPU resources.

  2. Disconnect from the Compute Engine instance:

    (vm)$ exit
    

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

  3. Delete the TPU resource.

    TPU VM

    $ gcloud compute tpus tpu-vm delete mask-rcnn-tutorial \
    --zone=europe-west4-a
    

    Command flag descriptions

    zone
    The zone where your Cloud TPU resided.

    TPU Node

    $ gcloud compute tpus execution-groups delete mask-rcnn-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 your model on Cloud TPU Pods may require some changes to your training script. For information, see Training on TPU Pods.

TPU Pod training

  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 Google Cloud CLI 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 Google Cloud 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 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. 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.

  6. Launch a Cloud TPU Pod

    This tutorial specifies a v3-32 Pod. For other Pod options, see TPU versions.

    TPU VM

    $ gcloud compute tpus tpu-vm create mask-rcnn-tutorial \
    --zone=europe-west4-a \
    --accelerator-type=v3-32 \
    --version=tpu-vm-tf-2.16.1-pod-pjrt
    

    Command flag descriptions

    zone
    The zone where you plan to create your Cloud TPU.
    accelerator-type
    The accelerator type specifies the version and size of the Cloud TPU you want to create. For more information about supported accelerator types for each TPU version, see TPU versions.
    version
    The Cloud TPU software version.

    TPU Node

    (vm)$ gcloud compute tpus execution-groups create \
    --zone=europe-west4-a \
    --name=mask-rcnn-tutorial \
    --accelerator-type=v3-32  \
    --tf-version=2.12.0
    

    Command flag descriptions

    zone
    The zone where you plan to create your Cloud TPU.
    tpu-only
    Creates the Cloud TPU only. By default the gcloud compute tpus execution-groups command creates both a VM and a Cloud TPU.
    accelerator-type
    The type of the Cloud TPU to create.
    tf-version
    The version of TensorFlow gcloud installs on the VM.
  7. 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 compute tpus tpu-vm ssh mask-rcnn-tutorial --zone=europe-west4-a
    

    TPU Node

    gcloud compute ssh mask-rcnn-tutorial --zone=europe-west4-a
    
  8. Install TensorFlow requirements.

    The command you use depends on whether you are using TPU VMs or TPU Nodes.

    TPU VM

    (vm)$ pip3 install -r /usr/share/tpu/models/official/requirements.txt 

    TPU Node

    (vm)$ pip3 install --user -r /usr/share/models/official/requirements.txt
    
  9. The training script requires an extra package. Install it now:

    (vm)$ pip3 install --user tensorflow-model-optimization>=0.1.3
    
  10. Set the Cloud TPU name variable.

    (vm)$ export TPU_NAME=mask-rcnn-tutorial
    
  11. Set up the following environment variables, replacing bucket-name with the name of your Cloud Storage bucket:

    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    
  12. Add some additional required environment variables:

    (vm)$ export RESNET_CHECKPOINT=gs://cloud-tpu-checkpoints/retinanet/resnet50-checkpoint-2018-02-07
    (vm)$ export DATA_DIR=${STORAGE_BUCKET}/coco
    (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 MODEL_DIR=${STORAGE_BUCKET}/mask-rcnn-pod
    
  13. Set the PYTHONPATH environment variable:

    TPU VM

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

    TPU Node

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

    TPU VM

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

    TPU Node

    (vm)$ cd /usr/share/models/official/legacy/detection
  15. Train the model:

    This procedure trains the model on the COCO dataset for 10 training steps. This training takes approximately 10 minutes on a v3-32 Cloud TPU.

    TPU VM

    (vm)$ python3 train.py \
    --tpu=${TPU_NAME} \
    --experiment=maskrcnn_resnetfpn_coco \
    --mode=train_and_eval \
    --config_file=configs/experiments/maskrcnn/r50fpn_640_coco_scratch_tpu4x4.yaml \
    --model_dir=${MODEL_DIR} \
    --params_override="task.train_data.input_path=${TRAIN_FILE_PATTERN},task.validation_data.input_path=${EVAL_FILE_PATTERN},task.annotation_file=${VAL_JSON_FILE},runtime.distribution_strategy=tpu,trainer.train_steps=10,trainer.validation_steps=10,task.train_data.global_batch_size=256,task.validation_data.global_batch_size=256" 

    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.

    TPU Node

    (vm)$ python3 main.py \
    --strategy_type=tpu \
    --tpu=${TPU_NAME} \
    --model_dir=${MODEL_DIR} \
    --mode=train \
    --model=mask_rcnn \
    --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}} }"

    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.

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

 I0706 19:47:16.108213 139955064548416 controller.py:457] train | step: 10 | steps/sec:    0.1 | output: 
    {'frcnn_box_loss': 0.05632668,
     'frcnn_cls_loss': 1.3012192,
     'learning_rate': 0.008266499,
     'mask_loss': 1.2371812,
     'model_loss': 2.9746659,
     'rpn_box_loss': 0.08227444,
     'rpn_score_loss': 0.2976642,
     'total_loss': 4.493513,
     'training_loss': 4.493513}
train | step:     10 | steps/sec:    0.1 | output: 
    {'frcnn_box_loss': 0.05632668,
     'frcnn_cls_loss': 1.3012192,
     'learning_rate': 0.008266499,
     'mask_loss': 1.2371812,
     'model_loss': 2.9746659,
     'rpn_box_loss': 0.08227444,
     'rpn_score_loss': 0.2976642,
     'total_loss': 4.493513,
     'training_loss': 4.493513}
 

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.

After running the training, delete the TPU VM and remove your storage bucket.

  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. 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 compute tpus tpu-vm delete mask-rcnn-tutorial \
    --zone=europe-west4-a
    

    TPU Node

    $ gcloud compute tpus execution-groups delete mask-rcnn-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. The output from the following command shouldn't include any of the TPU resources created in this tutorial:

    $ gcloud compute tpus execution-groups list --zone=europe-west4-a
    
  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

The TensorFlow Cloud TPU tutorials generally train the model using a sample dataset. The results of this training are not usable for inference. To use a model for inference, you can train the data on a publicly available dataset or your own dataset. 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 and Tune hyperparameters.

Inference

Once you have trained your model, you can use it for inference (also called prediction). You can use the Cloud TPU inference converter tool to prepare and optimize a TensorFlow model for inference on Cloud TPU v5e. For more information about inference on Cloud TPU v5e, see Cloud TPU v5e inference introduction.