Most long context LLMs can only work in text-only mode, long-llava-qwen2-7b is a open source large-Context Multimodal LLM and can perform language, image, and video understanding. In stead of proposing a new model archiecture, we extended llava to support make it support long context in a multimodal setting (i.e., multiple images, short and long videos). long-llava-qwen2-7b was fine-tuned from Qwen2-7B-Instruct.
1. Visual Needle In A Haystack - Pressure Testing LLMs
Visual Needle-In-A-Haystack (V-NIAH), a purely synthetic long vision benchmark inspired by the language model's NIAH test. The test designed 5 video question-answering problems as the needle and inserted each as a single frame into hours-long videos. We sampled the videos at 1 FPS as the visual input. The image of the needle is sourced from existing VQA benchmarks or AI-generated to avoid any contamination. The AI-generated images and questions are purposely chosen to be "counterfactual"
or "counter-commonsense", ensuring the model cannot answer based on language knowledge alone. Each question includes a "locating prompt" so that a capable system or human can locate the needle frame from the video haystack and answer the question.
V-NIAH
The horizontal axis depicts the cumulative frames constituting the video haystack. The vertical axis indicates the positioning of the needle image within that sequence. For example, a frame depth of 0% would situate the needle image at the outset of the video. The black dotted line signifies the training duration of the backbone language model, with each frame comprising 576 tokens.
long-llava-qwen2-7b scored averagely ~88.0% on this NIAH benchmark across different numbers of frame depths and frames shown in this plot.
MME is a comprehensive evaluation benchmark for multimodal large language models. It measures both perception and cognition abilities on a total of 14 subtasks, including existence, count, position, color, poster, celebrity, scene, landmark, artwork, OCR, commonsense reasoning, numerical calculation, text translation, and code reasoning. long-llava-qwen2-7b achieves SOTAs on both perception and cognition evaluation.
Video-MME, the first-ever full-spectrum, Multi-Modal Evaluation benchmark of MLLMs in Video analysis.It covers a wide range of short videos (< 2min), Medium Video (4min ~ 15min), long video (30min ~ 60min). 900 videos with a total of 254 hours are manually selected and annotated by repeatedly viewing all the video content, resulting in 2,700 question-answer pairs. Also, subtitles are also provided with the video for evaluation.
long-llava-qwen2-7b scored a overall 57.1% with subtitles and 52.9% with as shown in this table (adapted from the VideoMME Leaderboard), which makes it the SOTA for 7B models.
This example demonstrates long_llava_qwen2_7b's long context capability by understanding both images and videos. This can be useful for onboarding new developers.
demo
Run the Demo on your local machine (Mininum Requriement: g5.4xlarge is recommended.)
To get started, please follow the instructions as below:
And then open your broswer at http://localhost:6006 or https://xxxxxxxxxxxx.gradio.live if share=Ture is enabled in local_demo/multimodal_chat.py.
How to use the model from Python Code (HuggingFace transformers)
First, make sure to have transformers >= 4.42.0.
The model supports multi-image and multi-prompt generation. Meaning that you can pass multiple images in your prompt.
1from transformers import pipeline
2from PIL import Image
3import requests
45model_id ="aws-prototyping/long-llava-qwen2-7b"6pipe = pipeline("image-to-text", model=model_id)7url ="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"8image = Image.open(requests.get(url, stream=True).raw)910# Define a chat histiry and use `apply_chat_template` to get correctly formatted prompt11# Each value in "content" has to be a list of dicts with types ("text", "image") 12conversation =[13{1415"role":"user",16"content":[17{"type":"text","text":"What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud"},18{"type":"image"},19],20},21]22prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)2324outputs = pipe(image, prompt=prompt, generate_kwargs={"max_new_tokens":200})25print(outputs)26>>>{"generated_text":"\nUSER: What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud\nASSISTANT: Lava"}
Using pure transformers:
Below is an example script to run generation in float16 precision on a GPU device:
python
1import requests
2from PIL import Image
34import torch
5from transformers import AutoProcessor, LlavaForConditionalGeneration
67model_id ="aws-prototyping/long-llava-qwen2-7b"8model = LlavaForConditionalGeneration.from_pretrained(9 model_id,10 torch_dtype=torch.bfloat16,11 low_cpu_mem_usage=True,12).to(0)1314processor = AutoProcessor.from_pretrained(model_id)1516# Define a chat histiry and use `apply_chat_template` to get correctly formatted prompt17# Each value in "content" has to be a list of dicts with types ("text", "image") 18conversation =[19{2021"role":"user",22"content":[23{"type":"text","text":"What are these?"},24{"type":"image"},25],26},27]28prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)2930image_file ="http://images.cocodataset.org/val2017/000000039769.jpg"31raw_image = Image.open(requests.get(image_file, stream=True).raw)32inputs = processor(images=raw_image, text=prompt, return_tensors='pt').to(0, torch.float16)3334output = model.generate(**inputs, max_new_tokens=200, do_sample=False)35print(processor.decode(output[0][2:], skip_special_tokens=True))
Model optimization
4-bit quantization through bitsandbytes library
First make sure to install bitsandbytes, pip install bitsandbytes and make sure to have access to a CUDA compatible GPU device. Simply change the snippet above with:
Use Flash-Attention 2 to further speed-up generation
First make sure to install flash-attn. Refer to the original repository of Flash Attention regarding that package installation. Simply change the snippet above with:
Important Note - Currently vLLM serving only supports single image inference. The support of multiple images as input is on the roadmap, and please refer Multi-modality Support Refactoring for details.
Run the client
python
1import base64
23import requests
4from openai import OpenAI
56# Modify OpenAI's API key and API base to use vLLM's API server.7openai_api_key ="EMPTY"8openai_api_base ="http://localhost:8000/v1"910client = OpenAI(11# defaults to os.environ.get("OPENAI_API_KEY")12 api_key=openai_api_key,13 base_url=openai_api_base,14)1516models = client.models.list()17model = models.data[0].id1819image_url ="https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"2021# Use image url in the payload22chat_completion_from_url = client.chat.completions.create(23 messages=[{24"role":25"user",26"content":[27{28"type":"text",29"text":"What’s in this image?"30},31{32"type":"image_url",33"image_url":{34"url": image_url
35},36},37],38}],39 model=model,40 max_tokens=64,41)4243result = chat_completion_from_url.choices[0].message.content
44print(f"Chat completion output:{result}")454647# Use base64 encoded image in the payload48defencode_image_base64_from_url(image_url:str)->str:49"""Encode an image retrieved from a remote url to base64 format."""5051with requests.get(image_url)as response:52 response.raise_for_status()53 result = base64.b64encode(response.content).decode('utf-8')5455return result
565758image_base64 = encode_image_base64_from_url(image_url=image_url)59chat_completion_from_base64 = client.chat.completions.create(60 messages=[{61"role":62"user",63"content":[64{65"type":"text",66"text":"What’s in this image?"67},68{69"type":"image_url",70"image_url":{71"url":f"data:image/jpeg;base64,{image_base64}"72},73},74],75}],76 model=model,77 max_tokens=64,78)7980result = chat_completion_from_base64.choices[0].message.content
81print(f"Chat completion output:{result}")
Before using the long-llava-qwen2-7b model, it is important to perform your own independent assessment, and take measures to ensure that your use would comply with your own specific quality control practices and standards, and that your use would comply with the local rules, laws, regulations, licenses and terms that apply to you, and your content.
Citation
If you find our work helpful, feel free to give us a cite.
@misc{long-llava-qwen2-7b-2024,
author = { {Yin Song and Chen Wu and Eden Duthie} },
title = { {aws-prototyping/long-llava-qwen2-7b} },
year = 2024,
url = { https://huggingface.co/aws-prototyping/long-llava-qwen2-7b },
publisher = { Hugging Face }
}