late-chunking
БесплатноБез исполняемых скриптовНе проверенLate chunking (Jina method): embed the full document with a long-context encoder, then mean-pool token embeddings per chunk. Preserves cross-chunk context…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Late Chunking
The Problem with Naive Chunking
Traditional pipeline: split document into chunks first, embed each chunk independently. Each chunk embedding sees only its own 200-400 tokens — pronouns, anaphora, and shared terminology with earlier sections become invisible.
Document: "Acme Corp reported Q3 revenue of $42M...
The company attributed growth to...
Its subscription tier..."
Chunk 2: "The company attributed growth to..."
^^^ "the company" refers to Acme Corp — lost in isolation
A query like "Acme Corp revenue growth drivers" may match Chunk 1 but not Chunk 2, even though Chunk 2 is the one answering the question.
The Late Chunking Fix
- Run the full document through a long-context encoder (8k, 32k, or 128k tokens) in a single forward pass so every token attends to every other token.
- Record token-level embeddings and chunk token offsets.
- Mean-pool the token embeddings inside each chunk span to produce chunk vectors.
Every chunk vector now encodes the entire document's context, not just its own span.
Minimal Implementation with jina-embeddings-v3
jina-embeddings-v3 supports 8192 tokens and exposes encode_chunks for this
workflow.
from transformers import AutoModel, AutoTokenizer
import torch
import numpy as np
model_id = "jinaai/jina-embeddings-v3"
tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
model = AutoModel.from_pretrained(model_id, trust_remote_code=True).eval()
def chunk_by_sentence(text: str, max_chars: int = 400):
"""Return (chunk_text, (start_char, end_char)) tuples."""
import re
sentences = re.split(r"(?<=[.!?])\s+", text)
chunks, buf, start = [], "", 0
pos = 0
for s in sentences:
if len(buf) + len(s) > max_chars and buf:
chunks.append((buf.strip(), (start, pos)))
buf, start = s + " ", pos
else:
buf += s + " "
pos += len(s) + 1
if buf.strip():
chunks.append((buf.strip(), (start, pos)))
return chunks
def char_to_token_spans(text: str, char_spans):
enc = tok(text, return_offsets_mapping=True, add_special_tokens=True,
truncation=True, max_length=8192)
offsets = enc["offset_mapping"]
token_spans = []
for c_start, c_end in char_spans:
t_start = next((i for i, (a, b) in enumerate(offsets) if a >= c_start and b > 0), None)
t_end = next((i for i, (a, b) in enumerate(offsets) if b >= c_end and b > 0), None)
if t_start is not None and t_end is not None:
token_spans.append((t_start, t_end + 1))
return enc, token_spans
@torch.inference_mode()
def late_chunk_embed(text: str):
chunks = chunk_by_sentence(text)
chunk_texts = [c[0] for c in chunks]
char_spans = [c[1] for c in chunks]
enc, token_spans = char_to_token_spans(text, char_spans)
input_ids = torch.tensor([enc["input_ids"]])
attn = torch.tensor([enc["attention_mask"]])
out = model(input_ids=input_ids, attention_mask=attn, task_id="retrieval.passage")
token_embs = out.last_hidden_state[0] # (T, D)
vectors = []
for (ts, te) in token_spans:
pooled = token_embs[ts:te].mean(dim=0)
pooled = torch.nn.functional.normalize(pooled, dim=-1)
vectors.append(pooled.cpu().numpy())
return chunk_texts, np.vstack(vectors)
Comparison: Naive vs Late Chunking
from sentence_transformers import SentenceTransformer
naive_model = SentenceTransformer("jinaai/jina-embeddings-v3", trust_remote_code=True)
def naive_chunk_embed(text: str):
chunks = [c[0] for c in chunk_by_sentence(text)]
vecs = naive_model.encode(chunks, normalize_embeddings=True,
prompt_name="retrieval.passage")
return chunks, vecs
def cos(a, b):
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
query_model = SentenceTransformer("jinaai/jina-embeddings-v3", trust_remote_code=True)
q = query_model.encode("Acme revenue growth drivers", prompt_name="retrieval.query",
normalize_embeddings=True)
doc = open("acme_10q.txt").read()
_, naive_vecs = naive_chunk_embed(doc)
_, late_vecs = late_chunk_embed(doc)
print("naive top-1:", max(cos(q, v) for v in naive_vecs))
print("late top-1:", max(cos(q, v) for v in late_vecs))
Reported Benchmarks (Jina, 2024)
On BeIR subsets with ~8k-token documents, late chunking improves nDCG@10 by 3-8% over naive chunking using the same encoder. Biggest lift on:
- Scientific papers (SciFact, NFCorpus) — heavy cross-reference.
- Legal documents — anaphoric references to parties defined once.
- Customer support transcripts — pronoun-heavy dialogue.
No lift (or slight regression) on FAQ-like corpora where chunks are already self-contained.
Chunk Size Considerations
| Chunk size | Effect with late chunking |
|---|---|
| 64-128 tokens | Small chunks benefit MOST — naive loses most context |
| 256-512 tokens | Mod |
Установить late-chunking в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл late-chunking?
Late chunking (Jina method): embed the full document with a long-context encoder, then mean-pool token embeddings per chunk. Preserves cross-chunk context lost by traditional chunk-then-embed pipelines. USE WHEN: user mentions "late chunking", "Jina late chunking", "long-context embeddings", "cross-chunk context", "mean pool token embeddings", "jina-embeddings-v3", "token-level pooling for retrieval" DO NOT USE FOR: choosing chunk sizes - use `chunking-strategies`; picking an embedder - use `embedding-models`; fine-tuning - use `embedding-fine-tuning`
Как установить скилл late-chunking?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл late-chunking запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
от AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
от Anthropicxlsx
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
от Anthropicpptx
Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…
от Anthropic