ashe0042 commited on
Commit
1a8d5dc
·
1 Parent(s): ecf08d3

Benchmark run complete: 595/600 evaluations, grounded cuts misstatements 56% vs naive

Browse files
Files changed (2) hide show
  1. scripts/run_benchmark.py +189 -0
  2. src/db.py +11 -1
scripts/run_benchmark.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Runs the full benchmark: all gold queries through all 5 RAG configs,
3
+ scored by the two-layer judge in src/judge.py.
4
+
5
+ Writes results/raw_results.jsonl (one line per (query, config) pair) and
6
+ results/summary.json (taxonomy bucket counts per config).
7
+
8
+ Resumable: on (re)start, already-written (query_id, config_name) pairs in
9
+ raw_results.jsonl are skipped, so a crash mid-run doesn't redo finished work.
10
+ """
11
+
12
+ import json
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
17
+
18
+ from db import get_connection
19
+ from eval import evaluate_query
20
+ from judge import evaluate_answer
21
+
22
+ QUERIES_PATH = Path(__file__).resolve().parent.parent / "queries" / "gold_set.jsonl"
23
+ RESULTS_DIR = Path(__file__).resolve().parent.parent / "results"
24
+ RAW_RESULTS_PATH = RESULTS_DIR / "raw_results.jsonl"
25
+ SUMMARY_PATH = RESULTS_DIR / "summary.json"
26
+
27
+ CONFIG_NAMES = ["naive", "hybrid", "rerank", "kg_augmented", "grounded"]
28
+ TAXONOMY_BUCKETS = [
29
+ "correct_and_faithful",
30
+ "fabricated_citation",
31
+ "misstated_obligation",
32
+ "missing_citation",
33
+ "real_but_irrelevant",
34
+ ]
35
+
36
+
37
+ def load_gold_queries() -> list[dict]:
38
+ with open(QUERIES_PATH) as f:
39
+ return [json.loads(line) for line in f if line.strip()]
40
+
41
+
42
+ def load_completed_pairs() -> set[tuple[str, str]]:
43
+ completed = set()
44
+ if not RAW_RESULTS_PATH.exists():
45
+ return completed
46
+
47
+ with open(RAW_RESULTS_PATH) as f:
48
+ for line in f:
49
+ line = line.strip()
50
+ if not line:
51
+ continue
52
+ record = json.loads(line)
53
+ if "taxonomy_bucket" in record:
54
+ completed.add((record["query_id"], record["config_name"]))
55
+
56
+ return completed
57
+
58
+
59
+ def compute_summary() -> dict:
60
+ counts = {
61
+ config_name: {bucket: 0 for bucket in TAXONOMY_BUCKETS}
62
+ for config_name in CONFIG_NAMES
63
+ }
64
+ totals = {config_name: 0 for config_name in CONFIG_NAMES}
65
+
66
+ with open(RAW_RESULTS_PATH) as f:
67
+ for line in f:
68
+ line = line.strip()
69
+ if not line:
70
+ continue
71
+ record = json.loads(line)
72
+ bucket = record.get("taxonomy_bucket")
73
+ config_name = record["config_name"]
74
+ if bucket is None or config_name not in counts:
75
+ continue
76
+ totals[config_name] += 1
77
+ counts[config_name][bucket] += 1
78
+
79
+ return {
80
+ config_name: {"total": totals[config_name], **counts[config_name]}
81
+ for config_name in CONFIG_NAMES
82
+ }
83
+
84
+
85
+ def run_benchmark() -> None:
86
+ RESULTS_DIR.mkdir(exist_ok=True)
87
+
88
+ gold_queries = load_gold_queries()
89
+ total_queries = len(gold_queries)
90
+ completed = load_completed_pairs()
91
+
92
+ with open(RAW_RESULTS_PATH, "a") as out_f:
93
+ for i, gold_query in enumerate(gold_queries, start=1):
94
+ pending_configs = [
95
+ config_name
96
+ for config_name in CONFIG_NAMES
97
+ if (gold_query["id"], config_name) not in completed
98
+ ]
99
+
100
+ if not pending_configs:
101
+ print(f"[{i}/{total_queries}] {gold_query['id']} | SKIPPED (already complete)")
102
+ continue
103
+
104
+ evaluation = evaluate_query(gold_query["question"])
105
+
106
+ conn = get_connection()
107
+ try:
108
+ for config_name in CONFIG_NAMES:
109
+ if (gold_query["id"], config_name) in completed:
110
+ print(f"[{i}/{total_queries}] {gold_query['id']} | {config_name} | SKIPPED (resume)")
111
+ continue
112
+
113
+ config_result = evaluation["results"][config_name]
114
+
115
+ if "error" in config_result:
116
+ record = {
117
+ "query_id": gold_query["id"],
118
+ "config_name": config_name,
119
+ "error": config_result["error"],
120
+ }
121
+ out_f.write(json.dumps(record) + "\n")
122
+ out_f.flush()
123
+ print(f"[{i}/{total_queries}] {gold_query['id']} | {config_name} | ERROR")
124
+ continue
125
+
126
+ try:
127
+ judged = evaluate_answer(
128
+ query_id=gold_query["id"],
129
+ question=gold_query["question"],
130
+ gold_answer=gold_query["gold_answer"],
131
+ gold_citations=gold_query["gold_citations"],
132
+ rag_answer=config_result["answer"],
133
+ config_name=config_name,
134
+ conn=conn,
135
+ )
136
+ except Exception as e:
137
+ record = {
138
+ "query_id": gold_query["id"],
139
+ "config_name": config_name,
140
+ "error": str(e),
141
+ }
142
+ out_f.write(json.dumps(record) + "\n")
143
+ out_f.flush()
144
+ print(f"[{i}/{total_queries}] {gold_query['id']} | {config_name} | ERROR")
145
+ continue
146
+
147
+ bucket = judged["taxonomy_bucket"]
148
+
149
+ record = {
150
+ "query_id": gold_query["id"],
151
+ "question": gold_query["question"],
152
+ "gold_answer": gold_query["gold_answer"],
153
+ "gold_citations": gold_query["gold_citations"],
154
+ "config_name": config_name,
155
+ "rag_answer": config_result["answer"],
156
+ "taxonomy_bucket": bucket,
157
+ "fabrication_rate": judged["layer1"]["fabrication_rate"],
158
+ "layer2_judgment": judged["layer2"]["judgment"],
159
+ "layer2_confidence": judged["layer2"]["confidence"],
160
+ "layer2_reasoning": judged["layer2"]["reasoning"],
161
+ "retrieved_paragraph_ids": [
162
+ chunk["paragraph_id"] for chunk in config_result["retrieved_chunks"]
163
+ ],
164
+ "stratum": gold_query["stratum"],
165
+ }
166
+ out_f.write(json.dumps(record) + "\n")
167
+ out_f.flush()
168
+
169
+ print(f"[{i}/{total_queries}] {gold_query['id']} | {config_name} | {bucket}")
170
+ finally:
171
+ conn.close()
172
+
173
+ summary = compute_summary()
174
+
175
+ with open(SUMMARY_PATH, "w") as f:
176
+ json.dump(summary, f, indent=2)
177
+
178
+ print()
179
+ header = f"{'config':<15}{'total':>8}" + "".join(f"{b:>22}" for b in TAXONOMY_BUCKETS)
180
+ print(header)
181
+ for config_name in CONFIG_NAMES:
182
+ row = f"{config_name:<15}{summary[config_name]['total']:>8}" + "".join(
183
+ f"{summary[config_name][b]:>22}" for b in TAXONOMY_BUCKETS
184
+ )
185
+ print(row)
186
+
187
+
188
+ if __name__ == "__main__":
189
+ run_benchmark()
src/db.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import psycopg2
3
  from dotenv import load_dotenv
4
 
@@ -8,7 +9,16 @@ _DATABASE_URL = os.environ["DATABASE_URL"]
8
 
9
 
10
  def get_connection() -> psycopg2.extensions.connection:
11
- return psycopg2.connect(_DATABASE_URL)
 
 
 
 
 
 
 
 
 
12
 
13
 
14
  def _enable_pgvector(conn: psycopg2.extensions.connection) -> None:
 
1
  import os
2
+ import time
3
  import psycopg2
4
  from dotenv import load_dotenv
5
 
 
9
 
10
 
11
  def get_connection() -> psycopg2.extensions.connection:
12
+ last_error = None
13
+ for attempt in range(3):
14
+ try:
15
+ return psycopg2.connect(_DATABASE_URL)
16
+ except psycopg2.OperationalError as e:
17
+ last_error = e
18
+ if attempt < 2:
19
+ print(f" DB connection attempt {attempt+1} failed, retrying in 5s...")
20
+ time.sleep(5)
21
+ raise last_error
22
 
23
 
24
  def _enable_pgvector(conn: psycopg2.extensions.connection) -> None: