Training EfficientNet on Cloud TPU (TF 2.x)

This tutorial shows you how to train a Keras EfficientNet model on Cloud TPU using tf.distribute.TPUStrategy.

If you are not familiar with Cloud TPU, it is strongly recommended that you go through the quickstart to learn how to create a Cloud TPU and Compute Engine VM.

Objectives

  • Create a Cloud Storage bucket to hold your dataset and model output.
  • Prepare a fake imagenet dataset that is similar to the ImageNet dataset.
  • Run the training job.
  • Verify the output results.

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 Cloud Console, on the project selector page, select or create a Cloud project.

    Go to the project selector page

  3. Make sure that billing is enabled for your Google Cloud project. Learn how to confirm 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.

Set up your resources

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

  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}
    
  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 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 Compute Engine (VM) and your Cloud TPU node.

  6. From your Cloud Shell, launch the Compute Engine VM resource using the ctpu up command.

    ctpu up --vm-only \
       --name=efficientnet-tutorial \
       --zone=europe-west4-a \
       --disk-size-gb=300 \
       --machine-type=n1-standard-16 \
       --tf-version=2.3
    

    Command flag descriptions

    name
    The name of the Cloud TPU to create.
    zone
    The zone where you plan to create your 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.
    tf-version
    The version of Tensorflow ctpu installs on the VM.

    For more information on the CTPU utility, see the CTPU Reference.

  7. When prompted, press y to create your Cloud TPU resources.

    When the ctpu up 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 efficientnet-tutorial --zone=europe-west4-a
    

Set Cloud Storage bucket variables

Set up the following environment variables, replacing bucket-name with the name of your Cloud Storage bucket:

(vm)$ export STORAGE_BUCKET=gs://bucket-name
(vm)$ export MODEL_DIR=${STORAGE_BUCKET}/efficientnet-2x
(vm)$ export DATA_DIR=gs://cloud-tpu-test-datasets/fake_imagenet

The training application expects your training data to be accessible in Cloud Storage. The training application also uses your Cloud Storage bucket to store checkpoints during training.

Train and evaluate the EfficientNet model with fake_imagenet

ImageNet is an image database. The images in the database are organized into a hierarchy, with each node of the hierarchy depicted by hundreds and thousands of images.

This tutorial uses a demonstration version of the full ImageNet dataset, referred to as fake_imagenet. This demonstration version allows you to test the tutorial, while reducing the storage and time requirements typically associated with running a model against the full ImageNet database.

The fake_imagenet dataset is at this location on Cloud Storage:

gs://cloud-tpu-test-datasets/fake_imagenet

The fake_imagenet dataset is only useful for understanding how to use a Cloud TPU and validating end-to-end performance. The accuracy numbers and saved model will not be meaningful.

For information on how to download and process the full ImageNet dataset, see Downloading, preprocessing, and uploading the ImageNet dataset.

  1. Launch a Cloud TPU resource using the ctpu utility.

    (vm)$ ctpu up --tpu-only \
     --name=efficientnet-tutorial \
     --tpu-size=v3-8  \
     --zone=europe-west4-a \
     --tf-version=2.3
    

    Command flag descriptions

    tpu-only
    Create a Cloud TPU only. By default the ctpu up command creates a VM and a Cloud TPU.
    name
    The name of the Cloud TPU to create.
    tpu-size
    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 ctpu installs on the VM.
  2. Set the Cloud TPU name variable. This will either be a name you specified with the --name parameter to ctpu up or the default, your username:

    (vm)$ export TPU_NAME=efficientnet-tutorial
    
  3. The EfficientNet training script requires an extra packages. Install them now:

    (vm)$ sudo pip3 install tensorflow-addons
    (vm)$ sudo pip3 install tensorflow-model-optimization>=0.1.3
    
  4. Add the top-level /models folder to the Python path with the command

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

    The EfficientNet model is pre-installed on your Compute Engine VM.

  5. Navigate to the directory:

    (vm)$ cd /usr/share/models/official/vision/image_classification/
    
  6. Run the training script. This uses a fake_imagenet dataset and trains EfficientNet for one epoch.

    (vm)$ python3 classifier_trainer.py \
    --mode=train_and_eval \
    --model_type=efficientnet \
    --dataset=imagenet \
    --tpu=${TPU_NAME} \
    --data_dir=${DATA_DIR} \
    --model_dir=${MODEL_DIR} \
    --config_file=configs/examples/efficientnet/imagenet/efficientnet-b0-tpu.yaml \
    --params_override="train.epochs=1, train_dataset.builder=records, validation_dataset.builder=records"
    

    Command flag descriptions

    mode
    When set to train_and_eval this script trains and evaluates the model. When set to export_only this script exports a saved model.
    model_type
    The type of the model. For example, efficientnet, etc.
    dataset
    The name of the dataset. For example, imagenet.
    tpu
    Uses the name specified in the TPU_NAME environment variable.
    data_dir
    Specifies the Cloud Storage path for training input. It is set to the fake_imagenet dataset in this example.
    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.
    config_file
    The path to the json file containing the pre-trained EfficientNet model. This file contains the model architecture.
    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.

This will train EfficientNet for 1 epoch and will complete on a v3-8 Cloud TPU node in under 10 minutes. At the end of the training, output similar to the following appears:

I1107 20:28:57.561836 140033625347520 efficientnet_ctl_imagenet_main.py:222] Training 1 epochs, each epoch has 1251 steps, total steps: 1251; Eval 48 steps
I1107 20:34:09.638025 140033625347520 efficientnet_ctl_imagenet_main.py:358] Training loss: 0.6292637, accuracy: 0.99680257 at epoch 1
I1107 20:34:21.682796 140033625347520 efficientnet_ctl_imagenet_main.py:372] Test loss: 3.8977659, accuracy: 0.0% at epoch: 1
I1107 20:34:22.028973 140033625347520 efficientnet_ctl_imagenet_main.py:392]
Run stats:
{'train_loss': 0.6292637, 'train_acc': 0.99680257, 'eval_acc': 0.0, 'step_timestamp_log':
['BatchTimestamp < batch_index: 1, timestamp: 1573158554.11 >'],
'train_finish_time': 1573158861.683073, 'eval_loss': 3.8977659>}

To train the EfficientNet to convergence, run it for 90 epochs as shown in the following script. Training and evaluation are done together. Each epoch has 1251 steps for a total of 112590 training steps and 48 evaluation steps.

   (vm)$ python3 classifier_trainer.py \
     --mode=train_and_eval \
     --model_type=efficientnet \
     --dataset=imagenet \
     --tpu=${TPU_NAME} \
     --data_dir=${DATA_DIR} \
     --model_dir=${MODEL_DIR} \
     --config_file=configs/examples/efficientnet/imagenet/efficientnet-b0-tpu.yaml \
     --params_override="train_dataset.builder=records, validation_dataset.builder=records"

Command flag descriptions

mode
When set to `train_and_eval` this script trains and evaluates the model. When set to `export_only` this script exports a saved model.
model_type
The type of the model. For example, efficientnet, etc.
dataset
The name of the dataset. For example, imagenet.
tpu
Uses the name specified in the TPU_NAME variable.
data_dir
Specifies the Cloud Storage path for training input. It is set to the fake_imagenet dataset in this example.
model_dir
Specifies the directory where checkpoints and summaries are stored during model training. If the folder is missing, the script 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 a Cloud TPU of the same size and TensorFlow version.
config_file
The path to the JSON file containing the pre-trained EfficientNet model. This file contains the model architecture.
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.

Since the training and evaluation was done on the fake_imagenet dataset, the output results do not reflect actual output that would appear if the training and evaluation was performed on a real dataset.

At this point, you can either conclude this tutorial and clean up your GCP resources, or you can further explore running the model on Cloud TPU Pods.

Scaling your model with Cloud TPU Pods

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

  • v2-32
  • v3-32

With Cloud TPU Pods, training and evaluation are done together.

