Tamqeen commited on
Commit
d822d50
β€’
1 Parent(s): f9dbd8c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +453 -78
app.py CHANGED
@@ -1,105 +1,480 @@
1
- from transformers import AutoTokenizer
2
- import transformers
 
 
 
 
 
 
 
 
 
 
 
 
3
  import torch
4
 
5
- model = "meta-llama/Llama-2-7b-chat-hf" # meta-llama/Llama-2-7b-chat-hf
 
 
 
 
 
6
 
7
- tokenizer = AutoTokenizer.from_pretrained(model, use_auth_token=True)
 
 
8
 
9
- from transformers import pipeline
10
 
11
- llama_pipeline = pipeline(
12
- "text-generation", # LLM task
13
- model=model,
14
- torch_dtype=torch.float16,
15
- device_map="auto",
 
 
 
 
 
16
  )
17
 
18
- def get_response(prompt: str) -> None:
19
- """
20
- Generate a response from the Llama model.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- Parameters:
23
- prompt (str): The user's input/question for the model.
24
 
25
- Returns:
26
- None: Prints the model's response.
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  """
28
- sequences = llama_pipeline(
29
- prompt,
30
- do_sample=True,
31
- top_k=10,
32
- num_return_sequences=1,
33
- eos_token_id=tokenizer.eos_token_id,
34
- max_length=256,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  )
36
- print("Chatbot:", sequences[0]['generated_text'])
37
 
38
- SYSTEM_PROMPT = """<s>[INST] <<SYS>>
39
- You are a helpful bot. Your answers are clear and concise.
40
- <</SYS>>
 
 
 
 
41
 
42
- """
 
 
 
 
 
 
 
 
 
43
 
44
- # Formatting function for message and history
45
- def format_message(message: str, history: list, memory_limit: int = 3) -> str:
46
- """
47
- Formats the message and history for the Llama model.
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- Parameters:
50
- message (str): Current message to send.
51
- history (list): Past conversation history.
52
- memory_limit (int): Limit on how many past interactions to consider.
 
53
 
54
- Returns:
55
- str: Formatted message string
56
- """
57
- # always keep len(history) <= memory_limit
58
- if len(history) > memory_limit:
59
- history = history[-memory_limit:]
60
 
61
- if len(history) == 0:
62
- return SYSTEM_PROMPT + f"{message} [/INST]"
 
 
 
 
 
 
 
 
63
 
64
- formatted_message = SYSTEM_PROMPT + f"{history[0][0]} [/INST] {history[0][1]} </s>"
65
 
66
- # Handle conversation history
67
- for user_msg, model_answer in history[1:]:
68
- formatted_message += f"<s>[INST] {user_msg} [/INST] {model_answer} </s>"
 
 
 
 
 
 
 
 
 
69
 
70
- # Handle the current message
71
- formatted_message += f"<s>[INST] {message} [/INST]"
72
 
73
- return formatted_message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- # Generate a response from the Llama model
76
- def get_llama_response(message: str, history: list) -> str:
77
- """
78
- Generates a conversational response from the Llama model.
79
 
80
- Parameters:
81
- message (str): User's input message.
82
- history (list): Past conversation history.
 
 
83
 
84
- Returns:
85
- str: Generated response from the Llama model.
86
- """
87
- query = format_message(message, history)
88
- response = ""
89
-
90
- sequences = llama_pipeline(
91
- query,
92
- do_sample=True,
93
- top_k=10,
94
- num_return_sequences=1,
95
- eos_token_id=tokenizer.eos_token_id,
96
- max_length=1024,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  )
98
- #generated_text = sequences[0]['generated_text']
99
- response = generated_text[len(query):] # Remove the prompt from the output
100
 
101
- print("Chatbot:", response.strip())
102
- return response.strip()
103
- import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
- gr.ChatInterface(get_llama_response).launch()
 
1
+ import os
2
+ import subprocess
3
+
4
+ # Install flash attention
5
+ subprocess.run(
6
+ "pip install flash-attn --no-build-isolation",
7
+ env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
8
+ shell=True,
9
+ )
10
+
11
+
12
+ import copy
13
+ import spaces
14
+ import time
15
  import torch
16
 
17
+ from threading import Thread
18
+ from typing import List, Dict, Union
19
+ import urllib
20
+ from PIL import Image
21
+ import io
22
+ import datasets
23
 
24
+ import gradio as gr
25
+ from transformers import AutoProcessor, TextIteratorStreamer
26
+ from transformers import Idefics2ForConditionalGeneration
27
 
 
28
 
29
+ DEVICE = torch.device("cuda")
30
+ MODELS = {
31
+ "idefics2-8b-chatty": Idefics2ForConditionalGeneration.from_pretrained(
32
+ "HuggingFaceM4/idefics2-8b-chatty",
33
+ torch_dtype=torch.bfloat16,
34
+ _attn_implementation="flash_attention_2",
35
+ ).to(DEVICE),
36
+ }
37
+ PROCESSOR = AutoProcessor.from_pretrained(
38
+ "HuggingFaceM4/idefics2-8b",
39
  )
40
 
41
+ SYSTEM_PROMPT = [
42
+ {
43
+ "role": "system",
44
+ "content": [
45
+ {
46
+ "type": "text",
47
+ "text": "The following is a conversation between Idefics2, a highly knowledgeable and intelligent visual AI assistant created by Hugging Face, referred to as Assistant, and a human user called User. In the following interactions, User and Assistant will converse in natural language, and Assistant will do its best to answer User’s questions. Assistant has the ability to perceive images and reason about them, but it cannot generate images. Assistant was built to be respectful, polite and inclusive. It knows a lot, and always tells the truth. When prompted with an image, it does not make up facts.",
48
+ },
49
+ ],
50
+ },
51
+ {
52
+ "role": "assistant",
53
+ "content": [
54
+ {
55
+ "type": "text",
56
+ "text": "Hello, I'm Idefics2, Huggingface's latest multimodal assistant. How can I help you?",
57
+ },
58
+ ],
59
+ }
60
+ ]
61
+ examples_path = os.path.dirname(__file__)
62
+ EXAMPLES = [
63
+ [
64
+ {
65
+ "text": "For 2024, the interest expense is twice what it was in 2014, and the long-term debt is 10% higher than its 2015 level. Can you calculate the combined total of the interest and long-term debt for 2024?",
66
+ "files": [f"{examples_path}/example_images/mmmu_example_2.png"],
67
+ }
68
+ ],
69
+ [
70
+ {
71
+ "text": "What's in the image?",
72
+ "files": [f"{examples_path}/example_images/plant_bulb.webp"],
73
+ }
74
+ ],
75
+ [
76
+ {
77
+ "text": "Describe the image",
78
+ "files": [f"{examples_path}/example_images/baguettes_guarding_paris.png"],
79
+ }
80
+ ],
81
+ [
82
+ {
83
+ "text": "Read what's written on the paper",
84
+ "files": [f"{examples_path}/example_images/paper_with_text.png"],
85
+ }
86
+ ],
87
+ [
88
+ {
89
+ "text": "The respective main characters of these two movies meet in real life. Imagine their discussion. It should be sassy, and the beginning of a mysterious adventure.",
90
+ "files": [f"{examples_path}/example_images/barbie.jpeg", f"{examples_path}/example_images/oppenheimer.jpeg"],
91
+ }
92
+ ],
93
+ [
94
+ {
95
+ "text": "Can you explain this meme?",
96
+ "files": [f"{examples_path}/example_images/running_girl_meme.webp"],
97
+ }
98
+ ],
99
+ [
100
+ {
101
+ "text": "What happens to fish if pelicans increase?",
102
+ "files": [f"{examples_path}/example_images/ai2d_example_2.jpeg"],
103
+ }
104
+ ],
105
+ [
106
+ {
107
+ "text": "Give an art-critic description of this well known painting",
108
+ "files": [f"{examples_path}/example_images/Van-Gogh-Starry-Night.jpg"],
109
+ }
110
+ ],
111
+ [
112
+ {
113
+ "text": "Chase wants to buy 4 kilograms of oval beads and 5 kilograms of star-shaped beads. How much will he spend?",
114
+ "files": [f"{examples_path}/example_images/mmmu_example.jpeg"],
115
+ }
116
+ ],
117
+ [
118
+ {
119
+ "text": "Write an online ad for that product.",
120
+ "files": [f"{examples_path}/example_images/shampoo.jpg"],
121
+ }
122
+ ],
123
+ [
124
+ {
125
+ "text": "Describe this image in detail and explain why it is disturbing.",
126
+ "files": [f"{examples_path}/example_images/cat_cloud.jpeg"],
127
+ }
128
+ ],
129
+ [
130
+ {
131
+ "text": "Why is this image cute?",
132
+ "files": [
133
+ f"{examples_path}/example_images/kittens-cats-pet-cute-preview.jpg"
134
+ ],
135
+ }
136
+ ],
137
+ [
138
+ {
139
+ "text": "What is formed by the deposition of either the weathered remains of other rocks?",
140
+ "files": [f"{examples_path}/example_images/ai2d_example.jpeg"],
141
+ }
142
+ ],
143
+ [
144
+ {
145
+ "text": "What's funny about this image?",
146
+ "files": [f"{examples_path}/example_images/pope_doudoune.webp"],
147
+ }
148
+ ],
149
+ [
150
+ {
151
+ "text": "Can this happen in real life?",
152
+ "files": [f"{examples_path}/example_images/elephant_spider_web.webp"],
153
+ }
154
+ ],
155
+ [
156
+ {
157
+ "text": "What's unusual about this image?",
158
+ "files": [f"{examples_path}/example_images/dragons_playing.png"],
159
+ }
160
+ ],
161
+ [
162
+ {
163
+ "text": "Why is that image comical?",
164
+ "files": [f"{examples_path}/example_images/eye_glasses.jpeg"],
165
+ }
166
+ ],
167
+ ]
168
+
169
+ BOT_AVATAR = "IDEFICS_logo.png"
170
+
171
+
172
+ # Chatbot utils
173
+ def turn_is_pure_media(turn):
174
+ return turn[1] is None
175
+
176
+
177
+ def load_image_from_url(url):
178
+ with urllib.request.urlopen(url) as response:
179
+ image_data = response.read()
180
+ image_stream = io.BytesIO(image_data)
181
+ image = Image.open(image_stream)
182
+ return image
183
 
 
 
