Sign in

Sampled softmax

Sampled softmax cross-entropy

A softmax cross-entropy computed over the correct item and a small sample of wrong ones, with a correction for how the sample was drawn.

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

  1. Take query embeddings (N, D), the embedding of each query's positive item (N, D), and SS sampled negative embeddings (S, D) shared by all queries.
  2. Score each query against its positive and against every negative with a dot product, divided by the temperature.
  3. When logq_correction is on, subtract the given sampling log-probabilities from the matching scores.
  4. Put the positive in column 0 and the negatives after it. This (N, 1 + S) matrix is what logits returns.
  5. Take the cross-entropy of each row with column 0 as the correct class, and reduce with reduction.
  6. 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_q whenever 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 SS 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

IfUse instead
The number of classes is in the thousands or fewerFull softmax cross-entropy
You only have pairs of an observed and an unobserved item per userBPR
Negatives are simply the other items in the batch with no sampling correctionInfoNCE

Math foundations

  1. The full softmax it replaces

    ℓfull=−ln⁡es(q, i+)∑j=1Mes(q, j)\ell_{\text{full}} = -\ln \frac{e^{s(q,\,i^{+})}}{\sum_{j=1}^{M} e^{s(q,\,j)}}

    Cross-entropy over the whole catalogue of MM items. The sum in the denominator is the expensive part.

  2. The score

    s(q,j)=q⊤vjτs(q, j) = \frac{q^{\top} v_j}{\tau}

    The dot product of the query embedding and the item embedding, divided by the temperature.

  3. The logQ correction

    s~(q,j)=s(q,j)−ln⁡Qj\tilde{s}(q, j) = s(q, j) - \ln Q_j

    QjQ_j is the expected number of times item jj appears in the sample, for example SS times its sampling probability. Items that are sampled often have their scores lowered inside the loss, which cancels the extra pushes they receive.

  4. The sampled loss

    ℓ=−ln⁡es~(q, i+)es~(q, i+)+∑j∈Ses~(q, j)\ell = -\ln \frac{e^{\tilde{s}(q,\,i^{+})}}{e^{\tilde{s}(q,\,i^{+})} + \sum_{j \in \mathcal{S}} e^{\tilde{s}(q,\,j)}}

    Cross-entropy over 1+S1 + S candidates. The cost per query no longer depends on the size of the catalogue.

  5. Gradient with respect to the corrected logits

    ∂ℓ∂s~(q,j)=Pj−1[j=i+],Pj=softmax⁡(s~)j\frac{\partial \ell}{\partial \tilde{s}(q, j)} = P_j - \mathbf{1}[j = i^{+}], \qquad P_j = \operatorname{softmax}(\tilde{s})_j

    Predicted minus target over the sampled candidates. The correction changes PjP_j, and through it how hard each negative is pushed away.

Symbols

qq
the query embedding
vjv_j
the embedding of item j
i+i^{+}
the positive item for the query
s(q,j)s(q, j)
the score of item j for the query
s~(q,j)\tilde{s}(q, j)
the score after the logQ correction
τ\tau
the temperature, temperature in the config, default 1
QjQ_j
expected sampling count of item j; its log is passed as pos_log_q or neg_log_q
S\mathcal{S}
the set of S sampled negatives
MM
the number of items in the catalogue
PjP_j
softmax probability of candidate j among the sampled candidates
ℓ\ell
the loss for one query

Worked by hand

One query, positive score 2 with no correction, and S=2S = 2 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.

s~1=1−ln⁡0.8=1.2231,s~2=0−ln⁡0.1=2.3026\tilde{s}_1 = 1 - \ln 0.8 = 1.2231, \qquad \tilde{s}_2 = 0 - \ln 0.1 = 2.3026
e2+e1.2231+e2.3026=7.3891+3.3979+10=20.787e^{2} + e^{1.2231} + e^{2.3026} = 7.3891 + 3.3979 + 10 = 20.787
ℓ=−ln⁡7.389120.787=−ln⁡0.3555=1.0343\ell = -\ln\frac{7.3891}{20.787} = -\ln 0.3555 = 1.0343
uncorrected:−ln⁡e2e2+e1+e0=0.4076\text{uncorrected:} \quad -\ln\frac{e^{2}}{e^{2} + e^{1} + e^{0}} = 0.4076

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

  1. 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.

  2. 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.

  3. 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.

  4. 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 SS.

  5. 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.