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]–rerankingandretrieval(keyed by dataset), each asrerankandretrieve -
dict[str, Any]–return it, with the time taken in
seconds.
Source code in src/muscari/evaluation/plan.py
summary
¶
The averaged metrics of an evaluation, without the per-query values.
Source code in src/muscari/evaluation/plan.py
add_evaluation_arguments
¶
Add the options of an EvaluationPlan; prefix keeps them apart from a script's own options.
Source code in src/muscari/evaluation/options.py
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
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
modelnorsaeis given.
Source code in src/muscari/evaluation/models.py
needs_remote_code
¶
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
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
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
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
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
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
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
resampleis unknown.
Source code in src/muscari/evaluation/comparison.py
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
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
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
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
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
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.