Skip to content
Edit this page

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 texts is empty.

Source code in src/muscari/analysis/texts.py
@torch.no_grad()
def 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:
        ``by_kind``: for each kind, the number of texts, the mean tokens per text, the mean,
        median and 95th percentile of active latents per text (``l0``), the share of latents
        never active (``never_fired_frac``), the share active in more than 10% of the texts
        (``dense_frac``) and the largest share of texts one latent is active in
        (``max_document_frequency``).

        ``flops``: for each pair of kinds, the sum over latents of the product of their
        activation probabilities. This estimates the number of multiplications when a text of
        one kind is scored against a text of the other through an inverted index. It is the
        FLOPS figure as naver/splade computes it from a query index and a document index.

    Raises:
        ValueError: if ``texts`` is empty.
    """
    if not texts:
        raise ValueError("texts is empty.")

    counts = _PooledCounts(kinds_of(texts), sae.num_latents)
    for batch in token_batches(texts, batch_tokens):
        counts.add(sae, batch)

    probabilities = counts.probabilities()
    kinds = list(probabilities)
    flops = [
        {"kinds": [first, second], "flops": (probabilities[first] * probabilities[second]).sum().item()}
        for position, first in enumerate(kinds)
        for second in kinds[position:]
    ]

    by_kind = {kind: counts.summary(kind, probability) for kind, probability in probabilities.items()}
    return {"by_kind": by_kind, "flops": flops}

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 texts is empty or top_n is not positive.

Source code in src/muscari/analysis/latents.py
@torch.no_grad()
def 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 ``texts`` is empty or ``top_n`` is not positive.
    """
    if not texts:
        raise ValueError("texts is empty.")
    if top_n < 1:
        raise ValueError("top_n must be positive.")

    vocabulary = int(max(int(text.token_ids.max()) for text in texts)) + 1
    counts = LatentCounts(kinds_of(texts), sae.num_latents, vocabulary)

    for batch in token_batches(texts, batch_tokens):
        counts.add(sae, batch)

    return _records(counts, len(texts), top_n)

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; None for 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
@torch.no_grad()
def 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.

    Args:
        source: the encoder the SAE was trained on.
        sae: an exported SAE.
        query: the first text.
        document: the second text.
        query_prompt: prompt the encoder expects for queries, or the name of one of the
            source's prompts.
        document_prompt: the same for documents.
        top: how many latents to return; ``None`` for all of them.

    Returns:
        One entry per shared latent; empty when the texts share none or one of them has no
        content token.
    """
    query_side = token_latents(source, sae, query, prompt=query_prompt)
    document_side = token_latents(source, sae, document, prompt=document_prompt)
    if not query_side.tokens or not document_side.tokens:
        return []

    query_weights, query_rows = _pooled(query_side)
    document_weights, document_rows = _pooled(document_side)
    products = query_weights * document_weights

    shared = int((products > 0).sum())
    values, latents = products.topk(shared if top is None else min(top, shared))

    return [
        SharedLatent(
            latent,
            value,
            query_side.tokens[int(query_rows[latent])],
            document_side.tokens[int(document_rows[latent])],
        )
        for value, latent in zip(values.tolist(), latents.tolist(), strict=True)
    ]

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
@torch.no_grad()
def 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.
    """
    batch = source.encode_texts([prompt], [text])
    features = sae.encode(batch.activations.to(sae.encoder_weight.device))
    tokens = source.tokenizer.convert_ids_to_tokens(batch.token_ids.tolist())

    return TokenLatents(tokens, features)

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_masked_lm(
    model_name_or_path: str, *, revision: str | None = None
) -> Any

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
def load_masked_lm(model_name_or_path: str, *, revision: str | None = None) -> Any:
    """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.
    """
    from transformers import AutoModelForMaskedLM

    model, info = AutoModelForMaskedLM.from_pretrained(model_name_or_path, revision=revision, output_loading_info=True)

    # The output projection is usually tied to the input embeddings and then absent from the file.
    missing = sorted(key for key in info["missing_keys"] if not key.endswith(("decoder.weight", "decoder.bias")))
    if missing:
        raise ValueError(f"{model_name_or_path} has no trained language-model head (missing weights: {missing[:3]}).")

    return model

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_state of this encoder.

  • model (Any) –

    the encoder with its head, from load_masked_lm. It is moved to the device of source.

  • 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 of source.

  • 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_tokens and

  • dict[str, float] –

    texts.

