wang16888 commited on
Commit
7f91570
·
verified ·
1 Parent(s): 447fa72

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -50
app.py CHANGED
@@ -1,64 +1,137 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
8
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
27
 
28
- response = ""
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from datasets import load_dataset
3
 
4
+ import os
5
+ import spaces
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfig
7
+ import torch
8
+ from threading import Thread
9
+ from sentence_transformers import SentenceTransformer
10
+ from datasets import load_dataset
11
+ import time
12
 
13
+ token = os.environ["HF_TOKEN"]
14
+ ST = SentenceTransformer("mixedbread-ai/mxbai-embed-large-v1")
15
 
16
+ dataset = load_dataset("not-lain/wikipedia",revision = "embedded")
 
 
 
 
 
 
 
 
17
 
18
+ data = dataset["train"]
19
+ data = data.add_faiss_index("embeddings") # column name that has the embeddings of the dataset
 
 
 
20
 
 
21
 
22
+ model_id = "meta-llama/Meta-Llama-3-8B-Instruct"
23
 
24
+ # use quantization to lower GPU usage
25
+ bnb_config = BitsAndBytesConfig(
26
+ load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16
27
+ )
 
 
 
 
28
 
29
+ tokenizer = AutoTokenizer.from_pretrained(model_id,token=token)
30
+ model = AutoModelForCausalLM.from_pretrained(
31
+ model_id,
32
+ torch_dtype=torch.bfloat16,
33
+ device_map="auto",
34
+ quantization_config=bnb_config,
35
+ token=token
36
+ )
37
+ terminators = [
38
+ tokenizer.eos_token_id,
39
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
40
+ ]
41
 
42
+ SYS_PROMPT = """You are an assistant for answering questions.
43
+ You are given the extracted parts of a long document and a question. Provide a conversational answer.
44
+ If you don't know the answer, just say "I do not know." Don't make up an answer."""
45
 
46
+
47
+
48
+ def search(query: str, k: int = 3 ):
49
+ """a function that embeds a new query and returns the most probable results"""
50
+ embedded_query = ST.encode(query) # embed new query
51
+ scores, retrieved_examples = data.get_nearest_examples( # retrieve results
52
+ "embeddings", embedded_query, # compare our new embedded query with the dataset embeddings
53
+ k=k # get only top k results
54
+ )
55
+ return scores, retrieved_examples
56
+
57
+ def format_prompt(prompt,retrieved_documents,k):
58
+ """using the retrieved documents we will prompt the model to generate our responses"""
59
+ PROMPT = f"Question:{prompt}\nContext:"
60
+ for idx in range(k) :
61
+ PROMPT+= f"{retrieved_documents['text'][idx]}\n"
62
+ return PROMPT
63
+
64
+
65
+ @spaces.GPU(duration=150)
66
+ def talk(prompt,history):
67
+ k = 1 # number of retrieved documents
68
+ scores , retrieved_documents = search(prompt, k)
69
+ formatted_prompt = format_prompt(prompt,retrieved_documents,k)
70
+ formatted_prompt = formatted_prompt[:2000] # to avoid GPU OOM
71
+ messages = [{"role":"system","content":SYS_PROMPT},{"role":"user","content":formatted_prompt}]
72
+ # tell the model to generate
73
+ input_ids = tokenizer.apply_chat_template(
74
+ messages,
75
+ add_generation_prompt=True,
76
+ return_tensors="pt"
77
+ ).to(model.device)
78
+ outputs = model.generate(
79
+ input_ids,
80
+ max_new_tokens=1024,
81
+ eos_token_id=terminators,
82
+ do_sample=True,
83
+ temperature=0.6,
84
+ top_p=0.9,
85
+ )
86
+ streamer = TextIteratorStreamer(
87
+ tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True
88
+ )
89
+ generate_kwargs = dict(
90
+ input_ids= input_ids,
91
+ streamer=streamer,
92
+ max_new_tokens=1024,
93
+ do_sample=True,
94
+ top_p=0.95,
95
+ temperature=0.75,
96
+ eos_token_id=terminators,
97
+ )
98
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
99
+ t.start()
100
+
101
+ outputs = []
102
+ for text in streamer:
103
+ outputs.append(text)
104
+ print(outputs)
105
+ yield "".join(outputs)
106
+
107
+
108
+ TITLE = "# RAG"
109
+
110
+ DESCRIPTION = """
111
+ A rag pipeline with a chatbot feature
112
+ Resources used to build this project :
113
+ * embedding model : https://huggingface.co/mixedbread-ai/mxbai-embed-large-v1
114
+ * dataset : https://huggingface.co/datasets/not-lain/wikipedia
115
+ * faiss docs : https://huggingface.co/docs/datasets/v2.18.0/en/package_reference/main_classes#datasets.Dataset.add_faiss_index
116
+ * chatbot : https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct
117
+ * Full documentation : https://huggingface.co/blog/not-lain/rag-chatbot-using-llama3
118
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
 
121
+ demo = gr.ChatInterface(
122
+ fn=talk,
123
+ chatbot=gr.Chatbot(
124
+ show_label=True,
125
+ show_share_button=True,
126
+ show_copy_button=True,
127
+ likeable=True,
128
+ layout="bubble",
129
+ bubble_full_width=False,
130
+ ),
131
+ theme="Soft",
132
+ examples=[["what's anarchy ? "]],
133
+ title=TITLE,
134
+ description=DESCRIPTION,
135
+
136
+ )
137
+ demo.launch(debug=True)