mattritchey commited on
Commit
947fdcc
1 Parent(s): 0effa40

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +203 -0
app.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+
4
+ from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain_community.document_loaders import UnstructuredFileLoader
6
+ from langchain.vectorstores.faiss import FAISS
7
+ from langchain.vectorstores.utils import DistanceStrategy
8
+ from langchain_community.embeddings import HuggingFaceEmbeddings
9
+
10
+ from langchain.chains import RetrievalQA
11
+ from langchain.prompts.prompt import PromptTemplate
12
+ from langchain.vectorstores.base import VectorStoreRetriever
13
+
14
+ import torch
15
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
16
+ from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline
17
+
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.
33
+ You are given the following extracted parts of a long document and a question. Provide a detailed answer.
34
+ If you don't know the answer, just say "Hmm, I'm not sure." Don't try to make up an answer.
35
+ =======
36
+ {context}
37
+ =======
38
+ Question: {question}
39
+ Output:\n"""
40
+
41
+ QA_PROMPT = PromptTemplate(
42
+ template=template,
43
+ input_variables=["question", "context"]
44
+ )
45
+
46
+ # Commented out: MR
47
+ # # Load Phi-2 model from hugging face hub
48
+ # model_id = "microsoft/phi-2"
49
+
50
+ # tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
51
+ # model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float32, device_map="auto", trust_remote_code=True)
52
+
53
+ # # sentence transformers to be used in vector store
54
+ # embeddings = HuggingFaceEmbeddings(
55
+ # model_name="sentence-transformers/multi-qa-MiniLM-L6-cos-v1",
56
+ # model_kwargs={'device': 'cpu'},
57
+ # encode_kwargs={'normalize_embeddings': False}
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
+ # Load data
69
+ loader = UnstructuredFileLoader(filename)
70
+ raw_documents = loader.load()
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
+ # Creating a vectorstore
83
+ vectorstore = FAISS.from_documents(
84
+ documents, embeddings, distance_strategy=DistanceStrategy.COSINE)
85
+
86
+ return VectorStoreRetriever(vectorstore=vectorstore, search_kwargs={"k": 2})
87
+
88
+ # Retrieveal QA chian
89
+
90
+
91
+ def get_retrieval_qa_chain(text_file, hf_model):
92
+ retriever = default_retriever
93
+ if text_file != default_text_file:
94
+ retriever = prepare_vector_store_retriever(text_file)
95
+
96
+ chain = RetrievalQA.from_chain_type(
97
+ llm=hf_model,
98
+ retriever=retriever,
99
+ chain_type_kwargs={"prompt": QA_PROMPT},
100
+ )
101
+ return chain
102
+
103
+ # Generates response using the question answering chain defined earlier
104
+
105
+
106
+ def generate(question, answer, text_file, max_new_tokens):
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
+ # replaces the retreiver in the question answering chain whenever a new file is uploaded
144
+
145
+
146
+ def upload_file(file):
147
+ return file, file
148
+
149
+
150
+ with gr.Blocks() as demo:
151
+ gr.Markdown("""
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.
155
+ The context size of the Phi-2 model is 2048 tokens, so even this medium size wikipedia page (11.5k tokens) does not fit in the context window.
156
+ Retrieval Augmented Generation (RAG) enables us to retrieve just the few small chunks of the document that are relevant to the our query and inject it into our prompt.
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
+ default_text_file = "Oppenheimer-movie-wiki.txt"
161
+ default_retriever = prepare_vector_store_retriever(default_text_file)
162
+
163
+ text_file = gr.State(default_text_file)
164
+
165
+ gr.Markdown(
166
+ "## Upload a txt file or Use the Default 'Oppenheimer-movie-wiki.txt' that has already been loaded")
167
+
168
+ file_name = gr.Textbox(label="Loaded text file",
169
+ value=default_text_file, lines=1, interactive=False)
170
+ upload_button = gr.UploadButton(
171
+ label="Click to upload a text file",
172
+ file_types=["text"],
173
+ file_count="single"
174
+ )
175
+ upload_button.upload(upload_file, upload_button, [file_name, text_file])
176
+
177
+ gr.Markdown("## Enter your question")
178
+ tokens_slider = gr.Slider(8, 256, value=64, label="Maximum new tokens",
179
+ info="A larger `max_new_tokens` parameter value gives you longer text responses but at the cost of a slower response time.")
180
+
181
+ with gr.Row():
182
+ with gr.Column():
183
+ ques = gr.Textbox(label="Question",
184
+ placeholder="Enter text here", lines=3)
185
+ with gr.Column():
186
+ ans = gr.Textbox(label="Answer", lines=4, interactive=False)
187
+ with gr.Row():
188
+ with gr.Column():
189
+ btn = gr.Button("Submit")
190
+ with gr.Column():
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?"
199
+ ],
200
+ inputs=[ques],
201
+ )
202
+
203
+ demo.queue().launch()