Repository navigation
Expand file tree
/
Copy pathcheck_chunking.py
More file actions
executable file
·333 lines (300 loc) · 10.6 KB
/
Copy pathcheck_chunking.py
File metadata and controls
executable file
·333 lines (300 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#!/usr/bin/env -S uv run --script
#
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "fastembed>=0.7,<1",
# "langchain-text-splitters>=0.3,<2",
# "qdrant-client>=1.15,<2",
# ]
# ///
"""Check chunk sizes on your own documents, and see why answers are missed.
Inputs: a folder of .txt or .md files, and a CSV with the columns
question, doc (a file name in the folder), and passage (text copied from that file that answers the question).
For each chunk size and token budget, prints recall at that budget: the share of questions whose
passage is in the text sent to the model. Then it sorts the misses by cause and suggests what to try.
./check_chunking.py docs/ questions.csv --sizes 128,256,510 --budgets 1000,4000
"""
import argparse
import csv
import re
from collections import Counter
from pathlib import Path
from fastembed import TextEmbedding
from langchain_text_splitters import RecursiveCharacterTextSplitter
from qdrant_client import QdrantClient, models
from tokenizers import Tokenizer
# A passage counts as reached when this share of its characters is in the text sent to the model.
REACHED_AT = 0.8
TOP_K = 200
# Small batches keep memory low: the model's working memory grows with batch size times chunk length squared.
EMBED_BATCH = 32
# The embedding model adds two special tokens to every chunk.
SPECIAL_TOKENS = 2
# Below this share of shared words, a question is worded differently from its passage.
REWORDED_BELOW = 0.3
STOPWORDS = {
"the",
"a",
"an",
"and",
"or",
"of",
"to",
"in",
"on",
"for",
"with",
"by",
"from",
"at",
"as",
"is",
"are",
"was",
"were",
"be",
"been",
"what",
"which",
"who",
"when",
"where",
"why",
"how",
"do",
"does",
"did",
"can",
"could",
"would",
"should",
"will",
"this",
"that",
"these",
"those",
"it",
"its",
}
ADVICE = {
"reached": "",
"split": "The answer is cut by a chunk boundary. Try splitting at section headings, or a larger chunk size.",
"wrong part": "The right document was sent, but search ranked other parts of it higher than the answer. Try hybrid search or a reranker, or a larger budget.",
"reworded": "The document was not found, and the question uses different words from the passage. Dense search handles this best; keep it, and check the embedding model.",
"not found": "The document was not found, although the question shares words with the passage. Add keyword search (BM25) next to dense search, as hybrid search.",
}
def normalized(text: str) -> tuple[str, list[int]]:
"""Lowercase letters and digits only, with a map back to the original offsets."""
index = [i for i, c in enumerate(text) if c.isalnum()]
return "".join(text[i].lower() for i in index), index
def find(doc: str, passage: str) -> tuple[int, int] | None:
norm_doc, index = normalized(doc)
norm_passage = normalized(passage)[0]
start = norm_doc.find(norm_passage) if norm_passage else -1
if start < 0:
return None
return index[start], index[start + len(norm_passage) - 1] + 1
def words(text: str) -> set[str]:
return {
w
for w in re.findall(r"[a-z0-9]+", text.lower())
if len(w) > 2 and w not in STOPWORDS
}
def shared_words(question: str, passage: str) -> float:
q = words(question)
return len(q & words(passage)) / len(q) if q else 0.0
def chunk(docs: dict[str, str], size: int, count) -> list[dict]:
splitter = RecursiveCharacterTextSplitter(
chunk_size=size, chunk_overlap=0, length_function=count, add_start_index=True
)
chunks = []
for name, text in docs.items():
for part in splitter.create_documents([text]):
start = part.metadata["start_index"]
chunks.append(
{
"doc": name,
"start": start,
"end": start + len(part.page_content),
"text": part.page_content,
"tokens": count(part.page_content),
}
)
return chunks
def covered(spans: list[tuple[int, int]], passage: tuple[int, int]) -> int:
"""Characters of the passage inside the sent spans, counting each character once."""
s, e = passage
hit = [False] * (e - s)
for a, b in spans:
for i in range(max(a, s), min(b, e)):
hit[i - s] = True
return sum(hit)
def diagnose(q: dict, chunks: list[dict], ranked: list[int], budget: int) -> str:
"""Fill the budget in rank order, then say whether the passage was reached, and if not, why."""
used, spans, doc_sent = 0, [], False
for i in ranked:
c = chunks[i]
if used + c["tokens"] > budget:
break
used += c["tokens"]
if c["doc"] == q["doc"]:
doc_sent = True
spans.append((c["start"], c["end"]))
length = q["span"][1] - q["span"][0]
share = covered(spans, q["span"]) / length
if share >= REACHED_AT:
return "reached"
holding = [
c
for c in chunks
if c["doc"] == q["doc"]
and c["start"] < q["span"][1]
and c["end"] > q["span"][0]
]
if share > 0 and len(holding) > 1:
return "split"
if doc_sent:
return "wrong part"
return (
"reworded"
if shared_words(q["question"], q["passage"]) < REWORDED_BELOW
else "not found"
)
def tokens_sent(chunks: list[dict], ranked: list[int], budget: int) -> int:
used = 0
for i in ranked:
if used + chunks[i]["tokens"] > budget:
break
used += chunks[i]["tokens"]
return used
def main() -> None:
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("docs", type=Path)
parser.add_argument("questions", type=Path)
parser.add_argument(
"--sizes", default="128,256,510", help="maximum chunk sizes in tokens"
)
parser.add_argument(
"--budgets", default="1000,4000", help="tokens of retrieved text per answer"
)
parser.add_argument("--model", default="BAAI/bge-small-en-v1.5")
parser.add_argument(
"--limit",
type=int,
default=512,
help="the embedding model's input limit in tokens",
)
parser.add_argument(
"--qdrant-url", default=":memory:", help="a server URL, or :memory:"
)
args = parser.parse_args()
docs = {
p.name: p.read_text()
for p in sorted(args.docs.iterdir())
if p.suffix in {".txt", ".md"}
}
rows = list(csv.DictReader(args.questions.open()))
questions = []
for row in rows:
span = find(docs.get(row["doc"], ""), row["passage"])
if span:
questions.append({**row, "span": span})
print(
f"{len(docs)} documents, {len(questions)} of {len(rows)} passages found in their document"
)
tokenizer = Tokenizer.from_pretrained(args.model)
count = lambda text: len(tokenizer.encode(text, add_special_tokens=False).ids)
embedder = TextEmbedding(args.model)
client = (
QdrantClient(location=":memory:")
if args.qdrant_url == ":memory:"
else QdrantClient(url=args.qdrant_url)
)
query_vectors = list(embedder.query_embed([q["question"] for q in questions]))
sizes = [int(s) for s in args.sizes.split(",")]
budgets = [int(b) for b in args.budgets.split(",")]
results: dict[tuple[int, int], list[str]] = {}
tokens: dict[tuple[int, int], float] = {}
longest: dict[int, int] = {}
for size in sizes:
chunks = chunk(docs, size, count)
longest[size] = max(c["tokens"] for c in chunks) + SPECIAL_TOKENS
vectors = list(
embedder.embed([c["text"] for c in chunks], batch_size=EMBED_BATCH)
)
name = f"check_chunking_{size}"
if client.collection_exists(name):
client.delete_collection(name)
client.create_collection(
name,
vectors_config=models.VectorParams(
size=len(vectors[0]), distance=models.Distance.COSINE
),
)
client.upload_points(
name,
points=[
models.PointStruct(id=i, vector=v.tolist())
for i, v in enumerate(vectors)
],
)
ranked = [
[
int(p.id)
for p in client.query_points(name, query=v.tolist(), limit=TOP_K).points
]
for v in query_vectors
]
for budget in budgets:
results[(size, budget)] = [
diagnose(q, chunks, r, budget) for q, r in zip(questions, ranked)
]
tokens[(size, budget)] = sum(
tokens_sent(chunks, r, budget) for r in ranked
) / len(ranked)
print(
"\nRecall at each budget (share of answer passages sent to the model), and tokens sent per answer:\n"
)
print(
f"{'max size':>9} {'longest input':>14}"
+ "".join(f"{'recall @' + str(b):>14}{'tokens':>8}" for b in budgets)
)
for size in sizes:
cells = "".join(
f"{results[(size, b)].count('reached') / len(questions):>14.0%}{tokens[(size, b)]:>8.0f}"
for b in budgets
)
print(f"{size:>9} {longest[size]:>14}{cells}")
over = [s for s in sizes if longest[s] > args.limit]
if over:
print(
f"\nWarning: sizes {over} produce inputs over the model's {args.limit}-token limit; the model drops the rest of those chunks."
)
budget = budgets[0]
best = max(sizes, key=lambda s: results[(s, budget)].count("reached"))
causes = Counter(c for c in results[(best, budget)] if c != "reached")
print(
f"\nWhere to look: misses for {best}-token chunks at a {budget}-token budget ({sum(causes.values())} of {len(questions)} questions)\n"
)
for cause, n in causes.most_common():
print(f" {n:4} {cause}: {ADVICE[cause]}")
examples = [
q["question"]
for q, c in zip(questions, results[(best, budget)])
if c == cause
][:2]
for e in examples:
print(f" for example: {e[:100]}")
if len(budgets) > 1:
gained = sum(
a != "reached" and b == "reached"
for a, b in zip(results[(best, budget)], results[(best, budgets[-1])])
)
print(
f"\n {gained} of these are reached at a {budgets[-1]}-token budget, so a larger budget would recover them, at {tokens[(best, budgets[-1])] / tokens[(best, budget)]:.1f}x the tokens per answer."
)
if __name__ == "__main__":
main()