[1]:
# Copyright 2021 NVIDIA Corporation. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

NVTabular / HugeCTR Criteo Example

Here we’ll show how to use NVTabular first as a preprocessing library to prepare the Criteo Display Advertising Challenge dataset, and then train a model using HugeCTR.

Data Prep

Before we get started, make sure you’ve run the optimize_criteo notebook, which will convert the tsv data published by Criteo into the parquet format that our accelerated readers prefer. It’s fair to mention at this point that that notebook will take ~30 minutes to run. While we’re hoping to release accelerated csv readers in the near future, we also believe that inefficiencies in existing data representations like csv are in no small part a consequence of inefficiencies in the existing hardware/software stack. Accelerating these pipelines on new hardware like GPUs may require us to make new choices about the representations we use to store that data, and parquet represents a strong alternative.

[2]:
# Standard Libraries
import os
from time import time
import re
import shutil
import glob
import warnings

# External Dependencies
import numpy as np
import cupy as cp
import cudf
import dask_cudf
from dask_cuda import LocalCUDACluster
from dask.distributed import Client
from dask.utils import parse_bytes
from dask.delayed import delayed
import rmm

# NVTabular
import nvtabular as nvt
from nvtabular.ops import Categorify, Clip, FillMissing, HashBucket, LambdaOp, LogOp, Normalize, Rename, get_embedding_sizes
from nvtabular.io import Shuffle
from nvtabular.utils import _pynvml_mem_size, device_mem_size

# HugeCTR
import hugectr
from mpi4py import MPI
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Input In [2], in <cell line: 24>()
     22 from nvtabular.ops import Categorify, Clip, FillMissing, HashBucket, LambdaOp, LogOp, Normalize, Rename, get_embedding_sizes
     23 from nvtabular.io import Shuffle
---> 24 from nvtabular.utils import _pynvml_mem_size, device_mem_size
     26 # HugeCTR
     27 import hugectr

ImportError: cannot import name '_pynvml_mem_size' from 'nvtabular.utils' (/nvtabular/nvtabular/utils.py)

Dataset and Dataset Schema

Once our data is ready, we’ll define some high level parameters to describe where our data is and what it “looks like” at a high level.

[3]:
# define some information about where to get our data
BASE_DIR = "/raid/criteo/tests/"
input_path = os.path.join(BASE_DIR, "crit_int_pq")
dask_workdir = os.path.join(BASE_DIR, "test_dask/workdir")
output_path = os.path.join(BASE_DIR, "test_dask/output")
stats_path = os.path.join(BASE_DIR, "test_dask/stats")

NUM_TRAIN_DAYS = 23 # number of days worth of data to use for training, the rest will be used for validation

# Make sure we have a clean worker space for Dask
if os.path.isdir(dask_workdir):
    shutil.rmtree(dask_workdir)
os.makedirs(dask_workdir)

# Make sure we have a clean stats space for Dask
if os.path.isdir(stats_path):
    shutil.rmtree(stats_path)
os.mkdir(stats_path)

# Make sure we have a clean output path
if os.path.isdir(output_path):
    shutil.rmtree(output_path)
os.mkdir(output_path)
---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
Input In [3], in <cell line: 13>()
     11 if os.path.isdir(dask_workdir):
     12     shutil.rmtree(dask_workdir)
---> 13 os.makedirs(dask_workdir)
     15 # Make sure we have a clean stats space for Dask
     16 if os.path.isdir(stats_path):

File /usr/lib/python3.8/os.py:213, in makedirs(name, mode, exist_ok)
    211 if head and tail and not path.exists(head):
    212     try:
--> 213         makedirs(head, exist_ok=exist_ok)
    214     except FileExistsError:
    215         # Defeats race condition when another thread created the path
    216         pass

File /usr/lib/python3.8/os.py:213, in makedirs(name, mode, exist_ok)
    211 if head and tail and not path.exists(head):
    212     try:
--> 213         makedirs(head, exist_ok=exist_ok)
    214     except FileExistsError:
    215         # Defeats race condition when another thread created the path
    216         pass

File /usr/lib/python3.8/os.py:213, in makedirs(name, mode, exist_ok)
    211 if head and tail and not path.exists(head):
    212     try:
--> 213         makedirs(head, exist_ok=exist_ok)
    214     except FileExistsError:
    215         # Defeats race condition when another thread created the path
    216         pass

File /usr/lib/python3.8/os.py:223, in makedirs(name, mode, exist_ok)
    221         return
    222 try:
