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argparse
2
+ import hashlib
3
+ import json
4
+ import os
5
+ import time
6
+ from threading import Thread
7
+ import logging
8
+ import gradio as gr
9
+ import torch
10
+
11
+ from tinyllava.model.builder import load_pretrained_model
12
+ from tinyllava.mm_utils import (
13
+ KeywordsStoppingCriteria,
14
+ load_image_from_base64,
15
+ process_images,
16
+ tokenizer_image_token,
17
+ get_model_name_from_path,
18
+ )
19
+ from PIL import Image
20
+ from io import BytesIO
21
+ import base64
22
+ import torch
23
+ from transformers import StoppingCriteria
24
+ from tinyllava.constants import (
25
+ DEFAULT_IM_END_TOKEN,
26
+ DEFAULT_IM_START_TOKEN,
27
+ DEFAULT_IMAGE_TOKEN,
28
+ IMAGE_TOKEN_INDEX,
29
+ )
30
+ from tinyllava.conversation import SeparatorStyle, conv_templates, default_conversation
31
+
32
+ from transformers import TextIteratorStreamer
33
+ from pathlib import Path
34
+
35
+ DEFAULT_MODEL_PATH = "bczhou/TinyLLaVA-3.1B"
36
+ DEFAULT_MODEL_NAME = "TinyLLaVA-3.1B"
37
+
38
+
39
+ block_css = """
40
+
41
+ #buttons button {
42
+ min-width: min(120px,100%);
43
+ }
44
+ """
45
+ title_markdown = """
46
+ # TinyLLaVA: A Framework of Small-scale Large Multimodal Models
47
+ [[Code](https://github.com/DLCV-BUAA/TinyLLaVABench)] | 📚 [[Paper](https://arxiv.org/pdf/2402.14289.pdf)]
48
+ """
49
+ tos_markdown = """
50
+ ### Terms of use
51
+ By using this service, users are required to agree to the following terms:
52
+ The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes.
53
+ For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
54
+ """
55
+ learn_more_markdown = """
56
+ ### License
57
+ The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation.
58
+ """
59
+ ack_markdown = """
60
+ ### Acknowledgement
61
+ The template for this web demo is from [LLaVA](https://github.com/haotian-liu/LLaVA), and we are very grateful to LLaVA for their open source contributions to the community!
62
+ """
63
+
64
+
65
+ def regenerate(state, image_process_mode):
66
+ state.messages[-1][-1] = None
67
+ prev_human_msg = state.messages[-2]
68
+ if type(prev_human_msg[1]) in (tuple, list):
69
+ prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
70
+ state.skip_next = False
71
+ return (state, state.to_gradio_chatbot(), "", None)
72
+
73
+
74
+ def clear_history():
75
+ state = default_conversation.copy()
76
+ return (state, state.to_gradio_chatbot(), "", None)
77
+
78
+
79
+ def add_text(state, text, image, image_process_mode):
80
+ if len(text) <= 0 and image is None:
81
+ state.skip_next = True
82
+ return (state, state.to_gradio_chatbot(), "", None)
83
+
84
+ text = text[:1536] # Hard cut-off
85
+ if image is not None:
86
+ text = text[:1200] # Hard cut-off for images
87
+ if "<image>" not in text:
88
+ # text = '<Image><image></Image>' + text
89
+ text = text + "\n<image>"
90
+ text = (text, image, image_process_mode)
91
+ if len(state.get_images(return_pil=True)) > 0:
92
+ state = default_conversation.copy()
93
+ state.append_message(state.roles[0], text)
94
+ state.append_message(state.roles[1], None)
95
+ state.skip_next = False
96
+ return (state, state.to_gradio_chatbot(), "", None)
97
+
98
+
99
+ def load_demo():
100
+ state = default_conversation.copy()
101
+ return state
102
+
103
+
104
+ @torch.inference_mode()
105
+ def get_response(params):
106
+ prompt = params["prompt"]
107
+ ori_prompt = prompt
108
+ images = params.get("images", None)
109
+ num_image_tokens = 0
110
+ if images is not None and len(images) > 0:
111
+ if len(images) > 0:
112
+ if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
113
+ raise ValueError(
114
+ "Number of images does not match number of <image> tokens in prompt"
115
+ )
116
+
117
+ images = [load_image_from_base64(image) for image in images]
118
+ images = process_images(images, image_processor, model.config)
119
+
120
+ if type(images) is list:
121
+ images = [
122
+ image.to(model.device, dtype=torch.float16) for image in images
123
+ ]
124
+ else:
125
+ images = images.to(model.device, dtype=torch.float16)
126
+
127
+ replace_token = DEFAULT_IMAGE_TOKEN
128
+ if getattr(model.config, "mm_use_im_start_end", False):
129
+ replace_token = (
130
+ DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
131
+ )
132
+ prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
133
+
134
+ num_image_tokens = (
135
+ prompt.count(replace_token) * model.get_vision_tower().num_patches
136
+ )
137
+ else:
138
+ images = None
139
+ image_args = {"images": images}
140
+ else:
141
+ images = None
142
+ image_args = {}
143
+
144
+ temperature = float(params.get("temperature", 1.0))
145
+ top_p = float(params.get("top_p", 1.0))
146
+ max_context_length = getattr(model.config, "max_position_embeddings", 2048)
147
+ max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
148
+ stop_str = params.get("stop", None)
149
+ do_sample = True if temperature > 0.001 else False
150
+ logger.info(prompt)
151
+ input_ids = (
152
+ tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt")
153
+ .unsqueeze(0)
154
+ .to(model.device)
155
+ )
156
+ keywords = [stop_str]
157
+
158
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
159
+ streamer = TextIteratorStreamer(
160
+ tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15
161
+ )
162
+
163
+ max_new_tokens = min(
164
+ max_new_tokens, max_context_length - input_ids.shape[-1] - num_image_tokens
165
+ )
166
+
167
+ if max_new_tokens < 1:
168
+ yield json.dumps(
169
+ {
170
+ "text": ori_prompt
171
+ + "Exceeds max token length. Please start a new conversation, thanks.",
172
+ "error_code": 0,
173
+ }
174
+ ).encode() + b"\0"
175
+ return
176
+
177
+ # local inference
178
+ # BUG: If stopping_criteria is set, an error occur:
179
+ # RuntimeError: The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 0
180
+ generate_kwargs = dict(
181
+ inputs=input_ids,
182
+ do_sample=do_sample,
183
+ temperature=temperature,
184
+ top_p=top_p,
185
+ max_new_tokens=max_new_tokens,
186
+ streamer=streamer,
187
+ # stopping_criteria=[stopping_criteria],
188
+ use_cache=True,
189
+ **image_args,
190
+ )
191
+ thread = Thread(target=model.generate, kwargs=generate_kwargs)
192
+ thread.start()
193
+ logger.debug(ori_prompt)
194
+ logger.debug(generate_kwargs)
195
+ generated_text = ori_prompt
196
+ for new_text in streamer:
197
+ generated_text += new_text
198
+ if generated_text.endswith(stop_str):
199
+ generated_text = generated_text[: -len(stop_str)]
200
+ yield json.dumps({"text": generated_text, "error_code": 0}).encode()
201
+
202
+
203
+ def http_bot(state, temperature, top_p, max_new_tokens):
204
+ if state.skip_next:
205
+ # This generate call is skipped due to invalid inputs
206
+ yield (state, state.to_gradio_chatbot())
207
+ return
208
+
209
+ if len(state.messages) == state.offset + 2:
210
+ # First round of conversation
211
+
212
+ if "tinyllava" in model_name.lower():
213
+ if "3.1b" in model_name.lower() or "phi" in model_name.lower():
214
+ template_name = "phi"
215
+ elif "2.0b" in model_name.lower() or "stablelm" in model_name.lower():
216
+ template_name = "phi"
217
+ elif "qwen" in model_name.lower():
218
+ template_name = "qwen"
219
+ else:
220
+ template_name = "v1"
221
+
222
+ elif "llava" in model_name.lower():
223
+
224
+ if "llama-2" in model_name.lower():
225
+ template_name = "llava_llama_2"
226
+ elif "v1" in model_name.lower():
227
+ if "mmtag" in model_name.lower():
228
+ template_name = "v1_mmtag"
229
+ elif (
230
+ "plain" in model_name.lower()
231
+ and "finetune" not in model_name.lower()
232
+ ):
233
+ template_name = "v1_mmtag"
234
+ else:
235
+ template_name = "llava_v1"
236
+ elif "mpt" in model_name.lower():
237
+ template_name = "mpt"
238
+ else:
239
+ if "mmtag" in model_name.lower():
240
+ template_name = "v0_mmtag"
241
+ elif (
242
+ "plain" in model_name.lower()
243
+ and "finetune" not in model_name.lower()
244
+ ):
245
+ template_name = "v0_mmtag"
246
+ else:
247
+ template_name = "llava_v0"
248
+ elif "mpt" in model_name:
249
+ template_name = "mpt_text"
250
+ elif "llama-2" in model_name:
251
+ template_name = "llama_2"
252
+ else:
253
+ template_name = "vicuna_v1"
254
+ new_state = conv_templates[template_name].copy()
255
+ new_state.append_message(new_state.roles[0], state.messages[-2][1])
256
+ new_state.append_message(new_state.roles[1], None)
257
+ state = new_state
258
+
259
+ # Construct prompt
260
+ prompt = state.get_prompt()
261
+
262
+ all_images = state.get_images(return_pil=True)
263
+ all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
264
+
265
+ # Make requests
266
+ # pload = {"model": model_name, "prompt": prompt, "temperature": float(temperature), "top_p": float(top_p),
267
+ # "max_new_tokens": min(int(max_new_tokens), 1536), "stop": (
268
+ # state.sep
269
+ # if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT]
270
+ # else state.sep2
271
+ # ), "images": state.get_images()}
272
+
273
+ pload = {
274
+ "model": model_name,
275
+ "prompt": prompt,
276
+ "temperature": float(temperature),
277
+ "top_p": float(top_p),
278
+ "max_new_tokens": min(int(max_new_tokens), 1536),
279
+ "stop": (
280
+ state.sep
281
+ if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT]
282
+ else state.sep2
283
+ ), "images": state.get_images()}
284
+
285
+ state.messages[-1][-1] = "▌"
286
+ yield (state, state.to_gradio_chatbot())
287
+
288
+ # for stream
289
+ output = get_response(pload)
290
+ for chunk in output:
291
+ if chunk:
292
+ data = json.loads(chunk.decode())
293
+ if data["error_code"] == 0:
294
+ output = data["text"][len(prompt) :].strip()
295
+ state.messages[-1][-1] = output + "▌"
296
+ yield (state, state.to_gradio_chatbot())
297
+ else:
298
+ output = data["text"] + f" (error_code: {data['error_code']})"
299
+ state.messages[-1][-1] = output
300
+ yield (state, state.to_gradio_chatbot())
301
+ return
302
+ time.sleep(0.03)
303
+
304
+ state.messages[-1][-1] = state.messages[-1][-1][:-1]
305
+ yield (state, state.to_gradio_chatbot())
306
+
307
+
308
+ def build_demo():
309
+ textbox = gr.Textbox(
310
+ show_label=False, placeholder="Enter text and press ENTER", container=False
311
+ )
312
+ with gr.Blocks(title="TinyLLaVA", theme=gr.themes.Default(), css=block_css) as demo:
313
+ state = gr.State()
314
+ gr.Markdown(title_markdown)
315
+
316
+ with gr.Row():
317
+ with gr.Column(scale=5):
318
+ with gr.Row(elem_id="Model ID"):
319
+ gr.Dropdown(
320
+ choices=[DEFAULT_MODEL_NAME],
321
+ value=DEFAULT_MODEL_NAME,
322
+ interactive=True,
323
+ label="Model ID",
324
+ container=False,
325
+ )
326
+ imagebox = gr.Image(type="pil")
327
+ image_process_mode = gr.Radio(
328
+ ["Crop", "Resize", "Pad", "Default"],
329
+ value="Default",
330
+ label="Preprocess for non-square image",
331
+ visible=False,
332
+ )
333
+
334
+ # cur_dir = os.path.dirname(os.path.abspath(__file__))
335
+ cur_dir = Path(__file__).parent
336
+ gr.Examples(
337
+ examples=[
338
+ [
339
+ f"{cur_dir}/examples/extreme_ironing.jpg",
340
+ "What is unusual about this image?",
341
+ ],
342
+ [
343
+ f"{cur_dir}/examples/waterview.jpg",
344
+ "What are the things I should be cautious about when I visit here?",
345
+ ],
346
+ ],
347
+ inputs=[imagebox, textbox],
348
+ )
349
+
350
+ with gr.Accordion("Parameters", open=False) as _:
351
+ temperature = gr.Slider(
352
+ minimum=0.0,
353
+ maximum=1.0,
354
+ value=0.2,
355
+ step=0.1,
356
+ interactive=True,
357
+ label="Temperature",
358
+ )
359
+ top_p = gr.Slider(
360
+ minimum=0.0,
361
+ maximum=1.0,
362
+ value=0.7,
363
+ step=0.1,
364
+ interactive=True,
365
+ label="Top P",
366
+ )
367
+ max_output_tokens = gr.Slider(
368
+ minimum=0,
369
+ maximum=1024,
370
+ value=512,
371
+ step=64,
372
+ interactive=True,
373
+ label="Max output tokens",
374
+ )
375
+
376
+ with gr.Column(scale=8):
377
+ chatbot = gr.Chatbot(elem_id="chatbot", label="Chatbot", height=550)
378
+ with gr.Row():
379
+ with gr.Column(scale=8):
380
+ textbox.render()
381
+ with gr.Column(scale=1, min_width=50):
382
+ submit_btn = gr.Button(value="Send", variant="primary")
383
+ with gr.Row(elem_id="buttons") as _:
384
+ regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=True)
385
+ clear_btn = gr.Button(value="🗑️ Clear", interactive=True)
386
+
387
+ gr.Markdown(tos_markdown)
388
+ gr.Markdown(learn_more_markdown)
389
+ gr.Markdown(ack_markdown)
390
+
391
+ regenerate_btn.click(
392
+ regenerate,
393
+ [state, image_process_mode],
394
+ [state, chatbot, textbox, imagebox],
395
+ queue=False,
396
+ ).then(
397
+ http_bot, [state, temperature, top_p, max_output_tokens], [state, chatbot]
398
+ )
399
+
400
+ clear_btn.click(
401
+ clear_history, None, [state, chatbot, textbox, imagebox], queue=False
402
+ )
403
+
404
+ textbox.submit(
405
+ add_text,
406
+ [state, textbox, imagebox, image_process_mode],
407
+ [state, chatbot, textbox, imagebox],
408
+ queue=False,
409
+ ).then(
410
+ http_bot, [state, temperature, top_p, max_output_tokens], [state, chatbot]
411
+ )
412
+
413
+ submit_btn.click(
414
+ add_text,
415
+ [state, textbox, imagebox, image_process_mode],
416
+ [state, chatbot, textbox, imagebox],
417
+ queue=False,
418
+ ).then(
419
+ http_bot, [state, temperature, top_p, max_output_tokens], [state, chatbot]
420
+ )
421
+
422
+ demo.load(load_demo, None, [state], queue=False)
423
+ return demo
424
+
425
+
426
+ def parse_args():
427
+ parser = argparse.ArgumentParser()
428
+ parser.add_argument("--host", type=str, default=None)
429
+ parser.add_argument("--port", type=int, default=None)
430
+ parser.add_argument("--share", default=None)
431
+ parser.add_argument("--model-path", type=str, default=DEFAULT_MODEL_PATH)
432
+ parser.add_argument("--model-name", type=str, default=DEFAULT_MODEL_NAME)
433
+ parser.add_argument("--load-8bit", action="store_true")
434
+ parser.add_argument("--load-4bit", action="store_true")
435
+ args = parser.parse_args()
436
+ return args
437
+
438
+
439
+ if __name__ == "__main__":
440
+ logging.basicConfig(
441
+ level=logging.INFO,
442
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
443
+ )
444
+ logger = logging.getLogger(__name__)
445
+ logger.info(gr.__version__)
446
+ args = parse_args()
447
+ model_name = args.model_name
448
+ tokenizer, model, image_processor, context_len = load_pretrained_model(
449
+ model_path=args.model_path,
450
+ model_base=None,
451
+ model_name=args.model_name,
452
+ load_4bit=args.load_4bit,
453
+ load_8bit=args.load_8bit
454
+ )
455
+
456
+ demo = build_demo()
457
+ demo.queue()
458
+ demo.launch(server_name=args.host, server_port=args.port, share=args.share)