A bi-encoder embeds the query and every document separately and scores them with a dot product, so document vectors can be precomputed and searched in milliseconds. A cross-encoder reads the query and the document together and can model their interaction, which makes it more accurate and far too slow to run over a whole corpus. Production search uses both: retrieve a short list with the bi-encoder, then rerank it with the cross-encoder. Implement the pieces with fixed, given weights.
bi_encoder_retrieve(q, D, k)
q is a query vector of shape (d,), D a document matrix of shape (n, d). Score every document by cosine similarity and return the indices of the top k as a Python list, highest score first (ties broken by the lower index).cross_encoder_score(q, D, w, b)
D as a NumPy array rounded to 4 decimals.rerank_cascade(q, D, k, w, b)
k with the bi-encoder, score only those with the cross-encoder, and return (final_order, candidates): the candidate indices sorted by cross-encoder score descending (ties by lower index) and the original candidate list.cascade_cost(n_docs, k, cost_bi, cost_cross)
(full_cross, cascade, speedup) with the speedup rounded to 2 decimals.np.argsort(-scores, kind="stable") gives descending order with the lower index winning ties.