AI Wiki中文/EN

Chunking: where did the rest of the evidence go?

文档切分

Track source spans, compare overlap with sentence boundaries, and measure coverage under a budget.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The answer is present, but no result contains it

“The Orion exhibit opens on Tuesday at noon.” Split that sentence after “on” and neither piece contains the exhibit name together with its opening day. A search system can index every word and still fail to retrieve a usable piece of evidence.

Chunking chooses the units that are indexed or supplied as context. Those units need not be identical. You can retrieve a sentence and then supply its surrounding paragraph, provided the larger context retains the correct source and fits the budget. DPR used fixed passages in its retrieval corpus; Dense X Retrieval studies passages, sentences and self-contained propositions as different retrieval units. Neither observation establishes one universally best chunk size. DPR Dense X, physical PDF 3

Begin with headings, paragraphs or sentences when documents already have useful structure. A learned semantic splitter adds a model and a new failure mode; justify it against those inexpensive baselines. An isolated sentence may still contain “it,” an omitted table header or a condition introduced in the preceding paragraph.

Full-index evidence coverage can fall after redundant chunks consume the context budget.
Full-index evidence coverage can fall after redundant chunks consume the context budget.

A boundary is also a claim about context

Represent each extractive chunk with a half-open character interval in the original document:

cj=(docID,aj,bj),text⁡(cj)=D[aj:bj].c_j=(\mathrm{docID},a_j,b_j),\qquad \operatorname{text}(c_j)=D[a_j:b_j].

Keep a source version as well: offsets into a revised document can point to different text. Character positions are not byte positions, and neither measures the tokens consumed by a language model.

For a token sequence of length N, fixed windows of length L and overlap O advance by a stride:

s=L−O,0≤O<L.s=L-O,\qquad 0\le O<L.

The number of windows, stopping as soon as the last one reaches the end, is:

M={0N=0,1+⌈max⁡(0,N−L)L−O⌉N>0.M=\begin{cases}0&N=0,\\1+\left\lceil\dfrac{\max(0,N-L)}{L-O}\right\rceil&N>0.\end{cases}

Overlap reduces some boundary failures but stores repeated text. It can also make retrieval return several almost identical hits. Let annotated evidence intervals be a finite set A. A deliberately strict diagnostic counts an interval as covered only when one retrieved chunk contains it whole:

Coverage⁡(C,A)=1∣A∣∑(u,v)∈A1[∃c∈C:ac≤u∧bc≥v].\operatorname{Coverage}(C,A)=\frac{1}{|A|}\sum_{(u,v)\in A}\mathbf1[\exists c\in C:a_c\le u\land b_c\ge v].

This measures containment of those annotations, not semantic answerability. A reader able to combine adjacent pieces might recover evidence that this metric marks missing. Conversely, containing one answer span may omit a condition needed to interpret it.

The generator sees only a selected subset S with context budget B:

∑c∈Stokens⁡(c)≤B.\sum_{c\in S}\operatorname{tokens}(c)\le B.

Real budgeting must include instructions, the question, separators and reserved output. Our program budgets only source chunks, measured by whitespace-separated units; this is explicitly not a BPE token counter.

Count evidence before and after packing

The following Python 3.12 standard-library program uses two invented museum sentences, 16 whitespace units in total. It compares nonoverlapping length-5 windows, length-5 windows with overlap 4, and punctuation-based sentences. Original offsets let every displayed extract be checked against its source. The sentence rule is intentionally simple: abbreviations and complex punctuation need a better parser.

"""Original character-preserving chunks; whitespace tokens, not model tokens."""
import json
import re

TEXT = 'The Orion exhibit opens on Tuesday at noon. The Lyra exhibit opens on Friday at dusk.'


def spans(text):
    return [(m.start(), m.end()) for m in re.finditer(r'\S+', text)]


def fixed(text, size, overlap=0):
    if not isinstance(size, int) or not isinstance(overlap, int) or not 0 <= overlap < size:
        raise ValueError('require 0 <= overlap < positive integer size')
    tokens = spans(text); result = []
    for start in range(0, len(tokens), size-overlap):
        end = min(start+size, len(tokens))
        a, b = tokens[start][0], tokens[end-1][1]
        result.append(dict(start=a, end=b, text=text[a:b], tokens=end-start))
        if end == len(tokens):
            break
    return result


def sentences(text):
    result = []
    for match in re.finditer(r'[^.!?]+[.!?]?', text):
        raw = match.group(); a = match.start()+len(raw)-len(raw.lstrip()); b = match.end()
        if a < b:
            result.append(dict(start=a, end=b, text=text[a:b], tokens=len(spans(text[a:b]))))
    return result


def evidence_coverage(chunks, intervals):
    return sum(any(c['start'] <= a and c['end'] >= b for c in chunks) for a, b in intervals)/len(intervals) if intervals else None


def packed(chunks, budget):
    if not isinstance(budget, int) or budget < 0:
        raise ValueError('nonnegative integer budget')
    result = []; cost = 0; seen = set()
    for c in chunks:
        key = (c['start'], c['end'])
        if key in seen:
            continue
        seen.add(key)
        if cost+c['tokens'] <= budget:
            result.append(c); cost += c['tokens']
    return result, cost


def parents(children, original):
    # Return whole sentences intersecting a hit, preserving exact source offsets.
    return [p for p in sentences(original) if any(c['start'] < p['end'] and p['start'] < c['end'] for c in children)]


def demo():
    labels = ['Orion exhibit opens on Tuesday', 'Lyra exhibit opens on Friday']
    evidence = [(TEXT.index(s), TEXT.index(s)+len(s)) for s in labels]
    methods = [fixed(TEXT, 5), fixed(TEXT, 5, 4), sentences(TEXT)]
    names = ['fixed', 'overlap', 'sentences']
    rows = []
    for name, cs in zip(names, methods):
        chosen, cost = packed(cs, 16)
        rows.append(dict(name=name, chunks=len(cs), stored_tokens=sum(c['tokens'] for c in cs),
                         coverage=evidence_coverage(cs, evidence), budget_coverage=evidence_coverage(chosen, evidence), used_tokens=cost))
    hit = fixed(TEXT, 5)[1]
    return dict(text=TEXT, evidence=evidence, methods=rows, parent_spans=parents([hit], TEXT), original_tokens=len(spans(TEXT)))


if __name__ == '__main__':
    print(json.dumps(demo(), allow_nan=False))

There are 4 fixed chunks, 12 overlapping chunks and 2 sentence chunks. They store 16, 60 and 16 units respectively. The two annotated name-to-day spans have full-index coverage 0, 1 and 1. Under a budget of 16 units, the greedy packer yields coverage 0, 0.5 and 1: repeated early windows crowd out the second exhibit. The packer follows source order here, so this is a packing counterexample, not a comparison of trained retrievers.

The hit crossing the sentence boundary expands to both parent sentences. Parent recovery can restore context, but it also raises cost. packed removes exact duplicate intervals; it does not merge partly overlapping intervals. Change that policy and recompute the scores instead of carrying over these numbers.

Building token spans costs O(N) in the number of characters scanned. Materializing chunk strings additionally costs the total copied text length; large overlap can multiply it. The simple coverage checker compares every annotation against every chunk. These small routines prioritize traceability over indexing throughput.

Smaller is not automatically more precise

Dense X defines a proposition as a minimal distinct meaning with enough resolved context to stand on its own, and constructs propositions using a distilled generator. That is more than sentence splitting. Rewriting “it” into an entity name can help retrieval, but generated text needs an explicit link back to the original evidence. Dense X

Tune chunking on development questions; keep evaluation questions separate. Check tables, lists, code, multilingual text, long sentences and repeated headers. Measure retrieval quality and downstream answers under the same context budget. If a comparison lets one method supply much more text, it has changed two variables at once.

For exact document-ID requests, bypass chunk retrieval. For missing or contradictory evidence, preserve uncertainty instead of asking a larger window to manufacture an answer. Chunking controls what information is available, not whether the source is correct.

Move the boundary

  1. Explain. Why can an index contain every word yet fail strict evidence coverage? Answer: An annotated interval may cross a boundary so that no single retrieved chunk contains the required relation. Word presence and contiguous evidence containment are different conditions.
  2. Calculate. With N=16, L=5 and O=4, how many chunks and stored units result here? Answer: The stride is 1 and the formula gives 12 windows. All are length 5, so they store 60 units, despite only 16 units in the original.
  3. Modify. What happens if sentence chunks receive a budget of 7? Answer: Each sentence has 8 units, so the current whole-chunk packer includes neither. A policy that truncates chunks would be a different algorithm and could again split evidence.
  4. Investigate. How would you compare sentence and proposition retrieval? Answer: Preserve source mappings, use the same retrieval model and held-out questions, and control the final model-token budget. Audit rewritten propositions for lost conditions or invented context; report extraction cost separately.

Retrieval granularity is an experimental choice

Read DPR for passage retrieval and Dense X for a direct comparison of retrieval-unit choices. Their trained models and corpora are not reproduced by the two-sentence fixture. Continue with vector databases for persistence and versioning, and RAG evaluation for the difference between finding context and answering correctly.

Make a prediction, then check

Does complete coverage in the index guarantee complete coverage in a fixed context budget?

Choose one answer

Learning objectives

  • Choose retrieval units separately from the context units supplied to a reader.
  • Run the original example, explain its counterexample and identify the untested deployment assumptions.

Prerequisites & connections

Explore related knowledge →

References

  1. Dense X Retrieval: What Retrieval Granularity Should We Use? — arXiv v1
    Tong Chen; Hongwei Wang; Sihao Chen; Wenhao Yu; Kaixin Ma; Xinran Zhao; Dong Yu; Hongming Zhang · 2023
  2. Dense Passage Retrieval for Open-Domain Question Answering — arXiv v1
    Vladimir Karpukhin; Barlas Oğuz; Sewon Min; Ledell Wu; Sergey Edunov; Danqi Chen; Wen-tau Yih · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author. Recorded source scopes (some exact source objects reused from earlier checks): Read PDF 1 identity and 3: self-contained propositions, passage/sentence/proposition units, distillation construction; no reported accuracy reproduced. Viewed physical PDF3–4: independent encoders, dot product, loss and negatives. Read PDF5 hybrid-score paragraph; v1 author list differs from final proceedings. 5 paired equations and four explained exercises. Checked original character spans, full and budgeted containment, overlap storage, duplicates, parent recovery and whitespace-token limits.

  • Checked original character spans, full and budgeted containment, overlap storage, duplicates, parent recovery and whitespace-token limits.
  • Four computed SVG variants per topic;12 numeric/geometry tests and42 responsive cases passed. Fourteen selected final captures directly viewed. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.