Overview
A retrieval model may have to choose among millions of items. A full softmax would score every item for every training example, which is too slow. Sampled softmax scores only the correct item and a small set of sampled wrong ones, and applies ordinary cross-entropy to those few. Sampling introduces a bias: popular items are drawn as negatives more often and so get pushed down more than they deserve. The logQ correction removes the bias by subtracting from each score the log of how likely that item was to be sampled.
A short history
Yoshua Bengio and Jean-Sébastien Senécal proposed approximating the softmax by importance sampling in 2003, to speed up neural language models with large vocabularies. Sébastien Jean and colleagues applied the idea to neural machine translation in 2015. Recommender systems then adopted it: the 2016 YouTube recommendation paper by Covington, Adams and Sargin trained over millions of videos with sampled negatives and a correction for the sampling.
How it works
- Take query embeddings (N, D), the embedding of each query's positive item (N, D), and sampled negative embeddings (S, D) shared by all queries.
- Score each query against its positive and against every negative with a dot product, divided by the temperature.
- When
logq_correctionis on, subtract the given sampling log-probabilities from the matching scores. - Put the positive in column 0 and the negatives after it. This (N, 1 + S) matrix is what
logitsreturns. - Take the cross-entropy of each row with column 0 as the correct class, and reduce with
reduction. - In
backward, form softmax minus one-hot on those logits and carry it back to the query, positive and negative embeddings.
Watch out for
- Without the correction, negatives drawn by popularity teach the model to under-rank popular items. Pass
neg_log_qwhenever sampling is not uniform, including in-batch negatives. - A sampled negative can be the query's own positive, or another item the user liked. The template does not remove such accidental hits, so the sampler should.
- Too few negatives give a noisy, biased estimate of the full softmax. The sampled loss approaches the full loss only as grows.
- The correction is for training only. At serving time, rank by the raw dot product, without subtracting anything.
- The template is the loss alone. The two towers and the negative sampler are yours to provide.
Use cases
When to use it
Two-tower retrieval and recommendation with very large item catalogues, and language models with very large vocabularies, where a full softmax per step is too costly.
In industry
- Video and music recommendation
- YouTube's published candidate generation model treats recommendation as classification over millions of videos and trains with sampled negatives.
- E-commerce search
- Two-tower retrieval models over large product catalogues train with sampled or in-batch negatives and subtract the log of each item's sampling probability.
- Language modelling
- Word-level language models with very large vocabularies used sampled softmax to avoid scoring every word at each training step.
Choosing it: what must hold
- A number of classes or items so large that a full softmax per step is too slow.
- A known probability with which each negative is sampled, so the correction term can be computed.
- A separate plan for inference, such as approximate nearest neighbour search, since sampling only speeds up training.
When to choose something else
| If | Use instead |
|---|---|
| The number of classes is in the thousands or fewer | Full softmax cross-entropy |
| You only have pairs of an observed and an unobserved item per user | BPR |
| Negatives are simply the other items in the batch with no sampling correction | InfoNCE |
Math foundations
The full softmax it replaces
Cross-entropy over the whole catalogue of items. The sum in the denominator is the expensive part.
The score
The dot product of the query embedding and the item embedding, divided by the temperature.
The logQ correction
is the expected number of times item appears in the sample, for example times its sampling probability. Items that are sampled often have their scores lowered inside the loss, which cancels the extra pushes they receive.
The sampled loss
Cross-entropy over candidates. The cost per query no longer depends on the size of the catalogue.
Gradient with respect to the corrected logits
Predicted minus target over the sampled candidates. The correction changes , and through it how hard each negative is pushed away.
Symbols
- the query embedding
- the embedding of item j
- the positive item for the query
- the score of item j for the query
- the score after the logQ correction
- the temperature,
temperaturein the config, default 1 - expected sampling count of item j; its log is passed as
pos_log_qorneg_log_q - the set of S sampled negatives
- the number of items in the catalogue
- softmax probability of candidate j among the sampled candidates
- the loss for one query
Worked by hand
One query, positive score 2 with no correction, and negatives. A popular negative has score 1 and sampling probability 0.4. A rare one has score 0 and sampling probability 0.05. Their expected counts are 0.8 and 0.1.
The corrected loss is 1.0343 against 0.4076 uncorrected. The rare negative counts for much more after correction, because one draw of it stands in for the many rare items that were not sampled.
Visual example
Loading the example.
Try this
- Move across the curve: the height is what the model is charged.
- Move each control and watch which part of the curve it changes.
Code sample
import numpy as np
from impl import SampledSoftmax
from config import SampledSoftmaxConfig
loss = SampledSoftmax(SampledSoftmaxConfig())
rng = np.random.default_rng(0)
catalogue = rng.normal(size=(1000, 16)) # item-tower embeddings
popularity = rng.dirichlet(np.ones(1000)) # how often each item is sampled
query = rng.normal(size=(4, 16)) # query-tower embeddings, (N, D)
positives = np.array([3, 14, 15, 92]) # the item each query interacted with
negatives = rng.choice(1000, size=64, p=popularity) # S = 64 shared sampled negatives
neg_log_q = np.log(64 * popularity[negatives]) # log expected sampling count
print(loss.forward(query, catalogue[positives], catalogue[negatives], neg_log_q=neg_log_q))
g_query, g_pos, g_neg = loss.backward(query, catalogue[positives], catalogue[negatives], neg_log_q=neg_log_q)Read the implementation (70 lines)
"""Sampled softmax for two-tower retrieval: cross-entropy over one positive and S sampled negatives, with the logQ
correction for the sampling distribution.
NumPy only. `forward` returns the loss, `backward` its gradients with respect to the query, positive-item and
negative-item embeddings.
"""
from __future__ import annotations
import numpy as np
try:
from .config import SampledSoftmaxConfig
except ImportError: # run from the template's own folder
from config import SampledSoftmaxConfig
def _log_softmax(z: np.ndarray, axis: int = -1) -> np.ndarray:
"""log(softmax(z)) along `axis`, with the maximum subtracted first so exp cannot overflow."""
shifted = z - z.max(axis=axis, keepdims=True)
return shifted - np.log(np.exp(shifted).sum(axis=axis, keepdims=True))
class SampledSoftmax:
"""Cross-entropy over [positive, S shared negatives] for each query, the positive being the correct class."""
def __init__(self, config: SampledSoftmaxConfig | None = None) -> None:
self.config = config or SampledSoftmaxConfig()
def logits(self, query, pos, neg, pos_log_q=None, neg_log_q=None) -> np.ndarray:
"""Corrected scores of every query against its positive (column 0) and the negatives (columns 1..S).
query: (N, D) query-tower embeddings. pos: (N, D) embedding of each query's positive item.
neg: (S, D) embeddings of the sampled negatives, shared by all queries.
pos_log_q: (N,) log sampling probability (or log expected count) of each positive, or None.
neg_log_q: (S,) the same for each negative, or None. Returns (N, 1 + S).
"""
query, pos, neg = (np.asarray(x, dtype=float) for x in (query, pos, neg))
if query.ndim != 2 or pos.shape != query.shape or neg.ndim != 2 or neg.shape[1] != query.shape[1]:
raise ValueError(f"expected query (N, D), pos (N, D), neg (S, D); got {query.shape}, {pos.shape}, {neg.shape}")
pos_logit = (query * pos).sum(axis=1) / self.config.temperature
neg_logit = query @ neg.T / self.config.temperature
if self.config.logq_correction:
if pos_log_q is not None:
pos_logit = pos_logit - np.asarray(pos_log_q, dtype=float).reshape(query.shape[0])
if neg_log_q is not None:
neg_logit = neg_logit - np.asarray(neg_log_q, dtype=float).reshape(1, neg.shape[0])
return np.concatenate([pos_logit[:, None], neg_logit], axis=1)
def forward(self, query, pos, neg, pos_log_q=None, neg_log_q=None):
"""Loss for the arguments described in `logits`. Returns a float, or (N,) for "none"."""
per_query = -_log_softmax(self.logits(query, pos, neg, pos_log_q, neg_log_q))[:, 0]
if self.config.reduction == "none":
return per_query
return float(per_query.mean()) if self.config.reduction == "mean" else float(per_query.sum())
def backward(self, query, pos, neg, pos_log_q=None, neg_log_q=None) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Gradients of the reduced loss with respect to query (N, D), pos (N, D) and neg (S, D).
For "none" the per-query gradients are returned unscaled (the gradient of the sum).
"""
query, pos, neg = (np.asarray(x, dtype=float) for x in (query, pos, neg))
g_logits = np.exp(_log_softmax(self.logits(query, pos, neg, pos_log_q, neg_log_q)))
g_logits[:, 0] -= 1.0 # softmax minus one-hot at the positive
if self.config.reduction == "mean":
g_logits /= query.shape[0]
g_logits /= self.config.temperature
g_pos_logit, g_neg_logit = g_logits[:, :1], g_logits[:, 1:]
g_query = g_pos_logit * pos + g_neg_logit @ neg
return g_query, g_pos_logit * query, g_neg_logit.T @ query
__call__ = forward- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build SampledSoftmax(SampledSoftmaxConfig()). Make a catalogue of 1000 random item embeddings with a skewed popularity distribution, draw 64 negatives by popularity, and set neg_log_q to the log of 64 times each one's probability. Compare forward with and without neg_log_q, then inspect logits to see which columns moved most.
Check on learning
- Negatives are sampled in proportion to popularity and no correction is applied. What does the trained model do to popular items, and why?
A way to think about it
Count how often a popular item appears as a negative compared with a rare one. Each appearance is a push downward that has nothing to do with relevance.
- In the worked example the rare negative ends up with a higher corrected logit than the positive. Is that a mistake?
A way to think about it
A sampled rare item represents all the unsampled items like it. Dividing by a small expected count is how one sample is scaled up to stand for many.
- The correction is subtracted during training but not at serving time. Why would applying it when ranking be wrong?
A way to think about it
The correction compensates for the sampling procedure. At serving time nothing is sampled. Think about what subtracting log-popularity would do to the ranking.
- A sampled negative happens to be an item the user also interacted with. What does the loss ask for, and how would you guard against it?
A way to think about it
It pushes a true positive down. Consider filtering known positives out of the sample, or masking their logits, and how the frequency of this changes with .
- How does this loss relate to the in-batch InfoNCE loss?
A way to think about it
Both are cross-entropy over one positive and some negatives. Compare where the negatives come from, and what sampling distribution in-batch negatives follow.