Skip to content
Edit this page

muscari.evaluation

Evaluate sparse encoders: reranking, retrieval from a corpus, caps on the vector size, and comparisons of runs. Requires the retrieval extra, except for comparison and runs.

Running an evaluation

EvaluationPlan dataclass

EvaluationPlan(
    benchmark: str | None = None,
    files: Sequence[str] | None = None,
    split: str | None = None,
    query_column: str = "query",
    document_column: str = "text",
    label_column: str = "label",
    group_column: str | None = None,
    title_column: str | None = None,
    without_title: bool = False,
    queries: int = 0,
    retrieval: Sequence[str] = (),
    retrieval_split: str = "test",
    retrieval_queries: int = 0,
    top_k: int = 100,
    caps: Sequence[Cap] = (lambda: [FULL])(),
    batch_size: int = 32,
    chunk: int = 1024,
)

Everything evaluate runs; the fields mirror the options of muscari eval-retriever.

benchmark or files selects a reranking set; retrieval lists MTEB-layout datasets. queries and retrieval_queries draw samples of that many queries; 0 uses all.

evaluate

evaluate(
    model: SparseEncoder,
    plan: EvaluationPlan,
    *,
    seed: int = 42,
) -> dict[str, Any]

Run every evaluation the plan asks for; empty when it asks for none.

Returns:

  • dict[str, Any] –

    reranking and retrieval (keyed by dataset), each as rerank and retrieve

  • dict[str, Any] –

    return it, with the time taken in seconds.

Source code in src/muscari/evaluation/plan.py
def evaluate(model: SparseEncoder, plan: EvaluationPlan, *, seed: int = 42) -> dict[str, Any]:
    """Run every evaluation the plan asks for; empty when it asks for none.

    Returns:
        ``reranking`` and ``retrieval`` (keyed by dataset), each as ``rerank`` and ``retrieve``
        return it, with the time taken in ``seconds``.
    """
    result: dict[str, Any] = {}
    caps = list(dict.fromkeys(plan.caps))

    if plan.benchmark or plan.files:
        result["reranking"] = _reranking(model, plan, caps, seed)

    for source in plan.retrieval:
        result.setdefault("retrieval", {})[public_name(source)] = _retrieval(model, plan, source, caps, seed)

    return result

summary

summary(result: Mapping[str, Any]) -> dict[str, Any]

The averaged metrics of an evaluation, without the per-query values.

Source code in src/muscari/evaluation/plan.py
def summary(result: Mapping[str, Any]) -> dict[str, Any]:
    """The averaged metrics of an evaluation, without the per-query values."""
    short: dict[str, Any] = {}

    if "reranking" in result:
        short["reranking"] = result["reranking"]["caps"]
    for name, retrieval in result.get("retrieval", {}).items():
        short.setdefault("retrieval", {})[name] = retrieval["caps"]

    return short

add_evaluation_arguments

add_evaluation_arguments(
    parser: ArgumentParser, *, prefix: str = ""
) -> None

Add the options of an EvaluationPlan; prefix keeps them apart from a script's own options.

Source code in src/muscari/evaluation/options.py
def add_evaluation_arguments(parser: argparse.ArgumentParser, *, prefix: str = "") -> None:
    """Add the options of an ``EvaluationPlan``; ``prefix`` keeps them apart from a script's own options."""
    _add_reranking(parser, prefix)
    _add_retrieval(parser, prefix)

    group = parser.add_argument_group("evaluation")
    group.add_argument(
        f"--{prefix}caps",
        nargs="+",
        type=parse_cap,
        default=[FULL],
        help="inference-time caps QUERY/DOCUMENT on the active dimensions, or full",
    )
    group.add_argument(f"--{prefix}batch-size", type=int, default=32)
    group.add_argument(f"--{prefix}chunk", type=int, default=1024, help="texts encoded between two scorings")

plan_from_args

plan_from_args(
    args: Namespace, *, prefix: str = ""
) -> EvaluationPlan

The plan that options added by add_evaluation_arguments with the same prefix describe.

Source code in src/muscari/evaluation/options.py
def plan_from_args(args: argparse.Namespace, *, prefix: str = "") -> EvaluationPlan:
    """The plan that options added by ``add_evaluation_arguments`` with the same ``prefix`` describe."""
    attribute = prefix.replace("-", "_")
    values = {field.name: getattr(args, attribute + field.name) for field in fields(EvaluationPlan)}
    return EvaluationPlan(**values)

