ehristoforu commited on
Commit
eb19ee3
1 Parent(s): 5b841ba

Upload 4 files

Browse files
Files changed (4) hide show
  1. app (15).py +456 -0
  2. dialogues.py +241 -0
  3. requirements (15).txt +2 -0
  4. share_btn (2).py +111 -0
app (15).py ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import os
3
+ import random
4
+ import re
5
+ from io import StringIO
6
+
7
+ import gradio as gr
8
+ import pandas as pd
9
+ from huggingface_hub import upload_file
10
+ from text_generation import Client
11
+
12
+ from dialogues import DialogueTemplate
13
+ from share_btn import (community_icon_html, loading_icon_html, share_btn_css,
14
+ share_js)
15
+
16
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
17
+ API_TOKEN = os.environ.get("API_TOKEN", None)
18
+ DIALOGUES_DATASET = "HuggingFaceH4/starchat_playground_dialogues"
19
+
20
+ model2endpoint = {
21
+ "starchat-alpha": "https://api-inference.huggingface.co/models/HuggingFaceH4/starcoderbase-finetuned-oasst1",
22
+ "starchat-beta": "https://api-inference.huggingface.co/models/HuggingFaceH4/starchat-beta",
23
+ }
24
+ model_names = list(model2endpoint.keys())
25
+
26
+
27
+ def randomize_seed_generator():
28
+ seed = random.randint(0, 1000000)
29
+ return seed
30
+
31
+
32
+ def save_inputs_and_outputs(now, inputs, outputs, generate_kwargs, model):
33
+ buffer = StringIO()
34
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f")
35
+ file_name = f"prompts_{timestamp}.jsonl"
36
+ data = {"model": model, "inputs": inputs, "outputs": outputs, "generate_kwargs": generate_kwargs}
37
+ pd.DataFrame([data]).to_json(buffer, orient="records", lines=True)
38
+
39
+ # Push to Hub
40
+ upload_file(
41
+ path_in_repo=f"{now.date()}/{now.hour}/{file_name}",
42
+ path_or_fileobj=buffer.getvalue().encode(),
43
+ repo_id=DIALOGUES_DATASET,
44
+ token=HF_TOKEN,
45
+ repo_type="dataset",
46
+ )
47
+
48
+ # Clean and rerun
49
+ buffer.close()
50
+
51
+
52
+ def get_total_inputs(inputs, chatbot, preprompt, user_name, assistant_name, sep):
53
+ past = []
54
+ for data in chatbot:
55
+ user_data, model_data = data
56
+
57
+ if not user_data.startswith(user_name):
58
+ user_data = user_name + user_data
59
+ if not model_data.startswith(sep + assistant_name):
60
+ model_data = sep + assistant_name + model_data
61
+
62
+ past.append(user_data + model_data.rstrip() + sep)
63
+
64
+ if not inputs.startswith(user_name):
65
+ inputs = user_name + inputs
66
+
67
+ total_inputs = preprompt + "".join(past) + inputs + sep + assistant_name.rstrip()
68
+
69
+ return total_inputs
70
+
71
+
72
+ def wrap_html_code(text):
73
+ pattern = r"<.*?>"
74
+ matches = re.findall(pattern, text)
75
+ if len(matches) > 0:
76
+ return f"```{text}```"
77
+ else:
78
+ return text
79
+
80
+
81
+ def has_no_history(chatbot, history):
82
+ return not chatbot and not history
83
+
84
+
85
+ def generate(
86
+ RETRY_FLAG,
87
+ model_name,
88
+ system_message,
89
+ user_message,
90
+ chatbot,
91
+ history,
92
+ temperature,
93
+ top_k,
94
+ top_p,
95
+ max_new_tokens,
96
+ repetition_penalty,
97
+ do_save=True,
98
+ ):
99
+ client = Client(
100
+ model2endpoint[model_name],
101
+ headers={"Authorization": f"Bearer {API_TOKEN}"},
102
+ timeout=60,
103
+ )
104
+ # Don't return meaningless message when the input is empty
105
+ if not user_message:
106
+ print("Empty input")
107
+
108
+ if not RETRY_FLAG:
109
+ history.append(user_message)
110
+ seed = 42
111
+ else:
112
+ seed = randomize_seed_generator()
113
+
114
+ past_messages = []
115
+ for data in chatbot:
116
+ user_data, model_data = data
117
+
118
+ past_messages.extend(
119
+ [{"role": "user", "content": user_data}, {"role": "assistant", "content": model_data.rstrip()}]
120
+ )
121
+
122
+ if len(past_messages) < 1:
123
+ dialogue_template = DialogueTemplate(
124
+ system=system_message, messages=[{"role": "user", "content": user_message}]
125
+ )
126
+ prompt = dialogue_template.get_inference_prompt()
127
+ else:
128
+ dialogue_template = DialogueTemplate(
129
+ system=system_message, messages=past_messages + [{"role": "user", "content": user_message}]
130
+ )
131
+ prompt = dialogue_template.get_inference_prompt()
132
+
133
+ generate_kwargs = {
134
+ "temperature": temperature,
135
+ "top_k": top_k,
136
+ "top_p": top_p,
137
+ "max_new_tokens": max_new_tokens,
138
+ }
139
+
140
+ temperature = float(temperature)
141
+ if temperature < 1e-2:
142
+ temperature = 1e-2
143
+ top_p = float(top_p)
144
+
145
+ generate_kwargs = dict(
146
+ temperature=temperature,
147
+ max_new_tokens=max_new_tokens,
148
+ top_p=top_p,
149
+ repetition_penalty=repetition_penalty,
150
+ do_sample=True,
151
+ truncate=4096,
152
+ seed=seed,
153
+ stop_sequences=["<|end|>"],
154
+ )
155
+
156
+ stream = client.generate_stream(
157
+ prompt,
158
+ **generate_kwargs,
159
+ )
160
+
161
+ output = ""
162
+ for idx, response in enumerate(stream):
163
+ if response.token.special:
164
+ continue
165
+ output += response.token.text
166
+ if idx == 0:
167
+ history.append(" " + output)
168
+ else:
169
+ history[-1] = output
170
+
171
+ chat = [
172
+ (wrap_html_code(history[i].strip()), wrap_html_code(history[i + 1].strip()))
173
+ for i in range(0, len(history) - 1, 2)
174
+ ]
175
+
176
+ # chat = [(history[i].strip(), history[i + 1].strip()) for i in range(0, len(history) - 1, 2)]
177
+
178
+ yield chat, history, user_message, ""
179
+
180
+ if HF_TOKEN and do_save:
181
+ try:
182
+ now = datetime.datetime.now()
183
+ current_time = now.strftime("%Y-%m-%d %H:%M:%S")
184
+ print(f"[{current_time}] Pushing prompt and completion to the Hub")
185
+ save_inputs_and_outputs(now, prompt, output, generate_kwargs, model_name)
186
+ except Exception as e:
187
+ print(e)
188
+
189
+ return chat, history, user_message, ""
190
+
191
+
192
+ examples = [
193
+ "How can I write a Python function to generate the nth Fibonacci number?",
194
+ "How do I get the current date using shell commands? Explain how it works.",
195
+ "What's the meaning of life?",
196
+ "Write a function in Javascript to reverse words in a given string.",
197
+ "Give the following data {'Name':['Tom', 'Brad', 'Kyle', 'Jerry'], 'Age':[20, 21, 19, 18], 'Height' : [6.1, 5.9, 6.0, 6.1]}. Can you plot one graph with two subplots as columns. The first is a bar graph showing the height of each person. The second is a bargraph showing the age of each person? Draw the graph in seaborn talk mode.",
198
+ "Create a regex to extract dates from logs",
199
+ "How to decode JSON into a typescript object",
200
+ "Write a list into a jsonlines file and save locally",
201
+ ]
202
+
203
+
204
+ def clear_chat():
205
+ return [], []
206
+
207
+
208
+ def delete_last_turn(chat, history):
209
+ if chat and history:
210
+ chat.pop(-1)
211
+ history.pop(-1)
212
+ history.pop(-1)
213
+ return chat, history
214
+
215
+
216
+ def process_example(args):
217
+ for [x, y] in generate(args):
218
+ pass
219
+ return [x, y]
220
+
221
+
222
+ # Regenerate response
223
+ def retry_last_answer(
224
+ selected_model,
225
+ system_message,
226
+ user_message,
227
+ chat,
228
+ history,
229
+ temperature,
230
+ top_k,
231
+ top_p,
232
+ max_new_tokens,
233
+ repetition_penalty,
234
+ do_save,
235
+ ):
236
+ if chat and history:
237
+ # Removing the previous conversation from chat
238
+ chat.pop(-1)
239
+ # Removing bot response from the history
240
+ history.pop(-1)
241
+ # Setting up a flag to capture a retry
242
+ RETRY_FLAG = True
243
+ # Getting last message from user
244
+ user_message = history[-1]
245
+
246
+ yield from generate(
247
+ RETRY_FLAG,
248
+ selected_model,
249
+ system_message,
250
+ user_message,
251
+ chat,
252
+ history,
253
+ temperature,
254
+ top_k,
255
+ top_p,
256
+ max_new_tokens,
257
+ repetition_penalty,
258
+ do_save,
259
+ )
260
+
261
+
262
+ title = """<h1 align="center">⭐ StarChat Playground 💬</h1>"""
263
+ custom_css = """
264
+ #banner-image {
265
+ display: block;
266
+ margin-left: auto;
267
+ margin-right: auto;
268
+ }
269
+
270
+ #chat-message {
271
+ font-size: 14px;
272
+ min-height: 300px;
273
+ }
274
+ """
275
+
276
+ with gr.Blocks(analytics_enabled=False, css=custom_css) as demo:
277
+ gr.HTML(title)
278
+
279
+ with gr.Row():
280
+ with gr.Column():
281
+ gr.Image("thumbnail.png", elem_id="banner-image", show_label=False)
282
+ with gr.Column():
283
+ gr.Markdown(
284
+ """
285
+ 💻 This demo showcases a series of **[StarChat](https://huggingface.co/models?search=huggingfaceh4/starchat)** language models, which are fine-tuned versions of the StarCoder family to act as helpful coding assistants. The base model has 16B parameters and was pretrained on one trillion tokens sourced from 80+ programming languages, GitHub issues, Git commits, and Jupyter notebooks (all permissively licensed).
286
+
287
+ 📝 For more details, check out our [blog post](https://huggingface.co/blog/starchat-alpha).
288
+
289
+ ⚠️ **Intended Use**: this app and its [supporting models](https://huggingface.co/models?search=huggingfaceh4/starchat) are provided as educational tools to explain large language model fine-tuning; not to serve as replacement for human expertise.
290
+
291
+ ⚠️ **Known Failure Modes**: the alpha and beta version of **StarChat** have not been aligned to human preferences with techniques like RLHF, so they can produce problematic outputs (especially when prompted to do so). Since the base model was pretrained on a large corpus of code, it may produce code snippets that are syntactically valid but semantically incorrect. For example, it may produce code that does not compile or that produces incorrect results. It may also produce code that is vulnerable to security exploits. We have observed the model also has a tendency to produce false URLs which should be carefully inspected before clicking. For more details on the model's limitations in terms of factuality and biases, see the [model card](https://huggingface.co/HuggingFaceH4/starchat-alpha#bias-risks-and-limitations).
292
+
293
+ ⚠️ **Data Collection**: by default, we are collecting the prompts entered in this app to further improve and evaluate the models. Do **NOT** share any personal or sensitive information while using the app! You can opt out of this data collection by removing the checkbox below.
294
+ """
295
+ )
296
+
297
+ with gr.Row():
298
+ do_save = gr.Checkbox(
299
+ value=True,
300
+ label="Store data",
301
+ info="You agree to the storage of your prompt and generated text for research and development purposes:",
302
+ )
303
+
304
+ with gr.Row():
305
+ selected_model = gr.Radio(choices=model_names, value=model_names[1], label="Select a model")
306
+
307
+ with gr.Accordion(label="System Prompt", open=False, elem_id="parameters-accordion"):
308
+ system_message = gr.Textbox(
309
+ elem_id="system-message",
310
+ placeholder="Below is a conversation between a human user and a helpful AI coding assistant.",
311
+ show_label=False,
312
+ )
313
+ with gr.Row():
314
+ with gr.Box():
315
+ output = gr.Markdown()
316
+ chatbot = gr.Chatbot(elem_id="chat-message", label="Chat")
317
+
318
+ with gr.Row():
319
+ with gr.Column(scale=3):
320
+ user_message = gr.Textbox(placeholder="Enter your message here", show_label=False, elem_id="q-input")
321
+ with gr.Row():
322
+ send_button = gr.Button("Send", elem_id="send-btn", visible=True)
323
+
324
+ regenerate_button = gr.Button("Regenerate", elem_id="retry-btn", visible=True)
325
+
326
+ delete_turn_button = gr.Button("Delete last turn", elem_id="delete-btn", visible=True)
327
+
328
+ clear_chat_button = gr.Button("Clear chat", elem_id="clear-btn", visible=True)
329
+
330
+ with gr.Accordion(label="Parameters", open=False, elem_id="parameters-accordion"):
331
+ temperature = gr.Slider(
332
+ label="Temperature",
333
+ value=0.2,
334
+ minimum=0.0,
335
+ maximum=1.0,
336
+ step=0.1,
337
+ interactive=True,
338
+ info="Higher values produce more diverse outputs",
339
+ )
340
+ top_k = gr.Slider(
341
+ label="Top-k",
342
+ value=50,
343
+ minimum=0.0,
344
+ maximum=100,
345
+ step=1,
346
+ interactive=True,
347
+ info="Sample from a shortlist of top-k tokens",
348
+ )
349
+ top_p = gr.Slider(
350
+ label="Top-p (nucleus sampling)",
351
+ value=0.95,
352
+ minimum=0.0,
353
+ maximum=1,
354
+ step=0.05,
355
+ interactive=True,
356
+ info="Higher values sample more low-probability tokens",
357
+ )
358
+ max_new_tokens = gr.Slider(
359
+ label="Max new tokens",
360
+ value=512,
361
+ minimum=0,
362
+ maximum=1024,
363
+ step=4,
364
+ interactive=True,
365
+ info="The maximum numbers of new tokens",
366
+ )
367
+ repetition_penalty = gr.Slider(
368
+ label="Repetition Penalty",
369
+ value=1.2,
370
+ minimum=0.0,
371
+ maximum=10,
372
+ step=0.1,
373
+ interactive=True,
374
+ info="The parameter for repetition penalty. 1.0 means no penalty.",
375
+ )
376
+ # with gr.Group(elem_id="share-btn-container"):
377
+ # community_icon = gr.HTML(community_icon_html, visible=True)
378
+ # loading_icon = gr.HTML(loading_icon_html, visible=True)
379
+ # share_button = gr.Button("Share to community", elem_id="share-btn", visible=True)
380
+ with gr.Row():
381
+ gr.Examples(
382
+ examples=examples,
383
+ inputs=[user_message],
384
+ cache_examples=False,
385
+ fn=process_example,
386
+ outputs=[output],
387
+ )
388
+
389
+ history = gr.State([])
390
+ RETRY_FLAG = gr.Checkbox(value=False, visible=False)
391
+
392
+ # To clear out "message" input textbox and use this to regenerate message
393
+ last_user_message = gr.State("")
394
+
395
+ user_message.submit(
396
+ generate,
397
+ inputs=[
398
+ RETRY_FLAG,
399
+ selected_model,
400
+ system_message,
401
+ user_message,
402
+ chatbot,
403
+ history,
404
+ temperature,
405
+ top_k,
406
+ top_p,
407
+ max_new_tokens,
408
+ repetition_penalty,
409
+ do_save,
410
+ ],
411
+ outputs=[chatbot, history, last_user_message, user_message],
412
+ )
413
+
414
+ send_button.click(
415
+ generate,
416
+ inputs=[
417
+ RETRY_FLAG,
418
+ selected_model,
419
+ system_message,
420
+ user_message,
421
+ chatbot,
422
+ history,
423
+ temperature,
424
+ top_k,
425
+ top_p,
426
+ max_new_tokens,
427
+ repetition_penalty,
428
+ do_save,
429
+ ],
430
+ outputs=[chatbot, history, last_user_message, user_message],
431
+ )
432
+
433
+ regenerate_button.click(
434
+ retry_last_answer,
435
+ inputs=[
436
+ selected_model,
437
+ system_message,
438
+ user_message,
439
+ chatbot,
440
+ history,
441
+ temperature,
442
+ top_k,
443
+ top_p,
444
+ max_new_tokens,
445
+ repetition_penalty,
446
+ do_save,
447
+ ],
448
+ outputs=[chatbot, history, last_user_message, user_message],
449
+ )
450
+
451
+ delete_turn_button.click(delete_last_turn, [chatbot, history], [chatbot, history])
452
+ clear_chat_button.click(clear_chat, outputs=[chatbot, history])
453
+ selected_model.change(clear_chat, outputs=[chatbot, history])
454
+ # share_button.click(None, [], [], _js=share_js)
455
+
456
+ demo.queue(concurrency_count=16).launch(debug=True)
dialogues.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import json
17
+ import os
18
+ from dataclasses import asdict, dataclass
19
+ from pathlib import Path
20
+ from typing import Any, Dict, List, Optional, Type, TypeVar, Union
21
+
22
+ from huggingface_hub import ModelHubMixin, hf_hub_download
23
+
24
+ # Generic variable that is either ModelHubMixin or a subclass thereof
25
+ T = TypeVar("T", bound="ModelHubMixin")
26
+
27
+ TEMPLATE_FILENAME = "dialogue_template.json"
28
+ IGNORE_INDEX = -100
29
+
30
+
31
+ @dataclass
32
+ class DialogueTemplate(ModelHubMixin):
33
+ """Converts all turns of a dialogue between a user and assistant to a standardized format.
34
+
35
+ Adapted from OpenAI's ChatML (https://github.com/openai/openai-python/blob/main/chatml.md) and Vicuna (https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py)
36
+ """
37
+
38
+ system: str
39
+ messages: List[Dict[str, str]] = None
40
+ system_token: str = "<|system|>"
41
+ user_token: str = "<|user|>"
42
+ assistant_token: str = "<|assistant|>"
43
+ end_token: str = "<|end|>"
44
+
45
+ def get_training_prompt(self) -> str:
46
+ prompt = self.system_token + "\n" + self.system + self.end_token + "\n"
47
+ if self.messages is None:
48
+ raise ValueError("Dialogue template must have at least one message.")
49
+ for message in self.messages:
50
+ if message["role"] == "user":
51
+ prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n"
52
+ else:
53
+ prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n"
54
+ return prompt
55
+
56
+ def get_inference_prompt(self) -> str:
57
+ prompt = self.system_token + "\n" + self.system + self.end_token + "\n"
58
+ if self.messages is None:
59
+ raise ValueError("Dialogue template must have at least one message.")
60
+ for message in self.messages:
61
+ if message["role"] == "user":
62
+ prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n"
63
+ else:
64
+ prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n"
65
+ prompt += self.assistant_token + "\n"
66
+ return prompt
67
+
68
+ def get_dialogue(self):
69
+ """Helper function to format the messages as an easy-to-read dialogue."""
70
+ prompt = ""
71
+ if self.messages is None:
72
+ raise ValueError("Dialogue template must have at least one message.")
73
+ for message in self.messages:
74
+ if message["role"] == "user":
75
+ prompt += "\n\nHuman: " + message["content"]
76
+ else:
77
+ prompt += "\n\nAssistant: " + message["content"]
78
+ return prompt
79
+
80
+ def get_special_tokens(self) -> List[str]:
81
+ return [self.system_token, self.user_token, self.assistant_token, self.end_token]
82
+
83
+ def copy(self):
84
+ return DialogueTemplate(
85
+ system=self.system,
86
+ messages=self.messages,
87
+ system_token=self.system_token,
88
+ user_token=self.user_token,
89
+ assistant_token=self.assistant_token,
90
+ end_token=self.end_token,
91
+ )
92
+
93
+ def to_dict(self) -> Dict[str, Any]:
94
+ return {k: v for k, v in asdict(self).items()}
95
+
96
+ @classmethod
97
+ def from_dict(cls, data):
98
+ return DialogueTemplate(
99
+ system=data["system"] if "system" in data else "",
100
+ messages=data["messages"] if "messages" in data else None,
101
+ system_token=data["system_token"] if "system_token" in data else "<|system|>",
102
+ user_token=data["user_token"] if "user_token" in data else "<|user|>",
103
+ assistant_token=data["assistant_token"] if "assistant_token" in data else "<|assistant|>",
104
+ end_token=data["end_token"] if "end_token" in data else "<|end|>",
105
+ )
106
+
107
+ def _save_pretrained(self, save_directory: Union[str, Path]) -> None:
108
+ save_directory = Path(save_directory)
109
+ save_directory.mkdir(exist_ok=True)
110
+ with open(save_directory / "dialogue_template.json", "w") as f:
111
+ json.dump(self.to_dict(), f, indent=2)
112
+
113
+ @classmethod
114
+ def _from_pretrained(
115
+ cls: Type[T],
116
+ *,
117
+ model_id: str,
118
+ revision: Optional[str],
119
+ cache_dir: Optional[Union[str, Path]],
120
+ force_download: bool,
121
+ proxies: Optional[Dict],
122
+ resume_download: bool,
123
+ local_files_only: bool,
124
+ token: Optional[Union[str, bool]],
125
+ **model_kwargs,
126
+ ) -> T:
127
+ """Loads the dialogue template from a local directory or the Huggingface Hub.
128
+
129
+ Args:
130
+ model_id (`str`):
131
+ ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`).
132
+ revision (`str`, *optional*):
133
+ Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the
134
+ latest commit on `main` branch.
135
+ force_download (`bool`, *optional*, defaults to `False`):
136
+ Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
137
+ the existing cache.
138
+ resume_download (`bool`, *optional*, defaults to `False`):
139
+ Whether to delete incompletely received files. Will attempt to resume the download if such a file exists.
140
+ proxies (`Dict[str, str]`, *optional*):
141
+ A dictionary of proxy servers to use by protocol or endpoint (e.g., `{'http': 'foo.bar:3128',
142
+ 'http://hostname': 'foo.bar:4012'}`).
143
+ token (`str` or `bool`, *optional*):
144
+ The token to use as HTTP bearer authorization for remote files. By default, it will use the token
145
+ cached when running `huggingface-cli login`.
146
+ cache_dir (`str`, `Path`, *optional*):
147
+ Path to the folder where cached files are stored.
148
+ local_files_only (`bool`, *optional*, defaults to `False`):
149
+ If `True`, avoid downloading the file and return the path to the local cached file if it exists.
150
+ model_kwargs:
151
+ Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method.
152
+ """
153
+ if os.path.isdir(model_id): # Can either be a local directory
154
+ print("Loading dialogue template from local directory")
155
+ template_file = os.path.join(model_id, TEMPLATE_FILENAME)
156
+ else: # Or a template on the Hub
157
+ template_file = hf_hub_download( # Download from the hub, passing same input args
158
+ repo_id=model_id,
159
+ filename=TEMPLATE_FILENAME,
160
+ revision=revision,
161
+ cache_dir=cache_dir,
162
+ force_download=force_download,
163
+ proxies=proxies,
164
+ resume_download=resume_download,
165
+ token=token,
166
+ local_files_only=local_files_only,
167
+ )
168
+
169
+ # Load template
170
+ with open(template_file, "r") as f:
171
+ data = json.load(f)
172
+ return cls.from_dict(data=data)
173
+
174
+
175
+ # A shortened version of the system message in Anthropic's HHH prompt: https://gist.github.com/jareddk/2509330f8ef3d787fc5aaac67aab5f11#file-hhh_prompt-txt
176
+ default_template = DialogueTemplate(
177
+ system="Below is a dialogue between a human user and an AI assistant. The assistant is happy to help with almost anything, and will do its best to understand exactly what is needed.",
178
+ )
179
+
180
+ # OpenAI and OpenAssistant train on few to no system messages.
181
+ # TODO: consider defining this as the `default` template
182
+ no_system_template = DialogueTemplate(
183
+ system="",
184
+ )
185
+
186
+ alpaca_template = DialogueTemplate(
187
+ system="Below is an instruction that describes a task. Write a response that appropriately completes the request.",
188
+ user_token="### Instruction:",
189
+ assistant_token="### Response:",
190
+ )
191
+
192
+ SUPPORTED_DIALOGUE_TEMPLATES = {
193
+ "default": default_template,
194
+ "no_system": no_system_template,
195
+ "alpaca": alpaca_template,
196
+ }
197
+
198
+
199
+ def get_dialogue_template(template: str) -> DialogueTemplate:
200
+ if template not in SUPPORTED_DIALOGUE_TEMPLATES.keys():
201
+ raise ValueError(f"Template {template} is not supported!")
202
+ return SUPPORTED_DIALOGUE_TEMPLATES[template].copy()
203
+
204
+
205
+ def prepare_dialogue(example, dialogue_template, is_train=True):
206
+ """Format example to single- or multi-turn dialogue."""
207
+ # TODO: make this simpler by just ensuring every dataset has a messages column
208
+ if "messages" in example.keys() and example["messages"] is not None:
209
+ dialogue_template.messages = example["messages"]
210
+ elif all(k in example.keys() for k in ("prompt", "completion")):
211
+ # Construct single-turn dialogue from prompt and completion
212
+ dialogue_template.messages = [
213
+ {"role": "user", "content": example["prompt"]},
214
+ {"role": "assistant", "content": example["completion"]},
215
+ ]
216
+ elif "prompt" in example.keys():
217
+ # Construct single-turn dialogue from prompt (inference only)
218
+ dialogue_template.messages = [
219
+ {"role": "user", "content": example["prompt"]},
220
+ ]
221
+ else:
222
+ raise ValueError(
223
+ f"Could not format example as dialogue! Require either `messages` or `[prompt, completion]` or `[prompt]` keys but found {list(example.keys())}"
224
+ )
225
+ if is_train:
226
+ example["text"] = dialogue_template.get_training_prompt()
227
+ else:
228
+ example["text"] = dialogue_template.get_inference_prompt()
229
+ return example
230
+
231
+
232
+ def mask_user_labels(tokenizer, dialogue_template, labels):
233
+ """Masks the user turns of a dialogue from the loss"""
234
+ user_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.user_token)
235
+ assistant_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.assistant_token)
236
+ for idx, label_id in enumerate(labels):
237
+ if label_id == user_token_id:
238
+ current_idx = idx
239
+ while labels[current_idx] != assistant_token_id and current_idx < len(labels):
240
+ labels[current_idx] = IGNORE_INDEX
241
+ current_idx += 1
requirements (15).txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ huggingface_hub
2
+ text-generation
share_btn (2).py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
2
+ <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
3
+ <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
4
+ </svg>"""
5
+
6
+ loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
7
+ style="color: #ffffff;
8
+ "
9
+ xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
10
+
11
+ share_js = """async () => {
12
+ async function uploadFile(file){
13
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
14
+ const response = await fetch(UPLOAD_URL, {
15
+ method: 'POST',
16
+ headers: {
17
+ 'Content-Type': file.type,
18
+ 'X-Requested-With': 'XMLHttpRequest',
19
+ },
20
+ body: file, /// <- File inherits from Blob
21
+ });
22
+ const url = await response.text();
23
+ return url;
24
+ }
25
+
26
+ async function getInputImgFile(imgEl){
27
+ const res = await fetch(imgEl.src);
28
+ const blob = await res.blob();
29
+ const imgId = Date.now() % 200;
30
+ const isPng = imgEl.src.startsWith(`data:image/png`);
31
+ if(isPng){
32
+ const fileName = `sd-perception-${{imgId}}.png`;
33
+ return new File([blob], fileName, { type: 'image/png' });
34
+ }else{
35
+ const fileName = `sd-perception-${{imgId}}.jpg`;
36
+ return new File([blob], fileName, { type: 'image/jpeg' });
37
+ }
38
+ }
39
+
40
+ // const gradioEl = document.querySelector('body > gradio-app');
41
+ const gradioEl = document.querySelector("gradio-app");
42
+ const inputTxt = gradioEl.querySelector('#q-input textarea').value;
43
+ const outputTxt = gradioEl.querySelector('#q-output').outerHTML;
44
+
45
+ const titleLength = 150;
46
+ let titleTxt = inputTxt;
47
+ if(titleTxt.length > titleLength){
48
+ titleTxt = titleTxt.slice(0, titleLength) + ' ...';
49
+ }
50
+
51
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
52
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
53
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
54
+
55
+ if(!inputTxt || !outputTxt){
56
+ return;
57
+ };
58
+
59
+ shareBtnEl.style.pointerEvents = 'none';
60
+ shareIconEl.style.display = 'none';
61
+ loadingIconEl.style.removeProperty('display');
62
+
63
+ const descriptionMd = `### Question:
64
+ ${inputTxt}
65
+
66
+ ### Answer:
67
+
68
+ ${outputTxt}`;
69
+
70
+ const params = {
71
+ title: titleTxt,
72
+ description: descriptionMd,
73
+ };
74
+
75
+ const paramsStr = Object.entries(params)
76
+ .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
77
+ .join('&');
78
+
79
+ window.open(`https://huggingface.co/spaces/HuggingFaceH4/star-chat-demo/discussions/new?${paramsStr}`, '_blank');
80
+
81
+ shareBtnEl.style.removeProperty('pointer-events');
82
+ shareIconEl.style.removeProperty('display');
83
+ loadingIconEl.style.display = 'none';
84
+ }"""
85
+
86
+ share_btn_css = """
87
+ a {text-decoration-line: underline; font-weight: 600;}
88
+ .animate-spin {
89
+ animation: spin 1s linear infinite;
90
+ }
91
+ @keyframes spin {
92
+ from { transform: rotate(0deg); }
93
+ to { transform: rotate(360deg); }
94
+ }
95
+ #share-btn-container {
96
+ display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem;
97
+ }
98
+ #share-btn {
99
+ all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;
100
+ }
101
+ #share-btn * {
102
+ all: unset;
103
+ }
104
+ #share-btn-container div:nth-child(-n+2){
105
+ width: auto !important;
106
+ min-height: 0px !important;
107
+ }
108
+ #share-btn-container .wrap {
109
+ display: none !important;
110
+ }
111
+ """