Skip to content
Edit this page

muscari.heads

Heads that turn an encoder's token states into a sparse vector, as Sentence Transformers modules. Requires the retrieval extra.

SAE head

build_sparse_encoder

build_sparse_encoder(
    sae: ExportedSAE | str | Path,
    model_name_or_path: str | None = None,
    *,
    query_prompt: str | None = None,
    document_prompt: str | None = None,
    max_seq_length: int | None = None,
    head_kwargs: dict[str, Any] | None = None,
    bidirectional: bool = False,
    **kwargs: Any,
) -> SparseEncoder

Put an exported SAE on top of its encoder as a SparseEncoder, ready to encode or to train.

An SAE of the final hidden states goes on the model as it is. An SAE of an earlier layer, recorded as an index into the model's hidden_states, goes on a DecoderTransformer cut after that layer, which is how SPLARE uses a published SAE of a language model.

Parameters:

  • sae (ExportedSAE | str | Path) –

    an exported SAE or its directory.

  • model_name_or_path (str | None, default: None ) –

    the encoder; default: the base model recorded with the SAE.

  • query_prompt (str | None, default: None ) –

    prompt the encoder expects for queries, registered as the prompt "query" so that encode_query uses it.

  • document_prompt (str | None, default: None ) –

    the same for documents, registered as "document".

  • max_seq_length (int | None, default: None ) –

    truncation length; default: the length the SAE was trained with.

  • head_kwargs (dict[str, Any] | None, default: None ) –

    arguments for SAEPooling, for example {"masked_latents": [...]}.

  • bidirectional (bool, default: False ) –

    let every token attend to the whole text; for decoder language models.

  • kwargs (Any, default: {} ) –

    passed on to SparseEncoder.

Raises:

  • ValueError –

    if no encoder is given and none is recorded, or if the layer the SAE was trained on is neither last_hidden_state nor a positive index.

Source code in src/muscari/heads/sae/build.py
def build_sparse_encoder(
    sae: ExportedSAE | str | Path,
    model_name_or_path: str | None = None,
    *,
    query_prompt: str | None = None,
    document_prompt: str | None = None,
    max_seq_length: int | None = None,
    head_kwargs: dict[str, Any] | None = None,
    bidirectional: bool = False,
    **kwargs: Any,
) -> SparseEncoder:
    """Put an exported SAE on top of its encoder as a ``SparseEncoder``, ready to encode or to train.

    An SAE of the final hidden states goes on the model as it is. An SAE of an earlier layer,
    recorded as an index into the model's ``hidden_states``, goes on a ``DecoderTransformer``
    cut after that layer, which is how SPLARE uses a published SAE of a language model.

    Args:
        sae: an exported SAE or its directory.
        model_name_or_path: the encoder; default: the base model recorded with the SAE.
        query_prompt: prompt the encoder expects for queries, registered as the prompt ``"query"``
            so that ``encode_query`` uses it.
        document_prompt: the same for documents, registered as ``"document"``.
        max_seq_length: truncation length; default: the length the SAE was trained with.
        head_kwargs: arguments for ``SAEPooling``, for example ``{"masked_latents": [...]}``.
        bidirectional: let every token attend to the whole text; for decoder language models.
        kwargs: passed on to ``SparseEncoder``.

    Raises:
        ValueError: if no encoder is given and none is recorded, or if the layer the SAE was
            trained on is neither ``last_hidden_state`` nor a positive index.
    """
    if not isinstance(sae, ExportedSAE):
        sae = load_sae(sae)

    layer = sae.config.get("layer", "last_hidden_state")
    if layer != "last_hidden_state" and not (str(layer).isdigit() and int(layer) > 0):
        raise ValueError(
            f"A retrieval head needs an SAE of last_hidden_state or of a layer index above 0, not {layer!r}."
        )

    model_name_or_path = model_name_or_path or sae.config.get("base_model")
    if model_name_or_path is None:
        raise ValueError("model_name_or_path is required: the SAE config records no base model.")

    transformer = _transformer(
        model_name_or_path,
        layer,
        bidirectional=bidirectional,
        max_seq_length=max_seq_length or sae.config.get("max_seq_length"),
    )
    head = SAEPooling.from_sae(sae, **(head_kwargs or {}))

    prompts = {name: prompt for name, prompt in (("query", query_prompt), ("document", document_prompt)) if prompt}
    return SparseEncoder(modules=[transformer, head], prompts=prompts or None, similarity_fn_name="dot", **kwargs)

SAEPooling

SAEPooling(
    d_in: int,
    num_latents: int,
    k: int | None = None,
    activation: str = "topk",
    saturation: str = "log1p",
    normalize_states: bool = False,
    include_prompt: bool = False,
    special_token_ids: Sequence[int] | None = None,
    masked_latents: Sequence[int] | None = None,
    latent_gate: bool = False,
    trainable: bool = False,
    token_chunk: int = 4096,
)

Bases: ContentTokens, SAEForward, SavedHead

Turn token states into one sparse vector per text with the encoder half of an SAE.

For every content token h: pre = h @ encoder_weight.T + encoder_bias; a Top-K SAE keeps the k largest entries, a JumpReLU SAE those above their threshold; the kept entries pass through ReLU and, unless saturation="none", log1p. A text's vector holds, for each latent, the maximum over its content tokens. Padding, special tokens and, by default, the tokens of the prompt are not content, which matches what the SAE was trained on.

Parameters:

  • d_in (int) –

    width of the token states.

  • num_latents (int) –

    number of latents, the dimension of the output.

  • k (int | None, default: None ) –

    latents kept per token; required for activation="topk". It need not be the k the SAE was trained with: SAE-SPLADE (Zong et al., arXiv 2604.21511) treats the two as separate settings and reports that this per-token limit shapes sparsity more than the FLOPS regulariser does.

  • saturation (str, default: 'log1p' ) –

    "log1p" applies log(1 + x) to the kept activations, as SPLADE, SAE-SPLADE, SPLARE and the Shizuku models do; "none" keeps them as they are, as LightOn's SlideOn does, whose scores are raw dot products. The scale of the scores, and with it the scale a contrastive loss needs, differs between the two.

  • activation (str, default: 'topk' ) –

    "topk" or "jumprelu".

  • normalize_states (bool, default: False ) –

    scale every token state to unit length before the SAE's encoder. It must match how the SAE was trained; from_sae takes it from the SAE's config.

  • include_prompt (bool, default: False ) –

    pool the prompt's tokens too. By default they are left out when the model passes a prompt length. Sentence Transformers counts the tokens of the prompt on its own; where a token straddles the end of the prompt this can differ by one token from the character-based rule used when the SAE was trained.

  • special_token_ids (Sequence[int] | None, default: None ) –

    ids that are never pooled. Filled in when the module becomes part of a model, with the tokens the tokenizer adds around a text: classifier, separator, beginning, end and padding. Unknown and mask tokens can occur inside a text and were content when the SAE was trained, so they are pooled.

  • masked_latents (Sequence[int] | None, default: None ) –

    latents whose output is always zero, for example ones that are active in nearly every text and so cannot tell texts apart.

  • latent_gate (bool, default: False ) –

    multiply each latent's pooled weight by a trained non-negative factor that starts at one, as SlideOn's head does. The factor is trained even when trainable is off; a latent whose factor reaches zero is switched off.

  • trainable (bool, default: False ) –

    train the SAE's encoder together with the transformer. The default keeps it frozen, as the Shizuku models and SPLARE do; SlideOn trains it.

  • token_chunk (int, default: 4096 ) –

    content tokens processed at a time; bounds the size of the (tokens, num_latents) product.