load_model

load_model(
    model: str | None,
    *,
    sae: str | None = None,
    query_prompt: str | None = None,
    document_prompt: str | None = None,
    max_seq_length: int | None = None,
    device: str | None = None,
    trust_remote_code: bool = False,
) -> SparseEncoder

The encoder to evaluate, in eval mode, with the given prompts overriding its own.

With sae the encoder is an untrained SAE head on model (by default the base model the SAE records). Otherwise model is a saved SparseEncoder; remote code runs only with trust_remote_code, unless the model needs none (needs_remote_code).

Raises:

  • ValueError –

    if neither model nor sae is given.

Source code in src/muscari/evaluation/models.py
def load_model(
    model: str | None,
    *,
    sae: str | None = None,
    query_prompt: str | None = None,
    document_prompt: str | None = None,
    max_seq_length: int | None = None,
    device: str | None = None,
    trust_remote_code: bool = False,
) -> SparseEncoder:
    """The encoder to evaluate, in eval mode, with the given prompts overriding its own.

    With ``sae`` the encoder is an untrained SAE head on ``model`` (by default the base model
    the SAE records). Otherwise ``model`` is a saved ``SparseEncoder``; remote code runs only
    with ``trust_remote_code``, unless the model needs none (``needs_remote_code``).

    Raises:
        ValueError: if neither ``model`` nor ``sae`` is given.
    """
    if sae:
        encoder = build_sparse_encoder(
            sae,
            model,
            query_prompt=query_prompt or None,
            document_prompt=document_prompt or None,
            max_seq_length=max_seq_length,
            device=device,
        )
        return encoder.eval()

    if not model:
        raise ValueError("Give a model, or an SAE for an untrained SAE head.")

    trusted = trust_remote_code or not needs_remote_code(model)
    encoder = SparseEncoder(model, device=device, trust_remote_code=trusted)
    if max_seq_length:
        encoder.max_seq_length = max_seq_length

    for name, prompt in (("query", query_prompt), ("document", document_prompt)):
        if prompt is not None:
            encoder.prompts[name] = prompt

    return encoder.eval()

needs_remote_code

needs_remote_code(path: str) -> bool

Whether a saved model names modules or architectures that this environment does not provide.

A local directory whose modules, those of a Router included, are all part of Sentence Transformers or this project, that holds no Python file and whose config.json files have no auto_map loads without running code from the model.

Source code in src/muscari/evaluation/models.py
def needs_remote_code(path: str) -> bool:
    """Whether a saved model names modules or architectures that this environment does not provide.

    A local directory whose modules, those of a ``Router`` included, are all part of Sentence
    Transformers or this project, that holds no Python file and whose ``config.json`` files have
    no ``auto_map`` loads without running code from the model.
    """
    directory = Path(path)
    if not directory.is_dir() or any(directory.rglob("*.py")):
        return True
    if any(not name.startswith(LOCAL_MODULE_PREFIXES) for name in _module_types(directory)):
        return True

    configs = (json.loads(file.read_text(encoding="utf-8")) for file in directory.rglob("config.json"))
    return any("auto_map" in config for config in configs)

Reranking

rerank

rerank(
    model: SparseEncoder,
    examples: Sequence[RerankingExample],
    *,
    caps: Sequence[Cap] = (FULL,),
    batch_size: int = 32,
    chunk: int = 256,
    seed: int = 42,
    k: int = 10,
) -> dict[str, Any]

nDCG@k and MRR@k of ranking each query's candidates, for each pair of caps.

Each distinct document is encoded once. The query vectors stay on the model's device and the documents are encoded chunk at a time; only the (query, candidate) pairs that are ranked are scored, so a vocabulary-sized output, which can be nearly dense before training, is never held for the whole collection and no sparse tensor is built on the accelerator, whose sparse support varies (Apple MPS).

Candidates are shuffled with seed before ranking, as muscari probe-sae does, so an untrained SAE head gives that command's sparse.plain on the same queries, up to float32 rounding of the scores.

