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:

Objectives

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

Costs

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

    gcloud storage buckets create gs://bucket-name --project=${PROJECT_ID} --location=us-central1
    

    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 tpu-vm create 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 TPU (VM).

  6. Launch a TPU VM using gcloud. For more information, see the gcloud Reference.

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

    Command flag descriptions

    zone
    The zone where you plan to create your Cloud TPU.
    accelerator-type
    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.
    version
    The Cloud TPU software version.
  7. Connect to the TPU VM instance using SSH. When you are connected to the VM, your shell prompt changes from username@projectname to username@vm-name:

    gcloud compute tpus tpu-vm ssh bert-tutorial --zone=us-central1-b
    
  8. Create an environment variable for the TPU name.

    (vm)$ export TPU_NAME=local
    

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 https://storage.googleapis.com/tf_model_garden/nlp/bert/v3/uncased_L-12_H-768_A-12.tar.gz -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)$ gcloud storage cp uncased_L-12_H-768_A-12 ${STORAGE_BUCKET} --recursive

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.

    (vm)$ pip3 install -r /usr/share/tpu/models/official/requirements.txt
    
  3. Set the PYTHONPATH environment variable

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

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

    (vm)$ python3 official/nlp/train.py \
      --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

    tpu
    The name of the Cloud TPU to use for training.
    mode
    One of train, eval, train_and_eval, or predict.
    model_dir
    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 controller.py:457] 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 controller.py:277]  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.

    $ gcloud compute tpus tpu-vm delete bert-tutorial \
      --zone=us-central1-b
    
  3. Verify the resources have been deleted by running gcloud compute tpus tpu-vm list. The deletion might take several minutes. The output from the following command shouldn't include any of the resources created in this tutorial:

    $ gcloud compute tpus tpu-vm list --zone=us-central1-b
    
  4. Delete your Cloud Storage bucket using the gcloud CLI as shown in the following example. Replace bucket-name with the name of your Cloud Storage bucket.

    $ gcloud storage rm gs://bucket-name --recursive
    

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.

Inference

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.