Raises:

  • ValueError –

    if the tokenizer has no mask token, texts is empty or nothing was masked.

Source code in src/muscari/analysis/mlm.py
@torch.no_grad()
def 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.

    Args:
        sae: an exported SAE trained on ``last_hidden_state`` of this encoder.
        model: the encoder with its head, from ``load_masked_lm``. It is moved to the device of
            ``source``.
        source: supplies the tokenizer, the prompts, the truncation length and the content
            mask. Its own model is not used.
        texts: ``(kind, text)`` pairs, as for the other methods of ``source``.
        mask_probability: share of content tokens masked.
        batch_size: texts per forward pass. The head produces one logit per vocabulary entry
            and position, so keep this small.
        seed: seed of the mask.

    Returns:
        ``loss_clean``, ``loss_spliced``, ``loss_mean``, ``recovered``
        ``= (loss_mean - loss_spliced) / (loss_mean - loss_clean)``, ``masked_tokens`` and
        ``texts``.

    Raises:
        ValueError: if the tokenizer has no mask token, ``texts`` is empty or nothing was masked.
    """
    if getattr(source.tokenizer, "mask_token_id", None) is None:
        raise ValueError("The tokenizer has no mask token.")
    if not texts:
        raise ValueError("texts is empty.")
    if not 0 < mask_probability < 1:
        raise ValueError("mask_probability must be between 0 and 1.")

    batches = masked_batches(source, texts, mask_probability=mask_probability, batch_size=batch_size, seed=seed)
    if not batches:
        raise ValueError("No token was masked; give more or longer texts.")

    device = source.device
    model = model.to(device).eval()
    sae = sae.to(device)
    mean_state = _MeanState(sae.d_in)
    masked_tokens = sum(int(batch.masked.sum()) for batch in batches)

    clean = masked_loss(model, batches, device, observe=mean_state) / masked_tokens
    spliced = masked_loss(model, batches, device, replace=sae.forward) / masked_tokens
    mean = mean_state.mean().to(device)
    ablated = masked_loss(model, batches, device, replace=lambda states: mean.expand_as(states)) / masked_tokens

    return {
        "loss_clean": clean,
        "loss_spliced": spliced,
        "loss_mean": ablated,
        "recovered": (ablated - spliced) / (ablated - clean),
        "masked_tokens": masked_tokens,
        "texts": len(texts),
    }

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_latents does 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 of original, spliced and empty (see PooledText),

  • 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] –

    cosine holds 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 fuse dense.original with

  • dict[str, Any] –

    sparse.plain, both of which come from one pass through the encoder. rrf is

  • dict[str, Any] –

    reciprocal rank fusion, which has nothing to tune. weighted maps 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_dense and

  • 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] ) –

    plain as they are, and idf with every latent weighted by

  • dict[str, Any] –

    ln(1 + (N - df + 0.5) / (df + 0.5)), where df is the number of the N

  • dict[str, Any] –

    distinct candidate documents it is active in. l0 is the mean number of active

  • dict[str, Any] –

    latents of a query and of a document. bm25 ranks by BM25 over summed activations as

  • dict[str, Any] –

    muscari.analysis.latent_terms describes, with the settings of bm25; it also

  • dict[str, Any] –

    holds over_plain, over_idf and over_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_dot ranks by the inner

  • dict[str, Any] –

    product of the same weights. flops is 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] –

    flops before it was removed.

Raises:

  • ValueError –

    if examples is empty or a masked latent is outside the SAE.

Source code in src/muscari/analysis/probe/report.py
def 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.

    Args:
        source: the encoder the SAE was trained on.
        sae: the exported SAE.
        examples: queries with candidates and binary labels.
        query_kind: the prompt to prepend to queries, or the name of a prompt in ``source.prompts``.
        document_kind: the same for documents.
        k: cut-off of nDCG and MRR.
        seed: candidates are shuffled with this seed before ranking, so that ties are not
            broken by the order of the dataset.
        bm25: the BM25 over summed activations to report; default ``BM25Settings()``.
        masked_latents: latents to leave out of every sparse vector, as ``masked_latents``
            does in an SAE head. The dense rankings do not change.

    Returns:
        Every nDCG@k and MRR@k below is a mean over the queries and comes with its standard
        error under the key ``<metric>_stderr``.

        ``dense``: for each of ``original``, ``spliced`` and ``empty`` (see ``PooledText``),
        nDCG@k and MRR@k of ranking by cosine similarity of the sentence embeddings, and
        ``recovered``: ``(spliced - empty) / (original - empty)`` for each metric, the share
        of the encoder's ranking quality that survives the SAE, with 1 for all of it.
        ``cosine`` holds the similarity between the original and the spliced embedding of the
        same text.

        ``hybrid``: nDCG@k and MRR@k of rankings that fuse ``dense.original`` with
        ``sparse.plain``, both of which come from one pass through the encoder. ``rrf`` is
        reciprocal rank fusion, which has nothing to tune. ``weighted`` maps a weight of the
        dense score, from 0.1 to 0.9, to the ranking by ``fuse_scores``; choose the weight on
        one split and report it on another. Every entry also holds ``over_dense`` and
        ``over_sparse``: the mean per-query gain over each fused ranking, with the standard
        error of that paired difference.

        ``sparse``: nDCG@k and MRR@k of ranking by the dot product of the pooled sparse
        vectors: ``plain`` as they are, and ``idf`` with every latent weighted by
        ``ln(1 + (N - df + 0.5) / (df + 0.5))``, where ``df`` is the number of the ``N``
        distinct candidate documents it is active in. ``l0`` is the mean number of active
        latents of a query and of a document. ``bm25`` ranks by BM25 over summed activations as
        ``muscari.analysis.latent_terms`` describes, with the settings of ``bm25``; it also
        holds ``over_plain``, ``over_idf`` and ``over_dense``, its paired gains over those
        rankings, and ``majority_latents``, the number of latents active in more than half of
        the documents, for which the paper's IDF is negative. ``sum_dot`` ranks by the inner
        product of the same weights. ``flops`` is the sum over latents of the share of
        queries times the share of documents in which the latent is active. ``masked_latents``
        lists the latents that were left out, each with those two shares and its part of
        ``flops`` before it was removed.

    Raises:
        ValueError: if ``examples`` is empty or a masked latent is outside the SAE.
    """
    if not examples:
        raise ValueError("examples is empty.")

    collection = pool_collection(source, sae, examples, query_kind, document_kind)
    report = probe_collection(without(collection, masked_latents), examples, k=k, seed=seed, bm25=bm25)
    report["sparse"]["masked_latents"] = masked_record(collection, masked_latents)

    return report

