muscari.analysis¶
Measure an SAE as a retriever would use it: pooled per text, per latent, and in reranking.
Per text and per latent¶
evaluate_texts
¶
evaluate_texts(
sae: ExportedSAE,
texts: Sequence[EncodedText],
batch_tokens: int = 1024,
) -> dict[str, Any]
Measure the pooled, per-text vectors that a sparse index would store.
A latent is active in a text when it is active on at least one of its tokens, which is the
sparsity pattern of max pooling. Saturating the values, for example with log1p, does
not change it.
Returns:
-
dict[str, Any]–by_kind: for each kind, the number of texts, the mean tokens per text, the mean, -
dict[str, Any]–median and 95th percentile of active latents per text (
l0), the share of latents -
dict[str, Any]–never active (
never_fired_frac), the share active in more than 10% of the texts -
dict[str, Any]–(
dense_frac) and the largest share of texts one latent is active in -
dict[str, Any]–(
max_document_frequency). -
dict[str, Any]–flops: for each pair of kinds, the sum over latents of the product of their -
dict[str, Any]–activation probabilities. This estimates the number of multiplications when a text of
-
dict[str, Any]–one kind is scored against a text of the other through an inverted index. It is the
-
dict[str, Any]–FLOPS figure as naver/splade computes it from a query index and a document index.
Raises:
-
ValueError–if
textsis empty.
Source code in src/muscari/analysis/texts.py
latent_statistics
¶
latent_statistics(
sae: ExportedSAE,
texts: Sequence[EncodedText],
top_n: int = 10,
batch_tokens: int = 1024,
) -> list[dict[str, Any]]
For every latent, how often it fires, where in a text, and on which vocabulary tokens.
A latent can follow a token, a kind of text or a position rather than a meaning. The record of a latent holds what is needed to tell these apart:
latent: its index.
frequency: the share of tokens it fires on.
frequency_by_kind: the same share among the tokens of each kind.
text_frequency: the share of texts in which it fires on at least one token.
mean_activation: its mean value where it fires (0 if it never does).
first_token_share, last_token_share: the part of its firings that fall on the first
and on the last content token of a text. Compare with 1 / tokens per text.
mean_position: the mean relative position of its firings, from 0 for the first token
of a text to 1 for the last (0.5 if it never fires).
top_tokens: up to top_n entries {"token_id", "share", "token_rate"}, where
share is the part of the latent's firings that fall on this token and token_rate is
the part of this token's occurrences on which the latent fires. A latent with one token at
a share and token_rate near 1 behaves like a vocabulary entry for that token.
Records are sorted by frequency, highest first. A text cut by max_seq_length or by the
token budget of the collection ends early, so its last token is not the end of the original.
The number of distinct (latent, token) pairs is kept in memory; a few million evaluated
tokens are fine.
Raises:
-
ValueError–if
textsis empty ortop_nis not positive.
Source code in src/muscari/analysis/latents.py
Why two texts match¶
shared_latents
¶
shared_latents(
source: EncoderActivationSource,
sae: ExportedSAE,
query: str,
document: str,
*,
query_prompt: str = "",
document_prompt: str = "",
top: int | None = 10,
) -> list[SharedLatent]
The latents active in both texts, largest contribution to their score first.
Each text is pooled as an SAE-based retriever pools it before any training: the maximum over
the content tokens of log1p(activation). The score of the pair is the dot product of the
two pooled vectors, and a shared latent contributes the product of its two weights.
Parameters:
-
source(EncoderActivationSource) –the encoder the SAE was trained on.
-
sae(ExportedSAE) –an exported SAE.
-
query(str) –the first text.
-
document(str) –the second text.
-
query_prompt(str, default:'') –prompt the encoder expects for queries, or the name of one of the source's prompts.
-
document_prompt(str, default:'') –the same for documents.
-
top(int | None, default:10) –how many latents to return;
Nonefor all of them.
Returns:
-
list[SharedLatent]–One entry per shared latent; empty when the texts share none or one of them has no
-
list[SharedLatent]–content token.
Source code in src/muscari/analysis/matches.py
SharedLatent
¶
Bases: NamedTuple
One latent that is active in both texts.
Attributes:
-
latent(int) –index of the latent.
-
weight(float) –product of the two texts' pooled weights for it. Over all shared latents the weights add up to the dot product of the pooled vectors.
-
query_token(str) –the token of the query on which the latent is strongest.
-
document_token(str) –the same for the document.
token_latents
¶
token_latents(
source: EncoderActivationSource,
sae: ExportedSAE,
text: str,
*,
prompt: str = "",
) -> TokenLatents
Encode one text and return its content tokens with their latent activations.
prompt is prepended as given, or names one of the source's prompts. The activations are
dense, num_latents values per token, so this is for looking at single texts.
Source code in src/muscari/analysis/matches.py
TokenLatents
¶
Bases: NamedTuple
The content tokens of one text and what the SAE makes of each.
Attributes:
-
tokens(list[str]) –the tokenizer's token behind each row.
-
features(Tensor) –(n_content_tokens, num_latents)activations, on the SAE's device.
Through the language-model head¶
load_masked_lm
¶
Load an encoder together with its language-model head.
Raises:
-
ValueError–if the checkpoint holds no trained head, as with encoders saved after fine-tuning as embedding models. A head initialised at random would yield a loss that means nothing.
Source code in src/muscari/analysis/mlm.py
mlm_loss_recovered
¶
mlm_loss_recovered(
sae: ExportedSAE,
model: Any,
source: EncoderActivationSource,
texts: Sequence[tuple[str, str]],
*,
mask_probability: float = 0.15,
batch_size: int = 4,
seed: int = 42,
) -> dict[str, float]
Compare the masked-language-model loss with and without the SAE in the path.
Each content token is replaced by the mask token with probability mask_probability.
The loss is the mean cross-entropy over the masked positions, measured three times on the
same masked inputs: with the encoder untouched (loss_clean), with the final hidden
state of every content position replaced by the SAE's reconstruction (loss_spliced),
and with it replaced by the mean of those states over all evaluated texts
(loss_mean). Special and prompt positions are never replaced.
Parameters:
-
sae(ExportedSAE) –an exported SAE trained on
last_hidden_stateof this encoder. -
model(Any) –the encoder with its head, from
load_masked_lm. It is moved to the device ofsource. -
source(EncoderActivationSource) –supplies the tokenizer, the prompts, the truncation length and the content mask. Its own model is not used.
-
texts(Sequence[tuple[str, str]]) –(kind, text)pairs, as for the other methods ofsource. -
mask_probability(float, default:0.15) –share of content tokens masked.
-
batch_size(int, default:4) –texts per forward pass. The head produces one logit per vocabulary entry and position, so keep this small.
-
seed(int, default:42) –seed of the mask.
Returns:
-
dict[str, float]–loss_clean,loss_spliced,loss_mean,recovered -
dict[str, float]–= (loss_mean - loss_spliced) / (loss_mean - loss_clean),masked_tokensand -
dict[str, float]–texts.
Raises:
-
ValueError–if the tokenizer has no mask token,
textsis empty or nothing was masked.
Source code in src/muscari/analysis/mlm.py
Reranking probe¶
probe_reranking
¶
probe_reranking(
source: EncoderActivationSource,
sae: ExportedSAE,
examples: Sequence[RerankingExample],
*,
query_kind: str = "",
document_kind: str = "",
k: int = 10,
seed: int = 42,
bm25: BM25Settings | None = None,
masked_latents: Sequence[int] = (),
) -> dict[str, Any]
Rerank the candidates of every query densely and sparsely, with nothing trained.
Parameters:
-
source(EncoderActivationSource) –the encoder the SAE was trained on.
-
sae(ExportedSAE) –the exported SAE.
-
examples(Sequence[RerankingExample]) –queries with candidates and binary labels.
-
query_kind(str, default:'') –the prompt to prepend to queries, or the name of a prompt in
source.prompts. -
document_kind(str, default:'') –the same for documents.
-
k(int, default:10) –cut-off of nDCG and MRR.
-
seed(int, default:42) –candidates are shuffled with this seed before ranking, so that ties are not broken by the order of the dataset.
-
bm25(BM25Settings | None, default:None) –the BM25 over summed activations to report; default
BM25Settings(). -
masked_latents(Sequence[int], default:()) –latents to leave out of every sparse vector, as
masked_latentsdoes in an SAE head. The dense rankings do not change.
Returns:
-
dict[str, Any]–Every nDCG@k and MRR@k below is a mean over the queries and comes with its standard
-
dict[str, Any]–error under the key
<metric>_stderr. -
dict[str, Any]–dense: for each oforiginal,splicedandempty(seePooledText), -
dict[str, Any]–nDCG@k and MRR@k of ranking by cosine similarity of the sentence embeddings, and
-
dict[str, Any]–recovered:(spliced - empty) / (original - empty)for each metric, the share -
dict[str, Any]–of the encoder's ranking quality that survives the SAE, with 1 for all of it.
-
dict[str, Any]–cosineholds the similarity between the original and the spliced embedding of the -
dict[str, Any]–same text.
-
dict[str, Any]–hybrid: nDCG@k and MRR@k of rankings that fusedense.originalwith -
dict[str, Any]–sparse.plain, both of which come from one pass through the encoder.rrfis -
dict[str, Any]–reciprocal rank fusion, which has nothing to tune.
weightedmaps a weight of the -
dict[str, Any]–dense score, from 0.1 to 0.9, to the ranking by
fuse_scores; choose the weight on -
dict[str, Any]–one split and report it on another. Every entry also holds
over_denseand -
dict[str, Any]–over_sparse: the mean per-query gain over each fused ranking, with the standard -
dict[str, Any]–error of that paired difference.
-
dict[str, Any]–sparse: nDCG@k and MRR@k of ranking by the dot product of the pooled sparse -
vectors(dict[str, Any]) –plainas they are, andidfwith every latent weighted by -
dict[str, Any]–ln(1 + (N - df + 0.5) / (df + 0.5)), wheredfis the number of theN -
dict[str, Any]–distinct candidate documents it is active in.
l0is the mean number of active -
dict[str, Any]–latents of a query and of a document.
bm25ranks by BM25 over summed activations as -
dict[str, Any]–muscari.analysis.latent_termsdescribes, with the settings ofbm25; it also -
dict[str, Any]–holds
over_plain,over_idfandover_dense, its paired gains over those -
dict[str, Any]–rankings, and
majority_latents, the number of latents active in more than half of -
dict[str, Any]–the documents, for which the paper's IDF is negative.
sum_dotranks by the inner -
dict[str, Any]–product of the same weights.
flopsis the sum over latents of the share of -
dict[str, Any]–queries times the share of documents in which the latent is active.
masked_latents -
dict[str, Any]–lists the latents that were left out, each with those two shares and its part of
-
dict[str, Any]–flopsbefore it was removed.
Raises:
-
ValueError–if
examplesis empty or a masked latent is outside the SAE.
Source code in src/muscari/analysis/probe/report.py
BM25Settings
dataclass
¶
The BM25 over summed activations that the probe reports, as LatentTermBM25 defines it.
RerankingExample
dataclass
¶
RerankingExample(
query: str,
documents: tuple[str, ...],
labels: tuple[int, ...],
query_id: str | None = None,
)
One query with its candidate documents; labels are 1 for relevant and 0 otherwise.
query_id identifies the query across runs, so per-query results can be paired.
group_reranking_rows
¶
group_reranking_rows(
rows: Iterable[Mapping[str, Any]],
*,
query_column: str,
document_column: str,
label_column: str,
group_column: str | None = None,
title_column: str | None = None,
max_queries: int | None = None,
) -> list[RerankingExample]
Group long-format rows, one candidate document per row, into one example per query.
Rows belong together when they share the value of group_column, or the query text if
no such column is given; that value becomes the query_id. Queries are taken in order
of first appearance; with max_queries only the first ones are kept, so shuffle the rows
beforehand to draw a sample. Queries without a relevant candidate cannot be scored and are
left out.
With title_column a document is "{title} {text}", the form the JQaRA evaluator uses.
Raises:
-
ValueError–if a column is missing or no query with a relevant candidate is found.
Source code in src/muscari/analysis/probe/examples.py
probe_collection
¶
probe_collection(
collection: PooledCollection,
examples: Sequence[RerankingExample],
*,
k: int = 10,
seed: int = 42,
bm25: BM25Settings | None = None,
) -> dict[str, Any]
The rankings of probe_reranking for texts that are already pooled.
Pooling is the expensive part, so several maskings of one collection can be compared by
pooling once with pool_collection and passing without(collection, latents) here.
Source code in src/muscari/analysis/probe/report.py
pool_collection
¶
pool_collection(
source: EncoderActivationSource,
sae: ExportedSAE,
examples: Sequence[RerankingExample],
query_kind: str,
document_kind: str,
) -> PooledCollection
Pool the distinct queries and documents of examples, each once.
Source code in src/muscari/analysis/probe/collection.py
PooledCollection
dataclass
¶
PooledCollection(
queries: dict[str, PooledText],
documents: dict[str, PooledText],
num_latents: int,
)
Pooled queries and documents, keyed by their text, and the latent weights over the documents.
weights maps plain to ones and idf to ln(1 + (N - df + 0.5) / (df + 0.5)).
bm25
¶
bm25(
*, k1: float, b: float, transform: str, idf_form: str
) -> LatentTermBM25
BM25 over the summed activations of the documents, as LatentTermBM25 defines it.
Source code in src/muscari/analysis/probe/collection.py
mean_l0
¶
Mean number of active latents of a query and of a document.
Source code in src/muscari/analysis/probe/collection.py
without
¶
without(
collection: PooledCollection, latents: Sequence[int]
) -> PooledCollection
A collection in which latents are active in no query and no document.
The sentence embeddings are kept as they are: masking changes what is indexed, not what the SAE reconstructs.
Raises:
-
ValueError–if a latent is outside the SAE.
Source code in src/muscari/analysis/probe/masking.py
text_frequencies
¶
text_frequencies(
collection: PooledCollection,
) -> tuple[Tensor, Tensor]
Per latent, the share of the queries and the share of the documents in which it is active.
Source code in src/muscari/analysis/probe/masking.py
flops
¶
flops(collection: PooledCollection) -> float
The sum over latents of P(active in a query) * P(active in a document).
It is the expected number of multiplications when one query is scored against one document through an inverted index, measured on the queries and documents of this collection.
Source code in src/muscari/analysis/probe/masking.py
PooledText
¶
Bases: NamedTuple
What a retriever would keep of one text.
Attributes:
-
indices(Tensor) –(nnz,)latents active on at least one content token, ascending. -
values(Tensor) –(nnz,)the maximum over the content tokens oflog1p(activation). -
embeddings(Tensor) –(3, d_in)mean-pooled sentence embeddings in the order ofVARIANTS: from the encoder's own token states, with the content tokens replaced by the SAE's reconstruction, and with them replaced by the SAE's decoder bias, which is what the SAE returns for an empty code. -
sums(Tensor | None) –(nnz,)the sum over the content tokens of the activation, the quantity thatmuscari.analysis.latent_termsscores;Nonewhen it was not computed.
pool_texts
¶
pool_texts(
source: EncoderActivationSource,
sae: ExportedSAE,
kind: str,
texts: Sequence[str],
token_chunk: int = 2048,
) -> list[PooledText]
Encode texts and reduce each one to its sparse vector and its sentence embeddings.
The sparse vector is the one an SAE-based sparse retriever starts from: log1p of the
SAE's activations, then the maximum over the content tokens. The sentence embeddings are
means over every attended position, which is the pooling of the ruri family and of most
encoders trained as embedding models; they mean little for an encoder that was not.
The SAE must have been trained on last_hidden_state for the embeddings to be valid.
Source code in src/muscari/analysis/probe/pooling.py
ranking_metrics
¶
nDCG@k and MRR@k of one query with binary labels, ranking by descending scores.
Candidates with equal scores keep their input order, so shuffle them first if that order could carry information. The ideal ranking for nDCG puts every relevant candidate first.
Raises:
-
ValueError–if no candidate is relevant.
Source code in src/muscari/analysis/probe/scoring.py
sparse_scores
¶
sparse_scores(
query: PooledText,
documents: Sequence[PooledText],
weights: Tensor,
) -> Tensor
Dot products of the query's sparse vector with each document's, with one weight per latent.
Source code in src/muscari/analysis/probe/scoring.py
fuse_scores
¶
dense_weight * z(dense) + (1 - dense_weight) * z(sparse) over one query's candidates.
z standardises a score list to zero mean and unit variance among the candidates, so the
two scales become comparable; a constant list contributes nothing. The standardisation
needs all candidates of the query, as in reranking.
Source code in src/muscari/analysis/probe/scoring.py
reciprocal_rank_fusion
¶
Sum over the lists of 1 / (constant + rank), with rank 1 for the highest score.
Reciprocal rank fusion (Cormack et al., 2009) uses only the ranks, so it has nothing to tune; 60 is the constant of that paper. Equal scores keep their input order.
Source code in src/muscari/analysis/probe/scoring.py
BM25 over latents¶
LatentTermBM25
dataclass
¶
LatentTermBM25(
documents: Sequence[SparseText],
num_latents: int,
k1: float = 8.0,
b: float = 0.7,
transform: str = "sqrt",
idf_form: str = "lucene",
)
BM25 with the paper's defaults over a fixed set of documents.
Parameters:
-
documents(Sequence[SparseText]) –the collection; every document as its active latents and their summed activations.
-
num_latents(int) –size of the SAE's dictionary.
-
k1(float, default:8.0) –BM25's saturation.
-
b(float, default:0.7) –BM25's length normalisation.
-
transform(str, default:'sqrt') –name of
phiinTRANSFORMS. -
idf_form(str, default:'lucene') –name of the IDF in
IDF_FORMS;"lucene"is never negative and"okapi"is the paper's.
Raises:
-
ValueError–if
documentsis empty, ortransformoridf_formis unknown.
document_frequency
cached
property
¶
Number of documents in which each latent is active.
idf
cached
property
¶
IDF of every latent over the documents, in the form idf_form names.
majority_latents
property
¶
Latents active in more than half of the documents, whose Okapi IDF is negative.
average_length
cached
property
¶
Mean over the documents of the sum of their weights.
weights
¶
scores
¶
BM25 of query against each of candidates, with the collection's statistics.
Source code in src/muscari/analysis/latent_terms.py
dot
¶
Inner product of the same weights, without IDF, saturation or length normalisation.
Source code in src/muscari/analysis/latent_terms.py
okapi_idf
¶
log((N - n + 0.5) / (n + 0.5)); negative for a latent active in more than half.
Source code in src/muscari/analysis/term_weights.py
lucene_idf
¶
log(1 + (N - n + 0.5) / (n + 0.5)); positive for every latent.