ratyim commited on
Commit
6915385
·
verified ·
1 Parent(s): 3b60621

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -258
app.py CHANGED
@@ -1,265 +1,114 @@
1
- #!/usr/bin/env python
2
- # encoding: utf-8
3
- import timm
4
- import spaces
5
- import gradio as gr
6
- from PIL import Image
7
- import traceback
8
- import re
9
  import torch
10
- import argparse
11
- from transformers import AutoModel, AutoTokenizer
12
-
13
- # README, How to run demo on different devices
14
- # For Nvidia GPUs support BF16 (like A100, H100, RTX3090)
15
- # python web_demo.py --device cuda --dtype bf16
16
-
17
- # For Nvidia GPUs do NOT support BF16 (like V100, T4, RTX2080)
18
- # python web_demo.py --device cuda --dtype fp16
19
-
20
- # For Mac with MPS (Apple silicon or AMD GPUs).
21
- # PYTORCH_ENABLE_MPS_FALLBACK=1 python web_demo.py --device mps --dtype fp16
22
-
23
- # Argparser
24
- parser = argparse.ArgumentParser(description='demo')
25
- parser.add_argument('--device', type=str, default='cuda', help='cuda or mps')
26
- parser.add_argument('--dtype', type=str, default='bf16', help='bf16 or fp16')
27
- args = parser.parse_args()
28
- device = args.device
29
- assert device in ['cuda', 'mps']
30
- if args.dtype == 'bf16':
31
- dtype = torch.bfloat16
32
- else:
33
- dtype = torch.float16
34
-
35
- # Load model
36
- model_path = 'openbmb/MiniCPM-V-2'
37
- model = AutoModel.from_pretrained(model_path, trust_remote_code=True).to(dtype=torch.bfloat16)
38
- tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
39
-
40
- model = model.to(device=device, dtype=dtype)
41
- model.eval()
42
 
43
 
 
 
 
 
 
44
 
45
- ERROR_MSG = "Error, please retry"
46
- model_name = 'MiniCPM-V 2.0'
47
 
48
- form_radio = {
49
- 'choices': ['Beam Search', 'Sampling'],
50
- #'value': 'Beam Search',
51
- 'value': 'Sampling',
52
- 'interactive': True,
53
- 'label': 'Decode Type'
54
- }
55
- # Beam Form
56
- num_beams_slider = {
57
- 'minimum': 0,
58
- 'maximum': 5,
59
- 'value': 3,
60
- 'step': 1,
61
- 'interactive': True,
62
- 'label': 'Num Beams'
63
- }
64
- repetition_penalty_slider = {
65
- 'minimum': 0,
66
- 'maximum': 3,
67
- 'value': 1.2,
68
- 'step': 0.01,
69
- 'interactive': True,
70
- 'label': 'Repetition Penalty'
71
- }
72
- repetition_penalty_slider2 = {
73
- 'minimum': 0,
74
- 'maximum': 3,
75
- 'value': 1.05,
76
- 'step': 0.01,
77
- 'interactive': True,
78
- 'label': 'Repetition Penalty'
79
- }
80
- max_new_tokens_slider = {
81
- 'minimum': 1,
82
- 'maximum': 4096,
83
- 'value': 1024,
84
- 'step': 1,
85
- 'interactive': True,
86
- 'label': 'Max New Tokens'
87
- }
88
 
89
- top_p_slider = {
90
- 'minimum': 0,
91
- 'maximum': 1,
92
- 'value': 0.8,
93
- 'step': 0.05,
94
- 'interactive': True,
95
- 'label': 'Top P'
96
- }
97
- top_k_slider = {
98
- 'minimum': 0,
99
- 'maximum': 200,
100
- 'value': 100,
101
- 'step': 1,
102
- 'interactive': True,
103
- 'label': 'Top K'
104
  }
