Update rag_core.py
Browse files- rag_core.py +29 -13
rag_core.py
CHANGED
|
@@ -23,6 +23,7 @@ embedder = None
|
|
| 23 |
passage_embeddings = None
|
| 24 |
tokenizer = None
|
| 25 |
generator = None
|
|
|
|
| 26 |
|
| 27 |
|
| 28 |
def load_passage_sample(embedding_tokenizer):
|
|
@@ -234,31 +235,46 @@ def build_prompt(question, hits):
|
|
| 234 |
return prompt_text(question, context), used
|
| 235 |
|
| 236 |
|
| 237 |
-
def
|
| 238 |
-
"""
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
inputs = tokenizer(prompt, return_tensors="pt", truncation=False)
|
| 243 |
if inputs["input_ids"].shape[1] > 512:
|
| 244 |
raise ValueError("The prompt exceeds the lesson's 512-token budget.")
|
| 245 |
|
| 246 |
-
|
| 247 |
with torch.inference_mode():
|
| 248 |
-
output_ids =
|
| 249 |
-
**
|
| 250 |
max_new_tokens=64,
|
| 251 |
do_sample=False,
|
| 252 |
)
|
| 253 |
return tokenizer.decode(output_ids[0].cpu(), skip_special_tokens=True).strip()
|
| 254 |
|
| 255 |
|
| 256 |
-
def answer_question(question, retrieval_only=False, min_score=MIN_SCORE):
|
| 257 |
hits = retrieve(question)
|
| 258 |
if retrieval_only:
|
| 259 |
return {
|
| 260 |
"answer": "Retrieval only: no answer was generated.",
|
| 261 |
-
"status": "
|
| 262 |
"retrieved": hits,
|
| 263 |
"used": [],
|
| 264 |
"prompt": "",
|
|
@@ -271,13 +287,13 @@ def answer_question(question, retrieval_only=False, min_score=MIN_SCORE):
|
|
| 271 |
"used": [],
|
| 272 |
"prompt": "",
|
| 273 |
}
|
| 274 |
-
if generator is None:
|
| 275 |
-
raise RuntimeError("Run load_generator() during
|
| 276 |
prompt, used = build_prompt(question, hits)
|
| 277 |
-
answer = generate_answer(prompt)
|
| 278 |
return {
|
| 279 |
"answer": answer or NO_ANSWER,
|
| 280 |
-
"status": "
|
| 281 |
"retrieved": hits,
|
| 282 |
"used": used,
|
| 283 |
"prompt": prompt,
|
|
|
|
| 23 |
passage_embeddings = None
|
| 24 |
tokenizer = None
|
| 25 |
generator = None
|
| 26 |
+
cpu_generator = None
|
| 27 |
|
| 28 |
|
| 29 |
def load_passage_sample(embedding_tokenizer):
|
|
|
|
| 235 |
return prompt_text(question, context), used
|
| 236 |
|
| 237 |
|
| 238 |
+
def get_cpu_generator():
|
| 239 |
+
"""Load an independent CPU model only if CPU fallback is requested."""
|
| 240 |
+
global cpu_generator
|
| 241 |
+
if cpu_generator is None:
|
| 242 |
+
cpu_generator = AutoModelForSeq2SeqLM.from_pretrained(GENERATION_MODEL)
|
| 243 |
+
cpu_generator.to("cpu")
|
| 244 |
+
cpu_generator.eval()
|
| 245 |
+
return cpu_generator
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def generate_answer(prompt, device="cuda"):
|
| 249 |
+
"""Generate on ZeroGPU's CUDA worker or on a separate CPU model."""
|
| 250 |
+
if tokenizer is None:
|
| 251 |
+
raise RuntimeError("Run load_generator() at app startup first.")
|
| 252 |
+
if device not in ("cpu", "cuda"):
|
| 253 |
+
raise ValueError("device must be cpu or cuda")
|
| 254 |
+
model = generator if device == "cuda" else get_cpu_generator()
|
| 255 |
+
if model is None:
|
| 256 |
+
raise RuntimeError("Generation model was not loaded at startup.")
|
| 257 |
|
| 258 |
inputs = tokenizer(prompt, return_tensors="pt", truncation=False)
|
| 259 |
if inputs["input_ids"].shape[1] > 512:
|
| 260 |
raise ValueError("The prompt exceeds the lesson's 512-token budget.")
|
| 261 |
|
| 262 |
+
model_inputs = {name: tensor.to(device) for name, tensor in inputs.items()}
|
| 263 |
with torch.inference_mode():
|
| 264 |
+
output_ids = model.generate(
|
| 265 |
+
**model_inputs,
|
| 266 |
max_new_tokens=64,
|
| 267 |
do_sample=False,
|
| 268 |
)
|
| 269 |
return tokenizer.decode(output_ids[0].cpu(), skip_special_tokens=True).strip()
|
| 270 |
|
| 271 |
|
| 272 |
+
def answer_question(question, retrieval_only=False, min_score=MIN_SCORE, device="cuda"):
|
| 273 |
hits = retrieve(question)
|
| 274 |
if retrieval_only:
|
| 275 |
return {
|
| 276 |
"answer": "Retrieval only: no answer was generated.",
|
| 277 |
+
"status": "retrieval_only_cpu",
|
| 278 |
"retrieved": hits,
|
| 279 |
"used": [],
|
| 280 |
"prompt": "",
|
|
|
|
| 287 |
"used": [],
|
| 288 |
"prompt": "",
|
| 289 |
}
|
| 290 |
+
if tokenizer is None or generator is None:
|
| 291 |
+
raise RuntimeError("Run load_generator() during startup first.")
|
| 292 |
prompt, used = build_prompt(question, hits)
|
| 293 |
+
answer = generate_answer(prompt, device=device)
|
| 294 |
return {
|
| 295 |
"answer": answer or NO_ANSWER,
|
| 296 |
+
"status": f"generated_on_{device}",
|
| 297 |
"retrieved": hits,
|
| 298 |
"used": used,
|
| 299 |
"prompt": prompt,
|