Sub topic 8
Input length, truncation, and chunking
This chapter assumes you have built the retrieve-then-rerank pipeline from the earlier chapters and know what a token is. It covers what happens when a passage is too long for the cross-encoder, and how to handle it.
Why length matters
A cross-encoder reads the query and passage as one sequence. That sequence has a fixed maximum length, set by the model and by the max_length argument. The model cross-encoder/ms-marco-MiniLM-L-6-v2 is commonly run with max_length=512 tokens.
The limit covers three things together:
- the query tokens
- the passage tokens
- the special tokens, usually
[CLS]and two[SEP]
If the pair is longer, the tokenizer truncates it. Truncation usually cuts the end of the passage, so the model never sees the cut text. If the answer sits in the dropped part, the score is low even though the passage is relevant. Nothing raises an error. Relevant passages just rank lower than they should.
Cost also grows with length. Transformer attention cost grows faster than linearly with sequence length, so long inputs are slower than short ones.
Check how much you lose
Measure before you fix anything. Count tokens for your candidate passages and see how many exceed the budget.
from sentence_transformers import CrossEncoder
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2", max_length=512)
tokenizer = model.tokenizer
def token_count(query, passage):
q = len(tokenizer.encode(query, add_special_tokens=False))
p = len(tokenizer.encode(passage, add_special_tokens=False))
return q + p + 3
query = "How do I rotate an API key?"
passage = "Rotate keys from the Security page. " * 200
print(token_count(query, passage), "tokens; limit is", model.max_length)If a large share of your candidates go over the limit, truncation is affecting your results.
Chunk, score, aggregate
The usual fix is to split long passages into overlapping windows. You score each window with the query and then combine the window scores. Overlap keeps a sentence from being split with no context on either side.
def chunk_passage(text, query, max_tokens=512, overlap=64):
q_len = len(tokenizer.encode(query, add_special_tokens=False))
budget = max_tokens - q_len - 3
ids = tokenizer.encode(text, add_special_tokens=False)
step = budget - overlap
chunks = []
for start in range(0, max(len(ids), 1), step):
chunks.append(tokenizer.decode(ids[start:start + budget]))
if start + budget >= len(ids):
break
return chunks
def score_long(query, text):
chunks = chunk_passage(text, query)
scores = model.predict([(query, c) for c in chunks])
return float(max(scores))
print(score_long(query, passage))Taking the maximum assumes one good window is enough to make the passage relevant. That fits most question-answering tasks. Other options are the mean, which rewards passages that are relevant throughout, or the first window plus the best window.
Chunk at index time when you can
Chunking at query time repeats work on every search. If you control ingestion, split documents into chunks before indexing. Then the first-stage retriever and the reranker see the same units. Prefer boundaries such as paragraphs or headings over fixed token counts, and keep chunk sizes under the reranker's budget with room for the query.
Chunks that are too small lose context, and the model may not tell what a pronoun refers to. Chunks that are too large hit the limit again. Common starting points are 200 to 400 tokens with some overlap. Tune the size on your own evaluation set.
Common mistakes
- Setting
max_lengthhigher than the model was trained for. Positional embeddings beyond the trained length are untrained, so quality can drop or the call can fail. - Setting
max_lengthvery low to save time, then cutting off the answer. - Showing the user a chunk that was reranked, but returning the whole document, or the reverse. Keep track of which chunk produced the score.
- Returning several chunks of one document as separate results. Deduplicate by document ID if you want one result per document.
Exercise
A query has 20 tokens and the cross-encoder has max_length=512 with 3 special tokens. What is the passage token budget per chunk, and how many chunks does a 1,000-token passage need with an overlap of 64 tokens?
Show answer
The budget is 512 - 20 - 3 = 489 tokens. The step between windows is 489 - 64 = 425. Windows start at tokens 0, 425, and 850. The second window ends at token 914, which is short of 1,000, so a third window is needed. That gives 3 chunks.