#
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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.
#
from typing import Dict, Optional
import tensorflow as tf
from tensorflow.python.ops import embedding_ops
from merlin.models.tf.blocks.sampling.base import EmbeddingWithMetadata, ItemSampler
from merlin.models.tf.blocks.sampling.queue import FIFOQueue
from merlin.models.tf.typing import TabularData
[docs]class CachedCrossBatchSampler(ItemSampler):
"""Provides efficient cached cross-batch [1]_ / inter-batch [2]_ negative sampling
for two-tower item retrieval model. The caches consists of a fixed capacity FIFO queue
which keeps the item embeddings from the last N batches. All items in the queue are
sampled as negatives for upcoming batches.
It is more efficient than computing embeddings exclusively for negative items.
This is a popularity-biased sampling as popular items are observed more often
in training batches.
Compared to `InBatchSampler`, the `CachedCrossBatchSampler` allows for larger number
of negative items, not limited to the batch size. The gradients are not computed
for the cached negative embeddings which is a scalable approach. A common combination
of samplers for the `ItemRetrievalScorer` is `[InBatchSampler(),
CachedCrossBatchSampler(ignore_last_batch_on_sample=True)]`, which computes gradients for
the in-batch negatives and not for the cached item embeddings.
P.s. Ignoring the false negatives (negative items equal to the positive ones) is
managed by `ItemRetrievalScorer(..., sampling_downscore_false_negatives=True)`
References
----------
.. [1] Wang, Jinpeng, Jieming Zhu, and Xiuqiang He. "Cross-Batch Negative Sampling
for Training Two-Tower Recommenders." Proceedings of the 44th International ACM
SIGIR Conference on Research and Development in Information Retrieval. 2021.
.. [2] Zhou, Chang, et al. "Contrastive learning for debiased candidate generation
in large-scale recommender systems." Proceedings of the 27th ACM SIGKDD Conference
on Knowledge Discovery & Data Mining. 2021.
Parameters
----------
capacity: int
The queue capacity to store samples
ignore_last_batch_on_sample: bool
Whether should include the last batch in the sampling. By default `False`,
as for sampling from the current batch we recommend `InBatchSampler()`, which
allows computing gradients for in-batch negative items
"""
[docs] def __init__(
self,
capacity: int,
ignore_last_batch_on_sample: bool = True,
**kwargs,
):
assert capacity > 0
super().__init__(max_num_samples=capacity, **kwargs)
self.ignore_last_batch_on_sample = ignore_last_batch_on_sample
self.item_metadata_dtypes: Dict[str, tf.dtypes.DType] = {}
self._last_batch_size = 0
self._item_embeddings_queue: Optional[FIFOQueue] = None
@property
def item_embeddings_queue(self) -> FIFOQueue:
if not self._item_embeddings_queue:
raise ValueError("Item embeddings queue is not initialized")
return self._item_embeddings_queue
def _maybe_build(self, inputs: TabularData) -> None:
items_metadata = inputs["metadata"]
if not self.item_metadata_dtypes:
self.item_metadata_dtypes = {
feat_name: items_metadata[feat_name].dtype for feat_name in items_metadata
}
super()._maybe_build(inputs)
[docs] def build(self, input_shapes: TabularData) -> None:
queue_size = self.max_num_samples
item_embeddings_dims = list(input_shapes["embeddings"][1:])
self._item_embeddings_queue = FIFOQueue(
capacity=queue_size,
dims=item_embeddings_dims,
dtype=tf.float32,
name="item_emb",
)
self.items_metadata_queue = dict()
items_metadata = input_shapes["metadata"]
for feat_name in items_metadata:
dims = []
if items_metadata[feat_name].dims is not None:
dims = list(items_metadata[feat_name][1:])
self.items_metadata_queue[feat_name] = FIFOQueue(
capacity=queue_size,
dims=dims,
dtype=self.item_metadata_dtypes[feat_name],
name=f"item_metadata_{feat_name}",
)
def _check_built(self) -> None:
if self._item_embeddings_queue is None:
raise Exception(
f"The {self.__class__.__name__} layer was not built yet. "
"You need to call() that layer at least once before "
"so that it is built before calling add() or sample() directly"
)
[docs] def call(self, inputs: TabularData, training=True) -> EmbeddingWithMetadata:
"""Adds the current batch to the FIFO queue cache and samples all items
embeddings from the last N cached batches.
Parameters
----------
inputs : TabularData
Dict with two keys:
"items_embeddings": Items embeddings tensor
"items_metadata": Dict like `{"<feature name>": "<feature tensor>"}` which contains
features that might be relevant for the sampler (e.g. item id, item popularity, item
recency).
The `CachedCrossBatchSampler` does not use metadata features
specifically, but "item_id" is required when using in combination with
`ItemRetrievalScorer(..., sampling_downscore_false_negatives=True)`, so that
false negatives are identified and downscored.
training : bool, optional
Flag indicating if on training mode, by default True
Returns
-------
EmbeddingWithMetadata
Value object with the sampled item embeddings and item metadata
"""
if self.ignore_last_batch_on_sample:
items_embeddings = self.sample()
self.add(inputs, training)
else:
self.add(inputs, training)
items_embeddings = self.sample()
return items_embeddings
[docs] def add( # type: ignore
self,
inputs: TabularData,
training: bool = True,
) -> None:
self._check_built()
if training:
self._check_inputs_batch_sizes(inputs)
items_embeddings = inputs["embeddings"]
items_metadata = inputs["metadata"]
self.item_embeddings_queue.enqueue_many(items_embeddings)
for feat_name in items_metadata:
self.items_metadata_queue[feat_name].enqueue_many(items_metadata[feat_name])
self._last_batch_size = tf.shape(items_embeddings)[0]
[docs] def sample(self) -> EmbeddingWithMetadata:
self._check_built()
items_embeddings = self.item_embeddings_queue.list_all()
items_metadata = {
feat_name: self.items_metadata_queue[feat_name].list_all()
for feat_name in self.items_metadata_queue
}
return EmbeddingWithMetadata(
items_embeddings,
items_metadata,
)
[docs]class PopularityBasedSampler(ItemSampler):
"""
Provides a popularity-based negative sampling for the softmax layer
to ensure training efficiency when the catalog of items is very large.
The capacity of the queue is fixed and is equal to the catalog size.
For each batch, we sample `max_num_samples` unique negatives.
This implementation does not require the actual item frequencies/probabilities
distribution, but instead tries to approximate the item
probabilities using the log_uniform (zipfian) distribution.
The only requirement is that the item ids are decreasingly sorted by their count frequency.
We use the default log-uniform (zipfian) sampler given by Tensorflow:
[log_uniform_candidate_sampler](https://www.tensorflow.org/api_docs/python/tf/random/log_uniform_candidate_sampler)
The `Categorify` op provided by nvtabular supports the frequency-based encoding as default.
P.s. Ignoring the false negatives (negative items equal to the positive ones) is
managed by `ItemRetrievalScorer(..., sampling_downscore_false_negatives=True)`
Parameters
----------
max_num_samples: int
The number of unique negatives to sample at each batch.
max_id: int
The maximum id value to be sampled. It should be equal to the
categorical feature cardinality
min_id: int
The minimum id value to be sampled. Useful to ignore the first categorical
encoded ids, which are usually reserved for <nulls>, out-of-vocabulary or padding.
Defaults to 0.
seed: int
Fix the random values returned by the sampler to ensure reproducibility
Defaults to None
item_id_feature_name: str
Name of the column containing the item ids
Defaults to `item_id`
"""
[docs] def __init__(
self,
max_id: int,
min_id: int = 0,
max_num_samples: int = 100,
seed: Optional[int] = None,
item_id_feature_name: str = "item_id",
**kwargs,
):
super().__init__(max_num_samples=max_num_samples, **kwargs)
self.max_id = max_id
self.min_id = min_id
self.seed = seed
self.item_id_feature_name = item_id_feature_name
assert (
self.max_num_samples <= self.max_id
), f"Number of items to sample `{self.max_num_samples}`"
f" should be less than total number of ids `{self.max_id}`"
def _check_inputs(self, inputs):
assert (
self.item_id_feature_name in inputs["metadata"]
), "The 'item_id' metadata feature is required by PopularityBasedSampler."
[docs] def add(self, embeddings: tf.Tensor, items_metadata: TabularData, training=True):
pass
[docs] def call(
self, inputs: TabularData, item_weights: tf.Tensor, training=True
) -> EmbeddingWithMetadata:
if training:
self._check_inputs(inputs)
tf.assert_equal(
int(tf.shape(item_weights)[0]),
self.max_id + 1,
"The first dimension of the items embeddings "
f"({int(tf.shape(item_weights)[0])}) and "
f"the the number of possible classes ({self.max_id+1}) should match.",
)
items_embeddings = self.sample(item_weights)
return items_embeddings
def _required_features(self):
return [self.item_id_feature_name]
[docs] def sample(self, item_weights) -> EmbeddingWithMetadata: # type: ignore
sampled_ids, _, _ = tf.random.log_uniform_candidate_sampler(
true_classes=tf.ones((1, 1), dtype=tf.int64),
num_true=1,
num_sampled=self.max_num_samples,
unique=True,
range_max=self.max_id - self.min_id,
seed=self.seed,
)
# Shifting the sampled ids to ignore the first ids (usually reserved for nulls, OOV)
sampled_ids += self.min_id
items_embeddings = embedding_ops.embedding_lookup(item_weights, sampled_ids)
return EmbeddingWithMetadata(
items_embeddings,
metadata={self.item_id_feature_name: tf.cast(sampled_ids, tf.int32)},
)
[docs] def get_distribution_probs(self):
"""Tries to approximate the log uniform (zipfian) distribution
used by tf.random.log_uniform_candidate_sampler
(https://www.tensorflow.org/api_docs/python/tf/random/log_uniform_candidate_sampler)
Returns
-------
tf.Tensor
A tensor with the expected probability distribution of item ids
assuming log-uniform (zipfian) distribution
"""
range_max = self.max_id - self.min_id
ids = tf.range(0, range_max, dtype=tf.float32)
estimated_probs = (tf.math.log(ids + 2.0) - tf.math.log(ids + 1.0)) / tf.math.log(
range_max + 1.0
)
# Appending zero(s) in the beginning as padding items should never be samples
# (thus prob must be zero)
estimated_probs = tf.concat(
[tf.zeros(self.min_id + 1, dtype=tf.float32), estimated_probs], axis=0
)
return estimated_probs