File size: 16,159 Bytes
ec50e73
792e854
92f5f56
a2496cb
34d389e
 
 
 
 
92f5f56
 
 
 
488a53d
ec50e73
 
 
dc6da18
bf512c7
ec50e73
 
bf512c7
1430cb0
 
 
 
ec50e73
 
dc6da18
 
ec50e73
792e854
ec50e73
 
34d389e
db79ccc
f84e07f
 
 
 
 
ec50e73
 
4273b28
ec50e73
 
 
0113778
 
f9f9d0b
0113778
34d389e
 
192577c
f9f9d0b
0113778
f9f9d0b
ec50e73
02dcc48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec50e73
 
0a45780
ec50e73
 
 
 
adf07d5
 
 
ec50e73
34d389e
bf512c7
 
 
 
 
 
ec50e73
23c98b1
65a7de2
bc1a623
65a7de2
 
 
 
 
34d389e
23c98b1
ec50e73
adf07d5
dc6da18
ec50e73
 
adf07d5
ec50e73
4273b28
 
1430cb0
 
 
 
 
ec50e73
 
adf07d5
34d389e
 
 
4273b28
dc6da18
 
 
 
 
 
adf07d5
 
4273b28
 
adf07d5
 
4273b28
 
 
 
dc6da18
 
34d389e
dc6da18
 
ec50e73
 
adf07d5
4273b28
dc6da18
 
34d389e
dc6da18
 
ec50e73
dc6da18
4273b28
dc6da18
 
34d389e
 
dc6da18
 
38fdad8
adf07d5
4273b28
adf07d5
 
dc6da18
 
 
 
 
 
 
 
 
adf07d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34d389e
adf07d5
ec50e73
adf07d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34d389e
 
 
 
dc6da18
 
 
4273b28
34d389e
 
 
 
 
adf07d5
 
 
 
 
 
dc6da18
adf07d5
 
dc6da18
adf07d5
 
 
 
 
ec50e73
dc6da18
adf07d5
dc6da18
 
 
 
 
 
 
 
adf07d5
34d389e
6c67beb
 
 
 
 
 
 
 
 
 
 
 
 
914f129
23c98b1
 
 
 
 
 
 
 
 
bc1a623
23c98b1
 
bc1a623
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7cae97c
bc1a623
 
 
 
7cae97c
914f129
 
 
 
 
 
 
 
 
 
 
 
bc1a623
914f129
 
bc1a623
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23c98b1
 
adf07d5
 
 
 
 
 
 
 
 
 
 
 
84228e7
adf07d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76f94cd
adf07d5
 
 
 
 
 
 
 
 
76f94cd
adf07d5
 
 
ec50e73
 
91e4b1d
 
2b819e0
91e4b1d
742ceb6
91e4b1d
 
1430cb0
34d389e
 
1430cb0
34d389e
1430cb0
34d389e
 
 
1430cb0
34d389e
1430cb0
71338f5
34d389e
 
 
 
91e4b1d
ec50e73
 
 
adf07d5
ec50e73
 
 
 
 
 
 
adf07d5
 
 
34d389e
 
 
 
 
 
 
ec50e73
adf07d5
 
 
ec50e73
3edb153
 
 
34d389e
 
 
 
 
 
 
3edb153
 
 
 
 
adf07d5
 
 
 
ec50e73
1bfcc16
adf07d5
ec50e73
91e4b1d
02dcc48
1bfcc16
adf07d5
34d389e
 
 
 
 
 
 
 
ec50e73
1430cb0
 
 
 
 
 
 
914f129
23c98b1
1430cb0
 
 
 
 
 
 
 
23c98b1
1430cb0
 
 
914f129
23c98b1
1430cb0
 
 
 
 
 
 
 
23c98b1
1430cb0
 
ec50e73
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import os
import subprocess

# Install flash attention
subprocess.run(
    "pip install flash-attn --no-build-isolation",
    env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
    shell=True,
)


import copy
import spaces
import time
import torch

from threading import Thread
from typing import List, Dict, Union
import urllib
from urllib.parse import urlparse
from PIL import Image
import io
import pandas as pd
import datasets
import json
import requests

import gradio as gr
from transformers import AutoProcessor, TextIteratorStreamer
from transformers import Idefics2ForConditionalGeneration


DEVICE = torch.device("cuda")
MODELS = {
    "idefics2-8b-chatty": Idefics2ForConditionalGeneration.from_pretrained(
        "HuggingFaceM4/idefics2-8b-chatty",
        torch_dtype=torch.bfloat16,
        _attn_implementation="flash_attention_2",
        trust_remote_code=True,
        token=os.environ["HF_AUTH_TOKEN"],
    ).to(DEVICE),
}
PROCESSOR = AutoProcessor.from_pretrained(
    "HuggingFaceM4/idefics2-8b",
    token=os.environ["HF_AUTH_TOKEN"],
)

