MindForeverVoyaging commited on
Commit
2079139
1 Parent(s): 2ab5fe1

initial commit

Browse files
Files changed (6) hide show
  1. .gitignore +1 -0
  2. app.py +466 -0
  3. chunked_data.parquet +3 -0
  4. embeddings.npy +3 -0
  5. gitattributes.txt +35 -0
  6. requirements.txt +8 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .venv/
app.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import re
4
+ from sentence_transformers import SentenceTransformer, CrossEncoder
5
+ import hnswlib
6
+ import numpy as np
7
+ from typing import Iterator
8
+
9
+ import gradio as gr
10
+ import pandas as pd
11
+ import torch
12
+
13
+ from easyllm.clients import huggingface
14
+ from transformers import AutoTokenizer
15
+
16
+ huggingface.prompt_builder = "llama2"
17
+ huggingface.api_key = os.environ["HUGGINGFACE_TOKEN"]
18
+ MAX_MAX_NEW_TOKENS = 2048
19
+ DEFAULT_MAX_NEW_TOKENS = 1024
20
+ MAX_INPUT_TOKEN_LENGTH = 4000
21
+ EMBED_DIM = 1024
22
+ K = 10
23
+ EF = 100
24
+ SEARCH_INDEX = "search_index.bin"
25
+ EMBEDDINGS_FILE = "embeddings.npy"
26
+ DOCUMENT_DATASET = "chunked_data.parquet"
27
+ COSINE_THRESHOLD = 0.7
28
+
29
+ torch_device = "cuda" if torch.cuda.is_available() else "cpu"
30
+ print("Running on device:", torch_device)
31
+ print("CPU threads:", torch.get_num_threads())
32
+
33
+ model_id = "meta-llama/Llama-2-70b-chat-hf"
34
+ biencoder = SentenceTransformer("intfloat/e5-large-v2", device=torch_device)
35
+ cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-12-v2", max_length=512, device=torch_device)
36
+
37
+ tokenizer = AutoTokenizer.from_pretrained(model_id, use_auth_token=os.environ["HUGGINGFACE_TOKEN"])
38
+
39
+
40
+ def create_qa_prompt(query, relevant_chunks):
41
+ stuffed_context = " ".join(relevant_chunks)
42
+ return f"""\
43
+ Use the following pieces of context given in to answer the question at the end. \
44
+ If you don't know the answer, just say that you don't know, don't try to make up an answer. \
45
+ Keep the answer short and succinct.
46
+
47
+ Context: {stuffed_context}
48
+ Question: {query}
49
+ Helpful Answer: \
50
+ """
51
+
52
+
53
+ def create_condense_question_prompt(question, chat_history):
54
+ return f"""\
55
+ Given the following conversation and a follow up question, \
56
+ rephrase the follow up question to be a standalone question in its original language. \
57
+ Output the json object with single field `question` and value being the rephrased standalone question.
58
+ Only output json object and nothing else.
59
+
60
+ Chat History:
61
+ {chat_history}
62
+ Follow Up Input: {question}
63
+ """
64
+
65
+
66
+ def get_prompt(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> str:
67
+ texts = [f"<s>[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n"]
68
+ # The first user input is _not_ stripped
69
+ do_strip = False
70
+ for user_input, response in chat_history:
71
+ user_input = user_input.strip() if do_strip else user_input
72
+ do_strip = True
73
+ texts.append(f"{user_input} [/INST] {response.strip()} </s><s>[INST] ")
74
+ message = message.strip() if do_strip else message
75
+ texts.append(f"{message} [/INST]")
76
+ return "".join(texts)
77
+
78
+
79
+ def get_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> int:
80
+ prompt = get_prompt(message, chat_history, system_prompt)
81
+ input_ids = tokenizer([prompt], return_tensors="np", add_special_tokens=False)["input_ids"]
82
+ return input_ids.shape[-1]
83
+
84
+
85
+ # https://www.philschmid.de/llama-2#how-to-prompt-llama-2-chat
86
+ def get_completion(
87
+ prompt,
88
+ system_prompt=None,
89
+ model=model_id,
90
+ max_new_tokens=1024,
91
+ temperature=0.2,
92
+ top_p=0.95,
93
+ top_k=50,
94
+ stream=False,
95
+ debug=False,
96
+ ):
97
+ if temperature < 1e-2:
98
+ temperature = 1e-2
99
+ messages = []
100
+ if system_prompt is not None:
101
+ messages.append({"role": "system", "content": system_prompt})
102
+ messages.append({"role": "user", "content": prompt})
103
+ response = huggingface.ChatCompletion.create(
104
+ model=model,
105
+ messages=messages,
106
+ temperature=temperature, # this is the degree of randomness of the model's output
107
+ max_tokens=max_new_tokens, # this is the number of new tokens being generated
108
+ top_p=top_p,
109
+ top_k=top_k,
110
+ stream=stream,
111
+ debug=debug,
112
+ )
113
+ return response["choices"][0]["message"]["content"] if not stream else response
114
+
115
+
116
+ # load the index for the PEFT docs
117
+ def load_hnsw_index(index_file):
118
+ # Load the HNSW index from the specified file
119
+ index = hnswlib.Index(space="ip", dim=EMBED_DIM)
120
+ index.load_index(index_file)
121
+ return index
122
+
123
+
124
+ # create the index for the PEFT docs from numpy embeddings
125
+ # avoid the arch mismatches when creating search index
126
+ def create_hnsw_index(embeddings_file, M=16, efC=100):
127
+ embeddings = np.load(embeddings_file)
128
+ # Create the HNSW index
129
+ num_dim = embeddings.shape[1]
130
+ ids = np.arange(embeddings.shape[0])
131
+ index = hnswlib.Index(space="ip", dim=num_dim)
132
+ index.init_index(max_elements=embeddings.shape[0], ef_construction=efC, M=M)
133
+ index.add_items(embeddings, ids)
134
+ return index
135
+
136
+
137
+ def create_query_embedding(query):
138
+ # Encode the query to get its embedding
139
+ embedding = biencoder.encode([query], normalize_embeddings=True)[0]
140
+ return embedding
141
+
142
+
143
+ def find_nearest_neighbors(query_embedding):
144
+ search_index.set_ef(EF)
145
+ # Find the k-nearest neighbors for the query embedding
146
+ labels, distances = search_index.knn_query(query_embedding, k=K)
147
+ labels = [label for label, distance in zip(labels[0], distances[0]) if (1 - distance) >= COSINE_THRESHOLD]
148
+ relevant_chunks = data_df.iloc[labels]["chunk_content"].tolist()
149
+ return relevant_chunks
150
+
151
+
152
+ def rerank_chunks_with_cross_encoder(query, chunks):
153
+ # Create a list of tuples, each containing a query-chunk pair
154
+ pairs = [(query, chunk) for chunk in chunks]
155
+
156
+ # Get scores for each query-chunk pair using the cross encoder
157
+ scores = cross_encoder.predict(pairs)
158
+
159
+ # Sort the chunks based on their scores in descending order
160
+ sorted_chunks = [chunk for _, chunk in sorted(zip(scores, chunks), reverse=True)]
161
+
162
+ return sorted_chunks
163
+
164
+
165
+ def generate_condensed_query(query, history):
166
+ chat_history = ""
167
+ for turn in history:
168
+ chat_history += f"Human: {turn[0]}\n"
169
+ chat_history += f"Assistant: {turn[1]}\n"
170
+
171
+ condense_question_prompt = create_condense_question_prompt(query, chat_history)
172
+ condensed_question = json.loads(get_completion(condense_question_prompt, max_new_tokens=64, temperature=0))
173
+ return condensed_question["question"]
174
+
175
+
176
+ DEFAULT_SYSTEM_PROMPT = """\
177
+ You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
178
+
179
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\
180
+ """
181
+ MAX_MAX_NEW_TOKENS = 2048
182
+ DEFAULT_MAX_NEW_TOKENS = 1024
183
+ MAX_INPUT_TOKEN_LENGTH = 4000
184
+
185
+ DESCRIPTION = """
186
+ # PEFT Docs QA Chatbot 🤗
187
+ """
188
+
189
+ LICENSE = """
190
+ <p/>
191
+
192
+ ---
193
+ As a derivate work of [Llama-2-70b-chat](https://huggingface.co/meta-llama/Llama-2-70b-chat) by Meta,
194
+ this demo is governed by the original [license](https://huggingface.co/spaces/huggingface-projects/llama-2-70b-chat/blob/main/LICENSE.txt) and [acceptable use policy](https://huggingface.co/spaces/huggingface-projects/llama-2-70b-chat/blob/main/USE_POLICY.md).
195
+ """
196
+
197
+ if not torch.cuda.is_available():
198
+ DESCRIPTION += "\n<p>Running on CPU 🥶.</p>"
199
+
200
+
201
+ def clear_and_save_textbox(message: str) -> tuple[str, str]:
202
+ return "", message
203
+
204
+
205
+ def display_input(message: str, history: list[tuple[str, str]]) -> list[tuple[str, str]]:
206
+ history.append((message, ""))
207
+ return history
208
+
209
+
210
+ def delete_prev_fn(history: list[tuple[str, str]]) -> tuple[list[tuple[str, str]], str]:
211
+ try:
212
+ message, _ = history.pop()
213
+ except IndexError:
214
+ message = ""
215
+ return history, message or ""
216
+
217
+
218
+ def wrap_html_code(text):
219
+ pattern = r"<.*?>"
220
+ matches = re.findall(pattern, text)
221
+ if len(matches) > 0:
222
+ return f"```{text}```"
223
+ else:
224
+ return text
225
+
226
+
227
+ def generate(
228
+ message: str,
229
+ history_with_input: list[tuple[str, str]],
230
+ system_prompt: str,
231
+ max_new_tokens: int,
232
+ temperature: float,
233
+ top_p: float,
234
+ top_k: int,
235
+ ) -> Iterator[list[tuple[str, str]]]:
236
+ if max_new_tokens > MAX_MAX_NEW_TOKENS:
237
+ raise ValueError
238
+ history = history_with_input[:-1]
239
+ if len(history) > 0:
240
+ condensed_query = generate_condensed_query(message, history)
241
+ print(f"{condensed_query=}")
242
+ else:
243
+ condensed_query = message
244
+ query_embedding = create_query_embedding(condensed_query)
245
+ relevant_chunks = find_nearest_neighbors(query_embedding)
246
+ reranked_relevant_chunks = rerank_chunks_with_cross_encoder(condensed_query, relevant_chunks)
247
+ qa_prompt = create_qa_prompt(condensed_query, reranked_relevant_chunks)
248
+ print(f"{qa_prompt=}")
249
+ generator = get_completion(
250
+ qa_prompt,
251
+ system_prompt=system_prompt,
252
+ stream=True,
253
+ max_new_tokens=max_new_tokens,
254
+ temperature=temperature,
255
+ top_k=top_k,
256
+ top_p=top_p,
257
+ )
258
+
259
+ output = ""
260
+ for idx, response in enumerate(generator):
261
+ token = response["choices"][0]["delta"].get("content", "") or ""
262
+ output += token
263
+ if idx == 0:
264
+ history.append((message, output))
265
+ else:
266
+ history[-1] = (message, output)
267
+
268
+ history = [
269
+ (wrap_html_code(history[i][0].strip()), wrap_html_code(history[i][1].strip()))
270
+ for i in range(0, len(history))
271
+ ]
272
+ yield history
273
+
274
+ return history
275
+
276
+
277
+ def process_example(message: str) -> tuple[str, list[tuple[str, str]]]:
278
+ generator = generate(message, [], DEFAULT_SYSTEM_PROMPT, 1024, 0.2, 0.95, 50)
279
+ for x in generator:
280
+ pass
281
+ return "", x
282
+
283
+
284
+ def check_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> None:
285
+ input_token_length = get_input_token_length(message, chat_history, system_prompt)
286
+ if input_token_length > MAX_INPUT_TOKEN_LENGTH:
287
+ raise gr.Error(
288
+ f"The accumulated input is too long ({input_token_length} > {MAX_INPUT_TOKEN_LENGTH}). Clear your chat history and try again."
289
+ )
290
+
291
+
292
+ search_index = create_hnsw_index(EMBEDDINGS_FILE) # load_hnsw_index(SEARCH_INDEX)
293
+ data_df = pd.read_parquet(DOCUMENT_DATASET).reset_index()
294
+ with gr.Blocks(css="style.css") as demo:
295
+ gr.Markdown(DESCRIPTION)
296
+
297
+ with gr.Group():
298
+ chatbot = gr.Chatbot(label="Chatbot")
299
+ with gr.Row():
300
+ textbox = gr.Textbox(
301
+ container=False,
302
+ show_label=False,
303
+ placeholder="Type a message...",
304
+ scale=10,
305
+ )
306
+ submit_button = gr.Button("Submit", variant="primary", scale=1, min_width=0)
307
+ with gr.Row():
308
+ retry_button = gr.Button("🔄 Retry", variant="secondary")
309
+ undo_button = gr.Button("↩️ Undo", variant="secondary")
310
+ clear_button = gr.Button("🗑️ Clear", variant="secondary")
311
+
312
+ saved_input = gr.State()
313
+
314
+ with gr.Accordion(label="Advanced options", open=False):
315
+ system_prompt = gr.Textbox(label="System prompt", value=DEFAULT_SYSTEM_PROMPT, lines=6)
316
+ max_new_tokens = gr.Slider(
317
+ label="Max new tokens",
318
+ minimum=1,
319
+ maximum=MAX_MAX_NEW_TOKENS,
320
+ step=1,
321
+ value=DEFAULT_MAX_NEW_TOKENS,
322
+ )
323
+ temperature = gr.Slider(
324
+ label="Temperature",
325
+ minimum=0.1,
326
+ maximum=4.0,
327
+ step=0.1,
328
+ value=0.2,
329
+ )
330
+ top_p = gr.Slider(
331
+ label="Top-p (nucleus sampling)",
332
+ minimum=0.05,
333
+ maximum=1.0,
334
+ step=0.05,
335
+ value=0.95,
336
+ )
337
+ top_k = gr.Slider(
338
+ label="Top-k",
339
+ minimum=1,
340
+ maximum=1000,
341
+ step=1,
342
+ value=50,
343
+ )
344
+
345
+ gr.Examples(
346
+ examples=[
347
+ "What is 🤗 PEFT?",
348
+ "How do I create a LoraConfig?",
349
+ "What are the different tuners supported?",
350
+ "How do I use LoRA with custom models?",
351
+ "What are the different real-world applications that I can use PEFT for?",
352
+ ],
353
+ inputs=textbox,
354
+ outputs=[textbox, chatbot],
355
+ # fn=process_example,
356
+ cache_examples=False,
357
+ )
358
+
359
+ gr.Markdown(LICENSE)
360
+
361
+ textbox.submit(
362
+ fn=clear_and_save_textbox,
363
+ inputs=textbox,
364
+ outputs=[textbox, saved_input],
365
+ api_name=False,
366
+ queue=False,
367
+ ).then(fn=display_input, inputs=[saved_input, chatbot], outputs=chatbot, api_name=False, queue=False,).then(
368
+ fn=check_input_token_length,
369
+ inputs=[saved_input, chatbot, system_prompt],
370
+ api_name=False,
371
+ queue=False,
372
+ ).success(
373
+ fn=generate,
374
+ inputs=[
375
+ saved_input,
376
+ chatbot,
377
+ system_prompt,
378
+ max_new_tokens,
379
+ temperature,
380
+ top_p,
381
+ top_k,
382
+ ],
383
+ outputs=chatbot,
384
+ api_name=False,
385
+ )
386
+
387
+ button_event_preprocess = (
388
+ submit_button.click(
389
+ fn=clear_and_save_textbox,
390
+ inputs=textbox,
391
+ outputs=[textbox, saved_input],
392
+ api_name=False,
393
+ queue=False,
394
+ )
395
+ .then(
396
+ fn=display_input,
397
+ inputs=[saved_input, chatbot],
398
+ outputs=chatbot,
399
+ api_name=False,
400
+ queue=False,
401
+ )
402
+ .then(
403
+ fn=check_input_token_length,
404
+ inputs=[saved_input, chatbot, system_prompt],
405
+ api_name=False,
406
+ queue=False,
407
+ )
408
+ .success(
409
+ fn=generate,
410
+ inputs=[
411
+ saved_input,
412
+ chatbot,
413
+ system_prompt,
414
+ max_new_tokens,
415
+ temperature,
416
+ top_p,
417
+ top_k,
418
+ ],
419
+ outputs=chatbot,
420
+ api_name=False,
421
+ )
422
+ )
423
+
424
+ retry_button.click(
425
+ fn=delete_prev_fn,
426
+ inputs=chatbot,
427
+ outputs=[chatbot, saved_input],
428
+ api_name=False,
429
+ queue=False,
430
+ ).then(fn=display_input, inputs=[saved_input, chatbot], outputs=chatbot, api_name=False, queue=False,).then(
431
+ fn=generate,
432
+ inputs=[
433
+ saved_input,
434
+ chatbot,
435
+ system_prompt,
436
+ max_new_tokens,
437
+ temperature,
438
+ top_p,
439
+ top_k,
440
+ ],
441
+ outputs=chatbot,
442
+ api_name=False,
443
+ )
444
+
445
+ undo_button.click(
446
+ fn=delete_prev_fn,
447
+ inputs=chatbot,
448
+ outputs=[chatbot, saved_input],
449
+ api_name=False,
450
+ queue=False,
451
+ ).then(
452
+ fn=lambda x: x,
453
+ inputs=[saved_input],
454
+ outputs=textbox,
455
+ api_name=False,
456
+ queue=False,
457
+ )
458
+
459
+ clear_button.click(
460
+ fn=lambda: ([], ""),
461
+ outputs=[chatbot, saved_input],
462
+ queue=False,
463
+ api_name=False,
464
+ )
465
+
466
+ demo.queue(max_size=20).launch(debug=True, share=False)
chunked_data.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9bd56497444e3ae38e46f271d20dff959a0b5de7b0a64355dbac51f2bef660e
3
+ size 109712
embeddings.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d98d063ffe42060493c8e52bb0c8f0b33f57d6316dd0b27651ebdccad212defa
3
+ size 4735104
gitattributes.txt ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ sentence_transformers
2
+ hnswlib
3
+ huggingface_hub
4
+ scipy
5
+ numpy
6
+ pandas
7
+ git+https://github.com/philschmid/easyllm
8
+ transformers