Training DLRM and DCN on Cloud TPU (TF 2.x)

This tutorial shows how to train DLRM and DCN v2 ranking models which can be used for tasks such as click-through rate (CTR) prediction. See the note in Set up to run the DLRM or DCN model to see how to set parameters to train either a DLRM or a DCN v2 ranking model.

The model inputs are numerical and categorical features, and output is a scalar (for example click probability). The model can be trained and evaluated on Cloud TPU. The deep ranking models are both memory intensive (for embedding tables/lookup) and compute intensive for deep networks (MLPs). TPUs are designed for both.

The model uses a TPUEmbedding layer for categorical features. TPU embedding supports large embedding tables with fast lookup, the size of embedding tables scales linearly with the size of a TPU pod. Up to 90 GB embedding tables can be used for TPU v3-8, 5.6 TB for a v3-512 Pod, and 22.4 TB for a v3-2048 TPU Pod.

The model code is in TensorFlow Recommenders library, while input pipeline, configuration and training loop is described in the TensorFlow Model Garden.

Objectives

  • Set up the training environment
  • Run the training job using synthetic data
  • Verify the output results

Costs

This tutorial uses billable components of Google Cloud, including:

  • Compute Engine
  • Cloud TPU
  • Cloud Storage

Use the pricing calculator to generate a cost estimate based on your projected usage. 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 Cloud project. Learn how to confirm that billing is enabled for your project.

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

Set up your resources

This section provides information on setting up Cloud Storage bucket, VM, and Cloud TPU resources used by this tutorial.

  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 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 where the -l option specifies the region where the bucket should be created. See the types and zones for more details on zones and regions:

    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 compute tpus execution-groups tool 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.

    The bucket location must be in the same region as your Compute Engine (VM) and your Cloud TPU node.

  6. Launch a Compute Engine VM and Cloud TPU using the gcloud command.

    $ gcloud compute tpus execution-groups create \
     --vm-only \
     --name=dlrm-dcn-tutorial \
     --zone=zone \
     --disk-size=300 \
     --machine-type=n1-standard-8 \
     --tf-version=2.6.0
    

    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 ctpu installs on the VM.

    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.

    If you are not connected to the Compute Engine instance, you can connect by running the following command:

    gcloud compute ssh dlrm-dcn-tutorial --zone=zone
    

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

Set Cloud Storage bucket variables

Set up the following environment variables, replacing bucket-name with the name of your Cloud Storage bucket:

(vm)$ export STORAGE_BUCKET=gs://bucket-name
(vm)$ export TPU_NAME=dlrm-dcn-tutorial
(vm)$ export PYTHONPATH="$PYTHONPATH:/usr/share/models/"
(vm)$ export EXPERIMENT_NAME=dlrm-exp

The training application expects your training data to be accessible in Cloud Storage. The training application also uses your Cloud Storage bucket to store checkpoints during training.

Set up to run the DLRM or DCN model with synthetic data

The model can be trained on various datasets. Two commonly used ones are Criteo Terabyte and Criteo Kaggle. This tutorial trains on synthetic data by setting the flag use_synthetic_data=True.

The synthetic dataset is only useful for understanding how to use a Cloud TPU and validating end-to-end performance. The accuracy numbers and saved model will not be meaningful.

Visit the Criteo Terabyte and Criteo Kaggle websites for information on how to download and preprocess these datasets.

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

    (vm)$ gcloud compute tpus execution-groups create \
     --tpu-only \
     --accelerator-type=v3-8  \
     --name=dlrm-dcn-tutorial \
     --zone=zone \
     --tf-version=2.6.0
    

    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 gcloud installs on the VM.
  2. Install a required package.

    (vm)$ pip install tensorflow-recommenders
    
  3. Run the training script. This uses a fake, Criteo-like dataset to train the DLRM model. The training takes approximately 20 minutes.

