forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiBaaf05cfKadir Yönak2 months ago112 commits

embedder.py127 lines, 5.8 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
9from typing import Protocol
10
11import numpy as np
12
13
14def cosine_sim(a, b) -> float:
15 a = np.asarray(a, dtype=np.float32); b = np.asarray(b, dtype=np.float32)
16 na = np.linalg.norm(a); nb = np.linalg.norm(b)
17 if na == 0 or nb == 0:
18 return 0.0
19 return float(np.dot(a, b) / (na * nb))
20
21
22def cosine_matrix(query, matrix) -> np.ndarray:
23 """query (d,) ile matrix (n,d) arasında cosine skorları (n,). Satırlar normalize varsayılmaz."""
24 q = np.asarray(query, dtype=np.float32)
25 m = np.asarray(matrix, dtype=np.float32)
26 qn = q / (np.linalg.norm(q) + 1e-12)
27 mn = m / (np.linalg.norm(m, axis=1, keepdims=True) + 1e-12)
28 return mn @ qn
29
30
31class Embedder(Protocol):
32 dim: int
33 def embed(self, texts: list[str], batch_size: int = 12) -> np.ndarray: ...
34
35
36# FlagEmbedding, repo'nun TAMAMINI (onnx/model.onnx_data ~2GB dahil) snapshot_download
37# ile ister; biz yalnız PyTorch modelini kullandığımız için sadece gerekli dosyaları
38# çekeriz. Böylece 2GB onnx inmez ve cache tam sayılmadığı için üretilen
39# IncompleteSnapshotError'dan kaçınılır.
40_NEEDED_PATTERNS = ["*.json", "*.model", "pytorch_model.bin", "model.safetensors",
41 "sentencepiece*", "tokenizer*", "config*",
42 "colbert_linear.pt", "sparse_linear.pt"]
43
44
45class BGEM3Embedder:
46 """BGE-M3 (BAAI/bge-m3). Dense 1024-dim + opsiyonel sparse."""
47 dim = 1024
48
49 def __init__(self, model_name: str = "BAAI/bge-m3", use_fp16: bool | None = None,
50 max_length: int = 8192, cache=None):
51 self.model_name = model_name
52 self.max_length = max_length
53 self._use_fp16 = use_fp16
54 self._model = None
55 # Opsiyonel EmbeddingCache (bkz. src/cache/embedding_cache.py). None ise
56 # davranış ÖNCEKİYLE BİREBİR AYNI (mevcut testler bozulmaz).
57 self.cache = cache
58
59 def _resolve_model_path(self) -> str:
60 """Model dizinini çöz: yerel dizinse doğrudan; değilse yalnız gerekli
61 dosyaları (onnx hariç) cache'ten ver, yoksa indir. FlagEmbedding yerel
62 dizin görünce snapshot_download'ı atlar (2GB onnx istemez)."""
63 import os
64 if os.path.isdir(self.model_name):
65 return self.model_name
66 from huggingface_hub import snapshot_download
67 try: # önce cache (ağsız)
68 return snapshot_download(self.model_name, allow_patterns=_NEEDED_PATTERNS,
69 local_files_only=True)
70 except Exception: # cache yok → gerekli dosyaları indir
71 return snapshot_download(self.model_name, allow_patterns=_NEEDED_PATTERNS)
72
73 def _load(self):
74 if self._model is None:
75 import torch
76 from FlagEmbedding import BGEM3FlagModel
77 fp16 = self._use_fp16
78 if fp16 is None:
79 fp16 = torch.cuda.is_available() # fp16 yalnız GPU'da
80 self._model = BGEM3FlagModel(self._resolve_model_path(), use_fp16=fp16)
81 return self._model
82
83 @property
84 def loaded(self) -> bool:
85 return self._model is not None
86
87 def embed(self, texts: list[str], batch_size: int = 12) -> np.ndarray:
88 """Dense embedding matrisi (n, 1024), L2-normalize.
89
90 `self.cache` verilmişse cache-aware: cache'te ZATEN olan metinler modele
91 HİÇ GÖNDERİLMEZ, yalnız miss olan metinler modele verilir + sonuç cache'e
92 yazılır (batch miss-merge — bkz. src/cache/embedding_cache.py). Cache
93 yoksa davranış ÖNCEKİYLE BİREBİR AYNI (regresyon yok)."""
94 if not texts:
95 return np.zeros((0, self.dim), dtype=np.float32)
96 if self.cache is None:
97 out = self._load().encode(texts, batch_size=batch_size,
98 max_length=self.max_length,
99 return_dense=True, return_sparse=False)
100 return np.asarray(out["dense_vecs"], dtype=np.float32)
101
102 hits, misses = self.cache.get_many(texts, model=self.model_name)
103 if misses:
104 out = self._load().encode(misses, batch_size=batch_size,
105 max_length=self.max_length,
106 return_dense=True, return_sparse=False)
107 new_vecs = np.asarray(out["dense_vecs"], dtype=np.float32)
108 new_items = {t: new_vecs[i] for i, t in enumerate(misses)}
109 self.cache.set_many(new_items, model=self.model_name)
110 hits.update(new_items)
111 # giriş sırasını koru (aynı metin tekrar geçse bile aynı vektörü döndürür)
112 return np.asarray([hits[t] for t in texts], dtype=np.float32)
113
114 def embed_sparse(self, texts: list[str], batch_size: int = 12) -> list[dict]:
115 """Sparse (lexical) ağırlıklar — hibrit retrieval için (token-id -> ağırlık)."""
116 if not texts:
117 return []
118 out = self._load().encode(texts, batch_size=batch_size,
119 max_length=self.max_length,
120 return_dense=False, return_sparse=True)
121 return list(out["lexical_weights"])
122
123 def embed_chunks(self, chunks, batch_size: int = 12):
124 """Chunk listesi → (chunk_id listesi, dense matris). chunk.text embed edilir."""
125 ids = [c.chunk_id for c in chunks]
126 vecs = self.embed([c.text for c in chunks], batch_size=batch_size)
127 return ids, vecs