# Copyright 2022 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.
# ======================================================================

# Each user is responsible for checking the content of datasets and the
# applicable licenses and determining if suitable for the intended use.
https://developer.download.nvidia.com/notebooks/dlsw-notebooks/merlin_transformers4rec_getting-started-session-based-01-etl-with-nvtabular/nvidia_logo.png

ETL with NVTabular

In this notebook we are going to generate synthetic data and then create sequential features with NVTabular. Such data will be used in the next notebook to train a session-based recommendation model.

NVTabular is a feature engineering and preprocessing library for tabular data designed to quickly and easily manipulate terabyte scale datasets used to train deep learning based recommender systems. It provides a high level abstraction to simplify code and accelerates computation on the GPU using the RAPIDS cuDF library.

Import required libraries

import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"
import glob

import cudf
import numpy as np
import pandas as pd

import nvtabular as nvt
from nvtabular.ops import *
from merlin.schema.tags import Tags
/usr/local/lib/python3.8/dist-packages/merlin/dtypes/mappings/tf.py:52: UserWarning: Tensorflow dtype mappings did not load successfully due to an error: No module named 'tensorflow'
  warn(f"Tensorflow dtype mappings did not load successfully due to an error: {exc.msg}")
/usr/local/lib/python3.8/dist-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm

Define Input/Output Path

INPUT_DATA_DIR = os.environ.get("INPUT_DATA_DIR", "/workspace/data/")

Create a Synthetic Input Data

NUM_ROWS = os.environ.get("NUM_ROWS", 100000)
long_tailed_item_distribution = np.clip(np.random.lognormal(3., 1., int(NUM_ROWS)).astype(np.int32), 1, 50000)
# generate random item interaction features 
df = pd.DataFrame(np.random.randint(70000, 90000, int(NUM_ROWS)), columns=['session_id'])
df['item_id'] = long_tailed_item_distribution

# generate category mapping for each item-id
df['category'] = pd.cut(df['item_id'], bins=334, labels=np.arange(1, 335)).astype(np.int32)
df['age_days'] = np.random.uniform(0, 1, int(NUM_ROWS)).astype(np.float32)
df['weekday_sin']= np.random.uniform(0, 1, int(NUM_ROWS)).astype(np.float32)

# generate day mapping for each session 
map_day = dict(zip(df.session_id.unique(), np.random.randint(1, 10, size=(df.session_id.nunique()))))
df['day'] =  df.session_id.map(map_day)

Visualize couple of rows of the synthetic dataset:

df.head()
session_id item_id category age_days weekday_sin day
0 77378 45 11 0.278357 0.584583 1
1 74811 2 1 0.646034 0.403526 6
2 74106 11 3 0.586394 0.040917 4
3 82547 47 12 0.989547 0.962060 5
4 72220 17 4 0.604099 0.370005 7

Feature Engineering with NVTabular

Deep Learning models require dense input features. Categorical features are sparse, and need to be represented by dense embeddings in the model. To allow for that, categorical features first need to be encoded as contiguous integers (0, ..., |C|), where |C| is the feature cardinality (number of unique values), so that their embeddings can be efficiently stored in embedding layers. We will use NVTabular to preprocess the categorical features, so that all categorical columns are encoded as contiguous integers. Note that the Categorify op encodes OOVs or nulls to 0 automatically. In our synthetic dataset we do not have any nulls. On the other hand 0 is also used for padding the sequences in input block, therefore, you can set start_index=1 arg in the Categorify op if you want the encoded null or OOV values to start from 1 instead of 0 because we reserve 0 for padding the sequence features.

Here our goal is to create sequential features. To do so, we are grouping the features together at the session level in the following cell. In this synthetically generated example dataset, we do not have a timestamp column, but if we had one (that’s the case for most real-world datasets), we would be sorting the interactions by the timestamp column as in this example notebook. Note that we also trim each feature sequence in a session to a certain length. Here, we use the NVTabular library so that we can easily preprocess and create features on GPU with a few lines.

SESSIONS_MAX_LENGTH =20

# Categorify categorical features
categ_feats = ['item_id', 'category'] >> nvt.ops.Categorify()

# Define Groupby Workflow
groupby_feats = categ_feats + ['session_id', 'day', 'age_days', 'weekday_sin']

