Sub topic 8
Input length, truncation, and chunking
This chapter assumes you can run the two-stage pipeline from the earlier chapters. You should know what a bi-encoder and a cross-encoder are, and what a token is. It covers one practical limit of cross-encoders: they read a fixed number of tokens, and anything beyond that is silently dropped.
Why input length matters for a cross-encoder
A cross-encoder reads the query and the passage as one sequence. The model sees [CLS] query [SEP] passage [SEP] and produces a single score. Every transformer has a maximum sequence length, counted in tokens. The cross-encoder/ms-marco-MiniLM-L-6-v2 model was trained with sequences of up to 512 tokens. That budget is shared by the query, the special tokens, and the passage.
A token is a piece of a word produced by the model's tokenizer. English prose averages about 1.3 tokens per word, so 512 tokens is roughly 350 to 400 words. Code, tables, URLs, and non-English text often use more tokens per word.
If the pair is longer than the limit, the tokenizer truncates it. The model never sees the cut text. It can't tell you what it missed, and the score looks normal.
How truncation works
Sentence-transformers' CrossEncoder takes a max_length argument. It tokenizes each pair and truncates to that length. The Hugging Face tokenizer's truncation strategy decides which side is cut. The common strategies are:
| Strategy | What is cut | Effect |
|---|---|---|
| `only_second` | The passage only | The query is always kept in full. This is the usual choice for reranking. |
| `longest_first` | Whichever side is longer, one token at a time | Usually cuts the passage, but a very long query is cut as well. |
| `do_not_truncate` | Nothing | The model raises an error or misbehaves when the pair is too long. |
In practice the passage is the long part, so the head of the passage is what survives. The tail is lost. This is a problem for documents where the answer is not near the start, such as a long help page with an FAQ at the bottom.
You can measure how often this happens before you rely on a model. Count tokens for your own candidates:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("cross-encoder/ms-marco-MiniLM-L-6-v2")
MAX_LEN = 512
def pair_length(query, passage):
enc = tokenizer(query, passage, truncation=False)
return len(enc["input_ids"])
query = "How do I rotate an API key?"
passages = [
"API keys can be rotated from the Security page by creating a new key.",
"Release notes. " * 400,
]
for p in passages:
n = pair_length(query, p)
status = "TRUNCATED" if n > MAX_LEN else "ok"
print(f"{n:5d} tokens {status} {p[:40]!r}")The tokenizer may print a warning that the sequence is longer than the model's maximum length. That warning is expected here, because truncation=False is the point of the measurement.
Run a check like this over a sample of real candidates. If more than a small share of your passages exceed the limit, you need a chunking strategy.
Chunking: split first, then score
Chunking means splitting a long document into smaller passages, each short enough to fit in the model's window. You rerank the chunks, not the whole document. This is usually done at indexing time, so the first-stage retriever also works on chunks.
Three decisions matter.
- Chunk size. Leave room for the query and special tokens. With a 512-token limit, a chunk of 200 to 350 tokens is a common choice. Smaller chunks are more focused. Larger chunks keep more context.
- Overlap. Repeat the last part of one chunk at the start of the next, often 10 to 20 percent. This stops an answer from being split across a boundary.
- Boundaries. Split on paragraphs or sentences where you can, not at arbitrary token counts. A chunk that begins mid-sentence is harder for the model to read.
Here is a token-based chunker that respects the model's tokenizer:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("cross-encoder/ms-marco-MiniLM-L-6-v2")
def chunk_text(text, chunk_tokens=300, overlap_tokens=50):
ids = tokenizer(text, add_special_tokens=False)["input_ids"]
step = chunk_tokens - overlap_tokens
chunks = []
for start in range(0, len(ids), step):
window = ids[start:start + chunk_tokens]
chunks.append(tokenizer.decode(window))
if start + chunk_tokens >= len(ids):
break
return chunks
doc = "Step one is to open the Security page. " * 120
chunks = chunk_text(doc)
print(len(chunks), "chunks")
print(len(tokenizer(chunks[0], add_special_tokens=False)["input_ids"]), "tokens in first chunk")This splits at token positions, so it can cut mid-sentence. It is a simple baseline. For production, split on sentence or paragraph boundaries first, then pack sentences into chunks until the token budget is reached.
Scoring chunks and combining them
Once a document is split, one document has many chunk scores. You need a rule to turn them into one document-level result, or to return the chunk directly.
- Return the best chunk. If your application shows passages, as in question answering or retrieval for a language model, rank the chunks themselves. This is the simplest option.
- Max-pool per document. Score every chunk, then give each document the score of its best chunk. This works when one relevant passage makes a document relevant.
- Mean or sum. Averaging dilutes a strong chunk with weak ones. Summing favors long documents. Both are usually worse than max for relevance.
from collections import defaultdict
from sentence_transformers import CrossEncoder
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2", max_length=512)
def rerank_documents(query, chunks):
# chunks: list of (doc_id, chunk_text)
scores = model.predict([(query, text) for _, text in chunks])
best = defaultdict(lambda: float("-inf"))
for (doc_id, _), score in zip(chunks, scores):
best[doc_id] = max(best[doc_id], float(score))
return sorted(best.items(), key=lambda x: x[1], reverse=True)
chunks = [
("guide", "Rotate API keys from the Security page."),
("guide", "Release notes for version 2.1 and earlier."),
("faq", "Our API returns JSON by default."),
]
print(rerank_documents("How do I rotate an API key?", chunks))Chunking has a cost. Each document now produces several pairs, so the number of cross-encoder calls grows. Candidate depth is then counted in chunks, not documents. Fifty candidate documents of ten chunks each is 500 pairs. The latency chapter covers how that affects cost.
Context lost at chunk boundaries
A chunk read alone can lose meaning. A chunk that says "It can be done from the same page" has no referent. A bi-encoder may retrieve it and the cross-encoder may score it low, or the reverse. Two common fixes:
- Add a title or heading prefix. Prepend the document title and section heading to each chunk before scoring. This is cheap and often helps a lot.
- Use overlap and sentence-aware splits, as described above.
Keep the prefix short. Every prefix token reduces the room for the passage.
Long queries
Queries are usually short, but not always. A user may paste an error message or a paragraph. With longest_first, a long query can push the passage out of the window. Cap the query length, for example at 64 tokens, before pairing. With only_second truncation, a very long query leaves little or no room for the passage, so capping matters there as well.
Mismatched windows between stages
The bi-encoder and the cross-encoder have separate limits. all-MiniLM-L6-v2 truncates at 256 tokens by default, while the cross-encoder above allows 512. If you chunk to 400 tokens, the bi-encoder sees only the first 256 of each chunk when it indexes. The retriever then embeds a partial chunk, and relevant text in the tail is invisible at the first stage. Chunk to the smallest window in your pipeline, or set max_seq_length deliberately on each model and know what each stage sees.
Debugging truncation problems
Signs that truncation is hurting you:
- Long documents rank worse than short ones on queries where you know they are relevant.
- Relevant documents score well when you test only their first paragraph.
- Recall at the first stage is high, but the reranker moves relevant long documents down.
A direct test is to score the same passage twice, once as is and once with the answer sentence moved to the start. If the score jumps, the answer was being cut. Also log the share of pairs that exceed max_length in production. A rising share means your content changed and your chunking no longer fits.
Do not raise max_length above what the model was trained for. Position embeddings past the training length are untrained or poorly trained, and quality usually drops. Some newer rerankers are trained on longer inputs, such as 1024 or 8192 tokens. If you need that, pick one of those models. Check its documented limit, and remember that attention cost grows with sequence length, so latency rises too.
Exercise
Your cross-encoder has a 512-token limit and you rerank whole 2,000-token help articles. Relevant articles with the answer near the end rank poorly. Give two changes that fix this, and one thing to check about the first-stage model after the change.
Show answer
First, split each article into chunks of roughly 200 to 350 tokens with some overlap, and score the chunks; then take the best chunk score per document (max-pooling) or return the chunk itself. Second, prepend the article title or section heading to each chunk so it keeps its context. After the change, check the first-stage bi-encoder's own maximum sequence length (for example 256 tokens). If chunks are longer than that window, the bi-encoder embeds only part of each chunk, so chunk to the smallest window in the pipeline.
Exercise
A teammate sets max_length=2048 on cross-encoder/ms-marco-MiniLM-L-6-v2 to "avoid truncation". Why is this a poor fix?
Show answer
The model was trained with sequences up to 512 tokens, so its position embeddings beyond that are not trained for this task and relevance quality usually drops. Attention cost also grows with length, so latency rises. The better fixes are chunking the text or choosing a reranker trained for longer inputs.