Running the Transformer with Tensor2Tensor

This tutorial shows you how to train the Transformer model (from Attention Is All You Need) with Tensor2Tensor on a Cloud TPU.

Model description

The Transformer model uses stacks of self-attention layers and feed-forward layers to process sequential input like text. It supports the following variants:

  • transformer (decoder-only) for single sequence modeling. Example use case: language modeling.
  • transformer (encoder-decoder) for sequence to sequence modeling. Example use case: translation.
  • transformer_encoder (encoder-only) runs only the encoder for sequence to class modeling. Example use case: sentiment classification.

The Transformer is just one of the models in the Tensor2Tensor library. Tensor2Tensor (T2T) is a library of deep learning models and datasets as well as a set of scripts that allow you to train the models and to download and prepare the data.

Before you begin

Before starting this tutorial, follow the steps below to check that your Google Cloud Platform project is correctly set up.

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Select or create a GCP project.

    Go to the project selector page

  3. Make sure that billing is enabled for your Google Cloud Platform project. Learn how to enable billing.

  4. Verify that you have sufficient quota to use either TPU devices or Pods.

Set up your resources

This section provides information on setting up Cloud Storage storage, VM, and Cloud TPU resources for tutorials.

Create a Cloud Storage bucket

You need a Cloud Storage bucket to store the data you use to train your model and the training results. The ctpu up tool used in this tutorial sets up default permissions for the Cloud TPU service account. If you want finer-grain permissions, review the access level permissions.

The bucket location must be in the same region as your virtual machine (VM) and your TPU node. VMs and TPU nodes are located in specific zones, which are subdivisions within a region.

  1. Go to the Cloud Storage page on the GCP Console.

    Go to the Cloud Storage page

  2. Create a new bucket, specifying the following options:

    • A unique name of your choosing.
    • Default storage class: Standard
    • Location: Specify a bucket location in the same region where you plan to create your TPU node. See TPU types and zones to learn where various TPU types are available.

Use the ctpu tool

This section demonstrates using the Cloud TPU provisioning tool (ctpu) for creating and managing Cloud TPU project resources. The resources are comprised of a virtual machine (VM) and a Cloud TPU resource that have the same name. These resources must reside in the same region/zone as the bucket you just created.

You can also set up your VM and TPU resources using gcloud commands or through the Cloud Console. For more information, see the creating and deleting TPUs page for details.

Run ctpu up to create resources

  1. Open a Cloud Shell window.

    Open Cloud Shell

  2. Run gcloud config set project <Your-Project> to use the project where you want to create Cloud TPU.

  3. Run ctpu up specifying the flags shown for either a Cloud TPU device or Pod slice. Refer to CTPU Reference for flag options and descriptions.

  4. Set up either a Cloud TPU device or a Pod slice:

TPU Device

Set up a Cloud TPU device:

$ ctpu up 

The following configuration message appears:

ctpu will use the following configuration:

Name: [your TPU's name]
Zone: [your project's zone]
GCP Project: [your project's name]
TensorFlow Version: 1.14
VM:
  Machine Type: [your machine type]
  Disk Size: [your disk size]
  Preemptible: [true or false]
Cloud TPU:
  Size: [your TPU size]
  Preemptible: [true or false]

OK to create your Cloud TPU resources with the above configuration? [Yn]:

Press y to create your Cloud TPU resources.

TPU Pod

Set up a Cloud TPU slice on the VM and the zone you are working in:

$ ctpu up --zone=us-central1-a --tpu-size=v2-32 --machine-type n1-standard-8 

The following configuration message appears:

ctpu will use the following configuration:

Name: [your TPU's name]
Zone: [your project's zone]
GCP Project: [your project's name]
TensorFlow Version: 1.14
VM:
  Machine Type: [your machine type]
  Disk Size: [your disk size]
  Preemptible: [true or false]
Cloud TPU:
  Size: [your TPU size]
  Preemptible: [true or false]

OK to create your Cloud TPU resources with the above configuration? [Yn]:

Press y to create your Cloud TPU resources.

The ctpu up command creates a virtual machine (VM) and Cloud TPU services.

From this point on, a prefix of (vm)$ means you should run the command on the Compute Engine VM instance.

Verify your Compute Engine VM

When the ctpu up command has finished executing, verify that your shell prompt is username@tpuname, which shows you are logged into your Compute Engine VM.

Determine if you need to add disk space to your VM

T2T conveniently packages data generation for many common open-source datasets in its t2t-datagen script. The script downloads the data, preprocess it, and makes it ready for training. To do so, it needs at least 200 GB of local disk space.

You can skip this step if you used ctpu up to create your Compute Engine VM since it provides 250 GB of disk space for your VM. If you set up your Compute Engine VM using gcloud commands or the Cloud Console, and did not specify the VM disk size to be at least 200 GB, follow the instructions below.

  • Follow the Compute Engine guide to add a disk to your Compute Engine VM.
  • Set the disk size to 200 GB (the recommended minimum size).
  • Set When deleting instance to Delete disk to ensure that the disk is removed when you remove the VM.

Make a note of the path to your new disk. For example: /mnt/disks/mnt-dir.

Generate the training dataset

On your Compute Engine VM:

  1. Create the following environment variables:

    (vm)$ export STORAGE_BUCKET=gs://YOUR-BUCKET-NAME
    (vm)$ export DATA_DIR=$STORAGE_BUCKET/data
    (vm)$ export TMP_DIR=YOUR-TMP-DIRECTORY

    where:

    • YOUR-BUCKET-NAME is the name of your Cloud Storage bucket.
    • DATA_DIR is a location on Cloud Storage that holds the training and evaluation data.
    • YOUR-TMP_DIRECTORY is a location to use to store temporary data. If you added a disk to your Compute Engine VM, this will be a location on the added disk (for example, /mnt/disks/mnt-dir/t2t_tmp. Otherwise, it will be a temporary directory on your VM (for example, /tmp/t2t_tmp).
  2. If you added a new disk to your Compute Engine VM, create a temporary directory on the added disk.

    (vm)$ mkdir /mnt/disks/mnt-dir/t2t_tmp
  3. Add the path to tensor2tensor scripts used to process the model data:

    (vm)$ export PATH=.local/bin:$PATH
  4. Use the t2t-datagen script to generate the training and evaluation data on the Cloud Storage bucket, so that the Cloud TPU can access the data:

    (vm)$ t2t-datagen --problem=translate_ende_wmt32k_packed --data_dir=$DATA_DIR --tmp_dir=$TMP_DIR

Downloading, preprocessing, and uploading to Cloud Storage takes approximately 2 hours. You can view the data on Cloud Storage:

  1. Navigate to the Google Cloud Platform Console.
  2. Select Storage from the left-hand menu.
  3. Click the name of the bucket you created for this tutorial.

You should see sharded files named translate_ende_wmt32k_packed-train and translate_ende_wmt32k_packed-dev.

Train a language model on a single Cloud TPU or a Cloud TPU Pod

You can use the transformer model for language modeling. To generate the training data and specify the output file, run the following commands:

(vm)$ export OUT_DIR=$STORAGE_BUCKET/training/transformer_lang_model
(vm)$ t2t-datagen --problem=languagemodel_lm1b32k_packed --data_dir=$DATA_DIR --tmp_dir=$TMP_DIR

This download, preprocessing, and upload to Cloud Storage takes approximately two hours.

To train and evaluate the model on a single Cloud TPU device or pod, run the following command:

TPU Device

  1. (vm)$ t2t-trainer \
      --model=transformer \
      --hparams_set=transformer_tpu \
      --problem=languagemodel_lm1b32k_packed \
      --train_steps=10 \
      --eval_steps=3 \
      --data_dir=$DATA_DIR \
      --output_dir=$OUT_DIR \
      --use_tpu=True \
      --cloud_tpu_name=$TPU_NAME
  • --cloud_tpu_name specifies the name of the Cloud TPU. Note that ctpu passes this name to the Compute Engine VM as an environment variable (TPU_NAME).
  • --data_dir specifies the Cloud Storage path for training input. It is set to a data directory in a Cloud Storage bucket.
  • --output_dir specifies the directory where checkpoints and summaries are stored during model training. If the folder is missing, the program creates one.

The above command runs 10 training steps, then 3 evaluation steps. It runs in approximately 5 minutes on a v3-8 TPU node. To make this model more accurate, you need to increase the number of training steps by adjusting the --train_steps flag. It is recommended that you train the model using at least 40k steps. The model typically converges to its maximum quality after ~250k steps.

TPU Pod

  1. (vm)$ t2t-trainer \
        --problem=languagemodel_lm1b32k_packed \
        --use_tpu \
        --model=transformer \
        --hparams_set=transformer_tpu \
        --cloud_tpu_name=$TPU_NAME \
        --data_dir=$DATA_DIR \
        --output_dir=$OUT_DIR \
        --tpu_num_shards=32  \
        --schedule=train \
        --train_steps=25000 \
        --eval_steps=3
    
    • --cloud_tpu_name specifies the name of the Cloud TPU. Note that ctpu passes this name to the Compute Engine VM as an environment variable (TPU_NAME).
    • --data_dir specifies the Cloud Storage path for training input.
    • --output_dir specifies the directory where checkpoints and summaries are stored during model training. If the folder is missing, the program creates one.

The above command runs 25,000 training steps, and then runs three evaluation steps. It takes approximately 30 minutes to complete this training on a Cloud TPU v2-32. It is recommended that you train the model using at least 40k steps. The model typically converges to its maximum quality after ~250k steps.

Train an English-German translation model on a single Cloud TPU

Run the following commands on your Compute Engine VM:

  1. Set up an environment variable for the training directory, which must be a Cloud Storage location:

    (vm)$ OUT_DIR=$STORAGE_BUCKET/training/transformer_ende_1
  2. Run t2t-trainer to train and evaluate the model:

    (vm)$ t2t-trainer \
      --model=transformer \
      --hparams_set=transformer_tpu \
      --problem=translate_ende_wmt32k_packed \
      --train_steps=10 \
      --eval_steps=3 \
      --data_dir=$DATA_DIR \
      --output_dir=$OUT_DIR \
      --use_tpu=True \
      --cloud_tpu_name=$TPU_NAME

    The above command runs 10 training steps, then 3 evaluation steps. It runs in approximately 5 minutes on a v3-8 TPU node. You can (and should) increase the number of training steps by adjusting the --train_steps flag. Translations usually begin to be reasonable after ~40k steps. The model typically converges to its maximum quality after ~250k steps.

  3. View the output in your Cloud Storage bucket by going to the Google Cloud Platform Console and choosing Storage from the left-hand menu. Click the name of the bucket that you created for this tutorial. Within the bucket, navigate to the training directory, for example, /training/transformer_ende_1, to see the model output.

  4. To see training and evaluation metrics, launch TensorBoard and point it at the training directory in Cloud Storage.

Train a sentiment classifier on a single Cloud TPU

You can use the transformer_encoder model for sentiment classification. Run the following commands to generate the training data and specify the output file:

(vm)$ t2t-datagen --problem=sentiment_imdb --data_dir=$DATA_DIR --tmp_dir=$TMP_DIR
(vm)$ OUT_DIR=$STORAGE_BUCKET/training/transformer_sentiment_classifier

Run the following command to train and evaluate the model:

(vm)$ t2t-trainer \
  --model=transformer_encoder \
  --hparams_set=transformer_tiny_tpu \
  --problem=sentiment_imdb \
  --train_steps=10 \
  --eval_steps=1 \
  --data_dir=$DATA_DIR \
  --output_dir=$OUT_DIR \
  --use_tpu=True \
  --cloud_tpu_name=$TPU_NAME

The above command runs 10 training steps, then 3 evaluation steps. It runs in approximately 5 minutes on a v3-8 TPU node. This model achieves approximately 85% accuracy after approximately 2,000 steps.

Clean up

To avoid incurring charges to your GCP account for the resources used in this topic:

  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, run ctpu delete with the --zone flag you used when you set up the Cloud TPU to delete your Compute Engine VM and your Cloud TPU:

    $ ctpu delete [optional: --zone]
    
  3. Run ctpu status to make sure you have no instances allocated to avoid unnecessary charges for TPU usage. The deletion might take several minutes. A response like the one below indicates there are no more allocated instances:

    2018/04/28 16:16:23 WARNING: Setting zone to "us-central1-b"
    No instances currently exist.
            Compute Engine VM:     --
            Cloud TPU:             --
    
  4. Run gsutil as shown, replacing YOUR-BUCKET-NAME with the name of the Cloud Storage bucket you created for this tutorial:

    $ gsutil rm -r gs://YOUR-BUCKET-NAME
    

What's next

Was this page helpful? Let us know how we did:

Send feedback about...

Need help? Visit our support page.