m-ric HF staff commited on
Commit
970b02a
1 Parent(s): 3cc9923

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +262 -13
app.py CHANGED
@@ -1,19 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- max_textboxes = 10
 
 
 
4
 
5
- def variable_outputs(k):
6
- k = int(k)
7
- return [gr.Textbox(visible=True)]*k + [gr.Textbox(visible=False)]*(max_textboxes-k)
 
 
8
 
9
- with gr.Blocks() as demo:
10
- s = gr.Slider(1, max_textboxes, value=max_textboxes, step=1, label="How many textboxes to show:")
11
- textboxes = []
12
- for i in range(max_textboxes):
13
- t = gr.Textbox(f"Textbox {i}")
14
- textboxes.append(t)
15
 
16
- s.change(variable_outputs, s, textboxes)
 
 
 
 
 
 
17
 
18
- if __name__ == "__main__":
19
- demo.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 numpy as np
16
+ import torch
17
+
18
+ from threading import Thread
19
+ from typing import List, Dict, Union
20
+ import urllib
21
+ from PIL import Image
22
+ import io
23
+ import datasets
24
+
25
  import gradio as gr
26
+ from transformers import AutoProcessor, TextIteratorStreamer
27
+ from transformers import Idefics2ForConditionalGeneration
28
+
29
+
30
+ DEVICE = torch.device("cuda")
31
+ MODELS = {
32
+ "idefics2-8b-chatty": Idefics2ForConditionalGeneration.from_pretrained(
33
+ "HuggingFaceM4/idefics2-8b-chatty",
34
+ torch_dtype=torch.bfloat16,
35
+ _attn_implementation="flash_attention_2",
36
+ ).to(DEVICE),
37
+ }
38
+ PROCESSOR = AutoProcessor.from_pretrained(
39
+ "HuggingFaceM4/idefics2-8b",
40
+ )
41
+
42
+ SYSTEM_PROMPT = [
43
+ {
44
+ "role": "system",
45
+ "content": [
46
+ {
47
+ "type": "text",
48
+ "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.",
49
+ },
50
+ ],
51
+ },
52
+ {
53
+ "role": "assistant",
54
+ "content": [
55
+ {
56
+ "type": "text",
57
+ "text": "Hello, I'm Idefics2, Huggingface's latest multimodal assistant. How can I help you?",
58
+ },
59
+ ],
60
+ }
61
+ ]
62
+ examples_path = os.path.dirname(__file__)
63
+ EXAMPLES = [
64
+ [
65
+ {
66
+ "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?",
67
+ "files": [f"{examples_path}/example_images/mmmu_example_2.png"],
68
+ }
69
+ ],
70
+ ]
71
+
72
+ BOT_AVATAR = "IDEFICS_logo.png"
73
+
74
+
75
+ # Chatbot utils
76
+ def turn_is_pure_media(turn):
77
+ return turn[1] is None
78
+
79
+
80
+ def load_image_from_url(url):
81
+ with urllib.request.urlopen(url) as response:
82
+ image_data = response.read()
83
+ image_stream = io.BytesIO(image_data)
84
+ image = Image.open(image_stream)
85
+ return image
86
+
87
+
88
+ def img_to_bytes(image_path):
89
+ image = Image.open(image_path).convert(mode='RGB')
90
+ buffer = io.BytesIO()
91
+ image.save(buffer, format="JPEG")
92
+ img_bytes = buffer.getvalue()
93
+ image.close()
94
+ return img_bytes
95
+
96
+
97
+ def format_user_prompt_with_im_history_and_system_conditioning(
98
+ user_prompt, chat_history
99
+ ) -> List[Dict[str, Union[List, str]]]:
100
+ """
101
+ Produces the resulting list that needs to go inside the processor.
102
+ It handles the potential image(s), the history and the system conditionning.
103
+ """
104
+ resulting_messages = copy.deepcopy(SYSTEM_PROMPT)
105
+ resulting_images = []
106
+ for resulting_message in resulting_messages:
107
+ if resulting_message["role"] == "user":
108
+ for content in resulting_message["content"]:
109
+ if content["type"] == "image":
110
+ resulting_images.append(load_image_from_url(content["image"]))
111
+
112
+ # Format history
113
+ for turn in chat_history:
114
+ if not resulting_messages or (
115
+ resulting_messages and resulting_messages[-1]["role"] != "user"
116
+ ):
117
+ resulting_messages.append(
118
+ {
119
+ "role": "user",
120
+ "content": [],
121
+ }
122
+ )
123
+
124
+ if turn_is_pure_media(turn):
125
+ media = turn[0][0]
126
+ resulting_messages[-1]["content"].append({"type": "image"})
127
+ resulting_images.append(Image.open(media))
128
+ else:
129
+ user_utterance, assistant_utterance = turn
130
+ resulting_messages[-1]["content"].append(
131
+ {"type": "text", "text": user_utterance.strip()}
132
+ )
133
+ resulting_messages.append(
134
+ {
135
+ "role": "assistant",
136
+ "content": [{"type": "text", "text": user_utterance.strip()}],
137
+ }
138
+ )
139
+
140
+ # Format current input
141
+ if not user_prompt["files"]:
142
+ resulting_messages.append(
143
+ {
144
+ "role": "user",
145
+ "content": [{"type": "text", "text": user_prompt["text"]}],
146
+ }
147
+ )
148
+ else:
149
+ # Choosing to put the image first (i.e. before the text), but this is an arbiratrary choice.
150
+ resulting_messages.append(
151
+ {
152
+ "role": "user",
153
+ "content": [{"type": "image"}] * len(user_prompt["files"])
154
+ + [{"type": "text", "text": user_prompt["text"]}],
155
+ }
156
+ )
157
+ resulting_images.extend([Image.open(path) for path in user_prompt["files"]])
158
+
159
+ return resulting_messages, resulting_images
160
+
161
+
162
+ def extract_images_from_msg_list(msg_list):
163
+ all_images = []
164
+ for msg in msg_list:
165
+ for c_ in msg["content"]:
166
+ if isinstance(c_, Image.Image):
167
+ all_images.append(c_)
168
+ return all_images
169
+
170
+
171
+ @spaces.GPU(duration=180)
172
+ def model_inference(
173
+ user_prompt,
174
+ chat_history,
175
+ model_selector,
176
+ temperature,
177
+ top_p,
178
+ ):
179
+ if not user_prompt["files"]:
180
+ gr.Error("Please give me a picture of someone to rate!")
181
+
182
+ streamer = TextIteratorStreamer(
183
+ PROCESSOR.tokenizer,
184
+ skip_prompt=True,
185
+ timeout=5.0,
186
+ )
187
+
188
+ # Common parameters to all decoding strategies
189
+ # This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
190
+ generation_args = {
191
+ "max_new_tokens": 512,
192
+ "repetition_penalty": 1.1,
193
+ "streamer": streamer,
194
+ }
195
+
196
+ generation_args["temperature"] = temperature
197
+ generation_args["do_sample"] = True
198
+ generation_args["top_p"] = top_p
199
+
200
+ # Creating model inputs
201
+ (
202
+ resulting_text,
203
+ resulting_images,
204
+ ) = format_user_prompt_with_im_history_and_system_conditioning(
205
+ user_prompt=user_prompt,
206
+ chat_history=chat_history,
207
+ )
208
+ prompt = PROCESSOR.apply_chat_template(resulting_text, add_generation_prompt=True)
209
+ inputs = PROCESSOR(
210
+ text=prompt,
211
+ images=resulting_images if resulting_images else None,
212
+ return_tensors="pt",
213
+ )
214
+ inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
215
+ generation_args.update(inputs)
216
+
217
+ # # The regular non streaming generation mode
218
+ # _ = generation_args.pop("streamer")
219
+ # generated_ids = MODELS[model_selector].generate(**generation_args)
220
+ # generated_text = PROCESSOR.batch_decode(generated_ids[:, generation_args["input_ids"].size(-1): ], skip_special_tokens=True)[0]
221
+ # return generated_text
222
+
223
+ # The streaming generation mode
224
+ thread = Thread(
225
+ target=MODELS[model_selector].generate,
226
+ kwargs=generation_args,
227
+ )
228
+ thread.start()
229
+
230
+ print("Start generating")
231
+ acc_text = ""
232
+ for text_token in streamer:
233
+ time.sleep(0.04)
234
+ acc_text += text_token
235
+ if acc_text.endswith("<end_of_utterance>"):
236
+ acc_text = acc_text[:-18]
237
+ yield acc_text
238
+ print("Success - generated the following text:", acc_text)
239
+ print("-----")
240
+
241
+
242
+ chatbot = gr.Chatbot(
243
+ label="Idefics2-Chatty",
244
+ avatar_images=[None, BOT_AVATAR],
245
+ height=450,
246
+ )
247
 
248
+ with gr.Blocks(
249
+ fill_height=True,
250
+ 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;}""",
251
+ ) as demo:
252
 
253
+ gr.Markdown("# 🐶 Hugging Face Idefics2 8B Chatty")
254
+ 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.")
255
+ gr.Markdown("If you want to learn more about Idefics2 and its variants, you can check our [blog post](https://huggingface.co/blog/idefics2).")
256
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
257
+ # model selector should be set to `visbile=False` ultimately
258
 
 
 
 
 
 
 
259
 
260
+ gr.ChatInterface(
261
+ fn=model_inference,
262
+ chatbot=chatbot,
263
+ examples=EXAMPLES,
264
+ multimodal=True,
265
+ cache_examples=False,
266
+ )
267
 
268
+ demo.launch()