Training transformer on Cloud TPU (TF 2.x)


If you are not familiar with Cloud TPU, see TPU getting started guides.

This tutorial shows you how to train a Transformer model on Cloud TPU. Transformer is a neural network architecture that solves sequence to sequence problems using attention mechanisms. Unlike traditional neural seq2seq models, Transformer does not involve recurrent connections. The attention mechanism learns dependencies between tokens in two sequences. Since attention weights apply to all tokens in the sequences, the Transformer model is able to easily capture long-distance dependencies.

Transformer's overall structure follows the standard encoder-decoder pattern. The encoder uses self-attention to compute a representation of the input sequence. The decoder generates the output sequence one token at a time, taking the encoder output and previous decoder-output tokens as inputs.

The model also applies embeddings on the input and output tokens, and adds a constant positional encoding. The positional encoding adds information about the position of each token.

Objectives

  • Create a Cloud Storage bucket to hold your dataset and model output.
  • Download and pre process the dataset used to train the model.
  • 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

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

Before starting this tutorial, check that your Google Cloud project is correctly set up.

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  5. Make sure that billing is enabled for your Google Cloud project.

  6. This walkthrough uses billable components of Google Cloud. Check the Cloud TPU pricing page to estimate your costs. Be sure to clean up resources you create when you've finished with them to avoid unnecessary charges.

Train with a single Cloud TPU device

This section provides information on setting up a Cloud Storage bucket and a TPU VM for single device training.

  1. Open a Cloud Shell window.

    Open Cloud Shell

  2. Create an environment variable for your project ID.

    export PROJECT_ID=project-id
  3. Configure Google Cloud CLI to use the your Google Cloud project where you want to create a 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 Google Cloud API calls with your credentials.

  4. Create a Service Account for the Cloud TPU project.

    Service accounts allow the Cloud TPU service to access other Google Cloud services.

    $ 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-central2

    This Cloud Storage bucket stores the data you use to train your model and the training results. The gcloud command used in this tutorial to set up the TPU also 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.

