Cross-Encoder Reranker max_length=512: Half My Chunk Was Never Read

2026-11-30来源 dev.toEnglish

My reranker gave the right passage a score of -7.9. The passage contained the exact sentence the user asked about, word for word. It just contained it around token 600, and the reranker stopped reading at 512.

No error. No warning. Just a confident, wrong ranking.

This is the cross-encoder reranker max_length=512 problem, and if your RAG pipeline uses bge-reranker, an ms-marco cross-encoder, or anything else built on a BERT-style encoder, it is probably happening to you right now.

TL;DR

  • Cross-encoder rerankers read [CLS] query [SEP] passage [SEP] as one sequence, and most are capped at 512 tokens total.
  • Anything past the cap is cut off before the model sees it. The default longest_first truncation trims the passage tail, so answers near the end of a chunk score as if they don't exist.
  • Your chunker probably counts tokens with a different tokenizer (often tiktoken) than your reranker (WordPiece or SentencePiece), so "512-token chunks" can be well over 512 reranker tokens.
  • Fix it by sizing chunks with the reranker's own tokenizer, or by scoring overlapping windows and taking the max score (MaxP).
  • Raising max_length only works if the model has the position embeddings for it, and it costs at least linear compute per pair, with the attention part growing quadratically.

What happened in my RAG pipeline?

The setup was boring on purpose. Hybrid retrieval pulls the top 50 chunks, a cross-encoder reranks them, the top 5 go to the LLM.

A user asked about the refund window for annual plans. The policy doc had a chunk that started with three paragraphs about monthly billing and then, near the bottom, said "Annual plans can be refunded within 30 days of renewal."

Embedding retrieval had that chunk at #3. After reranking, it was #14 and never reached the model. The LLM answered with the monthly policy, sounding very sure of itself.

When I pulled the chunk and fed it to the reranker by hand, then fed it again with only the last paragraph, the score jumped from strongly negative to strongly positive. Same text. Same query. The only difference was whether the answer survived truncation.

What does max_length=512 actually do to a cross-encoder reranker?

It defines a hard token budget for the query and passage combined, and everything over budget gets deleted before inference. A cross-encoder doesn't embed the query and passage separately. It concatenates them and runs full attention across both, which is why it ranks better than a bi-encoder and also why it has a single shared length limit.

For a BERT-style model the input looks like this:

[CLS] what is the refund window for annual plans [SEP] Monthly plans renew on ... [SEP] 

XLM-RoBERTa models like bge-reranker-base use <s> query </s></s> passage </s>, so that's 4 special tokens instead of 3. Either way, the 512 includes them.

In sentence-transformers, CrossEncoder.predict tokenizes pairs with truncation=True style behaviour and the model's max_length. With the longest_first strategy, Hugging Face tokenizers remove tokens one at a time from whichever sequence is currently longer. Your query is 15 tokens and your passage is 700, so the passage loses its tail until the pair fits.

Two details make this nasty:

  1. It's silent. The "sequence length is longer than the specified maximum" warning only shows up when you tokenize without truncation. Rerankers truncate explicitly, so you get nothing.
  2. It's position-biased. The beginning of every chunk is always read. The end is the part that disappears. If your chunker splits on headings, the end of a chunk is often where the specific answer lives, after the setup paragraphs.

Why do my 512-token chunks overflow a 512-token reranker?

Because your chunker and your reranker are almost certainly counting with different tokenizers. Most chunking code I've seen, mine included, uses tiktoken's cl100k_base or o200k_base because that's what the LLM uses. Those vocabularies are large and pack English efficiently.

BERT's WordPiece vocabulary has about 30K entries. It splits rarer words into more pieces. Product names, version strings, URLs, code identifiers, and anything non-English get chopped up much harder.

So my chunker said "500 tokens, safe." The reranker's tokenizer said something like 600 for the same text. Then add the query and the special tokens.

The real budget for the passage is:

passage_budget = max_length - query_tokens - special_tokens = 512 - 20 - 4 = 488 (for a 20-token query on an XLM-R reranker) 

Not 512. And measured with the reranker's tokenizer, not the LLM's.

How do I check if my reranker is truncating chunks?

Tokenize every chunk with the reranker's own tokenizer, paired with a realistic query, and count how many exceed max_length. This takes a minute to run and tells you exactly how bad it is.