--> 223     mkdir(name, mode)
    224 except OSError:
    225     # Cannot rely on checking for EEXIST, since the operating system
    226     # could give priority to other errors like EACCES or EROFS
    227     if not exist_ok or not path.isdir(name):

PermissionError: [Errno 13] Permission denied: '/raid/criteo'
[4]:
! ls $BASE_DIR
ls: cannot access '/raid/criteo/tests/': No such file or directory
[5]:
fname = 'day_{}.parquet'
num_days = len([i for i in os.listdir(input_path) if re.match(fname.format('[0-9]{1,2}'), i) is not None])
train_paths = [os.path.join(input_path, fname.format(day)) for day in range(NUM_TRAIN_DAYS)]
valid_paths = [os.path.join(input_path, fname.format(day)) for day in range(NUM_TRAIN_DAYS, num_days)]
print(train_paths)
print(valid_paths)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Input In [5], in <cell line: 2>()
      1 fname = 'day_{}.parquet'
----> 2 num_days = len([i for i in os.listdir(input_path) if re.match(fname.format('[0-9]{1,2}'), i) is not None])
      3 train_paths = [os.path.join(input_path, fname.format(day)) for day in range(NUM_TRAIN_DAYS)]
      4 valid_paths = [os.path.join(input_path, fname.format(day)) for day in range(NUM_TRAIN_DAYS, num_days)]

FileNotFoundError: [Errno 2] No such file or directory: '/raid/criteo/tests/crit_int_pq'

Deploy a Distributed-Dask Cluster

Now we configure and deploy a Dask Cluster. Please, read this document to know how to set the parameters.

[6]:
# Dask dashboard
dashboard_port = "8787"

# Deploy a Single-Machine Multi-GPU Cluster
protocol = "tcp"             # "tcp" or "ucx"
NUM_GPUS = [0,1,2,3,4,5,6,7]
visible_devices = ",".join([str(n) for n in NUM_GPUS])  # Delect devices to place workers
device_limit_frac = 0.7      # Spill GPU-Worker memory to host at this limit.
device_pool_frac = 0.8
part_mem_frac = 0.15

# Use total device size to calculate args.device_limit_frac
device_size = device_mem_size(kind="total")
device_limit = int(device_limit_frac * device_size)
device_pool_size = int(device_pool_frac * device_size)
part_size = int(part_mem_frac * device_size)

# Check if any device memory is already occupied
for dev in visible_devices.split(","):
    fmem = _pynvml_mem_size(kind="free", index=int(dev))
    used = (device_size - fmem) / 1e9
    if used > 1.0:
        warnings.warn(f"BEWARE - {used} GB is already occupied on device {int(dev)}!")

cluster = None               # (Optional) Specify existing scheduler port
if cluster is None:
    cluster = LocalCUDACluster(
        protocol = protocol,
        n_workers=len(visible_devices.split(",")),
        CUDA_VISIBLE_DEVICES = visible_devices,
        device_memory_limit = device_limit,
        local_directory=dask_workdir,
        dashboard_address=":" + dashboard_port,
    )

# Create the distributed client
client = Client(cluster)
client
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [6], in <cell line: 13>()
     10 part_mem_frac = 0.15
     12 # Use total device size to calculate args.device_limit_frac
---> 13 device_size = device_mem_size(kind="total")
     14 device_limit = int(device_limit_frac * device_size)
     15 device_pool_size = int(device_pool_frac * device_size)

NameError: name 'device_mem_size' is not defined

Initilize Memory Pools

