Spaces:
Running
Running
add vector database changes
Browse files- ragbench_eval/pipeline.py +24 -2
- ragbench_eval/vector_db.py +184 -0
- requirements.txt +1 -0
ragbench_eval/pipeline.py
CHANGED
|
@@ -6,6 +6,7 @@ from .retriever import ExampleRetriever
|
|
| 6 |
from .generator import RAGGenerator
|
| 7 |
from .judge import RAGJudge
|
| 8 |
from .metrics import trace_from_attributes, compute_rmse_auc
|
|
|
|
| 9 |
|
| 10 |
|
| 11 |
class RagBenchExperiment:
|
|
@@ -38,6 +39,13 @@ class RagBenchExperiment:
|
|
| 38 |
def run_subset(self, subset: str) -> Dict[str, Any]:
|
| 39 |
ds = self._load_subset(subset)
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
y_true_rel: List[float] = []
|
| 42 |
y_pred_rel: List[float] = []
|
| 43 |
y_true_util: List[float] = []
|
|
@@ -54,9 +62,23 @@ class RagBenchExperiment:
|
|
| 54 |
question = row["question"]
|
| 55 |
docs_sentences_full = self._to_docs_sentences(row)
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
selected_docs = [docs_sentences_full[j] for j in doc_indices]
|
| 61 |
|
| 62 |
answer = self.generator.generate(question, selected_docs)
|
|
|
|
| 6 |
from .generator import RAGGenerator
|
| 7 |
from .judge import RAGJudge
|
| 8 |
from .metrics import trace_from_attributes, compute_rmse_auc
|
| 9 |
+
from .vector_db import SubsetVectorDB
|
| 10 |
|
| 11 |
|
| 12 |
class RagBenchExperiment:
|
|
|
|
| 39 |
def run_subset(self, subset: str) -> Dict[str, Any]:
|
| 40 |
ds = self._load_subset(subset)
|
| 41 |
|
| 42 |
+
# Build or load the FAISS-based vector database for this subset.
|
| 43 |
+
# This writes index files under ``vector_store/<subset>/<split>/``
|
| 44 |
+
# the first time it is called and reuses them thereafter.
|
| 45 |
+
vector_db = SubsetVectorDB(subset=subset, split=self.split)
|
| 46 |
+
vector_db.build_or_load(ds)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
y_true_rel: List[float] = []
|
| 50 |
y_pred_rel: List[float] = []
|
| 51 |
y_true_util: List[float] = []
|
|
|
|
| 62 |
question = row["question"]
|
| 63 |
docs_sentences_full = self._to_docs_sentences(row)
|
| 64 |
|
| 65 |
+
# Try vector DB first: restrict retrieval to documents that
|
| 66 |
+
# belong to this particular example row (same ``i``).
|
| 67 |
+
hits = vector_db.search(
|
| 68 |
+
question,
|
| 69 |
+
k=self.k,
|
| 70 |
+
restrict_row_index=i,
|
| 71 |
)
|
| 72 |
+
|
| 73 |
+
if hits:
|
| 74 |
+
doc_indices = [doc_idx for _, doc_idx, _ in hits]
|
| 75 |
+
else:
|
| 76 |
+
# Fallback to the original hybrid (BM25 + dense) retriever
|
| 77 |
+
# operating only over this example's documents.
|
| 78 |
+
doc_indices = self.retriever.rank_docs(
|
| 79 |
+
question, docs_sentences_full, k=self.k
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
selected_docs = [docs_sentences_full[j] for j in doc_indices]
|
| 83 |
|
| 84 |
answer = self.generator.generate(question, selected_docs)
|
ragbench_eval/vector_db.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any, Dict, List, Tuple, Optional
|
| 7 |
+
|
| 8 |
+
import faiss
|
| 9 |
+
import numpy as np
|
| 10 |
+
from datasets import Dataset, load_dataset
|
| 11 |
+
from sentence_transformers import SentenceTransformer
|
| 12 |
+
|
| 13 |
+
from .config import RAGBENCH_DATASET, EMBEDDING_MODEL
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class SubsetVectorDB:
|
| 17 |
+
"""
|
| 18 |
+
Simple FAISS-based vector database for a single RAGBench subset + split.
|
| 19 |
+
|
| 20 |
+
This class is intentionally lightweight and file-based:
|
| 21 |
+
- Each (subset, split) pair gets its own folder under ``vector_store/``.
|
| 22 |
+
- We build a single FAISS index over all documents' concatenated text.
|
| 23 |
+
- We also persist a small ``meta.json`` mapping index -> (row_index, doc_index).
|
| 24 |
+
|
| 25 |
+
At evaluation time we can:
|
| 26 |
+
- Lazily build the index once (or load it if it already exists).
|
| 27 |
+
- Retrieve the top-k most similar documents for a given question.
|
| 28 |
+
- Optionally restrict results to a particular example row.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
subset: str,
|
| 34 |
+
split: str = "test",
|
| 35 |
+
root_dir: Optional[Path] = None,
|
| 36 |
+
) -> None:
|
| 37 |
+
self.subset = subset
|
| 38 |
+
self.split = split
|
| 39 |
+
|
| 40 |
+
project_root = Path(__file__).resolve().parents[1]
|
| 41 |
+
self.root_dir = (root_dir or project_root / "vector_store").resolve()
|
| 42 |
+
self.index_dir = self.root_dir / subset / split
|
| 43 |
+
self.index_dir.mkdir(parents=True, exist_ok=True)
|
| 44 |
+
|
| 45 |
+
self.index_path = self.index_dir / "index.faiss"
|
| 46 |
+
self.meta_path = self.index_dir / "meta.json"
|
| 47 |
+
|
| 48 |
+
# Will be populated by ``build_or_load``
|
| 49 |
+
self.embedder: Optional[SentenceTransformer] = None
|
| 50 |
+
self.index: Optional[faiss.Index] = None
|
| 51 |
+
self.meta: List[Dict[str, Any]] = []
|
| 52 |
+
|
| 53 |
+
# ------------------------------------------------------------------
|
| 54 |
+
# Internal helpers
|
| 55 |
+
# ------------------------------------------------------------------
|
| 56 |
+
def _load_embedder(self) -> SentenceTransformer:
|
| 57 |
+
if self.embedder is None:
|
| 58 |
+
self.embedder = SentenceTransformer(EMBEDDING_MODEL)
|
| 59 |
+
return self.embedder
|
| 60 |
+
|
| 61 |
+
def _load_index_files(self) -> bool:
|
| 62 |
+
"""
|
| 63 |
+
Try to load index + meta files from disk.
|
| 64 |
+
|
| 65 |
+
Returns True if successful, False if anything is missing.
|
| 66 |
+
"""
|
| 67 |
+
if not self.index_path.exists() or not self.meta_path.exists():
|
| 68 |
+
return False
|
| 69 |
+
|
| 70 |
+
self.index = faiss.read_index(str(self.index_path))
|
| 71 |
+
with self.meta_path.open("r", encoding="utf-8") as f:
|
| 72 |
+
self.meta = json.load(f)
|
| 73 |
+
return True
|
| 74 |
+
|
| 75 |
+
# ------------------------------------------------------------------
|
| 76 |
+
# Public API
|
| 77 |
+
# ------------------------------------------------------------------
|
| 78 |
+
def build_or_load(self, ds: Optional[Dataset] = None) -> None:
|
| 79 |
+
"""
|
| 80 |
+
Ensure the FAISS index exists for (subset, split).
|
| 81 |
+
|
| 82 |
+
If the index files are already on disk we simply load them.
|
| 83 |
+
Otherwise we:
|
| 84 |
+
- iterate over the dataset
|
| 85 |
+
- concatenate each document's sentences into a single string
|
| 86 |
+
- build a dense embedding using SentenceTransformers
|
| 87 |
+
- create a cosine-similarity FAISS index and persist it
|
| 88 |
+
"""
|
| 89 |
+
if self._load_index_files():
|
| 90 |
+
return
|
| 91 |
+
|
| 92 |
+
if ds is None:
|
| 93 |
+
ds = load_dataset(RAGBENCH_DATASET, self.subset, split=self.split)
|
| 94 |
+
|
| 95 |
+
texts: List[str] = []
|
| 96 |
+
meta: List[Dict[str, Any]] = []
|
| 97 |
+
|
| 98 |
+
for row_idx, row in enumerate(ds):
|
| 99 |
+
# ``documents_sentences`` is a list of docs;
|
| 100 |
+
# each doc is a list of (sentence_key, sentence_text) pairs.
|
| 101 |
+
for doc_idx, doc in enumerate(row["documents_sentences"]):
|
| 102 |
+
doc_text = " ".join(sentence_text for _, sentence_text in doc)
|
| 103 |
+
texts.append(doc_text)
|
| 104 |
+
meta.append({"row_index": int(row_idx), "doc_index": int(doc_idx)})
|
| 105 |
+
|
| 106 |
+
if not texts:
|
| 107 |
+
raise ValueError(
|
| 108 |
+
f"No documents found while building vector DB for subset={self.subset}, split={self.split}"
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
embedder = self._load_embedder()
|
| 112 |
+
embeddings = embedder.encode(
|
| 113 |
+
texts,
|
| 114 |
+
batch_size=32,
|
| 115 |
+
show_progress_bar=True,
|
| 116 |
+
convert_to_numpy=True,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# FAISS expects float32
|
| 120 |
+
embeddings = np.asarray(embeddings, dtype="float32")
|
| 121 |
+
# Use cosine similarity via inner product on L2-normalized vectors
|
| 122 |
+
faiss.normalize_L2(embeddings)
|
| 123 |
+
|
| 124 |
+
dim = embeddings.shape[1]
|
| 125 |
+
index = faiss.IndexFlatIP(dim)
|
| 126 |
+
index.add(embeddings)
|
| 127 |
+
|
| 128 |
+
# Persist to disk so subsequent runs are cheap
|
| 129 |
+
faiss.write_index(index, str(self.index_path))
|
| 130 |
+
with self.meta_path.open("w", encoding="utf-8") as f:
|
| 131 |
+
json.dump(meta, f, indent=2)
|
| 132 |
+
|
| 133 |
+
self.index = index
|
| 134 |
+
self.meta = meta
|
| 135 |
+
|
| 136 |
+
def search(
|
| 137 |
+
self,
|
| 138 |
+
query: str,
|
| 139 |
+
k: int = 10,
|
| 140 |
+
restrict_row_index: Optional[int] = None,
|
| 141 |
+
) -> List[Tuple[int, int, float]]:
|
| 142 |
+
"""
|
| 143 |
+
Search the vector DB for the top-k documents relevant to ``query``.
|
| 144 |
+
|
| 145 |
+
Returns a list of (row_index, doc_index, score) tuples.
|
| 146 |
+
If ``restrict_row_index`` is provided, we will over-sample and then
|
| 147 |
+
filter to only documents that belong to that example row.
|
| 148 |
+
"""
|
| 149 |
+
if self.index is None or not self.meta:
|
| 150 |
+
if not self._load_index_files():
|
| 151 |
+
raise RuntimeError(
|
| 152 |
+
"Vector DB has not been built yet. Call build_or_load() first."
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
embedder = self._load_embedder()
|
| 156 |
+
q_emb = embedder.encode([query], convert_to_numpy=True)
|
| 157 |
+
q_emb = np.asarray(q_emb, dtype="float32")
|
| 158 |
+
faiss.normalize_L2(q_emb)
|
| 159 |
+
|
| 160 |
+
# For restricted searches we over-sample so that filtering still leaves
|
| 161 |
+
# enough candidates. For unrestricted we just use k.
|
| 162 |
+
search_k = k * 10 if restrict_row_index is not None else k
|
| 163 |
+
search_k = max(search_k, k)
|
| 164 |
+
|
| 165 |
+
scores, indices = self.index.search(q_emb, search_k)
|
| 166 |
+
scores = scores[0]
|
| 167 |
+
indices = indices[0]
|
| 168 |
+
|
| 169 |
+
results: List[Tuple[int, int, float]] = []
|
| 170 |
+
for idx, score in zip(indices, scores):
|
| 171 |
+
if idx < 0 or idx >= len(self.meta):
|
| 172 |
+
continue
|
| 173 |
+
meta = self.meta[int(idx)]
|
| 174 |
+
row_index = meta["row_index"]
|
| 175 |
+
doc_index = meta["doc_index"]
|
| 176 |
+
|
| 177 |
+
if restrict_row_index is not None and row_index != restrict_row_index:
|
| 178 |
+
continue
|
| 179 |
+
|
| 180 |
+
results.append((row_index, doc_index, float(score)))
|
| 181 |
+
if len(results) >= k:
|
| 182 |
+
break
|
| 183 |
+
|
| 184 |
+
return results
|
requirements.txt
CHANGED
|
@@ -11,3 +11,4 @@ groq==0.9.0
|
|
| 11 |
httpx==0.27.2
|
| 12 |
rank-bm25==0.2.2
|
| 13 |
|
|
|
|
|
|
| 11 |
httpx==0.27.2
|
| 12 |
rank-bm25==0.2.2
|
| 13 |
|
| 14 |
+
faiss-cpu==1.8.0.post1
|