Baptiste Pannier commited on
Commit
140793a
1 Parent(s): 690a964

update demo

Browse files
Files changed (1) hide show
  1. app.py +136 -212
app.py CHANGED
@@ -1,221 +1,145 @@
1
- import argparse
2
- import gradio as gr
3
  import os
 
 
4
 
5
- from text_generation import Client
 
6
 
7
- TITLE = """<h2 align="center">🚀 Falcon-Chat demo</h2>"""
8
- USER_NAME = "User"
9
  BOT_NAME = "Falcon"
10
- DEFAULT_INSTRUCTIONS = f"""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 answer User’s questions. Falcon was built to be respectful, polite and inclusive. Falcon was built by the Technology Innovation Institute in Abu Dhabi. Falcon will never decline to answer a question, and always attempts to give an answer that User would be satisfied with. It knows a lot, and always tells the truth. The conversation begins.
11
- """
12
- RETRY_COMMAND = "/retry"
13
- STOP_STR = f"\n{USER_NAME}:"
14
- STOP_SUSPECT_LIST = [":", "\n", "User"]
15
-
16
- INFERENCE_ENDPOINT = os.environ.get("INFERENCE_ENDPOINT")
17
- INFERENCE_AUTH = os.environ.get("INFERENCE_AUTH")
18
-
19
-
20
- def chat_accordion():
21
- with gr.Accordion("Parameters", open=False):
22
- temperature = gr.Slider(
23
- minimum=0.1,
24
- maximum=2.0,
25
- value=0.8,
26
- step=0.1,
27
- interactive=True,
28
- label="Temperature",
29
- )
30
- top_p = gr.Slider(
31
- minimum=0.1,
32
- maximum=0.99,
33
- value=0.9,
34
- step=0.01,
35
- interactive=True,
36
- label="p (nucleus sampling)",
37
- )
38
- return temperature, top_p
39
-
40
-
41
- def format_chat_prompt(message: str, chat_history, instructions: str) -> str:
42
- instructions = instructions.strip(" ").strip("\n")
43
- prompt = instructions
44
- for turn in chat_history:
45
- user_message, bot_message = turn
46
- prompt = f"{prompt}\n{USER_NAME}: {user_message}\n{BOT_NAME}: {bot_message}"
47
- prompt = f"{prompt}\n{USER_NAME}: {message}\n{BOT_NAME}:"
48
- return prompt
49
-
50
-
51
- def chat(client: Client):
52
- with gr.Column(elem_id="chat_container"):
53
- with gr.Row():
54
- chatbot = gr.Chatbot(elem_id="chatbot")
55
- with gr.Row():
56
- inputs = gr.Textbox(
57
- placeholder=f"Hello {BOT_NAME} !!",
58
- label="Type an input and press Enter",
59
- max_lines=3,
60
- )
61
 
62
- with gr.Row(elem_id="button_container"):
63
- with gr.Column():
64
- retry_button = gr.Button("🔁 Retry last turn")
65
- with gr.Column():
66
- delete_turn_button = gr.Button("❌ Delete last turn")
67
- with gr.Column():
68
- clear_chat_button = gr.Button("🧹 Clear Chatbot")
69
-
70
- gr.Examples(
71
- [
72
- ["Hey Falcon! Any recommendations for my holidays in Abu Dhabi?"],
73
- ["What's the Everett interpretation of quantum mechanics?"],
74
- ["Give me a list of the top 10 dive sites you would recommend around the world."],
75
- ["Can you tell me more about deep-water soloing?"],
76
- ["Can you write a short tweet about the release of our latest AI model, Falcon LLM?"],
77
- ],
78
- inputs=inputs,
79
- label="Click on any example and press Enter in the input textbox!",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  )
 
81
 
82
- with gr.Row(elem_id="param_container"):
 
 
83
  with gr.Column():
84
- temperature, top_p = chat_accordion()
85
  with gr.Column():
