File size: 18,510 Bytes
c58ee05
 
0285eae
059c495
c58ee05
 
0285eae
c58ee05
 
e65a984
0285eae
351a51d
c58ee05
 
0285eae
 
5f64773
2fef107
d7a0f2f
0285eae
be3a86c
ce01d23
c58ee05
d7a0f2f
 
 
 
 
 
c58ee05
d7a0f2f
0285eae
 
 
 
 
 
 
92776ad
 
d7a0f2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94dec10
 
 
 
 
 
 
d7a0f2f
 
 
 
 
 
 
 
 
351a51d
7703eca
943046d
d7a0f2f
 
 
 
351a51d
7703eca
943046d
d7a0f2f
 
 
 
50136b5
7703eca
50136b5
d7a0f2f
 
0285eae
d7a0f2f
 
 
 
 
 
 
 
 
 
 
 
0285eae
d7a0f2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74d6bba
d7a0f2f
 
 
 
 
 
 
0285eae
 
 
 
 
 
 
 
 
 
 
 
d7a0f2f
 
 
0285eae
d7a0f2f
351a51d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1f1826
 
0285eae
 
50c0ffd
 
55bc27f
 
 
0285eae
 
d7a0f2f
 
 
 
 
 
 
 
 
0285eae
 
d7a0f2f
0285eae
d7a0f2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0285eae
7b6a5b3
d7a0f2f
 
 
 
 
 
 
 
 
 
 
0285eae
d7a0f2f
d442dca
d7a0f2f
 
157d6d0
 
b8310dc
 
 
 
 
 
 
 
 
 
 
32241a9
d442dca
d7a0f2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0285eae
 
 
 
d7a0f2f
0285eae
 
 
 
d7a0f2f
 
 
 
 
 
0285eae
d7a0f2f
0285eae
 
 
c9eb8b9
0285eae
 
 
 
 
 
d7a0f2f
 
 
 
 
 
 
 
 
0285eae
d7a0f2f
0285eae
d7a0f2f
 
 
0285eae
d7a0f2f
ce01d23
fed4096
 
738d1d5
fed4096
 
 
d7a0f2f
 
 
 
 
 
 
 
 
 
 
0285eae
d442dca
 
 
 
 
 
 
 
d7a0f2f
 
 
 
 
 
 
 
 
 
 
 
 
 
0285eae
d7a0f2f
 
 
 
 
 
 
 
 
 
0285eae
d7a0f2f
 
 
 
 
 
 
0285eae
d7a0f2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
import datetime
import random
import os
import re
from io import StringIO

import gradio as gr
import pandas as pd

from huggingface_hub import Repository, upload_file
from text_generation import Client
from text_generation.errors import UnknownError
from share_btn import (community_icon_html, loading_icon_html, share_btn_css,
                       share_js)

HF_TOKEN = os.environ.get("HF_TOKEN", None)
API_TOKEN = os.environ.get("API_TOKEN", HF_TOKEN)

DIALOGUES_DATASET = "ArmelR/gradio_playground_dialogues"

API_URL_G = "https://api-inference.huggingface.co/models/ArmelR/starcoder-gradio-v0"
API_URL_S = "https://api-inference.huggingface.co/models/HuggingFaceH4/starcoderbase-finetuned-oasst1"
API_URL_B = "https://api-inference.huggingface.co/models/HuggingFaceH4/starchat-beta"

model2endpoint = {
    "starChat-alpha": API_URL_S,
    "starCoder-gradio": API_URL_G,
    "starChat-beta": API_URL_B
}

model_names = list(model2endpoint.keys())

with open("./HHH_prompt_short.txt", "r") as f:
    HHH_PROMPT = f.read() + "\n\n"

with open("./TA_prompt_v0.txt", "r") as f:
    TA_PROMPT = f.read()

NO_PROMPT = ""

def randomize_seed_generator():
    seed = random.randint(0, 1000000)
    return seed


def save_inputs_and_outputs(now, inputs, outputs, generate_kwargs, model):
    buffer = StringIO()
    timestamp = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f")
    file_name = f"prompts_{timestamp}.jsonl"
    data = {"model": model, "inputs": inputs, "outputs": outputs, "generate_kwargs": generate_kwargs}
    pd.DataFrame([data]).to_json(buffer, orient="records", lines=True)

    # Push to Hub
    upload_file(
        path_in_repo=f"{now.date()}/{now.hour}/{file_name}",
        path_or_fileobj=buffer.getvalue().encode(),
        repo_id=DIALOGUES_DATASET,
        token=HF_TOKEN,
        repo_type="dataset",
    )

    # Clean and rerun
    buffer.close()

