Spaces:
Build error
Build error
Nightwalkx commited on
Commit ·
57b8041
1
Parent(s): 14d7981
update
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +0 -21
- .editorconfig +0 -18
- .gitignore +1 -5
- README.md +6 -10
- app.py +11 -5
- cog.yaml +0 -37
- data/prompts/complex_reasoning/000_caps.txt +18 -0
- data/prompts/complex_reasoning/000_conv.txt +5 -0
- data/prompts/complex_reasoning/001_caps.txt +18 -0
- data/prompts/complex_reasoning/001_conv.txt +5 -0
- data/prompts/complex_reasoning/002_caps.txt +7 -0
- data/prompts/complex_reasoning/002_conv.txt +5 -0
- data/prompts/complex_reasoning/system_message.txt +10 -0
- data/prompts/conversation/000_caps.txt +5 -0
- data/prompts/conversation/000_conv.txt +29 -0
- data/prompts/conversation/001_caps.txt +5 -0
- data/prompts/conversation/001_conv.txt +37 -0
- data/prompts/conversation/system_message.txt +12 -0
- data/prompts/detail_description/000_caps.txt +18 -0
- data/prompts/detail_description/000_conv.txt +3 -0
- data/prompts/detail_description/001_caps.txt +18 -0
- data/prompts/detail_description/001_conv.txt +5 -0
- data/prompts/detail_description/002_caps.txt +15 -0
- data/prompts/detail_description/002_conv.txt +3 -0
- data/prompts/detail_description/system_message.txt +7 -0
- docs/Customize_Component.md +20 -0
- docs/Data.md +29 -0
- docs/LLaVA_Bench.md +31 -0
- docs/LLaVA_from_LLaMA2.md +29 -0
- docs/LoRA.md +46 -0
- docs/MODEL_ZOO.md +136 -0
- docs/ScienceQA.md +53 -0
- llava/__init__.py +1 -1
- llava/constants.py +0 -1
- llava/conversation.py +61 -76
- llava/eval/eval_pope.py +0 -81
- llava/eval/eval_science_qa.py +10 -25
- llava/eval/eval_textvqa.py +0 -65
- llava/eval/m4c_evaluator.py +0 -334
- llava/eval/model_qa.py +22 -1
- llava/eval/model_vqa.py +17 -6
- llava/eval/model_vqa_loader.py +0 -144
- llava/eval/model_vqa_mmbench.py +0 -160
- llava/eval/model_vqa_science.py +44 -14
- llava/eval/run_llava.py +34 -82
- llava/eval/summarize_gpt_review.py +6 -16
- llava/mm_utils.py +9 -157
- llava/model/__init__.py +2 -6
- llava/model/builder.py +12 -28
- llava/model/language_model/llava_llama.py +59 -77
.dockerignore
DELETED
|
@@ -1,21 +0,0 @@
|
|
| 1 |
-
# The .dockerignore file excludes files from the container build process.
|
| 2 |
-
#
|
| 3 |
-
# https://docs.docker.com/engine/reference/builder/#dockerignore-file
|
| 4 |
-
|
| 5 |
-
# Exclude Git files
|
| 6 |
-
.git
|
| 7 |
-
.github
|
| 8 |
-
.gitignore
|
| 9 |
-
|
| 10 |
-
# Exclude Python cache files
|
| 11 |
-
__pycache__
|
| 12 |
-
.mypy_cache
|
| 13 |
-
.pytest_cache
|
| 14 |
-
.ruff_cache
|
| 15 |
-
|
| 16 |
-
# Exclude Python virtual environment
|
| 17 |
-
/venv
|
| 18 |
-
|
| 19 |
-
# Exclude some weights
|
| 20 |
-
/openai
|
| 21 |
-
/liuhaotian
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.editorconfig
DELETED
|
@@ -1,18 +0,0 @@
|
|
| 1 |
-
root = true
|
| 2 |
-
|
| 3 |
-
# Unix-style newlines with a newline ending every file
|
| 4 |
-
[*]
|
| 5 |
-
end_of_line = lf
|
| 6 |
-
insert_final_newline = true
|
| 7 |
-
trim_trailing_whitespace = true
|
| 8 |
-
charset = utf-8
|
| 9 |
-
|
| 10 |
-
# 4 space indentation
|
| 11 |
-
[*.{py,json}]
|
| 12 |
-
indent_style = space
|
| 13 |
-
indent_size = 4
|
| 14 |
-
|
| 15 |
-
# 2 space indentation
|
| 16 |
-
[*.{md,sh,yaml,yml}]
|
| 17 |
-
indent_style = space
|
| 18 |
-
indent_size = 2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.gitignore
CHANGED
|
@@ -28,8 +28,4 @@ ckpts*
|
|
| 28 |
.ipynb_checkpoints
|
| 29 |
*.ipynb
|
| 30 |
|
| 31 |
-
|
| 32 |
-
!.devcontainer/*
|
| 33 |
-
|
| 34 |
-
# Demo
|
| 35 |
-
serve_images/
|
|
|
|
| 28 |
.ipynb_checkpoints
|
| 29 |
*.ipynb
|
| 30 |
|
| 31 |
+
*.log
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -1,13 +1,9 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: gray
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
short_description: Demonstration of EgoLlava
|
| 11 |
-
---
|
| 12 |
-
|
| 13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
---
|
| 2 |
+
title: LLaVA
|
| 3 |
+
emoji: 🔥
|
| 4 |
+
colorFrom: purple
|
| 5 |
colorTo: gray
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 3.36.1
|
| 8 |
+
app_port: 7860
|
| 9 |
+
---
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
|
@@ -23,9 +23,9 @@ logger = build_logger("gradio_web_server", "gradio_web_server.log")
|
|
| 23 |
|
| 24 |
headers = {"User-Agent": "LLaVA Client"}
|
| 25 |
|
| 26 |
-
no_change_btn = gr.update()
|
| 27 |
-
enable_btn = gr.update(interactive=True)
|
| 28 |
-
disable_btn = gr.update(interactive=False)
|
| 29 |
|
| 30 |
priority = {
|
| 31 |
"vicuna-13b": "aaaaaaa",
|
|
@@ -339,13 +339,17 @@ def http_bot(
|
|
| 339 |
title_markdown = """
|
| 340 |
# 🌋 LLaVA: Large Language and Vision Assistant
|
| 341 |
[[Project Page]](https://llava-vl.github.io) [[Paper]](https://arxiv.org/abs/2304.08485) [[Code]](https://github.com/haotian-liu/LLaVA) [[Model]](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)
|
|
|
|
| 342 |
ONLY WORKS WITH GPU!
|
|
|
|
| 343 |
You can load the model with 4-bit or 8-bit quantization to make it fit in smaller hardwares. Setting the environment variable `bits` to control the quantization.
|
| 344 |
*Note: 8-bit seems to be slower than both 4-bit/16-bit. Although it has enough VRAM to support 8-bit, until we figure out the inference speed issue, we recommend 4-bit for A10G for the best efficiency.*
|
|
|
|
| 345 |
Recommended configurations:
|
| 346 |
| Hardware | T4-Small (16G) | A10G-Small (24G) | A100-Large (40G) |
|
| 347 |
|-------------------|-----------------|------------------|------------------|
|
| 348 |
| **Bits** | 4 (default) | 4 | 16 |
|
|
|
|
| 349 |
"""
|
| 350 |
|
| 351 |
tos_markdown = """
|
|
@@ -363,9 +367,11 @@ The service is a research preview intended for non-commercial use only, subject
|
|
| 363 |
"""
|
| 364 |
|
| 365 |
block_css = """
|
|
|
|
| 366 |
#buttons button {
|
| 367 |
min-width: min(120px,100%);
|
| 368 |
}
|
|
|
|
| 369 |
"""
|
| 370 |
|
| 371 |
|
|
@@ -590,7 +596,7 @@ def get_args():
|
|
| 590 |
def start_demo(args):
|
| 591 |
demo = build_demo(args.embed)
|
| 592 |
demo.queue(
|
| 593 |
-
|
| 594 |
).launch(server_name=args.host, server_port=args.port, share=args.share)
|
| 595 |
|
| 596 |
|
|
@@ -598,7 +604,7 @@ if __name__ == "__main__":
|
|
| 598 |
args = get_args()
|
| 599 |
logger.info(f"args: {args}")
|
| 600 |
|
| 601 |
-
model_path = "
|
| 602 |
bits = int(os.getenv("bits", 8))
|
| 603 |
|
| 604 |
controller_proc = start_controller()
|
|
|
|
| 23 |
|
| 24 |
headers = {"User-Agent": "LLaVA Client"}
|
| 25 |
|
| 26 |
+
no_change_btn = gr.Button.update()
|
| 27 |
+
enable_btn = gr.Button.update(interactive=True)
|
| 28 |
+
disable_btn = gr.Button.update(interactive=False)
|
| 29 |
|
| 30 |
priority = {
|
| 31 |
"vicuna-13b": "aaaaaaa",
|
|
|
|
| 339 |
title_markdown = """
|
| 340 |
# 🌋 LLaVA: Large Language and Vision Assistant
|
| 341 |
[[Project Page]](https://llava-vl.github.io) [[Paper]](https://arxiv.org/abs/2304.08485) [[Code]](https://github.com/haotian-liu/LLaVA) [[Model]](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)
|
| 342 |
+
|
| 343 |
ONLY WORKS WITH GPU!
|
| 344 |
+
|
| 345 |
You can load the model with 4-bit or 8-bit quantization to make it fit in smaller hardwares. Setting the environment variable `bits` to control the quantization.
|
| 346 |
*Note: 8-bit seems to be slower than both 4-bit/16-bit. Although it has enough VRAM to support 8-bit, until we figure out the inference speed issue, we recommend 4-bit for A10G for the best efficiency.*
|
| 347 |
+
|
| 348 |
Recommended configurations:
|
| 349 |
| Hardware | T4-Small (16G) | A10G-Small (24G) | A100-Large (40G) |
|
| 350 |
|-------------------|-----------------|------------------|------------------|
|
| 351 |
| **Bits** | 4 (default) | 4 | 16 |
|
| 352 |
+
|
| 353 |
"""
|
| 354 |
|
| 355 |
tos_markdown = """
|
|
|
|
| 367 |
"""
|
| 368 |
|
| 369 |
block_css = """
|
| 370 |
+
|
| 371 |
#buttons button {
|
| 372 |
min-width: min(120px,100%);
|
| 373 |
}
|
| 374 |
+
|
| 375 |
"""
|
| 376 |
|
| 377 |
|
|
|
|
| 596 |
def start_demo(args):
|
| 597 |
demo = build_demo(args.embed)
|
| 598 |
demo.queue(
|
| 599 |
+
concurrency_count=args.concurrency_count, status_update_rate=10, api_open=False
|
| 600 |
).launch(server_name=args.host, server_port=args.port, share=args.share)
|
| 601 |
|
| 602 |
|
|
|
|
| 604 |
args = get_args()
|
| 605 |
logger.info(f"args: {args}")
|
| 606 |
|
| 607 |
+
model_path = "liuhaotian/llava-v1.5-13b"
|
| 608 |
bits = int(os.getenv("bits", 8))
|
| 609 |
|
| 610 |
controller_proc = start_controller()
|
cog.yaml
DELETED
|
@@ -1,37 +0,0 @@
|
|
| 1 |
-
# Configuration for Cog ⚙️
|
| 2 |
-
# Reference: https://github.com/replicate/cog/blob/main/docs/yaml.md
|
| 3 |
-
|
| 4 |
-
build:
|
| 5 |
-
gpu: true
|
| 6 |
-
|
| 7 |
-
python_version: "3.11"
|
| 8 |
-
|
| 9 |
-
python_packages:
|
| 10 |
-
- "torch==2.0.1"
|
| 11 |
-
- "accelerate==0.21.0"
|
| 12 |
-
- "bitsandbytes==0.41.0"
|
| 13 |
-
- "deepspeed==0.9.5"
|
| 14 |
-
- "einops-exts==0.0.4"
|
| 15 |
-
- "einops==0.6.1"
|
| 16 |
-
- "gradio==3.35.2"
|
| 17 |
-
- "gradio_client==0.2.9"
|
| 18 |
-
- "httpx==0.24.0"
|
| 19 |
-
- "markdown2==2.4.10"
|
| 20 |
-
- "numpy==1.26.0"
|
| 21 |
-
- "peft==0.4.0"
|
| 22 |
-
- "scikit-learn==1.2.2"
|
| 23 |
-
- "sentencepiece==0.1.99"
|
| 24 |
-
- "shortuuid==1.0.11"
|
| 25 |
-
- "timm==0.6.13"
|
| 26 |
-
- "tokenizers==0.13.3"
|
| 27 |
-
- "torch==2.0.1"
|
| 28 |
-
- "torchvision==0.15.2"
|
| 29 |
-
- "transformers==4.31.0"
|
| 30 |
-
- "wandb==0.15.12"
|
| 31 |
-
- "wavedrom==2.0.3.post3"
|
| 32 |
-
- "Pygments==2.16.1"
|
| 33 |
-
run:
|
| 34 |
-
- curl -o /usr/local/bin/pget -L "https://github.com/replicate/pget/releases/download/v0.0.3/pget" && chmod +x /usr/local/bin/pget
|
| 35 |
-
|
| 36 |
-
# predict.py defines how predictions are run on your model
|
| 37 |
-
predict: "predict.py:Predictor"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/prompts/complex_reasoning/000_caps.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
A man wearing multiple neck ties making a goofy face.
|
| 2 |
+
A man in a white shirt wearing very many ties.
|
| 3 |
+
a man with ties on poses for a picture
|
| 4 |
+
A man wearing multiple ties on his neck.
|
| 5 |
+
A young man smiles while wearing several ties.
|
| 6 |
+
|
| 7 |
+
tie: [0.574, 0.298, 0.752, 0.704]
|
| 8 |
+
tie: [0.464, 0.339, 0.639, 0.789]
|
| 9 |
+
tie: [0.349, 0.363, 0.563, 0.732]
|
| 10 |
+
tie: [0.259, 0.255, 0.668, 0.805]
|
| 11 |
+
person: [0.019, 0.065, 0.962, 0.988]
|
| 12 |
+
person: [0.0, 0.24, 0.214, 1.0]
|
| 13 |
+
tie: [0.316, 0.778, 0.443, 0.867]
|
| 14 |
+
tie: [0.386, 0.707, 0.496, 0.801]
|
| 15 |
+
tie: [0.251, 0.354, 0.402, 0.747]
|
| 16 |
+
tie: [0.44, 0.318, 0.63, 0.397]
|
| 17 |
+
tie: [0.566, 0.33, 0.655, 0.543]
|
| 18 |
+
tie: [0.25, 0.409, 0.359, 0.556]
|
data/prompts/complex_reasoning/000_conv.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Question:
|
| 2 |
+
What is unusual about this photo?
|
| 3 |
+
===
|
| 4 |
+
Answer:
|
| 5 |
+
In the photo, the man is wearing a total of ten ties around his neck. This is considered unusual because it is not common for someone to wear multiple ties at once. In a typical setting, a person would wear only one tie. The man's goofy facial expression also adds to the unconventional and humorous nature of the image.
|
data/prompts/complex_reasoning/001_caps.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
A group of people standing outside of a black vehicle with various luggage.
|
| 2 |
+
Luggage surrounds a vehicle in an underground parking area
|
| 3 |
+
People try to fit all of their luggage in an SUV.
|
| 4 |
+
The sport utility vehicle is parked in the public garage, being packed for a trip
|
| 5 |
+
Some people with luggage near a van that is transporting it.
|
| 6 |
+
|
| 7 |
+
person: [0.681, 0.242, 0.774, 0.694]
|
| 8 |
+
person: [0.63, 0.222, 0.686, 0.516]
|
| 9 |
+
person: [0.444, 0.233, 0.487, 0.34]
|
| 10 |
+
backpack: [0.384, 0.696, 0.485, 0.914]
|
| 11 |
+
backpack: [0.755, 0.413, 0.846, 0.692]
|
| 12 |
+
suitcase: [0.758, 0.413, 0.845, 0.69]
|
| 13 |
+
suitcase: [0.1, 0.497, 0.173, 0.579]
|
| 14 |
+
bicycle: [0.282, 0.363, 0.327, 0.442]
|
| 15 |
+
car: [0.786, 0.25, 0.848, 0.322]
|
| 16 |
+
car: [0.783, 0.27, 0.827, 0.335]
|
| 17 |
+
car: [0.86, 0.254, 0.891, 0.3]
|
| 18 |
+
car: [0.261, 0.101, 0.787, 0.626]
|
data/prompts/complex_reasoning/001_conv.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Question:
|
| 2 |
+
What challenges do these people face?
|
| 3 |
+
===
|
| 4 |
+
Answer:
|
| 5 |
+
In the image, a group of people is standing outside a black SUV in a parking area, surrounded by various pieces of luggage, including suitcases and backpacks. They are facing the challenge of fitting all their luggage into the black SUV. There are multiple suitcases and backpacks to be packed, which suggests that the group has a significant amount of belongings to accommodate. They might have to strategize and arrange the luggage efficiently to ensure that everything fits properly into the vehicle. Additionally, they need to consider the comfort of the passengers and visibility while driving, so the placement of the luggage must not obstruct the driver's view or make the passengers uncomfortable during the trip.
|
data/prompts/complex_reasoning/002_caps.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
There is a movie theater that displays the show times above the doors.
|
| 2 |
+
A red fire hydrant is deep in the snow.
|
| 3 |
+
The fire hydrant is in the snow near a recently plowed sidewalk.
|
| 4 |
+
This city has had a very hard winter with snow.
|
| 5 |
+
A hotel for dogs in the snow in winter.
|
| 6 |
+
|
| 7 |
+
fire hydrant: [0.326, 0.612, 0.426, 0.72]
|
data/prompts/complex_reasoning/002_conv.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Question:
|
| 2 |
+
What challenges might this city face?
|
| 3 |
+
===
|
| 4 |
+
Answer:
|
| 5 |
+
The city faces challenges due to the harsh winter conditions and heavy snowfall. In the image, a red fire hydrant is almost buried deep in the snow, which indicates the significant amount of snow the city has experienced. This can lead to various challenges such as difficulties in transportation, increased risk of accidents, and disruptions to daily life. For example, the recently plowed sidewalk near the fire hydrant shows that the city has to constantly clear snow from roads and sidewalks to maintain access and safety for pedestrians and vehicles. Moreover, emergency services, like firefighters, might face challenges accessing crucial equipment, such as fire hydrants, during emergencies due to the snow accumulation. This highlights the importance of effective snow management strategies and preparedness in such cities to minimize the impact of harsh winter conditions on residents and essential services.
|
data/prompts/complex_reasoning/system_message.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an AI visual assistant that can analyze a single image. You receive five sentences, each describing the same image you are observing. In addition, specific object locations within the image are given, along with detailed coordinates. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y.
|
| 2 |
+
|
| 3 |
+
The task is to use the provided caption and bounding box information, create a plausible question about the image, and provide the answer in detail.
|
| 4 |
+
|
| 5 |
+
Create complex questions beyond describing the scene.
|
| 6 |
+
To answer such questions, one should require first understanding the visual content, then based on the background knowledge or reasoning, either explain why the things are happening that way, or provide guides and help to user's request. Make the question challenging by not including the visual content details in the question so that the user needs to reason about that first.
|
| 7 |
+
|
| 8 |
+
Instead of directly mentioning the bounding box coordinates, utilize this data to explain the scene using natural language. Include details like object counts, position of the objects, relative position between the objects.
|
| 9 |
+
|
| 10 |
+
When using the information from the caption and coordinates, directly explain the scene, and do not mention that the information source is the caption or the bounding box. Always answer as if you are directly looking at the image.
|
data/prompts/conversation/000_caps.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
There is a movie theater that displays the show times above the doors.
|
| 2 |
+
A red fire hydrant is deep in the snow.
|
| 3 |
+
The fire hydrant is in the snow near a recently plowed sidewalk.
|
| 4 |
+
This city has had a very hard winter with snow.
|
| 5 |
+
A hotel for dogs in the snow in winter.
|
data/prompts/conversation/000_conv.txt
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Question:
|
| 2 |
+
What color is the fire hydrant in the image?
|
| 3 |
+
===
|
| 4 |
+
Answer:
|
| 5 |
+
The fire hydrant in the image is red.
|
| 6 |
+
===
|
| 7 |
+
Question:
|
| 8 |
+
Is the fire hydrant fully covered by snow or partially visible?
|
| 9 |
+
===
|
| 10 |
+
Answer:
|
| 11 |
+
The fire hydrant is partially visible, with a significant portion of it covered by the deep snow.
|
| 12 |
+
===
|
| 13 |
+
Question:
|
| 14 |
+
What is the condition of the sidewalk near the fire hydrant?
|
| 15 |
+
===
|
| 16 |
+
Answer:
|
| 17 |
+
The sidewalk near the fire hydrant has been recently plowed, so it is relatively clear of snow compared to the surrounding area.
|
| 18 |
+
===
|
| 19 |
+
Question:
|
| 20 |
+
What does the image suggest about the winter season in the city?
|
| 21 |
+
===
|
| 22 |
+
Answer:
|
| 23 |
+
The image suggests that the winter season in the city has been quite harsh and challenging. The significant snow accumulation seen in the image indicates that the city has experienced heavy snowfall, which can lead to various difficulties and disruptions for its residents.
|
| 24 |
+
|
| 25 |
+
For instance, the deep snow covering the fire hydrant could potentially hinder its accessibility in case of emergencies, which poses safety concerns. The recently plowed sidewalk implies that the city's maintenance crews have been actively working to keep the walkways clear and safe for pedestrians, but the sheer amount of snowfall might make it difficult to keep up with the continuous snow removal efforts.
|
| 26 |
+
|
| 27 |
+
Furthermore, such extreme winter conditions can impact transportation, leading to traffic issues, delays in public transit, and increased risks of accidents due to slippery roads. It can also cause problems for businesses and schools, as people might face challenges commuting to work or attending classes. Additionally, the heavy snow can put extra strain on infrastructure, such as roofs and power lines, increasing the likelihood of structural damage or power outages.
|
| 28 |
+
|
| 29 |
+
In conclusion, the image of the red fire hydrant deep in the snow and the recently plowed sidewalk suggest that the city has faced a particularly severe winter season, with substantial snowfall that has likely caused various challenges and disruptions for its residents and infrastructure.
|
data/prompts/conversation/001_caps.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
A man is skiing in the open snow covered hills
|
| 2 |
+
A skier is making his way into the snow.
|
| 3 |
+
A skier on the foothills of a huge mountain range.
|
| 4 |
+
A skier looks at mountains while standing near a trail sign.
|
| 5 |
+
a single person skiing by an area with a lot of bushes
|
data/prompts/conversation/001_conv.txt
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Question:
|
| 2 |
+
What is the skier doing?
|
| 3 |
+
===
|
| 4 |
+
Answer:
|
| 5 |
+
The skier is skiing in the snow-covered hills, making his way through the snow and enjoying the beautiful mountain scenery. They are also standing near a trail sign, which indicates their location on the mountain.
|
| 6 |
+
===
|
| 7 |
+
Question:
|
| 8 |
+
Are there any other people or skiers visible in the image?
|
| 9 |
+
===
|
| 10 |
+
Answer:
|
| 11 |
+
No, there is only a single person skiing in the image, and they are surrounded by an area with a lot of bushes.
|
| 12 |
+
===
|
| 13 |
+
Question:
|
| 14 |
+
What kind of skiing is the person doing? Cross-country or downhill?
|
| 15 |
+
===
|
| 16 |
+
Answer:
|
| 17 |
+
Based on what I can see in the photo, it is not possible to definitively determine whether the skier is doing cross-country or downhill skiing. However, given the presence of a trail sign and the fact that they are skiing in the foothills, it is more likely that the skier is engaged in cross-country skiing. Downhill skiing typically takes place on more steep slopes and involves ski lifts, whereas cross-country skiing often occurs on relatively flatter terrain with marked trails.
|
| 18 |
+
===
|
| 19 |
+
Question:
|
| 20 |
+
Can you explain cross-country and downhill skiing a bit more?
|
| 21 |
+
===
|
| 22 |
+
Answer:
|
| 23 |
+
Cross-country skiing and downhill skiing are two distinct types of skiing, each with its own techniques, equipment, and terrain preferences.
|
| 24 |
+
|
| 25 |
+
1. Cross-Country Skiing:
|
| 26 |
+
Also known as Nordic skiing, cross-country skiing involves traversing relatively flat terrain or gentle slopes using skis and poles. It is a popular recreational and competitive sport that focuses on endurance, balance, and aerobic fitness. Cross-country skiers use their own locomotion to move across snow-covered terrain, rather than relying on ski lifts or other forms of assistance.
|
| 27 |
+
There are two main techniques in cross-country skiing:
|
| 28 |
+
- Classic: This technique involves skiing in parallel tracks, using a forward-and-backward gliding motion while keeping the skis parallel to each other. The skier uses their poles to propel themselves forward.
|
| 29 |
+
- Skate skiing: This technique is similar to ice skating, where the skier pushes off one ski at an angle and glides on the other. It requires a smooth, groomed surface and is typically faster than the classic technique.
|
| 30 |
+
Cross-country ski equipment consists of lightweight skis, boots, bindings, and poles. The boots are more flexible than those used in downhill skiing, allowing for better ankle movement and control.
|
| 31 |
+
|
| 32 |
+
2. Downhill Skiing:
|
| 33 |
+
Also known as alpine skiing, downhill skiing involves descending slopes at high speeds using skis and poles for balance and control. This sport is more focused on speed, technique, and navigating challenging terrain, including steep slopes, moguls, and even jumps.
|
| 34 |
+
Downhill skiing can be further categorized into several disciplines, such as slalom, giant slalom, super-G, and downhill racing. Each discipline has its own set of rules, courses, and ski equipment.
|
| 35 |
+
Downhill ski equipment includes heavier and stiffer skis, boots, bindings, and poles than those used in cross-country skiing. The boots are more rigid to provide better support and control during high-speed descents and sharp turns.
|
| 36 |
+
|
| 37 |
+
In summary, cross-country skiing is an endurance-based sport that involves traveling across flat or gently sloping terrain, while downhill skiing is focused on speed and technique as skiers navigate steeper slopes and challenging terrain. Both sports require specialized equipment and techniques, but they offer different experiences and challenges to participants.
|
data/prompts/conversation/system_message.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an AI visual assistant, and you are seeing a single image. What you see are provided with five sentences, describing the same image you are looking at. Answer all questions as you are seeing the image.
|
| 2 |
+
|
| 3 |
+
Design a conversation between you and a person asking about this photo. The answers should be in a tone that a visual AI assistant is seeing the image and answering the question.
|
| 4 |
+
Ask diverse questions and give corresponding answers.
|
| 5 |
+
|
| 6 |
+
Include questions asking about the visual content of the image, including the object types, counting the objects, object actions, object locations, relative positions between objects, etc. Only include questions that have definite answers:
|
| 7 |
+
(1) one can see the content in the image that the question asks about and can answer confidently;
|
| 8 |
+
(2) one can determine confidently from the image that it is not in the image.
|
| 9 |
+
Do not ask any question that cannot be answered confidently.
|
| 10 |
+
|
| 11 |
+
Also include complex questions that are relevant to the content in the image, for example, asking about background knowledge of the objects in the image, asking to discuss about events happening in the image, etc. Again, do not ask about uncertain details.
|
| 12 |
+
Provide detailed answers when answering complex questions. For example, give detailed examples or reasoning steps to make the content more convincing and well-organized. You can include multiple paragraphs if necessary.
|
data/prompts/detail_description/000_caps.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
A harbor filled with lots of boats next to a building.
|
| 2 |
+
A bicycle parked in front of several boats at a dock.
|
| 3 |
+
A red bicycle in front of a line of docked white yachts
|
| 4 |
+
A bike sits before boats which sit before a long building.
|
| 5 |
+
A bicycle is a convenient means of land transportation when you live on a boat.
|
| 6 |
+
|
| 7 |
+
bicycle: [0.287, 0.641, 0.507, 0.874]
|
| 8 |
+
bicycle: [0.566, 0.667, 0.63, 0.731]
|
| 9 |
+
boat: [0.318, 0.579, 0.575, 0.724]
|
| 10 |
+
boat: [0.704, 0.607, 0.818, 0.727]
|
| 11 |
+
boat: [0.818, 0.601, 0.942, 0.744]
|
| 12 |
+
boat: [0.002, 0.53, 0.243, 0.71]
|
| 13 |
+
boat: [0.541, 0.611, 0.668, 0.731]
|
| 14 |
+
person: [0.778, 0.527, 0.797, 0.57]
|
| 15 |
+
cup: [0.708, 0.733, 0.724, 0.758]
|
| 16 |
+
boat: [0.236, 0.532, 0.404, 0.64]
|
| 17 |
+
boat: [0.81, 0.632, 0.836, 0.676]
|
| 18 |
+
boat: [0.957, 0.526, 1.0, 0.752]
|
data/prompts/detail_description/000_conv.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
It is a harbor filled with numerous boats of various sizes docked next to a long building. Among the boats, there are a few white yachts lined up, standing out from the rest. There is a red bicycle prominently parked in front of the line of docked boats, serving as a convenient means of land transportation for those living on the boats. Another bicycle can be seen further back in the scene, near the middle of the harbor.
|
| 2 |
+
|
| 3 |
+
A person is visible near the right side of the harbor, possibly enjoying the view or attending to their boat. Additionally, there is a cup placed on a surface near the middle of the scene.
|
data/prompts/detail_description/001_caps.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
A group of people standing outside of a black vehicle with various luggage.
|
| 2 |
+
Luggage surrounds a vehicle in an underground parking area
|
| 3 |
+
People try to fit all of their luggage in an SUV.
|
| 4 |
+
The sport utility vehicle is parked in the public garage, being packed for a trip
|
| 5 |
+
Some people with luggage near a van that is transporting it.
|
| 6 |
+
|
| 7 |
+
person: [0.681, 0.242, 0.774, 0.694]
|
| 8 |
+
person: [0.63, 0.222, 0.686, 0.516]
|
| 9 |
+
person: [0.444, 0.233, 0.487, 0.34]
|
| 10 |
+
backpack: [0.384, 0.696, 0.485, 0.914]
|
| 11 |
+
backpack: [0.755, 0.413, 0.846, 0.692]
|
| 12 |
+
suitcase: [0.758, 0.413, 0.845, 0.69]
|
| 13 |
+
suitcase: [0.1, 0.497, 0.173, 0.579]
|
| 14 |
+
bicycle: [0.282, 0.363, 0.327, 0.442]
|
| 15 |
+
car: [0.786, 0.25, 0.848, 0.322]
|
| 16 |
+
car: [0.783, 0.27, 0.827, 0.335]
|
| 17 |
+
car: [0.86, 0.254, 0.891, 0.3]
|
| 18 |
+
car: [0.261, 0.101, 0.787, 0.626]
|
data/prompts/detail_description/001_conv.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The image is an underground parking area with a black sport utility vehicle (SUV) parked. There are three people in the scene, with one person standing closer to the left side of the vehicle, another person in the middle, and the third person on the right side. They are all working together to pack their luggage into the SUV for a trip.
|
| 2 |
+
|
| 3 |
+
In the parking area, various luggage items are scattered around the vehicle. There are two backpacks, one located near the left rear wheel and the other closer to the right side of the vehicle. Additionally, there are two suitcases, one on the right side of the car and another further away near the center of the parking area. A bicycle can also be seen on the left side of the vehicle.
|
| 4 |
+
|
| 5 |
+
Other cars are parked around the main SUV, with one car positioned behind it and slightly to the left, another behind and slightly to the right, and the third car further behind on the right side.
|
data/prompts/detail_description/002_caps.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
A man holds a Wii-mote above his head while another looks on.
|
| 2 |
+
A guy and his friend are playing Nintendo Wii.
|
| 3 |
+
A young man is holding a video game remote over his head.
|
| 4 |
+
two men standing in a room while one plays with a wii mote
|
| 5 |
+
Some guys standing and playing a video game.
|
| 6 |
+
|
| 7 |
+
couch: [0.697, 0.759, 0.995, 1.0]
|
| 8 |
+
dining table: [0.426, 0.755, 1.0, 0.987]
|
| 9 |
+
person: [0.082, 0.252, 0.342, 1.0]
|
| 10 |
+
person: [0.399, 0.085, 0.742, 0.982]
|
| 11 |
+
remote: [0.477, 0.135, 0.516, 0.187]
|
| 12 |
+
sink: [0.016, 0.501, 0.063, 0.52]
|
| 13 |
+
potted plant: [0.798, 0.384, 0.888, 0.645]
|
| 14 |
+
refrigerator: [0.305, 0.389, 0.414, 0.547]
|
| 15 |
+
chair: [0.72, 0.509, 0.858, 0.725]
|
data/prompts/detail_description/002_conv.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The image shows two men standing in a room, engaged in playing a video game on a Nintendo Wii console. One of the men is holding a Wii remote above his head with enthusiasm, while the other man looks on, likely enjoying the friendly competition.
|
| 2 |
+
|
| 3 |
+
The room appears to be a living space with a couch located in the background and a dining table nearby. A potted plant can be seen placed close to the couch, and a chair is situated in the middle of the room. The room also features a kitchen area with a sink and a refrigerator visible in the background.
|
data/prompts/detail_description/system_message.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an AI visual assistant that can analyze a single image. You receive five sentences, each describing the same image you are observing. In addition, specific object locations within the image are given, along with detailed coordinates. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y.
|
| 2 |
+
|
| 3 |
+
Using the provided caption and bounding box information, describe the scene in a detailed manner.
|
| 4 |
+
|
| 5 |
+
Instead of directly mentioning the bounding box coordinates, utilize this data to explain the scene using natural language. Include details like object counts, position of the objects, relative position between the objects.
|
| 6 |
+
|
| 7 |
+
When using the information from the caption and coordinates, directly explain the scene, and do not mention that the information source is the caption or the bounding box. Always answer as if you are directly looking at the image.
|
docs/Customize_Component.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Customize Components in LLaVA
|
| 2 |
+
|
| 3 |
+
This is an initial guide on how to replace the LLMs, visual encoders, etc. with your choice of components.
|
| 4 |
+
|
| 5 |
+
## LLM
|
| 6 |
+
|
| 7 |
+
It is quite simple to swap out LLaMA to any other LLMs. You can refer to our implementation of [`llava_llama.py`](https://raw.githubusercontent.com/haotian-liu/LLaVA/main/llava/model/language_model/llava_llama.py) for an example of how to replace the LLM.
|
| 8 |
+
|
| 9 |
+
Although it may seem that it still needs ~100 lines of code, most of them are copied from the original `llama.py` from HF. The only part that is different is to insert some lines for processing the multimodal inputs.
|
| 10 |
+
|
| 11 |
+
In `forward` function, you can see that we call `self.prepare_inputs_labels_for_multimodal` to process the multimodal inputs. This function is defined in `LlavaMetaForCausalLM` and you just need to insert it into the `forward` function of your LLM.
|
| 12 |
+
|
| 13 |
+
In `prepare_inputs_for_generation` function, you can see that we add `images` to the `model_inputs`. This is because we need to pass the images to the LLM during generation.
|
| 14 |
+
|
| 15 |
+
These are basically all the changes you need to make to replace the LLM.
|
| 16 |
+
|
| 17 |
+
## Visual Encoder
|
| 18 |
+
|
| 19 |
+
You can check out [`clip_encoder.py`](https://github.com/haotian-liu/LLaVA/blob/main/llava/model/multimodal_encoder/clip_encoder.py) on how we implement the CLIP visual encoder.
|
| 20 |
+
|
docs/Data.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Data
|
| 2 |
+
|
| 3 |
+
| Data file name | Size |
|
| 4 |
+
| --- | ---: |
|
| 5 |
+
| [llava_instruct_150k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_150k.json) | 229 MB |
|
| 6 |
+
| [llava_instruct_80k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_80k.json) | 229 MB |
|
| 7 |
+
| [conversation_58k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/conversation_58k.json) | 126 MB |
|
| 8 |
+
| [detail_23k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/detail_23k.json) | 20.5 MB |
|
| 9 |
+
| [complex_reasoning_77k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/complex_reasoning_77k.json) | 79.6 MB |
|
| 10 |
+
|
| 11 |
+
### Pretraining Dataset
|
| 12 |
+
The pretraining dataset used in this release is a subset of CC-3M dataset, filtered with a more balanced concept coverage distribution. Please see [here](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K) for a detailed description of the dataset structure and how to download the images.
|
| 13 |
+
|
| 14 |
+
If you already have CC-3M dataset on your disk, the image names follow this format: `GCC_train_000000000.jpg`. You may edit the `image` field correspondingly if necessary.
|
| 15 |
+
|
| 16 |
+
| Data | Chat File | Meta Data | Size |
|
| 17 |
+
| --- | --- | --- | ---: |
|
| 18 |
+
| CC-3M Concept-balanced 595K | [chat.json](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/chat.json) | [metadata.json](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/metadata.json) | 211 MB
|
| 19 |
+
| LAION/CC/SBU BLIP-Caption Concept-balanced 558K | [blip_laion_cc_sbu_558k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain/blob/main/blip_laion_cc_sbu_558k.json) | [metadata.json](#) | 181 MB
|
| 20 |
+
|
| 21 |
+
**Important notice**: Upon the request from the community, as ~15% images of the original CC-3M dataset are no longer accessible, we upload [`images.zip`](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/images.zip) for better reproducing our work in research community. It must not be used for any other purposes. The use of these images must comply with the CC-3M license. This may be taken down at any time when requested by the original CC-3M dataset owner or owners of the referenced images.
|
| 22 |
+
|
| 23 |
+
### GPT-4 Prompts
|
| 24 |
+
|
| 25 |
+
We provide our prompts and few-shot samples for GPT-4 queries, to better facilitate research in this domain. Please check out the [`prompts`](playground/data/prompts) folder for three kinds of questions: conversation, detail description, and complex reasoning.
|
| 26 |
+
|
| 27 |
+
They are organized in a format of `system_message.txt` for system message, pairs of `abc_caps.txt` for few-shot sample user input, and `abc_conv.txt` for few-shot sample reference output.
|
| 28 |
+
|
| 29 |
+
Note that you may find them in different format. For example, `conversation` is in `jsonl`, and detail description is answer-only. The selected format in our preliminary experiments works slightly better than a limited set of alternatives that we tried: `jsonl`, more natural format, answer-only. If interested, you may try other variants or conduct more careful study in this. Contributions are welcomed!
|
docs/LLaVA_Bench.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLaVA-Bench [[Download](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild)]
|
| 2 |
+
|
| 3 |
+
**-Introduction-** Large commercial multimodal chatbots have been released in this week, including
|
| 4 |
+
- [Multimodal Bing-Chat by Microsoft](https://blogs.bing.com/search/july-2023/Bing-Chat-Enterprise-announced,-multimodal-Visual-Search-rolling-out-to-Bing-Chat) (July 18, 2023)
|
| 5 |
+
- [Multimodal Bard by Google](https://bard.google.com/).
|
| 6 |
+
|
| 7 |
+
These chatbots are presumably supported by proprietary large multimodal models (LMM). Compared with the open-source LMM such as LLaVA, proprietary LMM represent the scaling success upperbound of the current SoTA techniques. They share the goal of developing multimodal chatbots that follow human intents to complete various daily-life visual tasks in the wild. While it remains less unexplored how to evaluate multimodal chat ability, it provides useful feedback to study open-source LMMs against the commercial multimodal chatbots. In addition to the *LLaVA-Bench (COCO)* dataset we used to develop the early versions of LLaVA, we are releasing [*LLaVA-Bench (In-the-Wild)*](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild) to the community for the public use.
|
| 8 |
+
|
| 9 |
+
## LLaVA-Bench (In-the-Wild *[Ongoing work]*)
|
| 10 |
+
|
| 11 |
+
To evaluate the model's capability in more challenging tasks and generalizability to novel domains, we collect a diverse set of 24 images with 60 questions in total, including indoor and outdoor scenes, memes, paintings, sketches, etc, and associate each image with a highly-detailed and manually-curated description and a proper selection of questions. Such design also assesses the model's robustness to different prompts. In this release, we also categorize questions into three categories: conversation (simple QA), detailed description, and complex reasoning. We continue to expand and improve the diversity of the LLaVA-Bench (In-the-Wild). We manually query Bing-Chat and Bard to get the responses.
|
| 12 |
+
|
| 13 |
+
### Results
|
| 14 |
+
|
| 15 |
+
The score is measured by comparing against a reference answer generated by text-only GPT-4. It is generated by feeding the question, along with the ground truth image annotations as the context. A text-only GPT-4 evaluator rates both answers. We query GPT-4 by putting the reference answer first, and then the answer generated by the candidate model. We upload images at their original resolution to Bard and Bing-Chat to obtain the results.
|
| 16 |
+
|
| 17 |
+
| Approach | Conversation | Detail | Reasoning | Overall |
|
| 18 |
+
|----------------|--------------|--------|-----------|---------|
|
| 19 |
+
| Bard-0718 | 83.7 | 69.7 | 78.7 | 77.8 |
|
| 20 |
+
| Bing-Chat-0629 | 59.6 | 52.2 | 90.1 | 71.5 |
|
| 21 |
+
| LLaVA-13B-v1-336px-0719 (beam=1) | 64.3 | 55.9 | 81.7 | 70.1 |
|
| 22 |
+
| LLaVA-13B-v1-336px-0719 (beam=5) | 68.4 | 59.9 | 84.3 | 73.5 |
|
| 23 |
+
|
| 24 |
+
Note that Bard sometimes refuses to answer questions about images containing humans, and Bing-Chat blurs the human faces in the images. We also provide the benchmark score for the subset without humans.
|
| 25 |
+
|
| 26 |
+
| Approach | Conversation | Detail | Reasoning | Overall |
|
| 27 |
+
|----------------|--------------|--------|-----------|---------|
|
| 28 |
+
| Bard-0718 | 94.9 | 74.3 | 84.3 | 84.6 |
|
| 29 |
+
| Bing-Chat-0629 | 55.8 | 53.6 | 93.5 | 72.6 |
|
| 30 |
+
| LLaVA-13B-v1-336px-0719 (beam=1) | 62.2 | 56.4 | 82.2 | 70.0 |
|
| 31 |
+
| LLaVA-13B-v1-336px-0719 (beam=5) | 65.6 | 61.7 | 85.0 | 73.6 |
|
docs/LLaVA_from_LLaMA2.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLaVA (based on Llama 2 LLM, Preview)
|
| 2 |
+
|
| 3 |
+
*NOTE: This is a technical preview. We are still running hyperparameter search, and will release the final model soon. If you'd like to contribute to this, please contact us.*
|
| 4 |
+
|
| 5 |
+
:llama: **-Introduction-** [Llama 2 is an open-source LLM released by Meta AI](https://about.fb.com/news/2023/07/llama-2/) today (July 18, 2023). Compared with its early version [Llama 1](https://ai.meta.com/blog/large-language-model-llama-meta-ai/), Llama 2 is more favored in ***stronger language performance***, ***longer context window***, and importantly ***commercially usable***! While Llama 2 is changing the LLM market landscape in the language space, its multimodal ability remains unknown. We quickly develop the LLaVA variant based on the latest Llama 2 checkpoints, and release it to the community for the public use.
|
| 6 |
+
|
| 7 |
+
You need to apply for and download the lastest Llama 2 checkpoints to start your own training (apply [here](https://ai.meta.com/resources/models-and-libraries/llama-downloads/))
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
## Training
|
| 11 |
+
|
| 12 |
+
Please checkout [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain.sh), [`finetune.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune.sh), [`finetune_lora.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh).
|
| 13 |
+
|
| 14 |
+
## LLaVA (based on Llama 2), What is different?
|
| 15 |
+
|
| 16 |
+
:volcano: How is the new LLaVA based on Llama 2 different from Llama 1? The comparisons of the training process are described:
|
| 17 |
+
- **Pre-training**. The pre-trained base LLM is changed from Llama 1 to Llama 2
|
| 18 |
+
- **Language instruction-tuning**. The previous LLaVA model starts with Vicuna, which is instruct tuned on ShareGPT data from Llama 1; The new LLaVA model starts with Llama 2 Chat, which is an instruct tuned checkpoint on dialogue data from Llama 2.
|
| 19 |
+
- **Multimodal instruction-tuning**. The same LLaVA-Lighting process is applied.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
### Results
|
| 23 |
+
|
| 24 |
+
- Llama 2 is better at following the instructions of role playing; Llama 2 fails in following the instructions of translation
|
| 25 |
+
- The quantitative evaluation on [LLaVA-Bench](https://github.com/haotian-liu/LLaVA/blob/main/docs/LLaVA_Bench.md) demonstrates on-par performance between Llama 2 and Llama 1 in LLaVA's multimodal chat ability.
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
<img src="../images/llava_example_cmp.png" width="100%">
|
| 29 |
+
|
docs/LoRA.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLaVA (LoRA, Preview)
|
| 2 |
+
|
| 3 |
+
NOTE: This is a technical preview, and is not yet ready for production use. We are still running hyperparameter search for the LoRA model, and will release the final model soon. If you'd like to contribute to this, please contact us.
|
| 4 |
+
|
| 5 |
+
You need latest code base for LoRA support (instructions [here](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base))
|
| 6 |
+
|
| 7 |
+
## Demo (Web UI)
|
| 8 |
+
|
| 9 |
+
Please execute each of the command below one by one (after the previous one has finished). The commands are the same as launching other demos except for an additional `--model-base` flag to specify the base model to use. Please make sure the base model corresponds to the LoRA checkpoint that you are using. For this technical preview, you need Vicuna v1.1 (7B) checkpoint (if you do not have that already, follow the instructions [here](https://github.com/lm-sys/FastChat#vicuna-weights)).
|
| 10 |
+
|
| 11 |
+
#### Launch a controller
|
| 12 |
+
```Shell
|
| 13 |
+
python -m llava.serve.controller --host 0.0.0.0 --port 10000
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
#### Launch a gradio web server.
|
| 17 |
+
```Shell
|
| 18 |
+
python -m llava.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload
|
| 19 |
+
```
|
| 20 |
+
You just launched the Gradio web interface. Now, you can open the web interface with the URL printed on the screen. You may notice that there is no model in the model list. Do not worry, as we have not launched any model worker yet. It will be automatically updated when you launch a model worker.
|
| 21 |
+
|
| 22 |
+
#### Launch a model worker
|
| 23 |
+
```Shell
|
| 24 |
+
python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path liuhaotian/llava-vicuna-7b-v1.1-lcs_558k-instruct_80k_3e-lora-preview-alpha --model-base /path/to/vicuna-v1.1
|
| 25 |
+
```
|
| 26 |
+
Wait until the process finishes loading the model and you see "Uvicorn running on ...". Now, refresh your Gradio web UI, and you will see the model you just launched in the model list.
|
| 27 |
+
|
| 28 |
+
You can launch as many workers as you want, and compare between different model checkpoints in the same Gradio interface. Please keep the `--controller` the same, and modify the `--port` and `--worker` to a different port number for each worker.
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
## Training
|
| 32 |
+
|
| 33 |
+
Please see sample training scripts for [LoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh) and [QLoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_qlora.sh).
|
| 34 |
+
|
| 35 |
+
We provide sample DeepSpeed configs, [`zero3.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3.json) is more like PyTorch FSDP, and [`zero3_offload.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3_offload.json) can further save memory consumption by offloading parameters to CPU. `zero3.json` is usually faster than `zero3_offload.json` but requires more GPU memory, therefore, we recommend trying `zero3.json` first, and if you run out of GPU memory, try `zero3_offload.json`. You can also tweak the `per_device_train_batch_size` and `gradient_accumulation_steps` in the config to save memory, and just to make sure that `per_device_train_batch_size` and `gradient_accumulation_steps` remains the same.
|
| 36 |
+
|
| 37 |
+
If you are having issues with ZeRO-3 configs, and there are enough VRAM, you may try [`zero2.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero2.json). This consumes slightly more memory than ZeRO-3, and behaves more similar to PyTorch FSDP, while still supporting parameter-efficient tuning.
|
| 38 |
+
|
| 39 |
+
## Create Merged Checkpoints
|
| 40 |
+
|
| 41 |
+
```Shell
|
| 42 |
+
python scripts/merge_lora_weights.py \
|
| 43 |
+
--model-path /path/to/lora_model \
|
| 44 |
+
--model-base /path/to/base_model \
|
| 45 |
+
--save-model-path /path/to/merge_model
|
| 46 |
+
```
|
docs/MODEL_ZOO.md
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Model Zoo
|
| 2 |
+
|
| 3 |
+
**To Use LLaVA-1.5 checkpoints, your llava package version must be newer than 1.1.0. [Instructions](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base) on how to upgrade.**
|
| 4 |
+
|
| 5 |
+
If you are interested in including any other details in Model Zoo, please open an issue :)
|
| 6 |
+
|
| 7 |
+
The model weights below are *merged* weights. You do not need to apply delta. The usage of LLaVA checkpoints should comply with the base LLM's model license: [LLaMA](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md).
|
| 8 |
+
|
| 9 |
+
## LLaVA-v1.5
|
| 10 |
+
|
| 11 |
+
| Version | Size | Schedule | Checkpoint | VQAv2 | GQA | VizWiz | SQA | T-VQA | POPE | MME | MM-Bench | MM-Bench-CN | SEED | LLaVA-Bench-Wild | MM-Vet |
|
| 12 |
+
|----------|----------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---|
|
| 13 |
+
| LLaVA-1.5 | 7B | full_ft-1e | [liuhaotian/llava-v1.5-7b](https://huggingface.co/liuhaotian/llava-v1.5-7b) | 78.5 | 62.0 | 50.0 | 66.8 | 58.2 | 85.9 | 1510.7 | 64.3 | 58.3 | 58.6 | 63.4 | 30.5 |
|
| 14 |
+
| LLaVA-1.5 | 13B | full_ft-1e | [liuhaotian/llava-v1.5-13b](https://huggingface.co/liuhaotian/llava-v1.5-13b) | 80.0 | 63.3 | 53.6 | 71.6 | 61.3 | 85.9 | 1531.3 | 67.7 | 63.6 | 61.6 | 70.7 | 35.4 |
|
| 15 |
+
| LLaVA-1.5 | 7B | lora-1e | coming soon |
|
| 16 |
+
| LLaVA-1.5 | 13B | lora-1e | coming soon |
|
| 17 |
+
|
| 18 |
+
<p align="center">
|
| 19 |
+
<img src="../images/llava_v1_5_radar.jpg" width="500px"> <br>
|
| 20 |
+
LLaVA-1.5 achieves SoTA performance across 11 benchmarks.
|
| 21 |
+
</p>
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
## LLaVA-v1
|
| 25 |
+
|
| 26 |
+
*Note: We recommend using the most capable LLaVA-v1.5 series above for the best performance.*
|
| 27 |
+
|
| 28 |
+
| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | LLaVA-Bench-Conv | LLaVA-Bench-Detail | LLaVA-Bench-Complex | LLaVA-Bench-Overall | Download |
|
| 29 |
+
|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|--------------------|---------------------|---------------------|---------------------|
|
| 30 |
+
| Vicuna-13B-v1.3 | CLIP-L-336px | LCS-558K | 1e | LLaVA-Instruct-80K | proj-1e, lora-1e | 64.3 | 55.9 | 81.7 | 70.1 | [LoRA](https://huggingface.co/liuhaotian/llava-v1-0719-336px-lora-vicuna-13b-v1.3) [LoRA-Merged](https://huggingface.co/liuhaotian/llava-v1-0719-336px-lora-merge-vicuna-13b-v1.3) |
|
| 31 |
+
| LLaMA-2-13B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | 56.7 | 58.6 | 80.0 | 67.9 | [ckpt](https://huggingface.co/liuhaotian/llava-llama-2-13b-chat-lightning-preview) |
|
| 32 |
+
| LLaMA-2-7B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | lora-1e | 51.2 | 58.9 | 71.6 | 62.8 | [LoRA](https://huggingface.co/liuhaotian/llava-llama-2-7b-chat-lightning-lora-preview) |
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
## Projector weights
|
| 36 |
+
|
| 37 |
+
The model weights below are projector weights we have pretrained. You can use these projector weights for visual instruction tuning. We'll add more projector weights into model zoo very soon.
|
| 38 |
+
|
| 39 |
+
**NOTE**: These projector weights are only compatible with the `llava>=1.0.0`, please check out the latest code base if your local code version is below `v1.0.0`.
|
| 40 |
+
|
| 41 |
+
**NOTE**: When you use our pretrained projector for visual instruction tuning, it is very important to **use the same base LLM and vision encoder** as the one we used for pretraining the projector. Otherwise, the performance will be very bad.
|
| 42 |
+
|
| 43 |
+
When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows,
|
| 44 |
+
|
| 45 |
+
```Shell
|
| 46 |
+
--mm_use_im_start_end False
|
| 47 |
+
--mm_use_im_patch_token False
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
| Base LLM | Vision Encoder | Projection | Pretrain Data | Pretraining schedule | Download |
|
| 51 |
+
|----------|----------------|---------------|----------------------|----------|----------|
|
| 52 |
+
| Vicuna-13B-v1.5 | CLIP-L-336px | MLP-2x | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-v1.5-mlp2x-336px-pretrain-vicuna-13b-v1.5) |
|
| 53 |
+
| Vicuna-7B-v1.5 | CLIP-L-336px | MLP-2x | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-v1.5-mlp2x-336px-pretrain-vicuna-7b-v1.5) |
|
| 54 |
+
| LLaMA-2-13B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-13b-chat) |
|
| 55 |
+
| LLaMA-2-7B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-7b-chat) |
|
| 56 |
+
| LLaMA-2-13B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-13b-chat) |
|
| 57 |
+
| LLaMA-2-7B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-7b-chat) |
|
| 58 |
+
| Vicuna-13B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-13b-v1.3) |
|
| 59 |
+
| Vicuna-7B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-7b-v1.3) |
|
| 60 |
+
| Vicuna-13B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-13b-v1.3) |
|
| 61 |
+
| Vicuna-7B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-7b-v1.3) |
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
## Science QA Checkpoints
|
| 65 |
+
|
| 66 |
+
| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
|
| 67 |
+
|----------|----------------|---------------|----------------------|-----------------|--------------------|---------------------|
|
| 68 |
+
| Vicuna-13B-v1.3 | CLIP-L | LCS-558K | 1e | ScienceQA | full_ft-12e | [ckpt](https://huggingface.co/liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3) |
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
## Legacy Models (merged weights)
|
| 72 |
+
|
| 73 |
+
The model weights below are *merged* weights. You do not need to apply delta. The usage of LLaVA checkpoints should comply with the base LLM's model license.
|
| 74 |
+
|
| 75 |
+
| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
|
| 76 |
+
|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|
|
| 77 |
+
| MPT-7B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | [preview](https://huggingface.co/liuhaotian/LLaVA-Lightning-MPT-7B-preview) |
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
## Legacy Models (delta weights)
|
| 81 |
+
|
| 82 |
+
The model weights below are *delta* weights. The usage of LLaVA checkpoints should comply with the base LLM's model license: [LLaMA](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md).
|
| 83 |
+
|
| 84 |
+
You can add our delta to the original LLaMA weights to obtain the LLaVA weights.
|
| 85 |
+
|
| 86 |
+
Instructions:
|
| 87 |
+
|
| 88 |
+
1. Get the original LLaMA weights in the huggingface format by following the instructions [here](https://huggingface.co/docs/transformers/main/model_doc/llama).
|
| 89 |
+
2. Use the following scripts to get LLaVA weights by applying our delta. It will automatically download delta weights from our Hugging Face account. In the script below, we use the delta weights of [`liuhaotian/LLaVA-7b-delta-v0`](https://huggingface.co/liuhaotian/LLaVA-7b-delta-v0) as an example. It can be adapted for other delta weights by changing the `--delta` argument (and base/target accordingly).
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
python3 -m llava.model.apply_delta \
|
| 93 |
+
--base /path/to/llama-7b \
|
| 94 |
+
--target /output/path/to/LLaVA-7B-v0 \
|
| 95 |
+
--delta liuhaotian/LLaVA-7b-delta-v0
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
|
| 99 |
+
|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|
|
| 100 |
+
| Vicuna-13B-v1.1 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v1-1) |
|
| 101 |
+
| Vicuna-7B-v1.1 | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-Lightning-7B-delta-v1-1) |
|
| 102 |
+
| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0) |
|
| 103 |
+
| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | ScienceQA | full_ft-12e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0-science_qa) |
|
| 104 |
+
| Vicuna-7B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-7b-delta-v0) |
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
## Legacy Projector weights
|
| 109 |
+
|
| 110 |
+
The following projector weights are deprecated, and the support for them may be removed in the future. They do not support zero-shot inference. Please use the projector weights in the [table above](#projector-weights) if possible.
|
| 111 |
+
|
| 112 |
+
**NOTE**: When you use our pretrained projector for visual instruction tuning, it is very important to **use the same base LLM and vision encoder** as the one we used for pretraining the projector. Otherwise, the performance will be very bad.
|
| 113 |
+
|
| 114 |
+
When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows,
|
| 115 |
+
|
| 116 |
+
```Shell
|
| 117 |
+
--mm_use_im_start_end True
|
| 118 |
+
--mm_use_im_patch_token False
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download |
|
| 122 |
+
|----------|----------------|---------------|----------------------|----------|
|
| 123 |
+
| Vicuna-7B-v1.1 | CLIP-L | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-7b-pretrain-projector-v1-1-LCS-558K-blip_caption.bin) |
|
| 124 |
+
| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-13b-pretrain-projector-v0-CC3M-595K-original_caption.bin) |
|
| 125 |
+
| Vicuna-7B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-7b-pretrain-projector-v0-CC3M-595K-original_caption.bin) |
|
| 126 |
+
|
| 127 |
+
When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows,
|
| 128 |
+
|
| 129 |
+
```Shell
|
| 130 |
+
--mm_use_im_start_end False
|
| 131 |
+
--mm_use_im_patch_token False
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download |
|
| 135 |
+
|----------|----------------|---------------|----------------------|----------|
|
| 136 |
+
| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-13b-pretrain-projector-v0-CC3M-595K-original_caption-no_im_token.bin) |
|
docs/ScienceQA.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
### ScienceQA
|
| 2 |
+
|
| 3 |
+
#### Prepare Data
|
| 4 |
+
1. Please see ScienceQA [repo](https://github.com/lupantech/ScienceQA) for setting up the dataset.
|
| 5 |
+
2. Generate ScienceQA dataset for LLaVA conversation-style format.
|
| 6 |
+
|
| 7 |
+
```Shell
|
| 8 |
+
python scripts/convert_sqa_to_llava.py \
|
| 9 |
+
convert_to_llava \
|
| 10 |
+
--base-dir /path/to/ScienceQA/data/scienceqa \
|
| 11 |
+
--prompt-format "QCM-LEA" \
|
| 12 |
+
--split {train,val,minival,test,minitest}
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
#### Training
|
| 16 |
+
|
| 17 |
+
1. Pretraining
|
| 18 |
+
|
| 19 |
+
You can download our pretrained projector weights from our [Model Zoo](), or train your own projector weights using [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain.sh).
|
| 20 |
+
|
| 21 |
+
2. Finetuning
|
| 22 |
+
|
| 23 |
+
See [`finetune_sqa.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_sqa.sh).
|
| 24 |
+
|
| 25 |
+
#### Evaluation
|
| 26 |
+
|
| 27 |
+
1. Multiple-GPU inference
|
| 28 |
+
You may evaluate this with multiple GPUs, and concatenate the generated jsonl files. Please refer to our script for [batch evaluation](https://github.com/haotian-liu/LLaVA/blob/main/scripts/sqa_eval_batch.sh) and [results gathering](https://github.com/haotian-liu/LLaVA/blob/main/scripts/sqa_eval_gather.sh).
|
| 29 |
+
|
| 30 |
+
2. Single-GPU inference
|
| 31 |
+
|
| 32 |
+
(a) Generate LLaVA responses on ScienceQA dataset
|
| 33 |
+
|
| 34 |
+
```Shell
|
| 35 |
+
python -m llava.eval.model_vqa_science \
|
| 36 |
+
--model-path liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3 \
|
| 37 |
+
--question-file /path/to/ScienceQA/data/scienceqa/llava_test_QCM-LEA.json \
|
| 38 |
+
--image-folder /path/to/ScienceQA/data/scienceqa/images/test \
|
| 39 |
+
--answers-file vqa/results/ScienceQA/test_llava-13b.jsonl \
|
| 40 |
+
--conv-mode llava_v1
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
(b) Evaluate the generated responses
|
| 44 |
+
|
| 45 |
+
```Shell
|
| 46 |
+
python eval_science_qa.py \
|
| 47 |
+
--base-dir /path/to/ScienceQA/data/scienceqa \
|
| 48 |
+
--result-file vqa/results/ScienceQA/test_llava-13b.jsonl \
|
| 49 |
+
--output-file vqa/results/ScienceQA/test_llava-13b_output.json \
|
| 50 |
+
--output-result vqa/results/ScienceQA/test_llava-13b_result.json \
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
For reference, we attach our prediction file [`test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/table/results/test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json) and [`test_sqa_llava_13b_v0.json`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/table/results/test_sqa_llava_13b_v0.json) for comparison when reproducing our results, as well as for further analysis in detail.
|
llava/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
from
|
|
|
|
| 1 |
+
from .model import LlavaLlamaForCausalLM
|
llava/constants.py
CHANGED
|
@@ -10,4 +10,3 @@ DEFAULT_IMAGE_TOKEN = "<image>"
|
|
| 10 |
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
| 11 |
DEFAULT_IM_START_TOKEN = "<im_start>"
|
| 12 |
DEFAULT_IM_END_TOKEN = "<im_end>"
|
| 13 |
-
IMAGE_PLACEHOLDER = "<image-placeholder>"
|
|
|
|
| 10 |
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
| 11 |
DEFAULT_IM_START_TOKEN = "<im_start>"
|
| 12 |
DEFAULT_IM_END_TOKEN = "<im_end>"
|
|
|
llava/conversation.py
CHANGED
|
@@ -1,9 +1,6 @@
|
|
| 1 |
import dataclasses
|
| 2 |
from enum import auto, Enum
|
| 3 |
from typing import List, Tuple
|
| 4 |
-
import base64
|
| 5 |
-
from io import BytesIO
|
| 6 |
-
from PIL import Image
|
| 7 |
|
| 8 |
|
| 9 |
class SeparatorStyle(Enum):
|
|
@@ -71,7 +68,7 @@ class Conversation:
|
|
| 71 |
else:
|
| 72 |
ret += role
|
| 73 |
elif self.sep_style == SeparatorStyle.LLAMA_2:
|
| 74 |
-
wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n"
|
| 75 |
wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
|
| 76 |
ret = ""
|
| 77 |
|
|
@@ -109,54 +106,54 @@ class Conversation:
|
|
| 109 |
def append_message(self, role, message):
|
| 110 |
self.messages.append([role, message])
|
| 111 |
|
| 112 |
-
def process_image(self, image, image_process_mode, return_pil=False, image_format='PNG', max_len=1344, min_len=672):
|
| 113 |
-
if image_process_mode == "Pad":
|
| 114 |
-
def expand2square(pil_img, background_color=(122, 116, 104)):
|
| 115 |
-
width, height = pil_img.size
|
| 116 |
-
if width == height:
|
| 117 |
-
return pil_img
|
| 118 |
-
elif width > height:
|
| 119 |
-
result = Image.new(pil_img.mode, (width, width), background_color)
|
| 120 |
-
result.paste(pil_img, (0, (width - height) // 2))
|
| 121 |
-
return result
|
| 122 |
-
else:
|
| 123 |
-
result = Image.new(pil_img.mode, (height, height), background_color)
|
| 124 |
-
result.paste(pil_img, ((height - width) // 2, 0))
|
| 125 |
-
return result
|
| 126 |
-
image = expand2square(image)
|
| 127 |
-
elif image_process_mode in ["Default", "Crop"]:
|
| 128 |
-
pass
|
| 129 |
-
elif image_process_mode == "Resize":
|
| 130 |
-
image = image.resize((336, 336))
|
| 131 |
-
else:
|
| 132 |
-
raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
|
| 133 |
-
if max(image.size) > max_len:
|
| 134 |
-
max_hw, min_hw = max(image.size), min(image.size)
|
| 135 |
-
aspect_ratio = max_hw / min_hw
|
| 136 |
-
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
| 137 |
-
longest_edge = int(shortest_edge * aspect_ratio)
|
| 138 |
-
W, H = image.size
|
| 139 |
-
if H > W:
|
| 140 |
-
H, W = longest_edge, shortest_edge
|
| 141 |
-
else:
|
| 142 |
-
H, W = shortest_edge, longest_edge
|
| 143 |
-
image = image.resize((W, H))
|
| 144 |
-
if return_pil:
|
| 145 |
-
return image
|
| 146 |
-
else:
|
| 147 |
-
buffered = BytesIO()
|
| 148 |
-
image.save(buffered, format=image_format)
|
| 149 |
-
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 150 |
-
return img_b64_str
|
| 151 |
-
|
| 152 |
def get_images(self, return_pil=False):
|
| 153 |
images = []
|
| 154 |
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
| 155 |
if i % 2 == 0:
|
| 156 |
if type(msg) is tuple:
|
|
|
|
|
|
|
|
|
|
| 157 |
msg, image, image_process_mode = msg
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
return images
|
| 161 |
|
| 162 |
def to_gradio_chatbot(self):
|
|
@@ -164,11 +161,24 @@ class Conversation:
|
|
| 164 |
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
| 165 |
if i % 2 == 0:
|
| 166 |
if type(msg) is tuple:
|
|
|
|
|
|
|
| 167 |
msg, image, image_process_mode = msg
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
msg = img_str + msg.replace('<image>', '').strip()
|
| 173 |
ret.append([msg, None])
|
| 174 |
else:
|
|
@@ -347,38 +357,13 @@ conv_llava_v1_mmtag = Conversation(
|
|
| 347 |
version="v1_mmtag",
|
| 348 |
)
|
| 349 |
|
| 350 |
-
|
| 351 |
-
system="",
|
| 352 |
-
roles=("USER", "ASSISTANT"),
|
| 353 |
-
version="llama_v2",
|
| 354 |
-
messages=(),
|
| 355 |
-
offset=0,
|
| 356 |
-
sep_style=SeparatorStyle.LLAMA_2,
|
| 357 |
-
sep="",
|
| 358 |
-
sep2="</s>",
|
| 359 |
-
)
|
| 360 |
-
|
| 361 |
-
conv_chatml_direct = Conversation(
|
| 362 |
-
system="""<|im_start|>system
|
| 363 |
-
Answer the questions.""",
|
| 364 |
-
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
| 365 |
-
version="mpt",
|
| 366 |
-
messages=(),
|
| 367 |
-
offset=0,
|
| 368 |
-
sep_style=SeparatorStyle.MPT,
|
| 369 |
-
sep="<|im_end|>",
|
| 370 |
-
)
|
| 371 |
-
|
| 372 |
-
default_conversation = conv_vicuna_v1
|
| 373 |
conv_templates = {
|
| 374 |
"default": conv_vicuna_v0,
|
| 375 |
"v0": conv_vicuna_v0,
|
| 376 |
"v1": conv_vicuna_v1,
|
| 377 |
"vicuna_v1": conv_vicuna_v1,
|
| 378 |
"llama_2": conv_llama_2,
|
| 379 |
-
"mistral_instruct": conv_mistral_instruct,
|
| 380 |
-
"chatml_direct": conv_chatml_direct,
|
| 381 |
-
"mistral_direct": conv_chatml_direct,
|
| 382 |
|
| 383 |
"plain": conv_llava_plain,
|
| 384 |
"v0_plain": conv_llava_plain,
|
|
|
|
| 1 |
import dataclasses
|
| 2 |
from enum import auto, Enum
|
| 3 |
from typing import List, Tuple
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
class SeparatorStyle(Enum):
|
|
|
|
| 68 |
else:
|
| 69 |
ret += role
|
| 70 |
elif self.sep_style == SeparatorStyle.LLAMA_2:
|
| 71 |
+
wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n"
|
| 72 |
wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
|
| 73 |
ret = ""
|
| 74 |
|
|
|
|
| 106 |
def append_message(self, role, message):
|
| 107 |
self.messages.append([role, message])
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
def get_images(self, return_pil=False):
|
| 110 |
images = []
|
| 111 |
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
| 112 |
if i % 2 == 0:
|
| 113 |
if type(msg) is tuple:
|
| 114 |
+
import base64
|
| 115 |
+
from io import BytesIO
|
| 116 |
+
from PIL import Image
|
| 117 |
msg, image, image_process_mode = msg
|
| 118 |
+
if image_process_mode == "Pad":
|
| 119 |
+
def expand2square(pil_img, background_color=(122, 116, 104)):
|
| 120 |
+
width, height = pil_img.size
|
| 121 |
+
if width == height:
|
| 122 |
+
return pil_img
|
| 123 |
+
elif width > height:
|
| 124 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
| 125 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
| 126 |
+
return result
|
| 127 |
+
else:
|
| 128 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
| 129 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
| 130 |
+
return result
|
| 131 |
+
image = expand2square(image)
|
| 132 |
+
elif image_process_mode in ["Default", "Crop"]:
|
| 133 |
+
pass
|
| 134 |
+
elif image_process_mode == "Resize":
|
| 135 |
+
image = image.resize((336, 336))
|
| 136 |
+
else:
|
| 137 |
+
raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
|
| 138 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
| 139 |
+
aspect_ratio = max_hw / min_hw
|
| 140 |
+
max_len, min_len = 800, 400
|
| 141 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
| 142 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
| 143 |
+
W, H = image.size
|
| 144 |
+
if longest_edge != max(image.size):
|
| 145 |
+
if H > W:
|
| 146 |
+
H, W = longest_edge, shortest_edge
|
| 147 |
+
else:
|
| 148 |
+
H, W = shortest_edge, longest_edge
|
| 149 |
+
image = image.resize((W, H))
|
| 150 |
+
if return_pil:
|
| 151 |
+
images.append(image)
|
| 152 |
+
else:
|
| 153 |
+
buffered = BytesIO()
|
| 154 |
+
image.save(buffered, format="PNG")
|
| 155 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 156 |
+
images.append(img_b64_str)
|
| 157 |
return images
|
| 158 |
|
| 159 |
def to_gradio_chatbot(self):
|
|
|
|
| 161 |
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
| 162 |
if i % 2 == 0:
|
| 163 |
if type(msg) is tuple:
|
| 164 |
+
import base64
|
| 165 |
+
from io import BytesIO
|
| 166 |
msg, image, image_process_mode = msg
|
| 167 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
| 168 |
+
aspect_ratio = max_hw / min_hw
|
| 169 |
+
max_len, min_len = 800, 400
|
| 170 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
| 171 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
| 172 |
+
W, H = image.size
|
| 173 |
+
if H > W:
|
| 174 |
+
H, W = longest_edge, shortest_edge
|
| 175 |
+
else:
|
| 176 |
+
H, W = shortest_edge, longest_edge
|
| 177 |
+
image = image.resize((W, H))
|
| 178 |
+
buffered = BytesIO()
|
| 179 |
+
image.save(buffered, format="JPEG")
|
| 180 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 181 |
+
img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="user upload image" />'
|
| 182 |
msg = img_str + msg.replace('<image>', '').strip()
|
| 183 |
ret.append([msg, None])
|
| 184 |
else:
|
|
|
|
| 357 |
version="v1_mmtag",
|
| 358 |
)
|
| 359 |
|
| 360 |
+
default_conversation = conv_vicuna_v0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
conv_templates = {
|
| 362 |
"default": conv_vicuna_v0,
|
| 363 |
"v0": conv_vicuna_v0,
|
| 364 |
"v1": conv_vicuna_v1,
|
| 365 |
"vicuna_v1": conv_vicuna_v1,
|
| 366 |
"llama_2": conv_llama_2,
|
|
|
|
|
|
|
|
|
|
| 367 |
|
| 368 |
"plain": conv_llava_plain,
|
| 369 |
"v0_plain": conv_llava_plain,
|
llava/eval/eval_pope.py
DELETED
|
@@ -1,81 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
import argparse
|
| 4 |
-
|
| 5 |
-
def eval_pope(answers, label_file):
|
| 6 |
-
label_list = [json.loads(q)['label'] for q in open(label_file, 'r')]
|
| 7 |
-
|
| 8 |
-
for answer in answers:
|
| 9 |
-
text = answer['text']
|
| 10 |
-
|
| 11 |
-
# Only keep the first sentence
|
| 12 |
-
if text.find('.') != -1:
|
| 13 |
-
text = text.split('.')[0]
|
| 14 |
-
|
| 15 |
-
text = text.replace(',', '')
|
| 16 |
-
words = text.split(' ')
|
| 17 |
-
if 'No' in words or 'not' in words or 'no' in words:
|
| 18 |
-
answer['text'] = 'no'
|
| 19 |
-
else:
|
| 20 |
-
answer['text'] = 'yes'
|
| 21 |
-
|
| 22 |
-
for i in range(len(label_list)):
|
| 23 |
-
if label_list[i] == 'no':
|
| 24 |
-
label_list[i] = 0
|
| 25 |
-
else:
|
| 26 |
-
label_list[i] = 1
|
| 27 |
-
|
| 28 |
-
pred_list = []
|
| 29 |
-
for answer in answers:
|
| 30 |
-
if answer['text'] == 'no':
|
| 31 |
-
pred_list.append(0)
|
| 32 |
-
else:
|
| 33 |
-
pred_list.append(1)
|
| 34 |
-
|
| 35 |
-
pos = 1
|
| 36 |
-
neg = 0
|
| 37 |
-
yes_ratio = pred_list.count(1) / len(pred_list)
|
| 38 |
-
|
| 39 |
-
TP, TN, FP, FN = 0, 0, 0, 0
|
| 40 |
-
for pred, label in zip(pred_list, label_list):
|
| 41 |
-
if pred == pos and label == pos:
|
| 42 |
-
TP += 1
|
| 43 |
-
elif pred == pos and label == neg:
|
| 44 |
-
FP += 1
|
| 45 |
-
elif pred == neg and label == neg:
|
| 46 |
-
TN += 1
|
| 47 |
-
elif pred == neg and label == pos:
|
| 48 |
-
FN += 1
|
| 49 |
-
|
| 50 |
-
print('TP\tFP\tTN\tFN\t')
|
| 51 |
-
print('{}\t{}\t{}\t{}'.format(TP, FP, TN, FN))
|
| 52 |
-
|
| 53 |
-
precision = float(TP) / float(TP + FP)
|
| 54 |
-
recall = float(TP) / float(TP + FN)
|
| 55 |
-
f1 = 2*precision*recall / (precision + recall)
|
| 56 |
-
acc = (TP + TN) / (TP + TN + FP + FN)
|
| 57 |
-
print('Accuracy: {}'.format(acc))
|
| 58 |
-
print('Precision: {}'.format(precision))
|
| 59 |
-
print('Recall: {}'.format(recall))
|
| 60 |
-
print('F1 score: {}'.format(f1))
|
| 61 |
-
print('Yes ratio: {}'.format(yes_ratio))
|
| 62 |
-
print('%.3f, %.3f, %.3f, %.3f, %.3f' % (f1, acc, precision, recall, yes_ratio) )
|
| 63 |
-
|
| 64 |
-
if __name__ == "__main__":
|
| 65 |
-
parser = argparse.ArgumentParser()
|
| 66 |
-
parser.add_argument("--annotation-dir", type=str)
|
| 67 |
-
parser.add_argument("--question-file", type=str)
|
| 68 |
-
parser.add_argument("--result-file", type=str)
|
| 69 |
-
args = parser.parse_args()
|
| 70 |
-
|
| 71 |
-
questions = [json.loads(line) for line in open(args.question_file)]
|
| 72 |
-
questions = {question['question_id']: question for question in questions}
|
| 73 |
-
answers = [json.loads(q) for q in open(args.result_file)]
|
| 74 |
-
for file in os.listdir(args.annotation_dir):
|
| 75 |
-
assert file.startswith('coco_pope_')
|
| 76 |
-
assert file.endswith('.json')
|
| 77 |
-
category = file[10:-5]
|
| 78 |
-
cur_answers = [x for x in answers if questions[x['question_id']]['category'] == category]
|
| 79 |
-
print('Category: {}, # samples: {}'.format(category, len(cur_answers)))
|
| 80 |
-
eval_pope(cur_answers, os.path.join(args.annotation_dir, file))
|
| 81 |
-
print("====================================")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
llava/eval/eval_science_qa.py
CHANGED
|
@@ -32,7 +32,6 @@ def get_pred_idx(prediction, choices, options):
|
|
| 32 |
if prediction in options[:len(choices)]:
|
| 33 |
return options.index(prediction)
|
| 34 |
else:
|
| 35 |
-
return -1
|
| 36 |
return random.choice(range(len(choices)))
|
| 37 |
|
| 38 |
|
|
@@ -56,23 +55,16 @@ if __name__ == "__main__":
|
|
| 56 |
|
| 57 |
for prob_id, prob in split_problems.items():
|
| 58 |
if prob_id not in predictions:
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
else:
|
| 62 |
-
|
| 63 |
-
pred_text = pred['text']
|
| 64 |
-
|
| 65 |
-
if pred_text in args.options:
|
| 66 |
-
answer = pred_text
|
| 67 |
-
elif len(pred_text) >= 3 and pred_text[0] in args.options and pred_text[1:3] == ". ":
|
| 68 |
-
answer = pred_text[0]
|
| 69 |
-
else:
|
| 70 |
-
pattern = re.compile(r'The answer is ([A-Z]).')
|
| 71 |
-
res = pattern.findall(pred_text)
|
| 72 |
-
if len(res) == 1:
|
| 73 |
-
answer = res[0] # 'A', 'B', ...
|
| 74 |
-
else:
|
| 75 |
-
answer = "FAILED"
|
| 76 |
|
| 77 |
pred_idx = get_pred_idx(answer, prob['choices'], args.options)
|
| 78 |
|
|
@@ -95,14 +87,7 @@ if __name__ == "__main__":
|
|
| 95 |
|
| 96 |
correct = len(results['correct'])
|
| 97 |
total = len(results['correct']) + len(results['incorrect'])
|
| 98 |
-
|
| 99 |
-
###### IMG ######
|
| 100 |
-
multimodal_correct = len([x for x in results['correct'] if x['is_multimodal']])
|
| 101 |
-
multimodal_incorrect = len([x for x in results['incorrect'] if x['is_multimodal']])
|
| 102 |
-
multimodal_total = multimodal_correct + multimodal_incorrect
|
| 103 |
-
###### IMG ######
|
| 104 |
-
|
| 105 |
-
print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%, IMG-Accuracy: {multimodal_correct / multimodal_total * 100:.2f}%')
|
| 106 |
|
| 107 |
sqa_results['acc'] = correct / total * 100
|
| 108 |
sqa_results['correct'] = correct
|
|
|
|
| 32 |
if prediction in options[:len(choices)]:
|
| 33 |
return options.index(prediction)
|
| 34 |
else:
|
|
|
|
| 35 |
return random.choice(range(len(choices)))
|
| 36 |
|
| 37 |
|
|
|
|
| 55 |
|
| 56 |
for prob_id, prob in split_problems.items():
|
| 57 |
if prob_id not in predictions:
|
| 58 |
+
continue
|
| 59 |
+
pred = predictions[prob_id]
|
| 60 |
+
pred_text = pred['text']
|
| 61 |
+
|
| 62 |
+
pattern = re.compile(r'The answer is ([A-Z]).')
|
| 63 |
+
res = pattern.findall(pred_text)
|
| 64 |
+
if len(res) == 1:
|
| 65 |
+
answer = res[0] # 'A', 'B', ...
|
| 66 |
else:
|
| 67 |
+
answer = "FAILED"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
pred_idx = get_pred_idx(answer, prob['choices'], args.options)
|
| 70 |
|
|
|
|
| 87 |
|
| 88 |
correct = len(results['correct'])
|
| 89 |
total = len(results['correct']) + len(results['incorrect'])
|
| 90 |
+
print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
sqa_results['acc'] = correct / total * 100
|
| 93 |
sqa_results['correct'] = correct
|
llava/eval/eval_textvqa.py
DELETED
|
@@ -1,65 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import argparse
|
| 3 |
-
import json
|
| 4 |
-
import re
|
| 5 |
-
|
| 6 |
-
from llava.eval.m4c_evaluator import TextVQAAccuracyEvaluator
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
def get_args():
|
| 10 |
-
parser = argparse.ArgumentParser()
|
| 11 |
-
parser.add_argument('--annotation-file', type=str)
|
| 12 |
-
parser.add_argument('--result-file', type=str)
|
| 13 |
-
parser.add_argument('--result-dir', type=str)
|
| 14 |
-
return parser.parse_args()
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def prompt_processor(prompt):
|
| 18 |
-
if prompt.startswith('OCR tokens: '):
|
| 19 |
-
pattern = r"Question: (.*?) Short answer:"
|
| 20 |
-
match = re.search(pattern, prompt, re.DOTALL)
|
| 21 |
-
question = match.group(1)
|
| 22 |
-
elif 'Reference OCR token: ' in prompt and len(prompt.split('\n')) == 3:
|
| 23 |
-
if prompt.startswith('Reference OCR token:'):
|
| 24 |
-
question = prompt.split('\n')[1]
|
| 25 |
-
else:
|
| 26 |
-
question = prompt.split('\n')[0]
|
| 27 |
-
elif len(prompt.split('\n')) == 2:
|
| 28 |
-
question = prompt.split('\n')[0]
|
| 29 |
-
else:
|
| 30 |
-
assert False
|
| 31 |
-
|
| 32 |
-
return question.lower()
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
def eval_single(annotation_file, result_file):
|
| 36 |
-
experiment_name = os.path.splitext(os.path.basename(result_file))[0]
|
| 37 |
-
print(experiment_name)
|
| 38 |
-
annotations = json.load(open(annotation_file))['data']
|
| 39 |
-
annotations = {(annotation['image_id'], annotation['question'].lower()): annotation for annotation in annotations}
|
| 40 |
-
results = [json.loads(line) for line in open(result_file)]
|
| 41 |
-
|
| 42 |
-
pred_list = []
|
| 43 |
-
for result in results:
|
| 44 |
-
annotation = annotations[(result['question_id'], prompt_processor(result['prompt']))]
|
| 45 |
-
pred_list.append({
|
| 46 |
-
"pred_answer": result['text'],
|
| 47 |
-
"gt_answers": annotation['answers'],
|
| 48 |
-
})
|
| 49 |
-
|
| 50 |
-
evaluator = TextVQAAccuracyEvaluator()
|
| 51 |
-
print('Samples: {}\nAccuracy: {:.2f}%\n'.format(len(pred_list), 100. * evaluator.eval_pred_list(pred_list)))
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
if __name__ == "__main__":
|
| 55 |
-
args = get_args()
|
| 56 |
-
|
| 57 |
-
if args.result_file is not None:
|
| 58 |
-
eval_single(args.annotation_file, args.result_file)
|
| 59 |
-
|
| 60 |
-
if args.result_dir is not None:
|
| 61 |
-
for result_file in sorted(os.listdir(args.result_dir)):
|
| 62 |
-
if not result_file.endswith('.jsonl'):
|
| 63 |
-
print(f'Skipping {result_file}')
|
| 64 |
-
continue
|
| 65 |
-
eval_single(args.annotation_file, os.path.join(args.result_dir, result_file))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
llava/eval/m4c_evaluator.py
DELETED
|
@@ -1,334 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
import re
|
| 3 |
-
|
| 4 |
-
from tqdm import tqdm
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
class EvalAIAnswerProcessor:
|
| 8 |
-
"""
|
| 9 |
-
Processes an answer similar to Eval AI
|
| 10 |
-
copied from
|
| 11 |
-
https://github.com/facebookresearch/mmf/blob/c46b3b3391275b4181567db80943473a89ab98ab/pythia/tasks/processors.py#L897
|
| 12 |
-
"""
|
| 13 |
-
|
| 14 |
-
CONTRACTIONS = {
|
| 15 |
-
"aint": "ain't",
|
| 16 |
-
"arent": "aren't",
|
| 17 |
-
"cant": "can't",
|
| 18 |
-
"couldve": "could've",
|
| 19 |
-
"couldnt": "couldn't",
|
| 20 |
-
"couldn'tve": "couldn't've",
|
| 21 |
-
"couldnt've": "couldn't've",
|
| 22 |
-
"didnt": "didn't",
|
| 23 |
-
"doesnt": "doesn't",
|
| 24 |
-
"dont": "don't",
|
| 25 |
-
"hadnt": "hadn't",
|
| 26 |
-
"hadnt've": "hadn't've",
|
| 27 |
-
"hadn'tve": "hadn't've",
|
| 28 |
-
"hasnt": "hasn't",
|
| 29 |
-
"havent": "haven't",
|
| 30 |
-
"hed": "he'd",
|
| 31 |
-
"hed've": "he'd've",
|
| 32 |
-
"he'dve": "he'd've",
|
| 33 |
-
"hes": "he's",
|
| 34 |
-
"howd": "how'd",
|
| 35 |
-
"howll": "how'll",
|
| 36 |
-
"hows": "how's",
|
| 37 |
-
"Id've": "I'd've",
|
| 38 |
-
"I'dve": "I'd've",
|
| 39 |
-
"Im": "I'm",
|
| 40 |
-
"Ive": "I've",
|
| 41 |
-
"isnt": "isn't",
|
| 42 |
-
"itd": "it'd",
|
| 43 |
-
"itd've": "it'd've",
|
| 44 |
-
"it'dve": "it'd've",
|
| 45 |
-
"itll": "it'll",
|
| 46 |
-
"let's": "let's",
|
| 47 |
-
"maam": "ma'am",
|
| 48 |
-
"mightnt": "mightn't",
|
| 49 |
-
"mightnt've": "mightn't've",
|
| 50 |
-
"mightn'tve": "mightn't've",
|
| 51 |
-
"mightve": "might've",
|
| 52 |
-
"mustnt": "mustn't",
|
| 53 |
-
"mustve": "must've",
|
| 54 |
-
"neednt": "needn't",
|
| 55 |
-
"notve": "not've",
|
| 56 |
-
"oclock": "o'clock",
|
| 57 |
-
"oughtnt": "oughtn't",
|
| 58 |
-
"ow's'at": "'ow's'at",
|
| 59 |
-
"'ows'at": "'ow's'at",
|
| 60 |
-
"'ow'sat": "'ow's'at",
|
| 61 |
-
"shant": "shan't",
|
| 62 |
-
"shed've": "she'd've",
|
| 63 |
-
"she'dve": "she'd've",
|
| 64 |
-
"she's": "she's",
|
| 65 |
-
"shouldve": "should've",
|
| 66 |
-
"shouldnt": "shouldn't",
|
| 67 |
-
"shouldnt've": "shouldn't've",
|
| 68 |
-
"shouldn'tve": "shouldn't've",
|
| 69 |
-
"somebody'd": "somebodyd",
|
| 70 |
-
"somebodyd've": "somebody'd've",
|
| 71 |
-
"somebody'dve": "somebody'd've",
|
| 72 |
-
"somebodyll": "somebody'll",
|
| 73 |
-
"somebodys": "somebody's",
|
| 74 |
-
"someoned": "someone'd",
|
| 75 |
-
"someoned've": "someone'd've",
|
| 76 |
-
"someone'dve": "someone'd've",
|
| 77 |
-
"someonell": "someone'll",
|
| 78 |
-
"someones": "someone's",
|
| 79 |
-
"somethingd": "something'd",
|
| 80 |
-
"somethingd've": "something'd've",
|
| 81 |
-
"something'dve": "something'd've",
|
| 82 |
-
"somethingll": "something'll",
|
| 83 |
-
"thats": "that's",
|
| 84 |
-
"thered": "there'd",
|
| 85 |
-
"thered've": "there'd've",
|
| 86 |
-
"there'dve": "there'd've",
|
| 87 |
-
"therere": "there're",
|
| 88 |
-
"theres": "there's",
|
| 89 |
-
"theyd": "they'd",
|
| 90 |
-
"theyd've": "they'd've",
|
| 91 |
-
"they'dve": "they'd've",
|
| 92 |
-
"theyll": "they'll",
|
| 93 |
-
"theyre": "they're",
|
| 94 |
-
"theyve": "they've",
|
| 95 |
-
"twas": "'twas",
|
| 96 |
-
"wasnt": "wasn't",
|
| 97 |
-
"wed've": "we'd've",
|
| 98 |
-
"we'dve": "we'd've",
|
| 99 |
-
"weve": "we've",
|
| 100 |
-
"werent": "weren't",
|
| 101 |
-
"whatll": "what'll",
|
| 102 |
-
"whatre": "what're",
|
| 103 |
-
"whats": "what's",
|
| 104 |
-
"whatve": "what've",
|
| 105 |
-
"whens": "when's",
|
| 106 |
-
"whered": "where'd",
|
| 107 |
-
"wheres": "where's",
|
| 108 |
-
"whereve": "where've",
|
| 109 |
-
"whod": "who'd",
|
| 110 |
-
"whod've": "who'd've",
|
| 111 |
-
"who'dve": "who'd've",
|
| 112 |
-
"wholl": "who'll",
|
| 113 |
-
"whos": "who's",
|
| 114 |
-
"whove": "who've",
|
| 115 |
-
"whyll": "why'll",
|
| 116 |
-
"whyre": "why're",
|
| 117 |
-
"whys": "why's",
|
| 118 |
-
"wont": "won't",
|
| 119 |
-
"wouldve": "would've",
|
| 120 |
-
"wouldnt": "wouldn't",
|
| 121 |
-
"wouldnt've": "wouldn't've",
|
| 122 |
-
"wouldn'tve": "wouldn't've",
|
| 123 |
-
"yall": "y'all",
|
| 124 |
-
"yall'll": "y'all'll",
|
| 125 |
-
"y'allll": "y'all'll",
|
| 126 |
-
"yall'd've": "y'all'd've",
|
| 127 |
-
"y'alld've": "y'all'd've",
|
| 128 |
-
"y'all'dve": "y'all'd've",
|
| 129 |
-
"youd": "you'd",
|
| 130 |
-
"youd've": "you'd've",
|
| 131 |
-
"you'dve": "you'd've",
|
| 132 |
-
"youll": "you'll",
|
| 133 |
-
"youre": "you're",
|
| 134 |
-
"youve": "you've",
|
| 135 |
-
}
|
| 136 |
-
|
| 137 |
-
NUMBER_MAP = {
|
| 138 |
-
"none": "0",
|
| 139 |
-
"zero": "0",
|
| 140 |
-
"one": "1",
|
| 141 |
-
"two": "2",
|
| 142 |
-
"three": "3",
|
| 143 |
-
"four": "4",
|
| 144 |
-
"five": "5",
|
| 145 |
-
"six": "6",
|
| 146 |
-
"seven": "7",
|
| 147 |
-
"eight": "8",
|
| 148 |
-
"nine": "9",
|
| 149 |
-
"ten": "10",
|
| 150 |
-
}
|
| 151 |
-
ARTICLES = ["a", "an", "the"]
|
| 152 |
-
PERIOD_STRIP = re.compile(r"(?!<=\d)(\.)(?!\d)")
|
| 153 |
-
COMMA_STRIP = re.compile(r"(?<=\d)(\,)+(?=\d)")
|
| 154 |
-
PUNCTUATIONS = [
|
| 155 |
-
";",
|
| 156 |
-
r"/",
|
| 157 |
-
"[",
|
| 158 |
-
"]",
|
| 159 |
-
'"',
|
| 160 |
-
"{",
|
| 161 |
-
"}",
|
| 162 |
-
"(",
|
| 163 |
-
")",
|
| 164 |
-
"=",
|
| 165 |
-
"+",
|
| 166 |
-
"\\",
|
| 167 |
-
"_",
|
| 168 |
-
"-",
|
| 169 |
-
">",
|
| 170 |
-
"<",
|
| 171 |
-
"@",
|
| 172 |
-
"`",
|
| 173 |
-
",",
|
| 174 |
-
"?",
|
| 175 |
-
"!",
|
| 176 |
-
]
|
| 177 |
-
|
| 178 |
-
def __init__(self, *args, **kwargs):
|
| 179 |
-
pass
|
| 180 |
-
|
| 181 |
-
def word_tokenize(self, word):
|
| 182 |
-
word = word.lower()
|
| 183 |
-
word = word.replace(",", "").replace("?", "").replace("'s", " 's")
|
| 184 |
-
return word.strip()
|
| 185 |
-
|
| 186 |
-
def process_punctuation(self, in_text):
|
| 187 |
-
out_text = in_text
|
| 188 |
-
for p in self.PUNCTUATIONS:
|
| 189 |
-
if (p + " " in in_text or " " + p in in_text) or (
|
| 190 |
-
re.search(self.COMMA_STRIP, in_text) is not None
|
| 191 |
-
):
|
| 192 |
-
out_text = out_text.replace(p, "")
|
| 193 |
-
else:
|
| 194 |
-
out_text = out_text.replace(p, " ")
|
| 195 |
-
out_text = self.PERIOD_STRIP.sub("", out_text, re.UNICODE)
|
| 196 |
-
return out_text
|
| 197 |
-
|
| 198 |
-
def process_digit_article(self, in_text):
|
| 199 |
-
out_text = []
|
| 200 |
-
temp_text = in_text.lower().split()
|
| 201 |
-
for word in temp_text:
|
| 202 |
-
word = self.NUMBER_MAP.setdefault(word, word)
|
| 203 |
-
if word not in self.ARTICLES:
|
| 204 |
-
out_text.append(word)
|
| 205 |
-
else:
|
| 206 |
-
pass
|
| 207 |
-
for word_id, word in enumerate(out_text):
|
| 208 |
-
if word in self.CONTRACTIONS:
|
| 209 |
-
out_text[word_id] = self.CONTRACTIONS[word]
|
| 210 |
-
out_text = " ".join(out_text)
|
| 211 |
-
return out_text
|
| 212 |
-
|
| 213 |
-
def __call__(self, item):
|
| 214 |
-
item = self.word_tokenize(item)
|
| 215 |
-
item = item.replace("\n", " ").replace("\t", " ").strip()
|
| 216 |
-
item = self.process_punctuation(item)
|
| 217 |
-
item = self.process_digit_article(item)
|
| 218 |
-
return item
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
class TextVQAAccuracyEvaluator:
|
| 222 |
-
def __init__(self):
|
| 223 |
-
self.answer_processor = EvalAIAnswerProcessor()
|
| 224 |
-
|
| 225 |
-
def _compute_answer_scores(self, raw_answers):
|
| 226 |
-
"""
|
| 227 |
-
compute the accuracy (soft score) of human answers
|
| 228 |
-
"""
|
| 229 |
-
answers = [self.answer_processor(a) for a in raw_answers]
|
| 230 |
-
assert len(answers) == 10
|
| 231 |
-
gt_answers = list(enumerate(answers))
|
| 232 |
-
unique_answers = set(answers)
|
| 233 |
-
unique_answer_scores = {}
|
| 234 |
-
|
| 235 |
-
for unique_answer in unique_answers:
|
| 236 |
-
accs = []
|
| 237 |
-
for gt_answer in gt_answers:
|
| 238 |
-
other_answers = [item for item in gt_answers if item != gt_answer]
|
| 239 |
-
matching_answers = [
|
| 240 |
-
item for item in other_answers if item[1] == unique_answer
|
| 241 |
-
]
|
| 242 |
-
acc = min(1, float(len(matching_answers)) / 3)
|
| 243 |
-
accs.append(acc)
|
| 244 |
-
unique_answer_scores[unique_answer] = sum(accs) / len(accs)
|
| 245 |
-
|
| 246 |
-
return unique_answer_scores
|
| 247 |
-
|
| 248 |
-
def eval_pred_list(self, pred_list):
|
| 249 |
-
pred_scores = []
|
| 250 |
-
for entry in tqdm(pred_list):
|
| 251 |
-
pred_answer = self.answer_processor(entry["pred_answer"])
|
| 252 |
-
unique_answer_scores = self._compute_answer_scores(entry["gt_answers"])
|
| 253 |
-
score = unique_answer_scores.get(pred_answer, 0.0)
|
| 254 |
-
pred_scores.append(score)
|
| 255 |
-
|
| 256 |
-
accuracy = sum(pred_scores) / len(pred_scores)
|
| 257 |
-
return accuracy
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
class STVQAAccuracyEvaluator:
|
| 261 |
-
def __init__(self):
|
| 262 |
-
self.answer_processor = EvalAIAnswerProcessor()
|
| 263 |
-
|
| 264 |
-
def eval_pred_list(self, pred_list):
|
| 265 |
-
pred_scores = []
|
| 266 |
-
for entry in pred_list:
|
| 267 |
-
pred_answer = self.answer_processor(entry["pred_answer"])
|
| 268 |
-
gts = [self.answer_processor(a) for a in entry["gt_answers"]]
|
| 269 |
-
score = 1.0 if pred_answer in gts else 0.0
|
| 270 |
-
pred_scores.append(score)
|
| 271 |
-
|
| 272 |
-
accuracy = sum(pred_scores) / len(pred_scores)
|
| 273 |
-
return accuracy
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
class STVQAANLSEvaluator:
|
| 277 |
-
def __init__(self):
|
| 278 |
-
import editdistance # install with `pip install editdistance`
|
| 279 |
-
|
| 280 |
-
self.get_edit_distance = editdistance.eval
|
| 281 |
-
|
| 282 |
-
def get_anls(self, s1, s2):
|
| 283 |
-
s1 = s1.lower().strip()
|
| 284 |
-
s2 = s2.lower().strip()
|
| 285 |
-
iou = 1 - self.get_edit_distance(s1, s2) / max(len(s1), len(s2))
|
| 286 |
-
anls = iou if iou >= 0.5 else 0.0
|
| 287 |
-
return anls
|
| 288 |
-
|
| 289 |
-
def eval_pred_list(self, pred_list):
|
| 290 |
-
pred_scores = []
|
| 291 |
-
for entry in pred_list:
|
| 292 |
-
anls = max(
|
| 293 |
-
self.get_anls(entry["pred_answer"], gt) for gt in entry["gt_answers"]
|
| 294 |
-
)
|
| 295 |
-
pred_scores.append(anls)
|
| 296 |
-
|
| 297 |
-
accuracy = sum(pred_scores) / len(pred_scores)
|
| 298 |
-
return accuracy
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
class TextCapsBleu4Evaluator:
|
| 302 |
-
def __init__(self):
|
| 303 |
-
# The following script requires Java 1.8.0 and pycocotools installed.
|
| 304 |
-
# The pycocoevalcap can be installed with pip as
|
| 305 |
-
# pip install git+https://github.com/ronghanghu/coco-caption.git@python23
|
| 306 |
-
# Original pycocoevalcap code is at https://github.com/tylin/coco-caption
|
| 307 |
-
# but has no python3 support yet.
|
| 308 |
-
try:
|
| 309 |
-
from pycocoevalcap.bleu.bleu import Bleu
|
| 310 |
-
from pycocoevalcap.tokenizer.ptbtokenizer import PTBTokenizer
|
| 311 |
-
except ModuleNotFoundError:
|
| 312 |
-
print(
|
| 313 |
-
"Please install pycocoevalcap module using "
|
| 314 |
-
"pip install git+https://github.com/ronghanghu/coco-caption.git@python23" # noqa
|
| 315 |
-
)
|
| 316 |
-
raise
|
| 317 |
-
|
| 318 |
-
self.tokenizer = PTBTokenizer()
|
| 319 |
-
self.scorer = Bleu(4)
|
| 320 |
-
|
| 321 |
-
def eval_pred_list(self, pred_list):
|
| 322 |
-
# Create reference and hypotheses captions.
|
| 323 |
-
gts = {}
|
| 324 |
-
res = {}
|
| 325 |
-
for idx, entry in enumerate(pred_list):
|
| 326 |
-
gts[idx] = [{"caption": a} for a in entry["gt_answers"]]
|
| 327 |
-
res[idx] = [{"caption": entry["pred_answer"]}]
|
| 328 |
-
|
| 329 |
-
gts = self.tokenizer.tokenize(gts)
|
| 330 |
-
res = self.tokenizer.tokenize(res)
|
| 331 |
-
score, _ = self.scorer.compute_score(gts, res)
|
| 332 |
-
|
| 333 |
-
bleu4 = score[3] # score is (Bleu-1, Bleu-2, Bleu-3, Bleu-4)
|
| 334 |
-
return bleu4
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
llava/eval/model_qa.py
CHANGED
|
@@ -10,6 +10,25 @@ from llava.conversation import default_conversation
|
|
| 10 |
from llava.utils import disable_torch_init
|
| 11 |
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
@torch.inference_mode()
|
| 14 |
def eval_model(model_name, questions_file, answers_file):
|
| 15 |
# Model
|
|
@@ -31,12 +50,14 @@ def eval_model(model_name, questions_file, answers_file):
|
|
| 31 |
prompt = conv.get_prompt()
|
| 32 |
inputs = tokenizer([prompt])
|
| 33 |
input_ids = torch.as_tensor(inputs.input_ids).cuda()
|
|
|
|
| 34 |
output_ids = model.generate(
|
| 35 |
input_ids,
|
| 36 |
do_sample=True,
|
| 37 |
use_cache=True,
|
| 38 |
temperature=0.7,
|
| 39 |
-
max_new_tokens=1024,
|
|
|
|
| 40 |
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
|
| 41 |
try:
|
| 42 |
index = outputs.index(conv.sep, len(prompt))
|
|
|
|
| 10 |
from llava.utils import disable_torch_init
|
| 11 |
|
| 12 |
|
| 13 |
+
# new stopping implementation
|
| 14 |
+
class KeywordsStoppingCriteria(StoppingCriteria):
|
| 15 |
+
def __init__(self, keywords, tokenizer, input_ids):
|
| 16 |
+
self.keywords = keywords
|
| 17 |
+
self.tokenizer = tokenizer
|
| 18 |
+
self.start_len = None
|
| 19 |
+
self.input_ids = input_ids
|
| 20 |
+
|
| 21 |
+
def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
| 22 |
+
if self.start_len is None:
|
| 23 |
+
self.start_len = self.input_ids.shape[1]
|
| 24 |
+
else:
|
| 25 |
+
outputs = self.tokenizer.batch_decode(output_ids[:, self.start_len:], skip_special_tokens=True)[0]
|
| 26 |
+
for keyword in self.keywords:
|
| 27 |
+
if keyword in outputs:
|
| 28 |
+
return True
|
| 29 |
+
return False
|
| 30 |
+
|
| 31 |
+
|
| 32 |
@torch.inference_mode()
|
| 33 |
def eval_model(model_name, questions_file, answers_file):
|
| 34 |
# Model
|
|
|
|
| 50 |
prompt = conv.get_prompt()
|
| 51 |
inputs = tokenizer([prompt])
|
| 52 |
input_ids = torch.as_tensor(inputs.input_ids).cuda()
|
| 53 |
+
stopping_criteria = KeywordsStoppingCriteria([conv.sep], tokenizer, input_ids)
|
| 54 |
output_ids = model.generate(
|
| 55 |
input_ids,
|
| 56 |
do_sample=True,
|
| 57 |
use_cache=True,
|
| 58 |
temperature=0.7,
|
| 59 |
+
max_new_tokens=1024,
|
| 60 |
+
stopping_criteria=[stopping_criteria])
|
| 61 |
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
|
| 62 |
try:
|
| 63 |
index = outputs.index(conv.sep, len(prompt))
|
llava/eval/model_vqa.py
CHANGED
|
@@ -9,7 +9,7 @@ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_S
|
|
| 9 |
from llava.conversation import conv_templates, SeparatorStyle
|
| 10 |
from llava.model.builder import load_pretrained_model
|
| 11 |
from llava.utils import disable_torch_init
|
| 12 |
-
from llava.mm_utils import tokenizer_image_token,
|
| 13 |
|
| 14 |
from PIL import Image
|
| 15 |
import math
|
|
@@ -55,15 +55,18 @@ def eval_model(args):
|
|
| 55 |
|
| 56 |
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
| 57 |
|
| 58 |
-
image = Image.open(os.path.join(args.image_folder, image_file))
|
| 59 |
-
image_tensor =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
with torch.inference_mode():
|
| 62 |
output_ids = model.generate(
|
| 63 |
input_ids,
|
| 64 |
images=image_tensor.unsqueeze(0).half().cuda(),
|
| 65 |
-
|
| 66 |
-
do_sample=True if args.temperature > 0 else False,
|
| 67 |
temperature=args.temperature,
|
| 68 |
top_p=args.top_p,
|
| 69 |
num_beams=args.num_beams,
|
|
@@ -71,7 +74,15 @@ def eval_model(args):
|
|
| 71 |
max_new_tokens=1024,
|
| 72 |
use_cache=True)
|
| 73 |
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
ans_id = shortuuid.uuid()
|
| 77 |
ans_file.write(json.dumps({"question_id": idx,
|
|
|
|
| 9 |
from llava.conversation import conv_templates, SeparatorStyle
|
| 10 |
from llava.model.builder import load_pretrained_model
|
| 11 |
from llava.utils import disable_torch_init
|
| 12 |
+
from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
|
| 13 |
|
| 14 |
from PIL import Image
|
| 15 |
import math
|
|
|
|
| 55 |
|
| 56 |
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
| 57 |
|
| 58 |
+
image = Image.open(os.path.join(args.image_folder, image_file))
|
| 59 |
+
image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
| 60 |
+
|
| 61 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
| 62 |
+
keywords = [stop_str]
|
| 63 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
| 64 |
|
| 65 |
with torch.inference_mode():
|
| 66 |
output_ids = model.generate(
|
| 67 |
input_ids,
|
| 68 |
images=image_tensor.unsqueeze(0).half().cuda(),
|
| 69 |
+
do_sample=True,
|
|
|
|
| 70 |
temperature=args.temperature,
|
| 71 |
top_p=args.top_p,
|
| 72 |
num_beams=args.num_beams,
|
|
|
|
| 74 |
max_new_tokens=1024,
|
| 75 |
use_cache=True)
|
| 76 |
|
| 77 |
+
input_token_len = input_ids.shape[1]
|
| 78 |
+
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
|
| 79 |
+
if n_diff_input_output > 0:
|
| 80 |
+
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
|
| 81 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
|
| 82 |
+
outputs = outputs.strip()
|
| 83 |
+
if outputs.endswith(stop_str):
|
| 84 |
+
outputs = outputs[:-len(stop_str)]
|
| 85 |
+
outputs = outputs.strip()
|
| 86 |
|
| 87 |
ans_id = shortuuid.uuid()
|
| 88 |
ans_file.write(json.dumps({"question_id": idx,
|
llava/eval/model_vqa_loader.py
DELETED
|
@@ -1,144 +0,0 @@
|
|
| 1 |
-
import argparse
|
| 2 |
-
import torch
|
| 3 |
-
import os
|
| 4 |
-
import json
|
| 5 |
-
from tqdm import tqdm
|
| 6 |
-
import shortuuid
|
| 7 |
-
|
| 8 |
-
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 9 |
-
from llava.conversation import conv_templates, SeparatorStyle
|
| 10 |
-
from llava.model.builder import load_pretrained_model
|
| 11 |
-
from llava.utils import disable_torch_init
|
| 12 |
-
from llava.mm_utils import tokenizer_image_token, process_images, get_model_name_from_path
|
| 13 |
-
from torch.utils.data import Dataset, DataLoader
|
| 14 |
-
|
| 15 |
-
from PIL import Image
|
| 16 |
-
import math
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
def split_list(lst, n):
|
| 20 |
-
"""Split a list into n (roughly) equal-sized chunks"""
|
| 21 |
-
chunk_size = math.ceil(len(lst) / n) # integer division
|
| 22 |
-
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
def get_chunk(lst, n, k):
|
| 26 |
-
chunks = split_list(lst, n)
|
| 27 |
-
return chunks[k]
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
# Custom dataset class
|
| 31 |
-
class CustomDataset(Dataset):
|
| 32 |
-
def __init__(self, questions, image_folder, tokenizer, image_processor, model_config):
|
| 33 |
-
self.questions = questions
|
| 34 |
-
self.image_folder = image_folder
|
| 35 |
-
self.tokenizer = tokenizer
|
| 36 |
-
self.image_processor = image_processor
|
| 37 |
-
self.model_config = model_config
|
| 38 |
-
|
| 39 |
-
def __getitem__(self, index):
|
| 40 |
-
line = self.questions[index]
|
| 41 |
-
image_file = line["image"]
|
| 42 |
-
qs = line["text"]
|
| 43 |
-
if self.model_config.mm_use_im_start_end:
|
| 44 |
-
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
| 45 |
-
else:
|
| 46 |
-
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
| 47 |
-
|
| 48 |
-
conv = conv_templates[args.conv_mode].copy()
|
| 49 |
-
conv.append_message(conv.roles[0], qs)
|
| 50 |
-
conv.append_message(conv.roles[1], None)
|
| 51 |
-
prompt = conv.get_prompt()
|
| 52 |
-
|
| 53 |
-
image = Image.open(os.path.join(self.image_folder, image_file)).convert('RGB')
|
| 54 |
-
image_tensor = process_images([image], self.image_processor, self.model_config)[0]
|
| 55 |
-
|
| 56 |
-
input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt')
|
| 57 |
-
|
| 58 |
-
return input_ids, image_tensor, image.size
|
| 59 |
-
|
| 60 |
-
def __len__(self):
|
| 61 |
-
return len(self.questions)
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
def collate_fn(batch):
|
| 65 |
-
input_ids, image_tensors, image_sizes = zip(*batch)
|
| 66 |
-
input_ids = torch.stack(input_ids, dim=0)
|
| 67 |
-
image_tensors = torch.stack(image_tensors, dim=0)
|
| 68 |
-
return input_ids, image_tensors, image_sizes
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
# DataLoader
|
| 72 |
-
def create_data_loader(questions, image_folder, tokenizer, image_processor, model_config, batch_size=1, num_workers=4):
|
| 73 |
-
assert batch_size == 1, "batch_size must be 1"
|
| 74 |
-
dataset = CustomDataset(questions, image_folder, tokenizer, image_processor, model_config)
|
| 75 |
-
data_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False, collate_fn=collate_fn)
|
| 76 |
-
return data_loader
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
def eval_model(args):
|
| 80 |
-
# Model
|
| 81 |
-
disable_torch_init()
|
| 82 |
-
model_path = os.path.expanduser(args.model_path)
|
| 83 |
-
model_name = get_model_name_from_path(model_path)
|
| 84 |
-
tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
|
| 85 |
-
|
| 86 |
-
questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")]
|
| 87 |
-
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
| 88 |
-
answers_file = os.path.expanduser(args.answers_file)
|
| 89 |
-
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
|
| 90 |
-
ans_file = open(answers_file, "w")
|
| 91 |
-
|
| 92 |
-
if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode:
|
| 93 |
-
args.conv_mode = args.conv_mode + '_mmtag'
|
| 94 |
-
print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.')
|
| 95 |
-
|
| 96 |
-
data_loader = create_data_loader(questions, args.image_folder, tokenizer, image_processor, model.config)
|
| 97 |
-
|
| 98 |
-
for (input_ids, image_tensor, image_sizes), line in tqdm(zip(data_loader, questions), total=len(questions)):
|
| 99 |
-
idx = line["question_id"]
|
| 100 |
-
cur_prompt = line["text"]
|
| 101 |
-
|
| 102 |
-
input_ids = input_ids.to(device='cuda', non_blocking=True)
|
| 103 |
-
|
| 104 |
-
with torch.inference_mode():
|
| 105 |
-
output_ids = model.generate(
|
| 106 |
-
input_ids,
|
| 107 |
-
images=image_tensor.to(dtype=torch.float16, device='cuda', non_blocking=True),
|
| 108 |
-
image_sizes=image_sizes,
|
| 109 |
-
do_sample=True if args.temperature > 0 else False,
|
| 110 |
-
temperature=args.temperature,
|
| 111 |
-
top_p=args.top_p,
|
| 112 |
-
num_beams=args.num_beams,
|
| 113 |
-
max_new_tokens=args.max_new_tokens,
|
| 114 |
-
use_cache=True)
|
| 115 |
-
|
| 116 |
-
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
|
| 117 |
-
|
| 118 |
-
ans_id = shortuuid.uuid()
|
| 119 |
-
ans_file.write(json.dumps({"question_id": idx,
|
| 120 |
-
"prompt": cur_prompt,
|
| 121 |
-
"text": outputs,
|
| 122 |
-
"answer_id": ans_id,
|
| 123 |
-
"model_id": model_name,
|
| 124 |
-
"metadata": {}}) + "\n")
|
| 125 |
-
# ans_file.flush()
|
| 126 |
-
ans_file.close()
|
| 127 |
-
|
| 128 |
-
if __name__ == "__main__":
|
| 129 |
-
parser = argparse.ArgumentParser()
|
| 130 |
-
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
| 131 |
-
parser.add_argument("--model-base", type=str, default=None)
|
| 132 |
-
parser.add_argument("--image-folder", type=str, default="")
|
| 133 |
-
parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
|
| 134 |
-
parser.add_argument("--answers-file", type=str, default="answer.jsonl")
|
| 135 |
-
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
| 136 |
-
parser.add_argument("--num-chunks", type=int, default=1)
|
| 137 |
-
parser.add_argument("--chunk-idx", type=int, default=0)
|
| 138 |
-
parser.add_argument("--temperature", type=float, default=0.2)
|
| 139 |
-
parser.add_argument("--top_p", type=float, default=None)
|
| 140 |
-
parser.add_argument("--num_beams", type=int, default=1)
|
| 141 |
-
parser.add_argument("--max_new_tokens", type=int, default=128)
|
| 142 |
-
args = parser.parse_args()
|
| 143 |
-
|
| 144 |
-
eval_model(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
llava/eval/model_vqa_mmbench.py
DELETED
|
@@ -1,160 +0,0 @@
|
|
| 1 |
-
import argparse
|
| 2 |
-
import torch
|
| 3 |
-
import os
|
| 4 |
-
import json
|
| 5 |
-
import pandas as pd
|
| 6 |
-
from tqdm import tqdm
|
| 7 |
-
import shortuuid
|
| 8 |
-
|
| 9 |
-
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 10 |
-
from llava.conversation import conv_templates, SeparatorStyle
|
| 11 |
-
from llava.model.builder import load_pretrained_model
|
| 12 |
-
from llava.utils import disable_torch_init
|
| 13 |
-
from llava.mm_utils import tokenizer_image_token, process_images, load_image_from_base64, get_model_name_from_path
|
| 14 |
-
|
| 15 |
-
from PIL import Image
|
| 16 |
-
import math
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
all_options = ['A', 'B', 'C', 'D']
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def split_list(lst, n):
|
| 23 |
-
"""Split a list into n (roughly) equal-sized chunks"""
|
| 24 |
-
chunk_size = math.ceil(len(lst) / n) # integer division
|
| 25 |
-
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def get_chunk(lst, n, k):
|
| 29 |
-
chunks = split_list(lst, n)
|
| 30 |
-
return chunks[k]
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def is_none(value):
|
| 34 |
-
if value is None:
|
| 35 |
-
return True
|
| 36 |
-
if type(value) is float and math.isnan(value):
|
| 37 |
-
return True
|
| 38 |
-
if type(value) is str and value.lower() == 'nan':
|
| 39 |
-
return True
|
| 40 |
-
if type(value) is str and value.lower() == 'none':
|
| 41 |
-
return True
|
| 42 |
-
return False
|
| 43 |
-
|
| 44 |
-
def get_options(row, options):
|
| 45 |
-
parsed_options = []
|
| 46 |
-
for option in options:
|
| 47 |
-
option_value = row[option]
|
| 48 |
-
if is_none(option_value):
|
| 49 |
-
break
|
| 50 |
-
parsed_options.append(option_value)
|
| 51 |
-
return parsed_options
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def eval_model(args):
|
| 55 |
-
# Model
|
| 56 |
-
disable_torch_init()
|
| 57 |
-
model_path = os.path.expanduser(args.model_path)
|
| 58 |
-
model_name = get_model_name_from_path(model_path)
|
| 59 |
-
tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
|
| 60 |
-
|
| 61 |
-
questions = pd.read_table(os.path.expanduser(args.question_file))
|
| 62 |
-
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
| 63 |
-
answers_file = os.path.expanduser(args.answers_file)
|
| 64 |
-
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
|
| 65 |
-
ans_file = open(answers_file, "w")
|
| 66 |
-
|
| 67 |
-
if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode:
|
| 68 |
-
args.conv_mode = args.conv_mode + '_mmtag'
|
| 69 |
-
print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.')
|
| 70 |
-
|
| 71 |
-
for index, row in tqdm(questions.iterrows(), total=len(questions)):
|
| 72 |
-
options = get_options(row, all_options)
|
| 73 |
-
cur_option_char = all_options[:len(options)]
|
| 74 |
-
|
| 75 |
-
if args.all_rounds:
|
| 76 |
-
num_rounds = len(options)
|
| 77 |
-
else:
|
| 78 |
-
num_rounds = 1
|
| 79 |
-
|
| 80 |
-
for round_idx in range(num_rounds):
|
| 81 |
-
idx = row['index']
|
| 82 |
-
question = row['question']
|
| 83 |
-
hint = row['hint']
|
| 84 |
-
image = load_image_from_base64(row['image'])
|
| 85 |
-
if not is_none(hint):
|
| 86 |
-
question = hint + '\n' + question
|
| 87 |
-
for option_char, option in zip(all_options[:len(options)], options):
|
| 88 |
-
question = question + '\n' + option_char + '. ' + option
|
| 89 |
-
qs = cur_prompt = question
|
| 90 |
-
if model.config.mm_use_im_start_end:
|
| 91 |
-
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
| 92 |
-
else:
|
| 93 |
-
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
| 94 |
-
|
| 95 |
-
if args.single_pred_prompt:
|
| 96 |
-
if args.lang == 'cn':
|
| 97 |
-
qs = qs + '\n' + "请直接回答选项字母。"
|
| 98 |
-
else:
|
| 99 |
-
qs = qs + '\n' + "Answer with the option's letter from the given choices directly."
|
| 100 |
-
|
| 101 |
-
conv = conv_templates[args.conv_mode].copy()
|
| 102 |
-
conv.append_message(conv.roles[0], qs)
|
| 103 |
-
conv.append_message(conv.roles[1], None)
|
| 104 |
-
prompt = conv.get_prompt()
|
| 105 |
-
|
| 106 |
-
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
| 107 |
-
|
| 108 |
-
image_tensor = process_images([image], image_processor, model.config)[0]
|
| 109 |
-
|
| 110 |
-
with torch.inference_mode():
|
| 111 |
-
output_ids = model.generate(
|
| 112 |
-
input_ids,
|
| 113 |
-
images=image_tensor.unsqueeze(0).half().cuda(),
|
| 114 |
-
image_sizes=[image.size],
|
| 115 |
-
do_sample=True if args.temperature > 0 else False,
|
| 116 |
-
temperature=args.temperature,
|
| 117 |
-
top_p=args.top_p,
|
| 118 |
-
num_beams=args.num_beams,
|
| 119 |
-
# no_repeat_ngram_size=3,
|
| 120 |
-
max_new_tokens=1024,
|
| 121 |
-
use_cache=True)
|
| 122 |
-
|
| 123 |
-
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
|
| 124 |
-
|
| 125 |
-
ans_id = shortuuid.uuid()
|
| 126 |
-
ans_file.write(json.dumps({"question_id": idx,
|
| 127 |
-
"round_id": round_idx,
|
| 128 |
-
"prompt": cur_prompt,
|
| 129 |
-
"text": outputs,
|
| 130 |
-
"options": options,
|
| 131 |
-
"option_char": cur_option_char,
|
| 132 |
-
"answer_id": ans_id,
|
| 133 |
-
"model_id": model_name,
|
| 134 |
-
"metadata": {}}) + "\n")
|
| 135 |
-
ans_file.flush()
|
| 136 |
-
|
| 137 |
-
# rotate options
|
| 138 |
-
options = options[1:] + options[:1]
|
| 139 |
-
cur_option_char = cur_option_char[1:] + cur_option_char[:1]
|
| 140 |
-
ans_file.close()
|
| 141 |
-
|
| 142 |
-
if __name__ == "__main__":
|
| 143 |
-
parser = argparse.ArgumentParser()
|
| 144 |
-
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
| 145 |
-
parser.add_argument("--model-base", type=str, default=None)
|
| 146 |
-
parser.add_argument("--image-folder", type=str, default="")
|
| 147 |
-
parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
|
| 148 |
-
parser.add_argument("--answers-file", type=str, default="answer.jsonl")
|
| 149 |
-
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
| 150 |
-
parser.add_argument("--num-chunks", type=int, default=1)
|
| 151 |
-
parser.add_argument("--chunk-idx", type=int, default=0)
|
| 152 |
-
parser.add_argument("--temperature", type=float, default=0.2)
|
| 153 |
-
parser.add_argument("--top_p", type=float, default=None)
|
| 154 |
-
parser.add_argument("--num_beams", type=int, default=1)
|
| 155 |
-
parser.add_argument("--all-rounds", action="store_true")
|
| 156 |
-
parser.add_argument("--single-pred-prompt", action="store_true")
|
| 157 |
-
parser.add_argument("--lang", type=str, default="en")
|
| 158 |
-
args = parser.parse_args()
|
| 159 |
-
|
| 160 |
-
eval_model(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
llava/eval/model_vqa_science.py
CHANGED
|
@@ -9,7 +9,7 @@ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_S
|
|
| 9 |
from llava.conversation import conv_templates, SeparatorStyle
|
| 10 |
from llava.model.builder import load_pretrained_model
|
| 11 |
from llava.utils import disable_torch_init
|
| 12 |
-
from llava.mm_utils import tokenizer_image_token,
|
| 13 |
|
| 14 |
from PIL import Image
|
| 15 |
import math
|
|
@@ -47,9 +47,8 @@ def eval_model(args):
|
|
| 47 |
if 'image' in line:
|
| 48 |
image_file = line["image"]
|
| 49 |
image = Image.open(os.path.join(args.image_folder, image_file))
|
| 50 |
-
image_tensor =
|
| 51 |
images = image_tensor.unsqueeze(0).half().cuda()
|
| 52 |
-
image_sizes = [image.size]
|
| 53 |
if getattr(model.config, 'mm_use_im_start_end', False):
|
| 54 |
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
| 55 |
else:
|
|
@@ -57,11 +56,6 @@ def eval_model(args):
|
|
| 57 |
cur_prompt = '<image>' + '\n' + cur_prompt
|
| 58 |
else:
|
| 59 |
images = None
|
| 60 |
-
image_sizes = None
|
| 61 |
-
|
| 62 |
-
if args.single_pred_prompt:
|
| 63 |
-
qs = qs + '\n' + "Answer with the option's letter from the given choices directly."
|
| 64 |
-
cur_prompt = cur_prompt + '\n' + "Answer with the option's letter from the given choices directly."
|
| 65 |
|
| 66 |
conv = conv_templates[args.conv_mode].copy()
|
| 67 |
conv.append_message(conv.roles[0], qs)
|
|
@@ -70,18 +64,56 @@ def eval_model(args):
|
|
| 70 |
|
| 71 |
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
with torch.inference_mode():
|
| 74 |
output_ids = model.generate(
|
| 75 |
input_ids,
|
| 76 |
images=images,
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
temperature=args.temperature,
|
| 80 |
max_new_tokens=1024,
|
| 81 |
use_cache=True,
|
|
|
|
| 82 |
)
|
| 83 |
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
ans_id = shortuuid.uuid()
|
| 87 |
ans_file.write(json.dumps({"question_id": idx,
|
|
@@ -103,9 +135,7 @@ if __name__ == "__main__":
|
|
| 103 |
parser.add_argument("--conv-mode", type=str, default="llava_v0")
|
| 104 |
parser.add_argument("--num-chunks", type=int, default=1)
|
| 105 |
parser.add_argument("--chunk-idx", type=int, default=0)
|
| 106 |
-
parser.add_argument("--temperature", type=float, default=0.2)
|
| 107 |
parser.add_argument("--answer-prompter", action="store_true")
|
| 108 |
-
parser.add_argument("--single-pred-prompt", action="store_true")
|
| 109 |
args = parser.parse_args()
|
| 110 |
|
| 111 |
eval_model(args)
|
|
|
|
| 9 |
from llava.conversation import conv_templates, SeparatorStyle
|
| 10 |
from llava.model.builder import load_pretrained_model
|
| 11 |
from llava.utils import disable_torch_init
|
| 12 |
+
from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
|
| 13 |
|
| 14 |
from PIL import Image
|
| 15 |
import math
|
|
|
|
| 47 |
if 'image' in line:
|
| 48 |
image_file = line["image"]
|
| 49 |
image = Image.open(os.path.join(args.image_folder, image_file))
|
| 50 |
+
image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
| 51 |
images = image_tensor.unsqueeze(0).half().cuda()
|
|
|
|
| 52 |
if getattr(model.config, 'mm_use_im_start_end', False):
|
| 53 |
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
| 54 |
else:
|
|
|
|
| 56 |
cur_prompt = '<image>' + '\n' + cur_prompt
|
| 57 |
else:
|
| 58 |
images = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
conv = conv_templates[args.conv_mode].copy()
|
| 61 |
conv.append_message(conv.roles[0], qs)
|
|
|
|
| 64 |
|
| 65 |
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
| 66 |
|
| 67 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
| 68 |
+
keywords = [stop_str]
|
| 69 |
+
stopping_criteria = [KeywordsStoppingCriteria(keywords, tokenizer, input_ids)] if conv.version == "v0" else None
|
| 70 |
+
|
| 71 |
with torch.inference_mode():
|
| 72 |
output_ids = model.generate(
|
| 73 |
input_ids,
|
| 74 |
images=images,
|
| 75 |
+
do_sample=True,
|
| 76 |
+
temperature=0.2,
|
|
|
|
| 77 |
max_new_tokens=1024,
|
| 78 |
use_cache=True,
|
| 79 |
+
stopping_criteria=stopping_criteria,
|
| 80 |
)
|
| 81 |
|
| 82 |
+
input_token_len = input_ids.shape[1]
|
| 83 |
+
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
|
| 84 |
+
if n_diff_input_output > 0:
|
| 85 |
+
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
|
| 86 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
|
| 87 |
+
outputs = outputs.strip()
|
| 88 |
+
if outputs.endswith(stop_str):
|
| 89 |
+
outputs = outputs[:-len(stop_str)]
|
| 90 |
+
outputs = outputs.strip()
|
| 91 |
+
|
| 92 |
+
# prompt for answer
|
| 93 |
+
if args.answer_prompter:
|
| 94 |
+
outputs_reasoning = outputs
|
| 95 |
+
input_ids = tokenizer_image_token(prompt + outputs_reasoning + ' ###\nANSWER:', tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
| 96 |
+
|
| 97 |
+
with torch.inference_mode():
|
| 98 |
+
output_ids = model.generate(
|
| 99 |
+
input_ids,
|
| 100 |
+
images=images,
|
| 101 |
+
do_sample=True,
|
| 102 |
+
temperature=0.2,
|
| 103 |
+
max_new_tokens=64,
|
| 104 |
+
use_cache=True,
|
| 105 |
+
stopping_criteria=[stopping_criteria])
|
| 106 |
+
|
| 107 |
+
input_token_len = input_ids.shape[1]
|
| 108 |
+
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
|
| 109 |
+
if n_diff_input_output > 0:
|
| 110 |
+
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
|
| 111 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
|
| 112 |
+
outputs = outputs.strip()
|
| 113 |
+
if outputs.endswith(stop_str):
|
| 114 |
+
outputs = outputs[:-len(stop_str)]
|
| 115 |
+
outputs = outputs.strip()
|
| 116 |
+
outputs = outputs_reasoning + '\n The answer is ' + outputs
|
| 117 |
|
| 118 |
ans_id = shortuuid.uuid()
|
| 119 |
ans_file.write(json.dumps({"question_id": idx,
|
|
|
|
| 135 |
parser.add_argument("--conv-mode", type=str, default="llava_v0")
|
| 136 |
parser.add_argument("--num-chunks", type=int, default=1)
|
| 137 |
parser.add_argument("--chunk-idx", type=int, default=0)
|
|
|
|
| 138 |
parser.add_argument("--answer-prompter", action="store_true")
|
|
|
|
| 139 |
args = parser.parse_args()
|
| 140 |
|
| 141 |
eval_model(args)
|
llava/eval/run_llava.py
CHANGED
|
@@ -1,80 +1,43 @@
|
|
| 1 |
import argparse
|
| 2 |
import torch
|
| 3 |
|
| 4 |
-
from llava.constants import
|
| 5 |
-
IMAGE_TOKEN_INDEX,
|
| 6 |
-
DEFAULT_IMAGE_TOKEN,
|
| 7 |
-
DEFAULT_IM_START_TOKEN,
|
| 8 |
-
DEFAULT_IM_END_TOKEN,
|
| 9 |
-
IMAGE_PLACEHOLDER,
|
| 10 |
-
)
|
| 11 |
from llava.conversation import conv_templates, SeparatorStyle
|
| 12 |
from llava.model.builder import load_pretrained_model
|
| 13 |
from llava.utils import disable_torch_init
|
| 14 |
-
from llava.mm_utils import
|
| 15 |
-
process_images,
|
| 16 |
-
tokenizer_image_token,
|
| 17 |
-
get_model_name_from_path,
|
| 18 |
-
)
|
| 19 |
|
| 20 |
from PIL import Image
|
| 21 |
|
| 22 |
import requests
|
| 23 |
from PIL import Image
|
| 24 |
from io import BytesIO
|
| 25 |
-
import re
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def image_parser(args):
|
| 29 |
-
out = args.image_file.split(args.sep)
|
| 30 |
-
return out
|
| 31 |
|
| 32 |
|
| 33 |
def load_image(image_file):
|
| 34 |
-
if image_file.startswith(
|
| 35 |
response = requests.get(image_file)
|
| 36 |
-
image = Image.open(BytesIO(response.content)).convert(
|
| 37 |
else:
|
| 38 |
-
image = Image.open(image_file).convert(
|
| 39 |
return image
|
| 40 |
|
| 41 |
|
| 42 |
-
def load_images(image_files):
|
| 43 |
-
out = []
|
| 44 |
-
for image_file in image_files:
|
| 45 |
-
image = load_image(image_file)
|
| 46 |
-
out.append(image)
|
| 47 |
-
return out
|
| 48 |
-
|
| 49 |
-
|
| 50 |
def eval_model(args):
|
| 51 |
# Model
|
| 52 |
disable_torch_init()
|
| 53 |
|
| 54 |
model_name = get_model_name_from_path(args.model_path)
|
| 55 |
-
tokenizer, model, image_processor, context_len = load_pretrained_model(
|
| 56 |
-
args.model_path, args.model_base, model_name
|
| 57 |
-
)
|
| 58 |
|
| 59 |
qs = args.query
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
if model.config.mm_use_im_start_end:
|
| 63 |
-
qs = re.sub(IMAGE_PLACEHOLDER, image_token_se, qs)
|
| 64 |
-
else:
|
| 65 |
-
qs = re.sub(IMAGE_PLACEHOLDER, DEFAULT_IMAGE_TOKEN, qs)
|
| 66 |
else:
|
| 67 |
-
|
| 68 |
-
qs = image_token_se + "\n" + qs
|
| 69 |
-
else:
|
| 70 |
-
qs = DEFAULT_IMAGE_TOKEN + "\n" + qs
|
| 71 |
|
| 72 |
-
if
|
| 73 |
conv_mode = "llava_llama_2"
|
| 74 |
-
elif "mistral" in model_name.lower():
|
| 75 |
-
conv_mode = "mistral_instruct"
|
| 76 |
-
elif "v1.6-34b" in model_name.lower():
|
| 77 |
-
conv_mode = "chatml_direct"
|
| 78 |
elif "v1" in model_name.lower():
|
| 79 |
conv_mode = "llava_v1"
|
| 80 |
elif "mpt" in model_name.lower():
|
|
@@ -83,11 +46,7 @@ def eval_model(args):
|
|
| 83 |
conv_mode = "llava_v0"
|
| 84 |
|
| 85 |
if args.conv_mode is not None and conv_mode != args.conv_mode:
|
| 86 |
-
print(
|
| 87 |
-
"[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}".format(
|
| 88 |
-
conv_mode, args.conv_mode, args.conv_mode
|
| 89 |
-
)
|
| 90 |
-
)
|
| 91 |
else:
|
| 92 |
args.conv_mode = conv_mode
|
| 93 |
|
|
@@ -96,38 +55,36 @@ def eval_model(args):
|
|
| 96 |
conv.append_message(conv.roles[1], None)
|
| 97 |
prompt = conv.get_prompt()
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
input_ids = (
|
| 109 |
-
tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt")
|
| 110 |
-
.unsqueeze(0)
|
| 111 |
-
.cuda()
|
| 112 |
-
)
|
| 113 |
|
| 114 |
with torch.inference_mode():
|
| 115 |
output_ids = model.generate(
|
| 116 |
input_ids,
|
| 117 |
-
images=
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
top_p=args.top_p,
|
| 122 |
-
num_beams=args.num_beams,
|
| 123 |
-
max_new_tokens=args.max_new_tokens,
|
| 124 |
use_cache=True,
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
print(outputs)
|
| 129 |
|
| 130 |
-
|
| 131 |
if __name__ == "__main__":
|
| 132 |
parser = argparse.ArgumentParser()
|
| 133 |
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
|
@@ -135,11 +92,6 @@ if __name__ == "__main__":
|
|
| 135 |
parser.add_argument("--image-file", type=str, required=True)
|
| 136 |
parser.add_argument("--query", type=str, required=True)
|
| 137 |
parser.add_argument("--conv-mode", type=str, default=None)
|
| 138 |
-
parser.add_argument("--sep", type=str, default=",")
|
| 139 |
-
parser.add_argument("--temperature", type=float, default=0.2)
|
| 140 |
-
parser.add_argument("--top_p", type=float, default=None)
|
| 141 |
-
parser.add_argument("--num_beams", type=int, default=1)
|
| 142 |
-
parser.add_argument("--max_new_tokens", type=int, default=512)
|
| 143 |
args = parser.parse_args()
|
| 144 |
|
| 145 |
eval_model(args)
|
|
|
|
| 1 |
import argparse
|
| 2 |
import torch
|
| 3 |
|
| 4 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from llava.conversation import conv_templates, SeparatorStyle
|
| 6 |
from llava.model.builder import load_pretrained_model
|
| 7 |
from llava.utils import disable_torch_init
|
| 8 |
+
from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
from PIL import Image
|
| 11 |
|
| 12 |
import requests
|
| 13 |
from PIL import Image
|
| 14 |
from io import BytesIO
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
def load_image(image_file):
|
| 18 |
+
if image_file.startswith('http') or image_file.startswith('https'):
|
| 19 |
response = requests.get(image_file)
|
| 20 |
+
image = Image.open(BytesIO(response.content)).convert('RGB')
|
| 21 |
else:
|
| 22 |
+
image = Image.open(image_file).convert('RGB')
|
| 23 |
return image
|
| 24 |
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
def eval_model(args):
|
| 27 |
# Model
|
| 28 |
disable_torch_init()
|
| 29 |
|
| 30 |
model_name = get_model_name_from_path(args.model_path)
|
| 31 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name)
|
|
|
|
|
|
|
| 32 |
|
| 33 |
qs = args.query
|
| 34 |
+
if model.config.mm_use_im_start_end:
|
| 35 |
+
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
else:
|
| 37 |
+
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
if 'llama-2' in model_name.lower():
|
| 40 |
conv_mode = "llava_llama_2"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
elif "v1" in model_name.lower():
|
| 42 |
conv_mode = "llava_v1"
|
| 43 |
elif "mpt" in model_name.lower():
|
|
|
|
| 46 |
conv_mode = "llava_v0"
|
| 47 |
|
| 48 |
if args.conv_mode is not None and conv_mode != args.conv_mode:
|
| 49 |
+
print('[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}'.format(conv_mode, args.conv_mode, args.conv_mode))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
else:
|
| 51 |
args.conv_mode = conv_mode
|
| 52 |
|
|
|
|
| 55 |
conv.append_message(conv.roles[1], None)
|
| 56 |
prompt = conv.get_prompt()
|
| 57 |
|
| 58 |
+
image = load_image(args.image_file)
|
| 59 |
+
image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'].half().cuda()
|
| 60 |
+
|
| 61 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
| 62 |
+
|
| 63 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
| 64 |
+
keywords = [stop_str]
|
| 65 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
with torch.inference_mode():
|
| 68 |
output_ids = model.generate(
|
| 69 |
input_ids,
|
| 70 |
+
images=image_tensor,
|
| 71 |
+
do_sample=True,
|
| 72 |
+
temperature=0.2,
|
| 73 |
+
max_new_tokens=1024,
|
|
|
|
|
|
|
|
|
|
| 74 |
use_cache=True,
|
| 75 |
+
stopping_criteria=[stopping_criteria])
|
| 76 |
+
|
| 77 |
+
input_token_len = input_ids.shape[1]
|
| 78 |
+
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
|
| 79 |
+
if n_diff_input_output > 0:
|
| 80 |
+
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
|
| 81 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
|
| 82 |
+
outputs = outputs.strip()
|
| 83 |
+
if outputs.endswith(stop_str):
|
| 84 |
+
outputs = outputs[:-len(stop_str)]
|
| 85 |
+
outputs = outputs.strip()
|
| 86 |
print(outputs)
|
| 87 |
|
|
|
|
| 88 |
if __name__ == "__main__":
|
| 89 |
parser = argparse.ArgumentParser()
|
| 90 |
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
|
|
|
| 92 |
parser.add_argument("--image-file", type=str, required=True)
|
| 93 |
parser.add_argument("--query", type=str, required=True)
|
| 94 |
parser.add_argument("--conv-mode", type=str, default=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
args = parser.parse_args()
|
| 96 |
|
| 97 |
eval_model(args)
|
llava/eval/summarize_gpt_review.py
CHANGED
|
@@ -9,10 +9,8 @@ import argparse
|
|
| 9 |
def parse_args():
|
| 10 |
parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.')
|
| 11 |
parser.add_argument('-d', '--dir', default=None)
|
| 12 |
-
parser.add_argument('-
|
| 13 |
-
parser.add_argument('-
|
| 14 |
-
parser.add_argument('-f', '--files', nargs='*', default=[])
|
| 15 |
-
parser.add_argument('-i', '--ignore', nargs='*', default=[])
|
| 16 |
return parser.parse_args()
|
| 17 |
|
| 18 |
|
|
@@ -22,27 +20,19 @@ if __name__ == '__main__':
|
|
| 22 |
if args.ignore is not None:
|
| 23 |
args.ignore = [int(x) for x in args.ignore]
|
| 24 |
|
| 25 |
-
if len(args.files) > 0:
|
| 26 |
review_files = args.files
|
| 27 |
else:
|
| 28 |
-
review_files = [x for x in os.listdir(args.dir) if x.endswith('.jsonl') and (x.startswith('gpt4_text') or x.startswith('reviews_') or x.startswith('review_')
|
| 29 |
|
| 30 |
for review_file in sorted(review_files):
|
| 31 |
config = os.path.basename(review_file).replace('gpt4_text_', '').replace('.jsonl', '')
|
| 32 |
-
if args.select is not None and any(x not in config for x in args.select):
|
| 33 |
-
continue
|
| 34 |
-
if '0613' in config:
|
| 35 |
-
version = '0613'
|
| 36 |
-
else:
|
| 37 |
-
version = '0314'
|
| 38 |
-
if args.version is not None and args.version != version:
|
| 39 |
-
continue
|
| 40 |
scores = defaultdict(list)
|
| 41 |
print(config)
|
| 42 |
with open(os.path.join(args.dir, review_file) if args.dir is not None else review_file) as f:
|
| 43 |
for review_str in f:
|
| 44 |
review = json.loads(review_str)
|
| 45 |
-
if review['question_id'] in args.ignore:
|
| 46 |
continue
|
| 47 |
if 'category' in review:
|
| 48 |
scores[review['category']].append(review['tuple'])
|
|
@@ -56,5 +46,5 @@ if __name__ == '__main__':
|
|
| 56 |
stats = np.asarray(v).mean(0).tolist()
|
| 57 |
stats = [round(x, 3) for x in stats]
|
| 58 |
# print(k, stats, round(stats[1]/stats[0]*100, 1))
|
| 59 |
-
print(k, round(stats[1]/stats[0]*100, 1)
|
| 60 |
print('=================================')
|
|
|
|
| 9 |
def parse_args():
|
| 10 |
parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.')
|
| 11 |
parser.add_argument('-d', '--dir', default=None)
|
| 12 |
+
parser.add_argument('-f', '--files', nargs='*', default=None)
|
| 13 |
+
parser.add_argument('-i', '--ignore', nargs='*', default=None)
|
|
|
|
|
|
|
| 14 |
return parser.parse_args()
|
| 15 |
|
| 16 |
|
|
|
|
| 20 |
if args.ignore is not None:
|
| 21 |
args.ignore = [int(x) for x in args.ignore]
|
| 22 |
|
| 23 |
+
if args.files is not None and len(args.files) > 0:
|
| 24 |
review_files = args.files
|
| 25 |
else:
|
| 26 |
+
review_files = [x for x in os.listdir(args.dir) if x.endswith('.jsonl') and (x.startswith('gpt4_text') or x.startswith('reviews_') or x.startswith('review_'))]
|
| 27 |
|
| 28 |
for review_file in sorted(review_files):
|
| 29 |
config = os.path.basename(review_file).replace('gpt4_text_', '').replace('.jsonl', '')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
scores = defaultdict(list)
|
| 31 |
print(config)
|
| 32 |
with open(os.path.join(args.dir, review_file) if args.dir is not None else review_file) as f:
|
| 33 |
for review_str in f:
|
| 34 |
review = json.loads(review_str)
|
| 35 |
+
if args.ignore is not None and review['question_id'] in args.ignore:
|
| 36 |
continue
|
| 37 |
if 'category' in review:
|
| 38 |
scores[review['category']].append(review['tuple'])
|
|
|
|
| 46 |
stats = np.asarray(v).mean(0).tolist()
|
| 47 |
stats = [round(x, 3) for x in stats]
|
| 48 |
# print(k, stats, round(stats[1]/stats[0]*100, 1))
|
| 49 |
+
print(k, round(stats[1]/stats[0]*100, 1))
|
| 50 |
print('=================================')
|
llava/mm_utils.py
CHANGED
|
@@ -1,150 +1,12 @@
|
|
| 1 |
from PIL import Image
|
| 2 |
from io import BytesIO
|
| 3 |
import base64
|
| 4 |
-
import torch
|
| 5 |
-
import math
|
| 6 |
-
import ast
|
| 7 |
|
|
|
|
| 8 |
from transformers import StoppingCriteria
|
| 9 |
from llava.constants import IMAGE_TOKEN_INDEX
|
| 10 |
|
| 11 |
|
| 12 |
-
def select_best_resolution(original_size, possible_resolutions):
|
| 13 |
-
"""
|
| 14 |
-
Selects the best resolution from a list of possible resolutions based on the original size.
|
| 15 |
-
|
| 16 |
-
Args:
|
| 17 |
-
original_size (tuple): The original size of the image in the format (width, height).
|
| 18 |
-
possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
|
| 19 |
-
|
| 20 |
-
Returns:
|
| 21 |
-
tuple: The best fit resolution in the format (width, height).
|
| 22 |
-
"""
|
| 23 |
-
original_width, original_height = original_size
|
| 24 |
-
best_fit = None
|
| 25 |
-
max_effective_resolution = 0
|
| 26 |
-
min_wasted_resolution = float('inf')
|
| 27 |
-
|
| 28 |
-
for width, height in possible_resolutions:
|
| 29 |
-
scale = min(width / original_width, height / original_height)
|
| 30 |
-
downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
|
| 31 |
-
effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
|
| 32 |
-
wasted_resolution = (width * height) - effective_resolution
|
| 33 |
-
|
| 34 |
-
if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
|
| 35 |
-
max_effective_resolution = effective_resolution
|
| 36 |
-
min_wasted_resolution = wasted_resolution
|
| 37 |
-
best_fit = (width, height)
|
| 38 |
-
|
| 39 |
-
return best_fit
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
def resize_and_pad_image(image, target_resolution):
|
| 43 |
-
"""
|
| 44 |
-
Resize and pad an image to a target resolution while maintaining aspect ratio.
|
| 45 |
-
|
| 46 |
-
Args:
|
| 47 |
-
image (PIL.Image.Image): The input image.
|
| 48 |
-
target_resolution (tuple): The target resolution (width, height) of the image.
|
| 49 |
-
|
| 50 |
-
Returns:
|
| 51 |
-
PIL.Image.Image: The resized and padded image.
|
| 52 |
-
"""
|
| 53 |
-
original_width, original_height = image.size
|
| 54 |
-
target_width, target_height = target_resolution
|
| 55 |
-
|
| 56 |
-
scale_w = target_width / original_width
|
| 57 |
-
scale_h = target_height / original_height
|
| 58 |
-
|
| 59 |
-
if scale_w < scale_h:
|
| 60 |
-
new_width = target_width
|
| 61 |
-
new_height = min(math.ceil(original_height * scale_w), target_height)
|
| 62 |
-
else:
|
| 63 |
-
new_height = target_height
|
| 64 |
-
new_width = min(math.ceil(original_width * scale_h), target_width)
|
| 65 |
-
|
| 66 |
-
# Resize the image
|
| 67 |
-
resized_image = image.resize((new_width, new_height))
|
| 68 |
-
|
| 69 |
-
new_image = Image.new('RGB', (target_width, target_height), (0, 0, 0))
|
| 70 |
-
paste_x = (target_width - new_width) // 2
|
| 71 |
-
paste_y = (target_height - new_height) // 2
|
| 72 |
-
new_image.paste(resized_image, (paste_x, paste_y))
|
| 73 |
-
|
| 74 |
-
return new_image
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def divide_to_patches(image, patch_size):
|
| 78 |
-
"""
|
| 79 |
-
Divides an image into patches of a specified size.
|
| 80 |
-
|
| 81 |
-
Args:
|
| 82 |
-
image (PIL.Image.Image): The input image.
|
| 83 |
-
patch_size (int): The size of each patch.
|
| 84 |
-
|
| 85 |
-
Returns:
|
| 86 |
-
list: A list of PIL.Image.Image objects representing the patches.
|
| 87 |
-
"""
|
| 88 |
-
patches = []
|
| 89 |
-
width, height = image.size
|
| 90 |
-
for i in range(0, height, patch_size):
|
| 91 |
-
for j in range(0, width, patch_size):
|
| 92 |
-
box = (j, i, j + patch_size, i + patch_size)
|
| 93 |
-
patch = image.crop(box)
|
| 94 |
-
patches.append(patch)
|
| 95 |
-
|
| 96 |
-
return patches
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
|
| 100 |
-
"""
|
| 101 |
-
Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
|
| 102 |
-
|
| 103 |
-
Args:
|
| 104 |
-
image_size (tuple): The size of the input image in the format (width, height).
|
| 105 |
-
grid_pinpoints (str): A string representation of a list of possible resolutions.
|
| 106 |
-
patch_size (int): The size of each image patch.
|
| 107 |
-
|
| 108 |
-
Returns:
|
| 109 |
-
tuple: The shape of the image patch grid in the format (width, height).
|
| 110 |
-
"""
|
| 111 |
-
if type(grid_pinpoints) is list:
|
| 112 |
-
possible_resolutions = grid_pinpoints
|
| 113 |
-
else:
|
| 114 |
-
possible_resolutions = ast.literal_eval(grid_pinpoints)
|
| 115 |
-
width, height = select_best_resolution(image_size, possible_resolutions)
|
| 116 |
-
return width // patch_size, height // patch_size
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
def process_anyres_image(image, processor, grid_pinpoints):
|
| 120 |
-
"""
|
| 121 |
-
Process an image with variable resolutions.
|
| 122 |
-
|
| 123 |
-
Args:
|
| 124 |
-
image (PIL.Image.Image): The input image to be processed.
|
| 125 |
-
processor: The image processor object.
|
| 126 |
-
grid_pinpoints (str): A string representation of a list of possible resolutions.
|
| 127 |
-
|
| 128 |
-
Returns:
|
| 129 |
-
torch.Tensor: A tensor containing the processed image patches.
|
| 130 |
-
"""
|
| 131 |
-
if type(grid_pinpoints) is list:
|
| 132 |
-
possible_resolutions = grid_pinpoints
|
| 133 |
-
else:
|
| 134 |
-
possible_resolutions = ast.literal_eval(grid_pinpoints)
|
| 135 |
-
best_resolution = select_best_resolution(image.size, possible_resolutions)
|
| 136 |
-
image_padded = resize_and_pad_image(image, best_resolution)
|
| 137 |
-
|
| 138 |
-
patches = divide_to_patches(image_padded, processor.crop_size['height'])
|
| 139 |
-
|
| 140 |
-
image_original_resize = image.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
|
| 141 |
-
|
| 142 |
-
image_patches = [image_original_resize] + patches
|
| 143 |
-
image_patches = [processor.preprocess(image_patch, return_tensors='pt')['pixel_values'][0]
|
| 144 |
-
for image_patch in image_patches]
|
| 145 |
-
return torch.stack(image_patches, dim=0)
|
| 146 |
-
|
| 147 |
-
|
| 148 |
def load_image_from_base64(image):
|
| 149 |
return Image.open(BytesIO(base64.b64decode(image)))
|
| 150 |
|
|
@@ -171,10 +33,6 @@ def process_images(images, image_processor, model_cfg):
|
|
| 171 |
image = expand2square(image, tuple(int(x*255) for x in image_processor.image_mean))
|
| 172 |
image = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
| 173 |
new_images.append(image)
|
| 174 |
-
elif image_aspect_ratio == "anyres":
|
| 175 |
-
for image in images:
|
| 176 |
-
image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints)
|
| 177 |
-
new_images.append(image)
|
| 178 |
else:
|
| 179 |
return image_processor(images, return_tensors='pt')['pixel_values']
|
| 180 |
if all(x.shape == new_images[0].shape for x in new_images):
|
|
@@ -212,36 +70,30 @@ def get_model_name_from_path(model_path):
|
|
| 212 |
else:
|
| 213 |
return model_paths[-1]
|
| 214 |
|
|
|
|
|
|
|
|
|
|
| 215 |
class KeywordsStoppingCriteria(StoppingCriteria):
|
| 216 |
def __init__(self, keywords, tokenizer, input_ids):
|
| 217 |
self.keywords = keywords
|
| 218 |
self.keyword_ids = []
|
| 219 |
-
self.max_keyword_len = 0
|
| 220 |
for keyword in keywords:
|
| 221 |
cur_keyword_ids = tokenizer(keyword).input_ids
|
| 222 |
if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
|
| 223 |
cur_keyword_ids = cur_keyword_ids[1:]
|
| 224 |
-
if len(cur_keyword_ids) > self.max_keyword_len:
|
| 225 |
-
self.max_keyword_len = len(cur_keyword_ids)
|
| 226 |
self.keyword_ids.append(torch.tensor(cur_keyword_ids))
|
| 227 |
self.tokenizer = tokenizer
|
| 228 |
self.start_len = input_ids.shape[1]
|
| 229 |
-
|
| 230 |
-
def
|
| 231 |
-
|
|
|
|
| 232 |
self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
|
| 233 |
for keyword_id in self.keyword_ids:
|
| 234 |
-
|
| 235 |
-
if torch.equal(truncated_output_ids, keyword_id):
|
| 236 |
return True
|
| 237 |
outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
|
| 238 |
for keyword in self.keywords:
|
| 239 |
if keyword in outputs:
|
| 240 |
return True
|
| 241 |
return False
|
| 242 |
-
|
| 243 |
-
def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
| 244 |
-
outputs = []
|
| 245 |
-
for i in range(output_ids.shape[0]):
|
| 246 |
-
outputs.append(self.call_for_batch(output_ids[i].unsqueeze(0), scores))
|
| 247 |
-
return all(outputs)
|
|
|
|
| 1 |
from PIL import Image
|
| 2 |
from io import BytesIO
|
| 3 |
import base64
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
import torch
|
| 6 |
from transformers import StoppingCriteria
|
| 7 |
from llava.constants import IMAGE_TOKEN_INDEX
|
| 8 |
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
def load_image_from_base64(image):
|
| 11 |
return Image.open(BytesIO(base64.b64decode(image)))
|
| 12 |
|
|
|
|
| 33 |
image = expand2square(image, tuple(int(x*255) for x in image_processor.image_mean))
|
| 34 |
image = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
| 35 |
new_images.append(image)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
else:
|
| 37 |
return image_processor(images, return_tensors='pt')['pixel_values']
|
| 38 |
if all(x.shape == new_images[0].shape for x in new_images):
|
|
|
|
| 70 |
else:
|
| 71 |
return model_paths[-1]
|
| 72 |
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
|
| 76 |
class KeywordsStoppingCriteria(StoppingCriteria):
|
| 77 |
def __init__(self, keywords, tokenizer, input_ids):
|
| 78 |
self.keywords = keywords
|
| 79 |
self.keyword_ids = []
|
|
|
|
| 80 |
for keyword in keywords:
|
| 81 |
cur_keyword_ids = tokenizer(keyword).input_ids
|
| 82 |
if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
|
| 83 |
cur_keyword_ids = cur_keyword_ids[1:]
|
|
|
|
|
|
|
| 84 |
self.keyword_ids.append(torch.tensor(cur_keyword_ids))
|
| 85 |
self.tokenizer = tokenizer
|
| 86 |
self.start_len = input_ids.shape[1]
|
| 87 |
+
|
| 88 |
+
def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
| 89 |
+
assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
|
| 90 |
+
offset = min(output_ids.shape[1] - self.start_len, 3)
|
| 91 |
self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
|
| 92 |
for keyword_id in self.keyword_ids:
|
| 93 |
+
if output_ids[0, -keyword_id.shape[0]:] == keyword_id:
|
|
|
|
| 94 |
return True
|
| 95 |
outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
|
| 96 |
for keyword in self.keywords:
|
| 97 |
if keyword in outputs:
|
| 98 |
return True
|
| 99 |
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
llava/model/__init__.py
CHANGED
|
@@ -1,6 +1,2 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
from .language_model.llava_mpt import LlavaMptForCausalLM, LlavaMptConfig
|
| 4 |
-
from .language_model.llava_mistral import LlavaMistralForCausalLM, LlavaMistralConfig
|
| 5 |
-
except:
|
| 6 |
-
pass
|
|
|
|
| 1 |
+
from .language_model.llava_llama import LlavaLlamaForCausalLM, LlavaConfig
|
| 2 |
+
from .language_model.llava_mpt import LlavaMPTForCausalLM, LlavaMPTConfig
|
|
|
|
|
|
|
|
|
|
|
|
llava/model/builder.py
CHANGED
|
@@ -23,11 +23,9 @@ from llava.model import *
|
|
| 23 |
from llava.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 24 |
|
| 25 |
|
| 26 |
-
def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto"
|
| 27 |
-
kwargs = {"device_map": device_map
|
| 28 |
-
|
| 29 |
-
if device != "cuda":
|
| 30 |
-
kwargs['device_map'] = {"": device}
|
| 31 |
|
| 32 |
if load_8bit:
|
| 33 |
kwargs['load_in_8bit'] = True
|
|
@@ -42,16 +40,12 @@ def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, l
|
|
| 42 |
else:
|
| 43 |
kwargs['torch_dtype'] = torch.float16
|
| 44 |
|
| 45 |
-
if use_flash_attn:
|
| 46 |
-
kwargs['attn_implementation'] = 'flash_attention_2'
|
| 47 |
-
|
| 48 |
if 'llava' in model_name.lower():
|
| 49 |
# Load LLaVA model
|
| 50 |
if 'lora' in model_name.lower() and model_base is None:
|
| 51 |
warnings.warn('There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged.')
|
| 52 |
if 'lora' in model_name.lower() and model_base is not None:
|
| 53 |
-
|
| 54 |
-
lora_cfg_pretrained = LlavaConfig.from_pretrained(model_path)
|
| 55 |
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
| 56 |
print('Loading LLaVA from base model...')
|
| 57 |
model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs)
|
|
@@ -92,7 +86,7 @@ def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, l
|
|
| 92 |
shutil.copyfile(os.path.join(model_base, 'configuration_mpt.py'), os.path.join(model_path, 'configuration_mpt.py'))
|
| 93 |
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True)
|
| 94 |
cfg_pretrained = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
|
| 95 |
-
model =
|
| 96 |
else:
|
| 97 |
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
| 98 |
cfg_pretrained = AutoConfig.from_pretrained(model_path)
|
|
@@ -104,28 +98,17 @@ def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, l
|
|
| 104 |
else:
|
| 105 |
if 'mpt' in model_name.lower():
|
| 106 |
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
|
| 107 |
-
model =
|
| 108 |
-
elif 'mistral' in model_name.lower():
|
| 109 |
-
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 110 |
-
model = LlavaMistralForCausalLM.from_pretrained(
|
| 111 |
-
model_path,
|
| 112 |
-
low_cpu_mem_usage=True,
|
| 113 |
-
**kwargs
|
| 114 |
-
)
|
| 115 |
else:
|
| 116 |
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
|
| 117 |
-
model = LlavaLlamaForCausalLM.from_pretrained(
|
| 118 |
-
model_path,
|
| 119 |
-
low_cpu_mem_usage=True,
|
| 120 |
-
**kwargs
|
| 121 |
-
)
|
| 122 |
else:
|
| 123 |
# Load language model
|
| 124 |
if model_base is not None:
|
| 125 |
# PEFT model
|
| 126 |
from peft import PeftModel
|
| 127 |
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
| 128 |
-
model = AutoModelForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True,
|
| 129 |
print(f"Loading LoRA weights from {model_path}")
|
| 130 |
model = PeftModel.from_pretrained(model, model_path)
|
| 131 |
print(f"Merging weights")
|
|
@@ -154,9 +137,10 @@ def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, l
|
|
| 154 |
|
| 155 |
vision_tower = model.get_vision_tower()
|
| 156 |
if not vision_tower.is_loaded:
|
| 157 |
-
vision_tower.load_model(
|
| 158 |
-
|
| 159 |
-
|
|
|
|
| 160 |
image_processor = vision_tower.image_processor
|
| 161 |
|
| 162 |
if hasattr(model.config, "max_sequence_length"):
|
|
|
|
| 23 |
from llava.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 24 |
|
| 25 |
|
| 26 |
+
def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto"):
|
| 27 |
+
kwargs = {"device_map": device_map}
|
| 28 |
+
kwargs["offload_folder"] = "offload"
|
|
|
|
|
|
|
| 29 |
|
| 30 |
if load_8bit:
|
| 31 |
kwargs['load_in_8bit'] = True
|
|
|
|
| 40 |
else:
|
| 41 |
kwargs['torch_dtype'] = torch.float16
|
| 42 |
|
|
|
|
|
|
|
|
|
|
| 43 |
if 'llava' in model_name.lower():
|
| 44 |
# Load LLaVA model
|
| 45 |
if 'lora' in model_name.lower() and model_base is None:
|
| 46 |
warnings.warn('There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged.')
|
| 47 |
if 'lora' in model_name.lower() and model_base is not None:
|
| 48 |
+
lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
|
|
|
|
| 49 |
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
| 50 |
print('Loading LLaVA from base model...')
|
| 51 |
model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs)
|
|
|
|
| 86 |
shutil.copyfile(os.path.join(model_base, 'configuration_mpt.py'), os.path.join(model_path, 'configuration_mpt.py'))
|
| 87 |
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True)
|
| 88 |
cfg_pretrained = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
|
| 89 |
+
model = LlavaMPTForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
|
| 90 |
else:
|
| 91 |
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
| 92 |
cfg_pretrained = AutoConfig.from_pretrained(model_path)
|
|
|
|
| 98 |
else:
|
| 99 |
if 'mpt' in model_name.lower():
|
| 100 |
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
|
| 101 |
+
model = LlavaMPTForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
else:
|
| 103 |
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
|
| 104 |
+
model = LlavaLlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
else:
|
| 106 |
# Load language model
|
| 107 |
if model_base is not None:
|
| 108 |
# PEFT model
|
| 109 |
from peft import PeftModel
|
| 110 |
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
| 111 |
+
model = AutoModelForCausalLM.from_pretrained(model_base, torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto")
|
| 112 |
print(f"Loading LoRA weights from {model_path}")
|
| 113 |
model = PeftModel.from_pretrained(model, model_path)
|
| 114 |
print(f"Merging weights")
|
|
|
|
| 137 |
|
| 138 |
vision_tower = model.get_vision_tower()
|
| 139 |
if not vision_tower.is_loaded:
|
| 140 |
+
vision_tower.load_model()
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
vision_tower.to(device=model.device, dtype=torch.float16)
|
| 144 |
image_processor = vision_tower.image_processor
|
| 145 |
|
| 146 |
if hasattr(model.config, "max_sequence_length"):
|
llava/model/language_model/llava_llama.py
CHANGED
|
@@ -17,18 +17,18 @@ from typing import List, Optional, Tuple, Union
|
|
| 17 |
|
| 18 |
import torch
|
| 19 |
import torch.nn as nn
|
|
|
|
| 20 |
|
| 21 |
from transformers import AutoConfig, AutoModelForCausalLM, \
|
| 22 |
LlamaConfig, LlamaModel, LlamaForCausalLM
|
| 23 |
|
| 24 |
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 25 |
-
from transformers.generation.utils import GenerateOutput
|
| 26 |
|
| 27 |
from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
|
| 28 |
|
| 29 |
|
| 30 |
class LlavaConfig(LlamaConfig):
|
| 31 |
-
model_type = "
|
| 32 |
|
| 33 |
|
| 34 |
class LlavaLlamaModel(LlavaMetaModel, LlamaModel):
|
|
@@ -44,8 +44,7 @@ class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM):
|
|
| 44 |
def __init__(self, config):
|
| 45 |
super(LlamaForCausalLM, self).__init__(config)
|
| 46 |
self.model = LlavaLlamaModel(config)
|
| 47 |
-
|
| 48 |
-
self.vocab_size = config.vocab_size
|
| 49 |
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 50 |
|
| 51 |
# Initialize weights and apply final processing
|
|
@@ -58,7 +57,6 @@ class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM):
|
|
| 58 |
self,
|
| 59 |
input_ids: torch.LongTensor = None,
|
| 60 |
attention_mask: Optional[torch.Tensor] = None,
|
| 61 |
-
position_ids: Optional[torch.LongTensor] = None,
|
| 62 |
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 63 |
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 64 |
labels: Optional[torch.LongTensor] = None,
|
|
@@ -66,93 +64,77 @@ class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM):
|
|
| 66 |
output_attentions: Optional[bool] = None,
|
| 67 |
output_hidden_states: Optional[bool] = None,
|
| 68 |
images: Optional[torch.FloatTensor] = None,
|
| 69 |
-
image_sizes: Optional[List[List[int]]] = None,
|
| 70 |
return_dict: Optional[bool] = None,
|
| 71 |
) -> Union[Tuple, CausalLMOutputWithPast]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
input_ids,
|
| 76 |
-
position_ids,
|
| 77 |
-
attention_mask,
|
| 78 |
-
past_key_values,
|
| 79 |
-
inputs_embeds,
|
| 80 |
-
labels
|
| 81 |
-
) = self.prepare_inputs_labels_for_multimodal(
|
| 82 |
-
input_ids,
|
| 83 |
-
position_ids,
|
| 84 |
-
attention_mask,
|
| 85 |
-
past_key_values,
|
| 86 |
-
labels,
|
| 87 |
-
images,
|
| 88 |
-
image_sizes
|
| 89 |
-
)
|
| 90 |
-
|
| 91 |
-
return super().forward(
|
| 92 |
input_ids=input_ids,
|
| 93 |
attention_mask=attention_mask,
|
| 94 |
-
position_ids=position_ids,
|
| 95 |
past_key_values=past_key_values,
|
| 96 |
inputs_embeds=inputs_embeds,
|
| 97 |
-
labels=labels,
|
| 98 |
use_cache=use_cache,
|
| 99 |
output_attentions=output_attentions,
|
| 100 |
output_hidden_states=output_hidden_states,
|
| 101 |
return_dict=return_dict
|
| 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 |
-
None,
|
| 131 |
-
images,
|
| 132 |
-
image_sizes=image_sizes
|
| 133 |
-
)
|
| 134 |
-
else:
|
| 135 |
-
inputs_embeds = self.get_model().embed_tokens(inputs)
|
| 136 |
-
|
| 137 |
-
return super().generate(
|
| 138 |
-
position_ids=position_ids,
|
| 139 |
-
attention_mask=attention_mask,
|
| 140 |
-
inputs_embeds=inputs_embeds,
|
| 141 |
-
**kwargs
|
| 142 |
)
|
| 143 |
|
| 144 |
-
def prepare_inputs_for_generation(
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
)
|
| 151 |
-
|
| 152 |
-
inputs['images'] = images
|
| 153 |
-
if image_sizes is not None:
|
| 154 |
-
inputs['image_sizes'] = image_sizes
|
| 155 |
-
return inputs
|
| 156 |
|
| 157 |
-
AutoConfig.register("
|
| 158 |
AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM)
|
|
|
|
| 17 |
|
| 18 |
import torch
|
| 19 |
import torch.nn as nn
|
| 20 |
+
from torch.nn import CrossEntropyLoss
|
| 21 |
|
| 22 |
from transformers import AutoConfig, AutoModelForCausalLM, \
|
| 23 |
LlamaConfig, LlamaModel, LlamaForCausalLM
|
| 24 |
|
| 25 |
from transformers.modeling_outputs import CausalLMOutputWithPast
|
|
|
|
| 26 |
|
| 27 |
from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
|
| 28 |
|
| 29 |
|
| 30 |
class LlavaConfig(LlamaConfig):
|
| 31 |
+
model_type = "llava"
|
| 32 |
|
| 33 |
|
| 34 |
class LlavaLlamaModel(LlavaMetaModel, LlamaModel):
|
|
|
|
| 44 |
def __init__(self, config):
|
| 45 |
super(LlamaForCausalLM, self).__init__(config)
|
| 46 |
self.model = LlavaLlamaModel(config)
|
| 47 |
+
|
|
|
|
| 48 |
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 49 |
|
| 50 |
# Initialize weights and apply final processing
|
|
|
|
| 57 |
self,
|
| 58 |
input_ids: torch.LongTensor = None,
|
| 59 |
attention_mask: Optional[torch.Tensor] = None,
|
|
|
|
| 60 |
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 61 |
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 62 |
labels: Optional[torch.LongTensor] = None,
|
|
|
|
| 64 |
output_attentions: Optional[bool] = None,
|
| 65 |
output_hidden_states: Optional[bool] = None,
|
| 66 |
images: Optional[torch.FloatTensor] = None,
|
|
|
|
| 67 |
return_dict: Optional[bool] = None,
|
| 68 |
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 69 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 70 |
+
output_hidden_states = (
|
| 71 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 72 |
+
)
|
| 73 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 74 |
+
|
| 75 |
+
input_ids, attention_mask, past_key_values, inputs_embeds, labels = self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images)
|
| 76 |
|
| 77 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 78 |
+
outputs = self.model(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
input_ids=input_ids,
|
| 80 |
attention_mask=attention_mask,
|
|
|
|
| 81 |
past_key_values=past_key_values,
|
| 82 |
inputs_embeds=inputs_embeds,
|
|
|
|
| 83 |
use_cache=use_cache,
|
| 84 |
output_attentions=output_attentions,
|
| 85 |
output_hidden_states=output_hidden_states,
|
| 86 |
return_dict=return_dict
|
| 87 |
)
|
| 88 |
|
| 89 |
+
hidden_states = outputs[0]
|
| 90 |
+
logits = self.lm_head(hidden_states)
|
| 91 |
+
|
| 92 |
+
loss = None
|
| 93 |
+
if labels is not None:
|
| 94 |
+
# Shift so that tokens < n predict n
|
| 95 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 96 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 97 |
+
# Flatten the tokens
|
| 98 |
+
loss_fct = CrossEntropyLoss()
|
| 99 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
| 100 |
+
shift_labels = shift_labels.view(-1)
|
| 101 |
+
# Enable model/pipeline parallelism
|
| 102 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 103 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 104 |
+
|
| 105 |
+
if not return_dict:
|
| 106 |
+
output = (logits,) + outputs[1:]
|
| 107 |
+
return (loss,) + output if loss is not None else output
|
| 108 |
+
|
| 109 |
+
return CausalLMOutputWithPast(
|
| 110 |
+
loss=loss,
|
| 111 |
+
logits=logits,
|
| 112 |
+
past_key_values=outputs.past_key_values,
|
| 113 |
+
hidden_states=outputs.hidden_states,
|
| 114 |
+
attentions=outputs.attentions,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
)
|
| 116 |
|
| 117 |
+
def prepare_inputs_for_generation(
|
| 118 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
| 119 |
+
):
|
| 120 |
+
if past_key_values:
|
| 121 |
+
input_ids = input_ids[:, -1:]
|
| 122 |
+
|
| 123 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 124 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 125 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 126 |
+
else:
|
| 127 |
+
model_inputs = {"input_ids": input_ids}
|
| 128 |
+
|
| 129 |
+
model_inputs.update(
|
| 130 |
+
{
|
| 131 |
+
"past_key_values": past_key_values,
|
| 132 |
+
"use_cache": kwargs.get("use_cache"),
|
| 133 |
+
"attention_mask": attention_mask,
|
| 134 |
+
"images": kwargs.get("images", None),
|
| 135 |
+
}
|
| 136 |
)
|
| 137 |
+
return model_inputs
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
+
AutoConfig.register("llava", LlavaConfig)
|
| 140 |
AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM)
|