212. Correct in-batch softmax for item popularity
Why it matters YouTube-style two-tower retrieval models use this correction when training on in-batch negatives.
In-batch negatives oversample popular items. The logQ correction subtracts the log sampling probability of each item from its logit before the softmax.
Write logq_loss(U, V, q). U is (B, d) user vectors, V is (B, d) the matching positive item vectors (row i is user i's positive). q is (B,) the sampling probability of each item. Logits S = U V^T, corrected S'[i, j] = S[i, j] - log q[j]. Return the mean cross-entropy with the diagonal as the target.
def logq_loss(U, V, q)Example 1
Input: U = V = identity (2, 2) and q = [0.5, 0.5]
Output: logits [[1, 0], [0, 1]] (the shift is the same for every column) and loss log(1 + e^-1), about 0.3133
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Subtract log q as a row vector so it shifts each column; then a stable log-softmax per row.
Hint 2
Logits are U @ V.T.
Hint 3
Column j belongs to item j, so subtract log q[j] from column j.
Hint 4
Stable log-sum-exp per row, minus the diagonal.
Common mistakes
- Subtracting log q from rows, which has no effect.
- Adding log q instead of subtracting it.
Understand the idea
Two-tower retrieval models often use the other items in a batch as negatives. Popular items show up in batches far more often, so the model keeps pushing them down and learns to under-rank them. The logQ correction fixes this by subtracting the log of each item's sampling probability from its logit, so items that appear often get a smaller penalty. Worked example for one row: user scores S[0] = [2, 1] for items with q = [0.5, 0.25]. log q = [-0.693, -1.386], so the corrected row is [2.693, 2.386]. Target is item 0, so the loss is log(1 + e^(2.386 - 2.693)) = log(1 + e^-0.307) = about 0.551.
S = U V^T, then S'[i, j] = S[i, j] - log q[j], then cross-entropy on each row with the diagonal as the correct class, averaged over rows
The correction belongs to the item, so it shifts columns. Shifting rows would cancel inside each row's softmax and do nothing. Used in: YouTube and other large-scale candidate retrieval systems trained with in-batch softmax.
Shapes and data flow
U (B, d) @ V^T (d, B) -> S (B, B) S - log q[None, :] shifts column j by -log q_j target = diagonal
Topics
Companies1
- ByteDance the topic appears in interview reports ByteDance Machine Learning Engineer Interview Process
From public interview reports and guides. Not affiliated with or endorsed by these companies.