184
 
185
+ def img_to_bytes(image_path):
186
+ image = Image.open(image_path).convert(mode='RGB')
187
+ buffer = io.BytesIO()
188
+ image.save(buffer, format="JPEG")
189
+ img_bytes = buffer.getvalue()
190
+ image.close()
191
+ return img_bytes
192
+
193
+
194
+ def format_user_prompt_with_im_history_and_system_conditioning(
195
+ user_prompt, chat_history
196
+ ) -> List[Dict[str, Union[List, str]]]:
197
+ """
198
+ Produces the resulting list that needs to go inside the processor.
199
+ It handles the potential image(s), the history and the system conditionning.
200
  """
201
+ resulting_messages = copy.deepcopy(SYSTEM_PROMPT)
202
+ resulting_images = []
203
+ for resulting_message in resulting_messages:
204
+ if resulting_message["role"] == "user":
205
+ for content in resulting_message["content"]:
206
+ if content["type"] == "image":
207
+ resulting_images.append(load_image_from_url(content["image"]))
208
+
209
+ # Format history
210
+ for turn in chat_history:
211
+ if not resulting_messages or (
212
+ resulting_messages and resulting_messages[-1]["role"] != "user"
213
+ ):
214
+ resulting_messages.append(
215
+ {
216
+ "role": "user",
217
+ "content": [],
218
+ }
219
+ )
220
+
221
+ if turn_is_pure_media(turn):
222
+ media = turn[0][0]
223
+ resulting_messages[-1]["content"].append({"type": "image"})
224
+ resulting_images.append(Image.open(media))
225
+ else:
226
+ user_utterance, assistant_utterance = turn
227
+ resulting_messages[-1]["content"].append(
228
+ {"type": "text", "text": user_utterance.strip()}
229
+ )
230
+ resulting_messages.append(
231
+ {
232
+ "role": "assistant",
233
+ "content": [{"type": "text", "text": user_utterance.strip()}],
234
+ }
235
+ )
236
+
237
+ # Format current input
238
+ if not user_prompt["files"]:
239
+ resulting_messages.append(
240
+ {
241
+ "role": "user",
242
+ "content": [{"type": "text", "text": user_prompt["text"]}],
243
+ }
244
+ )
245
+ else:
246
+ # Choosing to put the image first (i.e. before the text), but this is an arbiratrary choice.
247
+ resulting_messages.append(
248
+ {
249
+ "role": "user",
250
+ "content": [{"type": "image"}] * len(user_prompt["files"])
251
+ + [{"type": "text", "text": user_prompt["text"]}],
252
+ }
253
+ )
254
+ resulting_images.extend([Image.open(path) for path in user_prompt["files"]])
255
+
256
+ return resulting_messages, resulting_images
257
+
258
+
259
+ def extract_images_from_msg_list(msg_list):
260
+ all_images = []
261
+ for msg in msg_list:
262
+ for c_ in msg["content"]:
263
+ if isinstance(c_, Image.Image):
264
+ all_images.append(c_)
265
+ return all_images
266
+
267
+
268
+ @spaces.GPU(duration=180)
269
+ def model_inference(
270
+ user_prompt,
271
+ chat_history,
272
+ model_selector,
273
+ decoding_strategy,
274
+ temperature,
275
+ max_new_tokens,
276
+ repetition_penalty,
277
+ top_p,
278
+ ):
279
+ if user_prompt["text"].strip() == "" and not user_prompt["files"]:
280
+ gr.Error("Please input a query and optionally image(s).")
281
+
282
+ if user_prompt["text"].strip() == "" and user_prompt["files"]:
283
+ gr.Error("Please input a text query along the image(s).")
284
+
285
+ streamer = TextIteratorStreamer(
286
+ PROCESSOR.tokenizer,
287
+ skip_prompt=True,
288
+ timeout=5.0,
289
  )
 
