BERT FineTuning with Cloud TPU: Sentence and Sentence-Pair Classification Tasks

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.
  • Clone the BERT repository and other required files.
  • 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 Cloud Storage bucket using the following command:

    gsutil mb -p ${PROJECT_ID} -c standard -l us-central1 -b on gs://bucket-name

    This Cloud Storage bucket stores the data you use to train your model and the training results.

    In order for the Cloud TPU to read and write to the storage bucket, the service account for your project needs read/write or Admin permissions on it. See the section on storage buckets for how to view and set those permissions.

  5. Launch a Compute Engine VM and Cloud TPU using the ctpu up command.

    $ ctpu up --tpu-size=v3-8 \
     --machine-type=n1-standard-8 \
     --zone=us-central1-b \
     --tf-version=1.15.3 \
  6. The configuration you specified appears. Enter y to approve or n to cancel.

  7. When the ctpu up command has finished executing, verify that your shell prompt has changed from username@project to username@vm-name. This change shows that you are now logged into your Compute Engine VM.

    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.

  1. Define some environment variables

    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    (vm)$ export TPU_NAME=bert-tutorial
    (vm)$ export PYTHONPATH="${PYTHONPATH}:/usr/share/tpu/models"
    (vm)$ export BERT_BASE_DIR=gs://cloud-tpu-checkpoints/bert/uncased_L-12_H-768_A-12
    (vm)$ export GLUE_DIR=$HOME/glue_data
    (vm)$ export TASK_NAME=MRPC

Clone the BERT repository

From your Compute Engine virtual machine (VM), clone the BERT repository.

(vm)$ git clone


This tutorial uses the General Language Understanding Evaluation (GLUE) benchmark to evaluate and analyze the performance of the model. To use this benchmark, download the script using the following git clone command:

(vm)$ git clone download_glue_data

Download the GLUE data

Next, run the on your Compute Engine VM.

(vm)$ python3 download_glue_data/ --data_dir $HOME/glue_data --tasks all

Train the model

From your Compute Engine VM, run the following command.

python3 ./bert/ \
--task_name=${TASK_NAME} \
--do_train=true \
--do_eval=true \
--data_dir=${GLUE_DIR}/${TASK_NAME} \
--vocab_file=${BERT_BASE_DIR}/vocab.txt \
--bert_config_file=${BERT_BASE_DIR}/bert_config.json \
--init_checkpoint=${BERT_BASE_DIR}/bert_model.ckpt \
--max_seq_length=128 \
--train_batch_size=32 \
--learning_rate=2e-5 \
--num_train_epochs=3.0 \
--output_dir=${STORAGE_BUCKET}/${TASK_NAME}-output/ \
--use_tpu=True \

Verify your results

The training should take less than 5 minutes. When the training completes, you should see results similar to the following:

***** Eval results *****
  eval_accuracy = 0.845588
  eval_loss = 0.64990824
  global_step = 343
  loss = 0.34979442

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.