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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# encoding: utf-8
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import traceback
|
| 6 |
+
import re
|
| 7 |
+
import torch
|
| 8 |
+
import argparse
|
| 9 |
+
from transformers import AutoModel, AutoTokenizer
|
| 10 |
+
|
| 11 |
+
# README, How to run demo on different devices
|
| 12 |
+
|
| 13 |
+
# For Nvidia GPUs.
|
| 14 |
+
# python web_demo_2.5.py --device cuda
|
| 15 |
+
|
| 16 |
+
# For Mac with MPS (Apple silicon or AMD GPUs).
|
| 17 |
+
# PYTORCH_ENABLE_MPS_FALLBACK=1 python web_demo_2.5.py --device mps
|
| 18 |
+
|
| 19 |
+
# Argparser
|
| 20 |
+
parser = argparse.ArgumentParser(description='demo')
|
| 21 |
+
parser.add_argument('--device', type=str, default='cuda', help='cuda or mps')
|
| 22 |
+
args = parser.parse_args()
|
| 23 |
+
device = args.device
|
| 24 |
+
assert device in ['cuda', 'mps']
|
| 25 |
+
|
| 26 |
+
# Load model
|
| 27 |
+
model_path = 'openbmb/MiniCPM-Llama3-V-2_5'
|
| 28 |
+
if 'int4' in model_path:
|
| 29 |
+
if device == 'mps':
|
| 30 |
+
print('Error: running int4 model with bitsandbytes on Mac is not supported right now.')
|
| 31 |
+
exit()
|
| 32 |
+
model = AutoModel.from_pretrained(model_path, trust_remote_code=True)
|
| 33 |
+
else:
|
| 34 |
+
model = AutoModel.from_pretrained(model_path, trust_remote_code=True, torch_dtype=torch.float16, device_map=device)
|
| 35 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
| 36 |
+
model.eval()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
ERROR_MSG = "Error, please retry"
|
| 41 |
+
model_name = 'MiniCPM-V 2.5'
|
| 42 |
+
|
| 43 |
+
form_radio = {
|
| 44 |
+
'choices': ['Beam Search', 'Sampling'],
|
| 45 |
+
#'value': 'Beam Search',
|
| 46 |
+
'value': 'Sampling',
|
| 47 |
+
'interactive': True,
|
| 48 |
+
'label': 'Decode Type'
|
| 49 |
+
}
|
| 50 |
+
# Beam Form
|
| 51 |
+
num_beams_slider = {
|
| 52 |
+
'minimum': 0,
|
| 53 |
+
'maximum': 5,
|
| 54 |
+
'value': 3,
|
| 55 |
+
'step': 1,
|
| 56 |
+
'interactive': True,
|
| 57 |
+
'label': 'Num Beams'
|
| 58 |
+
}
|
| 59 |
+
repetition_penalty_slider = {
|
| 60 |
+
'minimum': 0,
|
| 61 |
+
'maximum': 3,
|
| 62 |
+
'value': 1.2,
|
| 63 |
+
'step': 0.01,
|
| 64 |
+
'interactive': True,
|
| 65 |
+
'label': 'Repetition Penalty'
|
| 66 |
+
}
|
| 67 |
+
repetition_penalty_slider2 = {
|
| 68 |
+
'minimum': 0,
|
| 69 |
+
'maximum': 3,
|
| 70 |
+
'value': 1.05,
|
| 71 |
+
'step': 0.01,
|
| 72 |
+
'interactive': True,
|
| 73 |
+
'label': 'Repetition Penalty'
|
| 74 |
+
}
|
| 75 |
+
max_new_tokens_slider = {
|
| 76 |
+
'minimum': 1,
|
| 77 |
+
'maximum': 4096,
|
| 78 |
+
'value': 1024,
|
| 79 |
+
'step': 1,
|
| 80 |
+
'interactive': True,
|
| 81 |
+
'label': 'Max New Tokens'
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
top_p_slider = {
|
| 85 |
+
'minimum': 0,
|
| 86 |
+
'maximum': 1,
|
| 87 |
+
'value': 0.8,
|
| 88 |
+
'step': 0.05,
|
| 89 |
+
'interactive': True,
|
| 90 |
+
'label': 'Top P'
|
| 91 |
+
}
|
| 92 |
+
top_k_slider = {
|
| 93 |
+
'minimum': 0,
|
| 94 |
+
'maximum': 200,
|
| 95 |
+
'value': 100,
|
| 96 |
+
'step': 1,
|
| 97 |
+
'interactive': True,
|
| 98 |
+
'label': 'Top K'
|
| 99 |
+
}
|
| 100 |
+
temperature_slider = {
|
| 101 |
+
'minimum': 0,
|
| 102 |
+
'maximum': 2,
|
| 103 |
+
'value': 0.7,
|
| 104 |
+
'step': 0.05,
|
| 105 |
+
'interactive': True,
|
| 106 |
+
'label': 'Temperature'
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def create_component(params, comp='Slider'):
|
| 111 |
+
if comp == 'Slider':
|
| 112 |
+
return gr.Slider(
|
| 113 |
+
minimum=params['minimum'],
|
| 114 |
+
maximum=params['maximum'],
|
| 115 |
+
value=params['value'],
|
| 116 |
+
step=params['step'],
|
| 117 |
+
interactive=params['interactive'],
|
| 118 |
+
label=params['label']
|
| 119 |
+
)
|
| 120 |
+
elif comp == 'Radio':
|
| 121 |
+
return gr.Radio(
|
| 122 |
+
choices=params['choices'],
|
| 123 |
+
value=params['value'],
|
| 124 |
+
interactive=params['interactive'],
|
| 125 |
+
label=params['label']
|
| 126 |
+
)
|
| 127 |
+
elif comp == 'Button':
|
| 128 |
+
return gr.Button(
|
| 129 |
+
value=params['value'],
|
| 130 |
+
interactive=True
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def chat(img, msgs, ctx, params=None, vision_hidden_states=None):
|
| 135 |
+
default_params = {"num_beams":3, "repetition_penalty": 1.2, "max_new_tokens": 1024}
|
| 136 |
+
if params is None:
|
| 137 |
+
params = default_params
|
| 138 |
+
if img is None:
|
| 139 |
+
return -1, "Error, invalid image, please upload a new image", None, None
|
| 140 |
+
try:
|
| 141 |
+
image = img.convert('RGB')
|
| 142 |
+
answer = model.chat(
|
| 143 |
+
image=image,
|
| 144 |
+
msgs=msgs,
|
| 145 |
+
tokenizer=tokenizer,
|
| 146 |
+
**params
|
| 147 |
+
)
|
| 148 |
+
res = re.sub(r'(<box>.*</box>)', '', answer)
|
| 149 |
+
res = res.replace('<ref>', '')
|
| 150 |
+
res = res.replace('</ref>', '')
|
| 151 |
+
res = res.replace('<box>', '')
|
| 152 |
+
answer = res.replace('</box>', '')
|
| 153 |
+
return 0, answer, None, None
|
| 154 |
+
except Exception as err:
|
| 155 |
+
print(err)
|
| 156 |
+
traceback.print_exc()
|
| 157 |
+
return -1, ERROR_MSG, None, None
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def upload_img(image, _chatbot, _app_session):
|
| 161 |
+
image = Image.fromarray(image)
|
| 162 |
+
|
| 163 |
+
_app_session['sts']=None
|
| 164 |
+
_app_session['ctx']=[]
|
| 165 |
+
_app_session['img']=image
|
| 166 |
+
_chatbot.append(('', 'Image uploaded successfully, you can talk to me now'))
|
| 167 |
+
return _chatbot, _app_session
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def respond(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature):
|
| 171 |
+
if _app_cfg.get('ctx', None) is None:
|
| 172 |
+
_chat_bot.append((_question, 'Please upload an image to start'))
|
| 173 |
+
return '', _chat_bot, _app_cfg
|
| 174 |
+
|
| 175 |
+
_context = _app_cfg['ctx'].copy()
|
| 176 |
+
if _context:
|
| 177 |
+
_context.append({"role": "user", "content": _question})
|
| 178 |
+
else:
|
| 179 |
+
_context = [{"role": "user", "content": _question}]
|
| 180 |
+
print('<User>:', _question)
|
| 181 |
+
|
| 182 |
+
if params_form == 'Beam Search':
|
| 183 |
+
params = {
|
| 184 |
+
'sampling': False,
|
| 185 |
+
'num_beams': num_beams,
|
| 186 |
+
'repetition_penalty': repetition_penalty,
|
| 187 |
+
"max_new_tokens": 896
|
| 188 |
+
}
|
| 189 |
+
else:
|
| 190 |
+
params = {
|
| 191 |
+
'sampling': True,
|
| 192 |
+
'top_p': top_p,
|
| 193 |
+
'top_k': top_k,
|
| 194 |
+
'temperature': temperature,
|
| 195 |
+
'repetition_penalty': repetition_penalty_2,
|
| 196 |
+
"max_new_tokens": 896
|
| 197 |
+
}
|
| 198 |
+
code, _answer, _, sts = chat(_app_cfg['img'], _context, None, params)
|
| 199 |
+
print('<Assistant>:', _answer)
|
| 200 |
+
|
| 201 |
+
_context.append({"role": "assistant", "content": _answer})
|
| 202 |
+
_chat_bot.append((_question, _answer))
|
| 203 |
+
if code == 0:
|
| 204 |
+
_app_cfg['ctx']=_context
|
| 205 |
+
_app_cfg['sts']=sts
|
| 206 |
+
return '', _chat_bot, _app_cfg
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def regenerate_button_clicked(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature):
|
| 210 |
+
if len(_chat_bot) <= 1:
|
| 211 |
+
_chat_bot.append(('Regenerate', 'No question for regeneration.'))
|
| 212 |
+
return '', _chat_bot, _app_cfg
|
| 213 |
+
elif _chat_bot[-1][0] == 'Regenerate':
|
| 214 |
+
return '', _chat_bot, _app_cfg
|
| 215 |
+
else:
|
| 216 |
+
_question = _chat_bot[-1][0]
|
| 217 |
+
_chat_bot = _chat_bot[:-1]
|
| 218 |
+
_app_cfg['ctx'] = _app_cfg['ctx'][:-2]
|
| 219 |
+
return respond(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
with gr.Blocks() as demo:
|
| 224 |
+
with gr.Row():
|
| 225 |
+
with gr.Column(scale=1, min_width=300):
|
| 226 |
+
params_form = create_component(form_radio, comp='Radio')
|
| 227 |
+
with gr.Accordion("Beam Search") as beams_according:
|
| 228 |
+
num_beams = create_component(num_beams_slider)
|
| 229 |
+
repetition_penalty = create_component(repetition_penalty_slider)
|
| 230 |
+
with gr.Accordion("Sampling") as sampling_according:
|
| 231 |
+
top_p = create_component(top_p_slider)
|
| 232 |
+
top_k = create_component(top_k_slider)
|
| 233 |
+
temperature = create_component(temperature_slider)
|
| 234 |
+
repetition_penalty_2 = create_component(repetition_penalty_slider2)
|
| 235 |
+
regenerate = create_component({'value': 'Regenerate'}, comp='Button')
|
| 236 |
+
with gr.Column(scale=3, min_width=500):
|
| 237 |
+
app_session = gr.State({'sts':None,'ctx':None,'img':None})
|
| 238 |
+
bt_pic = gr.Image(label="Upload an image to start")
|
| 239 |
+
chat_bot = gr.Chatbot(label=f"Chat with {model_name}")
|
| 240 |
+
txt_message = gr.Textbox(label="Input text")
|
| 241 |
+
|
| 242 |
+
regenerate.click(
|
| 243 |
+
regenerate_button_clicked,
|
| 244 |
+
[txt_message, chat_bot, app_session, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature],
|
| 245 |
+
[txt_message, chat_bot, app_session]
|
| 246 |
+
)
|
| 247 |
+
txt_message.submit(
|
| 248 |
+
respond,
|
| 249 |
+
[txt_message, chat_bot, app_session, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature],
|
| 250 |
+
[txt_message, chat_bot, app_session]
|
| 251 |
+
)
|
| 252 |
+
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])
|
| 253 |
+
|
| 254 |
+
# launch
|
| 255 |
+
demo.launch(share=False, debug=True, show_api=False, server_port=8080, server_name="0.0.0.0")
|
| 256 |
+
|