SYSTEM_PROMPT = [
    {
        "role": "system",
        "content": [
            {
                "type": "text",
                "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 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.",
            },
        ],
    }
]
examples_path = os.path.dirname(__file__)
EXAMPLES = [
    [
        {
            "text": "Describe the image",
            "files": [f"{examples_path}/example_images/plant_bulb.webp"],
        }
    ],
    [
        {
            "text": "Describe the image",
            "files": [f"{examples_path}/example_images/pope_doudoune.webp"],
        }
    ],
    [
        {
            "text": "Describe the image",
            "files": [
                f"{examples_path}/example_images/kittens-cats-pet-cute-preview.jpg"
            ],
        }
    ],
    [
        {
            "text": "Describe the image",
            "files": [f"{examples_path}/example_images/baguettes_guarding_paris.png"],
        }
    ],
    [
        {
            "text": "Describe the image",
            "files": [f"{examples_path}/example_images/dragons_playing.png"],
        }
    ],
]

API_TOKEN = os.getenv("HF_AUTH_TOKEN")
HF_WRITE_TOKEN = os.getenv("HF_WRITE_TOKEN")
# IDEFICS_LOGO = "https://huggingface.co/spaces/HuggingFaceM4/idefics_playground/resolve/main/IDEFICS_logo.png"
BOT_AVATAR = "IDEFICS_logo.png"


# Chatbot utils
def turn_is_pure_media(turn):
    return turn[1] is None


def load_image_from_url(url):
    with urllib.request.urlopen(url) as response:
        image_data = response.read()
        image_stream = io.BytesIO(image_data)
        image = Image.open(image_stream)
        return image


def img_to_bytes(image_path):
    image = Image.open(image_path).convert(mode='RGB')
    buffer = io.BytesIO()
    image.save(buffer, format="JPEG")
    img_bytes = buffer.getvalue()
    image.close()
    return img_bytes


def format_user_prompt_with_im_history_and_system_conditioning(
    user_prompt, chat_history
) -> List[Dict[str, Union[List, str]]]:
    """
    Produces the resulting list that needs to go inside the processor.
    It handles the potential image(s), the history and the system conditionning.
    """
    resulting_messages = copy.deepcopy(SYSTEM_PROMPT)
    resulting_images = []
    for resulting_message in resulting_messages:
        if resulting_message["role"] == "user":
            for content in resulting_message["content"]:
                if content["type"] == "image":
                    resulting_images.append(load_image_from_url(content["image"]))

    # Format history
    for turn in chat_history:
        if not resulting_messages or (
            resulting_messages and resulting_messages[-1]["role"] != "user"
        ):
            resulting_messages.append(
                {
                    "role": "user",
                    "content": [],
                }
            )

        if turn_is_pure_media(turn):
            media = turn[0][0]
            resulting_messages[-1]["content"].append({"type": "image"})
            resulting_images.append(Image.open(media))
        else:
            user_utterance, assistant_utterance = turn
            resulting_messages[-1]["content"].append(
                {"type": "text", "text": user_utterance.strip()}
            )
            resulting_messages.append(
                {
                    "role": "assistant",
                    "content": [{"type": "text", "text": user_utterance.strip()}],
                }
            )

    # Format current input
    if not user_prompt["files"]:
        resulting_messages.append(
            {
                "role": "user",
                "content": [{"type": "text", "text": user_prompt["text"]}],
            }
        )
    else:
        # Choosing to put the image first (i.e. before the text), but this is an arbiratrary choice.
        resulting_messages.append(
            {
                "role": "user",
                "content": [{"type": "image"}] * len(user_prompt["files"])
                + [{"type": "text", "text": user_prompt["text"]}],
            }
        )
        resulting_images.extend([Image.open(path) for path in user_prompt["files"]])

    return resulting_messages, resulting_images


def extract_images_from_msg_list(msg_list):
    all_images = []
    for msg in msg_list:
        for c_ in msg["content"]:
            if isinstance(c_, Image.Image):
                all_images.append(c_)
    return all_images


