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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
+ Chat History:
60
+ {chat_history}
61
+ Follow Up Input: {question}
62
+ """
63
+
64
+
65
+ def get_prompt(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> str:
66
+ texts = [f"<s>[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n"]
67
+ # The first user input is _not_ stripped
68
+ do_strip = False
69
+ for user_input, response in chat_history:
70
+ user_input = user_input.strip() if do_strip else user_input
71
+ do_strip = True
72
+ texts.append(f"{user_input} [/INST] {response.strip()} </s><s>[INST] ")
73
+ message = message.strip() if do_strip else message
74
+ texts.append(f"{message} [/INST]")
75
+ return "".join(texts)
76
+
77
+
78
+ def get_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> int:
79
+ prompt = get_prompt(message, chat_history, system_prompt)
80
+ input_ids = tokenizer([prompt], return_tensors="np", add_special_tokens=False)["input_ids"]
81
+ return input_ids.shape[-1]
82
+
83
+
84
+ # https://www.philschmid.de/llama-2#how-to-prompt-llama-2-chat
85
+ def get_completion(
86
+ prompt,
87
+ system_prompt=None,
88
+ model=model_id,
89
+ max_new_tokens=1024,
90
+ temperature=0.2,
91
+ top_p=0.95,
92
+ top_k=50,
93
+ stream=False,
94
+ debug=False,
95
+ ):
96
+ if temperature < 1e-2:
97
+ temperature = 1e-2
98
+ messages = []
99
+ if system_prompt is not None:
100
+ messages.append({"role": "system", "content": system_prompt})
101
+ messages.append({"role": "user", "content": prompt})
102
+ response = huggingface.ChatCompletion.create(
103
+ model=model,
104
+ messages=messages,
105
+ temperature=temperature, # this is the degree of randomness of the model's output
106
+ max_tokens=max_new_tokens, # this is the number of new tokens being generated
107
+ top_p=top_p,
108
+ top_k=top_k,
109
+ stream=stream,
110
+ debug=debug,
111
+ )
112
+ return response["choices"][0]["message"]["content"] if not stream else response
113
+
114
+
115
+ # load the index for the PEFT docs
116
+ def load_hnsw_index(index_file):
117
+ # Load the HNSW index from the specified file
118
+ index = hnswlib.Index(space="ip", dim=EMBED_DIM)
119
+ index.load_index(index_file)
120
+ return index
121
+
122
+
123
+ # create the index for the PEFT docs from numpy embeddings
124
+ # avoid the arch mismatches when creating search index
125
+ def create_hnsw_index(embeddings_file, M=16, efC=100):
126
+ embeddings = np.load(embeddings_file)
127
+ # Create the HNSW index
128
+ num_dim = embeddings.shape[1]
129
+ ids = np.arange(embeddings.shape[0])
130
+ index = hnswlib.Index(space="ip", dim=num_dim)
131
+ index.init_index(max_elements=embeddings.shape[0], ef_construction=efC, M=M)
132
+ index.add_items(embeddings, ids)
133
+ return index
134
+
135
+
136
+ def create_query_embedding(query):
137
+ # Encode the query to get its embedding
138
+ embedding = biencoder.encode([query], normalize_embeddings=True)[0]
139
+ return embedding
140
+
141
+
142
+ def find_nearest_neighbors(query_embedding):
143
+ search_index.set_ef(EF)
144
+ # Find the k-nearest neighbors for the query embedding
145
+ labels, distances = search_index.knn_query(query_embedding, k=K)
146
+ labels = [label for label, distance in zip(labels[0], distances[0]) if (1 - distance) >= COSINE_THRESHOLD]
147
+ relevant_chunks = data_df.iloc[labels]["chunk_content"].tolist()
148
+ return relevant_chunks
149
+
150
+
151
+ def rerank_chunks_with_cross_encoder(query, chunks):
152
+ # Create a list of tuples, each containing a query-chunk pair
153
+ pairs = [(query, chunk) for chunk in chunks]
154
+
155
+ # Get scores for each query-chunk pair using the cross encoder
156
+ scores = cross_encoder.predict(pairs)
157
+
158
+ # Sort the chunks based on their scores in descending order
159
+ sorted_chunks = [chunk for _, chunk in sorted(zip(scores, chunks), reverse=True)]
160
+
161
+ return sorted_chunks
162
+
163
+
164
+ def generate_condensed_query(query, history):
165
+ chat_history = ""
166
+ for turn in history:
167
+ chat_history += f"Human: {turn[0]}\n"
168
+ chat_history += f"Assistant: {turn[1]}\n"
169
+
170
+ condense_question_prompt = create_condense_question_prompt(query, chat_history)
171
+ condensed_question = json.loads(get_completion(condense_question_prompt, max_new_tokens=64, temperature=0))
172
+ return condensed_question["question"]
173
+
174
+
175
+ DEFAULT_SYSTEM_PROMPT = """\
176
+ 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.
177
+ 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.\
178
+ """
179
+ MAX_MAX_NEW_TOKENS = 2048
180
+ DEFAULT_MAX_NEW_TOKENS = 1024
181
+ MAX_INPUT_TOKEN_LENGTH = 4000
182
+
183
+ DESCRIPTION = """
184
+ # PEFT Docs QA Chatbot 🤗
185
+ """
186
+
187
+ LICENSE = """
188
+ <p/>
189
+ ---
190
+ As a derivate work of [Llama-2-70b-chat](https://huggingface.co/meta-llama/Llama-2-70b-chat) by Meta,
191
+ 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).
192
+ """
193
+
194
+ if not torch.cuda.is_available():
195
+ DESCRIPTION += "\n<p>Running on CPU 🥶.</p>"
196
+
197
+
198
+ def clear_and_save_textbox(message: str) -> tuple[str, str]:
199
+ return "", message
200
+
201
+
202
+ def display_input(message: str, history: list[tuple[str, str]]) -> list[tuple[str, str]]:
203
+ history.append((message, ""))
204
+ return history
205
+
206
+
207
+ def delete_prev_fn(history: list[tuple[str, str]]) -> tuple[list[tuple[str, str]], str]:
208
+ try:
209
+ message, _ = history.pop()
210
+ except IndexError:
211
+ message = ""
212
+ return history, message or ""
213
+
214
+
215
+ def wrap_html_code(text):
216
+ pattern = r"<.*?>"
217
+ matches = re.findall(pattern, text)
218
+ if len(matches) > 0:
219
+ return f"```{text}```"
220
+ else:
221
+ return text
222
+
223
+
224
+ def generate(
225
+ message: str,
226
+ history_with_input: list[tuple[str, str]],
227
+ system_prompt: str,
228
+ max_new_tokens: int,
229
+ temperature: float,
230
+ top_p: float,
231
+ top_k: int,
232
+ ) -> Iterator[list[tuple[str, str]]]:
233
+ if max_new_tokens > MAX_MAX_NEW_TOKENS:
234
+ raise ValueError
235
+ history = history_with_input[:-1]
236
+ if len(history) > 0:
237
+ condensed_query = generate_condensed_query(message, history)
238
+ print(f"{condensed_query=}")
239
+ else:
240
+ condensed_query = message
241
+ query_embedding = create_query_embedding(condensed_query)
242
+ relevant_chunks = find_nearest_neighbors(query_embedding)
243
+ reranked_relevant_chunks = rerank_chunks_with_cross_encoder(condensed_query, relevant_chunks)
244
+ qa_prompt = create_qa_prompt(condensed_query, reranked_relevant_chunks)
245
+ print(f"{qa_prompt=}")
246
+ generator = get_completion(
247
+ qa_prompt,
248
+ system_prompt=system_prompt,
249
+ stream=True,
250
+ max_new_tokens=max_new_tokens,
251
+ temperature=temperature,
252
+ top_k=top_k,
253
+ top_p=top_p,
254
+ )
255
+
256
+ output = ""
257
+ for idx, response in enumerate(generator):
258
+ token = response["choices"][0]["delta"].get("content", "") or ""
259
+ output += token
260
+ if idx == 0:
261
+ history.append((message, output))
262
+ else:
263
+ history[-1] = (message, output)
264
+
265
+ history = [
266
+ (wrap_html_code(history[i][0].strip()), wrap_html_code(history[i][1].strip()))
267
+ for i in range(0, len(history))
268
+ ]
269
+ yield history
270
+
271
+ return history
272
+
273
+
274
+ def process_example(message: str) -> tuple[str, list[tuple[str, str]]]:
275
+ generator = generate(message, [], DEFAULT_SYSTEM_PROMPT, 1024, 0.2, 0.95, 50)
276
+ for x in generator:
277
+ pass
278
+ return "", x
279
+
280
+
281
+ def check_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> None:
282
+ input_token_length = get_input_token_length(message, chat_history, system_prompt)
283
+ if input_token_length > MAX_INPUT_TOKEN_LENGTH:
284
+ raise gr.Error(
285
+ f"The accumulated input is too long ({input_token_length} > {MAX_INPUT_TOKEN_LENGTH}). Clear your chat history and try again."
286
+ )
287
+
288
+
289
+ search_index = create_hnsw_index(EMBEDDINGS_FILE) # load_hnsw_index(SEARCH_INDEX)
290
+ data_df = pd.read_parquet(DOCUMENT_DATASET).reset_index()
291
+ with gr.Blocks(css="style.css") as demo:
292
+ gr.Markdown(DESCRIPTION)
293
+
294
+ with gr.Group():
295
+ chatbot = gr.Chatbot(label="Chatbot")
296
+ with gr.Row():
297
+ textbox = gr.Textbox(
298
+ container=False,
299
+ show_label=False,
300
+ placeholder="Type a message...",
301
+ scale=10,
302
+ )
303
+ submit_button = gr.Button("Submit", variant="primary", scale=1, min_width=0)
304
+ with gr.Row():
305
+ retry_button = gr.Button("🔄 Retry", variant="secondary")
306
+ undo_button = gr.Button("↩️ Undo", variant="secondary")
307
+ clear_button = gr.Button("🗑️ Clear", variant="secondary")
308
+
309
+ saved_input = gr.State()
310
+
311
+ with gr.Accordion(label="Advanced options", open=False):
312
+ system_prompt = gr.Textbox(label="System prompt", value=DEFAULT_SYSTEM_PROMPT, lines=6)
313
+ max_new_tokens = gr.Slider(
314
+ label="Max new tokens",
315
+ minimum=1,
316
+ maximum=MAX_MAX_NEW_TOKENS,
317
+ step=1,
318
+ value=DEFAULT_MAX_NEW_TOKENS,
319
+ )
320
+ temperature = gr.Slider(
321
+ label="Temperature",
322
+ minimum=0.1,
323
+ maximum=4.0,
324
+ step=0.1,
325
+ value=0.2,
326
+ )
327
+ top_p = gr.Slider(
328
+ label="Top-p (nucleus sampling)",
329
+ minimum=0.05,
330
+ maximum=1.0,
331
+ step=0.05,
332
+ value=0.95,
333
+ )
334
+ top_k = gr.Slider(
335
+ label="Top-k",
336
+ minimum=1,
337
+ maximum=1000,
338
+ step=1,
339
+ value=50,
340
+ )
341
+
342
+ gr.Examples(
343
+ examples=[
344
+ "What is 🤗 PEFT?",
345
+ "How do I create a LoraConfig?",
346
+ "What are the different tuners supported?",
347
+ "How do I use LoRA with custom models?",
348
+ "What are the different real-world applications that I can use PEFT for?",
349
+ ],
350
+ inputs=textbox,
351
+ outputs=[textbox, chatbot],
352
+ # fn=process_example,
353
+ cache_examples=False,
354
+ )
355
+
356
+ gr.Markdown(LICENSE)
357
+
358
+ textbox.submit(
359
+ fn=clear_and_save_textbox,
360
+ inputs=textbox,
361
+ outputs=[textbox, saved_input],
362
+ api_name=False,
363
+ queue=False,
364
+ ).then(fn=display_input, inputs=[saved_input, chatbot], outputs=chatbot, api_name=False, queue=False,).then(
365
+ fn=check_input_token_length,
366
+ inputs=[saved_input, chatbot, system_prompt],
367
+ api_name=False,
368
+ queue=False,
369
+ ).success(
370
+ fn=generate,
371
+ inputs=[
372
+ saved_input,
373
+ chatbot,
374
+ system_prompt,
375
+ max_new_tokens,
376
+ temperature,
377
+ top_p,
378
+ top_k,
379
+ ],
380
+ outputs=chatbot,
381
+ api_name=False,
382
+ )
383
+
384
+ button_event_preprocess = (
385
+ submit_button.click(
386
+ fn=clear_and_save_textbox,
387
+ inputs=textbox,
388
+ outputs=[textbox, saved_input],
389
+ api_name=False,
390
+ queue=False,
391
+ )
392
+ .then(
393
+ fn=display_input,
394
+ inputs=[saved_input, chatbot],
395
+ outputs=chatbot,
396
+ api_name=False,
397
+ queue=False,
398
+ )
399
+ .then(
400
+ fn=check_input_token_length,
401
+ inputs=[saved_input, chatbot, system_prompt],
402
+ api_name=False,
403
+ queue=False,
404
+ )
405
+ .success(
406
+ fn=generate,
407
+ inputs=[
408
+ saved_input,
409
+ chatbot,
410
+ system_prompt,
411
+ max_new_tokens,
412
+ temperature,
413
+ top_p,
414
+ top_k,
415
+ ],
416
+ outputs=chatbot,
417
+ api_name=False,
418
+ )
419
+ )
420
+
421
+ retry_button.click(
422
+ fn=delete_prev_fn,
423
+ inputs=chatbot,
424
+ outputs=[chatbot, saved_input],
425
+ api_name=False,
426
+ queue=False,
427
+ ).then(fn=display_input, inputs=[saved_input, chatbot], outputs=chatbot, api_name=False, queue=False,).then(
428
+ fn=generate,
429
+ inputs=[
430
+ saved_input,
431
+ chatbot,
432
+ system_prompt,
433
+ max_new_tokens,
434
+ temperature,
435
+ top_p,
436
+ top_k,
437
+ ],
438
+ outputs=chatbot,
439
+ api_name=False,
440
+ )
441
+
442
+ undo_button.click(
443
+ fn=delete_prev_fn,
444
+ inputs=chatbot,
445
+ outputs=[chatbot, saved_input],
446
+ api_name=False,
447
+ queue=False,
448
+ ).then(
449
+ fn=lambda x: x,
450
+ inputs=[saved_input],
451
+ outputs=textbox,
452
+ api_name=False,
453
+ queue=False,
454
+ )
455
+
456
+ clear_button.click(
457
+ fn=lambda: ([], ""),
458
+ outputs=[chatbot, saved_input],
459
+ queue=False,
460
+ api_name=False,
461
+ )
462
+
463
+ demo.queue(max_size=20).launch(debug=True, share=False)