BM25Settings dataclass

BM25Settings(
    k1: float = 8.0,
    b: float = 0.7,
    transform: str = "sqrt",
    idf_form: str = "lucene",
)

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
def 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.
    """
    key_column = group_column or query_column
    needed = {key_column, query_column, document_column, label_column} | ({title_column} if title_column else set())
    grouped: dict[Any, tuple[str, list[str], list[int]]] = {}

    for row in rows:
        if missing := sorted(needed - set(row)):
            raise ValueError(f"The data has no column {missing}; it has {sorted(row)}.")

        key = row[key_column]
        if key not in grouped:
            if max_queries is not None and len(grouped) >= max_queries:
                continue
            grouped[key] = (str(row[query_column]), [], [])

        document = str(row[document_column])
        if title_column:
            document = f"{row[title_column]} {document}"

        grouped[key][1].append(document)
        grouped[key][2].append(int(row[label_column] > 0))

    examples = [
        RerankingExample(query, tuple(documents), tuple(labels), str(key))
        for key, (query, documents, labels) in grouped.items()
        if any(labels)
    ]
    if not examples:
        raise ValueError("No query with a relevant candidate was found; check the column names.")

    return examples

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
def 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.
    """
    settings = bm25 or BM25Settings()
    latent_terms = collection.bm25(
        k1=settings.k1, b=settings.b, transform=settings.transform, idf_form=settings.idf_form
    )

    generator = torch.Generator().manual_seed(seed)
    tally = Tally(k)
    for example in examples:
        shuffle = torch.randperm(len(example.documents), generator=generator)
        _score_example(example, shuffle, collection, latent_terms, tally)

    return result(examples, collection, latent_terms, tally, settings)

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
def 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."""
    queries = list(dict.fromkeys(example.query for example in examples))
    documents = list(dict.fromkeys(document for example in examples for document in example.documents))

    return PooledCollection(
        queries=dict(zip(queries, pool_texts(source, sae, query_kind, queries), strict=True)),
        documents=dict(zip(documents, pool_texts(source, sae, document_kind, documents), strict=True)),
        num_latents=sae.num_latents,
    )

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
def bm25(self, *, k1: float, b: float, transform: str, idf_form: str) -> LatentTermBM25:
    """BM25 over the summed activations of the documents, as ``LatentTermBM25`` defines it."""
    documents = [summed(vector) for vector in self.documents.values()]
    return LatentTermBM25(documents, self.num_latents, k1=k1, b=b, transform=transform, idf_form=idf_form)

mean_l0

mean_l0() -> dict[str, float]

Mean number of active latents of a query and of a document.

Source code in src/muscari/analysis/probe/collection.py
def mean_l0(self) -> dict[str, float]:
    """Mean number of active latents of a query and of a document."""
    return {
        "query": _mean_l0(self.queries.values(), len(self.queries)),
        "document": _mean_l0(self.documents.values(), len(self.documents)),
    }

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
def 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.
    """
    outside = [latent for latent in latents if not 0 <= latent < collection.num_latents]
    if outside:
        raise ValueError(f"The SAE has {collection.num_latents} latents; cannot mask {outside}.")

    if not latents:
        return collection

    masked = torch.tensor(sorted(set(latents)), dtype=torch.long)

    return PooledCollection(
        queries={text: _without(vector, masked) for text, vector in collection.queries.items()},
        documents={text: _without(vector, masked) for text, vector in collection.documents.items()},
        num_latents=collection.num_latents,
    )

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
def text_frequencies(collection: PooledCollection) -> tuple[torch.Tensor, torch.Tensor]:
    """Per latent, the share of the queries and the share of the documents in which it is active."""
    queries, documents = collection.queries.values(), collection.documents.values()

    return (
        _frequency(queries, len(collection.queries), collection.num_latents),
        _frequency(documents, len(collection.documents), collection.num_latents),
    )

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
def 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.
    """
    queries, documents = text_frequencies(collection)

    return float(queries @ documents)

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 of log1p(activation).

  • embeddings (Tensor) –

    (3, d_in) mean-pooled sentence embeddings in the order of VARIANTS: 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 that muscari.analysis.latent_terms scores; None when 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
@torch.no_grad()
def 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.
    """
    pooled: list[PooledText | None] = [None] * len(texts)
    order = sorted(range(len(texts)), key=lambda position: len(texts[position]))

    for start in range(0, len(order), source.text_batch_size):
        positions = order[start : start + source.text_batch_size]
        batch = source.encode_texts([kind] * len(positions), [texts[position] for position in positions])

        pooling = SparsePooling(sae, batch, token_chunk)
        embeddings = _embeddings(batch, sae, pooling)

        for row, position in enumerate(positions):
            indices, maxima, sums = pooling.text(row)
            pooled[position] = PooledText(indices, maxima, embeddings[row], sums)

    return [text for text in pooled if text is not None]

