Spaces:
Build error
Build error
import base64 | |
import copy | |
import logging | |
import os | |
import re | |
from io import BytesIO | |
from typing import List, Optional, Tuple, Union | |
from urllib.parse import urlparse | |
import gradio as gr | |
import PIL | |
from accelerate.utils import get_max_memory, set_seed | |
from PIL import Image | |
from transformers import AutoConfig, AutoProcessor, IdeficsForVisionText2Text | |
MODELS = [ | |
"HuggingFaceM4/idefics-9b-instruct", | |
"HuggingFaceM4/idefics-80b-instruct", | |
] | |
SYSTEM_PROMPT = [ | |
"""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. | |
The conversation begins:""", | |
"""\nUser:<fake_token_around_image><image:https://i1.pickpik.com/photos/515/906/355/kittens-cats-pet-cute-preview.jpg><fake_token_around_image>Describe this image.<end_of_utterance>""", | |
"""\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>""", | |
( | |
"\nUser:How about this" | |
" image?<fake_token_around_image><image:https://cdn.pixabay.com/photo/2017/09/25/13/12/puppy-2785074_1280.jpg><fake_token_around_image>Can" | |
" you describe it too?<end_of_utterance>" | |
), | |
"""\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>""", | |
"\nUser: What kind of breed is it?<end_of_utterance>", | |
"""\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>""", | |
"\nUser: What can you tell me about this breed of dogs?<end_of_utterance>", | |
"""\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>""", | |
"\nUser: ghjkhjabnufs<end_of_utterance>", | |
"""\nAssistant: That doesn’t seem to be a word. Could you ask me another way?<end_of_utterance>""", | |
"\nUser: Do you like Cavalier King Charles Spaniel?<end_of_utterance>\n", | |
"""\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>""", | |
( | |
"\nUser: How many dogs do you see in this" | |
" image?<fake_token_around_image><image:https://i.dailymail.co.uk/i/pix/2011/07/01/article-2010308-0CD22A8300000578-496_634x414.jpg><fake_token_around_image><end_of_utterance>" | |
), | |
"""\nAssistant: There is no dogs in this image. The picture shows a tennis player jumping to volley the ball.<end_of_utterance>""", | |
] | |
BAN_TOKENS = "<image>;<fake_token_around_image>" | |
EOS_TOKENS = "</s>;<end_of_utterance>;User" | |
TOKENIZER_FAST = True | |
MAX_SEQ_LEN = 2048 | |
logging.basicConfig(level=logging.INFO) | |
logger = logging.getLogger() | |
SEED = 38 | |
set_seed(38) | |
import requests | |
from io import BytesIO | |
import uuid | |
from PIL import Image | |
from PIL import Image | |
import tempfile | |
def convert_to_rgb_pil(image): | |
if image.mode == "RGB": | |
return image | |
image_rgba = image.convert("RGBA") | |
background = Image.new("RGBA", image_rgba.size, (255, 255, 255)) | |
alpha_composite = Image.alpha_composite(background, image_rgba) | |
alpha_composite = alpha_composite.convert("RGB") | |
# Save the converted image to a temporary file | |
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") | |
temp_file_path = temp_file.name | |
alpha_composite.save(temp_file_path) | |
temp_file.close() | |
return temp_file_path # Return the path to the saved image | |
def convert_to_rgb(filepath_or_pilimg): | |
# `image.convert("RGB")` would only work for .jpg images, as it creates a wrong background | |
# for transparent images. The call to `alpha_composite` handles this case | |
if isinstance(filepath_or_pilimg, PIL.Image.Image): | |
return convert_to_rgb_pil(filepath_or_pilimg) | |
with Image.open(filepath_or_pilimg) as image: | |
# Check if the image is already in the RGB format | |
if image.mode == "RGB": | |
return filepath_or_pilimg # If already in RGB, return the original path | |
# Convert image to RGBA | |
image_rgba = image.convert("RGBA") | |
# Create a white background image of the same size | |
background = Image.new("RGBA", image_rgba.size, (255, 255, 255)) | |
# Composite the original image over the white background | |
alpha_composite = Image.alpha_composite(background, image_rgba) | |
# Convert the composited image to RGB format | |
alpha_composite = alpha_composite.convert("RGB") | |
# Save the converted image to a temporary file | |
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") | |
temp_file_path = temp_file.name | |
alpha_composite.save(temp_file_path) | |
temp_file.close() | |
return temp_file_path # Return the path to the saved image | |
def base64_to_pil(encoded_image): | |
decoded_image = base64.b64decode(encoded_image) | |
pil_image = Image.open(BytesIO(decoded_image)) | |
return pil_image | |
def im_markdown_to_pil(im_markdown_str): | |
pattern = r'<img src="data:image/png;base64,([^"]+)" />' | |
match = re.search(pattern, im_markdown_str) | |
img_b64_str = match.group(1) | |
return base64_to_pil(img_b64_str) | |
def split_str_on_im_markdown(string_with_potential_im_markdown): | |
""" | |
Extract from a string (typically the user prompt string) the potentional images saved as a base64 representation | |
inside a markdown. | |
""" | |
pattern = r'<img src="data:image/png;base64,([^"]+)" />' | |
parts = re.split(pattern, string_with_potential_im_markdown) | |
result = [] | |
for i, part in enumerate(parts): | |
if i % 2 == 0: | |
result.append(part) | |
else: | |
img_tag = f'<img src="data:image/png;base64,{part.strip()}" />' | |
result.append(img_tag) | |
return result | |
# Fetching utils | |
def is_url(string): | |
""" | |
Checks if the passed string contains a valid url and nothing else. e.g. if space is included it's immediately | |
invalidated the url | |
""" | |
if " " in string: | |
return False | |
result = urlparse(string) | |
return all([result.scheme, result.netloc]) | |
def isolate_images_urls(prompt_list): | |
""" | |
Convert a full string prompt to the list format expected by the processor. | |
In particular, image urls (as delimited by <fake_token_around_image>) should be their own elements. | |
From: | |
``` | |
[ | |
"bonjour<fake_token_around_image><image:IMG_URL><fake_token_around_image>hello", | |
PIL.Image.Image, | |
"Aurevoir", | |
] | |
``` | |
to: | |
``` | |
[ | |
"bonjour", | |
IMG_URL, | |
"hello", | |
PIL.Image.Image, | |
"Aurevoir", | |
] | |
``` | |
""" | |
print(f"******* isolate_images_urls *******") | |
print(f"params: prompt_list is - {prompt_list}") | |
linearized_list = [] | |
for prompt in prompt_list: | |
print(f"inside FOR loop: prompt in prompt_list is - {prompt}") | |
# Prompt can be either a string, or a PIL image | |
if isinstance(prompt, PIL.Image.Image): | |
print(f"inside first IF in FOR loop: prompt is of type PIL.Image.Image") | |
linearized_list.append(prompt) | |
print(f"linearized_list after append is - {linearized_list}") | |
elif isinstance(prompt, str) and "/tmp/gradio/" in prompt: #isinstance(prompt, PIL.Image.Image): | |
print(f"inside IF in FOR loop: prompt is a string and is a path for temporary file") | |
linearized_list.append(prompt) | |
print(f"linearized_list after append is - {linearized_list}") | |
elif isinstance(prompt, str) and "/tmp/gradio/" not in prompt: | |
print(f"inside ELIF in FOR loop: prompt is a string and is NOT a path for temporary file") | |
if "<fake_token_around_image>" not in prompt: | |
print(f"inside IF inside ELIF in FOR loop: '<fake_token_around_image>' is NOT in prompt") | |
linearized_list.append(prompt) | |
print(f"linearized_list after append is - {linearized_list}") | |
else: | |
print(f"inside ELSE inside ELIF in FOR loop: '<fake_token_around_image>' IS IN prompt") | |
prompt_splitted = prompt.split("<fake_token_around_image>") | |
print(f"prompt_splitted is - {prompt_splitted}") | |
for ps in prompt_splitted: | |
print(f"Inside FOR loop inside FOR loop: ps in prompt_split is {ps}") | |
if ps == "": | |
continue | |
if ps.startswith("<image:"): | |
linearized_list.append(ps[7:-1]) | |
else: | |
linearized_list.append(ps) | |
else: | |
raise TypeError( | |
f"Unrecognized type for `prompt`. Got {type(type(prompt))}. Was expecting something in [`str`," | |
" `PIL.Image.Image`]" | |
) | |
print(f"linearized_list to be returned is - {linearized_list}") | |
return linearized_list | |
# Chatbot handling utils | |
def handle_manual_images_in_user_prompt(user_prompt: str) -> List[Union[str, PIL.Image.Image]]: | |
""" | |
Handle the case of textually manually inputted images (i.e. the `<fake_token_around_image><image:IMG_URL><fake_token_around_image>`) in the user prompt | |
by fetching them and replacing the whole sub-sequence by a PIL image. | |
""" | |
if "<fake_token_around_image>" in user_prompt: | |
splitted_user_prompt = isolate_images_urls([user_prompt]) | |
resulting_user_prompt = [] | |
for up in splitted_user_prompt: | |
if is_url(up): | |
img = processor.image_processor.fetch_images([up])[0] | |
resulting_user_prompt.append(img) | |
else: | |
resulting_user_prompt.append(up) | |
return resulting_user_prompt | |
else: | |
return [user_prompt] | |
def user_prompt_list_to_markdown(user_prompt_list: List[Union[str, PIL.Image.Image]]): | |
""" | |
Convert a user prompt in the list format (i.e. elements are either a PIL image or a string) into | |
the markdown format that is used for the chatbot history and rendering. | |
""" | |
print("********** user_prompt_list_to_markdown *********") | |
print(f" param : user_prompt_list is - {user_prompt_list}") | |
resulting_string = "" | |
for elem in user_prompt_list: | |
print(f"inside user_prompt_list_to_markdown, for loop on user_prompt_list") | |
print(f"elem is - {elem} ") | |
if isinstance(elem, str) and "/tmp/gradio/" not in elem: | |
resulting_string += elem | |
print(f"inside IF - when elem is string and is not temp image filepath. resulting_string is - {resulting_string}") | |
#elif isinstance(elem, str) and "/tmp/gradio/" in elem: | |
# resulting_string += f"![](/file={convert_to_rgb(elem)})" #f"![](/file={image})" | |
# print(f"inside first ELIF - when elem is string and is the temp image filepath. resulting_string is - {resulting_string}") | |
elif isinstance(elem, PIL.Image.Image) or "/tmp/gradio/" in elem: #and "/tmp/gradio/" in elem: | |
resulting_string += f"![](/file={convert_to_rgb(elem)})" #pil_to_markdown_im(convert_to_rgb(elem)) | |
print(f"inside the ELIF - when elem is an instance of PIL.Image.Image or has /temp/file/path. resulting_string after pil_to_markdown_im() operation is - {resulting_string}") | |
else: | |
raise ValueError( | |
"Unknown type for `user_prompt_list`. Expected an element of type `str` or `PIL.Image.Image` and got" | |
f" `{type(elem)}`" | |
) | |
print(f" final resulting_string that will be returned is - {resulting_string}") | |
return resulting_string | |
def remove_spaces_around_token(text): | |
pattern = r'\s*(<fake_token_around_image>)\s*' | |
replacement = r'\1' | |
result = re.sub(pattern, replacement, text) | |
return result | |
# Model and generation utils | |
def load_processor_tokenizer_model(model_name): | |
processor = AutoProcessor.from_pretrained( | |
model_name, | |
token=os.getenv("HF_AUTH_TOKEN", True), | |
truncation_side="left", | |
) | |
tokenizer = processor.tokenizer | |
config = AutoConfig.from_pretrained(model_name, use_auth_token=os.getenv("HF_AUTH_TOKEN", True)) | |
max_memory_map = get_max_memory() | |
for key in max_memory_map.keys(): | |
if key != "cpu": | |
# Get this in GB | |
max_memory_map[key] = max_memory_map[key] // (1024 * 1024 * 1024) | |
# Decrease 2 for Pytorch overhead and 2 for the forward to be safe | |
max_memory_map[key] = f"{max_memory_map[key] - 4} GiB" | |
model = IdeficsForVisionText2Text.from_pretrained( | |
model_name, | |
token=os.getenv("HF_AUTH_TOKEN", True), | |
device_map="auto", | |
offload_folder="./offload", | |
torch_dtype=config.torch_dtype, | |
max_memory=max_memory_map, | |
) | |
model.eval() | |
print("Current device map:", model.hf_device_map) | |
print("Model default generation config:", model.generation_config) | |
# TODO: the device_map looks very inefficien right now. that could be improved | |
return processor, tokenizer, model | |
def format_user_prompt_with_im_history_and_system_conditioning( | |
current_user_prompt_str: str, current_image: Optional[PIL.Image.Image], history: List[Tuple[str, str]] | |
) -> List[Union[str, PIL.Image.Image]]: | |
""" | |
Produces the resulting list that needs to go inside the processor. | |
It handles the potential image box input, the history and the system conditionning. | |
""" | |
resulting_list = copy.deepcopy(SYSTEM_PROMPT) | |
# Format history | |
for turn in history: | |
user_utterance, assistant_utterance = turn | |
splitted_user_utterance = split_str_on_im_markdown(user_utterance) | |
splitted_user_utterance = [ | |
im_markdown_to_pil(s) if s.startswith('<img src="data:image/png;base64,') else s | |
for s in splitted_user_utterance | |
if s != "" | |
] | |
if isinstance(splitted_user_utterance[0], str): | |
resulting_list.append("\nUser: ") | |
else: | |
resulting_list.append("\nUser:") | |
resulting_list.extend(splitted_user_utterance) | |
resulting_list.append(f"<end_of_utterance>\nAssistant: {assistant_utterance}") | |
# Format current input | |
current_user_prompt_str = remove_spaces_around_token(current_user_prompt_str) | |
if current_image is None: | |
if "<img src=data:image/png;base64" in current_user_prompt_str: | |
raise ValueError("The UI does not support inputing via the text box an image in base64.") | |
current_user_prompt_list = handle_manual_images_in_user_prompt(current_user_prompt_str) | |
resulting_list.append("\nUser: ") | |
resulting_list.extend(current_user_prompt_list) | |
resulting_list.append("<end_of_utterance>\nAssistant:") | |
return resulting_list, current_user_prompt_list | |
else: | |
# Choosing to put the image first when the image is inputted through the UI, but this is an arbiratrary choice. | |
resulting_list.extend(["\nUser:", current_image, f"{current_user_prompt_str}<end_of_utterance>\nAssistant:"]) | |
return resulting_list, [current_user_prompt_str] | |
def model_generation( | |
prompt_list, | |
processor, | |
tokenizer, | |
model, | |
temperature, | |
no_repeat_ngram_size, | |
max_new_tokens, | |
min_length, | |
ban_tokens, | |
eos_tokens, | |
force_words, | |
repetition_penalty, | |
hide_special_tokens, | |
decoding_strategy, | |
num_beams, | |
length_penalty, | |
top_k, | |
top_p, | |
penalty_alpha, | |
): | |
input_args = processor( | |
isolate_images_urls(prompt_list), | |
truncation=True, | |
max_length=MAX_SEQ_LEN - max_new_tokens, | |
padding=True, | |
add_end_of_utterance_token=False, # Already taken care of inside the prompts, so bypassing the processor's handling of this token | |
) | |
for k, v in input_args.items(): | |
input_args[k] = v.to(0) | |
# Excluding some words from the generation | |
bad_words_ids = None | |
ban_tokens = ban_tokens.replace("\\n", "\n") | |
bad_words = ban_tokens.split(";") | |
if len(bad_words) > 0: | |
bad_words_ids = tokenizer(bad_words, add_special_tokens=False).input_ids | |
# Forcing some words in the generation | |
force_words_ids = None | |
if force_words != "": | |
force_words = force_words.replace("\\n", "\n") | |
force_words = force_words.split(";") | |
if len(force_words) > 0: | |
force_words_ids = tokenizer(force_words, add_special_tokens=False).input_ids | |
eos_token_ids = None | |
if eos_tokens != "": | |
eos_tokens = eos_tokens.replace("\\n", "\n") | |
eos_tokens = eos_tokens.split(";") | |
if len(eos_tokens) > 0: | |
eos_token_ids = [] | |
for eos_token in eos_tokens: | |
tokenized_eos_token = tokenizer.convert_tokens_to_ids(eos_token) | |
if tokenized_eos_token == 0: # <unk> with our llama tokenizer | |
raise ValueError(f"Unknown tokens specified for exit condition.") | |
eos_token_ids += [tokenized_eos_token] | |
# Common parameters to all decoding strategies | |
# This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies | |
generation_args = { | |
"no_repeat_ngram_size": no_repeat_ngram_size, | |
"max_new_tokens": max_new_tokens, | |
"min_length": min_length, | |
"bad_words_ids": bad_words_ids, | |
"force_words_ids": force_words_ids, | |
"repetition_penalty": repetition_penalty, | |
"eos_token_id": eos_token_ids, | |
} | |
assert decoding_strategy in [ | |
"Greedy", | |
"beam_search", | |
"beam_sampling", | |
"sampling_top_k", | |
"Top P Sampling", | |
"contrastive_sampling", | |
] | |
if decoding_strategy == "Greedy": | |
pass | |
elif decoding_strategy == "beam_search": | |
generation_args["num_beams"] = num_beams | |
generation_args["length_penalty"] = length_penalty | |
assert generation_args["num_beams"] > 1 | |
elif decoding_strategy == "beam_sampling": | |
generation_args["temperature"] = temperature | |
generation_args["num_beams"] = num_beams | |
generation_args["length_penalty"] = length_penalty | |
generation_args["do_sample"] = True | |
assert generation_args["num_beams"] > 1 | |
elif decoding_strategy == "sampling_top_k": | |
generation_args["temperature"] = temperature | |
generation_args["do_sample"] = True | |
generation_args["top_k"] = top_k | |
elif decoding_strategy == "Top P Sampling": | |
generation_args["temperature"] = temperature | |
generation_args["do_sample"] = True | |
generation_args["top_p"] = top_p | |
elif decoding_strategy == "contrastive_sampling": | |
generation_args["temperature"] = temperature | |
generation_args["do_sample"] = True | |
generation_args["penalty_alpha"] = penalty_alpha | |
generation_args["top_k"] = top_k | |
generated_tokens = model.generate( | |
**input_args, | |
**generation_args, | |
) | |
tokens = tokenizer.convert_ids_to_tokens(generated_tokens[0]) | |
decoded_skip_special_tokens = repr( | |
tokenizer.batch_decode(generated_tokens, skip_special_tokens=hide_special_tokens)[0] | |
) | |
actual_generated_tokens = generated_tokens[:, input_args["input_ids"].shape[-1] :] | |
first_end_token = len(actual_generated_tokens[0]) | |
actual_generated_tokens = actual_generated_tokens[:, :first_end_token] | |
generated_text = tokenizer.batch_decode(actual_generated_tokens, skip_special_tokens=hide_special_tokens)[0] | |
logger.info( | |
"Result: \n" | |
f"----Prompt: `{prompt_list}`\n" | |
f"----Tokens ids - prompt + generation: `{generated_tokens[0].tolist()}`\n" | |
f"----Tokens converted - prompt + generation: `{tokens}`\n" | |
f"----String decoded with skipped special tokens - prompt + generation: `{decoded_skip_special_tokens}`\n" | |
f"----Total length - prompt + generation `{len(generated_tokens[0].tolist())}`\n" | |
f"----Token ids - generation: `{actual_generated_tokens[0].tolist()}`\n" | |
f"----Tokens converted - generation: `{tokenizer.convert_ids_to_tokens(actual_generated_tokens[0])}`\n" | |
f"----String decoded with skipped special tokens - generation: `{generated_text}`\n" | |
f"----Total length - generation: `{len(actual_generated_tokens[0].tolist())}`\n" | |
f"----Generation mode: `{decoding_strategy}`\n" | |
f"----Generation parameters: `{generation_args}`\n" | |
) | |
return generated_text | |
dope_callback = gr.CSVLogger() | |
dope_hf_callback = gr.HuggingFaceDatasetSaver( | |
hf_token=os.getenv("HF_AUTH_TOKEN"), | |
dataset_name="HuggingFaceM4/gradio_dope_data_points", | |
private=True, | |
) | |
problematic_callback = gr.CSVLogger() | |
textbox = gr.Textbox( | |
show_label=False, | |
value="Describe the battle against the fierce dragons.", | |
visible=True, | |
container=False, | |
label="Text input", | |
) | |
with gr.Blocks(title="IDEFICS-Chat", theme=gr.themes.Base()) as demo: | |
gr.Markdown( | |
""" | |
# IDEFICS | |
This is a demo for [IDEFICS](https://huggingface.co/HuggingFaceM4/idefics-80b), a open-access large visual lanugage model built built solely on publicly available data and models. | |
<br>Like GPT-4, the multimodal model accepts arbitrary sequences of image and text inputs and produces text outputs. | |
<br>IDEFICS (which stans for **I**mage-aware **D**ecoder **E**nhanced à la **F**lamingo with **I**nterleaved **C**ross-attention**S**) is an open-access reproduction of [Flamingo](https://huggingface.co/papers/2204.14198), a closed-source visual language model developed by Deepmind. | |
The [model cards](https://huggingface.co/HuggingFaceM4/idefics-80b) and [dataset card](https://huggingface.co/datasets/HuggingFaceM4/OBELISC) provide plenty of information about the model and training data. | |
<br>We provide an [interactive visualization](https://atlas.nomic.ai/map/f2fba2aa-3647-4f49-a0f3-9347daeee499/ee4a84bd-f125-4bcc-a683-1b4e231cb10f) (TODO: change to official link when have it) that allows exploring the content of the training data. | |
<br>You can also [read more about](https://github.com/huggingface/m4-logs/blob/master/memos/README.md) some of the technical challenges encountered during training IDEFICS. | |
""" | |
) | |
with gr.Row(): | |
with gr.Column(scale=3): | |
with gr.Row(elem_id="model_selector_row"): | |
model_selector = gr.Dropdown( | |
choices=MODELS, | |
value="HuggingFaceM4/idefics-9b-instruct", | |
interactive=True, | |
show_label=False, | |
container=False, | |
label="Model" | |
) | |
processor, tokenizer, model = load_processor_tokenizer_model(model_selector.value) | |
imagebox = gr.Image(type="pil", label="Image input") | |
with gr.Accordion("Advanced parameters", open=False, visible=True) as parameter_row: | |
max_new_tokens = gr.Slider( | |
minimum=0, | |
maximum=2048, | |
value=512, | |
step=1, | |
interactive=True, | |
label="Maximum number of new tokens to generate", | |
) | |
min_length = gr.Slider( | |
minimum=0, | |
maximum=50, | |
value=0, | |
step=1, | |
interactive=True, | |
label="Minimum number of new tokens to generate", | |
) | |
repetition_penalty = gr.Slider( | |
minimum=0.0, | |
maximum=5.0, | |
value=1.0, | |
step=0.1, | |
interactive=True, | |
label="Repetition penalty", | |
info="1.0 means no penalty", | |
) | |
no_repeat_ngram_size = gr.Slider( | |
minimum=0, | |
maximum=10, | |
value=0, | |
step=1, | |
interactive=True, | |
label="N-gram repetition threshold", | |
info="If set to int > 0, all ngrams of that size can only occur once.", | |
) | |
decoding_strategy = gr.Radio( | |
[ | |
"Greedy", | |
# "beam_search", | |
# "beam_sampling", | |
# "sampling_top_k", | |
"Top P Sampling", | |
], | |
value="Top P Sampling", | |
label="Decoding strategy", | |
interactive=True, | |
) | |
temperature = gr.Slider( | |
minimum=0.0, | |
maximum=5.0, | |
value=1.2, | |
step=0.1, | |
interactive=True, | |
label="Sampling temperature", | |
) | |
decoding_strategy.change( | |
fn=lambda selection: gr.Slider.update( | |
visible=( | |
selection in ["contrastive_sampling", "beam_sampling", "Top P Sampling", "sampling_top_k"] | |
) | |
), | |
inputs=decoding_strategy, | |
outputs=temperature, | |
) | |
num_beams = gr.Slider( | |
minimum=0, | |
maximum=20, | |
value=3.0, | |
step=1.0, | |
interactive=True, | |
visible=False, | |
label="Number of beams", | |
info="Only used if `decoding_strategy` is `beam_search` or `beam_sampling`.", | |
) | |
decoding_strategy.change( | |
fn=lambda selection: gr.Slider.update(visible=(selection in ["beam_search", "beam_sampling"])), | |
inputs=decoding_strategy, | |
outputs=num_beams, | |
) | |
top_p = gr.Slider( | |
minimum=0.0, | |
maximum=1.0, | |
value=0.8, | |
step=0.01, | |
interactive=True, | |
visible=True, | |
label="Top P", | |
info=( | |
"If set to float < 1, only the smallest set of most probable tokens with probabilities that" | |
" add up to top_p or higher are kept for generation." | |
), | |
) | |
decoding_strategy.change( | |
fn=lambda selection: gr.Slider.update(visible=(selection in ["Top P Sampling"])), | |
inputs=decoding_strategy, | |
outputs=top_p, | |
) | |
top_k = gr.Slider( | |
minimum=0, | |
maximum=500, | |
value=50, | |
step=1, | |
interactive=True, | |
visible=False, | |
label="Top K", | |
info="The number of highest probability vocabulary tokens to keep for top-k-filtering.", | |
) | |
decoding_strategy.change( | |
fn=lambda selection: gr.Slider.update(visible=(selection in ["sampling_top_k"])), | |
inputs=decoding_strategy, | |
outputs=top_k, | |
) | |
length_penalty = gr.Slider( | |
minimum=-1000.0, | |
maximum=1000.0, | |
value=1.0, | |
step=0.1, | |
interactive=True, | |
visible=False, | |
label="Length penalty", | |
info=( | |
"length_penalty > 0.0 promotes longer sequences, while length_penalty < 0.0 encourages shorter" | |
" sequences. Only used if `decoding_strategy` is `beam_search` or `beam_sampling`." | |
), | |
) | |
decoding_strategy.change( | |
fn=lambda selection: gr.Slider.update(visible=(selection in ["beam_search", "beam_sampling"])), | |
inputs=decoding_strategy, | |
outputs=length_penalty, | |
) | |
penalty_alpha = gr.Slider( | |
minimum=0.0, | |
maximum=5.0, | |
value=0.95, | |
step=0.05, | |
interactive=True, | |
visible=False, | |
label="Penalty alpha", | |
info="Only used if `decoding_strategy` is `contrastive_sampling`.", | |
) | |
decoding_strategy.change( | |
fn=lambda selection: gr.Slider.update(visible=(selection in ["contrastive_sampling"])), | |
inputs=decoding_strategy, | |
outputs=penalty_alpha, | |
) | |
with gr.Column(scale=6): | |
def prefetch_images_in_history(user_prompt_str): | |
""" | |
Pre-fetch the images that are passed in the chatbot default history. | |
""" | |
return user_prompt_list_to_markdown(handle_manual_images_in_user_prompt(user_prompt_str)) | |
chatbot = gr.Chatbot( | |
elem_id="chatbot", | |
label="ChatIDEFICS", | |
visible=True, | |
height=550, | |
value=[ | |
[ | |
( | |
prefetch_images_in_history( | |
"""Write a funny story including the following characters. | |
There should be drama and most importantly romance. | |
Character 1:<fake_token_around_image><image:https://m.media-amazon.com/images/M/MV5BODg1OTczMWEtNTU3MS00OTUzLThjODEtNDg1MWQwZmExYmFlXkEyXkFqcGdeQWFybm8@._V1_QL75_UX500_CR0,0,500,281_.jpg><fake_token_around_image> | |
Character 2:<fake_token_around_image><image:https://static.wikia.nocookie.net/dreamworks/images/0/09/Shrek_dreamworks.png/revision/latest?cb=20170921225439><fake_token_around_image> | |
Character 3:<fake_token_around_image><image:https://upload.wikimedia.org/wikipedia/en/e/ef/Marsupilami_1.jpg><fake_token_around_image> | |
The plot should take place in the world pictured here:<fake_token_around_image><image:https://www.astronomy.com/wp-content/uploads/sites/2/2021/09/ON1.jpg><fake_token_around_image>""" | |
) | |
), | |
( | |
"""Once upon a time, in a world where the sky was a dome and the ground was covered in grass, there lived a beautiful princess named Mulan. She was kind, brave, and always ready to help others. One day, while walking through the forest, she stumbled upon a strange creature. It was a green ogre named Shrek, who was lost and looking for his way back home. | |
Mulan, being the kind-hearted person she was, decided to help Shrek find his way back. As they traveled together, they began to develop a strong bond. Shrek was impressed by Mulan's bravery and determination, while Mulan admired Shrek's loyalty and sense of humor. | |
However, their journey was not without obstacles. They encountered a mischievous cat named Hoboua, who was always causing trouble and getting into fights. Despite his troublemaking ways, Hoboua had a good heart and eventually became a valuable ally to Mulan and Shrek. | |
As they traveled, they faced many challenges, including battling fierce dragons and navigating treacherous mountains. Through it all, Mulan and Shrek grew closer, and their feelings for each other deepened. | |
Finally, they reached Shrek's home, and he was reunited with his family and friends. Mulan, however, was sad to leave him behind. But Shrek had a surprise for her. He had fallen in love with her and wanted to be with her forever. | |
Mulan was overjoyed, and they shared a passionate kiss. From that day on, they lived happily ever after, exploring the world together and facing any challenges that came their way. | |
And so, the story of Mulan and Shrek's romance came to an end, leaving a lasting impression on all who heard it.""" | |
), | |
], | |
], | |
) | |
with gr.Row(): | |
with gr.Column(scale=8): | |
textbox.render() | |
with gr.Column(scale=1, min_width=60): | |
submit_btn = gr.Button(value="Submit", visible=True) | |
with gr.Column(scale=1, min_width=20): | |
clear_btn = gr.ClearButton([textbox, chatbot]) | |
with gr.Column(scale=1, min_width=15): | |
dope_bttn = gr.Button("Dope🔥") | |
with gr.Column(scale=1, min_width=15): | |
problematic_bttn = gr.Button("Problematic😬") | |
def model_inference( | |
user_prompt_str, | |
chat_history, | |
image, | |
decoding_strategy, | |
num_beams, | |
temperature, | |
no_repeat_ngram_size, | |
max_new_tokens, | |
min_length, | |
repetition_penalty, | |
length_penalty, | |
top_k, | |
top_p, | |
penalty_alpha, | |
): | |
# global processor, model, tokenizer | |
force_words = "" | |
hide_special_tokens = False | |
formated_prompt_list, user_prompt_list = format_user_prompt_with_im_history_and_system_conditioning( | |
current_user_prompt_str=user_prompt_str.strip(), | |
current_image=image, | |
history=chat_history, | |
) | |
generated_text = model_generation( | |
prompt_list=formated_prompt_list, | |
processor=processor, | |
tokenizer=tokenizer, | |
model=model, | |
temperature=temperature, | |
no_repeat_ngram_size=no_repeat_ngram_size, | |
max_new_tokens=max_new_tokens, | |
min_length=min_length, | |
ban_tokens=BAN_TOKENS, | |
eos_tokens=EOS_TOKENS, | |
force_words=force_words, | |
repetition_penalty=repetition_penalty, | |
hide_special_tokens=hide_special_tokens, | |
decoding_strategy=decoding_strategy, | |
num_beams=num_beams, | |
length_penalty=length_penalty, | |
top_k=top_k, | |
top_p=top_p, | |
penalty_alpha=penalty_alpha, | |
) | |
if image is None: | |
# Case where there is no image OR the image is passed as `<fake_token_around_image><image:IMAGE_URL><fake_token_around_image>` | |
chat_history.append( | |
(user_prompt_list_to_markdown(user_prompt_list), generated_text.strip("<end_of_utterance>")) | |
) | |
else: | |
# Case where the image is passed through the Image Box. | |
# Convert the image into base64 for both passing it through the chat history and | |
# displaying the image inside the same bubble as the text. | |
chat_history.append( | |
( | |
f"{user_prompt_list_to_markdown([image] + user_prompt_list)}", | |
generated_text.strip("<end_of_utterance>"), | |
) | |
) | |
return "", None, chat_history | |
def process_example(message, image): | |
clear_msg, image_value, chat = model_inference( | |
user_prompt_str=message, | |
chat_history=[], | |
image=image, | |
decoding_strategy="Greedy", | |
num_beams=None, | |
temperature=None, | |
no_repeat_ngram_size=None, | |
max_new_tokens=512, | |
min_length=16, | |
repetition_penalty=None, | |
length_penalty=None, | |
top_k=None, | |
top_p=0.95, | |
penalty_alpha=None, | |
) | |
return clear_msg, image_value, chat | |
textbox.submit( | |
fn=model_inference, | |
inputs=[ | |
textbox, | |
chatbot, | |
imagebox, | |
decoding_strategy, | |
num_beams, | |
temperature, | |
no_repeat_ngram_size, | |
max_new_tokens, | |
min_length, | |
repetition_penalty, | |
length_penalty, | |
top_k, | |
top_p, | |
penalty_alpha, | |
], | |
outputs=[textbox, imagebox, chatbot], | |
) | |
submit_btn.click( | |
fn=model_inference, | |
inputs=[ | |
textbox, | |
chatbot, | |
imagebox, | |
decoding_strategy, | |
num_beams, | |
temperature, | |
no_repeat_ngram_size, | |
max_new_tokens, | |
min_length, | |
repetition_penalty, | |
length_penalty, | |
top_k, | |
top_p, | |
penalty_alpha, | |
], | |
outputs=[ | |
textbox, | |
imagebox, | |
chatbot, | |
], | |
) | |
# Using Flagging for saving dope and problematic examples | |
# Dope examples flagging | |
dope_hf_callback.setup( | |
[ | |
model_selector, | |
textbox, | |
chatbot, | |
imagebox, | |
decoding_strategy, | |
num_beams, | |
temperature, | |
no_repeat_ngram_size, | |
max_new_tokens, | |
min_length, | |
repetition_penalty, | |
length_penalty, | |
top_k, | |
top_p, | |
penalty_alpha, | |
], | |
"gradio_dope_data_points" | |
) | |
dope_bttn.click( | |
lambda *args: dope_hf_callback.flag(args), | |
[ | |
model_selector, | |
textbox, | |
chatbot, | |
imagebox, | |
decoding_strategy, | |
num_beams, | |
temperature, | |
no_repeat_ngram_size, | |
max_new_tokens, | |
min_length, | |
repetition_penalty, | |
length_penalty, | |
top_k, | |
top_p, | |
penalty_alpha, | |
], | |
None, | |
preprocess=False | |
) | |
# Problematic examples flagging | |
problematic_callback.setup( | |
[ | |
model_selector, | |
textbox, | |
chatbot, | |
imagebox, | |
decoding_strategy, | |
num_beams, | |
temperature, | |
no_repeat_ngram_size, | |
max_new_tokens, | |
min_length, | |
repetition_penalty, | |
length_penalty, | |
top_k, | |
top_p, | |
penalty_alpha, | |
], | |
"gradio_problematic_data_points" | |
) | |
problematic_bttn.click( | |
lambda *args: problematic_callback.flag(args), | |
[ | |
model_selector, | |
textbox, | |
chatbot, | |
imagebox, | |
decoding_strategy, | |
num_beams, | |
temperature, | |
no_repeat_ngram_size, | |
max_new_tokens, | |
min_length, | |
repetition_penalty, | |
length_penalty, | |
top_k, | |
top_p, | |
penalty_alpha, | |
], | |
None, | |
preprocess=False | |
) | |
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.""" | |
) | |
examples_path = os.path.dirname(__file__) | |
gr.Examples( | |
examples=[ | |
["What are the armed baguettes guarding?", f"{examples_path}/example_images/baguettes_guarding_paris.png"], | |
# [ | |
# "Can you tell me a very short story based on this image?", | |
# f"{examples_path}/example_images/chicken_on_money.png", | |
# ], | |
# ["Can you describe the image?", f"{examples_path}/example_images/bear_costume.png"], | |
# ["What is this animal and why is it unusual?", f"{examples_path}/example_images/blue_dog.png"], | |
# [ | |
# "What is this object and do you think it is horrifying?", | |
# f"{examples_path}/example_images/can_horror.png", | |
# ], | |
# ["What is this sketch for? How would you make an argument to prove this sketch was made by Picasso himself?", f"{examples_path}/example_images/cat_sketch.png"], | |
# ["Which celebrity does this claymation figure look like?", f"{examples_path}/example_images/kanye.jpg"], | |
# [ | |
# "Which famous person does the person in the image look like? Could you craft an engaging narrative featuring this character from the image as the main protagonist?", | |
# f"{examples_path}/example_images/obama-harry-potter.jpg", | |
# ], | |
# [ | |
# "Is there a celebrity look-alike in this image? What is happening to the person?", | |
# f"{examples_path}/example_images/ryan-reynolds-borg.jpg", | |
# ], | |
# ["Can you describe this image in details please?", f"{examples_path}/example_images/dragons_playing.png"], | |
# ["What can you tell me about the cap in this image?", f"{examples_path}/example_images/ironman_cap.png"], | |
# [ | |
# "Can you write an advertisement for Coca-Cola based on this image?", | |
# f"{examples_path}/example_images/polar_bear_coke.png", | |
# ], | |
# [ | |
# "What is the rabbit doing in this image? Do you think this image is real?", | |
# f"{examples_path}/example_images/rabbit_force.png", | |
# ], | |
# ["What is happening in this image and why is it unusual?", f"{examples_path}/example_images/ramen.png"], | |
# [ | |
# "What I should look most forward to when I visit this place?", | |
# f"{examples_path}/example_images/tree_fortress.jpg", | |
# ], | |
# ["Who is the person in the image and what is he doing?", f"{examples_path}/example_images/tom-cruise-astronaut-pegasus.jpg"], | |
# [ | |
# "What is happening in this image? Which famous personality does this person in center looks like?", | |
# f"{examples_path}/example_images/gandhi_selfie.jpg", | |
# ], | |
# [ | |
# ( | |
# "<fake_token_around_image><image:https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/stable-diffusion-xl-coreml/a_high_quality_photo_of_a_surfing_dog.7667.final_float16_original.jpg><fake_token_around_image>What" | |
# " do you think the dog is doing and is it unusual?" | |
# ), | |
# None, | |
# ], | |
], | |
inputs=[textbox, imagebox], | |
outputs=[textbox, imagebox, chatbot], | |
fn=process_example, | |
cache_examples=True, | |
examples_per_page=5, | |
label="Click on any example below to get started", | |
) | |
demo.queue() | |
demo.launch(share=False) | |