Source code in src/muscari/evaluation/reranking.py
@torch.no_grad()
def rerank(
    model: SparseEncoder,
    examples: Sequence[RerankingExample],
    *,
    caps: Sequence[Cap] = (FULL,),
    batch_size: int = 32,
    chunk: int = 256,
    seed: int = 42,
    k: int = 10,
) -> dict[str, Any]:
    """nDCG@k and MRR@k of ranking each query's candidates, for each pair of caps.

    Each distinct document is encoded once. The query vectors stay on the model's device and the
    documents are encoded ``chunk`` at a time; only the (query, candidate) pairs that are ranked
    are scored, so a vocabulary-sized output, which can be nearly dense before training, is
    never held for the whole collection and no sparse tensor is built on the accelerator, whose
    sparse support varies (Apple MPS).

    Candidates are shuffled with ``seed`` before ranking, as ``muscari probe-sae`` does, so an
    untrained SAE head gives that command's ``sparse.plain`` on the same queries, up to float32
    rounding of the scores.
    """
    queries = list(dict.fromkeys(example.query for example in examples))
    documents = list(dict.fromkeys(document for example in examples for document in example.documents))
    pairs = _Pairs(examples, queries, documents)

    capped = CappedVectors(encode(model.encode_query, queries, batch_size), caps)
    scores = torch.empty(len(caps), pairs.query.shape[0], dtype=torch.float64)
    for start, end in chunks(len(documents), chunk, "documents"):
        vectors = encode(model.encode_document, documents[start:end], batch_size)
        _score_chunk(scores, pairs, capped, vectors, start)

    generator = torch.Generator().manual_seed(seed)
    shuffles = [torch.randperm(len(example.documents), generator=generator) for example in examples]
    result: dict[str, Any] = {"queries": len(examples), "documents": len(documents), "dimensions": capped.dimension}
    result["caps"], result["per_query"] = {}, {}

    for index in range(len(caps)):
        per_query = _per_query(examples, scores[index], shuffles, k)
        result["caps"][capped.label(index)] = mean_metrics(per_query) | capped.summary(index)
        result["per_query"][capped.label(index)] = per_query

    return result

reranking_examples

reranking_examples(
    *,
    benchmark: str | None = None,
    data_files: Sequence[str] | None = None,
    split: str | None = None,
    query_column: str = "query",
    document_column: str = "text",
    label_column: str = "label",
    group_column: str | None = None,
    title_column: str | None = None,
    without_title: bool = False,
    max_queries: int | None = None,
    seed: int = 42,
) -> list[RerankingExample]

Examples of a known benchmark (its preset wins over the column arguments) or of local files.

With max_queries a sample of queries is drawn after shuffling the rows with seed; the whole split is used otherwise.

Source code in src/muscari/evaluation/reranking_data.py
def reranking_examples(
    *,
    benchmark: str | None = None,
    data_files: Sequence[str] | None = None,
    split: str | None = None,
    query_column: str = "query",
    document_column: str = "text",
    label_column: str = "label",
    group_column: str | None = None,
    title_column: str | None = None,
    without_title: bool = False,
    max_queries: int | None = None,
    seed: int = 42,
) -> list[RerankingExample]:
    """Examples of a known benchmark (its preset wins over the column arguments) or of local files.

    With ``max_queries`` a sample of queries is drawn after shuffling the rows with ``seed``; the
    whole split is used otherwise.
    """
    preset = BENCHMARKS.get(benchmark or "", {})
    columns = {
        "query_column": preset.get("query_column", query_column),
        "document_column": preset.get("document_column", document_column),
        "label_column": preset.get("label_column", label_column),
    }
    group = preset.get("group_column", group_column)
    title = None if without_title else preset.get("title_column", title_column)

    rows = load_rows(
        dataset=preset.get("dataset"),
        subsets=None,
        data_files=None if preset else data_files,
        split=split or preset.get("split", "test"),
        column_names=[*columns.values(), *(name for name in (group, title) if name)],
        seed=seed,
    )
    return group_reranking_rows(rows, **columns, group_column=group, title_column=title, max_queries=max_queries)

Retrieval

retrieve

retrieve(
    model: SparseEncoder,
    queries: Mapping[str, str],
    corpus: Mapping[str, str],
    qrels: Mapping[str, Mapping[str, int]],
    *,
    caps: Sequence[Cap] = (FULL,),
    top_k: int = 100,
    batch_size: int = 32,
    chunk: int = 1024,
    k: int = 10,
) -> dict[str, Any]

Rank the whole corpus for every query that has a relevant document in qrels.

The corpus is encoded chunk documents at a time and merged into a running top-top_k per query on the model's device, so neither the corpus vectors nor the full score matrix are kept.

Raises:

  • ValueError –

    if no query has a relevant document.

