Running MNIST on Cloud TPU

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.

Model description

The MNIST dataset contains a large number of images of hand-written 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:

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

You can find more information about the dataset at the MNIST database site.

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 via softmax.

This version of the MNIST model uses tf.estimator —a high-level TensorFlow API—which is the recommended way to build and run a machine learning model on a Cloud TPU.

The Tensorflow Estimator API simplifies the model development process by hiding most of the low-level implementation, which also makes it easy to 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

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

    Go to the project selector page

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

    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 GCP 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:

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

  6. Launch the Compute Engine resources required for this using the gcloud command.

    $ gcloud compute tpus execution-groups create \
     --name=mnist-tutorial \
     --zone=europe-west4-a \
     --tf-version=1.15.5 \
     --machine-type=n1-standard-1 \
     --accelerator-type=v3-8
    

    Command flag descriptions

    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 the gcloud command installs on your VM.
    machine-type
    The machine type of the Compute Engine VM to create.
    accelerator-type
    The type of the Cloud TPU to create.

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

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

When the gcloud 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. If you are not connected to the Compute Engine instance, you can do so by running the following command:

  gcloud compute ssh mnist-tutorial --zone=europe-west4-a

From this point on, a prefix of (vm)$ means you should run the command on the Compute Engine VM instance.

  1. Create environment variables for the storage bucket and model directory. Replace bucket-name with the name of your Cloud Storage bucket
    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    
    (vm)$ export TPU_NAME=mnist-tutorial
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/mnist
    (vm)$ export DATA_DIR=${STORAGE_BUCKET}/data
    (vm)$ export PYTHONPATH="${PYTHONPATH}:/usr/share/tpu/models"
    

Get the data

The MNIST dataset is hosted on the MNIST database site. Follow the instructions below to download and convert the data to the required format, and to upload the converted data to Cloud Storage.

Download and convert the MNIST data

The convert_to_records.py script downloads the data and converts it to the TFRecord format expected by the example MNIST model.

Use the following commands to run the script and decompress the files:

(vm)$ python3 /usr/share/tensorflow/tensorflow/examples/how_tos/reading_data/convert_to_records.py --directory=./data
(vm)$ gunzip ./data/*.gz

Upload the data to Cloud Storage

Upload the data to your Cloud Storage bucket so that the TPU server can access the data:

(vm)$ gsutil cp -r ./data ${DATA_DIR}

Run the MNIST TPU model

The MNIST TPU model is pre-installed on your Compute Engine VM in the following directory:

/usr/share/tpu/models/official/mnist/

The source code for the MNIST TPU model is also available on GitHub. You can run the model on a Cloud TPU. Alternatively, see how to run the model on a local machine.

Running the model on Cloud TPU

In the following steps, a prefix of (vm)$ means you should run the command on your Compute Engine VM.

  1. Change to the model directory:

      (vm)$ cd /usr/share/tpu/models/official/mnist/
    
  2. Run the MNIST model:

    (vm)$ python3 mnist_tpu.py \
      --tpu=${TPU_NAME} \
      --data_dir=${DATA_DIR} \
      --model_dir=${MODEL_DIR} \
      --use_tpu=True \
      --iterations=500 \
      --train_steps=2000
     

    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.
    data_dir
    The Cloud Storage path of training input. It is set to the fake_imagenet dataset in this example.
    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.
    use_tpu
    Set to true to train on a Cloud TPU.
    iterations
    The number batches needed to complete one epoch.
    iterations
    The number of batches needed to complete one epoch.

Running the model on a local (non-TPU) machine

To run the model on a non-TPU machine, omit --tpu, and set --use_tpu=False.

This causes the computation to land on a GPU if one is present. If no GPU is present, the computation falls back to the CPU.

What to expect

By default, the tf.estimator model reports loss value and step time in the following format:

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

Cleaning up

To avoid incurring charges to your GCP account for the resources used in this topic:

  1. Disconnect from the Compute Engine VM:

    (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 execution-groups delete mnist-tutorial \
      --zone=europe-west4-a
    
  3. 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=europe-west4-a
    
       NAME             STATUS
    
  4. 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

In this tutorial you have trained the MNIST 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.