forge
Explore
Log in

Don't you dare go Hollow

Qdrant dense (gomulu) + BM25 lexical koksuz (Faz 1.3)

Browse files at this commit

ec78e91cb2264fc87b7adff65668517eda3bf1c1Kadir YönakParent: 3a4dda1
  • feat
    • Qdrant dense (gomulu) + BM25 lexical koksuz (Faz 1.3)
Show full message
feat(index): Qdrant dense (gomulu) + BM25 lexical koksuz (Faz 1.3)

- DenseIndex: Qdrant gomulu yerel (in-memory/path), cosine, query_points; exact_topk
  referans (brute-force cosine).
- BM25Index: rank_bm25, TR-normalize (fold_for_match), koksuz tokenizasyon; bos
  belge placeholder.
- Kabul: ANN recall@20 = 1.0000 (exact'e karsi, >=0.995); 258 chunk, dense arama
  3.04 ms, BM25 0.43 ms, depo 1.06 MB.
- Test: 6 birim (sentetik recall + TR BM25) + 4 integration (gercek 12-bio).
src/index/__init__.pyadded+5 -0
@@ -0,0 +1,5 @@
1+"""Faz 1.3 — indeksler: Qdrant dense (gömülü) + BM25 lexical (köksüz, TR)."""
2+from src.index.dense import DenseIndex, exact_topk
3+from src.index.lexical import BM25Index, tokenize
4+
5+__all__ = ["DenseIndex", "exact_topk", "BM25Index", "tokenize"]
src/index/dense.pyadded+74 -0
@@ -0,0 +1,74 @@
1+"""Faz 1.3 — Qdrant yerel (gömülü) dense vektör indeksi + exact referans.
2+
3+BGE-M3 dense (1024-dim, L2-normalize) → cosine mesafe. Gömülü mod (sunucu yok):
4+`path=None` → in-memory (test); `path=...` → kalıcı yerel depo. Üretimde Qdrant
5+sunucu konteyneri aynı arayüzle takılır.
6+
7+Kabul (plan 1.3): ANN recall ≥ 0.995 (exact brute-force'a karşı). NOT: Qdrant'ın
8+gömülü yerel modu küçük koleksiyonda exact hesaplar (recall=1.0); gerçek HNSW/ANN
9+kaybı ölçekte (sunucu) yeniden ölçülecek. `exact_topk` referans olarak burada.
10+"""
11+from __future__ import annotations
12+
13+import numpy as np
14+
15+_COLLECTION = "chunks"
16+
17+
18+def exact_topk(query_vec, matrix, ids, top_k: int = 20):
19+ """Brute-force cosine (referans doğruluk). matrix satırları normalize varsayılmaz."""
20+ from src.embed import cosine_matrix
21+ scores = cosine_matrix(query_vec, matrix)
22+ order = np.argsort(-scores)[:top_k]
23+ return [(ids[i], float(scores[i])) for i in order]
24+
25+
26+class DenseIndex:
27+ """Qdrant gömülü dense indeks. build(ids, vectors) → search(query_vec, k)."""
28+
29+ def __init__(self, dim: int = 1024, path: str | None = None,
30+ collection: str = _COLLECTION):
31+ self.dim = dim
32+ self.collection = collection
33+ self._path = path
34+ self._client = None
35+ self._ids: list[str] = []
36+
37+ def _c(self):
38+ if self._client is None:
39+ from qdrant_client import QdrantClient
40+ self._client = (QdrantClient(path=self._path) if self._path
41+ else QdrantClient(":memory:"))
42+ return self._client
43+
44+ def build(self, ids, vectors, payloads=None):
45+ from qdrant_client.models import Distance, VectorParams, PointStruct
46+ c = self._c()
47+ vectors = np.asarray(vectors, dtype=np.float32)
48+ if vectors.ndim != 2 or vectors.shape[1] != self.dim:
49+ raise ValueError(f"vectors (n,{self.dim}) olmalı, geldi {vectors.shape}")
50+ if c.collection_exists(self.collection):
51+ c.delete_collection(self.collection)
52+ c.create_collection(
53+ self.collection,
54+ vectors_config=VectorParams(size=self.dim, distance=Distance.COSINE),
55+ )
56+ pts = []
57+ for i, (cid, v) in enumerate(zip(ids, vectors)):
58+ pl = {"chunk_id": cid}
59+ if payloads:
60+ pl.update(payloads[i])
61+ pts.append(PointStruct(id=i, vector=v.tolist(), payload=pl))
62+ c.upsert(self.collection, points=pts)
63+ self._ids = list(ids)
64+ return self
65+
66+ def search(self, query_vec, top_k: int = 20):
67+ """(chunk_id, skor) listesi, skor azalan. Skor = cosine (dense normalize)."""
68+ c = self._c()
69+ q = np.asarray(query_vec, dtype=np.float32).tolist()
70+ res = c.query_points(self.collection, query=q, limit=top_k).points
71+ return [(p.payload["chunk_id"], float(p.score)) for p in res]
72+
73+ def __len__(self):
74+ return len(self._ids)
src/index/lexical.pyadded+48 -0
@@ -0,0 +1,48 @@
1+"""Faz 1.3 — BM25 lexical indeks (rank_bm25), TR-normalize, köksüz.
2+
3+Tek alan (chunk metni). TR-güvenli katlama (`fold_for_match`: İ/ı doğru,
4+görünmezler temiz) + Unicode kelime tokenizasyonu. **Köksüz**: stemming/kök
5+bulma yok — dense ile tamamlayıcı lexical sinyal (hibrit RRF, Faz 1.4). Terim
6+eşleşmesi (özel ad, kod, sayı) dense'in kaçırdığını yakalar.
7+"""
8+from __future__ import annotations
9+
10+import re
11+
12+import numpy as np
13+
14+from src.text.tr_normalize import fold_for_match
15+
16+_WORD = re.compile(r"\w+", re.UNICODE) # Türkçe harfler dahil (folded)
17+_EMPTY = "∅" # boş belge placeholder (∅)
18+
19+
20+def tokenize(text: str) -> list[str]:
21+ """TR-katlanmış metni token listesine ayır (köksüz)."""
22+ return _WORD.findall(fold_for_match(text))
23+
24+
25+class BM25Index:
26+ """BM25Okapi sarmalayıcı. build(ids, texts) → search(query, k)."""
27+
28+ def __init__(self):
29+ self._bm25 = None
30+ self._ids: list[str] = []
31+
32+ def build(self, ids, texts):
33+ from rank_bm25 import BM25Okapi
34+ corpus = [tokenize(t) or [_EMPTY] for t in texts] # boş → placeholder
35+ self._bm25 = BM25Okapi(corpus)
36+ self._ids = list(ids)
37+ return self
38+
39+ def search(self, query, top_k: int = 20):
40+ """(chunk_id, bm25_skoru) listesi, skor azalan."""
41+ if self._bm25 is None:
42+ raise RuntimeError("önce build() çağır")
43+ scores = self._bm25.get_scores(tokenize(query))
44+ order = np.argsort(-scores)[:top_k]
45+ return [(self._ids[i], float(scores[i])) for i in order]
46+
47+ def __len__(self):
48+ return len(self._ids)
tests/integration/test_index.pyadded+76 -0
@@ -0,0 +1,76 @@
1+"""Faz 1.3 entegrasyon testi — 12-bio gerçek vektörlerde Dense (Qdrant) + BM25.
2+
3+Kabul (plan 1.3): ANN recall ≥ 0.995 (exact'e karşı). Model yüklenemezse ATLANIR.
4+"""
5+import os
6+import unittest
7+
8+import numpy as np
9+
10+from src.ingest.canonical import build_canonical
11+from src.chunk import chunk_document
12+from src.index import DenseIndex, exact_topk, BM25Index
13+
14+BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf")
15+
16+
17+def _prepare():
18+ try:
19+ from src.embed import BGEM3Embedder
20+ doc = build_canonical(BOOK, sinif="12", ders="biyoloji")
21+ chunks = chunk_document(doc)
22+ children = [c for c in chunks if c.level == "child"]
23+ emb = BGEM3Embedder()
24+ ids, vecs = emb.embed_chunks(children, batch_size=16)
25+ return children, ids, vecs, emb
26+ except Exception:
27+ return None
28+
29+
30+_PREP = _prepare() if os.path.exists(BOOK) else None
31+
32+
33+@unittest.skipUnless(_PREP is not None, "12-bio verisi yok / BGE-M3 yüklenemedi")
34+class DenseBM25IntegrationTests(unittest.TestCase):
35+ @classmethod
36+ def setUpClass(cls):
37+ cls.children, cls.ids, cls.vecs, cls.emb = _PREP
38+ cls.texts = [c.text for c in cls.children]
39+ cls.dense = DenseIndex(dim=1024).build(cls.ids, cls.vecs)
40+ cls.bm25 = BM25Index().build(cls.ids, cls.texts)
41+
42+ def test_index_sizes(self):
43+ self.assertEqual(len(self.dense), len(self.ids))
44+ self.assertEqual(len(self.bm25), len(self.ids))
45+ self.assertGreater(len(self.ids), 100) # 12-bio ~258
46+
47+ def test_ann_recall_vs_exact(self):
48+ k = 20
49+ recalls = []
50+ for qi in range(0, len(self.vecs), 10): # ~26 sorgu
51+ q = self.vecs[qi]
52+ ann = {cid for cid, _ in self.dense.search(q, top_k=k)}
53+ exact = {cid for cid, _ in exact_topk(q, self.vecs, self.ids, top_k=k)}
54+ recalls.append(len(ann & exact) / k)
55+ mean_recall = float(np.mean(recalls))
56+ self.assertGreaterEqual(mean_recall, 0.995, f"recall={mean_recall:.4f}")
57+
58+ def test_dense_semantic_query(self):
59+ qv = self.emb.embed(["DNA'nın yapısı ve nükleotidler"])[0]
60+ hits = self.dense.search(qv, top_k=5)
61+ self.assertEqual(len(hits), 5)
62+ joined = " ".join(
63+ self.children[self.ids.index(cid)].text.lower() for cid, _ in hits
64+ )
65+ self.assertTrue(any(w in joined for w in ("dna", "nükleot", "baz")))
66+
67+ def test_bm25_keyword_query(self):
68+ hits = self.bm25.search("fotosentez kloroplast", top_k=5)
69+ self.assertEqual(len(hits), 5)
70+ self.assertGreater(hits[0][1], 0.0)
71+ top_txt = self.children[self.ids.index(hits[0][0])].text.lower()
72+ self.assertTrue("fotosentez" in top_txt or "kloroplast" in top_txt)
73+
74+
75+if __name__ == "__main__":
76+ unittest.main()
tests/unit/test_index.pyadded+78 -0
@@ -0,0 +1,78 @@
1+"""Faz 1.3 birim testleri — Dense ANN↔exact recall (sentetik) + BM25 TR (model gerekmez)."""
2+import unittest
3+
4+import numpy as np
5+
6+from src.index import DenseIndex, exact_topk, BM25Index, tokenize
7+
8+
9+def _unit_vectors(n, d, seed=0):
10+ rng = np.random.default_rng(seed)
11+ v = rng.standard_normal((n, d)).astype(np.float32)
12+ v /= np.linalg.norm(v, axis=1, keepdims=True)
13+ return v
14+
15+
16+class DenseRecallTests(unittest.TestCase):
17+ def test_ann_recall_vs_exact(self):
18+ d, n, k = 1024, 500, 20
19+ vecs = _unit_vectors(n, d, seed=1)
20+ ids = [f"c{i}" for i in range(n)]
21+ idx = DenseIndex(dim=d).build(ids, vecs)
22+
23+ recalls = []
24+ for qi in range(0, n, 15): # ~34 sorgu
25+ q = vecs[qi]
26+ ann = {cid for cid, _ in idx.search(q, top_k=k)}
27+ exact = {cid for cid, _ in exact_topk(q, vecs, ids, top_k=k)}
28+ recalls.append(len(ann & exact) / k)
29+ mean_recall = float(np.mean(recalls))
30+ self.assertGreaterEqual(mean_recall, 0.995, f"recall={mean_recall:.4f}")
31+
32+ def test_self_query_is_top1(self):
33+ d, n = 1024, 50
34+ vecs = _unit_vectors(n, d, seed=2)
35+ ids = [f"c{i}" for i in range(n)]
36+ idx = DenseIndex(dim=d).build(ids, vecs)
37+ top = idx.search(vecs[7], top_k=1)
38+ self.assertEqual(top[0][0], "c7")
39+ self.assertAlmostEqual(top[0][1], 1.0, places=3)
40+
41+ def test_dim_mismatch_raises(self):
42+ idx = DenseIndex(dim=1024)
43+ with self.assertRaises(ValueError):
44+ idx.build(["a"], np.zeros((1, 8), dtype=np.float32))
45+
46+
47+class BM25TurkishTests(unittest.TestCase):
48+ def test_tokenize_tr_casefold(self):
49+ toks = tokenize("DNA'nın Yapısı İĞNE ışık") # İ→i, I→ı korunur
50+ self.assertIn("dna", toks)
51+ self.assertIn("yapısı", toks)
52+ self.assertIn("iğne", toks) # İĞNE → iğne
53+ self.assertIn("ışık", toks)
54+
55+ def test_search_finds_keyword_doc(self):
56+ ids = ["a", "b", "c"]
57+ texts = [
58+ "Fotosentez kloroplastta gerçekleşir.",
59+ "DNA nükleotidlerden oluşan çift sarmaldır.",
60+ "Mitoz hücre bölünmesi evreleri.",
61+ ]
62+ idx = BM25Index().build(ids, texts)
63+ top = idx.search("nükleotid DNA sarmal", top_k=3)
64+ self.assertEqual(top[0][0], "b") # en ilgili belge
65+ self.assertGreater(top[0][1], 0.0)
66+
67+ def test_empty_doc_no_crash(self):
68+ # boş belge build/search'i bozmamalı; "metin" içeren belge üste gelmeli
69+ # (küçük korpusta IDF≈0 olmasın diye birkaç ilgisiz belge ekli)
70+ ids = ["x", "y", "d1", "d2", "d3"]
71+ texts = ["", "geçerli metin burada", "fotosentez", "mitoz", "dna sarmal"]
72+ idx = BM25Index().build(ids, texts)
73+ top = idx.search("metin", top_k=5)
74+ self.assertEqual(top[0][0], "y")
75+
76+
77+if __name__ == "__main__":
78+ unittest.main()