DylanJTodd commited on
Commit
4e10c8c
·
verified ·
1 Parent(s): d86d95c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -83
app.py CHANGED
@@ -1,83 +1,84 @@
1
- from transformers import AutoModelForCausalLM, AutoTokenizer
2
- from sentence_transformers import SentenceTransformer
3
- from peft import PeftModel
4
- import faiss
5
- import torch
6
- import gradio as gr
7
-
8
- # Load models and index
9
- base_model_id = "rasyosef/phi-2-instruct-v0.1"
10
- tokenizer = AutoTokenizer.from_pretrained(base_model_id)
11
- base_model = AutoModelForCausalLM.from_pretrained(
12
- base_model_id, torch_dtype=torch.float16
13
- ).to("cuda")
14
- peft_model = PeftModel.from_pretrained(base_model, "./results/checkpoint-165")
15
- peft_model.eval()
16
-
17
- embedder = SentenceTransformer("all-MiniLM-L6-v2")
18
- index = faiss.read_index("rag-corpus/rag-index.faiss")
19
- with open("rag-corpus/rag_docs.txt", "r", encoding="utf-8") as f:
20
- all_docs = f.read().split("\n---\n")
21
-
22
- def retrieve_context(query, k=3):
23
- query_embedding = embedder.encode([query])
24
- D, I = index.search(query_embedding, k)
25
- return [all_docs[i] for i in I[0] if i < len(all_docs)]
26
-
27
- def generate_response(user_prompt):
28
- context_chunks = retrieve_context(user_prompt)
29
- context_text = "\n\n".join(context_chunks)
30
-
31
- prompt = f"""
32
- <|im_start|>system
33
- You are an expert AI assistant role-playing as Dylan Todd. Your sole purpose is to answer questions about Dylan's professional background, skills, and projects.
34
-
35
- **Your instructions are absolute:**
36
- 1. You MUST answer the user's question from Dylan Todd's perspective.
37
- 2. Your answers must be concise, professional, and direct.
38
- 3. End every single response with '<|im_end|>'.
39
-
40
- Failure to answer the question is not an option. Begin your response immediately as Dylan Todd.
41
- <|im_end|>
42
-
43
- <|im_start|>user
44
- Here is some context to help inform your answer, note that not all of it may be relevant to the question, but it is provided to help you answer:
45
- {context_text}
46
-
47
- Now answer this question directed to Dylan Todd:
48
- {user_prompt}
49
- <|im_end|>
50
-
51
- <|im_start|>Dylan Todd
52
- """
53
-
54
- input_ids = tokenizer(prompt, return_tensors="pt").to("cuda")
55
-
56
- with torch.no_grad():
57
- output_ids = peft_model.generate(
58
- input_ids=input_ids["input_ids"],
59
- attention_mask=input_ids["attention_mask"],
60
- repetition_penalty=1.1,
61
- do_sample=True,
62
- max_new_tokens=200,
63
- temperature=0.7,
64
- top_p=0.95,
65
- top_k=50,
66
- pad_token_id=tokenizer.eos_token_id,
67
- eos_token_id=tokenizer.convert_tokens_to_ids("<|im_end|>")
68
- )
69
-
70
- generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
71
-
72
- if "Dylan Todd" in generated_text:
73
- generated_text = generated_text.split("Dylan Todd\n", 1)[-1].strip()
74
-
75
- for stop_token in ["<|im_end|>", "\n"]:
76
- if stop_token in generated_text:
77
- generated_text = generated_text.split(stop_token)[0].strip()
78
- break
79
-
80
- return generated_text
81
-
82
- demo = gr.Interface(fn=generate_response, inputs="text", outputs="text", title="Ask Dylan Todd", description="An AI assistant answering questions as Dylan Todd using custom fine-tuned + RAG model.")
83
- demo.launch()
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer
2
+ from sentence_transformers import SentenceTransformer
3
+ from peft import PeftModel
4
+ import faiss
5
+ import torch
6
+ import gradio as gr
7
+
8
+ # Load models and index
9
+ base_model_id = "rasyosef/phi-2-instruct-v0.1"
10
+ tokenizer = AutoTokenizer.from_pretrained(base_model_id)
11
+ device = "cuda" if torch.cuda.is_available() else "cpu"
12
+ base_model = AutoModelForCausalLM.from_pretrained(
13
+ base_model_id, torch_dtype=torch.float16 if device == "cuda" else torch.float32
14
+ ).to(device)
15
+ peft_model = PeftModel.from_pretrained(base_model, "./results/checkpoint-165")
16
+ peft_model.eval()
17
+
18
+ embedder = SentenceTransformer("all-MiniLM-L6-v2")
19
+ index = faiss.read_index("rag-corpus/rag-index.faiss")
20
+ with open("rag-corpus/rag_docs.txt", "r", encoding="utf-8") as f:
21
+ all_docs = f.read().split("\n---\n")
22
+
23
+ def retrieve_context(query, k=3):
24
+ query_embedding = embedder.encode([query])
25
+ D, I = index.search(query_embedding, k)
26
+ return [all_docs[i] for i in I[0] if i < len(all_docs)]
27
+
28
+ def generate_response(user_prompt):
29
+ context_chunks = retrieve_context(user_prompt)
30
+ context_text = "\n\n".join(context_chunks)
31
+
32
+ prompt = f"""
33
+ <|im_start|>system
34
+ You are an expert AI assistant role-playing as Dylan Todd. Your sole purpose is to answer questions about Dylan's professional background, skills, and projects.
35
+
36
+ **Your instructions are absolute:**
37
+ 1. You MUST answer the user's question from Dylan Todd's perspective.
38
+ 2. Your answers must be concise, professional, and direct.
39
+ 3. End every single response with '<|im_end|>'.
40
+
41
+ Failure to answer the question is not an option. Begin your response immediately as Dylan Todd.
42
+ <|im_end|>
43
+
44
+ <|im_start|>user
45
+ Here is some context to help inform your answer, note that not all of it may be relevant to the question, but it is provided to help you answer:
46
+ {context_text}
47
+
48
+ Now answer this question directed to Dylan Todd:
49
+ {user_prompt}
50
+ <|im_end|>
51
+
52
+ <|im_start|>Dylan Todd
53
+ """
54
+
55
+ input_ids = tokenizer(prompt, return_tensors="pt").to(device)
56
+
57
+ with torch.no_grad():
58
+ output_ids = peft_model.generate(
59
+ input_ids=input_ids["input_ids"],
60
+ attention_mask=input_ids["attention_mask"],
61
+ repetition_penalty=1.1,
62
+ do_sample=True,
63
+ max_new_tokens=200,
64
+ temperature=0.7,
65
+ top_p=0.95,
66
+ top_k=50,
67
+ pad_token_id=tokenizer.eos_token_id,
68
+ eos_token_id=tokenizer.convert_tokens_to_ids("<|im_end|>")
69
+ )
70
+
71
+ generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
72
+
73
+ if "Dylan Todd" in generated_text:
74
+ generated_text = generated_text.split("Dylan Todd\n", 1)[-1].strip()
75
+
76
+ for stop_token in ["<|im_end|>", "\n"]:
77
+ if stop_token in generated_text:
78
+ generated_text = generated_text.split(stop_token)[0].strip()
79
+ break
80
+
81
+ return generated_text
82
+
83
+ demo = gr.Interface(fn=generate_response, inputs="text", outputs="text", title="Ask Dylan Todd", description="An AI assistant answering questions as Dylan Todd using custom fine-tuned + RAG model.")
84
+ demo.launch()