Two encoders, one vector space
- : the query encoder.
- : the document encoder.
Queries and documents are embedded separately and compared by a dot product, which is why this shape is called a bi-encoder.
The separation is the entire engineering argument. Documents can be embedded once, offline, and the query is the only thing encoded at search time.
A cross-encoder reading the pair together scores better and cannot be indexed, because it has no vector for a document until it has seen the query.
The training objective
- : the passage that answers the query.
- : negatives, passages that do not.
- : a temperature, typically 0.05.
This is contrastive learning: pull the right pair together and push the wrong ones apart, in one softmax over the candidates.
This is where in-batch negatives come in.
The cheap trick that made it practical is to use the other documents in the same batch as negatives, so a batch of 1,024 gives 1,023 negatives per query at no extra cost.
Larger batches therefore train better retrievers, which is why this task is unusually sensitive to how much memory the training hardware has.
Hard negatives are where the quality is
A random negative is easy. A passage about the wrong football club is separated from the right one long before training is useful.
Hard negatives are passages the current retriever already ranks highly and which do not answer the query, mined by running the model over the corpus.
Training on them is what teaches the fine distinctions, and it usually takes two or three rounds of mine, retrain, mine again.
The risk is false negatives: a mined passage that does answer the query, labelled as wrong, actively teaches the model the opposite of the truth.
One system, in order
- Fine-tune the two encoders on query and passage pairs with in-batch negatives.
- Mine hard negatives with the resulting model and train again.
- Embed the whole corpus once and build an approximate index.
- At query time, embed the query and search the index.
- Rerank the top candidates with a cross-encoder if the latency allows.
Where it beats keywords and where it does not
Dense retrieval matches meaning, so it finds passages sharing no words with the query, which is exactly what BM25 cannot do.
Try a query like "error XT-4491".
It is weak on exact identifiers, rare product codes and names that were not in its training distribution, where a keyword index is perfect and effortless.
It also does not transfer. A retriever trained on web questions performs poorly on legal or medical corpora, while BM25 has no domain to be wrong about.
That complementarity is why hybrid search exists, and why very few serious systems run dense retrieval alone.