# 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
import glob

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/tqdm/auto.py:22: 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 79737 25 5 0.063386 0.095662 7
1 84134 13 3 0.496383 0.579252 9
2 72606 9 2 0.985958 0.474934 7
3 74682 32 6 0.269306 0.514035 8
4 83072 5 1 0.666667 0.299863 3

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. In this cell, we are creating temporal features and grouping them together at the session level, sorting the interactions by time. 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 = ['session_id', 'item_id', 'category'] >> nvt.ops.Categorify()

# Define Groupby Workflow
groupby_feats = categ_feats + ['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) 
    >> nvt.ops.ValueCount()
)

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

# 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', 'item_id-count'] + seq_feats_list)

dataset = nvt.Dataset(df, cpu=False)
# Generate statistics for the features
workflow.fit(dataset)
# Apply the preprocessing and return an NVTabular dataset
sessions_ds = workflow.transform(dataset)
# Convert the NVTabular dataset to a Dask cuDF dataframe (`to_ddf()`) and then to cuDF dataframe (`.compute()`)
sessions_gdf = sessions_ds.to_ddf().compute()
/usr/local/lib/python3.8/dist-packages/merlin/schema/tags.py:148: 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:148: 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:148: 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(
sessions_gdf.head(3)
session_id day-first item_id-count item_id-list category-list age_days-list weekday_sin-list
0 1 8 16 [72, 21, 43, 13, 21, 116, 23, 193, 66, 93, 62,... [13, 4, 8, 2, 4, 21, 5, 29, 12, 16, 11, 5, 2, ... [0.6169574, 0.3725929, 0.635214, 0.7594674, 0.... [0.99312943, 0.58012384, 0.5683752, 0.5297372,...
1 2 3 16 [5, 12, 31, 4, 357, 30, 70, 26, 139, 58, 15, 1... [1, 3, 6, 1, 64, 6, 13, 5, 27, 11, 3, 4, 6, 1,... [0.2574764, 0.955602, 0.13774076, 0.39638376, ... [0.4287902, 0.7267959, 0.57816744, 0.3242513, ...
2 3 8 16 [31, 107, 23, 34, 39, 211, 30, 10, 50, 16, 13,... [6, 19, 5, 6, 7, 34, 6, 3, 9, 3, 2, 2, 1, 2, 6... [0.7587048, 0.6397919, 0.62175024, 0.06377799,... [0.10030301, 0.79694194, 0.2412423, 0.07303198...

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 (Tags.CATEGORICAL) int64 False False NaN 0.0 0.0 0.0 .//categories/unique.session_id.parquet 0.0 19863.0 session_id 19864.0 408.0 NaN NaN
1 day-first () int64 False False NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 item_id-count (Tags.CATEGORICAL) int32 False False NaN 0.0 0.0 0.0 .//categories/unique.item_id.parquet 0.0 501.0 item_id 502.0 52.0 NaN NaN
3 item_id-list (Tags.ITEM_ID, Tags.LIST, Tags.ITEM, Tags.ID, ... int64 True True NaN 0.0 0.0 0.0 .//categories/unique.item_id.parquet 0.0 501.0 item_id 502.0 52.0 2.0 16.0
4 category-list (Tags.LIST, Tags.CATEGORICAL) int64 True True NaN 0.0 0.0 0.0 .//categories/unique.category.parquet 0.0 133.0 category 134.0 25.0 2.0 16.0
5 age_days-list (Tags.CONTINUOUS, Tags.LIST) float32 True True NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2.0 16.0
6 weekday_sin-list (Tags.CONTINUOUS, Tags.LIST) float32 True True NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2.0 16.0

The following will generate schema.pbtxt file in the provided folder.

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:148: 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(
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"))
from transformers4rec.data.preprocessing 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, 22.96it/s]

Checking the preprocessed outputs

TRAIN_PATHS = os.path.join(OUTPUT_DIR, "1", "train.parquet")
df = pd.read_parquet(TRAIN_PATHS)
df
session_id item_id-count item_id-list category-list age_days-list weekday_sin-list
0 4 15 [35, 70, 25, 1, 10, 20, 9, 32, 15, 11, 7, 23, ... [7, 13, 5, 2, 3, 2, 1, 6, 3, 3, 1, 5, 6, 12, 7] [0.84711254, 0.6552394, 0.025619755, 0.5728996... [0.7905686, 0.48484242, 0.64801055, 0.2551539,...
1 6 15 [18, 16, 1, 10, 5, 4, 37, 12, 6, 2, 2, 1, 24, ... [4, 3, 2, 3, 1, 1, 7, 3, 1, 1, 1, 2, 5, 4, 3] [0.016377483, 0.6438367, 0.60421264, 0.4781767... [0.19167548, 0.912451, 0.42025977, 0.82252496,...
2 18 14 [6, 484, 77, 6, 13, 217, 13, 74, 37, 56, 14, 8... [1, 103, 14, 1, 2, 34, 2, 13, 7, 10, 3, 15, 1, 2] [0.96464884, 0.5648495, 0.28859898, 0.68664587... [0.53506935, 0.28183028, 0.9697457, 0.25601965...
4 35 13 [32, 316, 3, 20, 15, 57, 6, 12, 29, 67, 30, 6,... [6, 56, 2, 2, 3, 10, 1, 3, 6, 12, 6, 1, 3] [0.8837129, 0.85585076, 0.8977313, 0.3338614, ... [0.8302146, 0.41416064, 0.70195556, 0.58645976...
5 52 12 [39, 4, 42, 19, 60, 18, 72, 118, 66, 21, 16, 12] [7, 1, 8, 4, 11, 4, 13, 23, 12, 4, 3, 3] [0.86138207, 0.64906603, 0.020369396, 0.887563... [0.2110438, 0.90020233, 0.8758156, 0.06587109,...
... ... ... ... ... ... ...
2254 19136 2 [24, 54] [5, 10] [0.8586158, 0.09733116] [0.73065376, 0.37647644]
2255 19144 2 [8, 19] [2, 4] [0.6810742, 0.39315262] [0.08033292, 0.6399043]
2256 19151 2 [11, 139] [3, 27] [0.87349886, 0.9999593] [0.488393, 0.1564067]
2257 19164 2 [9, 6] [1, 1] [0.11814103, 0.8120989] [0.79111385, 0.26691133]
2259 19187 2 [9, 10] [1, 3] [0.602314, 0.9958059] [0.85496294, 0.9630791]

1812 rows × 6 columns

import gc
del df
gc.collect()
656

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.