290
 
291
+ # Common parameters to all decoding strategies
292
+ # This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
293
+ generation_args = {
294
+ "max_new_tokens": max_new_tokens,
295
+ "repetition_penalty": repetition_penalty,
296
+ "streamer": streamer,
297
+ }
298
 
299
+ assert decoding_strategy in [
300
+ "Greedy",
301
+ "Top P Sampling",
302
+ ]
303
+ if decoding_strategy == "Greedy":
304
+ generation_args["do_sample"] = False
305
+ elif decoding_strategy == "Top P Sampling":
306
+ generation_args["temperature"] = temperature
307
+ generation_args["do_sample"] = True
308
+ generation_args["top_p"] = top_p
309
 
310
+ # Creating model inputs
311
+ (
312
+ resulting_text,
313
+ resulting_images,
314
+ ) = format_user_prompt_with_im_history_and_system_conditioning(
315
+ user_prompt=user_prompt,
316
+ chat_history=chat_history,
317
+ )
318
+ prompt = PROCESSOR.apply_chat_template(resulting_text, add_generation_prompt=True)
319
+ inputs = PROCESSOR(
320
+ text=prompt,
321
+ images=resulting_images if resulting_images else None,
322
+ return_tensors="pt",
323
+ )
324
+ inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
325
+ generation_args.update(inputs)
326
 
327
+ # # The regular non streaming generation mode
328
+ # _ = generation_args.pop("streamer")
329
+ # generated_ids = MODELS[model_selector].generate(**generation_args)
330
+ # generated_text = PROCESSOR.batch_decode(generated_ids[:, generation_args["input_ids"].size(-1): ], skip_special_tokens=True)[0]
331
+ # return generated_text
332
 
333
+ # The streaming generation mode
334
+ thread = Thread(
335
+ target=MODELS[model_selector].generate,
336
+ kwargs=generation_args,
337
+ )
338
+ thread.start()
339
 
340
+ print("Start generating")
341
+ acc_text = ""
342
+ for text_token in streamer:
343
+ time.sleep(0.04)
344
+ acc_text += text_token
345
+ if acc_text.endswith("<end_of_utterance>"):
346
+ acc_text = acc_text[:-18]
347
+ yield acc_text
348
+ print("Success - generated the following text:", acc_text)
349
+ print("-----")
350
 
 
351
 
352
+ FEATURES = datasets.Features(
353
+ {
354
+ "model_selector": datasets.Value("string"),
355
+ "images": datasets.Sequence(datasets.Image(decode=True)),
356
+ "conversation": datasets.Sequence({"User": datasets.Value("string"), "Assistant": datasets.Value("string")}),
357
+ "decoding_strategy": datasets.Value("string"),
358
+ "temperature": datasets.Value("float32"),
359
+ "max_new_tokens": datasets.Value("int32"),
360
+ "repetition_penalty": datasets.Value("float32"),
361
+ "top_p": datasets.Value("int32"),
362
+ }
363
+ )
364
 
 
 
