File size: 2,426 Bytes
727017f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
def6dde
 
 
 
 
 
 
 
 
 
 
727017f
 
def6dde
727017f
 
def6dde
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""Cross-encoder reranker that fixes the order of candidates already recalled by the server.

Embedding recall scores each memory on its own, so when a distractor shares the query's wording the
right memory can land second: the README's weak case, "Who is presenting at the quarterly review?",
ranks "The team agreed to ship the billing fix before the quarterly review." just above the memory
that actually answers it. A cross-encoder reads the (query, memory) pair together and scores
relevance directly, which separates those two. It runs on CPU over the handful of candidates the
server already returned, so it adds one small forward pass per recall and never touches the store.
"""
from __future__ import annotations

from collections.abc import Callable, Sequence
from functools import lru_cache
from typing import Any

MODEL = "cross-encoder/ms-marco-MiniLM-L-6-v2"  # ~80 MB, CPU, trained for query-passage relevance


@lru_cache(maxsize=1)
def _model():
    # Imported lazily so the module is cheap to import and the model loads once, on first recall.
    from sentence_transformers import CrossEncoder

    return CrossEncoder(MODEL)


def rerank(query: str, candidates: Sequence[Any], *, text: Callable[[Any], str] = lambda c: c.text) -> list[Any]:
    """Return ``candidates`` ordered by cross-encoder relevance to ``query``, highest first.

    The sort is stable, so candidates the reranker cannot separate keep the server's order, and a
    list shorter than two is returned unchanged. ``text`` reads the string to score from each
    candidate (``m.text`` for a recalled memory).
    """
    return [item for item, _ in rerank_with_scores(query, candidates, text=text)]


def rerank_with_scores(
    query: str, candidates: Sequence[Any], *, text: Callable[[Any], str] = lambda c: c.text
) -> list[tuple[Any, float | None]]:
    """Like :func:`rerank`, but pair each candidate with its cross-encoder relevance score.

    A list shorter than two is returned unchanged with ``None`` scores, since the reranker never
    ran. Callers can use the returned score for display so the shown number matches the order.
    """
    items = list(candidates)
    if len(items) < 2:
        return [(c, None) for c in items]
    scores = _model().predict([(query, text(c)) for c in items])
    order = sorted(range(len(items)), key=lambda i: scores[i], reverse=True)
    return [(items[i], float(scores[i])) for i in order]