The decoder of the SAE is not needed for retrieval and is not stored.

While balance_terms is a list, every training forward appends one load-balance term to it, as in SlideOn: num_latents * sum_j usage_j * probability_j, where usage_j is the share of the kept entries that fall on latent j (a constant) and probability_j is the mean over the tokens of the softmax of pre. It is 1 when either is uniform and grows when few latents take most tokens; its gradient lowers the pre-activations of the latents in use relative to the others. muscari.training.losses.LoadBalancedSpladeLoss collects these terms. The softmax needs the gradient of all num_latents pre-activations of every token, which is recomputed chunk by chunk in the backward pass instead of being stored.

Source code in src/muscari/heads/sae/pooling.py
def __init__(
    self,
    d_in: int,
    num_latents: int,
    k: int | None = None,
    activation: str = "topk",
    saturation: str = "log1p",
    normalize_states: bool = False,
    include_prompt: bool = False,
    special_token_ids: Sequence[int] | None = None,
    masked_latents: Sequence[int] | None = None,
    latent_gate: bool = False,
    trainable: bool = False,
    token_chunk: int = 4096,
) -> None:
    super().__init__()
    if activation not in ACTIVATIONS:
        raise ValueError(f"activation must be one of {ACTIVATIONS}, got {activation!r}.")
    if saturation not in SATURATIONS:
        raise ValueError(f"saturation must be one of {SATURATIONS}, got {saturation!r}.")
    if activation == "topk" and (k is None or not 0 < k <= num_latents):
        raise ValueError("A Top-K head needs k between 1 and num_latents.")
    if token_chunk < 1:
        raise ValueError("token_chunk must be positive.")

    self.d_in = d_in
    self.num_latents = num_latents
    self.k = k
    self.activation = activation
    self.saturation = saturation
    self.normalize_states = normalize_states
    self.include_prompt = include_prompt
    self.special_token_ids = None if special_token_ids is None else sorted(int(i) for i in special_token_ids)
    self.masked_latents = sorted(int(i) for i in masked_latents or [])
    self.latent_gate = latent_gate
    self.trainable = trainable
    self.token_chunk = token_chunk
    self.balance_terms: list[torch.Tensor] | None = None

    self.encoder_weight = nn.Parameter(torch.zeros(num_latents, d_in), requires_grad=trainable)
    self.encoder_bias = nn.Parameter(torch.zeros(num_latents), requires_grad=trainable)
    self.threshold: torch.Tensor | None
    self.register_buffer("threshold", torch.zeros(num_latents) if activation == "jumprelu" else None)
    self.gate = nn.Parameter(torch.ones(num_latents)) if latent_gate else None

from_sae classmethod

from_sae(
    sae: ExportedSAE | str | Path, **kwargs: Any
) -> SAEPooling

Build the head from an exported SAE or the directory that holds one.

kwargs are the constructor arguments other than the sizes and the activation rule. For a Top-K SAE, k overrides the number of latents kept per token, which otherwise is the SAE's own.

Raises:

  • ValueError –

    if k is given for a JumpReLU SAE, whose threshold decides what is kept.

Source code in src/muscari/heads/sae/pooling.py
@classmethod
def from_sae(cls, sae: ExportedSAE | str | Path, **kwargs: Any) -> SAEPooling:
    """Build the head from an exported SAE or the directory that holds one.

    ``kwargs`` are the constructor arguments other than the sizes and the activation rule.
    For a Top-K SAE, ``k`` overrides the number of latents kept per token, which otherwise
    is the SAE's own.

    Raises:
        ValueError: if ``k`` is given for a JumpReLU SAE, whose threshold decides what is kept.
    """
    if not isinstance(sae, ExportedSAE):
        sae = load_sae(sae)

    jumprelu = sae.threshold is not None
    k = kwargs.pop("k", None)
    if jumprelu and k is not None:
        raise ValueError("k cannot be set for a JumpReLU SAE.")

    head = cls(
        d_in=sae.d_in,
        num_latents=sae.num_latents,
        k=None if jumprelu else int(sae.config["k"] if k is None else k),
        normalize_states=kwargs.pop("normalize_states", sae.normalize_inputs),
        activation="jumprelu" if jumprelu else "topk",
        **kwargs,
    )

    with torch.no_grad():
        head.encoder_weight.copy_(sae.encoder_weight)
        head.encoder_bias.copy_(sae.encoder_bias)
        if head.threshold is not None and sae.threshold is not None:
            head.threshold.copy_(sae.threshold)

    return head

Vocabulary head

build_vocabulary_encoder

build_vocabulary_encoder(
    model_name_or_path: str,
    *,
    shift: float | str = 0.0,
    fan_out: int | None = None,
    include_prompt: bool = False,
    keep_special_tokens: bool = False,
    query_prompt: str | None = None,
    document_prompt: str | None = None,
    max_seq_length: int | None = None,
    shift_texts: Sequence[str] | None = None,
    shift_quantile: float = 0.999,
    head_divisor: float = 1.0,
    masked_tokens: Sequence[int] | None = None,
    fold: bool = False,
    probability_threshold: float | None = None,
    temperature: float = 1.0,
    energy: float = 0.0,
    energy_center: float | str = 0.0,
    saturate: bool = True,
    capacity: float | None = None,
    capacity_rate: float = 0.25,
    capacity_window: int = 2000,
    seed: int = 42,
    device: str | None = None,
) -> SparseEncoder

A SparseEncoder with VocabularyPooling on the masked-language-model head.

head_divisor divides the head's projection first (muscari.heads.rescale_head). shift="auto" then estimates theta as the shift_quantile of the content-token logits of shift_texts (documents, with the document prompt). fold merges the entries that differ in case or word-boundary marker (case_space_fold).

probability_threshold switches the head to normalised scores (muscari.heads.scores); energy_center="auto" then takes the median log-sum-exp of the content tokens of shift_texts. capacity caps the share of texts an entry appears in (muscari.heads.capacity).