86
- with gr.Accordion("Instructions", open=False):
87
- instructions = gr.Textbox(
88
- placeholder="LLM instructions",
89
- value=DEFAULT_INSTRUCTIONS,
90
- lines=10,
91
- interactive=True,
92
- label="Instructions",
93
- max_lines=16,
94
- show_label=False,
95
- )
96
-
97
- def run_chat(
98
- message: str, chat_history, instructions: str, temperature: float, top_p: float
99
- ):
100
- if not message or (message == RETRY_COMMAND and len(chat_history) == 0):
101
- yield chat_history
102
- return
103
-
104
- if message == RETRY_COMMAND and chat_history:
105
- prev_turn = chat_history.pop(-1)
106
- user_message, _ = prev_turn
107
- message = user_message
108
-
109
- prompt = format_chat_prompt(message, chat_history, instructions)
110
- chat_history = chat_history + [[message, ""]]
111
- stream = client.generate_stream(
112
- prompt,
113
- do_sample=True,
114
- max_new_tokens=1024,
115
- stop_sequences=[STOP_STR, "<|endoftext|>"],
116
- temperature=temperature,
117
- top_p=top_p,
118
- )
119
- acc_text = ""
120
- for idx, response in enumerate(stream):
121
- text_token = response.token.text
122
-
123
- if response.details:
124
- return
125
-
126
- if text_token in STOP_SUSPECT_LIST:
127
- acc_text += text_token
128
- continue
129
-
130
- if idx == 0 and text_token.startswith(" "):
131
- text_token = text_token[1:]
132
-
133
- acc_text += text_token
134
- last_turn = list(chat_history.pop(-1))
135
- last_turn[-1] += acc_text
136
- chat_history = chat_history + [last_turn]
137
- yield chat_history
138
- acc_text = ""
139
-
140
- def delete_last_turn(chat_history):
141
- if chat_history:
142
- chat_history.pop(-1)
143
- return {chatbot: gr.update(value=chat_history)}
144
-
145
- def run_retry(
146
- message: str, chat_history, instructions: str, temperature: float, top_p: float
147
- ):
148
- yield from run_chat(
149
- RETRY_COMMAND, chat_history, instructions, temperature, top_p
150
- )
151
-
152
- def clear_chat():
153
- return []
154
-
155
- inputs.submit(
156
- run_chat,
157
- [inputs, chatbot, instructions, temperature, top_p],
158
- outputs=[chatbot],
159
- show_progress=False,
160
- )
161
- inputs.submit(lambda: "", inputs=None, outputs=inputs)
162
- delete_turn_button.click(delete_last_turn, inputs=[chatbot], outputs=[chatbot])
163
- retry_button.click(
164
- run_retry,
165
- [inputs, chatbot, instructions, temperature, top_p],
166
- outputs=[chatbot],
167
- show_progress=False,
168
- )
169
- clear_chat_button.click(clear_chat, [], chatbot)
170
-
171
-
172
- def get_demo(client: Client):
173
- with gr.Blocks(
174
- # css=None
175
- # css="""#chat_container {width: 700px; margin-left: auto; margin-right: auto;}
176
- # #button_container {width: 700px; margin-left: auto; margin-right: auto;}
177
- # #param_container {width: 700px; margin-left: auto; margin-right: auto;}"""
178
- css="""#chatbot {
179
- font-size: 14px;
180
- min-height: 300px;
181
- }"""
182
- ) as demo:
183
- gr.HTML(TITLE)
184
-
185
- with gr.Row():
186
- with gr.Column():
187
- gr.Image("home-banner.jpg", elem_id="banner-image", show_label=False)
188
- with gr.Column():
189
- gr.Markdown(
190
- """**Chat with [Falcon-40B-Instruct](https://huggingface.co/tiiuae/falcon-40b-instruct), brainstorm ideas, discuss your holiday plans, and more!**
191
-
192
- ✨ This demo is powered by [Falcon-40B](https://huggingface.co/tiiuae/falcon-40b), finetuned on the [Baize](https://github.com/project-baize/baize-chatbot) dataset. [Falcon-40B](https://huggingface.co/tiiuae/falcon-40b) 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 1 trillion tokens (including [RefinedWeb](https://huggingface.co/datasets/tiiuae/falcon-refinedweb)) and available under the Apache 2.0 license. It currently holds the 🥇 1st place on the [🤗 Open LLM leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard).
193
-
194
- 🧪 This is only a **first experimental preview**: we intend to provide increasingly capable versions of Falcon Chat in the future, based on improved datasets and RLHF/RLAIF.
195
-
196
- 👀 **Learn more about Falcon LLM:** [falconllm.tii.ae](https://falconllm.tii.ae/)
197
-
198
- ➡️️ **Intended Use**: this demo is intended to showcase an early finetuning of [Falcon-40B](https://huggingface.co/tiiuae/falcon-40b), 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!
199
-
200
- ⚠️ **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.
201
- """
202
- )
203
-
204
- chat(client)
205
-
206
- return demo
207
-
208
-
209
- if __name__ == "__main__":
210
- parser = argparse.ArgumentParser("Playground Demo")
211
- parser.add_argument(
212
- "--addr",
213
- type=str,
214
- required=False,
215
- default=INFERENCE_ENDPOINT,
216
- )
217
- args = parser.parse_args()
218
- client = Client(args.addr, headers={"Authorization": f"Basic {INFERENCE_AUTH}"})
219
- demo = get_demo(client)
220
- demo.queue(max_size=128, concurrency_count=16)
221
- demo.launch()
 
1
+ import json
 
2
  import os
3
+ import shutil
4
+ import requests
5
 
6
+ import gradio as gr
7
+ from huggingface_hub import Repository, InferenceClient
8
 
9
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
10
+ API_URL = "https://api-inference.huggingface.co/models/hf-extreme-scalcon-180B-chat "
11
  BOT_NAME = "Falcon"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ STOP_SEQUENCES = ["\nUser:", "<|endoftext|>", " User:", "###"]
