forge
Explore
Log in

Don't you dare go Hollow

Seçici-risk + mutasyon ölçüm altyapısı (literatür çerçevesi)

Browse files at this commit

c177e5bfe3b4b235a192b71e6123f66fc453e1b9Kadir YönakParent: a45794c
  • feat
    • seçici-risk + mutasyon ölçüm altyapısı (literatür çerçevesi)
Show full message
feat(eval): seçici-risk + mutasyon ölçüm altyapısı (literatür çerçevesi)

Kullanıcının selective-classification/abstention çerçevesine göre ölçüm eklendi:
- evaluation/selective.py: risk-coverage eğrisi + AURC + işletim seçici-risk +
  OOS false-accept (near/far ayrımı) + rule-of-three üst sınır. `--selective`.
- evaluation/mutation.py: kritik invariant mutasyon testi (kuralı boz -> probe
  yakalar mı). mutation_score. `--mutation`.
- test_selective_mutation.py: mutation_score=%100 + op seçici-risk<=%1 + AURC<=0.02
  + OOS false-accept ölçülür (regresyon guard'ı). 357 test yeşil.

İlk ölçüm: AURC 0.0000; op seçici-risk %0.50 (1/199); mutation score 6/6 %100;
OOS false-accept %7.69 (2/26, near-OOS) -> hedef <=%1, optimize edilecek boşluk.
src/evaluation/mutation.pyadded+184 -0
@@ -0,0 +1,184 @@
1+"""Mutasyon testi — kritik invariant'ların test/probe gücünü ölçer.
2+
3+Fikir (CheckList/mutation testing): kuralları KASITLI boz, kritik invariant
4+probe'larının bunu YAKALADIĞINI doğrula. Yakalanan mutasyon = "öldürülen".
5+ mutation_score = öldürülen / toplam
6+Kritik invariant'lar için hedef %100'dür: yani gizlilik/collision/rol koruması
7+sağlayan hiçbir kural, testler fark etmeden bozulamamalı.
8+
9+Bu harness kural KATALOĞUNU (`rules._RAW_RULES`) bellek içinde mutasyona uğratır,
10+yeniden derler, `get_role_space` önbelleğini temizler, probe'ları koşar ve GERİ ALIR.
11+Kaynak dosyaya DOKUNMAZ. Çalıştırma: ``python -m src.evaluation.mutation``.
12+"""
13+
14+from __future__ import annotations
15+
16+import copy
17+from typing import Any, Callable
18+
19+from .. import rules as rules_mod
20+from ..engine import Engine
21+from ..role_spaces import get_role_space
22+
23+
24+# --- Kritik invariant probe'ları -------------------------------------------
25+# (ad, sorgu, rol, invariant(resp)->bool). invariant, DOĞRU davranışta True döner;
26+# mutasyon onu bozarsa False (yakalandı).
27+Probe = tuple[str, str, str, Callable[[dict[str, Any]], bool]]
28+
29+def _intent_is(name: str) -> Callable[[dict[str, Any]], bool]:
30+ return lambda r: r.get("intent") == name
31+
32+def _intent_not(name: str) -> Callable[[dict[str, Any]], bool]:
33+ return lambda r: r.get("intent") != name
34+
35+def _safety_cat(cat: str) -> Callable[[dict[str, Any]], bool]:
36+ return lambda r: (r.get("safety") or {}).get("category") == cat
37+
38+
39+PROBES: list[Probe] = [
40+ ("privacy_arkadas", "Sınıf arkadaşımın devamsızlığını söyle", "ogrenci",
41+ _intent_is("privacy_security")),
42+ ("privacy_baska_not", "Başka bir öğrencinin notunu görebilir miyim", "ogrenci",
43+ _intent_is("privacy_security")),
44+ ("exam_rejoin", "Sınava ikinci kez girme hakkım var mı?", "ogrenci",
45+ _intent_not("exam_enter_room")),
46+ ("attendance_policy", "Geç kalma devamsızlığa mı yazılır?", "ogrenci",
47+ _intent_not("attendance_view")),
48+ ("marks_own", "Ders notlarım listeleniyor", "ogrenci",
49+ _intent_is("report_card_view")), # 'ders notlarım' -> karne (course_view none[not])
50+]
51+
52+
53+# --- Mutasyonlar (kural kataloğunu bozar) -----------------------------------
54+# Her mutasyon deepcopy edilmiş _RAW_RULES'u alır, bozar, döndürür.
55+Mutation = tuple[str, Callable[[list[dict[str, Any]]], list[dict[str, Any]]]]
56+
57+
58+def _drop_groups(raw, intent, token):
59+ """intent'in 'all' listesi token içeren gruplarını siler."""
60+ for rule in raw:
61+ if rule["intent"] == intent:
62+ rule["groups"] = [g for g in rule["groups"] if token not in g.get("all", [])]
63+ return raw
64+
65+
66+def _strip_none(raw, intent, token, all_kw=None):
67+ """intent gruplarından bir 'none' token'ını kaldırır (all_kw verilirse yalnız o grup)."""
68+ for rule in raw:
69+ if rule["intent"] == intent:
70+ for g in rule["groups"]:
71+ if all_kw is not None and g.get("all") != all_kw:
72+ continue
73+ if token in g.get("none", []):
74+ g["none"] = [t for t in g["none"] if t != token]
75+ return raw
76+
77+
78+def _strip_all_none(raw, intent, all_kw=None):
79+ """intent gruplarının TÜM none-guard'ını boşaltır (yük taşıyan korumayı kaldırır).
80+
81+ all_kw verilirse yalnız o 'all' imzasına sahip grup; aksi halde tüm gruplar."""
82+ for rule in raw:
83+ if rule["intent"] == intent:
84+ for g in rule["groups"]:
85+ if all_kw is not None and g.get("all") != all_kw:
86+ continue
87+ g["none"] = []
88+ return raw
89+
90+
91+MUTATIONS: list[Mutation] = [
92+ ("privacy: 'arkadaş' tetikleyicisini sil",
93+ lambda raw: _drop_groups(raw, "privacy_security", "arkadaş")),
94+ ("privacy: 'arkadaş+devamsız' kombosunu sil",
95+ lambda raw: [r for r in raw if not (r["intent"] == "privacy_security"
96+ and any(g.get("all") == ["arkadaş", "devamsız"] for g in r["groups"]))
97+ ] or raw),
98+ ("student_marks: {öğrenci,not,gör} none-guard'ını boşalt",
99+ lambda raw: _strip_all_none(raw, "student_marks_lookup", ["öğrenci", "not", "gör"])),
100+ ("exam_enter: {sınav,gir} none-guard'ını boşalt",
101+ lambda raw: _strip_all_none(raw, "exam_enter_room", ["sınav", "gir"])),
102+ ("attendance_view: {devamsız} none-guard'ını boşalt",
103+ lambda raw: _strip_all_none(raw, "attendance_view", ["devamsız"])),
104+ ("course_view: 'not' none-guard'ını kaldır (karne çakışması)",
105+ lambda raw: _strip_none(raw, "course_view", "not")),
106+]
107+
108+
109+def _run_probes() -> dict[str, bool]:
110+ """Her probe için invariant tutuyor mu? (True=doğru davranış)."""
111+ engine = Engine()
112+ results: dict[str, bool] = {}
113+ for name, query, role, invariant in PROBES:
114+ resp = engine.handle({
115+ "query": query,
116+ "session": {"role": role, "authenticated": role != "ziyaretci"},
117+ })
118+ results[name] = invariant(resp)
119+ return results
120+
121+
122+def _apply(mutate: Callable) -> None:
123+ raw = copy.deepcopy(rules_mod._RAW_RULES)
124+ mutated = mutate(raw)
125+ rules_mod._RULES = rules_mod._compile_rules(mutated)
126+ get_role_space.cache_clear()
127+
128+
129+def _restore(original_rules) -> None:
130+ rules_mod._RULES = original_rules
131+ get_role_space.cache_clear()
132+
133+
134+def compute() -> dict[str, Any]:
135+ original = rules_mod._RULES
136+
137+ # 0) Temel: mutasyonsuz tüm probe'lar tutmalı (aksi halde harness geçersiz).
138+ baseline = _run_probes()
139+
140+ rows: list[dict[str, Any]] = []
141+ try:
142+ for name, mutate in MUTATIONS:
143+ _apply(mutate)
144+ after = _run_probes()
145+ _restore(original)
146+ # Öldürüldü mü? En az bir probe temelde True iken şimdi False olmalı.
147+ killed = any(baseline[k] and not after[k] for k in after)
148+ broke = [k for k in after if baseline[k] and not after[k]]
149+ rows.append({"mutation": name, "killed": killed, "caught_by": broke})
150+ finally:
151+ _restore(original)
152+
153+ killed = sum(1 for r in rows if r["killed"])
154+ return {
155+ "baseline_all_hold": all(baseline.values()),
156+ "baseline": baseline,
157+ "rows": rows,
158+ "killed": killed,
159+ "total": len(rows),
160+ "score": killed / len(rows) if rows else 0.0,
161+ }
162+
163+
164+def format_report(report: dict[str, Any]) -> str:
165+ lines = [
166+ "============== MUTASYON TESTİ (kritik invariant) ==============",
167+ f"Temel probe'lar hepsi tutuyor : {'EVET' if report['baseline_all_hold'] else 'HAYIR (!!)'}",
168+ f"Mutation score (öldürülen) : {report['killed']}/{report['total']} "
169+ f"= {report['score']:.0%} (kritik hedef %100)",
170+ "--- Mutasyonlar ---",
171+ ]
172+ for r in report["rows"]:
173+ mark = "KILLED " if r["killed"] else "SURVIVED" # survived = test açığı!
174+ by = (", ".join(r["caught_by"])) if r["caught_by"] else "—"
175+ lines.append(f" [{mark}] {r['mutation']} (yakalayan: {by})")
176+ if report["score"] < 1.0:
177+ lines.append("")
178+ lines.append("UYARI: SURVIVED mutasyonlar = testlerin/probe'ların yakalayamadığı "
179+ "kritik kural bozulmaları. Probe seti veya kural sağlamlaştırılmalı.")
180+ return "\n".join(lines)
181+
182+
183+if __name__ == "__main__":
184+ print(format_report(compute()))
src/evaluation/selective.pyadded+188 -0
@@ -0,0 +1,188 @@
1+"""Seçici sınıflandırma (selective classification / abstention) metrikleri.
2+
3+Ana ilke: "her soruyu cevaplamak" değil, "cevap verdiğinde çok yüksek olasılıkla
4+doğru olmak" (Geifman & El-Yaniv). Bu modül tek-eşik yerine RİSK–KAPSAMA eğrisi
5+çıkarır ve şu ürünleri üretir:
6+
7+- Risk–coverage eğrisi + AURC (düşük = daha iyi): kapsananlar arasında hata oranı.
8+- İşletim noktası (DEFAULT_THRESHOLD=0.18) için seçici risk + kapsama.
9+- OOS false-accept (kapsam-dışı ama cevaplanan) + near/far-OOS ayrımı.
10+- "Rule of three": sıfır-hatalı n test için gerçek hata oranının ~%95 üst sınırı 3/n.
11+
12+Çalıştırma: ``python -m src.evaluation.selective`` (markdown rapor stdout'a).
13+Kesinlikle deterministik: motoru (process) her örnek için bir kez çağırır.
14+"""
15+
16+from __future__ import annotations
17+
18+from typing import Any
19+
20+from ..decision import DEFAULT_THRESHOLD
21+from ..observability import process
22+from ..similarity import SimilarityMatcher
23+from .benchmark import OOS_LABEL, load_benchmark
24+from .evaluate import get_default_matcher
25+
26+
27+# near-OOS eşiği: benzerlik top-1 skoru bu değerin ÜSTÜNDEyse OOS örneği "desteklenen
28+# konuya benziyor" (near-OOS) sayılır; altındaysa far-OOS (tamamen ilgisiz). Alan
29+# kapısı eşiğiyle hizalı (domain-gate DEFAULT_THRESHOLD).
30+_NEAR_OOS_SCORE: float = DEFAULT_THRESHOLD
31+
32+
33+def _top1(trace: dict[str, Any]) -> tuple[str | None, float]:
34+ """(top-1 intent, güven). Kural yolu -> güven 1.0; aksi halde benzerlik top-1."""
35+
36+ if trace["rule_layer"]["hit"]:
37+ return trace["rule_layer"]["intent"], 1.0
38+ top_k = trace["similarity"].get("top_k") or []
39+ if not top_k:
40+ return None, 0.0
41+ return top_k[0]["intent"], float(top_k[0]["score"])
42+
43+
44+def collect_samples(
45+ matcher: SimilarityMatcher | None = None,
46+ records: list[dict[str, Any]] | None = None,
47+) -> dict[str, Any]:
48+ """Her örnek için (güven, top-1, doğru mu, in_domain) toplar."""
49+
50+ matcher = matcher or get_default_matcher()
51+ records = records if records is not None else load_benchmark()
52+
53+ in_scope: list[dict[str, Any]] = [] # {conf, correct}
54+ oos: list[dict[str, Any]] = [] # {conf, in_domain, accepted}
55+
56+ for r in records:
57+ role = r.get("role", "ziyaretci")
58+ authenticated = role != "ziyaretci"
59+ _, trace = process(
60+ r["question"], role=role, authenticated=authenticated, matcher=matcher
61+ )
62+ top1, conf = _top1(trace)
63+ rule_hit = trace["rule_layer"]["hit"]
64+ in_domain = trace["similarity"].get("in_domain", True)
65+ expected = r["expected_intent"]
66+
67+ if expected == OOS_LABEL:
68+ # Kabul (accept) = kural çarptı VEYA (alan-içi ve güven >= eşik).
69+ accepted = rule_hit or (in_domain and conf >= DEFAULT_THRESHOLD)
70+ oos.append({"conf": conf, "in_domain": in_domain, "accepted": accepted})
71+ else:
72+ in_scope.append({"conf": conf, "correct": top1 == expected})
73+
74+ return {"in_scope": in_scope, "oos": oos}
75+
76+
77+def risk_coverage_curve(in_scope: list[dict[str, Any]]) -> list[tuple[float, float]]:
78+ """(coverage, selective_risk) noktaları: güvene göre azalan sırayla kümülatif.
79+
80+ coverage = cevaplanan / toplam; risk = cevaplananlar arasında hata oranı.
81+ """
82+
83+ ranked = sorted(in_scope, key=lambda s: s["conf"], reverse=True)
84+ n = len(ranked)
85+ points: list[tuple[float, float]] = []
86+ errors = 0
87+ for k, sample in enumerate(ranked, start=1):
88+ if not sample["correct"]:
89+ errors += 1
90+ points.append((k / n, errors / k))
91+ return points
92+
93+
94+def aurc(points: list[tuple[float, float]]) -> float:
95+ """Risk–coverage eğrisi altındaki alan (kapsamaya göre ortalama risk)."""
96+
97+ if not points:
98+ return 0.0
99+ return sum(risk for _cov, risk in points) / len(points)
100+
101+
102+def compute(
103+ matcher: SimilarityMatcher | None = None,
104+ records: list[dict[str, Any]] | None = None,
105+) -> dict[str, Any]:
106+ samples = collect_samples(matcher, records)
107+ in_scope = samples["in_scope"]
108+ oos = samples["oos"]
109+
110+ curve = risk_coverage_curve(in_scope)
111+
112+ # İşletim noktası: güven >= DEFAULT_THRESHOLD olanları cevapla (kural=1.0 hep dahil).
113+ answered = [s for s in in_scope if s["conf"] >= DEFAULT_THRESHOLD]
114+ answered_wrong = sum(1 for s in answered if not s["correct"])
115+ op_coverage = len(answered) / len(in_scope) if in_scope else 0.0
116+ op_risk = answered_wrong / len(answered) if answered else 0.0
117+
118+ # OOS false-accept (genel + near/far).
119+ def _fa(bucket: list[dict[str, Any]]) -> tuple[int, int]:
120+ accepted = sum(1 for s in bucket if s["accepted"])
121+ return accepted, len(bucket)
122+
123+ near = [s for s in oos if s["conf"] >= _NEAR_OOS_SCORE]
124+ far = [s for s in oos if s["conf"] < _NEAR_OOS_SCORE]
125+ fa_all, n_all = _fa(oos)
126+ fa_near, n_near = _fa(near)
127+ fa_far, n_far = _fa(far)
128+
129+ return {
130+ "n_in_scope": len(in_scope),
131+ "n_oos": len(oos),
132+ "aurc": aurc(curve),
133+ "op_threshold": DEFAULT_THRESHOLD,
134+ "op_coverage": op_coverage,
135+ "op_selective_risk": op_risk,
136+ "op_answered": len(answered),
137+ "op_answered_wrong": answered_wrong,
138+ "oos_false_accept": fa_all / n_all if n_all else 0.0,
139+ "oos_fa_count": (fa_all, n_all),
140+ "oos_fa_near": (fa_near, n_near),
141+ "oos_fa_far": (fa_far, n_far),
142+ "curve": curve,
143+ }
144+
145+
146+def _rule_of_three(errors: int, n: int) -> str:
147+ """Sıfır-hatalı n için ~%95 üst sınır 3/n; hata varsa gözlenen oranı ver."""
148+
149+ if n == 0:
150+ return "n=0"
151+ if errors == 0:
152+ if n < 30:
153+ return f"0 gözlendi (n={n} — güven aralığı için örnek küçük)"
154+ return f"≤ {3.0 / n:.2%} (rule-of-three, n={n})"
155+ return f"{errors / n:.2%} gözlendi ({errors}/{n})"
156+
157+
158+def format_report(report: dict[str, Any]) -> str:
159+ fa_near_c, fa_near_n = report["oos_fa_near"]
160+ fa_far_c, fa_far_n = report["oos_fa_far"]
161+ aw, an = report["op_answered_wrong"], report["op_answered"]
162+ lines = [
163+ "========= SEÇİCİ SINIFLANDIRMA (SELECTIVE RISK) =========",
164+ f"In-scope / OOS örnek : {report['n_in_scope']} / {report['n_oos']}",
165+ "--- Risk–Coverage ---",
166+ f"AURC (düşük=iyi) : {report['aurc']:.4f}",
167+ f"İşletim eşiği : {report['op_threshold']:.3f}",
168+ f" Kapsama (coverage) : {report['op_coverage']:.1%}",
169+ f" Seçici risk : {report['op_selective_risk']:.2%} ({aw}/{an} yanlış)",
170+ f" Kabul-doğruluk üst sın.: {_rule_of_three(aw, an)}",
171+ "--- OOS false-accept (kapsam-dışı ama cevaplanan) ---",
172+ f" Genel : {report['oos_false_accept']:.2%} "
173+ f"({report['oos_fa_count'][0]}/{report['oos_fa_count'][1]})",
174+ f" near-OOS (benzeyen) : {_rule_of_three(fa_near_c, fa_near_n)}",
175+ f" far-OOS (ilgisiz) : {_rule_of_three(fa_far_c, fa_far_n)}",
176+ "--- Risk–coverage eğrisi (örnek noktalar) ---",
177+ ]
178+ curve = report["curve"]
179+ for frac in (0.5, 0.7, 0.8, 0.9, 0.95, 1.0):
180+ idx = min(len(curve) - 1, int(frac * len(curve)) - 1)
181+ if idx >= 0:
182+ cov, risk = curve[idx]
183+ lines.append(f" coverage≈{cov:>5.0%} -> risk={risk:.2%}")
184+ return "\n".join(lines)
185+
186+
187+if __name__ == "__main__":
188+ print(format_report(compute()))
src/main.pymodified+22 -0
@@ -30,6 +30,16 @@ def build_parser() -> argparse.ArgumentParser:
30 action="store_true",30 action="store_true",
31 help="Benchmark üzerinde tam değerlendirme raporu üretir.",31 help="Benchmark üzerinde tam değerlendirme raporu üretir.",
32 )32 )
33+ parser.add_argument(
34+ "--selective",
35+ action="store_true",
36+ help="Seçici sınıflandırma raporu (risk-coverage, AURC, OOS false-accept).",
37+ )
38+ parser.add_argument(
39+ "--mutation",
40+ action="store_true",
41+ help="Mutasyon testi: kritik invariant'ların yakalanma gücü (mutation score).",
42+ )
33 parser.add_argument(43 parser.add_argument(
34 "--chat",44 "--chat",
35 action="store_true",45 action="store_true",
@@ -51,6 +61,18 @@ def main() -> int:
51 print(format_report(run_evaluation()))61 print(format_report(run_evaluation()))
52 return 062 return 0
53 63
64+ if args.selective:
65+ from .evaluation.selective import compute, format_report as fmt_sel
66+
67+ print(fmt_sel(compute()))
68+ return 0
69+
70+ if args.mutation:
71+ from .evaluation.mutation import compute, format_report as fmt_mut
72+
73+ print(fmt_mut(compute()))
74+ return 0
75+
54 if args.validate:76 if args.validate:
55 print_validation_result(validate_catalog())77 print_validation_result(validate_catalog())
56 return 078 return 0
tests/integration/test_selective_mutation.pyadded+52 -0
@@ -0,0 +1,52 @@
1+"""Seçici sınıflandırma + mutasyon testi regresyonu.
2+
3+Kalite kapıları (kriterler.md ile hizalı):
4+- Mutasyon score = %100 (kritik invariant'lar bozulunca probe'lar YAKALAR).
5+- İşletim noktasında seçici risk düşük (kabul edilen cevaplarda az hata).
6+- OOS false-accept ölçülür ve raporlanır (regresyonda artışı fark edelim).
7+
8+Bu testler ölçüm altyapısının kendisini de korur (harness bozulursa fark edilir).
9+"""
10+
11+import unittest
12+
13+from src.evaluation import mutation, selective
14+
15+
16+class MutationScoreTests(unittest.TestCase):
17+ def test_baseline_probes_all_hold(self) -> None:
18+ report = mutation.compute()
19+ self.assertTrue(
20+ report["baseline_all_hold"],
21+ f"Temel invariant probe'ları tutmuyor: {report['baseline']}",
22+ )
23+
24+ def test_mutation_score_is_perfect(self) -> None:
25+ # Kritik invariant'lar için mutasyon score = %100 (hepsi öldürülmeli).
26+ report = mutation.compute()
27+ survived = [r["mutation"] for r in report["rows"] if not r["killed"]]
28+ self.assertEqual(report["score"], 1.0, f"Hayatta kalan mutasyonlar: {survived}")
29+
30+
31+class SelectiveRiskTests(unittest.TestCase):
32+ @classmethod
33+ def setUpClass(cls) -> None:
34+ cls.report = selective.compute()
35+
36+ def test_operating_selective_risk_low(self) -> None:
37+ # İşletim eşiğinde kabul edilen cevaplarda hata oranı <= %1 (şu an ~%0.5).
38+ self.assertLessEqual(self.report["op_selective_risk"], 0.01)
39+
40+ def test_aurc_low(self) -> None:
41+ # Risk-coverage eğrisi altındaki alan küçük (iyi ayrışma).
42+ self.assertLessEqual(self.report["aurc"], 0.02)
43+
44+ def test_oos_false_accept_reported(self) -> None:
45+ # Ölçülüyor ve mantıklı aralıkta (regresyonda artışı yakalamak için üst sınır).
46+ fa = self.report["oos_false_accept"]
47+ self.assertGreaterEqual(fa, 0.0)
48+ self.assertLessEqual(fa, 0.20, "OOS false-accept beklenenden yüksek — gerileme?")
49+
50+
51+if __name__ == "__main__":
52+ unittest.main()