forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiB184b84dAhmet Kaan Gümüş2 months ago189 commits

test_rerank.py92 lines, 4.0 KiBHistoryRawDownload
1"""Faz 1.5 entegrasyon — 12-bio üzerinde gerçek BGE-reranker-v2-m3.
2
3Resmi nDCG@10 (≥0.90) + rerank kazancı golden set (Faz 1.8) sonrası. Buradaki
4testler reranker'ın çalıştığını + bariz-ilgili chunk'ı üste çektiğini +
5çeşitlilik/parent genişletmeyi gerçek veride doğrular. Model yoksa ATLANIR.
6"""
7import os
8import unittest
9
10import corpus
11
12from src.ingest.canonical import build_canonical
13from src.chunk import chunk_document
14from src.index import DenseIndex, BM25Index
15from src.retrieve import SparseIndex, HybridRetriever
16from src.rerank import BGEReranker, rerank_select
17
18BOOK = corpus.book_path()
19
20
21def _prepare():
22 try:
23 from src.embed import BGEM3Embedder
24 doc = build_canonical(BOOK, sinif=corpus.find_book()[1], ders=corpus.find_book()[2])
25 chunks = chunk_document(doc)
26 children = [c for c in chunks if c.level == "child"]
27 chunks_by_id = {c.chunk_id: c for c in chunks} # child + parent
28 emb = corpus.shared_embedder()
29 ids, vecs = emb.embed_chunks(children, batch_size=16)
30 texts = [c.text for c in children]
31 sparse_docs = emb.embed_sparse(texts, batch_size=16)
32 dense = DenseIndex(dim=1024).build(ids, vecs)
33 bm25 = BM25Index().build(ids, texts)
34 sparse = SparseIndex().build(ids, sparse_docs)
35 retr = HybridRetriever(emb, dense, bm25, sparse)
36 rr = corpus.shared_reranker()
37 rr.rerank("ısınma", [("x", "deneme metni")]) # modeli yükle
38 return chunks_by_id, retr, rr
39 except Exception:
40 return None
41
42
43_PREP = _prepare() if os.path.exists(BOOK) else None
44
45
46@unittest.skipUnless(_PREP is not None, "korpus yok / BGE modelleri yüklenemedi")
47class RerankIntegrationTests(unittest.TestCase):
48 @classmethod
49 def setUpClass(cls):
50 cls.chunks_by_id, cls.retr, cls.rr = _PREP
51 # SORGU KORPUSTAN TÜRETİLİR. Eski hâli "DNA nükleotid çift sarmal"
52 # diyordu — 12-bio'ya özgü; 10. sınıf kitabında hiç geçmiyor ve test
53 # kendi verisine çakılıyordu (üstelik hiç koşmadığı için fark
54 # edilmiyordu). En uzun chunk'ın kendi metni her korpusta bulunur.
55 en_uzun = max(cls.chunks_by_id.values(), key=lambda c: len(c.text))
56 cls.QUERY = " ".join(en_uzun.text.split()[:20])
57
58 def test_rerank_scores_sorted(self):
59 hits = self.retr.retrieve(self.QUERY, top_k=20)
60 items = [(cid, self.chunks_by_id[cid].text) for cid, _ in hits]
61 ranked = self.rr.rerank(self.QUERY, items)
62 scores = [s for _, s in ranked]
63 self.assertEqual(scores, sorted(scores, reverse=True))
64 self.assertEqual(len(ranked), len(items))
65
66 def test_rerank_select_topn_and_parent(self):
67 hits = self.retr.retrieve(self.QUERY, top_k=40)
68 res = rerank_select(self.QUERY, hits, self.chunks_by_id,
69 self.rr, top_n=8, candidate_n=40, per_parent=1)
70 self.assertLessEqual(len(res), 8)
71 self.assertGreater(len(res), 0)
72 # en az bir sonuçta parent genişletme (child'ın parent'ı varsa)
73 self.assertTrue(any(r.parent_text for r in res if r.parent_id))
74 # SÖZLEŞME DEĞİŞTİ (#59): `per_parent` artık TAVAN değil; ilgili
75 # kanıtlar aynı parent'tan da gelebilir. Değişmez olan: tekrarsız ve
76 # skor-sıralı sonuç.
77 ids = [r.chunk_id for r in res]
78 self.assertEqual(len(ids), len(set(ids)), "aynı chunk iki kez seçildi")
79 skorlar = [r.score for r in res]
80 self.assertEqual(skorlar, sorted(skorlar, reverse=True))
81
82 def test_top1_is_relevant(self):
83 hits = self.retr.retrieve("fotosentez ışık reaksiyonu kloroplast", top_k=40)
84 res = rerank_select("fotosentez ışık reaksiyonu kloroplast", hits,
85 self.chunks_by_id, self.rr, top_n=5)
86 top_txt = res[0].text.lower()
87 self.assertTrue(any(w in top_txt for w in
88 ("fotosentez", "kloroplast", "ışık", "klorofil")))
89
90
91if __name__ == "__main__":
92 unittest.main()