Continuous Semantic Chunking for RAG: A Practical Optimization Approach

    This article explains why chunking decisions directly determine whether a retrieval-augmented generation (RAG) system can recall complete evidence, and how to optimize chunk boundaries while keeping the original document order intact. It contrasts continuous chunking with fixed-length splitting, overlap windows, and semantic clustering; shows how to protect document structure before computing sentence embeddings; defines an interpretable scoring function based on pairwise sentence similarity with tunable compatibility and per-chunk penalties; and applies dynamic programming with vector prefix sums to find globally optimal boundaries in roughly O(nWd) time. It also covers length constraints, fallback strategies for oversized units, traceable metadata, and a three-layer evaluation approach spanning chunking, retrieval, and generation.

    1. Why Chunking Is the Critical Step in RAG

    Retrieval-augmented generation typically splits a document into text chunks, builds an index over them, and then, once a user asks a question, retrieves the relevant chunks and passes them to the generation model as evidence.

    The pipeline looks straightforward, but it hides an easily underestimated problem: the retrieval system does not search the original document. It searches the retrieval units created by chunking. The chunking strategy therefore affects not only storage and compute cost, but also whether the right evidence can be recalled at all.

    When chunks are too large, several topics get mixed together and the text embedding struggles to emphasize any single local piece of knowledge. When chunks are too small, conditions, conclusions, explanations, and exceptions get split apart: the retrieved result may contain the right keywords yet lack the complete information needed to answer the question.

    Consider a business rule that first states who it applies to, then describes the application requirements, and finally lists the cases where it does not apply. If the text is split mechanically by fixed length, retrieval may return only the application requirements and miss the restrictions. A generation model answering from that evidence can produce an incomplete or even misleading conclusion.

    Chunking optimization therefore cannot focus only on “how many characters per chunk.” It has to satisfy three goals at once:

    • Semantic focus: the content inside one chunk should stay close to a single topic.
    • Context completeness: the conditions, references, and explanations needed to understand a conclusion must be preserved.
    • Engineering control: chunk length, chunk count, and processing cost must be explicitly bounded.

    The core method discussed here keeps the original sentence order unchanged and requires every chunk to be continuous. It builds a scoring function from sentence embeddings and then uses dynamic programming to find the split with the highest overall score.

    2. Continuous Chunking vs. Semantic Clustering

    Fixed-length chunking, overlapping windows, and semantic clustering each solve part of the problem, but they are not suited to the same tasks.

    Fixed-length chunking is simple to implement and produces fairly stable chunk sizes, which makes it a reasonable baseline. It cannot tell, however, whether a split happens to land on a topic transition.

    Overlapping windows let neighboring chunks share some context, which reduces information loss near boundaries, but they increase index size and produce duplicate retrieval results. With a large overlap ratio, they can also consume context space that could otherwise hold more independent evidence.

    Semantic clustering tends to group similar content together. The catch is that clustering does not require positions to be continuous: the first and last sentences of a document can land in the same cluster even though they are far apart. That suits topic summarization, but it cannot directly replace continuous segmentation.

    Suppose a passage contains five sentences:

    1. Describes the morning sky and light.
    2. Continues describing the scenery under the morning light.
    3. Shifts to work arrangements and time allocation.
    4. Adds how task priorities are set.
    5. Introduces organisms in a deep-sea environment.

    A natural split is:

    1. [sentence 1, sentence 2]
    2. [sentence 3, sentence 4]
    3. [sentence 5]

    The point is not “put all similar sentences together.” It is “walk along the original order and place boundaries where they belong.”

    Formally, given a document with n sentences, we look for a set of boundaries:

    1. 0 = b₀ < b₁ < ... < bₖ = n

    Chunk r corresponds to the half-open interval [bᵣ₋₁, bᵣ). All chunks are non-overlapping, cover the document completely, and preserve the original order.

    3. Preparing the Input: Protect Structure First, Then Compute Sentence Embeddings

    3.1 Do Not Treat All Text as Ordinary Sentences

    The first step of semantic chunking is not computing vectors. It is parsing the document reliably.

    Natural language prose can be handled sentence by sentence, but code, tables, formulas, headings, and lists carry different structural constraints. Punctuation inside code does not necessarily mark the end of a sentence, and a single table row does not always express a complete meaning on its own.

    The safer approach is to recognize the document structure first:

    • Ordinary paragraphs can be further split into sentences.
    • Code blocks should in principle be preserved as complete structural units.
    • Tables can be kept whole depending on size, or split by row groups with the header repeated.
    • Headings should be linked to the body text they belong to, so a heading does not become a standalone chunk with no information.
    • Avoid unnecessary cuts between a condition and its conclusion, or between a list lead-in and its items.

    When a structural unit itself exceeds the length limit, dedicated splitting rules must be applied. Simply declaring it indivisible is not an option.

    3.2 Mapping Sentences into a Semantic Space

    Let the vector of sentence i be eᵢ. To make cosine similarity convenient, normalize each vector to unit length:

    1. êᵢ = eᵢ / ||eᵢ||

    After normalization, the cosine similarity between two sentences is just a dot product:

    1. s(i, j) = êᵢ · êⱼ

    A higher similarity usually means the two sentences are represented more closely in the vector space. It is not proof of semantic equivalence, though: negated versus affirmative statements, different facts about the same entity, and short versus long sentences can all bias the judgment.

    The embedding model used for sentence comparison should be validated against the document language, domain, and text length. The model used at chunking time may be the same as or different from the one used at retrieval time; the optimal choice for the two tasks does not have to coincide.

    In an engineering implementation, also retain each sentence’s original position, owning heading, structural type, and length. This information is used both to control boundaries and to trace evidence back to its source.

    4. Building the Objective Function: Making Chunking Preferences Explainable

    With sentence vectors in place, one question remains: how do we decide that one split is better than another?

    An interpretable starting point is to measure the overall compatibility among sentences inside the same chunk.

    For a candidate chunk [a, b) containing m sentences, define:

    1. Q(a, b) =
    2. Σ s(i, j) - τ × m(m - 1) / 2
    3. a ≤ i < j < b

    where τ is the semantic compatibility threshold.

    This expression effectively computes, for every pair of sentences in the chunk:

    1. similarity - threshold

    Pairs above the threshold contribute positively; pairs below it contribute negatively. A candidate chunk containing a lot of unrelated content is penalized.

    This score alone is not enough. A single-sentence chunk has no sentence pairs, so its internal score is zero. If most sentence pairs fall below the threshold, the system may prefer to cut the document into many single-sentence chunks.

    So add a fixed cost λ per additional chunk:

    1. Score(a, b) = Q(a, b) - λ

    The overall objective is:

    1. maximize Σ Score(bᵣ₋₁, bᵣ)

    A larger λ makes the system less willing to produce many chunks; a larger τ makes it less willing to group sentences with weak semantic relations. The two parameters must be tuned jointly, not interpreted in isolation.

    Why Not Just Maximize Average Intra-Chunk Similarity

    Average similarity looks intuitive, but it has no natural definition for a single-sentence chunk, and small chunks tend to score high. Without count and length constraints, the objective can drift toward over-splitting.

    The pairwise-sum formulation has a scale issue of its own: the number of sentence pairs grows quadratically with the number of sentences in a chunk. Long chunks can therefore accumulate large positive or negative scores, which must be paired with a maximum length and a check of the score distribution across different length ranges.

    A normalized score can also be designed, but it needs to be re-validated for problems such as “too many fragments” or “preference for long chunks.”

    How Separation Between Chunks Is Expressed

    Internal consistency does not automatically maximize the topic difference between neighboring chunks, but it already produces a clear splitting preference.

    Ignoring the length constraint, suppose one chunk is split into a left and a right part. The change in total score is:

    1. gain = - (semantic compatibility contribution between the left and right parts) - λ

    When the similarity of cross-boundary sentence pairs is generally below the threshold and the negative contribution is large enough, splitting becomes the better option.

    This mechanism encourages topic separation under the continuity constraint. It does not try to make every chunk dissimilar from every other. The same topic recurring in different parts of a document is normal and should not be forcibly removed.

    5. Finding Globally Optimal Boundaries with Dynamic Programming

    Local methods usually decide whether to split based on the similarity of two adjacent sentences, but local judgments can miss the larger context.

    Two adjacent sentences may have low similarity because of pronouns and elided expressions while still belonging to the same argument; other sentences may share terminology yet have already moved on to a new question. Dynamic programming evaluates candidate chunks as wholes and avoids greedy sentence-by-sentence decisions.

    Define:

    1. D[t] = best segmentation score for the first t sentences

    Then:

    1. D[0] = 0
    2. D[t] = max {
    3. D[a] + Score(a, t)
    4. }

    where a ranges over all starting points that form a valid final chunk [a, t).

    Also record the optimal starting point Prev[t]. Once the computation finishes, walk the predecessors backward from n to recover all chunk boundaries.

    This “global optimum” has a clear precondition: it holds only for the defined scoring function and candidate set. It does not mean the result is the best segmentation from a human point of view, and certainly not that downstream question answering will perform best.

    Adding Length Constraints

    Real systems usually need to control minimum and maximum chunk length:

    1. Lmin ≤ Length(a, t) ≤ Lmax

    Length can be computed with the same tokenization rules used in retrieval and generation, or approximated by character count in early experiments. The two are not equivalent, so the actual context budget must be verified before production deployment.

    The maximum length is usually best treated as a hard constraint. The minimum length can use a soft penalty instead, because short definitions, warnings, or leftover content at the end of a document may genuinely deserve to stand alone.

    If length statistics are precomputed per sentence, the additivity assumption behind them should be stated explicitly. For length limits that must be strictly respected, the final text of each candidate chunk still needs to be rechecked after concatenation.

    6. Avoiding Repeated Computation with Vector Prefix Sums

    Recomputing all sentence-pair similarities for every candidate chunk noticeably increases processing cost on long documents.

    For unit-length vectors:

    1. ||Σ êᵢ||² = m + 2Σ s(i, j)

    Therefore:

    1. Σ s(i, j) = (||Σ êᵢ||² - m) / 2

    Build a prefix sum over the vectors:

    1. P[0] = 0
    2. P[t] = ê₀ + ê₁ + ... + êₜ₋₁

    The vector sum of a candidate chunk is:

    1. V(a, b) = P[b] - P[a]

    The total pairwise similarity inside a chunk can then be obtained with one vector subtraction and one squared norm, with no need to store the full sentence similarity matrix.

    The pseudocode below is illustrative. Input vectors are assumed normalized, and length uses additive per-sentence length statistics:

    1. Input:
    2. vectors sequence of sentence vectors
    3. unit_lengths length of each sentence
    4. min_length target minimum chunk length
    5. max_length maximum chunk length
    6. tau semantic compatibility threshold
    7. penalty fixed cost per chunk
    8. Build vector prefix sum P
    9. Build length prefix sum T
    10. D[0] = 0
    11. All other D[t] = negative infinity
    12. Prev[t] = unset
    13. for t = 1 ... n:
    14. for a = t - 1 ... 0:
    15. length = T[t] - T[a]
    16. if length > max_length:
    17. break
    18. m = t - a
    19. v = P[t] - P[a]
    20. pair_sum = (dot(v, v) - m) / 2
    21. score = pair_sum
    22. - tau * m * (m - 1) / 2
    23. - penalty
    24. if length < min_length:
    25. score -= short_chunk_soft_penalty(length)
    26. if boundary violates structure protection rules:
    27. continue
    28. candidate = D[a] + score
    29. if candidate > D[t]:
    30. D[t] = candidate
    31. Prev[t] = a
    32. if D[n] is unreachable:
    33. run the explicit fallback procedure
    34. else:
    35. walk Prev backward from n to recover the chunks

    If each endpoint examines at most W candidate starting points and the vector dimension is d, this illustrative implementation runs in about O(nWd) time and uses about O(nd) space for the vector prefix sums. Without limiting the candidate range, the worst case still requires examining a quadratic number of intervals.

    Numerical computation involves floating-point error, particularly in vector subtraction and norm calculations, so a tiny score difference should not be interpreted as a stable semantic conclusion.

    7. Four Pieces Needed for Production

    7.1 Handling Inputs That Cannot Satisfy the Constraints

    A long sentence, a very long code block, or a large table can exceed the maximum length. Forbidding splits outright leaves the dynamic program with no solution.

    Fallback strategies should be defined per structural type: split long sentences at clause boundaries first; split code along logical segments; split tables by row groups and repeat the necessary headers. If none of that works, fall back to a controlled length-based split and record the reason.

    7.2 Separating the Core Chunk from Retrieval Display Context

    The core chunk in the index can stay semantically focused, with neighboring content added on demand after a retrieval hit. This is not the same as large-scale overlap at index time.

    For example, when a rule passage is retrieved, its heading and preceding definitions can be added. The added content must respect the context budget and must not drag in unrelated sections.

    7.3 Keeping Traceable Metadata

    Each chunk should retain the document identifier, section path, original start and end positions, version, and chunking strategy identifier. This supports accurate citation, result deduplication, content updates, and debugging.

    If headings are inherited or extra context is added, distinguish the original chunk body from the added content so citation positions do not get confused.

    7.4 Setting Strategies per Document Type

    Regulations and policies emphasize applicable conditions and exceptions; technical material emphasizes the correspondence between code and explanation; operation manuals emphasize step completeness. A single threshold and length configuration is unlikely to fit all of them.

    In practice, choose structural rules per document type first, then apply the same continuous segmentation optimization framework. Parameters should be calibrated on a real question set rather than fixed from a handful of examples.

    8. Evaluating Whether Chunking Actually Improves the System

    Chunking quality cannot be judged by eye alone, nor by average intra-chunk similarity. A high-similarity chunk may lack the key evidence needed to answer a question, while a lower-similarity chunk may be exactly the one that preserves both the condition and the conclusion.

    Evaluate on three levels.

    Chunking Level

    Check the chunk length distribution, the proportion of chunks that are too short, the proportion that are too long, structural integrity, and how boundaries near human-annotated ones look.

    These metrics surface strategy degradation, such as a flood of single-sentence chunks, headings detached from their body text, or one chunk covering too many topics.

    Retrieval Level

    On a fixed question set, observe the recall of relevant evidence, its ranking position, the proportion of duplicate results, and whether the evidence fully covers the conditions the answer requires.

    Keep the index, query processing, number of retrieved results, and ranking pipeline as consistent as possible when comparing, so that changes elsewhere are not mistaken for chunking gains.

    Generation Level

    Then check answer correctness, how well the answer is supported by evidence, citation completeness, and context consumption. Where necessary, compare under the same number of retrieved chunks and the same context budget, since different chunking strategies can produce very different chunk sizes.

    Also include test questions that easily expose boundary problems: cross-passage condition checks, exception rule lookups, short definitions under a heading, and joint interpretation of a table and the surrounding text.

    9. Summary: Turning Chunking into an Optimizable, Verifiable Engineering Problem

    The core value of continuous semantic chunking is converting the experience-based judgment of “should we cut here” into an explicit objective function and a set of constraints.

    Sentence vectors provide the basis for semantic comparison, the scoring function expresses the tradeoff between internal consistency and chunk count, and dynamic programming searches for the optimal boundaries within the allowed candidate range. Structure protection, length control, fallback mechanisms, and metadata management make the method usable on real documents.

    Two things must always be kept apart: the optimization algorithm produces the optimal split under the scoring function, while a RAG system needs the split that improves evidence recall and answer reliability. Whether the two agree has to be verified against real business questions.

    The sensible implementation path is therefore to establish a fixed-length baseline, introduce continuous semantic optimization, and tune parameters gradually through end-to-end evaluation. A good chunking strategy is not one that pursues ever finer or ever larger chunks, but one that finds an explainable, maintainable balance among topic focus, evidence completeness, and system cost.