erenyanic commited on
Commit
34e60a9
·
verified ·
1 Parent(s): 1976d24

Add scripts/benchmark.py

Browse files
Files changed (1) hide show
  1. scripts/benchmark.py +386 -0
scripts/benchmark.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Threshold calibration and retrieval benchmark.
3
+
4
+ uv run python scripts/benchmark.py
5
+
6
+ Runs the 30-question evaluation set (20 answerable, 10 out-of-scope) through the
7
+ real retrieval path and sweeps the cosine similarity threshold to find the value
8
+ that best separates them. Writes a JSON result file and a Markdown report that
9
+ feeds the README's "Threshold Analysis" section.
10
+
11
+ With ``--with-rag`` it additionally exercises the full LLM path on a couple of
12
+ questions using DEEPSEEK_API_KEY from .env, to prove the generation side works
13
+ end to end. That flag is for the operator only; the web app never reads a key
14
+ from the environment.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import logging
22
+ import sys
23
+ import time
24
+ from pathlib import Path
25
+
26
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
27
+
28
+ import ehekim # noqa: F401 (applies the torch/Triton compatibility fix first)
29
+
30
+ import numpy as np
31
+
32
+ from ehekim.config import (
33
+ EMBEDDING_MODEL_ID,
34
+ PROJECT_ROOT,
35
+ REFUSAL_MESSAGE_TR,
36
+ get_settings,
37
+ operator_secrets,
38
+ )
39
+ from ehekim.embedding import Embedder
40
+ from ehekim.retrieval import build_rag_messages, expand_context, search
41
+ from ehekim.vectorstore import VectorStore
42
+
43
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
44
+ logger = logging.getLogger("benchmark")
45
+
46
+ DATA_DIR = PROJECT_ROOT / "data"
47
+ QUESTIONS_PATH = DATA_DIR / "benchmark_questions.json"
48
+ RESULTS_PATH = DATA_DIR / "benchmark_results.json"
49
+ REPORT_PATH = DATA_DIR / "threshold_report.md"
50
+ # Flat, viewer-friendly rendering of the 30-question evaluation set. The JSON
51
+ # above is nested (positive/negative arrays) and therefore does not render in the
52
+ # Hugging Face dataset viewer; this parquet does.
53
+ QUESTIONS_PARQUET_PATH = DATA_DIR / "benchmark_questions.parquet"
54
+
55
+ # Retrieval depth used for the analysis. Wider than the UI default so the sweep
56
+ # can see what a permissive threshold would have admitted.
57
+ ANALYSIS_TOP_K = 10
58
+ SWEEP = np.round(np.arange(0.20, 0.901, 0.01), 2)
59
+
60
+
61
+ def parse_args() -> argparse.Namespace:
62
+ p = argparse.ArgumentParser(description="e-hekim threshold benchmark")
63
+ p.add_argument("--top-k", type=int, default=ANALYSIS_TOP_K)
64
+ p.add_argument("--device", default=None)
65
+ p.add_argument("--with-rag", action="store_true",
66
+ help="Also call the LLM on two questions (needs DEEPSEEK_API_KEY in .env).")
67
+ return p.parse_args()
68
+
69
+
70
+ def evaluate(embedder: Embedder, store: VectorStore, questions: dict, top_k: int) -> list[dict]:
71
+ """Retrieve once per question; the sweep then reuses these scores."""
72
+ rows: list[dict] = []
73
+ for label, items in (("positive", questions["positive"]), ("negative", questions["negative"])):
74
+ for item in items:
75
+ outcome = search(
76
+ embedder=embedder,
77
+ store=store,
78
+ query=item["question"],
79
+ top_k=top_k,
80
+ threshold=0.0, # keep everything; the sweep applies the cut
81
+ )
82
+ hits = outcome.hits
83
+ expected_url = item.get("expected_url")
84
+ expected_rank = None
85
+ if expected_url:
86
+ for rank, hit in enumerate(hits, start=1):
87
+ if hit.url == expected_url:
88
+ expected_rank = rank
89
+ break
90
+ rows.append(
91
+ {
92
+ "id": item["id"],
93
+ "label": label,
94
+ "question": item["question"],
95
+ "expected_url": expected_url,
96
+ "expected_rank": expected_rank,
97
+ "expected_similarity": (
98
+ hits[expected_rank - 1].similarity if expected_rank else None
99
+ ),
100
+ "best_similarity": hits[0].similarity if hits else 0.0,
101
+ "top_url": hits[0].url if hits else None,
102
+ "top_title": hits[0].title if hits else None,
103
+ "similarities": [round(h.similarity, 4) for h in hits],
104
+ }
105
+ )
106
+ return rows
107
+
108
+
109
+ def sweep_thresholds(rows: list[dict]) -> list[dict]:
110
+ """Score the answer/refuse decision at every candidate threshold."""
111
+ positives = [r for r in rows if r["label"] == "positive"]
112
+ negatives = [r for r in rows if r["label"] == "negative"]
113
+
114
+ table: list[dict] = []
115
+ for threshold in SWEEP:
116
+ # A positive is answered correctly only if the system both decides to
117
+ # answer AND has the right source document above the cut. That is a
118
+ # stricter (and more honest) success criterion than "did not refuse".
119
+ tp = sum(
120
+ 1 for r in positives
121
+ if r["best_similarity"] >= threshold
122
+ and r["expected_similarity"] is not None
123
+ and r["expected_similarity"] >= threshold
124
+ )
125
+ answered_positives = sum(1 for r in positives if r["best_similarity"] >= threshold)
126
+ fn = len(positives) - answered_positives
127
+ fp = sum(1 for r in negatives if r["best_similarity"] >= threshold)
128
+ tn = len(negatives) - fp
129
+
130
+ precision = tp / (tp + fp) if (tp + fp) else 0.0
131
+ recall = tp / len(positives) if positives else 0.0
132
+ f1 = (2 * precision * recall / (precision + recall)) if (precision + recall) else 0.0
133
+ accuracy = (answered_positives + tn) / len(rows)
134
+
135
+ table.append(
136
+ {
137
+ "threshold": float(threshold),
138
+ "answered_positives": answered_positives,
139
+ "grounded_positives": tp,
140
+ "missed_positives": fn,
141
+ "false_answers_on_negatives": fp,
142
+ "correct_refusals": tn,
143
+ "precision": round(precision, 4),
144
+ "recall": round(recall, 4),
145
+ "f1": round(f1, 4),
146
+ "accuracy": round(accuracy, 4),
147
+ }
148
+ )
149
+ return table
150
+
151
+
152
+ def choose_threshold(table: list[dict]) -> tuple[float, dict]:
153
+ """Pick the most robust threshold among those achieving the best F1.
154
+
155
+ Several adjacent thresholds usually tie at the optimum. Taking the midpoint
156
+ of the widest tied run keeps the operating point as far as possible from
157
+ both failure modes, instead of sitting on a cliff edge.
158
+ """
159
+ best_f1 = max(row["f1"] for row in table)
160
+ tied = [row["threshold"] for row in table if row["f1"] == best_f1]
161
+
162
+ runs: list[list[float]] = []
163
+ current = [tied[0]]
164
+ for value in tied[1:]:
165
+ if round(value - current[-1], 2) <= 0.011:
166
+ current.append(value)
167
+ else:
168
+ runs.append(current)
169
+ current = [value]
170
+ runs.append(current)
171
+
172
+ widest = max(runs, key=len)
173
+ chosen = round(float(np.median(widest)), 2)
174
+ row = min(table, key=lambda r: abs(r["threshold"] - chosen))
175
+ return chosen, row
176
+
177
+
178
+ def render_report(rows: list[dict], table: list[dict], chosen: float, chosen_row: dict,
179
+ stats: dict) -> str:
180
+ lines: list[str] = []
181
+ lines.append("# Eşik Analizi (Threshold Analysis)\n")
182
+ lines.append(f"- Embedding modeli: `{EMBEDDING_MODEL_ID}` (768 boyut, kosinüs)")
183
+ lines.append(f"- Değerlendirme kümesi: {stats['n_positive']} pozitif + {stats['n_negative']} negatif soru")
184
+ lines.append(f"- Seçilen eşik: **{chosen:.2f}**\n")
185
+
186
+ lines.append("## Ayrışma (separation)\n")
187
+ lines.append("| Grup | En yüksek benzerlik (ort.) | Min | Maks |")
188
+ lines.append("|---|---:|---:|---:|")
189
+ lines.append(f"| Pozitif ({stats['n_positive']}) | {stats['pos_mean']:.4f} | "
190
+ f"{stats['pos_min']:.4f} | {stats['pos_max']:.4f} |")
191
+ lines.append(f"| Negatif ({stats['n_negative']}) | {stats['neg_mean']:.4f} | "
192
+ f"{stats['neg_min']:.4f} | {stats['neg_max']:.4f} |")
193
+ lines.append("")
194
+ lines.append(f"Ayrışma boşluğu: en düşük pozitif **{stats['pos_min']:.4f}** ile "
195
+ f"en yüksek negatif **{stats['neg_max']:.4f}** arasında "
196
+ f"**{stats['gap']:.4f}** fark var.\n")
197
+
198
+ lines.append("## Eşik taraması\n")
199
+ lines.append("| Eşik | Yanıtlanan poz. | Doğru kaynakla | Kaçırılan poz. | Negatife yanlış yanıt | F1 | Doğruluk |")
200
+ lines.append("|---:|---:|---:|---:|---:|---:|---:|")
201
+ shown = [r for r in table if abs(r["threshold"] * 100 % 5) < 1e-6 or r["threshold"] == chosen]
202
+ for row in shown:
203
+ marker = " **←**" if row["threshold"] == chosen_row["threshold"] else ""
204
+ lines.append(
205
+ f"| {row['threshold']:.2f}{marker} | {row['answered_positives']}/{stats['n_positive']} | "
206
+ f"{row['grounded_positives']}/{stats['n_positive']} | {row['missed_positives']} | "
207
+ f"{row['false_answers_on_negatives']}/{stats['n_negative']} | "
208
+ f"{row['f1']:.3f} | {row['accuracy']:.3f} |"
209
+ )
210
+ lines.append("")
211
+
212
+ failures = [r for r in rows if r["label"] == "positive" and r["expected_rank"] is None]
213
+ lines.append("## Kaynak makale geri çağırma (retrieval)\n")
214
+ hit_at_1 = sum(1 for r in rows if r["label"] == "positive" and r["expected_rank"] == 1)
215
+ hit_at_5 = sum(1 for r in rows
216
+ if r["label"] == "positive" and r["expected_rank"] is not None and r["expected_rank"] <= 5)
217
+ lines.append(f"- Beklenen kaynak ilk sırada: **{hit_at_1}/{stats['n_positive']}**")
218
+ lines.append(f"- Beklenen kaynak ilk 5'te: **{hit_at_5}/{stats['n_positive']}**")
219
+ lines.append(f"- Beklenen kaynak ilk {ANALYSIS_TOP_K}'da bulunamadı: **{len(failures)}**\n")
220
+
221
+ lines.append("## Soru bazında en yüksek benzerlik\n")
222
+ lines.append("| ID | Tür | Soru | En yüksek benzerlik | Beklenen kaynak sırası |")
223
+ lines.append("|---|---|---|---:|---:|")
224
+ for row in rows:
225
+ rank = row["expected_rank"] if row["expected_rank"] else ("—" if row["label"] == "negative" else "bulunamadı")
226
+ question = row["question"] if len(row["question"]) <= 62 else row["question"][:59] + "…"
227
+ lines.append(
228
+ f"| {row['id']} | {'poz' if row['label'] == 'positive' else 'neg'} | {question} | "
229
+ f"{row['best_similarity']:.4f} | {rank} |"
230
+ )
231
+ lines.append("")
232
+ return "\n".join(lines)
233
+
234
+
235
+ def write_questions_parquet(questions: dict, rows: list[dict], threshold: float) -> int:
236
+ """Write the 30-question set as one flat table, with measured outcomes.
237
+
238
+ One row per question, positives and negatives together, so a reader can see
239
+ the whole evaluation set and how the system actually scored on it without
240
+ cloning the repository.
241
+ """
242
+ import pandas as pd
243
+
244
+ by_id = {row["id"]: row for row in rows}
245
+ records: list[dict] = []
246
+
247
+ for label, items in (("positive", questions["positive"]), ("negative", questions["negative"])):
248
+ for item in items:
249
+ measured = by_id.get(item["id"], {})
250
+ best = measured.get("best_similarity")
251
+ answered = bool(best is not None and best >= threshold)
252
+ # A positive is correct when the system answers it; a negative is
253
+ # correct when the system refuses.
254
+ correct = answered if label == "positive" else not answered
255
+ records.append(
256
+ {
257
+ "id": item["id"],
258
+ "label": label,
259
+ "question": item["question"],
260
+ "topic": item.get("topic", ""),
261
+ "expected_answer": item.get("expected_answer", ""),
262
+ "expected_url": item.get("expected_url", ""),
263
+ "rationale": item.get("rationale", ""),
264
+ "best_similarity": round(float(best), 4) if best is not None else None,
265
+ "expected_source_rank": measured.get("expected_rank"),
266
+ "top_match_title": measured.get("top_title") or "",
267
+ "top_match_url": measured.get("top_url") or "",
268
+ "threshold": threshold,
269
+ "system_decision": "answer" if answered else "refuse",
270
+ "expected_decision": "answer" if label == "positive" else "refuse",
271
+ "correct": correct,
272
+ }
273
+ )
274
+
275
+ frame = pd.DataFrame.from_records(records)
276
+ frame.to_parquet(QUESTIONS_PARQUET_PATH, index=False)
277
+ return len(frame)
278
+
279
+
280
+ def run_rag_probe(embedder: Embedder, store: VectorStore, questions: dict, threshold: float) -> list[dict]:
281
+ """Exercise the generation path once on a positive and once on a negative."""
282
+ from ehekim import llm
283
+
284
+ api_key = operator_secrets().get("DEEPSEEK_API_KEY")
285
+ if not api_key:
286
+ logger.warning("DEEPSEEK_API_KEY yok; RAG denemesi atlanıyor.")
287
+ return []
288
+
289
+ probes = [questions["positive"][0], questions["negative"][0]]
290
+ out: list[dict] = []
291
+ for item in probes:
292
+ outcome = search(embedder=embedder, store=store, query=item["question"],
293
+ top_k=5, threshold=threshold)
294
+ if not outcome.grounded:
295
+ out.append({"id": item["id"], "refused_before_llm": True, "answer": REFUSAL_MESSAGE_TR,
296
+ "best_similarity": outcome.best_similarity})
297
+ logger.info("[%s] eşiğin altında -> LLM çağrılmadı.", item["id"])
298
+ continue
299
+ # Same path the API uses: expand after the gate, then generate.
300
+ passages = expand_context(store, outcome.hits)
301
+ result = llm.generate(
302
+ model_key=llm.DEFAULT_MODEL_KEY,
303
+ api_key=api_key,
304
+ messages=build_rag_messages(outcome.query, passages),
305
+ timeout=180.0,
306
+ )
307
+ out.append({"id": item["id"], "refused_before_llm": False, "answer": result.content,
308
+ "model": result.model, "reasoning_tokens": result.reasoning_tokens,
309
+ "context_passages": len(passages),
310
+ "best_similarity": outcome.best_similarity})
311
+ logger.info("[%s] yanıt alındı (%s): %s", item["id"], result.model, result.content[:160])
312
+ return out
313
+
314
+
315
+ def main() -> int:
316
+ args = parse_args()
317
+ settings = get_settings()
318
+ questions = json.loads(QUESTIONS_PATH.read_text(encoding="utf-8"))
319
+
320
+ store = VectorStore(settings.chroma_dir, settings.collection_name)
321
+ if store.count() == 0:
322
+ logger.error("Koleksiyon boş. Önce scripts/ingest.py çalıştırın.")
323
+ return 1
324
+ logger.info("Koleksiyon: %s parça", store.count())
325
+
326
+ embedder = Embedder(device=args.device, batch_size=16)
327
+ started = time.time()
328
+ rows = evaluate(embedder, store, questions, args.top_k)
329
+ logger.info("%s soru değerlendirildi (%.1fs)", len(rows), time.time() - started)
330
+
331
+ pos = np.array([r["best_similarity"] for r in rows if r["label"] == "positive"])
332
+ neg = np.array([r["best_similarity"] for r in rows if r["label"] == "negative"])
333
+ stats = {
334
+ "n_positive": int(len(pos)),
335
+ "n_negative": int(len(neg)),
336
+ "pos_mean": float(pos.mean()), "pos_min": float(pos.min()), "pos_max": float(pos.max()),
337
+ "neg_mean": float(neg.mean()), "neg_min": float(neg.min()), "neg_max": float(neg.max()),
338
+ "gap": float(pos.min() - neg.max()),
339
+ }
340
+ logger.info("Pozitif ort=%.4f min=%.4f | Negatif ort=%.4f maks=%.4f | boşluk=%.4f",
341
+ stats["pos_mean"], stats["pos_min"], stats["neg_mean"], stats["neg_max"], stats["gap"])
342
+
343
+ table = sweep_thresholds(rows)
344
+ chosen, chosen_row = choose_threshold(table)
345
+ logger.info("Seçilen eşik: %.2f (F1=%.3f, doğruluk=%.3f, negatife yanlış yanıt=%s)",
346
+ chosen, chosen_row["f1"], chosen_row["accuracy"],
347
+ chosen_row["false_answers_on_negatives"])
348
+
349
+ missing = [r["id"] for r in rows if r["label"] == "positive" and r["expected_rank"] is None]
350
+ if missing:
351
+ logger.warning("Beklenen kaynağı ilk %s içinde bulunamayan pozitif sorular: %s",
352
+ args.top_k, ", ".join(missing))
353
+
354
+ rag_probe = run_rag_probe(embedder, store, questions, chosen) if args.with_rag else []
355
+
356
+ RESULTS_PATH.write_text(json.dumps(
357
+ {
358
+ "embedding_model": EMBEDDING_MODEL_ID,
359
+ "collection_chunks": store.count(),
360
+ "analysis_top_k": args.top_k,
361
+ "chosen_threshold": chosen,
362
+ "chosen_row": chosen_row,
363
+ "separation": stats,
364
+ "per_question": rows,
365
+ "sweep": table,
366
+ "rag_probe": rag_probe,
367
+ }, ensure_ascii=False, indent=2), encoding="utf-8")
368
+ REPORT_PATH.write_text(render_report(rows, table, chosen, chosen_row, stats), encoding="utf-8")
369
+ n_questions = write_questions_parquet(questions, rows, chosen)
370
+ logger.info("Yazıldı: %s, %s ve %s (%s soru)",
371
+ RESULTS_PATH.name, REPORT_PATH.name, QUESTIONS_PARQUET_PATH.name, n_questions)
372
+
373
+ correct = sum(
374
+ 1 for r in rows
375
+ if (r["label"] == "positive") == (r["best_similarity"] >= chosen)
376
+ )
377
+ logger.info("Değerlendirme kümesi doğruluğu @%.2f: %s/%s", chosen, correct, len(rows))
378
+
379
+ if chosen_row["false_answers_on_negatives"] > 0:
380
+ logger.warning("Seçilen eşikte %s negatif soru hâlâ yanıtlanıyor.",
381
+ chosen_row["false_answers_on_negatives"])
382
+ return 0
383
+
384
+
385
+ if __name__ == "__main__":
386
+ raise SystemExit(main())