Source code in src/muscari/evaluation/retrieval.py
@torch.no_grad()
def retrieve(
    model: SparseEncoder,
    queries: Mapping[str, str],
    corpus: Mapping[str, str],
    qrels: Mapping[str, Mapping[str, int]],
    *,
    caps: Sequence[Cap] = (FULL,),
    top_k: int = 100,
    batch_size: int = 32,
    chunk: int = 1024,
    k: int = 10,
) -> dict[str, Any]:
    """Rank the whole ``corpus`` for every query that has a relevant document in ``qrels``.

    The corpus is encoded ``chunk`` documents at a time and merged into a running top-``top_k``
    per query on the model's device, so neither the corpus vectors nor the full score matrix
    are kept.

    Raises:
        ValueError: if no query has a relevant document.
    """
    query_ids = _answerable(queries, qrels)
    if not query_ids:
        raise ValueError("No query has a relevant document in the qrels.")

    document_ids = list(corpus)
    query_vectors = encode(model.encode_query, [queries[query_id] for query_id in query_ids], batch_size)
    device = query_vectors.device
    capped = CappedVectors(query_vectors, caps)
    best = [_TopK(len(query_ids), min(top_k, len(document_ids)), device) for _ in caps]

    for start, end in chunks(len(document_ids), chunk, "documents"):
        vectors = encode(model.encode_document, [corpus[doc] for doc in document_ids[start:end]], batch_size)
        rows = torch.arange(start, end, device=device).expand(len(query_ids), -1)

        for index, documents in capped.documents(vectors):
            best[index].merge(capped.queries[index] @ documents.T, rows)

    result: dict[str, Any] = {"queries": len(query_ids), "documents": len(document_ids), "dimensions": capped.dimension}
    result["caps"], result["per_query"] = {}, {}

    for index, top in enumerate(best):
        per_query = {
            query_id: retrieval_metrics([document_ids[row] for row in ranked], qrels[query_id], k=k, depth=top_k)
            for query_id, ranked in zip(query_ids, top.rows.cpu().tolist(), strict=True)
        }
        result["caps"][capped.label(index)] = mean_metrics(per_query) | capped.summary(index)
        result["per_query"][capped.label(index)] = per_query

    return result

retrieval_data

retrieval_data(
    source: str,
    *,
    split: str = "test",
    without_title: bool = False,
    max_queries: int | None = None,
    seed: int = 42,
) -> tuple[dict[str, str], dict[str, str], Qrels]

Queries, corpus and qrels of a dataset in the MTEB layout, from the Hub or a local directory.

A Hub dataset has the configurations corpus (id, text, optional title), queries (id, text) and qrels (query-id, corpus-id, score); a local directory has corpus.jsonl, queries.jsonl and qrels.jsonl with those columns. Where a set names its id column _id, that column is read instead. A document with a title is "{title} {text}". With max_queries a sample of the queries that have a relevant document is drawn with seed; the corpus is always used whole.

Source code in src/muscari/evaluation/retrieval_data.py
def retrieval_data(
    source: str,
    *,
    split: str = "test",
    without_title: bool = False,
    max_queries: int | None = None,
    seed: int = 42,
) -> tuple[dict[str, str], dict[str, str], Qrels]:
    """Queries, corpus and qrels of a dataset in the MTEB layout, from the Hub or a local directory.

    A Hub dataset has the configurations ``corpus`` (``id``, ``text``, optional ``title``),
    ``queries`` (``id``, ``text``) and ``qrels`` (``query-id``, ``corpus-id``, ``score``); a local
    directory has ``corpus.jsonl``, ``queries.jsonl`` and ``qrels.jsonl`` with those columns.
    Where a set names its id column ``_id``, that column is read instead.
    A document with a title is ``"{title} {text}"``. With ``max_queries`` a sample of the queries
    that have a relevant document is drawn with ``seed``; the corpus is always used whole.
    """
    corpus: dict[str, str] = {}
    for row in _table(source, "corpus", split):
        title = "" if without_title else str(row.get("title") or "").strip()
        corpus[_identifier(row)] = f"{title} {row['text']}" if title else str(row["text"])

    qrels: Qrels = {}
    for row in _table(source, "qrels", split):
        qrels.setdefault(str(row["query-id"]), {})[str(row["corpus-id"])] = int(row["score"])

    queries = {_identifier(row): str(row["text"]) for row in _table(source, "queries", split)}
    if max_queries:
        queries = _sample(queries, qrels, max_queries, seed)

    return queries, corpus, qrels