365
 
366
+ # Hyper-parameters for generation
367
+ max_new_tokens = gr.Slider(
368
+ minimum=8,
369
+ maximum=1024,
370
+ value=512,
371
+ step=1,
372
+ interactive=True,
373
+ label="Maximum number of new tokens to generate",
374
+ )
375
+ repetition_penalty = gr.Slider(
376
+ minimum=0.01,
377
+ maximum=5.0,
378
+ value=1.1,
379
+ step=0.01,
380
+ interactive=True,
381
+ label="Repetition penalty",
382
+ info="1.0 is equivalent to no penalty",
383
+ )
384
+ decoding_strategy = gr.Radio(
385
+ [
386
+ "Greedy",
387
+ "Top P Sampling",
388
+ ],
389
+ value="Greedy",
390
+ label="Decoding strategy",
391
+ interactive=True,
392
+ info="Higher values is equivalent to sampling more low-probability tokens.",
393
+ )
394
+ temperature = gr.Slider(
395
+ minimum=0.0,
396
+ maximum=5.0,
397
+ value=0.4,
398
+ step=0.1,
399
+ visible=False,
400
+ interactive=True,
401
+ label="Sampling temperature",
402
+ info="Higher values will produce more diverse outputs.",
403
+ )
404
+ top_p = gr.Slider(
405
+ minimum=0.01,
406
+ maximum=0.99,
407
+ value=0.8,
408
+ step=0.01,
409
+ visible=False,
410
+ interactive=True,
411
+ label="Top P",
412
+ info="Higher values is equivalent to sampling more low-probability tokens.",
413
+ )
414
 
 
 
 
 
415
 
416
+ chatbot = gr.Chatbot(
417
+ label="Idefics2-Chatty",
418
+ avatar_images=[None, BOT_AVATAR],
419
+ height=450,
420
+ )
421
 
422
+ with gr.Blocks(
423
+ fill_height=True,
424
+ css=""".gradio-container .avatar-container {height: 40px width: 40px !important;} #duplicate-button {margin: auto; color: white; background: #f1a139; border-radius: 100vh; margin-top: 2px; margin-bottom: 2px;}""",
425
+ ) as demo:
426
+
427
+ gr.Markdown("# 🐢 Hugging Face Idefics2 8B Chatty")
428
+ gr.Markdown("In this demo you'll be able to chat with [Idefics2-8B-chatty](https://huggingface.co/HuggingFaceM4/idefics2-8b-chatty), a variant of [Idefics2-8B](https://huggingface.co/HuggingFaceM4/idefics2-8b-chatty) further fine-tuned on chat datasets.")
429
+ gr.Markdown("If you want to learn more about Idefics2 and its variants, you can check our [blog post](https://huggingface.co/blog/idefics2).")
430
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
431
+ # model selector should be set to `visbile=False` ultimately
432
+ with gr.Row(elem_id="model_selector_row"):
433
+ model_selector = gr.Dropdown(
434
+ choices=MODELS.keys(),
435
+ value=list(MODELS.keys())[0],
436
+ interactive=True,
437
+ show_label=False,
438
+ container=False,
439
+ label="Model",
440
+ visible=False,
441
+ )
442
+
443
+ decoding_strategy.change(
444
+ fn=lambda selection: gr.Slider(
445
+ visible=(
446
+ selection
447
+ in [
448
+ "contrastive_sampling",
449
+ "beam_sampling",
450
+ "Top P Sampling",
451
+ "sampling_top_k",
452
+ ]
453
+ )
454
+ ),
455
+ inputs=decoding_strategy,
456
+ outputs=temperature,
457
+ )
458
+ decoding_strategy.change(
459
+ fn=lambda selection: gr.Slider(visible=(selection in ["Top P Sampling"])),
460
+ inputs=decoding_strategy,
461
+ outputs=top_p,
462
  )
 
 
463
 
464
+ gr.ChatInterface(
465
+ fn=model_inference,
466
+ chatbot=chatbot,
467
+ examples=EXAMPLES,
468
+ multimodal=True,
469
+ cache_examples=False,
470
+ additional_inputs=[
471
+ model_selector,
472
+ decoding_strategy,
473
+ temperature,
474
+ max_new_tokens,
475
+ repetition_penalty,
476
+ top_p,
477
+ ],
478
+ )
479
 
480
+ demo.launch()