Source code in src/muscari/heads/vocabulary/build.py
def build_vocabulary_encoder(
    model_name_or_path: str,
    *,
    shift: float | str = 0.0,
    fan_out: int | None = None,
    include_prompt: bool = False,
    keep_special_tokens: bool = False,
    query_prompt: str | None = None,
    document_prompt: str | None = None,
    max_seq_length: int | None = None,
    shift_texts: Sequence[str] | None = None,
    shift_quantile: float = 0.999,
    head_divisor: float = 1.0,
    masked_tokens: Sequence[int] | None = None,
    fold: bool = False,
    probability_threshold: float | None = None,
    temperature: float = 1.0,
    energy: float = 0.0,
    energy_center: float | str = 0.0,
    saturate: bool = True,
    capacity: float | None = None,
    capacity_rate: float = 0.25,
    capacity_window: int = 2000,
    seed: int = 42,
    device: str | None = None,
) -> SparseEncoder:
    """A ``SparseEncoder`` with ``VocabularyPooling`` on the masked-language-model head.

    ``head_divisor`` divides the head's projection first (``muscari.heads.rescale_head``).
    ``shift="auto"`` then estimates ``theta`` as the ``shift_quantile`` of the content-token
    logits of ``shift_texts`` (documents, with the document prompt). ``fold`` merges the entries
    that differ in case or word-boundary marker (``case_space_fold``).

    ``probability_threshold`` switches the head to normalised scores (``muscari.heads.scores``);
    ``energy_center="auto"`` then takes the median log-sum-exp of the content tokens of
    ``shift_texts``. ``capacity`` caps the share of texts an entry appears in
    (``muscari.heads.capacity``).
    """
    transformer = Transformer(model_name_or_path, transformer_task="fill-mask", max_seq_length=max_seq_length)
    rescale_head(transformer, head_divisor)

    head = VocabularyPooling(
        output_size(transformer),
        fan_out=fan_out,
        include_prompt=include_prompt,
        special_token_ids=[] if keep_special_tokens else None,
        masked_tokens=masked_tokens,
        fold=fold,
        probability_threshold=probability_threshold,
        temperature=temperature,
        energy=energy,
        saturate=saturate,
        capacity=capacity,
        capacity_rate=capacity_rate,
        capacity_window=capacity_window,
    )
    if fold:
        head.set_fold(case_space_fold(transformer.tokenizer, head.vocabulary_size))

    prompts = {name: prompt for name, prompt in (("query", query_prompt), ("document", document_prompt)) if prompt}
    model = SparseEncoder(modules=[transformer, head], prompts=prompts or None, similarity_fn_name="dot", device=device)

    _calibrate(model, head, shift, energy_center, shift_texts, shift_quantile=shift_quantile, seed=seed)
    return model

VocabularyPooling

VocabularyPooling(
    vocabulary_size: int,
    shift: float = 0.0,
    fan_out: int | None = None,
    include_prompt: bool = False,
    special_token_ids: Sequence[int] | None = None,
    masked_tokens: Sequence[int] | None = None,
    fold: bool = False,
    probability_threshold: float | None = None,
    temperature: float = 1.0,
    energy: float = 0.0,
    energy_center: float = 0.0,
    saturate: bool = True,
    capacity: float | None = None,
    capacity_rate: float = 0.25,
    capacity_window: int = 2000,
)

Bases: ContentTokens, VocabularyForward, SavedHead

Shifted, fanned-out SPLADE pooling of masked-language-model logits over content tokens.

Parameters:

  • vocabulary_size (int) –

    width of the logits, the dimension of the output.

  • shift (float, default: 0.0 ) –

    theta, subtracted from every logit before ReLU.

  • fan_out (int | None, default: None ) –

    logits kept per token after the shift; None keeps all of them.

  • include_prompt (bool, default: False ) –

    pool the prompt's tokens too; by default they are left out when the model passes a prompt length.

  • special_token_ids (Sequence[int] | None, default: None ) –

    ids that are never pooled; filled in from the tokenizer's framing tokens when the module becomes part of a model. [] pools every attended token.

  • masked_tokens (Sequence[int] | None, default: None ) –

    vocabulary entries that never get a weight: -1e4 is put in place of their shifted logits before the fan-out, so they take no slot of it either. The Shizuku vocabulary models do this during training for punctuation, symbols, byte fallbacks and special tokens (noise_token_ids finds such entries) and write the same value into the head's bias afterwards (muscari.heads.suppress_tokens).

  • fold (bool, default: False ) –

    merge vocabulary entries after the pooling. fold_index then holds, for every entry, the entry that stands for its group; that entry receives the largest weight of the group and the others become zero. SPARSEUP merges entries that differ in case or in the word-boundary marker this way, in training and at inference (case_space_fold builds that index). The index is saved with the module.

  • probability_threshold (float | None, default: None ) –

    normalise the logits of every token to log-probabilities and keep the entries whose probability exceeds this value, instead of shifting the logits (muscari.heads.scores). shift must then be 0.

  • temperature (float, default: 1.0 ) –

    divides the logits before that normalisation.

  • energy (float, default: 0.0 ) –

    share of the token's log-sum-exp that is added back to the normalised scores.

  • energy_center (float, default: 0.0 ) –

    subtracted from the log-sum-exp first.

  • saturate (bool, default: True ) –

    apply log(1 + x) after the ReLU, as SPLADE does. Normalised scores are log-ratios already; False pools them as they are.

  • capacity (float | None, default: None ) –

    largest share of the texts an entry should appear in. In training the head then keeps one bias per entry that holds the entry at this limit (muscari.heads.capacity); the biases are saved with the module.

  • capacity_rate (float, default: 0.25 ) –

    how fast those biases move.

  • capacity_window (int, default: 2000 ) –

    number of texts the running shares remember.

The input token_embeddings are the logits (batch, length, vocabulary_size) of a Transformer with transformer_task="fill-mask". The pooling runs in float32.

Source code in src/muscari/heads/vocabulary/pooling.py
def __init__(
    self,
    vocabulary_size: int,
    shift: float = 0.0,
    fan_out: int | None = None,
    include_prompt: bool = False,
    special_token_ids: Sequence[int] | None = None,
    masked_tokens: Sequence[int] | None = None,
    fold: bool = False,
    probability_threshold: float | None = None,
    temperature: float = 1.0,
    energy: float = 0.0,
    energy_center: float = 0.0,
    saturate: bool = True,
    capacity: float | None = None,
    capacity_rate: float = 0.25,
    capacity_window: int = 2000,
) -> None:
    super().__init__()
    _check_settings(vocabulary_size, shift, fan_out, probability_threshold, temperature)

    self.vocabulary_size = vocabulary_size
    self.include_prompt = include_prompt
    self.special_token_ids = None if special_token_ids is None else sorted(int(i) for i in special_token_ids)
    self.masked_tokens = sorted({int(i) for i in masked_tokens or []})
    if self.masked_tokens and not 0 <= self.masked_tokens[0] <= self.masked_tokens[-1] < vocabulary_size:
        raise ValueError("masked_tokens must be vocabulary entries.")

    self.shift = float(shift)
    self.fan_out = fan_out
    self.probability_threshold = probability_threshold
    self.temperature = float(temperature)
    self.energy = float(energy)
    self.energy_center = float(energy_center)
    self.saturate = saturate

    self.fold = fold
    self.register_buffer("fold_index", torch.arange(vocabulary_size) if fold else None)

    self.capacity = capacity
    self.capacity_rate = float(capacity_rate)
    self.capacity_window = int(capacity_window)
    self.term_capacity = (
        None if capacity is None else TermCapacity(vocabulary_size, capacity, capacity_rate, capacity_window)
    )

set_fold

set_fold(index: Tensor | Sequence[int]) -> None

Use index (vocabulary_size,) as the entry that stands for each entry.

Raises:

  • ValueError –

    if the module was built without fold, or the index has the wrong size, points outside the vocabulary, or names an entry that stands for another.

