Skip to content
Edit this page

muscari.encoding

Token activations of a frozen encoder: the content tokens of each text, streamed or collected.

Activation source

EncoderActivationSource

EncoderActivationSource(
    model: Any,
    tokenizer: Any,
    *,
    max_seq_length: int = 1024,
    text_batch_size: int = 64,
    layer: int | None = None,
    include_prompt: bool = False,
    prompts: Mapping[str, str] | None = None,
    device: str | device = "auto",
    amp_dtype: dtype | None = None,
)

Bases: ContentTokenizer, PromptedEncoding, TextCollector

Runs texts through a frozen encoder and returns the hidden state of each content token.

Padding, special tokens and (by default) the tokens of the prompt are dropped. What remains are the positions that carry the text itself, which is what a SPLADE-style head pools over.

Parameters:

  • model (Any) –

    a Hugging Face encoder (AutoModel). It is moved to device, put in eval mode and frozen.

  • tokenizer (Any) –

    its tokenizer. A fast tokenizer gives exact prompt masking through character offsets; a slow one falls back to counting the tokens of the prompt alone.

  • max_seq_length (int, default: 1024 ) –

    truncation length in tokens, special tokens included.

  • text_batch_size (int, default: 64 ) –

    number of texts per forward pass.

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

    None uses last_hidden_state, the tensor Sentence Transformers exposes as token_embeddings. An integer indexes hidden_states instead (0 is the embedding output).

  • include_prompt (bool, default: False ) –

    keep the tokens that lie entirely inside the prompt, as Sentence Transformers' Pooling(include_prompt=True) does; by default they are dropped.

  • prompts (Mapping[str, str] | None, default: None ) –

    named prompts, the text prepended to an input, as in Sentence Transformers: encode_batch(texts, prompt_name="query") prepends prompts["query"]. For texts that arrive as (kind, text) a kind that is a name here takes its prompt, and any other kind is itself the prompt. With {"query": "", "document": ""} an encoder without prompts still gets its statistics split into queries and documents.

  • device (str | device, default: 'auto' ) –

    "auto", a device string or a torch.device.

  • amp_dtype (dtype | None, default: None ) –

    run the encoder under autocast with this dtype, for example torch.bfloat16 on CUDA. Activations are always returned as float32.

Attributes:

  • d_in –

    hidden size of the encoder, the input width of the SAE.

  • texts_seen –

    number of texts encoded so far.

  • tokens_seen –

    number of content-token activations returned so far.

  • tokens_by_kind –

    the same count split by the kind of the text (its prompt or label).

  • encode_seconds –

    wall-clock time spent tokenizing and running the encoder.

Source code in src/muscari/encoding/source.py
def __init__(
    self,
    model: Any,
    tokenizer: Any,
    *,
    max_seq_length: int = 1024,
    text_batch_size: int = 64,
    layer: int | None = None,
    include_prompt: bool = False,
    prompts: Mapping[str, str] | None = None,
    device: str | torch.device = "auto",
    amp_dtype: torch.dtype | None = None,
) -> None:
    if max_seq_length < 1 or text_batch_size < 1:
        raise ValueError("max_seq_length and text_batch_size must be positive.")

    self.device = resolve_device(device)
    self.model = model.to(self.device).eval().requires_grad_(False)
    self.tokenizer = tokenizer
    self.d_in = int(model.config.hidden_size)

    self.max_seq_length = max_seq_length
    self.text_batch_size = text_batch_size
    self.layer = layer
    self.include_prompt = include_prompt
    self.prompts = dict(prompts or {})
    self.amp_dtype = amp_dtype

    self.reset_counters()
    self._prompt_token_counts: dict[str, int] = {}

reset_counters

reset_counters() -> None

Start the usage counters again from zero.

Source code in src/muscari/encoding/source.py
def reset_counters(self) -> None:
    """Start the usage counters again from zero."""
    self.texts_seen = 0
    self.tokens_seen = 0
    self.tokens_by_kind: dict[str, int] = defaultdict(int)
    self.encode_seconds = 0.0

from_pretrained classmethod

from_pretrained(
    model_name_or_path: str,
    *,
    revision: str | None = None,
    **kwargs: Any,
) -> EncoderActivationSource

Load the encoder and tokenizer with AutoModel and AutoTokenizer.

kwargs are the constructor arguments other than model and tokenizer.

