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

embedder.py201 lines, 9.4 KiBHistoryRawDownload
1"""Faz 1.2 — BGE-M3 embedder (dense + sparse).
2
3Sağlayıcı-değiştirilebilir arayüz (`Embedder`): ileride e5-large/TurkEmbed baseline
4aynı arayüzle eklenir (mimari §0.1: model = aday, benchmark'ta yarışır).
5Model **lazy** yüklenir → import ucuz, testte model olmadan da kurulabilir.
6GPU varsa otomatik kullanılır (fp16). Dense vektörler L2-normalize (cosine = dot).
7"""
8from __future__ import annotations
9
10import os
11import threading
12from typing import Protocol
13
14import numpy as np
15
16
17def cosine_sim(a, b) -> float:
18 a = np.asarray(a, dtype=np.float32); b = np.asarray(b, dtype=np.float32)
19 na = np.linalg.norm(a); nb = np.linalg.norm(b)
20 if na == 0 or nb == 0:
21 return 0.0
22 return float(np.dot(a, b) / (na * nb))
23
24
25def cosine_matrix(query, matrix) -> np.ndarray:
26 """query (d,) ile matrix (n,d) arasında cosine skorları (n,). Satırlar normalize varsayılmaz."""
27 q = np.asarray(query, dtype=np.float32)
28 m = np.asarray(matrix, dtype=np.float32)
29 qn = q / (np.linalg.norm(q) + 1e-12)
30 mn = m / (np.linalg.norm(m, axis=1, keepdims=True) + 1e-12)
31 return mn @ qn
32
33
34# #80: model surumu PINLENEBILIR olmali. `snapshot_download`'a `revision`
35# verilmediginde her indirme depo HEAD'ini alir; yayinci agirligi guncellerse
36# UYGULAMA SESSIZCE BASKA BIR MODELE GECER ve olculmus butun sayilar (kapi
37# degerleri dahil) o modele ait OLMAKTAN CIKAR. Bos birakmak eski davranistir;
38# uretimde bir commit sha'si verilmelidir.
39MODEL_REVISION = os.environ.get("HEZARFEN_EMBED_REVISION") or None
40
41
42class Embedder(Protocol):
43 dim: int
44 def embed(self, texts: list[str], batch_size: int = 12) -> np.ndarray: ...
45
46
47# FlagEmbedding, repo'nun TAMAMINI (onnx/model.onnx_data ~2GB dahil) snapshot_download
48# ile ister; biz yalnız PyTorch modelini kullandığımız için sadece gerekli dosyaları
49# çekeriz. Böylece 2GB onnx inmez ve cache tam sayılmadığı için üretilen
50# IncompleteSnapshotError'dan kaçınılır.
51_NEEDED_PATTERNS = ["*.json", "*.model", "pytorch_model.bin", "model.safetensors",
52 "sentencepiece*", "tokenizer*", "config*",
53 "colbert_linear.pt", "sparse_linear.pt"]
54
55
56class BGEM3Embedder:
57 """BGE-M3 (BAAI/bge-m3). Dense 1024-dim + opsiyonel sparse."""
58 dim = 1024
59
60 def __init__(self, model_name: str = "BAAI/bge-m3", use_fp16: bool | None = None,
61 max_length: int = 8192, cache=None):
62 self.model_name = model_name
63 self.max_length = max_length
64 self._use_fp16 = use_fp16
65 self._model = None
66 # #80: cift-kontrollu kilit (bkz. `_load`)
67 self._load_lock = threading.Lock()
68 # Opsiyonel EmbeddingCache (bkz. src/cache/embedding_cache.py). None ise
69 # davranış ÖNCEKİYLE BİREBİR AYNI (mevcut testler bozulmaz).
70 self.cache = cache
71
72 def _resolve_model_path(self) -> str:
73 """Model dizinini çöz: yerel dizinse doğrudan; değilse yalnız gerekli
74 dosyaları (onnx hariç) cache'ten ver, yoksa indir. FlagEmbedding yerel
75 dizin görünce snapshot_download'ı atlar (2GB onnx istemez)."""
76 import os
77 if os.path.isdir(self.model_name):
78 return self.model_name
79 from huggingface_hub import snapshot_download
80 try: # önce cache (ağsız)
81 return snapshot_download(self.model_name, allow_patterns=_NEEDED_PATTERNS,
82 revision=MODEL_REVISION, local_files_only=True)
83 except Exception: # cache yok → gerekli dosyaları indir
84 return snapshot_download(self.model_name, allow_patterns=_NEEDED_PATTERNS,
85 revision=MODEL_REVISION)
86
87
88# M4-6 (#80, EXP-010/OPS-07) -- MODEL YASAM DONGUSU.
89#
90# KOSULARAK KANITLANDI: `_load` kontrol-sonra-ata (check-then-set) desenindeydi
91# ve HIC KILIT YOKTU. FastAPI uc noktalari `def` (sync) oldugu icin Starlette
92# bunlari anyio worker havuzunda (varsayilan 40) GERCEKTEN paralel kosturuyor.
93# Gercek sinifla olculdu: 8 thread -> **8 model yuklemesi** (1 olmaliydi).
94#
95# Basarisizlik: soguk servise 8 ogrenci ayni anda sorarsa BGE-M3 (+reranker)
96# 8 kez paralel yuklenir -> 8 paralel snapshot_download (~2,3 GB x 2 model)
97# ve/veya 8 kopya agirlik RAM'de -> OOM-kill. Hayatta kalsa bile yalniz son
98# atanan ornek kullanilir (digerleri bosa harcanmis is).
99#
100# CIFT KONTROLLU KILIT: hizli yol (model zaten yuklu) kilide HIC girmez;
101# yalniz ilk yukleme serilesir.
102 def _load(self):
103 if self._model is not None: # hızlı yol: kilide girme
104 return self._model
105 with self._load_lock:
106 if self._model is None: # ikinci kontrol (kilit altında)
107 self._model = self._build_model()
108 return self._model
109
110 def _build_model(self):
111 """Ağır yükleme — AYRI bir metot, çünkü eşzamanlılık sözleşmesi
112 (tam bir kez yükleme) torch'u hiç içe aktarmadan test edilebilmeli.
113
114 Testlerde `sys.modules["FlagEmbedding"]` yamalamak torch'un C uzantı
115 importunu bozuyordu (`SystemError: bad call flags`) — ürün hatası
116 değil ama kırılgan bir dikiş. Buradan yamalanır."""
117 import torch
118 from FlagEmbedding import BGEM3FlagModel
119 fp16 = self._use_fp16
120 if fp16 is None:
121 fp16 = torch.cuda.is_available() # fp16 yalnız GPU'da
122 return BGEM3FlagModel(self._resolve_model_path(), use_fp16=fp16)
123
124 def warmup(self):
125 """Modeli AÇILIŞTA yükle — ilk isteği bekletmemek için.
126
127 Servis `main()` boru hattını arka planda kurarken bu zaten çağrılır
128 (#82); ayrıca elle/lifespan'dan çağrılabilir."""
129 self._load()
130 return self
131
132 @property
133 def loaded(self) -> bool:
134 return self._model is not None
135
136 def embed(self, texts: list[str], batch_size: int = 12) -> np.ndarray:
137 """Dense embedding matrisi (n, 1024), L2-normalize.
138
139 `self.cache` verilmişse cache-aware: cache'te ZATEN olan metinler modele
140 HİÇ GÖNDERİLMEZ, yalnız miss olan metinler modele verilir + sonuç cache'e
141 yazılır (batch miss-merge — bkz. src/cache/embedding_cache.py). Cache
142 yoksa davranış ÖNCEKİYLE BİREBİR AYNI (regresyon yok)."""
143 if not texts:
144 return np.zeros((0, self.dim), dtype=np.float32)
145 if self.cache is None:
146 out = self._load().encode(texts, batch_size=batch_size,
147 max_length=self.max_length,
148 return_dense=True, return_sparse=False)
149 return np.asarray(out["dense_vecs"], dtype=np.float32)
150
151 hits, misses = self.cache.get_many(texts, model=self.model_name)
152 if misses:
153 out = self._load().encode(misses, batch_size=batch_size,
154 max_length=self.max_length,
155 return_dense=True, return_sparse=False)
156 new_vecs = np.asarray(out["dense_vecs"], dtype=np.float32)
157 new_items = {t: new_vecs[i] for i, t in enumerate(misses)}
158 self.cache.set_many(new_items, model=self.model_name)
159 hits.update(new_items)
160 # giriş sırasını koru (aynı metin tekrar geçse bile aynı vektörü döndürür)
161 return np.asarray([hits[t] for t in texts], dtype=np.float32)
162
163 def embed_sparse(self, texts: list[str], batch_size: int = 12) -> list[dict]:
164 """Sparse (lexical) ağırlıklar — hibrit retrieval için (token-id -> ağırlık)."""
165 if not texts:
166 return []
167 out = self._load().encode(texts, batch_size=batch_size,
168 max_length=self.max_length,
169 return_dense=False, return_sparse=True)
170 return list(out["lexical_weights"])
171
172 def embed_chunks(self, chunks, batch_size: int = 12):
173 """Chunk listesi → (chunk_id listesi, dense matris). chunk.text embed edilir."""
174 ids = [c.chunk_id for c in chunks]
175 vecs = self.embed([c.text for c in chunks], batch_size=batch_size)
176 return ids, vecs
177
178 def embed_both(self, texts: list[str], batch_size: int = 12):
179 """Dense + sparse'ı **TEK geçişte** üretir → `(matris, lexical_weights)`.
180
181 #82 (EXP-010/OPS-10): `embed()` ve `embed_sparse()` ayrı çağrıldığında
182 korpus **iki kez** kodlanıyor — soğuk başlangıçta bu, tokenize+forward
183 maliyetinin iki katı demek. Hesaplanan: BGE-M3 CPU'da 4,1 chunk/s →
184 258 chunk ≈ 63 s, **iki geçiş ≈ 126 s**; üstüne PDF parse (ölçüldü:
185 194 sayfa = 28,2 s) → **~155 s sağır servis**.
186
187 Model zaten tek `encode()` çağrısında ikisini birden döndürebiliyor.
188
189 DÜRÜST SINIR: bu yol embedding **cache'ini kullanmaz**. Cache yalnız
190 dense içindir (`embedding_cache` dense vektör saklar); sparse için
191 karşılığı yok. Bu yüzden `embed_both`, cache'in işe yaradığı
192 ARTIMLI güncellemelerde değil, **ilk kurulumda** (tamamen soğuk) tercih
193 edilmelidir. Çağıran hangisini kullanacağına karar verir.
194 """
195 if not texts:
196 return np.zeros((0, self.dim), dtype=np.float32), []
197 out = self._load().encode(texts, batch_size=batch_size,
198 max_length=self.max_length,
199 return_dense=True, return_sparse=True)
200 return (np.asarray(out["dense_vecs"], dtype=np.float32),
201 list(out["lexical_weights"]))