105
- temperature_slider = {
106
- 'minimum': 0,
107
- 'maximum': 2,
108
- 'value': 0.7,
109
- 'step': 0.05,
110
- 'interactive': True,
111
- 'label': 'Temperature'
112
- }
113
-
114
-
115
- def create_component(params, comp='Slider'):
116
- if comp == 'Slider':
117
- return gr.Slider(
118
- minimum=params['minimum'],
119
- maximum=params['maximum'],
120
- value=params['value'],
121
- step=params['step'],
122
- interactive=params['interactive'],
123
- label=params['label']
124
- )
125
- elif comp == 'Radio':
126
- return gr.Radio(
127
- choices=params['choices'],
128
- value=params['value'],
129
- interactive=params['interactive'],
130
- label=params['label']
131
- )
132
- elif comp == 'Button':
133
- return gr.Button(
134
- value=params['value'],
135
- interactive=True
136
- )
137
-
138
- @spaces.GPU(duration=120)
139
- def chat(img, msgs, ctx, params=None, vision_hidden_states=None):
140
- default_params = {"num_beams":3, "repetition_penalty": 1.2, "max_new_tokens": 1024}
141
- if params is None:
142
- params = default_params
143
- if img is None:
144
- return -1, "Error, invalid image, please upload a new image", None, None
145
- try:
146
- image = img.convert('RGB')
147
- answer, context, _ = model.chat(
148
- image=image,
149
- msgs=msgs,
150
- context=None,
151
- tokenizer=tokenizer,
152
- **params
153
- )
154
- res = re.sub(r'(<box>.*</box>)', '', answer)
155
- res = res.replace('<ref>', '')
156
- res = res.replace('</ref>', '')
157
- res = res.replace('<box>', '')
158
- answer = res.replace('</box>', '')
159
- return -1, answer, None, None
160
- except Exception as err:
161
- print(err)
162
- traceback.print_exc()
163
- return -1, ERROR_MSG, None, None
164
-
165
-
166
- def upload_img(image, _chatbot, _app_session):
167
- image = Image.fromarray(image)
168
-
169
- _app_session['sts']=None
170
- _app_session['ctx']=[]
171
- _app_session['img']=image
172
- _chatbot.append(('', 'Image uploaded successfully, you can talk to me now'))
173
- return _chatbot, _app_session
174
-
175
-
176
- def respond(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature):
177
- if _app_cfg.get('ctx', None) is None:
178
- _chat_bot.append((_question, 'Please upload an image to start'))
179
- return '', _chat_bot, _app_cfg
180
-
181
- _context = _app_cfg['ctx'].copy()
182
- if _context:
183
- _context.append({"role": "user", "content": _question})
184
- else:
185
- _context = [{"role": "user", "content": _question}]
186
- print('<User>:', _question)
187
-
188
- if params_form == 'Beam Search':
189
- params = {
190
- 'sampling': False,
191
- 'num_beams': num_beams,
192
- 'repetition_penalty': repetition_penalty,
193
- "max_new_tokens": 896
194
- }
195
- else:
196
- params = {
197
- 'sampling': True,
198
- 'top_p': top_p,
199
- 'top_k': top_k,
200
- 'temperature': temperature,
201
- 'repetition_penalty': repetition_penalty_2,
202
- "max_new_tokens": 896
203
- }
204
- code, _answer, _, sts = chat(_app_cfg['img'], _context, None, params)
205
- print('<Assistant>:', _answer)
206
-
207
- _context.append({"role": "assistant", "content": _answer})
208
- _chat_bot.append((_question, _answer))
209
- if code == 0:
210
- _app_cfg['ctx']=_context
211
- _app_cfg['sts']=sts
212
- return '', _chat_bot, _app_cfg
213
-
214
-
215
- def regenerate_button_clicked(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature):
216
- if len(_chat_bot) <= 1:
217
- _chat_bot.append(('Regenerate', 'No question for regeneration.'))
218
- return '', _chat_bot, _app_cfg
219
- elif _chat_bot[-1][0] == 'Regenerate':
220
- return '', _chat_bot, _app_cfg
221
- else:
222
- _question = _chat_bot[-1][0]
223
- _chat_bot = _chat_bot[:-1]
224
- _app_cfg['ctx'] = _app_cfg['ctx'][:-2]
225
- return respond(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature)
226
-
227
-
228
-
229
- with gr.Blocks() as demo:
230
- with gr.Row():
231
- with gr.Column(scale=1, min_width=300):
232
- params_form = create_component(form_radio, comp='Radio')
233
- with gr.Accordion("Beam Search") as beams_according:
234
- num_beams = create_component(num_beams_slider)
235
- repetition_penalty = create_component(repetition_penalty_slider)
236
- with gr.Accordion("Sampling") as sampling_according:
237
- top_p = create_component(top_p_slider)
238
- top_k = create_component(top_k_slider)
239
- temperature = create_component(temperature_slider)
240
- repetition_penalty_2 = create_component(repetition_penalty_slider2)
241
- regenerate = create_component({'value': 'Regenerate'}, comp='Button')
242
- with gr.Column(scale=3, min_width=500):
243
- app_session = gr.State({'sts':None,'ctx':None,'img':None})
244
- bt_pic = gr.Image(label="Upload an image to start")
245
- chat_bot = gr.Chatbot(label=f"Chat with {model_name}")
246
- txt_message = gr.Textbox(label="Input text")
247
-
248
- regenerate.click(
249
- regenerate_button_clicked,
250
- [txt_message, chat_bot, app_session, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature],
251
- [txt_message, chat_bot, app_session]
252
- )
253
- txt_message.submit(
254
- respond,
255
- [txt_message, chat_bot, app_session, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature],
256
- [txt_message, chat_bot, app_session]
257
- )
258
- bt_pic.upload(lambda: None, None, chat_bot, queue=False).then(upload_img, inputs=[bt_pic,chat_bot,app_session], outputs=[chat_bot,app_session])
259
-
260
- # launch
261
- #demo.launch(share=False, debug=True, show_api=False, server_port=8080, server_name="0.0.0.0")
262
- demo.launch()
263
-
264
-
265
-
 
 
 
 
 
 
 
 
 
