Running MNIST on Cloud TPU (TF 2.x)


This tutorial contains a high-level description of the MNIST model, instructions on downloading the MNIST TensorFlow TPU code sample, and a guide to running the code on Cloud TPU.

Disclaimer

This tutorial uses a third-party dataset. Google provides no representation, warranty, or other guarantees about the validity, or any other aspects of this dataset.

Model description

The MNIST dataset contains a large number of images of handwritten digits in the range 0 to 9, as well as the labels identifying the digit in each image.

This tutorial trains a machine learning model to classify images based on the MNIST dataset. After training, the model classifies incoming images into 10 categories (0 to 9) based on what it's learned about handwritten images from the MNIST dataset. You can then send the model an image that it hasn't seen before, and the model identifies the digit in the image based on what the model has learned during training.

The MNIST dataset has been split into three parts:

  • 60,000 examples of training data
  • 10,000 examples of test data
  • 5,000 examples of validation data

The model has a mixture of seven layers:

  • 2 x convolution
  • 2 x max pooling
  • 2 x dense (fully connected)
  • 1 x dropout

Loss is computed using categorical cross entropy.

This version of the MNIST model uses the Keras API, a recommended way to build and run a machine learning model on a Cloud TPU.

Keras simplifies the model development process by hiding most of the low-level implementation, which also lets you switch between TPU and other test platforms such as GPUs or CPUs.

Objectives

  • Create a Cloud Storage bucket to hold your dataset and model output.
  • 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

This section provides information on setting up Cloud Storage bucket and a Compute Engine VM.

  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.

    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:

    gcloud storage buckets create gs://bucket-name \
    --project=${PROJECT_ID} \
    --location=us-central1
    

    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.

  6. Create a TPU VM using the gcloud command.

    $ gcloud compute tpus tpu-vm create mnist-tutorial \
       --zone=us-central1-b \
       --accelerator-type=v3-8 \
       --version=tpu-vm-tf-2.17.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.

  7. 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 mnist-tutorial --zone=us-central1-b
    
  8. Create an environment variable for the TPU name.

    (vm)$ export TPU_NAME=local
    
  9. Install TensorFlow requirements.

    (vm)$ pip3 install -r /usr/share/tpu/models/official/requirements.txt
    

Train the model

The source code for the MNIST TPU model is available on GitHub.

  1. Set the following variables. Replace bucket-name with your bucket name:

    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/mnist
    (vm)$ export DATA_DIR=${STORAGE_BUCKET}/data
    
  2. Set the PYTHONPATH environment variable.

    (vm)$ export PYTHONPATH="${PYTHONPATH}:/usr/share/tpu/models"
    
  3. 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
    
  4. Change to directory that stores the model:

    (vm)$ cd /usr/share/tpu/models/official/legacy/image_classification
    
  5. Run the MNIST training script:

    (vm)$ python3 mnist_main.py \
      --tpu=${TPU_NAME} \
      --model_dir=${MODEL_DIR} \
      --data_dir=${DATA_DIR} \
      --train_epochs=10 \
      --distribution_strategy=tpu \
      --download
    

    Command flag descriptions

    tpu
    The name of the Cloud TPU. If not specified when setting up the Compute Engine VM and Cloud TPU, defaults to your username.
    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.
    data_dir
    The Cloud Storage path of training input. It is set to the fake_imagenet dataset in this example.
    train_epochs
    The number of epochs to train the model.
    distribution_strategy
    To train the ResNet model on a Cloud TPU, set distribution_strategy to tpu.
    download
    When set to true, the script downloads and preprocesses the MNIST dataset, if it hasn't been downloaded already.

The training script runs in under 5 minutes on a v3-8 Cloud TPU and displays output similar to:

Run stats:
{
  'accuracy_top_1': 0.9762369990348816,
  'eval_loss': 0.07863274961709976,
  'loss': 0.1111728847026825,
  'training_accuracy_top_1': 0.966645359992981
}

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 mnist-tutorial \
      --zone=us-central1-b
    
  3. Verify the resources have been deleted by running gcloud compute tpus tpu-vm list. The deletion might take several minutes. The output from the following command shouldn't include any of the resources created in this tutorial:

    $ gcloud compute tpus tpu-vm list --zone=us-central1-b
  4. Delete your Cloud Storage bucket using the following command. 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.