Sign in

Two-tower retrieval

Two-tower retrieval model

A retrieval model with two separate encoders, one for users and one for items, that scores a pair by the dot product of their embeddings.

Overview

A recommender may have to choose among millions of items for each request, far too many to score one by one with a heavy model. The two-tower design splits the work. One network turns the user's features into a vector, another turns each item's features into a vector in the same space, and the match score is their dot product. Because the item side never looks at the user, every item vector can be computed ahead of time and stored. Serving a request then needs one pass through the user tower and a nearest-neighbour search. Training uses pairs that really occurred and treats the other items in the same batch as the wrong answers.

A short history

The design goes back to the Deep Structured Semantic Model, published by Po-Sen Huang and colleagues at Microsoft in 2013, which embedded queries and documents with separate networks for web search. Google described deep candidate generation for YouTube in 2016 and a two-tower model with a correction for sampling bias in 2019. The appeal is practical: item embeddings can be computed in advance and searched with a nearest neighbour index in milliseconds.

How it works

  1. Pass user features through the user tower and item features through the item tower. Each tower is a ReLU hidden layer and a linear layer.
  2. Scale every output vector to unit length, so the dot product of a user and an item is their cosine similarity.
  3. For a batch of nn observed pairs, compute all n×nn \times n scores between its users and its items and divide by the temperature.
  4. Treat each row as a classification problem: the user's own item on the diagonal is the correct answer and the other n−1n - 1 items are negatives.
  5. Minimise the cross-entropy of every row and send the gradient back through both towers.
  6. To serve, embed all items once with item_embed, embed the user with user_embed, and return the highest-scoring items. The retrieve method does this by exact search.

Watch out for

  • Popular items appear in many batches and so serve as negatives more often than rare ones, which pushes their scores down unfairly. Production systems correct for this, the template does not.
  • Another item in the batch may be one the user would also like. Treating it as a negative teaches the model something false, and the effect grows with batch size.
  • User and item meet only through one dot product, so the model cannot learn rules that need a specific user feature combined with a specific item feature. A later ranking stage usually handles that.
  • A very small temperature makes the loss depend almost entirely on the hardest negative, which makes training noisy. A large one gives a weak, blurry signal.

Use cases

When to use it

The first, candidate-generation stage of a recommendation or search system, where a few hundred candidates must be drawn from a very large catalogue within milliseconds.

In industry

Video and music streaming
Candidate retrieval: narrowing millions of items to a few hundred for each user before a heavier ranking model runs.
Web and product search
Semantic search: embedding the query and the documents separately and retrieving by vector similarity.
Online advertising
Selecting a shortlist of relevant ads for a user or page from a very large inventory.

Choosing it: what must hold

  • A very large set of candidates, too many to score one by one with a full model.
  • Logged positive pairs, such as a user and an item they clicked.
  • Acceptance that user and item features meet only at the final dot product, which limits how fine the scoring can be.
  • A nearest neighbour index to serve the item embeddings.

When to choose something else

IfUse instead
There are only a few hundred candidates to scoreA ranking model with full feature crosses, such as DCN, DeepFM or DIN
You have interactions but no user or item featuresMatrix factorization
Both inputs are the same kind of objectA Siamese network with shared weights

