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:

Objectives

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

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

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}
    

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

  6. Launch a Compute Engine VM and Cloud TPU using the gcloud compute tpus execution-groups command.

    $ gcloud compute tpus execution-groups create \
     --name=bert-tutorial \
     --zone=us-central1-b \
     --tf-version=1.15.5 \
     --machine-type=n1-standard-8 \
     --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 gcloud installs on the 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. The configuration you specified appears. Enter y to approve or n to cancel.

    When the gcloud 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 https://github.com/google-research/bert

Download download_glue_data.py

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 download_glue_data.py script using the following git clone command:

(vm)$ git clone https://gist.github.com/7f702beb69199612a039004f42c9982e.git download_glue_data

Download the GLUE data

Next, run the download_glue_data.py on your Compute Engine VM.

(vm)$ python3 download_glue_data/download_glue_data.py --data_dir $HOME/glue_data --tasks ${TASK_NAME}

Train the model

From your Compute Engine VM, run the following command.

python3 ./bert/run_classifier.py \
--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 \
--tpu_name=${TPU_NAME}

Command flag descriptions

task_name
The task name. In this tutorial we are using the Microsoft Research Paraphrase Corpus (MSRPC) task.
do_train
Perform model training.
do_eval
Perform model evaluation.
data_dir
The Cloud Storage path where training data are stored.
vocab_file
The BERT vocabulary file.
bert_config_file
The BERT configuration file.
init_checkpoint
The path to the json file containing the initial checkpoint of the pre-trained BERT model.
max_seq_length
The maximum text sequence length. BERT limits the maximum length of a tokenized text sequence to 512. You can set any sequence length equal to or below this value.
train_batch_size
The training batch size.
learning_rate
The learning rate.
num_train_epochs
The number of epochs to train the model.
output_dir
The training script output directory.
use_tpu
Set to true to train on a Cloud TPU.
tpu_name
The name of the Cloud TPU to use for training.

Verify your results

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

I1109 21:55:34.984220 139985090225920 run_classifier.py:923] ***** Eval results *****
INFO:tensorflow:  eval_accuracy = 0.8455882
I1109 21:55:34.984345 139985090225920 run_classifier.py:925]   eval_accuracy = 0.8455882
INFO:tensorflow:  eval_loss = 0.77791333
I1109 21:55:34.984572 139985090225920 run_classifier.py:925]   eval_loss = 0.77791333
INFO:tensorflow:  global_step = 343
I1109 21:55:34.984693 139985090225920 run_classifier.py:925]   global_step = 343
INFO:tensorflow:  loss = 0.88203496
I1109 21:55:34.984774 139985090225920 run_classifier.py:925]   loss = 0.88203496

Cleaning up

To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.

  1. Disconnect from the Compute Engine VM:

    (vm)$ exit
    

    Your prompt should now be user@projectname, showing you are in the Cloud Shell.

  2. In your Cloud Shell, use the gcloud compute tpus execution-groups command shown below to delete your Compute Engine VM and the Cloud TPU.

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

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.