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 todevice, 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) –Noneuseslast_hidden_state, the tensor Sentence Transformers exposes astoken_embeddings. An integer indexeshidden_statesinstead (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")prependsprompts["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 atorch.device. -
amp_dtype(dtype | None, default:None) –run the encoder under autocast with this dtype, for example
torch.bfloat16on 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
reset_counters
¶
Start the usage counters again from zero.
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
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
kindsandtextsdiffer in length.
Source code in src/muscari/encoding/source.py
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_nameis not a name inprompts.
Source code in src/muscari/encoding/prompting.py
resolve_prompt
¶
The text encode_batch prepends for these arguments.
Raises:
-
ValueError–if
prompt_nameis not a name inprompts.
Source code in src/muscari/encoding/prompting.py
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 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
kindsandtextsdiffer in length.
Source code in src/muscari/encoding/tokenization.py
TextCollector
¶
Mixin that streams and collects activations; the class using it provides encode_texts.
stream
¶
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
collect
¶
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
collect_by_kind
¶
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
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
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 byattendedit 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
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_tokensis smaller than two batches.
Source code in src/muscari/encoding/streams.py
unit_length
¶
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.