Training with Cloud TPU Pods

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

    (vm)$ ctpu delete --tpu-only \
     --name=efficientnet-tutorial \
     --zone=europe-west4-a
  2. Run the ctpu up command, using the tpu-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 --tpu-only \
      --name=efficientnet-tutorial \
      --zone=europe-west4-a \
      --tpu-size=v3-32 \
      --tf-version=2.3
    

    Command flag descriptions

    tpu-only
    Create a Cloud TPU only. By default the ctpu up 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.
    tpu-size
    The type of the Cloud TPU to create.
    tf-version
    The version of Tensorflow ctpu installs on the VM.
    gcloud compute ssh efficientnet-tutorial --zone=europe-west4-a
    
  3. Update the MODEL_DIR directory to store the Cloud TPU Pod training data.

    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/efficientnet-2x-pod
    
  4. Define your Cloud TPU name.

    (vm)$ export TPU_NAME=efficientnet-tutorial
    
  5. Navigate to the directory:

    (vm)$ cd /usr/share/models/official/vision/image_classification/
    
  6. Train the model.

    (vm)$ python3 classifier_trainer.py \
    --mode=train_and_eval \
    --model_type=efficientnet \
    --dataset=imagenet \
    --tpu=${TPU_NAME} \
    --data_dir=${DATA_DIR} \
    --model_dir=${MODEL_DIR} \
    --config_file=configs/examples/efficientnet/imagenet/efficientnet-b0-tpu.yaml \
    --params_override="train.epochs=1, train_dataset.builder=records, validation_dataset.builder=records"
    

    Command flag descriptions

    mode
    When set to train_and_eval this script trains and evaluates the model. When set to export_only this script exports a saved model.
    model_type
    The type of the model. For example, efficientnet, etc.
    dataset
    The name of the dataset. For example, imagenet.
    tpu
    Uses the name specified in the TPU_NAME variable.
    data_dir
    Specifies the Cloud Storage path for training input. It is set to the fake_imagenet dataset in this example.
    model_dir
    Specifies the directory where checkpoints and summaries are stored during model training. If the folder is missing, the script 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.
    config_file
    The path to the json file containing the pre-trained EfficientNet model. This file contains the model architecture.
    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 procedure trains the model on the fake_imagenet dataset to 1 epoch (312 total training steps and 12 evaluation steps). This training takes approximately 2 minutes on a v3-32 Cloud TPU. When the training and evaluation complete, a message similar to the following appears:

1107 22:45:19.821746 140317155378624 efficientnet_ctl_imagenet_main.py:358] Training loss: 0.22576721, accuracy: 0.838141 at epoch 1
I1107 22:45:33.892045 140317155378624 efficientnet_ctl_imagenet_main.py:372] Test loss: 0.26673648, accuracy: 0.0% at epoch: 1
I1107 22:45:34.851322 140317155378624 efficientnet_ctl_imagenet_main.py:392] Run stats:
{'train_loss': 0.22576721, 'train_acc': 0.838141, 'eval_acc': 0.0, 'step_timestamp_log': ['BatchTimestamp <batch_index: 1, timestamp: 1573166574.67>'], 'train_finish_time': 1573166733.892282, 'eval_loss': 0.26673648}

Cleaning up

To avoid incurring charges to your Google Cloud Platform account for the resources used in this tutorial:

  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:

    $ ctpu delete --name=efficientnet-tutorial \
      --zone=europe-west4-a
    
  3. Run ctpu status to make sure you have no instances allocated to avoid unnecessary charges for Cloud TPU usage. The deletion might take several minutes. A response like the one below indicates there are no more allocated instances:

    $ ctpu status --name=efficientnet-tutorial --zone=europe-west4-a
    
    2018/04/28 16:16:23 WARNING: Setting zone to "europe-west4-a"
    No instances currently exist.
            Compute Engine VM:     --
            Cloud TPU:             --
    
  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

In this tutorial you have trained the EfficientNet 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 how to train and evaluate using your own data in place of the fake_imagenet or ImageNet datasets by following the dataset conversion tutorial. The tutorial explains how to use the image classification data converter example script to convert a raw dataset for image classification into TFRecords usable by Cloud TPU Tensorflow models.

  • Run a Cloud TPU colab that demonstrates how to run an image classification model using your own image data.

  • Explore the other Cloud TPU tutorials.

  • Learn to use the TPU monitoring tools in TensorBoard.