Files
anorandClaude Opus 4.8 927d88d5ee chore: замер эффекта sufficiency-цикла на golden (eval_sufficiency.py)
ЧЕСТНЫЙ РЕЗУЛЬТАТ: recall@8 не изменился (69%→69%, схемы 33%→33%). Цикл добирает контекст в 6/26 вопросов, но не вытаскивает пропущенные golden-цитаты — слабость схем это retrieval/ASR-расхождение ручных разборов vs торрент, не нехватка объёма контекста. Регрессии нет; ценность цикла (если есть) — в полноте ответа на мультихоп, а не в recall.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 22:31:19 +10:00

66 lines
2.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Замер эффекта sufficiency-цикла на retrieval-recall golden-набора.
eval_rag.py меряет recall через index.search() напрямую — цикл он не видит.
Здесь: для каждого golden-вопроса сравниваем recall БАЗОВОГО top-k против
контекста ПОСЛЕ добора циклом (_expand: проверка достаточности + подзапросы).
Особый интерес — слабая категория «схема». Нужны индекс + ZAI (проверка).
python scripts/eval_sufficiency.py
"""
import json
import sys
from collections import defaultdict
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # корень в путь
from rag import config # noqa: E402
from rag.agent import make_llm # noqa: E402
from rag.agent.answer import _expand # noqa: E402
from rag.eval import question_hit # noqa: E402
from rag.index import STEmbedder, load_hybrid # noqa: E402
K = 8
def _quotes(q: dict) -> list[str]:
return [c["quote"] for c in q.get("citations", []) if c.get("quote")]
def main() -> int:
questions = json.loads(
(config.EVAL_DIR / "golden_qa.json").read_text(encoding="utf-8"))["questions"]
scored = [q for q in questions if q.get("expect") == "answer" and _quotes(q)]
print(f"вопросов с цитатами: {len(scored)}; грузим индекс + bge-m3…", flush=True)
index = load_hybrid(STEmbedder(config.EMBEDDING_MODEL))
assessor = make_llm("zai")
base, loop, expanded = [], [], 0
per_cat = defaultdict(lambda: {"base": [], "loop": []})
for q in scored:
hits = index.search(q["question"], k=K)
merged = _expand(q["question"], hits, index, assessor, K, None)
if len(merged) > len(hits):
expanded += 1
qs = _quotes(q)
b = question_hit(qs, [c.text for c, _ in hits])
l = question_hit(qs, [c.text for c, _ in merged])
base.append(b); loop.append(l)
per_cat[q["category"]]["base"].append(b)
per_cat[q["category"]]["loop"].append(l)
def pct(xs):
return 100 * sum(xs) / len(xs) if xs else 0.0
print(f"\n=== recall@{K}: цикл добрал контекст в {expanded}/{len(scored)} вопросах ===")
print(f"ВСЕГО: базлайн {pct(base):3.0f}% → с циклом {pct(loop):3.0f}%")
for cat in sorted(per_cat):
b, l = per_cat[cat]["base"], per_cat[cat]["loop"]
mark = " ↑" if pct(l) > pct(b) else ""
print(f" {cat:14} {pct(b):3.0f}% → {pct(l):3.0f}% (n={len(b)}){mark}")
return 0
if __name__ == "__main__":
raise SystemExit(main())