import os import gradio as gr import requests models = [ "HuggingFaceM4/tr_209_ift_mixture_opt_step-14000" ] SYSTEM_PROMPT = """The following is a conversation between a highly knowledgeable and intelligent 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 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: User:Describe this image. Assistant: Five kittens are standing together in the center of the photograph. From the left to right, there is one orange kitte, 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. User:How about this image?Can you describe it too? Assistant: 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. User: What kind of breed is it? Assistant: 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. User: What can you tell me about this breed of dogs? Assistant: 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. User: ghjkhjabnufs Assistant: That doesn’t seem to be a word. Could you ask me another way? User: Do you like Cavalier King Charles Spaniel? Assistant: 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. User: How many dogs do you see in this image? Assistant: There is no dogs in this image. The picture shows a tennis player jumping to volley the ball.""" BAN_TOKENS = ";" EOS_TOKENS = ";User" from accelerate.utils import get_max_memory from transformers import AutoTokenizer from m4.models.vllama.configuration_vllama import VLlamaConfig from m4.models.vllama.modeling_vllama import VLlamaForCausalLM import logging from PIL import Image from io import BytesIO from m4.training.packing import image_attention_mask_for_packed_input_ids, incremental_to_binary_attention_mask from m4.training.utils import build_image_transform import torch import re TOKENIZER_FAST = True MAX_SEQ_LEN = 1024 logging.basicConfig(level=logging.INFO) logger = logging.getLogger() def load_tokenizer_model(model_name): tokenizer = AutoTokenizer.from_pretrained( model_name, use_fast=TOKENIZER_FAST, use_auth_token=os.getenv("HF_AUTH_TOKEN", True), # `use_fast=False` for 1B3 OPT, True for all the other models ) tokenizer.padding_side = "left" config = VLlamaConfig.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 = VLlamaForCausalLM.from_pretrained( model_name, use_auth_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 tokenizer, model def fetch_images(url_images): images = [] for url in url_images: if isinstance(url, str): images.append(Image.open(BytesIO(requests.get(url, stream=True).content))) else: images.append(url) return images def model_generation( prompt, images, 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, ): # Preparing inputs tokens = tokenizer( [prompt], truncation=True, max_length=MAX_SEQ_LEN, padding=True, add_special_tokens=False, ) input_ids = torch.tensor([[tokenizer.bos_token_id] + tokens.input_ids[0]]) attention_mask = torch.tensor([[1] + tokens.attention_mask[0]]) image_attention_mask = [ incremental_to_binary_attention_mask( image_attention_mask_for_packed_input_ids(input_ids[0].unsqueeze(0), tokenizer)[0], num_classes=len(images) ) ] image_transform = build_image_transform(eval=True) pixel_values = [torch.stack([image_transform(img) for img in images])] input_ids = input_ids.to(0) attention_mask = attention_mask.to(0) pixel_values = torch.stack(pixel_values).to(0) image_attention_mask = torch.cat(image_attention_mask, 0).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(eos_token, add_special_tokens=False).input_ids if len(tokenized_eos_token) > 1: raise ValueError( f"eos_tokens should be one token, here {eos_token} is {len(tokenized_eos_token)} tokens:" f" {tokenized_eos_token}" ) eos_token_ids += tokenized_eos_token # Inputs input_args = { "input_ids": input_ids, "attention_mask": attention_mask, "pixel_values": pixel_values, "image_attention_mask": image_attention_mask, } # Common parameters to all decoding strategies # This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies generation_args = { "temperature": temperature, "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", "sampling_top_p", "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["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["do_sample"] = True generation_args["top_k"] = top_k elif decoding_strategy == "sampling_top_p": generation_args["do_sample"] = True generation_args["top_p"] = top_p elif decoding_strategy == "contrastive_sampling": 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_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}`\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"----Token ids - generation: `{actual_generated_tokens[0].tolist()}`" f"----Tokens converted - generation: `{tokenizer.convert_ids_to_tokens(actual_generated_tokens[0])}`" f"----String decoded with skipped special tokens - generation: `{generated_text}`\n" f"----Generation mode: `{decoding_strategy}`\n" f"----Generation parameters: `{generation_args}`\n" ) return generated_text textbox = gr.Textbox( show_label=False, value="Describe all of the parts of this image.", placeholder="To input images, use the following syntax: `textexttext`", visible=True, container=False ) with gr.Blocks(title="LLaVA", theme=gr.themes.Base()) as demo: # state = gr.State() with gr.Row(): with gr.Column(scale=3): with gr.Row(elem_id="model_selector_row"): model_selector = gr.Dropdown( choices=models, value=models[0] if len(models) > 0 else "", interactive=True, show_label=False, container=False) tokenizer, model = load_tokenizer_model(model_selector.value) imagebox = gr.Image(type="pil", label="Image input - This image box is not supported yet! To include images, do through the text by adding ``. The backend takes care of parsing that and download the correponding image. That way, you can technically interleave as many images and texts as you want. No need to add space before and after ``") with gr.Accordion("Parameters", open=False, visible=True) as parameter_row: temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.2, step=0.1, interactive=True, label="Temperature",) top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",) max_output_tokens = gr.Slider(minimum=0, maximum=1024, value=512, step=64, interactive=True, label="Max output tokens",) with gr.Column(scale=6): chatbot = gr.Chatbot( elem_id="chatbot", label="Idefics Chatbot", visible=True, height=550, value=[ [ "Where can we typically find animals like this one?", "Animals like the one in the image, which is a llama, can typically be found in rural areas, such as farms or ranches. Llamas are often used as pack animals in mountainous regions, as they are well-adapted to the challenging terrain and can carry heavy loads. They are also valued for their wool, which is used to make clothing and other textiles. In addition, llamas are sometimes kept as pets or for their therapeutic benefits, as they are known to be calm and gentle animals." ], [ "How many of these animals can we fit into an engine like that?", "The image shows a helicopter with a large engine, but it is not possible to determine the exact number of animals that can fit into it based on the image alone. The size and capacity of the helicopter's engine would depend on various factors, such as the size of the animals, the weight of the animals, and the size of the helicopter itself. However, it is safe to assume that the helicopter is designed to carry a limited number of animals, and it is not intended to be used as a means of transporting large groups of animals." ] ] ) 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]) cur_dir = os.path.dirname(os.path.abspath(__file__)) # gr.Examples(examples=[ # [f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image?"], # [f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"], # ], inputs=[textbox]) # gr.Examples( # examples=[ # [ # ("How many of these animals can we fit into an engine like that?", "The image shows a helicopter with a large engine, but it is not possible to determine the exact number of animals that can fit into it based on the image alone. The size and capacity of the helicopter's engine would depend on various factors, such as the size of the animals, the weight of the animals, and the size of the helicopter itself. However, it is safe to assume that the helicopter is designed to carry a limited number of animals, and it is not intended to be used as a means of transporting large groups of animals."), # ], # ], # inputs = [chatbot] # ) def format_prompt_with_history_and_system_conditioning(current_user_prompt, history): resulting_text = SYSTEM_PROMPT for turn in history: user_utterance, assistant_utterance = turn resulting_text += f"\nUser:{user_utterance}\nAssistant:{assistant_utterance}" resulting_text += f"\nUser:{current_user_prompt}\nAssistant:" return resulting_text def model_inference( user_prompt, chat_history, ): global model, tokenizer temperature = 1.0 no_repeat_ngram_size = 0 max_new_tokens = 256 min_length = 16 force_words = "" repetition_penalty = 1.0 hide_special_tokens = False decoding_strategy = "greedy" num_beams = 3 length_penalty = 1. top_k = 50, top_p = 0.95 penalty_alpha = 0.95 formated_prompt = format_prompt_with_history_and_system_conditioning( current_user_prompt=user_prompt.strip(), history=chat_history, ) url_images = re.findall(r"", formated_prompt) for idx, url_image in enumerate(url_images): formated_prompt = formated_prompt.replace(url_image, "") url_images[idx] = url_images[idx][1:] images = fetch_images(url_images) generated_text = model_generation( prompt=formated_prompt, images=images, 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, ) chat_history.append((user_prompt, generated_text.strip())) return "", chat_history textbox.submit( fn=model_inference, inputs=[textbox, chatbot], outputs=[textbox, chatbot], ) submit_btn.click( fn=model_inference, inputs=[textbox, chatbot], outputs=[textbox, chatbot], ) demo.queue() demo.launch(share=True)