Truncate a sentence pair to a token budget with the longest-first strategy
Why it matters Rerankers, NLI and QA models in RAG pipelines truncate (query, passage) pairs on every request.
Cross-encoders and NLI models take two texts at once, such as a query and a passage. When the pair is too long, the longest-first strategy removes one token at a time from whichever side is currently longer, so neither side is wiped out.
Write truncate_pair(a, b, max_total). a and b are lists of token ids; max_total >= 0. While len(a) + len(b) > max_total, remove the LAST token of the longer list; when they have equal length, remove from a. Return (a_truncated, b_truncated) as new lists (do not modify the inputs).
def truncate_pair(a, b, max_total)Example
truncate_pair([1, 2, 3, 4, 5], [6, 7], 4) is ([1, 2], [6, 7]).
Understand the idea
Pair inputs share one length budget. Three common strategies: only_first cuts only text a, only_second cuts only text b, and longest_first removes one token at a time from whichever text is longer at that moment. Longest first keeps both texts as balanced as possible.
Worked example: a has 5 tokens, b has 2, budget 4. Total 7 > 4: a is longer, cut a to 4. Total 6: cut a to 3. Total 5: a (3) is longer than b (2), cut a to 2. Total 4 fits. Result a = [1, 2], b = [6, 7]. Cutting b first would delete b entirely and leave a = [1, 2, 3, 4].
Rule: while |a| + |b| > budget: remove the last token of the longer list (a on ties).
Cross-encoder rerankers in RAG, NLI classifiers and extractive QA use pair truncation before adding special tokens.