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

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 your TPU VM resources you create when you've finished with them to avoid unnecessary charges.

Cloud TPU single device training

This section describes how to configure Cloud TPU resources and train the EfficientNet model using a single Cloud TPU device.

  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 API calls with your credentials.

    For more information on the gcloud command, see the gcloud Reference.

  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. Export TPU setup variables

    Set the zone where you will train the model and store any training-related data.

    $ export ZONE=europe-west4-a
  6. Create a Cloud Storage bucket using the following command:

    gcloud storage buckets create gs://bucket-name --project=${PROJECT_ID} --location=europe-west4

    This Cloud Storage bucket stores the data you use to train your model and the training results. You use the gcloud compute tpus tpu-vm command to set 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.

  7. Prepare your dataset or use 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 lets you 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 won't be meaningful.

    If you want to use the full ImageNet dataset, see Downloading, preprocessing, and uploading the ImageNet dataset.

  8. Launch TPU resources using the gcloud command.

    $ gcloud compute tpus tpu-vm create efficientnet-tutorial \
      --zone=${ZONE} \
      --accelerator-type=v3-8 \
      --version=tpu-vm-tf-2.18.0-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.

    For more information on the gcloud command, see the gcloud Reference.

  9. Connect to the Compute Engine instance using SSH. When you are connected to the VM, your shell prompt changes from username@projectname to username@vm-name:

    gcloud compute tpus tpu-vm ssh efficientnet-tutorial --zone=${ZONE}
  10. Set the Cloud TPU name variable.

    (vm)$ export TPU_NAME=local
  11. Set Cloud Storage bucket variables

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

  12. 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
  13. Install TensorFlow requirements.

    (vm)$ pip3 install -r /usr/share/tpu/models/official/requirements.txt
  14. The EfficientNet training script requires extra packages. Install them now:

    (vm)$ sudo pip3 install tensorflow-addons
    (vm)$ sudo pip3 install tensorflow-model-optimization>=0.1.3
  15. Set some required environment variables:

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

    The EfficientNet model is pre-installed on your Cloud TPU VM.

  16. Change to directory that stores the model:

    (vm)$ cd /usr/share/tpu/models/official/legacy/image_classification
  17. Train the model. 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
    One of train, eval, or train_and_eval.
    model_type
    The type of the model. For example, efficientnet.
    dataset
    The name of the dataset. For example, imagenet.
    tpu
    The name of the Cloud TPU to run training or evaluation.
    data_dir
    Specifies the Cloud Storage path for training input. It is set to the fake_imagenet dataset in this example.
    model_dir
    The Cloud Storage path where checkpoints and summaries are stored during model training. You can reuse an existing folder to load previously generated checkpoints 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/legacy/detection/main.py.

    This will train EfficientNet for 1 epoch and will complete on a v3-8 Cloud TPU node in approximately 40 minutes. When the training script completes, output similar to the following appears:

    Run stats:
    {
      'accuracy_top_1': 0.0010172526817768812,
      'eval_loss': 7.104171276092529,
      'loss': 7.113735675811768,
      'training_accuracy_top_1': 0.0009773431811481714,
      'step_timestamp_log': [
        'BatchTimestamp<batch_index: 0,
        timestamp: 1604960724.2224622>',
        'BatchTimestamp<batch_index: 1251,
        timestamp: 1604961281.3745298>'
      ],
      'train_finish_time': 1604961342.6359076,
      'avg_exp_per_second': 2071.493269569079
    }
    

    To train the EfficientNet to convergence on the ImageNet dataset, 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
    One of train, eval, or train_and_eval.
    model_type
    The type of the model. For example, efficientnet.
    dataset
    The name of the dataset. For example, imagenet.
    tpu
    The name of the Cloud TPU to run training or evaluation.
    data_dir
    Specifies the Cloud Storage path for training input. It is set to the fake_imagenet dataset in this example.
    model_dir
    The Cloud Storage path where checkpoints and summaries are stored during model training. You can reuse an existing folder to load previously generated checkpoints 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/legacy/detection/main.py.

    Since the training was done on the fake_imagenet dataset, the output results don't reflect actual output that would appear if the training was performed on a real dataset.

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

  18. Disconnect from the Compute Engine instance:

    (vm)$ exit

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

  19. Delete the TPU resource.

    $ gcloud compute tpus tpu-vm delete efficientnet-tutorial \
     --zone=${ZONE}

    Command flag descriptions

    zone
    The zone where your Cloud TPU resides.

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.

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

Cloud TPU Pod training

This section provides information on setting up a Cloud Storage bucket and Cloud TPU resources for 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. Create a Cloud Storage bucket using the following command or use a bucket you created earlier for your project:

    gcloud storage buckets create gs://bucket-name --project=${PROJECT_ID} --location=europe-west4

    This Cloud Storage bucket stores the data you use to train your model and the training results. The gcloud command 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 TPU VM.

  6. Export TPU setup variables

    Set the zone where you will train the model and store any training-related data.

    $ export ZONE=europe-west4-a

  7. Prepare your dataset or use 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.

    The default Pod training accesses a demonstration version of the full ImageNet dataset, referred to as fake_imagenet. This demonstration version allows you to test Pod training, while reducing the storage and time requirements typically associated with training a model against the full ImageNet database.

    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.

    If you want to use the full ImageNet dataset, see Downloading, preprocessing, and uploading the ImageNet dataset.

  8. Launch your Cloud TPU resources using the gcloud command.

    For more information on the gcloud command, see the gcloud Reference. This tutorial specifies a v3-32 Pod. For other Pod options, see the available TPU types page.

    This tutorial specifies a v3-32 Pod. For other Pod options, see the available TPU types page.

    $ gcloud compute tpus tpu-vm create efficientnet-tutorial \
     --zone=${ZONE} \
     --accelerator-type=v3-32 \
     --version=tpu-vm-tf-2.18.0-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.
  9. Connect to the Compute Engine instance using SSH. When you are connected to the VM, your shell prompt changes from username@projectname to username@vm-name:

    gcloud compute tpus tpu-vm ssh efficientnet-tutorial --zone=europe-west4-a
  10. Export TPU setup variables:

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

    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.

  11. Install TensorFlow requirements.

    (vm)$ pip3 install -r /usr/share/tpu/models/official/requirements.txt
  12. Set some required environment variables:

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

    (vm)$ cd /usr/share/tpu/models/official/legacy/image_classification/
  14. 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.
    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
    The Cloud Storage path where checkpoints and summaries are stored during model training. You can reuse an existing folder to load previously generated checkpoints 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/legacy/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:

Run stats:
{
  'accuracy_top_1': 0.0009969075908884406,
  'eval_loss': 7.105168342590332,
  'loss': 7.114983081817627,
  'training_accuracy_top_1': 0.0010031675919890404,
  'step_timestamp_log': [
    'BatchTimestamp<batch_index: 0,
    timestamp: 1605041621.4997303>',
    'BatchTimestamp<batch_index: 312,
    timestamp: 1605041970.8633356>'
  ],
  'train_finish_time': 1605042032.2274444,
  'avg_exp_per_second': 3111.5120716536226
}

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.

  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.

    $ gcloud compute tpus tpu-vm delete efficientnet-tutorial \
    --zone=${ZONE}
  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=${ZONE}
  4. Delete your Cloud Storage bucket using the gcloud CLI as shown in the following example. Replace bucket-name with the name of your Cloud Storage bucket.

    $ gcloud storage rm gs://bucket-name --recursive

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.

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