Training a two-tower retrieval model with in-batch negatives treats every other item in the batch as a negative. Popular items appear in many batches, so they are used as negatives far more often than a uniform sampler would use them, and the model learns to score them too low. The standard fix subtracts the log of each item's sampling probability from its logit. Implement the frequency estimator and the corrected loss with NumPy.
streaming_frequency(batches, alpha)
batches is a list of lists of item ids, seen in order at steps t = 1, 2, .... For each item keep B[item], the step at which it was last seen, and A[item], an estimate of the gap between appearances. On the first appearance set A[item] = t and B[item] = t; on a later appearance at step t update A[item] = (1 - alpha) * A[item] + alpha * (t - B[item]) and then B[item] = t. The estimated sampling probability per step is 1 / A[item]. Return a dict mapping item id to its probability rounded to 4 decimals.logq_corrected_logits(scores, item_ids, probs)
scores is a (B, B) array where entry (i, j) is the similarity between query i and the item at batch position j; item_ids lists the item at each position; probs maps item id to probability. Return scores[i, j] - log(probs[item_ids[j]]) as a (B, B) array rounded to 4 decimals.in_batch_softmax_loss(logits)
i is column i. Use a numerically stable log-softmax. Return a float rounded to 4 decimals.correction_effect(scores, item_ids, probs)
(uncorrected_loss, corrected_loss): the loss on the raw scores and on the corrected logits, both rounded to 4 decimals.x - max(x) - log(sum(exp(x - max(x)))).-log q_j to a column, so a popular item (large q_j) receives a smaller boost than a rare one.