yinsong1986 commited on
Commit
a0aee3d
1 Parent(s): 45ced03

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +318 -3
README.md CHANGED
@@ -1,3 +1,318 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ inference: false
4
+ ---
5
+
6
+ # long-llava-qwen2-7b Model
7
+
8
+ 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](https://github.com/huggingface/transformers/tree/main/src/transformers/models/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](https://huggingface.co/Qwen/Qwen2-7B-Instruct).
9
+
10
+ ## Model Details
11
+
12
+ - **Developed by:** [AWS Contributors](https://github.com/orgs/aws-samples/teams/aws-prototype-ml-apac)
13
+ - **Model type:** llava
14
+ - **Supported languages**: 27 additional languages besides English and Chinese
15
+ - Western Europe: German, French, Spanish, Portuguese, Italian, Dutch
16
+ - Eastern & Central Europe: Russian, Czech, Polish
17
+ - Middle East: Arabic, Persian, Hebrew, Turkish
18
+ - Eastern Asia: Japanese, Korean
19
+ - South-Eastern Asia: Vietnamese, Thai, Indonesian, Malay, Lao, Burmese, Cebuano, Khmer, Tagalog
20
+ - Southern Asia: Hindi, Bengali, Urdu
21
+ - **Finetuned from weights:** [Qwen2-7B-Instruct](https://huggingface.co/Qwen/Qwen2-7B-Instruct)
22
+ - **Supported Serving Framework:**
23
+ - [HuggingFace transformers](https://huggingface.co/docs/transformers/index)
24
+ - [vLLM](https://github.com/vllm-project/vllm)
25
+ - [Large Model Inference (LMI) container on SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/large-model-inference-container-docs.html)
26
+ - **Model License:** Apache 2.0
27
+ - **Contact:** [GitHub issues](https://github.com/awslabs/extending-the-context-length-of-open-source-llms/issues)
28
+ - **Inference Code** [Github Repo](https://github.com/awslabs/extending-the-context-length-of-open-source-llms/blob/main/long-llava-qwen2-7b/)
29
+
30
+
31
+ ## Evaluations
32
+
33
+ **[1. Visual Needle In A Haystack - Pressure Testing LLMs](https://huggingface.co/datasets/lmms-lab/v_niah_needles)**
34
+ 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"
35
+ 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.
36
+
37
+ ![V-NIAH](images/v-niah-long-llava-qwen2-7b.png)
38
+
39
+ 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.
40
+
41
+ `long-llava-qwen2-7b` scored averagely `~88.0%` on this NIAH benchmark across different numbers of frame depths and frames shown in this plot.
42
+
43
+ **[2. MME: A Comprehensive Evaluation Benchmark for Image Understanding](https://github.com/BradyFU/Awesome-Multimodal-Large-Language-Models/tree/Evaluation)**
44
+
45
+ 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.
46
+
47
+ | Models | mme_cognition_score | mme_percetion_score |
48
+ |--------------------|----------------------|---------------------|
49
+ |**long_llava_qwen2_7b** | **350** | **1494.64386**|
50
+ |[llava_1.5_7b_hf](https://huggingface.co/llava-hf/llava-1.5-7b-hf) | 326.42857 |1492.13225 |
51
+
52
+
53
+ **[3. VideoMME: Comprehensive Evaluation Benchmark of Multi-modal LLMs in Video Understanding](https://video-mme.github.io/home_page.html)**
54
+
55
+ 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.
56
+
57
+ `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](https://video-mme.github.io/home_page.html)*), which makes it the SOTA for `7B` models.
58
+
59
+ | Models | LLM Params | Overall (%) - w/o subs | Overall (%) - w subs |
60
+ |--------------------|------------|-------------------------|------------------------|
61
+ |**long_llava_qwen2_7b** | 7B | **52.9** | **57.1** |
62
+ |[LongVA](https://github.com/EvolvingLMMs-Lab/LongVA) | 7B | 52.6 | 54.3 |
63
+ |[VideoLLaMA 2](https://github.com/DAMO-NLP-SG/VideoLLaMA2) | 7B | 47.9 | 50.3 |
64
+ |[ShareGemini](https://github.com/Share14/ShareGemini) | 7B | 43.2 | 47.9 |
65
+ |[Chat-UniVi-v1.5](https://github.com/PKU-YuanGroup/Chat-UniVi) | 7B | 40.6 | 45.9 |
66
+ |[VideoChat2-Mistral](https://github.com/OpenGVLab/Ask-Anything/tree/main/video_chat2) | 7B | 39.5 | 43.8 |
67
+ |[ST-LLM](https://github.com/TencentARC/ST-LLM) | 7B | 37.9 | 42.3 |
68
+ |[Qwen-VL-Chat](https://github.com/QwenLM/Qwen-VL) | 7B | 41.1 | 41.9 |
69
+ |[Video-LLaVA](https://github.com/PKU-YuanGroup/Video-LLaVA) |7B | 39.9 | 41.6 |
70
+
71
+
72
+ ## Local Demo
73
+ 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.
74
+
75
+ ![demo](images/long-llava-qwen2-7b-demo.gif)
76
+
77
+ ### Run the Demo on your local machine (Mininum Requriement: [g5.4xlarge](https://aws.amazon.com/ec2/instance-types/g5/) is recommended.)
78
+
79
+ To get started, please follow the instructions as below:
80
+
81
+ git clone https://github.com/awslabs/extending-the-context-length-of-open-source-llms.git
82
+
83
+ cd long-llava-qwen2-7b
84
+ conda create -n long-llava python=3.12 -y
85
+ conda activate long-llava
86
+ pip install -r local_demo/requirements.txt
87
+
88
+ python local_demo/multimodal_chat.py
89
+
90
+ 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`.
91
+
92
+ ## How to use the model from Python Code (HuggingFace transformers)
93
+
94
+ First, make sure to have `transformers >= 4.42.0`.
95
+ The model supports multi-image and multi-prompt generation. Meaning that you can pass multiple images in your prompt.
96
+
97
+ ### Using `pipeline`:
98
+
99
+ Below we used [`"aws-prototyping/long-llava-qwen2-7b"`](https://huggingface.co/aws-prototyping/long-llava-qwen2-7b) checkpoint.
100
+
101
+ ```python
102
+ from transformers import pipeline
103
+ from PIL import Image
104
+ import requests
105
+
106
+ model_id = "aws-prototyping/long-llava-qwen2-7b"
107
+ pipe = pipeline("image-to-text", model=model_id)
108
+ url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
109
+ image = Image.open(requests.get(url, stream=True).raw)
110
+
111
+ # Define a chat histiry and use `apply_chat_template` to get correctly formatted prompt
112
+ # Each value in "content" has to be a list of dicts with types ("text", "image")
113
+ conversation = [
114
+ {
115
+
116
+ "role": "user",
117
+ "content": [
118
+ {"type": "text", "text": "What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud"},
119
+ {"type": "image"},
120
+ ],
121
+ },
122
+ ]
123
+ prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
124
+
125
+ outputs = pipe(image, prompt=prompt, generate_kwargs={"max_new_tokens": 200})
126
+ print(outputs)
127
+ >>> {"generated_text": "\nUSER: What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud\nASSISTANT: Lava"}
128
+ ```
129
+
130
+ ### Using pure `transformers`:
131
+
132
+ Below is an example script to run generation in `float16` precision on a GPU device:
133
+
134
+ ```python
135
+ import requests
136
+ from PIL import Image
137
+
138
+ import torch
139
+ from transformers import AutoProcessor, LlavaForConditionalGeneration
140
+
141
+ model_id = "aws-prototyping/long-llava-qwen2-7b"
142
+ model = LlavaForConditionalGeneration.from_pretrained(
143
+ model_id,
144
+ torch_dtype=torch.bfloat16,
145
+ low_cpu_mem_usage=True,
146
+ ).to(0)
147
+
148
+ processor = AutoProcessor.from_pretrained(model_id)
149
+
150
+ # Define a chat histiry and use `apply_chat_template` to get correctly formatted prompt
151
+ # Each value in "content" has to be a list of dicts with types ("text", "image")
152
+ conversation = [
153
+ {
154
+
155
+ "role": "user",
156
+ "content": [
157
+ {"type": "text", "text": "What are these?"},
158
+ {"type": "image"},
159
+ ],
160
+ },
161
+ ]
162
+ prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
163
+
164
+ image_file = "http://images.cocodataset.org/val2017/000000039769.jpg"
165
+ raw_image = Image.open(requests.get(image_file, stream=True).raw)
166
+ inputs = processor(images=raw_image, text=prompt, return_tensors='pt').to(0, torch.float16)
167
+
168
+ output = model.generate(**inputs, max_new_tokens=200, do_sample=False)
169
+ print(processor.decode(output[0][2:], skip_special_tokens=True))
170
+ ```
171
+
172
+ ### Model optimization
173
+
174
+ #### 4-bit quantization through `bitsandbytes` library
175
+
176
+ 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:
177
+
178
+ ```diff
179
+ model = LlavaForConditionalGeneration.from_pretrained(
180
+ model_id,
181
+ torch_dtype=torch.float16,
182
+ low_cpu_mem_usage=True,
183
+ + load_in_4bit=True
184
+ )
185
+ ```
186
+
187
+ #### Use Flash-Attention 2 to further speed-up generation
188
+
189
+ First make sure to install `flash-attn`. Refer to the [original repository of Flash Attention](https://github.com/Dao-AILab/flash-attention) regarding that package installation. Simply change the snippet above with:
190
+
191
+ ```diff
192
+ model = LlavaForConditionalGeneration.from_pretrained(
193
+ model_id,
194
+ torch_dtype=torch.bfloat16,
195
+ low_cpu_mem_usage=True,
196
+ + use_flash_attention_2=True
197
+ ).to(0)
198
+ ```
199
+
200
+ ## Serve the model on vLLM
201
+ On an AWS `g5.4xlarge` or larger instance, install vLLM as per [vLLM docs](https://vllm.readthedocs.io/en/latest/).
202
+ ```shell
203
+ pip install vllm==0.5.5
204
+ ```
205
+
206
+ ### Start the server
207
+ ```shell
208
+ vllm serve aws-prototyping/long-llava-qwen2-7b \
209
+ —max_model_len 8192
210
+ ```
211
+ **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](https://github.com/vllm-project/vllm/issues/4194) for details.
212
+
213
+ ### Run the client
214
+ ```python
215
+ import base64
216
+
217
+ import requests
218
+ from openai import OpenAI
219
+
220
+ # Modify OpenAI's API key and API base to use vLLM's API server.
221
+ openai_api_key = "EMPTY"
222
+ openai_api_base = "http://localhost:8000/v1"
223
+
224
+ client = OpenAI(
225
+ # defaults to os.environ.get("OPENAI_API_KEY")
226
+ api_key=openai_api_key,
227
+ base_url=openai_api_base,
228
+ )
229
+
230
+ models = client.models.list()
231
+ model = models.data[0].id
232
+
233
+ image_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"
234
+
235
+ # Use image url in the payload
236
+ chat_completion_from_url = client.chat.completions.create(
237
+ messages=[{
238
+ "role":
239
+ "user",
240
+ "content": [
241
+ {
242
+ "type": "text",
243
+ "text": "What’s in this image?"
244
+ },
245
+ {
246
+ "type": "image_url",
247
+ "image_url": {
248
+ "url": image_url
249
+ },
250
+ },
251
+ ],
252
+ }],
253
+ model=model,
254
+ max_tokens=64,
255
+ )
256
+
257
+ result = chat_completion_from_url.choices[0].message.content
258
+ print(f"Chat completion output:{result}")
259
+
260
+
261
+ # Use base64 encoded image in the payload
262
+ def encode_image_base64_from_url(image_url: str) -> str:
263
+ """Encode an image retrieved from a remote url to base64 format."""
264
+
265
+ with requests.get(image_url) as response:
266
+ response.raise_for_status()
267
+ result = base64.b64encode(response.content).decode('utf-8')
268
+
269
+ return result
270
+
271
+
272
+ image_base64 = encode_image_base64_from_url(image_url=image_url)
273
+ chat_completion_from_base64 = client.chat.completions.create(
274
+ messages=[{
275
+ "role":
276
+ "user",
277
+ "content": [
278
+ {
279
+ "type": "text",
280
+ "text": "What’s in this image?"
281
+ },
282
+ {
283
+ "type": "image_url",
284
+ "image_url": {
285
+ "url": f"data:image/jpeg;base64,{image_base64}"
286
+ },
287
+ },
288
+ ],
289
+ }],
290
+ model=model,
291
+ max_tokens=64,
292
+ )
293
+
294
+ result = chat_completion_from_base64.choices[0].message.content
295
+ print(f"Chat completion output:{result}")
296
+ ```
297
+
298
+ ## Deploy the model on a SageMaker LMI Endpoint
299
+
300
+ Please refer to this [Jupyter Notebook](https://github.com/awslabs/extending-the-context-length-of-open-source-llms/tree/main/long-llava-qwen2-7b/notebooks/deploy-on-aws-sagemaker-long-llava-qwen2-7b.ipynb) to see how to deploy a Sagemaker [large model inference (LMI) container](https://docs.aws.amazon.com/sagemaker/latest/dg/large-model-inference-container-docs.html).
301
+
302
+
303
+ ## Limitations
304
+ 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.
305
+
306
+ ## Citation
307
+
308
+ If you find our work helpful, feel free to give us a cite.
309
+
310
+ ```
311
+ @misc{long-llava-qwen2-7b-2024,
312
+ author = { {Yin Song and Chen Wu and Eden Duthie} },
313
+ title = { {aws-prototyping/long-llava-qwen2-7b} },
314
+ year = 2024,
315
+ url = { https://huggingface.co/aws-prototyping/long-llava-qwen2-7b },
316
+ publisher = { Hugging Face }
317
+ }
318
+ ```