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 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.
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.
-
Sign in to your Google Account.
If you don't already have one, sign up for a new account.
-
In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Cloud project. Learn how to confirm that billing is enabled for your project.
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.
Open a Cloud Shell window.
Create an environment variable for your project's ID.
export PROJECT_ID=project-id
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. ClickAuthorize
at the bottom of the page to allowgcloud
to make GCP API calls with your credentials.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
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
ctpu up
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.
Launch a Compute Engine VM using the
ctpu up
command.$ ctpu up --project=${PROJECT_ID} \ --zone=europe-west4-a \ --vm-only \ --disk-size-gb=300 \ --machine-type=n1-standard-8 \ --name=mask-rcnn-tutorial \ --tf-version=2.4.1
Command flag descriptions
project
- Your GCP project ID
zone
- The zone where you plan to create your Cloud TPU.
vm-only
- Creates the VM without creating a Cloud TPU. By default the
ctpu up
command creates a VM and a Cloud TPU. disk-size-gb
- The size of the hard disk in GB of the VM created by the
ctpu up
command. machine-type
- The machine type of the Compute Engine VM to create.
name
- The name of the Cloud TPU to create.
tf-version
- The version of Tensorflow
ctpu
installs on the VM.
The configuration you specified appears. Enter y to approve or n to cancel.
When the
ctpu up
command has finished executing, verify that your shell prompt has changed fromusername@projectname
tousername@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)$ pip3 install --user -r /usr/share/models/official/requirements.txt
Prepare the data
Add an environment variable for your storage bucket. Replace bucket-name with your bucket name.
(vm)$ export STORAGE_BUCKET=gs://bucket-name
Add an environment variable for the data directory.
(vm)$ export DATA_DIR=${STORAGE_BUCKET}/coco
Add an environment variable for the model directory.
(vm)$ export MODEL_DIR=${STORAGE_BUCKET}/mask-rcnn
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.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 training the Cloud TPU
Run the following command to create your Cloud TPU.
(vm)$ ctpu up --project=${PROJECT_ID} \ --tpu-only \ --tpu-size=v3-8 \ --zone=europe-west4-a \ --name=mask-rcnn-tutorial \ --tf-version=2.4.1
Command flag descriptions
project
- Your GCP project ID
tpu-only
- Create a Cloud TPU only. By default the
ctpu up
command creates a VM and a Cloud TPU. tpu-size
- 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
ctpu
installs on the VM.
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.Add an environment variable for your Cloud TPU's name.
(vm)$ export TPU_NAME=mask-rcnn-tutorial
Run the training and evaluation
The following script runs a sample training that trains for just 10 steps and takes approxiately 6 mimutes 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.
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
Run the following command to train Mask-RCNN model:
(vm)$ python3 /usr/share/models/official/vision/detection/main.py \ --strategy_type=tpu \ --tpu=${TPU_NAME} \ --model_dir=${MODEL_DIR} \ --mode=train \ --model=mask_rcnn \ --params_override="{train: { total_steps: 10, 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}, eval_samples: 5000} }"
Parameter Description tpu
Specifies the name of the Cloud TPU. This is set by specifying the environment variable ( TPU_NAME
).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.RESNET_CHECKPOINT
Specifies a pretrained checkpoint. Mask-RCNN 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. Run the evaluation:
(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=mask_rcnn \ --params_override="{eval: { val_json_file: ${VAL_JSON_FILE}, eval_file_pattern: ${EVAL_FILE_PATTERN}, eval_samples: 5000 } }"
Parameter Description tpu
Specifies the name of the Cloud TPU. This is set by specifying the environment variable ( TPU_NAME
).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.
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.
Delete the Cloud TPU resource you created for training the model on a single Cloud TPU device.
(vm)$ ctpu delete --tpu-only --zone=europe-west4-a --name=mask-rcnn-tutorial
Run the
ctpu up
command, using thetpu-size
parameter to specify the Pod slice you want to use. For example, the following command uses a v3-32 Pod slice.(vm)$ ctpu up --project=${PROJECT_ID} \ --tpu-only \ --tpu-size=v3-32 \ --zone=europe-west4-a \ --name=mask-rcnn-tutorial \ --tf-version=2.4.1
Update the TPU_NAME and MODEL_DIR environment variables.
(vm)$ export TPU_NAME=mask-rcnn-tutorial (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/mask-rcnn-pods
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=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}} }"
Parameter Description tpu
Specifies the name of the Cloud TPU. This is set by specifying the environment variable ( TPU_NAME
).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.RESNET_CHECKPOINT
Specifies a pretrained checkpoint. Mask-RCNN 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.
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.
Delete the Cloud TPU resource you created to train the model on a Pod.
(vm)$ ctpu delete --project=${PROJECT_ID} \ --tpu-only \ --zone=europe-west4-a \ --name=mask-rcnn-tutorial
Launch a new TPU device to run evaluation.
(vm)$ ctpu up --project=${PROJECT_ID} \ --tpu-only \ --tpu-size=v3-8 \ --zone=europe-west4-a \ --tf-version=2.4.1 \ --name=mask-rcnn-tutorial
Update the TPU_NAME environment variable.
(vm)$ export TPU_NAME=mask-rcnn-tutorial
Start the evaluation.
(vm)$ python3 /usr/share/models/official/vision/detection/main.py \ --strategy_type=tpu \ --tpu=mask-rcnn-tutorial \ --model_dir=${MODEL_DIR} \ --checkpoint_path=${MODEL_DIR} \ --mode=eval_once \ --model=mask_rcnn \ --params_override="{eval: { val_json_file: ${VAL_JSON_FILE}, eval_file_pattern: ${EVAL_FILE_PATTERN}, eval_samples: 5000 } }"
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.
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.In your VM or Cloud Shell, run
ctpu delete
with the--name
and--zone
flags you used when you set up the Cloud TPU to delete your Cloud TPU:$ ctpu delete --project=${PROJECT_ID} \ --name=mask-rcnn-tutorial \ --zone=europe-west4-a
Run the following command to verify the Compute Engine VM and Cloud TPU have been shut down:
$ ctpu status --project=${PROJECT_ID} \ --name=mask-rcnn-tutorial \ --zone=europe-west4-a
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 "europe-west4-a" No instances currently exist. Compute Engine VM: -- Cloud TPU: --
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
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.
- Learn more about
ctpu
, including how to install it on a local machine. - Explore the TPU tools in TensorBoard.