Train the Transformer model on a single Cloud TPU

  1. Launch a Cloud TPU VM using the gcloud command.

      $ gcloud compute tpus tpu-vm create transformer-tutorial \
         --zone=us-central2-b \
         --accelerator-type=v4-8 \
         --version=tpu-vm-tf-2.18.0-pjrt

    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.
  2. Connect to the TPU VM 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 transformer-tutorial --zone=us-central2-b
  3. Export environment variables.

      (vm)$ export STORAGE_BUCKET=gs://bucket-name
      (vm)$ export SENTENCEPIECE_MODEL=sentencepiece
      (vm)$ export SENTENCEPIECE_MODEL_PATH=${STORAGE_BUCKET}/${SENTENCEPIECE_MODEL}.model
      (vm)$ export TFDS_DIR=${STORAGE_BUCKET}/tfds
      (vm)$ export PARAM_SET=big
      (vm)$ export TPU_NAME=local
      (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/transformer/model_${PARAM_SET}
      (vm)$  export PYTHONPATH="/usr/share/tpu/models:$PYTHONPATH"
  4. When creating your TPU, if you set the --version parameter to a version ending with -pjrt, set the following environment variables to enable the PJRT runtime:

      (vm)$ export NEXT_PLUGGABLE_DEVICE_USE_C_API=true
      (vm)$ export TF_PLUGGABLE_DEVICE_LIBRARY_PATH=/lib/libtpu.so
  5. Install TensorFlow requirements.

    (vm)$ pip3 install -r /usr/share/tpu/models/official/requirements.txt
  6. Download and preprocess the dataset

     (vm)$ python3 -c "import tensorflow_datasets as tfds; tfds.load('wmt14_translate/de-en', split='train+validation', shuffle_files=True, download=True)"
      (vm)$ python3 /usr/share/tpu/models/official/nlp/data/train_sentencepiece.py --output_model_path=${SENTENCEPIECE_MODEL}
  7. Copy the dataset to the Cloud Storage bucket

      (vm)$ gcloud storage cp ${SENTENCEPIECE_MODEL}.model ${STORAGE_BUCKET}
      (vm)$ gcloud storage cp ${SENTENCEPIECE_MODEL}.vocab ${STORAGE_BUCKET}
      (vm)$ gcloud storage cp tensorflow_datasets/wmt14_translate ${TFDS_DIR}/wmt14_translate --recursive
  8. Navigate to the training directory

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

    (vm)$ python3 official/nlp/train.py \
      --tpu=${TPU_NAME} \
      --experiment=wmt_transformer/large \
      --mode=train_and_eval \
      --model_dir=${MODEL_DIR} \
      --params_override="runtime.distribution_strategy=tpu, task.train_data.tfds_data_dir=${TFDS_DIR}, task.validation_data.tfds_data_dir=${TFDS_DIR}, task.sentencepiece_model_path=${SENTENCEPIECE_MODEL_PATH}, trainer.train_steps=10000, trainer.validation_interval=10000"

    Command flag descriptions

    tpu
    The name of the Cloud TPU. This is set by specifying the environment variable (TPU_NAME).
    experiment
    The model to train.
    mode
    The mode in which to run the script.
    model_dir
    The Cloud Storage bucket where checkpoints and summaries are stored during training. You can use an existing folder to load previously generated checkpoints created on a TPU of the same size and TensorFlow version.
    params_override
    Set model parameters.

    By default, the model will evaluate after every 10,000 steps. You can increase the number of training steps or specify how often to run evaluations by setting these parameters:

    • train.train_steps: The total number of training steps to run.
    • trainer.validation_interval: The number of training steps to run between evaluations.

    Training and evaluation takes approximately 20 minutes on a v4-8 Cloud TPU. When the training and evaluation complete, a message similar to the following appears:

    I0208 20:57:19.309512 140039467895872 controller.py:310]  eval | step:  10000 | eval time:   69.2 sec | output:
    {'bleu_score': 19.204771518707275,
     'sacrebleu_score': 18.307039308307356,
     'validation_loss': 2.0654342}
     eval | step:  10000 | eval time:   69.2 sec | output:
    {'bleu_score': 19.204771518707275,
     'sacrebleu_score': 18.307039308307356,
     'validation_loss': 2.0654342}
    

    You have now completed single-device training. Use the following steps to delete your single-device TPU resources.

  10. Disconnect from the Compute Engine instance:

    (vm)$ exit

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

  11. Delete the TPU resource.

    $ gcloud compute tpus tpu-vm delete transformer-tutorial \
    --zone=us-central2-b

    Command flag descriptions

    zone
    The zone where your Cloud TPU resided.

At this point, you can either conclude this tutorial and clean up, or you can continue and explore running the model on Cloud TPU Pods.

Scale your model with Cloud TPU Pods

Training your model on Cloud TPU Pods may require some changes to your training script. For information, see Training on TPU Pods.

TPU Pod training

  1. Open a Cloud Shell window.

    Open Cloud Shell

  2. Create a variable for your project ID.

    export PROJECT_ID=project-id
  3. Configure Google Cloud CLI to use the project where you want to create a 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 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 or use a bucket you created earlier for your project:

    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 gcloud command used in this tutorial sets up default permissions for the Cloud TPU Service Account you set up in the previous step. For more information on finer-grain permissions, see access level permissions.

Launch the TPU VM resources

  1. Launch a TPU VM Pod using the gcloud command. This tutorial specifies a v4-32 Pod. For other Pod options, see TPU types available TPU types page.

    $ gcloud compute tpus tpu-vm create transformer-tutorial \
      --zone=us-central2-b \
      --accelerator-type=v3-32 \
      --version=tpu-vm-tf-2.18.0-pod-pjrt

    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.
  2. Connect to the Compute Engine 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 transformer-tutorial --zone=us-central2-b
  3. Install TensorFlow requirements.

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