Math foundations

  1. A tower

    u=z∥z∥,z=relu⁡ ⁣(xW1+b1)W2+b2\mathbf{u} = \frac{\mathbf{z}}{\lVert \mathbf{z} \rVert}, \qquad \mathbf{z} = \operatorname{relu}\!\left(\mathbf{x} W_1 + \mathbf{b}_1\right) W_2 + \mathbf{b}_2

    Each tower maps its input to a unit-length vector. The user tower and the item tower have the same form but separate weights.

  2. The score

    sij=ui⊤vjτs_{ij} = \frac{\mathbf{u}_i^\top \mathbf{v}_j}{\tau}

    The cosine similarity of user ii and item jj, divided by the temperature. Before the division it lies between −1-1 and 11.

  3. In-batch softmax loss

    L=−1n∑i=1nlog⁡esii∑j=1nesijL = -\frac{1}{n}\sum_{i=1}^{n} \log \frac{e^{s_{ii}}}{\sum_{j=1}^{n} e^{s_{ij}}}

    For each user, the probability of picking their own item out of all the items in the batch. The other items act as negatives that cost nothing extra to compute.

  4. Gradient with respect to the scores

    ∂L∂sij=1n(pij−1[i=j]),pij=esij∑lesil\frac{\partial L}{\partial s_{ij}} = \frac{1}{n}\left(p_{ij} - \mathbb{1}[i = j]\right), \qquad p_{ij} = \frac{e^{s_{ij}}}{\sum_{l} e^{s_{il}}}

    The matched pair is pulled together and each negative is pushed away in proportion to the probability it currently receives, so hard negatives get the largest push.

  5. Gradient through the normalisation

    ∂L∂z=1∥z∥(d−u (u⊤d)),d=∂L∂u\frac{\partial L}{\partial \mathbf{z}} = \frac{1}{\lVert \mathbf{z} \rVert}\left(\mathbf{d} - \mathbf{u}\,(\mathbf{u}^\top \mathbf{d})\right), \qquad \mathbf{d} = \frac{\partial L}{\partial \mathbf{u}}

    Only the part of the gradient at right angles to the embedding passes through. Changing the length of z\mathbf{z} cannot change the loss, so that direction gets none.

Symbols

x\mathbf{x}
feature row of a user or an item
W1,b1,W2,b2W_1, \mathbf{b}_1, W_2, \mathbf{b}_2
hidden and output parameters of one tower
z\mathbf{z}
tower output before normalisation
ui,vj\mathbf{u}_i, \mathbf{v}_j
unit-length embeddings of user i and item j
τ\tau
temperature
sijs_{ij}
score of user i with item j
pijp_{ij}
softmax probability that user i picks item j within the batch
nn
number of pairs in the batch
d\mathbf{d}
gradient of the loss with respect to a unit embedding

Worked by hand

A batch of two pairs. For user 1 the cosine with their own item is 0.8 and with the other item is 0.2. Compute user 1's loss at temperature 1 and at temperature 0.1.

τ=1:p11=e0.8e0.8+e0.2=11+e−0.6=0.6457\tau = 1: \quad p_{11} = \frac{e^{0.8}}{e^{0.8} + e^{0.2}} = \frac{1}{1 + e^{-0.6}} = 0.6457
−ln⁡0.6457=0.4375-\ln 0.6457 = 0.4375
τ=0.1:p11=e8e8+e2=11+e−6=0.9975\tau = 0.1: \quad p_{11} = \frac{e^{8}}{e^{8} + e^{2}} = \frac{1}{1 + e^{-6}} = 0.9975
−ln⁡0.9975=0.0025-\ln 0.9975 = 0.0025

The same embeddings give a loss of 0.44 at temperature 1 and 0.0025 at temperature 0.1. A small temperature stretches the gap between cosines, so a modest difference already counts as a confident choice.

Visual example

Loading the example.

Try this

  • Press Run and watch each user dot settle next to the square of the item they chose.
  • Set the temperature to 1 and train again: the loss stays high because every item looks about equally likely.
  • Click a user dot, then click In-batch softmax in the diagram to read the probability of their own item.

Code sample

import numpy as np
from impl import TwoTower
from config import TwoTowerConfig

rng = np.random.default_rng(0)
taste = rng.normal(size=(500, 4))                                       # hidden reason a user likes an item
users = taste @ rng.normal(size=(4, 10)) + 0.1 * rng.normal(size=(500, 10))   # user features, (500, 10)
items = np.tanh(taste @ rng.normal(size=(4, 8)))                        # features of the item each user chose, (500, 8)

model = TwoTower(TwoTowerConfig(epochs=30)).fit(users[:400], items[:400])
top5 = model.retrieve(users[400:], items[400:], k=5)                    # (100, 5) item indices, best first
print(np.mean(top5[:, 0] == np.arange(100)))                            # how often the true item is ranked first
print(np.mean((top5 == np.arange(100)[:, None]).any(axis=1)))           # recall at 5
Read the implementation (144 lines)
"""Two-tower retrieval model trained with the in-batch sampled softmax, manual backpropagation and Adam.

NumPy only. Each tower is embed(x) = normalise(relu(x W1 + b1) W2 + b2), with normalise(z) = z / ||z||.
For a batch of n positive (user, item) pairs, scores S = U V^T / temperature has shape (n, n) and the loss is
the cross-entropy of each row against its diagonal entry: the user's own item is the positive, the other
n - 1 items in the batch are the negatives.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import TwoTowerConfig
except ImportError:  # run from the template's own folder
    from config import TwoTowerConfig


class _Adam:
    """Adam optimizer over a dict of NumPy arrays; `step` updates the arrays in place."""

    def __init__(self, params: dict, lr: float, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8) -> None:
        self.params, self.lr, self.beta1, self.beta2, self.eps = params, lr, beta1, beta2, eps
        self.m = {k: np.zeros_like(v) for k, v in params.items()}
        self.v = {k: np.zeros_like(v) for k, v in params.items()}
        self.t = 0

    def step(self, grads: dict) -> None:
        """Apply one update. grads: same keys and shapes as the parameters."""
        self.t += 1
        for k, g in grads.items():
            self.m[k] = self.beta1 * self.m[k] + (1 - self.beta1) * g
            self.v[k] = self.beta2 * self.v[k] + (1 - self.beta2) * g * g
            m_hat = self.m[k] / (1 - self.beta1**self.t)
            v_hat = self.v[k] / (1 - self.beta2**self.t)
            self.params[k] -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)

class TwoTower:
    """User tower and item tower with a dot-product score. After `fit`: `params`, `loss_history_`."""

    def __init__(self, config: TwoTowerConfig | None = None) -> None:
        self.config = config or TwoTowerConfig()
        self.params: dict[str, np.ndarray] = {}
        self.loss_history_: list[float] = []

    def initialize(self, user_dim: int, item_dim: int) -> None:
        """Create both towers for user features of width `user_dim` and item features of width `item_dim`."""
        rng = np.random.default_rng(self.config.seed)
        h, e = self.config.hidden_dim, self.config.embed_dim
        self.params = {}
        for side, d in (("user", user_dim), ("item", item_dim)):
            self.params[f"{side}_W1"] = np.sqrt(2.0 / d) * rng.normal(size=(d, h))
            self.params[f"{side}_b1"] = np.zeros(h)
            self.params[f"{side}_W2"] = np.sqrt(1.0 / h) * rng.normal(size=(h, e))
            self.params[f"{side}_b2"] = np.zeros(e)

    def _tower(self, side: str, X: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Run one tower. X: (n, d). Returns (hidden (n, h), norms (n, 1), unit embeddings (n, e))."""
        p = self.params
        hidden = np.maximum(X @ p[f"{side}_W1"] + p[f"{side}_b1"], 0.0)
        z = hidden @ p[f"{side}_W2"] + p[f"{side}_b2"]
        norm = np.sqrt(np.sum(z**2, axis=1, keepdims=True) + 1e-12)
        return hidden, norm, z / norm

    def _tower_backward(self, side: str, X: np.ndarray, hidden, norm, unit, d_unit) -> dict:
        """Gradients of one tower's weights given d_unit = d loss / d (unit embeddings), shape (n, e)."""
        p = self.params
        # Through z / ||z||: remove the component along the embedding, then divide by the norm.
        dz = (d_unit - unit * np.sum(unit * d_unit, axis=1, keepdims=True)) / norm
        d_hidden = (dz @ p[f"{side}_W2"].T) * (hidden > 0)
        return {
            f"{side}_W1": X.T @ d_hidden,
            f"{side}_b1": d_hidden.sum(axis=0),
            f"{side}_W2": hidden.T @ dz,
            f"{side}_b2": dz.sum(axis=0),
        }

    def loss_and_grads(self, users: np.ndarray, items: np.ndarray) -> tuple[float, dict]:
        """In-batch softmax loss and its gradient for every parameter.

        users: (n, user_dim). items: (n, item_dim). Row i of each is one observed positive pair.
        """
        n = len(users)
        tau = self.config.temperature
        hu, nu, U = self._tower("user", users)
        hv, nv, V = self._tower("item", items)
        S = U @ V.T / tau
        S = S - S.max(axis=1, keepdims=True)
        P = np.exp(S)
        P /= P.sum(axis=1, keepdims=True)
        loss = -np.mean(np.log(P[np.arange(n), np.arange(n)] + 1e-300))
        dS = P.copy()
        dS[np.arange(n), np.arange(n)] -= 1.0
        dS /= n * tau
        grads = self._tower_backward("user", users, hu, nu, U, dS @ V)
        grads.update(self._tower_backward("item", items, hv, nv, V, dS.T @ U))
        return float(loss), grads

    def fit(self, users: np.ndarray, items: np.ndarray) -> "TwoTower":
        """Train on positive pairs. users: (n, user_dim). items: (n, item_dim), row i is the item user i chose."""
        cfg = self.config
        users = np.asarray(users, dtype=float)
        items = np.asarray(items, dtype=float)
        if users.ndim != 2 or items.ndim != 2 or len(users) != len(items):
            raise ValueError("users and items must be 2-D with the same number of rows (one positive pair per row)")
        self.initialize(users.shape[1], items.shape[1])
        optimizer = _Adam(self.params, cfg.lr)
        rng = np.random.default_rng(cfg.seed + 1)
        self.loss_history_ = []
        n = len(users)
        for _ in range(cfg.epochs):
            order = rng.permutation(n)
            total, count = 0.0, 0
            for start in range(0, n, cfg.batch_size):
                rows = order[start : start + cfg.batch_size]
                if len(rows) < 2:  # a single pair has no negatives
                    continue
                loss, grads = self.loss_and_grads(users[rows], items[rows])
                optimizer.step(grads)
                total += loss * len(rows)
                count += len(rows)
            self.loss_history_.append(total / max(count, 1))
        return self

    def user_embed(self, users: np.ndarray) -> np.ndarray:
        """Unit-length user vectors. users: (n, user_dim). Returns (n, embed_dim)."""
        if not self.params:
            raise RuntimeError("call fit (or initialize) before embedding")
        return self._tower("user", np.asarray(users, dtype=float))[2]

    def item_embed(self, items: np.ndarray) -> np.ndarray:
        """Unit-length item vectors. items: (m, item_dim). Returns (m, embed_dim)."""
        if not self.params:
            raise RuntimeError("call fit (or initialize) before embedding")
        return self._tower("item", np.asarray(items, dtype=float))[2]

    def score(self, users: np.ndarray, items: np.ndarray) -> np.ndarray:
        """Cosine similarity of every user with every item. Returns shape (n_users, n_items), values in [-1, 1]."""
        return self.user_embed(users) @ self.item_embed(items).T

    def retrieve(self, users: np.ndarray, items: np.ndarray, k: int = 10) -> np.ndarray:
        """Indices of the k best items for each user, best first (exact search). Returns (n_users, k)."""
        scores = self.score(users, items)
        k = min(k, scores.shape[1])
        return np.argsort(-scores, axis=1, kind="stable")[:, :k]
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Create a hidden two-dimensional taste vector for each of 500 users and each of 500 items, and derive noisy user and item features from them. Pair each user with the item whose taste is closest. Fit TwoTower with the default TwoTowerConfig, then call retrieve with k of 10 and measure how often a user's paired item is in their top 10. Repeat with batch_size 8 and 128, and with temperature 1.0.

Check on learning

  1. Why must the item tower never see user features? What exactly would be lost at serving time if it did?
    A way to think about it

    Count how many item-tower passes a request would need in each design when the catalogue has ten million items.

  2. In-batch negatives are drawn in proportion to how often an item appears in the data. What bias does that create for popular items?
    A way to think about it

    A popular item is the wrong answer for many users in many batches. Follow what the gradient does to its score for a user who has never interacted with it.

  3. You increase the batch size from 8 to 128 and recall improves. Give a reason based on the loss formula.
    A way to think about it

    Look at the denominator. With more items in it, the task of picking the right one is harder and more like the real retrieval problem.

  4. The embeddings are normalised to unit length. What could a model without normalisation do to lower the loss that has nothing to do with matching?
    A way to think about it

    If lengths are free, growing every vector scales every score. Consider what that does to the softmax, and compare with the role of the temperature.