retrieval_metrics

retrieval_metrics(
    ranked: Sequence[str],
    relevance: Mapping[str, int],
    *,
    k: int = 10,
    depth: int = 100,
) -> dict[str, float]

nDCG@k with graded gains, MRR@k and recall@depth of one ranked list of document ids.

Gains are the qrels scores, as in pytrec_eval; documents with a score of zero or less are not relevant.

Raises:

  • ValueError –

    if no document is relevant.

Source code in src/muscari/evaluation/retrieval_data.py
def retrieval_metrics(
    ranked: Sequence[str],
    relevance: Mapping[str, int],
    *,
    k: int = 10,
    depth: int = 100,
) -> dict[str, float]:
    """nDCG@k with graded gains, MRR@k and recall@depth of one ranked list of document ids.

    Gains are the qrels scores, as in ``pytrec_eval``; documents with a score of zero or less
    are not relevant.

    Raises:
        ValueError: if no document is relevant.
    """
    gains = sorted((score for score in relevance.values() if score > 0), reverse=True)
    if not gains:
        raise ValueError("The query has no relevant document.")

    dcg = sum(max(relevance.get(doc, 0), 0) / math.log2(rank + 2) for rank, doc in enumerate(ranked[:k]))
    ideal = sum(gain / math.log2(rank + 2) for rank, gain in enumerate(gains[:k]))
    first = next((rank for rank, doc in enumerate(ranked[:k]) if relevance.get(doc, 0) > 0), None)
    found = sum(1 for doc in ranked[:depth] if relevance.get(doc, 0) > 0)

    return {
        f"ndcg@{k}": dcg / ideal,
        f"mrr@{k}": 0.0 if first is None else 1.0 / (first + 1),
        f"recall@{depth}": found / len(gains),
    }

Comparing runs

compare

compare(
    a: Sequence[Mapping[str, float]],
    b: Sequence[Mapping[str, float]],
    *,
    resample: str = "runs-and-queries",
    resamples: int = 10000,
    confidence: float = 0.95,
    seed: int = 42,
) -> dict[str, Any]

Paired comparison of b - a; each arm is a list of runs, {query_id: value} each.

The interval is a percentile bootstrap. "runs-and-queries" draws, for every resample, the runs of each arm with replacement and the queries with replacement; "queries" keeps the runs and draws only queries. The p-value flips the sign of each query's difference of run-averaged values at random and counts how often the mean is at least as far from zero as the one observed (with the observed statistic included, so it is never zero); it treats the runs as given.

Raises:

  • ValueError –

    if the arms share no query or resample is unknown.

Source code in src/muscari/evaluation/comparison.py
def compare(
    a: Sequence[Mapping[str, float]],
    b: Sequence[Mapping[str, float]],
    *,
    resample: str = "runs-and-queries",
    resamples: int = 10_000,
    confidence: float = 0.95,
    seed: int = 42,
) -> dict[str, Any]:
    """Paired comparison of ``b - a``; each arm is a list of runs, ``{query_id: value}`` each.

    The interval is a percentile bootstrap. ``"runs-and-queries"`` draws, for every resample,
    the runs of each arm with replacement and the queries with replacement; ``"queries"``
    keeps the runs and draws only queries. The p-value flips the sign of each query's
    difference of run-averaged values at random and counts how often the mean is at least as
    far from zero as the one observed (with the observed statistic included, so it is never
    zero); it treats the runs as given.

    Raises:
        ValueError: if the arms share no query or ``resample`` is unknown.
    """
    if resample not in RESAMPLES:
        raise ValueError(f"Unknown resample: {resample!r}.")

    values_a, values_b = align_runs(a, b)
    differences = values_b.mean(dim=0) - values_a.mean(dim=0)
    means, extreme = _bootstrap(values_a, values_b, resample, resamples, seed)

    tail = (1 - confidence) / 2
    low, high = torch.quantile(means, torch.tensor([tail, 1 - tail], dtype=torch.float64)).tolist()

    return {
        "queries": values_a.shape[1],
        "mean_a": float(values_a.mean()),
        "mean_b": float(values_b.mean()),
        "run_means_a": values_a.mean(dim=1).tolist(),
        "run_means_b": values_b.mean(dim=1).tolist(),
        "run_std_a": _spread(values_a),
        "run_std_b": _spread(values_b),
        "difference": float(differences.mean()),
        "ci_low": low,
        "ci_high": high,
        "confidence": confidence,
        "resample": resample if max(values_a.shape[0], values_b.shape[0]) > 1 else "queries",
        "p_value": (extreme + 1) / (resamples + 1),
        "b_better": int((differences > 0).sum()),
        "a_better": int((differences < 0).sum()),
    }

