VictorSanh commited on
Commit
c569980
1 Parent(s): da9b25b

the updated app with transformers integration - TO REPLACE ONCE AMY's PR is ready

Browse files
the_updated_app_with_tfrm_integration.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import os
3
+ import spaces
4
+ import subprocess
5
+ import time
6
+ import torch
7
+
8
+ from threading import Thread
9
+ from typing import List, Dict, Union
10
+ from urllib.parse import urlparse
11
+ from PIL import Image
12
+
13
+ import gradio as gr
14
+ from transformers import AutoProcessor, TextIteratorStreamer
15
+ from transformers import Idefics2ForConditionalGeneration
16
+
17
+ subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
18
+
19
+ DEVICE = torch.device("cuda")
20
+ MODELS = {
21
+ "idefics2": Idefics2ForConditionalGeneration.from_pretrained(
22
+ "/fsx/m4/victor/idefics2-tfrm-compatible",
23
+ torch_dtype=torch.bfloat16,
24
+ _attn_implementation="flash_attention_2",
25
+ trust_remote_code=True,
26
+ ).to(DEVICE),
27
+ }
28
+ PROCESSOR = AutoProcessor.from_pretrained(
29
+ "HuggingFaceM4/idefics2-tfrm-compatible",
30
+ token=os.environ["HF_AUTH_TOKEN"],
31
+ )
32
+ BAD_WORDS_IDS = PROCESSOR.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
33
+ EOS_WORDS_IDS = PROCESSOR.tokenizer("<end_of_utterance>", add_special_tokens=False).input_ids + [PROCESSOR.tokenizer.eos_token_id]
34
+
35
+ SYSTEM_PROMPT = [ # Deactivating the system propmpt for now, but if I were to reactivate it, I would need to a/ transform turns into dict for applying the chat template, b/ manually overwrite the `default_template` to add the first line (that is not part of any turns), in particular for handling the bos_token.
36
+ # """The following is a conversation between a highly knowledgeable and intelligent visual AI assistant, called 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 the content of visual inputs. 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.
37
+
38
+ # The conversation begins:""",
39
+ # """\nUser:""",
40
+ # "https://i1.pickpik.com/photos/515/906/355/kittens-cats-pet-cute-preview.jpg",
41
+ # "Describe this image.<end_of_utterance>",
42
+ # """\nAssistant: Five kittens are standing together in the center of the photograph. From the left to right, there is one orange kitten, two kittens white and black stripes, and two brown kittens with an orange head. They are in bright green grass and it looks like they are moving forward.<end_of_utterance>""",
43
+ # "\nUser:How about this image?",
44
+ # "https://cdn.pixabay.com/photo/2017/09/25/13/12/puppy-2785074_1280.jpg",
45
+ # "Can you describe it too?<end_of_utterance>",
46
+ # """\nAssistant: A dog is lying on the floor, looking at the camera. It is looking directly at you. The dog has a white body and brown patches on its face and ears. Its eyes are dark. Its nose is black, and it has long, floppy ears, white paws, long fur, big eyes.<end_of_utterance>""",
47
+ # "\nUser: What kind of breed is it?<end_of_utterance>",
48
+ # """\nAssistant: It looks like a Cavalier King Charles Spaniel. These breeds are known for their gentle, affectionate nature. Their long ears and big, brown eyes give them a sweet, expressive face. Cavaliers are small dogs weighing between 13 and 20 pounds. They have a silky, medium-length coat that comes in various colors, including black and tan, tricolor, red and white, or black.<end_of_utterance>""",
49
+ # "\nUser: What can you tell me about this breed of dogs?<end_of_utterance>",
50
+ # """\nAssistant: One specific characteristic of the Cavalier King Charles Spaniel is its friendly and affectionate nature. This breed is known for being extremely sociable and forming strong bonds with their owners. They are often described as "velcro dogs" because they love to be close to their human companions, whether it's sitting on their laps, cuddling on the couch, or simply following them around the house.<end_of_utterance>""",
51
+ # "\nUser: ghjkhjabnufs<end_of_utterance>",
52
+ # """\nAssistant: That doesn’t seem to be a word. Could you ask me another way?<end_of_utterance>""",
53
+ # "\nUser: Do you like Cavalier King Charles Spaniel?<end_of_utterance>",
54
+ # """\nAssistant: I do not have personal opinions as I’m just a computer program. However, cavaliers are known for being excellent family pets due to their gentle and patient demeanor, making them great with children and other pets. Their affectionate nature also makes them ideal therapy dogs, as they can provide comfort and emotional support to those in need.<end_of_utterance>""",
55
+ # "\nUser: How many dogs do you see in this image?",
56
+ # "https://i.dailymail.co.uk/i/pix/2011/07/01/article-2010308-0CD22A8300000578-496_634x414.jpg",
57
+ # "<end_of_utterance>",
58
+ # """\nAssistant: There is no dogs in this image. The picture shows a tennis player jumping to volley the ball.<end_of_utterance>""",
59
+ ]
60
+
61
+ API_TOKEN = os.getenv("HF_AUTH_TOKEN")
62
+ # IDEFICS_LOGO = "https://huggingface.co/spaces/HuggingFaceM4/idefics_playground/resolve/main/IDEFICS_logo.png"
63
+ BOT_AVATAR = "IDEFICS_logo.png"
64
+
65
+
66
+ # Chatbot utils
67
+ def turn_is_pure_media(turn):
68
+ return turn[1] is None
69
+
70
+
71
+ def format_user_prompt_with_im_history_and_system_conditioning(
72
+ user_prompt, chat_history
73
+ ) -> List[Dict[str, Union[List, str]]]:
74
+ """
75
+ Produces the resulting list that needs to go inside the processor.
76
+ It handles the potential image(s), the history and the system conditionning.
77
+ """
78
+ resulting_list = copy.deepcopy(SYSTEM_PROMPT)
79
+
80
+ # Format history
81
+ for turn in chat_history:
82
+ if not resulting_list or (resulting_list and resulting_list[-1]["role"] != "user"):
83
+ resulting_list.append(
84
+ {
85
+ "role": "user",
86
+ "content": [],
87
+ }
88
+ )
89
+
90
+ if turn_is_pure_media(turn):
91
+ media = turn[0][0]
92
+ resulting_list[-1]["content"].append(Image.open(media))
93
+ else:
94
+ user_utterance, assistant_utterance = turn
95
+ resulting_list[-1]["content"].append(user_utterance.strip())
96
+ resulting_list.append(
97
+ {
98
+ "role": "assistant",
99
+ "content": [assistant_utterance]
100
+ }
101
+ )
102
+
103
+ # Format current input
104
+ if not user_prompt["files"]:
105
+ resulting_list.append(
106
+ {
107
+ "role": "user",
108
+ "content": [user_prompt['text']],
109
+ }
110
+ )
111
+ else:
112
+ # Choosing to put the image first (i.e. before the text), but this is an arbiratrary choice.
113
+ resulting_list.append(
114
+ {
115
+ "role": "user",
116
+ "content": [Image.open(im['path']) for im in user_prompt['files']] + [user_prompt['text']],
117
+ }
118
+ )
119
+
120
+ return resulting_list
121
+
122
+
123
+ def extract_images_from_msg_list(msg_list):
124
+ all_images = []
125
+ for msg in msg_list:
126
+ for c_ in msg["content"]:
127
+ if isinstance(c_, Image.Image):
128
+ all_images.append(c_)
129
+ return all_images
130
+
131
+
132
+ @spaces.GPU(duration=180)
133
+ def model_inference(
134
+ user_prompt,
135
+ chat_history,
136
+ model_selector,
137
+ decoding_strategy,
138
+ temperature,
139
+ max_new_tokens,
140
+ repetition_penalty,
141
+ top_p,
142
+ ):
143
+ if user_prompt["text"].strip() == "" and not user_prompt["files"]:
144
+ gr.Error("Please input a query and optionally image(s).")
145
+
146
+ if user_prompt["text"].strip() == "" and user_prompt["files"]:
147
+ gr.Error("Please input a text query along the image(s).")
148
+
149
+ for file in user_prompt["files"]:
150
+ if not file["mime_type"].startswith("image/"):
151
+ gr.Error("Idefics2 only supports images. Please input a valid image.")
152
+
153
+ streamer = TextIteratorStreamer(
154
+ PROCESSOR.tokenizer,
155
+ skip_prompt=True,
156
+ timeout=5.,
157
+ )
158
+
159
+ # Common parameters to all decoding strategies
160
+ # This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
161
+ generation_args = {
162
+ "max_new_tokens": max_new_tokens,
163
+ "repetition_penalty": repetition_penalty,
164
+ "bad_words_ids": BAD_WORDS_IDS,
165
+ "eos_token_id": EOS_WORDS_IDS,
166
+ "streamer": streamer,
167
+ }
168
+
169
+ assert decoding_strategy in [
170
+ "Greedy",
171
+ "Top P Sampling",
172
+ ]
173
+ if decoding_strategy == "Greedy":
174
+ generation_args["do_sample"] = False
175
+ elif decoding_strategy == "Top P Sampling":
176
+ generation_args["temperature"] = temperature
177
+ generation_args["do_sample"] = True
178
+ generation_args["top_p"] = top_p
179
+
180
+ # Creating model inputs
181
+ formated_prompt_list = format_user_prompt_with_im_history_and_system_conditioning(
182
+ user_prompt=user_prompt,
183
+ chat_history=chat_history,
184
+ )
185
+ msg = PROCESSOR.apply_chat_template(formated_prompt_list, add_generation_prompt=True, tokenize=False)
186
+ inputs = PROCESSOR.tokenizer(msg, return_tensors="pt", add_special_tokens=False)
187
+ all_images = extract_images_from_msg_list(formated_prompt_list)
188
+ if all_images:
189
+ img_inp = PROCESSOR(all_images)
190
+ inputs["pixel_values"] = torch.tensor(img_inp["pixel_values"])
191
+ inputs["pixel_attention_mask"] = torch.tensor(img_inp["pixel_attention_mask"])
192
+ inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
193
+ generation_args.update(inputs)
194
+
195
+ # # The regular non streaming generation mode (it returns the prompt too though)
196
+ # _ = generation_args.pop("streamer")
197
+ # generated_ids = MODELS[model_selector].generate(**generation_args)
198
+ # generated_text = PROCESSOR.batch_decode(generated_ids, skip_special_tokens=True)[0]
199
+ # return generated_text
200
+
201
+ # The streaming generation mode
202
+ thread = Thread(
203
+ target=MODELS[model_selector].generate,
204
+ kwargs=generation_args,
205
+ )
206
+ thread.start()
207
+
208
+ print("start generating")
209
+ acc_text = ""
210
+ for text_token in streamer:
211
+ time.sleep(0.04)
212
+ acc_text += text_token
213
+ if acc_text.endswith("<end_of_utterance>"):
214
+ acc_text = acc_text[:-18]
215
+ yield acc_text
216
+ print("success - generated the following text:", acc_text)
217
+
218
+
219
+ # Hyper-parameters for generation
220
+ max_new_tokens = gr.Slider(
221
+ minimum=8,
222
+ maximum=1024,
223
+ value=512,
224
+ step=1,
225
+ interactive=True,
226
+ label="Maximum number of new tokens to generate",
227
+ )
228
+ repetition_penalty = gr.Slider(
229
+ minimum=0.01,
230
+ maximum=5.0,
231
+ value=1.0,
232
+ step=0.01,
233
+ interactive=True,
234
+ label="Repetition penalty",
235
+ info="1.0 is equivalent to no penalty",
236
+ )
237
+ decoding_strategy = gr.Radio(
238
+ [
239
+ "Greedy",
240
+ "Top P Sampling",
241
+ ],
242
+ value="Greedy",
243
+ label="Decoding strategy",
244
+ interactive=True,
245
+ info="Higher values is equivalent to sampling more low-probability tokens.",
246
+ )
247
+ temperature = gr.Slider(
248
+ minimum=0.0,
249
+ maximum=5.0,
250
+ value=0.4,
251
+ step=0.1,
252
+ interactive=True,
253
+ label="Sampling temperature",
254
+ info="Higher values will produce more diverse outputs.",
255
+ )
256
+ top_p = gr.Slider(
257
+ minimum=0.01,
258
+ maximum=0.99,
259
+ value=0.8,
260
+ step=0.01,
261
+ interactive=True,
262
+ label="Top P",
263
+ info="Higher values is equivalent to sampling more low-probability tokens.",
264
+ )
265
+
266
+
267
+ chatbot = gr.Chatbot(
268
+ label="IDEFICS2",
269
+ avatar_images=[None, BOT_AVATAR],
270
+ height=750,
271
+ )
272
+
273
+
274
+ with gr.Blocks(fill_height=True) as demo:
275
+ # model selector should be set to `visbile=False` ultimately
276
+ with gr.Row(elem_id="model_selector_row"):
277
+ model_selector = gr.Dropdown(
278
+ choices=MODELS.keys(),
279
+ value=list(MODELS.keys())[0],
280
+ interactive=True,
281
+ show_label=False,
282
+ container=False,
283
+ label="Model",
284
+ visible=True,
285
+ )
286
+
287
+ decoding_strategy.change(
288
+ fn=lambda selection: gr.Slider(
289
+ visible=(
290
+ selection in ["contrastive_sampling", "beam_sampling", "Top P Sampling", "sampling_top_k"]
291
+ )
292
+ ),
293
+ inputs=decoding_strategy,
294
+ outputs=temperature,
295
+ )
296
+ decoding_strategy.change(
297
+ fn=lambda selection: gr.Slider(visible=(selection in ["Top P Sampling"])),
298
+ inputs=decoding_strategy,
299
+ outputs=top_p,
300
+ )
301
+
302
+ gr.ChatInterface(
303
+ fn=model_inference,
304
+ chatbot=chatbot,
305
+ # examples=[{"text": "hello"}, {"text": "hola"}, {"text": "merhaba"}],
306
+ title="Idefics2 Playground",
307
+ multimodal=True,
308
+ additional_inputs=[model_selector, decoding_strategy, temperature, max_new_tokens, repetition_penalty, top_p],
309
+ )
310
+
311
+ demo.launch()