python3 /usr/share/models/official/recommendation/ranking/train.py --mode=train_and_eval \
--model_dir=${STORAGE_BUCKET}/model_dirs/${EXPERIMENT_NAME} --params_override="
runtime:
    distribution_strategy: 'tpu'
task:
    use_synthetic_data: true
    train_data:
        input_path: '${DATA_DIR}/train/*'
        global_batch_size: 16384
    validation_data:
        input_path: '${DATA_DIR}/eval/*'
        global_batch_size: 16384
    model:
        num_dense_features: 13
        bottom_mlp: [512,256,64]
        embedding_dim: 64
        top_mlp: [1024,1024,512,256,1]
        interaction: 'dot'
        vocab_sizes: [39884406, 39043, 17289, 7420, 20263, 3, 7120, 1543, 63,
            38532951, 2953546, 403346, 10, 2208, 11938, 155, 4, 976, 14,
            39979771, 25641295, 39664984, 585935, 12972, 108, 36]
trainer:
    use_orbit: false
    validation_interval: 1000
    checkpoint_interval: 1000
    validation_steps: 500
    train_steps: 1000
    steps_per_loop: 1000
"

Command flag descriptions

use_orbit
Whether to use the orbit library for training, or keras compile/fit APIs.
train_steps
The number of steps used to train the model.
validation_steps
The number of steps used to run evaluate.
validation_interval
The number of training steps to run between evaluations, must be <= train_steps.
steps_per_loop
The number of steps per graph-mode loop. This reduces communication in the eager context.

This training runs for approximately 10 minutes on a v3-8 TPU. When it completes, you will see messages similar to the following:

I0621 21:32:58.519792 139675269142336 tpu_embedding_v2_utils.py:907] Done with log of TPUEmbeddingConfiguration.
I0621 21:32:58.540874 139675269142336 tpu_embedding_v2.py:389] Done initializing TPU Embedding engine.
1000/1000 [==============================] - 335s 335ms/step - auc: 0.7360 - accuracy: 0.6709 - prediction_mean: 0.4984 
- label_mean: 0.4976 - loss: 0.0734 - regularization_loss: 0.0000e+00 - total_loss: 0.0734 - val_auc: 0.7403 
- val_accuracy: 0.6745 - val_prediction_mean: 0.5065 - val_label_mean: 0.4976 - val_loss: 0.0749 
- val_regularization_loss: 0.0000e+00 - val_total_loss: 0.0749

Model: "ranking"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
tpu_embedding (TPUEmbedding) multiple                  1         
_________________________________________________________________
mlp (MLP)                    multiple                  154944    
_________________________________________________________________
mlp_1 (MLP)                  multiple                  2131969   
_________________________________________________________________
dot_interaction (DotInteract multiple                  0         
_________________________________________________________________
ranking_1 (Ranking)          multiple                  0         
=================================================================
Total params: 2,286,914
Trainable params: 2,286,914
Non-trainable params: 0
_________________________________________________________________
I0621 21:43:54.977140 139675269142336 train.py:177] Train history: {'auc': [0.7359596490859985], 
'accuracy': [0.67094486951828], 'prediction_mean': [0.4983849823474884], 'label_mean': [0.4975697994232178], 
'loss': [0.07338511198759079], 'regularization_loss': [0], 'total_loss': [0.07338511198759079],
'val_auc': [0.7402724623680115], 'val_accuracy': [0.6744520664215088], 'val_prediction_mean': [0.5064718723297119],
'val_label_mean': [0.4975748658180237], 'val_loss': [0.07486172765493393], 
'val_regularization_loss': [0], 'val_total_loss': [0.07486172765493393]}

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, use the following command to delete your Compute Engine VM and Cloud TPU:

    $ gcloud compute tpus execution-groups delete dlrm-dcn-tutorial \
      --zone=zone
    
  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=zone
    

    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

In this tutorial you have trained the DLRM-DCN 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. Models trained on Cloud TPUs 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.