1
  import torch
2
+ from PIL import Image
3
+ import gradio as gr
4
+ import spaces
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
+ import os
7
+ from threading import Thread
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
 
10
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
11
+ MODEL_ID = "THUDM/glm-4-9b-chat"
12
+ MODEL_ID2 = "THUDM/glm-4-9b-chat-1m"
13
+ MODELS = os.environ.get("MODELS")
14
+ MODEL_NAME = MODELS.split("/")[-1]
15
 
16
+ TITLE = "<h1><center>GLM-4-9B</center></h1>"
 
17
 
18
+ DESCRIPTION = f'<h3><center>MODEL: <a href="https://hf.co/{MODELS}">{MODEL_NAME}</a></center></h3>'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ CSS = """
21
+ .duplicate-button {
22
+ margin: auto !important;
23
+ color: white !important;
24
+ background: black !important;
25
+ border-radius: 100vh !important;
 
 
 
 
 
 
 
 
 
26
  }
27
+ """
28
+
29
+ model = AutoModelForCausalLM.from_pretrained(
30
+ MODELS,
31
+ torch_dtype=torch.bfloat16,
32
+ low_cpu_mem_usage=True,
33
+ trust_remote_code=True,
34
+ ).to(0).eval()
35
+
36
+ tokenizer = AutoTokenizer.from_pretrained(MODELS,trust_remote_code=True)
37
+
38
+
39
+ @spaces.GPU
40
+ def stream_chat(message: str, history: list, temperature: float, max_length: int):
41
+ print(f'message is - {message}')
42
+ print(f'history is - {history}')
43
+ conversation = []
44
+ for prompt, answer in history:
45
+ conversation.extend([{"role": "user", "content": prompt}, {"role": "assistant", "content": answer}])
46
+ conversation.append({"role": "user", "content": message})
47
+
48
+ print(f"Conversation is -\n{conversation}")
49
+
50
+ input_ids = tokenizer.apply_chat_template(conversation, tokenize=True, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)
51
+ streamer = TextIteratorStreamer(tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
52
+
53
+ generate_kwargs = dict(
54
+ max_length=max_length,
55
+ streamer=streamer,
56
+ do_sample=True,
57
+ top_k=1,
58
+ temperature=temperature,
59
+ repetition_penalty=1.2,
60
+ )
61
+ gen_kwargs = {**input_ids, **generate_kwargs}
62
+
63
+ with torch.no_grad():
64
+ thread = Thread(target=model.generate, kwargs=gen_kwargs)
65
+ thread.start()
66
+ buffer = ""
67
+ for new_text in streamer:
68
+ buffer += new_text
69
+ yield buffer
70
+
71
+
72
+
73
+
74
+ chatbot = gr.Chatbot(height=450)
75
+
76
+ with gr.Blocks(css=CSS) as demo:
77
+ gr.HTML(TITLE)
78
+ gr.HTML(DESCRIPTION)
79
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_classes="duplicate-button")
80
+ gr.ChatInterface(
81
+ fn=stream_chat,
82
+ chatbot=chatbot,
83
+ fill_height=True,
84
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
85
+ additional_inputs=[
86
+ gr.Slider(
87
+ minimum=0,
88
+ maximum=1,
89
+ step=0.1,
90
+ value=0.8,
91
+ label="Temperature",
92
+ render=False,
93
+ ),
94
+ gr.Slider(
95
+ minimum=128,
96
+ maximum=8192,
97
+ step=1,
98
+ value=1024,
99
+ label="Max Length",
100
+ render=False,
101
+ ),
102
+ ],
103
+ examples=[
104
+ ["Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option."],
105
+ ["What are 5 creative things I could do with my kids' art? I don't want to throw them away, but it's also so much clutter."],
106
+ ["Tell me a random fun fact about the Roman Empire."],
107
+ ["Show me a code snippet of a website's sticky header in CSS and JavaScript."],
108
+ ],
109
+ cache_examples=False,
110
+ )
111
+
112
+
113
+ if __name__ == "__main__":
114
+ demo.launch()