torVik commited on
Commit
4431f86
·
verified ·
1 Parent(s): 1c90ac6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +176 -43
app.py CHANGED
@@ -1,67 +1,200 @@
 
 
 
 
 
 
1
  import gradio as gr
2
  import spaces
3
- from huggingface_hub import InferenceClient
4
- import gradio as gr
5
 
 
6
 
 
 
7
 
8
- """
9
- 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
10
- """
11
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
12
 
13
- @spaces.GPU()
14
- def respond(
15
- message,
16
- history: list[tuple[str, str]],
17
- system_message,
18
- max_tokens,
19
- temperature,
20
- top_p,
21
- ):
22
- messages = [{"role": "system", "content": system_message}]
23
 
24
- for val in history:
25
- if val[0]:
26
- messages.append({"role": "user", "content": val[0]})
27
- if val[1]:
28
- messages.append({"role": "assistant", "content": val[1]})
29
 
30
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- response = ""
 
 
 
 
33
 
34
- for message in client.chat_completion(
35
- messages,
36
- max_tokens=max_tokens,
37
- stream=True,
38
- temperature=temperature,
 
39
  top_p=top_p,
40
- ):
41
- token = message.choices[0].delta.content
 
 
 
 
 
42
 
43
- response += token
44
- yield response
 
 
45
 
46
- """
47
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
48
- """
49
- demo = gr.ChatInterface(
50
- respond,
51
  additional_inputs=[
52
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
53
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
54
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
55
  gr.Slider(
 
 
 
 
 
 
 
 
56
  minimum=0.1,
 
 
 
 
 
 
 
57
  maximum=1.0,
58
- value=0.95,
59
  step=0.05,
60
- label="Top-p (nucleus sampling)",
 
 
 
 
 
 
 
61
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  ],
63
  )
64
 
 
 
 
 
 
 
 
 
65
 
66
  if __name__ == "__main__":
67
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ from threading import Thread
5
+ from typing import Iterator
6
+
7
  import gradio as gr
8
  import spaces
9
+ import torch
10
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
11
 
12
+ DESCRIPTION = "# Mistral-7B v0.2"
13
 
14
+ if not torch.cuda.is_available():
15
+ DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"
16
 
17
+ MAX_MAX_NEW_TOKENS = 2048
18
+ DEFAULT_MAX_NEW_TOKENS = 1024
19
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
 
20
 
21
+ if torch.cuda.is_available():
22
+ model_id = "mistralai/Mistral-7B-Instruct-v0.2"
23
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
24
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
 
 
 
 
 
 
25
 
 
 
 
 
 
26
 
27
+ @spaces.GPU
28
+ def generate(
29
+ message: str,
30
+ chat_history: list[tuple[str, str]],
31
+ max_new_tokens: int = 1024,
32
+ temperature: float = 0.6,
33
+ top_p: float = 0.9,
34
+ top_k: int = 50,
35
+ repetition_penalty: float = 1.2,
36
+ ) -> Iterator[str]:
37
+ conversation = []
38
+ for user, assistant in chat_history:
39
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
40
+ conversation.append({"role": "user", "content": message})
41
 
42
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
43
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
44
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
45
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
46
+ input_ids = input_ids.to(model.device)
47
 
48
+ streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
49
+ generate_kwargs = dict(
50
+ {"input_ids": input_ids},
51
+ streamer=streamer,
52
+ max_new_tokens=max_new_tokens,
53
+ do_sample=True,
54
  top_p=top_p,
55
+ top_k=top_k,
56
+ temperature=temperature,
57
+ num_beams=1,
58
+ repetition_penalty=repetition_penalty,
59
+ )
60
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
61
+ t.start()
62
 
63
+ outputs = []
64
+ for text in streamer:
65
+ outputs.append(text)
66
+ yield "".join(outputs)
67
 
68
+
69
+ chat_interface = gr.ChatInterface(
70
+ fn=generate,
 
 
71
  additional_inputs=[
 
 
 
72
  gr.Slider(
73
+ label="Max new tokens",
74
+ minimum=1,
75
+ maximum=MAX_MAX_NEW_TOKENS,
76
+ step=1,
77
+ value=DEFAULT_MAX_NEW_TOKENS,
78
+ ),
79
+ gr.Slider(
80
+ label="Temperature",
81
  minimum=0.1,
82
+ maximum=4.0,
83
+ step=0.1,
84
+ value=0.6,
85
+ ),
86
+ gr.Slider(
87
+ label="Top-p (nucleus sampling)",
88
+ minimum=0.05,
89
  maximum=1.0,
 
90
  step=0.05,
91
+ value=0.9,
92
+ ),
93
+ gr.Slider(
94
+ label="Top-k",
95
+ minimum=1,
96
+ maximum=1000,
97
+ step=1,
98
+ value=50,
99
  ),
100
+ gr.Slider(
101
+ label="Repetition penalty",
102
+ minimum=1.0,
103
+ maximum=2.0,
104
+ step=0.05,
105
+ value=1.2,
106
+ ),
107
+ ],
108
+ stop_btn=None,
109
+ examples=[
110
+ ["Hello there! How are you doing?"],
111
+ ["Can you explain briefly to me what is the Python programming language?"],
112
+ ["Explain the plot of Cinderella in a sentence."],
113
+ ["How many hours does it take a man to eat a Helicopter?"],
114
+ ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
115
  ],
116
  )
117
 
118
+ with gr.Blocks(css="style.css") as demo:
119
+ gr.Markdown(DESCRIPTION)
120
+ gr.DuplicateButton(
121
+ value="Duplicate Space for private use",
122
+ elem_id="duplicate-button",
123
+ visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
124
+ )
125
+ chat_interface.render()
126
 
127
  if __name__ == "__main__":
128
+ demo.queue(max_size=20).launch()
129
+
130
+
131
+
132
+
133
+
134
+ # import gradio as gr
135
+ # import spaces
136
+ # from huggingface_hub import InferenceClient
137
+ # import gradio as gr
138
+
139
+
140
+
141
+ # """
142
+ # 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
143
+ # """
144
+ # client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
145
+
146
+ # @spaces.GPU()
147
+ # def respond(
148
+ # message,
149
+ # history: list[tuple[str, str]],
150
+ # system_message,
151
+ # max_tokens,
152
+ # temperature,
153
+ # top_p,
154
+ # ):
155
+ # messages = [{"role": "system", "content": system_message}]
156
+
157
+ # for val in history:
158
+ # if val[0]:
159
+ # messages.append({"role": "user", "content": val[0]})
160
+ # if val[1]:
161
+ # messages.append({"role": "assistant", "content": val[1]})
162
+
163
+ # messages.append({"role": "user", "content": message})
164
+
165
+ # response = ""
166
+
167
+ # for message in client.chat_completion(
168
+ # messages,
169
+ # max_tokens=max_tokens,
170
+ # stream=True,
171
+ # temperature=temperature,
172
+ # top_p=top_p,
173
+ # ):
174
+ # token = message.choices[0].delta.content
175
+
176
+ # response += token
177
+ # yield response
178
+
179
+ # """
180
+ # For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
181
+ # """
182
+ # demo = gr.ChatInterface(
183
+ # respond,
184
+ # additional_inputs=[
185
+ # gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
186
+ # gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
187
+ # gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
188
+ # gr.Slider(
189
+ # minimum=0.1,
190
+ # maximum=1.0,
191
+ # value=0.95,
192
+ # step=0.05,
193
+ # label="Top-p (nucleus sampling)",
194
+ # ),
195
+ # ],
196
+ # )
197
+
198
+
199
+ # if __name__ == "__main__":
200
+ # demo.launch()