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. tf.estimator is only available in Tensorflow 1.x. If you are using Tensorflow 2.x, see the MNIST tutorial which uses the Keras API instead.


  • Create a Cloud Storage bucket to hold your dataset and model output.
  • Run the training job.
  • Verify the output results.


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. 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 Cloud project. Learn how to check if billing is enabled on a 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 Cloud project. Learn how to check if billing is enabled on a 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 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 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 GCP API calls with your credentials.

  4. Create a Service Account for the Cloud TPU project.

    gcloud beta services identity create --service --project $PROJECT_ID

    The command returns a Cloud TPU Service Account with following format:

  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 \

    Command flag descriptions

    The name of the Cloud TPU to create.
    The zone where you plan to create your Cloud TPU.
    The version of Tensorflow the gcloud command installs on your VM.
    The machine type of the Compute Engine VM to create.
    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 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/ --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:


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 \
      --tpu=${TPU_NAME} \
      --data_dir=${DATA_DIR} \
      --model_dir=${MODEL_DIR} \
      --use_tpu=True \
      --iterations=500 \

    Command flag descriptions

    The name of the Cloud TPU. If not specified when setting up the Compute Engine VM and Cloud TPU, defaults to your username.
    The Cloud Storage path of training input. It is set to the fake_imagenet dataset in this example.
    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.
    Set to true to train on a Cloud TPU.
    The number batches needed to complete one epoch.
    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

Clean 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 \
  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 \
       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

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.


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.