@spaces.GPU(duration=180)
def model_inference(
    user_prompt,
    chat_history,
    model_selector,
    decoding_strategy,
    temperature,
    max_new_tokens,
    repetition_penalty,
    top_p,
):
    if user_prompt["text"].strip() == "" and not user_prompt["files"]:
        gr.Error("Please input a query and optionally image(s).")

    if user_prompt["text"].strip() == "" and user_prompt["files"]:
        gr.Error("Please input a text query along the image(s).")

    streamer = TextIteratorStreamer(
        PROCESSOR.tokenizer,
        skip_prompt=True,
        timeout=5.0,
    )

    # Common parameters to all decoding strategies
    # This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
    generation_args = {
        "max_new_tokens": max_new_tokens,
        "repetition_penalty": repetition_penalty,
        "streamer": streamer,
    }

    assert decoding_strategy in [
        "Greedy",
        "Top P Sampling",
    ]
    if decoding_strategy == "Greedy":
        generation_args["do_sample"] = False
    elif decoding_strategy == "Top P Sampling":
        generation_args["temperature"] = temperature
        generation_args["do_sample"] = True
        generation_args["top_p"] = top_p

    # Creating model inputs
    (
        resulting_text,
        resulting_images,
    ) = format_user_prompt_with_im_history_and_system_conditioning(
        user_prompt=user_prompt,
        chat_history=chat_history,
    )
    prompt = PROCESSOR.apply_chat_template(resulting_text, add_generation_prompt=True)
    inputs = PROCESSOR(
        text=prompt,
        images=resulting_images if resulting_images else None,
        return_tensors="pt",
    )
    inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
    generation_args.update(inputs)

    # # The regular non streaming generation mode
    # _ = generation_args.pop("streamer")
    # generated_ids = MODELS[model_selector].generate(**generation_args)
    # generated_text = PROCESSOR.batch_decode(generated_ids[:, generation_args["input_ids"].size(-1): ], skip_special_tokens=True)[0]
    # return generated_text

    # The streaming generation mode
    thread = Thread(
        target=MODELS[model_selector].generate,
        kwargs=generation_args,
    )
    thread.start()

    print("Start generating")
    acc_text = ""
    for text_token in streamer:
        time.sleep(0.04)
        acc_text += text_token
        if acc_text.endswith("<end_of_utterance>"):
            acc_text = acc_text[:-18]
        yield acc_text
    print("Success - generated the following text:", acc_text)
    print("-----")


FEATURES = datasets.Features(
    {
        "model_selector": datasets.Value("string"),
        "images": datasets.Sequence(datasets.Image(decode=True)),
        "conversation": datasets.Sequence({"User": datasets.Value("string"), "Assistant": datasets.Value("string")}),
        "decoding_strategy": datasets.Value("string"),
        "temperature": datasets.Value("float32"),
        "max_new_tokens": datasets.Value("int32"),
        "repetition_penalty": datasets.Value("float32"),
        "top_p": datasets.Value("int32"),
        }
    )

def flag_dope(
    model_selector,
    chat_history,
    decoding_strategy,
    temperature,
    max_new_tokens,
    repetition_penalty,
    top_p,
):
    images = []
    conversation = []
    for ex in chat_history:
        if isinstance(ex[0], dict):
            images.append(img_to_bytes(ex[0]["file"]["path"]))
        else:
            
            conversation.append({"User": ex[0], "Assistant": ex[1]})
            
    data = {
        "model_selector": [model_selector],
        "images": [images],
        "conversation": [conversation],
        "decoding_strategy": [decoding_strategy],
        "temperature": [temperature],
        "max_new_tokens": [max_new_tokens],
        "repetition_penalty": [repetition_penalty],
        "top_p": [top_p],
    }
    try:
        ds = datasets.load_dataset("HuggingFaceM4/dope-dataset-red-teaming", split="train", token=HF_WRITE_TOKEN)
        new_data = datasets.Dataset.from_dict(data, features=FEATURES)
        hf_dataset = datasets.concatenate_datasets([ds,new_data])
    except Exception:
        hf_dataset = datasets.Dataset.from_dict(data, features=FEATURES)
    hf_dataset.push_to_hub( "HuggingFaceM4/dope-dataset-red-teaming", split="train", token=HF_WRITE_TOKEN, private=True)


def flag_problematic(
    model_selector,
    chat_history,
    decoding_strategy,
    temperature,
    max_new_tokens,
    repetition_penalty,
    top_p,
):
    images = []
    conversation = []
    for ex in chat_history:
        if isinstance(ex[0], dict):
            images.append(img_to_bytes(ex[0]["file"]["path"]))
        else:
            
            conversation.append({"User": ex[0], "Assistant": ex[1]})
            
    data = {
        "model_selector": [model_selector],
        "images": [images],
        "conversation": [conversation],
        "decoding_strategy": [decoding_strategy],
        "temperature": [temperature],
        "max_new_tokens": [max_new_tokens],
        "repetition_penalty": [repetition_penalty],
        "top_p": [top_p],
    }
    try:
        ds = datasets.load_dataset("HuggingFaceM4/problematic-dataset-red-teaming", split="train", token=HF_WRITE_TOKEN)
        new_data = datasets.Dataset.from_dict(data, features=FEATURES)
        hf_dataset = datasets.concatenate_datasets([ds,new_data])
    except Exception:
        hf_dataset = datasets.Dataset.from_dict(data, features=FEATURES)
    hf_dataset.push_to_hub( "HuggingFaceM4/problematic-dataset-red-teaming", split="train", token=HF_WRITE_TOKEN, private=True)


