Upload pipeline.py with huggingface_hub
Browse files- pipeline.py +40 -0
pipeline.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import json, torch, numpy as np
|
| 3 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder
|
| 4 |
+
import faiss
|
| 5 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 6 |
+
|
| 7 |
+
class Chronos:
|
| 8 |
+
def __init__(self, model_dir="."):
|
| 9 |
+
with open(f"{model_dir}/rag_config.json") as f:
|
| 10 |
+
config = json.load(f)
|
| 11 |
+
self.embedder = SentenceTransformer(config["embedder_model"])
|
| 12 |
+
self.index = faiss.read_index(f"{model_dir}/jjk_index.faiss")
|
| 13 |
+
with open(f"{model_dir}/chunks.txt", "r", encoding="utf-8") as f:
|
| 14 |
+
raw = f.read().split("<|CHUNK_END|>")
|
| 15 |
+
self.chunks = [c.strip() for c in raw if c.strip()]
|
| 16 |
+
self.reranker = CrossEncoder(f"{model_dir}/cross_encoder_model")
|
| 17 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
|
| 18 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 19 |
+
model_dir, torch_dtype=torch.float16, device_map='auto', trust_remote_code=True
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def ask(self, question, max_tokens=350):
|
| 23 |
+
q_emb = self.embedder.encode([question]).astype('float32')
|
| 24 |
+
_, indices = self.index.search(q_emb, 30)
|
| 25 |
+
candidates = [self.chunks[i] for i in indices[0]]
|
| 26 |
+
pairs = [(question, c) for c in candidates]
|
| 27 |
+
scores = self.reranker.predict(pairs)
|
| 28 |
+
best = sorted(zip(scores, candidates), reverse=True)[:4]
|
| 29 |
+
context = "\n\n".join([c for _, c in best])
|
| 30 |
+
messages = [
|
| 31 |
+
{"role": "system", "content": "You are Chronos, a historian specializing in the 20th century. Use the provided Wikipedia context to answer accurately. Be detailed but concise and friendly."},
|
| 32 |
+
{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"}
|
| 33 |
+
]
|
| 34 |
+
prompt = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 35 |
+
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.model.device)
|
| 36 |
+
outputs = self.model.generate(**inputs, max_new_tokens=max_tokens,
|
| 37 |
+
temperature=0.7, do_sample=True,
|
| 38 |
+
pad_token_id=self.tokenizer.eos_token_id)
|
| 39 |
+
answer = self.tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
|
| 40 |
+
return answer.strip()
|