# Group interaction features by session
groupby_features = groupby_feats >> nvt.ops.Groupby(
    groupby_cols=["session_id"], 
    aggs={
        "item_id": ["list", "count"],
        "category": ["list"],     
        "day": ["first"],
        "age_days": ["list"],
        'weekday_sin': ["list"],
        },
    name_sep="-")

# Select and truncate the sequential features
sequence_features_truncated = (
    groupby_features['category-list']
    >> nvt.ops.ListSlice(-SESSIONS_MAX_LENGTH, pad=True) 
)

sequence_features_truncated_item = (
    groupby_features['item_id-list']
    >> nvt.ops.ListSlice(-SESSIONS_MAX_LENGTH, pad=True) 
    >> TagAsItemID()
)  
sequence_features_truncated_cont = (
    groupby_features['age_days-list', 'weekday_sin-list'] 
    >> nvt.ops.ListSlice(-SESSIONS_MAX_LENGTH, pad=True) 
    >> nvt.ops.AddMetadata(tags=[Tags.CONTINUOUS])
)

# Filter out sessions with length 1 (not valid for next-item prediction training and evaluation)
MINIMUM_SESSION_LENGTH = 2
selected_features = (
    groupby_features['item_id-count', 'day-first', 'session_id'] + 
    sequence_features_truncated_item +
    sequence_features_truncated + 
    sequence_features_truncated_cont
)
    
filtered_sessions = selected_features >> nvt.ops.Filter(f=lambda df: df["item_id-count"] >= MINIMUM_SESSION_LENGTH)

seq_feats_list = filtered_sessions['item_id-list', 'category-list', 'age_days-list', 'weekday_sin-list'] >>  nvt.ops.ValueCount()

workflow = nvt.Workflow(filtered_sessions['session_id', 'day-first'] + seq_feats_list)

dataset = nvt.Dataset(df)

