Lab 3 — วิธีตัดชิ้น
Lab walkthrough · EP10 RAG Fundamentals
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP10 RAG Fundamentals
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
ตำรา: การตัดชิ้นคือ หนึ่งในการตัดสินใจที่มีผลมากที่สุด ของระบบ RAG (§16.4) แล็บนี้เราตัดคลังเดียวกันสี่แบบ แล้ววัดด้วย hit@3 แบบ Lab 2 บนคำถาม 20 ข้อ
สิ่งที่จะได้ทำ
- ตรวจสูตรจำนวนชิ้น (สมการ 16.19) กับโค้ดของ Lab 1
- ขนาดคงที่ 512 กับ 128 token
- ตัดตามโครงสร้าง — ตัดที่หัวข้อของตำรา (§16.4.3)
- Parent-child — ค้นด้วยชิ้นเล็ก ส่งชิ้นใหญ่ (§16.4.4)
- กลับไปดูคำถามที่พลาดตั้งแต่ Lab 1
แล็บนี้ใช้แค่ embedding model และค้นด้วย dense อย่างเดียว เพื่อให้ต่างกันแค่วิธีตัดชิ้น
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §16.4 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
เหมือน Lab 1: Python 3.10+ หรือ Colab และ OPENROUTER_API_KEY (Colab: 🔑 Secrets · เครื่องตัวเอง: ไฟล์ .env) แล็บนี้ทำ embedding สี่คลัง — ค่าใช้จ่ายไม่ถึง 1 เซ็นต์ดอลลาร์ วิธีตั้งค่า key และเหตุผลที่เลือก model อยู่ใน Lab 1
%pip install -q "openai>=1.50" python-dotenv "pypdf>=6" numpy "tokenizers==0.23.3"1. ตำรา คำถาม 20 ข้อ และตัววัดผล
cell แรกคือของเดิมจาก Lab 1: client, embed, โหลดหน้า 292–374 และ n_tokens สำหรับนับ token ต่างจาก Lab 1 หนึ่งจุด: ทุกชิ้นเก็บ pages เป็นรายการ — ชิ้นที่ตัดตามหัวข้ออาจคร่อมสองหน้า
import os, re, math, urllib.request
import numpy as np
from openai import OpenAI
from pypdf import PdfReader
from tokenizers import Tokenizer
def load_key():
try: # Google Colab Secrets
from google.colab import userdata
return userdata.get("OPENROUTER_API_KEY")
except ImportError:
pass
from dotenv import load_dotenv
load_dotenv()
return os.environ["OPENROUTER_API_KEY"]
EMBED_MODEL = "qwen/qwen3-embedding-8b"
EMBED_EXTRA = {"provider": {"order": ["nebius"], "allow_fallbacks": False}}
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key(), max_retries=5)
tok = Tokenizer.from_pretrained("google/gemma-4-26b-a4b-it")
def n_tokens(text):
return len(tok.encode(text, add_special_tokens=False).ids)
def embed(texts):
vectors = []
for i in range(0, len(texts), 64):
r = client.embeddings.create(model=EMBED_MODEL, input=texts[i:i + 64], extra_body=EMBED_EXTRA)
vectors += [d.embedding for d in r.data]
V = np.array(vectors)
return V / np.linalg.norm(V, axis=1, keepdims=True)
urllib.request.urlretrieve("https://arxiv.org/pdf/2606.24937v1", "hitchhikers-guide-v1.pdf")
reader = PdfReader("hitchhikers-guide-v1.pdf")
HEADER = "H. Roitman — The Hitchhiker’s Guide to Agentic AI: From Foundations to Systems\n"
pages = [{"source": "hitchhikers-guide-v1.pdf", "page": n,
"text": reader.pages[n - 1].extract_text().replace(HEADER, "")}
for n in range(292, 375)]Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
TESTS = [
("What is PLAID?", {301}),
("What is HyDE?", {303}),
("What does FAISS stand for?", {298}),
("How can I search millions of vectors quickly?", {298}),
("Which method compares every query token with every document token?", {300}),
("How do I make keyword search understand synonyms?", {299}),
("When should I fine-tune a model instead of looking things up?", {296}),
("Which chunks should I give the model if small ones retrieve better but lack context?", {302, 303}),
("How do I combine keyword search and embedding search?", {298}),
("What analogy does the textbook use to explain RAG?", {295}),
("How does the textbook add randomness to retry waits?", {357}),
("What does FIFO mean for conversation history?", {345}),
("Where should the unchanging part of a prompt go so caching works?", {358}),
("When should a person approve an agent's action?", {355}),
("How does Graph RAG find groups of related entities?", {305}),
("Which chunking method splits where the topic changes?", {302}),
("Which frameworks are compared in Table 18.1?", {359}),
("What is the difference between episodic and semantic memory?", {321, 322}),
("What does an evaluator-optimizer workflow do?", {370, 371}),
("How does the harness notice an agent repeating the same tool call?", {357, 363}),
]
QV = embed([q for q, _ in TESTS])def evaluate(name, search_chunks, parent_of=None, parents=None):
E = embed([c["text"] for c in search_chunks])
returned = parents if parents else search_chunks
hits, context = 0, []
for (q, gold), qv in zip(TESTS, QV):
order = list(np.argsort(-(E @ qv)))
# ✏️ TODO 1 (▶ วิดีโอ 1:46): แปลงลำดับของชิ้นลูกเป็นลำดับของชิ้นแม่ โดยตัดแม่ที่ซ้ำ (รักษาลำดับ)
if parent_of:
order = ___
top3 = [returned[i] for i in order[:3]]
# ✏️ TODO 2 (▶ วิดีโอ 1:59): เป็น hit ถ้าชิ้นใดใน top3 มีหน้าที่อยู่ใน gold (ใช้ set ตัดกัน)
hits += ___
context.append(sum(n_tokens(c["text"]) for c in top3))
print(f"{name:28s} {len(search_chunks):4d} chunks · hit@3 {hits:2d}/{len(TESTS)} · "
f"context ≈ {np.mean(context):,.0f} tokens")
return Edef evaluate(name, search_chunks, parent_of=None, parents=None):
E = embed([c["text"] for c in search_chunks])
returned = parents if parents else search_chunks
hits, context = 0, []
for (q, gold), qv in zip(TESTS, QV):
order = list(np.argsort(-(E @ qv)))
if parent_of:
order = list(dict.fromkeys(parent_of[i] for i in order))
top3 = [returned[i] for i in order[:3]]
hits += any(set(c["pages"]) & gold for c in top3)
context.append(sum(n_tokens(c["text"]) for c in top3))
print(f"{name:28s} {len(search_chunks):4d} chunks · hit@3 {hits:2d}/{len(TESTS)} · "
f"context ≈ {np.mean(context):,.0f} tokens")
return E2. ขนาดคงที่ + สูตรจำนวนชิ้น
\[N_{\text{chunks}}=\left\lceil\frac{L-O}{W-O}\right\rceil\qquad(16.19)\]
chunk_page ของ Lab 1 — เพิ่มให้คืน pages เป็นรายการ
def chunk_page(page, W=512, O=64):
ids = tok.encode(page["text"], add_special_tokens=False).ids
return [{"source": page["source"], "pages": [page["page"]],
"text": tok.decode(ids[start:start + W])}
for start in range(0, max(len(ids) - O, 1), W - O)]
# ✏️ TODO 3 (▶ วิดีโอ 2:26): จำนวนชิ้นตามสมการ 16.19: ceil((L − O) / (W − O))
def expected_chunks(L, W, O):
return ___
for p in pages[:5]:
L = n_tokens(p["text"])
print(p["page"], "L =", L, "· formula:", expected_chunks(L, 512, 64), "· ours:", len(chunk_page(p)))def chunk_page(page, W=512, O=64):
ids = tok.encode(page["text"], add_special_tokens=False).ids
return [{"source": page["source"], "pages": [page["page"]],
"text": tok.decode(ids[start:start + W])}
for start in range(0, max(len(ids) - O, 1), W - O)]
def expected_chunks(L, W, O):
return math.ceil((L - O) / (W - O))
for p in pages[:5]:
L = n_tokens(p["text"])
print(p["page"], "L =", L, "· formula:", expected_chunks(L, 512, 64), "· ours:", len(chunk_page(p)))292 L = 598 · formula: 2 · ours: 2
293 L = 763 · formula: 2 · ours: 2
294 L = 240 · formula: 1 · ours: 1
295 L = 471 · formula: 1 · ours: 1
296 L = 454 · formula: 1 · ours: 1
fixed512 = [c for p in pages for c in chunk_page(p)]
E_fixed512 = evaluate("fixed 512 / overlap 64", fixed512)fixed 512 / overlap 64 141 chunks · hit@3 12/20 · context ≈ 1,055 tokens
fixed128 = [c for p in pages for c in chunk_page(p, W=128, O=16)]
E_fixed128 = evaluate("fixed 128 / overlap 16", fixed128)
print(repr(fixed128[12]["text"]))fixed 128 / overlap 16 431 chunks · hit@3 14/20 · context ≈ 339 tokens
' with relevant knowledge before each reasoning step, while Memory\nprovides continuity across steps and sessions.\n• The Orchestration Harness coordinates everything: it decides when to retrieve, when to call\ntools, when to delegate to sub-agents, and when to ask the human for guidance.\n• MCP provides the standardized interface through which the agent accesses all external tools,\nand A2A provides the equivalent interface for inter-agent communication.\n293'
3. ตัดตามโครงสร้าง (§16.4.3)
ตำราแบ่งด้วยหัวข้อ Chapter 16, 16.4.1 Fixed-Size … — เราเริ่มชิ้นใหม่ ทุกครั้งที่เจอหัวข้อ และเมื่อชิ้นจะยาวเกิน 512 token · ตัดทีละบรรทัด ไม่ตัดกลางบรรทัด · ชิ้นหนึ่งอาจคร่อมสองหน้า
HEADING = re.compile(r"^(Chapter \d+|\d+\.\d+(\.\d+)?\s+[A-Z].{2,90})$")
def lines_of(pages):
for p in pages:
lines = p["text"].split("\n")
if lines[-1].strip().isdigit(): # the page number at the bottom
lines = lines[:-1]
for line in lines:
yield line, p["page"]
# ✏️ TODO 4 (▶ วิดีโอ 4:18): เริ่มชิ้นใหม่เมื่อยังไม่มีชิ้น, บรรทัดนี้เป็นหัวข้อ, หรือเพิ่มแล้วจะเกิน max_tokens
def structure_chunks(pages, max_tokens=512):
chunks, cur = [], None
for line, page in lines_of(pages):
n = n_tokens(line)
if ___:
if cur:
chunks.append(cur)
cur = {"source": "hitchhikers-guide-v1.pdf", "pages": [], "lines": [], "tokens": 0}
cur["lines"].append(line)
cur["pages"].append(page)
cur["tokens"] += n
chunks.append(cur)
for c in chunks:
c["text"] = "\n".join(c.pop("lines"))
c["pages"] = sorted(set(c["pages"]))
return chunksHEADING = re.compile(r"^(Chapter \d+|\d+\.\d+(\.\d+)?\s+[A-Z].{2,90})$")
def lines_of(pages):
for p in pages:
lines = p["text"].split("\n")
if lines[-1].strip().isdigit(): # the page number at the bottom
lines = lines[:-1]
for line in lines:
yield line, p["page"]
def structure_chunks(pages, max_tokens=512):
chunks, cur = [], None
for line, page in lines_of(pages):
n = n_tokens(line)
if cur is None or HEADING.match(line.strip()) or cur["tokens"] + n > max_tokens:
if cur:
chunks.append(cur)
cur = {"source": "hitchhikers-guide-v1.pdf", "pages": [], "lines": [], "tokens": 0}
cur["lines"].append(line)
cur["pages"].append(page)
cur["tokens"] += n
chunks.append(cur)
for c in chunks:
c["text"] = "\n".join(c.pop("lines"))
c["pages"] = sorted(set(c["pages"]))
return chunkssections = structure_chunks(pages)
print(len(sections), "chunks")
for c in sections[3:7]:
print(c["pages"], c["tokens"], "tokens ·", c["text"].split("\n")[0])
E_sections = evaluate("structure (≤ 512)", sections)184 chunks
[295] 94 tokens · Chapter 16
[295] 118 tokens · 16.1 Motivation and Problem Statement
[295] 223 tokens · 16.1.1 Parametric vs. Non-Parametric Knowledge
[296] 172 tokens · 16.1.2 When to Use RAG vs. Fine-Tuning vs. Long Context
structure (≤ 512) 184 chunks · hit@3 16/20 · context ≈ 436 tokens
4. Parent-child (§16.4.4)
ลูก = ชิ้นละ 128 token (ซ้อน 16) ตัดจากแต่ละ แม่ = ชิ้นตามหัวข้อของส่วนที่ 3 ค้นด้วยลูก (แม่น) → ส่งแม่ให้ model (บริบทครบ)
# ✏️ TODO 5 (▶ วิดีโอ 5:29): ทุกลูกได้ pages ของแม่ และจด index ของแม่ไว้ใน parent_of
children, parent_of = [], []
for pi, parent in enumerate(sections):
for child in chunk_page({"source": parent["source"], "page": 0, "text": parent["text"]}, W=128, O=16):
child["pages"] = ___
children.append(child)
parent_of.append(___)
E_child = evaluate("parent-child (128 → section)", children, parent_of, sections)children, parent_of = [], []
for pi, parent in enumerate(sections):
for child in chunk_page({"source": parent["source"], "page": 0, "text": parent["text"]}, W=128, O=16):
child["pages"] = parent["pages"]
children.append(child)
parent_of.append(pi)
E_child = evaluate("parent-child (128 → section)", children, parent_of, sections)parent-child (128 → section) 461 chunks · hit@3 17/20 · context ≈ 740 tokens
5. คำถามที่พลาดตั้งแต่ Lab 1
ใช้วิธีที่ดีที่สุดของเรา (parent-child) — หัวข้อที่มี “library card” ขึ้นมาอันดับเท่าไร
question = ("In Roitman's book The Hitchhiker's Guide to Agentic AI, "
"what analogy does the RAG chapter use to explain RAG?")
order = list(dict.fromkeys(parent_of[i] for i in np.argsort(-(E_child @ embed([question])[0]))))
print("library card section at rank", [r for r, pi in enumerate(order, 1) if "library card" in sections[pi]["text"]])library card section at rank [17]
สรุป
| วิธีตัดชิ้น | ชิ้น | hit@3 (20 ข้อ) | context ต่อคำถาม |
|---|---|---|---|
| ขนาดคงที่ 512 / ซ้อน 64 (Lab 1) | 141 | 12 | ≈ 1,050 token |
| ขนาดคงที่ 128 / ซ้อน 16 | 431 | 14 | ≈ 340 token — แต่ชิ้นเริ่มกลางประโยค |
| ตัดตามหัวข้อ (≤ 512) | 184 | 16 | ≈ 440 token |
| parent-child (ลูก 128 → แม่ = หัวข้อ) | 461 ลูก | 17 | ≈ 740 token |
- สมการ 16.19 ตรงกับจำนวนชิ้นของเราทุกหน้า
- คำถามยาวจาก Lab 1: หัวข้อ “library card” อยู่อันดับ 17 — ไม่มีวิธีตัดชิ้นไหนช่วย → แปลงคำถามก่อนค้น (EP11)
แบบฝึกหัด
- ลอง
chunk_page(p, W=512, O=0)(ไม่ซ้อน) — บนคำถาม 20 ข้อของเรา ไม่ซ้อนได้ มากกว่า ซ้อน! ลองหาว่าข้อไหนต่างกัน และคิดว่าทำไม (overlap ช่วยเมื่อประโยคสำคัญถูกตัดที่รอยต่อ — คำถามของเรามีกรณีนั้นไหม) - ใช้ hybrid จาก Lab 2 แทน dense กับชิ้นตามหัวข้อ — hit@3 เป็นเท่าไร
- ลอง
structure_chunks(pages, max_tokens=256)
ถัดไป — Lab 4: สร้าง RAG ตัวเดิมด้วย LangChain แล้วเทียบกับโค้ดที่เราเขียนเองทีละชิ้น