<jupyter_start><jupyter_text>Criteo Example Here we'll show how to use NVTabular first as a preprocessing library to prepare the [Criteo Display Advertising Challenge](https://www.kaggle.com/c/criteo-display-ad-challenge) dataset, and then as a dataloader to train a FastAI model on the prepared data. The large memory footprint of the Criteo dataset presents a great opportunity to highlight the advantages of the online fashion in which NVTabular loads and transforms data. Data PrepBefore we get started, make sure you've run the [`optimize_criteo` notebook](./optimize_criteo.ipynb), 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 ~4 hours 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.  Quick Aside: Clearing CacheThe following line is not strictly necessary, but is included for those who want to validate NVIDIA's benchmarks. We start by clearing the existing cache to start as "fresh" as possible. If you're having trouble running it, try executing the container with the `--privileged` flag.<jupyter_code>!sync; echo 3 > /proc/sys/vm/drop_caches
import os
from time import time
import re
import glob
import warnings

# tools for data preproc/loading
import torch
import rmm
import nvtabular as nvt
from nvtabular.ops import Normalize, FillMissing, Categorify, Moments, Median, Encoder, LogOp, ZeroFill
from nvtabular.torch_dataloader import DLDataLoader, TorchTensorBatchDatasetItr, create_tensors_plain

# tools for training
from fastai.basic_train import Learner
from fastai.basic_data import DataBunch
from fastai.tabular import TabularModel
from fastai.metrics import accuracy<jupyter_output>/opt/conda/lib/python3.6/site-packages/numba/cuda/envvars.py:17: NumbaWarning: 
Environment variables with the 'NUMBAPRO' prefix are deprecated and consequently ignored, found use of NUMBAPRO_NVVM=/usr/local/cuda/nvvm/lib64/libnvvm.so.

For more information about alternatives visit: ('http://numba.pydata.org/numba-doc/latest/cuda/overview.html', '#cudatoolkit-lookup')
  warnings.warn(errors.NumbaWarning(msg))
/opt/conda/lib/python3.6/site-packages/numba/cuda/envvars.py:17: NumbaWarning: 
Environment variables with the 'NUMBAPRO' prefix are deprecated and consequently ignored, found use of NUMBAPRO_LIBDEVICE=/usr/local/cuda/nvvm/libdevice/.

For more information about alternatives visit: ('http://numba.pydata.org/numba-doc/latest/cuda/overview.html', '#cudatoolkit-lookup')
  warnings.warn(errors.NumbaWarning(msg))<jupyter_text>Initializing the Memory PoolFor applications like the one that follows where RAPIDS will be the only workhorse user of GPU memory and resource, a good best practices is to use the RAPIDS Memory Manager library `rmm` to allocate a dedicated pool of GPU memory that allows for fast, asynchronous memory management. Here, we'll dedicate 80% of free GPU memory to this pool to make sure we get the most utilization possible.<jupyter_code>rmm.reinitialize(pool_allocator=True, initial_pool_size=0.8 * rmm.get_info().free)<jupyter_output><empty_output><jupyter_text>Dataset and Dataset SchemaOnce 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.<jupyter_code># define some information about where to get our data
INPUT_DATA_DIR = os.environ.get('INPUT_DATA_DIR', '/data')
OUTPUT_DATA_DIR = os.environ.get('OUTPUT_DATA_DIR', '/processed') # where we'll save our procesed data to
NUM_TRAIN_DAYS = 23 # number of days worth of data to use for training, the rest will be used for validation

# 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
# ! ls $INPUT_DATA_DIR
fname = 'day_{}.parquet'
num_days = len([i for i in os.listdir(INPUT_DATA_DIR) if re.match(fname.format('[0-9]{1,2}'), i) is not None])
train_paths = [os.path.join(INPUT_DATA_DIR, fname.format(day)) for day in range(NUM_TRAIN_DAYS)]
valid_paths = [os.path.join(INPUT_DATA_DIR, fname.format(day)) for day in range(NUM_TRAIN_DAYS, num_days)]<jupyter_output><empty_output><jupyter_text>PreprocessingAt 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 ThresholdingOne 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.<jupyter_code>proc = nvt.Workflow(
    cat_names=CATEGORICAL_COLUMNS,
    cont_names=CONTINUOUS_COLUMNS,
    label_name=LABEL_COLUMNS,
    to_cpu=False)

# log -> normalize continuous features. Note that doing this in the opposite
# order wouldn't make sense! Note also that we're zero filling continuous
# values before the log: this is a good time to remember that LogOp
# performs log(1+x), not log(x)
proc.add_cont_feature([ZeroFill(), LogOp()])
proc.add_cont_preprocess(Normalize())

