Inputs are silently truncated at `max_seq_length` with no way for the caller to detect it
SentenceTransformer.encode() truncates inputs that exceed max_seq_length and gives the
caller no signal that it happened. The result is a valid-looking embedding of a document
whose tail never reached the encoder.
Why the usual safety net does not fire
transformers does warn about over-long sequences, but only when max_length is not
passed:
# transformers/tokenization_utils_base.py
if max_length is None and len(ids) > self.model_max_length and verbose and self.model_max_length != 0:
logger.warning("Token indices sequence length is longer than the specified maximum ...")Transformer.preprocess() always passes a max_length together with
truncation="longest_first":
# sentence_transformers/base/modules/transformer.py
modality_kwargs = {
"text": {"padding": True, "truncation": "longest_first"},
...
}
...
modality_kwargs["text"]["max_length"] = task_max_lengthso that warning is disabled by construction, and Sentence Transformers does not emit one of its own. Grepping the package for truncation-related logging finds only the query expansion warnings.
Minimal reproduction
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
print("max_seq_length:", model.max_seq_length)
text = "alpha bravo charlie delta " * 400 # far beyond the limit
a = model.encode(text)
b = model.encode(text + text) # twice the document, same leading tokens
print("identical:", np.array_equal(a, b)) # TrueDoubling the document changes nothing, and nothing in the API says why. The same holds for any two documents sharing a long enough prefix.
Detecting it today
The only way I found is to tokenize a second time, without truncation, and compare:
n = len(model.tokenizer(text, truncation=False)["input_ids"])
lost = n > model.max_seq_lengthThat costs a full extra tokenization pass per text, and it is easy not to realise it is needed at all. In an indexing pipeline this surfaced only after we added tokenizer-side accounting of our own; until then the loss was invisible everywhere in the system.
Why I think the information is already within reach
_NON_MODEL_FEATURE_KEYS in the same file already lists overflow_to_sample_mapping
and offset_mapping among the keys that must not be forwarded to the model. So the
overflow mechanism is known here; it is just never requested, and its absence is never
reported.
What I am asking
Not a change of default behaviour — truncation is the right default, and most callers want it. The gap is that it is unobservable. A few options, in increasing order of invasiveness:
- Documentation only. A short note that inputs over
max_seq_lengthare truncated silently, with the two-pass snippet above as the way to check. Happy to write it — I am not sure which page you would want it on. - Opt-in warning. Something like
Transformer(..., warn_on_truncation=True), default off, logging once perencodecall with the number of affected inputs. - Expose a count through a key that is already filtered out of the forward inputs, so callers can read it without any change to the forward path.
happy to open a PR for whichever of these you prefer, or to drop it if you consider the current behaviour documented enough. I wrote #3987 (thread-budget parity in the CPU backend comparison docs), so this is the same corner of the library.
Source: huggingface/sentence-transformers