per_query

per_query(
    result: Mapping[str, Any],
    *,
    task: str,
    cap: str,
    metric: str,
    stage: str,
) -> dict[str, float]

{query_id: value} of one run; task is reranking or retrieval/<dataset>.

A result with before and after evaluations, as a training script writes, is read at stage.

Raises:

  • KeyError –

    naming the part of the result that is missing.

Source code in src/muscari/evaluation/runs.py
def per_query(result: Mapping[str, Any], *, task: str, cap: str, metric: str, stage: str) -> dict[str, float]:
    """``{query_id: value}`` of one run; ``task`` is ``reranking`` or ``retrieval/<dataset>``.

    A result with ``before`` and ``after`` evaluations, as a training script writes, is read
    at ``stage``.

    Raises:
        KeyError: naming the part of the result that is missing.
    """
    if "after" in result or "before" in result:
        result = result[stage]

    section: Any = result
    for key in task.split("/", 1):
        if key not in section:
            raise KeyError(f"The result has no {task!r}; it has {sorted(section)}.")
        section = section[key]

    if cap not in section["per_query"]:
        raise KeyError(f"No cap {cap!r}; the result has {sorted(section['per_query'])}.")

    return {query_id: float(values[metric]) for query_id, values in section["per_query"][cap].items()}

align_runs

align_runs(
    a: Sequence[Mapping[str, float]],
    b: Sequence[Mapping[str, float]],
) -> tuple[Tensor, ...]

The runs of both arms as (runs, queries) matrices over the queries every run has.

Raises:

  • ValueError –

    if the runs share no query.

Source code in src/muscari/evaluation/runs.py
def align_runs(a: Sequence[Mapping[str, float]], b: Sequence[Mapping[str, float]]) -> tuple[torch.Tensor, ...]:
    """The runs of both arms as ``(runs, queries)`` matrices over the queries every run has.

    Raises:
        ValueError: if the runs share no query.
    """
    shared = sorted(set(a[0]).intersection(*a[1:], *b))
    if not shared:
        raise ValueError("The two arms share no query.")

    return tuple(
        torch.tensor([[run[query_id] for query_id in shared] for run in runs], dtype=torch.float64) for runs in (a, b)
    )

Diagnostics

head_report

head_report(
    model: SparseEncoder,
    queries: Sequence[str],
    documents: Sequence[str],
    *,
    batch_size: int = 16,
    dense_share: float = 0.5,
) -> dict[str, Any]

How dense the model's vectors are on queries and documents.

For each side: the number of non-zero dimensions per text, its share of all dimensions (density), the weights, how many dimensions are non-zero in at least dense_share of the texts and how many in none, and the value a FLOPS regulariser would see. flops is the expected number of dimensions a query and a document share, the sum over dimensions of the two shares of texts in which the dimension is non-zero.

Source code in src/muscari/evaluation/diagnostics/vectors.py
@torch.no_grad()
def head_report(
    model: SparseEncoder,
    queries: Sequence[str],
    documents: Sequence[str],
    *,
    batch_size: int = 16,
    dense_share: float = 0.5,
) -> dict[str, Any]:
    """How dense the model's vectors are on ``queries`` and ``documents``.

    For each side: the number of non-zero dimensions per text, its share of all dimensions
    (``density``), the weights, how many dimensions are non-zero in at least ``dense_share`` of
    the texts and how many in none, and the value a FLOPS regulariser would see. ``flops`` is
    the expected number of dimensions a query and a document share, the sum over dimensions of
    the two shares of texts in which the dimension is non-zero.
    """
    if not queries or not documents:
        raise ValueError("head_report needs at least one query and one document.")

    query_vectors = encode_side(model, queries, "query", batch_size)
    document_vectors = encode_side(model, documents, "document", batch_size)
    shares = [(vectors > 0).float().mean(dim=0) for vectors in (query_vectors, document_vectors)]

    return {
        "dimensions": int(query_vectors.shape[1]),
        "dense_share": dense_share,
        "query": _side(query_vectors, dense_share),
        "document": _side(document_vectors, dense_share),
        "flops": float((shares[0] * shares[1]).sum()),
    }

logit_report

logit_report(
    model: SparseEncoder,
    documents: Sequence[str],
    *,
    quantiles: Sequence[float] = (
        0.5,
        0.9,
        0.99,
        0.999,
        0.9999,
    ),
    shifts: Sequence[float] = (),
    batch_size: int = 16,
    seed: int = 42,
) -> dict[str, Any]

Where the content-token logits of a vocabulary head lie, before its shift.

quantiles maps each quantile to the logit there; a shift set to that logit lets the remaining share through. active_share gives, for the head's own shift, for zero and for every value in shifts, the share of (token, vocabulary) logits above it, which is the share of entries that are non-zero before the per-token fan-out and the pooling. SPARSEUP sets the shift near the 99.9th percentile; Geng and Yang report a flat optimum when 30% to 50% of the entries are active at the start, for a different head and loss.

Raises:

  • TypeError –

    if the model's document head is not a VocabularyPooling.

Source code in src/muscari/evaluation/diagnostics/vectors.py
@torch.no_grad()
def logit_report(
    model: SparseEncoder,
    documents: Sequence[str],
    *,
    quantiles: Sequence[float] = (0.5, 0.9, 0.99, 0.999, 0.9999),
    shifts: Sequence[float] = (),
    batch_size: int = 16,
    seed: int = 42,
) -> dict[str, Any]:
    """Where the content-token logits of a vocabulary head lie, before its shift.

    ``quantiles`` maps each quantile to the logit there; a shift set to that logit lets the
    remaining share through. ``active_share`` gives, for the head's own shift, for zero and for
    every value in ``shifts``, the share of ``(token, vocabulary)`` logits above it, which is
    the share of entries that are non-zero before the per-token fan-out and the pooling.
    SPARSEUP sets the shift near the 99.9th percentile; Geng and Yang report a flat optimum when
    30% to 50% of the entries are active at the start, for a different head and loss.

    Raises:
        TypeError: if the model's document head is not a ``VocabularyPooling``.
    """
    head = head_of(model, "document")
    if not isinstance(head, VocabularyPooling):
        raise TypeError("logit_report needs a model whose document head is a VocabularyPooling.")

    values = sample_content_logits(model, documents, batch_size=batch_size, seed=seed)
    candidates = sorted({0.0, float(head.shift), *(float(shift) for shift in shifts)})

    return {
        "sampled_logits": int(values.numel()),
        "shift": float(head.shift),
        "fan_out": head.fan_out,
        "mean": float(values.mean()),
        "std": float(values.std()),
        "max": float(values.max()),
        "quantiles": {str(q): float(torch.quantile(values, q)) for q in quantiles},
        "active_share": {str(shift): float((values > shift).float().mean()) for shift in candidates},
    }

contrastive_report

contrastive_report(
    model: SparseEncoder,
    queries: Sequence[str],
    positives: Sequence[str],
    *,
    scales: Sequence[float] = (1.0, 0.5, 0.2, 0.1, 0.05),
    batch_size: int = 16,
    encode_batch_size: int = 16,
) -> dict[str, Any]

The in-batch contrastive loss of (query, positive) pairs at several scales of the scores.

The pairs are cut into consecutive batches of batch_size; within a batch the positives of the other queries are the negatives, as in the training loss. For every scale the report gives the mean loss and the mean probability the softmax puts on the positive. A loss far above chance_loss (the logarithm of the batch size) means the softmax is saturated on wrong documents, which a smaller scale relieves; accuracy, the share of queries whose positive scores highest, does not depend on the scale.

