Day 7: Measuring Retrieval Quality – the Test Bench
Goal: Create test questions with expected sources, build a test bench as a job, measure hits@k and MRR – and use them to compare card size, overlap and heading instead of guessing · Duration: approx. 100 min · Prerequisite: Day 6
State before this chapter
# on rag1
curl -s http://127.0.0.1:6333/collections/wissen -o info.json# on rag1
jq '.result.points_count' info.jsonExpected:
173
# on rag1
kubectl -n rag get pod curlExpected: 1/1 Running. If it says
Completed, recreate the pod as on Day 6, Drill 6, Step
1.
Introduction
Yesterday the question about the pods that go first when memory runs short brought the wrong cards. What now? Larger cards? Smaller ones? More overlap? A different model? Each of these ideas sounds reasonable – and each can make the hits worse without anyone noticing, because after a change people try one or two questions and are satisfied.
Today you build a test bench: a fixed set of test questions for which you know where the answer is, and a program that counts the position at which the right card lands. With it you compare four variants of the pipeline. One of them refutes an assumption from Day 6.
Today you learn:
- to formulate test questions with expected sources – and why they contain judgements,
- to calculate and read hits@k and MRR,
- to run a test bench as a job next to the pipeline,
- to build in card size, overlap and context as switches and compare them,
- how little 13 questions carry statistically.
Background
The picture for today: the library management’s spot check
The library management wants to know whether the librarian is doing a good job. It does not ask “How is it going?”, but draws up a list of test questions for which it knows the right card. Then it asks every question and notes whether the right card is brought first, among the first three or not at all. When the card cabinet is rearranged, it asks the same questions again. Only this way does it see whether the rearrangement helped.
The terms
| Term | Meaning | in the picture |
|---|---|---|
| Test question | question with a known correct source | the management’s test question |
| Gold standard | the list of expected sources | answer sheet |
| hits@k | share of questions with a correct card among the first k | “brought among the first three” |
| MRR | mean of 1/position of the first correct card (0 if none) | points: position 1 = 1, position 2 = ½, position 3 = ⅓ |
| Variant | the same pipeline with one switch changed | rearranged cabinet |
| Sample | the test questions are only a small slice of all questions | one list, not all readers |
Remember: A change to the pipeline is only an improvement when the same test questions do better afterwards.
Drill 1: The test questions
Where you are: on rag1.
What you have afterwards:
testfragen.jsonwith 13 questions and the sections that contain the answers.
Step 1 – the folder.
# on rag1
mkdir -p ~/kurs/07# on rag1
cd ~/kurs/07Step 2 – the questions. Every question gets an identifier, the text and a list of permitted places made of source and section. If more than one section counts as correct, all of them are in the list:
# on rag1
nano testfragen.json[
{"id": "f01", "frage": "Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?",
"erwartet": [{"quelle": "k8s-pod-qos.md", "abschnitt": "Quality of Service classes"}]},
{"id": "f02", "frage": "Wie groß darf ein Secret höchstens sein?",
"erwartet": [{"quelle": "k8s-secret.md", "abschnitt": "Size limit"}]},
{"id": "f03", "frage": "Wird eine als Volume eingehängte ConfigMap automatisch aktualisiert?",
"erwartet": [{"quelle": "k8s-configmap.md", "abschnitt": "Mounted ConfigMaps are updated automatically"}]},
{"id": "f04", "frage": "Wie verhindere ich, dass eine ConfigMap versehentlich geändert wird?",
"erwartet": [{"quelle": "k8s-configmap.md", "abschnitt": "Immutable ConfigMaps"}]},
{"id": "f05", "frage": "Was muss ein Pod erfüllen, damit er die QoS-Klasse Guaranteed bekommt?",
"erwartet": [{"quelle": "k8s-pod-qos.md", "abschnitt": "Guaranteed"}, {"quelle": "k8s-pod-qos.md", "abschnitt": "Criteria"}]},
{"id": "f06", "frage": "Wozu dient eine Startup-Probe?",
"erwartet": [{"quelle": "k8s-pod-lifecycle.md", "abschnitt": "Startup probe"}]},
{"id": "f07", "frage": "Wie lange wartet Kubernetes beim Beenden eines Pods, bevor es die Container hart beendet?",
"erwartet": [{"quelle": "k8s-pod-lifecycle.md", "abschnitt": "Termination of Pods"}]},
{"id": "f08", "frage": "Welche Phasen kann ein Pod haben?",
"erwartet": [{"quelle": "k8s-pod-lifecycle.md", "abschnitt": "Pod phase"}]},
{"id": "f09", "frage": "Wie halte ich Pods von einem bestimmten Node fern?",
"erwartet": [{"quelle": "k8s-taint-and-toleration.md", "abschnitt": "Concepts"}, {"quelle": "k8s-taint-and-toleration.md", "abschnitt": "Taints and Tolerations"}]},
{"id": "f10", "frage": "Was passiert mit den Pods, wenn ein Node nicht mehr erreichbar ist?",
"erwartet": [{"quelle": "k8s-taint-and-toleration.md", "abschnitt": "Taint based Evictions"}]},
{"id": "f11", "frage": "Wie hinterlege ich Zugangsdaten für eine private Container-Registry?",
"erwartet": [{"quelle": "k8s-secret.md", "abschnitt": "Docker config Secrets"}, {"quelle": "k8s-secret.md", "abschnitt": "Container image pull Secrets"}, {"quelle": "k8s-secret.md", "abschnitt": "Using imagePullSecrets"}]},
{"id": "f12", "frage": "Der Drucker druckt nicht mehr. Was soll ich tun?",
"erwartet": [{"quelle": "karte-druck.txt", "abschnitt": "Druckdienst neu starten"}]},
{"id": "f13", "frage": "Wie komme ich von zu Hause ins Firmennetz?",
"erwartet": [{"quelle": "karte-vpn.txt", "abschnitt": "VPN-Zugang einrichten"}]}
]The questions are deliberately different: eleven about the English documentation, two about the practice company’s handbook, sometimes almost word for word (f06 “Startup-Probe”), sometimes in completely different words (f12 “Der Drucker druckt nicht mehr” – the printer is not printing any more – for the card “Druckdienst neu starten”, f13 “von zu Hause ins Firmennetz” – from home into the company network – for “VPN”).
Why source and section? The pipeline splits at headings. No matter how large the cards are – a section stays the same. This way, variants with 112 or 293 cards can be checked with the same questions.
Remember: The gold standard contains judgements. Whoever decides which sections count as correct decides what is measured – write them down before you compare variants, not afterwards.
Save your progress? Sign up for free
Drill 2: The test bench
Where you are: on rag1, in
~/kurs/07.What you have afterwards:
eval.pyas a job and the baseline for the collectionwissen.
Step 1 – the program.
# on rag1
nano eval.py"""Prüfstand: Testfragen stellen und messen, auf welchem Platz die erwartete Karte liegt."""
import json
import os
import urllib.request
EMBED = os.environ.get("EMBED_URL", "http://embed.rag:11434")
QDRANT = os.environ.get("QDRANT_URL", "http://qdrant.rag:6333")
SAMMLUNG = os.environ.get("SAMMLUNG", "wissen")
MODELL = os.environ.get("MODELL", "bge-m3")
FRAGEN = os.environ.get("FRAGEN", "/testfragen/testfragen.json")
K = 5
def anfrage(methode, url, daten):
req = urllib.request.Request(
url,
data=json.dumps(daten).encode(),
method=methode,
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req, timeout=300) as antwort:
return json.load(antwort)
def rang(punkte, erwartet):
"""Platz der ersten Karte aus einem erwarteten Abschnitt, None wenn keine unter den ersten K."""
for platz, punkt in enumerate(punkte, start=1):
ort = {
"quelle": punkt["payload"]["quelle"],
"abschnitt": punkt["payload"]["abschnitt"],
}
if ort in erwartet:
return platz
return None
def main():
with open(FRAGEN, encoding="utf-8") as datei:
fragen = json.load(datei)
plaetze = []
for frage in fragen:
vektor = anfrage(
"POST", f"{EMBED}/api/embed", {"model": MODELL, "input": [frage["frage"]]}
)["embeddings"][0]
punkte = anfrage(
"POST",
f"{QDRANT}/collections/{SAMMLUNG}/points/query",
{"query": vektor, "limit": K, "with_payload": ["quelle", "abschnitt"]},
)["result"]["points"]
platz = rang(punkte, frage["erwartet"])
plaetze.append(platz)
print(f"{frage['id']:>4} Platz {platz or '-'} {frage['frage']}", flush=True)
n = len(plaetze)
ergebnis = {
"sammlung": SAMMLUNG,
"fragen": n,
"treffer@1": round(sum(1 for p in plaetze if p and p <= 1) / n, 2),
"treffer@3": round(sum(1 for p in plaetze if p and p <= 3) / n, 2),
"treffer@5": round(sum(1 for p in plaetze if p) / n, 2),
"mrr": round(sum(1 / p for p in plaetze if p) / n, 2),
}
print(json.dumps(ergebnis, ensure_ascii=False), flush=True)
if __name__ == "__main__":
main()| Part | What it does |
|---|---|
anfrage |
as in ingest.py: JSON there, JSON back |
rang (rank) |
goes through the hits from the top and returns the position of the
first card whose source and section are in erwartet
(expected); None if none is among the first five |
main |
per question: embed, fetch the five nearest cards, note and print the position; at the end hits@1, hits@3, hits@5 and MRR |
MRR is calculated like this: position 1 counts 1, position 2 counts ½, position 3 counts ⅓ – not found counts 0. The mean over all questions is the MRR. It rewards the right card being far in front, because on Day 9 the language model only gets to see the first cards.
Step 2 – program and questions into the cluster.
# on rag1
kubectl -n rag create configmap eval-code --from-file=eval.py# on rag1
kubectl -n rag create configmap testfragen --from-file=testfragen.jsonStep 3 – the manifest. It is built like the job from Day 6, only with a different program and the test questions instead of the corpus:
# on rag1
nano eval-job.yamlapiVersion: batch/v1
kind: Job
metadata:
name: eval
namespace: rag
spec:
backoffLimit: 0
ttlSecondsAfterFinished: 86400
template:
spec:
restartPolicy: Never
containers:
- name: eval
image: python:3.14.10-slim-trixie
command: ["python", "/code/eval.py"]
env:
- name: SAMMLUNG
value: wissen
resources:
requests:
cpu: 100m
memory: 64Mi
limits:
memory: 128Mi
volumeMounts:
- name: code
mountPath: /code
- name: testfragen
mountPath: /testfragen
volumes:
- name: code
configMap:
name: eval-code
- name: testfragen
configMap:
name: testfragen| Setting | Meaning |
|---|---|
backoffLimit: 0 |
no second attempt – an error in the test bench should be visible, not repeated |
env SAMMLUNG |
the collection that is tested |
limits.memory: 128Mi |
the test bench only keeps questions and hits in memory |
volumes |
the ConfigMaps eval-code and
testfragen |
Step 4 – the baseline.
# on rag1
kubectl apply -f eval-job.yaml# on rag1
kubectl -n rag wait --for=condition=Complete job/eval --timeout=600s# on rag1
kubectl -n rag logs job/evalExpected (in the lab after 9 seconds;
Platz means position):
f01 Platz - Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?
f02 Platz 1 Wie groß darf ein Secret höchstens sein?
f03 Platz 1 Wird eine als Volume eingehängte ConfigMap automatisch aktualisiert?
f04 Platz 1 Wie verhindere ich, dass eine ConfigMap versehentlich geändert wird?
f05 Platz 1 Was muss ein Pod erfüllen, damit er die QoS-Klasse Guaranteed bekommt?
f06 Platz 1 Wozu dient eine Startup-Probe?
f07 Platz 3 Wie lange wartet Kubernetes beim Beenden eines Pods, bevor es die Container hart beendet?
f08 Platz 1 Welche Phasen kann ein Pod haben?
f09 Platz - Wie halte ich Pods von einem bestimmten Node fern?
f10 Platz - Was passiert mit den Pods, wenn ein Node nicht mehr erreichbar ist?
f11 Platz 1 Wie hinterlege ich Zugangsdaten für eine private Container-Registry?
f12 Platz 1 Der Drucker druckt nicht mehr. Was soll ich tun?
f13 Platz 1 Wie komme ich von zu Hause ins Firmennetz?
{"sammlung": "wissen", "fragen": 13, "treffer@1": 0.69, "treffer@3": 0.77, "treffer@5": 0.77, "mrr": 0.72}
| Metric | Value | Meaning |
|---|---|---|
treffer@1 |
0.69 | 9 of 13 questions: the right card is right at the front |
treffer@3 |
0.77 | 10 of 13: plus f07 in position 3 |
treffer@5 |
0.77 | positions 4 and 5 add nothing |
mrr |
0.72 | (9 · 1 + ⅓) / 13 |
What you see: The handbook questions work, even in completely different words. Three questions about the documentation – memory shortage, keeping pods away, node unreachable – miss their section completely. That is the number you want to improve.
Remember: The baseline is the most important run of the day. Without it, every later number is just a number.
Save your progress? Sign up for free
Drill 3: Switches at the intake desk
Where you are: on rag1, in
~/kurs/07.What you have afterwards: an
ingest.pywhose card size, overlap and context can be set via environment variables – and which creates its collection itself.
Step 1 – the program from Day 6 as the starting point.
# on rag1
cp ../06/ingest.py ingest.pyStep 2 – the changes. The green lines are new or changed:
# on rag1
nano ingest.py"""Annahmestelle: Dokumente laden, säubern, in Karten teilen, einbetten, in Qdrant ablegen."""
import hashlib
import json
import os
import pathlib
import re
import sys
import time
import urllib.error
import urllib.request
import uuid
KORPUS = pathlib.Path(os.environ.get("KORPUS", "/korpus"))
EMBED = os.environ.get("EMBED_URL", "http://embed.rag:11434")
QDRANT = os.environ.get("QDRANT_URL", "http://qdrant.rag:6333")
SAMMLUNG = os.environ.get("SAMMLUNG", "wissen")
MODELL = os.environ.get("MODELL", "bge-m3")
MAX_ZEICHEN = int(os.environ.get("MAX_ZEICHEN", "1000"))
UEBERLAPPUNG = os.environ.get("UEBERLAPPUNG", "ja") == "ja"
KONTEXT = os.environ.get("KONTEXT", "ja") == "ja"
STAPEL = 16
def anfrage(methode, url, daten=None):
body = json.dumps(daten).encode() if daten is not None else None
req = urllib.request.Request(
url, data=body, method=methode, headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=300) as antwort:
return json.load(antwort)
def saeubern(text):
"""Front Matter, Kommentare, Hugo-Shortcodes und Links entfernen; Titel zurückgeben."""
titel = None
kopf = re.match(r"^---\n(.*?)\n---\n", text, re.DOTALL)
if kopf:
t = re.search(r"^title:\s*(.+)$", kopf.group(1), re.MULTILINE)
titel = t.group(1).strip().strip('"') if t else None
text = text[kopf.end() :]
text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)
text = re.sub(
r'\{\{<\s*glossary_tooltip[^>]*?text="([^"]+)"[^>]*>\}\}', r"\1", text
)
text = re.sub(r"\{\{[<%].*?[%>]\}\}", "", text, flags=re.DOTALL)
text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return titel, text.strip()
def karten(titel, text):
"""Nach Überschriften trennen, Absätze bis MAX_ZEICHEN bündeln, letzter Absatz als Überlappung."""
abschnitt, absaetze, ergebnis = titel, [], []
def abschliessen():
if absaetze:
ergebnis.append((abschnitt, "\n\n".join(absaetze)))
for absatz in re.split(r"\n\s*\n", text):
absatz = absatz.strip()
if not absatz:
continue
ueberschrift = re.match(r"^#{1,4}\s+(.+)$", absatz)
if ueberschrift:
abschliessen()
abschnitt, absaetze = (
re.sub(r"\s*\{#[^}]*\}", "", ueberschrift.group(1)).strip(),
[],
)
continue
if absaetze and len("\n\n".join(absaetze)) + len(absatz) > MAX_ZEICHEN:
abschliessen()
behalten = UEBERLAPPUNG and len(absaetze[-1]) < MAX_ZEICHEN // 2
absaetze = [absaetze[-1]] if behalten else []
absaetze.append(absatz)
abschliessen()
return ergebnis
def eingabe(titel, abschnitt, text):
"""Genau dieser Text wird eingebettet."""
if not KONTEXT:
return text
return f"{titel} – {abschnitt}\n{text}"
def punkt_id(quelle, text):
"""Hash über alles, was den Vektor bestimmt: Modell, Quelle und eingebetteter Text."""
return str(
uuid.UUID(
hashlib.sha256(f"{MODELL}\n{quelle}\n{text}".encode()).hexdigest()[:32]
)
)
def sammlung_anlegen():
"""Collection mit Index auf quelle anlegen, falls es sie noch nicht gibt."""
try:
anfrage("GET", f"{QDRANT}/collections/{SAMMLUNG}")
return
except urllib.error.HTTPError as fehler:
if fehler.code != 404:
raise
anfrage(
"PUT",
f"{QDRANT}/collections/{SAMMLUNG}",
{"vectors": {"size": 1024, "distance": "Cosine"}},
)
anfrage(
"PUT",
f"{QDRANT}/collections/{SAMMLUNG}/index?wait=true",
{"field_name": "quelle", "field_schema": "keyword"},
)
print(f"Collection {SAMMLUNG} angelegt", flush=True)
def vorhandene(ids):
antwort = anfrage(
"POST",
f"{QDRANT}/collections/{SAMMLUNG}/points",
{"ids": ids, "with_payload": False, "with_vector": False},
)
return {p["id"] for p in antwort["result"]}
def einbetten(texte):
antwort = anfrage("POST", f"{EMBED}/api/embed", {"model": MODELL, "input": texte})
return antwort["embeddings"]
def main():
start = time.time()
sammlung_anlegen()
zaehler = {"dokumente": 0, "karten": 0, "neu": 0, "unveraendert": 0, "geloescht": 0}
for datei in sorted(KORPUS.iterdir()):
if datei.name.startswith(".") or datei.suffix not in (".md", ".txt"):
continue
titel, text = saeubern(datei.read_text(encoding="utf-8"))
titel = titel or text.split(":", 1)[0]
lizenz = (
"CC BY 4.0, kubernetes.io"
if datei.name.startswith("k8s-")
else "Übungsfirma"
)
liste = karten(titel, text)
punkte = []
for nr, (abschnitt, inhalt) in enumerate(liste):
punkte.append(
{
"id": punkt_id(datei.name, eingabe(titel, abschnitt, inhalt)),
"payload": {
"quelle": datei.name,
"titel": titel,
"abschnitt": abschnitt,
"nr": nr,
"lizenz": lizenz,
"text": inhalt,
},
}
)
alt = vorhandene([p["id"] for p in punkte])
neu = [p for p in punkte if p["id"] not in alt]
for i in range(0, len(neu), STAPEL):
stapel = neu[i : i + STAPEL]
vektoren = einbetten(
[
eingabe(
p["payload"]["titel"],
p["payload"]["abschnitt"],
p["payload"]["text"],
)
for p in stapel
]
)
for p, v in zip(stapel, vektoren):
p["vector"] = v
anfrage(
"PUT",
f"{QDRANT}/collections/{SAMMLUNG}/points?wait=true",
{"points": stapel},
)
# Karten dieser Quelle, die es nicht mehr gibt, entfernen
filter_ = {
"must": [{"key": "quelle", "match": {"value": datei.name}}],
"must_not": [{"has_id": [p["id"] for p in punkte]}],
}
zaehl = anfrage(
"POST",
f"{QDRANT}/collections/{SAMMLUNG}/points/count",
{"filter": filter_, "exact": True},
)["result"]["count"]
if zaehl:
anfrage(
"POST",
f"{QDRANT}/collections/{SAMMLUNG}/points/delete?wait=true",
{"filter": filter_},
)
zaehler["dokumente"] += 1
zaehler["karten"] += len(punkte)
zaehler["neu"] += len(neu)
zaehler["unveraendert"] += len(punkte) - len(neu)
zaehler["geloescht"] += zaehl
print(
f"{datei.name}: {len(punkte)} Karten, {len(neu)} neu, {zaehl} gelöscht",
flush=True,
)
ergebnis = {**zaehler, "sekunden": round(time.time() - start, 1)}
print(json.dumps(ergebnis, ensure_ascii=False), flush=True)
if __name__ == "__main__":
sys.exit(main())| Change | Effect |
|---|---|
UEBERLAPPUNG, KONTEXT |
two switches (overlap, context), default ja (yes) –
without a setting the program behaves as on Day 6 |
behalten = UEBERLAPPUNG and … |
with UEBERLAPPUNG=nein (no), every card starts without
the last paragraph of the previous one |
if not KONTEXT: return text |
with KONTEXT=nein, only the card text is embedded,
without title and section |
sammlung_anlegen (create collection) |
asks for the collection; on 404 it creates it with an index on
quelle – so variants need no curl commands of
their own |
import urllib.error |
for HTTPError, to tell 404 apart from other errors |
Because the default values stay the same, neither the embedded texts
nor the fingerprints change for wissen.
Step 3 – the new program into the cluster.
# on rag1
kubectl -n rag delete configmap ingest-code# on rag1
kubectl -n rag create configmap ingest-code --from-file=ingest.pyStep 4 – putting it to the test. The job from Day 6 with the new program:
# on rag1
kubectl -n rag delete job ingest# on rag1
kubectl apply -f ../06/ingest-job.yaml# on rag1
kubectl -n rag wait --for=condition=Complete job/ingest --timeout=900s# on rag1
kubectl -n rag logs job/ingestExpected (excerpt – the last line):
{"dokumente": 9, "karten": 173, "neu": 0, "unveraendert": 173, "geloescht": 0, "sekunden": 0.2}
Nothing new: the change has no effect on wissen, just as
intended.
Remember: Switches with the previous behaviour as the default make a pipeline extensible without touching the existing index. The test is a run that reports “0 new”.
Save your progress? Sign up for free
Drill 4: The first variant – smaller cards
Where you are: on rag1, in
~/kurs/07.What you have afterwards: the collection
wissen-500with cards of at most 500 characters – and its measurements.
Step 1 – the job for the variant.
# on rag1
cp ../06/ingest-job.yaml ingest-500.yaml# on rag1
nano ingest-500.yamlapiVersion: batch/v1
kind: Job
metadata:
name: ingest-500
namespace: rag
spec:
backoffLimit: 1
ttlSecondsAfterFinished: 86400
template:
spec:
restartPolicy: Never
containers:
- name: ingest
image: python:3.14.10-slim-trixie
command: ["python", "/code/ingest.py"]
env:
- name: SAMMLUNG
value: wissen-500
- name: MAX_ZEICHEN
value: "500"
- name: UEBERLAPPUNG
value: "ja"
- name: KONTEXT
value: "ja"
resources:
requests:
cpu: 100m
memory: 64Mi
limits:
memory: 256Mi
volumeMounts:
- name: code
mountPath: /code
- name: korpus
mountPath: /korpus
volumes:
- name: code
configMap:
name: ingest-code
- name: korpus
configMap:
name: korpus| Setting | Value | Meaning |
|---|---|---|
name |
ingest-500 |
a job of its own per variant; ingest stays for
wissen |
SAMMLUNG |
wissen-500 |
a collection of its own – the baseline stays untouched |
MAX_ZEICHEN |
"500" |
cards half the size |
UEBERLAPPUNG, KONTEXT |
"ja" |
as before; only one switch is ever changed |
Values of environment variables are always strings in Kubernetes, hence the quotation marks.
Step 2 – classify.
# on rag1
date +%T# on rag1
kubectl apply -f ingest-500.yaml# on rag1
kubectl -n rag wait --for=condition=Complete job/ingest-500 --timeout=1800s# on rag1
date +%TIn the lab from 21:21:36 to 21:25:56.
# on rag1
kubectl -n rag logs job/ingest-500Expected:
Collection wissen-500 angelegt
k8s-configmap.md: 34 Karten, 34 neu, 0 gelöscht
k8s-pod-lifecycle.md: 109 Karten, 109 neu, 0 gelöscht
k8s-pod-qos.md: 27 Karten, 27 neu, 0 gelöscht
k8s-secret.md: 77 Karten, 77 neu, 0 gelöscht
k8s-taint-and-toleration.md: 42 Karten, 42 neu, 0 gelöscht
karte-backup.txt: 1 Karten, 1 neu, 0 gelöscht
karte-druck.txt: 1 Karten, 1 neu, 0 gelöscht
karte-urlaub.txt: 1 Karten, 1 neu, 0 gelöscht
karte-vpn.txt: 1 Karten, 1 neu, 0 gelöscht
{"dokumente": 9, "karten": 293, "neu": 293, "unveraendert": 0, "geloescht": 0, "sekunden": 254.5}
What you see: 293 instead of 173 cards, but hardly more time (254.5 instead of 246.6 seconds). The computing time depends mainly on the amount of text, not on the number of cards.
Step 3 – point the test bench at the variant.
# on rag1
cp eval-job.yaml eval-wissen-500.yaml# on rag1
nano eval-wissen-500.yamlChange only the line with the collection:
env:
- name: SAMMLUNG
value: wissen-500Step 4 – test. The job is called eval
again, so delete the old one first:
# on rag1
kubectl -n rag delete job eval# on rag1
kubectl apply -f eval-wissen-500.yaml# on rag1
kubectl -n rag wait --for=condition=Complete job/eval --timeout=600s# on rag1
kubectl -n rag logs job/evalExpected (excerpt – the changed lines and the result):
f07 Platz 5 Wie lange wartet Kubernetes beim Beenden eines Pods, bevor es die Container hart beendet?
f10 Platz 2 Was passiert mit den Pods, wenn ein Node nicht mehr erreichbar ist?
{"sammlung": "wissen-500", "fragen": 13, "treffer@1": 0.69, "treffer@3": 0.77, "treffer@5": 0.85, "mrr": 0.75}
What you see: f10 moves up to position 2, f07 drops from 3 to 5. On balance a little better – but a difference of exactly one question.
Remember: One variant, one change, one collection of its own. Whoever turns two switches at the same time does not know afterwards which one had the effect.
Save your progress? Sign up for free
Drill 5: The remaining variants
Where you are: on rag1, in
~/kurs/07.What you have afterwards: four variants compared with the baseline.
Step 1 – three more runs. Repeat Drill 4 three
times. To do so, copy ingest-500.yaml and change only
name, SAMMLUNG and the one switch in the copy;
point the test bench at the new collection as in Drill 4, Steps 3 and
4:
| File | name |
SAMMLUNG |
MAX_ZEICHEN |
UEBERLAPPUNG |
KONTEXT |
|---|---|---|---|---|---|
ingest-2000.yaml |
ingest-2000 |
wissen-2000 |
"2000" |
"ja" |
"ja" |
ingest-ohne-ueberlappung.yaml |
ingest-ohne-ueberlappung |
wissen-ohne-ueberlappung |
"1000" |
"nein" |
"ja" |
ingest-ohne-kontext.yaml |
ingest-ohne-kontext |
wissen-ohne-kontext |
"1000" |
"ja" |
"nein" |
Each run takes four minutes; classifying and testing happen one after the other.
Step 2 – the results. The last lines of the three ingest jobs in the lab:
{"dokumente": 9, "karten": 112, "neu": 112, "unveraendert": 0, "geloescht": 0, "sekunden": 216.5}
{"dokumente": 9, "karten": 161, "neu": 161, "unveraendert": 0, "geloescht": 0, "sekunden": 211.6}
{"dokumente": 9, "karten": 173, "neu": 173, "unveraendert": 0, "geloescht": 0, "sekunden": 221.9}
And the last lines of the three test runs:
{"sammlung": "wissen-2000", "fragen": 13, "treffer@1": 0.69, "treffer@3": 0.69, "treffer@5": 0.69, "mrr": 0.69}
{"sammlung": "wissen-ohne-ueberlappung", "fragen": 13, "treffer@1": 0.69, "treffer@3": 0.69, "treffer@5": 0.77, "mrr": 0.71}
{"sammlung": "wissen-ohne-kontext", "fragen": 13, "treffer@1": 0.77, "treffer@3": 0.92, "treffer@5": 0.92, "mrr": 0.83}
Step 3 – everything in one table.
| Variant | Cards | Seconds | hits@1 | hits@3 | hits@5 | MRR |
|---|---|---|---|---|---|---|
| Baseline (1000, with overlap, with context) | 173 | 246.6 | 0.69 | 0.77 | 0.77 | 0.72 |
| Max. 500 characters | 293 | 254.5 | 0.69 | 0.77 | 0.85 | 0.75 |
| Max. 2000 characters | 112 | 216.5 | 0.69 | 0.69 | 0.69 | 0.69 |
| without overlap | 161 | 211.6 | 0.69 | 0.69 | 0.77 | 0.71 |
| without context | 173 | 221.9 | 0.77 | 0.92 | 0.92 | 0.83 |
What you see: Large cards and missing overlap each lose one question. Small cards add one in position 5. The clearest jump comes from the variant without a heading in the embedded text: f09 and f10 jump to position 1, f07 to position 2; only f04 drops from 1 to 3.
On Day 6 it said: “The heading is embedded too” – with the note that this is an assumption. In this corpus with these questions it is wrong. One possible explanation, which you can see in f09: with a title such as “Pod Lifecycle – Termination of Pods” in front of every card, all 64 cards of the lifecycle page resemble each other more strongly – and push to the front for general questions.
Remember: Recommendations from articles are hypotheses for your test bench, not results. Here the test bench refuted a widespread recommendation.
Save your progress? Sign up for free
Drill 6: How much do 13 questions carry?
Where you are: on rag1, in
~/kurs/07.What you have afterwards: a feel for the uncertainty of your numbers – and for the judgements in the gold standard.
Step 1 – one question weighs 0.08. With 13 questions, each single one changes hits@k by 1/13 ≈ 0.077. The gap between the baseline and “without context” at hits@3 (0.77 to 0.92) is exactly two questions. The variants 500, 2000 and “without overlap” differ from the baseline by one question – that is not a reliable result.
Step 2 – what is in front for f09. You ask question f09 directly against both collections:
# on rag1
jq -n --arg f "Wie halte ich Pods von einem bestimmten Node fern?" '{model: "bge-m3", input: [$f]}' > f09-anfrage.json# on rag1
kubectl -n rag exec -i curl -- curl -s embed.rag:11434/api/embed -d @- < f09-anfrage.json > f09-embed.json# on rag1
jq '{query: .embeddings[0], limit: 3, with_payload: ["quelle", "abschnitt"]}' f09-embed.json > f09-suche.json# on rag1
curl -s -X POST http://127.0.0.1:6333/collections/wissen/points/query -H 'Content-Type: application/json' -d @f09-suche.json -o f09-wissen.json# on rag1
jq -c '.result.points[] | {score, quelle: .payload.quelle, abschnitt: .payload.abschnitt}' f09-wissen.jsonExpected:
{"score":0.6062392,"quelle":"k8s-pod-lifecycle.md","abschnitt":"Termination of Pods"}
{"score":0.5977421,"quelle":"k8s-secret.md","abschnitt":"Information security for Secrets"}
{"score":0.59661096,"quelle":"k8s-taint-and-toleration.md","abschnitt":"Example Use Cases"}
# on rag1
curl -s -X POST http://127.0.0.1:6333/collections/wissen-ohne-kontext/points/query -H 'Content-Type: application/json' -d @f09-suche.json -o f09-ohne-kontext.json# on rag1
jq -c '.result.points[] | {score, quelle: .payload.quelle, abschnitt: .payload.abschnitt}' f09-ohne-kontext.jsonExpected:
{"score":0.6171009,"quelle":"k8s-taint-and-toleration.md","abschnitt":"Concepts"}
{"score":0.6170685,"quelle":"k8s-pod-lifecycle.md","abschnitt":"Pod behavior during kubelet restarts"}
{"score":0.61105114,"quelle":"k8s-secret.md","abschnitt":"Information security for Secrets"}
What you see: Two things. First, in
wissen-ohne-kontext the right card is only 0.00003 ahead of
second place – a lucky hit could just as well be a miss. Second, in
wissen position 3 holds the section “Example Use Cases” of
the taint page. It contains examples such as “dedicated nodes” – you
could accept it as a correct answer. The gold standard from Drill 1 does
not. With this one extra entry, the baseline would arithmetically reach
hits@3 of 0.85 instead of 0.77 (11 instead of 10 of 13).
Remember: Small test sets show gross errors, not fine differences. Whoever decides between two variants needs more questions – and a gold standard that is fixed before the comparison.
If it does not work
kubectl execreportscannot exec into a container in a completed pod; current phase is Succeeded: the helper podcurlhas expired. Recreate it as on Day 6, Drill 6, Step 1.
Save your progress? Sign up for free
Diagnosis task
A colleague proudly reports: “I set the card size to 500, the search is much better now – I tried the question about node failures, it comes up in position 2 instead of not at all.” He wants to take the change to production. You have ten minutes.
Solution: One question is not a test. Run the test bench against baseline and variant (Drill 4): f10 really does improve from “not found” to position 2, but f07 drops from position 3 to 5, and hits@3 stays at 0.77. The variant “without context” does clearly better on the same questions (hits@3 0.92). Before either of them goes to production, more test questions belong in the gold standard – at least enough that a single question does not tip the result.
Challenge
Write ten more test questions – before you look at which variant
answers them well – and run the test bench against wissen
and wissen-ohne-kontext. Does the lead of “without context”
hold with 23 questions? Also add the section “Example Use Cases” to f09
and watch which numbers change.
Save your progress? Sign up for free
Checkpoint
# on rag1
curl -s http://127.0.0.1:6333/collections -o sammlungen.json# on rag1
jq -c '[.result.collections[].name] | sort' sammlungen.jsonExpected:
["handbuch","wissen","wissen-2000","wissen-500","wissen-ohne-kontext","wissen-ohne-ueberlappung"]
# on rag1
kubectl -n rag logs job/evalExpected (excerpt – the last line): a result like the one above, for the collection you tested last.
Test yourself
- What does hits@3 measure, and what does MRR measure in addition?
- Why does the test bench check source and section and not the ID of the card?
- Why does every variant get a collection of its own?
- The variant “without context” is better. Does that prove that headings should never be embedded along with the text?
- How much does a single question change hits@k with 13 test questions?
- Why must the gold standard be fixed before you compare variants?
Answers:
- hits@3: for how many questions a correct card is among the first three. MRR also takes the position into account: hits further in front count more.
- The IDs change with card size, overlap and context. The sections stay the same because the pipeline splits at headings – so the same questions fit all variants.
- So that the baseline stays unchanged and every variant can be measured independently.
- No. It applies to this corpus, this model and these 13 questions – and the gap is two questions. It is a strong indication that has to be confirmed with more questions.
- By 1/13, i.e. about 0.077.
- Otherwise you adapt the answer sheet to the variant you want to like – as with “Example Use Cases”, which would improve the baseline by one question.
Interview note
“How do you know whether a change to your RAG system improves the search?” – With a fixed set of test questions including expected sources, measured as hits@k and MRR, before and after the change, one change per run. Part of that is honesty about the size: with 13 questions, one question is 7.7 points. A concrete example makes an impression: “A widespread recommendation – embedding headings along with the text – pushed hits@3 down from 0.92 to 0.77 in our test.”
Enterprise note
In production, the gold standard grows from real queries: questions for which users click “not helpful” are added with the right source. The test bench runs in CI on every change to the pipeline, model or index and blocks changes that fall below a threshold – rules decide, not impressions. To choose between variants, teams rely on hundreds of questions so that individual outliers do not decide.
Summary
You created 13 test questions with expected sections and built a test bench as a job. The baseline: hits@1 0.69, hits@3 0.77, MRR 0.72 – three questions without a hit. With two new switches and automatically created collections, you classified and tested four variants. Card size and overlap each moved one question. Without the heading in the embedded text, hits@3 rose to 0.92 and MRR to 0.83 – the assumption from Day 6 did not stand up to measurement. At the same time you saw how little 13 questions carry and which judgements are in the gold standard. No variant finds the question about memory shortage (f01). That is where Day 8 starts.
Commands at a glance
| Command | What it does | Parameters |
|---|---|---|
kubectl -n rag create configmap testfragen --from-file=testfragen.json |
test questions into the cluster | – |
kubectl apply -f eval-job.yaml |
start the test bench | – |
kubectl -n rag logs job/eval |
positions and metrics | – |
kubectl -n rag delete job eval |
clear the test bench for the next run | – |
cp ../06/ingest-job.yaml ingest-500.yaml |
derive a variant from the existing job | – |
kubectl apply -f ingest-500.yaml |
classify a variant | – |
kubectl -n rag wait --for=condition=Complete job/<name> |
wait for the end | --timeout |
curl -s http://127.0.0.1:6333/collections |
list all collections | – |