ranking_metrics

ranking_metrics(
    scores: Tensor, labels: Tensor, k: int = 10
) -> dict[str, float]

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
def ranking_metrics(scores: torch.Tensor, labels: torch.Tensor, k: int = 10) -> dict[str, float]:
    """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.
    """
    relevant = int(labels.sum())
    if relevant == 0:
        raise ValueError("The query has no relevant candidate.")

    top = labels[scores.argsort(descending=True, stable=True)[:k]].double()
    discounts = 1.0 / torch.log2(torch.arange(2, top.shape[0] + 2).double())
    ideal = discounts[: min(relevant, k)].sum()
    hits = top.nonzero()

    return {
        f"ndcg@{k}": float((top * discounts).sum() / ideal),
        f"mrr@{k}": 1.0 / (int(hits[0]) + 1) if hits.numel() else 0.0,
    }

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
def sparse_scores(query: PooledText, documents: Sequence[PooledText], weights: torch.Tensor) -> torch.Tensor:
    """Dot products of the query's sparse vector with each document's, with one weight per latent."""
    dense_query = torch.zeros(weights.shape[0], dtype=torch.float64)
    dense_query[query.indices] = query.values.double()
    dense_query *= weights

    lengths = torch.tensor([document.indices.shape[0] for document in documents])
    owner = torch.repeat_interleave(torch.arange(len(documents)), lengths)
    latents = torch.cat([document.indices for document in documents])
    values = torch.cat([document.values for document in documents])

    products = dense_query[latents] * values
    return torch.zeros(len(documents), dtype=torch.float64).index_add_(0, owner, products)

