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
U = V = identity (2, 2) and q = [0.5, 0.5] give logits [[1, 0], [0, 1]] (the shift is the same for every column) and loss log(1 + e^-1), about 0.3133.
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. Rule: 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