Training Mask RCNN on Cloud TPU

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

This tutorial uses tf.contrib.tpu.TPUEstimator to train the model. The TPUEstimator API is a high-level TensorFlow API and is the recommended way 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.

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

    If you don't already have one, sign up for a new account.

  2. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to the project selector page

  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 an environment 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 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 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 command 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 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 the Compute Engine and Cloud TPU resources required for this tutorial using the gcloud compute tpus execution-groups command.

    gcloud compute tpus execution-groups create \
     --vm-only \
     --name=mask-rcnn-tutorial \
     --zone=europe-west4-a \
     --disk-size=300 \
     --machine-type=n1-standard-8 \
     --tf-version=1.15.5
    

    Command flag descriptions

    vm-only
    Create the Compute Engine VM only, do not create 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 command.
    machine-type
    The machine type of the Compute Engine VM to create.
    tf-version
    The version of Tensorflow gcloud installs on the VM.
  7. The configuration you specified appears. Enter y to approve or n to cancel.

  8. 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 mask-rcnn-tutorial --zone=europe-west4-a
    

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

Install extra packages

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

(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' && \
  pip3 install --user -U gast==0.2.2

Update the keepalive values of your VM connection

This tutorial requires a long-lived connection to the Compute Engine instance. To ensure you aren't disconnected from the instance, run the following command:

(vm)$ sudo /sbin/sysctl \
  -w net.ipv4.tcp_keepalive_time=120 \
  net.ipv4.tcp_keepalive_intvl=120 \
  net.ipv4.tcp_keepalive_probes=5

Prepare the data

  1. Add an environment variable for your storage bucket. Replace bucket-name with your bucket name.

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

    (vm)$ export DATA_DIR=${STORAGE_BUCKET}/coco
    
  3. Add an environment variable for the model directory.

    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/mask-rcnn
    
  4. 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.

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

Set up and start the Cloud TPU

  1. Run the following command to create your Cloud TPU.

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

    Command flag descriptions

    tpu-only
    Create the Cloud TPU only, does not create a Compute Engine.
    accelerator-type
    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 installs on the VM.
  2. 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.

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

    (vm)$ export TPU_NAME=mask-rcnn-tutorial
    

Run the training and evaluation

  1. Add some required environment variables:

    (vm)$ export PYTHONPATH="${PYTHONPATH}:/usr/share/tpu/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 ACCELERATOR_TYPE=v3-8
    
  2. Navigate to the /usr/share directory.

    (vm)$ cd /usr/share
    
  3. Run the following command to run both the training and evaluation.

    (vm)$ python3 tpu/models/official/mask_rcnn/mask_rcnn_main.py \
    --use_tpu=True \
    --tpu=${TPU_NAME} \
    --model_dir=${MODEL_DIR} \
    --num_cores=8 \
    --mode="train_and_eval" \
    --config_file="/usr/share/tpu/models/official/mask_rcnn/configs/cloud/${ACCELERATOR_TYPE}.yaml" \
    --params_override="checkpoint=${RESNET_CHECKPOINT}, training_file_pattern=${TRAIN_FILE_PATTERN}, validation_file_pattern=${EVAL_FILE_PATTERN}, val_json_file=${VAL_JSON_FILE}"
      

    Command flag descriptions

    use_tpu
    Set to true to train on a Cloud TPU.
    tpu
    The name of the Cloud TPU to run training or evaluation.
    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.
    num_cores
    The number of Cloud TPU cores to use when training.
    mode
    One of train, eval, or train_and_eval.
    config_file
    The configuration file used by the training/evaluation script.
    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.

Once completed, the training script displays output like the following:

Eval results: {
  'AP75': 0.40665552,
  'APs': 0.21580082,
  'ARmax10': 0.48935828,
  'ARs': 0.3210774,
  'ARl': 0.6564725,
  'AP50': 0.58614284,
  'mask_AP': 0.33921072,
  'mask_AP50': 0.553329,
  'ARm': 0.5500552,
  'mask_APm': 0.37276757,
  'mask_ARmax100': 0.46716768,
  'mask_AP75': 0.36201102,
  'ARmax1': 0.3094466,
  'ARmax100': 0.51287305,
  'APm': 0.40756866,
  'APl': 0.48908308,
  'mask_ARm': 0.50562346,
  'mask_ARl': 0.6192515,
  'mask_APs': 0.17869519,
  'mask_ARmax10': 0.44764888,
  'mask_ARmax1': 0.2897982,
  'mask_ARs': 0.27102336,
  'mask_APl': 0.46426648,
  'AP': 0.37379172
}

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.

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

    (vm)$ gcloud compute tpus execution-groups delete mask-rcnn-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 --tpu-only \
      --accelerator-type=v3-32 \
      --zone=europe-west4-a \
      --name=mask-rcnn-tutorial \
      --tf-version=1.15.5
    

    Command flag descriptions

    tpu-only
    Create a Cloud TPU only. By default the gcloud command creates a VM and a Cloud TPU.
    accelerator-type
    The type of the Cloud TPU to create.
    zone
    The zone where you plan to create your Cloud TPU.
    name
    The name of the Cloud TPU to create.
    tf-version
    The version of Tensorflow gcloud compute tpus execution-groups installs on the VM.
  3. Update the TPU_NAME, MODEL_DIR, and ACCELERATOR_TYPE environment variables.

    (vm)$ export TPU_NAME=mask-rcnn-tutorial
    (vm)$ export ACCELERATOR_TYPE=v3-32
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/mask-rcnn-pods
    
  4. Start the training script.

    (vm)$ python3 tpu/models/official/mask_rcnn/mask_rcnn_main.py \
      --use_tpu=True \
      --tpu=${TPU_NAME} \
      --iterations_per_loop=500 \
      --model_dir=${MODEL_DIR} \
      --num_cores=32 \
      --mode="train" \
      --config_file="/usr/share/tpu/models/official/mask_rcnn/configs/cloud/${ACCELERATOR_TYPE}.yaml" \
      --params_override="checkpoint=${RESNET_CHECKPOINT}, training_file_pattern=${TRAIN_FILE_PATTERN}, validation_file_pattern=${EVAL_FILE_PATTERN}, val_json_file=${VAL_JSON_FILE}"
      

    Command flag descriptions

    use_tpu
    Set to true to train on a Cloud TPU.
    tpu
    The name of the Cloud TPU to run training or evaluation.
    iterations_per_loop
    The number of iterations to complete in one epoch.
    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.
    num_cores
    The number of Cloud TPU cores to use when training.
    mode
    One of train, eval, or train_and_eval.
    config_file
    The configuration file used by the training/evaluation script.
    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 completed, the training script output should look like this:

I1201 07:22:49.762461 139992247961344 tpu_estimator.py:616] Shutdown TPU system.
INFO:tensorflow:Loss for final step: 0.7160271.

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

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

    (vm)$ gcloud compute tpus execution-groups delete mask-rcnn-tutorial \
      --tpu-only \
      --zone=europe-west4-a
      
  2. Start a v2-8 Cloud TPU to run the evaluation. Use the same name that you used for the Compute Engine VM, which should still be running.

    (vm)$ gcloud compute tpus execution-groups create --tpu-only \
      --accelerator-type=v2-8 \
      --zone=europe-west4-a \
      --name=mask-rcnn-tutorial \
      --tf-version=1.15.5
    

    Command flag descriptions

    tpu-only
    Create a Cloud TPU only. By default the gcloud command creates a VM and a Cloud TPU.
    accelerator-type
    The type of the Cloud TPU to create.
    zone
    The zone where you plan to create your Cloud TPU.
    name
    The name of the Cloud TPU to create.
    tf-version
    The version of Tensorflow gcloud installs on the VM.
  3. Start the evaluation.

    (vm)$ python3 tpu/models/official/mask_rcnn/mask_rcnn_main.py \
      --use_tpu=True \
      --tpu=${TPU_NAME} \
      --iterations_per_loop=500 \
      --mode=eval \
      --model_dir=${MODEL_DIR} \
      --config_file="/usr/share/tpu/models/official/mask_rcnn/configs/cloud/${ACCELERATOR_TYPE}.yaml" \
      --params_override="checkpoint=${CHECKPOINT},training_file_pattern=${PATH_GCS_MASKRCNN}/train-*,val_json_file=${PATH_GCS_MASKRCNN}/instances_val2017.json,validation_file_pattern=${PATH_GCS_MASKRCNN}/val-*,init_learning_rate=0.28,learning_rate_levels=[0.028, 0.0028, 0.00028],learning_rate_steps=[6000, 8000, 10000],momentum=0.95,num_batch_norm_group=1,num_steps_per_eval=500,global_gradient_clip_ratio=0.02,total_steps=11250,train_batch_size=512,warmup_steps=1864"
      

    Command flag descriptions

    use_tpu
    Use a TPU for training or evaluation.
    tpu
    The name of the Cloud TPU to run training or evaluation.
    iterations_per_loop
    The number of iterations to complete in one epoch.
    mode
    One of train, eval, or train_and_eval.
    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.
    config_file
    The configuration file used by the training/evaluation script.

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.

Clean up the Compute Engine VM instance and Cloud TPU 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 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. 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

In this tutorial you have trained the Mask-RCNN 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. Models trained on Cloud TPUs 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.