Source code in src/muscari/heads/vocabulary/pooling.py
def set_fold(self, index: torch.Tensor | Sequence[int]) -> None:
    """Use ``index`` ``(vocabulary_size,)`` as the entry that stands for each entry.

    Raises:
        ValueError: if the module was built without ``fold``, or the index has the wrong
            size, points outside the vocabulary, or names an entry that stands for another.
    """
    index = torch.as_tensor(index, dtype=torch.long)

    if self.fold_index is None:
        raise ValueError("Build the module with fold=True to merge entries.")
    if index.shape != (self.vocabulary_size,) or index.min() < 0 or index.max() >= self.vocabulary_size:
        raise ValueError("The fold index needs one vocabulary entry per vocabulary entry.")
    if not torch.equal(index[index], index):
        raise ValueError("An entry that stands for a group must stand for itself.")

    self.fold_index.copy_(index.to(self.fold_index.device))

stores_weights

stores_weights() -> bool

The fold index and the capacity biases are tensors; without them the config is enough.

Source code in src/muscari/heads/vocabulary/pooling.py
def stores_weights(self) -> bool:
    """The fold index and the capacity biases are tensors; without them the config is enough."""
    return self.fold or self.term_capacity is not None

estimate_shift

estimate_shift(
    model: SparseEncoder,
    texts: Sequence[str],
    *,
    quantile: float = 0.999,
    samples_per_batch: int = 200000,
    batch_size: int = 16,
    seed: int = 42,
) -> float

The quantile of the content-token logits of texts encoded as documents.

The logits are sampled as sample_content_logits describes.

Source code in src/muscari/heads/vocabulary/calibration.py
def estimate_shift(
    model: SparseEncoder,
    texts: Sequence[str],
    *,
    quantile: float = 0.999,
    samples_per_batch: int = 200_000,
    batch_size: int = 16,
    seed: int = 42,
) -> float:
    """The ``quantile`` of the content-token logits of ``texts`` encoded as documents.

    The logits are sampled as ``sample_content_logits`` describes.
    """
    values = sample_content_logits(model, texts, samples_per_batch=samples_per_batch, batch_size=batch_size, seed=seed)
    return float(torch.quantile(values, quantile))

estimate_energy_center

estimate_energy_center(
    model: SparseEncoder,
    texts: Sequence[str],
    *,
    quantile: float = 0.5,
    batch_size: int = 16,
) -> float

The quantile of the log-sum-exp of the content-token logits of texts as documents.

The logits are divided by the head's temperature first, as its forward pass does.

Source code in src/muscari/heads/vocabulary/calibration.py
def estimate_energy_center(
    model: SparseEncoder,
    texts: Sequence[str],
    *,
    quantile: float = 0.5,
    batch_size: int = 16,
) -> float:
    """The ``quantile`` of the log-sum-exp of the content-token logits of ``texts`` as documents.

    The logits are divided by the head's temperature first, as its forward pass does.
    """
    temperature = _head(model).temperature
    energies = _content_logits(model, texts, batch_size, lambda logits: token_energy(logits, temperature))

    return float(torch.quantile(energies, quantile))

sample_content_logits

sample_content_logits(
    model: SparseEncoder,
    texts: Sequence[str],
    *,
    samples_per_batch: int = 200000,
    batch_size: int = 16,
    seed: int = 42,
) -> Tensor

A random sample of the content-token logits of texts encoded as documents, before the shift.

Every batch contributes a uniform random sample of at most samples_per_batch of its (token, vocabulary) logits, drawn with seed, so memory does not grow with the vocabulary. The model's document head must be a VocabularyPooling.

Source code in src/muscari/heads/vocabulary/calibration.py
def sample_content_logits(
    model: SparseEncoder,
    texts: Sequence[str],
    *,
    samples_per_batch: int = 200_000,
    batch_size: int = 16,
    seed: int = 42,
) -> torch.Tensor:
    """A random sample of the content-token logits of ``texts`` encoded as documents, before the shift.

    Every batch contributes a uniform random sample of at most ``samples_per_batch`` of its
    ``(token, vocabulary)`` logits, drawn with ``seed``, so memory does not grow with the
    vocabulary. The model's document head must be a ``VocabularyPooling``.
    """
    generator = torch.Generator().manual_seed(seed)

    def sample(logits: torch.Tensor) -> torch.Tensor:
        flat = logits.reshape(-1)
        if flat.numel() <= samples_per_batch:
            return flat

        return flat[torch.randint(flat.numel(), (samples_per_batch,), generator=generator).to(flat.device)]

    values = _content_logits(model, texts, batch_size, sample)
    if values.numel() > 16_000_000:  # torch.quantile's limit
        values = values[torch.randperm(values.numel(), generator=generator)[:16_000_000]]

    return values

noise_token_ids

noise_token_ids(
    tokenizer: Any,
    *,
    single_ascii: bool = False,
    extra: Sequence[str] = (),
) -> dict[str, list[int]]

Vocabulary entries that carry no content, by kind, found by their form.

  • special: the tokenizer's special tokens.
  • byte: byte fallbacks written <0xHH>.
  • marker: a word-boundary marker with nothing after it.
  • symbol: entries whose text, without the marker, consists only of punctuation, symbols, separators, marks, control characters and modifier letters (Unicode categories P, S, Z, M, C and Lm). Repeated signs and the long-vowel mark fall in here.
  • single_ascii: one ASCII letter or digit; only with single_ascii=True.
  • extra: the tokens named in extra.

These are the rules the model card of mahiyama/splade-ja-310m lists for the entries it suppresses; the card also includes single ASCII characters, a list of decorative signs (covered by symbol here) and words of its corpus added by hand, which is what extra is for. Look at the result before using it: a rule on form cannot tell that a sign matters in a domain.

Raises:

  • ValueError –

    if a token of extra is not in the vocabulary.

Source code in src/muscari/heads/vocabulary/tokens.py
def noise_token_ids(tokenizer: Any, *, single_ascii: bool = False, extra: Sequence[str] = ()) -> dict[str, list[int]]:
    """Vocabulary entries that carry no content, by kind, found by their form.

    - ``special``: the tokenizer's special tokens.
    - ``byte``: byte fallbacks written ``<0xHH>``.
    - ``marker``: a word-boundary marker with nothing after it.
    - ``symbol``: entries whose text, without the marker, consists only of punctuation,
      symbols, separators, marks, control characters and modifier letters (Unicode categories
      P, S, Z, M, C and Lm). Repeated signs and the long-vowel mark fall in here.
    - ``single_ascii``: one ASCII letter or digit; only with ``single_ascii=True``.
    - ``extra``: the tokens named in ``extra``.

    These are the rules the model card of ``mahiyama/splade-ja-310m`` lists for the entries it
    suppresses; the card also includes single ASCII characters, a list of decorative signs
    (covered by ``symbol`` here) and words of its corpus added by hand, which is what ``extra``
    is for. Look at the result before using it: a rule on form cannot tell that a sign matters
    in a domain.

    Raises:
        ValueError: if a token of ``extra`` is not in the vocabulary.
    """
    vocabulary: dict[str, int] = tokenizer.get_vocab()
    special = {int(index) for index in tokenizer.all_special_ids}
    groups: dict[str, list[int]] = {name: [] for name in ("byte", "marker", "symbol", "single_ascii")}

    for token, index in vocabulary.items():
        if index not in special and (kind := _noise_kind(token, single_ascii)) is not None:
            groups[kind].append(index)

    if missing := [token for token in extra if token not in vocabulary]:
        raise ValueError(f"Not in the vocabulary: {missing}.")

    groups = {"special": sorted(special), **groups, "extra": [vocabulary[token] for token in extra]}
    return {name: sorted(indices) for name, indices in groups.items()}

