Running the Transformer with Tensor2Tensor on Cloud TPU

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.

Objectives

  • Generate the training dataset
  • Train a language model on a single Cloud TPU or a Cloud TPU Pod
  • Train an English-German translation model on a single Cloud TPU
  • Train a sentiment classifier on a single Cloud TPU
  • Clean up Cloud TPU resources

Costs

This tutorial uses 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

If you plan to train on a TPU Pod slice, please make sure you read Training on TPU Pods that explains the special considerations when training on a Pod slice.

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

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 the 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 europe-west4 -b on gs://bucket-name
    

    This Cloud Storage bucket stores the data you use to train your model and the training results. The gcloud compute tpus execution-groups 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.

  6. Launch a Compute Engine VM using the gcloud command.

    $ gcloud compute tpus execution-groups create \
     --vm-only \
     --name=transformer-tutorial \
     --zone=europe-west4-a \
     --disk-size=300 \
     --machine-type=n1-standard-8 \
     --tf-version=1.15.5
    

    Command flag descriptions

    vm-only
    Create a VM only. By default the gcloud compute tpus execution-groups command creates a VM and a Cloud TPU.
    name
    The name of the Cloud TPU to create.
    zone
    The zone where you plan to create your Cloud TPU.
    disk-size
    The size of the hard disk in GB of the VM created by the gcloud compute tpus execution-groups command.
    machine-type
    The machine type of the Compute Engine VM to create.
    tf-version
    The version of Tensorflow gcloud compute tpus execution-groups installs on the VM.

    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 compute tpus execution-groups command has finished executing, verify that your shell prompt has changed from username@projectname to username@vm-name. This change shows that you are now logged into your Compute Engine VM.

    gcloud compute ssh transformer-tutorial --zone=europe-west4-a
    

    As you continue these instructions, run each command that begins with (vm)$ in your Compute Engine instance.