[7]:
# Initialize RMM pool on ALL workers
def _rmm_pool():
    rmm.reinitialize(
        # RMM may require the pool size to be a multiple of 256.
        pool_allocator=True,
        initial_pool_size=(device_pool_size // 256) * 256, # Use default size
    )

client.run(_rmm_pool)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [7], in <cell line: 9>()
      2 def _rmm_pool():
      3     rmm.reinitialize(
      4         # RMM may require the pool size to be a multiple of 256.
      5         pool_allocator=True,
      6         initial_pool_size=(device_pool_size // 256) * 256, # Use default size
      7     )
----> 9 client.run(_rmm_pool)

NameError: name 'client' is not defined

Preprocessing

At this point, our data still isn’t in a form that’s ideal for consumption by neural networks. The most pressing issues are missing values and the fact that our categorical variables are still represented by random, discrete identifiers, and need to be transformed into contiguous indices that can be leveraged by a learned embedding. Less pressing, but still important for learning dynamics, are the distributions of our continuous variables, which are distributed across multiple orders of magnitude and are uncentered (i.e. E[x] != 0).

We can fix these issues in a conscise and GPU-accelerated manner with an NVTabular Workflow. We’ll instantiate one with our current dataset schema, then symbolically add operations on that schema. By setting all these Ops to use replace=True, the schema itself will remain unmodified, while the variables represented by each field in the schema will be transformed.

Frequency Thresholding

One interesting thing worth pointing out is that we’re using frequency thresholding in our Categorify op. This handy functionality will map all categories which occur in the dataset with some threshold level of infrequency (which we’ve set here to be 15 occurrences throughout the dataset) to the same index, keeping the model from overfitting to sparse signals.

[8]:
# define our dataset schema
CONTINUOUS_COLUMNS = ['I' + str(x) for x in range(1,14)]
CATEGORICAL_COLUMNS =  ['C' + str(x) for x in range(1,27)]
LABEL_COLUMNS = ['label']
COLUMNS = CONTINUOUS_COLUMNS + CATEGORICAL_COLUMNS + LABEL_COLUMNS

num_buckets=10000000
categorify_op = Categorify(out_path=stats_path, max_size=num_buckets)
cat_features = CATEGORICAL_COLUMNS >> categorify_op
cont_features = CONTINUOUS_COLUMNS >> FillMissing() >> Clip(min_value=0) >> Normalize()
features = cat_features + cont_features + LABEL_COLUMNS

workflow = nvt.Workflow(features, client=client)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [8], in <cell line: 13>()
     10 cont_features = CONTINUOUS_COLUMNS >> FillMissing() >> Clip(min_value=0) >> Normalize()
     11 features = cat_features + cont_features + LABEL_COLUMNS
---> 13 workflow = nvt.Workflow(features, client=client)

NameError: name 'client' is not defined

Now instantiate dataset iterators to loop through our dataset (which we couldn’t fit into GPU memory). We need to enforce the required HugeCTR data types, so we set them in a dictionary and give as an argument when creating our dataset

[9]:
dict_dtypes={}

for col in CATEGORICAL_COLUMNS:
    dict_dtypes[col] = np.int64

for col in CONTINUOUS_COLUMNS:
    dict_dtypes[col] = np.float32

for col in LABEL_COLUMNS:
    dict_dtypes[col] = np.float32
[10]:
train_dataset = nvt.Dataset(train_paths, engine='parquet', part_size=part_size)
valid_dataset = nvt.Dataset(valid_paths, engine='parquet', part_size=part_size)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [10], in <cell line: 1>()
----> 1 train_dataset = nvt.Dataset(train_paths, engine='parquet', part_size=part_size)
      2 valid_dataset = nvt.Dataset(valid_paths, engine='parquet', part_size=part_size)

NameError: name 'train_paths' is not defined

Now run them through our workflows to collect statistics on the train set, then transform and save to parquet files.

[11]:
output_train_dir = os.path.join(output_path, 'train/')
output_valid_dir = os.path.join(output_path, 'valid/')
! mkdir -p $output_train_dir
! mkdir -p $output_valid_dir
mkdir: cannot create directory ‘/raid/criteo’: Permission denied
mkdir: cannot create directory ‘/raid/criteo’: Permission denied

For reference, let’s time it to see how long it takes…

[12]:
%%time
workflow.fit(train_dataset)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
File <timed eval>:1, in <module>

NameError: name 'workflow' is not defined
[13]:
%%time
workflow.transform(train_dataset).to_parquet(output_path=output_train_dir,
                                         shuffle=nvt.io.Shuffle.PER_PARTITION,
                                         dtypes=dict_dtypes,
                                         cats=CATEGORICAL_COLUMNS,
                                         conts=CONTINUOUS_COLUMNS,
                                         labels=LABEL_COLUMNS)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
File <timed eval>:1, in <module>

NameError: name 'workflow' is not defined
[14]:
%%time
workflow.transform(valid_dataset).to_parquet(output_path=output_valid_dir,
                                             dtypes=dict_dtypes,
                                             cats=CATEGORICAL_COLUMNS,
                                             conts=CONTINUOUS_COLUMNS,
                                             labels=LABEL_COLUMNS)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
File <timed eval>:1, in <module>

NameError: name 'workflow' is not defined

Get the embeddings table size, to configurate HugeCTR

[15]:
embeddings = [c[0] for c in categorify_op.get_embedding_sizes(CATEGORICAL_COLUMNS).values()]
embeddings = np.clip(a=embeddings, a_min=None, a_max=num_buckets).tolist()
print(embeddings)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

And just like that, we have training and validation sets ready to feed to a model!

HugeCTR

Training

We’ll run huge_ctr using the DLRM configuration file.

First, we’ll shutdown our Dask client from earlier to free up some memory so that we can share it with HugeCTR.

[16]:
client.shutdown()
cluster.close()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [16], in <cell line: 1>()
----> 1 client.shutdown()
      2 cluster.close()

NameError: name 'client' is not defined

Finally, we run HugeCTR. Please, look at the jupyter-lab console to see the HugeCTR output. For reference, let’s time it to see how long it takes…

[17]:
%% time
solver = hugectr.solver_parser_helper(num_epochs = 0,
                                    max_iter = 10000,
                                    max_eval_batches = 100,
                                    batchsize_eval = 2720,
                                    batchsize = 2720,
                                    display = 1000,
                                    eval_interval = 3200,
                                    i64_input_key = True,
                                    use_mixed_precision = False,
                                    repeat_dataset = True)
optimizer = hugectr.optimizer.CreateOptimizer(optimizer_type = hugectr.Optimizer_t.SGD,
                                    use_mixed_precision = False)
model = hugectr.Model(solver, optimizer)
model.add(hugectr.Input(data_reader_type = hugectr.DataReaderType_t.Parquet,
                            source = "/raid/criteo/tests/test_dask/output/train/_file_list.txt",
                            eval_source = "/raid/criteo/tests/test_dask/output/valid/_file_list.txt",
                            check_type = hugectr.Check_t.Non,
                            label_dim = 1, label_name = "label",
                            dense_dim = 13, dense_name = "dense",
                            slot_size_array = [10000000, 10000000, 3014529, 400781, 11, 2209, 11869, 148, 4, 977, 15, 38713, 10000000, 10000000, 10000000, 584616, 12883, 109, 37, 17177, 7425, 20266, 4, 7085, 1535, 64],
                            data_reader_sparse_param_array =
                            [hugectr.DataReaderSparseParam(hugectr.DataReaderSparse_t.Localized, 30, 1, 26)],
                            sparse_names = ["data1"]))
model.add(hugectr.SparseEmbedding(embedding_type = hugectr.Embedding_t.LocalizedSlotSparseEmbeddingHash,
                            max_vocabulary_size_per_gpu = 15500000,
                            embedding_vec_size = 128,
                            combiner = 0,
                            sparse_embedding_name = "sparse_embedding1",
                            bottom_name = "data1"))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,
                            bottom_names = ["dense"],
                            top_names = ["fc1"],
                            num_output=512))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.ReLU,
                            bottom_names = ["fc1"],
                            top_names = ["relu1"]))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,
                            bottom_names = ["relu1"],
                            top_names = ["fc2"],
                            num_output=256))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.ReLU,
                            bottom_names = ["fc2"],
                            top_names = ["relu2"]))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,
                            bottom_names = ["relu2"],
                            top_names = ["fc3"],
                            num_output=128))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.ReLU,
                            bottom_names = ["fc3"],
                            top_names = ["relu3"]))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.Interaction,
                            bottom_names = ["relu3", "sparse_embedding1"],
                            top_names = ["interaction1"]))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,
                            bottom_names = ["interaction1"],
                            top_names = ["fc4"],
                            num_output=1024))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.ReLU,
                            bottom_names = ["fc4"],
                            top_names = ["relu4"]))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,
                            bottom_names = ["relu4"],
                            top_names = ["fc5"],
                            num_output=1024))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.ReLU,
                            bottom_names = ["fc5"],
                            top_names = ["relu5"]))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,
                            bottom_names = ["relu5"],
                            top_names = ["fc6"],
                            num_output=512))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.ReLU,
                            bottom_names = ["fc6"],
                            top_names = ["relu6"]))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,
                            bottom_names = ["relu6"],
                            top_names = ["fc7"],
                            num_output=256))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.ReLU,
                            bottom_names = ["fc7"],
                            top_names = ["relu7"]))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.InnerProduct,
                            bottom_names = ["relu7"],
                            top_names = ["fc8"],
                            num_output=1))
model.add(hugectr.DenseLayer(layer_type = hugectr.Layer_t.BinaryCrossEntropyLoss,
                            bottom_names = ["fc8", "label"],
                            top_names = ["loss"]))
model.compile()
model.summary()
model.fit()
UsageError: Cell magic `%%` not found.