case_space_fold

case_space_fold(
    tokenizer: Any, vocabulary_size: int | None = None
) -> Tensor

For every vocabulary entry, the entry that stands for its group of spellings.

Entries whose text is equal after lower-casing and removing the word-boundary marker form a group. The group is represented by its lower-case entry that starts a word if there is one, otherwise by its lower-case entry without a marker, otherwise by its lowest id. This follows the description in the SPARSEUP paper (arXiv 2611.09680), where it takes ModernBERT's vocabulary from about 50,000 entries to about 34,000 and is reported to add about 1.5 points of nDCG@10 on BEIR-13. Special tokens and ids beyond the tokenizer's vocabulary stand for themselves. A script without case and a vocabulary without boundary markers fold nothing.

Source code in src/muscari/heads/vocabulary/tokens.py
def case_space_fold(tokenizer: Any, vocabulary_size: int | None = None) -> torch.Tensor:
    """For every vocabulary entry, the entry that stands for its group of spellings.

    Entries whose text is equal after lower-casing and removing the word-boundary marker form a
    group. The group is represented by its lower-case entry that starts a word if there is one,
    otherwise by its lower-case entry without a marker, otherwise by its lowest id. This follows
    the description in the SPARSEUP paper (arXiv 2611.09680), where it takes ModernBERT's
    vocabulary from about 50,000 entries to about 34,000 and is reported to add about 1.5 points
    of nDCG@10 on BEIR-13. Special tokens and ids beyond the tokenizer's vocabulary stand for
    themselves. A script without case and a vocabulary without boundary markers fold nothing.
    """
    vocabulary: dict[str, int] = tokenizer.get_vocab()
    size = max(vocabulary.values()) + 1 if vocabulary_size is None else vocabulary_size
    special = {int(index) for index in tokenizer.all_special_ids}
    groups: dict[str, list[tuple[int, int]]] = {}

    for token, index in vocabulary.items():
        if index in special or index >= size:
            continue

        starts_word, text = split_marker(token)
        lower = text.lower()
        # Lower numbers are preferred: lower case first, then word start, no marker, continuation.
        rank = (0 if text == lower else 3) + {True: 0, None: 1, False: 2}[starts_word]
        groups.setdefault(lower, []).append((rank, index))

    fold = torch.arange(size)
    for members in groups.values():
        representative = min(members)[1]
        for _, index in members:
            fold[index] = representative

    return fold

token_scores

token_scores(
    logits: Tensor,
    *,
    shift: float = 0.0,
    probability_threshold: float | None = None,
    temperature: float = 1.0,
    energy: float = 0.0,
    energy_center: float = 0.0,
) -> Tensor

Scores (tokens, vocabulary) whose positive part a vocabulary head pools.

Without probability_threshold this is the shifted logit, logits - shift. With it, the logits are divided by temperature and normalised per token as the module describes.

Source code in src/muscari/heads/scores.py
def token_scores(
    logits: torch.Tensor,
    *,
    shift: float = 0.0,
    probability_threshold: float | None = None,
    temperature: float = 1.0,
    energy: float = 0.0,
    energy_center: float = 0.0,
) -> torch.Tensor:
    """Scores ``(tokens, vocabulary)`` whose positive part a vocabulary head pools.

    Without ``probability_threshold`` this is the shifted logit, ``logits - shift``. With it,
    the logits are divided by ``temperature`` and normalised per token as the module describes.
    """
    if probability_threshold is None:
        return logits - shift

    scaled = logits / temperature
    energies = torch.logsumexp(scaled, dim=-1, keepdim=True)
    scores = scaled - energies - math.log(probability_threshold)

    if energy:
        scores = scores + energy * (energies - energy_center)
    return scores

token_energy

token_energy(
    logits: Tensor, temperature: float = 1.0
) -> Tensor

E_i of every token: the log-sum-exp of its logits divided by temperature.

Source code in src/muscari/heads/scores.py
def token_energy(logits: torch.Tensor, temperature: float = 1.0) -> torch.Tensor:
    """``E_i`` of every token: the log-sum-exp of its logits divided by ``temperature``."""
    return torch.logsumexp(logits / temperature, dim=-1)

TermCapacity

TermCapacity(
    size: int,
    capacity: float,
    rate: float = 0.25,
    window: int = 2000,
)

Bases: Module

Running shares and biases of size entries; both are saved with the module.

Parameters:

  • size (int) –

    number of entries.

  • capacity (float) –

    largest share of the texts an entry should appear in, in (0, 1).

  • rate (float, default: 0.25 ) –

    growth of the bias per window texts and per unit of log(share / capacity).

  • window (int, default: 2000 ) –

    number of texts the running share remembers.

Source code in src/muscari/heads/capacity.py
def __init__(self, size: int, capacity: float, rate: float = 0.25, window: int = 2000) -> None:
    super().__init__()
    if not 0 < capacity < 1:
        raise ValueError("capacity must be between 0 and 1.")
    if rate <= 0 or window <= 0:
        raise ValueError("rate and window must be positive.")

    self.capacity = float(capacity)
    self.rate = float(rate)
    self.window = int(window)
    self.register_buffer("share", torch.zeros(size))
    self.register_buffer("bias", torch.zeros(size))

observe

observe(pooled: Tensor) -> None

Take in the pooled vectors (texts, size) of one forward pass and move the biases.

Source code in src/muscari/heads/capacity.py
@torch.no_grad()
def observe(self, pooled: torch.Tensor) -> None:
    """Take in the pooled vectors ``(texts, size)`` of one forward pass and move the biases."""
    texts = pooled.shape[0]
    if texts == 0:
        return

    seen = (pooled > 0).float().mean(dim=0).to(self.share.device)
    keep = math.exp(-texts / self.window)
    self.share.mul_(keep).add_(seen, alpha=1 - keep)

    excess = torch.log(self.share.clamp_min(SHARE_FLOOR) / self.capacity)
    self.bias.add_(excess, alpha=self.rate * texts / self.window).clamp_(min=0)

Separate query and document encoders

combine_encoders

combine_encoders(
    query: SparseEncoder,
    document: SparseEncoder,
    *,
    shared_vocabulary: bool = True,
) -> SparseEncoder

One SparseEncoder that encodes queries with query and documents with document.

The two encoders keep their own tokenizer, transformer and head. Their prompts named query and document are carried over. Nothing aligns the two sides here: train the model, typically with the document side as it is and the query side learning to match it.

Parameters:

  • query (SparseEncoder) –

    the encoder for queries.

  • document (SparseEncoder) –

    the encoder for documents, with the same number of output dimensions.

  • shared_vocabulary (bool, default: True ) –

    also require identical tokenizer vocabularies, which heads on the language-model head need. Pass False for SAE heads, whose dimensions are the latents of one SAE whatever the tokenizer.

Raises:

  • ValueError –

    if the output dimensions differ, or the vocabularies do when they must agree.