Source code in src/muscari/encoding/source.py
@classmethod
def from_pretrained(
    cls,
    model_name_or_path: str,
    *,
    revision: str | None = None,
    **kwargs: Any,
) -> EncoderActivationSource:
    """Load the encoder and tokenizer with ``AutoModel`` and ``AutoTokenizer``.

    ``kwargs`` are the constructor arguments other than ``model`` and ``tokenizer``.
    """
    from transformers import AutoModel, AutoTokenizer

    tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, revision=revision)
    model = AutoModel.from_pretrained(model_name_or_path, revision=revision)
    return cls(model, tokenizer, **kwargs)

encode_texts

encode_texts(
    kinds: list[str], texts: list[str]
) -> EncodedBatch

Encode one batch and return its content-token activations.

kinds holds, for each text, the name of a prompt in prompts or the prompt itself, so that one batch can mix queries and documents; encode_batch is the simpler call for texts that share a prompt. A text may contribute zero rows, for example when it is empty.

Raises:

  • ValueError –

    if kinds and texts differ in length.

Source code in src/muscari/encoding/source.py
@torch.no_grad()
def encode_texts(self, kinds: list[str], texts: list[str]) -> EncodedBatch:
    """Encode one batch and return its content-token activations.

    ``kinds`` holds, for each text, the name of a prompt in ``prompts`` or the prompt
    itself, so that one batch can mix queries and documents; ``encode_batch`` is the
    simpler call for texts that share a prompt. A text may contribute zero rows, for
    example when it is empty.

    Raises:
        ValueError: if ``kinds`` and ``texts`` differ in length.
    """
    return self._encode(kinds, [self.prompts.get(kind, kind) for kind in kinds], texts)

PromptedEncoding

Mixin with encode_batch; the class using it provides prompts and _encode.

encode_batch

encode_batch(
    texts: str | Sequence[str],
    *,
    prompt_name: str | None = None,
    prompt: str | None = None,
) -> Tensor

Encode texts that share one prompt and return their content-token activations.

The prompt follows Sentence Transformers: prompt is prepended as given, prompt_name names one of prompts and is ignored when prompt is set, and with neither nothing is prepended. The result is (n_content_tokens, d_in), rows in the order of the texts and of their tokens. The texts are encoded in one forward pass.

Raises:

  • ValueError –

    if prompt_name is not a name in prompts.

Source code in src/muscari/encoding/prompting.py
def encode_batch(
    self,
    texts: str | Sequence[str],
    *,
    prompt_name: str | None = None,
    prompt: str | None = None,
) -> torch.Tensor:
    """Encode texts that share one prompt and return their content-token activations.

    The prompt follows Sentence Transformers: ``prompt`` is prepended as given,
    ``prompt_name`` names one of ``prompts`` and is ignored when ``prompt`` is set, and with
    neither nothing is prepended. The result is ``(n_content_tokens, d_in)``, rows in the
    order of the texts and of their tokens. The texts are encoded in one forward pass.

    Raises:
        ValueError: if ``prompt_name`` is not a name in ``prompts``.
    """
    texts = [texts] if isinstance(texts, str) else list(texts)
    resolved = self.resolve_prompt(prompt_name=prompt_name, prompt=prompt)
    kind = prompt_name if prompt is None and prompt_name is not None else resolved

    return self._encode([kind] * len(texts), [resolved] * len(texts), texts).activations

resolve_prompt

resolve_prompt(
    *,
    prompt_name: str | None = None,
    prompt: str | None = None,
) -> str

The text encode_batch prepends for these arguments.

Raises:

  • ValueError –

    if prompt_name is not a name in prompts.

Source code in src/muscari/encoding/prompting.py
def resolve_prompt(self, *, prompt_name: str | None = None, prompt: str | None = None) -> str:
    """The text ``encode_batch`` prepends for these arguments.

    Raises:
        ValueError: if ``prompt_name`` is not a name in ``prompts``.
    """
    if prompt is not None:
        return prompt
    if prompt_name is None:
        return ""
    if prompt_name not in self.prompts:
        raise ValueError(f"Prompt name {prompt_name!r} is not one of the prompts {sorted(self.prompts)!r}.")

    return self.prompts[prompt_name]

ContentTokenizer

Mixin that tokenizes prompt + text and finds the content tokens.

Content tokens are the attended positions that are neither special tokens nor, unless include_prompt is set, tokens that lie entirely inside the prompt. The class using it provides tokenizer, max_seq_length, include_prompt and prompts.

tokenize

tokenize(
    kinds: list[str], texts: list[str]
) -> tuple[Any, Tensor]

Tokenize one batch as encode_texts does and return the encoding and the content mask.

Each kind is the name of a prompt in prompts or the prompt itself. The mask is boolean (batch, seq) and marks the positions whose activations encode_texts returns.

