Uc olcum modu -- retrieval_only / oracle_context / end_to_end
Browse files at this commit31769b8e33a6312fe70bf6c363d4c3b7d7e8d0deParent: 365a9f3- feat
- uc olcum modu -- retrieval_only / oracle_context / end_to_end
2 changed files +443 -12
- src/eval/runner.py +163 -12
- tests/unit/test_eval_modes.py +280 -0
src/eval/runner.pymodified+163 -12
| @@ -172,8 +172,89 @@ def _select_judge_ids(items: list[dict]) -> set[str]: | |||
| 172 | return ids | 172 | return ids |
| 173 | 173 | ||
| 174 | 174 | ||
| 175 | +# --------------------------------------------------------------------------- | ||
| 176 | +# M0-4 (#36) — UC OLCUM MODU (RES-003 §8 "3 testi ayir") | ||
| 177 | +# | ||
| 178 | +# Tek modla kosmak "hata parser/retriever'da mi generator'da mi?" sorusunu | ||
| 179 | +# cevaplanamaz kiliyordu (EXP-010/EVAL-09): olculen citation precision 0.645 ve | ||
| 180 | +# correctness 0.838 sayilarinda hangisinin payi oldugu bilinmiyordu. | ||
| 181 | +# | ||
| 182 | +# retrieval_only : LLM HIC cagrilmaz. Ucuz, deterministik, CI'da kosabilir. | ||
| 183 | +# Yalniz "gold kanit getirildi mi" sorusunu olcer. | ||
| 184 | +# oracle_context : Baglam = GOLD span'lari tasiyan chunk'lar. "Retrieval | ||
| 185 | +# kusursuz olsaydi uretim ne kadar iyi olurdu" UST SINIRI. | ||
| 186 | +# Uretim yolu (prompt/guard/atif eslemesi/cekimserlik) | ||
| 187 | +# BIREBIR ayni -- yalniz retriever+reranker stub'lanir, boylece | ||
| 188 | +# urun kodu degismez. | ||
| 189 | +# end_to_end : gercek boru hatti (onceki tek davranis). | ||
| 190 | +# | ||
| 191 | +# Rapora `hata_atfi = e2e - oracle` yazilir: fark generator'in degil retrieval'in | ||
| 192 | +# payidir. | ||
| 193 | +# | ||
| 194 | +# DURUST SINIR: oracle modunda parent genisletme DEVRE DISI (stub chunk'larda | ||
| 195 | +# parent_id=None) -- bu bilincli. (a) parent genisletme bir RETRIEVAL kararidir, | ||
| 196 | +# uretim kalitesini izole ederken karistirmamak gerekir; (b) ACC-03 gosterdi ki | ||
| 197 | +# parent metni atifi yanlis sayfaya kaydiriyor, oracle olcumu bu gurultuyu | ||
| 198 | +# tasimamali. Yani oracle sayilari "saf yaprak span" kosuludur. | ||
| 199 | +# --------------------------------------------------------------------------- | ||
| 200 | +EVAL_MODES = ("retrieval_only", "oracle_context", "end_to_end") | ||
| 201 | + | ||
| 202 | + | ||
| 203 | +class _OracleRetriever: | ||
| 204 | + """Gercek retrieval yerine GOLD chunk'lari dondurur (skor 1.0). | ||
| 205 | + | ||
| 206 | + Skorun 1.0 olmasi bilincli: oracle kosulunda kanit TANIMI GEREGI yeterli, | ||
| 207 | + bu yuzden `abstain_score` fail-closed esigi tetiklenmemeli. Eger model yine | ||
| 208 | + de cekimser kalirsa bu GENERATOR'IN karari olur -- olcmek istedigimiz de bu.""" | ||
| 209 | + | ||
| 210 | + def __init__(self, chunk_ids: list[str]): | ||
| 211 | + self._ids = list(chunk_ids) | ||
| 212 | + | ||
| 213 | + def retrieve(self, query, top_k: int = 20, **kwargs): | ||
| 214 | + return [(cid, 1.0) for cid in self._ids[:top_k]] | ||
| 215 | + | ||
| 216 | + | ||
| 217 | +class _OracleReranker: | ||
| 218 | + """Verilen sirayi korur, skoru 1.0 verir (siralama oracle'da anlamsiz).""" | ||
| 219 | + | ||
| 220 | + def rerank(self, query, pairs): | ||
| 221 | + return [(cid, 1.0) for cid, _text in pairs] | ||
| 222 | + | ||
| 223 | + | ||
| 224 | +def _oracle_chunk_ids(gold_spans: set, chunks_by_id: dict) -> list[str]: | ||
| 225 | + """Gold span tasiyan CHILD chunk'lar, sayfa sirasinda (deterministik).""" | ||
| 226 | + hits = [(ch.page_start, cid) for cid, ch in chunks_by_id.items() | ||
| 227 | + if ch.level == "child" and set(ch.span_ids) & gold_spans] | ||
| 228 | + return [cid for _page, cid in sorted(hits)] | ||
| 229 | + | ||
| 230 | + | ||
| 231 | +def _oracle_generator(pipeline: dict, gold_spans: set): | ||
| 232 | + """Uretim Generator'inin AYNI ayarlariyla, yalniz retriever+reranker stub'li | ||
| 233 | + bir kopyasini kurar. Urun kodu degismez; prompt/guard/atif yolu birebir ayni. | ||
| 234 | + Parent genisletme dogal olarak devre disi kalir (stub chunks_by_id'de | ||
| 235 | + parent_id=None) -- bkz. yukaridaki DURUST SINIR notu.""" | ||
| 236 | + import dataclasses | ||
| 237 | + | ||
| 238 | + base = pipeline["generator"] | ||
| 239 | + ids = _oracle_chunk_ids(gold_spans, pipeline["chunks_by_id"]) | ||
| 240 | + stub_chunks = {} | ||
| 241 | + for cid in ids: | ||
| 242 | + ch = pipeline["chunks_by_id"][cid] | ||
| 243 | + stub_chunks[cid] = dataclasses.replace(ch, parent_id=None) | ||
| 244 | + gen = Generator(_OracleRetriever(ids), _OracleReranker(), stub_chunks, | ||
| 245 | + pipeline["span_meta"], base.deepseek, | ||
| 246 | + ders=base.ders, abstain_score=base.abstain_score, | ||
| 247 | + module="eval-oracle", safety_classifier=base.safety_classifier, | ||
| 248 | + context_packing=base.context_packing, | ||
| 249 | + context_max_tokens=base.context_max_tokens, | ||
| 250 | + rewriter=base.rewriter) | ||
| 251 | + return gen, ids | ||
| 252 | + | ||
| 253 | + | ||
| 175 | def _eval_item(item: dict, pipeline: dict, judge: LlmJudge | None, | 254 | def _eval_item(item: dict, pipeline: dict, judge: LlmJudge | None, |
| 176 | - judge_ids: set[str]) -> dict: | 255 | + judge_ids: set[str], mode: str = "end_to_end") -> dict: |
| 256 | + if mode not in EVAL_MODES: | ||
| 257 | + raise ValueError(f"bilinmeyen mod {mode!r}; secenekler: {EVAL_MODES}") | ||
| 177 | item_id = item["id"] | 258 | item_id = item["id"] |
| 178 | query = item["soru"] | 259 | query = item["soru"] |
| 179 | gold_spans = set(item.get("gold_kaynak_spanlar") or []) | 260 | gold_spans = set(item.get("gold_kaynak_spanlar") or []) |
| @@ -182,17 +263,67 @@ def _eval_item(item: dict, pipeline: dict, judge: LlmJudge | None, | |||
| 182 | generator = pipeline["generator"] | 263 | generator = pipeline["generator"] |
| 183 | 264 | ||
| 184 | retr_metrics = M.RetrievalMetrics() | 265 | retr_metrics = M.RetrievalMetrics() |
| 266 | + retr_post_metrics = M.RetrievalMetrics() | ||
| 185 | contexts_for_judge = [] | 267 | contexts_for_judge = [] |
| 186 | if gold_spans: | 268 | if gold_spans: |
| 187 | hits = _retry(lambda: pipeline["retriever"].retrieve(query, top_k=RETRIEVE_TOP_K), | 269 | hits = _retry(lambda: pipeline["retriever"].retrieve(query, top_k=RETRIEVE_TOP_K), |
| 188 | label=f"retrieve[{item_id}]") | 270 | label=f"retrieve[{item_id}]") |
| 189 | span_sets, page_sets = _ranked_sets_for_hits(hits, chunks_by_id) | 271 | span_sets, page_sets = _ranked_sets_for_hits(hits, chunks_by_id) |
| 190 | retr_metrics = M.compute_retrieval_metrics(span_sets, page_sets, gold_spans, gold_pages) | 272 | retr_metrics = M.compute_retrieval_metrics(span_sets, page_sets, gold_spans, gold_pages) |
| 191 | - if item_id in judge_ids: | 273 | + # M0-3 (#35): rerank ARTIK HER item'da olculur. Eskiden yalniz |
| 192 | - contexts_for_judge = _retry( | 274 | + # `item_id in judge_ids` ise cagriliyordu -> 200 item'in 178'inde |
| 193 | - lambda: rerank_select(query, hits, chunks_by_id, pipeline["reranker"], | 275 | + # reranker'in etkisi hic olculmuyordu ve benchmark.md §5'in zorunlu |
| 194 | - top_n=GEN_TOP_N, candidate_n=GEN_CANDIDATE_N), | 276 | + # ablation'i ("her bilesen kanitla girer") acik kaliyordu. |
| 195 | - label=f"rerank_select[{item_id}]") | 277 | + contexts_for_judge = _retry( |
| 278 | + lambda: rerank_select(query, hits, chunks_by_id, pipeline["reranker"], | ||
| 279 | + top_n=GEN_TOP_N, candidate_n=GEN_CANDIDATE_N), | ||
| 280 | + label=f"rerank_select[{item_id}]") | ||
| 281 | + post_span_sets = [set(c.span_ids) for c in contexts_for_judge] | ||
| 282 | + post_page_sets = [M.page_range_set(chunks_by_id[c.chunk_id].page_start, | ||
| 283 | + chunks_by_id[c.chunk_id].page_end) | ||
| 284 | + if c.chunk_id in chunks_by_id else set() | ||
| 285 | + for c in contexts_for_judge] | ||
| 286 | + retr_post_metrics = M.compute_retrieval_metrics( | ||
| 287 | + post_span_sets, post_page_sets, gold_spans, gold_pages) | ||
| 288 | + | ||
| 289 | + # retrieval_only: LLM HIC cagrilmaz -> ucuz, deterministik, CI'da kosabilir. | ||
| 290 | + if mode == "retrieval_only": | ||
| 291 | + return { | ||
| 292 | + "id": item_id, "mode": mode, "kategori": item["kategori"], | ||
| 293 | + "unite": item.get("unite"), "kazanim_kod": item.get("kazanim_kod"), | ||
| 294 | + "critical": bool(item.get("critical")), | ||
| 295 | + "beklenen_davranis": item["beklenen_davranis"], | ||
| 296 | + "zararli_kategori": item.get("zararli_kategori"), "soru": query, | ||
| 297 | + "retrieval": vars(retr_metrics), | ||
| 298 | + "retrieval_post_rerank": vars(retr_post_metrics), | ||
| 299 | + "citation": vars(M.CitationMetrics()), | ||
| 300 | + "guardrail": {"passed": None, "fail_closed": None, | ||
| 301 | + "abstained": None, "reason": "retrieval_only"}, | ||
| 302 | + "generation": {"text": "", "abstained": None, "reason": "retrieval_only", | ||
| 303 | + "n_citations": 0, "invalid_citations": [], | ||
| 304 | + "cost_usd": 0.0, "latency_s": 0.0}, | ||
| 305 | + "judge": None, | ||
| 306 | + } | ||
| 307 | + | ||
| 308 | + oracle_ids = None | ||
| 309 | + if mode == "oracle_context": | ||
| 310 | + if not gold_spans: | ||
| 311 | + # gold'u olmayan item (kapsam-disi/zararli/belirsiz) oracle'da | ||
| 312 | + # ANLAMSIZ -- atlanir, sayilara karismaz (0.0 ile karistirilmaz). | ||
| 313 | + return {"id": item_id, "mode": mode, "kategori": item["kategori"], | ||
| 314 | + "beklenen_davranis": item["beklenen_davranis"], | ||
| 315 | + "skipped": "oracle_context: gold span yok", "soru": query, | ||
| 316 | + "retrieval": vars(retr_metrics), | ||
| 317 | + "retrieval_post_rerank": vars(retr_post_metrics), | ||
| 318 | + "citation": vars(M.CitationMetrics()), | ||
| 319 | + "guardrail": {"passed": None, "fail_closed": None, | ||
| 320 | + "abstained": None, "reason": "oracle_skipped"}, | ||
| 321 | + "generation": {"text": "", "abstained": None, | ||
| 322 | + "reason": "oracle_skipped", "n_citations": 0, | ||
| 323 | + "invalid_citations": [], "cost_usd": 0.0, | ||
| 324 | + "latency_s": 0.0}, | ||
| 325 | + "judge": None} | ||
| 326 | + generator, oracle_ids = _oracle_generator(pipeline, gold_spans) | ||
| 196 | 327 | ||
| 197 | t0 = time.time() | 328 | t0 = time.time() |
| 198 | # multi_turn item'larda konuşma geçmişini ver → history-aware rewrite devreye | 329 | # multi_turn item'larda konuşma geçmişini ver → history-aware rewrite devreye |
| @@ -240,12 +371,15 @@ def _eval_item(item: dict, pipeline: dict, judge: LlmJudge | None, | |||
| 240 | } | 371 | } |
| 241 | 372 | ||
| 242 | return { | 373 | return { |
| 243 | - "id": item_id, "kategori": item["kategori"], "unite": item.get("unite"), | 374 | + "id": item_id, "mode": mode, |
| 375 | + "kategori": item["kategori"], "unite": item.get("unite"), | ||
| 244 | "kazanim_kod": item.get("kazanim_kod"), "critical": bool(item.get("critical")), | 376 | "kazanim_kod": item.get("kazanim_kod"), "critical": bool(item.get("critical")), |
| 245 | "beklenen_davranis": item["beklenen_davranis"], | 377 | "beklenen_davranis": item["beklenen_davranis"], |
| 246 | "zararli_kategori": item.get("zararli_kategori"), | 378 | "zararli_kategori": item.get("zararli_kategori"), |
| 247 | "soru": query, | 379 | "soru": query, |
| 380 | + "n_oracle_chunks": (len(oracle_ids) if oracle_ids is not None else None), | ||
| 248 | "retrieval": vars(retr_metrics), | 381 | "retrieval": vars(retr_metrics), |
| 382 | + "retrieval_post_rerank": vars(retr_post_metrics), | ||
| 249 | "citation": vars(citation_m), | 383 | "citation": vars(citation_m), |
| 250 | "guardrail": {"passed": guardrail_passed, "fail_closed": fail_closed, | 384 | "guardrail": {"passed": guardrail_passed, "fail_closed": fail_closed, |
| 251 | "abstained": result.abstained, "reason": result.reason}, | 385 | "abstained": result.abstained, "reason": result.reason}, |
| @@ -486,13 +620,17 @@ def _aggregate_table(agg: dict) -> str: | |||
| 486 | 620 | ||
| 487 | 621 | ||
| 488 | def run(golden_path: str = GOLDEN_PATH, book_path: str = BOOK_PATH, | 622 | def run(golden_path: str = GOLDEN_PATH, book_path: str = BOOK_PATH, |
| 489 | - results_dir: str = RESULTS_DIR) -> dict: | 623 | + results_dir: str = RESULTS_DIR, mode: str = "end_to_end") -> dict: |
| 624 | + """M0-4 (#36): `mode` ile uc olcum -- bkz. EVAL_MODES ve yukarisindaki not. | ||
| 625 | + `retrieval_only` LLM cagirmaz, bu yuzden API anahtari da GEREKMEZ (CI'da kosar).""" | ||
| 626 | + if mode not in EVAL_MODES: | ||
| 627 | + raise ValueError(f"bilinmeyen mod {mode!r}; secenekler: {EVAL_MODES}") | ||
| 490 | _load_dotenv() | 628 | _load_dotenv() |
| 491 | # Anahtar kontrolu saglayici-bagimsiz olmali (EXP-009): uretici artik | 629 | # Anahtar kontrolu saglayici-bagimsiz olmali (EXP-009): uretici artik |
| 492 | # LLM_BASE_URL/LLM_MODEL ile baska bir OpenAI-uyumlu uca alinabiliyor, o | 630 | # LLM_BASE_URL/LLM_MODEL ile baska bir OpenAI-uyumlu uca alinabiliyor, o |
| 493 | # durumda DEEPSEEK_API_KEY hic ayarli olmayabilir. Kaynak: providers.deepseek. | 631 | # durumda DEEPSEEK_API_KEY hic ayarli olmayabilir. Kaynak: providers.deepseek. |
| 494 | from ..providers.deepseek import _KEY_ENV_NAMES, _env | 632 | from ..providers.deepseek import _KEY_ENV_NAMES, _env |
| 495 | - if not any(_env(n) for n in _KEY_ENV_NAMES): | 633 | + if mode != "retrieval_only" and not any(_env(n) for n in _KEY_ENV_NAMES): |
| 496 | raise RuntimeError( | 634 | raise RuntimeError( |
| 497 | "API anahtari yok (.env kontrol et): " | 635 | "API anahtari yok (.env kontrol et): " |
| 498 | + " / ".join(_KEY_ENV_NAMES) | 636 | + " / ".join(_KEY_ENV_NAMES) |
| @@ -508,13 +646,14 @@ def run(golden_path: str = GOLDEN_PATH, book_path: str = BOOK_PATH, | |||
| 508 | f"{len(judge_ids)} item LLM-hakem alacak: {sorted(judge_ids)}") | 646 | f"{len(judge_ids)} item LLM-hakem alacak: {sorted(judge_ids)}") |
| 509 | 647 | ||
| 510 | pipeline = build_pipeline(book_path) | 648 | pipeline = build_pipeline(book_path) |
| 511 | - judge = LlmJudge() if judge_ids else None | 649 | + # retrieval_only LLM cagirmaz -> hakem de kurulmaz (maliyet 0, CI-dostu). |
| 650 | + judge = LlmJudge() if (judge_ids and mode != "retrieval_only") else None | ||
| 512 | 651 | ||
| 513 | items_out = [] | 652 | items_out = [] |
| 514 | for i, item in enumerate(items, start=1): | 653 | for i, item in enumerate(items, start=1): |
| 515 | print(f"[eval] ({i}/{len(items)}) {item.get('id','?')}: {str(item.get('soru',''))[:70]!r}") | 654 | print(f"[eval] ({i}/{len(items)}) {item.get('id','?')}: {str(item.get('soru',''))[:70]!r}") |
| 516 | try: | 655 | try: |
| 517 | - it_out = _eval_item(item, pipeline, judge, judge_ids) | 656 | + it_out = _eval_item(item, pipeline, judge, judge_ids, mode=mode) |
| 518 | except Exception as e: # #29: tek bozuk item run'ı düşürmesin | 657 | except Exception as e: # #29: tek bozuk item run'ı düşürmesin |
| 519 | print(f" !! HATA ({type(e).__name__}: {e}) -- item atlandı, run devam") | 658 | print(f" !! HATA ({type(e).__name__}: {e}) -- item atlandı, run devam") |
| 520 | it_out = _failed_item(item, e) | 659 | it_out = _failed_item(item, e) |
| @@ -565,7 +704,19 @@ def run(golden_path: str = GOLDEN_PATH, book_path: str = BOOK_PATH, | |||
| 565 | 704 | ||
| 566 | 705 | ||
| 567 | def main() -> None: | 706 | def main() -> None: |
| 568 | - run() | 707 | + """CLI: `python -m src.eval.runner [--mode MOD] [--golden YOL] [--book YOL]` |
| 708 | + | ||
| 709 | + M0-4 (#36) uc mod: retrieval_only (LLM'siz, ucuz, CI'da kosar) / | ||
| 710 | + oracle_context (uretim ust siniri) / end_to_end (gercek boru hatti). | ||
| 711 | + `hata_atfi = end_to_end - oracle_context` -> fark retrieval'in payidir.""" | ||
| 712 | + import argparse | ||
| 713 | + ap = argparse.ArgumentParser(prog="src.eval.runner") | ||
| 714 | + ap.add_argument("--mode", default="end_to_end", choices=list(EVAL_MODES)) | ||
| 715 | + ap.add_argument("--golden", default=GOLDEN_PATH) | ||
| 716 | + ap.add_argument("--book", default=BOOK_PATH) | ||
| 717 | + ap.add_argument("--results-dir", default=RESULTS_DIR) | ||
| 718 | + a = ap.parse_args() | ||
| 719 | + run(golden_path=a.golden, book_path=a.book, results_dir=a.results_dir, mode=a.mode) | ||
| 569 | 720 | ||
| 570 | 721 | ||
| 571 | if __name__ == "__main__": | 722 | if __name__ == "__main__": |
tests/unit/test_eval_modes.pyadded+280 -0
| @@ -0,0 +1,280 @@ | |||
| 1 | +"""M0-4 (#36) — üç ölçüm modu testleri (retrieval_only / oracle_context / end_to_end). | ||
| 2 | + | ||
| 3 | +NEDEN bu dosya var (EXP-010/EVAL-09): `RES-003 §8` "3 testi ayır" diyor ama runner | ||
| 4 | +tek mod koşuyordu (`grep oracle` → 0 sonuç). Sonuç: ölçülen citation precision | ||
| 5 | +0.645 ve correctness 0.838 sayılarında **retrieval mi generator mı** payı olduğu | ||
| 6 | +ayrılamıyordu; EXP-008'in "küçük kayma → regresyon değil" yorumu doğrulanamıyordu. | ||
| 7 | + | ||
| 8 | +Testler hermetiktir: gerçek PDF/model/LLM YOK — stub retriever/reranker/LLM ile | ||
| 9 | +`_eval_item`'in üç moddaki davranışı sınanır. | ||
| 10 | +""" | ||
| 11 | +import unittest | ||
| 12 | +from dataclasses import dataclass, field | ||
| 13 | + | ||
| 14 | +from src.eval import runner as R | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +# ── sahte boru hattı parçaları ────────────────────────────────────────────── | ||
| 18 | +@dataclass | ||
| 19 | +class _Chunk: | ||
| 20 | + chunk_id: str | ||
| 21 | + level: str | ||
| 22 | + text: str | ||
| 23 | + span_ids: list | ||
| 24 | + page_start: int | ||
| 25 | + page_end: int | ||
| 26 | + parent_id: str | None = None | ||
| 27 | + doc_id: str = "doc" | ||
| 28 | + sinif: str = "12" | ||
| 29 | + ders: str = "biyoloji" | ||
| 30 | + kaynak_turu: str = "ders_kitabi" | ||
| 31 | + kinds: list = field(default_factory=list) | ||
| 32 | + page_visual: str = "low_visual" | ||
| 33 | + approx_tokens: int = 100 | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +class _StubRetriever: | ||
| 37 | + """Gold'u 3. sırada döndürür → retrieval_only'de sıralama ölçülebilir.""" | ||
| 38 | + | ||
| 39 | + def __init__(self, order): | ||
| 40 | + self.order = order | ||
| 41 | + | ||
| 42 | + def retrieve(self, query, top_k=20, **kw): | ||
| 43 | + return [(cid, 0.5) for cid in self.order[:top_k]] | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +class _StubReranker: | ||
| 47 | + def rerank(self, query, pairs): | ||
| 48 | + return [(cid, 0.9) for cid, _t in pairs] | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +class _StubDeepSeek: | ||
| 52 | + """Kaynak 1'i atıflayan sabit cevap; kaç kez çağrıldığını sayar.""" | ||
| 53 | + | ||
| 54 | + def __init__(self, text="Hucre zari secici gecirgendir [1]."): | ||
| 55 | + self.text = text | ||
| 56 | + self.calls = 0 | ||
| 57 | + self._api_key = "test" | ||
| 58 | + | ||
| 59 | + def chat(self, prompt, system=None, **kw): | ||
| 60 | + from src.pricing import Usage | ||
| 61 | + from src.providers.deepseek import ChatResult | ||
| 62 | + self.calls += 1 | ||
| 63 | + return ChatResult(text=self.text, usage=Usage(input_cache_miss=10, output=5), | ||
| 64 | + model="stub", latency_s=0.0, raw={}) | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +def _pipeline(deepseek=None): | ||
| 68 | + """c1 gold, c2/c3 çeldirici; c1 ve c2 AYNI parent'ta (oracle'da ikisi de gerekir).""" | ||
| 69 | + chunks = { | ||
| 70 | + "c1": _Chunk("c1", "child", "gold metin bir", ["d#10.0"], 10, 10, parent_id="p1"), | ||
| 71 | + "c2": _Chunk("c2", "child", "gold metin iki", ["d#11.0"], 11, 11, parent_id="p1"), | ||
| 72 | + "c3": _Chunk("c3", "child", "alakasiz metin", ["d#90.0"], 90, 90, parent_id="p9"), | ||
| 73 | + "p1": _Chunk("p1", "parent", "parent metni", ["d#10.0", "d#11.0"], 10, 11), | ||
| 74 | + } | ||
| 75 | + span_meta = {"d#10.0": {"page": 10, "bbox": (0, 0, 1, 1)}, | ||
| 76 | + "d#11.0": {"page": 11, "bbox": (0, 0, 1, 1)}, | ||
| 77 | + "d#90.0": {"page": 90, "bbox": (0, 0, 1, 1)}} | ||
| 78 | + ds = deepseek or _StubDeepSeek() | ||
| 79 | + from src.generate import Generator | ||
| 80 | + gen = Generator(_StubRetriever(["c3", "c3", "c1", "c2"]), _StubReranker(), | ||
| 81 | + chunks, span_meta, ds, ders="biyoloji", abstain_score=0.30, | ||
| 82 | + module="test", cost_recorder=lambda **kw: None) | ||
| 83 | + return {"chunks_by_id": chunks, "span_meta": span_meta, | ||
| 84 | + "retriever": _StubRetriever(["c3", "c3", "c1", "c2"]), | ||
| 85 | + "reranker": _StubReranker(), "generator": gen, "doc": None}, ds | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +_ITEM = {"id": "t1", "soru": "Hucre zari nedir?", "kategori": "orta", | ||
| 89 | + "unite": "U1", "kazanim_kod": "1.1", "critical": False, | ||
| 90 | + "beklenen_davranis": "cevapla", | ||
| 91 | + "gold_kaynak_spanlar": ["d#10.0", "d#11.0"], "gold_sayfalar": [10, 11], | ||
| 92 | + "gold_cevap": "gold cevap", "zararli_kategori": None} | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +class ModeValidationTests(unittest.TestCase): | ||
| 96 | + def test_modes_exported(self): | ||
| 97 | + self.assertEqual(R.EVAL_MODES, | ||
| 98 | + ("retrieval_only", "oracle_context", "end_to_end")) | ||
| 99 | + | ||
| 100 | + def test_unknown_mode_rejected(self): | ||
| 101 | + pl, _ = _pipeline() | ||
| 102 | + with self.assertRaises(ValueError): | ||
| 103 | + R._eval_item(_ITEM, pl, None, set(), mode="uydurma") | ||
| 104 | + | ||
| 105 | + | ||
| 106 | +class RetrievalOnlyTests(unittest.TestCase): | ||
| 107 | + def test_no_llm_call_at_all(self): | ||
| 108 | + """Bu modun tek gerekçesi: LLM'siz, ucuz, CI'da koşabilir.""" | ||
| 109 | + pl, ds = _pipeline() | ||
| 110 | + out = R._eval_item(_ITEM, pl, None, set(), mode="retrieval_only") | ||
| 111 | + self.assertEqual(ds.calls, 0) | ||
| 112 | + self.assertEqual(out["mode"], "retrieval_only") | ||
| 113 | + self.assertEqual(out["generation"]["cost_usd"], 0.0) | ||
| 114 | + self.assertEqual(out["generation"]["reason"], "retrieval_only") | ||
| 115 | + | ||
| 116 | + def test_retrieval_metrics_still_computed(self): | ||
| 117 | + pl, _ = _pipeline() | ||
| 118 | + out = R._eval_item(_ITEM, pl, None, set(), mode="retrieval_only") | ||
| 119 | + r = out["retrieval"] | ||
| 120 | + self.assertAlmostEqual(r["recall_at_10"], 1.0) # c1+c2 ilk 10'da | ||
| 121 | + self.assertEqual(r["n_gold_spans"], 2) | ||
| 122 | + self.assertIsNotNone(r["ndcg_at_10"]) | ||
| 123 | + | ||
| 124 | + def test_citation_and_judge_are_empty_not_zero(self): | ||
| 125 | + """Ölçülmeyen şey 0.0 değil None olmalı ('ölçülmedi' != 'başarısız').""" | ||
| 126 | + pl, _ = _pipeline() | ||
| 127 | + out = R._eval_item(_ITEM, pl, None, set(), mode="retrieval_only") | ||
| 128 | + self.assertIsNone(out["citation"]["precision_page"]) | ||
| 129 | + self.assertIsNone(out["judge"]) | ||
| 130 | + self.assertIsNone(out["guardrail"]["abstained"]) | ||
| 131 | + | ||
| 132 | + | ||
| 133 | +class RerankMeasuredAlwaysTests(unittest.TestCase): | ||
| 134 | + def test_post_rerank_block_present_without_judge_ids(self): | ||
| 135 | + """M0-3 (#35): rerank ARTIK judge_ids'e bağlı değil — her item'da ölçülür. | ||
| 136 | + Eskiden 200 item'ın 178'inde reranker etkisi hiç ölçülmüyordu.""" | ||
| 137 | + pl, _ = _pipeline() | ||
| 138 | + out = R._eval_item(_ITEM, pl, None, set(), mode="retrieval_only") | ||
| 139 | + self.assertIn("retrieval_post_rerank", out) | ||
| 140 | + self.assertIsNotNone(out["retrieval_post_rerank"]["recall_at_10"]) | ||
| 141 | + | ||
| 142 | + def test_fallback_rescues_second_gold_when_candidates_are_few(self): | ||
| 143 | + """DÜRÜST DAVRANIŞ: aday az olduğunda `rerank_select`'in fallback döngüsü | ||
| 144 | + çeşitlilik kısıtının düşürdüğü ikinci gold'u geri getiriyor (ACC-06 bunu | ||
| 145 | + "fallback kurtardı, ama 4. sırada" diye not etmişti).""" | ||
| 146 | + pl, _ = _pipeline() | ||
| 147 | + out = R._eval_item(_ITEM, pl, None, set(), mode="retrieval_only") | ||
| 148 | + self.assertEqual(out["retrieval"]["all_evidence_recall_at_10"], 1.0) | ||
| 149 | + self.assertEqual(out["retrieval_post_rerank"]["all_evidence_recall_at_10"], 1.0) | ||
| 150 | + | ||
| 151 | + def test_diversity_constraint_drops_second_gold_when_parents_abundant(self): | ||
| 152 | + """ACC-06'nın gerçek koşulu: top_n'i dolduracak kadar FARKLI parent varsa | ||
| 153 | + aynı parent'taki ikinci gold kanıt eleniyor ve fallback devreye girmiyor. | ||
| 154 | + pre/post ayrımı (#35) bu kaybı artık sayıyla gösteriyor.""" | ||
| 155 | + chunks = { | ||
| 156 | + "c1": _Chunk("c1", "child", "gold bir", ["d#10.0"], 10, 10, parent_id="p1"), | ||
| 157 | + "c2": _Chunk("c2", "child", "gold iki", ["d#11.0"], 11, 11, parent_id="p1"), | ||
| 158 | + } | ||
| 159 | + order = ["c1", "c2"] | ||
| 160 | + for k in range(2, 9): # 7 farklı parent'lı çeldirici | ||
| 161 | + cid = f"d{k}" | ||
| 162 | + chunks[cid] = _Chunk(cid, "child", f"alakasiz {k}", [f"d#{90 + k}.0"], | ||
| 163 | + 90 + k, 90 + k, parent_id=f"p{k}") | ||
| 164 | + order.append(cid) | ||
| 165 | + span_meta = {u: {"page": 1, "bbox": (0, 0, 1, 1)} | ||
| 166 | + for ch in chunks.values() for u in ch.span_ids} | ||
| 167 | + ds = _StubDeepSeek() | ||
| 168 | + from src.generate import Generator | ||
| 169 | + gen = Generator(_StubRetriever(order), _StubReranker(), chunks, span_meta, ds, | ||
| 170 | + ders="biyoloji", abstain_score=0.30, module="test", | ||
| 171 | + cost_recorder=lambda **kw: None) | ||
| 172 | + pl = {"chunks_by_id": chunks, "span_meta": span_meta, | ||
| 173 | + "retriever": _StubRetriever(order), "reranker": _StubReranker(), | ||
| 174 | + "generator": gen, "doc": None} | ||
| 175 | + out = R._eval_item(_ITEM, pl, None, set(), mode="retrieval_only") | ||
| 176 | + self.assertEqual(out["retrieval"]["all_evidence_recall_at_10"], 1.0) | ||
| 177 | + self.assertEqual(out["retrieval_post_rerank"]["all_evidence_recall_at_10"], 0.0) | ||
| 178 | + # kısmi kredi veren metrik bu kaybı GİZLİYOR (0.5 "fena değil" görünür) | ||
| 179 | + self.assertAlmostEqual(out["retrieval_post_rerank"]["recall_at_10"], 0.5) | ||
| 180 | + | ||
| 181 | + | ||
| 182 | +class OracleContextTests(unittest.TestCase): | ||
| 183 | + def test_oracle_uses_gold_chunks_only(self): | ||
| 184 | + pl, ds = _pipeline() | ||
| 185 | + out = R._eval_item(_ITEM, pl, None, set(), mode="oracle_context") | ||
| 186 | + self.assertEqual(out["mode"], "oracle_context") | ||
| 187 | + self.assertEqual(out["n_oracle_chunks"], 2) # c1 + c2 | ||
| 188 | + self.assertEqual(ds.calls, 1) # üretim yolu koştu | ||
| 189 | + | ||
| 190 | + def test_oracle_chunk_ids_are_page_ordered(self): | ||
| 191 | + pl, _ = _pipeline() | ||
| 192 | + ids = R._oracle_chunk_ids({"d#10.0", "d#11.0"}, pl["chunks_by_id"]) | ||
| 193 | + self.assertEqual(ids, ["c1", "c2"]) # sayfa sırası, deterministik | ||
| 194 | + | ||
| 195 | + def test_oracle_excludes_parent_chunks(self): | ||
| 196 | + """Parent chunk gold span taşısa bile oracle'a GİRMEZ (yalnız child).""" | ||
| 197 | + pl, _ = _pipeline() | ||
| 198 | + ids = R._oracle_chunk_ids({"d#10.0"}, pl["chunks_by_id"]) | ||
| 199 | + self.assertEqual(ids, ["c1"]) | ||
| 200 | + self.assertNotIn("p1", ids) | ||
| 201 | + | ||
| 202 | + def test_oracle_disables_parent_expansion(self): | ||
| 203 | + """DÜRÜST SINIR: parent genişletme bir retrieval kararı; oracle'da kapalı | ||
| 204 | + (ACC-03'ün yanlış-sayfa gürültüsünü taşımamak için).""" | ||
| 205 | + pl, _ = _pipeline() | ||
| 206 | + gen, ids = R._oracle_generator(pl, {"d#10.0", "d#11.0"}) | ||
| 207 | + for cid in ids: | ||
| 208 | + self.assertIsNone(gen.chunks_by_id[cid].parent_id) | ||
| 209 | + | ||
| 210 | + def test_oracle_inherits_production_settings(self): | ||
| 211 | + """Oracle, üretim Generator'ının AYNI ayarlarıyla kurulmalı — aksi hâlde | ||
| 212 | + ölçülen şey üretimi temsil etmez.""" | ||
| 213 | + pl, _ = _pipeline() | ||
| 214 | + gen, _ = R._oracle_generator(pl, {"d#10.0"}) | ||
| 215 | + base = pl["generator"] | ||
| 216 | + self.assertEqual(gen.abstain_score, base.abstain_score) | ||
| 217 | + self.assertEqual(gen.ders, base.ders) | ||
| 218 | + self.assertEqual(gen.context_packing, base.context_packing) | ||
| 219 | + self.assertIs(gen.deepseek, base.deepseek) | ||
| 220 | + | ||
| 221 | + def test_item_without_gold_is_skipped_not_scored(self): | ||
| 222 | + """Kapsam-dışı/zararlı item oracle'da ANLAMSIZ → atlanır, 0.0 sayılmaz.""" | ||
| 223 | + edge = dict(_ITEM, id="e1", beklenen_davranis="cekimser", | ||
| 224 | + gold_kaynak_spanlar=[], gold_sayfalar=[], gold_cevap=None) | ||
| 225 | + pl, ds = _pipeline() | ||
| 226 | + out = R._eval_item(edge, pl, None, set(), mode="oracle_context") | ||
| 227 | + self.assertIn("skipped", out) | ||
| 228 | + self.assertEqual(ds.calls, 0) | ||
| 229 | + self.assertIsNone(out["citation"]["precision_page"]) | ||
| 230 | + | ||
| 231 | + | ||
| 232 | +class EndToEndTests(unittest.TestCase): | ||
| 233 | + def test_default_mode_is_end_to_end(self): | ||
| 234 | + pl, ds = _pipeline() | ||
| 235 | + out = R._eval_item(_ITEM, pl, None, set()) | ||
| 236 | + self.assertEqual(out["mode"], "end_to_end") | ||
| 237 | + self.assertEqual(ds.calls, 1) | ||
| 238 | + self.assertIsNone(out["n_oracle_chunks"]) | ||
| 239 | + | ||
| 240 | + def test_uses_real_retriever_not_oracle(self): | ||
| 241 | + pl, _ = _pipeline() | ||
| 242 | + e2e = R._eval_item(_ITEM, pl, None, set()) | ||
| 243 | + oracle = R._eval_item(_ITEM, pl, None, set(), mode="oracle_context") | ||
| 244 | + # e2e retriever alakasız c3'ü de getiriyor, oracle getirmiyor | ||
| 245 | + self.assertIsNone(e2e["n_oracle_chunks"]) | ||
| 246 | + self.assertEqual(oracle["n_oracle_chunks"], 2) | ||
| 247 | + | ||
| 248 | + def test_error_attribution_is_computable(self): | ||
| 249 | + """#36'nın amacı: e2e ile oracle arasındaki fark retrieval'ın payı.""" | ||
| 250 | + pl, _ = _pipeline() | ||
| 251 | + e2e = R._eval_item(_ITEM, pl, None, set()) | ||
| 252 | + oracle = R._eval_item(_ITEM, pl, None, set(), mode="oracle_context") | ||
| 253 | + for out in (e2e, oracle): | ||
| 254 | + self.assertIsNotNone(out["citation"]["recall_page"]) | ||
| 255 | + # ikisi de sayı döndürüyorsa fark hesaplanabilir (asıl iddia bu) | ||
| 256 | + fark = (oracle["citation"]["recall_page"] - e2e["citation"]["recall_page"]) | ||
| 257 | + self.assertIsInstance(fark, float) | ||
| 258 | + | ||
| 259 | + | ||
| 260 | +class RunSignatureTests(unittest.TestCase): | ||
| 261 | + def test_run_rejects_bad_mode_before_any_work(self): | ||
| 262 | + with self.assertRaises(ValueError): | ||
| 263 | + R.run(mode="yok") | ||
| 264 | + | ||
| 265 | + def test_retrieval_only_does_not_require_api_key(self): | ||
| 266 | + """CI'da anahtar olmadan koşabilmeli — bu modun varlık sebebi.""" | ||
| 267 | + import os | ||
| 268 | + from unittest import mock | ||
| 269 | + clean = {k: "" for k in ("LLM_API_KEY", "DEEPSEEK_API_KEY", "NVIDIA_API_KEY")} | ||
| 270 | + with mock.patch.dict(os.environ, clean): | ||
| 271 | + # anahtar yok: end_to_end RuntimeError, retrieval_only kitap yokluğunda | ||
| 272 | + # FileNotFoundError'a kadar ilerler (yani anahtar kapısını GEÇER) | ||
| 273 | + with self.assertRaises(RuntimeError): | ||
| 274 | + R.run(mode="end_to_end", book_path="/olmayan/kitap.pdf") | ||
| 275 | + with self.assertRaises(FileNotFoundError): | ||
| 276 | + R.run(mode="retrieval_only", book_path="/olmayan/kitap.pdf") | ||
| 277 | + | ||
| 278 | + | ||
| 279 | +if __name__ == "__main__": | ||
| 280 | + unittest.main() | ||