Search Tutorials
--Ads--Late Chunking and Contextual Chunk Headers
Keep document-level context inside each chunk so it can be found on its own.
Chunking has a hidden cost: it cuts each passage away from the rest of its document. A chunk that says "The limit was raised to 50,000 in 2025" is useless on its own if the reader does not know which limit, in which product, of which company. This lesson covers two techniques that put document-level context back into each chunk: contextual chunk headers, which are simple and cheap, and late chunking, which is an embedding-level technique.
The lost-context problem
Consider a quarterly report for "Acme Corp" split into chunks. One chunk reads:
Revenue grew by 3% over the previous quarter, driven by the new subscription tier.
A user asks: "What was Acme's revenue growth in Q2 2026?" The chunk mentions neither Acme nor Q2 2026, so its embedding may not be close to the question, and if several companies' reports are indexed, the LLM cannot tell which company the chunk describes.
Technique 1: Contextual chunk headers
Prepend a short header with document-level information to every chunk before embedding it: the document title, the section path, and other key metadata such as company, product or date.
def with_header(chunk: str, meta: dict) -> str:
parts = [meta.get("title"), meta.get("section"), meta.get("date")]
header = " | ".join(p for p in parts if p)
return f"[{header}]\n{chunk}" if header else chunk
chunk = "Revenue grew by 3% over the previous quarter, driven by the new subscription tier."
meta = {"title": "Acme Corp Quarterly Report", "section": "Financial results", "date": "Q2 2026"}
print(with_header(chunk, meta))
[Acme Corp Quarterly Report | Financial results | Q2 2026]
Revenue grew by 3% over the previous quarter, driven by the new subscription tier.
Embed and index the text with the header, and also show the header to the LLM, so that it knows where each chunk comes from. This costs almost nothing and is one of the highest-value changes you can make to a basic RAG pipeline. The structure-aware splitter in the earlier lesson already does this with heading paths.
A more powerful version asks an LLM to write a sentence of context for each chunk. That technique, called contextual retrieval, is covered in Module 6: Contextual Retrieval.
Technique 2: Late chunking
In normal ("early") chunking, the text is split first and each chunk is embedded separately, so each chunk's embedding sees only that chunk. Late chunking, proposed by Jina AI in 2024, reverses the order:
- Run the whole document (up to the model's context limit, such as 8,192 tokens) through a long-context embedding model, and keep the embedding of every token. Because the transformer's attention sees the whole document, each token embedding already contains information from the surrounding text.
- Decide the chunk boundaries as usual.
- For each chunk, average (mean-pool) the token embeddings that fall inside it.
The result is one vector per chunk, but each vector is "aware" of the rest of the document. The pronoun "it" in a chunk is embedded knowing what "it" refers to.
pip install sentence-transformers einops
import numpy as np
from sentence_transformers import SentenceTransformer
# A long-context embedding model that can return per-token embeddings (8,192 tokens)
model = SentenceTransformer("jinaai/jina-embeddings-v2-small-en", trust_remote_code=True)
model.max_seq_length = 8192
def late_chunk_embeddings(text: str, chunks: list[str]) -> np.ndarray:
"""Embed `chunks` (substrings of `text`, in order) with whole-document context."""
# 1. Character span of each chunk inside the full text
spans, pos = [], 0
for chunk in chunks:
start = text.index(chunk, pos)
spans.append((start, start + len(chunk)))
pos = start + len(chunk)
# 2. Token embeddings for the whole document, plus each token's character offsets
encoded = model.tokenizer(text, return_offsets_mapping=True, truncation=True, max_length=8192)
offsets = encoded["offset_mapping"]
token_vectors = model.encode(text, output_value="token_embeddings")
token_vectors = token_vectors.cpu().numpy() if hasattr(token_vectors, "cpu") else np.asarray(token_vectors)
# 3. Mean-pool the token vectors inside each chunk's span
vectors = []
for start, end in spans:
idx = [i for i, (s, e) in enumerate(offsets) if e > s and s >= start and e <= end]
v = token_vectors[idx].mean(axis=0) if idx else np.zeros(token_vectors.shape[1])
vectors.append(v / (np.linalg.norm(v) or 1.0))
return np.vstack(vectors)
text = ("Acme Corp published its Q2 2026 report. "
"Revenue grew by 3% over the previous quarter. "
"The company also opened two new offices in Pune.")
chunks = ["Acme Corp published its Q2 2026 report.",
"Revenue grew by 3% over the previous quarter.",
"The company also opened two new offices in Pune."]
vectors = late_chunk_embeddings(text, chunks)
query = model.encode("Acme revenue growth", normalize_embeddings=True)
print(vectors @ query)
Queries are embedded normally. Only the document side changes.
- It needs an embedding model that exposes token embeddings and supports long inputs; most hosted embedding APIs do not.
- Documents longer than the model's context window must be processed in large overlapping windows.
- The improvement is largest for documents full of references back to earlier text, and small for self-contained chunks.
Which one should you use?
| Technique | Cost | Works with any embedding model | Recommendation |
|---|---|---|---|
| Contextual chunk headers | Free | Yes | Always do this |
| Contextual retrieval (LLM-written context) | One LLM call per chunk at indexing time | Yes | Best quality for important collections |
| Late chunking | One long embedding pass per document | No | When you run your own long-context embedding model |
Key takeaways
- Chunks lose the context of their document; this hurts both retrieval and generation.
- Contextual headers (title, section, date) are free and should be added to every chunk.
- Late chunking embeds the whole document first and pools token vectors per chunk, so every chunk vector carries document context.
- For the highest quality, combine headers with LLM-written context (contextual retrieval).