On your Compute Engine VM:

  1. Create the following environment variables:

    (vm)$ export STORAGE_BUCKET=gs://bucket-name
    (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/transformer
    (vm)$ export DATA_DIR=${STORAGE_BUCKET}/data
    (vm)$ export TMP_DIR=${HOME}/t2t_tmp
  2. Create a directory to store temporary files:

    (vm)$ mkdir ${TMP_DIR}
  3. Add the path to the tensor2tensor scripts used to process the model data:

    (vm)$ export PATH=.local/bin:${PATH}

Train a language model on a single Cloud TPU

  1. Generate the training dataset for the language model.

    (vm)$ t2t-datagen --problem=languagemodel_lm1b32k_packed \
     --data_dir=${DATA_DIR} \
     --tmp_dir=${TMP_DIR}

    Command flag descriptions

    problem
    The problem name.
    data_dir
    The Cloud Storage path of training input.
    tmp_dir
    The temporary storage directory.
  2. Run the following command to create your Cloud TPU resource.

    (vm)$ gcloud compute tpus execution-groups create --tpu-only \
     --zone=europe-west4-a \
     --tf-version=1.15.5 \
     --name=transformer-tutorial

    Command flag descriptions

    tpu-only
    Create a Cloud TPU only. By default the gcloud compute tpus execution-groups command creates a VM and a Cloud TPU.
    zone
    The zone where you plan to create your Cloud TPU. This should be the same zone you used for the Compute Engine VM. For example, europe-west4-a.
    tf-version
    The version of Tensorflow ctpu installs on the VM.
    name
    The name of the Cloud TPU to create.
  3. Set an environment variable for the TPU name.

    (vm)$ export TPU_NAME=transformer-tutorial
  4. Run the training script.

    (vm)$ t2t-trainer \
     --model=transformer \
     --hparams_set=transformer_tpu \
     --problem=languagemodel_lm1b32k_packed \
     --eval_steps=3 \
     --data_dir=${DATA_DIR} \
     --output_dir=${MODEL_DIR}/language_lm1b32k \
     --use_tpu=True \
     --cloud_tpu_name=${TPU_NAME} \
     --train_steps=10

    Command flag descriptions

    model
    The model to train.
    hparams_set
    The hyperparameters to use during training.
    problem
    The problem name.
    eval-steps
    The number of steps to evaluate for.
    data_dir
    The Cloud Storage path where training data are stored.
    output_dir
    Base output directory for run.
    use_tpu
    Set to `true` to use a Cloud TPU, otherwise `false`.
    cloud_tpu_name
    The name of the Cloud TPU to use for training.
    train_steps
    The number of steps to train for.

    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.

  5. Delete the Cloud TPU resource you created.

    $ gcloud compute tpus execution-groups delete transformer-tutorial \
      --zone=europe-west4-a \
      --tpu-only

Train a language model on a Cloud TPU Pod

  1. Run the gcloud command, using the accelerator-type parameter to specify the Pod slice you want to use. For example, the following command uses a v2-32 Pod slice.

    (vm)$ gcloud compute tpus execution-groups create \
     --tpu-only \
     --accelerator-type=v2-32 \
     --name=transformer-tutorial-pod \
     --zone=europe-west4-a \
     --tf-version=1.15.5

    Command flag descriptions

    tpu-only
    Creates the Cloud TPU without creating a VM. By default the gcloud compute tpus execution-groups command creates a VM and a Cloud TPU.
    accelerator-type
    The type of the Cloud TPU to create.
    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 ctpu installs on the VM.
  2. Set an environment variable for the new TPU name.

    (vm)$ export TPU_NAME=transformer-tutorial-pod
  3. Run the training script.

    (vm)$ t2t-trainer \
     --model=transformer \
     --hparams_set=transformer_tpu \
     --problem=languagemodel_lm1b32k_packed \
     --eval_steps=3 \
     --data_dir=${DATA_DIR} \
     --output_dir=${MODEL_DIR}/language_lm1b32k_pod \
     --use_tpu=True \
     --cloud_tpu_name=${TPU_NAME} \
     --tpu_num_shards=32  \
     --schedule=train \
     --train_steps=25000

    Command flag descriptions

    model
    The model to train.
    hparams_set
    The hyperparameters to use during training.
    problem
    The problem name.
    eval-steps
    The number of steps to evaluate for.
    data_dir
    The Cloud Storage path where training data are stored.
    output_dir
    Base output directory for run.
    use_tpu
    Set to `true` to use a Cloud TPU, otherwise `false`.
    cloud_tpu_name
    The name of the Cloud TPU to use for training.
    tpu_num_shards
    The number of Cloud TPU shards. The default value is '8'.
    schedule
    The method of experiment to run.
    train_steps
    The number of steps to train the model.

    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.

  4. Delete the Cloud TPU resource you created for training.

    (vm)$ gcloud compute tpus execution-groups delete transformer-tutorial \
      --zone=europe-west4-a \
      --tpu-only

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

  1. Use the t2t-datagen script to generate the training and evaluation data for the translation model on the Cloud Storage bucket:

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

    Command flag descriptions

    problem
    The problem name.
    data_dir
    The Cloud Storage path of training input.
    tmp_dir
    The temporary storage directory.
  2. Run the following command to create your Cloud TPU resource.

    (vm)$ gcloud compute tpus execution-groups create --tpu-only \
     --zone=europe-west4-a \
     --tf-version=1.15.5 \
     --name=transformer-tutorial

    Command flag descriptions

    tpu-only
    Create a Cloud TPU only. By default the gcloud compute tpus execution-groups command creates a VM and a Cloud TPU.
    zone
    The zone where you plan to create your Cloud TPU.
    tf-version
    The version of Tensorflow gcloud compute tpus execution-groups installs on the VM.
    name
    The name of the Cloud TPU to create.
  3. Set an environment variable for the new TPU name.

    (vm)$ export TPU_NAME=transformer-tutorial
  4. Run t2t-trainer to train and evaluate the model:

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

    Command flag descriptions

    model
    The model to train.
    hparams_set
    The hyperparameters to use during training.
    problem
    The problem name.
    eval-steps
    The number of steps to evaluate for.
    data_dir
    The Cloud Storage path where training data are stored.
    output_dir
    Base output directory for run.
    use_tpu
    Set to `true` to use a Cloud TPU, otherwise `false`.
    cloud_tpu_name
    The name of the Cloud TPU to use for training.
    train_steps
    The number of steps to train the model.

    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.

  5. Delete the Cloud TPU resource you created for training the model on a single device.

    (vm)$ gcloud compute tpus execution-groups delete transformer-tutorial \
     --tpu-only \
     --zone=europe-west4-a 

Train a sentiment classifier model on a single Cloud TPU

  1. Generate the dataset for the sentiment classifier model.

    (vm)$ t2t-datagen --problem=sentiment_imdb \
     --data_dir=${DATA_DIR} \
     --tmp_dir=${TMP_DIR}
  2. Run the following command to create your Cloud TPU resource.

    (vm)$ gcloud compute tpus execution-groups create --tpu-only \
     --zone=europe-west4-a \
     --tf-version=1.15.5 \
     --name=transformer-tutorial

    Command flag descriptions

    tpu-only
    Create a Cloud TPU only. By default the gcloud compute tpus execution-groups command creates a VM and a Cloud TPU.
    zone
    The zone where you plan to create your Cloud TPU.
    tf-version
    The version of Tensorflow gcloud compute tpus execution-groups installs on the VM.
    name
    The name of the Cloud TPU to create.
  3. Run the training script.

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

    Command flag descriptions

    model
    The model to train.
    hparams_set
    The hyperparameters to use during training.
    problem
    The problem name.
    eval-steps
    The number of steps to evaluate for.
    data_dir
    The Cloud Storage path where training data are stored.
    output_dir
    Base output directory for run.
    use_tpu
    Set to `true` to use a Cloud TPU, otherwise `false`.
    cloud_tpu_name
    The name of the Cloud TPU to use for training.
    train_steps
    The number of steps to train the model.

    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 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. In your Cloud Shell, run gcloud compute tpus execution-groups with the --zone flag you used when you set up the Cloud TPU to delete your Compute Engine VM and your Cloud TPU:

    $ gcloud compute tpus execution-groups delete transformer-tutorial \
    --zone=europe-west4-a
    
  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=europe-west4-a
    

    You should see an empty list of TPUs like the following:

       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

The TensorFlow Cloud TPU tutorials generally train the 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. 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, 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.