def get_total_inputs(inputs, chatbot, preprompt, user_name, assistant_name, sep):
    past = []
    for data in chatbot:
        user_data, model_data = data

        if not user_data.startswith(user_name):
            user_data = user_name + user_data
        if not model_data.startswith(sep + assistant_name):
            model_data = sep + assistant_name + model_data

        past.append(user_data + model_data.rstrip() + sep)

    if not inputs.startswith(user_name):
        inputs = user_name + inputs

    total_inputs = preprompt + "".join(past) + inputs + sep + assistant_name.rstrip()

    return total_inputs
    
def wrap_html_code(text):
    pattern = r"<.*?>"
    matches = re.findall(pattern, text)
    if len(matches) > 0:
        return f"```{text}```"
    else:
        return text

def has_no_history(chatbot, history):
    return not chatbot and not history

def get_inference_prompt(messages, model_name):
    if model_name == "starChat-beta" :
        prompt = "<|system|>\n<|endoftext|>\n"
        for message in messages :
            if message["role"] == "user" :
                prompt += f"<|user|>\n{message['content']}<|endoftext|>\n<|assistant|>\n"
            else : # message["role"] == "assistant"
                prompt += f"\n{message['content']}<|endoftext|>\n"
    elif model_name == "starChat-alpha" :
        prompt = "<|system|>\n<|end|>\n"
        for message in messages :
            if message["role"] == "user" :
                prompt += f"<|user|>\n{message['content']}<|end|>\n<|assistant|>\n"
            else : # message["role"] == "assistant"
                prompt += f"\n{message['content']}<|end|>\n"
    else : # starCoder-gradio
        prompt = ""
        for message in messages :
            if message["role"] == "user" :
                prompt += f"Question: {message['content']}\n\nAnswer:"
            else : # message["role"] == "assistant"
                prompt += f" {message['content']}\n\n"
    return prompt
    
def generate(
    RETRY_FLAG,
    model_name,
    system_message,
    user_message,
    chatbot,
    history,
    temperature,
    top_k,
    top_p,
    max_new_tokens,
    repetition_penalty,
    do_save=True,
):
    client = Client(
        model2endpoint[model_name],
        headers={"Authorization": f"Bearer {API_TOKEN}"},
        timeout=60,
    )
    # Don't return meaningless message when the input is empty
    if not user_message:
        print("Empty input")

    if not RETRY_FLAG:
        history.append(user_message)
        seed = 42
    else:
        seed = randomize_seed_generator()

    past_messages = []
    for data in chatbot:
        user_data, model_data = data

        past_messages.extend(
            [{"role": "user", "content": user_data}, {"role": "assistant", "content": model_data.rstrip()}]
        )

    if len(past_messages) < 1:
        prompt = get_inference_prompt(messages=[{"role": "user", "content": user_message}], model_name=model_name)
    else:
        prompt = get_inference_prompt(messages=past_messages + [{"role": "user", "content": user_message}], model_name=model_name)

    generate_kwargs = {
        "temperature": temperature,
        "top_k": top_k,
        "top_p": top_p,
        "max_new_tokens": max_new_tokens,
    }

    temperature = float(temperature)
    if temperature < 1e-2:
        temperature = 1e-2
    top_p = float(top_p)

    generate_kwargs = dict(
        temperature=temperature,
        max_new_tokens=max_new_tokens,
        top_p=top_p,
        repetition_penalty=repetition_penalty,
        do_sample=True,
        truncate=4096,
        seed=seed,
        stop_sequences=["<|end|>", "Question:"],
    )

    try :
        stream = client.generate_stream(
            prompt,
            **generate_kwargs,
        )
    
        output = ""
        for idx, response in enumerate(stream):
            if response.token.special:
                continue
            output += response.token.text
            if idx == 0:
                history.append(" " + output)
            else:
                history[-1] = output
    
            chat = [
                (wrap_html_code(history[i].strip()), wrap_html_code(history[i + 1].strip()))
                for i in range(0, len(history) - 1, 2)
            ]
    
            # chat = [(history[i].strip(), history[i + 1].strip()) for i in range(0, len(history) - 1, 2)]
    
            yield chat, history, user_message, ""
    
        if HF_TOKEN and do_save:
            try:
                now = datetime.datetime.now()
                current_time = now.strftime("%Y-%m-%d %H:%M:%S")
                print(f"[{current_time}] Pushing prompt and completion to the Hub")
                save_inputs_and_outputs(now, prompt, output, generate_kwargs, model_name)
            except Exception as e:
                print(e)
    
        return chat, history, user_message, ""
    except UnknownError :
        error_message = "The model is currently loading. Please wait a few seconds and retry."
        return [(user_message, error_message)], history, user_message, ""

