In Sentence Transformers, how do you check and change how many tokens a loaded SentenceTransformer reads from each input text?
answer
- a property on the model
- set from the checkpoint's saved config
- 256 for all-MiniLM-L6-v2
- assign it before encoding
- ceiling: max_position_embeddings
basics
~10 sRead the model's max_seq_length property and assign a new value before encoding. Tokens past it are dropped without an error, and it must stay within the encoder's position-embedding limit, max_position_embeddings.
solid answer
~30 s`SentenceTransformer` exposes `max_seq_length` as a property; it is set from the checkpoint's saved configuration and is backed by the tokenizer's `model_max_length`. `sentence-transformers/all-MiniLM-L6-v2` reports 256 and `all-mpnet-base-v2` 384. Assigning `model.max_seq_length = 128` speeds up short texts; raising it lets longer chunks in, but only up to the encoder's `max_position_embeddings`, and quality past the length the model was trained on is not guaranteed. Longer inputs are truncated silently, so I count tokens with `model.tokenizer` on a sample of chunks before trusting the setting. For a single call, `encode(..., processing_kwargs={"text": {"max_length": 256, "truncation": True}})` overrides it.
go deeper
Know that model.max_seq_length shows the token limit, that it can be assigned, and that longer texts are cut without warning.
Explain where the value comes from, how it maps to the tokenizer's model_max_length, and why the encoder's position limit caps it.
Audit a corpus by token counts against the limit and choose between re-chunking, a longer-context checkpoint and a raised limit with measured retrieval.
Weigh chunk size, model context length and CPU latency together when setting an indexing standard across teams.
## Where the limit lives A Sentence Transformers model is a stack of modules run in order. For a classic checkpoint such as `sentence-transformers/all-MiniLM-L6-v2` that stack is a **`Transformer`** module (the encoder plus its tokenizer), a **`Pooling`** module (mean pooling) and a **`Normalize`** module. Only the first module reads tokens, so the input length limit belongs to it. `SentenceTransformer.max_seq_length` is a **property** that reaches into that first module. In the current release the `Transformer` module backs it with the tokenizer's `model_max_length`: - when the checkpoint was saved with a length (the classic `sentence_bert_config.json` carries `max_seq_length`), that value is used; - when nothing is configured, the library caps the tokenizer's limit at the encoder config's `max_position_embeddings`; - the property reads `None` when the first module defines no limit at all. Typical values from the docs: **256** for `all-MiniLM-L6-v2`, **384** for `all-mpnet-base-v2`, **512** for `BAAI/bge-base-en-v1.5` and `mixedbread-ai/mxbai-embed-large-v1`, **8,192** for `BAAI/bge-m3`. ## Reading and changing it ```python from sentence_transformers import SentenceTransformer model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") print(model.max_seq_length) # 256 lengths = [len(model.tokenizer(t)["input_ids"]) for t in sample_chunks] print(max(lengths), sum(l > model.max_seq_length for l in lengths)) model.max_seq_length = 128 # shorter: faster for short texts ``` The setter writes straight to the tokenizer, so every later `encode`, `encode_query` and `encode_document` call uses the new value. The options compare like this: | Change | Effect | Watch out for | |---|---|---| | Lower it (for example 128) | less compute per long input, faster batches | more of each long chunk is ignored | | Raise it toward the encoder limit | longer chunks fully read | slower; quality beyond the training length is not guaranteed | | Raise it past `max_position_embeddings` | the setter accepts it | the encoder has no positions that far, so long inputs fail in the forward pass | | Per-call `processing_kwargs={"text": {"max_length": 256, "truncation": True}}` | overrides for one `encode` call only | the model's own setting is unchanged afterwards | ## What happens to the overflow Anything past the limit is **truncated at tokenization time without an error or a warning**: the embedding is computed from the first `max_seq_length` tokens only. Why encoders behave this way is a question about how embedding models work; the practical consequence is that a chunker producing 600-token passages for a 256-token model silently indexes the first part of every chunk. That is why the token count, not the character count, is what you compare against the limit. Two habits catch the problem early: 1. Tokenize a representative sample of your chunks with `model.tokenizer` and count how many exceed `model.max_seq_length`. 2. Either size your chunks to fit, or pick a checkpoint whose limit covers them; raising the property on a short-context model is not a substitute for a long-context one. ## Prompts share the same budget A prompt is prepended to the text **before** tokenization, so its tokens count against `max_seq_length` too. An instruction such as `"Represent this sentence for searching relevant passages: "` costs several tokens on every query, and a long task instruction on documents can take a noticeable share of a 256- or 512-token window: - short queries are rarely affected, because they sit far below the limit; - long documents with a long document prompt lose that many tokens from their tail; - when auditing a corpus against the limit, tokenize the prompt plus the text, not the bare text. ## Saving and consistency - After changing the value, `save_pretrained` writes it with the model's tokenizer files, so the next load reads the same limit. - The corpus and the queries must be embedded under the same setting; re-embedding half an index at a different length mixes two slightly different representations of long texts. - `encode` sorts inputs by length and pads each batch only to its longest text, so a high limit costs nothing for batches of short texts; it costs time only when long texts are actually present. ## Common confusions - `max_seq_length` limits **input tokens**; `truncate_dim` limits **output dimensions**. They are unrelated knobs. - The older `get_max_seq_length()` method still exists but is deprecated in favour of the property. - A `CrossEncoder` has its own `max_seq_length` that applies to the query and passage pair together, which is a reranking concern rather than an embedding one.
- Your chunker emits 500-token passages and the model reports max_seq_length 256. What are your options?Re-chunk to roughly 200-250 tokens so each passage is read in full, or switch to a checkpoint whose limit covers 500 tokens, such as one configured for 512. Raising the property toward the encoder's `max_position_embeddings` is possible, but quality beyond the length the model was trained on is not guaranteed, so measure retrieval before shipping it.
- Does lowering max_seq_length change embeddings for texts already shorter than the new limit?No. A text shorter than the limit tokenizes to the same ids either way, so its embedding is unchanged. Only texts longer than the new limit lose tokens, which is why lowering the limit is a cheap speed-up for corpora of short texts.
- Expects encode to raise an error when a text exceeds max_seq_length
- Believes every model reads 512 tokens regardless of its configured limit
- Compares character counts, not token counts, against max_seq_length
- Confuses max_seq_length with truncate_dim, the output dimension setting
- Raises max_seq_length far past max_position_embeddings to embed whole documents