Overview
A recommender must combine two kinds of input: numbers such as age or price, and ids such as user and item. The Deep Learning Recommendation Model turns both into vectors of the same length. Each id looks up a learned vector called an embedding, and the numeric features pass through a small network that outputs one vector. The model then takes the dot product of every pair of vectors. A dot product is large when two vectors point the same way, so it is a direct measure of how well a user and an item match. A second network reads these match scores and outputs the click probability.
A short history
Maxim Naumov and colleagues at Facebook published DLRM in 2019 and released the code as open source. It combined two traditions: embeddings and dot products from collaborative filtering and factorization machines, and multilayer perceptrons from deep learning. Because its huge embedding tables stress memory in ways that vision models do not, it was adopted as a recommendation benchmark in MLPerf and shaped how hardware for recommendation is evaluated.
How it works
- Pass the dense features through the bottom MLP to get one vector of length
embedding_size. - Look up one embedding of the same length for each sparse field.
- Compute the dot product for every pair of these vectors.
- Concatenate with all the dot products.
- Pass that vector through the top MLP and a sigmoid to get the click probability.
- Train both MLPs and all embedding tables with Adam on the binary cross-entropy loss.
Watch out for
- An id that was rare in training has an embedding that barely moved from its random start, so its dot products are noise. New users and items need a fallback.
- The model only forms second-order interactions between whole vectors. A pattern that needs three fields at once must be recovered by the top MLP from pairwise scores.
- The number of dot products grows as with the number of vectors , so many sparse fields make the top MLP's input wide.
- This template keeps embedding tables in memory with one id per field and no multi-hot bags or sharding, so it suits vocabularies up to tens of thousands of ids.
Use cases
When to use it
Recommendation and click-through-rate prediction with a mix of numeric features and high-cardinality categorical ids such as user, item and context.
In industry
- Social media
- Ranking posts and ads by predicted click or engagement, the setting described in the original Facebook paper.
- Hardware and cloud
- Benchmarking recommendation training and inference systems, where DLRM is a standard workload.
- E-commerce
- Click and purchase prediction from user, item and context ids alongside a few dense features.
Choosing it: what must hold
- A mix of sparse categorical ids and dense numeric features.
- Very large interaction logs, enough to train an embedding for each id.
- Memory for the embedding tables, which usually dominate the model size.
When to choose something else
| If | Use instead |
|---|---|
| Higher-order feature crosses matter | Deep & Cross Network (DCN) |
| You want a simpler model with first- and second-order terms | DeepFM |
| The dataset is a modest table without large id vocabularies | LightGBM or CatBoost |
Math foundations
Dense and sparse vectors
Every input becomes a vector of the same length . The dense features share one vector, and each sparse field looks up a row of its own table.
Pairwise interactions
One number per pair of vectors. It is large and positive when the two vectors are aligned, which is how the model expresses that a user and an item fit together.
Number of interactions
Every unordered pair among the vectors is used once. A vector is not paired with itself.
Prediction
The top network reads the dense vector and all the match scores and outputs the click probability.
Gradient of an interaction
Each vector is pulled towards or away from its partner in the pair, depending on the sign of the error. This is how matching users and items end up with aligned embeddings.
Symbols
- the numeric features of one row
- output of the bottom MLP
- embedding table of sparse field f
- the id of field f in this row
- embedding of field f for this row
- embedding_size
- number of sparse fields
- number of vectors that interact
- dot product of vectors i and j
- predicted click probability
Worked by hand
Two sparse fields and . The bottom MLP gives , the user embedding is and the item embedding is .
The top MLP receives the five numbers (1, 2, -1.5, 2, 1): the dense vector and three interaction scores. The user and item score of 1 says these two embeddings are mildly aligned.
Visual example
Loading the example.
Try this
- Drag the training steps from 0 upward and watch the user and item arrows sort themselves into two groups.
- Keep Ana and switch the item from running shoes to the frying pan: the dot product of user and item flips and p falls.
- Raise the price and see z0 move, and with it the two dot products that involve z0.
Code sample
import numpy as np
from impl import DLRM
from config import DLRMConfig
rng = np.random.default_rng(0)
X_sparse = rng.integers(0, 10, size=(2000, 2)) # field 0: user id, field 1: item id
X_dense = rng.normal(size=(2000, 2))
same_group = X_sparse[:, 0] % 2 == X_sparse[:, 1] % 2
y = (same_group & (X_dense[:, 0] < 1.0)).astype(int)
model = DLRM(DLRMConfig(epochs=20)).fit(X_dense, X_sparse, y)
print((model.predict(X_dense, X_sparse) == y).mean())Read the implementation (177 lines)
"""DLRM: Deep Learning Recommendation Model.
NumPy only, manual backpropagation. Dense features go through a bottom MLP to a vector of the embedding size;
each sparse field looks up an embedding of the same size. Every pair of these vectors is compared by a dot
product, and a top MLP turns the dense vector plus all the pairwise dot products into a click probability.
dense -> bottom MLP -> z
sparse -> embeddings -> e_1 .. e_F
interactions = { <a, b> for every pair a, b among (z, e_1, .., e_F) }
logit = top MLP(concat(z, interactions))
"""
from __future__ import annotations
import numpy as np
try:
from .config import DLRMConfig
except ImportError: # run from the template's own folder
from config import DLRMConfig
def _sigmoid(z: np.ndarray) -> np.ndarray:
return 1.0 / (1.0 + np.exp(-np.clip(z, -60.0, 60.0)))
def _mlp_init(params: dict, prefix: str, sizes: list, rng: np.random.Generator) -> None:
"""Add the layers of an MLP to `params` as `<prefix>W<i>` (fan_in, fan_out) and `<prefix>b<i>` (fan_out,)."""
for i, (a, b) in enumerate(zip(sizes[:-1], sizes[1:])):
params[f"{prefix}W{i}"] = rng.normal(0.0, np.sqrt(2.0 / a), size=(a, b))
params[f"{prefix}b{i}"] = np.zeros(b)
def _mlp_forward(params: dict, prefix: str, x: np.ndarray, n_layers: int, last_linear: bool) -> list:
"""Run an MLP with ReLU layers on x (..., fan_in). Returns every activation, the input first.
last_linear: leave the last layer without ReLU (used when it produces a logit or a score).
"""
acts = [x]
for i in range(n_layers):
z = acts[-1] @ params[f"{prefix}W{i}"] + params[f"{prefix}b{i}"]
acts.append(z if (last_linear and i == n_layers - 1) else np.maximum(z, 0.0))
return acts
def _mlp_backward(params: dict, prefix: str, acts: list, d: np.ndarray, grads: dict, last_linear: bool) -> np.ndarray:
"""Backpropagate d (gradient at the MLP output) and store the weight gradients. Returns the input gradient."""
n_layers = len(acts) - 1
for i in range(n_layers - 1, -1, -1):
if not (last_linear and i == n_layers - 1):
d = d * (acts[i + 1] > 0)
a = acts[i].reshape(-1, acts[i].shape[-1])
grads[f"{prefix}W{i}"] = a.T @ d.reshape(-1, d.shape[-1])
grads[f"{prefix}b{i}"] = d.reshape(-1, d.shape[-1]).sum(axis=0)
d = d @ params[f"{prefix}W{i}"].T
return d
def _bce(logit: np.ndarray, y: np.ndarray) -> tuple[float, np.ndarray]:
"""Mean binary cross-entropy from logits, and its gradient with respect to the logits. Both inputs (n,)."""
loss = float(np.mean(np.logaddexp(0.0, logit) - y * logit))
return loss, (_sigmoid(logit) - y) / len(y)
def _adam_fit(model, arrays: tuple, y: np.ndarray) -> None:
"""Mini-batch Adam over `model.params` using `model.loss_and_grads(*batch_arrays, batch_y)`."""
cfg = model.config
rng = np.random.default_rng(cfg.seed + 1)
m = {k: np.zeros_like(p) for k, p in model.params.items()}
v = {k: np.zeros_like(p) for k, p in model.params.items()}
step = 0
model.loss_history = []
for _ in range(cfg.epochs):
order = rng.permutation(len(y))
total = 0.0
for start in range(0, len(y), cfg.batch_size):
rows = order[start:start + cfg.batch_size]
loss, grads = model.loss_and_grads(*[a[rows] for a in arrays], y[rows])
total += loss * len(rows)
step += 1
for name, g in grads.items():
m[name] = 0.9 * m[name] + 0.1 * g
v[name] = 0.999 * v[name] + 0.001 * g * g
model.params[name] -= cfg.learning_rate * (m[name] / (1 - 0.9**step)) / (
np.sqrt(v[name] / (1 - 0.999**step)) + 1e-8)
model.loss_history.append(total / len(y))
def _field_offsets(X_sparse: np.ndarray, field_dims) -> tuple[tuple, np.ndarray]:
"""Resolve the vocabulary size of each sparse field and the row offset of each field in a shared table.
X_sparse: (n, F) non-negative integer ids. field_dims: sizes from the config, or None to take max id + 1.
"""
if X_sparse.ndim != 2 or (X_sparse.size and X_sparse.min() < 0):
raise ValueError("X_sparse must be a 2-d array of non-negative integer ids")
dims = tuple(int(d) for d in (field_dims if field_dims is not None else X_sparse.max(axis=0) + 1))
if len(dims) != X_sparse.shape[1]:
raise ValueError(f"field_dims has {len(dims)} entries but X_sparse has {X_sparse.shape[1]} columns")
return dims, np.concatenate([[0], np.cumsum(dims)[:-1]]).astype(int)
def pairwise_dots(V: np.ndarray) -> np.ndarray:
"""Dot product of every pair of vectors. V: (n, m, k) -> (n, m (m - 1) / 2), pairs in row-major order
of the strict lower triangle: (1, 0), (2, 0), (2, 1), (3, 0), ..."""
rows, cols = np.tril_indices(V.shape[1], k=-1)
return (V @ V.transpose(0, 2, 1))[:, rows, cols]
class DLRM:
"""Click-through-rate model over dense features and categorical fields."""
def __init__(self, config: DLRMConfig | None = None) -> None:
self.config = config or DLRMConfig()
self.params: dict[str, np.ndarray] = {}
self.field_dims_: tuple = ()
self.loss_history: list[float] = []
def _init_params(self, X_dense: np.ndarray, X_sparse: np.ndarray) -> None:
cfg = self.config
rng = np.random.default_rng(cfg.seed)
self.field_dims_, self._offsets = _field_offsets(X_sparse, cfg.field_dims)
self._n_dense = X_dense.shape[1]
if self._n_dense == 0:
raise ValueError("DLRM needs at least one dense feature for the bottom MLP")
k, m = cfg.embedding_size, len(self.field_dims_) + 1
self.params = {"E": rng.normal(0.0, 1.0 / np.sqrt(k), size=(sum(self.field_dims_), k))}
_mlp_init(self.params, "bottom.", [self._n_dense, *cfg.bottom_sizes, k], rng)
_mlp_init(self.params, "top.", [k + m * (m - 1) // 2, *cfg.top_sizes, 1], rng)
self._n_bottom, self._n_top = len(cfg.bottom_sizes) + 1, len(cfg.top_sizes) + 1
self._tril = np.tril_indices(m, k=-1)
def _forward(self, X_dense: np.ndarray, X_sparse: np.ndarray):
p = self.params
X_dense, X_sparse = np.asarray(X_dense, dtype=float), np.asarray(X_sparse, dtype=int)
if X_dense.shape[1] != self._n_dense or X_sparse.shape[1] != len(self.field_dims_):
raise ValueError("the inputs do not have the number of columns the model was built with")
if X_sparse.size and ((X_sparse >= np.array(self.field_dims_)[None, :]).any() or X_sparse.min() < 0):
raise ValueError("X_sparse holds an id outside the field sizes the model was built with")
idx = X_sparse + self._offsets[None, :]
bottom = _mlp_forward(p, "bottom.", X_dense, self._n_bottom, last_linear=False)
V = np.concatenate([bottom[-1][:, None, :], p["E"][idx]], axis=1) # (n, F + 1, k)
top_in = np.hstack([bottom[-1], pairwise_dots(V)])
top = _mlp_forward(p, "top.", top_in, self._n_top, last_linear=True)
return top[-1][:, 0], (idx, bottom, V, top)
def loss_and_grads(self, X_dense: np.ndarray, X_sparse: np.ndarray, y: np.ndarray) -> tuple[float, dict]:
"""Mean log-loss and its gradients. X_dense: (n, d). X_sparse: (n, F) ids. y: (n,) 0/1 labels."""
p, k = self.params, self.config.embedding_size
logit, (idx, bottom, V, top) = self._forward(X_dense, X_sparse)
loss, d = _bce(logit, np.asarray(y, dtype=float))
grads: dict[str, np.ndarray] = {}
dtop_in = _mlp_backward(p, "top.", top, d[:, None], grads, last_linear=True)
m = V.shape[1]
dZ = np.zeros((len(V), m, m)) # gradient at the matrix of dot products V V^T
dZ[:, self._tril[0], self._tril[1]] = dtop_in[:, k:]
dV = (dZ + dZ.transpose(0, 2, 1)) @ V
_mlp_backward(p, "bottom.", bottom, dtop_in[:, :k] + dV[:, 0, :], grads, last_linear=False)
grads["E"] = np.zeros_like(p["E"])
np.add.at(grads["E"], idx, dV[:, 1:, :])
return loss, grads
def fit(self, X_dense: np.ndarray, X_sparse: np.ndarray, y: np.ndarray) -> "DLRM":
"""Train with mini-batch Adam.
X_dense: (n, d) float features, d >= 1. X_sparse: (n, F) one integer id per field. y: (n,) 0/1 labels.
"""
X_dense, X_sparse = np.asarray(X_dense, dtype=float), np.asarray(X_sparse, dtype=int)
self._init_params(X_dense, X_sparse)
_adam_fit(self, (X_dense, X_sparse), np.asarray(y, dtype=float))
return self
def predict_proba(self, X_dense: np.ndarray, X_sparse: np.ndarray) -> np.ndarray:
"""Probability of a positive label, (n,)."""
return _sigmoid(self._forward(X_dense, X_sparse)[0])
def predict(self, X_dense: np.ndarray, X_sparse: np.ndarray) -> np.ndarray:
"""0/1 labels at probability 0.5, (n,)."""
return (self._forward(X_dense, X_sparse)[0] >= 0).astype(int)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 6, run with
python3 -m unittest -v
Practice
Call pairwise_dots on an array of shape (1, 3, 2) holding the three vectors above and check the output order and values. Then fit DLRM on the README data, where a click needs the user and item to be in the same group, and compare accuracy for embedding_size=2 and embedding_size=8.
Check on learning
- Why must the bottom MLP output a vector of exactly the embedding size?
A way to think about it
Look at what operation comes next and what it requires of its two arguments.
- A user and an item were never seen together in training. How can the model still give a sensible score for the pair?
A way to think about it
Each embedding is trained from all the rows in which its id appears. Think about what the dot product of two separately trained vectors can express.
- What would the model lose if you dropped the dot products and fed the concatenated embeddings straight into the top MLP?
A way to think about it
The MLP would have to learn multiplication between coordinates from weighted sums and ReLUs. Consider the data needed, and compare with the cross layers or factorization machines you may have seen.
- With 26 sparse fields, how many interaction terms does the top MLP receive, and what does that suggest about scaling to hundreds of fields?
A way to think about it
Use with and then with .