Set up and start the Pod training

  1. Export Cloud TPU setup variables:

    (vm)$ export PYTHONPATH="/usr/share/tpu/models:$PYTHONPATH"
    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    (vm)$ export SENTENCEPIECE_MODEL=sentencepiece
    (vm)$ export SENTENCEPIECE_MODEL_PATH=${STORAGE_BUCKET}/${SENTENCEPIECE_MODEL}.model
    (vm)$ export TFDS_DIR=${STORAGE_BUCKET}/tfds
    (vm)$ export TPU_NAME=transformer-tutorial
    (vm)$ export PARAM_SET=big
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/transformer/model_${PARAM_SET}
    (vm)$ export TPU_LOAD_LIBRARY=0
  2. Download the dataset

    (vm)$ python3 -c "import tensorflow_datasets as tfds; tfds.load('wmt14_translate/de-en', split='train+validation', shuffle_files=True, download=True)"
    (vm)$ python3 /usr/share/tpu/models/official/nlp/data/train_sentencepiece.py --output_model_path=${SENTENCEPIECE_MODEL}
  3. Copy the dataset to Cloud Storage bucket

    (vm)$ gcloud storage cp ${SENTENCEPIECE_MODEL}.model ${STORAGE_BUCKET}
    (vm)$ gcloud storage cp ${SENTENCEPIECE_MODEL}.vocab ${STORAGE_BUCKET}
    (vm)$ gcloud storage cp tensorflow_datasets/wmt14_translate ${TFDS_DIR}/wmt14_translate --recursive
  4. Change to the training directory:

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

    (vm)$ python3 official/nlp/train.py \
    --tpu=${TPU_NAME} \
    --experiment=wmt_transformer/large \
    --mode=train_and_eval \
    --model_dir=${MODEL_DIR} \
    --params_override="runtime.distribution_strategy=tpu, task.train_data.tfds_data_dir=${TFDS_DIR}, task.validation_data.tfds_data_dir=${TFDS_DIR}, task.sentencepiece_model_path=${SENTENCEPIECE_MODEL_PATH}, trainer.train_steps=10000, trainer.validation_interval=10000"

    Command flag descriptions

    tpu
    The name of the Cloud TPU. This is set by specifying the environment variable (TPU_NAME).
    experiment
    The model to train.
    mode
    The mode in which to run the script.
    model_dir
    The Cloud Storage bucket where checkpoints and summaries are stored during training. You can use an existing folder to load previously generated checkpoints created on a TPU of the same size and TensorFlow version.
    params_override
    Set model parameters.

By default, the model will evaluate after every 10000 steps. In order to train to convergence, change train_steps to 200000. You can increase the number of training steps or specify how often to run evaluations by setting these parameters:

  • trainer.train_steps: Sets the total number of training steps to run.
  • trainer.validation_interval: Sets the number of training steps to run between evaluations.

Training and evaluation takes approximately 14 minutes on a v4-32 Cloud TPU. When the training and evaluation complete, messages similar to the following appear:

I0209 22:19:49.143219 139751309618240 controller.py:310]  eval | step:  10000 | eval time:   73.6 sec | output:
    {'bleu_score': 19.401752948760986,
     'sacrebleu_score': 18.442741330886378,
     'validation_loss': 2.0558002}
 eval | step:  10000 | eval time:   73.6 sec | output:
    {'bleu_score': 19.401752948760986,
     'sacrebleu_score': 18.442741330886378,
     'validation_loss': 2.0558002}

This training script trains for 20000 steps and runs evaluation every 2000 steps. This particular training and evaluation takes approximately 8 minutes on a v3-32 Cloud TPU Pod. When the training and evaluation complete, a message similar to the following appears:

INFO:tensorflow:Writing to file /tmp/tmpdmlanxcf
I0218 21:09:19.100718 140509661046592 translate.py:184] Writing to file /tmp/tmpdmlanxcf
I0218 21:09:28.043537 140509661046592 transformer_main.py:118] Bleu score (uncased): 1.799112930893898
I0218 21:09:28.043911 140509661046592 transformer_main.py:119] Bleu score (cased): 1.730366237461567

In order to train to convergence, change train_steps to 200000. You can increase the number of training steps or specify how often to run evaluations by setting these parameters:

  • --train_steps: Sets the total number of training steps to run.
  • --steps_between_evals: Number of training steps to run between evaluations.

When the training and evaluation complete, a message similar to the following appears:

0509 00:27:59.984464 140553148962624 translate.py:184] Writing to file /tmp/tmp_rk3m8jp
I0509 00:28:11.189308 140553148962624 transformer_main.py:119] Bleu score (uncased): 1.3239131309092045
I0509 00:28:11.189623 140553148962624 transformer_main.py:120] Bleu score (cased): 1.2855342589318752

Clean 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 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 transformer-tutorial \
      --zone=us-central2-b
  3. Run the gcloud CLI as shown, replacing bucket-name with the name of the Cloud Storage bucket you created for this tutorial:

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