lelafav502 commited on
Commit
db0d777
·
1 Parent(s): ebddb74

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +212 -4
app.py CHANGED
@@ -1,7 +1,215 @@
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
  import gradio as gr
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("✨ Delete all history")
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 Apache 2.0 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(message: str, chat_history, instructions: str, temperature: float, top_p: float):
98
+ if not message or (message == RETRY_COMMAND and len(chat_history) == 0):
99
+ yield chat_history
100
+ return
101
+
102
+ if message == RETRY_COMMAND and chat_history:
103
+ prev_turn = chat_history.pop(-1)
104
+ user_message, _ = prev_turn
105
+ message = user_message
106
+
107
+ prompt = format_chat_prompt(message, chat_history, instructions)
108
+ chat_history = chat_history + [[message, ""]]
109
+ stream = client.generate_stream(
110
+ prompt,
111
+ do_sample=True,
112
+ max_new_tokens=1024,
113
+ stop_sequences=[STOP_STR, "<|endoftext|>"],
114
+ temperature=temperature,
115
+ top_p=top_p,
116
+ )
117
+ acc_text = ""
118
+ for idx, response in enumerate(stream):
119
+ text_token = response.token.text
120
+
121
+ if response.details:
122
+ return
123
+
124
+ if text_token in STOP_SUSPECT_LIST:
125
+ acc_text += text_token
126
+ continue
127
+
128
+ if idx == 0 and text_token.startswith(" "):
129
+ text_token = text_token[1:]
130
+
131
+ acc_text += text_token
132
+ last_turn = list(chat_history.pop(-1))
133
+ last_turn[-1] += acc_text
134
+ chat_history = chat_history + [last_turn]
135
+ yield chat_history
136
+ acc_text = ""
137
+
138
+ def delete_last_turn(chat_history):
139
+ if chat_history:
140
+ chat_history.pop(-1)
141
+ return {chatbot: gr.update(value=chat_history)}
142
+
143
+ def run_retry(message: str, chat_history, instructions: str, temperature: float, top_p: float):
144
+ yield from run_chat(RETRY_COMMAND, chat_history, instructions, temperature, top_p)
145
+
146
+ def clear_chat():
147
+ return []
148
+
149
+ inputs.submit(
150
+ run_chat,
151
+ [inputs, chatbot, instructions, temperature, top_p],
152
+ outputs=[chatbot],
153
+ show_progress=False,
154
+ )
155
+ inputs.submit(lambda: "", inputs=None, outputs=inputs)
156
+ delete_turn_button.click(delete_last_turn, inputs=[chatbot], outputs=[chatbot])
157
+ retry_button.click(
158
+ run_retry,
159
+ [inputs, chatbot, instructions, temperature, top_p],
160
+ outputs=[chatbot],
161
+ show_progress=False,
162
+ )
163
+ clear_chat_button.click(clear_chat, [], chatbot)
164
+
165
+
166
+ def get_demo(client: Client):
167
+ with gr.Blocks(
168
+ # css=None
169
+ # css="""#chat_container {width: 700px; margin-left: auto; margin-right: auto;}
170
+ # #button_container {width: 700px; margin-left: auto; margin-right: auto;}
171
+ # #param_container {width: 700px; margin-left: auto; margin-right: auto;}"""
172
+ css="""#chatbot {
173
+ font-size: 14px;
174
+ min-height: 300px;
175
+ }"""
176
+ ) as demo:
177
+ gr.HTML(TITLE)
178
+
179
+ with gr.Row():
180
+ with gr.Column():
181
+ gr.Image("home-banner.jpg", elem_id="banner-image", show_label=False)
182
+ with gr.Column():
183
+ gr.Markdown(
184
+ """**Chat with [Falcon-40B-Instruct](https://huggingface.co/tiiuae/falcon-40b-instruct), brainstorm ideas, discuss your holiday plans, and more!**
185
+
186
+ ✨ 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, and running with [Text Generation Inference](https://github.com/huggingface/text-generation-inference). [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). This demo is made available by the [HuggingFace H4 team](https://huggingface.co/HuggingFaceH4).
187
+
188
+ 🧪 This is only a **first experimental preview**: the [H4 team](https://huggingface.co/HuggingFaceH4) intends to provide increasingly capable versions of Falcon Chat in the future, based on improved datasets and RLHF/RLAIF.
189
+
190
+ 👀 **Learn more about Falcon LLM:** [falconllm.tii.ae](https://falconllm.tii.ae/)
191
+
192
+ ➡️️ **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!
193
+
194
+ ⚠️ **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.
195
+ """
196
+ )
197
+
198
+ chat(client)
199
+
200
+ return demo
201
 
 
 
202
 
203
+ if __name__ == "__main__":
204
+ parser = argparse.ArgumentParser("Playground Demo")
205
+ parser.add_argument(
206
+ "--addr",
207
+ type=str,
208
+ required=False,
209
+ default=INFERENCE_ENDPOINT,
210
+ )
211
+ args = parser.parse_args()
212
+ client = Client(args.addr, headers={"Authorization": f"Basic {INFERENCE_AUTH}"})
213
+ demo = get_demo(client)
214
+ demo.queue(max_size=128, concurrency_count=16)
215
+ demo.launch()