fuse_scores

fuse_scores(
    dense: Tensor, sparse: Tensor, dense_weight: float
) -> Tensor

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
def fuse_scores(dense: torch.Tensor, sparse: torch.Tensor, dense_weight: float) -> torch.Tensor:
    """``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.
    """
    return dense_weight * _standardise(dense) + (1.0 - dense_weight) * _standardise(sparse)

reciprocal_rank_fusion

reciprocal_rank_fusion(
    score_lists: Sequence[Tensor], constant: float = 60.0
) -> Tensor

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
def reciprocal_rank_fusion(score_lists: Sequence[torch.Tensor], constant: float = 60.0) -> torch.Tensor:
    """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.
    """
    fused = torch.zeros(score_lists[0].shape[0], dtype=torch.float64)

    for scores in score_lists:
        ranks = torch.empty_like(fused)
        ranks[scores.argsort(descending=True, stable=True)] = torch.arange(1, fused.shape[0] + 1).double()
        fused += 1.0 / (constant + ranks)

    return fused

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 phi in TRANSFORMS.

  • 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 documents is empty, or transform or idf_form is unknown.

document_frequency cached property

document_frequency: Tensor

Number of documents in which each latent is active.

idf cached property

idf: Tensor

IDF of every latent over the documents, in the form idf_form names.

majority_latents property

majority_latents: int

Latents active in more than half of the documents, whose Okapi IDF is negative.

average_length cached property

average_length: float

Mean over the documents of the sum of their weights.

weights

weights(text: SparseText) -> Tensor

phi of the summed activations of one text.

Source code in src/muscari/analysis/latent_terms.py
def weights(self, text: SparseText) -> torch.Tensor:
    """``phi`` of the summed activations of one text."""
    return TRANSFORMS[self.transform](text[1].double())

scores

scores(
    query: SparseText, candidates: Sequence[SparseText]
) -> Tensor

BM25 of query against each of candidates, with the collection's statistics.

Source code in src/muscari/analysis/latent_terms.py
def scores(self, query: SparseText, candidates: Sequence[SparseText]) -> torch.Tensor:
    """BM25 of ``query`` against each of ``candidates``, with the collection's statistics."""
    owner, latents, frequency = self._flatten(candidates)
    lengths = torch.zeros(len(candidates), dtype=torch.float64).index_add_(0, owner, frequency)

    norm = self.k1 * (1.0 - self.b + self.b * lengths[owner] / self.average_length)
    saturated = frequency * (self.k1 + 1.0) / (frequency + norm)
    products = (self._dense_query(query) * self.idf)[latents] * saturated

    return torch.zeros(len(candidates), dtype=torch.float64).index_add_(0, owner, products)

dot

dot(
    query: SparseText, candidates: Sequence[SparseText]
) -> Tensor

Inner product of the same weights, without IDF, saturation or length normalisation.

Source code in src/muscari/analysis/latent_terms.py
def dot(self, query: SparseText, candidates: Sequence[SparseText]) -> torch.Tensor:
    """Inner product of the same weights, without IDF, saturation or length normalisation."""
    owner, latents, values = self._flatten(candidates)
    products = self._dense_query(query)[latents] * values

    return torch.zeros(len(candidates), dtype=torch.float64).index_add_(0, owner, products)

okapi_idf

okapi_idf(
    document_frequency: Tensor, n_documents: int
) -> Tensor

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
def okapi_idf(document_frequency: torch.Tensor, n_documents: int) -> torch.Tensor:
    """``log((N - n + 0.5) / (n + 0.5))``; negative for a latent active in more than half."""
    frequency = document_frequency.double()
    return torch.log((n_documents - frequency + 0.5) / (frequency + 0.5))

lucene_idf

lucene_idf(
    document_frequency: Tensor, n_documents: int
) -> Tensor

log(1 + (N - n + 0.5) / (n + 0.5)); positive for every latent.

Source code in src/muscari/analysis/term_weights.py
def lucene_idf(document_frequency: torch.Tensor, n_documents: int) -> torch.Tensor:
    """``log(1 + (N - n + 0.5) / (n + 0.5))``; positive for every latent."""
    frequency = document_frequency.double()
    return torch.log1p((n_documents - frequency + 0.5) / (frequency + 0.5))