"""LexSPLADE: target-word SPLADE pooling, loadable outside the training script.
The training script saves ``modules.json`` pointing at ``__main__`` classes that
only exist while it runs. These are the same two modules in an importable file,
so ``SparseEncoder(repo, trust_remote_code=True)`` works.
A sentence carries its target word wrapped in ```` / ````. The masked-LM
head is applied to **only the tokens between those markers** and the SPLADE
activations log(1 + relu(logit)) are summed over them. The result is a sparse
vector over the vocabulary describing *that word in that context*: a word
embedding, not a sentence embedding.
Pooling config (``1_TargetWordSpladePooling/config.json``):
- ``logit_centering`` (z): each span token's logits are shifted by
``mean + z * std`` over the vocabulary before the relu. RoBERTa/XLM-R logits
sit well above zero, so without this every dimension is active. The model
was trained with it and is only correct with it applied.
- ``blocked_token_ids``: dimensions zeroed in the output (special tokens, the
markers, stop words and non-word tokens).
- ``allowed_token_ids``: if set, a hard restriction of the output space.
The head runs on the span tokens alone, never on ``[batch, seq, vocab]``: at
XLM-R's 250k vocabulary the full logit tensor is several GB, and every
position outside the span would be discarded anyway.
"""
from __future__ import annotations
import inspect
import torch
from sentence_transformers.sparse_encoder import modules
def _mlm_head(auto_model) -> torch.nn.Module:
"""BERT calls the hidden -> vocab head ``cls``, RoBERTa/XLM-R ``lm_head``."""
for name in ("cls", "lm_head"):
head = getattr(auto_model, name, None)
if head is not None:
return head
raise ValueError(f"no MLM head found on {type(auto_model).__name__}")
class DenseHiddenStatesTransformer(modules.Transformer):
"""Masked-LM transformer that stops at the last hidden layer.
The MLM head is handed to the pooling module, which applies it to the
target span only.
"""
def forward(self, features: dict[str, torch.Tensor], **kwargs) -> dict[str, torch.Tensor]:
model = self.auto_model
inputs = {k: features[k] for k in ("input_ids", "attention_mask", "token_type_ids")
if k in features}
if ("token_type_ids" in inputs
and "token_type_ids" not in inspect.signature(model.base_model.forward).parameters):
del inputs["token_type_ids"]
out = model.base_model(**inputs, return_dict=True)
features["dense_token_embeddings"] = out.last_hidden_state
features["mlm_head"] = _mlm_head(model)
return features
class TargetWordSpladePooling(modules.SpladePooling):
"""SPLADE pooling of the MLM head over the span between ```` and ````."""
config_keys = modules.SpladePooling.config_keys + [
"m1_tok_id", "m2_tok_id", "allowed_token_ids", "blocked_token_ids", "logit_centering",
]
def __init__(
self,
*args,
m1_tok_id: int,
m2_tok_id: int,
allowed_token_ids: list[int] | None = None,
blocked_token_ids: list[int] | None = None,
logit_centering: float | None = None,
**kwargs,
):
super().__init__(*args, **kwargs)
self.m1_tok_id = m1_tok_id
self.m2_tok_id = m2_tok_id
self.allowed_token_ids = sorted(set(allowed_token_ids)) if allowed_token_ids else None
self.blocked_token_ids = sorted(set(blocked_token_ids)) if blocked_token_ids else None
self.logit_centering = logit_centering
def forward(self, features: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
head = features.pop("mlm_head")
hidden = features["dense_token_embeddings"]
input_ids, attention_mask = features["input_ids"], features["attention_mask"]
# Positions after and before , markers excluded.
is_open = input_ids == self.m1_tok_id
is_close = input_ids == self.m2_tok_id
span = ((is_open.cumsum(1) > 0) & (is_close.cumsum(1) == 0)
& ~is_open & attention_mask.bool())
# Markers truncated away: pool the whole sentence rather than return an
# empty vector. This silently yields a *sentence* embedding, so keep
# the target inside max_seq_length.
empty = span.sum(1) == 0
if empty.any():
span[empty] = attention_mask[empty].bool()
rows, _ = span.nonzero(as_tuple=True)
logits = head(hidden[span]).float()
if self.logit_centering is not None:
logits = logits - (logits.mean(-1, keepdim=True)
+ self.logit_centering * logits.std(-1, keepdim=True))
activ = torch.log1p(torch.relu(logits))
if self.activation_function == "log1p_relu":
activ = torch.log1p(activ)
pooled = activ.new_zeros(hidden.shape[0], activ.shape[-1])
if self.pooling_strategy == "max":
pooled = pooled.scatter_reduce(0, rows.unsqueeze(-1).expand_as(activ), activ, "amax")
else:
pooled = pooled.index_add(0, rows, activ)
if self.allowed_token_ids is not None:
keep = torch.zeros(pooled.shape[1], dtype=torch.bool, device=pooled.device)
keep[torch.tensor(self.allowed_token_ids, device=pooled.device)] = True
pooled = pooled.masked_fill(~keep, 0.0)
if self.blocked_token_ids is not None:
pooled = pooled.index_fill(
1, torch.tensor(self.blocked_token_ids, device=pooled.device), 0.0)
if self.embedding_dimension is None:
self.embedding_dimension = pooled.shape[1]
features["sentence_embedding"] = pooled
return features