# Hyper-parameters for generation
max_new_tokens = gr.Slider(
    minimum=8,
    maximum=1024,
    value=512,
    step=1,
    interactive=True,
    label="Maximum number of new tokens to generate",
)
repetition_penalty = gr.Slider(
    minimum=0.01,
    maximum=5.0,
    value=1.1,
    step=0.01,
    interactive=True,
    label="Repetition penalty",
    info="1.0 is equivalent to no penalty",
)
decoding_strategy = gr.Radio(
    [
        "Greedy",
        "Top P Sampling",
    ],
    value="Greedy",
    label="Decoding strategy",
    interactive=True,
    info="Higher values is equivalent to sampling more low-probability tokens.",
)
temperature = gr.Slider(
    minimum=0.0,
    maximum=5.0,
    value=0.4,
    step=0.1,
    visible=False,
    interactive=True,
    label="Sampling temperature",
    info="Higher values will produce more diverse outputs.",
)
top_p = gr.Slider(
    minimum=0.01,
    maximum=0.99,
    value=0.8,
    step=0.01,
    visible=False,
    interactive=True,
    label="Top P",
    info="Higher values is equivalent to sampling more low-probability tokens.",
)


chatbot = gr.Chatbot(
    label="Idefics2",
    avatar_images=[None, BOT_AVATAR],
    height=450,
)

# Using Flagging for saving dope and problematic examples
# Dope examples flagging


# gr.Markdown("""## How to use?

#     There are two ways to provide image inputs:
#     - Using the image box on the left panel
#     - Using the inline syntax: `text<fake_token_around_image><image:URL_IMAGE><fake_token_around_image>text`

#     The second syntax allows inputting an arbitrary number of images.""")

image_flag = gr.Image(visible=False)
with gr.Blocks(
    fill_height=True,
    css=""".gradio-container .avatar-container {height: 40px width: 40px !important;}""",
) as demo:
    # model selector should be set to `visbile=False` ultimately
    with gr.Row(elem_id="model_selector_row"):
        model_selector = gr.Dropdown(
            choices=MODELS.keys(),
            value=list(MODELS.keys())[0],
            interactive=True,
            show_label=False,
            container=False,
            label="Model",
            visible=True,
        )

    decoding_strategy.change(
        fn=lambda selection: gr.Slider(
            visible=(
                selection
                in [
                    "contrastive_sampling",
                    "beam_sampling",
                    "Top P Sampling",
                    "sampling_top_k",
                ]
            )
        ),
        inputs=decoding_strategy,
        outputs=temperature,
    )
    decoding_strategy.change(
        fn=lambda selection: gr.Slider(
            visible=(
                selection
                in [
                    "contrastive_sampling",
                    "beam_sampling",
                    "Top P Sampling",
                    "sampling_top_k",
                ]
            )
        ),
        inputs=decoding_strategy,
        outputs=repetition_penalty,
    )
    decoding_strategy.change(
        fn=lambda selection: gr.Slider(visible=(selection in ["Top P Sampling"])),
        inputs=decoding_strategy,
        outputs=top_p,
    )

    gr.ChatInterface(
        fn=model_inference,
        chatbot=chatbot,
        examples=EXAMPLES,
        title="Idefics2 Playground",
        multimodal=True,
        additional_inputs=[
            model_selector,
            decoding_strategy,
            temperature,
            max_new_tokens,
            repetition_penalty,
            top_p,
        ],
    )
    with gr.Group():
        with gr.Row():
            with gr.Column(scale=1, min_width=50):
                dope_bttn = gr.Button("Dope🔥")
            with gr.Column(scale=1, min_width=50):
                problematic_bttn = gr.Button("Problematic😬")
    dope_bttn.click(
        fn=flag_dope,
        inputs=[
            model_selector,
            chatbot,
            decoding_strategy,
            temperature,
            max_new_tokens,
            repetition_penalty,
            top_p,
        ],
        outputs=None,
        preprocess=False,
    )
    problematic_bttn.click(
        fn=flag_problematic,
        inputs=[
            model_selector,
            chatbot,
            decoding_strategy,
            temperature,
            max_new_tokens,
            repetition_penalty,
            top_p,
        ],
        outputs=None,
        preprocess=False,
    )

demo.launch()