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).

Signaturedef 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampletruncate_pair([1, 2, 3, 4, 5], [6, 7], 4)
  • Sample 2: both sides shrinktruncate_pair(list(range(10)), list(range(100, 107)), 9)
  • Test 3: already fitstruncate_pair([1], [2, 3], 5)
  • Test 4: budget zerotruncate_pair([1, 2], [3], 0)