Source code in src/muscari/heads/routes.py
def combine_encoders(
    query: SparseEncoder,
    document: SparseEncoder,
    *,
    shared_vocabulary: bool = True,
) -> SparseEncoder:
    """One ``SparseEncoder`` that encodes queries with ``query`` and documents with ``document``.

    The two encoders keep their own tokenizer, transformer and head. Their prompts named
    ``query`` and ``document`` are carried over. Nothing aligns the two sides here: train the
    model, typically with the document side as it is and the query side learning to match it.

    Args:
        query: the encoder for queries.
        document: the encoder for documents, with the same number of output dimensions.
        shared_vocabulary: also require identical tokenizer vocabularies, which heads on the
            language-model head need. Pass ``False`` for SAE heads, whose dimensions are the
            latents of one SAE whatever the tokenizer.

    Raises:
        ValueError: if the output dimensions differ, or the vocabularies do when they must agree.
    """
    sizes = (query.get_sentence_embedding_dimension(), document.get_sentence_embedding_dimension())
    if sizes[0] != sizes[1]:
        raise ValueError(f"The query encoder has {sizes[0]} dimensions and the document encoder {sizes[1]}.")
    if shared_vocabulary:
        _check_same_vocabulary(query, document)

    prompts: dict[str, str] = {}
    for name, encoder in zip(ROUTES, (query, document), strict=True):
        if prompt := encoder.prompts.get(name):
            prompts[name] = prompt

    query_modules: list[Any] = list(query)
    document_modules: list[Any] = list(document)
    router = Router.for_query_document(query_modules=query_modules, document_modules=document_modules)

    return SparseEncoder(
        modules=[router],
        prompts=prompts or None,
        similarity_fn_name="dot",
        device=str(document.device),
    )

build_asymmetric_sae_encoder

build_asymmetric_sae_encoder(
    sae: ExportedSAE | str | Path,
    query_model_name_or_path: str,
    texts: Sequence[str],
    model_name_or_path: str | None = None,
    *,
    query_prompt: str | None = None,
    document_prompt: str | None = None,
    max_seq_length: int | None = None,
    head_kwargs: dict[str, Any] | None = None,
    ridge: float = 0.001,
    text_batch_size: int = 32,
    device: str | None = None,
) -> SparseEncoder

Documents through the SAE's own encoder, queries through a smaller one with a stitched head.

The document side is build_sparse_encoder(sae, model_name_or_path). The query side is query_model_name_or_path with a trainable SAEPooling that starts as the SAE composed with a linear map from the small encoder's states to the large one's (muscari.heads.sae.stitching), fitted on texts encoded as queries. Both encoders must use the same tokenizer. Train the result before using it: the map is only a start.

Parameters:

  • sae (ExportedSAE | str | Path) –

    an exported SAE of last_hidden_state, or its directory or Hub repository.

  • query_model_name_or_path (str) –

    the encoder for queries.

  • texts (Sequence[str]) –

    queries to fit the map on; a few hundred are enough for a start.

  • model_name_or_path (str | None, default: None ) –

    the encoder for documents; default: the base model the SAE records.

  • query_prompt (str | None, default: None ) –

    prompt the query encoder expects.

  • document_prompt (str | None, default: None ) –

    prompt the document encoder expects.

  • max_seq_length (int | None, default: None ) –

    truncation length; default: the length the SAE was trained with.

  • head_kwargs (dict[str, Any] | None, default: None ) –

    arguments for both heads other than trainable and k, for example {"saturation": "none"}.

  • ridge (float, default: 0.001 ) –

    strength of the penalty of the fit.

  • text_batch_size (int, default: 32 ) –

    texts per forward pass during the fit.

  • device (str | None, default: None ) –

    device of the model.

Raises:

  • ValueError –

    if the SAE is not of last_hidden_state, records no base model while none is given, or the two encoders tokenize differently.

Source code in src/muscari/heads/sae/asymmetric.py
def build_asymmetric_sae_encoder(
    sae: ExportedSAE | str | Path,
    query_model_name_or_path: str,
    texts: Sequence[str],
    model_name_or_path: str | None = None,
    *,
    query_prompt: str | None = None,
    document_prompt: str | None = None,
    max_seq_length: int | None = None,
    head_kwargs: dict[str, Any] | None = None,
    ridge: float = 1e-3,
    text_batch_size: int = 32,
    device: str | None = None,
) -> SparseEncoder:
    """Documents through the SAE's own encoder, queries through a smaller one with a stitched head.

    The document side is ``build_sparse_encoder(sae, model_name_or_path)``. The query side is
    ``query_model_name_or_path`` with a trainable ``SAEPooling`` that starts as the SAE composed
    with a linear map from the small encoder's states to the large one's
    (``muscari.heads.sae.stitching``), fitted on ``texts`` encoded as queries. Both encoders
    must use the same tokenizer. Train the result before using it: the map is only a start.

    Args:
        sae: an exported SAE of ``last_hidden_state``, or its directory or Hub repository.
        query_model_name_or_path: the encoder for queries.
        texts: queries to fit the map on; a few hundred are enough for a start.
        model_name_or_path: the encoder for documents; default: the base model the SAE records.
        query_prompt: prompt the query encoder expects.
        document_prompt: prompt the document encoder expects.
        max_seq_length: truncation length; default: the length the SAE was trained with.
        head_kwargs: arguments for both heads other than ``trainable`` and ``k``, for example
            ``{"saturation": "none"}``.
        ridge: strength of the penalty of the fit.
        text_batch_size: texts per forward pass during the fit.
        device: device of the model.

    Raises:
        ValueError: if the SAE is not of ``last_hidden_state``, records no base model while none
            is given, or the two encoders tokenize differently.
    """
    if not isinstance(sae, ExportedSAE):
        sae = load_sae(sae)
    if sae.config.get("layer", "last_hidden_state") != "last_hidden_state":
        raise ValueError("A stitched query head needs an SAE of last_hidden_state.")

    length = max_seq_length or sae.config.get("max_seq_length")
    shared = dict(head_kwargs or {})
    document = build_sparse_encoder(
        sae,
        model_name_or_path,
        document_prompt=document_prompt,
        max_seq_length=length,
        head_kwargs=shared,
        device=device,
    )

    small, large = _sources(
        query_model_name_or_path,
        model_name_or_path or sae.config["base_model"],
        max_seq_length=length or 512,
        text_batch_size=text_batch_size,
        device=device or "auto",
    )
    weight, offset = fit_state_map(
        small,
        large,
        [(query_prompt or "", text) for text in texts],
        ridge=ridge,
        unit_length=sae.normalize_inputs,
    )
    query_head_kwargs = {name: value for name, value in shared.items() if name not in ("trainable", "k")}
    head = stitched_query_head(sae, weight, offset, **query_head_kwargs)

    query = SparseEncoder(
        modules=[Transformer(query_model_name_or_path, max_seq_length=length), head],
        prompts={"query": query_prompt} if query_prompt else None,
        similarity_fn_name="dot",
        device=device,
    )

    return combine_encoders(query, document, shared_vocabulary=False)

fit_state_map

