AI Hints
Home›RAG Tutorial›Judging Answers
RAG · Lesson 78 of 120

Comparing Settings

A chunk size experiment.

⏱ 2 min read▶ Video at 1:16:46🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Now we can run a real experiment. Which chunk size works best for Northwind? We'll build three indexes, and measure hit rate on the test set for each.

Comparing Settings
From the video: Comparing Settings
  • A real experiment
  • Three chunk sizes
  • Measure each

Three chunk sizes

Hit rate counts the questions whose fact is in the top three chunks. We build an index with chunks of one hundred and fifty, three hundred, and six hundred characters. Run it. Three hundred, our default, scores lowest here. Six hundred scores highest.

experiment.pypython
import json
from rag_kit import load_docs, make_chunks, Index

tests = json.load(open("eval_set.json"))
docs = load_docs()

def hit_rate(index, k=3):
    return sum(any(t["fact"] in c["text"] for s, c in index.search(t["question"], k))
               for t in tests) / len(tests)

for size in [150, 300, 600]:
    index = Index(make_chunks(docs, size=size, overlap=size // 6))
    print(f"chunk size {size}: hit rate {hit_rate(index):.0%}")
Output
chunk size 150: hit rate 80%
chunk size 300: hit rate 60%
chunk size 600: hit rate 90%
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses eval_set.json
[
 {"question": "What does E03 mean?", "source": "ebike_errors.md", "fact": "speed sensor"},
 {"question": "What is the APR?", "source": "finance.md", "fact": "9.9"},
 {"question": "Can I spread the payments?", "source": "finance.md", "fact": "spread the cost"},
 {"question": "How many hours until my e-bike is full again?", "source": "ebike_battery.md", "fact": "4 hours"},
 {"question": "How long until my money comes back?", "source": "returns.md", "fact": "7 working days"},
 {"question": "Can I get next-day delivery on a bike?", "source": "shipping.md", "fact": "Next-day"},
 {"question": "How much is a rental deposit?", "source": "rentals.md", "fact": "£150"},
 {"question": "When is the York shop open?", "source": "stores.md", "fact": "5:30pm"},
 {"question": "How much is a Basic service?", "source": "servicing.md", "fact": "£49"},
 {"question": "Do you deliver bikes to France?", "source": "shipping.md", "fact": "complete bikes"}
]

Careful conclusions

Bigger chunks find more facts, but cost more tokens per question. Ten questions is a small test, so one question changes the score by ten percent. Grow the test set before trusting small differences.

keyvalue
Bigger chunksmore hits, more tokens
Small test setnoisy scores
One question= 10%
Before decidingadd questions

Summary

Change one setting at a time, and compare scores on the same test set. Next, reading the failures.

Key takeaways
  • One setting
  • Same test set
  • Compare
Next up: Error Analysis — read the failures