Skip to content

Don't share the transformers tokenizer's backend in StaticEmbedding - #4253

Merged
tomaarsen merged 1 commit into
huggingface:mainfrom
LindseyZ1205:fix/static-embedding-shared-tokenizer
Oct 26, 2026
Merged

tomaarsen merged 1 commit into
huggingface:mainfrom
LindseyZ1205:fix/static-embedding-shared-tokenizer

Conversation

@LindseyZ1205

Copy link
Copy Markdown
Contributor

When StaticEmbedding is created with a PreTrainedTokenizerFast, it uses that tokenizer's backend tokenizers.Tokenizer (tokenizer._tokenizer) directly. Calling the transformers tokenizer sets the padding and truncation of this backend tokenizer, so after a call such as tokenizer(texts, padding=True), StaticEmbedding.preprocess() pads the texts of a batch to the longest one, and nn.EmbeddingBag averages the padding tokens into the embeddings of the shorter texts. After a call with truncation=True, max_length=..., it truncates its inputs to that length.

This also happens without any direct tokenizer call when another module uses the same tokenizer, for example in a Router that encodes queries with a StaticEmbedding and documents with a Transformer:

from sentence_transformers import SentenceTransformer
from sentence_transformers.sentence_transformer.modules import Pooling, Router, StaticEmbedding, Transformer

transformer = Transformer("sentence-transformers-testing/stsb-bert-tiny-safetensors")
static_embedding = StaticEmbedding(transformer.tokenizer, embedding_dim=128)
router = Router.for_query_document(query_modules=[static_embedding], document_modules=[transformer, Pooling(128)])
model = SentenceTransformer(modules=[router])

queries = ["What is a cat?", "How do cats and dogs get along with other animals at home?"]
before = model.encode_query(queries)
model.encode_document(["Cats are small domesticated felines."])
after = model.encode_query(queries)
print(model.similarity_pairwise(before, after))

On main, this prints a value well below 1 for the shorter query, for example tensor([0.2308, 1.0000]) (it depends on the random embedding weights): once documents have been encoded, the query embeddings change. With this change, it prints tensor([1.0000, 1.0000]).

This change copies the backend tokenizer, so that StaticEmbedding has its own and keeps tokenizing without padding or truncation. A tokenizers.Tokenizer that is passed directly is used as before.

I found this through code analysis, not in actual use. I searched the issues and pull requests about StaticEmbedding and its tokenizer and didn't find this. The closest is #3925, which fixed a tokenizer that was shared between WordEmbeddings instances.

Tests

New test_tokenize_after_transformers_tokenizer_call in tests/sentence_transformer/modules/test_static_embedding.py: it tokenizes two texts with a StaticEmbedding created from a PreTrainedTokenizerFast, before and after calling that tokenizer with padding=True, and with truncation=True, max_length=4. Both cases fail on main (the inputs have padding tokens, or are truncated) and pass with this change.

  • pytest tests/sentence_transformer/modules/test_static_embedding.py (HF_HUB_OFFLINE=1): 20 passed, 3 skipped and 1 failed on main; 22 passed, 3 skipped and the same 1 failed with this change. The failure is test_loading_model2vec, which downloads a model.
  • pytest tests/sentence_transformer/modules tests/base/modules tests/sparse_encoder/modules (HF_HUB_OFFLINE=1): 593 passed on main and 595 with this change, with the same 19 failures and 2390 errors in both runs, from tests that need models that aren't in my local cache.
  • The example above: tensor([1.0000, 1.0000]) with this change.
  • ruff check, ruff format --check and typos on the changed files: passed.
  • Not run: the tests that need models I don't have locally.

Versions: Python 3.12.13, transformers 5.17.0, tokenizers 0.23.2, torch 2.14.0.

AI assistance: Claude Code helped me find this bug and write the fix and the test.

StaticEmbedding used the backend tokenizer of a PreTrainedTokenizerFast
directly. Calling the transformers tokenizer sets the padding and
truncation of that backend tokenizer, so after a call such as
tokenizer(texts, padding=True), for example from a Transformer module
in the same Router, StaticEmbedding averaged padding tokens into the
embeddings of the shorter texts, and after a call with truncation, it
truncated its inputs. Copy the backend tokenizer instead.
@tomaarsen

Copy link
Copy Markdown
Member

Hello!

The copy makes sense. Sharing the backend can change StaticEmbedding's behavior during training, while saving and reloading creates independent tokenizers. Keeping them separate from construction avoids that discrepancy. So, I think this is probably better than not copying.

  • Tom Aarsen

@tomaarsen
tomaarsen merged commit 38561d3 into huggingface:main Oct 26, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants