BERT FineTuning 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.


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

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 gcloud command-line tool 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 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 compute tpus execution-groups 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 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 VMs

    $ gcloud alpha compute tpus tpu-vm create bert-tutorial \
    --zone=europe-west4-a \
    --accelerator-type=v3-8 \

    Command flag descriptions

    The zone where you plan to create your Cloud TPU.
    The type of the Cloud TPU to create.
    The Cloud TPU runtime version.

    TPU Node

    $ gcloud compute tpus execution-groups create \
    --name=bert-tutorial \
    --zone=europe-west4-a \
    --tf-version=2.5.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 alpha compute tpus tpu-vm ssh bert-tutorial --zone=europe-west4-a

    TPU Node

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

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

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

    TPU VM

    (vm)$ git clone
    (vm)$ pip3 install -r models/official/requirements.txt

    TPU Node

    (vm)$ sudo pip3 install -r /usr/share/models/official/requirements.txt
  2. Optional: download

    This tutorial uses the General Language Understanding Evaluation (GLUE) benchmark to evaluate and analyze the performance of the model. The GLUE data is provided for this tutorial at gs://cloud-tpu-checkpoints/bert/classification.

    If you want to work with raw GLUE data and create TFRecords, follow the dataset processing instructions on GitHub.

Define parameter values

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

    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    (vm)$ export BERT_BASE_DIR=gs://cloud-tpu-checkpoints/bert/keras_bert/uncased_L-24_H-1024_A-16
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/bert-output
    (vm)$ export GLUE_DIR=gs://cloud-tpu-checkpoints/bert/classification
    (vm)$ export TASK=mnli
  2. Set the PYTHONPATH environment variable

    TPU VM

    (vm)$ export PYTHONPATH="${PWD}/models:${PYTHONPATH}"

    TPU Node

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

    TPU VM

    (vm)$ cd ~/models/official/nlp/bert

    TPU Node

    (vm)$ cd /usr/share/models/official/nlp/bert

Train the model

From your Compute Engine VM, run the following command.

(vm)$ python3 \
  --mode='train_and_eval' \
  --input_meta_data_path=${GLUE_DIR}/${TASK}_meta_data \
  --train_data_path=${GLUE_DIR}/${TASK}_train.tf_record \
  --eval_data_path=${GLUE_DIR}/${TASK}_eval.tf_record \
  --bert_config_file=${BERT_BASE_DIR}/bert_config.json \
  --init_checkpoint=${BERT_BASE_DIR}/bert_model.ckpt \
  --train_batch_size=32 \
  --eval_batch_size=32 \
  --learning_rate=2e-5 \
  --num_train_epochs=1 \
  --model_dir=${MODEL_DIR} \
  --distribution_strategy=tpu \
  --tpu=${TPU_NAME} \

Command flag descriptions

One of train, eval, train_and_eval, or predict.
The path to a file that contains metadata about the dataset to be used for training and evaluation.
The Cloud Storage path for training input. It is set to the fake_imagenet dataset in this example.
The Cloud Storage path for evaluation input. It is set to the fake_imagenet dataset in this example.
The BERT configuration file.
The path to the json file containing the initial checkpoint of the pre-trained BERT model.
The training batch size.
The evaluation batch size.
The learning rate.
The number of epochs to train the model.
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.
To train the ResNet model on a TPU, set the distribution_strategy to tpu.
The name of the Cloud TPU to use for training.
The number of training steps to run before saving state to the CPU. A training step is the processing of one batch of examples. This includes both a forward pass and back propagation.

The training takes approximately 30 minutes on a v3-8 TPU. Upon completion the training script should display results like this:

12271/12271 [==============================]
  - 756s 62ms/step
  - loss: 0.4864
  - accuracy: 0.8055
  - val_loss: 0.3832
  - val_accuracy: 0.8546

To increase accuracy, set --num_tain_epochs=3.

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 VMs

    $ gcloud alpha 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. A response like the one below indicates your instances have been successfully deleted:

    $ gcloud compute tpus execution-groups list \
     Listed 0 items.
  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 BERT 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.


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.