Overview
In click prediction the signal often sits in combinations: this user group together with this item type. A standard network of weighted sums and ReLUs can approximate such products, but it learns them slowly. A cross layer builds them directly. It takes the current feature vector, mixes it with a weight matrix, and multiplies the result element by element with the original input. Every layer therefore raises the degree of the feature products by one. A normal deep network runs beside or after the cross layers to pick up patterns that are not simple products.
A short history
Ruoxi Wang and colleagues at Google introduced the Deep & Cross Network in 2017 to learn feature crosses automatically, instead of writing them by hand as in Wide & Deep. The second version, DCN-V2, published in 2021, replaced the original low-capacity cross layer with a full weight matrix and a low-rank variant that is cheap enough to serve. The authors reported that it was deployed in ranking systems at Google.
How it works
- Look up an embedding for each sparse field and concatenate them with the dense features into one vector .
- Apply the cross layers in turn: .
- Run a ReLU MLP. With
structure=\"parallel\"it reads , with\"stacked\"it reads the output of the last cross layer. - Combine: in the parallel form, concatenate the cross output and the MLP output. In the stacked form, use the MLP output alone.
- Apply a final linear layer and a sigmoid to get the click probability.
- Train all weights and embeddings with Adam on the binary cross-entropy loss.
Watch out for
- Each cross matrix has weights, where is the length of . With many fields or large embeddings this grows quickly. The original method offers a low-rank form that this template does not include.
- Dense features on large scales are multiplied with each other in every cross layer, so values and gradients can blow up. Standardise the dense inputs.
- More cross layers mean higher-degree products, which fit noise easily on small data. Start with one or two layers.
- An id outside the size given in
field_dimsraises an error at prediction time, so ids unseen in training need a reserved slot.
Use cases
When to use it
Click-through-rate and ranking models over mixed dense and categorical features, where products of features carry the signal and you do not want to hand-craft the crosses.
In industry
- Online advertising
- Click-through rate prediction, where combinations such as user country with ad category matter more than either feature alone.
- App and content stores
- Ranking candidates for a user from many sparse id features and their interactions.
- E-commerce
- Predicting purchase probability from crossed features such as user segment, product category and time of day.
Choosing it: what must hold
- Many sparse categorical features whose combinations carry signal.
- A large log of labelled interactions (clicks, installs, purchases) to train embeddings.
- An embedding layer and serving stack that can handle large id vocabularies.
When to choose something else
| If | Use instead |
|---|---|
| You already know the important crosses and want them explicit | Wide & Deep |
| Second-order interactions are enough | DeepFM |
| The user's behaviour history is the main signal | Deep Interest Network (DIN) |
| The table is small and has no high-cardinality ids | Gradient boosted trees such as CatBoost |
Math foundations
The input vector
The dense features and the embedding of each sparse field, joined end to end. Everything after this works on one vector of length .
Cross layer
A linear mix of the current features, multiplied element by element with the original input, plus a skip connection that keeps the lower-degree terms.
What one layer computes
Written out for the first layer: every pairwise product appears with its own weight . After layers the output holds feature products up to degree .
Jacobian of a cross layer
The factor backpropagation multiplies by. The identity term comes from the skip connection and gives gradients a direct path through the stack.
Output and loss
is the cross output joined with the MLP output (parallel) or the MLP output alone (stacked). The loss is the binary cross-entropy.
Symbols
- the input vector: dense features and embeddings
- embedding of sparse field f
- length of the input vector
- output of cross layer l
- weight matrix (D by D) and bias of cross layer l
- element-wise product
- n_cross_layers
- the vector fed to the output layer
- the sigmoid function
- predicted click probability and true label (0 or 1)
Worked by hand
One cross layer on with having rows and , and zero bias. This swaps the two features.
Both outputs now contain the product plus the original feature. One layer has produced a degree-2 cross without any hand-made feature.
Visual example
Loading the example.
Try this
- Set n_cross_layers to 0: the model is a straight line and cannot follow the product pattern at all.
- Switch the pattern to the three way product and step the layers from 1 to 2 to see degree 3 arrive.
- Choose a cross layer in the diagram to read its sum for the test point.
Code sample
import numpy as np
from impl import DCN
from config import DCNConfig
rng = np.random.default_rng(0)
X_dense = rng.normal(size=(1500, 3))
X_sparse = rng.integers(0, 6, size=(1500, 1)) # one categorical field with 6 ids
sign = np.where(X_sparse[:, 0] < 3, 1.0, -1.0)
y = (X_dense[:, 0] * sign > 0).astype(int) # a dense x categorical cross
model = DCN(DCNConfig(structure="parallel", epochs=20)).fit(X_dense, X_sparse, y)
print((model.predict(X_dense, X_sparse) == y).mean())Read the implementation (200 lines)
"""DCN: Deep & Cross Network v2, which learns explicit feature crosses next to a deep network.
NumPy only, manual backpropagation. Dense features and the embeddings of the sparse fields are concatenated
into x0. Each cross layer multiplies the running vector by x0 once more, raising the polynomial degree of the
feature interactions by one:
x_{l+1} = x0 * (x_l W_l + b_l) + x_l
"parallel" structure: the cross stack and an MLP both read x0 and their outputs are concatenated.
"stacked" structure: the MLP reads the output of the cross stack.
"""
from __future__ import annotations
import numpy as np
try:
from .config import DCNConfig
except ImportError: # run from the template's own folder
from config import DCNConfig
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 cross_layer(x0: np.ndarray, x: np.ndarray, W: np.ndarray, b: np.ndarray) -> np.ndarray:
"""One DCN v2 cross layer. x0, x: (n, D). W: (D, D). b: (D,). Returns x0 * (x W + b) + x, shape (n, D)."""
return x0 * (x @ W + b) + x
class DCN:
"""Click-through-rate model over dense features and categorical fields."""
def __init__(self, config: DCNConfig | None = None) -> None:
self.config = config or DCNConfig()
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]
D = self._n_dense + len(self.field_dims_) * cfg.embedding_size
if D == 0:
raise ValueError("the model needs at least one dense feature or one sparse field")
self.params = {"E": rng.normal(0.0, 0.1, size=(sum(self.field_dims_), cfg.embedding_size))}
for l in range(cfg.n_cross_layers):
self.params[f"cross.W{l}"] = rng.normal(0.0, np.sqrt(1.0 / D), size=(D, D))
self.params[f"cross.b{l}"] = np.zeros(D)
_mlp_init(self.params, "deep.", [D, *cfg.hidden_sizes], rng)
final = cfg.hidden_sizes[-1] + (D if cfg.structure == "parallel" else 0)
self.params["out.w"] = rng.normal(0.0, np.sqrt(1.0 / final), size=final)
self.params["out.b"] = np.zeros(1)
def _inputs(self, X_dense, X_sparse) -> tuple[np.ndarray, np.ndarray]:
"""Normalise the two inputs: either may be None when the model has no features of that kind."""
n = len(X_dense) if X_dense is not None else len(X_sparse)
X_dense = np.zeros((n, 0)) if X_dense is None else np.asarray(X_dense, dtype=float)
X_sparse = np.zeros((n, 0), dtype=int) if X_sparse is None else np.asarray(X_sparse, dtype=int)
return X_dense, X_sparse
def _forward(self, X_dense: np.ndarray, X_sparse: np.ndarray):
cfg, p = self.config, self.params
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, :]
x0 = np.hstack([X_dense, p["E"][idx].reshape(len(idx), -1)])
xs, us = [x0], []
for l in range(cfg.n_cross_layers):
u = xs[-1] @ p[f"cross.W{l}"] + p[f"cross.b{l}"]
us.append(u)
xs.append(x0 * u + xs[-1])
deep_in = x0 if cfg.structure == "parallel" else xs[-1]
acts = _mlp_forward(p, "deep.", deep_in, len(cfg.hidden_sizes), last_linear=False)
final = np.hstack([xs[-1], acts[-1]]) if cfg.structure == "parallel" else acts[-1]
return final @ p["out.w"] + p["out.b"][0], (idx, xs, us, acts, final)
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."""
cfg, p = self.config, self.params
logit, (idx, xs, us, acts, final) = self._forward(X_dense, X_sparse)
loss, d = _bce(logit, np.asarray(y, dtype=float))
grads = {"out.w": final.T @ d, "out.b": np.array([d.sum()])}
dfinal = np.outer(d, p["out.w"])
D = xs[0].shape[1]
if cfg.structure == "parallel":
dx = dfinal[:, :D] # into the cross stack
dx0 = _mlp_backward(p, "deep.", acts, dfinal[:, D:], grads, last_linear=False)
else:
dx = _mlp_backward(p, "deep.", acts, dfinal, grads, last_linear=False)
dx0 = np.zeros_like(xs[0])
for l in range(cfg.n_cross_layers - 1, -1, -1):
du = dx * xs[0]
dx0 = dx0 + dx * us[l]
grads[f"cross.W{l}"] = xs[l].T @ du
grads[f"cross.b{l}"] = du.sum(axis=0)
dx = dx + du @ p[f"cross.W{l}"].T
dx0 = dx0 + dx
grads["E"] = np.zeros_like(p["E"])
if idx.size:
np.add.at(grads["E"], idx, dx0[:, self._n_dense:].reshape(len(idx), idx.shape[1], -1))
return loss, grads
def fit(self, X_dense, X_sparse, y: np.ndarray) -> "DCN":
"""Train with mini-batch Adam.
X_dense: (n, d) float features or None. X_sparse: (n, F) one integer id per field, or None.
y: (n,) 0/1 labels.
"""
X_dense, X_sparse = self._inputs(X_dense, X_sparse)
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, X_sparse) -> np.ndarray:
"""Probability of a positive label, (n,)."""
return _sigmoid(self._forward(*self._inputs(X_dense, X_sparse))[0])
def predict(self, X_dense, X_sparse) -> np.ndarray:
"""0/1 labels at probability 0.5, (n,)."""
return (self._forward(*self._inputs(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 cross_layer(x0, x0, W, b) on the example above and confirm the result. Then build the README data, where the label depends on a dense feature times the sign of a categorical group, and compare the accuracy of DCN with n_cross_layers=1 and n_cross_layers=3, and with structure set to parallel and to stacked.
Check on learning
- A ReLU network can in principle approximate a product of two inputs. Why add cross layers at all?
A way to think about it
Think about how many ReLU units are needed to approximate multiplication over a range, and how much data it takes to learn that from scratch, compared with one multiplication built into the layer.
- Why does the cross layer multiply by the original input and not by itself? What would happen to the degree of the products in each case?
A way to think about it
Track the highest polynomial degree after 1, 2 and 3 layers under each rule. One grows by one per layer, the other doubles.
- In the parallel structure the MLP never sees the crossed features. In the stacked structure it does. When might each be the better choice?
A way to think about it
Ask whether the useful signal is a simple low-degree product, or something more complex built on top of products.
- If you removed the skip connection from the cross layer, what would be lost from the output?
A way to think about it
Expand one layer without the added term and list which degrees of product remain. Check whether the plain first-order features are still there.