Raises:

  • ValueError –

    if kinds and texts differ in length.

Source code in src/muscari/encoding/tokenization.py
def tokenize(self, kinds: list[str], texts: list[str]) -> tuple[Any, torch.Tensor]:
    """Tokenize one batch as ``encode_texts`` does and return the encoding and the content mask.

    Each kind is the name of a prompt in ``prompts`` or the prompt itself. The mask is
    boolean ``(batch, seq)`` and marks the positions whose activations ``encode_texts``
    returns.

    Raises:
        ValueError: if ``kinds`` and ``texts`` differ in length.
    """
    return self._tokenize([self.prompts.get(kind, kind) for kind in kinds], texts)

TextCollector

Mixin that streams and collects activations; the class using it provides encode_texts.

stream

stream(
    texts: Iterable[tuple[str, str]],
) -> Iterator[Tensor]

Yield one activation tensor per forward pass.

Texts are gathered into pools and sorted by length inside each pool so that a forward pass pads as little as possible. The output therefore follows the document order only loosely and consecutive rows are strongly correlated; pass it through shuffled_batches before training.

Source code in src/muscari/encoding/collection.py
def stream(self, texts: Iterable[tuple[str, str]]) -> Iterator[torch.Tensor]:
    """Yield one activation tensor per forward pass.

    Texts are gathered into pools and sorted by length inside each pool so that a forward
    pass pads as little as possible. The output therefore follows the document order only
    loosely and consecutive rows are strongly correlated; pass it through
    ``shuffled_batches`` before training.
    """
    for pool in self._pools(texts):
        for batch, _ in self._encode_pool(pool):
            yield batch.activations

collect

collect(
    texts: Iterable[tuple[str, str]], n_tokens: int
) -> Tensor

Collect up to n_tokens activations into one CPU tensor, for evaluation.

Raises:

  • ValueError –

    if the text source produces no activations at all.

Source code in src/muscari/encoding/collection.py
def collect(self, texts: Iterable[tuple[str, str]], n_tokens: int) -> torch.Tensor:
    """Collect up to ``n_tokens`` activations into one CPU tensor, for evaluation.

    Raises:
        ValueError: if the text source produces no activations at all.
    """
    return torch.cat([text.activations for text in self.collect_texts(texts, n_tokens)])

collect_by_kind

collect_by_kind(
    texts: Iterable[tuple[str, str]], n_tokens: int
) -> dict[str, Tensor]

Collect up to n_tokens activations in total, grouped by the kind of their text.

The groups keep the proportions in which the kinds occur in texts, so that an evaluation can be reported per side (queries, documents) as well as overall. Each value is a CPU tensor (n, d_in).

Raises:

  • ValueError –

    if the text source produces no activations at all.

Source code in src/muscari/encoding/collection.py
def collect_by_kind(self, texts: Iterable[tuple[str, str]], n_tokens: int) -> dict[str, torch.Tensor]:
    """Collect up to ``n_tokens`` activations in total, grouped by the kind of their text.

    The groups keep the proportions in which the kinds occur in ``texts``, so that an
    evaluation can be reported per side (queries, documents) as well as overall. Each value
    is a CPU tensor ``(n, d_in)``.

    Raises:
        ValueError: if the text source produces no activations at all.
    """
    return group_by_kind(self.collect_texts(texts, n_tokens))

collect_texts

collect_texts(
    texts: Iterable[tuple[str, str]], n_tokens: int
) -> list[EncodedText]

Collect texts one by one until n_tokens activations have been gathered.

Text boundaries are kept, which is what an evaluation of pooled, per-text vectors needs. Texts without content tokens are left out, and the last text is cut where the token budget ends.

Raises:

  • ValueError –

    if the text source produces no activations at all.

Source code in src/muscari/encoding/collection.py
def collect_texts(self, texts: Iterable[tuple[str, str]], n_tokens: int) -> list[EncodedText]:
    """Collect texts one by one until ``n_tokens`` activations have been gathered.

    Text boundaries are kept, which is what an evaluation of pooled, per-text vectors
    needs. Texts without content tokens are left out, and the last text is cut where the
    token budget ends.

    Raises:
        ValueError: if the text source produces no activations at all.
    """
    collected: list[EncodedText] = []
    remaining = n_tokens

    for text in self._encoded_texts(texts):
        if remaining <= 0:
            return collected

        collected.append(EncodedText(text.kind, text.activations[:remaining], text.token_ids[:remaining]))
        remaining -= collected[-1].activations.shape[0]

    if not collected:
        raise ValueError("No activations collected; the text source is empty.")

    return collected

Results

