diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..035e14937b3b57125ac54463770dfda25fbff6bf
--- /dev/null
+++ b/.devcontainer/Dockerfile
@@ -0,0 +1,53 @@
+FROM mcr.microsoft.com/devcontainers/base:ubuntu-20.04
+
+SHELL [ "bash", "-c" ]
+
+# update apt and install packages
+RUN apt update && \
+ apt install -yq \
+ ffmpeg \
+ dkms \
+ build-essential
+
+# add user tools
+RUN sudo apt install -yq \
+ jq \
+ jp \
+ tree \
+ tldr
+
+# add git-lfs and install
+RUN curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash && \
+ sudo apt-get install -yq git-lfs && \
+ git lfs install
+
+############################################
+# Setup user
+############################################
+
+USER vscode
+
+# install azcopy, a tool to copy to/from blob storage
+# for more info: https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azcopy-blobs-upload#upload-a-file
+RUN cd /tmp && \
+ wget https://azcopyvnext.azureedge.net/release20230123/azcopy_linux_amd64_10.17.0.tar.gz && \
+ tar xvf azcopy_linux_amd64_10.17.0.tar.gz && \
+ mkdir -p ~/.local/bin && \
+ mv azcopy_linux_amd64_10.17.0/azcopy ~/.local/bin && \
+ chmod +x ~/.local/bin/azcopy && \
+ rm -rf azcopy_linux_amd64*
+
+# Setup conda
+RUN cd /tmp && \
+ wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh && \
+ bash ./Miniconda3-latest-Linux-x86_64.sh -b && \
+ rm ./Miniconda3-latest-Linux-x86_64.sh
+
+# Install dotnet
+RUN cd /tmp && \
+ wget https://dot.net/v1/dotnet-install.sh && \
+ chmod +x dotnet-install.sh && \
+ ./dotnet-install.sh --channel 7.0 && \
+ ./dotnet-install.sh --channel 3.1 && \
+ rm ./dotnet-install.sh
+
diff --git a/.devcontainer/devcontainer.env b/.devcontainer/devcontainer.env
new file mode 100644
index 0000000000000000000000000000000000000000..4cf3a49c16e1113f4d941b409bb9c7bea6c90fe0
--- /dev/null
+++ b/.devcontainer/devcontainer.env
@@ -0,0 +1,2 @@
+SAMPLE_ENV_VAR1="Sample Value"
+SAMPLE_ENV_VAR2=332431bf-68bf
\ No newline at end of file
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json
new file mode 100644
index 0000000000000000000000000000000000000000..67f6ca20e17d808e3e77b806ad8a988b120f40a9
--- /dev/null
+++ b/.devcontainer/devcontainer.json
@@ -0,0 +1,71 @@
+{
+ "name": "LLaVA",
+ "build": {
+ "dockerfile": "Dockerfile",
+ "context": "..",
+ "args": {}
+ },
+ "features": {
+ "ghcr.io/devcontainers/features/docker-in-docker:2": {},
+ "ghcr.io/devcontainers/features/azure-cli:1": {},
+ "ghcr.io/azure/azure-dev/azd:0": {},
+ "ghcr.io/devcontainers/features/powershell:1": {},
+ "ghcr.io/devcontainers/features/common-utils:2": {},
+ "ghcr.io/devcontainers-contrib/features/zsh-plugins:0": {},
+ },
+ // "forwardPorts": [],
+ "postCreateCommand": "bash ./.devcontainer/postCreateCommand.sh",
+ "customizations": {
+ "vscode": {
+ "settings": {
+ "python.analysis.autoImportCompletions": true,
+ "python.analysis.autoImportUserSymbols": true,
+ "python.defaultInterpreterPath": "~/miniconda3/envs/llava/bin/python",
+ "python.formatting.provider": "yapf",
+ "python.linting.enabled": true,
+ "python.linting.flake8Enabled": true,
+ "isort.check": true,
+ "dev.containers.copyGitConfig": true,
+ "terminal.integrated.defaultProfile.linux": "zsh",
+ "terminal.integrated.profiles.linux": {
+ "zsh": {
+ "path": "/usr/bin/zsh"
+ },
+ }
+ },
+ "extensions": [
+ "aaron-bond.better-comments",
+ "eamodio.gitlens",
+ "EditorConfig.EditorConfig",
+ "foxundermoon.shell-format",
+ "GitHub.copilot-chat",
+ "GitHub.copilot-labs",
+ "GitHub.copilot",
+ "lehoanganh298.json-lines-viewer",
+ "mhutchie.git-graph",
+ "ms-azuretools.vscode-docker",
+ "ms-dotnettools.dotnet-interactive-vscode",
+ "ms-python.flake8",
+ "ms-python.isort",
+ "ms-python.python",
+ "ms-python.vscode-pylance",
+ "njpwerner.autodocstring",
+ "redhat.vscode-yaml",
+ "stkb.rewrap",
+ "yzhang.markdown-all-in-one",
+ ]
+ }
+ },
+ "mounts": [],
+ "runArgs": [
+ "--gpus",
+ "all",
+ // "--ipc",
+ // "host",
+ "--ulimit",
+ "memlock=-1",
+ "--env-file",
+ ".devcontainer/devcontainer.env"
+ ],
+ // "remoteUser": "root"
+}
diff --git a/.devcontainer/postCreateCommand.sh b/.devcontainer/postCreateCommand.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b32449207ce184a0d13eac79fbd83235acd451db
--- /dev/null
+++ b/.devcontainer/postCreateCommand.sh
@@ -0,0 +1,45 @@
+git config --global safe.directory '*'
+git config --global core.editor "code --wait"
+git config --global pager.branch false
+
+# Set AZCOPY concurrency to auto
+echo "export AZCOPY_CONCURRENCY_VALUE=AUTO" >> ~/.zshrc
+echo "export AZCOPY_CONCURRENCY_VALUE=AUTO" >> ~/.bashrc
+
+# Activate conda by default
+echo ". /home/vscode/miniconda3/bin/activate" >> ~/.zshrc
+echo ". /home/vscode/miniconda3/bin/activate" >> ~/.bashrc
+
+# Use llava environment by default
+echo "conda activate llava" >> ~/.zshrc
+echo "conda activate llava" >> ~/.bashrc
+
+# Add dotnet to PATH
+echo 'export PATH="$PATH:$HOME/.dotnet"' >> ~/.bashrc
+echo 'export PATH="$PATH:$HOME/.dotnet"' >> ~/.zshrc
+
+# Create and activate llava environment
+source /home/vscode/miniconda3/bin/activate
+conda create -y -q -n llava python=3.10
+conda activate llava
+
+# Install Nvidia Cuda Compiler
+conda install -y -c nvidia cuda-compiler
+
+pip install pre-commit==3.0.2
+
+# Install package locally
+pip install --upgrade pip # enable PEP 660 support
+pip install -e .
+
+# Install additional packages for training
+pip install -e ".[train]"
+pip install flash-attn --no-build-isolation
+
+# Download checkpoints to location outside of the repo
+git clone https://huggingface.co/liuhaotian/llava-v1.5-7b ~/llava-v1.5-7b
+
+# Commented because it is unlikely for users to have enough local GPU memory to load the model
+# git clone https://huggingface.co/liuhaotian/llava-v1.5-13b ~/llava-v1.5-13b
+
+echo "postCreateCommand.sh COMPLETE!"
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000000000000000000000000000000000000..e98058ee30350a2be1da90c47bf2f335ec21457b
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,21 @@
+# The .dockerignore file excludes files from the container build process.
+#
+# https://docs.docker.com/engine/reference/builder/#dockerignore-file
+
+# Exclude Git files
+.git
+.github
+.gitignore
+
+# Exclude Python cache files
+__pycache__
+.mypy_cache
+.pytest_cache
+.ruff_cache
+
+# Exclude Python virtual environment
+/venv
+
+# Exclude some weights
+/openai
+/liuhaotian
diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000000000000000000000000000000000000..d99a490bee397f969e93faa0c083b69674435ee8
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,18 @@
+root = true
+
+# Unix-style newlines with a newline ending every file
+[*]
+end_of_line = lf
+insert_final_newline = true
+trim_trailing_whitespace = true
+charset = utf-8
+
+# 4 space indentation
+[*.{py,json}]
+indent_style = space
+indent_size = 4
+
+# 2 space indentation
+[*.{md,sh,yaml,yml}]
+indent_style = space
+indent_size = 2
\ No newline at end of file
diff --git a/.gitattributes b/.gitattributes
index a6344aac8c09253b3b630fb776ae94478aa0275b..6e453c1b8e0b44807e1c6d6c63f4f5d973c237c9 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,35 +1,31 @@
-*.7z filter=lfs diff=lfs merge=lfs -text
-*.arrow filter=lfs diff=lfs merge=lfs -text
-*.bin filter=lfs diff=lfs merge=lfs -text
-*.bz2 filter=lfs diff=lfs merge=lfs -text
-*.ckpt filter=lfs diff=lfs merge=lfs -text
-*.ftz filter=lfs diff=lfs merge=lfs -text
-*.gz filter=lfs diff=lfs merge=lfs -text
-*.h5 filter=lfs diff=lfs merge=lfs -text
-*.joblib filter=lfs diff=lfs merge=lfs -text
-*.lfs.* filter=lfs diff=lfs merge=lfs -text
-*.mlmodel filter=lfs diff=lfs merge=lfs -text
-*.model filter=lfs diff=lfs merge=lfs -text
-*.msgpack filter=lfs diff=lfs merge=lfs -text
-*.npy filter=lfs diff=lfs merge=lfs -text
-*.npz filter=lfs diff=lfs merge=lfs -text
-*.onnx filter=lfs diff=lfs merge=lfs -text
-*.ot filter=lfs diff=lfs merge=lfs -text
-*.parquet filter=lfs diff=lfs merge=lfs -text
-*.pb filter=lfs diff=lfs merge=lfs -text
-*.pickle filter=lfs diff=lfs merge=lfs -text
-*.pkl filter=lfs diff=lfs merge=lfs -text
-*.pt filter=lfs diff=lfs merge=lfs -text
-*.pth filter=lfs diff=lfs merge=lfs -text
-*.rar filter=lfs diff=lfs merge=lfs -text
-*.safetensors filter=lfs diff=lfs merge=lfs -text
-saved_model/**/* filter=lfs diff=lfs merge=lfs -text
-*.tar.* filter=lfs diff=lfs merge=lfs -text
-*.tar filter=lfs diff=lfs merge=lfs -text
-*.tflite filter=lfs diff=lfs merge=lfs -text
-*.tgz filter=lfs diff=lfs merge=lfs -text
-*.wasm filter=lfs diff=lfs merge=lfs -text
-*.xz filter=lfs diff=lfs merge=lfs -text
-*.zip filter=lfs diff=lfs merge=lfs -text
-*.zst filter=lfs diff=lfs merge=lfs -text
-*tfevents* filter=lfs diff=lfs merge=lfs -text
+# https://git-scm.com/docs/gitattributes
+
+# Set the default behavior, in case people don't have core.autocrlf set.
+# https://git-scm.com/docs/gitattributes#_end_of_line_conversion
+* text=auto
+
+# common python attributes, taken from https://github.com/alexkaratarakis/gitattributes/blob/710900479a2bedeec7003d381719521ffbb18bf8/Python.gitattributes
+# Source files
+# ============
+*.pxd text diff=python
+*.py text diff=python
+*.py3 text diff=python
+*.pyw text diff=python
+*.pyx text diff=python
+*.pyz text diff=python
+*.pyi text diff=python
+
+# Binary files
+# ============
+*.db binary
+*.p binary
+*.pkl binary
+*.pickle binary
+*.pyc binary export-ignore
+*.pyo binary export-ignore
+*.pyd binary
+
+# Jupyter notebook
+*.ipynb text eol=lf
+alpha_clip_final/bpe_simple_vocab_16e6.txt.gz filter=lfs diff=lfs merge=lfs -text
+images/demo_cli.gif filter=lfs diff=lfs merge=lfs -text
diff --git a/.github/ISSUE_TEMPLATE/1-usage.yaml b/.github/ISSUE_TEMPLATE/1-usage.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..bb4094e5ab241057019bf767e2fd7b7e9dfc7e7a
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/1-usage.yaml
@@ -0,0 +1,31 @@
+name: Usage issues
+description: Report issues in usage.
+title: "[Usage] "
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Thanks for taking the time to fill out this form. Please give as detailed description as possible for us to better assist with the issue :)
+ - type: textarea
+ id: what-happened
+ attributes:
+ label: Describe the issue
+ description: Please give as detailed description as possible for us to better assist with the issue. Please paste the **FULL** error log here, so that we can better understand the issue. Wrap the log with ``` for better readability in GitHub.
+ placeholder: Issue
+ value: |
+ Issue:
+
+ Command:
+ ```
+ PASTE THE COMMANDS HERE.
+ ```
+
+ Log:
+ ```
+ PASTE THE LOGS HERE.
+ ```
+
+ Screenshots:
+ You may attach screenshots if it better explains the issue.
+ validations:
+ required: true
diff --git a/.github/ISSUE_TEMPLATE/2-feature-request.yaml b/.github/ISSUE_TEMPLATE/2-feature-request.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..a55dc3136718f89096452e9a3018de23b5c385d9
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/2-feature-request.yaml
@@ -0,0 +1,13 @@
+name: Feature Request
+description: Request for a new feature
+title: "[Feature request] "
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Thanks for your interest in our work. Please share your thoughts of the new features below.
+ - type: textarea
+ id: feature
+ attributes:
+ label: feature
+ placeholder: Start your thoughts here...
\ No newline at end of file
diff --git a/.github/ISSUE_TEMPLATE/3-question.yaml b/.github/ISSUE_TEMPLATE/3-question.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..7c4a4fc28f8ef61c6d5a4eca8f03a5c268998fcf
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/3-question.yaml
@@ -0,0 +1,13 @@
+name: Questions
+description: General questions about the work
+title: "[Question] "
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Thanks for your interest in our work. For this type of question, it may be more suitable to go to [discussion](https://github.com/haotian-liu/LLaVA/discussions) sections. If you believe an issue would be better for your request, please continue your post below :)
+ - type: textarea
+ id: question
+ attributes:
+ label: Question
+ placeholder: Start question here...
\ No newline at end of file
diff --git a/.github/ISSUE_TEMPLATE/4-discussion.yaml b/.github/ISSUE_TEMPLATE/4-discussion.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c6dc05c3d144d028eaf696b9518354f482d34a0f
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/4-discussion.yaml
@@ -0,0 +1,13 @@
+name: Discussions
+description: General discussions about the work
+title: "[Discussion] "
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Thanks for your interest in our work. For this type of question, it may be more suitable to go to [discussion](https://github.com/haotian-liu/LLaVA/discussions) sections. If you believe an issue would be better for your request, please continue your post below :)
+ - type: textarea
+ id: discussion
+ attributes:
+ label: Discussion
+ placeholder: Start discussion here...
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..6ff6a3dc8c18c7358083135d1eb5bbb9c20fa50f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,35 @@
+# Python
+__pycache__
+*.pyc
+*.egg-info
+dist
+
+# Log
+*.log
+*.log.*
+*.json
+*.jsonl
+
+# Data
+!**/alpaca-data-conversation.json
+
+# Editor
+.idea
+*.swp
+
+# Other
+.DS_Store
+wandb
+output
+
+checkpoints
+ckpts*
+
+.ipynb_checkpoints
+*.ipynb
+
+# DevContainer
+!.devcontainer/*
+
+# Demo
+serve_images/
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..3a0099656bc17e996c3700ce36926796693ba045
--- /dev/null
+++ b/README.md
@@ -0,0 +1,463 @@
+# ๐ LLaVA: Large Language and Vision Assistant
+
+*Visual instruction tuning towards large language and vision models with GPT-4 level capabilities.*
+
+[๐ข [LLaVA-NeXT Blog](https://llava-vl.github.io/blog/2024-01-30-llava-next/)] [[Project Page](https://llava-vl.github.io/)] [[Demo](https://llava.hliu.cc/)] [[Data](https://github.com/haotian-liu/LLaVA/blob/main/docs/Data.md)] [[Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)]
+
+๐คCommunity Contributions: [[llama.cpp](https://github.com/ggerganov/llama.cpp/pull/3436)] [[Colab](https://github.com/camenduru/LLaVA-colab)] [[๐คSpace](https://huggingface.co/spaces/badayvedat/LLaVA)] [[Replicate](https://replicate.com/yorickvp/llava-13b)] [[AutoGen](https://github.com/microsoft/autogen/blob/main/notebook/agentchat_lmm_llava.ipynb)] [[BakLLaVA](https://github.com/SkunkworksAI/BakLLaVA)]
+
+**Improved Baselines with Visual Instruction Tuning** [[Paper](https://arxiv.org/abs/2310.03744)] [[HF](https://huggingface.co/papers/2310.03744)]
+[Haotian Liu](https://hliu.cc), [Chunyuan Li](https://chunyuan.li/), [Yuheng Li](https://yuheng-li.github.io/), [Yong Jae Lee](https://pages.cs.wisc.edu/~yongjaelee/)
+
+**Visual Instruction Tuning** (NeurIPS 2023, **Oral**) [[Paper](https://arxiv.org/abs/2304.08485)] [[HF](https://huggingface.co/papers/2304.08485)]
+[Haotian Liu*](https://hliu.cc), [Chunyuan Li*](https://chunyuan.li/), [Qingyang Wu](https://scholar.google.ca/citations?user=HDiw-TsAAAAJ&hl=en/), [Yong Jae Lee](https://pages.cs.wisc.edu/~yongjaelee/) (*Equal Contribution)
+
+
+
+
+## Release
+
+- [2024/05/10] ๐ฅ **LLaVA-NeXT** (Stronger) models are released, stronger LMM with support of LLama-3 (8B) and Qwen-1.5 (72B/110B). [[Blog](https://llava-vl.github.io/blog/2024-05-10-llava-next-stronger-llms/)] [[Checkpoints](https://huggingface.co/collections/lmms-lab/llava-next-6623288e2d61edba3ddbf5ff)] [[Demo](https://llava-next.lmms-lab.com/)] [[Code](https://github.com/LLaVA-VL/LLaVA-NeXT/)]
+- [2024/05/10] ๐ฅ **LLaVA-NeXT** (Video) is released. The image-only-trained LLaVA-NeXT model is surprisingly strong on video tasks with zero-shot modality transfer. DPO training with AI feedback on videos can yield significant improvement. [[Blog](https://llava-vl.github.io/blog/2024-04-30-llava-next-video/)] [[Checkpoints](https://huggingface.co/collections/lmms-lab/llava-next-video-661e86f5e8dabc3ff793c944)] [[Code](https://github.com/LLaVA-VL/LLaVA-NeXT/)]
+- [03/10] Releasing **LMMs-Eval**, a highly efficient evaluation pipeline we used when developing LLaVA-NeXT. It supports the evaluation of LMMs on dozens of public datasets and allows new dataset onboarding, making the dev of new LMMs much faster. [[Blog](https://lmms-lab.github.io/lmms-eval-blog/lmms-eval-0.1/)] [[Codebase](https://github.com/EvolvingLMMs-Lab/lmms-eval)]
+- [1/30] ๐ฅ **LLaVA-NeXT** (LLaVA-1.6) is out! With additional scaling to LLaVA-1.5, LLaVA-NeXT-34B outperforms Gemini Pro on some benchmarks. It can now process 4x more pixels and perform more tasks/applications than before. Check out the [blog post](https://llava-vl.github.io/blog/2024-01-30-llava-next/), and explore the [demo](https://llava.hliu.cc/)! Models are available in [Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md). Training/eval data and scripts coming soon.
+- [11/10] [LLaVA-Plus](https://llava-vl.github.io/llava-plus/) is released: Learning to Use Tools for Creating Multimodal Agents, with LLaVA-Plus (LLaVA that Plug and Learn to Use Skills). [[Project Page](https://llava-vl.github.io/llava-plus/)] [[Demo](https://llavaplus.ngrok.io/)] [[Code](https://github.com/LLaVA-VL/LLaVA-Plus-Codebase)] [[Paper](https://arxiv.org/abs/2311.05437)]
+- [11/2] [LLaVA-Interactive](https://llava-vl.github.io/llava-interactive/) is released: Experience the future of human-AI multimodal interaction with an all-in-one demo for Image Chat, Segmentation, Generation and Editing. [[Project Page](https://llava-vl.github.io/llava-interactive/)] [[Demo](https://llavainteractive.ngrok.io/)] [[Code](https://github.com/LLaVA-VL/LLaVA-Interactive-Demo)] [[Paper](https://arxiv.org/abs/2311.00571)]
+- [10/26] ๐ฅ LLaVA-1.5 with LoRA achieves comparable performance as full-model finetuning, with a reduced GPU RAM requirement ([ckpts](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md#llava-v15), [script](https://github.com/haotian-liu/LLaVA#train)). We also provide a [doc](https://github.com/haotian-liu/LLaVA/blob/main/docs/Finetune_Custom_Data.md) on how to finetune LLaVA-1.5 on your own dataset with LoRA.
+- [10/12] Check out the Korean LLaVA (Ko-LLaVA), created by ETRI, who has generously supported our research! [[๐ค Demo](https://huggingface.co/spaces/etri-vilab/Ko-LLaVA)]
+- [10/5] ๐ฅ LLaVA-1.5 is out! Achieving SoTA on 11 benchmarks, with just simple modifications to the original LLaVA, utilizes all public data, completes training in ~1 day on a single 8-A100 node, and surpasses methods like Qwen-VL-Chat that use billion-scale data. Check out the [technical report](https://arxiv.org/abs/2310.03744), and explore the [demo](https://llava.hliu.cc/)! Models are available in [Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md). The training data and scripts of LLaVA-1.5 are released [here](https://github.com/haotian-liu/LLaVA#train), and evaluation scripts are released [here](https://github.com/haotian-liu/LLaVA/blob/main/docs/Evaluation.md)!
+- [9/26] LLaVA is improved with reinforcement learning from human feedback (RLHF) to improve fact grounding and reduce hallucination. Check out the new SFT and RLHF checkpoints at project [[LLavA-RLHF]](https://llava-rlhf.github.io/)
+- [9/22] [LLaVA](https://arxiv.org/abs/2304.08485) is accepted by NeurIPS 2023 as **oral presentation**, and [LLaVA-Med](https://arxiv.org/abs/2306.00890) is accepted by NeurIPS 2023 Datasets and Benchmarks Track as **spotlight presentation**.
+
+
+More
+
+- [11/6] Support **Intel** dGPU and CPU platforms. [More details here.](https://github.com/haotian-liu/LLaVA/tree/intel/docs/intel)
+- [10/12] LLaVA is now supported in [llama.cpp](https://github.com/ggerganov/llama.cpp/pull/3436) with 4-bit / 5-bit quantization support!
+- [10/11] The training data and scripts of LLaVA-1.5 are released [here](https://github.com/haotian-liu/LLaVA#train), and evaluation scripts are released [here](https://github.com/haotian-liu/LLaVA/blob/main/docs/Evaluation.md)!
+- [10/10] [Roboflow Deep Dive](https://blog.roboflow.com/first-impressions-with-llava-1-5/): First Impressions with LLaVA-1.5.
+- [9/20] We summarize our empirical study of training 33B and 65B LLaVA models in a [note](https://arxiv.org/abs/2309.09958). Further, if you are interested in the comprehensive review, evolution and trend of multimodal foundation models, please check out our recent survey paper [``Multimodal Foundation Models: From Specialists to General-Purpose Assistants''.](https://arxiv.org/abs/2309.10020)
+
+
+
+
+- [7/19] ๐ฅ We release a major upgrade, including support for LLaMA-2, LoRA training, 4-/8-bit inference, higher resolution (336x336), and a lot more. We release [LLaVA Bench](https://github.com/haotian-liu/LLaVA/blob/main/docs/LLaVA_Bench.md) for benchmarking open-ended visual chat with results from Bard and Bing-Chat. We also support and verify training with RTX 3090 and RTX A6000. Check out [LLaVA-from-LLaMA-2](https://github.com/haotian-liu/LLaVA/blob/main/docs/LLaVA_from_LLaMA2.md), and our [model zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)!
+- [6/26] [CVPR 2023 Tutorial](https://vlp-tutorial.github.io/) on **Large Multimodal Models: Towards Building and Surpassing Multimodal GPT-4**! Please check out [[Slides](https://datarelease.blob.core.windows.net/tutorial/vision_foundation_models_2023/slides/Chunyuan_cvpr2023_tutorial_lmm.pdf)] [[Notes](https://arxiv.org/abs/2306.14895)] [[YouTube](https://youtu.be/mkI7EPD1vp8)] [[Bilibli](https://www.bilibili.com/video/BV1Ng4y1T7v3/)].
+- [6/11] We released the preview for the most requested feature: DeepSpeed and LoRA support! Please see documentations [here](./docs/LoRA.md).
+- [6/1] We released **LLaVA-Med: Large Language and Vision Assistant for Biomedicine**, a step towards building biomedical domain large language and vision models with GPT-4 level capabilities. Checkout the [paper](https://arxiv.org/abs/2306.00890) and [page](https://github.com/microsoft/LLaVA-Med).
+- [5/6] We are releasing [LLaVA-Lighting-MPT-7B-preview](https://huggingface.co/liuhaotian/LLaVA-Lightning-MPT-7B-preview), based on MPT-7B-Chat! See [here](#LLaVA-MPT-7b) for more details.
+- [5/2] ๐ฅ We are releasing LLaVA-Lighting! Train a lite, multimodal GPT-4 with just $40 in 3 hours! See [here](#train-llava-lightning) for more details.
+- [4/27] Thanks to the community effort, LLaVA-13B with 4-bit quantization allows you to run on a GPU with as few as 12GB VRAM! Try it out [here](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/llava).
+- [4/17] ๐ฅ We released **LLaVA: Large Language and Vision Assistant**. We propose visual instruction tuning, towards building large language and vision models with GPT-4 level capabilities. Checkout the [paper](https://arxiv.org/abs/2304.08485) and [demo](https://llava.hliu.cc/).
+
+
+
+
+
+[](https://github.com/tatsu-lab/stanford_alpaca/blob/main/LICENSE)
+**Usage and License Notices**: This project utilizes certain datasets and checkpoints that are subject to their respective original licenses. Users must comply with all terms and conditions of these original licenses, including but not limited to the [OpenAI Terms of Use](https://openai.com/policies/terms-of-use) for the dataset and the specific licenses for base language models for checkpoints trained using the dataset (e.g. [Llama community license](https://ai.meta.com/llama/license/) for LLaMA-2 and Vicuna-v1.5). This project does not impose any additional constraints beyond those stipulated in the original licenses. Furthermore, users are reminded to ensure that their use of the dataset and checkpoints is in compliance with all applicable laws and regulations.
+
+
+## Contents
+- [Install](#install)
+- [LLaVA Weights](#llava-weights)
+- [Demo](#Demo)
+- [Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)
+- [Dataset](https://github.com/haotian-liu/LLaVA/blob/main/docs/Data.md)
+- [Train](#train)
+- [Evaluation](#evaluation)
+
+## Install
+
+If you are not using Linux, do *NOT* proceed, see instructions for [macOS](https://github.com/haotian-liu/LLaVA/blob/main/docs/macOS.md) and [Windows](https://github.com/haotian-liu/LLaVA/blob/main/docs/Windows.md).
+
+1. Clone this repository and navigate to LLaVA folder
+```bash
+git clone https://github.com/haotian-liu/LLaVA.git
+cd LLaVA
+```
+
+2. Install Package
+```Shell
+conda create -n llava python=3.10 -y
+conda activate llava
+pip install --upgrade pip # enable PEP 660 support
+pip install -e .
+```
+
+3. Install additional packages for training cases
+```
+pip install -e ".[train]"
+pip install flash-attn --no-build-isolation
+```
+
+### Upgrade to latest code base
+
+```Shell
+git pull
+pip install -e .
+
+# if you see some import errors when you upgrade,
+# please try running the command below (without #)
+# pip install flash-attn --no-build-isolation --no-cache-dir
+```
+
+### Quick Start With HuggingFace
+
+
+Example Code
+
+```Python
+from llava.model.builder import load_pretrained_model
+from llava.mm_utils import get_model_name_from_path
+from llava.eval.run_llava import eval_model
+
+model_path = "liuhaotian/llava-v1.5-7b"
+
+tokenizer, model, image_processor, context_len = load_pretrained_model(
+ model_path=model_path,
+ model_base=None,
+ model_name=get_model_name_from_path(model_path)
+)
+```
+
+Check out the details wth the `load_pretrained_model` function in `llava/model/builder.py`.
+
+You can also use the `eval_model` function in `llava/eval/run_llava.py` to get the output easily. By doing so, you can use this code on Colab directly after downloading this repository.
+
+``` python
+model_path = "liuhaotian/llava-v1.5-7b"
+prompt = "What are the things I should be cautious about when I visit here?"
+image_file = "https://llava-vl.github.io/static/images/view.jpg"
+
+args = type('Args', (), {
+ "model_path": model_path,
+ "model_base": None,
+ "model_name": get_model_name_from_path(model_path),
+ "query": prompt,
+ "conv_mode": None,
+ "image_file": image_file,
+ "sep": ",",
+ "temperature": 0,
+ "top_p": None,
+ "num_beams": 1,
+ "max_new_tokens": 512
+})()
+
+eval_model(args)
+```
+
+
+## LLaVA Weights
+Please check out our [Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md) for all public LLaVA checkpoints, and the instructions of how to use the weights.
+
+## Demo
+
+### Gradio Web UI
+
+To launch a Gradio demo locally, please run the following commands one by one. If you plan to launch multiple model workers to compare between different checkpoints, you only need to launch the controller and the web server *ONCE*.
+
+```mermaid
+flowchart BT
+ %% Declare Nodes
+ gws("Gradio (UI Server)")
+ c("Controller (API Server): PORT: 10000")
+ mw7b("Model Worker: llava-v1.5-7b PORT: 40000")
+ mw13b("Model Worker: llava-v1.5-13b PORT: 40001")
+ sglw13b("SGLang Backend: llava-v1.6-34b http://localhost:30000")
+ lsglw13b("SGLang Worker: llava-v1.6-34b PORT: 40002")
+
+ %% Declare Styles
+ classDef data fill:#3af,stroke:#48a,stroke-width:2px,color:#444
+ classDef success fill:#8f8,stroke:#0a0,stroke-width:2px,color:#444
+ classDef failure fill:#f88,stroke:#f00,stroke-width:2px,color:#444
+
+ %% Assign Styles
+ class id,od data;
+ class cimg,cs_s,scsim_s success;
+ class ncimg,cs_f,scsim_f failure;
+
+ subgraph Demo Connections
+ direction BT
+ c<-->gws
+
+ mw7b<-->c
+ mw13b<-->c
+ lsglw13b<-->c
+ sglw13b<-->lsglw13b
+ end
+```
+
+#### Launch a controller
+```Shell
+python -m llava.serve.controller --host 0.0.0.0 --port 10000
+```
+
+#### Launch a gradio web server.
+```Shell
+python -m llava.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload
+```
+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.
+
+#### Launch a SGLang worker
+
+This is the recommended way to serve LLaVA model with high throughput, and you need to install SGLang first. Note that currently `4-bit` quantization is not supported yet on SGLang-LLaVA, and if you have limited GPU VRAM, please check out model worker with [quantization](https://github.com/haotian-liu/LLaVA?tab=readme-ov-file#launch-a-model-worker-4-bit-8-bit-inference-quantized).
+
+```Shell
+pip install "sglang[all]"
+```
+
+You'll first launch a SGLang backend worker which will execute the models on GPUs. Remember the `--port` you've set and you'll use that later.
+
+```Shell
+# Single GPU
+CUDA_VISIBLE_DEVICES=0 python3 -m sglang.launch_server --model-path liuhaotian/llava-v1.5-7b --tokenizer-path llava-hf/llava-1.5-7b-hf --port 30000
+
+# Multiple GPUs with tensor parallel
+CUDA_VISIBLE_DEVICES=0,1 python3 -m sglang.launch_server --model-path liuhaotian/llava-v1.5-13b --tokenizer-path llava-hf/llava-1.5-13b-hf --port 30000 --tp 2
+```
+
+Tokenizers (temporary): `llava-hf/llava-1.5-7b-hf`, `llava-hf/llava-1.5-13b-hf`, `liuhaotian/llava-v1.6-34b-tokenizer`.
+
+You'll then launch a LLaVA-SGLang worker that will communicate between LLaVA controller and SGLang backend to route the requests. Set `--sgl-endpoint` to `http://127.0.0.1:port` where `port` is the one you just set (default: 30000).
+
+```Shell
+python -m llava.serve.sglang_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --sgl-endpoint http://127.0.0.1:30000
+```
+
+#### Launch a model worker
+
+This is the actual *worker* that performs the inference on the GPU. Each worker is responsible for a single model specified in `--model-path`.
+
+```Shell
+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-v1.5-13b
+```
+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.
+
+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.
+```Shell
+python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port --worker http://localhost: --model-path
+```
+
+If you are using an Apple device with an M1 or M2 chip, you can specify the mps device by using the `--device` flag: `--device mps`.
+
+#### Launch a model worker (Multiple GPUs, when GPU VRAM <= 24GB)
+
+If the VRAM of your GPU is less than 24GB (e.g., RTX 3090, RTX 4090, etc.), you may try running it with multiple GPUs. Our latest code base will automatically try to use multiple GPUs if you have more than one GPU. You can specify which GPUs to use with `CUDA_VISIBLE_DEVICES`. Below is an example of running with the first two GPUs.
+
+```Shell
+CUDA_VISIBLE_DEVICES=0,1 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-v1.5-13b
+```
+
+#### Launch a model worker (4-bit, 8-bit inference, quantized)
+
+You can launch the model worker with quantized bits (4-bit, 8-bit), which allows you to run the inference with reduced GPU memory footprint, potentially allowing you to run on a GPU with as few as 12GB VRAM. Note that inference with quantized bits may not be as accurate as the full-precision model. Simply append `--load-4bit` or `--load-8bit` to the **model worker** command that you are executing. Below is an example of running with 4-bit quantization.
+
+```Shell
+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-v1.5-13b --load-4bit
+```
+
+#### Launch a model worker (LoRA weights, unmerged)
+
+You can launch the model worker with LoRA weights, without merging them with the base checkpoint, to save disk space. There will be additional loading time, while the inference speed is the same as the merged checkpoints. Unmerged LoRA checkpoints do not have `lora-merge` in the model name, and are usually much smaller (less than 1GB) than the merged checkpoints (13G for 7B, and 25G for 13B).
+
+To load unmerged LoRA weights, you simply need to pass an additional argument `--model-base`, which is the base LLM that is used to train the LoRA weights. You can check the base LLM of each LoRA weights in the [model zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md).
+
+```Shell
+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-v1-0719-336px-lora-vicuna-13b-v1.3 --model-base lmsys/vicuna-13b-v1.3
+```
+
+### CLI Inference
+
+Chat about images using LLaVA without the need of Gradio interface. It also supports multiple GPUs, 4-bit and 8-bit quantized inference. With 4-bit quantization, for our LLaVA-1.5-7B, it uses less than 8GB VRAM on a single GPU.
+
+```Shell
+python -m llava.serve.cli \
+ --model-path liuhaotian/llava-v1.5-7b \
+ --image-file "https://llava-vl.github.io/static/images/view.jpg" \
+ --load-4bit
+```
+
+
+
+## Train
+
+*Below is the latest training configuration for LLaVA v1.5. For legacy models, please refer to README of [this](https://github.com/haotian-liu/LLaVA/tree/v1.0.1) version for now. We'll add them in a separate doc later.*
+
+LLaVA training consists of two stages: (1) feature alignment stage: use our 558K subset of the LAION-CC-SBU dataset to connect a *frozen pretrained* vision encoder to a *frozen LLM*; (2) visual instruction tuning stage: use 150K GPT-generated multimodal instruction-following data, plus around 515K VQA data from academic-oriented tasks, to teach the model to follow multimodal instructions.
+
+LLaVA is trained on 8 A100 GPUs with 80GB memory. To train on fewer GPUs, you can reduce the `per_device_train_batch_size` and increase the `gradient_accumulation_steps` accordingly. Always keep the global batch size the same: `per_device_train_batch_size` x `gradient_accumulation_steps` x `num_gpus`.
+
+### Hyperparameters
+We use a similar set of hyperparameters as Vicuna in finetuning. Both hyperparameters used in pretraining and finetuning are provided below.
+
+1. Pretraining
+
+| Hyperparameter | Global Batch Size | Learning rate | Epochs | Max length | Weight decay |
+| --- | ---: | ---: | ---: | ---: | ---: |
+| LLaVA-v1.5-13B | 256 | 1e-3 | 1 | 2048 | 0 |
+
+2. Finetuning
+
+| Hyperparameter | Global Batch Size | Learning rate | Epochs | Max length | Weight decay |
+| --- | ---: | ---: | ---: | ---: | ---: |
+| LLaVA-v1.5-13B | 128 | 2e-5 | 1 | 2048 | 0 |
+
+### Download Vicuna checkpoints (automatically)
+
+Our base model Vicuna v1.5, which is an instruction-tuned chatbot, will be downloaded automatically when you run our provided training scripts. No action is needed.
+
+### Pretrain (feature alignment)
+
+Please download the 558K subset of the LAION-CC-SBU dataset with BLIP captions we use in the paper [here](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain).
+
+Pretrain takes around 5.5 hours for LLaVA-v1.5-13B on 8x A100 (80G), due to the increased resolution to 336px. It takes around 3.5 hours for LLaVA-v1.5-7B.
+
+Training script with DeepSpeed ZeRO-2: [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/pretrain.sh).
+
+- `--mm_projector_type mlp2x_gelu`: the two-layer MLP vision-language connector.
+- `--vision_tower openai/clip-vit-large-patch14-336`: CLIP ViT-L/14 336px.
+
+
+Pretrain takes around 20 hours for LLaVA-7B on 8x V100 (32G)
+
+ We provide training script with DeepSpeed [here](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain_xformers.sh).
+Tips:
+- If you are using V100 which is not supported by FlashAttention, you can use the [memory-efficient attention](https://arxiv.org/abs/2112.05682) implemented in [xFormers](https://github.com/facebookresearch/xformers). Install xformers and replace `llava/train/train_mem.py` above with [llava/train/train_xformers.py](llava/train/train_xformers.py).
+
+
+### Visual Instruction Tuning
+
+1. Prepare data
+
+Please download the annotation of the final mixture our instruction tuning data [llava_v1_5_mix665k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_v1_5_mix665k.json), and download the images from constituting datasets:
+
+- COCO: [train2017](http://images.cocodataset.org/zips/train2017.zip)
+- GQA: [images](https://downloads.cs.stanford.edu/nlp/data/gqa/images.zip)
+- OCR-VQA: [download script](https://drive.google.com/drive/folders/1_GYPY5UkUy7HIcR0zq3ZCFgeZN7BAfm_?usp=sharing), **we save all files as `.jpg`**
+- TextVQA: [train_val_images](https://dl.fbaipublicfiles.com/textvqa/images/train_val_images.zip)
+- VisualGenome: [part1](https://cs.stanford.edu/people/rak248/VG_100K_2/images.zip), [part2](https://cs.stanford.edu/people/rak248/VG_100K_2/images2.zip)
+
+After downloading all of them, organize the data as follows in `./playground/data`,
+
+```
+โโโ coco
+โ โโโ train2017
+โโโ gqa
+โ โโโ images
+โโโ ocr_vqa
+โ โโโ images
+โโโ textvqa
+โ โโโ train_images
+โโโ vg
+ โโโ VG_100K
+ โโโ VG_100K_2
+```
+
+2. Start training!
+
+You may download our pretrained projectors in [Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md). It is not recommended to use legacy projectors, as they may be trained with a different version of the codebase, and if any option is off, the model will not function/train as we expected.
+
+Visual instruction tuning takes around 20 hours for LLaVA-v1.5-13B on 8x A100 (80G), due to the increased resolution to 336px. It takes around 10 hours for LLaVA-v1.5-7B on 8x A100 (40G).
+
+Training script with DeepSpeed ZeRO-3: [`finetune.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/finetune.sh).
+
+If you are do not have enough GPU memory:
+
+- Use LoRA: [`finetune_lora.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/finetune_lora.sh). We are able to fit 13B training in 8-A100-40G/8-A6000, and 7B training in 8-RTX3090. Make sure `per_device_train_batch_size*gradient_accumulation_steps` is the same as the provided script for best reproducibility.
+- Replace `zero3.json` with `zero3_offload.json` which offloads some parameters to CPU RAM. This slows down the training speed.
+
+If you are interested in finetuning LLaVA model to your own task/data, please check out [`Finetune_Custom_Data.md`](https://github.com/haotian-liu/LLaVA/blob/main/docs/Finetune_Custom_Data.md)ใ
+
+New options to note:
+
+- `--mm_projector_type mlp2x_gelu`: the two-layer MLP vision-language connector.
+- `--vision_tower openai/clip-vit-large-patch14-336`: CLIP ViT-L/14 336px.
+- `--image_aspect_ratio pad`: this pads the non-square images to square, instead of cropping them; it slightly reduces hallucination.
+- `--group_by_modality_length True`: this should only be used when your instruction tuning dataset contains both language (e.g. ShareGPT) and multimodal (e.g. LLaVA-Instruct). It makes the training sampler only sample a single modality (either image or language) during training, which we observe to speed up training by ~25%, and does not affect the final outcome.
+
+## Evaluation
+
+In LLaVA-1.5, we evaluate models on a diverse set of 12 benchmarks. To ensure the reproducibility, we evaluate the models with greedy decoding. We do not evaluate using beam search to make the inference process consistent with the chat demo of real-time outputs.
+
+See [Evaluation.md](https://github.com/haotian-liu/LLaVA/blob/main/docs/Evaluation.md).
+
+### GPT-assisted Evaluation
+
+Our GPT-assisted evaluation pipeline for multimodal modeling is provided for a comprehensive understanding of the capabilities of vision-language models. Please see our paper for more details.
+
+1. Generate LLaVA responses
+
+```Shell
+python model_vqa.py \
+ --model-path ./checkpoints/LLaVA-13B-v0 \
+ --question-file \
+ playground/data/coco2014_val_qa_eval/qa90_questions.jsonl \
+ --image-folder \
+ /path/to/coco2014_val \
+ --answers-file \
+ /path/to/answer-file-our.jsonl
+```
+
+2. Evaluate the generated responses. In our case, [`answer-file-ref.jsonl`](./playground/data/coco2014_val_qa_eval/qa90_gpt4_answer.jsonl) is the response generated by text-only GPT-4 (0314), with the context captions/boxes provided.
+
+```Shell
+OPENAI_API_KEY="sk-***********************************" python llava/eval/eval_gpt_review_visual.py \
+ --question playground/data/coco2014_val_qa_eval/qa90_questions.jsonl \
+ --context llava/eval/table/caps_boxes_coco2014_val_80.jsonl \
+ --answer-list \
+ /path/to/answer-file-ref.jsonl \
+ /path/to/answer-file-our.jsonl \
+ --rule llava/eval/table/rule.json \
+ --output /path/to/review.json
+```
+
+3. Summarize the evaluation results
+
+```Shell
+python summarize_gpt_review.py
+```
+
+## Citation
+
+If you find LLaVA useful for your research and applications, please cite using this BibTeX:
+```bibtex
+@misc{liu2024llavanext,
+ title={LLaVA-NeXT: Improved reasoning, OCR, and world knowledge},
+ url={https://llava-vl.github.io/blog/2024-01-30-llava-next/},
+ author={Liu, Haotian and Li, Chunyuan and Li, Yuheng and Li, Bo and Zhang, Yuanhan and Shen, Sheng and Lee, Yong Jae},
+ month={January},
+ year={2024}
+}
+
+@misc{liu2023improvedllava,
+ title={Improved Baselines with Visual Instruction Tuning},
+ author={Liu, Haotian and Li, Chunyuan and Li, Yuheng and Lee, Yong Jae},
+ publisher={arXiv:2310.03744},
+ year={2023},
+}
+
+@misc{liu2023llava,
+ title={Visual Instruction Tuning},
+ author={Liu, Haotian and Li, Chunyuan and Wu, Qingyang and Lee, Yong Jae},
+ publisher={NeurIPS},
+ year={2023},
+}
+```
+
+## Acknowledgement
+
+- [Vicuna](https://github.com/lm-sys/FastChat): the codebase we built upon, and our base model Vicuna-13B that has the amazing language capabilities!
+
+## Related Projects
+
+- [Instruction Tuning with GPT-4](https://github.com/Instruction-Tuning-with-GPT-4/GPT-4-LLM)
+- [LLaVA-Med: Training a Large Language-and-Vision Assistant for Biomedicine in One Day](https://github.com/microsoft/LLaVA-Med)
+- [Otter: In-Context Multi-Modal Instruction Tuning](https://github.com/Luodian/Otter)
+
+For future project ideas, please check out:
+- [SEEM: Segment Everything Everywhere All at Once](https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once)
+- [Grounded-Segment-Anything](https://github.com/IDEA-Research/Grounded-Segment-Anything) to detect, segment, and generate anything by marrying [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO) and [Segment-Anything](https://github.com/facebookresearch/segment-anything).
diff --git a/alpha_clip_final/__init__.py b/alpha_clip_final/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..32d2651e37e77b32fea14c905871da815929c2ce
--- /dev/null
+++ b/alpha_clip_final/__init__.py
@@ -0,0 +1 @@
+from .alpha_clip_new import *
diff --git a/alpha_clip_final/alpha_clip_new.py b/alpha_clip_final/alpha_clip_new.py
new file mode 100644
index 0000000000000000000000000000000000000000..390ca179b0d27240e6884da45376c640ce7e564b
--- /dev/null
+++ b/alpha_clip_final/alpha_clip_new.py
@@ -0,0 +1,252 @@
+import hashlib
+import os
+import urllib
+import warnings
+from typing import Any, Union, List
+from pkg_resources import packaging
+
+import torch
+from PIL import Image
+from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
+from tqdm import tqdm
+
+from .model_new import build_model
+from .simple_tokenizer import SimpleTokenizer as _Tokenizer
+
+try:
+ from torchvision.transforms import InterpolationMode
+ BICUBIC = InterpolationMode.BICUBIC
+except ImportError:
+ BICUBIC = Image.BICUBIC
+
+
+if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"):
+ warnings.warn("PyTorch version 1.7.1 or higher is recommended")
+
+
+__all__ = ["available_models", "load", "tokenize"]
+_tokenizer = _Tokenizer()
+
+_MODELS = {
+ "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
+ "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
+ "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
+ "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
+ "RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
+ "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
+ "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
+ "ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
+ "ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
+}
+
+
+def _download(url: str, root: str):
+ os.makedirs(root, exist_ok=True)
+ filename = os.path.basename(url)
+
+ expected_sha256 = url.split("/")[-2]
+ download_target = os.path.join(root, filename)
+
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
+
+ if os.path.isfile(download_target):
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
+ return download_target
+ else:
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
+
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
+ with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop:
+ while True:
+ buffer = source.read(8192)
+ if not buffer:
+ break
+
+ output.write(buffer)
+ loop.update(len(buffer))
+
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
+ raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match")
+
+ return download_target
+
+
+def _convert_image_to_rgb(image):
+ return image.convert("RGB")
+
+
+def _transform(n_px):
+ return Compose([
+ Resize(n_px, interpolation=BICUBIC),
+ CenterCrop(n_px),
+ _convert_image_to_rgb,
+ ToTensor(),
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
+ ])
+
+
+def available_models() -> List[str]:
+ """Returns the names of available CLIP models"""
+ return list(_MODELS.keys())
+
+
+def load(name: str, alpha_vision_ckpt_pth="None", device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None, lora_adapt=False, rank=16):
+ """Load a CLIP model
+
+ Parameters
+ ----------
+ name : str
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
+
+ alpha_vision_ckpt_pth: str
+ only changed when inferencing model instead of training
+
+ device : Union[str, torch.device]
+ The device to put the loaded model
+
+ jit : bool
+ Whether to load the optimized JIT model or more hackable non-JIT model (default).
+
+ download_root: str
+ path to download the model files; by default, it uses "~/.cache/clip"
+
+ Returns
+ -------
+ model : torch.nn.Module
+ The CLIP model
+
+ preprocess : Callable[[PIL.Image], torch.Tensor]
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
+ """
+ if name in _MODELS:
+ model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip"))
+ elif os.path.isfile(name):
+ model_path = name
+ else:
+ raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
+
+ with open(model_path, 'rb') as opened_file:
+ try:
+ # loading JIT archive
+ model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
+ state_dict = None
+ except RuntimeError:
+ # loading saved state dict
+ if jit:
+ warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
+ jit = False
+ state_dict = torch.load(opened_file, map_location="cpu")
+
+ if not jit:
+ model, depth_model = build_model(state_dict or model.state_dict(), lora_adapt=lora_adapt, rank=rank)
+ model=model.to(device)
+ depth_model=depth_model.to(device)
+ if str(device) == "cpu":
+ model.float()
+ if alpha_vision_ckpt_pth != "None":
+ model.visual.load_state_dict(torch.load(alpha_vision_ckpt_pth))
+ model.eval() # merge lora params if exists (for inference only)
+ return model, _transform(model.visual.input_resolution), depth_model
+
+ # patch the device names
+ device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
+ device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
+
+ def _node_get(node: torch._C.Node, key: str):
+ """Gets attributes of a node which is polymorphic over return type.
+
+ From https://github.com/pytorch/pytorch/pull/82628
+ """
+ sel = node.kindOf(key)
+ return getattr(node, sel)(key)
+
+ def patch_device(module):
+ try:
+ graphs = [module.graph] if hasattr(module, "graph") else []
+ except RuntimeError:
+ graphs = []
+
+ if hasattr(module, "forward1"):
+ graphs.append(module.forward1.graph)
+
+ for graph in graphs:
+ for node in graph.findAllNodes("prim::Constant"):
+ if "value" in node.attributeNames() and str(_node_get(node, "value")).startswith("cuda"):
+ node.copyAttributes(device_node)
+
+ model.apply(patch_device)
+ patch_device(model.encode_image)
+ patch_device(model.encode_text)
+
+ # patch dtype to float32 on CPU
+ if str(device) == "cpu":
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
+ float_node = float_input.node()
+
+ def patch_float(module):
+ try:
+ graphs = [module.graph] if hasattr(module, "graph") else []
+ except RuntimeError:
+ graphs = []
+
+ if hasattr(module, "forward1"):
+ graphs.append(module.forward1.graph)
+
+ for graph in graphs:
+ for node in graph.findAllNodes("aten::to"):
+ inputs = list(node.inputs())
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
+ if _node_get(inputs[i].node(), "value") == 5:
+ inputs[i].node().copyAttributes(float_node)
+
+ model.apply(patch_float)
+ patch_float(model.encode_image)
+ patch_float(model.encode_text)
+
+ model.float()
+ return model, _transform(model.input_resolution.item())
+
+
+def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = True) -> Union[torch.IntTensor, torch.LongTensor]:
+ """
+ Returns the tokenized representation of given input string(s)
+
+ Parameters
+ ----------
+ texts : Union[str, List[str]]
+ An input string or a list of input strings to tokenize
+
+ context_length : int
+ The context length to use; all CLIP models use 77 as the context length
+
+ truncate: bool
+ Whether to truncate the text in case its encoding is longer than the context length
+
+ Returns
+ -------
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
+ We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
+ """
+ if isinstance(texts, str):
+ texts = [texts]
+
+ sot_token = _tokenizer.encoder["<|startoftext|>"]
+ eot_token = _tokenizer.encoder["<|endoftext|>"]
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"):
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
+ else:
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
+
+ for i, tokens in enumerate(all_tokens):
+ if len(tokens) > context_length:
+ if truncate:
+ tokens = tokens[:context_length]
+ tokens[-1] = eot_token
+ else:
+ raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
+ result[i, :len(tokens)] = torch.tensor(tokens)
+
+ return result
diff --git a/alpha_clip_final/bpe_simple_vocab_16e6.txt.gz b/alpha_clip_final/bpe_simple_vocab_16e6.txt.gz
new file mode 100644
index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113
--- /dev/null
+++ b/alpha_clip_final/bpe_simple_vocab_16e6.txt.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
+size 1356917
diff --git a/alpha_clip_final/model_new.py b/alpha_clip_final/model_new.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7cbf3d43d7b465562196d05ccbaddcc9b4583af
--- /dev/null
+++ b/alpha_clip_final/model_new.py
@@ -0,0 +1,1009 @@
+from collections import OrderedDict
+from typing import Tuple, Union
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from torch import nn
+import loralib as lora
+import math
+import collections
+import torch.nn.init as init
+# import spconv.pytorch as spconv
+import sys
+sys.path.append('/home/aiops/wangzh/llava')
+from depth_anything_v2.dpt import DepthAnythingV2
+
+class CPEconv(nn.Module):
+ def __init__(self, in_channels, spatial_shape, kernel_size=(3, 3, 3), padding=(1, 1, 1)):
+ super(CPEconv, self).__init__()
+ self.in_channels = in_channels
+ self.spatial_shape = 6
+ self.conv3d = nn.Conv3d(in_channels, in_channels, kernel_size=kernel_size, padding=padding,groups=in_channels)
+ nn.init.zeros_(self.conv3d.weight)
+ if self.conv3d.bias is not None:
+ nn.init.zeros_(self.conv3d.bias)
+
+ self.register_buffer('target_tensor_template', torch.zeros(1, in_channels, self.spatial_shape, 1, 1))
+
+ def generate_3d_coords_from_depth(self, depth_maps):
+ # ๅ่ฎพ depth_maps ๅฝข็ถไธบ (B, H, W)
+ B, H, W = depth_maps.shape
+ z_min = depth_maps.min(dim=-1, keepdim=True)[0].min(dim=-2, keepdim=True)[0] # (B, 1, 1)
+ z_max = depth_maps.max(dim=-1, keepdim=True)[0].max(dim=-2, keepdim=True)[0] # (B, 1, 1)
+ z = (depth_maps - z_min) / (z_max - z_min + 1e-8)
+ # z = depth_maps # z ๅๆ ไธบๆทฑๅบฆๅผ๏ผๅฝข็ถไธบ (B, H, W)
+
+ return z
+
+ def forward(self, features, depth):
+ #features [197,256,768] depth [256,14,14]
+ B,h,w=depth.shape
+ _,_,C=features.shape
+ D = self.spatial_shape
+ features = features[1:,:,:]
+ features = features.permute(1,0,2)
+ coord=self.generate_3d_coords_from_depth(depth)
+ bnd=self.spatial_shape - 1
+ coord = (coord *bnd).to(torch.int64)
+ coord = (
+ coord.clamp(0, bnd) # clamp into bnd
+ )
+ target_tensor = self.target_tensor_template.expand(B, C, D, h, w).clone()
+ # target_tensor = torch.zeros(B, C, D, h, w).to(device=features.device)
+ # return 0
+
+ coord = coord.unsqueeze(1).expand(-1, C, -1, -1) # [B, C, H, W]
+ # reshape features ไปฅไพฟไธ coord ่ฟ่กๆไฝ
+ features = features.view(B, h, w, C) # [B, H, W, C]
+ features = features.permute(0, 3, 1, 2) # [B, C, H, W]
+ features = features.unsqueeze(2).to(dtype=target_tensor.dtype)
+ coord = coord.unsqueeze(2)
+ # import pdb;pdb.set_trace()
+
+ # scatter features into target_tensor
+ target_tensor = target_tensor.scatter_(2, coord, features)
+ # 2. ไฝฟ็จ b ็ๅผไฝไธบไธๆ ๏ผๅฐ features ็ๅผๅคๅถๅฐ็ฎๆ ๅผ ้็็ธๅบไฝ็ฝฎ
+ # 3. ไฝฟ็จ for ๅพช็ฏๅฐ features ็ๅผๅคๅถๅฐ็ฎๆ ๅผ ้
+ # for i in range(B):
+ # for j in range(h):
+ # for k in range(w):
+ # # ่ทๅๅจ features ไธญ็็ดขๅผ
+ # index = coord[i, j, k] # ไป b ไธญ่ทๅ็ดขๅผ
+ # target_tensor[i, :,index, j, k] = features[i, j * 14 + k, :] # ๅคๅถๅฏนๅบ็ features ๅผ
+ output = self.conv3d(target_tensor).mean(dim=2) #(B,768,14,14)
+ output = output.reshape(-1,output.size(0),output.size(1))
+ cls_feat = torch.zeros(1,output.size(-2), output.size(-1)).to(device=output.device,dtype=output.dtype)
+ out_feat = torch.cat([cls_feat,output],dim=0)
+
+ return out_feat
+class RPE(torch.nn.Module):
+ def __init__(self, patch_num, num_heads):
+ super(RPE, self).__init__()
+ self.num_heads = num_heads
+ self.pos_bnd = patch_num
+ self.rpe_num = 2 * self.pos_bnd + 1
+ self.rpe_table = torch.nn.Parameter(torch.zeros(3 * self.rpe_num, num_heads))
+ # torch.nn.init.trunc_normal_(self.rpe_table, std=0.02)
+
+ def generate_3d_coords_from_depth(self,depth_maps):
+ # ๅ่ฎพ depth_maps ๅฝข็ถไธบ (B, H, W)
+ B, H, W = depth_maps.shape
+
+ # ็ๆ็ฝๆ ผ i, j๏ผๅฝข็ถไธบ (H, W)
+ i, j = torch.meshgrid(torch.arange(H, device=depth_maps.device), torch.arange(W, device=depth_maps.device), indexing='ij')
+
+ # ๅฝไธๅ x ๅ y ๅๆ
+ x = j.float() / (W - 1) # (H, W)
+ y = i.float() / (H - 1) # (H, W)
+
+ # ๅฐ x ๅ y ๆฉๅฑๅฐ (B, H, W) ไปฅๅน้ depth_maps
+ x = x.unsqueeze(0).expand(B, -1, -1) # (B, H, W)
+ y = y.unsqueeze(0).expand(B, -1, -1) # (B, H, W)
+
+ z_min = depth_maps.min(dim=-1, keepdim=True)[0].min(dim=-2, keepdim=True)[0] # (B, 1, 1)
+ z_max = depth_maps.max(dim=-1, keepdim=True)[0].max(dim=-2, keepdim=True)[0] # (B, 1, 1)
+ z = (depth_maps - z_min) / (z_max - z_min + 1e-8)
+ # z = depth_maps # z ๅๆ ไธบๆทฑๅบฆๅผ๏ผๅฝข็ถไธบ (B, H, W)
+
+ # ็ปๅๆ (B, H, W, 3) ็ไธ็ปดๅๆ
+ coords = torch.stack([x, y, z], dim=-1) # (B, H, W, 3)
+
+ return coords
+
+
+ def compute_relative_positions(self,absolute_coords):
+ """
+ ่ฎก็ฎ็ธๅฏนไฝ็ฝฎ็ผ็
+ ๅๆฐ:
+ absolute_coords: ๅฝข็ถไธบ (N, 3) ็็ปๅฏนไธ็ปดๅๆ ๅผ ้
+ ่ฟๅ:
+ ็ธๅฏนไฝ็ฝฎ็ผ็ ๏ผๅฝข็ถไธบ (N, N, 3)
+ """
+ # ็กฎไฟ่พๅ ฅๆฏไธไธชๅผ ้
+ if not isinstance(absolute_coords, torch.Tensor):
+ raise ValueError("Input must be a PyTorch tensor.")
+ N = absolute_coords.shape[1]
+ relative_positions = absolute_coords.unsqueeze(2) - absolute_coords.unsqueeze(1)
+
+ return relative_positions
+
+
+ def forward(self,depth):
+ # B,K,K,3
+ # import pdb;pdb.set_trace()
+
+ depth=self.generate_3d_coords_from_depth(depth)
+ depth=depth.reshape(depth.size(0),-1,depth.size(-1))
+ # zeros_tensor = torch.zeros(depth.size(0), 1, depth.size(-1))
+ # depth = torch.cat((zeros_tensor,depth), dim=1)
+ coord=self.compute_relative_positions(depth)
+ # ๅฐ coord ไป [0, 1] ่ๅด่ฝฌๆขไธบ [0, width] ๆ [0, height]
+ # coord = coord.reshape(coord.size(0),-1,coord.size(-1))
+ # import pdb;pdb.set_trace()
+ coord = (coord * torch.tensor([self.pos_bnd, self.pos_bnd, self.pos_bnd], device=coord.device)).round().long()
+ idx = (
+ coord.clamp(-self.pos_bnd, self.pos_bnd) # clamp into bnd
+ + self.pos_bnd # relative position to positive index
+ + torch.arange(3, device=coord.device) * self.rpe_num # x, y, z stride
+ )
+ out = self.rpe_table.index_select(0, idx.reshape(-1))
+ # out = out.reshape(coord.size(0) ,coord.size(1) ,coord.size(2) , -1)
+ out = out.view(idx.shape + (-1,)).sum(3)
+
+ out = out.permute(0, 3, 1, 2) # (N, K, K, H) -> (N, H, K, K)
+ # out_new=torch.zeros(out.size(0),out.size(1),out.size(2)+1,out.size(3)+1)
+ # out_new[:, :, 1:, 1:] = out
+ return out
+
+class PositionEmbeddingCoordsSine(nn.Module):
+ def __init__(
+ self,
+ temperature=10000,
+ normalize=False,
+ scale=None,
+ pos_type="fourier",
+ d_pos=None,
+ d_in=3,
+ gauss_scale=1.0,
+ ):
+ super().__init__()
+ self.temperature = temperature
+ self.normalize = normalize
+ if scale is not None and normalize is False:
+ raise ValueError("normalize should be True if scale is passed")
+ if scale is None:
+ scale = 2 * math.pi
+ assert pos_type in ["sine", "fourier"]
+ self.pos_type = pos_type
+ self.scale = scale
+ self.ln = LayerNorm(768)
+ if pos_type == "fourier":
+ assert d_pos is not None
+ assert d_pos % 2 == 0
+ # define a gaussian matrix input_ch -> output_ch
+ B = torch.empty((d_in, d_pos // 2)).normal_()
+ B *= gauss_scale
+ # self.gauss_B = nn.Parameter(B)
+ self.register_buffer("gauss_B", B)
+ self.d_pos = d_pos
+ self.trans3d=nn.Conv1d(in_channels=3, out_channels=768, kernel_size=1)
+ init.zeros_(self.trans3d.weight)
+ if self.trans3d.bias is not None:
+ init.zeros_(self.trans3d.bias)
+ def get_sine_embeddings(self, xyz, num_channels, input_range):
+ ncoords = xyz.shape[1]
+ ndim = num_channels // xyz.shape[2]
+ if ndim % 2 != 0:
+ ndim -= 1
+ # automatically handle remainder by assiging it to the first dim
+ rems = num_channels - (ndim * xyz.shape[2])
+
+ assert (
+ ndim % 2 == 0
+ ), f"Cannot handle odd sized ndim={ndim} where num_channels={num_channels} and xyz={xyz.shape}"
+
+ final_embeds = []
+ prev_dim = 0
+
+ for d in range(xyz.shape[2]):
+ cdim = ndim
+ if rems > 0:
+ # add remainder in increments of two to maintain even size
+ cdim += 2
+ rems -= 2
+
+ if cdim != prev_dim:
+ dim_t = torch.arange(cdim, dtype=torch.float32, device=xyz.device)
+ dim_t = self.temperature ** (2 * (dim_t // 2) / cdim)
+
+ # create batch x cdim x nccords embedding
+ raw_pos = xyz[:, :, d]
+ if self.scale:
+ raw_pos *= self.scale
+ pos = raw_pos[:, :, None] / dim_t
+ pos = torch.stack(
+ (pos[:, :, 0::2].sin(), pos[:, :, 1::2].cos()), dim=3
+ ).flatten(2)
+ final_embeds.append(pos)
+ prev_dim = cdim
+
+ final_embeds = torch.cat(final_embeds, dim=2)
+ return final_embeds
+ def get_fourier_embeddings(self, xyz, num_channels=None, input_range=None):
+ if num_channels is None:
+ num_channels = self.gauss_B.shape[1] * 2
+ bsize, npoints = xyz.shape[0], xyz.shape[1]
+ assert num_channels > 0 and num_channels % 2 == 0
+ d_in, max_d_out = self.gauss_B.shape[0], self.gauss_B.shape[1]
+ d_out = num_channels // 2
+ # assert d_out <= max_d_out
+ assert d_in == xyz.shape[-1]
+
+ # clone coords so that shift/scale operations do not affect original tensor
+ # import pdb;pdb.set_trace()
+ ncoords = xyz.shape[1]
+ if self.normalize:
+ # xyz = shift_scale_points(xyz, src_range=input_range)
+ pass
+
+ xyz *= 2 * torch.pi
+ xyz_proj = torch.mm(xyz.view(-1, d_in), self.gauss_B[:, :d_out]).view(
+ bsize, npoints, d_out
+ )
+ final_embeds = [xyz_proj.sin(), xyz_proj.cos()]
+
+ # return batch x d_pos x npoints embedding
+ final_embeds = torch.cat(final_embeds, dim=2)
+ # import pdb;pdb.set_trace()
+ # final_embeds = self.ln(final_embeds)
+ final_embeds = F.normalize(final_embeds, p=2, dim=2)
+
+ # If necessary, you can permute it back to [batch, 196, 768]
+ return final_embeds
+
+ def forward(self, depth_map, num_channels=None, input_range=None):
+ cam_coords_tensor = self.generate_3d_coords_from_depth(depth_map) # (B, H, W, 3)
+ # cam_coords_tensor = torch.tensor(cam_coords, dtype=torch.float16) # (B, H, W, 3)
+ cam_coords_tensor = cam_coords_tensor.view(cam_coords_tensor.size(0), -1, 3) # (B, H*W, 3)
+ xyz=cam_coords_tensor
+ # import pdb;pdb.set_trace()
+ assert xyz.ndim == 3
+ # xyz is batch x npoints x 3
+ if self.pos_type == "sine":
+ with torch.no_grad():
+ return self.get_sine_embeddings(xyz, 768, input_range)
+ elif self.pos_type == "fourier":
+ with torch.no_grad():
+ return self.get_fourier_embeddings(xyz, num_channels, input_range)
+ else:
+ raise ValueError(f"Unknown {self.pos_type}")
+
+ def positiontrans3d(self,depth_map):
+ cam_coords_tensor = self.generate_3d_coords_from_depth(depth_map) # (B, H, W, 3)
+ # cam_coords_tensor = torch.tensor(cam_coords, dtype=torch.float16) # (B, H, W, 3)
+ cam_coords_tensor = cam_coords_tensor.view(cam_coords_tensor.size(0), -1, 3) # (B, H*W, 3)
+ x=cam_coords_tensor
+ x = x.permute(0, 2, 1) # (B, H*W, 3) -> (B, 3, H*W)
+ x = self.trans3d(x) # 1Dๅท็งฏๆ ๅฐ (B, 768, H*W)
+ x = x.permute(0, 2, 1) # ่ฝฌๆขๅ (B, H*W, 768)
+ return x
+ def generate_3d_coords_from_depth(self, depth_maps):
+ # ๅ่ฎพ depth_maps ๅฝข็ถไธบ (B, H, W)
+ B, H, W = depth_maps.shape
+
+ # ็ๆ็ฝๆ ผ i, j๏ผๅฝข็ถไธบ (H, W)
+ i, j = torch.meshgrid(torch.arange(H, device=depth_maps.device), torch.arange(W, device=depth_maps.device), indexing='ij')
+
+ # ๅฝไธๅ x ๅ y ๅๆ
+ x = j.float() / (W - 1) # (H, W)
+ y = i.float() / (H - 1) # (H, W)
+
+ # ๅฐ x ๅ y ๆฉๅฑๅฐ (B, H, W) ไปฅๅน้ depth_maps
+ x = x.unsqueeze(0).expand(B, -1, -1) # (B, H, W)
+ y = y.unsqueeze(0).expand(B, -1, -1) # (B, H, W)
+
+ z = depth_maps # z ๅๆ ไธบๆทฑๅบฆๅผ๏ผๅฝข็ถไธบ (B, H, W)
+
+ # ็ปๅๆ (B, H, W, 3) ็ไธ็ปดๅๆ
+ coords = torch.stack([x, y, z], dim=-1) # (B, H, W, 3)
+
+ return coords
+
+
+class Bottleneck(nn.Module):
+ expansion = 4
+
+ def __init__(self, inplanes, planes, stride=1):
+ super().__init__()
+
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
+ self.bn1 = nn.BatchNorm2d(planes)
+ self.relu1 = nn.ReLU(inplace=True)
+
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
+ self.bn2 = nn.BatchNorm2d(planes)
+ self.relu2 = nn.ReLU(inplace=True)
+
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
+
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
+ self.relu3 = nn.ReLU(inplace=True)
+
+ self.downsample = None
+ self.stride = stride
+
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
+ self.downsample = nn.Sequential(OrderedDict([
+ ("-1", nn.AvgPool2d(stride)),
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
+ ("1", nn.BatchNorm2d(planes * self.expansion))
+ ]))
+
+ def forward(self, x: torch.Tensor):
+ identity = x
+
+ out = self.relu1(self.bn1(self.conv1(x)))
+ out = self.relu2(self.bn2(self.conv2(out)))
+ out = self.avgpool(out)
+ out = self.bn3(self.conv3(out))
+
+ if self.downsample is not None:
+ identity = self.downsample(x)
+
+ out += identity
+ out = self.relu3(out)
+ return out
+
+
+class AttentionPool2d(nn.Module):
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
+ super().__init__()
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
+ self.num_heads = num_heads
+
+ def forward(self, x):
+ x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
+ x, _ = F.multi_head_attention_forward(
+ query=x[:1], key=x, value=x,
+ embed_dim_to_check=x.shape[-1],
+ num_heads=self.num_heads,
+ q_proj_weight=self.q_proj.weight,
+ k_proj_weight=self.k_proj.weight,
+ v_proj_weight=self.v_proj.weight,
+ in_proj_weight=None,
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
+ bias_k=None,
+ bias_v=None,
+ add_zero_attn=False,
+ dropout_p=0,
+ out_proj_weight=self.c_proj.weight,
+ out_proj_bias=self.c_proj.bias,
+ use_separate_proj_weight=True,
+ training=self.training,
+ need_weights=False
+ )
+ return x.squeeze(0)
+
+
+class ModifiedResNet(nn.Module):
+ """
+ A ResNet class that is similar to torchvision's but contains the following changes:
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
+ - The final pooling layer is a QKV attention instead of an average pool
+ """
+
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
+ super().__init__()
+ self.output_dim = output_dim
+ self.input_resolution = input_resolution
+
+ # the 3-layer stem
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
+ self.conv1_alpha = nn.Conv2d(in_channels=1, out_channels=width // 2, kernel_size=3, stride=2, padding=1, bias=False)
+ self.bn1 = nn.BatchNorm2d(width // 2)
+ self.relu1 = nn.ReLU(inplace=True)
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
+ self.bn2 = nn.BatchNorm2d(width // 2)
+ self.relu2 = nn.ReLU(inplace=True)
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
+ self.bn3 = nn.BatchNorm2d(width)
+ self.relu3 = nn.ReLU(inplace=True)
+ self.avgpool = nn.AvgPool2d(2)
+
+ # residual layers
+ self._inplanes = width # this is a *mutable* variable used during construction
+ self.layer1 = self._make_layer(width, layers[0])
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
+
+ embed_dim = width * 32 # the ResNet feature dimension
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
+
+ def _make_layer(self, planes, blocks, stride=1):
+ layers = [Bottleneck(self._inplanes, planes, stride)]
+
+ self._inplanes = planes * Bottleneck.expansion
+ for _ in range(1, blocks):
+ layers.append(Bottleneck(self._inplanes, planes))
+
+ return nn.Sequential(*layers)
+
+ def forward(self, x, alpha=None):
+ def stem(x):
+ x = self.relu1(self.bn1(self.conv1(x) + self.conv1_alpha(alpha)))
+ x = self.relu2(self.bn2(self.conv2(x)))
+ x = self.relu3(self.bn3(self.conv3(x)))
+ x = self.avgpool(x)
+ return x
+
+ x = x.type(self.conv1.weight.dtype)
+ x = stem(x)
+ x = self.layer1(x)
+ x = self.layer2(x)
+ x = self.layer3(x)
+ x = self.layer4(x)
+ x = self.attnpool(x)
+
+ return x
+
+
+class LayerNorm(nn.LayerNorm):
+ """Subclass torch's LayerNorm to handle fp16."""
+
+ def forward(self, x: torch.Tensor):
+ orig_type = x.dtype
+ # ret = super().forward(x.type(torch.float32))
+ ret = super().forward(x)
+ return ret.type(orig_type)
+
+
+class QuickGELU(nn.Module):
+ def forward(self, x: torch.Tensor):
+ return x * torch.sigmoid(1.702 * x)
+
+class Attention(nn.Module):
+ def __init__(
+ self,
+ dim,
+ num_heads=8,
+ qkv_bias=True,
+ scaled_cosine=False,
+ scale_heads=False,
+ logit_scale_max=math.log(1. / 0.01),
+ attn_drop=0.,
+ proj_drop=0.,
+ lora_adapt=False,
+ rank=16,
+ patch_num=16
+ ):
+ super().__init__()
+ self.scaled_cosine = scaled_cosine
+ self.scale_heads = scale_heads
+ assert dim % num_heads == 0, 'dim should be divisible by num_heads'
+ self.num_heads = num_heads
+ self.head_dim = dim // num_heads
+ self.scale = self.head_dim ** -0.5
+ self.logit_scale_max = logit_scale_max
+ self.use_rel_pos = True # ไฟๅญ็ธๅฏนไฝ็ฝฎ็ผ็ ็ไฝฟ็จ็ถๆ
+ self.rpe = RPE(patch_num=patch_num,num_heads=self.num_heads)
+ self.rpe.requires_grad=True
+ # import pdb;pdb.set_trace()
+ # keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original
+ if lora_adapt:
+ print("!!!!!!!!!!using lora for qkv projection!!!!!!!!!!")
+ self.in_proj = lora.MergedLinear(dim, 3*dim, r=rank, enable_lora=[True, False, True])
+ else:
+ self.in_proj = nn.Linear(dim, dim * 3)
+ # self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale)
+ # if qkv_bias:
+ # self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3))
+ # else:
+ # self.in_proj_bias = None
+
+ if self.scaled_cosine:
+ self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))))
+ else:
+ self.logit_scale = None
+ self.attn_drop = nn.Dropout(attn_drop)
+ if self.scale_heads:
+ self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1)))
+ else:
+ self.head_scale = None
+ self.out_proj = nn.Linear(dim, dim) if not lora_adapt else lora.Linear(dim, dim, r=rank)
+ self.out_drop = nn.Dropout(proj_drop)
+
+ def forward(self, x, attn_mask = None,depth=None):
+ L, N, C = x.shape
+ q, k, v = self.in_proj(x).chunk(3, dim=-1)
+ q = q.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
+ k = k.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
+ v = v.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
+
+ if self.logit_scale is not None:
+ attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2))
+ logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp()
+ attn = attn.view(N, self.num_heads, L, L) * logit_scale
+ attn = attn.view(-1, L, L)
+ else:
+ q = q * self.scale
+ attn = torch.bmm(q, k.transpose(-2, -1))
+
+ if depth is not None:
+ depth=depth.squeeze(1)
+ res= self.rpe(depth)
+ res=res.reshape(-1,res.size(-2),res.size(-1))
+ # import pdb;pdb.set_trace()
+ attn[:,1:,1:]=attn[:,1:,1:]+res
+
+ if attn_mask is not None:
+ if attn_mask.dtype == torch.bool:
+ new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype)
+ new_attn_mask.masked_fill_(attn_mask, float("-inf"))
+ attn_mask = new_attn_mask
+ attn += attn_mask
+
+ attn = attn.softmax(dim=-1)
+ attn = self.attn_drop(attn)
+
+ x = torch.bmm(attn, v)
+ if self.head_scale is not None:
+ x = x.view(N, self.num_heads, L, C) * self.head_scale
+ x = x.view(-1, L, C)
+ x = x.transpose(0, 1).reshape(L, N, C)
+ x = self.out_proj(x)
+ x = self.out_drop(x)
+ return x, attn
+
+
+class CustomResidualAttentionBlock(nn.Module):
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None, lora_adapt=False, rank=16,patch_num=16):
+ super().__init__()
+
+ self.attn = Attention(d_model, n_head, lora_adapt=lora_adapt, rank=rank,patch_num=patch_num)
+ self.ln_1 = LayerNorm(d_model)
+ self.mlp = nn.Sequential(OrderedDict([
+ ("c_fc", nn.Linear(d_model, d_model * 4) if not lora_adapt else lora.Linear(d_model, d_model*4, r=rank)),
+ ("gelu", QuickGELU()),
+ ("c_proj", nn.Linear(d_model * 4, d_model) if not lora_adapt else lora.Linear(d_model*4, d_model, r=rank))
+ ]))
+ self.ln_2 = LayerNorm(d_model)
+ self.ln_cpe = LayerNorm(d_model)
+ self.attn_mask = attn_mask
+ self.cpe=CPEconv(d_model,patch_num)
+
+
+ def attention(self, x: torch.Tensor,depth=None):
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
+ return self.attn(x, attn_mask=self.attn_mask,depth=depth)
+
+
+ def forward(self, x: torch.Tensor, return_attn=False,depth=None):
+ # import pdb;pdb.set_trace()
+ # x ([577, 50, 1024])
+ # if None:
+ shortcut=x
+ # import pdb;pdb.set_trace()
+ # shapes=x.shape
+ # x= x.reshape(-1,x.size(-1))
+ # import pdb;pdb.set_trace()
+ # cposi = self.cpe(x, depth).reshape(shapes)
+ cposi = self.cpe(self.ln_cpe(x), depth)
+ x =shortcut+cposi
+
+ attn_out, attn = self.attention(self.ln_1(x),depth)
+ x = x + attn_out
+ x = x + self.mlp(self.ln_2(x))
+ if return_attn:
+ return x, attn
+ else:
+ return x
+
+class ResidualAttentionBlock(nn.Module):
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
+ super().__init__()
+
+ self.attn = nn.MultiheadAttention(d_model, n_head)
+ self.ln_1 = LayerNorm(d_model)
+ self.mlp = nn.Sequential(OrderedDict([
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
+ ("gelu", QuickGELU()),
+ ("c_proj", nn.Linear(d_model * 4, d_model))
+ ]))
+ self.ln_2 = LayerNorm(d_model)
+ self.attn_mask = attn_mask
+
+ def attention(self, x: torch.Tensor):
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
+ return self.attn(x, x, x, attn_mask=self.attn_mask)[0]
+
+ def forward(self, x: torch.Tensor):
+ x = x + self.attention(self.ln_1(x))
+ x = x + self.mlp(self.ln_2(x))
+ return x
+
+class Transformer(nn.Module):
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
+ super().__init__()
+ self.width = width
+ self.layers = layers
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
+
+ def forward(self, x: torch.Tensor):
+ return self.resblocks(x)
+
+class CustomTransformer(nn.Module):
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None, lora_adapt=False, rank=16,patch_num=16):
+ super().__init__()
+ self.width = width
+ self.layers = layers
+ self.resblocks = nn.Sequential(*[CustomResidualAttentionBlock(width, heads, attn_mask, lora_adapt=lora_adapt, rank=rank,patch_num=patch_num) for _ in range(layers)])
+
+ def forward(self, x: torch.Tensor, return_attn=False,depth=None):
+ # import pdb;pdb.set_trace()
+ if return_attn:
+ for i, block in enumerate(self.resblocks):
+ if i == len(self.resblocks) - 1:
+ return block(x, return_attn=True,depth=depth)
+ else:
+ x = block(x,depth=depth)
+ assert False
+ for block in self.resblocks:
+ # import pdb;pdb.set_trace()
+ x = block(x, depth=depth) # ๅฐ depth ไผ ้็ปๆฏไธชๆจกๅ
+ return x
+ # return self.resblocks(x)
+
+# ////////////////////////////////////////////////////////////////////////////////////////////
+class VisionTransformer(nn.Module):
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int, lora_adapt=False, rank=16):
+ super().__init__()
+ self.input_resolution = input_resolution
+ self.output_dim = output_dim
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
+ self.conv1_alpha = nn.Conv2d(in_channels=1, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
+ nn.init.zeros_(self.conv1_alpha.weight)
+ scale = width ** -0.5
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
+ # self.depth_positional_embedding = nn.Parameter(scale * torch.zeros((input_resolution // patch_size) ** 2, width)) # ็จไบalpha็ๆทฑๅบฆ็ผ็
+ # self.depth_positional_embedding = PositionEmbeddingCoordsSine(temperature=10000,
+ # normalize=True,
+ # scale=2 * torch.pi,
+ # pos_type="fourier",
+ # d_pos=768, # ็คบไพ่พๅบ็ปดๅบฆ
+ # d_in=3,
+ # gauss_scale=1.0
+ # )
+ # self.sine_positional_embedding = PositionEmbeddingCoordsSine(temperature=10000,
+ # normalize=True,
+ # scale=2 * torch.pi,
+ # pos_type="sine",
+ # d_pos=768, # ็คบไพ่พๅบ็ปดๅบฆ
+ # d_in=3,
+ # gauss_scale=1.0
+ # )
+ # self.large_positional_embedding = PositionEmbeddingCoordsSine(temperature=10000,
+ # normalize=True,
+ # scale=2 * torch.pi,
+ # pos_type="sine",
+ # d_pos=1024, # ็คบไพ่พๅบ็ปดๅบฆ
+ # d_in=3,
+ # gauss_scale=1.0
+ # )
+ # self.depth_mlp=nn.Linear(768,768)
+ # nn.init.zeros_(self.depth_mlp.weight)
+ # if self.depth_mlp.bias is not None:
+ # nn.init.zeros_(self.depth_mlp.bias)
+ self.patch_size=patch_size
+
+ self.ln_pre = LayerNorm(width)
+ self.transformer = CustomTransformer(width, layers, heads, lora_adapt=lora_adapt, rank=rank,patch_num=input_resolution // patch_size)
+
+ self.ln_post = LayerNorm(width)
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
+
+ def forward(self, x: torch.Tensor, alpha=None, return_attn=False,pos_embed=None):
+ # import pdb;pdb.set_trace()
+ x = self.conv1(x) # shape = [*, width, grid, grid]
+ # ASSUME alpha is always not None!
+ # import pdb;pdb.set_trace()
+ # if pos_embed == "nodepth":
+ # pass
+ # else:
+ # x = x + self.conv1_alpha(alpha)
+ # import pdb;pdb.set_trace()
+
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
+ x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
+ # import pdb;pdb.set_trace()
+ alpha_resized = F.adaptive_avg_pool2d(alpha, (self.input_resolution // self.patch_size, self.input_resolution // self.patch_size))
+ # alpha_flattened = alpha_resized.flatten(start_dim=2).permute(0, 2, 1)
+ alpha_resized = alpha_resized.squeeze(1)
+ # x[:, 1:] += self.depth_positional_embedding.to(x.dtype) * alpha_flattened
+ # import pdb;pdb.set_trace()
+ # if pos_embed == "fourier":
+ # depth_embedding = self.depth_positional_embedding(alpha_resized)
+ # x[:, 1:] +=self.depth_mlp(depth_embedding)
+ # elif pos_embed == "sine":
+ # depth_embedding = self.sine_positional_embedding(alpha_resized)
+ # x[:, 1:] +=self.depth_mlp(depth_embedding)
+ # elif pos_embed == "3d":
+ # depth_embedding = self.depth_positional_embedding.positiontrans3d(alpha_resized)
+ # x[:, 1:] +=self.depth_mlp(depth_embedding)
+
+ x = x + self.positional_embedding.to(x.dtype)
+ x = self.ln_pre(x)
+ # import pdb;pdb.set_trace()
+ x = x.permute(1, 0, 2) # NLD -> LND
+ if return_attn:
+ x, attn_last = self.transformer(x, return_attn=True,depth=alpha_resized)
+ else:
+ x = self.transformer(x, return_attn=False,depth=alpha_resized)
+ x = x.permute(1, 0, 2) # LND -> NLD
+
+ # x = self.ln_post(x[:, 0, :])
+ x = self.ln_post(x)
+ # if self.proj is not None:
+ # x = x @ self.proj
+ if return_attn:
+ return x, attn_last
+ else:
+ return x
+# /////////////////////////////////////////////////////////////////////////////////////////////////////
+
+class CLIP(nn.Module):
+ def __init__(self,
+ embed_dim: int,
+ # vision
+ image_resolution: int,
+ vision_layers: Union[Tuple[int, int, int, int], int],
+ vision_width: int,
+ vision_patch_size: int,
+ # text
+ context_length: int,
+ vocab_size: int,
+ transformer_width: int,
+ transformer_heads: int,
+ transformer_layers: int,
+ lora_adapt = False,
+ rank = 16,
+ ):
+ super().__init__()
+
+ self.context_length = context_length
+
+ if isinstance(vision_layers, (tuple, list)):
+ vision_heads = vision_width * 32 // 64
+ self.visual = ModifiedResNet(
+ layers=vision_layers,
+ output_dim=embed_dim,
+ heads=vision_heads,
+ input_resolution=image_resolution,
+ width=vision_width
+ )
+ else:
+ vision_heads = vision_width // 64
+ self.visual = VisionTransformer(
+ input_resolution=image_resolution,
+ patch_size=vision_patch_size,
+ width=vision_width,
+ layers=vision_layers,
+ heads=vision_heads,
+ output_dim=embed_dim,
+ lora_adapt=lora_adapt,
+ rank=rank
+ )
+
+ self.transformer = Transformer(
+ width=transformer_width,
+ layers=transformer_layers,
+ heads=transformer_heads,
+ attn_mask=self.build_attention_mask()
+ )
+
+ self.vocab_size = vocab_size
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
+ self.ln_final = LayerNorm(transformer_width)
+ self.hidden_size = vision_width
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
+
+ self.initialize_parameters()
+
+ def initialize_parameters(self):
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
+ nn.init.normal_(self.positional_embedding, std=0.01)
+
+ if isinstance(self.visual, ModifiedResNet):
+ if self.visual.attnpool is not None:
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
+
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
+ for name, param in resnet_block.named_parameters():
+ if name.endswith("bn3.weight"):
+ nn.init.zeros_(param)
+
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
+ attn_std = self.transformer.width ** -0.5
+ fc_std = (2 * self.transformer.width) ** -0.5
+ for block in self.transformer.resblocks:
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
+
+ if self.text_projection is not None:
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
+
+ def build_attention_mask(self):
+ # lazily create causal attention mask, with full attention between the vision tokens
+ # pytorch uses additive attention mask; fill with -inf
+ mask = torch.empty(self.context_length, self.context_length)
+ mask.fill_(float("-inf"))
+ mask.triu_(1) # zero out the lower diagonal
+ return mask
+
+ @property
+ def dtype(self):
+ if not hasattr(self.visual, "conv1"):
+ return self.visual.module.conv1.weight.dtype
+ return self.visual.conv1.weight.dtype
+ @property
+ def device(self):
+ return torch.device("cuda")
+
+ def encode_image(self, image, alpha):
+ assert alpha is not None
+ return self.visual(image.type(self.dtype), alpha.type(self.dtype))
+
+ def encode_text(self, text):
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
+
+ x = x + self.positional_embedding.type(self.dtype)
+ x = x.permute(1, 0, 2) # NLD -> LND
+ x = self.transformer(x)
+ x = x.permute(1, 0, 2) # LND -> NLD
+ x = self.ln_final(x).type(self.dtype)
+
+ # x.shape = [batch_size, n_ctx, transformer.width]
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
+
+ return x
+
+ def our_encode_image(self,image, depth):
+ # import pdb;pdb.set_trace()
+ image_feature = self.visual(image, depth)
+ # 32. 577 . 768
+ return image_feature
+
+
+ def forward(self, image, text, alpha):
+ image_features = self.encode_image(image, alpha)
+ text_features = self.encode_text(text)
+
+ # normalized features
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
+
+ # cosine similarity as logits
+ logit_scale = self.logit_scale.exp()
+ logits_per_image = logit_scale * image_features @ text_features.t()
+ logits_per_text = logits_per_image.t()
+
+ # shape = [global_batch_size, global_batch_size]
+ return logits_per_image, logits_per_text
+
+
+def convert_weights(model: nn.Module):
+ """Convert applicable model parameters to fp16"""
+
+ def _convert_weights_to_fp16(l):
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
+ l.weight.data = l.weight.data.half()
+ if l.bias is not None:
+ l.bias.data = l.bias.data.half()
+
+ if isinstance(l, nn.MultiheadAttention):
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
+ tensor = getattr(l, attr)
+ if tensor is not None:
+ tensor.data = tensor.data.half()
+
+ for name in ["text_projection", "proj"]:
+ if hasattr(l, name):
+ attr = getattr(l, name)
+ if attr is not None:
+ attr.data = attr.data.half()
+
+ model.apply(_convert_weights_to_fp16)
+
+
+def build_model(state_dict: dict, lora_adapt=False, rank=16):
+ vit = "visual.proj" in state_dict
+
+ if vit:
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
+ image_resolution = vision_patch_size * grid_size
+ else:
+ counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
+ vision_layers = tuple(counts)
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
+ vision_patch_size = None
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
+ image_resolution = output_width * 32
+
+ embed_dim = state_dict["text_projection"].shape[1]
+ context_length = state_dict["positional_embedding"].shape[0]
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
+ transformer_width = state_dict["ln_final.weight"].shape[0]
+ transformer_heads = transformer_width // 64
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
+
+ # always load lora version
+ model = CLIP(
+ embed_dim,
+ image_resolution, vision_layers, vision_width, vision_patch_size,
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers,
+ lora_adapt=lora_adapt, rank=rank,
+ )
+
+ model_configs = {
+ 'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384]},
+ 'vitb': {'encoder': 'vitb', 'features': 128, 'out_channels': [96, 192, 384, 768]},
+ 'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]},
+ 'vitg': {'encoder': 'vitg', 'features': 384, 'out_channels': [1536, 1536, 1536, 1536]}
+ }
+ encoder = 'vitb'
+
+ depth_model=DepthAnythingV2(**model_configs[encoder])
+ depth_model.load_state_dict(torch.load(f'/home/aiops/wangzh/zss/Depth-Anything-V2/checkpoints/depth_anything_v2_{encoder}.pth', map_location='cpu'))
+
+
+ for key in ["input_resolution", "context_length", "vocab_size"]:
+ if key in state_dict:
+ del state_dict[key]
+ # para_wb to linear
+ new_state_dict = collections.OrderedDict()
+ for k, v in state_dict.items():
+ if 'visual' in k:
+ if 'in_proj_weight' in k:
+ new_state_dict[k.replace('in_proj_weight', 'in_proj.weight')] = v
+ elif 'in_proj_bias' in k:
+ new_state_dict[k.replace('in_proj_bias', 'in_proj.bias')] = v
+ else:
+ new_state_dict[k] = v
+ else:
+ new_state_dict[k] = v
+
+ state_dict = new_state_dict
+ # add rgba_conv_weight
+ if 'visual.conv1_alpha.weight' not in state_dict.keys(): # zero initialization on alpha channel
+ rgb_weight = state_dict['visual.conv1.weight'].clone().detach()
+ rgba_weigth = torch.zeros_like(rgb_weight)[:, 0:1, :, :]
+ state_dict['visual.conv1_alpha.weight'] = rgba_weigth
+ convert_weights(model)
+ model.load_state_dict(state_dict, strict=False)
+ return model.eval(), depth_model
diff --git a/alpha_clip_final/simple_tokenizer.py b/alpha_clip_final/simple_tokenizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a66286b7d5019c6e221932a813768038f839c91
--- /dev/null
+++ b/alpha_clip_final/simple_tokenizer.py
@@ -0,0 +1,132 @@
+import gzip
+import html
+import os
+from functools import lru_cache
+
+import ftfy
+import regex as re
+
+
+@lru_cache()
+def default_bpe():
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
+
+
+@lru_cache()
+def bytes_to_unicode():
+ """
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
+ The reversible bpe codes work on unicode strings.
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
+ """
+ bs = list(range(ord("!"), ord("~")+1))+list(range(ord("ยก"), ord("ยฌ")+1))+list(range(ord("ยฎ"), ord("รฟ")+1))
+ cs = bs[:]
+ n = 0
+ for b in range(2**8):
+ if b not in bs:
+ bs.append(b)
+ cs.append(2**8+n)
+ n += 1
+ cs = [chr(n) for n in cs]
+ return dict(zip(bs, cs))
+
+
+def get_pairs(word):
+ """Return set of symbol pairs in a word.
+ Word is represented as tuple of symbols (symbols being variable-length strings).
+ """
+ pairs = set()
+ prev_char = word[0]
+ for char in word[1:]:
+ pairs.add((prev_char, char))
+ prev_char = char
+ return pairs
+
+
+def basic_clean(text):
+ text = ftfy.fix_text(text)
+ text = html.unescape(html.unescape(text))
+ return text.strip()
+
+
+def whitespace_clean(text):
+ text = re.sub(r'\s+', ' ', text)
+ text = text.strip()
+ return text
+
+
+class SimpleTokenizer(object):
+ def __init__(self, bpe_path: str = default_bpe()):
+ self.byte_encoder = bytes_to_unicode()
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
+ merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
+ merges = merges[1:49152-256-2+1]
+ merges = [tuple(merge.split()) for merge in merges]
+ vocab = list(bytes_to_unicode().values())
+ vocab = vocab + [v+'' for v in vocab]
+ for merge in merges:
+ vocab.append(''.join(merge))
+ vocab.extend(['<|startoftext|>', '<|endoftext|>'])
+ self.encoder = dict(zip(vocab, range(len(vocab))))
+ self.decoder = {v: k for k, v in self.encoder.items()}
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
+ self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
+ self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
+
+ def bpe(self, token):
+ if token in self.cache:
+ return self.cache[token]
+ word = tuple(token[:-1]) + ( token[-1] + '',)
+ pairs = get_pairs(word)
+
+ if not pairs:
+ return token+''
+
+ while True:
+ bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
+ if bigram not in self.bpe_ranks:
+ break
+ first, second = bigram
+ new_word = []
+ i = 0
+ while i < len(word):
+ try:
+ j = word.index(first, i)
+ new_word.extend(word[i:j])
+ i = j
+ except:
+ new_word.extend(word[i:])
+ break
+
+ if word[i] == first and i < len(word)-1 and word[i+1] == second:
+ new_word.append(first+second)
+ i += 2
+ else:
+ new_word.append(word[i])
+ i += 1
+ new_word = tuple(new_word)
+ word = new_word
+ if len(word) == 1:
+ break
+ else:
+ pairs = get_pairs(word)
+ word = ' '.join(word)
+ self.cache[token] = word
+ return word
+
+ def encode(self, text):
+ bpe_tokens = []
+ text = whitespace_clean(basic_clean(text)).lower()
+ for token in re.findall(self.pat, text):
+ token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
+ bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
+ return bpe_tokens
+
+ def decode(self, tokens):
+ text = ''.join([self.decoder[token] for token in tokens])
+ text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('', ' ')
+ return text
diff --git a/answer_check.py b/answer_check.py
new file mode 100644
index 0000000000000000000000000000000000000000..337a005ccbcd6cde9fbefb4a65f02764179a26a4
--- /dev/null
+++ b/answer_check.py
@@ -0,0 +1,157 @@
+
+import json
+
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/annotations.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Counting/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Relative_Depth/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Spatial_Relation/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-13b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Visual_Correspondence/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-13b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Multi-view_Reasoning/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Object_Localization/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-13b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Jigsaw/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/CV-Bench/test3d-depth.jsonl', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/CV-Bench/test-count.jsonl', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+
+#
+# with open('/home/aiops/wangzh/data/blink/BLINK/Spatial_Relation/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/all.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/all.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/gpt4o-outdoor.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor-new/all.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/gemini-indoor.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor-new/all.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/gemini-indoor.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/realworldqa/updated.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/object_orientation.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/relative_depth.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/relative_size.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/relative_spatial_position.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+with open('/home/aiops/wangzh/data/scanner/indoor-new/all.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/orientation.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/relative_depth.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/relative_size.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/spatial_relation.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+
+ reader1 = json.load(reader1)
+
+ correct = 0
+ total = 0
+ for index, (line1, line2) in enumerate(zip(reader1, reader2), 1):
+ total += 1
+
+ answer = line2.strip()
+ ground_truth = line1['answer']
+ # ground_truth = json.loads(line1.strip())['answer']
+ # length = len(ground_truth)
+ flag = False
+ # choices = json.loads(line1.strip())['choices']
+
+ # if ground_truth in answer:
+ # correct += 1
+ # import pdb;pdb.set_trace()
+ # if ('A' in answer) and ('B' in answer) and ('C' in answer) and ('D' in answer):
+ # print('missed',index)
+ # continue
+ # if ground_truth == '(A)':
+ # if 'left' in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(B)':
+ # if 'right' in answer:
+ # correct += 1
+ # print("yes",index)
+ # if ground_truth == '(A)':
+ # if 'second' in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(B)':
+ # if 'third' in answer:
+ # correct += 1
+ # print("yes",index)
+ # count_sed = answer.count('sed')
+ # count_tird = answer.count('tird')
+ if ground_truth == 0:
+ if ('A' in answer) :
+ correct += 1
+ print("yes",index)
+
+ elif ground_truth == 1:
+ if ('B' in answer) :
+ correct += 1
+ print("yes",index)
+
+
+ elif ground_truth == 2:
+ if ('C' in answer) :
+ correct += 1
+ print("yes",index)
+
+
+ elif ground_truth == 3:
+ if ('D' in answer) :
+ correct += 1
+ print("yes",index)
+ # if ground_truth == answer:
+ # correct += 1
+ # print("yes",index)
+
+ # if ground_truth == '(A)':
+ # if 'A' in answer :
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(B)':
+ # if 'B' in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(C)':
+ # if 'C' in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(D)':
+ # if 'D' in answer:
+ # correct += 1
+ # print("yes",index)
+ # if ground_truth == '(A)':
+ # if choices[2] in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(B)':
+ # if choices[6] in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(C)':
+ # if choices[10] in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(D)':
+ # if choices[14] in answer:
+ # correct += 1
+ # print("yes",index)
+
+ print("correct =", correct)
+ print("total =", total)
+ print("acc =",correct/total)
+
+
+
+ # correct = 0
+ # total = 0
+ # for index, (line1, line2) in enumerate(zip(reader1, reader2), 1):
+ # total += 1
+ # answer = line2.strip()
+ # ground_truth = json.loads(line1.strip())['answer'].strip(".")[0]
+ # length = len(ground_truth)
+ # flag = False
+ # import pdb;pdb.set_trace()
+ # if length == 1 and ground_truth.isalpha():
+ # flag = True
+ # answer = answer.split(".")[0]
+ # elif length == 2 or length == 3:
+ # flag = True
+ # answer = answer.split(",")[0]
+
+ # if flag:
+ # if answer.lower() == ground_truth.lower():
+ # correct += 1
+ # else:
+ # print("->", index)
+ # print("correct =", correct)
+ # print("total =", total)
\ No newline at end of file
diff --git a/blink_check.py b/blink_check.py
new file mode 100644
index 0000000000000000000000000000000000000000..db9cbc14ad15fa43fee9e99fa199defec36ba4ee
--- /dev/null
+++ b/blink_check.py
@@ -0,0 +1,158 @@
+
+import json
+
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/annotations.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Counting/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Relative_Depth/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/7b-blink-depth.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Spatial_Relation/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-13b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Visual_Correspondence/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-13b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Multi-view_Reasoning/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Object_Localization/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-13b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Jigsaw/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/CV-Bench/test3d-depth.jsonl', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/CV-Bench/test-count.jsonl', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+
+# with open('/home/aiops/wangzh/data/realworldqa/updated.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+
+# with open('/home/aiops/wangzh/data/blink/BLINK/Spatial_Relation/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/all.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/object_orientation.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/relative_depth.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/relative_size.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/relative_spatial_position.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/none_spatial.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/orientation.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/relative_depth.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/relative_size.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/spatial_relation.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+
+ # reader1 = json.load(reader1)
+
+ correct = 0
+ total = 0
+ for index, (line1, line2) in enumerate(zip(reader1, reader2), 1):
+ total += 1
+
+ answer = line2.strip()
+ # ground_truth = line1['answer']
+ ground_truth = json.loads(line1.strip())['answer']
+ # length = len(ground_truth)
+ flag = False
+ # choices = json.loads(line1.strip())['choices']
+
+ # if ground_truth in answer:
+ # correct += 1
+ # import pdb;pdb.set_trace()
+ # if ('A' in answer) and ('B' in answer) and ('C' in answer) and ('D' in answer):
+ # print('missed',index)
+ # continue
+ # if ground_truth == '(A)':
+ # if 'left' in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(B)':
+ # if 'right' in answer:
+ # correct += 1
+ # print("yes",index)
+ # if ground_truth == '(A)':
+ # if 'second' in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(B)':
+ # if 'third' in answer:
+ # correct += 1
+ # print("yes",index)
+ # count_sed = answer.count('sed')
+ # count_tird = answer.count('tird')
+
+ # if ground_truth == answer:
+ # correct += 1
+ # print("yes",index)
+ if ground_truth == 0:
+ if ('A' in answer) :
+ correct += 1
+ print("yes",index)
+ else:
+ fail+=1
+ elif ground_truth == 1:
+ if ('B' in answer) :
+ correct += 1
+ print("yes",index)
+ else:
+ fail+=1
+
+ elif ground_truth == 2:
+ if ('C' in answer) :
+ correct += 1
+ print("yes",index)
+ else:
+ fail+=1
+
+ elif ground_truth == 3:
+ if ('D' in answer) :
+ correct += 1
+ print("yes",index)
+ else:
+ fail+=1
+ # if ground_truth == '(A)':
+ # if 'A' in answer :
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(B)':
+ # if 'B' in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(C)':
+ # if 'C' in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(D)':
+ # if 'D' in answer:
+ # correct += 1
+ # print("yes",index)
+ # if ground_truth == '(A)':
+ # if choices[2] in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(B)':
+ # if choices[6] in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(C)':
+ # if choices[10] in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(D)':
+ # if choices[14] in answer:
+ # correct += 1
+ # print("yes",index)
+
+ print("correct =", correct)
+ print("total =", total)
+ print("acc =",correct/total)
+
+
+
+ # correct = 0
+ # total = 0
+ # for index, (line1, line2) in enumerate(zip(reader1, reader2), 1):
+ # total += 1
+ # answer = line2.strip()
+ # ground_truth = json.loads(line1.strip())['answer'].strip(".")[0]
+ # length = len(ground_truth)
+ # flag = False
+ # import pdb;pdb.set_trace()
+ # if length == 1 and ground_truth.isalpha():
+ # flag = True
+ # answer = answer.split(".")[0]
+ # elif length == 2 or length == 3:
+ # flag = True
+ # answer = answer.split(",")[0]
+
+ # if flag:
+ # if answer.lower() == ground_truth.lower():
+ # correct += 1
+ # else:
+ # print("->", index)
+ # print("correct =", correct)
+ # print("total =", total)
\ No newline at end of file
diff --git a/check.py b/check.py
new file mode 100644
index 0000000000000000000000000000000000000000..92e09dbc8e2571d031835a48aa046cba9c7a2f6f
--- /dev/null
+++ b/check.py
@@ -0,0 +1,17 @@
+import torch
+
+# ๅ ่ฝฝๆจกๅๅๆฐ
+model_path = '/home/aiops/wangzh/zss/AlphaCLIP/train/final-negative-large-wiseconv/ckpt/iter_10000.pth' # ไฝ ็ๆจกๅ่ทฏๅพ
+checkpoint = torch.load(model_path)
+
+# ่พๅบ checkpoint ๅ ๅฎน
+# print("Checkpoint content:", checkpoint)
+import pdb;pdb.set_trace()
+# ๅฆๆ checkpoint ๆฏไธไธชๅ ๅซๆจกๅๅๆฐ็ๅญๅ ธ๏ผไพๅฆstate_dict๏ผ
+if isinstance(checkpoint, dict):
+ for key, value in checkpoint.items():
+ print(f"{key}: {value.shape}")
+ if 'cpe' in key:
+ print(value)
+else:
+ print("The checkpoint does not contain a dictionary with parameters.")
diff --git a/cog.yaml b/cog.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..55b739fd437a1897c1c1ec001f47aac2fbfdf68b
--- /dev/null
+++ b/cog.yaml
@@ -0,0 +1,37 @@
+# Configuration for Cog โ๏ธ
+# Reference: https://github.com/replicate/cog/blob/main/docs/yaml.md
+
+build:
+ gpu: true
+
+ python_version: "3.11"
+
+ python_packages:
+ - "torch==2.0.1"
+ - "accelerate==0.21.0"
+ - "bitsandbytes==0.41.0"
+ - "deepspeed==0.9.5"
+ - "einops-exts==0.0.4"
+ - "einops==0.6.1"
+ - "gradio==3.35.2"
+ - "gradio_client==0.2.9"
+ - "httpx==0.24.0"
+ - "markdown2==2.4.10"
+ - "numpy==1.26.0"
+ - "peft==0.4.0"
+ - "scikit-learn==1.2.2"
+ - "sentencepiece==0.1.99"
+ - "shortuuid==1.0.11"
+ - "timm==0.6.13"
+ - "tokenizers==0.13.3"
+ - "torch==2.0.1"
+ - "torchvision==0.15.2"
+ - "transformers==4.31.0"
+ - "wandb==0.15.12"
+ - "wavedrom==2.0.3.post3"
+ - "Pygments==2.16.1"
+ run:
+ - curl -o /usr/local/bin/pget -L "https://github.com/replicate/pget/releases/download/v0.0.3/pget" && chmod +x /usr/local/bin/pget
+
+# predict.py defines how predictions are run on your model
+predict: "predict.py:Predictor"
diff --git a/cv_check.py b/cv_check.py
new file mode 100644
index 0000000000000000000000000000000000000000..c22e54f7ff2a5e433b379bf91b593674f642ca78
--- /dev/null
+++ b/cv_check.py
@@ -0,0 +1,157 @@
+
+import json
+
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/annotations.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Counting/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Relative_Depth/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Spatial_Relation/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-13b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Visual_Correspondence/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-13b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Multi-view_Reasoning/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Object_Localization/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-13b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/blink/BLINK/Jigsaw/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+with open('/home/aiops/wangzh/data/CV-Bench/test3d.jsonl', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/CV-Bench/test3d.jsonl', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+
+#
+# with open('/home/aiops/wangzh/data/blink/BLINK/Spatial_Relation/output.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/all.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/all.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/gpt4o-outdoor.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor-new/all.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/gemini-indoor.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor-new/all.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/gemini-indoor.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/realworldqa/updated.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/object_orientation.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/relative_depth.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/relative_size.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/relative_spatial_position.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/none_spatial.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/orientation.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/relative_depth.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/relative_size.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+# with open('/home/aiops/wangzh/data/scanner/indoor/spatial_relation.json', 'r') as reader1, open('/home/aiops/wangzh/llava-spat/llava-v1.5-7b-final-neg-lora_answers.txt', 'r') as reader2:
+
+ # reader1 = json.load(reader1)
+
+ correct = 0
+ total = 0
+ for index, (line1, line2) in enumerate(zip(reader1, reader2), 1):
+ total += 1
+
+ answer = line2.strip()
+ # ground_truth = line1['answer']
+ ground_truth = json.loads(line1.strip())['answer']
+ # length = len(ground_truth)
+ flag = False
+ # choices = json.loads(line1.strip())['choices']
+
+ # if ground_truth in answer:
+ # correct += 1
+ # import pdb;pdb.set_trace()
+ # if ('A' in answer) and ('B' in answer) and ('C' in answer) and ('D' in answer):
+ # print('missed',index)
+ # continue
+ # if ground_truth == '(A)':
+ # if 'left' in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(B)':
+ # if 'right' in answer:
+ # correct += 1
+ # print("yes",index)
+ # if ground_truth == '(A)':
+ # if 'second' in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(B)':
+ # if 'third' in answer:
+ # correct += 1
+ # print("yes",index)
+ # count_sed = answer.count('sed')
+ # count_tird = answer.count('tird')
+ # if ground_truth == 0:
+ # if ('A' in answer) :
+ # correct += 1
+ # print("yes",index)
+
+ # elif ground_truth == 1:
+ # if ('B' in answer) :
+ # correct += 1
+ # print("yes",index)
+
+
+ # elif ground_truth == 2:
+ # if ('C' in answer) :
+ # correct += 1
+ # print("yes",index)
+
+
+ # elif ground_truth == 3:
+ # if ('D' in answer) :
+ # correct += 1
+ # print("yes",index)
+ # if ground_truth == answer:
+ # correct += 1
+ # print("yes",index)
+
+ if ground_truth == '(A)':
+ if 'A' in answer :
+ correct += 1
+ print("yes",index)
+ elif ground_truth == '(B)':
+ if 'B' in answer:
+ correct += 1
+ print("yes",index)
+ elif ground_truth == '(C)':
+ if 'C' in answer:
+ correct += 1
+ print("yes",index)
+ elif ground_truth == '(D)':
+ if 'D' in answer:
+ correct += 1
+ print("yes",index)
+ # if ground_truth == '(A)':
+ # if choices[2] in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(B)':
+ # if choices[6] in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(C)':
+ # if choices[10] in answer:
+ # correct += 1
+ # print("yes",index)
+ # elif ground_truth == '(D)':
+ # if choices[14] in answer:
+ # correct += 1
+ # print("yes",index)
+
+ print("correct =", correct)
+ print("total =", total)
+ print("acc =",correct/total)
+
+
+
+ # correct = 0
+ # total = 0
+ # for index, (line1, line2) in enumerate(zip(reader1, reader2), 1):
+ # total += 1
+ # answer = line2.strip()
+ # ground_truth = json.loads(line1.strip())['answer'].strip(".")[0]
+ # length = len(ground_truth)
+ # flag = False
+ # import pdb;pdb.set_trace()
+ # if length == 1 and ground_truth.isalpha():
+ # flag = True
+ # answer = answer.split(".")[0]
+ # elif length == 2 or length == 3:
+ # flag = True
+ # answer = answer.split(",")[0]
+
+ # if flag:
+ # if answer.lower() == ground_truth.lower():
+ # correct += 1
+ # else:
+ # print("->", index)
+ # print("correct =", correct)
+ # print("total =", total)
\ No newline at end of file
diff --git a/depth_anything_v2/dinov2.py b/depth_anything_v2/dinov2.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfeb601cd9405341410736acc17ab4da92b0a33c
--- /dev/null
+++ b/depth_anything_v2/dinov2.py
@@ -0,0 +1,416 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the Apache License, Version 2.0
+# found in the LICENSE file in the root directory of this source tree.
+
+# References:
+# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
+# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
+
+from functools import partial
+import math
+import logging
+from typing import Sequence, Tuple, Union, Callable
+
+import torch
+import torch.nn as nn
+import torch.utils.checkpoint
+from torch.nn.init import trunc_normal_
+
+from .dinov2_layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block
+
+
+logger = logging.getLogger("dinov2")
+
+
+def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module:
+ if not depth_first and include_root:
+ fn(module=module, name=name)
+ for child_name, child_module in module.named_children():
+ child_name = ".".join((name, child_name)) if name else child_name
+ named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True)
+ if depth_first and include_root:
+ fn(module=module, name=name)
+ return module
+
+
+class BlockChunk(nn.ModuleList):
+ def forward(self, x):
+ for b in self:
+ x = b(x)
+ return x
+
+
+class DinoVisionTransformer(nn.Module):
+ def __init__(
+ self,
+ img_size=224,
+ patch_size=16,
+ in_chans=3,
+ embed_dim=768,
+ depth=12,
+ num_heads=12,
+ mlp_ratio=4.0,
+ qkv_bias=True,
+ ffn_bias=True,
+ proj_bias=True,
+ drop_path_rate=0.0,
+ drop_path_uniform=False,
+ init_values=None, # for layerscale: None or 0 => no layerscale
+ embed_layer=PatchEmbed,
+ act_layer=nn.GELU,
+ block_fn=Block,
+ ffn_layer="mlp",
+ block_chunks=1,
+ num_register_tokens=0,
+ interpolate_antialias=False,
+ interpolate_offset=0.1,
+ ):
+ """
+ Args:
+ img_size (int, tuple): input image size
+ patch_size (int, tuple): patch size
+ in_chans (int): number of input channels
+ embed_dim (int): embedding dimension
+ depth (int): depth of transformer
+ num_heads (int): number of attention heads
+ mlp_ratio (int): ratio of mlp hidden dim to embedding dim
+ qkv_bias (bool): enable bias for qkv if True
+ proj_bias (bool): enable bias for proj in attn if True
+ ffn_bias (bool): enable bias for ffn if True
+ drop_path_rate (float): stochastic depth rate
+ drop_path_uniform (bool): apply uniform drop rate across blocks
+ weight_init (str): weight init scheme
+ init_values (float): layer-scale init values
+ embed_layer (nn.Module): patch embedding layer
+ act_layer (nn.Module): MLP activation layer
+ block_fn (nn.Module): transformer block class
+ ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"
+ block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
+ num_register_tokens: (int) number of extra cls tokens (so-called "registers")
+ interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings
+ interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings
+ """
+ super().__init__()
+ norm_layer = partial(nn.LayerNorm, eps=1e-6)
+
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
+ self.num_tokens = 1
+ self.n_blocks = depth
+ self.num_heads = num_heads
+ self.patch_size = patch_size
+ self.num_register_tokens = num_register_tokens
+ self.interpolate_antialias = interpolate_antialias
+ self.interpolate_offset = interpolate_offset
+
+ self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
+ num_patches = self.patch_embed.num_patches
+
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
+ assert num_register_tokens >= 0
+ self.register_tokens = (
+ nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None
+ )
+
+ if drop_path_uniform is True:
+ dpr = [drop_path_rate] * depth
+ else:
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
+
+ if ffn_layer == "mlp":
+ logger.info("using MLP layer as FFN")
+ ffn_layer = Mlp
+ elif ffn_layer == "swiglufused" or ffn_layer == "swiglu":
+ logger.info("using SwiGLU layer as FFN")
+ ffn_layer = SwiGLUFFNFused
+ elif ffn_layer == "identity":
+ logger.info("using Identity layer as FFN")
+
+ def f(*args, **kwargs):
+ return nn.Identity()
+
+ ffn_layer = f
+ else:
+ raise NotImplementedError
+
+ blocks_list = [
+ block_fn(
+ dim=embed_dim,
+ num_heads=num_heads,
+ mlp_ratio=mlp_ratio,
+ qkv_bias=qkv_bias,
+ proj_bias=proj_bias,
+ ffn_bias=ffn_bias,
+ drop_path=dpr[i],
+ norm_layer=norm_layer,
+ act_layer=act_layer,
+ ffn_layer=ffn_layer,
+ init_values=init_values,
+ )
+ for i in range(depth)
+ ]
+ if block_chunks > 0:
+ self.chunked_blocks = True
+ chunked_blocks = []
+ chunksize = depth // block_chunks
+ for i in range(0, depth, chunksize):
+ # this is to keep the block index consistent if we chunk the block list
+ chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize])
+ self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks])
+ else:
+ self.chunked_blocks = False
+ self.blocks = nn.ModuleList(blocks_list)
+
+ self.norm = norm_layer(embed_dim)
+ self.head = nn.Identity()
+
+ self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
+
+ self.init_weights()
+
+ def init_weights(self):
+ trunc_normal_(self.pos_embed, std=0.02)
+ nn.init.normal_(self.cls_token, std=1e-6)
+ if self.register_tokens is not None:
+ nn.init.normal_(self.register_tokens, std=1e-6)
+ named_apply(init_weights_vit_timm, self)
+
+ def interpolate_pos_encoding(self, x, w, h):
+ previous_dtype = x.dtype
+ npatch = x.shape[1] - 1
+ N = self.pos_embed.shape[1] - 1
+ if npatch == N and w == h:
+ return self.pos_embed
+ pos_embed = self.pos_embed.float()
+ class_pos_embed = pos_embed[:, 0]
+ patch_pos_embed = pos_embed[:, 1:]
+ dim = x.shape[-1]
+ w0 = w // self.patch_size
+ h0 = h // self.patch_size
+ # we add a small number to avoid floating point error in the interpolation
+ # see discussion at https://github.com/facebookresearch/dino/issues/8
+ # DINOv2 with register modify the interpolate_offset from 0.1 to 0.0
+ w0, h0 = w0 + self.interpolate_offset, h0 + self.interpolate_offset
+ # w0, h0 = w0 + 0.1, h0 + 0.1
+
+ sqrt_N = math.sqrt(N)
+ sx, sy = float(w0) / sqrt_N, float(h0) / sqrt_N
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed.reshape(1, int(sqrt_N), int(sqrt_N), dim).permute(0, 3, 1, 2),
+ scale_factor=(sx, sy),
+ # (int(w0), int(h0)), # to solve the upsampling shape issue
+ mode="bicubic",
+ antialias=self.interpolate_antialias
+ )
+
+ assert int(w0) == patch_pos_embed.shape[-2]
+ assert int(h0) == patch_pos_embed.shape[-1]
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
+
+ def prepare_tokens_with_masks(self, x, masks=None):
+ B, nc, w, h = x.shape
+ # import pdb;pdb.set_trace()
+ x = self.patch_embed(x)
+ if masks is not None:
+ x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
+
+ x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)
+ x = x + self.interpolate_pos_encoding(x, w, h)
+
+ if self.register_tokens is not None:
+ x = torch.cat(
+ (
+ x[:, :1],
+ self.register_tokens.expand(x.shape[0], -1, -1),
+ x[:, 1:],
+ ),
+ dim=1,
+ )
+
+ return x
+
+ def forward_features_list(self, x_list, masks_list):
+ x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]
+ for blk in self.blocks:
+ x = blk(x)
+
+ all_x = x
+ output = []
+ for x, masks in zip(all_x, masks_list):
+ x_norm = self.norm(x)
+ output.append(
+ {
+ "x_norm_clstoken": x_norm[:, 0],
+ "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
+ "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
+ "x_prenorm": x,
+ "masks": masks,
+ }
+ )
+ return output
+
+ def forward_features(self, x, masks=None):
+ if isinstance(x, list):
+ return self.forward_features_list(x, masks)
+
+ x = self.prepare_tokens_with_masks(x, masks)
+
+ for blk in self.blocks:
+ x = blk(x)
+
+ x_norm = self.norm(x)
+ return {
+ "x_norm_clstoken": x_norm[:, 0],
+ "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
+ "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
+ "x_prenorm": x,
+ "masks": masks,
+ }
+
+ def _get_intermediate_layers_not_chunked(self, x, n=1):
+ x = self.prepare_tokens_with_masks(x)
+ # If n is an int, take the n last blocks. If it's a list, take them
+ output, total_block_len = [], len(self.blocks)
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
+ for i, blk in enumerate(self.blocks):
+ x = blk(x)
+ if i in blocks_to_take:
+ output.append(x)
+ assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
+ return output
+
+ def _get_intermediate_layers_chunked(self, x, n=1):
+ x = self.prepare_tokens_with_masks(x)
+ output, i, total_block_len = [], 0, len(self.blocks[-1])
+ # If n is an int, take the n last blocks. If it's a list, take them
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
+ for block_chunk in self.blocks:
+ for blk in block_chunk[i:]: # Passing the nn.Identity()
+ x = blk(x)
+ if i in blocks_to_take:
+ output.append(x)
+ i += 1
+ assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
+ return output
+
+ def get_intermediate_layers(
+ self,
+ x: torch.Tensor,
+ n: Union[int, Sequence] = 1, # Layers or n last layers to take
+ reshape: bool = False,
+ return_class_token: bool = False,
+ norm=True
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
+ if self.chunked_blocks:
+ outputs = self._get_intermediate_layers_chunked(x, n)
+ else:
+ outputs = self._get_intermediate_layers_not_chunked(x, n)
+ if norm:
+ outputs = [self.norm(out) for out in outputs]
+ class_tokens = [out[:, 0] for out in outputs]
+ outputs = [out[:, 1 + self.num_register_tokens:] for out in outputs]
+ if reshape:
+ B, _, w, h = x.shape
+ outputs = [
+ out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous()
+ for out in outputs
+ ]
+ if return_class_token:
+ return tuple(zip(outputs, class_tokens))
+ return tuple(outputs)
+
+ def forward(self, *args, is_training=False, **kwargs):
+ ret = self.forward_features(*args, **kwargs)
+ if is_training:
+ return ret
+ else:
+ return self.head(ret["x_norm_clstoken"])
+
+
+def init_weights_vit_timm(module: nn.Module, name: str = ""):
+ """ViT weight initialization, original timm impl (for reproducibility)"""
+ if isinstance(module, nn.Linear):
+ trunc_normal_(module.weight, std=0.02)
+ if module.bias is not None:
+ nn.init.zeros_(module.bias)
+
+
+def vit_small(patch_size=16, num_register_tokens=0, **kwargs):
+ model = DinoVisionTransformer(
+ patch_size=patch_size,
+ embed_dim=384,
+ depth=12,
+ num_heads=6,
+ mlp_ratio=4,
+ block_fn=partial(Block, attn_class=MemEffAttention),
+ num_register_tokens=num_register_tokens,
+ **kwargs,
+ )
+ return model
+
+
+def vit_base(patch_size=16, num_register_tokens=0, **kwargs):
+ model = DinoVisionTransformer(
+ patch_size=patch_size,
+ embed_dim=768,
+ depth=12,
+ num_heads=12,
+ mlp_ratio=4,
+ block_fn=partial(Block, attn_class=MemEffAttention),
+ num_register_tokens=num_register_tokens,
+ **kwargs,
+ )
+ return model
+
+
+def vit_large(patch_size=16, num_register_tokens=0, **kwargs):
+ model = DinoVisionTransformer(
+ patch_size=patch_size,
+ embed_dim=1024,
+ depth=24,
+ num_heads=16,
+ mlp_ratio=4,
+ block_fn=partial(Block, attn_class=MemEffAttention),
+ num_register_tokens=num_register_tokens,
+ **kwargs,
+ )
+ return model
+
+
+def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs):
+ """
+ Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
+ """
+ model = DinoVisionTransformer(
+ patch_size=patch_size,
+ embed_dim=1536,
+ depth=40,
+ num_heads=24,
+ mlp_ratio=4,
+ block_fn=partial(Block, attn_class=MemEffAttention),
+ num_register_tokens=num_register_tokens,
+ **kwargs,
+ )
+ return model
+
+
+def DINOv2(model_name):
+ model_zoo = {
+ "vits": vit_small,
+ "vitb": vit_base,
+ "vitl": vit_large,
+ "vitg": vit_giant2
+ }
+
+ return model_zoo[model_name](
+ img_size=518,
+ patch_size=14,
+ init_values=1.0,
+ ffn_layer="mlp" if model_name != "vitg" else "swiglufused",
+ block_chunks=0,
+ num_register_tokens=0,
+ interpolate_antialias=False,
+ interpolate_offset=0.1
+ )
diff --git a/depth_anything_v2/dinov2_layers/__init__.py b/depth_anything_v2/dinov2_layers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8120f4bc83066cb3f825ce32daa3b437f88486f1
--- /dev/null
+++ b/depth_anything_v2/dinov2_layers/__init__.py
@@ -0,0 +1,11 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+from .mlp import Mlp
+from .patch_embed import PatchEmbed
+from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused
+from .block import NestedTensorBlock
+from .attention import MemEffAttention
diff --git a/depth_anything_v2/dinov2_layers/attention.py b/depth_anything_v2/dinov2_layers/attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..815a2bf53dbec496f6a184ed7d03bcecb7124262
--- /dev/null
+++ b/depth_anything_v2/dinov2_layers/attention.py
@@ -0,0 +1,83 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+# References:
+# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
+# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
+
+import logging
+
+from torch import Tensor
+from torch import nn
+
+
+logger = logging.getLogger("dinov2")
+
+
+try:
+ from xformers.ops import memory_efficient_attention, unbind, fmha
+
+ XFORMERS_AVAILABLE = True
+except ImportError:
+ logger.warning("xFormers not available")
+ XFORMERS_AVAILABLE = False
+
+
+class Attention(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ num_heads: int = 8,
+ qkv_bias: bool = False,
+ proj_bias: bool = True,
+ attn_drop: float = 0.0,
+ proj_drop: float = 0.0,
+ ) -> None:
+ super().__init__()
+ self.num_heads = num_heads
+ head_dim = dim // num_heads
+ self.scale = head_dim**-0.5
+
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj = nn.Linear(dim, dim, bias=proj_bias)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ def forward(self, x: Tensor) -> Tensor:
+ B, N, C = x.shape
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
+
+ q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
+ attn = q @ k.transpose(-2, -1)
+
+ attn = attn.softmax(dim=-1)
+ attn = self.attn_drop(attn)
+
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+ return x
+
+
+class MemEffAttention(Attention):
+ def forward(self, x: Tensor, attn_bias=None) -> Tensor:
+ if not XFORMERS_AVAILABLE:
+ assert attn_bias is None, "xFormers is required for nested tensors usage"
+ return super().forward(x)
+
+ B, N, C = x.shape
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
+
+ q, k, v = unbind(qkv, 2)
+
+ x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
+ x = x.reshape([B, N, C])
+
+ x = self.proj(x)
+ x = self.proj_drop(x)
+ return x
+
+
\ No newline at end of file
diff --git a/depth_anything_v2/dinov2_layers/block.py b/depth_anything_v2/dinov2_layers/block.py
new file mode 100644
index 0000000000000000000000000000000000000000..25488f57cc0ad3c692f86b62555f6668e2a66db1
--- /dev/null
+++ b/depth_anything_v2/dinov2_layers/block.py
@@ -0,0 +1,252 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+# References:
+# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
+# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
+
+import logging
+from typing import Callable, List, Any, Tuple, Dict
+
+import torch
+from torch import nn, Tensor
+
+from .attention import Attention, MemEffAttention
+from .drop_path import DropPath
+from .layer_scale import LayerScale
+from .mlp import Mlp
+
+
+logger = logging.getLogger("dinov2")
+
+
+try:
+ from xformers.ops import fmha
+ from xformers.ops import scaled_index_add, index_select_cat
+
+ XFORMERS_AVAILABLE = True
+except ImportError:
+ logger.warning("xFormers not available")
+ XFORMERS_AVAILABLE = False
+
+
+class Block(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ num_heads: int,
+ mlp_ratio: float = 4.0,
+ qkv_bias: bool = False,
+ proj_bias: bool = True,
+ ffn_bias: bool = True,
+ drop: float = 0.0,
+ attn_drop: float = 0.0,
+ init_values=None,
+ drop_path: float = 0.0,
+ act_layer: Callable[..., nn.Module] = nn.GELU,
+ norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
+ attn_class: Callable[..., nn.Module] = Attention,
+ ffn_layer: Callable[..., nn.Module] = Mlp,
+ ) -> None:
+ super().__init__()
+ # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")
+ self.norm1 = norm_layer(dim)
+ self.attn = attn_class(
+ dim,
+ num_heads=num_heads,
+ qkv_bias=qkv_bias,
+ proj_bias=proj_bias,
+ attn_drop=attn_drop,
+ proj_drop=drop,
+ )
+ self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+
+ self.norm2 = norm_layer(dim)
+ mlp_hidden_dim = int(dim * mlp_ratio)
+ self.mlp = ffn_layer(
+ in_features=dim,
+ hidden_features=mlp_hidden_dim,
+ act_layer=act_layer,
+ drop=drop,
+ bias=ffn_bias,
+ )
+ self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
+ self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+
+ self.sample_drop_ratio = drop_path
+
+ def forward(self, x: Tensor) -> Tensor:
+ def attn_residual_func(x: Tensor) -> Tensor:
+ return self.ls1(self.attn(self.norm1(x)))
+
+ def ffn_residual_func(x: Tensor) -> Tensor:
+ return self.ls2(self.mlp(self.norm2(x)))
+
+ if self.training and self.sample_drop_ratio > 0.1:
+ # the overhead is compensated only for a drop path rate larger than 0.1
+ x = drop_add_residual_stochastic_depth(
+ x,
+ residual_func=attn_residual_func,
+ sample_drop_ratio=self.sample_drop_ratio,
+ )
+ x = drop_add_residual_stochastic_depth(
+ x,
+ residual_func=ffn_residual_func,
+ sample_drop_ratio=self.sample_drop_ratio,
+ )
+ elif self.training and self.sample_drop_ratio > 0.0:
+ x = x + self.drop_path1(attn_residual_func(x))
+ x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2
+ else:
+ x = x + attn_residual_func(x)
+ x = x + ffn_residual_func(x)
+ return x
+
+
+def drop_add_residual_stochastic_depth(
+ x: Tensor,
+ residual_func: Callable[[Tensor], Tensor],
+ sample_drop_ratio: float = 0.0,
+) -> Tensor:
+ # 1) extract subset using permutation
+ b, n, d = x.shape
+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
+ x_subset = x[brange]
+
+ # 2) apply residual_func to get residual
+ residual = residual_func(x_subset)
+
+ x_flat = x.flatten(1)
+ residual = residual.flatten(1)
+
+ residual_scale_factor = b / sample_subset_size
+
+ # 3) add the residual
+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
+ return x_plus_residual.view_as(x)
+
+
+def get_branges_scales(x, sample_drop_ratio=0.0):
+ b, n, d = x.shape
+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
+ residual_scale_factor = b / sample_subset_size
+ return brange, residual_scale_factor
+
+
+def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None):
+ if scaling_vector is None:
+ x_flat = x.flatten(1)
+ residual = residual.flatten(1)
+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
+ else:
+ x_plus_residual = scaled_index_add(
+ x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor
+ )
+ return x_plus_residual
+
+
+attn_bias_cache: Dict[Tuple, Any] = {}
+
+
+def get_attn_bias_and_cat(x_list, branges=None):
+ """
+ this will perform the index select, cat the tensors, and provide the attn_bias from cache
+ """
+ batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list]
+ all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list))
+ if all_shapes not in attn_bias_cache.keys():
+ seqlens = []
+ for b, x in zip(batch_sizes, x_list):
+ for _ in range(b):
+ seqlens.append(x.shape[1])
+ attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens)
+ attn_bias._batch_sizes = batch_sizes
+ attn_bias_cache[all_shapes] = attn_bias
+
+ if branges is not None:
+ cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1])
+ else:
+ tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list)
+ cat_tensors = torch.cat(tensors_bs1, dim=1)
+
+ return attn_bias_cache[all_shapes], cat_tensors
+
+
+def drop_add_residual_stochastic_depth_list(
+ x_list: List[Tensor],
+ residual_func: Callable[[Tensor, Any], Tensor],
+ sample_drop_ratio: float = 0.0,
+ scaling_vector=None,
+) -> Tensor:
+ # 1) generate random set of indices for dropping samples in the batch
+ branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list]
+ branges = [s[0] for s in branges_scales]
+ residual_scale_factors = [s[1] for s in branges_scales]
+
+ # 2) get attention bias and index+concat the tensors
+ attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)
+
+ # 3) apply residual_func to get residual, and split the result
+ residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore
+
+ outputs = []
+ for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors):
+ outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x))
+ return outputs
+
+
+class NestedTensorBlock(Block):
+ def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]:
+ """
+ x_list contains a list of tensors to nest together and run
+ """
+ assert isinstance(self.attn, MemEffAttention)
+
+ if self.training and self.sample_drop_ratio > 0.0:
+
+ def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
+ return self.attn(self.norm1(x), attn_bias=attn_bias)
+
+ def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
+ return self.mlp(self.norm2(x))
+
+ x_list = drop_add_residual_stochastic_depth_list(
+ x_list,
+ residual_func=attn_residual_func,
+ sample_drop_ratio=self.sample_drop_ratio,
+ scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None,
+ )
+ x_list = drop_add_residual_stochastic_depth_list(
+ x_list,
+ residual_func=ffn_residual_func,
+ sample_drop_ratio=self.sample_drop_ratio,
+ scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None,
+ )
+ return x_list
+ else:
+
+ def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
+ return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))
+
+ def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
+ return self.ls2(self.mlp(self.norm2(x)))
+
+ attn_bias, x = get_attn_bias_and_cat(x_list)
+ x = x + attn_residual_func(x, attn_bias=attn_bias)
+ x = x + ffn_residual_func(x)
+ return attn_bias.split(x)
+
+ def forward(self, x_or_x_list):
+ if isinstance(x_or_x_list, Tensor):
+ return super().forward(x_or_x_list)
+ elif isinstance(x_or_x_list, list):
+ assert XFORMERS_AVAILABLE, "Please install xFormers for nested tensors usage"
+ return self.forward_nested(x_or_x_list)
+ else:
+ raise AssertionError
diff --git a/depth_anything_v2/dinov2_layers/drop_path.py b/depth_anything_v2/dinov2_layers/drop_path.py
new file mode 100644
index 0000000000000000000000000000000000000000..af05625984dd14682cc96a63bf0c97bab1f123b1
--- /dev/null
+++ b/depth_anything_v2/dinov2_layers/drop_path.py
@@ -0,0 +1,35 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+# References:
+# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
+# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
+
+
+from torch import nn
+
+
+def drop_path(x, drop_prob: float = 0.0, training: bool = False):
+ if drop_prob == 0.0 or not training:
+ return x
+ keep_prob = 1 - drop_prob
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
+ if keep_prob > 0.0:
+ random_tensor.div_(keep_prob)
+ output = x * random_tensor
+ return output
+
+
+class DropPath(nn.Module):
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
+
+ def __init__(self, drop_prob=None):
+ super(DropPath, self).__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, x):
+ return drop_path(x, self.drop_prob, self.training)
diff --git a/depth_anything_v2/dinov2_layers/layer_scale.py b/depth_anything_v2/dinov2_layers/layer_scale.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca5daa52bd81d3581adeb2198ea5b7dba2a3aea1
--- /dev/null
+++ b/depth_anything_v2/dinov2_layers/layer_scale.py
@@ -0,0 +1,28 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110
+
+from typing import Union
+
+import torch
+from torch import Tensor
+from torch import nn
+
+
+class LayerScale(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ init_values: Union[float, Tensor] = 1e-5,
+ inplace: bool = False,
+ ) -> None:
+ super().__init__()
+ self.inplace = inplace
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
+
+ def forward(self, x: Tensor) -> Tensor:
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
diff --git a/depth_anything_v2/dinov2_layers/mlp.py b/depth_anything_v2/dinov2_layers/mlp.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e4b315f972f9a9f54aef1e4ef4e81b52976f018
--- /dev/null
+++ b/depth_anything_v2/dinov2_layers/mlp.py
@@ -0,0 +1,41 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+# References:
+# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
+# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py
+
+
+from typing import Callable, Optional
+
+from torch import Tensor, nn
+
+
+class Mlp(nn.Module):
+ def __init__(
+ self,
+ in_features: int,
+ hidden_features: Optional[int] = None,
+ out_features: Optional[int] = None,
+ act_layer: Callable[..., nn.Module] = nn.GELU,
+ drop: float = 0.0,
+ bias: bool = True,
+ ) -> None:
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
+ self.act = act_layer()
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, x: Tensor) -> Tensor:
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.drop(x)
+ x = self.fc2(x)
+ x = self.drop(x)
+ return x
diff --git a/depth_anything_v2/dinov2_layers/patch_embed.py b/depth_anything_v2/dinov2_layers/patch_embed.py
new file mode 100644
index 0000000000000000000000000000000000000000..434294786631c6c79a0e7bb4bdbba0bb57ec5bbf
--- /dev/null
+++ b/depth_anything_v2/dinov2_layers/patch_embed.py
@@ -0,0 +1,89 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+# References:
+# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
+# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
+
+from typing import Callable, Optional, Tuple, Union
+
+from torch import Tensor
+import torch.nn as nn
+import torch
+
+def make_2tuple(x):
+ if isinstance(x, tuple):
+ assert len(x) == 2
+ return x
+
+ assert isinstance(x, int)
+ return (x, x)
+
+
+class PatchEmbed(nn.Module):
+ """
+ 2D image to patch embedding: (B,C,H,W) -> (B,N,D)
+
+ Args:
+ img_size: Image size.
+ patch_size: Patch token size.
+ in_chans: Number of input image channels.
+ embed_dim: Number of linear projection output channels.
+ norm_layer: Normalization layer.
+ """
+
+ def __init__(
+ self,
+ img_size: Union[int, Tuple[int, int]] = 224,
+ patch_size: Union[int, Tuple[int, int]] = 16,
+ in_chans: int = 3,
+ embed_dim: int = 768,
+ norm_layer: Optional[Callable] = None,
+ flatten_embedding: bool = True,
+ ) -> None:
+ super().__init__()
+
+ image_HW = make_2tuple(img_size)
+ patch_HW = make_2tuple(patch_size)
+ patch_grid_size = (
+ image_HW[0] // patch_HW[0],
+ image_HW[1] // patch_HW[1],
+ )
+
+ self.img_size = image_HW
+ self.patch_size = patch_HW
+ self.patches_resolution = patch_grid_size
+ self.num_patches = patch_grid_size[0] * patch_grid_size[1]
+
+ self.in_chans = in_chans
+ self.embed_dim = embed_dim
+
+ self.flatten_embedding = flatten_embedding
+
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW).to(torch.float16)
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
+
+ def forward(self, x: Tensor) -> Tensor:
+ _, _, H, W = x.shape
+ patch_H, patch_W = self.patch_size
+ # x=x.bfloat16()
+ assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}"
+ assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}"
+ # import pdb;pdb.set_trace()
+ x = self.proj(x) # B C H W
+ H, W = x.size(2), x.size(3)
+ x = x.flatten(2).transpose(1, 2) # B HW C
+ x = self.norm(x)
+ if not self.flatten_embedding:
+ x = x.reshape(-1, H, W, self.embed_dim) # B H W C
+ return x
+
+ def flops(self) -> float:
+ Ho, Wo = self.patches_resolution
+ flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
+ if self.norm is not None:
+ flops += Ho * Wo * self.embed_dim
+ return flops
diff --git a/depth_anything_v2/dinov2_layers/swiglu_ffn.py b/depth_anything_v2/dinov2_layers/swiglu_ffn.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3324b266fb0a50ccf8c3a0ede2ae10ac4dfa03e
--- /dev/null
+++ b/depth_anything_v2/dinov2_layers/swiglu_ffn.py
@@ -0,0 +1,63 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+from typing import Callable, Optional
+
+from torch import Tensor, nn
+import torch.nn.functional as F
+
+
+class SwiGLUFFN(nn.Module):
+ def __init__(
+ self,
+ in_features: int,
+ hidden_features: Optional[int] = None,
+ out_features: Optional[int] = None,
+ act_layer: Callable[..., nn.Module] = None,
+ drop: float = 0.0,
+ bias: bool = True,
+ ) -> None:
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
+ self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
+
+ def forward(self, x: Tensor) -> Tensor:
+ x12 = self.w12(x)
+ x1, x2 = x12.chunk(2, dim=-1)
+ hidden = F.silu(x1) * x2
+ return self.w3(hidden)
+
+
+try:
+ from xformers.ops import SwiGLU
+
+ XFORMERS_AVAILABLE = True
+except ImportError:
+ SwiGLU = SwiGLUFFN
+ XFORMERS_AVAILABLE = False
+
+
+class SwiGLUFFNFused(SwiGLU):
+ def __init__(
+ self,
+ in_features: int,
+ hidden_features: Optional[int] = None,
+ out_features: Optional[int] = None,
+ act_layer: Callable[..., nn.Module] = None,
+ drop: float = 0.0,
+ bias: bool = True,
+ ) -> None:
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
+ super().__init__(
+ in_features=in_features,
+ hidden_features=hidden_features,
+ out_features=out_features,
+ bias=bias,
+ )
diff --git a/depth_anything_v2/dpt.py b/depth_anything_v2/dpt.py
new file mode 100644
index 0000000000000000000000000000000000000000..443ac83e6bb56ad74e6199defbacff22946f458b
--- /dev/null
+++ b/depth_anything_v2/dpt.py
@@ -0,0 +1,231 @@
+import cv2
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torchvision.transforms import Compose
+
+from .dinov2 import DINOv2
+from .util.blocks import FeatureFusionBlock, _make_scratch
+from .util.transform import Resize, NormalizeImage, PrepareForNet
+
+
+def _make_fusion_block(features, use_bn, size=None):
+ return FeatureFusionBlock(
+ features,
+ nn.ReLU(False),
+ deconv=False,
+ bn=use_bn,
+ expand=False,
+ align_corners=True,
+ size=size,
+ )
+
+
+class ConvBlock(nn.Module):
+ def __init__(self, in_feature, out_feature):
+ super().__init__()
+
+ self.conv_block = nn.Sequential(
+ nn.Conv2d(in_feature, out_feature, kernel_size=3, stride=1, padding=1),
+ nn.BatchNorm2d(out_feature),
+ nn.ReLU(True)
+ )
+
+ def forward(self, x):
+ return self.conv_block(x)
+
+
+class DPTHead(nn.Module):
+ def __init__(
+ self,
+ in_channels,
+ features=256,
+ use_bn=False,
+ out_channels=[256, 512, 1024, 1024],
+ use_clstoken=False
+ ):
+ super(DPTHead, self).__init__()
+
+ self.use_clstoken = use_clstoken
+
+ self.projects = nn.ModuleList([
+ nn.Conv2d(
+ in_channels=in_channels,
+ out_channels=out_channel,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ ) for out_channel in out_channels
+ ])
+
+ self.resize_layers = nn.ModuleList([
+ nn.ConvTranspose2d(
+ in_channels=out_channels[0],
+ out_channels=out_channels[0],
+ kernel_size=4,
+ stride=4,
+ padding=0),
+ nn.ConvTranspose2d(
+ in_channels=out_channels[1],
+ out_channels=out_channels[1],
+ kernel_size=2,
+ stride=2,
+ padding=0),
+ nn.Identity(),
+ nn.Conv2d(
+ in_channels=out_channels[3],
+ out_channels=out_channels[3],
+ kernel_size=3,
+ stride=2,
+ padding=1)
+ ])
+
+ if use_clstoken:
+ self.readout_projects = nn.ModuleList()
+ for _ in range(len(self.projects)):
+ self.readout_projects.append(
+ nn.Sequential(
+ nn.Linear(2 * in_channels, in_channels),
+ nn.GELU()))
+
+ self.scratch = _make_scratch(
+ out_channels,
+ features,
+ groups=1,
+ expand=False,
+ )
+
+ self.scratch.stem_transpose = None
+
+ self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
+ self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
+ self.scratch.refinenet3 = _make_fusion_block(features, use_bn)
+ self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
+
+ head_features_1 = features
+ head_features_2 = 32
+
+ self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1)
+ self.scratch.output_conv2 = nn.Sequential(
+ nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1),
+ nn.ReLU(True),
+ nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0),
+ nn.ReLU(True),
+ nn.Identity(),
+ )
+
+ def forward(self, out_features, patch_h, patch_w):
+ out = []
+ for i, x in enumerate(out_features):
+ if self.use_clstoken:
+ x, cls_token = x[0], x[1]
+ readout = cls_token.unsqueeze(1).expand_as(x)
+ x = self.readout_projects[i](torch.cat((x, readout), -1))
+ else:
+ x = x[0]
+
+ x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w))
+
+ x = self.projects[i](x)
+ x = self.resize_layers[i](x)
+
+ out.append(x)
+
+ layer_1, layer_2, layer_3, layer_4 = out
+
+ layer_1_rn = self.scratch.layer1_rn(layer_1)
+ layer_2_rn = self.scratch.layer2_rn(layer_2)
+ layer_3_rn = self.scratch.layer3_rn(layer_3)
+ layer_4_rn = self.scratch.layer4_rn(layer_4)
+
+ path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
+ path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:])
+ path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:])
+ path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
+
+ out = self.scratch.output_conv1(path_1)
+ out = F.interpolate(out, (int(patch_h * 14), int(patch_w * 14)), mode="bilinear", align_corners=True)
+ out = self.scratch.output_conv2(out)
+
+ return out
+
+
+class DepthAnythingV2(nn.Module):
+ def __init__(
+ self,
+ encoder='vitl',
+ features=256,
+ out_channels=[256, 512, 1024, 1024],
+ use_bn=False,
+ use_clstoken=False
+ ):
+ super(DepthAnythingV2, self).__init__()
+
+ self.intermediate_layer_idx = {
+ 'vits': [2, 5, 8, 11],
+ 'vitb': [2, 5, 8, 11],
+ 'vitl': [4, 11, 17, 23],
+ 'vitg': [9, 19, 29, 39]
+ }
+
+ self.encoder = encoder
+ self.pretrained = DINOv2(model_name=encoder)
+
+ self.depth_head = DPTHead(self.pretrained.embed_dim, features, use_bn, out_channels=out_channels, use_clstoken=use_clstoken)
+
+ @torch.no_grad()
+ def forward(self, x, input_size=518):
+ # x, (h, w) = self.image2tensor(x, input_size)
+ b,c,h,w =x.shape
+ patch_h, patch_w = x.shape[-2] // 14, x.shape[-1] // 14
+ # import pdb;pdb.set_trace()
+ features = self.pretrained.get_intermediate_layers(x, self.intermediate_layer_idx[self.encoder], return_class_token=True)
+
+ depth = self.depth_head(features, patch_h, patch_w)
+ depth = F.relu(depth)
+ # depth=depth.squeeze(1)
+ # depth = F.interpolate(depth[:, None], (h, w), mode="bilinear", align_corners=True)[0, 0]
+
+ depth = depth.squeeze(1) # ็กฎไฟๆทฑๅบฆ็ปดๅบฆๅๅฐไธบ (b, h', w')
+ depth = F.interpolate(depth[:, None], (h, w), mode="bilinear", align_corners=True)
+
+
+
+ return depth
+
+ @torch.no_grad()
+ def infer_image(self, raw_image, input_size=518):
+ image, (h, w) = self.image2tensor(raw_image, input_size)
+
+ depth = self.forward(image)
+
+ depth = F.interpolate(depth[:, None], (h, w), mode="bilinear", align_corners=True)[0, 0]
+
+ return depth.cpu().numpy()
+
+ def image2tensor(self, raw_image, input_size=518):
+ transform = Compose([
+ Resize(
+ width=input_size,
+ height=input_size,
+ resize_target=False,
+ keep_aspect_ratio=True,
+ ensure_multiple_of=14,
+ resize_method='lower_bound',
+ image_interpolation_method=cv2.INTER_CUBIC,
+ ),
+ NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
+ PrepareForNet(),
+ ])
+
+ h, w = raw_image.shape[:2]
+
+ image = cv2.cvtColor(raw_image, cv2.COLOR_BGR2RGB) / 255.0
+
+ image = transform({'image': image})['image']
+ image = torch.from_numpy(image).unsqueeze(0)
+
+ DEVICE = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
+ image = image.to(DEVICE)
+
+ return image, (h, w)
diff --git a/depth_anything_v2/util/blocks.py b/depth_anything_v2/util/blocks.py
new file mode 100644
index 0000000000000000000000000000000000000000..382ea183a40264056142afffc201c992a2b01d37
--- /dev/null
+++ b/depth_anything_v2/util/blocks.py
@@ -0,0 +1,148 @@
+import torch.nn as nn
+
+
+def _make_scratch(in_shape, out_shape, groups=1, expand=False):
+ scratch = nn.Module()
+
+ out_shape1 = out_shape
+ out_shape2 = out_shape
+ out_shape3 = out_shape
+ if len(in_shape) >= 4:
+ out_shape4 = out_shape
+
+ if expand:
+ out_shape1 = out_shape
+ out_shape2 = out_shape * 2
+ out_shape3 = out_shape * 4
+ if len(in_shape) >= 4:
+ out_shape4 = out_shape * 8
+
+ scratch.layer1_rn = nn.Conv2d(in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
+ scratch.layer2_rn = nn.Conv2d(in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
+ scratch.layer3_rn = nn.Conv2d(in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
+ if len(in_shape) >= 4:
+ scratch.layer4_rn = nn.Conv2d(in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
+
+ return scratch
+
+
+class ResidualConvUnit(nn.Module):
+ """Residual convolution module.
+ """
+
+ def __init__(self, features, activation, bn):
+ """Init.
+
+ Args:
+ features (int): number of features
+ """
+ super().__init__()
+
+ self.bn = bn
+
+ self.groups=1
+
+ self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
+
+ self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
+
+ if self.bn == True:
+ self.bn1 = nn.BatchNorm2d(features)
+ self.bn2 = nn.BatchNorm2d(features)
+
+ self.activation = activation
+
+ self.skip_add = nn.quantized.FloatFunctional()
+
+ def forward(self, x):
+ """Forward pass.
+
+ Args:
+ x (tensor): input
+
+ Returns:
+ tensor: output
+ """
+
+ out = self.activation(x)
+ out = self.conv1(out)
+ if self.bn == True:
+ out = self.bn1(out)
+
+ out = self.activation(out)
+ out = self.conv2(out)
+ if self.bn == True:
+ out = self.bn2(out)
+
+ if self.groups > 1:
+ out = self.conv_merge(out)
+
+ return self.skip_add.add(out, x)
+
+
+class FeatureFusionBlock(nn.Module):
+ """Feature fusion block.
+ """
+
+ def __init__(
+ self,
+ features,
+ activation,
+ deconv=False,
+ bn=False,
+ expand=False,
+ align_corners=True,
+ size=None
+ ):
+ """Init.
+
+ Args:
+ features (int): number of features
+ """
+ super(FeatureFusionBlock, self).__init__()
+
+ self.deconv = deconv
+ self.align_corners = align_corners
+
+ self.groups=1
+
+ self.expand = expand
+ out_features = features
+ if self.expand == True:
+ out_features = features // 2
+
+ self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1)
+
+ self.resConfUnit1 = ResidualConvUnit(features, activation, bn)
+ self.resConfUnit2 = ResidualConvUnit(features, activation, bn)
+
+ self.skip_add = nn.quantized.FloatFunctional()
+
+ self.size=size
+
+ def forward(self, *xs, size=None):
+ """Forward pass.
+
+ Returns:
+ tensor: output
+ """
+ output = xs[0]
+
+ if len(xs) == 2:
+ res = self.resConfUnit1(xs[1])
+ output = self.skip_add.add(output, res)
+
+ output = self.resConfUnit2(output)
+
+ if (size is None) and (self.size is None):
+ modifier = {"scale_factor": 2}
+ elif size is None:
+ modifier = {"size": self.size}
+ else:
+ modifier = {"size": size}
+
+ output = nn.functional.interpolate(output, **modifier, mode="bilinear", align_corners=self.align_corners)
+
+ output = self.out_conv(output)
+
+ return output
diff --git a/depth_anything_v2/util/transform.py b/depth_anything_v2/util/transform.py
new file mode 100644
index 0000000000000000000000000000000000000000..b14aacd44ea086b01725a9ca68bb49eadcf37d73
--- /dev/null
+++ b/depth_anything_v2/util/transform.py
@@ -0,0 +1,158 @@
+import numpy as np
+import cv2
+
+
+class Resize(object):
+ """Resize sample to given size (width, height).
+ """
+
+ def __init__(
+ self,
+ width,
+ height,
+ resize_target=True,
+ keep_aspect_ratio=False,
+ ensure_multiple_of=1,
+ resize_method="lower_bound",
+ image_interpolation_method=cv2.INTER_AREA,
+ ):
+ """Init.
+
+ Args:
+ width (int): desired output width
+ height (int): desired output height
+ resize_target (bool, optional):
+ True: Resize the full sample (image, mask, target).
+ False: Resize image only.
+ Defaults to True.
+ keep_aspect_ratio (bool, optional):
+ True: Keep the aspect ratio of the input sample.
+ Output sample might not have the given width and height, and
+ resize behaviour depends on the parameter 'resize_method'.
+ Defaults to False.
+ ensure_multiple_of (int, optional):
+ Output width and height is constrained to be multiple of this parameter.
+ Defaults to 1.
+ resize_method (str, optional):
+ "lower_bound": Output will be at least as large as the given size.
+ "upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.)
+ "minimal": Scale as least as possible. (Output size might be smaller than given size.)
+ Defaults to "lower_bound".
+ """
+ self.__width = width
+ self.__height = height
+
+ self.__resize_target = resize_target
+ self.__keep_aspect_ratio = keep_aspect_ratio
+ self.__multiple_of = ensure_multiple_of
+ self.__resize_method = resize_method
+ self.__image_interpolation_method = image_interpolation_method
+
+ def constrain_to_multiple_of(self, x, min_val=0, max_val=None):
+ y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)
+
+ if max_val is not None and y > max_val:
+ y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int)
+
+ if y < min_val:
+ y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int)
+
+ return y
+
+ def get_size(self, width, height):
+ # determine new height and width
+ scale_height = self.__height / height
+ scale_width = self.__width / width
+
+ if self.__keep_aspect_ratio:
+ if self.__resize_method == "lower_bound":
+ # scale such that output size is lower bound
+ if scale_width > scale_height:
+ # fit width
+ scale_height = scale_width
+ else:
+ # fit height
+ scale_width = scale_height
+ elif self.__resize_method == "upper_bound":
+ # scale such that output size is upper bound
+ if scale_width < scale_height:
+ # fit width
+ scale_height = scale_width
+ else:
+ # fit height
+ scale_width = scale_height
+ elif self.__resize_method == "minimal":
+ # scale as least as possbile
+ if abs(1 - scale_width) < abs(1 - scale_height):
+ # fit width
+ scale_height = scale_width
+ else:
+ # fit height
+ scale_width = scale_height
+ else:
+ raise ValueError(f"resize_method {self.__resize_method} not implemented")
+
+ if self.__resize_method == "lower_bound":
+ new_height = self.constrain_to_multiple_of(scale_height * height, min_val=self.__height)
+ new_width = self.constrain_to_multiple_of(scale_width * width, min_val=self.__width)
+ elif self.__resize_method == "upper_bound":
+ new_height = self.constrain_to_multiple_of(scale_height * height, max_val=self.__height)
+ new_width = self.constrain_to_multiple_of(scale_width * width, max_val=self.__width)
+ elif self.__resize_method == "minimal":
+ new_height = self.constrain_to_multiple_of(scale_height * height)
+ new_width = self.constrain_to_multiple_of(scale_width * width)
+ else:
+ raise ValueError(f"resize_method {self.__resize_method} not implemented")
+
+ return (new_width, new_height)
+
+ def __call__(self, sample):
+ width, height = self.get_size(sample["image"].shape[1], sample["image"].shape[0])
+
+ # resize sample
+ sample["image"] = cv2.resize(sample["image"], (width, height), interpolation=self.__image_interpolation_method)
+
+ if self.__resize_target:
+ if "depth" in sample:
+ sample["depth"] = cv2.resize(sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST)
+
+ if "mask" in sample:
+ sample["mask"] = cv2.resize(sample["mask"].astype(np.float32), (width, height), interpolation=cv2.INTER_NEAREST)
+
+ return sample
+
+
+class NormalizeImage(object):
+ """Normlize image by given mean and std.
+ """
+
+ def __init__(self, mean, std):
+ self.__mean = mean
+ self.__std = std
+
+ def __call__(self, sample):
+ sample["image"] = (sample["image"] - self.__mean) / self.__std
+
+ return sample
+
+
+class PrepareForNet(object):
+ """Prepare sample for usage as network input.
+ """
+
+ def __init__(self):
+ pass
+
+ def __call__(self, sample):
+ image = np.transpose(sample["image"], (2, 0, 1))
+ sample["image"] = np.ascontiguousarray(image).astype(np.float32)
+
+ if "depth" in sample:
+ depth = sample["depth"].astype(np.float32)
+ sample["depth"] = np.ascontiguousarray(depth)
+
+ if "mask" in sample:
+ sample["mask"] = sample["mask"].astype(np.float32)
+ sample["mask"] = np.ascontiguousarray(sample["mask"])
+
+ return sample
\ No newline at end of file
diff --git a/docs/Customize_Component.md b/docs/Customize_Component.md
new file mode 100644
index 0000000000000000000000000000000000000000..e99a60879920b389799fb3a0baf1fd864ee0bccc
--- /dev/null
+++ b/docs/Customize_Component.md
@@ -0,0 +1,20 @@
+# Customize Components in LLaVA
+
+This is an initial guide on how to replace the LLMs, visual encoders, etc. with your choice of components.
+
+## LLM
+
+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.
+
+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.
+
+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.
+
+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.
+
+These are basically all the changes you need to make to replace the LLM.
+
+## Visual Encoder
+
+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.
+
diff --git a/docs/Data.md b/docs/Data.md
new file mode 100644
index 0000000000000000000000000000000000000000..a13877451bae7a6e774258a2f1753bbecb32b890
--- /dev/null
+++ b/docs/Data.md
@@ -0,0 +1,29 @@
+## Data
+
+| Data file name | Size |
+| --- | ---: |
+| [llava_instruct_150k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_150k.json) | 229 MB |
+| [llava_instruct_80k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_80k.json) | 229 MB |
+| [conversation_58k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/conversation_58k.json) | 126 MB |
+| [detail_23k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/detail_23k.json) | 20.5 MB |
+| [complex_reasoning_77k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/complex_reasoning_77k.json) | 79.6 MB |
+
+### Pretraining Dataset
+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.
+
+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.
+
+| Data | Chat File | Meta Data | Size |
+| --- | --- | --- | ---: |
+| 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
+| 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
+
+**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.
+
+### GPT-4 Prompts
+
+We provide our prompts and few-shot samples for GPT-4 queries, to better facilitate research in this domain. Please check out the [`prompts`](https://github.com/haotian-liu/LLaVA/tree/main/playground/data/prompts) folder for three kinds of questions: conversation, detail description, and complex reasoning.
+
+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.
+
+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!
diff --git a/docs/Evaluation.md b/docs/Evaluation.md
new file mode 100644
index 0000000000000000000000000000000000000000..4bc49735c0c8f6eebb498b7ff8cb93262e1cd5cc
--- /dev/null
+++ b/docs/Evaluation.md
@@ -0,0 +1,167 @@
+# Evaluation
+
+In LLaVA-1.5, we evaluate models on a diverse set of 12 benchmarks. To ensure the reproducibility, we evaluate the models with greedy decoding. We do not evaluate using beam search to make the inference process consistent with the chat demo of real-time outputs.
+
+Currently, we mostly utilize the official toolkit or server for the evaluation.
+
+## Evaluate on Custom Datasets
+
+You can evaluate LLaVA on your custom datasets by converting your dataset to LLaVA's jsonl format, and evaluate using [`model_vqa.py`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/model_vqa.py).
+
+Below we provide a general guideline for evaluating datasets with some common formats.
+
+1. Short-answer (e.g. VQAv2, MME).
+
+```
+
+Answer the question using a single word or phrase.
+```
+
+2. Option-only for multiple-choice (e.g. MMBench, SEED-Bench).
+
+```
+
+A.
+B.
+C.
+D.
+Answer with the option's letter from the given choices directly.
+```
+
+3. Natural QA (e.g. LLaVA-Bench, MM-Vet).
+
+No postprocessing is needed.
+
+## Scripts
+
+Before preparing task-specific data, **you MUST first download [eval.zip](https://drive.google.com/file/d/1atZSBBrAX54yYpxtVVW33zFvcnaHeFPy/view?usp=sharing)**. It contains custom annotations, scripts, and the prediction files with LLaVA v1.5. Extract to `./playground/data/eval`. This also provides a general structure for all datasets.
+
+### VQAv2
+
+1. Download [`test2015`](http://images.cocodataset.org/zips/test2015.zip) and put it under `./playground/data/eval/vqav2`.
+2. Multi-GPU inference.
+```Shell
+CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/v1_5/eval/vqav2.sh
+```
+3. Submit the results to the [evaluation server](https://eval.ai/web/challenges/challenge-page/830/my-submission): `./playground/data/eval/vqav2/answers_upload`.
+
+### GQA
+
+1. Download the [data](https://cs.stanford.edu/people/dorarad/gqa/download.html) and [evaluation scripts](https://cs.stanford.edu/people/dorarad/gqa/evaluate.html) following the official instructions and put under `./playground/data/eval/gqa/data`. You may need to modify `eval.py` as [this](https://gist.github.com/haotian-liu/db6eddc2a984b4cbcc8a7f26fd523187) due to the missing assets in the GQA v1.2 release.
+2. Multi-GPU inference.
+```Shell
+CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/v1_5/eval/gqa.sh
+```
+
+### VisWiz
+
+1. Download [`test.json`](https://vizwiz.cs.colorado.edu/VizWiz_final/vqa_data/Annotations.zip) and extract [`test.zip`](https://vizwiz.cs.colorado.edu/VizWiz_final/images/test.zip) to `test`. Put them under `./playground/data/eval/vizwiz`.
+2. Single-GPU inference.
+```Shell
+CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/vizwiz.sh
+```
+3. Submit the results to the [evaluation server](https://eval.ai/web/challenges/challenge-page/2185/my-submission): `./playground/data/eval/vizwiz/answers_upload`.
+
+### ScienceQA
+
+1. Under `./playground/data/eval/scienceqa`, download `images`, `pid_splits.json`, `problems.json` from the `data/scienceqa` folder of the ScienceQA [repo](https://github.com/lupantech/ScienceQA).
+2. Single-GPU inference and evaluate.
+```Shell
+CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/sqa.sh
+```
+
+### TextVQA
+
+1. Download [`TextVQA_0.5.1_val.json`](https://dl.fbaipublicfiles.com/textvqa/data/TextVQA_0.5.1_val.json) and [images](https://dl.fbaipublicfiles.com/textvqa/images/train_val_images.zip) and extract to `./playground/data/eval/textvqa`.
+2. Single-GPU inference and evaluate.
+```Shell
+CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/textvqa.sh
+```
+
+### POPE
+
+1. Download `coco` from [POPE](https://github.com/AoiDragon/POPE/tree/e3e39262c85a6a83f26cf5094022a782cb0df58d/output/coco) and put under `./playground/data/eval/pope`.
+2. Single-GPU inference and evaluate.
+```Shell
+CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/pope.sh
+```
+
+### MME
+
+1. Download the data following the official instructions [here](https://github.com/BradyFU/Awesome-Multimodal-Large-Language-Models/tree/Evaluation).
+2. Downloaded images to `MME_Benchmark_release_version`.
+3. put the official `eval_tool` and `MME_Benchmark_release_version` under `./playground/data/eval/MME`.
+4. Single-GPU inference and evaluate.
+```Shell
+CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mme.sh
+```
+
+### MMBench
+
+1. Download [`mmbench_dev_20230712.tsv`](https://download.openmmlab.com/mmclassification/datasets/mmbench/mmbench_dev_20230712.tsv) and put under `./playground/data/eval/mmbench`.
+2. Single-GPU inference.
+```Shell
+CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mmbench.sh
+```
+3. Submit the results to the [evaluation server](https://opencompass.org.cn/leaderboard-multimodal): `./playground/data/eval/mmbench/answers_upload/mmbench_dev_20230712`.
+
+### MMBench-CN
+
+1. Download [`mmbench_dev_cn_20231003.tsv`](https://download.openmmlab.com/mmclassification/datasets/mmbench/mmbench_dev_cn_20231003.tsv) and put under `./playground/data/eval/mmbench`.
+2. Single-GPU inference.
+```Shell
+CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mmbench_cn.sh
+```
+3. Submit the results to the evaluation server: `./playground/data/eval/mmbench/answers_upload/mmbench_dev_cn_20231003`.
+
+
+### SEED-Bench
+
+1. Following the official [instructions](https://github.com/AILab-CVC/SEED-Bench/blob/main/DATASET.md) to download the images and the videos. Put images under `./playground/data/eval/seed_bench/SEED-Bench-image`.
+2. Extract the video frame in the middle from the downloaded videos, and put them under `./playground/data/eval/seed_bench/SEED-Bench-video-image`. We provide our script `extract_video_frames.py` modified from the official one.
+3. Multiple-GPU inference and evaluate.
+```Shell
+CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/v1_5/eval/seed.sh
+```
+4. Optionally, submit the results to the leaderboard: `./playground/data/eval/seed_bench/answers_upload` using the official jupyter notebook.
+
+### LLaVA-Bench-in-the-Wild
+
+1. Extract contents of [`llava-bench-in-the-wild`](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild) to `./playground/data/eval/llava-bench-in-the-wild`.
+2. Single-GPU inference and evaluate.
+```Shell
+CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/llavabench.sh
+```
+
+### MM-Vet
+
+1. Extract [`mm-vet.zip`](https://github.com/yuweihao/MM-Vet/releases/download/v1/mm-vet.zip) to `./playground/data/eval/mmvet`.
+2. Single-GPU inference.
+```Shell
+CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mmvet.sh
+```
+3. Evaluate the predictions in `./playground/data/eval/mmvet/results` using the official jupyter notebook.
+
+## More Benchmarks
+
+Below are awesome benchmarks for multimodal understanding from the research community, that are not initially included in the LLaVA-1.5 release.
+
+### Q-Bench
+
+1. Download [`llvisionqa_dev.json`](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/llvisionqa_dev.json) (for `dev`-subset) and [`llvisionqa_test.json`](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/llvisionqa_test.json) (for `test`-subset). Put them under `./playground/data/eval/qbench`.
+2. Download and extract [images](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/images_llvisionqa.tar) and put all the images directly under `./playground/data/eval/qbench/images_llviqionqa`.
+3. Single-GPU inference (change `dev` to `test` for evaluation on test set).
+```Shell
+CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/qbench.sh dev
+```
+4. Submit the results by instruction [here](https://github.com/VQAssessment/Q-Bench#option-1-submit-results): `./playground/data/eval/qbench/llvisionqa_dev_answers.jsonl`.
+
+### Chinese-Q-Bench
+
+1. Download [`่ดจ่กก-้ฎ็ญ-้ช่ฏ้.json`](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/%E8%B4%A8%E8%A1%A1-%E9%97%AE%E7%AD%94-%E9%AA%8C%E8%AF%81%E9%9B%86.json) (for `dev`-subset) and [`่ดจ่กก-้ฎ็ญ-ๆต่ฏ้.json`](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/%E8%B4%A8%E8%A1%A1-%E9%97%AE%E7%AD%94-%E6%B5%8B%E8%AF%95%E9%9B%86.json) (for `test`-subset). Put them under `./playground/data/eval/qbench`.
+2. Download and extract [images](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/images_llvisionqa.tar) and put all the images directly under `./playground/data/eval/qbench/images_llviqionqa`.
+3. Single-GPU inference (change `dev` to `test` for evaluation on test set).
+```Shell
+CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/qbench_zh.sh dev
+```
+4. Submit the results by instruction [here](https://github.com/VQAssessment/Q-Bench#option-1-submit-results): `./playground/data/eval/qbench/llvisionqa_zh_dev_answers.jsonl`.
diff --git a/docs/Finetune_Custom_Data.md b/docs/Finetune_Custom_Data.md
new file mode 100644
index 0000000000000000000000000000000000000000..60baadaaef58ba96987f515b62caebf60a75dd2c
--- /dev/null
+++ b/docs/Finetune_Custom_Data.md
@@ -0,0 +1,37 @@
+# Finetune LLaVA on Custom Datasets
+
+## Dataset Format
+
+Convert your data to a JSON file of a List of all samples. Sample metadata should contain `id` (a unique identifier), `image` (the path to the image), and `conversations` (the conversation data between human and AI).
+
+A sample JSON for finetuning LLaVA for generating tag-style captions for Stable Diffusion:
+
+```json
+[
+ {
+ "id": "997bb945-628d-4724-b370-b84de974a19f",
+ "image": "part-000001/997bb945-628d-4724-b370-b84de974a19f.jpg",
+ "conversations": [
+ {
+ "from": "human",
+ "value": "\nWrite a prompt for Stable Diffusion to generate this image."
+ },
+ {
+ "from": "gpt",
+ "value": "a beautiful painting of chernobyl by nekro, pascal blanche, john harris, greg rutkowski, sin jong hun, moebius, simon stalenhag. in style of cg art. ray tracing. cel shading. hyper detailed. realistic. ue 5. maya. octane render. "
+ },
+ ]
+ },
+ ...
+]
+```
+
+## Command
+
+If you have a limited task-specific data, we recommend finetuning from LLaVA checkpoints with LoRA following this [script](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/finetune_task_lora.sh).
+
+If the amount of the task-specific data is sufficient, you can also finetune from LLaVA checkpoints with full-model finetuning following this [script](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/finetune_task.sh).
+
+You may need to adjust the hyperparameters to fit each specific dataset and your hardware constraint.
+
+
diff --git a/docs/Intel.md b/docs/Intel.md
new file mode 100644
index 0000000000000000000000000000000000000000..c759e4098aa06f89d04199182702176aa4c64b12
--- /dev/null
+++ b/docs/Intel.md
@@ -0,0 +1,7 @@
+# Intel Platforms
+
+* Support [Intel GPU Max Series](https://www.intel.com/content/www/us/en/products/details/discrete-gpus/data-center-gpu/max-series.html)
+* Support [Intel CPU Sapphire Rapides](https://ark.intel.com/content/www/us/en/ark/products/codename/126212/products-formerly-sapphire-rapids.html)
+* Based on [Intel Extension for Pytorch](https://intel.github.io/intel-extension-for-pytorch)
+
+More details in [**intel branch**](https://github.com/haotian-liu/LLaVA/tree/intel/docs/intel)
diff --git a/docs/LLaVA_Bench.md b/docs/LLaVA_Bench.md
new file mode 100644
index 0000000000000000000000000000000000000000..643fee99cd6252e2f53353b9744f3ad392e5db4f
--- /dev/null
+++ b/docs/LLaVA_Bench.md
@@ -0,0 +1,31 @@
+# LLaVA-Bench [[Download](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild)]
+
+**-Introduction-** Large commercial multimodal chatbots have been released in this week, including
+- [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)
+- [Multimodal Bard by Google](https://bard.google.com/).
+
+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 explored 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.
+
+## LLaVA-Bench (In-the-Wild *[Ongoing work]*)
+
+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.
+
+### Results
+
+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.
+
+| Approach | Conversation | Detail | Reasoning | Overall |
+|----------------|--------------|--------|-----------|---------|
+| Bard-0718 | 83.7 | 69.7 | 78.7 | 77.8 |
+| Bing-Chat-0629 | 59.6 | 52.2 | 90.1 | 71.5 |
+| LLaVA-13B-v1-336px-0719 (beam=1) | 64.3 | 55.9 | 81.7 | 70.1 |
+| LLaVA-13B-v1-336px-0719 (beam=5) | 68.4 | 59.9 | 84.3 | 73.5 |
+
+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.
+
+| Approach | Conversation | Detail | Reasoning | Overall |
+|----------------|--------------|--------|-----------|---------|
+| Bard-0718 | 94.9 | 74.3 | 84.3 | 84.6 |
+| Bing-Chat-0629 | 55.8 | 53.6 | 93.5 | 72.6 |
+| LLaVA-13B-v1-336px-0719 (beam=1) | 62.2 | 56.4 | 82.2 | 70.0 |
+| LLaVA-13B-v1-336px-0719 (beam=5) | 65.6 | 61.7 | 85.0 | 73.6 |
diff --git a/docs/LLaVA_from_LLaMA2.md b/docs/LLaVA_from_LLaMA2.md
new file mode 100644
index 0000000000000000000000000000000000000000..214754bf2f206c2d95ff744429d49420e2745d19
--- /dev/null
+++ b/docs/LLaVA_from_LLaMA2.md
@@ -0,0 +1,29 @@
+# LLaVA (based on Llama 2 LLM, Preview)
+
+*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.*
+
+: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.
+
+You need to apply for and download the latest Llama 2 checkpoints to start your own training (apply [here](https://ai.meta.com/resources/models-and-libraries/llama-downloads/))
+
+
+## Training
+
+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).
+
+## LLaVA (based on Llama 2), What is different?
+
+:volcano: How is the new LLaVA based on Llama 2 different from Llama 1? The comparisons of the training process are described:
+- **Pre-training**. The pre-trained base LLM is changed from Llama 1 to Llama 2
+- **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.
+- **Multimodal instruction-tuning**. The same LLaVA-Lighting process is applied.
+
+
+### Results
+
+- Llama 2 is better at following the instructions of role playing; Llama 2 fails in following the instructions of translation
+- 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.
+
+
+
+
diff --git a/docs/LoRA.md b/docs/LoRA.md
new file mode 100644
index 0000000000000000000000000000000000000000..bed25f57d0aaa8c37f63703f6f641999b02b1b3e
--- /dev/null
+++ b/docs/LoRA.md
@@ -0,0 +1,46 @@
+# LLaVA (LoRA, Preview)
+
+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.
+
+You need latest code base for LoRA support (instructions [here](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base))
+
+## Demo (Web UI)
+
+Please execute each of the commands 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)).
+
+#### Launch a controller
+```Shell
+python -m llava.serve.controller --host 0.0.0.0 --port 10000
+```
+
+#### Launch a gradio web server.
+```Shell
+python -m llava.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload
+```
+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.
+
+#### Launch a model worker
+```Shell
+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
+```
+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.
+
+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.
+
+
+## Training
+
+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).
+
+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.
+
+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.
+
+## Create Merged Checkpoints
+
+```Shell
+python scripts/merge_lora_weights.py \
+ --model-path /path/to/lora_model \
+ --model-base /path/to/base_model \
+ --save-model-path /path/to/merge_model
+```
diff --git a/docs/MODEL_ZOO.md b/docs/MODEL_ZOO.md
new file mode 100644
index 0000000000000000000000000000000000000000..2d870e6c0b8e97dc08d4e1b6a2d4ca0af9185ee1
--- /dev/null
+++ b/docs/MODEL_ZOO.md
@@ -0,0 +1,150 @@
+# Model Zoo
+
+**To Use LLaVA-1.6 checkpoints, your llava package version must be newer than 1.2.0. [Instructions](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base) on how to upgrade.**
+
+If you are interested in including any other details in Model Zoo, please open an issue :)
+
+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.
+
+## LLaVA-v1.6
+
+| Version | LLM | Schedule | Checkpoint | MMMU | MathVista | VQAv2 | GQA | VizWiz | SQA | TextVQA | POPE | MME | MM-Bench | MM-Bench-CN | SEED-IMG | LLaVA-Bench-Wild | MM-Vet |
+|----------|----------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
+| LLaVA-1.6 | Vicuna-7B | full_ft-1e | [liuhaotian/llava-v1.6-vicuna-7b](https://huggingface.co/liuhaotian/llava-v1.6-vicuna-7b) | 35.8 | 34.6 | 81.8 | 64.2 | 57.6 | 70.1 | 64.9 | 86.5 | 1519/332 | 67.4 | 60.6 | 70.2 | 81.6 | 43.9 |
+| LLaVA-1.6 | Vicuna-13B | full_ft-1e | [liuhaotian/llava-v1.6-vicuna-13b](https://huggingface.co/liuhaotian/llava-v1.6-vicuna-13b) | 36.2 | 35.3 | 82.8 | 65.4 | 60.5 | 73.6 | 67.1 | 86.2 | 1575/326 | 70 | 64.4 | 71.9 | 87.3 | 48.4 |
+| LLaVA-1.6 | Mistral-7B | full_ft-1e | [liuhaotian/llava-v1.6-mistral-7b](https://huggingface.co/liuhaotian/llava-v1.6-mistral-7b) | 35.3 | 37.7 | 82.2 | 64.8 | 60.0 | 72.8 | 65.7 | 86.7 | 1498/321 | 68.7 | 61.2 | 72.2 | 83.2 | 47.3 |
+| LLaVA-1.6 | Hermes-Yi-34B | full_ft-1e | [liuhaotian/llava-v1.6-34b](https://huggingface.co/liuhaotian/llava-v1.6-34b) | 51.1 | 46.5 | 83.7 | 67.1 | 63.8 | 81.8 | 69.5 | 87.7 | 1631/397 | 79.3 | 79 | 75.9 | 89.6 | 57.4 |
+
+*LLaVA-1.6-34B outperforms Gemini Pro on benchmarks like MMMU and MathVista.*
+
+
+## LLaVA-v1.5
+
+| Version | Size | Schedule | Checkpoint | VQAv2 | GQA | VizWiz | SQA | TextVQA | POPE | MME | MM-Bench | MM-Bench-CN | SEED | LLaVA-Bench-Wild | MM-Vet |
+|----------|----------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---|
+| 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 | 65.4 | 31.1 |
+| 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 | 72.5 | 36.1 |
+| LLaVA-1.5 | 7B | lora-1e | [liuhaotian/llava-v1.5-7b-lora](https://huggingface.co/liuhaotian/llava-v1.5-7b-lora) | 79.1 | 63.0 | 47.8 | 68.4 | 58.2 | 86.4 | 1476.9 | 66.1 | 58.9 | 60.1 | 67.9 | 30.2 |
+| LLaVA-1.5 | 13B | lora-1e | [liuhaotian/llava-v1.5-13b-lora](https://huggingface.co/liuhaotian/llava-v1.5-13b-lora) | 80.0 | 63.3 | 58.9 | 71.2 | 60.2 | 86.7 | 1541.7 | 68.5 | 61.5 | 61.3 | 69.5 | 38.3 |
+
+Base model: Vicuna v1.5. Training logs: [wandb](https://api.wandb.ai/links/lht/6orh56wc).
+
+
+
+ LLaVA-1.5 achieves SoTA performance across 11 benchmarks.
+
+
+
+## LLaVA-v1
+
+*Note: We recommend using the most capable LLaVA-v1.6 series above for the best performance.*
+
+| 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 |
+|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|--------------------|---------------------|---------------------|---------------------|
+| 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) |
+| 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) |
+| 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) |
+
+
+## Projector weights
+
+These are projector weights we have pretrained. You can use these projector weights for visual instruction tuning. They are just pretrained on image-text pairs and are NOT instruction-tuned, which means they do NOT follow instructions as well as our official models and can output repetitive, lengthy, and garbled outputs. If you want to have nice conversations with LLaVA, use the checkpoints above (LLaVA v1.6).
+
+NOTE: These projector weights are only compatible with `llava>=1.0.0`. Please check out the latest codebase if your local code version is below v1.0.0.
+
+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 poor.
+
+When using these projector weights to instruction-tune your LMM, please make sure that these options are correctly set as follows,
+
+```Shell
+--mm_use_im_start_end False
+--mm_use_im_patch_token False
+```
+
+| Base LLM | Vision Encoder | Projection | Pretrain Data | Pretraining schedule | Download |
+|----------|----------------|---------------|----------------------|----------|----------|
+| 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) |
+| 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) |
+| LLaMA-2-13B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-13b-chat) |
+| LLaMA-2-7B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-7b-chat) |
+| LLaMA-2-13B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-13b-chat) |
+| LLaMA-2-7B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-7b-chat) |
+| Vicuna-13B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-13b-v1.3) |
+| Vicuna-7B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-7b-v1.3) |
+| Vicuna-13B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-13b-v1.3) |
+| Vicuna-7B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-7b-v1.3) |
+
+
+## Science QA Checkpoints
+
+| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
+|----------|----------------|---------------|----------------------|-----------------|--------------------|---------------------|
+| 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) |
+
+
+## Legacy Models (merged weights)
+
+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.
+
+| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
+|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|
+| MPT-7B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | [preview](https://huggingface.co/liuhaotian/LLaVA-Lightning-MPT-7B-preview) |
+
+
+## Legacy Models (delta weights)
+
+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).
+
+You can add our delta to the original LLaMA weights to obtain the LLaVA weights.
+
+Instructions:
+
+1. Get the original LLaMA weights in the huggingface format by following the instructions [here](https://huggingface.co/docs/transformers/main/model_doc/llama).
+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).
+
+```bash
+python3 -m llava.model.apply_delta \
+ --base /path/to/llama-7b \
+ --target /output/path/to/LLaVA-7B-v0 \
+ --delta liuhaotian/LLaVA-7b-delta-v0
+```
+
+| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
+|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|
+| 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) |
+| 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) |
+| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0) |
+| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | ScienceQA | full_ft-12e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0-science_qa) |
+| Vicuna-7B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-7b-delta-v0) |
+
+
+
+## Legacy Projector weights
+
+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.
+
+**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.
+
+When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows,
+
+```Shell
+--mm_use_im_start_end True
+--mm_use_im_patch_token False
+```
+
+| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download |
+|----------|----------------|---------------|----------------------|----------|
+| 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) |
+| 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) |
+| 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) |
+
+When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows,
+
+```Shell
+--mm_use_im_start_end False
+--mm_use_im_patch_token False
+```
+
+| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download |
+|----------|----------------|---------------|----------------------|----------|
+| 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) |
diff --git a/docs/ScienceQA.md b/docs/ScienceQA.md
new file mode 100644
index 0000000000000000000000000000000000000000..8881c41c67002a3798435b051c9a609dd1c0d506
--- /dev/null
+++ b/docs/ScienceQA.md
@@ -0,0 +1,53 @@
+### ScienceQA
+
+#### Prepare Data
+1. Please see ScienceQA [repo](https://github.com/lupantech/ScienceQA) for setting up the dataset.
+2. Generate ScienceQA dataset for LLaVA conversation-style format.
+
+```Shell
+python scripts/convert_sqa_to_llava.py \
+ convert_to_llava \
+ --base-dir /path/to/ScienceQA/data/scienceqa \
+ --prompt-format "QCM-LEA" \
+ --split {train,val,minival,test,minitest}
+```
+
+#### Training
+
+1. Pretraining
+
+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).
+
+2. Finetuning
+
+See [`finetune_sqa.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_sqa.sh).
+
+#### Evaluation
+
+1. Multiple-GPU inference
+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).
+
+2. Single-GPU inference
+
+(a) Generate LLaVA responses on ScienceQA dataset
+
+```Shell
+python -m llava.eval.model_vqa_science \
+ --model-path liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3 \
+ --question-file /path/to/ScienceQA/data/scienceqa/llava_test_QCM-LEA.json \
+ --image-folder /path/to/ScienceQA/data/scienceqa/images/test \
+ --answers-file vqa/results/ScienceQA/test_llava-13b.jsonl \
+ --conv-mode llava_v1
+```
+
+(b) Evaluate the generated responses
+
+```Shell
+python eval_science_qa.py \
+ --base-dir /path/to/ScienceQA/data/scienceqa \
+ --result-file vqa/results/ScienceQA/test_llava-13b.jsonl \
+ --output-file vqa/results/ScienceQA/test_llava-13b_output.json \
+ --output-result vqa/results/ScienceQA/test_llava-13b_result.json \
+```
+
+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.
diff --git a/docs/Windows.md b/docs/Windows.md
new file mode 100644
index 0000000000000000000000000000000000000000..355ab81ffa1a73e874f3a8fb85d2742896068d08
--- /dev/null
+++ b/docs/Windows.md
@@ -0,0 +1,27 @@
+# Run LLaVA on Windows
+
+*NOTE: LLaVA on Windows is not fully supported. Currently we only support 16-bit inference. For a more complete support, please use [WSL2](https://learn.microsoft.com/en-us/windows/wsl/install) for now. More functionalities on Windows is to be added soon, stay tuned.*
+
+## Installation
+
+1. Clone this repository and navigate to LLaVA folder
+```bash
+git clone https://github.com/haotian-liu/LLaVA.git
+cd LLaVA
+```
+
+2. Install Package
+```Shell
+conda create -n llava python=3.10 -y
+conda activate llava
+python -m pip install --upgrade pip # enable PEP 660 support
+pip install torch==2.0.1+cu117 torchvision==0.15.2+cu117 torchaudio==2.0.2 --index-url https://download.pytorch.org/whl/cu117
+pip install -e .
+pip uninstall bitsandbytes
+```
+
+## Run demo
+
+See instructions [here](https://github.com/haotian-liu/LLaVA#demo).
+
+Note that quantization (4-bit, 8-bit) is *NOT* supported on Windows. Stay tuned for the 4-bit support on Windows!
diff --git a/docs/macOS.md b/docs/macOS.md
new file mode 100644
index 0000000000000000000000000000000000000000..0008e5e7cf52e99d85388ef7f0f77d76940c8cef
--- /dev/null
+++ b/docs/macOS.md
@@ -0,0 +1,29 @@
+# Run LLaVA on macOS
+
+*NOTE: LLaVA on macOS is not fully supported. Currently we only support 16-bit inference. More functionalities on macOS is to be added soon, stay tuned.*
+
+## Installation
+
+1. Clone this repository and navigate to LLaVA folder
+```bash
+git clone https://github.com/haotian-liu/LLaVA.git
+cd LLaVA
+```
+
+2. Install Package
+```Shell
+conda create -n llava python=3.10 -y
+conda activate llava
+python -mpip install --upgrade pip # enable PEP 660 support
+pip install -e .
+pip install torch==2.1.0 torchvision==0.16.0
+pip uninstall bitsandbytes
+```
+
+## Run demo
+
+Specify `--device mps` when launching model worker or CLI.
+
+See instructions [here](https://github.com/haotian-liu/LLaVA#demo).
+
+Note that quantization (4-bit, 8-bit) is *NOT* supported on macOS. Stay tuned for the 4-bit support on macOS!
diff --git a/eval.sh b/eval.sh
new file mode 100644
index 0000000000000000000000000000000000000000..574601cd9bf9b07df23e055710d98a9717fd0ea9
--- /dev/null
+++ b/eval.sh
@@ -0,0 +1,4 @@
+source /home/aiops/wangzh/miniconda3/bin/activate
+conda activate llava
+CUDA_VISIBLE_DEVICES=0 python -m rgbd_eval.py
+python new_check.py
\ No newline at end of file
diff --git a/finetune.sh b/finetune.sh
new file mode 100644
index 0000000000000000000000000000000000000000..451d442c002c5afe56e6598884b4554a2c3e8556
--- /dev/null
+++ b/finetune.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+deepspeed llava/train/train_mem.py \
+ --deepspeed ./scripts/zero2.json \
+ --lora_enable True --lora_r 128 --lora_alpha 256 --mm_projector_lr 2e-5 \
+ --model_name_or_path /home/aiops/wangzh/llava/vicuna-7b-v1.5 \
+ --version v1 \
+ --data_path /home/aiops/wangzh/llava/playground/data/llava_v1_5_mix665k.json \
+ --image_folder /home/aiops/wangzh/llava/playground/data \
+ --vision_tower openai/clip-vit-large-patch14-336 \
+ --pretrain_mm_mlp_adapter ./checkpoints/llava-v1.5-7b-pretrain-negfinal/mm_projector.bin \
+ --mm_projector_type mlp2x_gelu \
+ --mm_vision_select_layer -2 \
+ --mm_use_im_start_end False \
+ --mm_use_im_patch_token False \
+ --image_aspect_ratio pad \
+ --group_by_modality_length True \
+ --bf16 True \
+ --output_dir ./checkpoints/llava-v1.5-7b-final-neg-lora-newl \
+ --num_train_epochs 1 \
+ --per_device_train_batch_size 16\
+ --per_device_eval_batch_size 8 \
+ --gradient_accumulation_steps 1 \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 10 \
+ --save_total_limit 1 \
+ --learning_rate 2e-4 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --tf32 True \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --lazy_preprocess True \
+ --report_to wandb
diff --git a/gemini_test.py b/gemini_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..762dfcf04cc3488d1c6a6b7bbade2f5c60674469
--- /dev/null
+++ b/gemini_test.py
@@ -0,0 +1,177 @@
+import requests
+import json
+import base64
+import os
+import time
+import pandas as pd
+from tqdm import tqdm
+from concurrent.futures import ThreadPoolExecutor
+
+DEBUG = True
+
+SK_LIST = [
+ "sk-V8HaW6l4a6qkTRlR07423f3c8c67431c8a9d9c365c0b7d9b",
+ "sk-MZQXlv5tEG5hDX3yoK6sKRB4P9JBuw8PWtbeix1JITHWzIxW",
+ "sk-NgALyBkzs6LPt5kbvLS8WBILov33pL2rB6J5bLTI4FBk7O2p",
+ "sk-MEuJz0u5CyFyVgEP9CvUPhybfkP9eQg8iak82OU9pN6GC0xH",
+]
+
+COCO_ROOT = '/root/autodl-tmp/data/location_bench1/coco_resize/' # ๆ นๆฎ้่ฆไฟฎๆน่ทฏๅพ
+
+# ๅฐๅพ็่ฝฌbase64ๆ ผๅผ
+def encode_image(image_path):
+ with open(image_path, "rb") as image_file:
+ return base64.b64encode(image_file.read()).decode('utf-8')
+
+def gemini_label(question, img,idx, sk, attempt=0):
+ if attempt > 5:
+ return None
+
+ # ๆๅปบๅพ็่ทฏๅพๅนถ็ผ็ ไธบbase64
+ # image_path = os.path.join(COCO_ROOT, 'val{0:06}.jpg'.format(idx)) # ๆ นๆฎ้่ฆไฟฎๆน่ทฏๅพ
+ # image_path = f'/home/aiops/wangzh/data/RGBD-benchmark/out_doors/pic_all/{img}'
+ image_path = img
+ # image_path = '/home/aiops/wangzh/data/RGBD-benchmark/out_doors/pic_all/1_gpt4o.png'
+ base64_image = encode_image(image_path)
+ # import pdb;pdb.set_trace()
+ url = "https://open.xiaojingai.com/v1/chat/completions" # ๆฟๆขไธบๆฐAPI็URL
+ # "text": f'''You will see an image along with four corresponding descriptions (captions). Please carefully observe the image and select the description that best matches the content of the image. Choose one option from (A), (B), (C), or (D).
+ # Options: (A){question[0]}\n(B){question[1]}\n(C){question[2]}\n(D){question[3]}\nPlease provide your answer with only one of the options and nothing else.'''
+ try:
+ # ๆๅปบ่ฏทๆฑไฝ
+ # payload = json.dumps({
+ # "image": f"data:image/jpeg;base64,{base64_image}",
+ # "question": question
+ # })
+ payload = json.dumps({
+ "model": "gemini-1.5-pro",
+ # "model": "gpt-4o",
+ "stream": False,
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": f'''You will see an image along with four corresponding descriptions (captions). Please carefully observe the image and select the description that best matches the content of the image. Choose one option from (A), (B), (C), or (D).
+ Options: (A){question[0]}\n(B){question[1]}\n(C){question[2]}\n(D){question[3]}\nPlease provide your answer with only one of the options and nothing else.'''
+
+ },
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": f"data:image/jpeg;base64,{base64_image}"
+ }
+ }
+ ]
+ }
+ ],
+ "max_tokens": 1000
+ })
+ headers = {
+ 'Authorization': sk,
+ 'Content-Type': 'application/json'
+ }
+
+ # ๅ้POST่ฏทๆฑ
+ response = requests.post(url, headers=headers, data=payload)
+ print(response)
+ print("Response Status Code:", response.status_code) # ๆๅฐ็ถๆ็
+ print("Response Text:", response.text) # ๆๅฐๅๅบๅ ๅฎน
+ output = response.json() # ่ทๅๅ็ญ
+ print("output",output)
+ return {"id": idx, "answer": output}
+
+ except Exception as ex:
+ print(idx, ex)
+ time.sleep(2) # ็ญๅพ ๅ้่ฏ
+ return gemini_label(question, idx, sk, attempt + 1) # ้่ฏ
+
+def process_sample(i, img,questions, sk):
+ uid = uids[i]
+ question = questions[i]
+ img = img[i]
+ # import pdb;pdb.set_trace()
+ ans = gemini_label(question, img,uid, sk=sk)
+ return ans if ans is not None else 'None'
+
+if __name__ == '__main__':
+ save_path = './'
+ os.makedirs(os.path.join(save_path), exist_ok=True)
+
+ # meta_path = '/home/aiops/wangzh/data/RGBD-benchmark/out_doors/all.json'
+ meta_path = '/home/aiops/wangzh/data/scanner/indoor-new/all.json'
+ # meta = pd.read_csv(meta_path)
+ with open(meta_path, 'r', encoding='utf-8') as json_file:
+ meta = json.load(json_file)
+ import pdb;pdb.set_trace()
+ lens=len(meta)
+ uids = [meta[i]['id'] for i in range(lens)]
+ questions =[meta[i]['captions'] for i in range(lens)]
+ img = [meta[i]['image'] for i in range(lens)]
+ # print('get samples:', len(uids))
+ # print(uids[:5])
+ # img = [f'/home/aiops/wangzh/data/scanner/scannet_2d_HR3/{meta[i]['scene_id']}/color/{meta[i]['image']}' for i in range(lens)]
+ img = [f'/home/aiops/wangzh/data/scanner/scannet_2d_HR3/{meta[i]["scene_id"]}/color/{meta[i]["image"]}' for i in range(lens)]
+
+ answer_list = []
+
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ answer_list = list(tqdm(executor.map(lambda i: process_sample(i, img,questions, SK_LIST[i % 4]), range(len(uids))), total=len(uids)))
+
+ print('gemini label sample:', len(answer_list))
+ answer_list = pd.DataFrame(answer_list)
+ answer_list.to_csv(os.path.join(save_path, 'answers.csv'), index=False)
+
+
+
+# import requests
+# import json
+# import base64
+# import os
+
+# def encode_image(image_path):
+# with open(image_path, "rb") as image_file:
+# return base64.b64encode(image_file.read()).decode('utf-8')
+
+# def ask_question(image_path, caption, sk):
+# base64_image = encode_image(image_path)
+# url = "https://open.xiaojingai.com/v1/chat/completions"
+
+# payload = json.dumps({
+# "model": "gemini-1.5-pro",
+# "stream": False,
+# "messages": [
+# {
+# "role": "user",
+# "content": [
+# {
+# "type": "text",
+# "text":"describe what is love"
+# },
+# {
+# "type": "image_url",
+# "image_url": {
+# "url": f"data:image/jpeg;base64,{base64_image}"
+# }
+# }
+# ]
+# }
+# ],
+# "max_tokens": 1000
+# })
+
+# headers = {
+# 'Authorization': sk,
+# 'Content-Type': 'application/json'
+# }
+
+# response = requests.post(url, headers=headers, data=payload)
+# return response.json()
+
+# # Example usage
+# image_path = '/home/aiops/wangzh/data/RGBD-benchmark/out_doors/pic_all/1_gpt4o.png'
+# caption = "Describe the content of the image."
+# sk = "sk-V8HaW6l4a6qkTRlR07423f3c8c67431c8a9d9c365c0b7d9b"
+# response = ask_question(image_path, caption, sk)
+# print(response)
\ No newline at end of file
diff --git a/images/demo_cli.gif b/images/demo_cli.gif
new file mode 100644
index 0000000000000000000000000000000000000000..7415fabbfc29c6a228a44a87069c5f342ba594f2
--- /dev/null
+++ b/images/demo_cli.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:09227563f4fe04f077587eeb7b7c33ace2fbb8830e6cc9cfce03a25a57c43bfe
+size 10049954
diff --git a/images/llava_example_cmp.png b/images/llava_example_cmp.png
new file mode 100644
index 0000000000000000000000000000000000000000..b354be1874dad47a6bdef1f43cf84e2be4197856
Binary files /dev/null and b/images/llava_example_cmp.png differ
diff --git a/images/llava_logo.png b/images/llava_logo.png
new file mode 100644
index 0000000000000000000000000000000000000000..567428adb29c03dd83c1f08be6b4e972af453630
Binary files /dev/null and b/images/llava_logo.png differ
diff --git a/images/llava_v1_5_radar.jpg b/images/llava_v1_5_radar.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..4018fb008ffa2ad0a8ff8c28ce6729d77076c3bf
Binary files /dev/null and b/images/llava_v1_5_radar.jpg differ
diff --git a/llava-v1.5-7b-final-neg-lora_answers.txt b/llava-v1.5-7b-final-neg-lora_answers.txt
new file mode 100644
index 0000000000000000000000000000000000000000..1cfabfe841b39d5fdcb7f183c0c6df801afa774b
--- /dev/null
+++ b/llava-v1.5-7b-final-neg-lora_answers.txt
@@ -0,0 +1,159 @@
+A
+A
+A
+A
+A
+B
+B
+A
+A
+D
+D
+B
+D
+B
+C
+B
+B
+D
+C
+A
+A
+C
+C
+B
+A
+A
+C
+B
+C
+A
+C
+C
+C
+B
+B
+D
+B
+A
+C
+C
+B
+C
+B
+B
+C
+B
+B
+A
+A
+C
+C
+A
+A
+C
+B
+C
+B
+C
+B
+C
+B
+C
+B
+B
+B
+B
+B
+B
+C
+C
+C
+D
+B
+B
+A
+C
+C
+A
+A
+B
+C
+B
+A
+C
+C
+A
+A
+A
+C
+B
+A
+C
+C
+B
+A
+A
+A
+C
+B
+C
+A
+C
+C
+C
+(B)
+C
+B
+(C)
+A
+A
+A
+A
+A
+B
+B
+B
+C
+A
+A
+B
+B
+A
+A
+C
+D
+A
+B
+B
+B
+A
+B
+B
+B
+C
+A
+A
+B
+C
+A
+B
+C
+B
+A
+B
+B
+A
+C
+A
+B
+B
+C
+C
+A
+B
+A
+B
+B
+B
+B
diff --git a/llava/__init__.py b/llava/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d1f016db1028101d45ba7d68cb3f0bcb558c2bb
--- /dev/null
+++ b/llava/__init__.py
@@ -0,0 +1 @@
+from .model import LlavaLlamaForCausalLM
diff --git a/llava/constants.py b/llava/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..374be090510b302de9882d880c755787a8eafe11
--- /dev/null
+++ b/llava/constants.py
@@ -0,0 +1,13 @@
+CONTROLLER_HEART_BEAT_EXPIRATION = 30
+WORKER_HEART_BEAT_INTERVAL = 15
+
+LOGDIR = "."
+
+# Model Constants
+IGNORE_INDEX = -100
+IMAGE_TOKEN_INDEX = -200
+DEFAULT_IMAGE_TOKEN = ""
+DEFAULT_IMAGE_PATCH_TOKEN = ""
+DEFAULT_IM_START_TOKEN = ""
+DEFAULT_IM_END_TOKEN = ""
+IMAGE_PLACEHOLDER = ""
diff --git a/llava/conversation.py b/llava/conversation.py
new file mode 100644
index 0000000000000000000000000000000000000000..00c56867dd1fd88094df9556f3d1c57e71a7ada8
--- /dev/null
+++ b/llava/conversation.py
@@ -0,0 +1,396 @@
+import dataclasses
+from enum import auto, Enum
+from typing import List, Tuple
+import base64
+from io import BytesIO
+from PIL import Image
+
+
+class SeparatorStyle(Enum):
+ """Different separator style."""
+ SINGLE = auto()
+ TWO = auto()
+ MPT = auto()
+ PLAIN = auto()
+ LLAMA_2 = auto()
+
+
+@dataclasses.dataclass
+class Conversation:
+ """A class that keeps all conversation history."""
+ system: str
+ roles: List[str]
+ messages: List[List[str]]
+ offset: int
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
+ sep: str = "###"
+ sep2: str = None
+ version: str = "Unknown"
+
+ skip_next: bool = False
+
+ def get_prompt(self):
+ messages = self.messages
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
+ messages = self.messages.copy()
+ init_role, init_msg = messages[0].copy()
+ init_msg = init_msg[0].replace("", "").strip()
+ if 'mmtag' in self.version:
+ messages[0] = (init_role, init_msg)
+ messages.insert(0, (self.roles[0], ""))
+ messages.insert(1, (self.roles[1], "Received."))
+ else:
+ messages[0] = (init_role, "\n" + init_msg)
+
+ if self.sep_style == SeparatorStyle.SINGLE:
+ ret = self.system + self.sep
+ for role, message in messages:
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ ret += role + ": " + message + self.sep
+ else:
+ ret += role + ":"
+ elif self.sep_style == SeparatorStyle.TWO:
+ seps = [self.sep, self.sep2]
+ ret = self.system + seps[0]
+ for i, (role, message) in enumerate(messages):
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ ret += role + ": " + message + seps[i % 2]
+ else:
+ ret += role + ":"
+ elif self.sep_style == SeparatorStyle.MPT:
+ ret = self.system + self.sep
+ for role, message in messages:
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ ret += role + message + self.sep
+ else:
+ ret += role
+ elif self.sep_style == SeparatorStyle.LLAMA_2:
+ wrap_sys = lambda msg: f"<>\n{msg}\n<>\n\n" if len(msg) > 0 else msg
+ wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
+ ret = ""
+
+ for i, (role, message) in enumerate(messages):
+ if i == 0:
+ assert message, "first message should not be none"
+ assert role == self.roles[0], "first message should come from user"
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ if i == 0: message = wrap_sys(self.system) + message
+ if i % 2 == 0:
+ message = wrap_inst(message)
+ ret += self.sep + message
+ else:
+ ret += " " + message + " " + self.sep2
+ else:
+ ret += ""
+ ret = ret.lstrip(self.sep)
+ elif self.sep_style == SeparatorStyle.PLAIN:
+ seps = [self.sep, self.sep2]
+ ret = self.system
+ for i, (role, message) in enumerate(messages):
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ ret += message + seps[i % 2]
+ else:
+ ret += ""
+ else:
+ raise ValueError(f"Invalid style: {self.sep_style}")
+
+ return ret
+
+ def append_message(self, role, message):
+ self.messages.append([role, message])
+
+ def process_image(self, image, image_process_mode, return_pil=False, image_format='PNG', max_len=1344, min_len=672):
+ if image_process_mode == "Pad":
+ def expand2square(pil_img, background_color=(122, 116, 104)):
+ width, height = pil_img.size
+ if width == height:
+ return pil_img
+ elif width > height:
+ result = Image.new(pil_img.mode, (width, width), background_color)
+ result.paste(pil_img, (0, (width - height) // 2))
+ return result
+ else:
+ result = Image.new(pil_img.mode, (height, height), background_color)
+ result.paste(pil_img, ((height - width) // 2, 0))
+ return result
+ image = expand2square(image)
+ elif image_process_mode in ["Default", "Crop"]:
+ pass
+ elif image_process_mode == "Resize":
+ image = image.resize((336, 336))
+ else:
+ raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
+ if max(image.size) > max_len:
+ max_hw, min_hw = max(image.size), min(image.size)
+ aspect_ratio = max_hw / min_hw
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
+ longest_edge = int(shortest_edge * aspect_ratio)
+ W, H = image.size
+ if H > W:
+ H, W = longest_edge, shortest_edge
+ else:
+ H, W = shortest_edge, longest_edge
+ image = image.resize((W, H))
+ if return_pil:
+ return image
+ else:
+ buffered = BytesIO()
+ image.save(buffered, format=image_format)
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
+ return img_b64_str
+
+ def get_images(self, return_pil=False):
+ images = []
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
+ if i % 2 == 0:
+ if type(msg) is tuple:
+ msg, image, image_process_mode = msg
+ image = self.process_image(image, image_process_mode, return_pil=return_pil)
+ images.append(image)
+ return images
+
+ def to_gradio_chatbot(self):
+ ret = []
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
+ if i % 2 == 0:
+ if type(msg) is tuple:
+ msg, image, image_process_mode = msg
+ img_b64_str = self.process_image(
+ image, "Default", return_pil=False,
+ image_format='JPEG')
+ img_str = f''
+ msg = img_str + msg.replace('', '').strip()
+ ret.append([msg, None])
+ else:
+ ret.append([msg, None])
+ else:
+ ret[-1][-1] = msg
+ return ret
+
+ def copy(self):
+ return Conversation(
+ system=self.system,
+ roles=self.roles,
+ messages=[[x, y] for x, y in self.messages],
+ offset=self.offset,
+ sep_style=self.sep_style,
+ sep=self.sep,
+ sep2=self.sep2,
+ version=self.version)
+
+ def dict(self):
+ if len(self.get_images()) > 0:
+ return {
+ "system": self.system,
+ "roles": self.roles,
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
+ "offset": self.offset,
+ "sep": self.sep,
+ "sep2": self.sep2,
+ }
+ return {
+ "system": self.system,
+ "roles": self.roles,
+ "messages": self.messages,
+ "offset": self.offset,
+ "sep": self.sep,
+ "sep2": self.sep2,
+ }
+
+
+conv_vicuna_v0 = Conversation(
+ system="A chat between a curious human and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
+ roles=("Human", "Assistant"),
+ messages=(
+ ("Human", "What are the key differences between renewable and non-renewable energy sources?"),
+ ("Assistant",
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
+ "renewable and non-renewable energy sources:\n"
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
+ "energy sources are finite and will eventually run out.\n"
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
+ "and other negative effects.\n"
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
+ "have lower operational costs than non-renewable sources.\n"
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
+ "locations than non-renewable sources.\n"
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
+ ),
+ offset=2,
+ sep_style=SeparatorStyle.SINGLE,
+ sep="###",
+)
+
+conv_vicuna_v1 = Conversation(
+ system="A chat between a curious user and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
+ roles=("USER", "ASSISTANT"),
+ version="v1",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.TWO,
+ sep=" ",
+ sep2="",
+)
+
+conv_llama_2 = Conversation(
+ system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
+
+If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
+ roles=("USER", "ASSISTANT"),
+ version="llama_v2",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.LLAMA_2,
+ sep="",
+ sep2="",
+)
+
+conv_llava_llama_2 = Conversation(
+ system="You are a helpful language and vision assistant. "
+ "You are able to understand the visual content that the user provides, "
+ "and assist the user with a variety of tasks using natural language.",
+ roles=("USER", "ASSISTANT"),
+ version="llama_v2",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.LLAMA_2,
+ sep="",
+ sep2="",
+)
+
+conv_mpt = Conversation(
+ system="""<|im_start|>system
+A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
+ version="mpt",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.MPT,
+ sep="<|im_end|>",
+)
+
+conv_llava_plain = Conversation(
+ system="",
+ roles=("", ""),
+ messages=(
+ ),
+ offset=0,
+ sep_style=SeparatorStyle.PLAIN,
+ sep="\n",
+)
+
+conv_llava_v0 = Conversation(
+ system="A chat between a curious human and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
+ roles=("Human", "Assistant"),
+ messages=(
+ ),
+ offset=0,
+ sep_style=SeparatorStyle.SINGLE,
+ sep="###",
+)
+
+conv_llava_v0_mmtag = Conversation(
+ system="A chat between a curious user and an artificial intelligence assistant. "
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
+ "The visual content will be provided with the following format: visual content.",
+ roles=("Human", "Assistant"),
+ messages=(
+ ),
+ offset=0,
+ sep_style=SeparatorStyle.SINGLE,
+ sep="###",
+ version="v0_mmtag",
+)
+
+conv_llava_v1 = Conversation(
+ system="A chat between a curious human and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
+ roles=("USER", "ASSISTANT"),
+ version="v1",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.TWO,
+ sep=" ",
+ sep2="",
+)
+
+conv_llava_v1_mmtag = Conversation(
+ system="A chat between a curious user and an artificial intelligence assistant. "
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
+ "The visual content will be provided with the following format: visual content.",
+ roles=("USER", "ASSISTANT"),
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.TWO,
+ sep=" ",
+ sep2="",
+ version="v1_mmtag",
+)
+
+conv_mistral_instruct = Conversation(
+ system="",
+ roles=("USER", "ASSISTANT"),
+ version="llama_v2",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.LLAMA_2,
+ sep="",
+ sep2="",
+)
+
+conv_chatml_direct = Conversation(
+ system="""<|im_start|>system
+Answer the questions.""",
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
+ version="mpt",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.MPT,
+ sep="<|im_end|>",
+)
+
+default_conversation = conv_vicuna_v1
+conv_templates = {
+ "default": conv_vicuna_v0,
+ "v0": conv_vicuna_v0,
+ "v1": conv_vicuna_v1,
+ "vicuna_v1": conv_vicuna_v1,
+ "llama_2": conv_llama_2,
+ "mistral_instruct": conv_mistral_instruct,
+ "chatml_direct": conv_chatml_direct,
+ "mistral_direct": conv_chatml_direct,
+
+ "plain": conv_llava_plain,
+ "v0_plain": conv_llava_plain,
+ "llava_v0": conv_llava_v0,
+ "v0_mmtag": conv_llava_v0_mmtag,
+ "llava_v1": conv_llava_v1,
+ "v1_mmtag": conv_llava_v1_mmtag,
+ "llava_llama_2": conv_llava_llama_2,
+
+ "mpt": conv_mpt,
+}
+
+
+if __name__ == "__main__":
+ print(default_conversation.get_prompt())
diff --git a/llava/eval/eval_gpt_review.py b/llava/eval/eval_gpt_review.py
new file mode 100644
index 0000000000000000000000000000000000000000..8af4559c65fc2728b11fd2097a109981ee1ef686
--- /dev/null
+++ b/llava/eval/eval_gpt_review.py
@@ -0,0 +1,113 @@
+import argparse
+import json
+import os
+
+import openai
+import tqdm
+import ray
+import time
+
+NUM_SECONDS_TO_SLEEP = 3
+
+@ray.remote(num_cpus=4)
+def get_eval(content: str, max_tokens: int):
+ while True:
+ try:
+ response = openai.ChatCompletion.create(
+ model='gpt-4',
+ messages=[{
+ 'role': 'system',
+ 'content': 'You are a helpful and precise assistant for checking the quality of the answer.'
+ }, {
+ 'role': 'user',
+ 'content': content,
+ }],
+ temperature=0.2, # TODO: figure out which temperature is best for evaluation
+ max_tokens=max_tokens,
+ )
+ break
+ except openai.error.RateLimitError:
+ pass
+ except Exception as e:
+ print(e)
+ time.sleep(NUM_SECONDS_TO_SLEEP)
+
+ print('success!')
+ return response['choices'][0]['message']['content']
+
+
+def parse_score(review):
+ try:
+ score_pair = review.split('\n')[0]
+ score_pair = score_pair.replace(',', ' ')
+ sp = score_pair.split(' ')
+ if len(sp) == 2:
+ return [float(sp[0]), float(sp[1])]
+ else:
+ print('error', review)
+ return [-1, -1]
+ except Exception as e:
+ print(e)
+ print('error', review)
+ return [-1, -1]
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.')
+ parser.add_argument('-q', '--question')
+ # parser.add_argument('-a', '--answer')
+ parser.add_argument('-a', '--answer-list', nargs='+', default=[])
+ parser.add_argument('-r', '--rule')
+ parser.add_argument('-o', '--output')
+ parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output')
+ args = parser.parse_args()
+
+ ray.init()
+
+ f_q = open(os.path.expanduser(args.question))
+ f_ans1 = open(os.path.expanduser(args.answer_list[0]))
+ f_ans2 = open(os.path.expanduser(args.answer_list[1]))
+ rule_dict = json.load(open(os.path.expanduser(args.rule), 'r'))
+
+ review_file = open(f'{args.output}', 'w')
+
+ js_list = []
+ handles = []
+ idx = 0
+ for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2):
+ # if idx == 1:
+ # break
+
+ ques = json.loads(ques_js)
+ ans1 = json.loads(ans1_js)
+ ans2 = json.loads(ans2_js)
+
+ category = json.loads(ques_js)['category']
+ if category in rule_dict:
+ rule = rule_dict[category]
+ else:
+ rule = rule_dict['default']
+ prompt = rule['prompt']
+ role = rule['role']
+ content = (f'[Question]\n{ques["text"]}\n\n'
+ f'[{role} 1]\n{ans1["text"]}\n\n[End of {role} 1]\n\n'
+ f'[{role} 2]\n{ans2["text"]}\n\n[End of {role} 2]\n\n'
+ f'[System]\n{prompt}\n\n')
+ js_list.append({
+ 'id': idx+1,
+ 'question_id': ques['question_id'],
+ 'answer1_id': ans1['answer_id'],
+ 'answer2_id': ans2['answer_id'],
+ 'category': category})
+ idx += 1
+ handles.append(get_eval.remote(content, args.max_tokens))
+ # To avoid the rate limit set by OpenAI
+ time.sleep(NUM_SECONDS_TO_SLEEP)
+
+ reviews = ray.get(handles)
+ for idx, review in enumerate(reviews):
+ scores = parse_score(review)
+ js_list[idx]['content'] = review
+ js_list[idx]['tuple'] = scores
+ review_file.write(json.dumps(js_list[idx]) + '\n')
+ review_file.close()
diff --git a/llava/eval/eval_gpt_review_bench.py b/llava/eval/eval_gpt_review_bench.py
new file mode 100644
index 0000000000000000000000000000000000000000..06160f2422b5368f30fb967f7cae635208a1dc69
--- /dev/null
+++ b/llava/eval/eval_gpt_review_bench.py
@@ -0,0 +1,121 @@
+import argparse
+import json
+import os
+
+import openai
+import time
+
+NUM_SECONDS_TO_SLEEP = 0.5
+
+
+def get_eval(content: str, max_tokens: int):
+ while True:
+ try:
+ response = openai.ChatCompletion.create(
+ model='gpt-4-0314',
+ messages=[{
+ 'role': 'system',
+ 'content': 'You are a helpful and precise assistant for checking the quality of the answer.'
+ }, {
+ 'role': 'user',
+ 'content': content,
+ }],
+ temperature=0.2, # TODO: figure out which temperature is best for evaluation
+ max_tokens=max_tokens,
+ )
+ break
+ except openai.error.RateLimitError:
+ pass
+ except Exception as e:
+ print(e)
+ time.sleep(NUM_SECONDS_TO_SLEEP)
+
+ return response['choices'][0]['message']['content']
+
+
+def parse_score(review):
+ try:
+ score_pair = review.split('\n')[0]
+ score_pair = score_pair.replace(',', ' ')
+ sp = score_pair.split(' ')
+ if len(sp) == 2:
+ return [float(sp[0]), float(sp[1])]
+ else:
+ print('error', review)
+ return [-1, -1]
+ except Exception as e:
+ print(e)
+ print('error', review)
+ return [-1, -1]
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.')
+ parser.add_argument('-q', '--question')
+ parser.add_argument('-c', '--context')
+ parser.add_argument('-a', '--answer-list', nargs='+', default=[])
+ parser.add_argument('-r', '--rule')
+ parser.add_argument('-o', '--output')
+ parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output')
+ args = parser.parse_args()
+
+ f_q = open(os.path.expanduser(args.question))
+ f_ans1 = open(os.path.expanduser(args.answer_list[0]))
+ f_ans2 = open(os.path.expanduser(args.answer_list[1]))
+ rule_dict = json.load(open(os.path.expanduser(args.rule), 'r'))
+
+ if os.path.isfile(os.path.expanduser(args.output)):
+ cur_reviews = [json.loads(line) for line in open(os.path.expanduser(args.output))]
+ else:
+ cur_reviews = []
+
+ review_file = open(f'{args.output}', 'a')
+
+ context_list = [json.loads(line) for line in open(os.path.expanduser(args.context))]
+ image_to_context = {context['image']: context for context in context_list}
+
+ handles = []
+ idx = 0
+ for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2):
+ ques = json.loads(ques_js)
+ ans1 = json.loads(ans1_js)
+ ans2 = json.loads(ans2_js)
+
+ inst = image_to_context[ques['image']]
+
+ if isinstance(inst['caption'], list):
+ cap_str = '\n'.join(inst['caption'])
+ else:
+ cap_str = inst['caption']
+
+ category = 'llava_bench_' + json.loads(ques_js)['category']
+ if category in rule_dict:
+ rule = rule_dict[category]
+ else:
+ assert False, f"Visual QA category not found in rule file: {category}."
+ prompt = rule['prompt']
+ role = rule['role']
+ content = (f'[Context]\n{cap_str}\n\n'
+ f'[Question]\n{ques["text"]}\n\n'
+ f'[{role} 1]\n{ans1["text"]}\n\n[End of {role} 1]\n\n'
+ f'[{role} 2]\n{ans2["text"]}\n\n[End of {role} 2]\n\n'
+ f'[System]\n{prompt}\n\n')
+ cur_js = {
+ 'id': idx+1,
+ 'question_id': ques['question_id'],
+ 'answer1_id': ans1.get('answer_id', ans1['question_id']),
+ 'answer2_id': ans2.get('answer_id', ans2['answer_id']),
+ 'category': category
+ }
+ if idx >= len(cur_reviews):
+ review = get_eval(content, args.max_tokens)
+ scores = parse_score(review)
+ cur_js['content'] = review
+ cur_js['tuple'] = scores
+ review_file.write(json.dumps(cur_js) + '\n')
+ review_file.flush()
+ else:
+ print(f'Skipping {idx} as we already have it.')
+ idx += 1
+ print(idx)
+ review_file.close()
diff --git a/llava/eval/eval_gpt_review_visual.py b/llava/eval/eval_gpt_review_visual.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6e407a400a67020d801e6c27a3c32a2ee38f30c
--- /dev/null
+++ b/llava/eval/eval_gpt_review_visual.py
@@ -0,0 +1,118 @@
+import argparse
+import json
+import os
+
+import openai
+import time
+
+NUM_SECONDS_TO_SLEEP = 0.5
+
+
+def get_eval(content: str, max_tokens: int):
+ while True:
+ try:
+ response = openai.ChatCompletion.create(
+ model='gpt-4-0314',
+ messages=[{
+ 'role': 'system',
+ 'content': 'You are a helpful and precise assistant for checking the quality of the answer.'
+ }, {
+ 'role': 'user',
+ 'content': content,
+ }],
+ temperature=0.2, # TODO: figure out which temperature is best for evaluation
+ max_tokens=max_tokens,
+ )
+ break
+ except openai.error.RateLimitError:
+ pass
+ except Exception as e:
+ print(e)
+ time.sleep(NUM_SECONDS_TO_SLEEP)
+
+ return response['choices'][0]['message']['content']
+
+
+def parse_score(review):
+ try:
+ score_pair = review.split('\n')[0]
+ score_pair = score_pair.replace(',', ' ')
+ sp = score_pair.split(' ')
+ if len(sp) == 2:
+ return [float(sp[0]), float(sp[1])]
+ else:
+ print('error', review)
+ return [-1, -1]
+ except Exception as e:
+ print(e)
+ print('error', review)
+ return [-1, -1]
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.')
+ parser.add_argument('-q', '--question')
+ parser.add_argument('-c', '--context')
+ parser.add_argument('-a', '--answer-list', nargs='+', default=[])
+ parser.add_argument('-r', '--rule')
+ parser.add_argument('-o', '--output')
+ parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output')
+ args = parser.parse_args()
+
+ f_q = open(os.path.expanduser(args.question))
+ f_ans1 = open(os.path.expanduser(args.answer_list[0]))
+ f_ans2 = open(os.path.expanduser(args.answer_list[1]))
+ rule_dict = json.load(open(os.path.expanduser(args.rule), 'r'))
+
+ if os.path.isfile(os.path.expanduser(args.output)):
+ cur_reviews = [json.loads(line) for line in open(os.path.expanduser(args.output))]
+ else:
+ cur_reviews = []
+
+ review_file = open(f'{args.output}', 'a')
+
+ context_list = [json.loads(line) for line in open(os.path.expanduser(args.context))]
+ image_to_context = {context['image']: context for context in context_list}
+
+ handles = []
+ idx = 0
+ for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2):
+ ques = json.loads(ques_js)
+ ans1 = json.loads(ans1_js)
+ ans2 = json.loads(ans2_js)
+
+ inst = image_to_context[ques['image']]
+ cap_str = '\n'.join(inst['captions'])
+ box_str = '\n'.join([f'{instance["category"]}: {instance["bbox"]}' for instance in inst['instances']])
+
+ category = json.loads(ques_js)['category']
+ if category in rule_dict:
+ rule = rule_dict[category]
+ else:
+ assert False, f"Visual QA category not found in rule file: {category}."
+ prompt = rule['prompt']
+ role = rule['role']
+ content = (f'[Context]\n{cap_str}\n\n{box_str}\n\n'
+ f'[Question]\n{ques["text"]}\n\n'
+ f'[{role} 1]\n{ans1["text"]}\n\n[End of {role} 1]\n\n'
+ f'[{role} 2]\n{ans2["text"]}\n\n[End of {role} 2]\n\n'
+ f'[System]\n{prompt}\n\n')
+ cur_js = {
+ 'id': idx+1,
+ 'question_id': ques['question_id'],
+ 'answer1_id': ans1.get('answer_id', ans1['question_id']),
+ 'answer2_id': ans2.get('answer_id', ans2['answer_id']),
+ 'category': category
+ }
+ if idx >= len(cur_reviews):
+ review = get_eval(content, args.max_tokens)
+ scores = parse_score(review)
+ cur_js['content'] = review
+ cur_js['tuple'] = scores
+ review_file.write(json.dumps(cur_js) + '\n')
+ review_file.flush()
+ else:
+ print(f'Skipping {idx} as we already have it.')
+ idx += 1
+ print(idx)
+ review_file.close()
diff --git a/llava/eval/eval_pope.py b/llava/eval/eval_pope.py
new file mode 100644
index 0000000000000000000000000000000000000000..b115b8f2327ea9d972f9e41bcbb03c68be6b3508
--- /dev/null
+++ b/llava/eval/eval_pope.py
@@ -0,0 +1,81 @@
+import os
+import json
+import argparse
+
+def eval_pope(answers, label_file):
+ label_list = [json.loads(q)['label'] for q in open(label_file, 'r')]
+
+ for answer in answers:
+ text = answer['text']
+
+ # Only keep the first sentence
+ if text.find('.') != -1:
+ text = text.split('.')[0]
+
+ text = text.replace(',', '')
+ words = text.split(' ')
+ if 'No' in words or 'not' in words or 'no' in words:
+ answer['text'] = 'no'
+ else:
+ answer['text'] = 'yes'
+
+ for i in range(len(label_list)):
+ if label_list[i] == 'no':
+ label_list[i] = 0
+ else:
+ label_list[i] = 1
+
+ pred_list = []
+ for answer in answers:
+ if answer['text'] == 'no':
+ pred_list.append(0)
+ else:
+ pred_list.append(1)
+
+ pos = 1
+ neg = 0
+ yes_ratio = pred_list.count(1) / len(pred_list)
+
+ TP, TN, FP, FN = 0, 0, 0, 0
+ for pred, label in zip(pred_list, label_list):
+ if pred == pos and label == pos:
+ TP += 1
+ elif pred == pos and label == neg:
+ FP += 1
+ elif pred == neg and label == neg:
+ TN += 1
+ elif pred == neg and label == pos:
+ FN += 1
+
+ print('TP\tFP\tTN\tFN\t')
+ print('{}\t{}\t{}\t{}'.format(TP, FP, TN, FN))
+
+ precision = float(TP) / float(TP + FP)
+ recall = float(TP) / float(TP + FN)
+ f1 = 2*precision*recall / (precision + recall)
+ acc = (TP + TN) / (TP + TN + FP + FN)
+ print('Accuracy: {}'.format(acc))
+ print('Precision: {}'.format(precision))
+ print('Recall: {}'.format(recall))
+ print('F1 score: {}'.format(f1))
+ print('Yes ratio: {}'.format(yes_ratio))
+ print('%.3f, %.3f, %.3f, %.3f, %.3f' % (f1, acc, precision, recall, yes_ratio) )
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--annotation-dir", type=str)
+ parser.add_argument("--question-file", type=str)
+ parser.add_argument("--result-file", type=str)
+ args = parser.parse_args()
+
+ questions = [json.loads(line) for line in open(args.question_file)]
+ questions = {question['question_id']: question for question in questions}
+ answers = [json.loads(q) for q in open(args.result_file)]
+ for file in os.listdir(args.annotation_dir):
+ assert file.startswith('coco_pope_')
+ assert file.endswith('.json')
+ category = file[10:-5]
+ cur_answers = [x for x in answers if questions[x['question_id']]['category'] == category]
+ print('Category: {}, # samples: {}'.format(category, len(cur_answers)))
+ eval_pope(cur_answers, os.path.join(args.annotation_dir, file))
+ print("====================================")
diff --git a/llava/eval/eval_science_qa.py b/llava/eval/eval_science_qa.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccf206bbd7a5d6376eef82d61b3ef8bbe0f71c6c
--- /dev/null
+++ b/llava/eval/eval_science_qa.py
@@ -0,0 +1,114 @@
+import argparse
+import json
+import os
+import re
+import random
+
+
+def get_args():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--base-dir', type=str)
+ parser.add_argument('--result-file', type=str)
+ parser.add_argument('--output-file', type=str)
+ parser.add_argument('--output-result', type=str)
+ parser.add_argument('--split', type=str, default='test')
+ parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"])
+ return parser.parse_args()
+
+
+def convert_caps(results):
+ fakecaps = []
+ for result in results:
+ image_id = result['question_id']
+ caption = result['text']
+ fakecaps.append({"image_id": int(image_id), "caption": caption})
+ return fakecaps
+
+
+def get_pred_idx(prediction, choices, options):
+ """
+ Get the index (e.g. 2) from the prediction (e.g. 'C')
+ """
+ if prediction in options[:len(choices)]:
+ return options.index(prediction)
+ else:
+ return -1
+ return random.choice(range(len(choices)))
+
+
+if __name__ == "__main__":
+ args = get_args()
+
+ base_dir = args.base_dir
+ split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split]
+ problems = json.load(open(os.path.join(base_dir, "problems.json")))
+ predictions = [json.loads(line) for line in open(args.result_file)]
+ predictions = {pred['question_id']: pred for pred in predictions}
+ split_problems = {idx: problems[idx] for idx in split_indices}
+
+ results = {'correct': [], 'incorrect': []}
+ sqa_results = {}
+ sqa_results['acc'] = None
+ sqa_results['correct'] = None
+ sqa_results['count'] = None
+ sqa_results['results'] = {}
+ sqa_results['outputs'] = {}
+
+ for prob_id, prob in split_problems.items():
+ if prob_id not in predictions:
+ pred = {'text': 'FAILED', 'prompt': 'Unknown'}
+ pred_text = 'FAILED'
+ else:
+ pred = predictions[prob_id]
+ pred_text = pred['text']
+
+ if pred_text in args.options:
+ answer = pred_text
+ elif len(pred_text) >= 3 and pred_text[0] in args.options and pred_text[1:3] == ". ":
+ answer = pred_text[0]
+ else:
+ pattern = re.compile(r'The answer is ([A-Z]).')
+ res = pattern.findall(pred_text)
+ if len(res) == 1:
+ answer = res[0] # 'A', 'B', ...
+ else:
+ answer = "FAILED"
+
+ pred_idx = get_pred_idx(answer, prob['choices'], args.options)
+
+ analysis = {
+ 'question_id': prob_id,
+ 'parsed_ans': answer,
+ 'ground_truth': args.options[prob['answer']],
+ 'question': pred['prompt'],
+ 'pred': pred_text,
+ 'is_multimodal': '' in pred['prompt'],
+ }
+
+ sqa_results['results'][prob_id] = get_pred_idx(answer, prob['choices'], args.options)
+ sqa_results['outputs'][prob_id] = pred_text
+
+ if pred_idx == prob['answer']:
+ results['correct'].append(analysis)
+ else:
+ results['incorrect'].append(analysis)
+
+ correct = len(results['correct'])
+ total = len(results['correct']) + len(results['incorrect'])
+
+ ###### IMG ######
+ multimodal_correct = len([x for x in results['correct'] if x['is_multimodal']])
+ multimodal_incorrect = len([x for x in results['incorrect'] if x['is_multimodal']])
+ multimodal_total = multimodal_correct + multimodal_incorrect
+ ###### IMG ######
+
+ print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%, IMG-Accuracy: {multimodal_correct / multimodal_total * 100:.2f}%')
+
+ sqa_results['acc'] = correct / total * 100
+ sqa_results['correct'] = correct
+ sqa_results['count'] = total
+
+ with open(args.output_file, 'w') as f:
+ json.dump(results, f, indent=2)
+ with open(args.output_result, 'w') as f:
+ json.dump(sqa_results, f, indent=2)
diff --git a/llava/eval/eval_science_qa_gpt4.py b/llava/eval/eval_science_qa_gpt4.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2ff17c915481fb556aba6ec816a9e08f519c515
--- /dev/null
+++ b/llava/eval/eval_science_qa_gpt4.py
@@ -0,0 +1,104 @@
+import argparse
+import json
+import os
+import re
+import random
+from collections import defaultdict
+
+
+def get_args():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--base-dir', type=str)
+ parser.add_argument('--gpt4-result', type=str)
+ parser.add_argument('--our-result', type=str)
+ parser.add_argument('--split', type=str, default='test')
+ parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"])
+ return parser.parse_args()
+
+
+def convert_caps(results):
+ fakecaps = []
+ for result in results:
+ image_id = result['question_id']
+ caption = result['text']
+ fakecaps.append({"image_id": int(image_id), "caption": caption})
+ return fakecaps
+
+
+def get_pred_idx(prediction, choices, options):
+ """
+ Get the index (e.g. 2) from the prediction (e.g. 'C')
+ """
+ if prediction in options[:len(choices)]:
+ return options.index(prediction)
+ else:
+ return random.choice(range(len(choices)))
+
+
+if __name__ == "__main__":
+ args = get_args()
+
+ base_dir = args.base_dir
+ split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split]
+ problems = json.load(open(os.path.join(base_dir, "problems.json")))
+ our_predictions = [json.loads(line) for line in open(args.our_result)]
+ our_predictions = {pred['question_id']: pred for pred in our_predictions}
+ split_problems = {idx: problems[idx] for idx in split_indices}
+
+ gpt4_predictions = json.load(open(args.gpt4_result))['outputs']
+
+ results = defaultdict(lambda: 0)
+
+ for prob_id, prob in split_problems.items():
+ if prob_id not in our_predictions:
+ continue
+ if prob_id not in gpt4_predictions:
+ continue
+ our_pred = our_predictions[prob_id]['text']
+ gpt4_pred = gpt4_predictions[prob_id]
+
+ pattern = re.compile(r'The answer is ([A-Z]).')
+ our_res = pattern.findall(our_pred)
+ if len(our_res) == 1:
+ our_answer = our_res[0] # 'A', 'B', ...
+ else:
+ our_answer = "FAILED"
+ gpt4_res = pattern.findall(gpt4_pred)
+ if len(gpt4_res) == 1:
+ gpt4_answer = gpt4_res[0] # 'A', 'B', ...
+ else:
+ gpt4_answer = "FAILED"
+
+ our_pred_idx = get_pred_idx(our_answer, prob['choices'], args.options)
+ gpt4_pred_idx = get_pred_idx(gpt4_answer, prob['choices'], args.options)
+
+ if gpt4_answer == 'FAILED':
+ results['gpt4_failed'] += 1
+ # continue
+ gpt4_pred_idx = our_pred_idx
+ # if our_pred_idx != prob['answer']:
+ # print(our_predictions[prob_id]['prompt'])
+ # print('-----------------')
+ # print(f'LECTURE: {prob["lecture"]}')
+ # print(f'SOLUTION: {prob["solution"]}')
+ # print('=====================')
+ else:
+ # continue
+ pass
+ # gpt4_pred_idx = our_pred_idx
+
+ if gpt4_pred_idx == prob['answer']:
+ results['correct'] += 1
+ else:
+ results['incorrect'] += 1
+
+
+ if gpt4_pred_idx == prob['answer'] or our_pred_idx == prob['answer']:
+ results['correct_upperbound'] += 1
+
+ correct = results['correct']
+ total = results['correct'] + results['incorrect']
+ print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%')
+ print(f'Total: {total}, Correct (upper): {results["correct_upperbound"]}, Accuracy: {results["correct_upperbound"] / total * 100:.2f}%')
+ print(f'Total: {total}, GPT-4 NO-ANS (RANDOM): {results["gpt4_failed"]}, Percentage: {results["gpt4_failed"] / total * 100:.2f}%')
+
diff --git a/llava/eval/eval_science_qa_gpt4_requery.py b/llava/eval/eval_science_qa_gpt4_requery.py
new file mode 100644
index 0000000000000000000000000000000000000000..698546e995d365d1ccc2c25a87e6c5cd681e6eb6
--- /dev/null
+++ b/llava/eval/eval_science_qa_gpt4_requery.py
@@ -0,0 +1,149 @@
+import argparse
+import json
+import os
+import re
+import random
+from collections import defaultdict
+
+
+def get_args():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--base-dir', type=str)
+ parser.add_argument('--gpt4-result', type=str)
+ parser.add_argument('--requery-result', type=str)
+ parser.add_argument('--our-result', type=str)
+ parser.add_argument('--output-result', type=str)
+ parser.add_argument('--split', type=str, default='test')
+ parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"])
+ return parser.parse_args()
+
+
+def convert_caps(results):
+ fakecaps = []
+ for result in results:
+ image_id = result['question_id']
+ caption = result['text']
+ fakecaps.append({"image_id": int(image_id), "caption": caption})
+ return fakecaps
+
+
+def get_pred_idx(prediction, choices, options):
+ """
+ Get the index (e.g. 2) from the prediction (e.g. 'C')
+ """
+ if prediction in options[:len(choices)]:
+ return options.index(prediction)
+ else:
+ return random.choice(range(len(choices)))
+
+
+if __name__ == "__main__":
+ args = get_args()
+
+ base_dir = args.base_dir
+ split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split]
+ problems = json.load(open(os.path.join(base_dir, "problems.json")))
+ our_predictions = [json.loads(line) for line in open(args.our_result)]
+ our_predictions = {pred['question_id']: pred for pred in our_predictions}
+ split_problems = {idx: problems[idx] for idx in split_indices}
+
+ requery_predictions = [json.loads(line) for line in open(args.requery_result)]
+ requery_predictions = {pred['question_id']: pred for pred in requery_predictions}
+
+ gpt4_predictions = json.load(open(args.gpt4_result))['outputs']
+
+ results = defaultdict(lambda: 0)
+
+ sqa_results = {}
+ sqa_results['acc'] = None
+ sqa_results['correct'] = None
+ sqa_results['count'] = None
+ sqa_results['results'] = {}
+ sqa_results['outputs'] = {}
+
+ for prob_id, prob in split_problems.items():
+ if prob_id not in our_predictions:
+ assert False
+ if prob_id not in gpt4_predictions:
+ assert False
+ our_pred = our_predictions[prob_id]['text']
+ gpt4_pred = gpt4_predictions[prob_id]
+ if prob_id not in requery_predictions:
+ results['missing_requery'] += 1
+ requery_pred = "MISSING"
+ else:
+ requery_pred = requery_predictions[prob_id]['text']
+
+ pattern = re.compile(r'The answer is ([A-Z]).')
+ our_res = pattern.findall(our_pred)
+ if len(our_res) == 1:
+ our_answer = our_res[0] # 'A', 'B', ...
+ else:
+ our_answer = "FAILED"
+
+ requery_res = pattern.findall(requery_pred)
+ if len(requery_res) == 1:
+ requery_answer = requery_res[0] # 'A', 'B', ...
+ else:
+ requery_answer = "FAILED"
+
+ gpt4_res = pattern.findall(gpt4_pred)
+ if len(gpt4_res) == 1:
+ gpt4_answer = gpt4_res[0] # 'A', 'B', ...
+ else:
+ gpt4_answer = "FAILED"
+
+ our_pred_idx = get_pred_idx(our_answer, prob['choices'], args.options)
+ gpt4_pred_idx = get_pred_idx(gpt4_answer, prob['choices'], args.options)
+ requery_pred_idx = get_pred_idx(requery_answer, prob['choices'], args.options)
+
+ results['total'] += 1
+
+ if gpt4_answer == 'FAILED':
+ results['gpt4_failed'] += 1
+ if gpt4_pred_idx == prob['answer']:
+ results['gpt4_correct'] += 1
+ if our_pred_idx == prob['answer']:
+ results['gpt4_ourvisual_correct'] += 1
+ elif gpt4_pred_idx == prob['answer']:
+ results['gpt4_correct'] += 1
+ results['gpt4_ourvisual_correct'] += 1
+
+ if our_pred_idx == prob['answer']:
+ results['our_correct'] += 1
+
+ if requery_answer == 'FAILED':
+ sqa_results['results'][prob_id] = our_pred_idx
+ if our_pred_idx == prob['answer']:
+ results['requery_correct'] += 1
+ else:
+ sqa_results['results'][prob_id] = requery_pred_idx
+ if requery_pred_idx == prob['answer']:
+ results['requery_correct'] += 1
+ else:
+ print(f"""
+Question ({args.options[prob['answer']]}): {our_predictions[prob_id]['prompt']}
+Our ({our_answer}): {our_pred}
+GPT-4 ({gpt4_answer}): {gpt4_pred}
+Requery ({requery_answer}): {requery_pred}
+print("=====================================")
+""")
+
+ if gpt4_pred_idx == prob['answer'] or our_pred_idx == prob['answer']:
+ results['correct_upperbound'] += 1
+
+ total = results['total']
+ print(f'Total: {total}, Our-Correct: {results["our_correct"]}, Accuracy: {results["our_correct"] / total * 100:.2f}%')
+ print(f'Total: {total}, GPT-4-Correct: {results["gpt4_correct"]}, Accuracy: {results["gpt4_correct"] / total * 100:.2f}%')
+ print(f'Total: {total}, GPT-4 NO-ANS (RANDOM): {results["gpt4_failed"]}, Percentage: {results["gpt4_failed"] / total * 100:.2f}%')
+ print(f'Total: {total}, GPT-4-OursVisual-Correct: {results["gpt4_ourvisual_correct"]}, Accuracy: {results["gpt4_ourvisual_correct"] / total * 100:.2f}%')
+ print(f'Total: {total}, Requery-Correct: {results["requery_correct"]}, Accuracy: {results["requery_correct"] / total * 100:.2f}%')
+ print(f'Total: {total}, Correct upper: {results["correct_upperbound"]}, Accuracy: {results["correct_upperbound"] / total * 100:.2f}%')
+
+ sqa_results['acc'] = results["requery_correct"] / total * 100
+ sqa_results['correct'] = results["requery_correct"]
+ sqa_results['count'] = total
+
+ with open(args.output_result, 'w') as f:
+ json.dump(sqa_results, f, indent=2)
+
diff --git a/llava/eval/eval_textvqa.py b/llava/eval/eval_textvqa.py
new file mode 100644
index 0000000000000000000000000000000000000000..468f4bb120448a036bd5b5c7955464fe2e13892a
--- /dev/null
+++ b/llava/eval/eval_textvqa.py
@@ -0,0 +1,65 @@
+import os
+import argparse
+import json
+import re
+
+from llava.eval.m4c_evaluator import TextVQAAccuracyEvaluator
+
+
+def get_args():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--annotation-file', type=str)
+ parser.add_argument('--result-file', type=str)
+ parser.add_argument('--result-dir', type=str)
+ return parser.parse_args()
+
+
+def prompt_processor(prompt):
+ if prompt.startswith('OCR tokens: '):
+ pattern = r"Question: (.*?) Short answer:"
+ match = re.search(pattern, prompt, re.DOTALL)
+ question = match.group(1)
+ elif 'Reference OCR token: ' in prompt and len(prompt.split('\n')) == 3:
+ if prompt.startswith('Reference OCR token:'):
+ question = prompt.split('\n')[1]
+ else:
+ question = prompt.split('\n')[0]
+ elif len(prompt.split('\n')) == 2:
+ question = prompt.split('\n')[0]
+ else:
+ assert False
+
+ return question.lower()
+
+
+def eval_single(annotation_file, result_file):
+ experiment_name = os.path.splitext(os.path.basename(result_file))[0]
+ print(experiment_name)
+ annotations = json.load(open(annotation_file))['data']
+ annotations = {(annotation['image_id'], annotation['question'].lower()): annotation for annotation in annotations}
+ results = [json.loads(line) for line in open(result_file)]
+
+ pred_list = []
+ for result in results:
+ annotation = annotations[(result['question_id'], prompt_processor(result['prompt']))]
+ pred_list.append({
+ "pred_answer": result['text'],
+ "gt_answers": annotation['answers'],
+ })
+
+ evaluator = TextVQAAccuracyEvaluator()
+ print('Samples: {}\nAccuracy: {:.2f}%\n'.format(len(pred_list), 100. * evaluator.eval_pred_list(pred_list)))
+
+
+if __name__ == "__main__":
+ args = get_args()
+
+ if args.result_file is not None:
+ eval_single(args.annotation_file, args.result_file)
+
+ if args.result_dir is not None:
+ for result_file in sorted(os.listdir(args.result_dir)):
+ if not result_file.endswith('.jsonl'):
+ print(f'Skipping {result_file}')
+ continue
+ eval_single(args.annotation_file, os.path.join(args.result_dir, result_file))
diff --git a/llava/eval/generate_webpage_data_from_table.py b/llava/eval/generate_webpage_data_from_table.py
new file mode 100644
index 0000000000000000000000000000000000000000..92602258ccd953a1d7137056aaf15c8de8166e21
--- /dev/null
+++ b/llava/eval/generate_webpage_data_from_table.py
@@ -0,0 +1,111 @@
+"""Generate json file for webpage."""
+import json
+import os
+import re
+
+# models = ['llama', 'alpaca', 'gpt35', 'bard']
+models = ['vicuna']
+
+
+def read_jsonl(path: str, key: str=None):
+ data = []
+ with open(os.path.expanduser(path)) as f:
+ for line in f:
+ if not line:
+ continue
+ data.append(json.loads(line))
+ if key is not None:
+ data.sort(key=lambda x: x[key])
+ data = {item[key]: item for item in data}
+ return data
+
+
+def trim_hanging_lines(s: str, n: int) -> str:
+ s = s.strip()
+ for _ in range(n):
+ s = s.split('\n', 1)[1].strip()
+ return s
+
+
+if __name__ == '__main__':
+ questions = read_jsonl('table/question.jsonl', key='question_id')
+
+ # alpaca_answers = read_jsonl('table/answer/answer_alpaca-13b.jsonl', key='question_id')
+ # bard_answers = read_jsonl('table/answer/answer_bard.jsonl', key='question_id')
+ # gpt35_answers = read_jsonl('table/answer/answer_gpt35.jsonl', key='question_id')
+ # llama_answers = read_jsonl('table/answer/answer_llama-13b.jsonl', key='question_id')
+ vicuna_answers = read_jsonl('table/answer/answer_vicuna-13b.jsonl', key='question_id')
+ ours_answers = read_jsonl('table/results/llama-13b-hf-alpaca.jsonl', key='question_id')
+
+ review_vicuna = read_jsonl('table/review/review_vicuna-13b_llama-13b-hf-alpaca.jsonl', key='question_id')
+ # review_alpaca = read_jsonl('table/review/review_alpaca-13b_vicuna-13b.jsonl', key='question_id')
+ # review_bard = read_jsonl('table/review/review_bard_vicuna-13b.jsonl', key='question_id')
+ # review_gpt35 = read_jsonl('table/review/review_gpt35_vicuna-13b.jsonl', key='question_id')
+ # review_llama = read_jsonl('table/review/review_llama-13b_vicuna-13b.jsonl', key='question_id')
+
+ records = []
+ for qid in questions.keys():
+ r = {
+ 'id': qid,
+ 'category': questions[qid]['category'],
+ 'question': questions[qid]['text'],
+ 'answers': {
+ # 'alpaca': alpaca_answers[qid]['text'],
+ # 'llama': llama_answers[qid]['text'],
+ # 'bard': bard_answers[qid]['text'],
+ # 'gpt35': gpt35_answers[qid]['text'],
+ 'vicuna': vicuna_answers[qid]['text'],
+ 'ours': ours_answers[qid]['text'],
+ },
+ 'evaluations': {
+ # 'alpaca': review_alpaca[qid]['text'],
+ # 'llama': review_llama[qid]['text'],
+ # 'bard': review_bard[qid]['text'],
+ 'vicuna': review_vicuna[qid]['content'],
+ # 'gpt35': review_gpt35[qid]['text'],
+ },
+ 'scores': {
+ 'vicuna': review_vicuna[qid]['tuple'],
+ # 'alpaca': review_alpaca[qid]['score'],
+ # 'llama': review_llama[qid]['score'],
+ # 'bard': review_bard[qid]['score'],
+ # 'gpt35': review_gpt35[qid]['score'],
+ },
+ }
+
+ # cleanup data
+ cleaned_evals = {}
+ for k, v in r['evaluations'].items():
+ v = v.strip()
+ lines = v.split('\n')
+ # trim the first line if it's a pair of numbers
+ if re.match(r'\d+[, ]+\d+', lines[0]):
+ lines = lines[1:]
+ v = '\n'.join(lines)
+ cleaned_evals[k] = v.replace('Assistant 1', "**Assistant 1**").replace('Assistant 2', '**Assistant 2**')
+
+ r['evaluations'] = cleaned_evals
+ records.append(r)
+
+ # Reorder the records, this is optional
+ for r in records:
+ if r['id'] <= 20:
+ r['id'] += 60
+ else:
+ r['id'] -= 20
+ for r in records:
+ if r['id'] <= 50:
+ r['id'] += 10
+ elif 50 < r['id'] <= 60:
+ r['id'] -= 50
+ for r in records:
+ if r['id'] == 7:
+ r['id'] = 1
+ elif r['id'] < 7:
+ r['id'] += 1
+
+ records.sort(key=lambda x: x['id'])
+
+ # Write to file
+ with open('webpage/data.json', 'w') as f:
+ json.dump({'questions': records, 'models': models}, f, indent=2)
diff --git a/llava/eval/m4c_evaluator.py b/llava/eval/m4c_evaluator.py
new file mode 100644
index 0000000000000000000000000000000000000000..e30e958da061a4f0a0bfe34b12d2fcaeba7ff2f4
--- /dev/null
+++ b/llava/eval/m4c_evaluator.py
@@ -0,0 +1,334 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+import re
+
+from tqdm import tqdm
+
+
+class EvalAIAnswerProcessor:
+ """
+ Processes an answer similar to Eval AI
+ copied from
+ https://github.com/facebookresearch/mmf/blob/c46b3b3391275b4181567db80943473a89ab98ab/pythia/tasks/processors.py#L897
+ """
+
+ CONTRACTIONS = {
+ "aint": "ain't",
+ "arent": "aren't",
+ "cant": "can't",
+ "couldve": "could've",
+ "couldnt": "couldn't",
+ "couldn'tve": "couldn't've",
+ "couldnt've": "couldn't've",
+ "didnt": "didn't",
+ "doesnt": "doesn't",
+ "dont": "don't",
+ "hadnt": "hadn't",
+ "hadnt've": "hadn't've",
+ "hadn'tve": "hadn't've",
+ "hasnt": "hasn't",
+ "havent": "haven't",
+ "hed": "he'd",
+ "hed've": "he'd've",
+ "he'dve": "he'd've",
+ "hes": "he's",
+ "howd": "how'd",
+ "howll": "how'll",
+ "hows": "how's",
+ "Id've": "I'd've",
+ "I'dve": "I'd've",
+ "Im": "I'm",
+ "Ive": "I've",
+ "isnt": "isn't",
+ "itd": "it'd",
+ "itd've": "it'd've",
+ "it'dve": "it'd've",
+ "itll": "it'll",
+ "let's": "let's",
+ "maam": "ma'am",
+ "mightnt": "mightn't",
+ "mightnt've": "mightn't've",
+ "mightn'tve": "mightn't've",
+ "mightve": "might've",
+ "mustnt": "mustn't",
+ "mustve": "must've",
+ "neednt": "needn't",
+ "notve": "not've",
+ "oclock": "o'clock",
+ "oughtnt": "oughtn't",
+ "ow's'at": "'ow's'at",
+ "'ows'at": "'ow's'at",
+ "'ow'sat": "'ow's'at",
+ "shant": "shan't",
+ "shed've": "she'd've",
+ "she'dve": "she'd've",
+ "she's": "she's",
+ "shouldve": "should've",
+ "shouldnt": "shouldn't",
+ "shouldnt've": "shouldn't've",
+ "shouldn'tve": "shouldn't've",
+ "somebody'd": "somebodyd",
+ "somebodyd've": "somebody'd've",
+ "somebody'dve": "somebody'd've",
+ "somebodyll": "somebody'll",
+ "somebodys": "somebody's",
+ "someoned": "someone'd",
+ "someoned've": "someone'd've",
+ "someone'dve": "someone'd've",
+ "someonell": "someone'll",
+ "someones": "someone's",
+ "somethingd": "something'd",
+ "somethingd've": "something'd've",
+ "something'dve": "something'd've",
+ "somethingll": "something'll",
+ "thats": "that's",
+ "thered": "there'd",
+ "thered've": "there'd've",
+ "there'dve": "there'd've",
+ "therere": "there're",
+ "theres": "there's",
+ "theyd": "they'd",
+ "theyd've": "they'd've",
+ "they'dve": "they'd've",
+ "theyll": "they'll",
+ "theyre": "they're",
+ "theyve": "they've",
+ "twas": "'twas",
+ "wasnt": "wasn't",
+ "wed've": "we'd've",
+ "we'dve": "we'd've",
+ "weve": "we've",
+ "werent": "weren't",
+ "whatll": "what'll",
+ "whatre": "what're",
+ "whats": "what's",
+ "whatve": "what've",
+ "whens": "when's",
+ "whered": "where'd",
+ "wheres": "where's",
+ "whereve": "where've",
+ "whod": "who'd",
+ "whod've": "who'd've",
+ "who'dve": "who'd've",
+ "wholl": "who'll",
+ "whos": "who's",
+ "whove": "who've",
+ "whyll": "why'll",
+ "whyre": "why're",
+ "whys": "why's",
+ "wont": "won't",
+ "wouldve": "would've",
+ "wouldnt": "wouldn't",
+ "wouldnt've": "wouldn't've",
+ "wouldn'tve": "wouldn't've",
+ "yall": "y'all",
+ "yall'll": "y'all'll",
+ "y'allll": "y'all'll",
+ "yall'd've": "y'all'd've",
+ "y'alld've": "y'all'd've",
+ "y'all'dve": "y'all'd've",
+ "youd": "you'd",
+ "youd've": "you'd've",
+ "you'dve": "you'd've",
+ "youll": "you'll",
+ "youre": "you're",
+ "youve": "you've",
+ }
+
+ NUMBER_MAP = {
+ "none": "0",
+ "zero": "0",
+ "one": "1",
+ "two": "2",
+ "three": "3",
+ "four": "4",
+ "five": "5",
+ "six": "6",
+ "seven": "7",
+ "eight": "8",
+ "nine": "9",
+ "ten": "10",
+ }
+ ARTICLES = ["a", "an", "the"]
+ PERIOD_STRIP = re.compile(r"(?!<=\d)(\.)(?!\d)")
+ COMMA_STRIP = re.compile(r"(?<=\d)(\,)+(?=\d)")
+ PUNCTUATIONS = [
+ ";",
+ r"/",
+ "[",
+ "]",
+ '"',
+ "{",
+ "}",
+ "(",
+ ")",
+ "=",
+ "+",
+ "\\",
+ "_",
+ "-",
+ ">",
+ "<",
+ "@",
+ "`",
+ ",",
+ "?",
+ "!",
+ ]
+
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def word_tokenize(self, word):
+ word = word.lower()
+ word = word.replace(",", "").replace("?", "").replace("'s", " 's")
+ return word.strip()
+
+ def process_punctuation(self, in_text):
+ out_text = in_text
+ for p in self.PUNCTUATIONS:
+ if (p + " " in in_text or " " + p in in_text) or (
+ re.search(self.COMMA_STRIP, in_text) is not None
+ ):
+ out_text = out_text.replace(p, "")
+ else:
+ out_text = out_text.replace(p, " ")
+ out_text = self.PERIOD_STRIP.sub("", out_text, re.UNICODE)
+ return out_text
+
+ def process_digit_article(self, in_text):
+ out_text = []
+ temp_text = in_text.lower().split()
+ for word in temp_text:
+ word = self.NUMBER_MAP.setdefault(word, word)
+ if word not in self.ARTICLES:
+ out_text.append(word)
+ else:
+ pass
+ for word_id, word in enumerate(out_text):
+ if word in self.CONTRACTIONS:
+ out_text[word_id] = self.CONTRACTIONS[word]
+ out_text = " ".join(out_text)
+ return out_text
+
+ def __call__(self, item):
+ item = self.word_tokenize(item)
+ item = item.replace("\n", " ").replace("\t", " ").strip()
+ item = self.process_punctuation(item)
+ item = self.process_digit_article(item)
+ return item
+
+
+class TextVQAAccuracyEvaluator:
+ def __init__(self):
+ self.answer_processor = EvalAIAnswerProcessor()
+
+ def _compute_answer_scores(self, raw_answers):
+ """
+ compute the accuracy (soft score) of human answers
+ """
+ answers = [self.answer_processor(a) for a in raw_answers]
+ assert len(answers) == 10
+ gt_answers = list(enumerate(answers))
+ unique_answers = set(answers)
+ unique_answer_scores = {}
+
+ for unique_answer in unique_answers:
+ accs = []
+ for gt_answer in gt_answers:
+ other_answers = [item for item in gt_answers if item != gt_answer]
+ matching_answers = [
+ item for item in other_answers if item[1] == unique_answer
+ ]
+ acc = min(1, float(len(matching_answers)) / 3)
+ accs.append(acc)
+ unique_answer_scores[unique_answer] = sum(accs) / len(accs)
+
+ return unique_answer_scores
+
+ def eval_pred_list(self, pred_list):
+ pred_scores = []
+ for entry in tqdm(pred_list):
+ pred_answer = self.answer_processor(entry["pred_answer"])
+ unique_answer_scores = self._compute_answer_scores(entry["gt_answers"])
+ score = unique_answer_scores.get(pred_answer, 0.0)
+ pred_scores.append(score)
+
+ accuracy = sum(pred_scores) / len(pred_scores)
+ return accuracy
+
+
+class STVQAAccuracyEvaluator:
+ def __init__(self):
+ self.answer_processor = EvalAIAnswerProcessor()
+
+ def eval_pred_list(self, pred_list):
+ pred_scores = []
+ for entry in pred_list:
+ pred_answer = self.answer_processor(entry["pred_answer"])
+ gts = [self.answer_processor(a) for a in entry["gt_answers"]]
+ score = 1.0 if pred_answer in gts else 0.0
+ pred_scores.append(score)
+
+ accuracy = sum(pred_scores) / len(pred_scores)
+ return accuracy
+
+
+class STVQAANLSEvaluator:
+ def __init__(self):
+ import editdistance # install with `pip install editdistance`
+
+ self.get_edit_distance = editdistance.eval
+
+ def get_anls(self, s1, s2):
+ s1 = s1.lower().strip()
+ s2 = s2.lower().strip()
+ iou = 1 - self.get_edit_distance(s1, s2) / max(len(s1), len(s2))
+ anls = iou if iou >= 0.5 else 0.0
+ return anls
+
+ def eval_pred_list(self, pred_list):
+ pred_scores = []
+ for entry in pred_list:
+ anls = max(
+ self.get_anls(entry["pred_answer"], gt) for gt in entry["gt_answers"]
+ )
+ pred_scores.append(anls)
+
+ accuracy = sum(pred_scores) / len(pred_scores)
+ return accuracy
+
+
+class TextCapsBleu4Evaluator:
+ def __init__(self):
+ # The following script requires Java 1.8.0 and pycocotools installed.
+ # The pycocoevalcap can be installed with pip as
+ # pip install git+https://github.com/ronghanghu/coco-caption.git@python23
+ # Original pycocoevalcap code is at https://github.com/tylin/coco-caption
+ # but has no python3 support yet.
+ try:
+ from pycocoevalcap.bleu.bleu import Bleu
+ from pycocoevalcap.tokenizer.ptbtokenizer import PTBTokenizer
+ except ModuleNotFoundError:
+ print(
+ "Please install pycocoevalcap module using "
+ "pip install git+https://github.com/ronghanghu/coco-caption.git@python23" # noqa
+ )
+ raise
+
+ self.tokenizer = PTBTokenizer()
+ self.scorer = Bleu(4)
+
+ def eval_pred_list(self, pred_list):
+ # Create reference and hypotheses captions.
+ gts = {}
+ res = {}
+ for idx, entry in enumerate(pred_list):
+ gts[idx] = [{"caption": a} for a in entry["gt_answers"]]
+ res[idx] = [{"caption": entry["pred_answer"]}]
+
+ gts = self.tokenizer.tokenize(gts)
+ res = self.tokenizer.tokenize(res)
+ score, _ = self.scorer.compute_score(gts, res)
+
+ bleu4 = score[3] # score is (Bleu-1, Bleu-2, Bleu-3, Bleu-4)
+ return bleu4
diff --git a/llava/eval/model_qa.py b/llava/eval/model_qa.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e254da152ac644ff54fb5fa57e625d9e6ba31d1
--- /dev/null
+++ b/llava/eval/model_qa.py
@@ -0,0 +1,64 @@
+import argparse
+from transformers import AutoTokenizer, AutoModelForCausalLM, StoppingCriteria
+import torch
+import os
+import json
+from tqdm import tqdm
+import shortuuid
+
+from llava.conversation import default_conversation
+from llava.utils import disable_torch_init
+
+
+@torch.inference_mode()
+def eval_model(model_name, questions_file, answers_file):
+ # Model
+ disable_torch_init()
+ model_name = os.path.expanduser(model_name)
+ tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False)
+ model = AutoModelForCausalLM.from_pretrained(model_name,
+ torch_dtype=torch.float16).cuda()
+
+
+ ques_file = open(os.path.expanduser(questions_file), "r")
+ ans_file = open(os.path.expanduser(answers_file), "w")
+ for i, line in enumerate(tqdm(ques_file)):
+ idx = json.loads(line)["question_id"]
+ qs = json.loads(line)["text"]
+ cat = json.loads(line)["category"]
+ conv = default_conversation.copy()
+ conv.append_message(conv.roles[0], qs)
+ prompt = conv.get_prompt()
+ inputs = tokenizer([prompt])
+ input_ids = torch.as_tensor(inputs.input_ids).cuda()
+ output_ids = model.generate(
+ input_ids,
+ do_sample=True,
+ use_cache=True,
+ temperature=0.7,
+ max_new_tokens=1024,)
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
+ try:
+ index = outputs.index(conv.sep, len(prompt))
+ except ValueError:
+ outputs += conv.sep
+ index = outputs.index(conv.sep, len(prompt))
+
+ outputs = outputs[len(prompt) + len(conv.roles[1]) + 2:index].strip()
+ ans_id = shortuuid.uuid()
+ ans_file.write(json.dumps({"question_id": idx,
+ "text": outputs,
+ "answer_id": ans_id,
+ "model_id": model_name,
+ "metadata": {}}) + "\n")
+ ans_file.flush()
+ ans_file.close()
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--model-name", type=str, default="facebook/opt-350m")
+ parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
+ parser.add_argument("--answers-file", type=str, default="answer.jsonl")
+ args = parser.parse_args()
+
+ eval_model(args.model_name, args.question_file, args.answers_file)
diff --git a/llava/eval/model_vqa.py b/llava/eval/model_vqa.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1fa3086951014fb8fc8e31d53fd1794192be1a9
--- /dev/null
+++ b/llava/eval/model_vqa.py
@@ -0,0 +1,102 @@
+import argparse
+import torch
+import os
+import json
+from tqdm import tqdm
+import shortuuid
+
+from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
+from llava.conversation import conv_templates, SeparatorStyle
+from llava.model.builder import load_pretrained_model
+from llava.utils import disable_torch_init
+from llava.mm_utils import tokenizer_image_token, process_images, get_model_name_from_path
+
+from PIL import Image
+import math
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+def eval_model(args):
+ # Model
+ disable_torch_init()
+ model_path = os.path.expanduser(args.model_path)
+ model_name = get_model_name_from_path(model_path)
+ tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
+
+ questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")]
+ questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
+ answers_file = os.path.expanduser(args.answers_file)
+ os.makedirs(os.path.dirname(answers_file), exist_ok=True)
+ ans_file = open(answers_file, "w")
+ for line in tqdm(questions):
+ idx = line["question_id"]
+ image_file = line["image"]
+ qs = line["text"]
+ cur_prompt = qs
+ if model.config.mm_use_im_start_end:
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
+ else:
+ qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
+
+ conv = conv_templates[args.conv_mode].copy()
+ conv.append_message(conv.roles[0], qs)
+ conv.append_message(conv.roles[1], None)
+ prompt = conv.get_prompt()
+
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
+
+ image = Image.open(os.path.join(args.image_folder, image_file)).convert('RGB')
+ image_tensor = process_images([image], image_processor, model.config)[0]
+ model = model.to(torch.float16)
+ # import pdb;pdb.set_trace()
+ with torch.inference_mode():
+ output_ids = model.generate(
+ input_ids,
+ images=image_tensor.unsqueeze(0).half().cuda(),
+ image_sizes=[image.size],
+ do_sample=True if args.temperature > 0 else False,
+ temperature=args.temperature,
+ top_p=args.top_p,
+ num_beams=args.num_beams,
+ # no_repeat_ngram_size=3,
+ max_new_tokens=1024,
+ use_cache=True)
+
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
+
+ ans_id = shortuuid.uuid()
+ ans_file.write(json.dumps({"question_id": idx,
+ "prompt": cur_prompt,
+ "text": outputs,
+ "answer_id": ans_id,
+ "model_id": model_name,
+ "metadata": {}}) + "\n")
+ ans_file.flush()
+ ans_file.close()
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
+ parser.add_argument("--model-base", type=str, default=None)
+ parser.add_argument("--image-folder", type=str, default="")
+ parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
+ parser.add_argument("--answers-file", type=str, default="answer.jsonl")
+ parser.add_argument("--conv-mode", type=str, default="llava_v1")
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--temperature", type=float, default=0.2)
+ parser.add_argument("--top_p", type=float, default=None)
+ parser.add_argument("--num_beams", type=int, default=1)
+ args = parser.parse_args()
+
+ eval_model(args)
diff --git a/llava/eval/model_vqa_loader.py b/llava/eval/model_vqa_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..e460424b86d43d1cf7d6f5b5d7fcf33f734af384
--- /dev/null
+++ b/llava/eval/model_vqa_loader.py
@@ -0,0 +1,145 @@
+import argparse
+import torch
+import os
+import json
+from tqdm import tqdm
+import shortuuid
+
+from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
+from llava.conversation import conv_templates, SeparatorStyle
+from llava.model.builder import load_pretrained_model
+from llava.utils import disable_torch_init
+from llava.mm_utils import tokenizer_image_token, process_images, get_model_name_from_path
+from torch.utils.data import Dataset, DataLoader
+
+from PIL import Image
+import math
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+# Custom dataset class
+class CustomDataset(Dataset):
+ def __init__(self, questions, image_folder, tokenizer, image_processor, model_config):
+ self.questions = questions
+ self.image_folder = image_folder
+ self.tokenizer = tokenizer
+ self.image_processor = image_processor
+ self.model_config = model_config
+
+ def __getitem__(self, index):
+ line = self.questions[index]
+ image_file = line["image"]
+ qs = line["text"]
+ if self.model_config.mm_use_im_start_end:
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
+ else:
+ qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
+
+ conv = conv_templates[args.conv_mode].copy()
+ conv.append_message(conv.roles[0], qs)
+ conv.append_message(conv.roles[1], None)
+ prompt = conv.get_prompt()
+
+ image = Image.open(os.path.join(self.image_folder, image_file)).convert('RGB')
+ image_tensor = process_images([image], self.image_processor, self.model_config)[0]
+
+ input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt')
+
+ return input_ids, image_tensor, image.size
+
+ def __len__(self):
+ return len(self.questions)
+
+
+def collate_fn(batch):
+ input_ids, image_tensors, image_sizes = zip(*batch)
+ input_ids = torch.stack(input_ids, dim=0)
+ image_tensors = torch.stack(image_tensors, dim=0)
+ return input_ids, image_tensors, image_sizes
+
+
+# DataLoader
+def create_data_loader(questions, image_folder, tokenizer, image_processor, model_config, batch_size=1, num_workers=4):
+ assert batch_size == 1, "batch_size must be 1"
+ dataset = CustomDataset(questions, image_folder, tokenizer, image_processor, model_config)
+ data_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False, collate_fn=collate_fn)
+ return data_loader
+
+
+def eval_model(args):
+ # Model
+ disable_torch_init()
+ model_path = os.path.expanduser(args.model_path)
+ model_name = get_model_name_from_path(model_path)
+ tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
+ # import pdb;pdb.set_trace()
+ model = model.to(torch.float16)
+ questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")]
+ questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
+ answers_file = os.path.expanduser(args.answers_file)
+ os.makedirs(os.path.dirname(answers_file), exist_ok=True)
+ ans_file = open(answers_file, "w")
+
+ if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode:
+ args.conv_mode = args.conv_mode + '_mmtag'
+ print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.')
+
+ data_loader = create_data_loader(questions, args.image_folder, tokenizer, image_processor, model.config)
+
+ for (input_ids, image_tensor, image_sizes), line in tqdm(zip(data_loader, questions), total=len(questions)):
+ idx = line["question_id"]
+ cur_prompt = line["text"]
+
+ input_ids = input_ids.to(device='cuda', non_blocking=True)
+
+ with torch.inference_mode():
+ output_ids = model.generate(
+ input_ids,
+ images=image_tensor.to(dtype=torch.float16, device='cuda', non_blocking=True),
+ image_sizes=image_sizes,
+ do_sample=True if args.temperature > 0 else False,
+ temperature=args.temperature,
+ top_p=args.top_p,
+ num_beams=args.num_beams,
+ max_new_tokens=args.max_new_tokens,
+ use_cache=True)
+
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
+
+ ans_id = shortuuid.uuid()
+ ans_file.write(json.dumps({"question_id": idx,
+ "prompt": cur_prompt,
+ "text": outputs,
+ "answer_id": ans_id,
+ "model_id": model_name,
+ "metadata": {}}) + "\n")
+ # ans_file.flush()
+ ans_file.close()
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
+ parser.add_argument("--model-base", type=str, default=None)
+ parser.add_argument("--image-folder", type=str, default="")
+ parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
+ parser.add_argument("--answers-file", type=str, default="answer.jsonl")
+ parser.add_argument("--conv-mode", type=str, default="llava_v1")
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--temperature", type=float, default=0.2)
+ parser.add_argument("--top_p", type=float, default=None)
+ parser.add_argument("--num_beams", type=int, default=1)
+ parser.add_argument("--max_new_tokens", type=int, default=128)
+ args = parser.parse_args()
+
+ eval_model(args)
diff --git a/llava/eval/model_vqa_mmbench.py b/llava/eval/model_vqa_mmbench.py
new file mode 100644
index 0000000000000000000000000000000000000000..93a9de9e17d33d9efeee9e1f65c6d058a911e47b
--- /dev/null
+++ b/llava/eval/model_vqa_mmbench.py
@@ -0,0 +1,160 @@
+import argparse
+import torch
+import os
+import json
+import pandas as pd
+from tqdm import tqdm
+import shortuuid
+
+from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
+from llava.conversation import conv_templates, SeparatorStyle
+from llava.model.builder import load_pretrained_model
+from llava.utils import disable_torch_init
+from llava.mm_utils import tokenizer_image_token, process_images, load_image_from_base64, get_model_name_from_path
+
+from PIL import Image
+import math
+
+
+all_options = ['A', 'B', 'C', 'D']
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+def is_none(value):
+ if value is None:
+ return True
+ if type(value) is float and math.isnan(value):
+ return True
+ if type(value) is str and value.lower() == 'nan':
+ return True
+ if type(value) is str and value.lower() == 'none':
+ return True
+ return False
+
+def get_options(row, options):
+ parsed_options = []
+ for option in options:
+ option_value = row[option]
+ if is_none(option_value):
+ break
+ parsed_options.append(option_value)
+ return parsed_options
+
+
+def eval_model(args):
+ # Model
+ disable_torch_init()
+ model_path = os.path.expanduser(args.model_path)
+ model_name = get_model_name_from_path(model_path)
+ tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
+
+ questions = pd.read_table(os.path.expanduser(args.question_file))
+ questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
+ answers_file = os.path.expanduser(args.answers_file)
+ os.makedirs(os.path.dirname(answers_file), exist_ok=True)
+ ans_file = open(answers_file, "w")
+
+ if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode:
+ args.conv_mode = args.conv_mode + '_mmtag'
+ print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.')
+
+ for index, row in tqdm(questions.iterrows(), total=len(questions)):
+ options = get_options(row, all_options)
+ cur_option_char = all_options[:len(options)]
+
+ if args.all_rounds:
+ num_rounds = len(options)
+ else:
+ num_rounds = 1
+
+ for round_idx in range(num_rounds):
+ idx = row['index']
+ question = row['question']
+ hint = row['hint']
+ image = load_image_from_base64(row['image'])
+ if not is_none(hint):
+ question = hint + '\n' + question
+ for option_char, option in zip(all_options[:len(options)], options):
+ question = question + '\n' + option_char + '. ' + option
+ qs = cur_prompt = question
+ if model.config.mm_use_im_start_end:
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
+ else:
+ qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
+
+ if args.single_pred_prompt:
+ if args.lang == 'cn':
+ qs = qs + '\n' + "่ฏท็ดๆฅๅ็ญ้้กนๅญๆฏใ"
+ else:
+ qs = qs + '\n' + "Answer with the option's letter from the given choices directly."
+
+ conv = conv_templates[args.conv_mode].copy()
+ conv.append_message(conv.roles[0], qs)
+ conv.append_message(conv.roles[1], None)
+ prompt = conv.get_prompt()
+
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
+
+ image_tensor = process_images([image], image_processor, model.config)[0]
+ model = model.to(torch.float16)
+ with torch.inference_mode():
+ output_ids = model.generate(
+ input_ids,
+ images=image_tensor.unsqueeze(0).half().cuda(),
+ image_sizes=[image.size],
+ do_sample=True if args.temperature > 0 else False,
+ temperature=args.temperature,
+ top_p=args.top_p,
+ num_beams=args.num_beams,
+ # no_repeat_ngram_size=3,
+ max_new_tokens=1024,
+ use_cache=True)
+
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
+
+ ans_id = shortuuid.uuid()
+ ans_file.write(json.dumps({"question_id": idx,
+ "round_id": round_idx,
+ "prompt": cur_prompt,
+ "text": outputs,
+ "options": options,
+ "option_char": cur_option_char,
+ "answer_id": ans_id,
+ "model_id": model_name,
+ "metadata": {}}) + "\n")
+ ans_file.flush()
+
+ # rotate options
+ options = options[1:] + options[:1]
+ cur_option_char = cur_option_char[1:] + cur_option_char[:1]
+ ans_file.close()
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
+ parser.add_argument("--model-base", type=str, default=None)
+ parser.add_argument("--image-folder", type=str, default="")
+ parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
+ parser.add_argument("--answers-file", type=str, default="answer.jsonl")
+ parser.add_argument("--conv-mode", type=str, default="llava_v1")
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--temperature", type=float, default=0.2)
+ parser.add_argument("--top_p", type=float, default=None)
+ parser.add_argument("--num_beams", type=int, default=1)
+ parser.add_argument("--all-rounds", action="store_true")
+ parser.add_argument("--single-pred-prompt", action="store_true")
+ parser.add_argument("--lang", type=str, default="en")
+ args = parser.parse_args()
+
+ eval_model(args)
diff --git a/llava/eval/model_vqa_science.py b/llava/eval/model_vqa_science.py
new file mode 100644
index 0000000000000000000000000000000000000000..90fc681a20ee72131862772107f6be572f010c99
--- /dev/null
+++ b/llava/eval/model_vqa_science.py
@@ -0,0 +1,111 @@
+import argparse
+import torch
+import os
+import json
+from tqdm import tqdm
+import shortuuid
+
+from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
+from llava.conversation import conv_templates, SeparatorStyle
+from llava.model.builder import load_pretrained_model
+from llava.utils import disable_torch_init
+from llava.mm_utils import tokenizer_image_token, process_images, get_model_name_from_path
+
+from PIL import Image
+import math
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+def eval_model(args):
+ # Model
+ disable_torch_init()
+ model_path = os.path.expanduser(args.model_path)
+ model_name = get_model_name_from_path(model_path)
+ tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
+
+ questions = json.load(open(os.path.expanduser(args.question_file), "r"))
+ questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
+ answers_file = os.path.expanduser(args.answers_file)
+ os.makedirs(os.path.dirname(answers_file), exist_ok=True)
+ ans_file = open(answers_file, "w")
+ for i, line in enumerate(tqdm(questions)):
+ idx = line["id"]
+ question = line['conversations'][0]
+ qs = question['value'].replace('', '').strip()
+ cur_prompt = qs
+
+ if 'image' in line:
+ image_file = line["image"]
+ image = Image.open(os.path.join(args.image_folder, image_file))
+ image_tensor = process_images([image], image_processor, model.config)[0]
+ images = image_tensor.unsqueeze(0).half().cuda()
+ image_sizes = [image.size]
+ if getattr(model.config, 'mm_use_im_start_end', False):
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
+ else:
+ qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
+ cur_prompt = '' + '\n' + cur_prompt
+ else:
+ images = None
+ image_sizes = None
+
+ if args.single_pred_prompt:
+ qs = qs + '\n' + "Answer with the option's letter from the given choices directly."
+ cur_prompt = cur_prompt + '\n' + "Answer with the option's letter from the given choices directly."
+
+ conv = conv_templates[args.conv_mode].copy()
+ conv.append_message(conv.roles[0], qs)
+ conv.append_message(conv.roles[1], None)
+ prompt = conv.get_prompt()
+
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
+
+ with torch.inference_mode():
+ output_ids = model.generate(
+ input_ids,
+ images=images,
+ image_sizes=image_sizes,
+ do_sample=True if args.temperature > 0 else False,
+ temperature=args.temperature,
+ max_new_tokens=1024,
+ use_cache=True,
+ )
+
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
+
+ ans_id = shortuuid.uuid()
+ ans_file.write(json.dumps({"question_id": idx,
+ "prompt": cur_prompt,
+ "text": outputs,
+ "answer_id": ans_id,
+ "model_id": model_name,
+ "metadata": {}}) + "\n")
+ ans_file.flush()
+ ans_file.close()
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
+ parser.add_argument("--model-base", type=str, default=None)
+ parser.add_argument("--image-folder", type=str, default="")
+ parser.add_argument("--question-file", type=str, default="tables/question.json")
+ parser.add_argument("--answers-file", type=str, default="answer.jsonl")
+ parser.add_argument("--conv-mode", type=str, default="llava_v0")
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--temperature", type=float, default=0.2)
+ parser.add_argument("--answer-prompter", action="store_true")
+ parser.add_argument("--single-pred-prompt", action="store_true")
+ args = parser.parse_args()
+
+ eval_model(args)
diff --git a/llava/eval/qa_baseline_gpt35.py b/llava/eval/qa_baseline_gpt35.py
new file mode 100644
index 0000000000000000000000000000000000000000..babab6e12b4bb8cfa74a7edfa5e56cd1b3e2bf6c
--- /dev/null
+++ b/llava/eval/qa_baseline_gpt35.py
@@ -0,0 +1,74 @@
+"""Generate answers with GPT-3.5"""
+# Note: you need to be using OpenAI Python v0.27.0 for the code below to work
+import argparse
+import json
+import os
+import time
+import concurrent.futures
+
+import openai
+import tqdm
+import shortuuid
+
+MODEL = 'gpt-3.5-turbo'
+MODEL_ID = 'gpt-3.5-turbo:20230327'
+
+def get_answer(question_id: int, question: str, max_tokens: int):
+ ans = {
+ 'answer_id': shortuuid.uuid(),
+ 'question_id': question_id,
+ 'model_id': MODEL_ID,
+ }
+ for _ in range(3):
+ try:
+ response = openai.ChatCompletion.create(
+ model=MODEL,
+ messages=[{
+ 'role': 'system',
+ 'content': 'You are a helpful assistant.'
+ }, {
+ 'role': 'user',
+ 'content': question,
+ }],
+ max_tokens=max_tokens,
+ )
+ ans['text'] = response['choices'][0]['message']['content']
+ return ans
+ except Exception as e:
+ print('[ERROR]', e)
+ ans['text'] = '#ERROR#'
+ time.sleep(1)
+ return ans
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='ChatGPT answer generation.')
+ parser.add_argument('-q', '--question')
+ parser.add_argument('-o', '--output')
+ parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output')
+ args = parser.parse_args()
+
+ questions_dict = {}
+ with open(os.path.expanduser(args.question)) as f:
+ for line in f:
+ if not line:
+ continue
+ q = json.loads(line)
+ questions_dict[q['question_id']] = q['text']
+
+ answers = []
+
+ with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor:
+ futures = []
+ for qid, question in questions_dict.items():
+ future = executor.submit(get_answer, qid, question, args.max_tokens)
+ futures.append(future)
+
+ for future in tqdm.tqdm(concurrent.futures.as_completed(futures), total=len(futures)):
+ answers.append(future.result())
+
+ answers.sort(key=lambda x: x['question_id'])
+
+ with open(os.path.expanduser(args.output), 'w') as f:
+ table = [json.dumps(ans) for ans in answers]
+ f.write('\n'.join(table))
diff --git a/llava/eval/run_llava.py b/llava/eval/run_llava.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d5d1c09643fc7016caed33d568eacefd266a7f9
--- /dev/null
+++ b/llava/eval/run_llava.py
@@ -0,0 +1,145 @@
+import argparse
+import torch
+
+from llava.constants import (
+ IMAGE_TOKEN_INDEX,
+ DEFAULT_IMAGE_TOKEN,
+ DEFAULT_IM_START_TOKEN,
+ DEFAULT_IM_END_TOKEN,
+ IMAGE_PLACEHOLDER,
+)
+from llava.conversation import conv_templates, SeparatorStyle
+from llava.model.builder import load_pretrained_model
+from llava.utils import disable_torch_init
+from llava.mm_utils import (
+ process_images,
+ tokenizer_image_token,
+ get_model_name_from_path,
+)
+
+from PIL import Image
+
+import requests
+from PIL import Image
+from io import BytesIO
+import re
+
+
+def image_parser(args):
+ out = args.image_file.split(args.sep)
+ return out
+
+
+def load_image(image_file):
+ if image_file.startswith("http") or image_file.startswith("https"):
+ response = requests.get(image_file)
+ image = Image.open(BytesIO(response.content)).convert("RGB")
+ else:
+ image = Image.open(image_file).convert("RGB")
+ return image
+
+
+def load_images(image_files):
+ out = []
+ for image_file in image_files:
+ image = load_image(image_file)
+ out.append(image)
+ return out
+
+
+def eval_model(args):
+ # Model
+ disable_torch_init()
+
+ model_name = get_model_name_from_path(args.model_path)
+ tokenizer, model, image_processor, context_len = load_pretrained_model(
+ args.model_path, args.model_base, model_name
+ )
+
+ qs = args.query
+ image_token_se = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN
+ if IMAGE_PLACEHOLDER in qs:
+ if model.config.mm_use_im_start_end:
+ qs = re.sub(IMAGE_PLACEHOLDER, image_token_se, qs)
+ else:
+ qs = re.sub(IMAGE_PLACEHOLDER, DEFAULT_IMAGE_TOKEN, qs)
+ else:
+ if model.config.mm_use_im_start_end:
+ qs = image_token_se + "\n" + qs
+ else:
+ qs = DEFAULT_IMAGE_TOKEN + "\n" + qs
+
+ if "llama-2" in model_name.lower():
+ conv_mode = "llava_llama_2"
+ elif "mistral" in model_name.lower():
+ conv_mode = "mistral_instruct"
+ elif "v1.6-34b" in model_name.lower():
+ conv_mode = "chatml_direct"
+ elif "v1" in model_name.lower():
+ conv_mode = "llava_v1"
+ elif "mpt" in model_name.lower():
+ conv_mode = "mpt"
+ else:
+ conv_mode = "llava_v0"
+
+ if args.conv_mode is not None and conv_mode != args.conv_mode:
+ print(
+ "[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}".format(
+ conv_mode, args.conv_mode, args.conv_mode
+ )
+ )
+ else:
+ args.conv_mode = conv_mode
+
+ conv = conv_templates[args.conv_mode].copy()
+ conv.append_message(conv.roles[0], qs)
+ conv.append_message(conv.roles[1], None)
+ prompt = conv.get_prompt()
+
+ image_files = image_parser(args)
+ images = load_images(image_files)
+ image_sizes = [x.size for x in images]
+ images_tensor = process_images(
+ images,
+ image_processor,
+ model.config
+ ).to(model.device, dtype=torch.float16)
+
+ input_ids = (
+ tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt")
+ .unsqueeze(0)
+ .cuda()
+ )
+ model.to(torch.float16)
+ with torch.inference_mode():
+ output_ids = model.generate(
+ input_ids,
+ images=images_tensor,
+ image_sizes=image_sizes,
+ do_sample=True if args.temperature > 0 else False,
+ temperature=args.temperature,
+ top_p=args.top_p,
+ num_beams=args.num_beams,
+ max_new_tokens=args.max_new_tokens,
+ use_cache=True,
+ )
+
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
+ print(outputs)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
+ parser.add_argument("--model-base", type=str, default=None)
+ parser.add_argument("--image-file", type=str, required=True)
+ parser.add_argument("--query", type=str, required=True)
+ parser.add_argument("--conv-mode", type=str, default=None)
+ parser.add_argument("--sep", type=str, default=",")
+ parser.add_argument("--temperature", type=float, default=0.2)
+ parser.add_argument("--top_p", type=float, default=None)
+ parser.add_argument("--num_beams", type=int, default=1)
+ parser.add_argument("--max_new_tokens", type=int, default=512)
+ args = parser.parse_args()
+
+ eval_model(args)
diff --git a/llava/eval/run_llava_backup.py b/llava/eval/run_llava_backup.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d6238a5d3398f09ba9c8ecaabb47c3fd3cb891f
--- /dev/null
+++ b/llava/eval/run_llava_backup.py
@@ -0,0 +1,220 @@
+import argparse
+import torch
+import os
+import json
+from tqdm import tqdm
+
+from llava.constants import (
+ IMAGE_TOKEN_INDEX,
+ DEFAULT_IMAGE_TOKEN,
+ DEFAULT_IM_START_TOKEN,
+ DEFAULT_IM_END_TOKEN,
+ IMAGE_PLACEHOLDER,
+)
+from llava.conversation import conv_templates, SeparatorStyle
+from llava.model.builder import load_pretrained_model
+from llava.utils import disable_torch_init
+from llava.mm_utils import (
+ process_images,
+ tokenizer_image_token,
+ get_model_name_from_path,
+)
+
+from PIL import Image
+
+import requests
+from PIL import Image
+from io import BytesIO
+import re
+
+
+def image_parser(args):
+ out = args.image_file.split(args.sep)
+ return out
+
+
+def load_image(image_file):
+ if image_file.startswith("http") or image_file.startswith("https"):
+ response = requests.get(image_file)
+ image = Image.open(BytesIO(response.content)).convert("RGB")
+ else:
+ image = Image.open(image_file).convert("RGB")
+ return image
+
+
+def load_images(image_files):
+ out = []
+ for image_file in image_files:
+ image = load_image(image_file)
+ out.append(image)
+ return out
+
+
+def eval_model(args):
+ # Model
+ disable_torch_init()
+
+ model_name = get_model_name_from_path(args.model_path)
+ # import pdb;pdb.set_trace()
+ tokenizer, model, image_processor, context_len = load_pretrained_model(
+ args.model_path, args.model_base, model_name
+ )
+ model=model.to(torch.float16)
+ # import pdb;pdb.set_trace()
+
+ if "llama-2" in model_name.lower():
+ conv_mode = "llava_llama_2"
+ elif "mistral" in model_name.lower():
+ conv_mode = "mistral_instruct"
+ elif "v1.6-34b" in model_name.lower():
+ conv_mode = "chatml_direct"
+ elif "v1" in model_name.lower():
+ conv_mode = "llava_v1"
+ elif "mpt" in model_name.lower():
+ conv_mode = "mpt"
+ else:
+ conv_mode = "llava_v0"
+
+ if args.conv_mode is not None and conv_mode != args.conv_mode:
+ print(
+ "[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}".format(
+ conv_mode, args.conv_mode, args.conv_mode
+ )
+ )
+ else:
+ args.conv_mode = conv_mode
+
+ base_path = args.base_path
+ answers = []
+ # with open(os.path.join(base_path, "annotations.json"), "r") as reader:
+ # with open('/home/aiops/wangzh/data/blink/BLINK/Counting/output.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/blink/BLINK/Visual_Correspondence/output.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/blink/BLINK/Jigsaw/output.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/CV-Bench/test3d-depth.jsonl', "r") as reader:
+ # with open('/home/aiops/wangzh/data/CV-Bench/test3d.jsonl', "r") as reader:
+ # with open('/home/aiops/wangzh/data/blink/BLINK/Multi-view_Reasoning/output.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/blink/BLINK/Object_Localization/output.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/blink/BLINK/Relative_Depth/output.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/blink/BLINK/Spatial_Relation/output.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/all.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/realworldqa/updated.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/object_orientation.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/relative_depth.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/relative_size.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/relative_spatial_position.json', "r") as reader:
+ with open('/home/aiops/wangzh/llava-spat/outdoor.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/scanner/indoor-new/all.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/scanner/indoor/orientation.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/scanner/indoor/relative_depth.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/scanner/indoor/relative_size.json', "r") as reader:
+ # with open('/home/aiops/wangzh/data/scanner/indoor/spatial_relation.json', "r") as reader:
+ data = json.load(reader)
+ # for line in tqdm(reader):
+
+ for line in tqdm(data):
+ # data = json.loads(line.strip())
+ # path1 = os.path.join('/home/aiops/wangzh/data/blink/BLINK/Jigsaw/output_images',data['image_1'])
+ # path2 = os.path.join('/home/aiops/wangzh/data/blink/BLINK/Jigsaw/output_images',data['image_2'])
+ # path3 = os.path.join('/home/aiops/wangzh/data/blink/BLINK/Jigsaw/output_images',data['image_3'])
+ # args.image_file = f"{path1},{path2},{path3}"
+ # path1 = os.path.join('/home/aiops/wangzh/data/blink/BLINK/Visual_Correspondence/output_images',data['image_1'])
+ # path2 = os.path.join('/home/aiops/wangzh/data/blink/BLINK/Visual_Correspondence/output_images',data['image_2'])
+ # args.image_file = f"{path1},{path2}"
+ # args.image_file = os.path.join('/home/aiops/wangzh/data/blink/BLINK/Spatial_Relation/output_images',data['image_1'])
+ # args.image_file = os.path.join('/home/aiops/wangzh/data/CV-Bench',data['filename'])
+
+ # qs = f"Please answer the following questions with only one :{data['prompt']}"
+ # qs = f"{data['prompt']}Make a choice and explain it."
+ # qs = data['prompt']
+ # qs = f'''You are given a question with four possible answers labeled as (A), (B), (C),and (D). Please read the question carefully and choose the most appropriate answer by responding with the corresponding letter (A, B, C, or D) only. Do not provide any additional explanation or text.
+ # {data['prompt']}'''
+
+ # import pdb;pdb.set_trace()
+ # scen = line['scene_id']
+ # args.image_file = os.path.join('/home/aiops/wangzh/data/realworldqa/output_images',data['image'])
+ # args.image_file = os.path.join('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/pic_all',line['image'])
+ args.image_file = os.path.join('/home/aiops/wangzh/data/RGBD-benchmark/out_doors/pic_all',line['image'])
+ # args.image_file = os.path.join('/home/aiops/wangzh/data/scanner/scannet_2d_HR3',scen,'color',line['image'])
+ # qs = f'''You will see an image along with four corresponding descriptions (captions). Please carefully observe the image and select the description that best matches the content of the image. Choose one option from (A), (B), (C), or (D).
+ # Options: (A){line['captions'][0]}\n(B){line['captions'][1]}\n(C){line['captions'][2]}\n(D){line['captions'][3]}\nPlease provide your answer with only one of the options and nothing else.'''
+ # qs1 = f'''Please carefully observe the image and select the description that best matches the content of the image. Choose one option from (A), (B), (C), or (D).
+ # Options: (A){line['captions'][0]}\n(B){line['captions'][1]}\n(C){line['captions'][2]}\n(D){line['captions'][3]}\nPlease provide your answer with only one of the options and nothing else.'''
+ # qs2 = f''' Choose one option from (A), (B), (C), or (D).
+ # Options: (A){line['captions'][0]}\n(B){line['captions'][1]}\n(C){line['captions'][2]}\n(D){line['captions'][3]}\nPlease provide your answer with only one of the options and nothing else.'''
+ # qs3 = f'''Fully consider the spatial relationship of the objects in the picture. Choose one option from (A), (B), (C), or (D).
+ # Options: (A){line['captions'][0]}\n(B){line['captions'][1]}\n(C){line['captions'][2]}\n(D){line['captions'][3]}\n'''
+ qs = line['prompt']
+ qs = qs
+ # qs = data['question']
+
+ # args.image_file = os.path.join(base_path, data["image"])
+ # qs = data["question"]
+
+ # qs = args.query
+ image_token_se = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN
+ if IMAGE_PLACEHOLDER in qs:
+ if model.config.mm_use_im_start_end:
+ qs = re.sub(IMAGE_PLACEHOLDER, image_token_se, qs)
+ else:
+ qs = re.sub(IMAGE_PLACEHOLDER, DEFAULT_IMAGE_TOKEN, qs)
+ else:
+ if model.config.mm_use_im_start_end:
+ qs = image_token_se + "\n" + qs
+ else:
+ qs = DEFAULT_IMAGE_TOKEN + "\n" + qs
+
+ conv = conv_templates[args.conv_mode].copy()
+ conv.append_message(conv.roles[0], qs)
+ conv.append_message(conv.roles[1], None)
+ prompt = conv.get_prompt()
+
+ image_files = image_parser(args)
+ images = load_images(image_files)
+ image_sizes = [x.size for x in images]
+ images_tensor = process_images(
+ images,
+ image_processor,
+ model.config
+ ).to(model.device, dtype=torch.float16)
+
+ input_ids = (
+ tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt")
+ .unsqueeze(0)
+ .cuda()
+ )
+ # import pdb;pdb.set_trace()
+ with torch.inference_mode():
+ output_ids = model.generate(
+ input_ids,
+ images=images_tensor,
+ image_sizes=image_sizes,
+ do_sample=True if args.temperature > 0 else False,
+ temperature=args.temperature,
+ top_p=args.top_p,
+ num_beams=args.num_beams,
+ max_new_tokens=args.max_new_tokens,
+ use_cache=True,
+ )
+
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip().replace("\n", "")
+ answers.append(outputs)
+ # print(รoutputs)
+ with open(os.path.join('.',f"{model_name}_answers.txt"), "w") as writer:
+ writer.writelines([answer + "\n" for answer in answers])
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
+ parser.add_argument("--model-base", type=str, default=None)
+ parser.add_argument("--image-file", type=str, required=True)
+ parser.add_argument("--query", type=str, required=True)
+ parser.add_argument("--conv-mode", type=str, default=None)
+ parser.add_argument("--sep", type=str, default=",")
+ parser.add_argument("--temperature", type=float, default=0.2)
+ parser.add_argument("--top_p", type=float, default=None)
+ parser.add_argument("--num_beams", type=int, default=1)
+ parser.add_argument("--max_new_tokens", type=int, default=512)
+ args = parser.parse_args()
+
+ eval_model(args)
diff --git a/llava/eval/summarize_gpt_review.py b/llava/eval/summarize_gpt_review.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f796a3880341739677a5fe3bfbcc90515a0f324
--- /dev/null
+++ b/llava/eval/summarize_gpt_review.py
@@ -0,0 +1,60 @@
+import json
+import os
+from collections import defaultdict
+
+import numpy as np
+
+import argparse
+
+def parse_args():
+ parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.')
+ parser.add_argument('-d', '--dir', default=None)
+ parser.add_argument('-v', '--version', default=None)
+ parser.add_argument('-s', '--select', nargs='*', default=None)
+ parser.add_argument('-f', '--files', nargs='*', default=[])
+ parser.add_argument('-i', '--ignore', nargs='*', default=[])
+ return parser.parse_args()
+
+
+if __name__ == '__main__':
+ args = parse_args()
+
+ if args.ignore is not None:
+ args.ignore = [int(x) for x in args.ignore]
+
+ if len(args.files) > 0:
+ review_files = args.files
+ else:
+ 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_') or 'review' in args.dir)]
+
+ for review_file in sorted(review_files):
+ config = os.path.basename(review_file).replace('gpt4_text_', '').replace('.jsonl', '')
+ if args.select is not None and any(x not in config for x in args.select):
+ continue
+ if '0613' in config:
+ version = '0613'
+ else:
+ version = '0314'
+ if args.version is not None and args.version != version:
+ continue
+ scores = defaultdict(list)
+ print(config)
+ with open(os.path.join(args.dir, review_file) if args.dir is not None else review_file) as f:
+ for review_str in f:
+ review = json.loads(review_str)
+ if review['question_id'] in args.ignore:
+ continue
+ if 'category' in review:
+ scores[review['category']].append(review['tuple'])
+ scores['all'].append(review['tuple'])
+ else:
+ if 'tuple' in review:
+ scores['all'].append(review['tuple'])
+ else:
+ scores['all'].append(review['score'])
+ for k, v in sorted(scores.items()):
+ stats = np.asarray(v).mean(0).tolist()
+ stats = [round(x, 3) for x in stats]
+ # print(k, stats, round(stats[1]/stats[0]*100, 1))
+ print(k, round(stats[1]/stats[0]*100, 1), round(stats[0] * 10, 1), round(stats[1] * 10, 1))
+ print('=================================')
diff --git a/llava/eval/webpage/figures/alpaca.png b/llava/eval/webpage/figures/alpaca.png
new file mode 100644
index 0000000000000000000000000000000000000000..497a702ab5efb88b8f67333eae81645eecea78cd
Binary files /dev/null and b/llava/eval/webpage/figures/alpaca.png differ
diff --git a/llava/eval/webpage/figures/bard.jpg b/llava/eval/webpage/figures/bard.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..5b32cb501799175e3829f92b014795ad1cbee79d
Binary files /dev/null and b/llava/eval/webpage/figures/bard.jpg differ
diff --git a/llava/eval/webpage/figures/chatgpt.svg b/llava/eval/webpage/figures/chatgpt.svg
new file mode 100644
index 0000000000000000000000000000000000000000..8147382a3152de03c24b4cd91f9870ced1a95d54
--- /dev/null
+++ b/llava/eval/webpage/figures/chatgpt.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/llava/eval/webpage/figures/llama.jpg b/llava/eval/webpage/figures/llama.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..7217e5dc1bb683453204a20890f01f5806ce12cf
Binary files /dev/null and b/llava/eval/webpage/figures/llama.jpg differ
diff --git a/llava/eval/webpage/figures/swords_FILL0_wght300_GRAD0_opsz48.svg b/llava/eval/webpage/figures/swords_FILL0_wght300_GRAD0_opsz48.svg
new file mode 100644
index 0000000000000000000000000000000000000000..3bee468d34515fdcbef1a8b8803c9fc4f7dc0b34
--- /dev/null
+++ b/llava/eval/webpage/figures/swords_FILL0_wght300_GRAD0_opsz48.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/llava/eval/webpage/figures/vicuna.jpeg b/llava/eval/webpage/figures/vicuna.jpeg
new file mode 100644
index 0000000000000000000000000000000000000000..e7883dc886b96d078883e01aefd16792133e204a
Binary files /dev/null and b/llava/eval/webpage/figures/vicuna.jpeg differ
diff --git a/llava/eval/webpage/index.html b/llava/eval/webpage/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..c2e3cf020ba7d8e064f2cd801788a5d2d50b97da
--- /dev/null
+++ b/llava/eval/webpage/index.html
@@ -0,0 +1,162 @@
+
+
+
+
+
+ Who's GPT-4's favorite? Battles between State-of-the-Art Chatbots
+
+
+
+
+
+
+
+
+
+
Who's GPT-4's favorite? Battles between State-of-the-Art Chatbots