If you are not familiar with Cloud TPU, it is strongly recommended that you go through the quickstart to learn how to create a TPU and a Compute Engine VM.
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-outputted 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
This tutorial uses 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.
Before you begin
Before starting this tutorial, check that your Google Cloud project is correctly set up.
- 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.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.
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.
Cloud TPU single device training
This section provides information on setting up Cloud Storage bucket, VM, and Cloud TPU resources for single device training.
Open a Cloud Shell window.
Create a variable for your project's ID.
export PROJECT_ID=project-id
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. ClickAuthorize
at the bottom of the page to allowgcloud
to make Google Cloud API calls with your credentials.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
Create a Cloud Storage bucket using the following command:
$ gsutil mb -p ${PROJECT_ID} -c standard -l europe-west4 gs://bucket-name
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.
Prepare the dataset
To reduce your overall costs, we recommend you use a Compute Engine VM to perform any long running downloading or preprocessing of your data.
Open a Cloud Shell window.
Create a Compute Engine VM to download and preprocess your data.
gcloud compute tpus execution-groups create --name=transformer-tutorial \ --disk-size=300 \ --machine-type=n1-standard-8 \ --zone=europe-west4-a \ --tf-version=2.11.0 \ --vm-only
If you are not automatically connected to the Compute Engine instance, log in by running the following
ssh
command. When you are logged into the VM, your shell prompt changes fromusername@projectname
tousername@vm-name
: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.Export TPU setup variables
Export your project id, the name you want to use for your TPU resources, and the zone where you will train the model and store any training-related data.
$ export TPU_NAME=transformer-tutorial $ export ZONE=europe-west4-a
Export Cloud Storage bucket variables. Replace bucket-name with your bucket name:
(vm)$ export STORAGE_BUCKET=gs://bucket-name (vm)$ export GCS_DATA_DIR=${STORAGE_BUCKET}/data/transformer (vm)$ export DATA_DIR=${HOME}/transformer/data
Install the TensorFlow requirements and set the
PYTHONPATH
environment variable.(vm)$ pip3 install -r /usr/share/models/official/requirements.txt (vm)$ export PYTHONPATH="${PYTHONPATH}:/usr/share/models"
Change to directory that stores the model:
(vm)$ cd /usr/share/models/official/legacy/transformer
Download and preprocess the datasets
(vm)$ python3 data_download.py --data_dir=${DATA_DIR} (vm)$ gsutil cp -r ${DATA_DIR} ${GCS_DATA_DIR}
data_download.py
downloads and preprocesses the training and evaluation WMT datasets. After the data is downloaded and extracted, the training data is used to generate a vocabulary of sub tokens. The evaluation and training strings are tokenized, and the resulting data is sharded, shuffled, and saved as TFRecords.1.75GB of compressed data is downloaded. In total, the raw files (compressed, extracted, and combined files) take up 8.4GB of disk space. The resulting TFRecord and vocabulary files are 722MB. The script saves 460,000 cases and takes approximately 40 minutes to run.
Clean up the VM resources
Once the dataset has been converted to TFRecords and copied to the DATA_DIR on your Cloud Storage bucket, you can delete the Compute Engine instance.
Disconnect from the Compute Engine instance:
(vm)$ exit
Your prompt should now be
username@projectname
, showing you are back in the Cloud Shell.Delete your Compute Engine instance.
$ gcloud compute instances delete transformer-tutorial \ --zone=europe-west4-a
Train an English-German translation model on a single Cloud TPU
Launch a Compute Engine VM and Cloud TPU using the
gcloud
command. The command you use depends on whether you are using TPU VMs or TPU nodes. For more information on the two VM architecture, see System Architecture.TPU VM
$ gcloud compute tpus tpu-vm create transformer-tutorial \ --zone=europe-west4-a \ --accelerator-type=v3-8 \ --version=tpu-vm-tf-2.11.0
TPU Node
$ gcloud compute tpus execution-groups create \ --name=transformer-tutorial \ --disk-size=300 \ --machine-type=n1-standard-8 \ --zone=europe-west4-a \ --tf-version=2.11.0
Command flag descriptions
disk-size
- The size of the disk for the VM in GB.
machine_type
- The machine type
of the VM the
gcloud
command creates. tf-version
- The version of Tensorflow
gcloud compute tpus execution-groups
installs on the VM.
If you are not automatically logged in to the Compute Engine instance, log in by running the following
ssh
command.TPU VM
gcloud compute tpus tpu-vm ssh transformer-tutorial --zone=europe-west4-a
TPU Node
gcloud compute ssh transformer-tutorial --zone=europe-west4-a
Export data storage variables.
(vm)$ export STORAGE_BUCKET=gs://bucket-name (vm)$ export GCS_DATA_DIR=${STORAGE_BUCKET}/data/transformer (vm)$ export DATA_DIR=${HOME}/transformer/data (vm)$ export PARAM_SET=big (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/transformer/model_${PARAM_SET}
Install Tensorflow requirements.
TPU VM
(vm)$ pip3 install -r /usr/share/tpu/models/official/requirements.txt (vm)$ export PYTHONPATH="/usr/share/tpu/models:$PYTHONPATH"
TPU Node
(vm)$ pip3 install --user -r /usr/share/models/official/requirements.txt (vm)$ export PYTHONPATH="/usr/share/models:$PYTHONPATH"
Export a Cloud TPU variable.
TPU VM
(vm)$ export TPU_NAME=local
TPU Node
(vm)$ export TPU_NAME=transformer-tutorial
Change to the training directory.
TPU VM
(vm)$ cd /usr/share/tpu/models/official/legacy/transformer
TPU Node
(vm)$ cd /usr/share/models/official/legacy/transformer
Run the training script:
(vm)$ python3 transformer_main.py \ --tpu=${TPU_NAME} \ --model_dir=${MODEL_DIR} \ --data_dir=${GCS_DATA_DIR} \ --vocab_file=${GCS_DATA_DIR}/vocab.ende.32768 \ --bleu_source=${GCS_DATA_DIR}/newstest2014.en \ --bleu_ref=${GCS_DATA_DIR}/newstest2014.de \ --batch_size=6144 \ --train_steps=2000 \ --static_batch=true \ --use_ctl=true \ --param_set=big \ --max_length=64 \ --decode_batch_size=32 \ --decode_max_length=97 \ --padded_decode=true \ --distribution_strategy=tpu
Command flag descriptions
tpu
- The name of the Cloud TPU. This is set by specifying
the environment variable (
TPU_NAME
). 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.
data_dir
- The Cloud Storage path of training input. It is set to the fake_imagenet dataset in this example.
vocab_file
- A file that contains the vocabulary for translation.
bleu_source
- A file that contains source sentences for translation.
bleu_ref
- A file that contains the reference for the translation sentences.
train_steps
- The number of steps to train the model. One step processes one batch of data. This includes both a forward pass and back propagation.
batch_size
- The training batch size.
static_batch
- Specifies whether the batches in the dataset has static shapes.
use_ctl
- Specifies whether the script runs with a custom training loop.
param_set
- The parameter set to use when creating and training the model. The parameters define the input shape, model configuration, and other settings.
max_length
- The maximum length of an example in the dataset.
decode_batch_size
- The global batch size used for Transformer auto-regressive decoding on a Cloud TPU.
decode_max_length
- The maximum sequence length of the decode/eval data. This is used by the Transformer auto-regressive decoding on a Cloud TPU to minimize the amount of required data padding.
padded_decode
- Specifies whether the auto-regressive decoding runs with input data padded to the decode_max_length. Tor TPU/XLA-GPU runs, this flag must be set due to the static shape requirement.
distribution_strategy
- To train the ResNet model on a Cloud TPU, set
distribution_strategy
totpu
.
By default, the model will evaluate after every 2000 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:--train_steps
: Sets the total number of training steps to run.--steps_between_evals
: Number of training steps to run between evaluations.
Training and evaluation takes approximately 7 minutes on a v3-8 Cloud TPU. When the training and evaluation complete, a message similar to the following appears:
INFO:tensorflow:Writing to file /tmp/tmpej76vasn I0218 20:07:26.020797 140707963950912 translate.py:184] Writing to file /tmp/tmpej76vasn I0218 20:07:35.099256 140707963950912 transformer_main.py:118] Bleu score (uncased): 0.99971704185009 I0218 20:07:35.099616 140707963950912 transformer_main.py:119] Bleu score (cased): 0.9768599644303322
You have now completed single-device training. Use the following steps to delete your single-device TPU resources.
Disconnect from the Compute Engine instance:
(vm)$ exit
Your prompt should now be
username@projectname
, showing you are in the Cloud Shell.Delete the TPU resource.
TPU VM
$ gcloud compute tpus tpu-vm delete transformer-tutorial \ --zone=europe-west4-a
Command flag descriptions
zone
- The zone where your Cloud TPU resided.
TPU Node
$ gcloud compute tpus execution-groups delete transformer-tutorial \ --zone=europe-west4-a
Command flag descriptions
tpu-only
- Deletes only the Cloud TPU. The VM remains available.
zone
- The zone that contains the TPU to delete.
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.
The following instructions assume you have already opened a Cloud Shell, set up your TPU project, and created a Cloud Storage bucket as explained in the beginning of this tutorial.
TPU Pod training
Open a Cloud Shell window.
Create a variable for your project's ID.
export PROJECT_ID=project-id
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. ClickAuthorize
at the bottom of the page to allowgcloud
to make API calls with your credentials.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
Create a Cloud Storage bucket using the following command or use a bucket you created earlier for your project:
gsutil mb -p ${PROJECT_ID} -c standard -l us-central1 gs://bucket-name
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. If you want finer-grain permissions, review the access level permissions.
Launch the TPU VM resources
Launch a TPU VM Pod using the
gcloud
command. This tutorial specifies a v3-32 Pod. For other Pod options, see the available TPU types page.TPU VM
$ gcloud compute tpus tpu-vm create transformer-tutorial \ --zone=europe-west4-a \ --accelerator-type=v3-32 \ --version=tpu-vm-tf-2.11.0-pod
TPU Node
(vm)$ gcloud compute tpus execution-groups create \ --name=transformer-tutorial \ --accelerator-type=v3-32 \ --zone=europe-west4-a \ --tf-version=2.11.0
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. accelerator-type
- The type of the Cloud TPU to create.
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
gcloud
installs on the VM. name
- The name of the Cloud TPU to create.
If you are not automatically logged in to the Compute Engine instance, log in by running the following
ssh
command. When you are logged into the VM, your shell prompt changes fromusername@projectname
tousername@vm-name
:TPU VM
gcloud compute tpus tpu-vm ssh transformer-tutorial --zone=europe-west4-a
TPU Node
gcloud compute ssh transformer-tutorial --zone=europe-west4-a
Install Tensorflow and dependencies
Install TensorFlow requirements.
(vm)$ pip3 install -r /usr/share/tpu/models/official/requirements.txt (vm)$ export PYTHONPATH="/usr/share/tpu/models:$PYTHONPATH"
Export the PYTHONPATH variable.
TPU VM
(vm)$ PYTHONPATH="/usr/share/tpu/models:$PYTHONPATH"
TPU Node
(vm)$ export PYTHONPATH="/usr/share/models:$PYTHONPATH"
Set up and start the Pod training
Export Cloud TPU setup variables:
(vm)$ export STORAGE_BUCKET=gs://bucket-name (vm)$ export GCS_DATA_DIR=${STORAGE_BUCKET}/data/transformer (vm)$ export DATA_DIR=${HOME}/transformer/data (vm)$ export PARAM_SET=big (vm)$ export TPU_LOAD_LIBRARY=0 (vm)$ export RESNET_PRETRAIN_DIR=gs://cloud-tpu-checkpoints/retinanet/resnet50-checkpoint-2018-02-07 (vm)$ export TRAIN_FILE_PATTERN=${DATA_DIR}/train-* (vm)$ export EVAL_FILE_PATTERN=${DATA_DIR}/val-* (vm)$ export VAL_JSON_FILE=${DATA_DIR}/instances_val2017.json (vm)$ export MODEL_DIR=${STORAGE_BUCKET}/transformer/model_${PARAM_SET}_pod (vm)$ export TPU_NAME=transformer-tutorial
Change to the training directory:
TPU VM
(vm)$ cd /usr/share/tpu/models/official/legacy/transformer
TPU Node
(vm)$ cd /usr/share/models/official/legacy/transformer
Run the training script:
(vm)$ python3 transformer_main.py \ --tpu=${TPU_NAME} \ --model_dir=${MODEL_DIR} \ --data_dir=${GCS_DATA_DIR} \ --vocab_file=${GCS_DATA_DIR}/vocab.ende.32768 \ --bleu_source=${GCS_DATA_DIR}/newstest2014.en \ --bleu_ref=${GCS_DATA_DIR}/newstest2014.de \ --batch_size=6144 \ --train_steps=2000 \ --static_batch=true \ --use_ctl=true \ --param_set=big \ --max_length=64 \ --decode_batch_size=32 \ --decode_max_length=97 \ --padded_decode=true \ --distribution_strategy=tpu
Command flag descriptions
tpu
- The name of the Cloud TPU. This is set by specifying
the environment variable (
TPU_NAME
).
<dt><code>model_dir</code></dt> <dd>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.</dd> <dt><code>data_dir</code></dt> <dd>The Cloud Storage path of training input. It is set to the fake_imagenet dataset in this example.</dd> <dt><code>vocab_file</code></dt> <dd>A file that contains the vocabulary for translation.</dd> <dt><code>bleu_source</code></dt> <dd>A file that contains source sentences for translation.</dd> <dt><code>bleu_ref</code></dt> <dd>A file that contains the reference for the translation sentences.</dd> <dt><code>train_steps</code></dt> <dd>The number of steps to train the model. One step processes one batch of data. This includes both a forward pass and back propagation.</dd> <dt><code>batch_size</code></dt> <dd>The training batch size.</dd> <dt><code>static_batch</code></dt> <dd>Specifies whether the batches in the dataset has static shapes.</dd> <dt><code>use_ctl</code></dt> <dd>Specifies whether the script runs with a custom training loop.</dd> <dt><code>param_set</code></dt> <dd>The parameter set to use when creating and training the model. The parameters define the input shape, model configuration, and other settings.</dd> <dt><code>max_length</code></dt> <dd>The maximum length of an example in the dataset.</dd> <dt><code>decode_batch_size</code></dt> <dd>The global batch size used for Transformer auto-regressive decoding on a Cloud TPU.</dd> <dt><code>decode_max_length</code></dt> <dd>The maximum sequence length of the decode/eval data. This is used by the Transformer auto-regressive decoding on a Cloud TPU to minimize the amount of required data padding.</dd> <dt><code>padded_decode</code></dt> <dd>Specifies whether the auto-regressive decoding runs with input data padded to the decode_max_length. Tor TPU/XLA-GPU runs, this flag must be set due to the static shape requirement.</dd> <dt><code>distribution_strategy</code></dt> <dd>To train the ResNet model on a Cloud TPU, set <code>distribution_strategy</code> to <code>tpu</code>.</dd> </dl>
By default, the model will evaluate after every 2000 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:
--train_steps
: Sets the total number of training steps to run.--steps_between_evals
: Number of training steps to run between evaluations.
Training and evaluation takes approximately 7 minutes on a v3-32 Cloud TPU. When the training and evaluation complete, messages similar to the following appear:
I0415 00:28:33.108577 140097002981184 transformer_main.py:311] Train Step: 2000/2000 / loss = 5.139615058898926 I0415 00:28:33.108953 140097002981184 keras_utils.py:148] TimeHistory: 120.39 seconds, 102065.86 examples/second between steps 0 and 2000 . . . I0415 00:32:01.785520 140097002981184 transformer_main.py:116] Bleu score (uncased): 0.8316259831190109 I0415 00:32:01.786150 140097002981184 transformer_main.py:117] Bleu score (cased): 0.7945530116558075
This training script trains for 2000 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.
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.Delete your Cloud TPU and Compute Engine resources. The command you use to delete your resources depends upon whether you are using TPU VMs or TPU Nodes. For more information, see System Architecture.
TPU VM
$ gcloud compute tpus tpu-vm delete transformer-tutorial \ --zone=europe-west4-a
TPU Node
$ gcloud compute tpus execution-groups delete transformer-tutorial \ --zone=europe-west4-a
Run
gsutil
as shown, replacing bucket-name with the name of the Cloud Storage bucket you created for this tutorial:$ 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 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.