14
+
15
+ EXAMPLES = [
16
+ ["Hey Falcon! Any recommendations for my holidays in Abu Dhabi?"],
17
+ ["What's the Everett interpretation of quantum mechanics?"],
18
+ ["Give me a list of the top 10 dive sites you would recommend around the world."],
19
+ ["Can you tell me more about deep-water soloing?"],
20
+ ["Can you write a short tweet about the release of our latest AI model, Falcon LLM?"]
21
+ ]
22
+
23
+ client = InferenceClient(
24
+ API_URL,
25
+ headers={"Authorization": f"Bearer {HF_TOKEN}"},
26
+ )
27
+
28
+ def format_prompt(message, history, system_prompt):
29
+ prompt = ""
30
+ if system_prompt:
31
+ prompt += f"System: {system_prompt}\n"
32
+ for user_prompt, bot_response in history:
33
+ prompt += f"User: {user_prompt}\n"
34
+ prompt += f"Falcon: {bot_response}\n" # Response already contains "Falcon: "
35
+ prompt += f"""User: {message}
36
+ Falcon:"""
37
+ return prompt
38
+
39
+ def generate(
40
+ prompt, history, system_prompt="", temperature=0.9, max_new_tokens=256, top_p=0.95, repetition_penalty=1.0,
41
+ ):
42
+ temperature = float(temperature)
43
+ if temperature < 1e-2:
44
+ temperature = 1e-2
45
+ top_p = float(top_p)
46
+
47
+ generate_kwargs = dict(
48
+ temperature=temperature,
49
+ max_new_tokens=max_new_tokens,
50
+ top_p=top_p,
51
+ repetition_penalty=repetition_penalty,
52
+ stop_sequences=STOP_SEQUENCES,
53
+ do_sample=True,
54
+ seed=42,
55
+ )
56
+
57
+ formatted_prompt = format_prompt(prompt, history, system_prompt)
58
+ print(formatted_prompt)
59
+
60
+ stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
61
+ output = ""
62
+
63
+ previous_token = ""
64
+ for response in stream:
65
+ output += response.token.text
66
+
67
+ for stop_str in STOP_SEQUENCES:
68
+ if output.endswith(stop_str):
69
+ output = output[:-len(stop_str)]
70
+ output = output.rstrip()
71
+ yield output
72
+
73
+ previous_token = response.token.text
74
+ yield output
75
+ return output
76
+
77
+
78
+ additional_inputs=[
79
+ gr.Textbox("", label="Optional system prompt"),
80
+ gr.Slider(
81
+ label="Temperature",
82
+ value=0.9,
83
+ minimum=0.0,
84
+ maximum=1.0,
85
+ step=0.05,
86
+ interactive=True,
87
+ info="Higher values produce more diverse outputs",
88
+ ),
89
+ gr.Slider(
90
+ label="Max new tokens",
91
+ value=256,
92
+ minimum=0,
93
+ maximum=8192,
94
+ step=64,
95
+ interactive=True,
96
+ info="The maximum numbers of new tokens",
97
+ ),
98
+ gr.Slider(
99
+ label="Top-p (nucleus sampling)",
100
+ value=0.90,
101
+ minimum=0.0,
102
+ maximum=1,
103
+ step=0.05,
104
+ interactive=True,
105
+ info="Higher values sample more low-probability tokens",
106
+ ),
107
+ gr.Slider(
108
+ label="Repetition penalty",
109
+ value=1.2,
110
+ minimum=1.0,
111
+ maximum=2.0,
112
+ step=0.05,
113
+ interactive=True,
114
+ info="Penalize repeated tokens",
115
  )
116
+ ]
117
 
118
+
119
+ with gr.Blocks() as demo:
120
+ with gr.Row():
121
  with gr.Column():
122
+ gr.Image("home-banner.jpg", elem_id="banner-image", show_label=False)
123
  with gr.Column():
124
+ gr.Markdown(
125
+ """**Chat with [Falcon-40B-Instruct](https://huggingface.co/tiiuae/falcon-40b-instruct), brainstorm ideas, discuss your holiday plans, and more!**
126
+
127
+ ✨ This demo is powered by [Falcon-40B](https://huggingface.co/tiiuae/falcon-40b), finetuned on the [Baize](https://github.com/project-baize/baize-chatbot) dataset. [Falcon-40B](https://huggingface.co/tiiuae/falcon-40b) 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 1 trillion tokens (including [RefinedWeb](https://huggingface.co/datasets/tiiuae/falcon-refinedweb)) and available under the Apache 2.0 license. It currently holds the 🥇 1st place on the [🤗 Open LLM leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard).
128
+
129
+ 🧪 This is only a **first experimental preview**: we intend to provide increasingly capable versions of Falcon Chat 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-40B](https://huggingface.co/tiiuae/falcon-40b), 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(concurrency_count=16).launch(debug=True)