Two-tower recommendation: train together, retrieve separately
双塔推荐模型
Train two nonlinear encoders, cache item vectors and check what changes when item metadata changes.
two-tower-modelsDo not run a joint network for every item
A reader opens a recommendation page. Their recent interests have changed, but most item descriptions have not. If a network jointly processes the reader and each item, we must repeat that work for every candidate. A two-tower model moves the item-dependent work into a reusable encoding.
One tower encodes user and context features; the other encodes item features. They learn together, but can run separately at serving time. A lightweight comparison combines their outputs. Yi and colleagues describe this structure for recommendation, including the difficulty of biased in-batch negatives. PDF 2–3 Independent encoders also appear in dense text retrieval, although its inputs, labels and evaluation differ. DPR, PDF 3–4
This topic concentrates on recommendation features, cache consistency and the training denominator. Our example jointly trains two small nonlinear towers. It uses exact scoring over six items, not an approximate index or a production-scale retrieval system.
Independent features, shared learning signal
Let x describe a user and their current context, and z describe an item. Both encoders output d-dimensional vectors. The matching score is:
The parameters need not be shared between towers. What joins them is the loss: changing either vector changes the same score. Our encoders append a constant feature for bias, multiply by a learned matrix and apply tanh coordinatewise. Their outputs are not unit-normalized, so the comparison is a dot product, not cosine.
Given an observed positive item y and a finite catalog C, an exact softmax defines:
For B training examples, our objective averages their negative log probabilities and adds a quadratic penalty on both tower matrices:
This uses one labeled positive per example. Other items enter the denominator; they are competitors in this training objective, not independently verified dislikes. Multiple legitimate next items require an appropriate target or masking policy. Yi and colleagues give a weighted likelihood and distinguish full-catalog from batch denominators; our rewards are all one. PDF 3, equations 1–4
For the B-by-|C| score matrix, the data-loss gradient is:
If A contains bias-augmented user features and U=tanh(AW_u), the chain rule gives:
The item update exchanges U and V and uses the augmented item-feature matrix. Both updates use gradients computed from the same old parameter values. A finite-difference test checks every weight of both towers.
Large catalogs often replace the full denominator with sampled items. Popular items can appear as negatives more frequently. The source’s batch correction subtracts a log sampling probability from each logit:
The probability must match the actual sampling scheme; changing duplicate handling, forcing the positive into a batch, or using nonrandom batches can change what needs correcting. This is a training correction, not a rule to automatically subtract popularity at serving time. We do not reproduce the paper’s streaming probability estimator.
A separate exact expectation illustrates why inverse probabilities appear. For positive weights a_j and J drawn from q:
With a=(1,2,4) and q=(0.8,0.15,0.05), the uncorrected expected sampled weight is 1.3; the corrected expectation is 7, equal to the full sum. This identity does not make a logarithm or a ratio of random estimates unbiased. It is not a complete derivation of every sampled-softmax variant.
Train, cache, then change an item
Run the complete original program with Python 3.12 and NumPy 1.26.4. Nine authored user/context vectors span three interests. Six item vectors contain three topic features and a quality flag. The target items are 0, 2 and 4 for the corresponding interest groups. All features and labels are synthetic.
"""Original jointly trained nonlinear user/context and item-feature towers."""
import json
import numpy as np
def matrix(x):
x=np.asarray(x,float)
if x.ndim!=2 or min(x.shape)==0 or not np.isfinite(x).all():raise ValueError('nonempty finite feature matrix required')
return x
def encode(features,weights):
x=matrix(features);w=np.asarray(weights,float)
if w.ndim!=2 or w.shape[0]!=x.shape[1]+1 or w.shape[1]==0 or not np.isfinite(w).all():raise ValueError('compatible finite tower weights required')
a=np.column_stack([x,np.ones(len(x))]);return np.tanh(a@w),a
def objective_gradient(users,items,targets,model,regularization=.001):
q,a=encode(users,model[0]);v,b=encode(items,model[1]);targets=np.asarray(targets)
if targets.shape!=(len(q),) or targets.dtype.kind not in 'iu' or (targets<0).any() or (targets>=len(v)).any() or not np.isfinite(regularization) or regularization<0:raise ValueError('valid targets and ridge required')
scores=q@v.T;shift=scores-scores.max(axis=1,keepdims=True);exp=np.exp(shift);prob=exp/exp.sum(axis=1,keepdims=True)
loss=float(np.mean(np.log(exp.sum(axis=1))-shift[np.arange(len(q)),targets]))+.5*regularization*sum(float(np.sum(w*w)) for w in model)
error=prob.copy();error[np.arange(len(q)),targets]-=1;error/=len(q)
gradients=(a.T@((error@v)*(1-q*q))+regularization*model[0],b.T@((error.T@q)*(1-v*v))+regularization*model[1])
return loss,gradients
def fit(users,items,targets,dimension=4,steps=600,rate=.3,regularization=.001,seed=12):
x=matrix(users);y=matrix(items)
if not isinstance(dimension,int) or dimension<1 or not isinstance(steps,int) or steps<0 or not np.isfinite(rate) or rate<=0:raise ValueError('valid dimension and optimizer controls required')
rng=np.random.default_rng(seed);model=(rng.normal(0,.2,(x.shape[1]+1,dimension)),rng.normal(0,.2,(y.shape[1]+1,dimension)));history=[]
for step in range(steps+1):
loss,g=objective_gradient(x,y,targets,model,regularization);history.append(loss)
if step<steps:model=tuple(w-rate*dw for w,dw in zip(model,g))
return model,history
def retrieve(users,cached_items,user_weights,k=2,eligible=None):
q,_=encode(users,user_weights);v=matrix(cached_items)
if v.shape[1]!=q.shape[1] or not isinstance(k,int) or k<0:raise ValueError('matching dimensions and nonnegative k required')
allowed=np.ones(len(v),bool) if eligible is None else np.asarray(eligible)
if allowed.shape!=(len(v),) or allowed.dtype.kind!='b':raise ValueError('boolean eligibility vector required')
scores=q@v.T;ids=np.flatnonzero(allowed)
return [[int(i) for i in sorted(ids,key=lambda i:(-row[i],i))[:k]] for row in scores],scores
def fixture():
users=np.vstack([np.eye(3)[j]+offset for j in range(3) for offset in [0,.03,-.03]])
items=np.array([[1,0,0,1],[1,0,0,0],[0,1,0,1],[0,1,0,0],[0,0,1,1],[0,0,1,0]],float)
return users,items,np.repeat([0,2,4],3)
def demo():
users,items,targets=fixture();model,h=fit(users,items,targets);cached,_=encode(items,model[1]);ranked,scores=retrieve(users,cached,model[0])
changed=items.copy();changed[0]=items[4];fresh,_=encode(changed,model[1]);after,_=retrieve(users,fresh,model[0])
blocked,_=retrieve(users,cached,model[0],eligible=np.array([False,True,True,True,True,True]))
q=np.array([.8,.15,.05]);weights=np.array([1.,2.,4.]);naive=float(q@weights);corrected=float(q@(weights/q))
return dict(loss=[h[0],h[-1]],top1_accuracy=float(np.mean([row[0] for row in ranked]==targets)),
rankings=ranked,scores=scores.tolist(),cache_max_error=float(np.max(np.abs(scores-encode(users,model[0])[0]@encode(items,model[1])[0].T))),
stale_first=ranked[0],fresh_first=after[0],eligible_first=blocked[0],
sampling_example=dict(distribution=q.tolist(),unnormalized_weights=weights.tolist(),naive_expectation=naive,importance_expectation=corrected,full_sum=float(weights.sum())))
if __name__=='__main__':print(json.dumps(demo(),allow_nan=False))
With dimension 4, seed 12, 600 full-batch updates, learning rate 0.3 and lambda 0.001, the objective falls from 1.837959 to 0.200857. Top-1 accuracy is 1 on the training queries. This establishes fitting capacity on this fixture, not held-out quality.
Caching the trained item vectors gives exactly the same scores as encoding them afresh. For the first query, the top two are [0,1]. Replace item 0’s attributes with item 4’s attributes: the stale cache still returns [0,1], while re-encoding returns [1,2]. An explicit eligibility mask excluding item 0 also returns [1,2], for a different reason. Updating an item’s metadata, changing the item tower’s parameters and withdrawing an item are separate cache or filtering events.
For user feature dimension p, item feature dimension q, embedding dimension d, B examples and N items, a dense training step costs O(B p d + N q d + B N d). It stores the B-by-N score/error arrays and the encoded vectors. Cached exact retrieval costs O(p d + N d) per query, plus O(N log N) here for full sorting; the item cache stores N d numbers. A compatible nearest-neighbor index may reduce search work, but this example does not build one. If item features depend on the current user, a single globally cached item vector generally no longer represents that joint computation.
A cache can be numerically valid and semantically stale
Equal dimensions do not prove that vectors share a learned space. Keep the tower versions and feature schema together with the cache. Updating the item tower typically requires regenerating item vectors; updating only the user tower also changes the learned pairing and needs evaluation with the intended item version.
An item feature model can encode a new item when meaningful attributes are already available. An unseen identity alone has no learned meaning. Joint cross-features may help a later ranker, but inserting user-dependent computation into the item tower sacrifices the original caching separation. Use cold-start evaluation and ranking objectives to test those choices rather than assuming a retrieval score is a calibrated probability of user satisfaction.
Which work can be reused?
- Must the two towers share weights? Answer: No. They can have different parameters and input features; the common loss aligns their output spaces.
- What is the corrected expectation for a=(1,2,4) and q=(0.8,0.15,0.05)? Answer: 7. Each term q_j times a_j/q_j equals a_j. The naive expectation is only 1.3.
- Does an unbiased estimate of a sum imply an unbiased estimate of its logarithm? Answer: No. The logarithm is nonlinear. The expectation identity alone does not justify that claim about a loss.
- Why can identical vector dimensions fail to protect a cache after retraining? Answer: Retraining can change the coordinate system and feature mapping. Matching dimensions provide a shape check, not model-version compatibility.
What the small system actually reproduces
The model follows independent recommendation encoding and dot-product training described by Yi and colleagues; DPR provides a related independent-encoder comparison. The nonlinear matrices, full-catalog training, synthetic labels and cache experiment are original. The log-probability correction is explained from the recorded method page; streaming sketches, approximate retrieval and YouTube outcomes are not reproduced. A next experiment can hold out new context vectors and test cache version changes while keeping training labels fixed.
Make a prediction, then check
An item changes its metadata. Is its cached vector automatically current?
Learning objectives
- Separate joint learning from independent encoding and state the limits of sampled loss corrections.
- Run the original computation and explain a counterexample without claiming a public benchmark result.
Prerequisites & connections
Explore related knowledge →References
- Sampling-Bias-Corrected Neural Modeling for Large Corpus Item Recommendations
Xinyang Yi; Ji Yang; Lichan Hong; Derek Zhiyuan Cheng; Lukasz Heldt; Aditee Kumthekar; Zhe Zhao; Li Wei; Ed Chi · 2019 - Dense Passage Retrieval for Open-Domain Question Answering — arXiv v1
Vladimir Karpukhin; Barlas Oğuz; Sewon Min; Ledell Wu; Sergey Edunov; Danqi Chen; Wen-tau Yih · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF 1 identity and 2–3 text; viewed page 3. Independent towers, full/batch softmax and log sampling-probability correction. No streaming sketch or YouTube benchmark reproduction. Viewed physical PDF3–4: independent encoders, dot product, loss and negatives. Read PDF5 hybrid-score paragraph; v1 author list differs from final proceedings. 7 paired equations and four explained exercises. Jointly trained two nonlinear towers; checked every weight gradient, independent scalar dot products, stale versus refreshed item cache, eligibility and separate importance-weight expectation. Training accuracy is not held-out quality.
- Jointly trained two nonlinear towers; checked every weight gradient, independent scalar dot products, stale versus refreshed item cache, eligibility and separate importance-weight expectation. Training accuracy is not held-out quality.
- Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- Sampling-Bias-Corrected Neural Modeling for Large Corpus Item Recommendations · Read PDF 1 identity and 2–3 text; viewed page 3. Independent towers, full/batch softmax and log sampling-probability correction. No streaming sketch or YouTube benchmark reproduction.
- Dense Passage Retrieval for Open-Domain Question Answering — arXiv v1 · Viewed physical PDF3–4: independent encoders, dot product, loss and negatives. Read PDF5 hybrid-score paragraph; v1 author list differs from final proceedings.
Related topics