BERT Fine Tuning with Cloud TPU: Sentence and Sentence-Pair Classification Tasks (TF 2.x)

This tutorial shows you how to train the Bidirectional Encoder Representations from Transformers (BERT) model on Cloud TPU.

BERT is a method of pre-training language representations. Pre-training refers to how BERT is first trained on a large source of text, such as Wikipedia. You can then apply the training results to other Natural Language Processing (NLP) tasks, such as question answering and sentiment analysis. With BERT and Cloud TPU, you can train a variety of NLP models in about 30 minutes.

For more information about BERT, see the following resources:


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


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}
  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 us-central1 gs://bucket-name

    This Cloud Storage bucket stores the data you use to train your model and the training results. The command you use to create a TPU (gcloud compute tpus execution-groups create for the TPU Node architecture or gcloud compute tpus tpu-vm create for the TPU VM architecture) 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. Launch a Compute Engine VM and Cloud TPU using the gcloud command. The command you use depends on whether you are using a TPU VM or a TPU node. For more information on the two VM architecture, see System Architecture. For more information on the gcloud command, see the gcloud Reference.

    TPU VM

    $ gcloud compute tpus tpu-vm create bert-tutorial \
    --zone=us-central1-b \
    --accelerator-type=v3-8 \

    Command flag descriptions

    The zone where you plan to create your Cloud TPU.
    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.
    The Cloud TPU software version.

    TPU Node

    $ gcloud compute tpus execution-groups create \
      --name=bert-tutorial \
      --zone=us-central1-b \
      --tf-version=2.12.0 \
      --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 ctpu installs on the VM.
    The machine type of the Compute Engine VM to create.
    accelerator type
    The type of the Cloud TPU to create.
  7. If you are not automatically logged in to the Compute Engine instance, log in by running the following ssh command. When you are logged into the VM, your shell prompt changes from username@projectname to username@vm-name:

    TPU VM

    gcloud compute tpus tpu-vm ssh bert-tutorial --zone=us-central1-b

    TPU Node

    gcloud compute ssh bert-tutorial --zone=us-central1-b

    As you continue these instructions, run each command that begins with (vm)$ in your VM session window.

  8. Create an environment variable for the TPU name.

    TPU VM

    (vm)$ export TPU_NAME=local

    TPU Node

    (vm)$ export TPU_NAME=bert-tutorial

Prepare the dataset

  1. Define the storage bucket needed to store the model and the dataset:

    (vm)$ export STORAGE_BUCKET=gs://bucket-name
  2. Copy the pretrained checkpoint and vocab files to your storage bucket:

      (vm)$ curl -o uncased_L-12_H-768_A-12.tar.gz
      (vm)$ mkdir -p uncased_L-12_H-768_A-12
      (vm)$ tar -xvf uncased_L-12_H-768_A-12.tar.gz
      (vm)$ gsutil -m cp -R uncased_L-12_H-768_A-12 ${STORAGE_BUCKET} 

Train the model

  1. Define several parameter values that are required when you train and evaluate the model:

      (vm)$ export INIT_CHECKPOINT=${STORAGE_BUCKET}/uncased_L-12_H-768_A-12/bert_model.ckpt
      (vm)$ export TFDS_DIR=${STORAGE_BUCKET}/tfds
      (vm)$ export VOCAB_FILE=${STORAGE_BUCKET}/uncased_L-12_H-768_A-12/vocab.txt
      (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/bert-output
      (vm)$ export TASK=mnli

  2. Install TensorFlow requirements.

    The command you use depends on whether you are using a TPU VM or a TPU Node.

    TPU VM

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

    TPU Node

    (vm)$ pip3 install --user -r /usr/share/models/official/requirements.txt
    (vm)$ pip3 install tensorflow-datasets==4.6.0
  3. Set the PYTHONPATH environment variable

    TPU VM

    (vm)$ export PYTHONPATH=/usr/share/tpu/models

    TPU Node

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

    TPU VM

    (vm)$ cd /usr/share/tpu/models

    TPU Node

    (vm)$ cd /usr/share/models
  5. Run the training script:

    (vm)$ python3 official/nlp/ \
      --tpu=${TPU_NAME} \
      --experiment=bert/sentence_prediction_text \
      --mode=train_and_eval \
      --model_dir=${MODEL_DIR} \
      --config_file=official/nlp/configs/experiments/glue_mnli_text.yaml \
      --params_override="runtime.distribution_strategy=tpu, task.init_checkpoint=${INIT_CHECKPOINT}, task.train_data.tfds_data_dir=${TFDS_DIR}, task.train_data.vocab_file=${VOCAB_FILE}, task.validation_data.tfds_data_dir=${TFDS_DIR}, task.validation_data.vocab_file=${VOCAB_FILE}, trainer.train_steps=2000"     

    Command flag descriptions

    The name of the Cloud TPU to use for training.
    One of train, eval, train_and_eval, or predict.
    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.

    The script trains for 2000 steps and then runs 307 steps of evaluation. On a v3-8 TPU, after approximately 5 minutes the training script should complete and display results similar to this:

    I0719 00:47:52.683979 140297079573568] train | step:   2000 | steps/sec:   26.3 | output: 
    {'cls_accuracy': 0.7249375,
     'learning_rate': 1.4670059e-05,
     'training_loss': 0.6740678}
    train | step:   2000 | steps/sec:   26.3 | output: 
    {'cls_accuracy': 0.7249375,
     'learning_rate': 1.4670059e-05,
     'training_loss': 0.6740678}
    I0719 00:47:53.184051 140297079573568]  eval | step:   2000 | running 307 steps of evaluation...
    eval | step:   2000 | running 307 steps of evaluation...

Clean up

  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. The command you use to delete your resources depends upon whether you are using TPU VMs or TPU Nodes. For more information, see System Architecture.

    TPU VM

    $ gcloud compute tpus tpu-vm delete bert-tutorial \

    TPU Node

    $ gcloud compute tpus execution-groups delete bert-tutorial \
  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 should not include any of the resources created in this tutorial:

    TPU VM

    $ gcloud compute tpus tpu-vm list --zone=us-central1-b

    TPU Node

    $ gcloud compute tpus execution-groups list --zone=us-central1-b
  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 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.


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.