EncodedBatch

Bases: NamedTuple

Content-token activations of one forward pass.

Attributes:

  • activations (Tensor) –

    float32 (n_content_tokens, d_in) on the encoder's device; rows follow the batch order, then the token order inside each text.

  • tokens_per_text (Tensor) –

    CPU tensor (batch,) with the number of rows of each text.

  • token_ids (Tensor) –

    CPU tensor (n_content_tokens,) with the vocabulary id behind each row.

  • hidden_sums (Tensor) –

    float32 (batch, d_in) on the encoder's device: the sum of the hidden states over every attended position of a text, special and prompt tokens included. Divided by attended it is the mean-pooled sentence embedding.

  • attended (Tensor) –

    CPU tensor (batch,) with the number of attended positions of each text.

EncodedText

Bases: NamedTuple

Content-token activations of one text, on the CPU.

kind is the kind of the text: its prompt, or its label where labels are used.

group_by_kind

group_by_kind(
    texts: Iterable[EncodedText],
) -> dict[str, Tensor]

Concatenate the activations of texts per kind, in order of first appearance.

Source code in src/muscari/encoding/batches.py
def group_by_kind(texts: Iterable[EncodedText]) -> dict[str, torch.Tensor]:
    """Concatenate the activations of ``texts`` per kind, in order of first appearance."""
    groups: dict[str, list[torch.Tensor]] = defaultdict(list)

    for text in texts:
        groups[text.kind].append(text.activations)

    return {kind: torch.cat(parts) for kind, parts in groups.items()}

Streams

shuffled_batches

shuffled_batches(
    stream: Iterable[Tensor],
    *,
    batch_tokens: int,
    buffer_tokens: int,
    seed: int = 42,
) -> Iterator[Tensor]

Mix activations from many documents and emit batches of exactly batch_tokens rows.

Tokens of one document are highly correlated. They are accumulated in a buffer of buffer_tokens rows; whenever it fills up, a random half is emitted and the other half stays to be mixed with the next refill. When the stream ends the rest is emitted and the final partial batch is dropped. Every activation is emitted at most once.

The buffer is allocated once on the device of the first tensor. Peak memory is about 1.5 times buffer_tokens * d * 4 bytes.

Raises:

  • ValueError –

    if buffer_tokens is smaller than two batches.

Source code in src/muscari/encoding/streams.py
def shuffled_batches(
    stream: Iterable[torch.Tensor],
    *,
    batch_tokens: int,
    buffer_tokens: int,
    seed: int = 42,
) -> Iterator[torch.Tensor]:
    """Mix activations from many documents and emit batches of exactly ``batch_tokens`` rows.

    Tokens of one document are highly correlated. They are accumulated in a buffer of
    ``buffer_tokens`` rows; whenever it fills up, a random half is emitted and the other half
    stays to be mixed with the next refill. When the stream ends the rest is emitted and the
    final partial batch is dropped. Every activation is emitted at most once.

    The buffer is allocated once on the device of the first tensor. Peak memory is about 1.5
    times ``buffer_tokens * d * 4`` bytes.

    Raises:
        ValueError: if ``buffer_tokens`` is smaller than two batches.
    """
    if batch_tokens < 1:
        raise ValueError("batch_tokens must be positive.")
    if buffer_tokens < 2 * batch_tokens:
        raise ValueError("buffer_tokens must be at least 2 * batch_tokens.")

    buffer = _ShuffleBuffer(batch_tokens, buffer_tokens, seed)

    for activations in stream:
        yield from buffer.add(activations)

    yield from buffer.emit(buffer.filled)

unit_length

unit_length(batches: Iterable[Tensor]) -> Iterator[Tensor]

Scale every activation of every batch to unit length.

Training an SAE on these makes its features independent of the length of an activation. Gao et al. normalise their inputs this way after removing the mean over the dimensions; LightOn's SlideOn trains its SAE on unit-length token embeddings. Here the mean is left to the decoder bias. An SAE trained this way must be saved with normalize_inputs: true.

Source code in src/muscari/encoding/streams.py
def unit_length(batches: Iterable[torch.Tensor]) -> Iterator[torch.Tensor]:
    """Scale every activation of every batch to unit length.

    Training an SAE on these makes its features independent of the length of an activation.
    Gao et al. normalise their inputs this way after removing the mean over the dimensions;
    LightOn's SlideOn trains its SAE on unit-length token embeddings. Here the mean is left to
    the decoder bias. An SAE trained this way must be saved with ``normalize_inputs: true``.
    """
    for batch in batches:
        yield F.normalize(batch, dim=-1)