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 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.
Before you begin
Before starting this tutorial, check that your Google Cloud project is correctly set up.
- 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.
-
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 check if billing is enabled on a project.
-
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 check if billing is enabled on a 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 a variable for your project's ID.
export PROJECT_ID=project-id
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. 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
gcloud compute tpus execution-groups
tool 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.
Launch a Compute Engine VM instance.
$ gcloud compute tpus execution-groups create --vm-only \ --name=shapemask-tutorial \ --zone=us-central1-a \ --disk-size=300 \ --machine-type=n1-standard-16 \ --tf-version=1.15.5
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
ctpu
installs on the VM.
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 fromusername@projectname
tousername@vm-name
. This change shows that you are now logged into your Compute Engine VM.gcloud compute ssh shapemask-tutorial --zone=us-central1-a
As you continue these instructions, run each command that begins with
(vm)$
in your Compute Engine instance.Create an environment variable to store your Cloud Storage bucket location.
(vm)$ export STORAGE_BUCKET=gs://bucket-name
Create an environment variable for the data directory.
(vm)$ export DATA_DIR=${STORAGE_BUCKET}/coco
Clone the
tpu
repository.(vm)$ git clone -b shapemask https://github.com/tensorflow/tpu/
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
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.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
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=us-central1-a \ --tf-version=1.15.5
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. 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
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=shapemask-tutorial
Run the training and evaluation script
Create the following environment variables:
(vm)$ export MODEL_DIR=${STORAGE_BUCKET}/shapemask_exp (vm)$ export RESNET_CHECKPOINT=gs://cloud-tpu-checkpoints/shapemask/retinanet/resnet101-checkpoint-2018-02-24 (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 PYTHONPATH=${PYTHONPATH}:$HOME/tpu/models
Run the following script to perform training.
(vm)$ python3 ~/tpu/models/official/detection/main.py \ --model=shapemask \ --use_tpu=True \ --tpu=${TPU_NAME} \ --num_cores=8 \ --model_dir=${MODEL_DIR} \ --mode="train" \ --eval_after_training=False \ --params_override="{train: {iterations_per_loop: 1000, train_batch_size: 64, total_steps: 1000, learning_rate: {total_steps: 1000, warmup_learning_rate: 0.0067, warmup_steps: 500, init_learning_rate: 0.08, learning_rate_levels: [0.008, 0.0008], learning_rate_steps: [30000, 40000]}, checkpoint: { path: ${RESNET_CHECKPOINT}, prefix: resnet101/ }, train_file_pattern: ${TRAIN_FILE_PATTERN} }, resnet: {resnet_depth: 101}, 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: [1024, 1024]}, }"
Command flag descriptions
model
- The model to train.
use_tpu
- Set to
true
to train on a Cloud TPU. tpu_name
- The name of the Cloud TPU to use for training.
num_cores
- The number of Cloud TPU cores to use when training.
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
, ortrain_and_eval
. eval_after_training
- Set to
true
to evaluate the model after training, 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
.
At this point, 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.
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=us-central1-a \ --tpu-only
Go to your Cloud Storage bucket and delete the
checkpoint
file.Run the
gcloud compute tpus execution-groups
command, using theaccelerator-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=v2-32 \ --zone=us-central1-a \ --tf-version=1.15.5 \ --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.
Run the following script to train the model on a Pod.
With the given command line the training script takes approximately 45 minutes to run. To run to convergence, set
total_steps
to 22000.(vm)$ python3 ~/tpu/models/official/detection/main.py \ --model shapemask \ --use_tpu=True \ --tpu=${TPU_NAME} \ --num_cores=32 \ --model_dir=${MODEL_DIR} \ --mode="train" \ --eval_after_training=False \ --params_override="{train: {iterations_per_loop: 1000, train_batch_size: 256, total_steps: 1000, learning_rate: {total_steps: 1000, warmup_learning_rate: 0.0067, warmup_steps: 500, init_learning_rate: 0.08, learning_rate_levels: [0.008, 0.0008], learning_rate_steps: [15000, 20000]}, checkpoint: { path: ${RESNET_CHECKPOINT}, prefix: resnet101/ }, train_file_pattern: ${TRAIN_FILE_PATTERN} }, resnet: {resnet_depth: 101}, 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: [1024, 1024]}, }"
Command flag descriptions
strategy_type
- To train the RetinaNet model on a TPU, you must set the
distribution_strategy
totpu
. 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
, ortrain_and_eval
. model
- The model to train.
eval_after_training
- Set to
true
to evaluate the model after training, 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 model must be evaluated on a single Cloud TPU device. Delete the Cloud TPU Pod device.
$ gcloud compute tpus execution-groups delete shapemask-tutorial \ --zone=us-central1-a
Create a single Cloud TPU resource.
(vm)$ gcloud compute tpus execution-groups create \ --tpu-only \ --accelerator-type=v3-8 \ --name=shapemask-tutorial \ --zone=us-central1-a \ --tf-version=1.15.5
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
ctpu
installs on the VM.
Run the script to perform evaluation.
(vm)$ python3 ~/tpu/models/official/detection/main.py \ --model shapemask \ --use_tpu=True \ --tpu=${TPU_NAME} \ --num_cores=8 \ --model_dir=${MODEL_DIR} \ --mode="eval" \ --eval_after_training=False \ --params_override="{train: {iterations_per_loop: 1000, train_batch_size: 256, total_steps: 1000, learning_rate: {total_steps: 1000, warmup_learning_rate: 0.0067, warmup_steps: 500, init_learning_rate: 0.08, learning_rate_levels: [0.008, 0.0008], learning_rate_steps: [15000,20000]}, checkpoint: { path: ${RESNET_CHECKPOINT}, prefix: resnet101/ }, train_file_pattern: ${TRAIN_FILE_PATTERN} }, resnet: {resnet_depth: 101}, 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: [1024, 1024]}, }"
Command flag descriptions
model
- The model to train.
use_tpu
- Set to
true
to train on a Cloud TPU. tpu
- The name of the Cloud TPU. This is set using the
TPU_NAME
environment variable. num_cores
- The number of Cloud TPU cores to use when training.
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
, ortrain_and_eval
. eval_after_training
- Set to
true
to evaluate the model after training, 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 looks like this:
Eval result: { 'AP75': 0.116238795, 'AP': 0.121657856, 'mask_ARmax100': 0.29928473, 'APl': 0.17029367, 'mask_ARmax1': 0.17677748, 'ARs': 0.14137766, 'mask_AP': 0.12017078, 'ARmax10': 0.29230836, 'mask_AP50': 0.20920053, 'ARm': 0.34366703, 'AP50': 0.22949784, 'mask_ARl': 0.41743836, 'mask_ARs': 0.12669834, 'APs': 0.046222884, 'mask_APs': 0.041104294, 'mask_APl': 0.17535995, 'mask_ARm': 0.34216145, 'mask_ARmax10': 0.28690106, 'APm': 0.14354791, 'ARmax100': 0.3058479, 'ARmax1': 0.17576972, 'ARl': 0.41305476, 'mask_APm': 0.1422335, 'mask_AP75': 0.12010279 }
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.
Disconnect from the Compute Engine instance.
(vm)$ exit
Your prompt should now be
username@projectname
, showing you are in the Cloud Shell.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=us-central1-a
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=us-central1-a
You should see an empty list of TPUs like the following:
NAME STATUS
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
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 data set. 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, 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.
Train with different image sizes
You can try 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.