Overview
A plain two-tower model never lets the user side see anything about items until the final dot product. MQM gives the model a small, learned set of "item archetypes" (meta vectors), like learned clusters of item types. Each item maps to its closest archetype, and the user side can interact with those archetypes. You get some cross-tower signal while item embeddings stay precomputable.
A short history
MQM comes from the FIT paper, A Learnable Fully Interacted Two-Tower Model for Pre-Ranking System, published by Ant Group in 2025. Two-tower models had long been the standard for pre-ranking because item vectors can be computed ahead of time, at the cost of the towers never exchanging information. MQM is FIT's answer on the early side: a learned set of item archetypes the user side can interact with.
How it works
- Learn an item meta matrix with rows (meta vectors) of dimension .
- For an item, score its concatenated attribute embedding against every meta vector to get similarity scores .
- Training (soft query): blend the meta vectors with a softmax over , using a temperature that decays over training. Early on, many vectors update, which helps convergence.
- As approaches 0, the blend sharpens into picking one vector.
- Inference (hard query): take the single best-matching meta vector (argmax).
Watch out for
- N is a tuning knob: too few archetypes blur items together, too many weaken generalization.
- If decays too fast, most meta vectors stop training early and sit unused. Log how often each vector gets picked.
- The soft (train) and hard (inference) paths differ, so evaluate the hard path offline before shipping.
Use cases
When to use it
A two-tower pre-ranker underfits because the towers never exchange information, but you still need cached item embeddings for speed.
In industry
- Payments and super-apps
- Pre-ranking thousands of candidate services or offers per request, where item vectors must be cached but accuracy from a plain two-tower model has stalled.
- E-commerce
- Narrowing a retrieved set of products to a few hundred before the heavy ranking model, with some user and item interaction added cheaply.
- Short video and feeds
- Pre-ranking candidate posts where items arrive constantly and their embeddings need to be computed once, offline.
Choosing it: what must hold
- A two-tower pre-ranker already in place, with item embeddings cached.
- Evidence that the towers' late meeting is what limits accuracy.
- Room to tune the number of meta vectors and the temperature schedule, and to monitor usage.
When to choose something else
| If | Use instead |
|---|---|
| You can afford to score each pair with a full interaction model | A cross-feature ranking model such as DCN or DeepFM |
| A plain two-tower model already meets the accuracy target | Keep the plain two-tower model |
Math foundations
Scoring an item against the archetypes
One similarity score per meta vector. A high means the item looks like archetype .
The soft query used during training
A softmax-weighted blend of all the meta vectors. Because every vector takes part, every vector receives a gradient, which is what lets the archetypes learn.
The hard query used at inference
The single best-matching meta vector. It is the limit of the soft query as goes to 0, so training with a decaying temperature closes the gap between the two paths.
Symbols
- item meta matrix, rows of dimension
- meta vector , one learned item archetype
- the item's concatenated attribute embedding
- similarity between the item and meta vector
- temperature, decayed over training
- the soft and the hard queried meta vector
Worked by hand
Three meta vectors score for an item. Compare the blend weights at and at .
At all three archetypes are blended and all three learn. At the blend is already almost the hard pick of the first vector.
Visual example
Loading the example.
Try this
- Press Run and watch the soft query (the dot) close in on the hard query (the ring) as τ falls.
- Set the temperature at the end to 1 and train again: the dot stays away from the ring.
- Set the temperature at the start to 0.2 and at the end to 0.02, train, and count the hollow squares.
Code sample
import numpy as np
from impl import MetaQueryModule, MQMClickModel, make_click_data
from config import MQMConfig
cfg = MQMConfig(n_meta=8, dim=8)
mqm = MetaQueryModule(cfg)
e_c = np.random.default_rng(0).normal(size=(5, 8)) # 5 items, concatenated attribute embeddings
soft = mqm.forward(e_c, tau=mqm.tau_at(step=0, total_steps=100)) # training path, shape (5, 8)
grad_Q, grad_e = mqm.backward(np.ones_like(soft)) # gradients for Q and for e_c
hard = mqm.forward(e_c, hard=True) # inference path: one row of Q per item
print(mqm.usage_histogram(e_c), mqm.dead_vectors(e_c))
users, attrs, y = make_click_data(n=3000) # the training demonstration
model = MQMClickModel(cfg, attr_vocab_sizes=(12, 6), n_users=40).fit(users, attrs, y, epochs=25)
print(model.history[0], model.history[-1]) # loss falls, soft and hard convergeRead the implementation (280 lines)
"""Meta Query Module (MQM): the early-interaction block of the FIT two-tower pre-ranking model.
A two-tower model scores a user and an item from two vectors computed apart, so the user tower never sees the
item. MQM gives the user tower a small, cheap view of the item: a learned meta matrix Q with N rows (meta
vectors) of size D. For an item with concatenated attribute embedding e_c:
k_i = sim(e_c, q_i) similarity to every meta vector
soft: q_tilde = sum_i softmax(k / tau)_i q_i used in training, differentiable
hard: q_tilde = q_argmax(k) used at inference, one row of Q
The temperature tau decays during training, so the soft blend sharpens into the single best row and training
matches inference. Because the hard query returns one of only N vectors, the user tower can be run once per meta
vector instead of once per item.
`MetaQueryModule` is the module with manual gradients. `MQMClickModel` is a small click model that shows it
training; its user-side wiring is a simple stand-in, not the paper's (see the README). NumPy only.
"""
from __future__ import annotations
import numpy as np
try:
from .config import MQMConfig
except ImportError: # run from the template's own folder
from config import MQMConfig
_EPS = 1e-12
def _sigmoid(x: np.ndarray) -> np.ndarray:
return 0.5 * (1.0 + np.tanh(0.5 * x))
class MetaQueryModule:
"""Holds the meta matrix Q, shape (N, D), and answers soft and hard queries.
All item inputs `e` have shape (B, D): one concatenated attribute embedding per item of the batch.
"""
def __init__(self, config: MQMConfig | None = None) -> None:
self.config = config or MQMConfig()
rng = np.random.default_rng(self.config.seed)
self.Q = rng.normal(0.0, self.config.init_scale, size=(self.config.n_meta, self.config.dim))
self._cache = None
# ---- similarity -------------------------------------------------------------------------------------
def similarities(self, e: np.ndarray) -> np.ndarray:
"""k[b, i] = sim(e[b], Q[i]). e: shape (B, D). Returns shape (B, N)."""
e = self._check(e)
if self.config.similarity == "cosine":
e_hat = e / (np.linalg.norm(e, axis=1, keepdims=True) + _EPS)
q_hat = self.Q / (np.linalg.norm(self.Q, axis=1, keepdims=True) + _EPS)
return e_hat @ q_hat.T
return e @ self.Q.T
def _check(self, e: np.ndarray) -> np.ndarray:
e = np.asarray(e, dtype=float)
if e.ndim != 2 or e.shape[1] != self.config.dim:
raise ValueError(f"e must have shape (B, {self.config.dim}), got {e.shape}")
return e
# ---- queries ----------------------------------------------------------------------------------------
def forward(self, e: np.ndarray, tau: float | None = None, hard: bool = False) -> np.ndarray:
"""Query the meta matrix.
e: item embeddings, shape (B, D).
tau: softmax temperature of the soft query (defaults to config.tau_end). Ignored when hard.
hard: False gives the soft blend used in training, True the single best row used at inference.
Returns q_tilde, shape (B, D).
"""
e = self._check(e)
k = self.similarities(e)
if hard:
self._cache = None # the hard query has no gradient
return self.Q[k.argmax(axis=1)]
tau = self.config.tau_end if tau is None else float(tau)
if tau <= 0:
raise ValueError(f"tau must be positive, got {tau}")
z = k / tau
z = z - z.max(axis=1, keepdims=True)
p = np.exp(z)
p /= p.sum(axis=1, keepdims=True)
self._cache = (e, k, p, tau)
return p @ self.Q
def attention(self) -> np.ndarray:
"""softmax(k / tau) of the last soft query, shape (B, N)."""
if self._cache is None:
raise RuntimeError("run a soft forward first")
return self._cache[2]
def backward(self, grad_output: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Backpropagate through the last soft query.
grad_output: d loss / d q_tilde, shape (B, D).
Returns (grad_Q, grad_e): d loss / d Q, shape (N, D), and d loss / d e, shape (B, D).
"""
if self._cache is None:
raise RuntimeError("backward needs a soft forward first (the hard query has no gradient)")
e, k, p, tau = self._cache
g = np.asarray(grad_output, dtype=float)
grad_Q = p.T @ g # q_tilde = p @ Q, the direct path into Q
gq = g @ self.Q.T # (B, N): d loss / d p
grad_k = p * (gq - (p * gq).sum(axis=1, keepdims=True)) / tau # through the softmax
if self.config.similarity == "cosine":
e_norm = np.linalg.norm(e, axis=1, keepdims=True) + _EPS
q_norm = np.linalg.norm(self.Q, axis=1, keepdims=True) + _EPS
e_hat, q_hat = e / e_norm, self.Q / q_norm
gk_k = grad_k * k
grad_e = (grad_k @ q_hat - gk_k.sum(axis=1, keepdims=True) * e_hat) / e_norm
grad_Q = grad_Q + (grad_k.T @ e_hat - gk_k.sum(axis=0)[:, None] * q_hat) / q_norm
else:
grad_e = grad_k @ self.Q
grad_Q = grad_Q + grad_k.T @ e
return grad_Q, grad_e
# ---- temperature schedule ---------------------------------------------------------------------------
def tau_at(self, step: int, total_steps: int) -> float:
"""Temperature at a training step: exponential decay from tau_start (step 0) to tau_end (last step).
tau = tau_start * (tau_end / tau_start) ** (step / (total_steps - 1)), held at tau_end afterwards.
"""
cfg = self.config
if total_steps <= 1:
return cfg.tau_end
frac = min(max(step / (total_steps - 1), 0.0), 1.0)
return float(cfg.tau_start * (cfg.tau_end / cfg.tau_start) ** frac)
# ---- inference diagnostics --------------------------------------------------------------------------
def hard_indices(self, e: np.ndarray) -> np.ndarray:
"""Which meta vector each item picks at inference. e: shape (B, D). Returns ints, shape (B,)."""
return self.similarities(e).argmax(axis=1)
def usage_histogram(self, e: np.ndarray) -> np.ndarray:
"""How many of the items pick each meta vector at inference. Returns counts, shape (N,)."""
return np.bincount(self.hard_indices(e), minlength=self.config.n_meta)
def dead_vectors(self, e: np.ndarray) -> np.ndarray:
"""Indices of meta vectors that no item picks at inference (wasted rows of Q)."""
return np.flatnonzero(self.usage_histogram(e) == 0)
def soft_hard_gap(self, e: np.ndarray, tau: float) -> float:
"""Mean Euclidean distance between the soft query at temperature tau and the hard query."""
soft = self.forward(e, tau=tau)
hard = self.forward(e, hard=True)
return float(np.linalg.norm(soft - hard, axis=1).mean())
class MQMClickModel:
"""A tiny two-tower click model that uses the Meta Query Module (a training demonstration).
Item side: each item has A categorical attributes. Each attribute has its own embedding table of size
D / A, and the item's vector e_c (size D) is their concatenation.
Query: q_tilde = MQM(e_c), soft while training, hard at inference.
User side: u = tanh([p_user ; q_tilde] W + b), where p_user is a user-id embedding of size D. This is the
stand-in early interaction: the user tower reads the queried meta vector.
Score: y_hat = sigmoid(u . e_c + c), trained with binary cross-entropy and Adam.
attr_vocab_sizes: number of values of each item attribute (its length A must divide config.dim).
n_users: number of user ids.
"""
def __init__(self, config: MQMConfig, attr_vocab_sizes, n_users: int) -> None:
self.config = config
self.attr_vocab_sizes = [int(v) for v in attr_vocab_sizes]
n_attr = len(self.attr_vocab_sizes)
if n_attr == 0 or config.dim % n_attr != 0:
raise ValueError(f"the number of attributes ({n_attr}) must divide dim ({config.dim})")
self.attr_dim = config.dim // n_attr
D = config.dim
rng = np.random.default_rng(config.seed + 1)
self.mqm = MetaQueryModule(config)
self.params = {"Q": self.mqm.Q}
for a, size in enumerate(self.attr_vocab_sizes):
self.params[f"E{a}"] = rng.normal(0.0, 0.5, size=(size, self.attr_dim))
self.params["P"] = rng.normal(0.0, 0.5, size=(n_users, D))
self.params["W"] = rng.normal(0.0, 1.0 / np.sqrt(2 * D), size=(2 * D, D))
self.params["b"] = np.zeros(D)
self.params["c"] = np.zeros(1)
self.history: list[dict] = []
def item_embedding(self, attrs: np.ndarray) -> np.ndarray:
"""e_c for items. attrs: int array, shape (B, A). Returns shape (B, D)."""
attrs = np.asarray(attrs)
return np.concatenate([self.params[f"E{a}"][attrs[:, a]] for a in range(attrs.shape[1])], axis=1)
def _forward(self, users, attrs, tau, hard):
e = self.item_embedding(attrs)
q = self.mqm.forward(e, tau=tau, hard=hard)
x = np.concatenate([self.params["P"][users], q], axis=1)
u = np.tanh(x @ self.params["W"] + self.params["b"])
logit = (u * e).sum(axis=1) + self.params["c"][0]
return e, x, u, logit
def predict_proba(self, users, attrs, tau: float | None = None, hard: bool = True) -> np.ndarray:
"""Click probability, shape (B,). Hard query by default (inference); pass hard=False and tau for soft."""
return _sigmoid(self._forward(np.asarray(users), attrs, tau, hard)[3])
def loss(self, users, attrs, y, tau: float | None = None, hard: bool = True) -> float:
"""Mean binary cross-entropy of the labels y, shape (B,)."""
logit = self._forward(np.asarray(users), attrs, tau, hard)[3]
y = np.asarray(y, dtype=float)
return float(np.mean(np.logaddexp(0.0, logit) - y * logit))
def loss_and_grads(self, users, attrs, y, tau: float) -> tuple[float, dict]:
"""Soft-query loss and its gradient with respect to every entry of `self.params`."""
users, attrs, y = np.asarray(users), np.asarray(attrs), np.asarray(y, dtype=float)
D = self.config.dim
e, x, u, logit = self._forward(users, attrs, tau, hard=False)
loss = float(np.mean(np.logaddexp(0.0, logit) - y * logit))
d_logit = ((_sigmoid(logit) - y) / len(y))[:, None] # (B, 1)
d_pre = d_logit * e * (1.0 - u**2) # through u = tanh(pre)
d_x = d_pre @ self.params["W"].T
grad_Q, d_e_query = self.mqm.backward(d_x[:, D:])
d_e = d_logit * u + d_e_query # the score path plus the query path
grads = {"Q": grad_Q, "W": x.T @ d_pre, "b": d_pre.sum(axis=0), "c": np.array([d_logit.sum()])}
grads["P"] = np.zeros_like(self.params["P"])
np.add.at(grads["P"], users, d_x[:, :D])
for a in range(attrs.shape[1]):
g = np.zeros_like(self.params[f"E{a}"])
np.add.at(g, attrs[:, a], d_e[:, a * self.attr_dim:(a + 1) * self.attr_dim])
grads[f"E{a}"] = g
return loss, grads
def fit(self, users, attrs, y, epochs: int = 40, batch_size: int = 128, learning_rate: float = 0.02):
"""Train with Adam while tau decays from tau_start to tau_end over all steps.
users: int array (n,). attrs: int array (n, A). y: clicks in {0, 1}, shape (n,).
Appends one dict per epoch to `self.history`: epoch, tau, soft_loss (at that tau), hard_loss (inference
path) and gap (mean distance between soft and hard query outputs), all on the training data.
"""
users, attrs, y = np.asarray(users), np.asarray(attrs), np.asarray(y, dtype=float)
rng = np.random.default_rng(self.config.seed + 2)
n = len(y)
steps_per_epoch = int(np.ceil(n / batch_size))
total = epochs * steps_per_epoch
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 epoch in range(epochs):
order = rng.permutation(n)
for start in range(0, n, batch_size):
idx = order[start:start + batch_size]
tau = self.mqm.tau_at(step, total)
_, grads = self.loss_and_grads(users[idx], attrs[idx], y[idx], tau)
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] -= learning_rate * m_hat / (np.sqrt(v_hat) + 1e-8) # in place: Q is shared
tau = self.mqm.tau_at(step - 1, total)
self.history.append({
"epoch": epoch,
"tau": tau,
"soft_loss": self.loss(users, attrs, y, tau=tau, hard=False),
"hard_loss": self.loss(users, attrs, y, hard=True),
"gap": self.mqm.soft_hard_gap(self.item_embedding(attrs), tau),
})
return self
def make_click_data(n: int = 4000, n_users: int = 40, n_groups: int = 4, attr_vocab_sizes=(12, 6),
n_clusters: int = 4, seed: int = 0, taste_seed: int = 0):
"""Synthetic clicks: users fall into groups, items into clusters set by their first attribute, and a
group either likes or dislikes a cluster.
Returns (users, attrs, y): int array (n,), int array (n, A), clicks in {0, 1} of shape (n,).
The click probability is sigmoid(2.5 * taste[group of user, cluster of item]) with taste entries +1 or -1.
seed draws the rows; taste_seed draws the taste matrix, so two seeds with one taste_seed give a training
set and a held-out set from the same world.
"""
taste = np.random.default_rng(taste_seed).choice([-1.0, 1.0], size=(n_groups, n_clusters))
rng = np.random.default_rng(seed)
users = rng.integers(0, n_users, size=n)
attrs = np.stack([rng.integers(0, size, size=n) for size in attr_vocab_sizes], axis=1)
prob = _sigmoid(2.5 * taste[users % n_groups, attrs[:, 0] % n_clusters])
y = (rng.random(n) < prob).astype(float)
return users, attrs, y- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
In ModelManager, build MQM as its own nn.Module. Train with a schedule, then plot a histogram of meta-vector usage at inference to check for dead vectors.
Check on learning
- Why does MQM keep item embeddings precomputable, when letting the user tower read each item's own embedding directly would not?
A way to think about it
Ask what has to be recomputed when a new user arrives. The meta matrix is a fixed, small table that does not depend on which item is being scored.
- Your usage histogram shows 3 of 64 meta vectors receiving 90% of the items. Give two different causes and a test that would tell them apart.
A way to think about it
One cause is the temperature schedule, the other is that N is larger than the data needs. Rerun with a slower decay and see whether usage spreads, or with a smaller N and see whether accuracy holds.
- The model is trained on the soft query but served on the hard one. Under what conditions will offline accuracy measured on the soft path overstate what users see?
A way to think about it
Compare and when the final temperature is still large, or when an item sits between two archetypes with nearly equal scores.
- What would happen to training if you used the hard query from the first step?
A way to think about it
Look at which rows of receive a gradient under argmax. Then think about a meta vector that happens to start far from every item.