ozgur34 commited on
Commit
2b304a0
·
1 Parent(s): 01f88e4

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +273 -0
app.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import gradio as gr
4
+ from huggingface_hub import Repository
5
+ from text_generation import Client
6
+
7
+ # from dialogues import DialogueTemplate
8
+ from share_btn import (community_icon_html, loading_icon_html, share_btn_css,
9
+ share_js)
10
+
11
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
12
+ API_TOKEN = os.environ.get("API_TOKEN", None)
13
+ API_URL = os.environ.get("API_URL", None)
14
+ API_URL = "https://api-inference.huggingface.co/models/timdettmers/guanaco-33b-merged"
15
+
16
+ client = Client(
17
+ API_URL,
18
+ headers={"Authorization": f"Bearer {API_TOKEN}"},
19
+ )
20
+
21
+ repo = None
22
+
23
+
24
+ def get_total_inputs(inputs, chatbot, preprompt, user_name, assistant_name, sep):
25
+ past = []
26
+ for data in chatbot:
27
+ user_data, model_data = data
28
+
29
+ if not user_data.startswith(user_name):
30
+ user_data = user_name + user_data
31
+ if not model_data.startswith(sep + assistant_name):
32
+ model_data = sep + assistant_name + model_data
33
+
34
+ past.append(user_data + model_data.rstrip() + sep)
35
+
36
+ if not inputs.startswith(user_name):
37
+ inputs = user_name + inputs
38
+
39
+ total_inputs = preprompt + "".join(past) + inputs + sep + assistant_name.rstrip()
40
+
41
+ return total_inputs
42
+
43
+
44
+ def has_no_history(chatbot, history):
45
+ return not chatbot and not history
46
+
47
+
48
+ header = "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions."
49
+ prompt_template = "### Human: {query}\n### Assistant:{response}"
50
+
51
+ def generate(
52
+ user_message,
53
+ chatbot,
54
+ history,
55
+ temperature,
56
+ top_p,
57
+ max_new_tokens,
58
+ repetition_penalty,
59
+ ):
60
+ # Don't return meaningless message when the input is empty
61
+ if not user_message:
62
+ print("Empty input")
63
+
64
+ history.append(user_message)
65
+
66
+ past_messages = []
67
+ for data in chatbot:
68
+ user_data, model_data = data
69
+
70
+ past_messages.extend(
71
+ [{"role": "user", "content": user_data}, {"role": "assistant", "content": model_data.rstrip()}]
72
+ )
73
+
74
+ if len(past_messages) < 1:
75
+ prompt = header + prompt_template.format(query=user_message, response="")
76
+ else:
77
+ prompt = header
78
+ for i in range(0, len(past_messages), 2):
79
+ intermediate_prompt = prompt_template.format(query=past_messages[i]["content"], response=past_messages[i+1]["content"])
80
+ print("intermediate: ", intermediate_prompt)
81
+ prompt = prompt + '\n' + intermediate_prompt
82
+
83
+ prompt = prompt + prompt_template.format(query=user_message, response="")
84
+
85
+
86
+ generate_kwargs = {
87
+ "temperature": temperature,
88
+ "top_p": top_p,
89
+ "max_new_tokens": max_new_tokens,
90
+ }
91
+
92
+ temperature = float(temperature)
93
+ if temperature < 1e-2:
94
+ temperature = 1e-2
95
+ top_p = float(top_p)
96
+
97
+ generate_kwargs = dict(
98
+ temperature=temperature,
99
+ max_new_tokens=max_new_tokens,
100
+ top_p=top_p,
101
+ repetition_penalty=repetition_penalty,
102
+ do_sample=True,
103
+ truncate=999,
104
+ seed=42,
105
+ )
106
+
107
+ stream = client.generate_stream(
108
+ prompt,
109
+ **generate_kwargs,
110
+ )
111
+
112
+ output = ""
113
+ for idx, response in enumerate(stream):
114
+ if response.token.text == '':
115
+ break
116
+
117
+ if response.token.special:
118
+ continue
119
+ output += response.token.text
120
+ if idx == 0:
121
+ history.append(" " + output)
122
+ else:
123
+ history[-1] = output
124
+
125
+ chat = [(history[i].strip(), history[i + 1].strip()) for i in range(0, len(history) - 1, 2)]
126
+
127
+ yield chat, history, user_message, ""
128
+
129
+ return chat, history, user_message, ""
130
+
131
+
132
+ examples = [
133
+ "A Llama entered in my garden, what should I do?"
134
+ ]
135
+
136
+
137
+ def clear_chat():
138
+ return [], []
139
+
140
+
141
+ def process_example(args):
142
+ for [x, y] in generate(args):
143
+ pass
144
+ return [x, y]
145
+
146
+
147
+ title = """<h1 align="center">Guanaco Playground 💬</h1>"""
148
+ custom_css = """
149
+ #banner-image {
150
+ display: block;
151
+ margin-left: auto;
152
+ margin-right: auto;
153
+ }
154
+ #chat-message {
155
+ font-size: 14px;
156
+ min-height: 300px;
157
+ }
158
+ """
159
+
160
+ with gr.Blocks(analytics_enabled=False, css=custom_css) as demo:
161
+ gr.HTML(title)
162
+
163
+ with gr.Row():
164
+ with gr.Column():
165
+ gr.Markdown(
166
+ """
167
+ 💻 This demo showcases the Guanaco 33B model, released together with the paper [QLoRA](https://arxiv.org/abs/2305.14314)
168
+ """
169
+ )
170
+
171
+ with gr.Row():
172
+ with gr.Box():
173
+ output = gr.Markdown()
174
+ chatbot = gr.Chatbot(elem_id="chat-message", label="Chat")
175
+
176
+ with gr.Row():
177
+ with gr.Column(scale=3):
178
+ user_message = gr.Textbox(placeholder="Enter your message here", show_label=False, elem_id="q-input")
179
+ with gr.Row():
180
+ send_button = gr.Button("Send", elem_id="send-btn", visible=True)
181
+
182
+ clear_chat_button = gr.Button("Clear chat", elem_id="clear-btn", visible=True)
183
+
184
+ with gr.Accordion(label="Parameters", open=False, elem_id="parameters-accordion"):
185
+ temperature = gr.Slider(
186
+ label="Temperature",
187
+ value=0.7,
188
+ minimum=0.0,
189
+ maximum=1.0,
190
+ step=0.1,
191
+ interactive=True,
192
+ info="Higher values produce more diverse outputs",
193
+ )
194
+ top_p = gr.Slider(
195
+ label="Top-p (nucleus sampling)",
196
+ value=0.9,
197
+ minimum=0.0,
198
+ maximum=1,
199
+ step=0.05,
200
+ interactive=True,
201
+ info="Higher values sample more low-probability tokens",
202
+ )
203
+ max_new_tokens = gr.Slider(
204
+ label="Max new tokens",
205
+ value=1024,
206
+ minimum=0,
207
+ maximum=2048,
208
+ step=4,
209
+ interactive=True,
210
+ info="The maximum numbers of new tokens",
211
+ )
212
+ repetition_penalty = gr.Slider(
213
+ label="Repetition Penalty",
214
+ value=1.2,
215
+ minimum=0.0,
216
+ maximum=10,
217
+ step=0.1,
218
+ interactive=True,
219
+ info="The parameter for repetition penalty. 1.0 means no penalty.",
220
+ )
221
+ with gr.Row():
222
+ gr.Examples(
223
+ examples=examples,
224
+ inputs=[user_message],
225
+ cache_examples=False,
226
+ fn=process_example,
227
+ outputs=[output],
228
+ )
229
+
230
+ with gr.Row():
231
+ gr.Markdown(
232
+ "Disclaimer: The model can produce factually incorrect output, and should not be relied on to produce "
233
+ "factually accurate information. The model was trained on various public datasets; while great efforts "
234
+ "have been taken to clean the pretraining data, it is possible that this model could generate lewd, "
235
+ "biased, or otherwise offensive outputs.",
236
+ elem_classes=["disclaimer"],
237
+ )
238
+
239
+
240
+ history = gr.State([])
241
+ last_user_message = gr.State("")
242
+
243
+ user_message.submit(
244
+ generate,
245
+ inputs=[
246
+ user_message,
247
+ chatbot,
248
+ history,
249
+ temperature,
250
+ top_p,
251
+ max_new_tokens,
252
+ repetition_penalty,
253
+ ],
254
+ outputs=[chatbot, history, last_user_message, user_message],
255
+ )
256
+
257
+ send_button.click(
258
+ generate,
259
+ inputs=[
260
+ user_message,
261
+ chatbot,
262
+ history,
263
+ temperature,
264
+ top_p,
265
+ max_new_tokens,
266
+ repetition_penalty,
267
+ ],
268
+ outputs=[chatbot, history, last_user_message, user_message],
269
+ )
270
+
271
+ clear_chat_button.click(clear_chat, outputs=[chatbot, history])
272
+
273
+ demo.queue(concurrency_count=16).launch(debug=True)