examples = [
    "Use the gradio library to create a calculator. It should take into account the 4 basic operations. A user should be able to enter 2 numbers, choose an operation and get the corresponding result.",
    "Write a gradio application to convert an input temperature in celcius to a temperature in fahrenheit",
    "Write a gradio application for a chatbot. The chatbot should use a language model loaded with Hugging face’s transformers , and a user should be able to enter a text request to get the corresponding answer.",
    "Create a basic gradio application.",
    "What is gradio?"
]

def clear_chat():
    return [], []

def delete_last_turn(chat, history):
    if chat and history:
        chat.pop(-1)
        history.pop(-1)
        history.pop(-1)
    return chat, history

def process_example(args):
    for [x, y] in generate(args):
        pass
    return [x, y]

# Regenerate response
def retry_last_answer(
    selected_model,
    system_message,
    user_message,
    chat,
    history,
    temperature,
    top_k,
    top_p,
    max_new_tokens,
    repetition_penalty,
    do_save,
):
    if chat and history:
        # Removing the previous conversation from chat
        chat.pop(-1)
        # Removing bot response from the history
        history.pop(-1)
        # Setting up a flag to capture a retry
        RETRY_FLAG = True
        # Getting last message from user
        user_message = history[-1]

    yield from generate(
        RETRY_FLAG,
        selected_model,
        system_message,
        user_message,
        chat,
        history,
        temperature,
        top_k,
        top_p,
        max_new_tokens,
        repetition_penalty,
        do_save,
    )

title = """<h1 align="center">Chat with Gradio 💫➕</h1>"""
custom_css = """
#banner-image {
    display: block;
    margin-left: auto;
    margin-right: auto;
}
#chat-message {
    font-size: 14px;
    min-height: 300px;
}
"""

