File size: 16,323 Bytes
a805048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""
Runs the complete experimental evaluation of EvidenceGuard AI.

Steps
  1. Stratified DEV/TEST split of the 100 questions (30% per category, rounded: 29 dev / 71 test, seed 42).
  2. Threshold calibration of the verifier on the DEV split only (grid search, objective =
     behaviour accuracy of the complete system). Saved to results/calibrated_thresholds.json.
  3. Runs the 4 configurations on all 100 questions:
        1. Baseline RAG   2. RAG + hybrid retrieval & reranking
        3. RAG + evidence verification   4. EvidenceGuard (complete)
  4. Writes metrics (all / test / dev), per-question results, category breakdown,
     error analysis and failure cases to results/, and charts to results/charts/.

Usage:
  python scripts/run_evaluation.py                       # auto backend
  python scripts/run_evaluation.py --backend lite        # fully offline components
  python scripts/run_evaluation.py --backend full --llm hf_api   # HF models + HF Inference API
"""
from __future__ import annotations

import argparse
import csv
import itertools
import json
import platform
import random
import sys
import time
from collections import Counter, defaultdict
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

import config  # noqa: E402
from src.evaluation import aggregate, by_category, classify_error, score_question  # noqa: E402
from src.text_utils import normalize  # noqa: E402

RES = config.RESULTS_DIR
CH = config.CHARTS_DIR
ORDER = ["baseline", "rerank", "verify", "full"]
SHORT = {"baseline": "Baseline RAG", "rerank": "+ Reranking", "verify": "+ Verification", "full": "EvidenceGuard"}
COLORS = {"baseline": "#2a78d6", "rerank": "#eb6834", "verify": "#1baf7a", "full": "#eda100"}  # validated palette


def split(questions, dev_frac=0.3, seed=42):
    rng = random.Random(seed)
    by = defaultdict(list)
    for q in questions:
        by[q["category"]].append(q["id"])
    dev = set()
    for cat, ids in sorted(by.items()):
        ids = sorted(ids)
        rng.shuffle(ids)
        dev |= set(ids[: round(len(ids) * dev_frac)])
    return dev


def relevance_fn_factory(kb, questions):
    from sklearn.feature_extraction.text import TfidfVectorizer
    from sklearn.metrics.pairwise import cosine_similarity
    vec = TfidfVectorizer(stop_words="english", sublinear_tf=True).fit(
        [c.text for c in kb.chunks] + [q["question"] for q in questions])

    def f(q, a):
        return float(cosine_similarity(vec.transform([q]), vec.transform([a]))[0, 0])
    return f


def calibrate(system, dev_qs, page_text):
    """Grid search on DEV only. Two stages: sufficiency/abstention, then conflict sensitivity."""
    base = dict(system.verifier.th)
    pipe = system.pipelines["full"]

    def score(th):
        system.set_thresholds(th)
        rows = [score_question(q, pipe.answer(q["question"]), page_text) for q in dev_qs]
        a = aggregate(rows)
        return a["behaviour_accuracy"], a["abstention_accuracy"], a["unsupported_answer_rate"]

    best, best_s = dict(base), (-1, -1, 9)
    grid1 = itertools.product([0.15, 0.2, 0.25, 0.3, 0.35], [0.4, 0.45, 0.5, 0.55, 0.6, 0.65], [0.3, 0.35, 0.4])
    for rel, cov, conf in grid1:
        th = dict(base, min_relevance=rel, min_coverage=cov, partial_coverage=max(0.0, cov - 0.1),
                  min_confidence=conf)
        s = score(th)
        if (s[0], s[1], -s[2]) > (best_s[0], best_s[1], -best_s[2]):
            best, best_s = th, s
    for sc, sim in itertools.product([0.25, 0.3, 0.35, 0.45], [0.25, 0.3, 0.4]):
        th = dict(best, conflict_sentence_coverage=sc, conflict_topic_sim=sim)
        s = score(th)
        if (s[0], s[1], -s[2]) > (best_s[0], best_s[1], -best_s[2]):
            best, best_s = th, s
    system.set_thresholds(best)
    return best, {"dev_behaviour_accuracy": best_s[0], "dev_abstention_accuracy": best_s[1],
                  "dev_unsupported_rate": best_s[2]}


# ------------------------------------------------------------------------------------ charts
def charts(metrics_all, cat_tables, rows_by_cfg):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    plt.rcParams.update({"font.size": 10, "axes.spines.top": False, "axes.spines.right": False,
                         "axes.edgecolor": "#8a8986", "axes.labelcolor": "#0b0b0b", "xtick.color": "#52514e",
                         "ytick.color": "#52514e", "figure.facecolor": "#fcfcfb", "axes.facecolor": "#fcfcfb",
                         "grid.color": "#e6e5e1"})

    def grouped(metric_keys, labels, title, fname, ylim=1.0, pct=True):
        fig, ax = plt.subplots(figsize=(9, 4.2))
        n = len(ORDER)
        width = 0.8 / n
        for i, cfg in enumerate(ORDER):
            vals = [metrics_all[cfg][k] if metrics_all[cfg][k] is not None else 0 for k in metric_keys]
            xs = [j + (i - (n - 1) / 2) * width for j in range(len(metric_keys))]
            bars = ax.bar(xs, vals, width * 0.92, color=COLORS[cfg], label=SHORT[cfg], zorder=3)
            for b, v in zip(bars, vals):
                ax.text(b.get_x() + b.get_width() / 2, b.get_height() + ylim * 0.012,
                        f"{v:.2f}" if pct else f"{v:.3f}", ha="center", va="bottom", fontsize=7.5, color="#52514e")
        ax.set_xticks(range(len(metric_keys)), labels)
        ax.set_ylim(0, ylim * 1.12)
        ax.grid(axis="y", zorder=0)
        ax.set_title(title, loc="left", fontsize=12, color="#0b0b0b")
        ax.legend(frameon=False, ncol=4, loc="upper left", bbox_to_anchor=(0, -0.12))
        fig.tight_layout()
        fig.savefig(CH / fname, dpi=150)
        plt.close(fig)

    grouped(["precision_at_k", "recall_at_k", "mrr", "context_precision", "context_recall"],
            ["Precision@5", "Recall@5", "MRR", "Context precision", "Context recall"],
            "Retrieval quality (all 100 questions)", "retrieval_comparison.png")
    grouped(["answer_correctness", "behaviour_accuracy", "faithfulness", "grounded_faithfulness", "answer_relevance"],
            ["Answer correctness", "Behaviour accuracy", "Faithfulness\n(to context)",
             "Evidence-grounded\nfaithfulness", "Answer relevance\n(lexical proxy)"],
            "Answer quality (all 100 questions)", "answer_quality_comparison.png")
    grouped(["unsupported_answer_rate", "abstention_accuracy", "abstention_f1", "contradiction_f1",
             "citation_support_accuracy"],
            ["Unsupported answer\nrate (lower = better)", "Abstention\naccuracy", "Abstention F1",
             "Contradiction\ndetection F1", "Citation support\naccuracy"],
            "Reliability (all 100 questions)", "reliability_comparison.png")
    tmax = max(metrics_all[c]["avg_response_time_s"] for c in ORDER)
    grouped(["avg_response_time_s", "avg_retrieval_time_s", "avg_verification_time_s", "avg_generation_time_s"],
            ["Total", "Retrieval + rerank", "Verification", "Generation"],
            "Average time per question (seconds)", "response_time.png", ylim=tmax, pct=False)

    # behaviour accuracy by category
    cats = ["answerable", "multi_passage", "misleading", "conflicting", "missing"]
    fig, ax = plt.subplots(figsize=(9, 4.2))
    width = 0.2
    for i, cfg in enumerate(ORDER):
        vals = [cat_tables[cfg][c]["behaviour_accuracy"] for c in cats]
        xs = [j + (i - 1.5) * width for j in range(len(cats))]
        bars = ax.bar(xs, vals, width * 0.92, color=COLORS[cfg], label=SHORT[cfg], zorder=3)
        for b, v in zip(bars, vals):
            ax.text(b.get_x() + b.get_width() / 2, b.get_height() + 0.012, f"{v:.2f}", ha="center",
                    va="bottom", fontsize=7.5, color="#52514e")
    ax.set_xticks(range(len(cats)), ["Answerable\n(30)", "Multi-passage\n(20)", "Misleading\n(15)",
                                     "Conflicting\n(20)", "Missing info\n(15)"])
    ax.set_ylim(0, 1.12)
    ax.grid(axis="y", zorder=0)
    ax.set_title("Expected-behaviour accuracy by question category", loc="left", fontsize=12)
    ax.legend(frameon=False, ncol=4, loc="upper left", bbox_to_anchor=(0, -0.14))
    fig.tight_layout()
    fig.savefig(CH / "category_breakdown.png", dpi=150)
    plt.close(fig)

    # error taxonomy for baseline vs full
    fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), sharex=True)
    kinds = ["answered unanswerable question (hallucination risk)", "missed conflict", "over-abstention (answer was available)",
             "incomplete answer (some key facts missing)", "wrong/irrelevant answer content",
             "retrieval failure (no gold page retrieved)"]
    short = ["Answered unanswerable", "Missed conflict", "Over-abstention", "Incomplete answer",
             "Wrong content", "Retrieval failure"]
    mx = 0
    counts = {}
    for cfg in ("baseline", "full"):
        c = Counter(classify_error(r) for r in rows_by_cfg[cfg])
        counts[cfg] = [c.get(k, 0) for k in kinds]
        mx = max(mx, max(counts[cfg]))
    for ax, cfg in zip(axes, ("baseline", "full")):
        bars = ax.barh(short[::-1], counts[cfg][::-1], color=COLORS[cfg], zorder=3, height=0.6)
        for b, v in zip(bars, counts[cfg][::-1]):
            ax.text(v + mx * 0.02, b.get_y() + b.get_height() / 2, str(v), va="center", fontsize=8, color="#52514e")
        ax.set_title(f"{SHORT[cfg]} - errors ({sum(counts[cfg])})", loc="left", fontsize=11)
        ax.grid(axis="x", zorder=0)
        ax.set_xlim(0, mx * 1.2 + 1)
    fig.tight_layout()
    fig.savefig(CH / "error_analysis.png", dpi=150)
    plt.close(fig)


# ------------------------------------------------------------------------------------ main
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--backend", default=config.EG_BACKEND, choices=["auto", "full", "lite"])
    ap.add_argument("--llm", default=config.LLM_BACKEND, choices=["auto", "hf_api", "local", "extractive"])
    ap.add_argument("--no-calibrate", action="store_true")
    args = ap.parse_args()

    from src.system import EvidenceGuardSystem
    questions = json.loads(config.EVAL_DATA_PATH.read_text())
    import os
    os.environ["EG_IGNORE_CALIBRATION"] = "1"          # start from defaults; calibrate fresh
    t0 = time.time()
    system = EvidenceGuardSystem(args.backend, args.llm, thresholds=dict(config.THRESHOLDS))
    print("Components:", json.dumps(system.component_names(), indent=1))
    page_text = {(d, i + 1): normalize(t) for d, info in system.kb.docs.items() for i, t in enumerate(info.page_texts)}
    rel_fn = relevance_fn_factory(system.kb, questions)

    dev_ids = split(questions)
    dev_qs = [q for q in questions if q["id"] in dev_ids]
    if not args.no_calibrate:
        th, dev_scores = calibrate(system, dev_qs, page_text)
        (RES / "calibrated_thresholds.json").write_text(json.dumps(
            {"backend": system.effective_backend, "thresholds": th, "dev_ids": sorted(dev_ids), **dev_scores}, indent=2))
        print("Calibrated on DEV:", dev_scores)

    rows_by_cfg, per_q = {}, []
    for cfg in ORDER:
        rows = []
        for q in questions:
            r = system.pipelines[cfg].answer(q["question"])
            row = score_question(q, r, page_text, rel_fn)
            row["config"] = cfg
            row["split"] = "dev" if q["id"] in dev_ids else "test"
            row["error_type"] = classify_error(row)
            rows.append(row)
        rows_by_cfg[cfg] = rows
        per_q += rows
        print(f"{cfg:9s} done")

    metrics = {"all": {}, "test": {}, "dev": {}}
    cats = {}
    for cfg in ORDER:
        rows = rows_by_cfg[cfg]
        metrics["all"][cfg] = aggregate(rows)
        metrics["test"][cfg] = aggregate([r for r in rows if r["split"] == "test"])
        metrics["dev"][cfg] = aggregate([r for r in rows if r["split"] == "dev"])
        cats[cfg] = by_category(rows)

    meta = {
        "note": "Experiments use SYNTHETIC documents of a fictional university. Results do not establish "
                "real-world university policy accuracy.",
        "components": system.component_names(),
        "backend": args.backend, "llm_backend": args.llm,
        "thresholds": system.verifier.th, "n_questions": len(questions),
        "dev_questions": len(dev_ids), "test_questions": len(questions) - len(dev_ids),
        "python": platform.python_version(), "machine": platform.machine(),
        "cpu_count": os.cpu_count(), "runtime_s": round(time.time() - t0, 1),
        "date": time.strftime("%Y-%m-%d %H:%M"),
    }
    (RES / "metrics.json").write_text(json.dumps(
        {"meta": meta, "metrics": metrics, "by_category": cats, "config_names": SHORT}, indent=2))

    keys = list(metrics["all"]["full"].keys())
    with open(RES / "metrics.csv", "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["split", "configuration"] + keys)
        for sp in ("all", "test", "dev"):
            for cfg in ORDER:
                w.writerow([sp, SHORT[cfg]] + [metrics[sp][cfg][k] for k in keys])
    with open(RES / "category_breakdown.csv", "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["configuration", "category", "n", "answer_correctness", "behaviour_accuracy",
                    "unsupported_rate", "abstention_rate"])
        for cfg in ORDER:
            for c, v in cats[cfg].items():
                w.writerow([SHORT[cfg], c, v["n"], v["answer_correctness"], v["behaviour_accuracy"],
                            v["unsupported_rate"], v["abstention_rate"]])
    fields = ["config", "split", "id", "category", "question", "expected_behaviour", "decision", "abstained",
              "conflict_flagged", "correct", "behaviour_ok", "unsupported", "error_type", "keywords_hit",
              "keywords_total", "precision_at_k", "recall_at_k", "mrr", "faithfulness", "grounded_faithfulness",
              "citation_support", "confidence", "t_total", "answer", "expected_answer", "explanation", "retrieved"]
    with open(RES / "per_question_results.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
        w.writeheader()
        w.writerows(per_q)

    # error analysis + failure cases
    err = {cfg: Counter(r["error_type"] for r in rows_by_cfg[cfg]) for cfg in ORDER}
    with open(RES / "error_analysis.csv", "w", newline="") as f:
        w = csv.writer(f)
        types = sorted({t for c in err.values() for t in c})
        w.writerow(["error_type"] + [SHORT[c] for c in ORDER])
        for t in types:
            w.writerow([t] + [err[c].get(t, 0) for c in ORDER])
    fails = []
    for r in rows_by_cfg["full"]:
        if not r["behaviour_ok"]:
            b = next(x for x in rows_by_cfg["baseline"] if x["id"] == r["id"])
            fails.append({k: r[k] for k in ("id", "category", "question", "expected_behaviour", "error_type",
                                            "decision", "answer", "expected_answer", "explanation", "retrieved")}
                         | {"baseline_answer": b["answer"], "baseline_ok": b["behaviour_ok"]})
    wins = [{"id": r["id"], "category": r["category"], "question": r["question"],
             "baseline_answer": b["answer"], "evidenceguard_answer": r["answer"], "explanation": r["explanation"]}
            for r, b in zip(rows_by_cfg["full"], rows_by_cfg["baseline"]) if r["behaviour_ok"] and not b["behaviour_ok"]]
    (RES / "failure_cases.json").write_text(json.dumps({"evidenceguard_failures": fails,
                                                         "evidenceguard_fixes_over_baseline": wins}, indent=2))
    charts(metrics["all"], cats, rows_by_cfg)

    print("\n=== ALL 100 questions ===")
    show = ["recall_at_k", "mrr", "answer_correctness", "behaviour_accuracy", "grounded_faithfulness",
            "unsupported_answer_rate", "abstention_accuracy", "contradiction_f1", "citation_support_accuracy",
            "avg_response_time_s"]
    print(f"{'config':16s}" + "".join(f"{k[:14]:>15s}" for k in show))
    for sp in ("all", "test"):
        print(f"--- {sp}")
        for cfg in ORDER:
            print(f"{SHORT[cfg]:16s}" + "".join(f"{(metrics[sp][cfg][k] if metrics[sp][cfg][k] is not None else float('nan')):15.3f}" for k in show))
    print("\nErrors:", {SHORT[c]: dict(err[c]) for c in ("baseline", "full")})
    print(f"Runtime {meta['runtime_s']} s")


if __name__ == "__main__":
    main()