Source code in src/muscari/evaluation/diagnostics/losses.py
@torch.no_grad()
def contrastive_report(
    model: SparseEncoder,
    queries: Sequence[str],
    positives: Sequence[str],
    *,
    scales: Sequence[float] = (1.0, 0.5, 0.2, 0.1, 0.05),
    batch_size: int = 16,
    encode_batch_size: int = 16,
) -> dict[str, Any]:
    """The in-batch contrastive loss of ``(query, positive)`` pairs at several scales of the scores.

    The pairs are cut into consecutive batches of ``batch_size``; within a batch the positives of
    the other queries are the negatives, as in the training loss. For every scale the report
    gives the mean loss and the mean probability the softmax puts on the positive. A loss far
    above ``chance_loss`` (the logarithm of the batch size) means the softmax is saturated on
    wrong documents, which a smaller scale relieves; ``accuracy``, the share of queries whose
    positive scores highest, does not depend on the scale.
    """
    if len(queries) != len(positives):
        raise ValueError("contrastive_report needs one positive per query.")
    if len(queries) < 2:
        raise ValueError("contrastive_report needs at least two pairs.")

    query_vectors = encode_side(model, queries, "query", encode_batch_size)
    document_vectors = encode_side(model, positives, "document", encode_batch_size)
    batches = [
        query_vectors[start : start + batch_size] @ document_vectors[start : start + batch_size].T
        for start in range(0, len(queries), batch_size)
    ]
    batches = [scores for scores in batches if scores.shape[0] > 1]

    positive_scores = torch.cat([scores.diagonal() for scores in batches])
    negative_scores = torch.cat([scores[~torch.eye(scores.shape[0], dtype=torch.bool)] for scores in batches])
    pairs = int(positive_scores.shape[0])
    correct = sum(int((scores.argmax(dim=1) == torch.arange(scores.shape[0])).sum()) for scores in batches)

    return {
        "pairs": pairs,
        "batch_size": batch_size,
        "chance_loss": math.log(batch_size),
        "accuracy": correct / pairs,
        "positive_score_mean": float(positive_scores.mean()),
        "negative_score_mean": float(negative_scores.mean()),
        "negative_score_std": float(negative_scores.std()) if negative_scores.numel() > 1 else 0.0,
        "scales": _per_scale(batches, scales, pairs),
    }

teacher_report

teacher_report(
    positive_scores: Sequence[float] | Tensor,
    negative_scores: Sequence[Sequence[float]] | Tensor,
    *,
    temperatures: Sequence[float] = (0.5, 1.0, 2.0, 5.0),
    probabilities: bool = False,
    epsilon: float = 0.0001,
) -> dict[str, Any]

How spread a teacher's scores of each query's positive and negatives are.

negative_scores has one row per query with the same number of negatives. With probabilities the scores are turned into logits first, clamped to [epsilon, 1 - epsilon]. margin is the positive's score minus the best negative's; positive_not_first is the share of queries where a negative scores at least as high. For every temperature the report gives what the softmax of the scores divided by it looks like: the mean probability of the positive, the mean entropy, and the share of queries where the positive gets more than 0.99, for which the distillation target is close to the hard label the contrastive loss already uses.

Source code in src/muscari/evaluation/diagnostics/losses.py
def teacher_report(
    positive_scores: Sequence[float] | torch.Tensor,
    negative_scores: Sequence[Sequence[float]] | torch.Tensor,
    *,
    temperatures: Sequence[float] = (0.5, 1.0, 2.0, 5.0),
    probabilities: bool = False,
    epsilon: float = 1e-4,
) -> dict[str, Any]:
    """How spread a teacher's scores of each query's positive and negatives are.

    ``negative_scores`` has one row per query with the same number of negatives. With
    ``probabilities`` the scores are turned into logits first, clamped to
    ``[epsilon, 1 - epsilon]``. ``margin`` is the positive's score minus the best negative's;
    ``positive_not_first`` is the share of queries where a negative scores at least as high.
    For every temperature the report gives what the softmax of the scores divided by it looks
    like: the mean probability of the positive, the mean entropy, and the share of queries where
    the positive gets more than 0.99, for which the distillation target is close to the hard
    label the contrastive loss already uses.
    """
    positive = torch.as_tensor(positive_scores, dtype=torch.float64).reshape(-1)
    negative = torch.as_tensor(negative_scores, dtype=torch.float64)
    if negative.ndim != 2 or negative.shape[0] != positive.shape[0] or negative.shape[1] == 0:
        raise ValueError("teacher_report needs a (queries, negatives) table of negative scores, one row per positive.")

    if probabilities:
        positive, negative = (torch.logit(scores.clamp(epsilon, 1 - epsilon)) for scores in (positive, negative))
    scores = torch.cat([positive.unsqueeze(1), negative], dim=1)
    margin = positive - negative.max(dim=1).values

    return {
        "queries": int(positive.shape[0]),
        "negatives": int(negative.shape[1]),
        "scores_are_logits_of_probabilities": probabilities,
        "positive_mean": float(positive.mean()),
        "negative_mean": float(negative.mean()),
        "margin_quantiles": {str(q): float(torch.quantile(margin, q)) for q in QUANTILES},
        "positive_not_first": float((margin <= 0).double().mean()),
        "max_entropy": math.log(scores.shape[1]),
        "temperatures": _per_temperature(scores, temperatures),
    }