# categorification with frequency thresholding
proc.add_cat_preprocess(Categorify(use_frequency=True, freq_threshold=15))<jupyter_output><empty_output><jupyter_text>Now instantiate dataset iterators to loop through our dataset (which we couldn't fit into GPU memory)<jupyter_code>train_ds_iterator = nvt.dataset(train_paths, engine='parquet', gpu_memory_frac=0.3)
valid_ds_iterator = nvt.dataset(valid_paths, engine='parquet', gpu_memory_frac=0.3)<jupyter_output><empty_output><jupyter_text>Now run them through our workflows to collect statistics on the train set, then transform and save to parquet files.<jupyter_code>output_train_dir = os.path.join(OUTPUT_DATA_DIR, 'train/')
output_valid_dir = os.path.join(OUTPUT_DATA_DIR, 'valid/')
! mkdir -p $output_train_dir
! mkdir -p $output_valid_dir<jupyter_output><empty_output><jupyter_text>For reference, let's time it to see how long it takes...<jupyter_code>%%time
proc.apply(train_ds_iterator, apply_offline=True, record_stats=True, shuffle=True, output_path=output_train_dir, num_out_files=35)
%%time
proc.apply(valid_ds_iterator, apply_offline=True, record_stats=False, shuffle=True, output_path=output_valid_dir, num_out_files=35)<jupyter_output>CPU times: user 33.1 s, sys: 21.7 s, total: 54.8 s
Wall time: 34.9 s<jupyter_text>And just like that, we have training and validation sets ready to feed to a model!  Deep Learning Data LoadingWe'll start by using the parquet files we just created to feed an NVTabular `FileItrDataset`, which will looop through the files in chunks. First, we'll reinitialize our memory pool from earlier to free up some memory so that we can share it with PyTorch.<jupyter_code>rmm.reinitialize(pool_allocator=False)
train_paths = glob.glob(os.path.join(output_train_dir, "*.parquet"))
valid_paths = glob.glob(os.path.join(output_valid_dir, "*.parquet"))
train_data_itrs = TorchTensorBatchDatasetItr(train_paths, engine='parquet', gpu_memory_frac=0.1, sub_batch_size=1600000, cats=CATEGORICAL_COLUMNS, conts=CONTINUOUS_COLUMNS, labels=LABEL_COLUMNS)
valid_data_itrs = TorchTensorBatchDatasetItr(valid_paths, engine='parquet', gpu_memory_frac=0.1, sub_batch_size=1600000, cats=CATEGORICAL_COLUMNS, conts=CONTINUOUS_COLUMNS, labels=LABEL_COLUMNS)
def gen_col(batch):
    batch = create_tensors_plain(batch[0], CATEGORICAL_COLUMNS, CONTINUOUS_COLUMNS, LABEL_COLUMNS)
    return (batch[0], batch[1]), batch[2].long()
train_dataloader = DLDataLoader(train_data_itrs, collate_fn=gen_col, pin_memory=False, num_workers=0)
valid_dataloader = DLDataLoader(valid_data_itrs, collate_fn=gen_col, pin_memory=False, num_workers=0)
databunch = DataBunch(train_dataloader, valid_dataloader, collate_fn=gen_col, device="cuda")<jupyter_output><empty_output><jupyter_text>Now we have data ready to be fed to our model online!  TrainingOne extra handy functionality of NVTabular is the ability to use the stats collected by the `Categorify` op to define embedding dictionary sizes (i.e. the number of rows of your embedding table). It even includes a heuristic for computing a good embedding size (i.e. the number of columns of your embedding table) based off of the number of categories.<jupyter_code>embeddings = [x[1] for x in proc.df_ops['Categorify'].get_emb_sz(proc.stats["categories"], proc.columns_ctx['categorical']['base'])]
model = TabularModel(emb_szs=embeddings, n_cont=len(CONTINUOUS_COLUMNS), out_sz=2, layers=[512, 256])
learn =  Learner(databunch, model, metrics=[accuracy])
learn.loss_func = torch.nn.CrossEntropyLoss()
learning_rate = 1.32e-2
epochs = 1
start = time()
learn.fit_one_cycle(epochs, learning_rate)
t_final = time() - start
print(t_final)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07925867507886436, 'fraction_numerical': 0.008970820189274448, 'mean_word_length': 6.399708242159008, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 37, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '119235', 'license': 'Apache-2.0', 'n_tokens_mistral': 3175, 'n_tokens_neox': 3070, 'n_words': 1082, 'path': 'examples/criteo-example.ipynb', 'repo_name': 'rjzamora/NVTabular', 'size': '10144'}