Kaaaaaaa commited on
Commit
1124979
1 Parent(s): 0e303b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -59
app.py CHANGED
@@ -1,63 +1,178 @@
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
  )
 
 
 
60
 
 
61
 
62
- if __name__ == "__main__":
63
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict
2
+ from typing import List
3
+ from typing import Tuple
4
+ from typing import Union
5
+ from pathlib import Path
6
  import gradio as gr
7
+ import torch
8
+ import argparse
9
+ from threading import Thread
10
+ from transformers import (
11
+ AutoModelForCausalLM,
12
+ AutoTokenizer,
13
+ TextIteratorStreamer,
14
+ GenerationConfig,
15
+ PreTrainedModel,
16
+ PreTrainedTokenizer,
17
+ PreTrainedTokenizerFast,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  )
19
+ import warnings
20
+ import spaces
21
+ import os
22
 
23
+ warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
24
 
25
+ MODEL_PATH = os.environ.get('MODEL_PATH', 'IndexTeam/Index-1.9B-Chat')
26
+ TOKENIZER_PATH = os.environ.get("TOKENIZER_PATH", MODEL_PATH)
27
+
28
+ tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH, trust_remote_code=True)
29
+ model = AutoModelForCausalLM.from_pretrained(MODEL_PATH,
30
+ torch_dtype=torch.bfloat16,
31
+ device_map="auto",
32
+ trust_remote_code=True)
33
+
34
+ def _resolve_path(path: Union[str, Path]) -> Path:
35
+ return Path(path).expanduser().resolve()
36
+
37
+ @spaces.GPU
38
+ def hf_gen(dialog: List, top_k, top_p, temperature, repetition_penalty, max_dec_len):
39
+ """generate model output with huggingface api
40
+ Args:
41
+ query (str): actual model input.
42
+ top_p (float): only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation.
43
+ temperature (float): Strictly positive float value used to modulate the logits distribution.
44
+ max_dec_len (int): The maximum numbers of tokens to generate.
45
+ Yields:
46
+ str: real-time generation results of hf model
47
+ """
48
+ inputs = tokenizer.apply_chat_template(dialog, tokenize=False, add_generation_prompt=False)
49
+ enc = tokenizer(inputs, return_tensors="pt").to("cuda")
50
+ streamer = TextIteratorStreamer(tokenizer, **tokenizer.init_kwargs)
51
+ generation_kwargs = dict(
52
+ enc,
53
+ do_sample=True,
54
+ top_k=int(top_k),
55
+ top_p=float(top_p),
56
+ temperature=float(temperature),
57
+ repetition_penalty=float(repetition_penalty),
58
+ max_new_tokens=int(max_dec_len),
59
+ pad_token_id=tokenizer.eos_token_id,
60
+ streamer=streamer,
61
+ )
62
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
63
+ thread.start()
64
+ answer = ""
65
+ for new_text in streamer:
66
+ answer += new_text
67
+ yield answer[len(inputs):]
68
+
69
+ @spaces.GPU
70
+ def generate(chat_history: List, query, top_k, top_p, temperature, repetition_penalty, max_dec_len, system_message):
71
+ """generate after hitting "submit" button
72
+ Args:
73
+ chat_history (List): [[q_1, a_1], [q_2, a_2], ..., [q_n, a_n]]. list that stores all QA records
74
+ query (str): query of current round
75
+ top_p (float): only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation.
76
+ temperature (float): strictly positive float value used to modulate the logits distribution.
77
+ max_dec_len (int): The maximum numbers of tokens to generate.
78
+ Yields:
79
+ List: [[q_1, a_1], [q_2, a_2], ..., [q_n, a_n], [q_n+1, a_n+1]]. chat_history + QA of current round.
80
+ """
81
+ assert query != "", "Input must not be empty!!!"
82
+ # apply chat template
83
+ model_input = []
84
+ if system_message:
85
+ model_input.append({
86
+ "role": "system",
87
+ "content": system_message
88
+ })
89
+ for q, a in chat_history:
90
+ model_input.append({"role": "user", "content": q})
91
+ model_input.append({"role": "assistant", "content": a})
92
+ model_input.append({"role": "user", "content": query})
93
+ # yield model generation
94
+ chat_history.append([query, ""])
95
+ for answer in hf_gen(model_input, top_k, top_p, temperature, repetition_penalty, max_dec_len):
96
+ # chat_history[-1][1] = answer.strip("</s>")
97
+ chat_history[-1][1] = answer.strip(tokenizer.eos_token)
98
+ yield gr.update(value=""), chat_history
99
+
100
+ @spaces.GPU
101
+ def regenerate(chat_history: List, top_k, top_p, temperature, repetition_penalty, max_dec_len, system_message):
102
+ """re-generate the answer of last round's query
103
+ Args:
104
+ chat_history (List): [[q_1, a_1], [q_2, a_2], ..., [q_n, a_n]]. list that stores all QA records
105
+ top_p (float): only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation.
106
+ temperature (float): strictly positive float value used to modulate the logits distribution.
107
+ max_dec_len (int): The maximum numbers of tokens to generate.
108
+ Yields:
109
+ List: [[q_1, a_1], [q_2, a_2], ..., [q_n, a_n]]. chat_history
110
+ """
111
+ assert len(chat_history) >= 1, "History is empty. Nothing to regenerate!!"
112
+ # apply chat template
113
+ model_input = []
114
+ if system_message:
115
+ model_input.append({
116
+ "role": "system",
117
+ "content": system_message
118
+ })
119
+ for q, a in chat_history[:-1]:
120
+ model_input.append({"role": "user", "content": q})
121
+ model_input.append({"role": "assistant", "content": a})
122
+ model_input.append({"role": "user", "content": chat_history[-1][0]})
123
+ # yield model generation
124
+ for answer in hf_gen(model_input, top_k, top_p, temperature, repetition_penalty, max_dec_len):
125
+ # chat_history[-1][1] = answer.strip("</s>")
126
+ chat_history[-1][1] = answer.strip(tokenizer.eos_token)
127
+ yield gr.update(value=""), chat_history
128
+
129
+
130
+ def clear_history():
131
+ """clear all chat history
132
+ Returns:
133
+ List: empty chat history
134
+ """
135
+ torch.cuda.empty_cache()
136
+ return []
137
+
138
+
139
+ def reverse_last_round(chat_history):
140
+ """reverse last round QA and keep the chat history before
141
+ Args:
142
+ chat_history (List): [[q_1, a_1], [q_2, a_2], ..., [q_n, a_n]]. list that stores all QA records
143
+ Returns:
144
+ List: [[q_1, a_1], [q_2, a_2], ..., [q_n-1, a_n-1]]. chat_history without last round.
145
+ """
146
+ assert len(chat_history) >= 1, "History is empty. Nothing to reverse!!"
147
+ return chat_history[:-1]
148
+
149
+ # launch gradio demo
150
+ with gr.Blocks(theme="soft") as demo:
151
+ gr.Markdown("""# Index-1.9B Gradio Demo""")
152
+
153
+ with gr.Row():
154
+ with gr.Column(scale=1):
155
+ top_k = gr.Slider(1, 10, value=5, step=1, label="top_k")
156
+ top_p = gr.Slider(0, 1, value=0.8, step=0.1, label="top_p")
157
+ temperature = gr.Slider(0.1, 2.0, value=0.3, step=0.1, label="temperature")
158
+ repetition_penalty = gr.Slider(0.1, 2.0, value=1.1, step=0.1, label="repetition_penalty")
159
+ max_dec_len = gr.Slider(1, 4096, value=1024, step=1, label="max_dec_len")
160
+ with gr.Row():
161
+ system_message = gr.Textbox(label="System Message", placeholder="Input your system message", value="你是由哔哩哔哩自主研发的大语言模型,名为“Index”。你能够根据用户传入的信息,帮助用户完成指定的任务,并生成恰当的、符合要求的回复。")
162
+ with gr.Column(scale=10):
163
+ chatbot = gr.Chatbot(bubble_full_width=False, height=500, label='Index-1.9B')
164
+ user_input = gr.Textbox(label="User", placeholder="Input your query here!", lines=8)
165
+ with gr.Row():
166
+ submit = gr.Button("🚀 Submit")
167
+ clear = gr.Button("🧹 Clear")
168
+ regen = gr.Button("🔄 Regenerate")
169
+ reverse = gr.Button("⬅️ Reverse")
170
+
171
+ submit.click(generate, inputs=[chatbot, user_input, top_k, top_p, temperature, repetition_penalty, max_dec_len, system_message],
172
+ outputs=[user_input, chatbot])
173
+ regen.click(regenerate, inputs=[chatbot, top_k, top_p, temperature, repetition_penalty, max_dec_len, system_message],
174
+ outputs=[user_input, chatbot])
175
+ clear.click(clear_history, inputs=[], outputs=[chatbot])
176
+ reverse.click(reverse_last_round, inputs=[chatbot], outputs=[chatbot])
177
+
178
+ demo.queue().launch()