-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathqa_faiss_builder.py
More file actions
300 lines (244 loc) Β· 11.8 KB
/
Copy pathqa_faiss_builder.py
File metadata and controls
300 lines (244 loc) Β· 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#!/usr/bin/env python3
"""
Q&A-Based FAISS Vector Store Builder for AutoRAG Pipeline
Builds FAISS index from SELECTED Q&A pairs, not raw PDF text.
This is the correct approach - we use our curated Q&A pairs as the knowledge base.
"""
import os
import json
import argparse
import warnings
from pathlib import Path
from typing import List, Dict, Any, Tuple
import numpy as np
from sentence_transformers import SentenceTransformer
# Handle FAISS imports with graceful fallbacks
try:
import faiss
FAISS_AVAILABLE = True
except ImportError:
FAISS_AVAILABLE = False
warnings.warn("FAISS not available. Install with: pip install faiss-cpu faiss-gpu")
def build_qa_vector_store(qa_pairs_file: Path,
output_dir: Path,
embedding_model: str = 'all-MiniLM-L6-v2',
build_adaptive: bool = True) -> None:
"""
Build FAISS vector stores from selected Q&A pairs.
Creates both Standard and Adaptive RAG indices for CPU/GPU.
Args:
qa_pairs_file: JSON file with selected Q&A pairs
output_dir: Directory to save FAISS indices and metadata
embedding_model: SentenceTransformer model name
build_adaptive: Whether to build adaptive RAG indices (default: True)
Outputs:
- qa_faiss_index_standard_cpu.bin (Standard RAG - CPU)
- qa_faiss_index_standard_gpu.bin (Standard RAG - GPU)
- qa_faiss_index_adaptive_cpu.bin (Adaptive RAG - CPU)
- qa_faiss_index_adaptive_gpu.bin (Adaptive RAG - GPU)
"""
if not FAISS_AVAILABLE:
raise RuntimeError("FAISS not available. Install with: pip install faiss-cpu")
output_dir.mkdir(parents=True, exist_ok=True)
print(f'π₯ Loading Q&A pairs from: {qa_pairs_file}')
with open(qa_pairs_file, 'r', encoding='utf-8') as f:
qa_pairs = json.load(f)
print(f'π Loaded {len(qa_pairs)} Q&A pairs for vector store')
# Load embedding model
print(f'π§ Loading embedding model: {embedding_model}')
model = SentenceTransformer(embedding_model)
# Prepare texts for embedding (we'll embed the answers as our knowledge base)
texts = []
qa_metadata = []
for i, pair in enumerate(qa_pairs):
# Use answer as the knowledge base content (handle both HF and QA formats)
answer_text = pair.get('output', pair.get('answer', ''))
question_text = pair.get('instruction', pair.get('question', ''))
if len(answer_text.strip()) < 10: # Skip very short answers
print(f' β οΈ Skipping pair {i}: answer too short ({len(answer_text)} chars)')
continue
texts.append(answer_text)
qa_metadata.append({
'id': i,
'question': question_text,
'answer': answer_text,
'source_info': pair.get('source_info', {}),
'quality_score': pair.get('quality_score', 0.0),
'matrix_combination': pair.get('matrix_combination', ''),
'metadata': pair.get('metadata', {})
})
print(f'π Building vector store with {len(texts)} answer embeddings')
# Generate embeddings
print('π Generating embeddings...')
embeddings = model.encode(texts, show_progress_bar=True, convert_to_numpy=True)
print(f'β
Generated embeddings shape: {embeddings.shape}')
if len(embeddings) == 0:
raise ValueError("No embeddings generated - all answers may be too short or empty")
# Build FAISS index
dimension = embeddings.shape[1]
# Use IndexFlatIP for inner product similarity (good for sentence embeddings)
cpu_index = faiss.IndexFlatIP(dimension)
# Normalize embeddings for cosine similarity
faiss.normalize_L2(embeddings)
# Add embeddings to CPU index first
cpu_index.add(embeddings.astype(np.float32))
print(f'ποΈ Built base FAISS index with {cpu_index.ntotal} vectors')
# Initialize tracking of created indices
created_indices = {}
# 1. Standard RAG Indices (traditional approach)
print('\nπΉ Building Standard RAG indices...')
# Standard CPU index (copy of original)
standard_cpu_index = faiss.IndexFlatIP(dimension)
standard_cpu_index.add(embeddings.astype(np.float32))
standard_cpu_path = output_dir / 'qa_faiss_index_standard_cpu.bin'
faiss.write_index(standard_cpu_index, str(standard_cpu_path))
print(f'πΎ Standard CPU index: {standard_cpu_path}')
created_indices['standard_cpu'] = str(standard_cpu_path)
# Standard GPU index
gpu_available = False
try:
if faiss.get_num_gpus() > 0:
print('π Creating Standard GPU index...')
res = faiss.StandardGpuResources()
standard_gpu_index = faiss.index_cpu_to_gpu(res, 0, standard_cpu_index)
standard_gpu_path = output_dir / 'qa_faiss_index_standard_gpu.bin'
cpu_from_gpu = faiss.index_gpu_to_cpu(standard_gpu_index)
faiss.write_index(cpu_from_gpu, str(standard_gpu_path))
print(f'πΎ Standard GPU index: {standard_gpu_path}')
created_indices['standard_gpu'] = str(standard_gpu_path)
gpu_available = True
else:
print('β οΈ No GPU detected for standard indices')
except Exception as e:
print(f'β οΈ Standard GPU index creation failed: {e}')
# 2. Adaptive RAG Indices (enhanced approach)
if build_adaptive:
print('\nπΈ Building Adaptive RAG indices...')
# For adaptive RAG, we create embeddings that combine Q&A for better context matching
adaptive_texts = []
for pair in qa_pairs:
question = pair.get('instruction', pair.get('question', ''))
answer = pair.get('output', pair.get('answer', ''))
# Combine Q&A for richer semantic understanding
combined_text = f"Q: {question} A: {answer}"
adaptive_texts.append(combined_text)
# Generate adaptive embeddings
print('π Generating adaptive embeddings (Q+A combined)...')
adaptive_embeddings = model.encode(adaptive_texts, show_progress_bar=True, convert_to_numpy=True)
faiss.normalize_L2(adaptive_embeddings)
# Adaptive CPU index
adaptive_cpu_index = faiss.IndexFlatIP(dimension)
adaptive_cpu_index.add(adaptive_embeddings.astype(np.float32))
adaptive_cpu_path = output_dir / 'qa_faiss_index_adaptive_cpu.bin'
faiss.write_index(adaptive_cpu_index, str(adaptive_cpu_path))
print(f'πΎ Adaptive CPU index: {adaptive_cpu_path}')
created_indices['adaptive_cpu'] = str(adaptive_cpu_path)
# Adaptive GPU index
try:
if gpu_available:
print('π Creating Adaptive GPU index...')
res = faiss.StandardGpuResources()
adaptive_gpu_index = faiss.index_cpu_to_gpu(res, 0, adaptive_cpu_index)
adaptive_gpu_path = output_dir / 'qa_faiss_index_adaptive_gpu.bin'
cpu_from_gpu = faiss.index_gpu_to_cpu(adaptive_gpu_index)
faiss.write_index(cpu_from_gpu, str(adaptive_gpu_path))
print(f'πΎ Adaptive GPU index: {adaptive_gpu_path}')
created_indices['adaptive_gpu'] = str(adaptive_gpu_path)
except Exception as e:
print(f'β οΈ Adaptive GPU index creation failed: {e}')
# Initialize comprehensive model info
model_info = {
'embedding_model': embedding_model,
'dimension': int(dimension),
'total_vectors': int(standard_cpu_index.ntotal),
'index_type': 'IndexFlatIP',
'similarity_metric': 'cosine',
'normalized': True,
'gpu_available': gpu_available,
'adaptive_enabled': build_adaptive,
'created_indices': created_indices,
'rag_approaches': {
'standard': {
'description': 'Traditional RAG using answer embeddings only',
'embedding_strategy': 'answer_text_only',
'use_case': 'Fast retrieval, direct answer matching'
},
'adaptive': {
'description': 'Enhanced RAG using combined Q+A embeddings',
'embedding_strategy': 'question_answer_combined',
'use_case': 'Context-aware retrieval, better semantic matching'
}
}
}
# Legacy compatibility - create symlinks to standard indices
legacy_cpu_path = output_dir / 'qa_faiss_index_cpu.bin'
legacy_gpu_path = output_dir / 'qa_faiss_index_gpu.bin'
try:
if legacy_cpu_path.exists():
legacy_cpu_path.unlink()
legacy_cpu_path.symlink_to('qa_faiss_index_standard_cpu.bin')
print(f'π Legacy compatibility: {legacy_cpu_path} -> standard_cpu')
if gpu_available and 'standard_gpu' in created_indices:
if legacy_gpu_path.exists():
legacy_gpu_path.unlink()
legacy_gpu_path.symlink_to('qa_faiss_index_standard_gpu.bin')
print(f'π Legacy compatibility: {legacy_gpu_path} -> standard_gpu')
except Exception as e:
print(f'β οΈ Could not create legacy symlinks: {e}')
# Save metadata
metadata_path = output_dir / 'qa_metadata.json'
with open(metadata_path, 'w', encoding='utf-8') as f:
json.dump(qa_metadata, f, indent=2, ensure_ascii=False)
print(f'πΎ Saved metadata: {metadata_path}')
info_path = output_dir / 'model_info.json'
with open(info_path, 'w') as f:
json.dump(model_info, f, indent=2)
print(f'πΎ Saved model info: {info_path}')
print('β
Q&A vector store built successfully!')
print(f' - CPU FAISS Index: {cpu_index_path}')
print(f' - Metadata: {metadata_path}')
print(f' - Model Info: {info_path}')
def main():
parser = argparse.ArgumentParser(description='Build Q&A-based FAISS vector stores (Standard + Adaptive RAG)')
parser.add_argument('--qa-pairs-file', type=Path, required=True,
help='JSON file with selected Q&A pairs')
parser.add_argument('--output-dir', type=Path, required=True,
help='Output directory for FAISS indices')
parser.add_argument('--embedding-model', default='all-MiniLM-L6-v2',
help='SentenceTransformer model name')
parser.add_argument('--no-adaptive', action='store_true',
help='Skip building adaptive RAG indices (build standard only)')
parser.add_argument('--verbose', action='store_true',
help='Enable verbose output')
args = parser.parse_args()
print('ποΈ Q&A FAISS Vector Store Builder')
print('=' * 50)
print(f'Q&A Pairs: {args.qa_pairs_file}')
print(f'Output Dir: {args.output_dir}')
print(f'Embedding Model: {args.embedding_model}')
print(f'Build Adaptive: {not args.no_adaptive}')
print()
try:
build_qa_vector_store(
qa_pairs_file=args.qa_pairs_file,
output_dir=args.output_dir,
embedding_model=args.embedding_model,
build_adaptive=not args.no_adaptive
)
print('\nπ SUCCESS: Vector store(s) built successfully!')
print(f'π Output directory: {args.output_dir}')
# Show what was created
output_files = list(args.output_dir.glob('*.bin'))
if output_files:
print('\nπ¦ Created FAISS indices:')
for file in sorted(output_files):
print(f' β’ {file.name}')
except Exception as e:
print(f'β Error building Q&A vector store: {e}')
if args.verbose:
import traceback
traceback.print_exc()
return 1
return 0
if __name__ == '__main__':
exit(main())