Overview
A dot product collapses user and item into one number in one fixed way. Instead, LSS lets each tower output several vectors and compares every user vector with every item vector. A small network then learns how to read that grid of similarities, rather than you hand-picking a rule like "sum of max matches".
A short history
LSS comes from the same FIT paper, published by Ant Group in 2025. Earlier late-interaction models, ColBERT in search and then IntTower and RankTower in recommendation, compared several vectors per side but combined the similarities with a fixed rule such as sum of maxima. LSS replaces that fixed rule with a small learned network.
How it works
- The user tower outputs vectors (matrix ) and the item tower outputs vectors (matrix ).
- Compute the similarity matrix between them.
- Flatten and pass it through a few shallow fully connected layers.
- The output is the user-item score, trained with your usual loss (for example, click/no-click cross-entropy).
Watch out for
- The score is no longer one dot product, so you cannot use a standard ANN index (FAISS and similar) for billion-scale retrieval. Keep a dot-product retrieval stage in front and use LSS after it.
- Latency grows with ; keep both small.
- Overfitting is easy with a big MLP; "lightweight" is the point.
Use cases
When to use it
You are scoring hundreds to thousands of candidates (pre-ranking) and a single dot product leaves accuracy on the table.
In industry
- Payments and super-apps
- The final scoring step of a pre-ranker that must score hundreds to thousands of candidates within a few milliseconds.
- E-commerce
- Re-scoring retrieved products when a user has several distinct interests that a single vector blurs together.
- Advertising
- Pre-ranking ad candidates where a small accuracy gain before the main ranker is worth a modest latency cost.
Choosing it: what must hold
- A retrieval stage in front that already cuts the catalogue to at most a few thousand candidates.
- Towers that can output several vectors per side, with both counts kept small.
- A latency budget measured per batch, since cost grows with the product of the two counts.
When to choose something else
| If | Use instead |
|---|---|
| You need to search billions of items with an index | A single dot product with approximate nearest-neighbour search |
| You want late interaction with no extra parameters | The sum-max rule |
Math foundations
The similarity matrix
Every user vector compared with every item vector. A plain two-tower model is the special case , where is a single number.
The learned score
The grid is flattened and a small network turns it into a probability. The network decides which entries of matter and how they combine.
What it replaces
The fixed rule used by earlier late-interaction models: for each user vector take its best item match, then add. LSS can learn this rule and others that it cannot express.
The training loss
Binary cross-entropy on click or no click. Its gradient flows through the MLP into and from there into both towers.
Symbols
- the user tower's output vectors, one per row
- the item tower's output vectors, one per row
- the matrix of similarities
- flattened into one vector of length
- the sigmoid function
- predicted probability and the true label (1 for a click)
Worked by hand
With , suppose the similarity matrix is with rows and .
Sum-max sees only the two largest entries and returns 1.7. LSS receives all four numbers, so it can also react to the off-diagonal entries, for example to whether two user interests match the same item aspect.
Visual example
Loading the example.
Try this
- Switch the rule to the average one: now the single dot product is enough and LSS adds nothing.
- Choose the rule with exactly one match, lower the hidden units to 1, then raise them to 8.
- Click the similarity matrix stage, then move through the pairs and compare S with the label.
Code sample
from impl import DotProductHead, LSSHead, auc, make_pattern_data
from config import LSSConfig
cfg = LSSConfig(user_vectors=3, item_vectors=3, hidden_sizes=(32, 16), epochs=30)
U, I, y = make_pattern_data(n=2000, seed=0) # U: (2000, 3, 4), I: (2000, 3, 4), y: (2000,)
U_test, I_test, y_test = make_pattern_data(n=1000, seed=1)
lss = LSSHead(cfg).fit(U, I, y)
dot = DotProductHead(cfg).fit(U, I, y)
print(auc(y_test, lss.forward(U_test, I_test))) # close to 1
print(auc(y_test, dot.forward(U_test, I_test))) # close to 0.5
loss, grads, grad_U, grad_I = lss.backward(U[:8], I[:8], y[:8]) # grad_U and grad_I go to the towersRead the implementation (230 lines)
"""Lightweight Similarity Scorer (LSS): the late-interaction block of the FIT two-tower pre-ranking model.
A plain two-tower model ends in one dot product of one user vector and one item vector. LSS lets each tower
output several vectors and learns how to read all their pairwise similarities:
U: user tower output, m vectors of size d (m x d)
I: item tower output, n vectors of size d (n x d)
S = U I^T (m x n similarity matrix)
y_hat = sigmoid(MLP(vec(S))) a few shallow fully connected layers
trained with binary cross-entropy. The towers still run apart, so serving stays two-tower; only the small MLP
runs per user and item pair.
`LSSHead` is that head with manual backpropagation (gradients for the MLP weights and for U and I, so towers
can be trained through it). `DotProductHead` is the classic single dot product with the same interface, for
comparison. NumPy only.
"""
from __future__ import annotations
import numpy as np
try:
from .config import LSSConfig
except ImportError: # run from the template's own folder
from config import LSSConfig
def _sigmoid(x: np.ndarray) -> np.ndarray:
return 0.5 * (1.0 + np.tanh(0.5 * x))
def _bce(logit: np.ndarray, y: np.ndarray) -> float:
"""Mean binary cross-entropy from logits: log(1 + exp(z)) - y * z."""
return float(np.mean(np.logaddexp(0.0, logit) - y * logit))
def auc(y_true, score) -> float:
"""Area under the ROC curve: the chance a random positive is scored above a random negative (ties count half).
y_true: labels in {0, 1}, shape (B,). score: any real scores, shape (B,).
"""
y_true = np.asarray(y_true).astype(bool)
score = np.asarray(score, dtype=float)
n_pos, n_neg = int(y_true.sum()), int((~y_true).sum())
if n_pos == 0 or n_neg == 0:
raise ValueError("auc needs at least one positive and one negative")
order = np.argsort(score, kind="stable")
sorted_scores = score[order]
ranks = np.empty(len(score))
start = 0
while start < len(score): # average rank inside each run of tied scores
end = start
while end + 1 < len(score) and sorted_scores[end + 1] == sorted_scores[start]:
end += 1
ranks[order[start:end + 1]] = 0.5 * (start + end) + 1.0
start = end + 1
return float((ranks[y_true].sum() - n_pos * (n_pos + 1) / 2.0) / (n_pos * n_neg))
class _Head:
"""What both heads share: the public interface and the Adam training loop.
Inputs everywhere: U of shape (B, m, d), I of shape (B, n, d), labels y in {0, 1} of shape (B,).
A subclass fills `self.params` and implements `logits` and `_backward_from_logit`.
"""
def __init__(self, config: LSSConfig | None = None) -> None:
self.config = config or LSSConfig()
self.params: dict[str, np.ndarray] = {}
self.history: list[float] = []
def _check(self, U, I):
cfg = self.config
U, I = np.asarray(U, dtype=float), np.asarray(I, dtype=float)
if U.ndim != 3 or I.ndim != 3 or U.shape[0] != I.shape[0] or U.shape[2] != I.shape[2]:
raise ValueError(f"need U of shape (B, m, d) and I of shape (B, n, d), got {U.shape} and {I.shape}")
if U.shape[1] != cfg.user_vectors or I.shape[1] != cfg.item_vectors:
raise ValueError(
f"config expects {cfg.user_vectors} user and {cfg.item_vectors} item vectors, "
f"got {U.shape[1]} and {I.shape[1]}"
)
return U, I
def forward(self, U, I) -> np.ndarray:
"""y_hat, the predicted probability of a positive label, shape (B,)."""
return _sigmoid(self.logits(U, I))
predict_proba = forward
def loss(self, U, I, y) -> float:
"""Mean binary cross-entropy."""
return _bce(self.logits(U, I), np.asarray(y, dtype=float))
def backward(self, U, I, y):
"""Loss and all gradients for one batch.
Returns (loss, grads, grad_U, grad_I): grads maps each name in `self.params` to d loss / d that array;
grad_U has the shape of U and grad_I the shape of I (what the towers would receive).
"""
U, I = self._check(U, I)
y = np.asarray(y, dtype=float)
logit = self.logits(U, I)
d_logit = (_sigmoid(logit) - y) / len(y)
grads, grad_U, grad_I = self._backward_from_logit(U, I, d_logit)
return _bce(logit, y), grads, grad_U, grad_I
def fit(self, U, I, y):
"""Train the head's own weights with Adam on fixed tower outputs. Mean loss per epoch goes to `history`."""
cfg = self.config
U, I = self._check(U, I)
y = np.asarray(y, dtype=float)
rng = np.random.default_rng(cfg.seed)
m = {k: np.zeros_like(v) for k, v in self.params.items()}
v = {k: np.zeros_like(v) for k, v in self.params.items()}
step = 0
for _ in range(cfg.epochs):
order = rng.permutation(len(y))
losses = []
for start in range(0, len(y), cfg.batch_size):
idx = order[start:start + cfg.batch_size]
loss, grads, _, _ = self.backward(U[idx], I[idx], y[idx])
losses.append(loss)
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
m_hat = m[name] / (1.0 - 0.9**step)
v_hat = v[name] / (1.0 - 0.999**step)
self.params[name] = self.params[name] - cfg.learning_rate * m_hat / (np.sqrt(v_hat) + 1e-8)
self.history.append(float(np.mean(losses)))
return self
class LSSHead(_Head):
"""y_hat = sigmoid(MLP(vec(U I^T))). ReLU hidden layers of widths config.hidden_sizes.
params: "W0", "b0", "W1", "b1", ... The first layer reads the m * n flattened similarities, the last
layer outputs one logit.
"""
def __init__(self, config: LSSConfig | None = None) -> None:
super().__init__(config)
cfg = self.config
rng = np.random.default_rng(cfg.seed)
sizes = [cfg.user_vectors * cfg.item_vectors, *cfg.hidden_sizes, 1]
self.n_layers = len(sizes) - 1
for layer in range(self.n_layers):
fan_in, fan_out = sizes[layer], sizes[layer + 1]
self.params[f"W{layer}"] = rng.normal(0.0, np.sqrt(2.0 / fan_in), size=(fan_in, fan_out))
self.params[f"b{layer}"] = np.zeros(fan_out)
def similarity(self, U, I) -> np.ndarray:
"""S = U I^T for every row of the batch, shape (B, m, n)."""
U, I = self._check(U, I)
return U @ I.transpose(0, 2, 1)
def _activations(self, U, I) -> list[np.ndarray]:
"""[vec(S), hidden 1, ..., logit column]: the input of every layer plus the final output."""
S = self.similarity(U, I)
acts = [S.reshape(len(S), -1)]
for layer in range(self.n_layers):
z = acts[-1] @ self.params[f"W{layer}"] + self.params[f"b{layer}"]
acts.append(np.maximum(z, 0.0) if layer < self.n_layers - 1 else z)
return acts
def logits(self, U, I) -> np.ndarray:
"""MLP(vec(S)) before the sigmoid, shape (B,)."""
return self._activations(U, I)[-1][:, 0]
def _backward_from_logit(self, U, I, d_logit):
acts = self._activations(U, I)
grads = {}
delta = d_logit[:, None] # d loss / d (output of the current layer)
for layer in reversed(range(self.n_layers)):
if layer < self.n_layers - 1:
delta = delta * (acts[layer + 1] > 0) # through the ReLU
grads[f"W{layer}"] = acts[layer].T @ delta
grads[f"b{layer}"] = delta.sum(axis=0)
delta = delta @ self.params[f"W{layer}"].T
d_S = delta.reshape(U.shape[0], U.shape[1], I.shape[1]) # d loss / d S, shape (B, m, n)
grad_U = d_S @ I # S = U I^T => dU = dS I
grad_I = d_S.transpose(0, 2, 1) @ U # dI = dS^T U
return grads, grad_U, grad_I
class DotProductHead(_Head):
"""The classic two-tower score: y_hat = sigmoid(a * (u . i) + b).
u is the mean of the m user vectors and i the mean of the n item vectors, so u . i is the mean of all
entries of S. params: "a" (scale) and "b" (bias), each of shape (1,).
"""
def __init__(self, config: LSSConfig | None = None) -> None:
super().__init__(config)
self.params = {"a": np.ones(1), "b": np.zeros(1)}
def logits(self, U, I) -> np.ndarray:
U, I = self._check(U, I)
dot = (U.mean(axis=1) * I.mean(axis=1)).sum(axis=1)
return self.params["a"][0] * dot + self.params["b"][0]
def _backward_from_logit(self, U, I, d_logit):
u, i = U.mean(axis=1), I.mean(axis=1)
dot = (u * i).sum(axis=1)
a = self.params["a"][0]
grads = {"a": np.array([(d_logit * dot).sum()]), "b": np.array([d_logit.sum()])}
d_u = (d_logit * a)[:, None] * i # (B, d)
d_i = (d_logit * a)[:, None] * u
grad_U = np.repeat(d_u[:, None, :], U.shape[1], axis=1) / U.shape[1]
grad_I = np.repeat(d_i[:, None, :], I.shape[1], axis=1) / I.shape[1]
return grads, grad_U, grad_I
def make_pattern_data(n: int = 2000, user_vectors: int = 3, item_vectors: int = 3, dim: int = 4, seed: int = 0):
"""Synthetic tower outputs whose label a single dot product cannot read.
U and I are standard normal. The label is 1 when the "matched" similarities beat the "crossed" ones:
S[0, 0] + S[1, 1] > S[0, 1] + S[1, 0]
The mean of S (all a pooled dot product sees) weighs those four entries equally, so it carries no
information about the label, while a head that reads S entry by entry can learn it.
Returns (U, I, y) with shapes (n, m, dim), (n, n_item, dim), (n,).
"""
if user_vectors < 2 or item_vectors < 2:
raise ValueError("the pattern needs at least 2 user and 2 item vectors")
rng = np.random.default_rng(seed)
U = rng.normal(size=(n, user_vectors, dim))
I = rng.normal(size=(n, item_vectors, dim))
S = U @ I.transpose(0, 2, 1)
y = (S[:, 0, 0] + S[:, 1, 1] > S[:, 0, 1] + S[:, 1, 0]).astype(float)
return U, I, y- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Put a ScoringHead interface in ModelManager with two versions, DotProductHead and LSSHead. Train both on the same data, compare AUC and per-batch latency, and record both in your evaluation log.
Check on learning
- A single dot product can be served from an approximate nearest-neighbour index and LSS cannot. What property of the dot product does the index rely on that an MLP over breaks?
A way to think about it
An index finds the items whose single vector is closest to a single query vector. Ask whether the LSS score can be written as one inner product between a user vector and an item vector.
- Design a tiny dataset where the label depends on user and item in a way a single dot product cannot express but LSS can.
A way to think about it
Try a label that is 1 only when two different user vectors both find a match, or when exactly one of them does. Check whether any single pair of vectors could reproduce it.
- LSS at beats a dot product by a small margin offline but doubles scoring latency. How would you decide whether to ship it?
A way to think about it
Translate the accuracy gain into what it changes for the candidates passed to the next stage, and compare with what the latency costs in candidates you can no longer score.
- Why is a large MLP on top of likely to overfit, when the towers below it have far more parameters?
A way to think about it
Consider how few numbers contains and how directly the MLP sees the label. A big network can memorise patterns in inputs that are specific to the training pairs.