Spaces:
Build error
Build error
mattritchey
commited on
Commit
•
f1c52e8
1
Parent(s):
a8cd746
Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
|
2 |
import gradio as gr
|
3 |
|
@@ -18,15 +24,6 @@ from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline
|
|
18 |
from transformers import TextIteratorStreamer
|
19 |
from threading import Thread
|
20 |
|
21 |
-
# MR Added
|
22 |
-
from langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings
|
23 |
-
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
|
24 |
-
from langchain.callbacks.manager import CallbackManager
|
25 |
-
from langchain.llms import LlamaCpp
|
26 |
-
callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
|
27 |
-
model = 'dolphin-2_6-phi-2.Q4_K_M.gguf'
|
28 |
-
|
29 |
-
|
30 |
# Prompt template
|
31 |
template = """Instruction:
|
32 |
You are an AI assistant for answering questions about the provided context.
|
@@ -39,116 +36,85 @@ Question: {question}
|
|
39 |
Output:\n"""
|
40 |
|
41 |
QA_PROMPT = PromptTemplate(
|
42 |
-
|
43 |
-
|
44 |
)
|
45 |
|
46 |
-
#
|
47 |
-
|
48 |
-
# model_id = "microsoft/phi-2"
|
49 |
|
50 |
-
|
51 |
-
|
52 |
|
53 |
-
#
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
|
60 |
-
# MR Added
|
61 |
-
embeddings = SentenceTransformerEmbeddings(model_name="all-mpnet-base-v2")
|
62 |
-
|
63 |
-
# filename = "Oppenheimer-movie-wiki.txt"
|
64 |
# Returns a faiss vector store retriever given a txt file
|
65 |
-
|
66 |
-
|
67 |
def prepare_vector_store_retriever(filename):
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
# Split the text
|
73 |
-
text_splitter = CharacterTextSplitter(
|
74 |
-
separator="\n\n",
|
75 |
-
chunk_size=800,
|
76 |
-
chunk_overlap=0,
|
77 |
-
length_function=len
|
78 |
-
)
|
79 |
-
|
80 |
-
documents = text_splitter.split_documents(raw_documents)
|
81 |
|
82 |
-
|
83 |
-
|
84 |
-
|
|
|
|
|
|
|
|
|
85 |
|
86 |
-
|
87 |
|
88 |
-
#
|
|
|
89 |
|
|
|
90 |
|
|
|
91 |
def get_retrieval_qa_chain(text_file, hf_model):
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
|
103 |
# Generates response using the question answering chain defined earlier
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
|
|
|
|
|
105 |
|
106 |
-
|
107 |
-
# streamer = TextIteratorStreamer(tokenizer=tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=300.0)
|
108 |
-
# phi2_pipeline = pipeline(
|
109 |
-
# "text-generation", tokenizer=tokenizer, model=model, max_new_tokens=max_new_tokens,
|
110 |
-
# pad_token_id=tokenizer.eos_token_id, eos_token_id=tokenizer.eos_token_id,
|
111 |
-
# device_map="auto", streamer=streamer
|
112 |
-
# )
|
113 |
-
|
114 |
-
# hf_model = HuggingFacePipeline(pipeline=phi2_pipeline)
|
115 |
-
|
116 |
-
# qa_chain = get_retrieval_qa_chain(text_file, hf_model)
|
117 |
-
|
118 |
-
# query = f"{question}"
|
119 |
-
|
120 |
-
# thread = Thread(target=qa_chain.invoke, kwargs={"input": {"query": query}})
|
121 |
-
# thread.start()
|
122 |
-
|
123 |
-
# response = ""
|
124 |
-
# for token in streamer:
|
125 |
-
# response += token
|
126 |
-
# yield response.strip()
|
127 |
-
|
128 |
-
# MR Added
|
129 |
-
query = f"{question}"
|
130 |
-
hf_model = LlamaCpp(model_path=model,
|
131 |
-
n_ctx=10000,
|
132 |
-
max_tokens=max_new_tokens,
|
133 |
-
temperature=0,
|
134 |
-
n_gpu_layers=16,
|
135 |
-
n_batch=1024,
|
136 |
-
callback_manager=callback_manager,
|
137 |
-
verbose=True,
|
138 |
-
)
|
139 |
-
|
140 |
-
response = hf_model.invoke(query)
|
141 |
-
return response
|
142 |
|
143 |
-
|
|
|
144 |
|
|
|
|
|
|
|
|
|
145 |
|
|
|
146 |
def upload_file(file):
|
147 |
-
|
148 |
-
|
149 |
|
150 |
with gr.Blocks() as demo:
|
151 |
-
|
152 |
# Retrieval Augmented Generation with Phi-2: Question Answering demo
|
153 |
### This demo uses the Phi-2 language model and Retrieval Augmented Generation (RAG). It allows you to upload a txt file and ask the model questions related to the content of that file.
|
154 |
### If you don't have one, there is a txt file already loaded, the new Oppenheimer movie's entire wikipedia page. The movie came out very recently in July, 2023, so the Phi-2 model is not aware of it.
|
@@ -157,42 +123,37 @@ with gr.Blocks() as demo:
|
|
157 |
The model is then able to answer questions by incorporating knowledge from the newly provided document. RAG can be used with thousands of documents, but this demo is limited to just one txt file.
|
158 |
""")
|
159 |
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
with gr.
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
clear = gr.ClearButton([ques, ans])
|
192 |
-
|
193 |
-
btn.click(fn=generate, inputs=[ques, ans,
|
194 |
-
text_file, tokens_slider], outputs=[ans])
|
195 |
-
examples = gr.Examples(
|
196 |
examples=[
|
197 |
"Who portrayed J. Robert Oppenheimer in the new Oppenheimer movie?",
|
198 |
"In the plot of the movie, why did Lewis Strauss resent Robert Oppenheimer?"
|
@@ -200,4 +161,4 @@ with gr.Blocks() as demo:
|
|
200 |
inputs=[ques],
|
201 |
)
|
202 |
|
203 |
-
demo.queue().launch()
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
Created on Tue Jan 30 14:11:53 2024
|
4 |
+
|
5 |
+
@author: mritchey
|
6 |
+
"""
|
7 |
|
8 |
import gradio as gr
|
9 |
|
|
|
24 |
from transformers import TextIteratorStreamer
|
25 |
from threading import Thread
|
26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
# Prompt template
|
28 |
template = """Instruction:
|
29 |
You are an AI assistant for answering questions about the provided context.
|
|
|
36 |
Output:\n"""
|
37 |
|
38 |
QA_PROMPT = PromptTemplate(
|
39 |
+
template=template,
|
40 |
+
input_variables=["question", "context"]
|
41 |
)
|
42 |
|
43 |
+
# Load Phi-2 model from hugging face hub
|
44 |
+
model_id = "TheBloke/dolphin-2_6-phi-2-GPTQ" #change MR
|
|
|
45 |
|
46 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
47 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float32, device_map="auto", trust_remote_code=True)
|
48 |
|
49 |
+
# sentence transformers to be used in vector store
|
50 |
+
embeddings = HuggingFaceEmbeddings(
|
51 |
+
model_name="sentence-transformers/all-mpnet-base-v2", #Change MR
|
52 |
+
model_kwargs={'device': 'cpu'},
|
53 |
+
encode_kwargs={'normalize_embeddings': False}
|
54 |
+
)
|
55 |
|
|
|
|
|
|
|
|
|
56 |
# Returns a faiss vector store retriever given a txt file
|
|
|
|
|
57 |
def prepare_vector_store_retriever(filename):
|
58 |
+
# Load data
|
59 |
+
loader = UnstructuredFileLoader(filename)
|
60 |
+
raw_documents = loader.load()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
+
# Split the text
|
63 |
+
text_splitter = CharacterTextSplitter(
|
64 |
+
separator="\n\n",
|
65 |
+
chunk_size=800,
|
66 |
+
chunk_overlap=0,
|
67 |
+
length_function=len
|
68 |
+
)
|
69 |
|
70 |
+
documents = text_splitter.split_documents(raw_documents)
|
71 |
|
72 |
+
# Creating a vectorstore
|
73 |
+
vectorstore = FAISS.from_documents(documents, embeddings, distance_strategy=DistanceStrategy.COSINE)
|
74 |
|
75 |
+
return VectorStoreRetriever(vectorstore=vectorstore, search_kwargs={"k": 2})
|
76 |
|
77 |
+
# Retrieveal QA chian
|
78 |
def get_retrieval_qa_chain(text_file, hf_model):
|
79 |
+
retriever = default_retriever
|
80 |
+
if text_file != default_text_file:
|
81 |
+
retriever = prepare_vector_store_retriever(text_file)
|
82 |
+
|
83 |
+
chain = RetrievalQA.from_chain_type(
|
84 |
+
llm=hf_model,
|
85 |
+
retriever=retriever,
|
86 |
+
chain_type_kwargs={"prompt": QA_PROMPT},
|
87 |
+
)
|
88 |
+
return chain
|
89 |
|
90 |
# Generates response using the question answering chain defined earlier
|
91 |
+
def generate(question, answer, text_file, max_new_tokens):
|
92 |
+
streamer = TextIteratorStreamer(tokenizer=tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=300.0)
|
93 |
+
phi2_pipeline = pipeline(
|
94 |
+
"text-generation", tokenizer=tokenizer, model=model, max_new_tokens=max_new_tokens,
|
95 |
+
pad_token_id=tokenizer.eos_token_id, eos_token_id=tokenizer.eos_token_id,
|
96 |
+
device_map="auto", streamer=streamer
|
97 |
+
)
|
98 |
|
99 |
+
hf_model = HuggingFacePipeline(pipeline=phi2_pipeline)
|
100 |
+
qa_chain = get_retrieval_qa_chain(text_file, hf_model)
|
101 |
|
102 |
+
query = f"{question}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
|
104 |
+
thread = Thread(target=qa_chain.invoke, kwargs={"input": {"query": query}})
|
105 |
+
thread.start()
|
106 |
|
107 |
+
response = ""
|
108 |
+
for token in streamer:
|
109 |
+
response += token
|
110 |
+
yield response.strip()
|
111 |
|
112 |
+
# replaces the retreiver in the question answering chain whenever a new file is uploaded
|
113 |
def upload_file(file):
|
114 |
+
return file, file
|
|
|
115 |
|
116 |
with gr.Blocks() as demo:
|
117 |
+
gr.Markdown("""
|
118 |
# Retrieval Augmented Generation with Phi-2: Question Answering demo
|
119 |
### This demo uses the Phi-2 language model and Retrieval Augmented Generation (RAG). It allows you to upload a txt file and ask the model questions related to the content of that file.
|
120 |
### If you don't have one, there is a txt file already loaded, the new Oppenheimer movie's entire wikipedia page. The movie came out very recently in July, 2023, so the Phi-2 model is not aware of it.
|
|
|
123 |
The model is then able to answer questions by incorporating knowledge from the newly provided document. RAG can be used with thousands of documents, but this demo is limited to just one txt file.
|
124 |
""")
|
125 |
|
126 |
+
default_text_file = "Oppenheimer-movie-wiki.txt"
|
127 |
+
default_retriever = prepare_vector_store_retriever(default_text_file)
|
128 |
+
|
129 |
+
text_file = gr.State(default_text_file)
|
130 |
+
|
131 |
+
gr.Markdown("## Upload a txt file or Use the Default 'Oppenheimer-movie-wiki.txt' that has already been loaded")
|
132 |
+
|
133 |
+
file_name = gr.Textbox(label="Loaded text file", value=default_text_file, lines=1, interactive=False)
|
134 |
+
upload_button = gr.UploadButton(
|
135 |
+
label="Click to upload a text file",
|
136 |
+
file_types=["text"],
|
137 |
+
file_count="single"
|
138 |
+
)
|
139 |
+
upload_button.upload(upload_file, upload_button, [file_name, text_file])
|
140 |
+
|
141 |
+
gr.Markdown("## Enter your question")
|
142 |
+
tokens_slider = gr.Slider(8, 256, value=64, label="Maximum new tokens", info="A larger `max_new_tokens` parameter value gives you longer text responses but at the cost of a slower response time.")
|
143 |
+
|
144 |
+
with gr.Row():
|
145 |
+
with gr.Column():
|
146 |
+
ques = gr.Textbox(label="Question", placeholder="Enter text here", lines=3)
|
147 |
+
with gr.Column():
|
148 |
+
ans = gr.Textbox(label="Answer", lines=4, interactive=False)
|
149 |
+
with gr.Row():
|
150 |
+
with gr.Column():
|
151 |
+
btn = gr.Button("Submit")
|
152 |
+
with gr.Column():
|
153 |
+
clear = gr.ClearButton([ques, ans])
|
154 |
+
|
155 |
+
btn.click(fn=generate, inputs=[ques, ans, text_file, tokens_slider], outputs=[ans])
|
156 |
+
examples = gr.Examples(
|
|
|
|
|
|
|
|
|
|
|
157 |
examples=[
|
158 |
"Who portrayed J. Robert Oppenheimer in the new Oppenheimer movie?",
|
159 |
"In the plot of the movie, why did Lewis Strauss resent Robert Oppenheimer?"
|
|
|
161 |
inputs=[ques],
|
162 |
)
|
163 |
|
164 |
+
demo.queue().launch()
|