In-batch negatives are random documents. The retrieval mistakes that matter are near-misses, so the fine-tuning stage mines one hard negative per query and upweights it in the loss. EmbeddingGemma gives the hard negative of query the weight , where is its cosine similarity to the query, is stop-gradient (the weight is a constant for the backward pass) and . Implement the mining and the weighted loss.
mine_hard_negatives(Q, D, pos_idx)
Q is (B, d), D is (n, d) and pos_idx[i] is the index in D of query i's positive. For every query return the index of the highest-cosine document that is not its positive (lower index wins ties), as a list.hard_negative_weights(Q, N, alpha=5.0)
N[i] is the hard negative of query i. Return the (B,) array of rounded to 4 decimals.weighted_infonce(Q, P, N, tau=0.05, alpha=5.0)
i the denominator is over all positives and all hard negatives, except that query i's own hard negative term is multiplied by ; other queries' hard negatives enter with weight 1. Return the mean of rounded to 4 decimals. Use unrounded weights.own_hard_negative_share(Q, P, N, tau=0.05, alpha=5.0)
(B,) array rounded to 4 decimals.-inf before argmax.log weights: add to the logit of the own hard negative, then use a stable log-sum-exp.