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 thatencode_queryuses 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_statenor a positive index.
Source code in src/muscari/heads/sae/build.py
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 thekthe 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"applieslog(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_saetakes 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
trainableis 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
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
kis given for a JumpReLU SAE, whose threshold decides what is kept.
Source code in src/muscari/heads/sae/pooling.py
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
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;
Nonekeeps 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:
-1e4is 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_idsfinds 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_indexthen 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_foldbuilds 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).shiftmust 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;Falsepools 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
set_fold
¶
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
stores_weights
¶
The fold index and the capacity biases are tensors; without them the config is enough.
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
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
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
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 withsingle_ascii=True.extra: the tokens named inextra.
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
extrais not in the vocabulary.
Source code in src/muscari/heads/vocabulary/tokens.py
case_space_fold
¶
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
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
token_energy
¶
E_i of every token: the log-sum-exp of its logits divided by temperature.
TermCapacity
¶
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
windowtexts and per unit oflog(share / capacity). -
window(int, default:2000) –number of texts the running share remembers.
Source code in src/muscari/heads/capacity.py
observe
¶
Take in the pooled vectors (texts, size) of one forward pass and move the biases.
Source code in src/muscari/heads/capacity.py
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
Falsefor 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
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
trainableandk, 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
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
largeto unit length first, for an SAE that was trained on unit-length activations.
Returns:
-
tuple[Tensor, Tensor]–W(d_small, d_large)andc(d_large,)withh_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
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
head_of
¶
route_modules
¶
The modules a text of route passes through; all modules of a model without a Router.
Source code in src/muscari/heads/routes.py
is_asymmetric
¶
Language-model head¶
rescale_head
¶
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
divisoris not positive.
Source code in src/muscari/heads/mlm.py
head_norms
¶
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
graft_head
¶
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
suppress_tokens
¶
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
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_statesof the states to return:kis the output of blockk - 1(counting blocks from 0), before the final normalisation. This is the numbering ofmuscari train-sae --layer; a published SAE labelled with a 0-based block indexnneedsn + 1. The blocks above are removed, in memory and in what is saved.Nonereturns 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.pyis 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
bidirectional_mask
¶
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
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
¶
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
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.