# Generate statistics for the features and export parquet files
# this step will generate the schema file
workflow.fit_transform(dataset).to_parquet(os.path.join(INPUT_DATA_DIR, "processed_nvt"))
/usr/local/lib/python3.8/dist-packages/merlin/schema/tags.py:149: UserWarning: Compound tags like Tags.ITEM_ID have been deprecated and will be removed in a future version. Please use the atomic versions of these tags, like [<Tags.ITEM: 'item'>, <Tags.ID: 'id'>].
  warnings.warn(
/usr/local/lib/python3.8/dist-packages/merlin/schema/tags.py:149: UserWarning: Compound tags like Tags.ITEM_ID have been deprecated and will be removed in a future version. Please use the atomic versions of these tags, like [<Tags.ITEM: 'item'>, <Tags.ID: 'id'>].
  warnings.warn(
/usr/local/lib/python3.8/dist-packages/merlin/schema/tags.py:149: UserWarning: Compound tags like Tags.ITEM_ID have been deprecated and will be removed in a future version. Please use the atomic versions of these tags, like [<Tags.ITEM: 'item'>, <Tags.ID: 'id'>].
  warnings.warn(

It is possible to save the preprocessing workflow. That is useful to apply the same preprocessing to other data (with the same schema) and also to deploy the session-based recommendation pipeline to Triton Inference Server.

workflow.output_schema
name tags dtype is_list is_ragged properties.num_buckets properties.freq_threshold properties.max_size properties.start_index properties.cat_path properties.domain.min properties.domain.max properties.domain.name properties.embedding_sizes.cardinality properties.embedding_sizes.dimension properties.value_count.min properties.value_count.max
0 session_id () DType(name='int64', element_type=<ElementType.... False False NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 day-first () DType(name='int64', element_type=<ElementType.... False False NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 item_id-list (Tags.ID, Tags.LIST, Tags.ITEM, Tags.ITEM_ID, ... DType(name='int64', element_type=<ElementType.... True False NaN 0.0 0.0 0.0 .//categories/unique.item_id.parquet 0.0 488.0 item_id 489.0 51.0 20.0 20.0
3 category-list (Tags.CATEGORICAL, Tags.LIST) DType(name='int64', element_type=<ElementType.... True False NaN 0.0 0.0 0.0 .//categories/unique.category.parquet 0.0 164.0 category 165.0 28.0 20.0 20.0
4 age_days-list (Tags.CONTINUOUS, Tags.LIST) DType(name='float32', element_type=<ElementTyp... True False NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 20.0 20.0
5 weekday_sin-list (Tags.CONTINUOUS, Tags.LIST) DType(name='float32', element_type=<ElementTyp... True False NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 20.0 20.0

Save NVTabular workflow.

workflow.save(os.path.join(INPUT_DATA_DIR, "workflow_etl"))

Export pre-processed data by day

In this example we are going to split the preprocessed parquet files by days, to allow for temporal training and evaluation. There will be a folder for each day and three parquet files within each day folder: train.parquet, validation.parquet and test.parquet.

OUTPUT_DIR = os.environ.get("OUTPUT_DIR",os.path.join(INPUT_DATA_DIR, "sessions_by_day"))
# Read in the processed parquet file
sessions_gdf = cudf.read_parquet(os.path.join(INPUT_DATA_DIR, "processed_nvt/part_0.parquet"))
print(sessions_gdf.head(3))
   session_id  day-first                                       item_id-list  \
0       70000          6  [16, 30, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...   
1       70001          1  [5, 42, 24, 5, 144, 15, 85, 62, 0, 0, 0, 0, 0,...   
2       70002          4  [77, 25, 322, 56, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...   

                                       category-list  \
0  [4, 8, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...   
1  [3, 11, 6, 3, 37, 5, 22, 15, 0, 0, 0, 0, 0, 0,...   
2  [19, 7, 104, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...   

                                       age_days-list  \
0  [0.59015936, 0.6703282, 0.39532185, 0.9662245,...   
1  [0.57877135, 0.6347805, 0.088149734, 0.6561545...   
2  [0.5376647, 0.32101643, 0.522189, 0.044942442,...   

                                    weekday_sin-list  
0  [0.35127148, 0.49160567, 0.6861373, 0.67218935...  
1  [0.13620874, 0.3709723, 0.4606402, 0.6132054, ...  
2  [0.48387563, 0.036944088, 0.39473122, 0.618825...  
from transformers4rec.utils.data_utils import save_time_based_splits
save_time_based_splits(data=nvt.Dataset(sessions_gdf),
                       output_dir= OUTPUT_DIR,
                       partition_col='day-first',
                       timestamp_col='session_id', 
                      )
Creating time-based splits: 100%|██████████| 9/9 [00:00<00:00, 10.90it/s]

Check out the preprocessed outputs

TRAIN_PATHS = os.path.join(OUTPUT_DIR, "1", "train.parquet")
df = pd.read_parquet(TRAIN_PATHS)
df.head()
session_id item_id-list category-list age_days-list weekday_sin-list
0 70001 [5, 42, 24, 5, 144, 15, 85, 62, 0, 0, 0, 0, 0,... [3, 11, 6, 3, 37, 5, 22, 15, 0, 0, 0, 0, 0, 0,... [0.57877135, 0.6347805, 0.088149734, 0.6561545... [0.13620874, 0.3709723, 0.4606402, 0.6132054, ...
1 70006 [8, 4, 40, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0... [2, 1, 10, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,... [0.8325506, 0.90652025, 0.10265447, 0.82018495... [0.7054766, 0.8457117, 0.62498975, 0.302113, 0...
2 70009 [29, 16, 38, 1, 5, 22, 13, 29, 0, 0, 0, 0, 0, ... [8, 4, 10, 1, 3, 6, 4, 8, 0, 0, 0, 0, 0, 0, 0,... [0.6411028, 0.7770049, 0.6484449, 0.341628, 0.... [0.3938173, 0.46046025, 0.7886525, 0.54964787,...
4 70017 [10, 1, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0... [2, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... [0.8229121, 0.6468095, 0.7113366, 0.0, 0.0, 0.... [0.85833865, 0.061059132, 0.13624768, 0.0, 0.0...
5 70030 [69, 20, 17, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,... [17, 5, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,... [0.49626696, 0.36561915, 0.29867646, 0.1756632... [0.321747, 0.8811348, 0.7009088, 0.27151287, 0...
import gc
del df
gc.collect()
436

You have just created session-level features to train a session-based recommendation model using NVTabular. Now you can move to the the next notebook,02-session-based-XLNet-with-PyT.ipynb to train a session-based recommendation model using XLNet, one of the state-of-the-art NLP model. Please shut down this kernel to free the GPU memory before you start the next one.