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

dense.py199 lines, 8.7 KiBHistoryRawDownload
1"""Faz 1.3 — Qdrant yerel (gömülü) dense vektör indeksi + exact referans.
2
3BGE-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
5sunucu konteyneri aynı arayüzle takılır.
6
7Kabul (plan 1.3): ANN recall ≥ 0.995 (exact brute-force'a karşı). NOT: Qdrant'ın
8gömülü yerel modu küçük koleksiyonda exact hesaplar (recall=1.0); gerçek HNSW/ANN
9kaybı ölçekte (sunucu) yeniden ölçülecek. `exact_topk` referans olarak burada.
10"""
11from __future__ import annotations
12
13import numpy as np
14
15_COLLECTION = "chunks"
16
17
18def 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
26class 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, *, school,
45 doc_id: str = "", source_version: str = ""):
46 """Koleksiyonu SIFIRDAN kurar (var olanı siler).
47
48 `doc_id`/`source_version` her noktanın payload'ına yazılır — `delete()`
49 ve `upsert()` bunlar olmadan çalışamaz (bkz. `delete` docstring'i).
50
51 `school` ZORUNLUDUR ve varsayılanı YOKTUR (bkz. `guard/tenant.py`):
52 sahipsiz yazma bir hata, "paylaşılan/public bir satır" değil. Her
53 korpusun bir okulu vardır; okulsuz satır yazılamaz ve okunamaz.
54 """
55 from qdrant_client.models import Distance, VectorParams
56 c = self._c()
57 vectors = np.asarray(vectors, dtype=np.float32)
58 if vectors.ndim != 2 or vectors.shape[1] != self.dim:
59 raise ValueError(f"vectors (n,{self.dim}) olmalı, geldi {vectors.shape}")
60 if c.collection_exists(self.collection):
61 c.delete_collection(self.collection)
62 c.create_collection(
63 self.collection,
64 vectors_config=VectorParams(size=self.dim, distance=Distance.COSINE),
65 )
66 self._ids = []
67 self._next_id = 0
68 self.upsert(ids, vectors, payloads, school=school, doc_id=doc_id,
69 source_version=source_version)
70 return self
71
72 # M4-2 (#76, EXP-010/OPS-01) — SILME/GUNCELLEME API'SI YOKTU.
73 #
74 # OLCULDU: genel API yalniz `build/search/collection/dim` idi; `build()`
75 # her cagrida koleksiyonu SILIP SIFIRDAN kuruyordu (10 nokta build ->
76 # 5 yeni id ile build -> koleksiyonda 5 nokta kaldi, 15 degil).
77 #
78 # Daha temeli: chunk -> KAYNAK eslemesi hicbir indekste payload olarak
79 # tutulmuyordu (`payload={"chunk_id": cid}`) -> "su kaynagin vektorlerini
80 # sil" sorgusu TEKNIK OLARAK IFADE EDILEMIYORDU.
81 #
82 # BASARISIZLIK: ogretmen ders notunu silerse vektor silinemez -> silinmis
83 # nottan alinti yapan cevaplar uretilmeye DEVAM EDER. KVKK silme
84 # yukumlulugu de imkansiz hale gelir.
85
86 def upsert(self, ids, vectors, payloads=None, *, school,
87 doc_id: str = "", source_version: str = ""):
88 """Var olan koleksiyona EKLER/GUNCELLER — silmez.
89
90 Ayni `chunk_id` yeniden gelirse eski nokta silinip yenisi yazilir
91 (id'ler sirali tamsayi oldugu icin dogal bir upsert anahtari yok;
92 chunk_id filtresiyle silip ekliyoruz).
93
94 `school` (ZORUNLU) her noktanin payload'ina yazilir: koleksiyon
95 korpus-omru boyunca de-okunur (kalici/sunucu Qdrant'ta paylasilir) ve
96 okuma tarafi ancak bu damgayla kapsamlanabilir."""
97 from qdrant_client.models import PointStruct
98 from ..guard.tenant import require_owner
99 sahip = require_owner(school)
100 c = self._c()
101 vectors = np.asarray(vectors, dtype=np.float32)
102 if len(vectors) == 0:
103 return self
104 if vectors.ndim != 2 or vectors.shape[1] != self.dim:
105 raise ValueError(f"vectors (n,{self.dim}) olmalı, geldi {vectors.shape}")
106 if not hasattr(self, "_next_id"):
107 self._next_id = len(self._ids)
108 yeniden = [cid for cid in ids if cid in set(self._ids)]
109 if yeniden:
110 self.delete_chunks(yeniden)
111 pts = []
112 for i, (cid, v) in enumerate(zip(ids, vectors)):
113 pl = {"chunk_id": cid, "school": sahip}
114 if doc_id:
115 pl["doc_id"] = doc_id
116 if source_version:
117 pl["source_version"] = source_version
118 if payloads:
119 pl.update(payloads[i])
120 pts.append(PointStruct(id=self._next_id, vector=v.tolist(), payload=pl))
121 self._next_id += 1
122 c.upsert(self.collection, points=pts)
123 self._ids.extend(ids)
124 return self
125
126 def delete(self, doc_id: str) -> int:
127 """Bir KAYNAGIN tum vektorlerini siler. Doner: silinen nokta sayisi.
128
129 `doc_id` payload'da tutulmadan bu sorgu ifade edilemez — bu yuzden
130 `build`/`upsert` onu yaziyor. Eski (doc_id'siz) koleksiyonlarda hicbir
131 sey silinmez ve 0 doner; cagiran bunu bir HATA olarak gormeli.
132 """
133 from qdrant_client.models import FieldCondition, Filter, MatchValue
134 c = self._c()
135 if not c.collection_exists(self.collection):
136 return 0
137 flt = Filter(must=[FieldCondition(key="doc_id",
138 match=MatchValue(value=doc_id))])
139 kalan_once = len(self)
140 silinecek = {p.payload.get("chunk_id")
141 for p in self._scroll(flt)}
142 c.delete(self.collection, points_selector=flt)
143 self._ids = [cid for cid in self._ids if cid not in silinecek]
144 return kalan_once - len(self._ids)
145
146 def delete_chunks(self, chunk_ids) -> int:
147 """Belirli chunk'lari siler (upsert'in guncelleme yolu)."""
148 from qdrant_client.models import FieldCondition, Filter, MatchAny
149 c = self._c()
150 if not c.collection_exists(self.collection):
151 return 0
152 hedef = list(chunk_ids)
153 if not hedef:
154 return 0
155 flt = Filter(must=[FieldCondition(key="chunk_id",
156 match=MatchAny(any=hedef))])
157 c.delete(self.collection, points_selector=flt)
158 once = len(self._ids)
159 kume = set(hedef)
160 self._ids = [cid for cid in self._ids if cid not in kume]
161 return once - len(self._ids)
162
163 def _scroll(self, flt=None, limit: int = 10_000):
164 c = self._c()
165 pts, _ = c.scroll(self.collection, scroll_filter=flt, limit=limit,
166 with_payload=True, with_vectors=False)
167 return pts
168
169 def doc_ids(self) -> set:
170 """Koleksiyondaki kaynaklar — silme denetimi icin."""
171 return {p.payload.get("doc_id") for p in self._scroll()
172 if p.payload.get("doc_id")}
173
174 def search(self, query_vec, top_k: int = 20, *, school=None):
175 """(chunk_id, skor) listesi, skor azalan. Skor = cosine (dense normalize).
176
177 `school` = OKURUN okulu (istekten). Kapsam TAM EŞİTLİKTİR: yalnız o
178 okulun satırları döner; başka bir okulunki de damgasız (eski) satır da
179 dönmez. Okulsuz okur (`school=None`) HİÇBİR satır görmez — okul yokluğu
180 "hepsi" demek değildir (bkz. guard/tenant.py).
181
182 Kapsam SÜZGEÇLE ifade edilir, `limit` sonrası kırpmayla DEĞİL: aksi
183 hâlde yabancı okulun satırları `top_k`yı doldurup kendi okulunun
184 sonuçlarını dışarıda bırakırdı."""
185 from qdrant_client.models import FieldCondition, Filter, MatchValue
186 from ..guard.tenant import visible_owners
187 c = self._c()
188 q = np.asarray(query_vec, dtype=np.float32).tolist()
189 sahipler = sorted(visible_owners(school))
190 if not sahipler: # okulsuz okur → hiçbir satır yok
191 return []
192 flt = Filter(must=[FieldCondition(key="school",
193 match=MatchValue(value=sahipler[0]))])
194 res = c.query_points(self.collection, query=q, limit=top_k,
195 query_filter=flt).points
196 return [(p.payload["chunk_id"], float(p.score)) for p in res]
197
198 def __len__(self):
199 return len(self._ids)