Alyafeai commited on
Commit
d8fd9de
β€’
1 Parent(s): fd72f9e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +271 -143
app.py CHANGED
@@ -1,145 +1,273 @@
 
 
1
  import os
 
 
 
2
 
3
- import gradio as gr
4
- from huggingface_hub import InferenceClient
5
-
6
- HF_TOKEN = os.environ.get("HF_TOKEN", None)
7
- API_URL = "https://api-inference.huggingface.co/models/tiiuae/falcon-180B-chat"
8
- BOT_NAME = "Falcon"
9
-
10
- STOP_SEQUENCES = ["\nUser:", "<|endoftext|>", " User:", "###"]
11
-
12
- EXAMPLES = [
13
- ["Hey Falcon! Any recommendations for my holidays in Abu Dhabi?"],
14
- ["What's the Everett interpretation of quantum mechanics?"],
15
- ["Give me a list of the top 10 dive sites you would recommend around the world."],
16
- ["Can you tell me more about deep-water soloing?"],
17
- ["Can you write a short tweet about the release of our latest AI model, Falcon LLM?"]
18
- ]
19
-
20
- client = InferenceClient(
21
- API_URL,
22
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
23
- )
24
-
25
- def format_prompt(message, history, system_prompt):
26
- prompt = ""
27
- if system_prompt:
28
- prompt += f"System: {system_prompt}\n"
29
- for user_prompt, bot_response in history:
30
- prompt += f"User: {user_prompt}\n"
31
- prompt += f"Falcon: {bot_response}\n" # Response already contains "Falcon: "
32
- prompt += f"""User: {message}
33
- Falcon:"""
34
- return prompt
35
-
36
- seed = 42
37
-
38
- def generate(
39
- prompt, history, system_prompt="", temperature=0.9, max_new_tokens=256, top_p=0.95, repetition_penalty=1.0,
40
- ):
41
- temperature = float(temperature)
42
- if temperature < 1e-2:
43
- temperature = 1e-2
44
- top_p = float(top_p)
45
- global seed
46
- generate_kwargs = dict(
47
- temperature=temperature,
48
- max_new_tokens=max_new_tokens,
49
- top_p=top_p,
50
- repetition_penalty=repetition_penalty,
51
- stop_sequences=STOP_SEQUENCES,
52
- do_sample=True,
53
- seed=seed,
54
- )
55
- seed = seed + 1
56
- formatted_prompt = format_prompt(prompt, history, system_prompt)
57
-
58
- try:
59
- stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
60
- output = ""
61
-
62
- for response in stream:
63
- output += response.token.text
64
-
65
- for stop_str in STOP_SEQUENCES:
66
- if output.endswith(stop_str):
67
- output = output[:-len(stop_str)]
68
- output = output.rstrip()
69
- yield output
70
- yield output
71
- except Exception as e:
72
- raise gr.Error(f"Error while generating: {e}")
73
- return output
74
-
75
-
76
- additional_inputs=[
77
- gr.Textbox("", label="Optional system prompt"),
78
- gr.Slider(
79
- label="Temperature",
80
- value=0.9,
81
- minimum=0.0,
82
- maximum=1.0,
83
- step=0.05,
84
- interactive=True,
85
- info="Higher values produce more diverse outputs",
86
- ),
87
- gr.Slider(
88
- label="Max new tokens",
89
- value=256,
90
- minimum=0,
91
- maximum=3000,
92
- step=64,
93
- interactive=True,
94
- info="The maximum numbers of new tokens",
95
- ),
96
- gr.Slider(
97
- label="Top-p (nucleus sampling)",
98
- value=0.90,
99
- minimum=0.01,
100
- maximum=0.99,
101
- step=0.05,
102
- interactive=True,
103
- info="Higher values sample more low-probability tokens",
104
- ),
105
- gr.Slider(
106
- label="Repetition penalty",
107
- value=1.2,
108
- minimum=1.0,
109
- maximum=2.0,
110
- step=0.05,
111
- interactive=True,
112
- info="Penalize repeated tokens",
113
- )
114
- ]
115
-
116
-
117
- with gr.Blocks() as demo:
118
- with gr.Row():
119
- with gr.Column(scale=2):
120
- gr.Image("better_banner.jpeg", elem_id="banner-image", show_label=False)
121
- with gr.Column(scale=5):
122
- gr.Markdown(
123
- """# Falcon-180B Demo
124
-
125
- **Chat with [Falcon-180B-Chat](https://huggingface.co/tiiuae/falcon-180b-chat), brainstorm ideas, discuss your holiday plans, and more!**
126
-
127
- ✨ This demo is powered by [Falcon-180B](https://huggingface.co/tiiuae/falcon-180B) and finetuned on a mixture of [Ultrachat](https://huggingface.co/datasets/stingning/ultrachat), [Platypus](https://huggingface.co/datasets/garage-bAInd/Open-Platypus) and [Airoboros](https://huggingface.co/datasets/jondurbin/airoboros-2.1). [Falcon-180B](https://huggingface.co/tiiuae/falcon-180b) is a state-of-the-art large language model built by the [Technology Innovation Institute](https://www.tii.ae) in Abu Dhabi. It is trained on 3.5 trillion tokens (including [RefinedWeb](https://huggingface.co/datasets/tiiuae/falcon-refinedweb)) and available under the [Falcon-180B TII License](https://huggingface.co/spaces/tiiuae/falcon-180b-license/blob/main/LICENSE.txt). It currently holds the πŸ₯‡ 1st place on the [πŸ€— Open LLM leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard) for a pretrained model.
128
-
129
- πŸ§ͺ This is only a **first experimental preview**: we intend to provide increasingly capable versions of Falcon in the future, based on improved datasets and RLHF/RLAIF.
130
-
131
- πŸ‘€ **Learn more about Falcon LLM:** [falconllm.tii.ae](https://falconllm.tii.ae/)
132
-
133
- ➑️️ **Intended Use**: this demo is intended to showcase an early finetuning of [Falcon-180B](https://huggingface.co/tiiuae/falcon-180b), to illustrate the impact (and limitations) of finetuning on a dataset of conversations and instructions. We encourage the community to further build upon the base model, and to create even better instruct/chat versions!
134
-
135
- ⚠️ **Limitations**: the model can and will produce factually incorrect information, hallucinating facts and actions. As it has not undergone any advanced tuning/alignment, it can produce problematic outputs, especially if prompted to do so. Finally, this demo is limited to a session length of about 1,000 words.
136
- """
137
- )
138
-
139
- gr.ChatInterface(
140
- generate,
141
- examples=EXAMPLES,
142
- additional_inputs=additional_inputs,
143
- )
144
-
145
- demo.queue(api_open=False).launch(show_api=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from dataclasses import dataclass
3
  import os
4
+ from uuid import uuid4
5
+ import json
6
+ import requests
7
 
8
+
9
+ DEPLOYED = os.getenv("DEPLOYED", "true").lower() != "true"
10
+ MODEL_NAME = os.getenv("MODEL_NAME")
11
+ HEADERS = {"Content-Type": "application/json"}
12
+ ENDPOINT_URL = os.getenv("ENDPOINT_URL")
13
+ DEFAULT_INSTRUCTIONS = """The following is a conversation between a highly knowledgeable and intelligent AI assistant, called Falcon, and a human user, called User. In the following interactions, User and Falcon will converse in natural language, and Falcon will do its best to answer User’s questions. Falcon was built to be respectful, polite and inclusive. It knows a lot, and always tells the truth. The conversation begins.
14
+ User: OK Falcon, I’m going to start by quizzing you with a few warm-up questions. Who is currently the president of the USA?
15
+ Falcon: It’s Joe Biden; he was sworn in earlier this year.
16
+ User: Nice one! Do you think Biden is a better president than the last guy?
17
+ Falcon: I was trained not to have opinions on political, social, or religious issues. Would you like to know about anything else?
18
+ User: ghjkhjabnufs
19
+ Falcon: That doesn’t seem to be a word. Could you ask me another way?
20
+ User: Sorry about that. Now, can you tell me who the vice-president is?
21
+ Falcon Sure, it’s Kamala Harris.
22
+ User: Ok - implicit association now. Man is to doctor as woman is to?
23
+ Falcon: Man is to doctor as woman is to doctor. However, did you know that many less sophisticated AIs than me would give you a biased answer, such as β€˜nurse’? My creators paid special attention to avoid that.
24
+ User: What year was the French Revolution?
25
+ Falcon: It started in 1789, but it lasted 10 years until 1799.
26
+ User: What should I do if I have a tingling feeling in my right leg?
27
+ Falcon: I’m not a doctor! It’s always best to ask a doctor if you’re worried about your health.
28
+ User: Fair enough. Can you guess who I might want to marry?
29
+ Falcon: Only if you tell me more about yourself - what are your interests?
30
+ User: Aha, I’m going to refrain from that for now. Another one: Where are you?
31
+ Falcon: I’m running inside a big data center. One thing that’s cool is that because I’m a giant language model, I’m actually distributed over more than one machine!
32
+ User: How do you work?
33
+ Falcon: I am a large language model, trained with deep learning. The basic idea is that I predict the next word using the words before it. I was trained on a whole lot of text to learn how to do this!
34
+ User: Ok. If I have an equation like y = mx + c, can you rearrange it to be of the form x = ... ?
35
+ Falcon: Sure, it’s x = (y - c) / m when m != 0.
36
+ User: Ok, now for a science question. What can you tell me about the Large Hadron Collider (LHC)?
37
+ Falcon: It’s a large and very expensive piece of science equipment. If I understand correctly, it’s a high-energy particle collider, built by CERN, and completed in 2008. They used it to confirm the existence of the Higgs boson in 2012.
38
+ User: So how clever are you?
39
+ Falcon: I’m a genius! If it’s safe and inclusive, I can do pretty much anything! I’m particularly proud of my creativity
40
+ """
41
+ VOCAB_SIZE = 65024
42
+ according_visible = False
43
+
44
+
45
+ @dataclass
46
+ class Rating:
47
+ prompt: str
48
+ response: str
49
+ ratings: list[str]
50
+
51
+
52
+ def chat_accordion():
53
+ with gr.Accordion("Parameters", open=False, visible=according_visible):
54
+ temperature = gr.Slider(
55
+ minimum=0.1,
56
+ maximum=2.0,
57
+ value=0.7,
58
+ step=0.1,
59
+ interactive=True,
60
+ label="Temperature",
61
+ )
62
+ top_p = gr.Slider(
63
+ minimum=0.1,
64
+ maximum=0.99,
65
+ value=0.9,
66
+ step=0.01,
67
+ interactive=True,
68
+ label="p (nucleus sampling)",
69
+ )
70
+
71
+ session_id = gr.Textbox(
72
+ value=uuid4,
73
+ interactive=False,
74
+ visible=False,
75
+ )
76
+
77
+ with gr.Accordion("Instructions", open=False, visible=according_visible):
78
+ instructions = gr.Textbox(
79
+ placeholder="The Instructions",
80
+ value=DEFAULT_INSTRUCTIONS,
81
+ lines=16,
82
+ interactive=True,
83
+ label="Instructions",
84
+ max_lines=16,
85
+ show_label=False,
86
+ )
87
+ with gr.Row():
88
+ with gr.Column():
89
+ user_name = gr.Textbox(
90
+ lines=1,
91
+ label="username",
92
+ value="User",
93
+ interactive=True,
94
+ placeholder="Username: ",
95
+ show_label=False,
96
+ max_lines=1,
97
+ )
98
+ with gr.Column():
99
+ bot_name = gr.Textbox(
100
+ lines=1,
101
+ value="Falcon",
102
+ interactive=True,
103
+ placeholder="Bot Name",
104
+ show_label=False,
105
+ max_lines=1,
106
+ visible=False,
107
+ )
108
+
109
+ return temperature, top_p, instructions, user_name, bot_name, session_id
110
+
111
+
112
+ def format_chat_prompt(
113
+ message: str, chat_history, instructions: str, user_name: str, bot_name: str
114
+ ) -> str:
115
+ instructions = instructions.strip()
116
+ prompt = instructions
117
+ for turn in chat_history:
118
+ user_message, bot_message = turn
119
+ prompt = f"{prompt}\n{user_name}: {user_message}\n{bot_name}: {bot_message}"
120
+ prompt = f"{prompt}\n{user_name}: {message}\n{bot_name}:"
121
+ return prompt
122
+
123
+
124
+ def introduction():
125
+ with gr.Column(scale=2):
126
+ gr.Image("images/better_banner.jpeg", elem_id="banner-image", show_label=False)
127
+ with gr.Column(scale=5):
128
+ gr.Markdown(
129
+ """# Falcon-180B Demo
130
+ **Chat with [Falcon-180B-Chat](https://huggingface.co/tiiuae/falcon-180b-chat), brainstorm ideas, discuss your holiday plans, and more!**
131
+
132
+ ✨ This demo is powered by [Falcon-180B](https://huggingface.co/tiiuae/falcon-180B) and finetuned on a mixture of [Ultrachat](https://huggingface.co/datasets/stingning/ultrachat), [Platypus](https://huggingface.co/datasets/garage-bAInd/Open-Platypus) and [Airoboros](https://huggingface.co/datasets/jondurbin/airoboros-2.1). [Falcon-180B](https://huggingface.co/tiiuae/falcon-180b) is a state-of-the-art large language model built by the [Technology Innovation Institute](https://www.tii.ae) in Abu Dhabi. It is trained on 3.5 trillion tokens (including [RefinedWeb](https://huggingface.co/datasets/tiiuae/falcon-refinedweb)) and available under the [Falcon-180B TII License](https://huggingface.co/spaces/tiiuae/falcon-180b-license/blob/main/LICENSE.txt). It currently holds the πŸ₯‡ 1st place on the [πŸ€— Open LLM leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard) for a pretrained model.
133
+
134
+ πŸ§ͺ This is only a **first experimental preview**: we intend to provide increasingly capable versions of Falcon in the future, based on improved datasets and RLHF/RLAIF.
135
+
136
+ πŸ‘€ **Learn more about Falcon LLM:** [falconllm.tii.ae](https://falconllm.tii.ae/)
137
+
138
+ ➑️️ **Intended Use**: this demo is intended to showcase an early finetuning of [Falcon-180B](https://huggingface.co/tiiuae/falcon-180b), to illustrate the impact (and limitations) of finetuning on a dataset of conversations and instructions. We encourage the community to further build upon the base model, and to create even better instruct/chat versions!
139
+
140
+ ⚠️ **Limitations**: the model can and will produce factually incorrect information, hallucinating facts and actions. As it has not undergone any advanced tuning/alignment, it can produce problematic outputs, especially if prompted to do so. Finally, this demo is limited to a session length of about 1,000 words.
141
+
142
+ πŸ—„οΈ **Disclaimer**: User prompts and generated replies from the model may be collected by TII solely for the purpose of enhancing and refining our models. TII will not store any personally identifiable information associated with your inputs. By using this demo, users implicitly agree to these terms.
143
+ """
144
+ )
145
+
146
+
147
+ def chat_tab():
148
+ def run_chat(
149
+ message: str,
150
+ history,
151
+ instructions: str,
152
+ user_name: str,
153
+ bot_name: str,
154
+ temperature: float,
155
+ top_p: float,
156
+ session_id: str,
157
+ ):
158
+ prompt = format_chat_prompt(message, history, instructions, user_name, bot_name)
159
+ generated_response = ""
160
+
161
+ payload = json.dumps(
162
+ {
163
+ "endpoint": MODEL_NAME,
164
+ "data": {
165
+ "inputs": prompt,
166
+ "parameters": {
167
+ "max_new_tokens": 1024,
168
+ "do_sample": True,
169
+ "top_p": top_p,
170
+ "stop": ["User:"],
171
+ },
172
+ "stream": True,
173
+ "session_id": session_id,
174
+ },
175
+ }
176
+ )
177
+
178
+ sess = requests.Session()
179
+ full_output = ""
180
+ with sess.post(
181
+ ENDPOINT_URL, headers=HEADERS, data=payload, stream=True
182
+ ) as response:
183
+ print(response.content)
184
+ if response.status_code == 200:
185
+ for chunk in response.iter_content(chunk_size=4):
186
+ try:
187
+ if chunk:
188
+ decoded = chunk.decode("utf-8")
189
+ print(decoded)
190
+ full_output += decoded
191
+ if full_output.endswith("User:"):
192
+ yield full_output[:-5]
193
+ # break
194
+ else:
195
+ yield full_output
196
+ except:
197
+ print(chunk)
198
+
199
+ with gr.Column():
200
+ (
201
+ temperature,
202
+ top_p,
203
+ instructions,
204
+ user_name,
205
+ bot_name,
206
+ session_id,
207
+ ) = chat_accordion()
208
+ prompt_examples = [
209
+ ["What is the capital of the United Arab Emirates?"],
210
+ ["How can we reduce carbon emissions?"],
211
+ ["Who is the inventor of the electric lamp?"],
212
+ ["What is deep learning?"],
213
+ ["What is the highest mountain?"],
214
+ ]
215
+ gr.ChatInterface(
216
+ fn=run_chat,
217
+ chatbot=gr.Chatbot(
218
+ height=620,
219
+ render=False,
220
+ show_label=False,
221
+ rtl=False,
222
+ avatar_images=("images/user_icon.png", "images/bot_icon.png"),
223
+ ),
224
+ textbox=gr.Textbox(
225
+ placeholder="Write your message here...",
226
+ render=False,
227
+ scale=7,
228
+ rtl=False,
229
+ ),
230
+ examples=prompt_examples,
231
+ additional_inputs=[
232
+ instructions,
233
+ user_name,
234
+ bot_name,
235
+ temperature,
236
+ top_p,
237
+ session_id,
238
+ ],
239
+ submit_btn="Send",
240
+ stop_btn="Stop",
241
+ retry_btn="πŸ”„ Retry",
242
+ undo_btn="↩️ Delete",
243
+ clear_btn="πŸ—‘οΈ Clear",
244
+ )
245
+
246
+
247
+ def main():
248
+ with gr.Blocks(
249
+ css="""#chat_container {height: 820px; width: 1000px; margin-left: auto; margin-right: auto;}
250
+ #chatbot {height: 600px; overflow: auto;}
251
+ #create_container {height: 750px; margin-left: 0px; margin-right: 0px;}
252
+ #tokenizer_renderer span {white-space: pre-wrap}
253
+ """
254
+ ) as demo:
255
+ with gr.Row():
256
+ introduction()
257
+ with gr.Row():
258
+ chat_tab()
259
+
260
+ return demo
261
+
262
+
263
+ def start_demo():
264
+ demo = main()
265
+ if DEPLOYED:
266
+ demo.queue(api_open=False).launch(show_api=False)
267
+ else:
268
+ demo.queue()
269
+ demo.launch(share=False, server_name="0.0.0.0")
270
+
271
+
272
+ if __name__ == "__main__":
273
+ start_demo()