with gr.Blocks(analytics_enabled=False, css=custom_css) as demo:
    #gr.HTML(title)

    with gr.Row():
        #with gr.Column():
            #gr.Image("gradio.png", elem_id="banner-image", show_label=False)
        
        #with gr.Column():
        #    gr.Markdown(
        #        """
        #    💻 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).
        #    📝 For more details, check out our [blog post](https://huggingface.co/blog/starchat-alpha).
        #    ⚠️ **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.
        #    ⚠️ **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).
        #    ⚠️ **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.
        #        """
        #    )
        with gr.Column():
            gr.Markdown("""<img src="https://huggingface.co/spaces/codeparrot/gradio-playground/resolve/main/chat_with_gradio.png" height="200">""")
    with gr.Row():
        selected_model = gr.Radio(choices=model_names, value=model_names[1], label="Select a model")

    with gr.Accordion(label="System Prompt", open=False, elem_id="parameters-accordion"):
        system_message = gr.Textbox(
            elem_id="system-message",
            placeholder="Below is a conversation between a human user and a helpful AI coding assistant.",
            show_label=False,
        )
    with gr.Row():
        with gr.Box():
            output = gr.Markdown()
            chatbot = gr.Chatbot(elem_id="chat-message", label="Chat")

    with gr.Row():
        with gr.Column(scale=3):
            user_message = gr.Textbox(placeholder="Enter your message here", show_label=False, elem_id="q-input")
            with gr.Row():
                send_button = gr.Button("Send", elem_id="send-btn", visible=True)

                regenerate_button = gr.Button("Regenerate", elem_id="retry-btn", visible=True)

                delete_turn_button = gr.Button("Delete last turn", elem_id="delete-btn", visible=True)

                clear_chat_button = gr.Button("Clear chat", elem_id="clear-btn", visible=True)

            with gr.Accordion(label="Parameters", open=False, elem_id="parameters-accordion"):
                temperature = gr.Slider(
                    label="Temperature",
                    value=0.2,
                    minimum=0.0,
                    maximum=1.0,
                    step=0.1,
                    interactive=True,
                    info="Higher values produce more diverse outputs",
                )
                top_k = gr.Slider(
                    label="Top-k",
                    value=50,
                    minimum=0.0,
                    maximum=100,
                    step=1,
                    interactive=True,
                    info="Sample from a shortlist of top-k tokens",
                )
                top_p = gr.Slider(
                    label="Top-p (nucleus sampling)",
                    value=0.95,
                    minimum=0.0,
                    maximum=1,
                    step=0.05,
                    interactive=True,
                    info="Higher values sample more low-probability tokens",
                )
                max_new_tokens = gr.Slider(
                    label="Max new tokens",
                    value=512,
                    minimum=0,
                    maximum=1024,
                    step=4,
                    interactive=True,
                    info="The maximum numbers of new tokens",
                )
                repetition_penalty = gr.Slider(
                    label="Repetition Penalty",
                    value=1.2,
                    minimum=0.0,
                    maximum=10,
                    step=0.1,
                    interactive=True,
                    info="The parameter for repetition penalty. 1.0 means no penalty.",
                )
            with gr.Row():
                do_save = gr.Checkbox(
                    value=True,
                    label="Store data",
                    info="You agree to the storage of your prompt and generated text for research and development purposes:",
                )
            # with gr.Group(elem_id="share-btn-container"):
            #     community_icon = gr.HTML(community_icon_html, visible=True)
            #     loading_icon = gr.HTML(loading_icon_html, visible=True)
            # share_button = gr.Button("Share to community", elem_id="share-btn", visible=True)
            with gr.Row():
                gr.Examples(
                    examples=examples,
                    inputs=[user_message],
                    cache_examples=False,
                    fn=process_example,
                    outputs=[output],
                )
            with gr.Row():
                gr.Markdown(
                    """Chat-with-Gradio is a 15.5 billion parameter language model based on [BigCode's StarCoderplus model](https://huggingface.co/bigcode/starcoderplus) that has been trained on a wide variety of data sources. It includes the source code and issues from [gradio's Github repository](https://github.com/gradio-app/gradio) and data from [Hugging Face's spaces](https://huggingface.co/spaces). Its training also involves instruction fine-tuning with a processed subset of [OpenAssistant's oasst1 dataset](https://huggingface.co/datasets/HuggingFaceH4/oasst1_en).
                
                Type in the box below and click the button to generate answers to your most pressing questions!
                ⚠️ **Intended Use**: this app and its [supporting model](https://huggingface.co/bigcode/starcoderplus) are provided as tools to provide assistance when using gradio ; not to serve as replacement for human expertise. For more details on the model's limitations in terms of factuality and biases, see the [model card.](https://huggingface.co/bigcode/starcoderplus#intended-uses--limitations)
                
                ⚠️ **Data Collection**: by default, we are collecting the prompts entered in this app to further improve and evaluate the model. 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:)""")

    history = gr.State([])
    RETRY_FLAG = gr.Checkbox(value=False, visible=False)

    # To clear out "message" input textbox and use this to regenerate message
    last_user_message = gr.State("")

    user_message.submit(
        generate,
        inputs=[
            RETRY_FLAG,
            selected_model,
            system_message,
            user_message,
            chatbot,
            history,
            temperature,
            top_k,
            top_p,
            max_new_tokens,
            repetition_penalty,
            do_save,
        ],
        outputs=[chatbot, history, last_user_message, user_message],
    )

    send_button.click(
        generate,
        inputs=[
            RETRY_FLAG,
            selected_model,
            system_message,
            user_message,
            chatbot,
            history,
            temperature,
            top_k,
            top_p,
            max_new_tokens,
            repetition_penalty,
            do_save,
        ],
        outputs=[chatbot, history, last_user_message, user_message],
    )

    regenerate_button.click(
        retry_last_answer,
        inputs=[
            selected_model,
            system_message,
            user_message,
            chatbot,
            history,
            temperature,
            top_k,
            top_p,
            max_new_tokens,
            repetition_penalty,
            do_save,
        ],
        outputs=[chatbot, history, last_user_message, user_message],
    )

    delete_turn_button.click(delete_last_turn, [chatbot, history], [chatbot, history])
    clear_chat_button.click(clear_chat, outputs=[chatbot, history])
    selected_model.change(clear_chat, outputs=[chatbot, history])
    # share_button.click(None, [], [], _js=share_js)

demo.queue(concurrency_count=16).launch(debug=True)