from transformers import AutoTokenizer MODEL = "BAAI/bge-reranker-base" MAX_LEN = 512 tok = AutoTokenizer.from_pretrained(MODEL) def overflow(query: str, passage: str) -> int: # No truncation here: we want the true length ids = tok(query, passage, add_special_tokens=True)["input_ids"] return max(0, len(ids) - MAX_LEN) query = "what is the refund window for annual plans" # use a typical-length query over = [overflow(query, c) for c in chunks] cut = [o for o in over if o > 0] print(f"{len(cut)}/{len(chunks)} chunks truncated") if cut: cut.sort() print(f"median tokens lost: {cut[len(cut)//2]}, max: {cut[-1]}") 

On my index, about a third of the chunks were getting cut, and the median loss was close to a hundred tokens. That's a paragraph of text per chunk that the reranker never saw while confidently scoring it.

Also check what max_length your scoring call is actually using. Some libraries default to 512 in the scoring function even when the underlying model supports more. Print it. Don't assume.

How do I fix cross-encoder reranker truncation?

You have three real options, and the cheapest one is usually enough.

Fix 1: Size chunks with the reranker's tokenizer

Pass the reranker's tokenizer as the length function in your splitter and set the chunk size to the passage budget minus a margin.

from langchain_text_splitters import RecursiveCharacterTextSplitter def rerank_len(text: str) -> int: return len(tok(text, add_special_tokens=False)["input_ids"]) splitter = RecursiveCharacterTextSplitter( chunk_size=440, # 512 - longest expected query - specials - margin chunk_overlap=60, length_function=rerank_len, ) 

Pick the chunk size from your longest realistic query, not your average one. A user who pastes an error log as a query will eat your margin fast.

The downside: smaller chunks mean less context per hit for the LLM. You can fix that later by expanding each reranked hit to its neighbours before generation. Rank small, read big.

Fix 2: Score overlapping windows, keep the max (MaxP)

If you can't re-chunk, split each passage into windows that fit, score every window, and use the best window's score as the passage score. This is the MaxP approach from Dai and Callan's BERT ranking work, and it maps neatly onto modern rerankers.

from sentence_transformers import CrossEncoder model = CrossEncoder(MODEL, max_length=MAX_LEN) def windows(query: str, passage: str, overlap: int = 64): q_len = len(tok(query, add_special_tokens=False)["input_ids"]) budget = MAX_LEN - q_len - 8 # specials + decode drift margin ids = tok(passage, add_special_tokens=False)["input_ids"] start = 0 while True: yield tok.decode(ids[start:start + budget]) if start + budget >= len(ids): break start += budget - overlap def maxp_score(query: str, passage: str) -> float: wins = list(windows(query, passage)) return float(model.predict([(query, w) for w in wins]).max()) 

The 8-token margin matters. Decoding token IDs back to text and re-tokenizing doesn't always round-trip to the identical count, so leave room.

The cost is more pairs per query. A 700-token chunk becomes two windows, so roughly double the reranker compute for overflowing chunks only. That was a trade I was happy to make.

Fix 3: Use a long-context reranker, and set max_length on purpose

Some newer rerankers are built for longer inputs. If you use one, set max_length explicitly and measure latency, because the default in your scoring call may still be 512.

Can I just set max_length=1024 on any reranker?

No. A model trained with 512 learned position embeddings has no embedding for position 513. Depending on the library, pushing past it either throws an index error or gets clamped back to the model's limit. Check model.config.max_position_embeddings before touching it.

Even on models that support long inputs, the cost isn't free. Going from 512 to 2048 tokens is 4x the tokens per pair, and the attention part of the compute grows with the square of length, so about 16x there. Multiply that by 50 candidates per query and your reranker becomes the slowest stage in the pipeline.

There's also a quality question. A reranker trained mostly on short MS MARCO-style passages may not score a 2,000-token passage the same way it scores a 100-token one. Long input support and long input accuracy are different claims.

What should I check first?

Run the overflow audit. If fewer than a few percent of chunks overflow, you're fine. If a meaningful share do, re-chunk with the reranker's tokenizer if you can rebuild the index, and use MaxP if you can't.

Then add the audit to CI. Chunkers change, documents get longer, someone swaps the reranker model. Truncation will come back without telling you, the same way it arrived.

Does a cross-encoder reranker read the whole chunk?

No. A cross-encoder reranker reads at most max_length tokens, usually 512, and that budget covers the query, the passage, and the special tokens together. With the default longest_first truncation, the end of a long passage is silently dropped, so an answer near the bottom of a chunk scores as if it isn't there. Measure chunk length with the reranker's own tokenizer, keep each chunk under max_length minus query and special tokens, or score overlapping windows and take the max. Raising max_length only helps on models with position embeddings for the longer length, and it costs real latency.

Written by the developer behind Preterview, an interview prep platform.

原文:https://www.a8q9.cn/en/article/cross-encoder-reranker-max-length-512-half-my-chunk-was-never-read-1cd1f1.html

相关文章