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