fit_state_map(
    small: EncoderActivationSource,
    large: EncoderActivationSource,
    texts: Sequence[tuple[str, str]],
    *,
    ridge: float = 0.001,
    unit_length: bool = False,
) -> tuple[Tensor, Tensor]

Regress the content-token states of large on those of small over texts.

Parameters:

  • small (EncoderActivationSource) –

    source of the encoder whose states are mapped.

  • large (EncoderActivationSource) –

    source of the encoder whose states are the target, with the same tokenizer and prompts.

  • texts (Sequence[tuple[str, str]]) –

    (kind, text) pairs, as for the other methods of a source.

  • ridge (float, default: 0.001 ) –

    strength of the penalty, relative to the mean variance of the small states.

  • unit_length (bool, default: False ) –

    scale the states of large to unit length first, for an SAE that was trained on unit-length activations.

Returns:

  • tuple[Tensor, Tensor] –

    W (d_small, d_large) and c (d_large,) with h_large ~ h_small @ W + c.

Raises:

  • ValueError –

    if the two encoders split a text into different tokens, or no token is found.

Source code in src/muscari/heads/sae/stitching.py
@torch.no_grad()
def fit_state_map(
    small: EncoderActivationSource,
    large: EncoderActivationSource,
    texts: Sequence[tuple[str, str]],
    *,
    ridge: float = 1e-3,
    unit_length: bool = False,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Regress the content-token states of ``large`` on those of ``small`` over ``texts``.

    Args:
        small: source of the encoder whose states are mapped.
        large: source of the encoder whose states are the target, with the same tokenizer and prompts.
        texts: ``(kind, text)`` pairs, as for the other methods of a source.
        ridge: strength of the penalty, relative to the mean variance of the small states.
        unit_length: scale the states of ``large`` to unit length first, for an SAE that was
            trained on unit-length activations.

    Returns:
        ``W`` ``(d_small, d_large)`` and ``c`` ``(d_large,)`` with ``h_large ~ h_small @ W + c``.

    Raises:
        ValueError: if the two encoders split a text into different tokens, or no token is found.
    """
    moments = _Moments(small.d_in, large.d_in)

    for start in range(0, len(texts), small.text_batch_size):
        chunk = texts[start : start + small.text_batch_size]
        kinds, batch_texts = [kind for kind, _ in chunk], [text for _, text in chunk]
        x, y = small.encode_texts(kinds, batch_texts), large.encode_texts(kinds, batch_texts)

        if not torch.equal(x.token_ids, y.token_ids):
            raise ValueError("The two encoders tokenize the texts differently; they need the same tokenizer.")

        states = F.normalize(y.activations, dim=-1) if unit_length else y.activations
        moments.add(x.activations, states)

    if moments.n == 0:
        raise ValueError("The texts have no content tokens.")

    return moments.solve(ridge)

stitched_query_head

stitched_query_head(
    sae: ExportedSAE,
    weight: Tensor,
    offset: Tensor,
    *,
    k: int | None = None,
    **kwargs: object,
) -> SAEPooling

A trainable SAEPooling for the small encoder, started from the SAE composed with the map.

weight and offset come from fit_state_map. k defaults to the SAE's own; kwargs are further arguments of SAEPooling. The head takes states as they are, since the map already targets the scale the SAE was trained on.

Source code in src/muscari/heads/sae/stitching.py
@torch.no_grad()
def stitched_query_head(
    sae: ExportedSAE,
    weight: torch.Tensor,
    offset: torch.Tensor,
    *,
    k: int | None = None,
    **kwargs: object,
) -> SAEPooling:
    """A trainable ``SAEPooling`` for the small encoder, started from the SAE composed with the map.

    ``weight`` and ``offset`` come from ``fit_state_map``. ``k`` defaults to the SAE's own;
    ``kwargs`` are further arguments of ``SAEPooling``. The head takes states as they are, since
    the map already targets the scale the SAE was trained on.
    """
    jumprelu = sae.threshold is not None
    head = SAEPooling(
        d_in=weight.shape[0],
        num_latents=sae.num_latents,
        k=None if jumprelu else int(sae.config["k"] if k is None else k),
        activation="jumprelu" if jumprelu else "topk",
        normalize_states=False,
        trainable=True,
        **kwargs,  # type: ignore[arg-type]
    )

    encoder = sae.encoder_weight.cpu().float()
    head.encoder_weight.copy_(encoder @ weight.T)
    head.encoder_bias.copy_(sae.encoder_bias.cpu().float() + encoder @ offset)
    if head.threshold is not None and sae.threshold is not None:
        head.threshold.copy_(sae.threshold)

    return head

head_of

head_of(
    model: SparseEncoder, route: str = "document"
) -> Any

The last module of route, which is the pooling head.

Source code in src/muscari/heads/routes.py
def head_of(model: SparseEncoder, route: str = "document") -> Any:
    """The last module of ``route``, which is the pooling head."""
    return route_modules(model, route)[-1]

route_modules

route_modules(
    model: SparseEncoder, route: str = "document"
) -> list[Any]

The modules a text of route passes through; all modules of a model without a Router.

Source code in src/muscari/heads/routes.py
def route_modules(model: SparseEncoder, route: str = "document") -> list[Any]:
    """The modules a text of ``route`` passes through; all modules of a model without a ``Router``."""
    if not is_asymmetric(model):
        return list(model)

    router: Any = model[0]
    return list(router.sub_modules[route])

is_asymmetric

is_asymmetric(model: SparseEncoder) -> bool

Whether the model routes queries and documents through different modules.

Source code in src/muscari/heads/routes.py
def is_asymmetric(model: SparseEncoder) -> bool:
    """Whether the model routes queries and documents through different modules."""
    return isinstance(model[0], Router)

Language-model head

rescale_head

rescale_head(model: Any, divisor: float) -> None

Divide the head's projection matrix by divisor in place; 1 changes nothing.

The bias and the head's transform are left as they are: the paper names the projection matrix only. When the projection is tied to the input embeddings the shared matrix is divided once and stays shared, as the paper does. The input embeddings then shrink too. An encoder that normalises them before anything is added (ModernBERT) is unaffected; in one that first adds position embeddings (BERT, RoBERTa) their balance shifts.

Raises:

  • ValueError –

    if divisor is not positive.

Source code in src/muscari/heads/mlm.py
@torch.no_grad()
def rescale_head(model: Any, divisor: float) -> None:
    """Divide the head's projection matrix by ``divisor`` in place; 1 changes nothing.

    The bias and the head's transform are left as they are: the paper names the projection
    matrix only. When the projection is tied to the input embeddings the shared matrix is
    divided once and stays shared, as the paper does. The input embeddings then shrink too. An
    encoder that normalises them before anything is added (ModernBERT) is unaffected; in one
    that first adds position embeddings (BERT, RoBERTa) their balance shifts.

    Raises:
        ValueError: if ``divisor`` is not positive.
    """
    if divisor <= 0:
        raise ValueError("The divisor must be positive.")
    language_model(model).get_output_embeddings().weight.div_(divisor)

head_norms

head_norms(model: Any) -> dict[str, float | bool]

Mean and maximum L2 norm of the rows of the head's projection, one row per vocabulary entry.

Source code in src/muscari/heads/mlm.py
@torch.no_grad()
def head_norms(model: Any) -> dict[str, float | bool]:
    """Mean and maximum L2 norm of the rows of the head's projection, one row per vocabulary entry."""
    inner = language_model(model)
    norms = inner.get_output_embeddings().weight.float().norm(dim=1)
    return {"mean_row_norm": float(norms.mean()), "max_row_norm": float(norms.max()), "tied": is_tied(inner)}

graft_head

graft_head(
    backbone: str | Path,
    head_source: str | Path,
    **kwargs: Any,
) -> Any

A masked-language model with the encoder weights of backbone and the head of head_source.

Both must share the architecture and the vocabulary. The head's transform and bias come from head_source. A projection that head_source ties to its input embeddings is tied to the embeddings of backbone in the result; an untied projection is kept as it is. kwargs go to both from_pretrained calls.

The head was trained on the hidden states of head_source, not on those of backbone, so its logits may sit elsewhere: measure them again (muscari.evaluation.diagnostics.logit_report) before choosing a shift.

Raises:

  • ValueError –

    if the encoder weights of the two checkpoints do not have the same names and shapes.

Source code in src/muscari/heads/mlm.py
def graft_head(backbone: str | Path, head_source: str | Path, **kwargs: Any) -> Any:
    """A masked-language model with the encoder weights of ``backbone`` and the head of ``head_source``.

    Both must share the architecture and the vocabulary. The head's transform and bias come
    from ``head_source``. A projection that ``head_source`` ties to its input embeddings is tied
    to the embeddings of ``backbone`` in the result; an untied projection is kept as it is.
    ``kwargs`` go to both ``from_pretrained`` calls.

    The head was trained on the hidden states of ``head_source``, not on those of ``backbone``,
    so its logits may sit elsewhere: measure them again (``muscari.evaluation.diagnostics.logit_report``)
    before choosing a shift.

    Raises:
        ValueError: if the encoder weights of the two checkpoints do not have the same names and shapes.
    """
    from transformers import AutoModel, AutoModelForMaskedLM

    donor = AutoModelForMaskedLM.from_pretrained(str(head_source), **kwargs)
    body = AutoModel.from_pretrained(str(backbone), **kwargs)
    encoder: nn.Module = donor.base_model

    # A checkpoint saved without a head may carry a pooler, which a masked-language model drops.
    given = {name: tensor for name, tensor in body.state_dict().items() if not name.startswith("pooler.")}
    if different := _different_tensors(encoder.state_dict(), given):
        raise ValueError(f"The encoders differ in {len(different)} tensors, for example {different[:3]}.")

    encoder.load_state_dict(given)
    return donor

suppress_tokens

suppress_tokens(
    model: Any,
    token_ids: Sequence[int],
    value: float = -10000.0,
) -> None

Set the head's bias to value for token_ids, so that their logits are never positive.

-1e4 instead of minus infinity keeps half-precision arithmetic finite.

Raises:

  • ValueError –

    if the head has no bias.

Source code in src/muscari/heads/mlm.py
@torch.no_grad()
def suppress_tokens(model: Any, token_ids: Sequence[int], value: float = -1e4) -> None:
    """Set the head's bias to ``value`` for ``token_ids``, so that their logits are never positive.

    ``-1e4`` instead of minus infinity keeps half-precision arithmetic finite.

    Raises:
        ValueError: if the head has no bias.
    """
    projection = language_model(model).get_output_embeddings()
    bias = getattr(projection, "bias", None)
    if bias is None:
        raise ValueError("The head's projection has no bias to write to.")

    bias[torch.tensor(sorted({int(token) for token in token_ids}), dtype=torch.long, device=bias.device)] = value

Decoder language models

DecoderTransformer

DecoderTransformer(
    model_name_or_path: str,
    *,
    state_layer: int | None = None,
    bidirectional: bool = False,
    **kwargs: Any,
)

Bases: Transformer

Transformer that returns the residual stream after a chosen block, optionally bidirectional.

Parameters:

  • model_name_or_path (str) –

    the language model, loaded without its language-model head.

  • state_layer (int | None, default: None ) –

    index into the model's hidden_states of the states to return: k is the output of block k - 1 (counting blocks from 0), before the final normalisation. This is the numbering of muscari train-sae --layer; a published SAE labelled with a 0-based block index n needs n + 1. The blocks above are removed, in memory and in what is saved. None returns the final states.

  • bidirectional (bool, default: False ) –

    let every token attend to every token of the text, not only to the ones before it. The model was not trained that way, so its states change; SPLARE adapts the model to it before retrieval training (masked next-token prediction, as LLM2Vec does); examples/adapt_bidirectional.py is that stage. A block that is not attention, such as a linear-recurrence block, stays one-directional whatever the mask says.

  • kwargs (Any, default: {} ) –

    the arguments of Transformer.

The mask is passed as a (batch, 1, length, length) tensor, which decoders of the transformers library use in place of their causal mask.

Source code in src/muscari/heads/decoder.py
def __init__(
    self,
    model_name_or_path: str,
    *,
    state_layer: int | None = None,
    bidirectional: bool = False,
    **kwargs: Any,
) -> None:
    super().__init__(model_name_or_path, **kwargs)
    self.state_layer = state_layer
    self.bidirectional = bidirectional
    self._captured: torch.Tensor | None = None

    if state_layer is not None:
        self._cut_after(state_layer)

bidirectional_mask

bidirectional_mask(
    attention_mask: Tensor, dtype: dtype
) -> Tensor

The (batch, 1, length, length) mask that lets every token attend to every attended token.

It is additive: zero where attention is allowed and the most negative value of dtype at padding. Decoders of the transformers library use a mask of this shape as it is, in place of their causal mask.

Source code in src/muscari/heads/decoder.py
def bidirectional_mask(attention_mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
    """The ``(batch, 1, length, length)`` mask that lets every token attend to every attended token.

    It is additive: zero where attention is allowed and the most negative value of ``dtype``
    at padding. Decoders of the ``transformers`` library use a mask of this shape as it is, in
    place of their causal mask.
    """
    visible = attention_mask[:, None, None, :].expand(-1, 1, attention_mask.shape[1], -1).to(dtype)
    return (1.0 - visible) * torch.finfo(dtype).min

Shared

ContentTokens

Mixin for a pooling module with special_token_ids and include_prompt attributes.

special_token_ids are the ids left out of the pooling; None means they are taken from the model's tokenizer when the model is assembled. Unless include_prompt is set, the tokens of the prompt, whose length Sentence Transformers passes as prompt_length, are left out as well.

on_model_ready

on_model_ready(model: Any) -> None

Take the ids of the tokens that frame a text from the model's tokenizer unless they were given.

Source code in src/muscari/heads/content.py
def on_model_ready(self, model: Any) -> None:
    """Take the ids of the tokens that frame a text from the model's tokenizer unless they were given."""
    tokenizer = getattr(model, "tokenizer", None)
    if self.special_token_ids is None and tokenizer is not None:
        framing = (getattr(tokenizer, f"{name}_token_id", None) for name in ("cls", "sep", "bos", "eos", "pad"))
        self.special_token_ids = sorted({int(token_id) for token_id in framing if token_id is not None})

SavedHead

Bases: Module

Mixin for heads whose constructor arguments are their config_keys.

stores_weights says whether the head has tensors to save next to its config.