Uploading folder contents
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .devcontainer/Dockerfile +53 -0
- .devcontainer/devcontainer.env +2 -0
- .devcontainer/devcontainer.json +71 -0
- .devcontainer/postCreateCommand.sh +45 -0
- .dockerignore +21 -0
- .editorconfig +18 -0
- .gitattributes +31 -35
- .github/ISSUE_TEMPLATE/1-usage.yaml +31 -0
- .github/ISSUE_TEMPLATE/2-feature-request.yaml +13 -0
- .github/ISSUE_TEMPLATE/3-question.yaml +13 -0
- .github/ISSUE_TEMPLATE/4-discussion.yaml +13 -0
- .gitignore +35 -0
- LICENSE +201 -0
- README.md +463 -0
- alpha_clip_final/__init__.py +1 -0
- alpha_clip_final/alpha_clip_new.py +252 -0
- alpha_clip_final/bpe_simple_vocab_16e6.txt.gz +3 -0
- alpha_clip_final/model_new.py +1009 -0
- alpha_clip_final/simple_tokenizer.py +132 -0
- answer_check.py +157 -0
- blink_check.py +158 -0
- check.py +17 -0
- cog.yaml +37 -0
- cv_check.py +157 -0
- depth_anything_v2/dinov2.py +416 -0
- depth_anything_v2/dinov2_layers/__init__.py +11 -0
- depth_anything_v2/dinov2_layers/attention.py +83 -0
- depth_anything_v2/dinov2_layers/block.py +252 -0
- depth_anything_v2/dinov2_layers/drop_path.py +35 -0
- depth_anything_v2/dinov2_layers/layer_scale.py +28 -0
- depth_anything_v2/dinov2_layers/mlp.py +41 -0
- depth_anything_v2/dinov2_layers/patch_embed.py +89 -0
- depth_anything_v2/dinov2_layers/swiglu_ffn.py +63 -0
- depth_anything_v2/dpt.py +231 -0
- depth_anything_v2/util/blocks.py +148 -0
- depth_anything_v2/util/transform.py +158 -0
- docs/Customize_Component.md +20 -0
- docs/Data.md +29 -0
- docs/Evaluation.md +167 -0
- docs/Finetune_Custom_Data.md +37 -0
- docs/Intel.md +7 -0
- docs/LLaVA_Bench.md +31 -0
- docs/LLaVA_from_LLaMA2.md +29 -0
- docs/LoRA.md +46 -0
- docs/MODEL_ZOO.md +150 -0
- docs/ScienceQA.md +53 -0
- docs/Windows.md +27 -0
- docs/macOS.md +29 -0
- eval.sh +4 -0
- finetune.sh +38 -0
.devcontainer/Dockerfile
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM mcr.microsoft.com/devcontainers/base:ubuntu-20.04
|
| 2 |
+
|
| 3 |
+
SHELL [ "bash", "-c" ]
|
| 4 |
+
|
| 5 |
+
# update apt and install packages
|
| 6 |
+
RUN apt update && \
|
| 7 |
+
apt install -yq \
|
| 8 |
+
ffmpeg \
|
| 9 |
+
dkms \
|
| 10 |
+
build-essential
|
| 11 |
+
|
| 12 |
+
# add user tools
|
| 13 |
+
RUN sudo apt install -yq \
|
| 14 |
+
jq \
|
| 15 |
+
jp \
|
| 16 |
+
tree \
|
| 17 |
+
tldr
|
| 18 |
+
|
| 19 |
+
# add git-lfs and install
|
| 20 |
+
RUN curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash && \
|
| 21 |
+
sudo apt-get install -yq git-lfs && \
|
| 22 |
+
git lfs install
|
| 23 |
+
|
| 24 |
+
############################################
|
| 25 |
+
# Setup user
|
| 26 |
+
############################################
|
| 27 |
+
|
| 28 |
+
USER vscode
|
| 29 |
+
|
| 30 |
+
# install azcopy, a tool to copy to/from blob storage
|
| 31 |
+
# for more info: https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azcopy-blobs-upload#upload-a-file
|
| 32 |
+
RUN cd /tmp && \
|
| 33 |
+
wget https://azcopyvnext.azureedge.net/release20230123/azcopy_linux_amd64_10.17.0.tar.gz && \
|
| 34 |
+
tar xvf azcopy_linux_amd64_10.17.0.tar.gz && \
|
| 35 |
+
mkdir -p ~/.local/bin && \
|
| 36 |
+
mv azcopy_linux_amd64_10.17.0/azcopy ~/.local/bin && \
|
| 37 |
+
chmod +x ~/.local/bin/azcopy && \
|
| 38 |
+
rm -rf azcopy_linux_amd64*
|
| 39 |
+
|
| 40 |
+
# Setup conda
|
| 41 |
+
RUN cd /tmp && \
|
| 42 |
+
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh && \
|
| 43 |
+
bash ./Miniconda3-latest-Linux-x86_64.sh -b && \
|
| 44 |
+
rm ./Miniconda3-latest-Linux-x86_64.sh
|
| 45 |
+
|
| 46 |
+
# Install dotnet
|
| 47 |
+
RUN cd /tmp && \
|
| 48 |
+
wget https://dot.net/v1/dotnet-install.sh && \
|
| 49 |
+
chmod +x dotnet-install.sh && \
|
| 50 |
+
./dotnet-install.sh --channel 7.0 && \
|
| 51 |
+
./dotnet-install.sh --channel 3.1 && \
|
| 52 |
+
rm ./dotnet-install.sh
|
| 53 |
+
|
.devcontainer/devcontainer.env
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
SAMPLE_ENV_VAR1="Sample Value"
|
| 2 |
+
SAMPLE_ENV_VAR2=332431bf-68bf
|
.devcontainer/devcontainer.json
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "LLaVA",
|
| 3 |
+
"build": {
|
| 4 |
+
"dockerfile": "Dockerfile",
|
| 5 |
+
"context": "..",
|
| 6 |
+
"args": {}
|
| 7 |
+
},
|
| 8 |
+
"features": {
|
| 9 |
+
"ghcr.io/devcontainers/features/docker-in-docker:2": {},
|
| 10 |
+
"ghcr.io/devcontainers/features/azure-cli:1": {},
|
| 11 |
+
"ghcr.io/azure/azure-dev/azd:0": {},
|
| 12 |
+
"ghcr.io/devcontainers/features/powershell:1": {},
|
| 13 |
+
"ghcr.io/devcontainers/features/common-utils:2": {},
|
| 14 |
+
"ghcr.io/devcontainers-contrib/features/zsh-plugins:0": {},
|
| 15 |
+
},
|
| 16 |
+
// "forwardPorts": [],
|
| 17 |
+
"postCreateCommand": "bash ./.devcontainer/postCreateCommand.sh",
|
| 18 |
+
"customizations": {
|
| 19 |
+
"vscode": {
|
| 20 |
+
"settings": {
|
| 21 |
+
"python.analysis.autoImportCompletions": true,
|
| 22 |
+
"python.analysis.autoImportUserSymbols": true,
|
| 23 |
+
"python.defaultInterpreterPath": "~/miniconda3/envs/llava/bin/python",
|
| 24 |
+
"python.formatting.provider": "yapf",
|
| 25 |
+
"python.linting.enabled": true,
|
| 26 |
+
"python.linting.flake8Enabled": true,
|
| 27 |
+
"isort.check": true,
|
| 28 |
+
"dev.containers.copyGitConfig": true,
|
| 29 |
+
"terminal.integrated.defaultProfile.linux": "zsh",
|
| 30 |
+
"terminal.integrated.profiles.linux": {
|
| 31 |
+
"zsh": {
|
| 32 |
+
"path": "/usr/bin/zsh"
|
| 33 |
+
},
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
"extensions": [
|
| 37 |
+
"aaron-bond.better-comments",
|
| 38 |
+
"eamodio.gitlens",
|
| 39 |
+
"EditorConfig.EditorConfig",
|
| 40 |
+
"foxundermoon.shell-format",
|
| 41 |
+
"GitHub.copilot-chat",
|
| 42 |
+
"GitHub.copilot-labs",
|
| 43 |
+
"GitHub.copilot",
|
| 44 |
+
"lehoanganh298.json-lines-viewer",
|
| 45 |
+
"mhutchie.git-graph",
|
| 46 |
+
"ms-azuretools.vscode-docker",
|
| 47 |
+
"ms-dotnettools.dotnet-interactive-vscode",
|
| 48 |
+
"ms-python.flake8",
|
| 49 |
+
"ms-python.isort",
|
| 50 |
+
"ms-python.python",
|
| 51 |
+
"ms-python.vscode-pylance",
|
| 52 |
+
"njpwerner.autodocstring",
|
| 53 |
+
"redhat.vscode-yaml",
|
| 54 |
+
"stkb.rewrap",
|
| 55 |
+
"yzhang.markdown-all-in-one",
|
| 56 |
+
]
|
| 57 |
+
}
|
| 58 |
+
},
|
| 59 |
+
"mounts": [],
|
| 60 |
+
"runArgs": [
|
| 61 |
+
"--gpus",
|
| 62 |
+
"all",
|
| 63 |
+
// "--ipc",
|
| 64 |
+
// "host",
|
| 65 |
+
"--ulimit",
|
| 66 |
+
"memlock=-1",
|
| 67 |
+
"--env-file",
|
| 68 |
+
".devcontainer/devcontainer.env"
|
| 69 |
+
],
|
| 70 |
+
// "remoteUser": "root"
|
| 71 |
+
}
|
.devcontainer/postCreateCommand.sh
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
git config --global safe.directory '*'
|
| 2 |
+
git config --global core.editor "code --wait"
|
| 3 |
+
git config --global pager.branch false
|
| 4 |
+
|
| 5 |
+
# Set AZCOPY concurrency to auto
|
| 6 |
+
echo "export AZCOPY_CONCURRENCY_VALUE=AUTO" >> ~/.zshrc
|
| 7 |
+
echo "export AZCOPY_CONCURRENCY_VALUE=AUTO" >> ~/.bashrc
|
| 8 |
+
|
| 9 |
+
# Activate conda by default
|
| 10 |
+
echo ". /home/vscode/miniconda3/bin/activate" >> ~/.zshrc
|
| 11 |
+
echo ". /home/vscode/miniconda3/bin/activate" >> ~/.bashrc
|
| 12 |
+
|
| 13 |
+
# Use llava environment by default
|
| 14 |
+
echo "conda activate llava" >> ~/.zshrc
|
| 15 |
+
echo "conda activate llava" >> ~/.bashrc
|
| 16 |
+
|
| 17 |
+
# Add dotnet to PATH
|
| 18 |
+
echo 'export PATH="$PATH:$HOME/.dotnet"' >> ~/.bashrc
|
| 19 |
+
echo 'export PATH="$PATH:$HOME/.dotnet"' >> ~/.zshrc
|
| 20 |
+
|
| 21 |
+
# Create and activate llava environment
|
| 22 |
+
source /home/vscode/miniconda3/bin/activate
|
| 23 |
+
conda create -y -q -n llava python=3.10
|
| 24 |
+
conda activate llava
|
| 25 |
+
|
| 26 |
+
# Install Nvidia Cuda Compiler
|
| 27 |
+
conda install -y -c nvidia cuda-compiler
|
| 28 |
+
|
| 29 |
+
pip install pre-commit==3.0.2
|
| 30 |
+
|
| 31 |
+
# Install package locally
|
| 32 |
+
pip install --upgrade pip # enable PEP 660 support
|
| 33 |
+
pip install -e .
|
| 34 |
+
|
| 35 |
+
# Install additional packages for training
|
| 36 |
+
pip install -e ".[train]"
|
| 37 |
+
pip install flash-attn --no-build-isolation
|
| 38 |
+
|
| 39 |
+
# Download checkpoints to location outside of the repo
|
| 40 |
+
git clone https://huggingface.co/liuhaotian/llava-v1.5-7b ~/llava-v1.5-7b
|
| 41 |
+
|
| 42 |
+
# Commented because it is unlikely for users to have enough local GPU memory to load the model
|
| 43 |
+
# git clone https://huggingface.co/liuhaotian/llava-v1.5-13b ~/llava-v1.5-13b
|
| 44 |
+
|
| 45 |
+
echo "postCreateCommand.sh COMPLETE!"
|
.dockerignore
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# The .dockerignore file excludes files from the container build process.
|
| 2 |
+
#
|
| 3 |
+
# https://docs.docker.com/engine/reference/builder/#dockerignore-file
|
| 4 |
+
|
| 5 |
+
# Exclude Git files
|
| 6 |
+
.git
|
| 7 |
+
.github
|
| 8 |
+
.gitignore
|
| 9 |
+
|
| 10 |
+
# Exclude Python cache files
|
| 11 |
+
__pycache__
|
| 12 |
+
.mypy_cache
|
| 13 |
+
.pytest_cache
|
| 14 |
+
.ruff_cache
|
| 15 |
+
|
| 16 |
+
# Exclude Python virtual environment
|
| 17 |
+
/venv
|
| 18 |
+
|
| 19 |
+
# Exclude some weights
|
| 20 |
+
/openai
|
| 21 |
+
/liuhaotian
|
.editorconfig
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
root = true
|
| 2 |
+
|
| 3 |
+
# Unix-style newlines with a newline ending every file
|
| 4 |
+
[*]
|
| 5 |
+
end_of_line = lf
|
| 6 |
+
insert_final_newline = true
|
| 7 |
+
trim_trailing_whitespace = true
|
| 8 |
+
charset = utf-8
|
| 9 |
+
|
| 10 |
+
# 4 space indentation
|
| 11 |
+
[*.{py,json}]
|
| 12 |
+
indent_style = space
|
| 13 |
+
indent_size = 4
|
| 14 |
+
|
| 15 |
+
# 2 space indentation
|
| 16 |
+
[*.{md,sh,yaml,yml}]
|
| 17 |
+
indent_style = space
|
| 18 |
+
indent_size = 2
|
.gitattributes
CHANGED
|
@@ -1,35 +1,31 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
*.
|
| 11 |
-
*.
|
| 12 |
-
*.
|
| 13 |
-
*.
|
| 14 |
-
*.
|
| 15 |
-
*.
|
| 16 |
-
*.
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
*.
|
| 21 |
-
*.
|
| 22 |
-
*.
|
| 23 |
-
*.
|
| 24 |
-
*.
|
| 25 |
-
*.
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
*.
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
+
# https://git-scm.com/docs/gitattributes
|
| 2 |
+
|
| 3 |
+
# Set the default behavior, in case people don't have core.autocrlf set.
|
| 4 |
+
# https://git-scm.com/docs/gitattributes#_end_of_line_conversion
|
| 5 |
+
* text=auto
|
| 6 |
+
|
| 7 |
+
# common python attributes, taken from https://github.com/alexkaratarakis/gitattributes/blob/710900479a2bedeec7003d381719521ffbb18bf8/Python.gitattributes
|
| 8 |
+
# Source files
|
| 9 |
+
# ============
|
| 10 |
+
*.pxd text diff=python
|
| 11 |
+
*.py text diff=python
|
| 12 |
+
*.py3 text diff=python
|
| 13 |
+
*.pyw text diff=python
|
| 14 |
+
*.pyx text diff=python
|
| 15 |
+
*.pyz text diff=python
|
| 16 |
+
*.pyi text diff=python
|
| 17 |
+
|
| 18 |
+
# Binary files
|
| 19 |
+
# ============
|
| 20 |
+
*.db binary
|
| 21 |
+
*.p binary
|
| 22 |
+
*.pkl binary
|
| 23 |
+
*.pickle binary
|
| 24 |
+
*.pyc binary export-ignore
|
| 25 |
+
*.pyo binary export-ignore
|
| 26 |
+
*.pyd binary
|
| 27 |
+
|
| 28 |
+
# Jupyter notebook
|
| 29 |
+
*.ipynb text eol=lf
|
| 30 |
+
alpha_clip_final/bpe_simple_vocab_16e6.txt.gz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
images/demo_cli.gif filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
.github/ISSUE_TEMPLATE/1-usage.yaml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Usage issues
|
| 2 |
+
description: Report issues in usage.
|
| 3 |
+
title: "[Usage] "
|
| 4 |
+
body:
|
| 5 |
+
- type: markdown
|
| 6 |
+
attributes:
|
| 7 |
+
value: |
|
| 8 |
+
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 :)
|
| 9 |
+
- type: textarea
|
| 10 |
+
id: what-happened
|
| 11 |
+
attributes:
|
| 12 |
+
label: Describe the issue
|
| 13 |
+
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.
|
| 14 |
+
placeholder: Issue
|
| 15 |
+
value: |
|
| 16 |
+
Issue:
|
| 17 |
+
|
| 18 |
+
Command:
|
| 19 |
+
```
|
| 20 |
+
PASTE THE COMMANDS HERE.
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
Log:
|
| 24 |
+
```
|
| 25 |
+
PASTE THE LOGS HERE.
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
Screenshots:
|
| 29 |
+
You may attach screenshots if it better explains the issue.
|
| 30 |
+
validations:
|
| 31 |
+
required: true
|
.github/ISSUE_TEMPLATE/2-feature-request.yaml
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Feature Request
|
| 2 |
+
description: Request for a new feature
|
| 3 |
+
title: "[Feature request] "
|
| 4 |
+
body:
|
| 5 |
+
- type: markdown
|
| 6 |
+
attributes:
|
| 7 |
+
value: |
|
| 8 |
+
Thanks for your interest in our work. Please share your thoughts of the new features below.
|
| 9 |
+
- type: textarea
|
| 10 |
+
id: feature
|
| 11 |
+
attributes:
|
| 12 |
+
label: feature
|
| 13 |
+
placeholder: Start your thoughts here...
|
.github/ISSUE_TEMPLATE/3-question.yaml
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Questions
|
| 2 |
+
description: General questions about the work
|
| 3 |
+
title: "[Question] "
|
| 4 |
+
body:
|
| 5 |
+
- type: markdown
|
| 6 |
+
attributes:
|
| 7 |
+
value: |
|
| 8 |
+
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 :)
|
| 9 |
+
- type: textarea
|
| 10 |
+
id: question
|
| 11 |
+
attributes:
|
| 12 |
+
label: Question
|
| 13 |
+
placeholder: Start question here...
|
.github/ISSUE_TEMPLATE/4-discussion.yaml
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Discussions
|
| 2 |
+
description: General discussions about the work
|
| 3 |
+
title: "[Discussion] "
|
| 4 |
+
body:
|
| 5 |
+
- type: markdown
|
| 6 |
+
attributes:
|
| 7 |
+
value: |
|
| 8 |
+
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 :)
|
| 9 |
+
- type: textarea
|
| 10 |
+
id: discussion
|
| 11 |
+
attributes:
|
| 12 |
+
label: Discussion
|
| 13 |
+
placeholder: Start discussion here...
|
.gitignore
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__
|
| 3 |
+
*.pyc
|
| 4 |
+
*.egg-info
|
| 5 |
+
dist
|
| 6 |
+
|
| 7 |
+
# Log
|
| 8 |
+
*.log
|
| 9 |
+
*.log.*
|
| 10 |
+
*.json
|
| 11 |
+
*.jsonl
|
| 12 |
+
|
| 13 |
+
# Data
|
| 14 |
+
!**/alpaca-data-conversation.json
|
| 15 |
+
|
| 16 |
+
# Editor
|
| 17 |
+
.idea
|
| 18 |
+
*.swp
|
| 19 |
+
|
| 20 |
+
# Other
|
| 21 |
+
.DS_Store
|
| 22 |
+
wandb
|
| 23 |
+
output
|
| 24 |
+
|
| 25 |
+
checkpoints
|
| 26 |
+
ckpts*
|
| 27 |
+
|
| 28 |
+
.ipynb_checkpoints
|
| 29 |
+
*.ipynb
|
| 30 |
+
|
| 31 |
+
# DevContainer
|
| 32 |
+
!.devcontainer/*
|
| 33 |
+
|
| 34 |
+
# Demo
|
| 35 |
+
serve_images/
|
LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
README.md
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🌋 LLaVA: Large Language and Vision Assistant
|
| 2 |
+
|
| 3 |
+
*Visual instruction tuning towards large language and vision models with GPT-4 level capabilities.*
|
| 4 |
+
|
| 5 |
+
[📢 [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)]
|
| 6 |
+
|
| 7 |
+
🤝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)]
|
| 8 |
+
|
| 9 |
+
**Improved Baselines with Visual Instruction Tuning** [[Paper](https://arxiv.org/abs/2310.03744)] [[HF](https://huggingface.co/papers/2310.03744)] <br>
|
| 10 |
+
[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/)
|
| 11 |
+
|
| 12 |
+
**Visual Instruction Tuning** (NeurIPS 2023, **Oral**) [[Paper](https://arxiv.org/abs/2304.08485)] [[HF](https://huggingface.co/papers/2304.08485)] <br>
|
| 13 |
+
[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)
|
| 14 |
+
|
| 15 |
+
<!--p align="center">
|
| 16 |
+
<a href="https://llava.hliu.cc/"><img src="images/llava_logo.png" width="50%"></a> <br>
|
| 17 |
+
Generated by <a href="https://gligen.github.io/">GLIGEN</a> via "a cute lava llama with glasses" and box prompt
|
| 18 |
+
</p-->
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
## Release
|
| 22 |
+
|
| 23 |
+
- [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/)]
|
| 24 |
+
- [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/)]
|
| 25 |
+
- [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)]
|
| 26 |
+
- [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.
|
| 27 |
+
- [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)]
|
| 28 |
+
- [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)]
|
| 29 |
+
- [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.
|
| 30 |
+
- [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)]
|
| 31 |
+
- [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)!
|
| 32 |
+
- [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/)
|
| 33 |
+
- [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**.
|
| 34 |
+
|
| 35 |
+
<details>
|
| 36 |
+
<summary>More</summary>
|
| 37 |
+
|
| 38 |
+
- [11/6] Support **Intel** dGPU and CPU platforms. [More details here.](https://github.com/haotian-liu/LLaVA/tree/intel/docs/intel)
|
| 39 |
+
- [10/12] LLaVA is now supported in [llama.cpp](https://github.com/ggerganov/llama.cpp/pull/3436) with 4-bit / 5-bit quantization support!
|
| 40 |
+
- [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)!
|
| 41 |
+
- [10/10] [Roboflow Deep Dive](https://blog.roboflow.com/first-impressions-with-llava-1-5/): First Impressions with LLaVA-1.5.
|
| 42 |
+
- [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)
|
| 43 |
+
<p align="center">
|
| 44 |
+
<img src="https://github.com/Computer-Vision-in-the-Wild/CVinW_Readings/blob/main/images/mfm_evolution.jpeg?raw=true" width=50%/>
|
| 45 |
+
</p>
|
| 46 |
+
|
| 47 |
+
- [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)!
|
| 48 |
+
- [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/)].
|
| 49 |
+
- [6/11] We released the preview for the most requested feature: DeepSpeed and LoRA support! Please see documentations [here](./docs/LoRA.md).
|
| 50 |
+
- [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).
|
| 51 |
+
- [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.
|
| 52 |
+
- [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.
|
| 53 |
+
- [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).
|
| 54 |
+
- [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/).
|
| 55 |
+
|
| 56 |
+
</details>
|
| 57 |
+
|
| 58 |
+
<!-- <a href="https://llava.hliu.cc/"><img src="assets/demo.gif" width="70%"></a> -->
|
| 59 |
+
|
| 60 |
+
[](https://github.com/tatsu-lab/stanford_alpaca/blob/main/LICENSE)
|
| 61 |
+
**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.
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
## Contents
|
| 65 |
+
- [Install](#install)
|
| 66 |
+
- [LLaVA Weights](#llava-weights)
|
| 67 |
+
- [Demo](#Demo)
|
| 68 |
+
- [Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)
|
| 69 |
+
- [Dataset](https://github.com/haotian-liu/LLaVA/blob/main/docs/Data.md)
|
| 70 |
+
- [Train](#train)
|
| 71 |
+
- [Evaluation](#evaluation)
|
| 72 |
+
|
| 73 |
+
## Install
|
| 74 |
+
|
| 75 |
+
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).
|
| 76 |
+
|
| 77 |
+
1. Clone this repository and navigate to LLaVA folder
|
| 78 |
+
```bash
|
| 79 |
+
git clone https://github.com/haotian-liu/LLaVA.git
|
| 80 |
+
cd LLaVA
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
2. Install Package
|
| 84 |
+
```Shell
|
| 85 |
+
conda create -n llava python=3.10 -y
|
| 86 |
+
conda activate llava
|
| 87 |
+
pip install --upgrade pip # enable PEP 660 support
|
| 88 |
+
pip install -e .
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
3. Install additional packages for training cases
|
| 92 |
+
```
|
| 93 |
+
pip install -e ".[train]"
|
| 94 |
+
pip install flash-attn --no-build-isolation
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
### Upgrade to latest code base
|
| 98 |
+
|
| 99 |
+
```Shell
|
| 100 |
+
git pull
|
| 101 |
+
pip install -e .
|
| 102 |
+
|
| 103 |
+
# if you see some import errors when you upgrade,
|
| 104 |
+
# please try running the command below (without #)
|
| 105 |
+
# pip install flash-attn --no-build-isolation --no-cache-dir
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
### Quick Start With HuggingFace
|
| 109 |
+
|
| 110 |
+
<details>
|
| 111 |
+
<summary>Example Code</summary>
|
| 112 |
+
|
| 113 |
+
```Python
|
| 114 |
+
from llava.model.builder import load_pretrained_model
|
| 115 |
+
from llava.mm_utils import get_model_name_from_path
|
| 116 |
+
from llava.eval.run_llava import eval_model
|
| 117 |
+
|
| 118 |
+
model_path = "liuhaotian/llava-v1.5-7b"
|
| 119 |
+
|
| 120 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(
|
| 121 |
+
model_path=model_path,
|
| 122 |
+
model_base=None,
|
| 123 |
+
model_name=get_model_name_from_path(model_path)
|
| 124 |
+
)
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
Check out the details wth the `load_pretrained_model` function in `llava/model/builder.py`.
|
| 128 |
+
|
| 129 |
+
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.
|
| 130 |
+
|
| 131 |
+
``` python
|
| 132 |
+
model_path = "liuhaotian/llava-v1.5-7b"
|
| 133 |
+
prompt = "What are the things I should be cautious about when I visit here?"
|
| 134 |
+
image_file = "https://llava-vl.github.io/static/images/view.jpg"
|
| 135 |
+
|
| 136 |
+
args = type('Args', (), {
|
| 137 |
+
"model_path": model_path,
|
| 138 |
+
"model_base": None,
|
| 139 |
+
"model_name": get_model_name_from_path(model_path),
|
| 140 |
+
"query": prompt,
|
| 141 |
+
"conv_mode": None,
|
| 142 |
+
"image_file": image_file,
|
| 143 |
+
"sep": ",",
|
| 144 |
+
"temperature": 0,
|
| 145 |
+
"top_p": None,
|
| 146 |
+
"num_beams": 1,
|
| 147 |
+
"max_new_tokens": 512
|
| 148 |
+
})()
|
| 149 |
+
|
| 150 |
+
eval_model(args)
|
| 151 |
+
```
|
| 152 |
+
</details>
|
| 153 |
+
|
| 154 |
+
## LLaVA Weights
|
| 155 |
+
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.
|
| 156 |
+
|
| 157 |
+
## Demo
|
| 158 |
+
|
| 159 |
+
### Gradio Web UI
|
| 160 |
+
|
| 161 |
+
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*.
|
| 162 |
+
|
| 163 |
+
```mermaid
|
| 164 |
+
flowchart BT
|
| 165 |
+
%% Declare Nodes
|
| 166 |
+
gws("Gradio (UI Server)")
|
| 167 |
+
c("Controller (API Server):<br/>PORT: 10000")
|
| 168 |
+
mw7b("Model Worker:<br/>llava-v1.5-7b<br/>PORT: 40000")
|
| 169 |
+
mw13b("Model Worker:<br/>llava-v1.5-13b<br/>PORT: 40001")
|
| 170 |
+
sglw13b("SGLang Backend:<br/>llava-v1.6-34b<br/>http://localhost:30000")
|
| 171 |
+
lsglw13b("SGLang Worker:<br/>llava-v1.6-34b<br/>PORT: 40002")
|
| 172 |
+
|
| 173 |
+
%% Declare Styles
|
| 174 |
+
classDef data fill:#3af,stroke:#48a,stroke-width:2px,color:#444
|
| 175 |
+
classDef success fill:#8f8,stroke:#0a0,stroke-width:2px,color:#444
|
| 176 |
+
classDef failure fill:#f88,stroke:#f00,stroke-width:2px,color:#444
|
| 177 |
+
|
| 178 |
+
%% Assign Styles
|
| 179 |
+
class id,od data;
|
| 180 |
+
class cimg,cs_s,scsim_s success;
|
| 181 |
+
class ncimg,cs_f,scsim_f failure;
|
| 182 |
+
|
| 183 |
+
subgraph Demo Connections
|
| 184 |
+
direction BT
|
| 185 |
+
c<-->gws
|
| 186 |
+
|
| 187 |
+
mw7b<-->c
|
| 188 |
+
mw13b<-->c
|
| 189 |
+
lsglw13b<-->c
|
| 190 |
+
sglw13b<-->lsglw13b
|
| 191 |
+
end
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
#### Launch a controller
|
| 195 |
+
```Shell
|
| 196 |
+
python -m llava.serve.controller --host 0.0.0.0 --port 10000
|
| 197 |
+
```
|
| 198 |
+
|
| 199 |
+
#### Launch a gradio web server.
|
| 200 |
+
```Shell
|
| 201 |
+
python -m llava.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload
|
| 202 |
+
```
|
| 203 |
+
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.
|
| 204 |
+
|
| 205 |
+
#### Launch a SGLang worker
|
| 206 |
+
|
| 207 |
+
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).
|
| 208 |
+
|
| 209 |
+
```Shell
|
| 210 |
+
pip install "sglang[all]"
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
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.
|
| 214 |
+
|
| 215 |
+
```Shell
|
| 216 |
+
# Single GPU
|
| 217 |
+
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
|
| 218 |
+
|
| 219 |
+
# Multiple GPUs with tensor parallel
|
| 220 |
+
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
|
| 221 |
+
```
|
| 222 |
+
|
| 223 |
+
Tokenizers (temporary): `llava-hf/llava-1.5-7b-hf`, `llava-hf/llava-1.5-13b-hf`, `liuhaotian/llava-v1.6-34b-tokenizer`.
|
| 224 |
+
|
| 225 |
+
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).
|
| 226 |
+
|
| 227 |
+
```Shell
|
| 228 |
+
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
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
#### Launch a model worker
|
| 232 |
+
|
| 233 |
+
This is the actual *worker* that performs the inference on the GPU. Each worker is responsible for a single model specified in `--model-path`.
|
| 234 |
+
|
| 235 |
+
```Shell
|
| 236 |
+
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
|
| 237 |
+
```
|
| 238 |
+
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.
|
| 239 |
+
|
| 240 |
+
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.
|
| 241 |
+
```Shell
|
| 242 |
+
python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port <different from 40000, say 40001> --worker http://localhost:<change accordingly, i.e. 40001> --model-path <ckpt2>
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
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`.
|
| 246 |
+
|
| 247 |
+
#### Launch a model worker (Multiple GPUs, when GPU VRAM <= 24GB)
|
| 248 |
+
|
| 249 |
+
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.
|
| 250 |
+
|
| 251 |
+
```Shell
|
| 252 |
+
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
|
| 253 |
+
```
|
| 254 |
+
|
| 255 |
+
#### Launch a model worker (4-bit, 8-bit inference, quantized)
|
| 256 |
+
|
| 257 |
+
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.
|
| 258 |
+
|
| 259 |
+
```Shell
|
| 260 |
+
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
|
| 261 |
+
```
|
| 262 |
+
|
| 263 |
+
#### Launch a model worker (LoRA weights, unmerged)
|
| 264 |
+
|
| 265 |
+
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).
|
| 266 |
+
|
| 267 |
+
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).
|
| 268 |
+
|
| 269 |
+
```Shell
|
| 270 |
+
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
|
| 271 |
+
```
|
| 272 |
+
|
| 273 |
+
### CLI Inference
|
| 274 |
+
|
| 275 |
+
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.
|
| 276 |
+
|
| 277 |
+
```Shell
|
| 278 |
+
python -m llava.serve.cli \
|
| 279 |
+
--model-path liuhaotian/llava-v1.5-7b \
|
| 280 |
+
--image-file "https://llava-vl.github.io/static/images/view.jpg" \
|
| 281 |
+
--load-4bit
|
| 282 |
+
```
|
| 283 |
+
|
| 284 |
+
<img src="images/demo_cli.gif" width="70%">
|
| 285 |
+
|
| 286 |
+
## Train
|
| 287 |
+
|
| 288 |
+
*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.*
|
| 289 |
+
|
| 290 |
+
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.
|
| 291 |
+
|
| 292 |
+
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`.
|
| 293 |
+
|
| 294 |
+
### Hyperparameters
|
| 295 |
+
We use a similar set of hyperparameters as Vicuna in finetuning. Both hyperparameters used in pretraining and finetuning are provided below.
|
| 296 |
+
|
| 297 |
+
1. Pretraining
|
| 298 |
+
|
| 299 |
+
| Hyperparameter | Global Batch Size | Learning rate | Epochs | Max length | Weight decay |
|
| 300 |
+
| --- | ---: | ---: | ---: | ---: | ---: |
|
| 301 |
+
| LLaVA-v1.5-13B | 256 | 1e-3 | 1 | 2048 | 0 |
|
| 302 |
+
|
| 303 |
+
2. Finetuning
|
| 304 |
+
|
| 305 |
+
| Hyperparameter | Global Batch Size | Learning rate | Epochs | Max length | Weight decay |
|
| 306 |
+
| --- | ---: | ---: | ---: | ---: | ---: |
|
| 307 |
+
| LLaVA-v1.5-13B | 128 | 2e-5 | 1 | 2048 | 0 |
|
| 308 |
+
|
| 309 |
+
### Download Vicuna checkpoints (automatically)
|
| 310 |
+
|
| 311 |
+
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.
|
| 312 |
+
|
| 313 |
+
### Pretrain (feature alignment)
|
| 314 |
+
|
| 315 |
+
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).
|
| 316 |
+
|
| 317 |
+
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.
|
| 318 |
+
|
| 319 |
+
Training script with DeepSpeed ZeRO-2: [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/pretrain.sh).
|
| 320 |
+
|
| 321 |
+
- `--mm_projector_type mlp2x_gelu`: the two-layer MLP vision-language connector.
|
| 322 |
+
- `--vision_tower openai/clip-vit-large-patch14-336`: CLIP ViT-L/14 336px.
|
| 323 |
+
|
| 324 |
+
<details>
|
| 325 |
+
<summary>Pretrain takes around 20 hours for LLaVA-7B on 8x V100 (32G)</summary>
|
| 326 |
+
|
| 327 |
+
We provide training script with DeepSpeed [here](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain_xformers.sh).
|
| 328 |
+
Tips:
|
| 329 |
+
- 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).
|
| 330 |
+
</details>
|
| 331 |
+
|
| 332 |
+
### Visual Instruction Tuning
|
| 333 |
+
|
| 334 |
+
1. Prepare data
|
| 335 |
+
|
| 336 |
+
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:
|
| 337 |
+
|
| 338 |
+
- COCO: [train2017](http://images.cocodataset.org/zips/train2017.zip)
|
| 339 |
+
- GQA: [images](https://downloads.cs.stanford.edu/nlp/data/gqa/images.zip)
|
| 340 |
+
- OCR-VQA: [download script](https://drive.google.com/drive/folders/1_GYPY5UkUy7HIcR0zq3ZCFgeZN7BAfm_?usp=sharing), **we save all files as `.jpg`**
|
| 341 |
+
- TextVQA: [train_val_images](https://dl.fbaipublicfiles.com/textvqa/images/train_val_images.zip)
|
| 342 |
+
- 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)
|
| 343 |
+
|
| 344 |
+
After downloading all of them, organize the data as follows in `./playground/data`,
|
| 345 |
+
|
| 346 |
+
```
|
| 347 |
+
├── coco
|
| 348 |
+
│ └── train2017
|
| 349 |
+
├── gqa
|
| 350 |
+
│ └── images
|
| 351 |
+
├── ocr_vqa
|
| 352 |
+
│ └── images
|
| 353 |
+
├── textvqa
|
| 354 |
+
│ └── train_images
|
| 355 |
+
└── vg
|
| 356 |
+
├── VG_100K
|
| 357 |
+
└── VG_100K_2
|
| 358 |
+
```
|
| 359 |
+
|
| 360 |
+
2. Start training!
|
| 361 |
+
|
| 362 |
+
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.
|
| 363 |
+
|
| 364 |
+
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).
|
| 365 |
+
|
| 366 |
+
Training script with DeepSpeed ZeRO-3: [`finetune.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/finetune.sh).
|
| 367 |
+
|
| 368 |
+
If you are do not have enough GPU memory:
|
| 369 |
+
|
| 370 |
+
- 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.
|
| 371 |
+
- Replace `zero3.json` with `zero3_offload.json` which offloads some parameters to CPU RAM. This slows down the training speed.
|
| 372 |
+
|
| 373 |
+
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)。
|
| 374 |
+
|
| 375 |
+
New options to note:
|
| 376 |
+
|
| 377 |
+
- `--mm_projector_type mlp2x_gelu`: the two-layer MLP vision-language connector.
|
| 378 |
+
- `--vision_tower openai/clip-vit-large-patch14-336`: CLIP ViT-L/14 336px.
|
| 379 |
+
- `--image_aspect_ratio pad`: this pads the non-square images to square, instead of cropping them; it slightly reduces hallucination.
|
| 380 |
+
- `--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.
|
| 381 |
+
|
| 382 |
+
## Evaluation
|
| 383 |
+
|
| 384 |
+
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.
|
| 385 |
+
|
| 386 |
+
See [Evaluation.md](https://github.com/haotian-liu/LLaVA/blob/main/docs/Evaluation.md).
|
| 387 |
+
|
| 388 |
+
### GPT-assisted Evaluation
|
| 389 |
+
|
| 390 |
+
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.
|
| 391 |
+
|
| 392 |
+
1. Generate LLaVA responses
|
| 393 |
+
|
| 394 |
+
```Shell
|
| 395 |
+
python model_vqa.py \
|
| 396 |
+
--model-path ./checkpoints/LLaVA-13B-v0 \
|
| 397 |
+
--question-file \
|
| 398 |
+
playground/data/coco2014_val_qa_eval/qa90_questions.jsonl \
|
| 399 |
+
--image-folder \
|
| 400 |
+
/path/to/coco2014_val \
|
| 401 |
+
--answers-file \
|
| 402 |
+
/path/to/answer-file-our.jsonl
|
| 403 |
+
```
|
| 404 |
+
|
| 405 |
+
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.
|
| 406 |
+
|
| 407 |
+
```Shell
|
| 408 |
+
OPENAI_API_KEY="sk-***********************************" python llava/eval/eval_gpt_review_visual.py \
|
| 409 |
+
--question playground/data/coco2014_val_qa_eval/qa90_questions.jsonl \
|
| 410 |
+
--context llava/eval/table/caps_boxes_coco2014_val_80.jsonl \
|
| 411 |
+
--answer-list \
|
| 412 |
+
/path/to/answer-file-ref.jsonl \
|
| 413 |
+
/path/to/answer-file-our.jsonl \
|
| 414 |
+
--rule llava/eval/table/rule.json \
|
| 415 |
+
--output /path/to/review.json
|
| 416 |
+
```
|
| 417 |
+
|
| 418 |
+
3. Summarize the evaluation results
|
| 419 |
+
|
| 420 |
+
```Shell
|
| 421 |
+
python summarize_gpt_review.py
|
| 422 |
+
```
|
| 423 |
+
|
| 424 |
+
## Citation
|
| 425 |
+
|
| 426 |
+
If you find LLaVA useful for your research and applications, please cite using this BibTeX:
|
| 427 |
+
```bibtex
|
| 428 |
+
@misc{liu2024llavanext,
|
| 429 |
+
title={LLaVA-NeXT: Improved reasoning, OCR, and world knowledge},
|
| 430 |
+
url={https://llava-vl.github.io/blog/2024-01-30-llava-next/},
|
| 431 |
+
author={Liu, Haotian and Li, Chunyuan and Li, Yuheng and Li, Bo and Zhang, Yuanhan and Shen, Sheng and Lee, Yong Jae},
|
| 432 |
+
month={January},
|
| 433 |
+
year={2024}
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
@misc{liu2023improvedllava,
|
| 437 |
+
title={Improved Baselines with Visual Instruction Tuning},
|
| 438 |
+
author={Liu, Haotian and Li, Chunyuan and Li, Yuheng and Lee, Yong Jae},
|
| 439 |
+
publisher={arXiv:2310.03744},
|
| 440 |
+
year={2023},
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
@misc{liu2023llava,
|
| 444 |
+
title={Visual Instruction Tuning},
|
| 445 |
+
author={Liu, Haotian and Li, Chunyuan and Wu, Qingyang and Lee, Yong Jae},
|
| 446 |
+
publisher={NeurIPS},
|
| 447 |
+
year={2023},
|
| 448 |
+
}
|
| 449 |
+
```
|
| 450 |
+
|
| 451 |
+
## Acknowledgement
|
| 452 |
+
|
| 453 |
+
- [Vicuna](https://github.com/lm-sys/FastChat): the codebase we built upon, and our base model Vicuna-13B that has the amazing language capabilities!
|
| 454 |
+
|
| 455 |
+
## Related Projects
|
| 456 |
+
|
| 457 |
+
- [Instruction Tuning with GPT-4](https://github.com/Instruction-Tuning-with-GPT-4/GPT-4-LLM)
|
| 458 |
+
- [LLaVA-Med: Training a Large Language-and-Vision Assistant for Biomedicine in One Day](https://github.com/microsoft/LLaVA-Med)
|
| 459 |
+
- [Otter: In-Context Multi-Modal Instruction Tuning](https://github.com/Luodian/Otter)
|
| 460 |
+
|
| 461 |
+
For future project ideas, please check out:
|
| 462 |
+
- [SEEM: Segment Everything Everywhere All at Once](https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once)
|
| 463 |
+
- [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).
|
alpha_clip_final/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .alpha_clip_new import *
|
alpha_clip_final/alpha_clip_new.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import os
|
| 3 |
+
import urllib
|
| 4 |
+
import warnings
|
| 5 |
+
from typing import Any, Union, List
|
| 6 |
+
from pkg_resources import packaging
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from PIL import Image
|
| 10 |
+
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
|
| 13 |
+
from .model_new import build_model
|
| 14 |
+
from .simple_tokenizer import SimpleTokenizer as _Tokenizer
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
from torchvision.transforms import InterpolationMode
|
| 18 |
+
BICUBIC = InterpolationMode.BICUBIC
|
| 19 |
+
except ImportError:
|
| 20 |
+
BICUBIC = Image.BICUBIC
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"):
|
| 24 |
+
warnings.warn("PyTorch version 1.7.1 or higher is recommended")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
__all__ = ["available_models", "load", "tokenize"]
|
| 28 |
+
_tokenizer = _Tokenizer()
|
| 29 |
+
|
| 30 |
+
_MODELS = {
|
| 31 |
+
"RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
|
| 32 |
+
"RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
|
| 33 |
+
"RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
|
| 34 |
+
"RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
|
| 35 |
+
"RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
|
| 36 |
+
"ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
|
| 37 |
+
"ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
|
| 38 |
+
"ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
|
| 39 |
+
"ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _download(url: str, root: str):
|
| 44 |
+
os.makedirs(root, exist_ok=True)
|
| 45 |
+
filename = os.path.basename(url)
|
| 46 |
+
|
| 47 |
+
expected_sha256 = url.split("/")[-2]
|
| 48 |
+
download_target = os.path.join(root, filename)
|
| 49 |
+
|
| 50 |
+
if os.path.exists(download_target) and not os.path.isfile(download_target):
|
| 51 |
+
raise RuntimeError(f"{download_target} exists and is not a regular file")
|
| 52 |
+
|
| 53 |
+
if os.path.isfile(download_target):
|
| 54 |
+
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
|
| 55 |
+
return download_target
|
| 56 |
+
else:
|
| 57 |
+
warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
|
| 58 |
+
|
| 59 |
+
with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
|
| 60 |
+
with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop:
|
| 61 |
+
while True:
|
| 62 |
+
buffer = source.read(8192)
|
| 63 |
+
if not buffer:
|
| 64 |
+
break
|
| 65 |
+
|
| 66 |
+
output.write(buffer)
|
| 67 |
+
loop.update(len(buffer))
|
| 68 |
+
|
| 69 |
+
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
|
| 70 |
+
raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match")
|
| 71 |
+
|
| 72 |
+
return download_target
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _convert_image_to_rgb(image):
|
| 76 |
+
return image.convert("RGB")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _transform(n_px):
|
| 80 |
+
return Compose([
|
| 81 |
+
Resize(n_px, interpolation=BICUBIC),
|
| 82 |
+
CenterCrop(n_px),
|
| 83 |
+
_convert_image_to_rgb,
|
| 84 |
+
ToTensor(),
|
| 85 |
+
Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
|
| 86 |
+
])
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def available_models() -> List[str]:
|
| 90 |
+
"""Returns the names of available CLIP models"""
|
| 91 |
+
return list(_MODELS.keys())
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
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):
|
| 95 |
+
"""Load a CLIP model
|
| 96 |
+
|
| 97 |
+
Parameters
|
| 98 |
+
----------
|
| 99 |
+
name : str
|
| 100 |
+
A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
|
| 101 |
+
|
| 102 |
+
alpha_vision_ckpt_pth: str
|
| 103 |
+
only changed when inferencing model instead of training
|
| 104 |
+
|
| 105 |
+
device : Union[str, torch.device]
|
| 106 |
+
The device to put the loaded model
|
| 107 |
+
|
| 108 |
+
jit : bool
|
| 109 |
+
Whether to load the optimized JIT model or more hackable non-JIT model (default).
|
| 110 |
+
|
| 111 |
+
download_root: str
|
| 112 |
+
path to download the model files; by default, it uses "~/.cache/clip"
|
| 113 |
+
|
| 114 |
+
Returns
|
| 115 |
+
-------
|
| 116 |
+
model : torch.nn.Module
|
| 117 |
+
The CLIP model
|
| 118 |
+
|
| 119 |
+
preprocess : Callable[[PIL.Image], torch.Tensor]
|
| 120 |
+
A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
|
| 121 |
+
"""
|
| 122 |
+
if name in _MODELS:
|
| 123 |
+
model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip"))
|
| 124 |
+
elif os.path.isfile(name):
|
| 125 |
+
model_path = name
|
| 126 |
+
else:
|
| 127 |
+
raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
|
| 128 |
+
|
| 129 |
+
with open(model_path, 'rb') as opened_file:
|
| 130 |
+
try:
|
| 131 |
+
# loading JIT archive
|
| 132 |
+
model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
|
| 133 |
+
state_dict = None
|
| 134 |
+
except RuntimeError:
|
| 135 |
+
# loading saved state dict
|
| 136 |
+
if jit:
|
| 137 |
+
warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
|
| 138 |
+
jit = False
|
| 139 |
+
state_dict = torch.load(opened_file, map_location="cpu")
|
| 140 |
+
|
| 141 |
+
if not jit:
|
| 142 |
+
model, depth_model = build_model(state_dict or model.state_dict(), lora_adapt=lora_adapt, rank=rank)
|
| 143 |
+
model=model.to(device)
|
| 144 |
+
depth_model=depth_model.to(device)
|
| 145 |
+
if str(device) == "cpu":
|
| 146 |
+
model.float()
|
| 147 |
+
if alpha_vision_ckpt_pth != "None":
|
| 148 |
+
model.visual.load_state_dict(torch.load(alpha_vision_ckpt_pth))
|
| 149 |
+
model.eval() # merge lora params if exists (for inference only)
|
| 150 |
+
return model, _transform(model.visual.input_resolution), depth_model
|
| 151 |
+
|
| 152 |
+
# patch the device names
|
| 153 |
+
device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
|
| 154 |
+
device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
|
| 155 |
+
|
| 156 |
+
def _node_get(node: torch._C.Node, key: str):
|
| 157 |
+
"""Gets attributes of a node which is polymorphic over return type.
|
| 158 |
+
|
| 159 |
+
From https://github.com/pytorch/pytorch/pull/82628
|
| 160 |
+
"""
|
| 161 |
+
sel = node.kindOf(key)
|
| 162 |
+
return getattr(node, sel)(key)
|
| 163 |
+
|
| 164 |
+
def patch_device(module):
|
| 165 |
+
try:
|
| 166 |
+
graphs = [module.graph] if hasattr(module, "graph") else []
|
| 167 |
+
except RuntimeError:
|
| 168 |
+
graphs = []
|
| 169 |
+
|
| 170 |
+
if hasattr(module, "forward1"):
|
| 171 |
+
graphs.append(module.forward1.graph)
|
| 172 |
+
|
| 173 |
+
for graph in graphs:
|
| 174 |
+
for node in graph.findAllNodes("prim::Constant"):
|
| 175 |
+
if "value" in node.attributeNames() and str(_node_get(node, "value")).startswith("cuda"):
|
| 176 |
+
node.copyAttributes(device_node)
|
| 177 |
+
|
| 178 |
+
model.apply(patch_device)
|
| 179 |
+
patch_device(model.encode_image)
|
| 180 |
+
patch_device(model.encode_text)
|
| 181 |
+
|
| 182 |
+
# patch dtype to float32 on CPU
|
| 183 |
+
if str(device) == "cpu":
|
| 184 |
+
float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
|
| 185 |
+
float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
|
| 186 |
+
float_node = float_input.node()
|
| 187 |
+
|
| 188 |
+
def patch_float(module):
|
| 189 |
+
try:
|
| 190 |
+
graphs = [module.graph] if hasattr(module, "graph") else []
|
| 191 |
+
except RuntimeError:
|
| 192 |
+
graphs = []
|
| 193 |
+
|
| 194 |
+
if hasattr(module, "forward1"):
|
| 195 |
+
graphs.append(module.forward1.graph)
|
| 196 |
+
|
| 197 |
+
for graph in graphs:
|
| 198 |
+
for node in graph.findAllNodes("aten::to"):
|
| 199 |
+
inputs = list(node.inputs())
|
| 200 |
+
for i in [1, 2]: # dtype can be the second or third argument to aten::to()
|
| 201 |
+
if _node_get(inputs[i].node(), "value") == 5:
|
| 202 |
+
inputs[i].node().copyAttributes(float_node)
|
| 203 |
+
|
| 204 |
+
model.apply(patch_float)
|
| 205 |
+
patch_float(model.encode_image)
|
| 206 |
+
patch_float(model.encode_text)
|
| 207 |
+
|
| 208 |
+
model.float()
|
| 209 |
+
return model, _transform(model.input_resolution.item())
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = True) -> Union[torch.IntTensor, torch.LongTensor]:
|
| 213 |
+
"""
|
| 214 |
+
Returns the tokenized representation of given input string(s)
|
| 215 |
+
|
| 216 |
+
Parameters
|
| 217 |
+
----------
|
| 218 |
+
texts : Union[str, List[str]]
|
| 219 |
+
An input string or a list of input strings to tokenize
|
| 220 |
+
|
| 221 |
+
context_length : int
|
| 222 |
+
The context length to use; all CLIP models use 77 as the context length
|
| 223 |
+
|
| 224 |
+
truncate: bool
|
| 225 |
+
Whether to truncate the text in case its encoding is longer than the context length
|
| 226 |
+
|
| 227 |
+
Returns
|
| 228 |
+
-------
|
| 229 |
+
A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
|
| 230 |
+
We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
|
| 231 |
+
"""
|
| 232 |
+
if isinstance(texts, str):
|
| 233 |
+
texts = [texts]
|
| 234 |
+
|
| 235 |
+
sot_token = _tokenizer.encoder["<|startoftext|>"]
|
| 236 |
+
eot_token = _tokenizer.encoder["<|endoftext|>"]
|
| 237 |
+
all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
|
| 238 |
+
if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"):
|
| 239 |
+
result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
|
| 240 |
+
else:
|
| 241 |
+
result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
|
| 242 |
+
|
| 243 |
+
for i, tokens in enumerate(all_tokens):
|
| 244 |
+
if len(tokens) > context_length:
|
| 245 |
+
if truncate:
|
| 246 |
+
tokens = tokens[:context_length]
|
| 247 |
+
tokens[-1] = eot_token
|
| 248 |
+
else:
|
| 249 |
+
raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
|
| 250 |
+
result[i, :len(tokens)] = torch.tensor(tokens)
|
| 251 |
+
|
| 252 |
+
return result
|
alpha_clip_final/bpe_simple_vocab_16e6.txt.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
|
| 3 |
+
size 1356917
|
alpha_clip_final/model_new.py
ADDED
|
@@ -0,0 +1,1009 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import OrderedDict
|
| 2 |
+
from typing import Tuple, Union
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from torch import nn
|
| 8 |
+
import loralib as lora
|
| 9 |
+
import math
|
| 10 |
+
import collections
|
| 11 |
+
import torch.nn.init as init
|
| 12 |
+
# import spconv.pytorch as spconv
|
| 13 |
+
import sys
|
| 14 |
+
sys.path.append('/home/aiops/wangzh/llava')
|
| 15 |
+
from depth_anything_v2.dpt import DepthAnythingV2
|
| 16 |
+
|
| 17 |
+
class CPEconv(nn.Module):
|
| 18 |
+
def __init__(self, in_channels, spatial_shape, kernel_size=(3, 3, 3), padding=(1, 1, 1)):
|
| 19 |
+
super(CPEconv, self).__init__()
|
| 20 |
+
self.in_channels = in_channels
|
| 21 |
+
self.spatial_shape = 6
|
| 22 |
+
self.conv3d = nn.Conv3d(in_channels, in_channels, kernel_size=kernel_size, padding=padding,groups=in_channels)
|
| 23 |
+
nn.init.zeros_(self.conv3d.weight)
|
| 24 |
+
if self.conv3d.bias is not None:
|
| 25 |
+
nn.init.zeros_(self.conv3d.bias)
|
| 26 |
+
|
| 27 |
+
self.register_buffer('target_tensor_template', torch.zeros(1, in_channels, self.spatial_shape, 1, 1))
|
| 28 |
+
|
| 29 |
+
def generate_3d_coords_from_depth(self, depth_maps):
|
| 30 |
+
# 假设 depth_maps 形状为 (B, H, W)
|
| 31 |
+
B, H, W = depth_maps.shape
|
| 32 |
+
z_min = depth_maps.min(dim=-1, keepdim=True)[0].min(dim=-2, keepdim=True)[0] # (B, 1, 1)
|
| 33 |
+
z_max = depth_maps.max(dim=-1, keepdim=True)[0].max(dim=-2, keepdim=True)[0] # (B, 1, 1)
|
| 34 |
+
z = (depth_maps - z_min) / (z_max - z_min + 1e-8)
|
| 35 |
+
# z = depth_maps # z 坐标为深度值,形状为 (B, H, W)
|
| 36 |
+
|
| 37 |
+
return z
|
| 38 |
+
|
| 39 |
+
def forward(self, features, depth):
|
| 40 |
+
#features [197,256,768] depth [256,14,14]
|
| 41 |
+
B,h,w=depth.shape
|
| 42 |
+
_,_,C=features.shape
|
| 43 |
+
D = self.spatial_shape
|
| 44 |
+
features = features[1:,:,:]
|
| 45 |
+
features = features.permute(1,0,2)
|
| 46 |
+
coord=self.generate_3d_coords_from_depth(depth)
|
| 47 |
+
bnd=self.spatial_shape - 1
|
| 48 |
+
coord = (coord *bnd).to(torch.int64)
|
| 49 |
+
coord = (
|
| 50 |
+
coord.clamp(0, bnd) # clamp into bnd
|
| 51 |
+
)
|
| 52 |
+
target_tensor = self.target_tensor_template.expand(B, C, D, h, w).clone()
|
| 53 |
+
# target_tensor = torch.zeros(B, C, D, h, w).to(device=features.device)
|
| 54 |
+
# return 0
|
| 55 |
+
|
| 56 |
+
coord = coord.unsqueeze(1).expand(-1, C, -1, -1) # [B, C, H, W]
|
| 57 |
+
# reshape features 以便与 coord 进行操作
|
| 58 |
+
features = features.view(B, h, w, C) # [B, H, W, C]
|
| 59 |
+
features = features.permute(0, 3, 1, 2) # [B, C, H, W]
|
| 60 |
+
features = features.unsqueeze(2).to(dtype=target_tensor.dtype)
|
| 61 |
+
coord = coord.unsqueeze(2)
|
| 62 |
+
# import pdb;pdb.set_trace()
|
| 63 |
+
|
| 64 |
+
# scatter features into target_tensor
|
| 65 |
+
target_tensor = target_tensor.scatter_(2, coord, features)
|
| 66 |
+
# 2. 使用 b 的值作为下标,将 features 的值复制到目标张量的相应位置
|
| 67 |
+
# 3. 使用 for 循环将 features 的值复制到目标张量
|
| 68 |
+
# for i in range(B):
|
| 69 |
+
# for j in range(h):
|
| 70 |
+
# for k in range(w):
|
| 71 |
+
# # 获取在 features 中的索引
|
| 72 |
+
# index = coord[i, j, k] # 从 b 中获取索引
|
| 73 |
+
# target_tensor[i, :,index, j, k] = features[i, j * 14 + k, :] # 复制对应的 features 值
|
| 74 |
+
output = self.conv3d(target_tensor).mean(dim=2) #(B,768,14,14)
|
| 75 |
+
output = output.reshape(-1,output.size(0),output.size(1))
|
| 76 |
+
cls_feat = torch.zeros(1,output.size(-2), output.size(-1)).to(device=output.device,dtype=output.dtype)
|
| 77 |
+
out_feat = torch.cat([cls_feat,output],dim=0)
|
| 78 |
+
|
| 79 |
+
return out_feat
|
| 80 |
+
class RPE(torch.nn.Module):
|
| 81 |
+
def __init__(self, patch_num, num_heads):
|
| 82 |
+
super(RPE, self).__init__()
|
| 83 |
+
self.num_heads = num_heads
|
| 84 |
+
self.pos_bnd = patch_num
|
| 85 |
+
self.rpe_num = 2 * self.pos_bnd + 1
|
| 86 |
+
self.rpe_table = torch.nn.Parameter(torch.zeros(3 * self.rpe_num, num_heads))
|
| 87 |
+
# torch.nn.init.trunc_normal_(self.rpe_table, std=0.02)
|
| 88 |
+
|
| 89 |
+
def generate_3d_coords_from_depth(self,depth_maps):
|
| 90 |
+
# 假设 depth_maps 形状为 (B, H, W)
|
| 91 |
+
B, H, W = depth_maps.shape
|
| 92 |
+
|
| 93 |
+
# 生成网格 i, j,形状为 (H, W)
|
| 94 |
+
i, j = torch.meshgrid(torch.arange(H, device=depth_maps.device), torch.arange(W, device=depth_maps.device), indexing='ij')
|
| 95 |
+
|
| 96 |
+
# 归一化 x 和 y 坐标
|
| 97 |
+
x = j.float() / (W - 1) # (H, W)
|
| 98 |
+
y = i.float() / (H - 1) # (H, W)
|
| 99 |
+
|
| 100 |
+
# 将 x 和 y 扩展到 (B, H, W) 以匹配 depth_maps
|
| 101 |
+
x = x.unsqueeze(0).expand(B, -1, -1) # (B, H, W)
|
| 102 |
+
y = y.unsqueeze(0).expand(B, -1, -1) # (B, H, W)
|
| 103 |
+
|
| 104 |
+
z_min = depth_maps.min(dim=-1, keepdim=True)[0].min(dim=-2, keepdim=True)[0] # (B, 1, 1)
|
| 105 |
+
z_max = depth_maps.max(dim=-1, keepdim=True)[0].max(dim=-2, keepdim=True)[0] # (B, 1, 1)
|
| 106 |
+
z = (depth_maps - z_min) / (z_max - z_min + 1e-8)
|
| 107 |
+
# z = depth_maps # z 坐标为深度值,形状为 (B, H, W)
|
| 108 |
+
|
| 109 |
+
# 组合成 (B, H, W, 3) 的三维坐标
|
| 110 |
+
coords = torch.stack([x, y, z], dim=-1) # (B, H, W, 3)
|
| 111 |
+
|
| 112 |
+
return coords
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def compute_relative_positions(self,absolute_coords):
|
| 116 |
+
"""
|
| 117 |
+
计算相对位置编码
|
| 118 |
+
参数:
|
| 119 |
+
absolute_coords: 形状为 (N, 3) 的绝对三维坐标张量
|
| 120 |
+
返回:
|
| 121 |
+
相对位置编码,形状为 (N, N, 3)
|
| 122 |
+
"""
|
| 123 |
+
# 确保输入是一个张量
|
| 124 |
+
if not isinstance(absolute_coords, torch.Tensor):
|
| 125 |
+
raise ValueError("Input must be a PyTorch tensor.")
|
| 126 |
+
N = absolute_coords.shape[1]
|
| 127 |
+
relative_positions = absolute_coords.unsqueeze(2) - absolute_coords.unsqueeze(1)
|
| 128 |
+
|
| 129 |
+
return relative_positions
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def forward(self,depth):
|
| 133 |
+
# B,K,K,3
|
| 134 |
+
# import pdb;pdb.set_trace()
|
| 135 |
+
|
| 136 |
+
depth=self.generate_3d_coords_from_depth(depth)
|
| 137 |
+
depth=depth.reshape(depth.size(0),-1,depth.size(-1))
|
| 138 |
+
# zeros_tensor = torch.zeros(depth.size(0), 1, depth.size(-1))
|
| 139 |
+
# depth = torch.cat((zeros_tensor,depth), dim=1)
|
| 140 |
+
coord=self.compute_relative_positions(depth)
|
| 141 |
+
# 将 coord 从 [0, 1] 范围转换为 [0, width] 或 [0, height]
|
| 142 |
+
# coord = coord.reshape(coord.size(0),-1,coord.size(-1))
|
| 143 |
+
# import pdb;pdb.set_trace()
|
| 144 |
+
coord = (coord * torch.tensor([self.pos_bnd, self.pos_bnd, self.pos_bnd], device=coord.device)).round().long()
|
| 145 |
+
idx = (
|
| 146 |
+
coord.clamp(-self.pos_bnd, self.pos_bnd) # clamp into bnd
|
| 147 |
+
+ self.pos_bnd # relative position to positive index
|
| 148 |
+
+ torch.arange(3, device=coord.device) * self.rpe_num # x, y, z stride
|
| 149 |
+
)
|
| 150 |
+
out = self.rpe_table.index_select(0, idx.reshape(-1))
|
| 151 |
+
# out = out.reshape(coord.size(0) ,coord.size(1) ,coord.size(2) , -1)
|
| 152 |
+
out = out.view(idx.shape + (-1,)).sum(3)
|
| 153 |
+
|
| 154 |
+
out = out.permute(0, 3, 1, 2) # (N, K, K, H) -> (N, H, K, K)
|
| 155 |
+
# out_new=torch.zeros(out.size(0),out.size(1),out.size(2)+1,out.size(3)+1)
|
| 156 |
+
# out_new[:, :, 1:, 1:] = out
|
| 157 |
+
return out
|
| 158 |
+
|
| 159 |
+
class PositionEmbeddingCoordsSine(nn.Module):
|
| 160 |
+
def __init__(
|
| 161 |
+
self,
|
| 162 |
+
temperature=10000,
|
| 163 |
+
normalize=False,
|
| 164 |
+
scale=None,
|
| 165 |
+
pos_type="fourier",
|
| 166 |
+
d_pos=None,
|
| 167 |
+
d_in=3,
|
| 168 |
+
gauss_scale=1.0,
|
| 169 |
+
):
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.temperature = temperature
|
| 172 |
+
self.normalize = normalize
|
| 173 |
+
if scale is not None and normalize is False:
|
| 174 |
+
raise ValueError("normalize should be True if scale is passed")
|
| 175 |
+
if scale is None:
|
| 176 |
+
scale = 2 * math.pi
|
| 177 |
+
assert pos_type in ["sine", "fourier"]
|
| 178 |
+
self.pos_type = pos_type
|
| 179 |
+
self.scale = scale
|
| 180 |
+
self.ln = LayerNorm(768)
|
| 181 |
+
if pos_type == "fourier":
|
| 182 |
+
assert d_pos is not None
|
| 183 |
+
assert d_pos % 2 == 0
|
| 184 |
+
# define a gaussian matrix input_ch -> output_ch
|
| 185 |
+
B = torch.empty((d_in, d_pos // 2)).normal_()
|
| 186 |
+
B *= gauss_scale
|
| 187 |
+
# self.gauss_B = nn.Parameter(B)
|
| 188 |
+
self.register_buffer("gauss_B", B)
|
| 189 |
+
self.d_pos = d_pos
|
| 190 |
+
self.trans3d=nn.Conv1d(in_channels=3, out_channels=768, kernel_size=1)
|
| 191 |
+
init.zeros_(self.trans3d.weight)
|
| 192 |
+
if self.trans3d.bias is not None:
|
| 193 |
+
init.zeros_(self.trans3d.bias)
|
| 194 |
+
def get_sine_embeddings(self, xyz, num_channels, input_range):
|
| 195 |
+
ncoords = xyz.shape[1]
|
| 196 |
+
ndim = num_channels // xyz.shape[2]
|
| 197 |
+
if ndim % 2 != 0:
|
| 198 |
+
ndim -= 1
|
| 199 |
+
# automatically handle remainder by assiging it to the first dim
|
| 200 |
+
rems = num_channels - (ndim * xyz.shape[2])
|
| 201 |
+
|
| 202 |
+
assert (
|
| 203 |
+
ndim % 2 == 0
|
| 204 |
+
), f"Cannot handle odd sized ndim={ndim} where num_channels={num_channels} and xyz={xyz.shape}"
|
| 205 |
+
|
| 206 |
+
final_embeds = []
|
| 207 |
+
prev_dim = 0
|
| 208 |
+
|
| 209 |
+
for d in range(xyz.shape[2]):
|
| 210 |
+
cdim = ndim
|
| 211 |
+
if rems > 0:
|
| 212 |
+
# add remainder in increments of two to maintain even size
|
| 213 |
+
cdim += 2
|
| 214 |
+
rems -= 2
|
| 215 |
+
|
| 216 |
+
if cdim != prev_dim:
|
| 217 |
+
dim_t = torch.arange(cdim, dtype=torch.float32, device=xyz.device)
|
| 218 |
+
dim_t = self.temperature ** (2 * (dim_t // 2) / cdim)
|
| 219 |
+
|
| 220 |
+
# create batch x cdim x nccords embedding
|
| 221 |
+
raw_pos = xyz[:, :, d]
|
| 222 |
+
if self.scale:
|
| 223 |
+
raw_pos *= self.scale
|
| 224 |
+
pos = raw_pos[:, :, None] / dim_t
|
| 225 |
+
pos = torch.stack(
|
| 226 |
+
(pos[:, :, 0::2].sin(), pos[:, :, 1::2].cos()), dim=3
|
| 227 |
+
).flatten(2)
|
| 228 |
+
final_embeds.append(pos)
|
| 229 |
+
prev_dim = cdim
|
| 230 |
+
|
| 231 |
+
final_embeds = torch.cat(final_embeds, dim=2)
|
| 232 |
+
return final_embeds
|
| 233 |
+
def get_fourier_embeddings(self, xyz, num_channels=None, input_range=None):
|
| 234 |
+
if num_channels is None:
|
| 235 |
+
num_channels = self.gauss_B.shape[1] * 2
|
| 236 |
+
bsize, npoints = xyz.shape[0], xyz.shape[1]
|
| 237 |
+
assert num_channels > 0 and num_channels % 2 == 0
|
| 238 |
+
d_in, max_d_out = self.gauss_B.shape[0], self.gauss_B.shape[1]
|
| 239 |
+
d_out = num_channels // 2
|
| 240 |
+
# assert d_out <= max_d_out
|
| 241 |
+
assert d_in == xyz.shape[-1]
|
| 242 |
+
|
| 243 |
+
# clone coords so that shift/scale operations do not affect original tensor
|
| 244 |
+
# import pdb;pdb.set_trace()
|
| 245 |
+
ncoords = xyz.shape[1]
|
| 246 |
+
if self.normalize:
|
| 247 |
+
# xyz = shift_scale_points(xyz, src_range=input_range)
|
| 248 |
+
pass
|
| 249 |
+
|
| 250 |
+
xyz *= 2 * torch.pi
|
| 251 |
+
xyz_proj = torch.mm(xyz.view(-1, d_in), self.gauss_B[:, :d_out]).view(
|
| 252 |
+
bsize, npoints, d_out
|
| 253 |
+
)
|
| 254 |
+
final_embeds = [xyz_proj.sin(), xyz_proj.cos()]
|
| 255 |
+
|
| 256 |
+
# return batch x d_pos x npoints embedding
|
| 257 |
+
final_embeds = torch.cat(final_embeds, dim=2)
|
| 258 |
+
# import pdb;pdb.set_trace()
|
| 259 |
+
# final_embeds = self.ln(final_embeds)
|
| 260 |
+
final_embeds = F.normalize(final_embeds, p=2, dim=2)
|
| 261 |
+
|
| 262 |
+
# If necessary, you can permute it back to [batch, 196, 768]
|
| 263 |
+
return final_embeds
|
| 264 |
+
|
| 265 |
+
def forward(self, depth_map, num_channels=None, input_range=None):
|
| 266 |
+
cam_coords_tensor = self.generate_3d_coords_from_depth(depth_map) # (B, H, W, 3)
|
| 267 |
+
# cam_coords_tensor = torch.tensor(cam_coords, dtype=torch.float16) # (B, H, W, 3)
|
| 268 |
+
cam_coords_tensor = cam_coords_tensor.view(cam_coords_tensor.size(0), -1, 3) # (B, H*W, 3)
|
| 269 |
+
xyz=cam_coords_tensor
|
| 270 |
+
# import pdb;pdb.set_trace()
|
| 271 |
+
assert xyz.ndim == 3
|
| 272 |
+
# xyz is batch x npoints x 3
|
| 273 |
+
if self.pos_type == "sine":
|
| 274 |
+
with torch.no_grad():
|
| 275 |
+
return self.get_sine_embeddings(xyz, 768, input_range)
|
| 276 |
+
elif self.pos_type == "fourier":
|
| 277 |
+
with torch.no_grad():
|
| 278 |
+
return self.get_fourier_embeddings(xyz, num_channels, input_range)
|
| 279 |
+
else:
|
| 280 |
+
raise ValueError(f"Unknown {self.pos_type}")
|
| 281 |
+
|
| 282 |
+
def positiontrans3d(self,depth_map):
|
| 283 |
+
cam_coords_tensor = self.generate_3d_coords_from_depth(depth_map) # (B, H, W, 3)
|
| 284 |
+
# cam_coords_tensor = torch.tensor(cam_coords, dtype=torch.float16) # (B, H, W, 3)
|
| 285 |
+
cam_coords_tensor = cam_coords_tensor.view(cam_coords_tensor.size(0), -1, 3) # (B, H*W, 3)
|
| 286 |
+
x=cam_coords_tensor
|
| 287 |
+
x = x.permute(0, 2, 1) # (B, H*W, 3) -> (B, 3, H*W)
|
| 288 |
+
x = self.trans3d(x) # 1D卷积映射 (B, 768, H*W)
|
| 289 |
+
x = x.permute(0, 2, 1) # 转换回 (B, H*W, 768)
|
| 290 |
+
return x
|
| 291 |
+
def generate_3d_coords_from_depth(self, depth_maps):
|
| 292 |
+
# 假设 depth_maps 形状为 (B, H, W)
|
| 293 |
+
B, H, W = depth_maps.shape
|
| 294 |
+
|
| 295 |
+
# 生成网格 i, j,形状为 (H, W)
|
| 296 |
+
i, j = torch.meshgrid(torch.arange(H, device=depth_maps.device), torch.arange(W, device=depth_maps.device), indexing='ij')
|
| 297 |
+
|
| 298 |
+
# 归一化 x 和 y 坐标
|
| 299 |
+
x = j.float() / (W - 1) # (H, W)
|
| 300 |
+
y = i.float() / (H - 1) # (H, W)
|
| 301 |
+
|
| 302 |
+
# 将 x 和 y 扩展到 (B, H, W) 以匹配 depth_maps
|
| 303 |
+
x = x.unsqueeze(0).expand(B, -1, -1) # (B, H, W)
|
| 304 |
+
y = y.unsqueeze(0).expand(B, -1, -1) # (B, H, W)
|
| 305 |
+
|
| 306 |
+
z = depth_maps # z 坐标为深度值,形状为 (B, H, W)
|
| 307 |
+
|
| 308 |
+
# 组合成 (B, H, W, 3) 的三维坐标
|
| 309 |
+
coords = torch.stack([x, y, z], dim=-1) # (B, H, W, 3)
|
| 310 |
+
|
| 311 |
+
return coords
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
class Bottleneck(nn.Module):
|
| 315 |
+
expansion = 4
|
| 316 |
+
|
| 317 |
+
def __init__(self, inplanes, planes, stride=1):
|
| 318 |
+
super().__init__()
|
| 319 |
+
|
| 320 |
+
# all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
|
| 321 |
+
self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
|
| 322 |
+
self.bn1 = nn.BatchNorm2d(planes)
|
| 323 |
+
self.relu1 = nn.ReLU(inplace=True)
|
| 324 |
+
|
| 325 |
+
self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
|
| 326 |
+
self.bn2 = nn.BatchNorm2d(planes)
|
| 327 |
+
self.relu2 = nn.ReLU(inplace=True)
|
| 328 |
+
|
| 329 |
+
self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
|
| 330 |
+
|
| 331 |
+
self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
|
| 332 |
+
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
|
| 333 |
+
self.relu3 = nn.ReLU(inplace=True)
|
| 334 |
+
|
| 335 |
+
self.downsample = None
|
| 336 |
+
self.stride = stride
|
| 337 |
+
|
| 338 |
+
if stride > 1 or inplanes != planes * Bottleneck.expansion:
|
| 339 |
+
# downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
|
| 340 |
+
self.downsample = nn.Sequential(OrderedDict([
|
| 341 |
+
("-1", nn.AvgPool2d(stride)),
|
| 342 |
+
("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
|
| 343 |
+
("1", nn.BatchNorm2d(planes * self.expansion))
|
| 344 |
+
]))
|
| 345 |
+
|
| 346 |
+
def forward(self, x: torch.Tensor):
|
| 347 |
+
identity = x
|
| 348 |
+
|
| 349 |
+
out = self.relu1(self.bn1(self.conv1(x)))
|
| 350 |
+
out = self.relu2(self.bn2(self.conv2(out)))
|
| 351 |
+
out = self.avgpool(out)
|
| 352 |
+
out = self.bn3(self.conv3(out))
|
| 353 |
+
|
| 354 |
+
if self.downsample is not None:
|
| 355 |
+
identity = self.downsample(x)
|
| 356 |
+
|
| 357 |
+
out += identity
|
| 358 |
+
out = self.relu3(out)
|
| 359 |
+
return out
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
class AttentionPool2d(nn.Module):
|
| 363 |
+
def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
|
| 364 |
+
super().__init__()
|
| 365 |
+
self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
|
| 366 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim)
|
| 367 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim)
|
| 368 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim)
|
| 369 |
+
self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
|
| 370 |
+
self.num_heads = num_heads
|
| 371 |
+
|
| 372 |
+
def forward(self, x):
|
| 373 |
+
x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
|
| 374 |
+
x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
|
| 375 |
+
x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
|
| 376 |
+
x, _ = F.multi_head_attention_forward(
|
| 377 |
+
query=x[:1], key=x, value=x,
|
| 378 |
+
embed_dim_to_check=x.shape[-1],
|
| 379 |
+
num_heads=self.num_heads,
|
| 380 |
+
q_proj_weight=self.q_proj.weight,
|
| 381 |
+
k_proj_weight=self.k_proj.weight,
|
| 382 |
+
v_proj_weight=self.v_proj.weight,
|
| 383 |
+
in_proj_weight=None,
|
| 384 |
+
in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
|
| 385 |
+
bias_k=None,
|
| 386 |
+
bias_v=None,
|
| 387 |
+
add_zero_attn=False,
|
| 388 |
+
dropout_p=0,
|
| 389 |
+
out_proj_weight=self.c_proj.weight,
|
| 390 |
+
out_proj_bias=self.c_proj.bias,
|
| 391 |
+
use_separate_proj_weight=True,
|
| 392 |
+
training=self.training,
|
| 393 |
+
need_weights=False
|
| 394 |
+
)
|
| 395 |
+
return x.squeeze(0)
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
class ModifiedResNet(nn.Module):
|
| 399 |
+
"""
|
| 400 |
+
A ResNet class that is similar to torchvision's but contains the following changes:
|
| 401 |
+
- There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
|
| 402 |
+
- Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
|
| 403 |
+
- The final pooling layer is a QKV attention instead of an average pool
|
| 404 |
+
"""
|
| 405 |
+
|
| 406 |
+
def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
|
| 407 |
+
super().__init__()
|
| 408 |
+
self.output_dim = output_dim
|
| 409 |
+
self.input_resolution = input_resolution
|
| 410 |
+
|
| 411 |
+
# the 3-layer stem
|
| 412 |
+
self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
|
| 413 |
+
self.conv1_alpha = nn.Conv2d(in_channels=1, out_channels=width // 2, kernel_size=3, stride=2, padding=1, bias=False)
|
| 414 |
+
self.bn1 = nn.BatchNorm2d(width // 2)
|
| 415 |
+
self.relu1 = nn.ReLU(inplace=True)
|
| 416 |
+
self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
|
| 417 |
+
self.bn2 = nn.BatchNorm2d(width // 2)
|
| 418 |
+
self.relu2 = nn.ReLU(inplace=True)
|
| 419 |
+
self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
|
| 420 |
+
self.bn3 = nn.BatchNorm2d(width)
|
| 421 |
+
self.relu3 = nn.ReLU(inplace=True)
|
| 422 |
+
self.avgpool = nn.AvgPool2d(2)
|
| 423 |
+
|
| 424 |
+
# residual layers
|
| 425 |
+
self._inplanes = width # this is a *mutable* variable used during construction
|
| 426 |
+
self.layer1 = self._make_layer(width, layers[0])
|
| 427 |
+
self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
|
| 428 |
+
self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
|
| 429 |
+
self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
|
| 430 |
+
|
| 431 |
+
embed_dim = width * 32 # the ResNet feature dimension
|
| 432 |
+
self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
|
| 433 |
+
|
| 434 |
+
def _make_layer(self, planes, blocks, stride=1):
|
| 435 |
+
layers = [Bottleneck(self._inplanes, planes, stride)]
|
| 436 |
+
|
| 437 |
+
self._inplanes = planes * Bottleneck.expansion
|
| 438 |
+
for _ in range(1, blocks):
|
| 439 |
+
layers.append(Bottleneck(self._inplanes, planes))
|
| 440 |
+
|
| 441 |
+
return nn.Sequential(*layers)
|
| 442 |
+
|
| 443 |
+
def forward(self, x, alpha=None):
|
| 444 |
+
def stem(x):
|
| 445 |
+
x = self.relu1(self.bn1(self.conv1(x) + self.conv1_alpha(alpha)))
|
| 446 |
+
x = self.relu2(self.bn2(self.conv2(x)))
|
| 447 |
+
x = self.relu3(self.bn3(self.conv3(x)))
|
| 448 |
+
x = self.avgpool(x)
|
| 449 |
+
return x
|
| 450 |
+
|
| 451 |
+
x = x.type(self.conv1.weight.dtype)
|
| 452 |
+
x = stem(x)
|
| 453 |
+
x = self.layer1(x)
|
| 454 |
+
x = self.layer2(x)
|
| 455 |
+
x = self.layer3(x)
|
| 456 |
+
x = self.layer4(x)
|
| 457 |
+
x = self.attnpool(x)
|
| 458 |
+
|
| 459 |
+
return x
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
class LayerNorm(nn.LayerNorm):
|
| 463 |
+
"""Subclass torch's LayerNorm to handle fp16."""
|
| 464 |
+
|
| 465 |
+
def forward(self, x: torch.Tensor):
|
| 466 |
+
orig_type = x.dtype
|
| 467 |
+
# ret = super().forward(x.type(torch.float32))
|
| 468 |
+
ret = super().forward(x)
|
| 469 |
+
return ret.type(orig_type)
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
class QuickGELU(nn.Module):
|
| 473 |
+
def forward(self, x: torch.Tensor):
|
| 474 |
+
return x * torch.sigmoid(1.702 * x)
|
| 475 |
+
|
| 476 |
+
class Attention(nn.Module):
|
| 477 |
+
def __init__(
|
| 478 |
+
self,
|
| 479 |
+
dim,
|
| 480 |
+
num_heads=8,
|
| 481 |
+
qkv_bias=True,
|
| 482 |
+
scaled_cosine=False,
|
| 483 |
+
scale_heads=False,
|
| 484 |
+
logit_scale_max=math.log(1. / 0.01),
|
| 485 |
+
attn_drop=0.,
|
| 486 |
+
proj_drop=0.,
|
| 487 |
+
lora_adapt=False,
|
| 488 |
+
rank=16,
|
| 489 |
+
patch_num=16
|
| 490 |
+
):
|
| 491 |
+
super().__init__()
|
| 492 |
+
self.scaled_cosine = scaled_cosine
|
| 493 |
+
self.scale_heads = scale_heads
|
| 494 |
+
assert dim % num_heads == 0, 'dim should be divisible by num_heads'
|
| 495 |
+
self.num_heads = num_heads
|
| 496 |
+
self.head_dim = dim // num_heads
|
| 497 |
+
self.scale = self.head_dim ** -0.5
|
| 498 |
+
self.logit_scale_max = logit_scale_max
|
| 499 |
+
self.use_rel_pos = True # 保存相对位置编码的使用状态
|
| 500 |
+
self.rpe = RPE(patch_num=patch_num,num_heads=self.num_heads)
|
| 501 |
+
self.rpe.requires_grad=True
|
| 502 |
+
# import pdb;pdb.set_trace()
|
| 503 |
+
# keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original
|
| 504 |
+
if lora_adapt:
|
| 505 |
+
print("!!!!!!!!!!using lora for qkv projection!!!!!!!!!!")
|
| 506 |
+
self.in_proj = lora.MergedLinear(dim, 3*dim, r=rank, enable_lora=[True, False, True])
|
| 507 |
+
else:
|
| 508 |
+
self.in_proj = nn.Linear(dim, dim * 3)
|
| 509 |
+
# self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale)
|
| 510 |
+
# if qkv_bias:
|
| 511 |
+
# self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3))
|
| 512 |
+
# else:
|
| 513 |
+
# self.in_proj_bias = None
|
| 514 |
+
|
| 515 |
+
if self.scaled_cosine:
|
| 516 |
+
self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))))
|
| 517 |
+
else:
|
| 518 |
+
self.logit_scale = None
|
| 519 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 520 |
+
if self.scale_heads:
|
| 521 |
+
self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1)))
|
| 522 |
+
else:
|
| 523 |
+
self.head_scale = None
|
| 524 |
+
self.out_proj = nn.Linear(dim, dim) if not lora_adapt else lora.Linear(dim, dim, r=rank)
|
| 525 |
+
self.out_drop = nn.Dropout(proj_drop)
|
| 526 |
+
|
| 527 |
+
def forward(self, x, attn_mask = None,depth=None):
|
| 528 |
+
L, N, C = x.shape
|
| 529 |
+
q, k, v = self.in_proj(x).chunk(3, dim=-1)
|
| 530 |
+
q = q.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
|
| 531 |
+
k = k.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
|
| 532 |
+
v = v.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
|
| 533 |
+
|
| 534 |
+
if self.logit_scale is not None:
|
| 535 |
+
attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2))
|
| 536 |
+
logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp()
|
| 537 |
+
attn = attn.view(N, self.num_heads, L, L) * logit_scale
|
| 538 |
+
attn = attn.view(-1, L, L)
|
| 539 |
+
else:
|
| 540 |
+
q = q * self.scale
|
| 541 |
+
attn = torch.bmm(q, k.transpose(-2, -1))
|
| 542 |
+
|
| 543 |
+
if depth is not None:
|
| 544 |
+
depth=depth.squeeze(1)
|
| 545 |
+
res= self.rpe(depth)
|
| 546 |
+
res=res.reshape(-1,res.size(-2),res.size(-1))
|
| 547 |
+
# import pdb;pdb.set_trace()
|
| 548 |
+
attn[:,1:,1:]=attn[:,1:,1:]+res
|
| 549 |
+
|
| 550 |
+
if attn_mask is not None:
|
| 551 |
+
if attn_mask.dtype == torch.bool:
|
| 552 |
+
new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype)
|
| 553 |
+
new_attn_mask.masked_fill_(attn_mask, float("-inf"))
|
| 554 |
+
attn_mask = new_attn_mask
|
| 555 |
+
attn += attn_mask
|
| 556 |
+
|
| 557 |
+
attn = attn.softmax(dim=-1)
|
| 558 |
+
attn = self.attn_drop(attn)
|
| 559 |
+
|
| 560 |
+
x = torch.bmm(attn, v)
|
| 561 |
+
if self.head_scale is not None:
|
| 562 |
+
x = x.view(N, self.num_heads, L, C) * self.head_scale
|
| 563 |
+
x = x.view(-1, L, C)
|
| 564 |
+
x = x.transpose(0, 1).reshape(L, N, C)
|
| 565 |
+
x = self.out_proj(x)
|
| 566 |
+
x = self.out_drop(x)
|
| 567 |
+
return x, attn
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
class CustomResidualAttentionBlock(nn.Module):
|
| 571 |
+
def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None, lora_adapt=False, rank=16,patch_num=16):
|
| 572 |
+
super().__init__()
|
| 573 |
+
|
| 574 |
+
self.attn = Attention(d_model, n_head, lora_adapt=lora_adapt, rank=rank,patch_num=patch_num)
|
| 575 |
+
self.ln_1 = LayerNorm(d_model)
|
| 576 |
+
self.mlp = nn.Sequential(OrderedDict([
|
| 577 |
+
("c_fc", nn.Linear(d_model, d_model * 4) if not lora_adapt else lora.Linear(d_model, d_model*4, r=rank)),
|
| 578 |
+
("gelu", QuickGELU()),
|
| 579 |
+
("c_proj", nn.Linear(d_model * 4, d_model) if not lora_adapt else lora.Linear(d_model*4, d_model, r=rank))
|
| 580 |
+
]))
|
| 581 |
+
self.ln_2 = LayerNorm(d_model)
|
| 582 |
+
self.ln_cpe = LayerNorm(d_model)
|
| 583 |
+
self.attn_mask = attn_mask
|
| 584 |
+
self.cpe=CPEconv(d_model,patch_num)
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def attention(self, x: torch.Tensor,depth=None):
|
| 588 |
+
self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
|
| 589 |
+
return self.attn(x, attn_mask=self.attn_mask,depth=depth)
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def forward(self, x: torch.Tensor, return_attn=False,depth=None):
|
| 593 |
+
# import pdb;pdb.set_trace()
|
| 594 |
+
# x ([577, 50, 1024])
|
| 595 |
+
# if None:
|
| 596 |
+
shortcut=x
|
| 597 |
+
# import pdb;pdb.set_trace()
|
| 598 |
+
# shapes=x.shape
|
| 599 |
+
# x= x.reshape(-1,x.size(-1))
|
| 600 |
+
# import pdb;pdb.set_trace()
|
| 601 |
+
# cposi = self.cpe(x, depth).reshape(shapes)
|
| 602 |
+
cposi = self.cpe(self.ln_cpe(x), depth)
|
| 603 |
+
x =shortcut+cposi
|
| 604 |
+
|
| 605 |
+
attn_out, attn = self.attention(self.ln_1(x),depth)
|
| 606 |
+
x = x + attn_out
|
| 607 |
+
x = x + self.mlp(self.ln_2(x))
|
| 608 |
+
if return_attn:
|
| 609 |
+
return x, attn
|
| 610 |
+
else:
|
| 611 |
+
return x
|
| 612 |
+
|
| 613 |
+
class ResidualAttentionBlock(nn.Module):
|
| 614 |
+
def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
|
| 615 |
+
super().__init__()
|
| 616 |
+
|
| 617 |
+
self.attn = nn.MultiheadAttention(d_model, n_head)
|
| 618 |
+
self.ln_1 = LayerNorm(d_model)
|
| 619 |
+
self.mlp = nn.Sequential(OrderedDict([
|
| 620 |
+
("c_fc", nn.Linear(d_model, d_model * 4)),
|
| 621 |
+
("gelu", QuickGELU()),
|
| 622 |
+
("c_proj", nn.Linear(d_model * 4, d_model))
|
| 623 |
+
]))
|
| 624 |
+
self.ln_2 = LayerNorm(d_model)
|
| 625 |
+
self.attn_mask = attn_mask
|
| 626 |
+
|
| 627 |
+
def attention(self, x: torch.Tensor):
|
| 628 |
+
self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
|
| 629 |
+
return self.attn(x, x, x, attn_mask=self.attn_mask)[0]
|
| 630 |
+
|
| 631 |
+
def forward(self, x: torch.Tensor):
|
| 632 |
+
x = x + self.attention(self.ln_1(x))
|
| 633 |
+
x = x + self.mlp(self.ln_2(x))
|
| 634 |
+
return x
|
| 635 |
+
|
| 636 |
+
class Transformer(nn.Module):
|
| 637 |
+
def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
|
| 638 |
+
super().__init__()
|
| 639 |
+
self.width = width
|
| 640 |
+
self.layers = layers
|
| 641 |
+
self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
|
| 642 |
+
|
| 643 |
+
def forward(self, x: torch.Tensor):
|
| 644 |
+
return self.resblocks(x)
|
| 645 |
+
|
| 646 |
+
class CustomTransformer(nn.Module):
|
| 647 |
+
def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None, lora_adapt=False, rank=16,patch_num=16):
|
| 648 |
+
super().__init__()
|
| 649 |
+
self.width = width
|
| 650 |
+
self.layers = layers
|
| 651 |
+
self.resblocks = nn.Sequential(*[CustomResidualAttentionBlock(width, heads, attn_mask, lora_adapt=lora_adapt, rank=rank,patch_num=patch_num) for _ in range(layers)])
|
| 652 |
+
|
| 653 |
+
def forward(self, x: torch.Tensor, return_attn=False,depth=None):
|
| 654 |
+
# import pdb;pdb.set_trace()
|
| 655 |
+
if return_attn:
|
| 656 |
+
for i, block in enumerate(self.resblocks):
|
| 657 |
+
if i == len(self.resblocks) - 1:
|
| 658 |
+
return block(x, return_attn=True,depth=depth)
|
| 659 |
+
else:
|
| 660 |
+
x = block(x,depth=depth)
|
| 661 |
+
assert False
|
| 662 |
+
for block in self.resblocks:
|
| 663 |
+
# import pdb;pdb.set_trace()
|
| 664 |
+
x = block(x, depth=depth) # 将 depth 传递给每个模块
|
| 665 |
+
return x
|
| 666 |
+
# return self.resblocks(x)
|
| 667 |
+
|
| 668 |
+
# ////////////////////////////////////////////////////////////////////////////////////////////
|
| 669 |
+
class VisionTransformer(nn.Module):
|
| 670 |
+
def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int, lora_adapt=False, rank=16):
|
| 671 |
+
super().__init__()
|
| 672 |
+
self.input_resolution = input_resolution
|
| 673 |
+
self.output_dim = output_dim
|
| 674 |
+
self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
|
| 675 |
+
self.conv1_alpha = nn.Conv2d(in_channels=1, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
|
| 676 |
+
nn.init.zeros_(self.conv1_alpha.weight)
|
| 677 |
+
scale = width ** -0.5
|
| 678 |
+
self.class_embedding = nn.Parameter(scale * torch.randn(width))
|
| 679 |
+
self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
|
| 680 |
+
# self.depth_positional_embedding = nn.Parameter(scale * torch.zeros((input_resolution // patch_size) ** 2, width)) # 用于alpha的深度编码
|
| 681 |
+
# self.depth_positional_embedding = PositionEmbeddingCoordsSine(temperature=10000,
|
| 682 |
+
# normalize=True,
|
| 683 |
+
# scale=2 * torch.pi,
|
| 684 |
+
# pos_type="fourier",
|
| 685 |
+
# d_pos=768, # 示例输出维度
|
| 686 |
+
# d_in=3,
|
| 687 |
+
# gauss_scale=1.0
|
| 688 |
+
# )
|
| 689 |
+
# self.sine_positional_embedding = PositionEmbeddingCoordsSine(temperature=10000,
|
| 690 |
+
# normalize=True,
|
| 691 |
+
# scale=2 * torch.pi,
|
| 692 |
+
# pos_type="sine",
|
| 693 |
+
# d_pos=768, # 示例输出维度
|
| 694 |
+
# d_in=3,
|
| 695 |
+
# gauss_scale=1.0
|
| 696 |
+
# )
|
| 697 |
+
# self.large_positional_embedding = PositionEmbeddingCoordsSine(temperature=10000,
|
| 698 |
+
# normalize=True,
|
| 699 |
+
# scale=2 * torch.pi,
|
| 700 |
+
# pos_type="sine",
|
| 701 |
+
# d_pos=1024, # 示例输出维度
|
| 702 |
+
# d_in=3,
|
| 703 |
+
# gauss_scale=1.0
|
| 704 |
+
# )
|
| 705 |
+
# self.depth_mlp=nn.Linear(768,768)
|
| 706 |
+
# nn.init.zeros_(self.depth_mlp.weight)
|
| 707 |
+
# if self.depth_mlp.bias is not None:
|
| 708 |
+
# nn.init.zeros_(self.depth_mlp.bias)
|
| 709 |
+
self.patch_size=patch_size
|
| 710 |
+
|
| 711 |
+
self.ln_pre = LayerNorm(width)
|
| 712 |
+
self.transformer = CustomTransformer(width, layers, heads, lora_adapt=lora_adapt, rank=rank,patch_num=input_resolution // patch_size)
|
| 713 |
+
|
| 714 |
+
self.ln_post = LayerNorm(width)
|
| 715 |
+
self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
|
| 716 |
+
|
| 717 |
+
def forward(self, x: torch.Tensor, alpha=None, return_attn=False,pos_embed=None):
|
| 718 |
+
# import pdb;pdb.set_trace()
|
| 719 |
+
x = self.conv1(x) # shape = [*, width, grid, grid]
|
| 720 |
+
# ASSUME alpha is always not None!
|
| 721 |
+
# import pdb;pdb.set_trace()
|
| 722 |
+
# if pos_embed == "nodepth":
|
| 723 |
+
# pass
|
| 724 |
+
# else:
|
| 725 |
+
# x = x + self.conv1_alpha(alpha)
|
| 726 |
+
# import pdb;pdb.set_trace()
|
| 727 |
+
|
| 728 |
+
x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
|
| 729 |
+
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
|
| 730 |
+
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]
|
| 731 |
+
# import pdb;pdb.set_trace()
|
| 732 |
+
alpha_resized = F.adaptive_avg_pool2d(alpha, (self.input_resolution // self.patch_size, self.input_resolution // self.patch_size))
|
| 733 |
+
# alpha_flattened = alpha_resized.flatten(start_dim=2).permute(0, 2, 1)
|
| 734 |
+
alpha_resized = alpha_resized.squeeze(1)
|
| 735 |
+
# x[:, 1:] += self.depth_positional_embedding.to(x.dtype) * alpha_flattened
|
| 736 |
+
# import pdb;pdb.set_trace()
|
| 737 |
+
# if pos_embed == "fourier":
|
| 738 |
+
# depth_embedding = self.depth_positional_embedding(alpha_resized)
|
| 739 |
+
# x[:, 1:] +=self.depth_mlp(depth_embedding)
|
| 740 |
+
# elif pos_embed == "sine":
|
| 741 |
+
# depth_embedding = self.sine_positional_embedding(alpha_resized)
|
| 742 |
+
# x[:, 1:] +=self.depth_mlp(depth_embedding)
|
| 743 |
+
# elif pos_embed == "3d":
|
| 744 |
+
# depth_embedding = self.depth_positional_embedding.positiontrans3d(alpha_resized)
|
| 745 |
+
# x[:, 1:] +=self.depth_mlp(depth_embedding)
|
| 746 |
+
|
| 747 |
+
x = x + self.positional_embedding.to(x.dtype)
|
| 748 |
+
x = self.ln_pre(x)
|
| 749 |
+
# import pdb;pdb.set_trace()
|
| 750 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
| 751 |
+
if return_attn:
|
| 752 |
+
x, attn_last = self.transformer(x, return_attn=True,depth=alpha_resized)
|
| 753 |
+
else:
|
| 754 |
+
x = self.transformer(x, return_attn=False,depth=alpha_resized)
|
| 755 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
| 756 |
+
|
| 757 |
+
# x = self.ln_post(x[:, 0, :])
|
| 758 |
+
x = self.ln_post(x)
|
| 759 |
+
# if self.proj is not None:
|
| 760 |
+
# x = x @ self.proj
|
| 761 |
+
if return_attn:
|
| 762 |
+
return x, attn_last
|
| 763 |
+
else:
|
| 764 |
+
return x
|
| 765 |
+
# /////////////////////////////////////////////////////////////////////////////////////////////////////
|
| 766 |
+
|
| 767 |
+
class CLIP(nn.Module):
|
| 768 |
+
def __init__(self,
|
| 769 |
+
embed_dim: int,
|
| 770 |
+
# vision
|
| 771 |
+
image_resolution: int,
|
| 772 |
+
vision_layers: Union[Tuple[int, int, int, int], int],
|
| 773 |
+
vision_width: int,
|
| 774 |
+
vision_patch_size: int,
|
| 775 |
+
# text
|
| 776 |
+
context_length: int,
|
| 777 |
+
vocab_size: int,
|
| 778 |
+
transformer_width: int,
|
| 779 |
+
transformer_heads: int,
|
| 780 |
+
transformer_layers: int,
|
| 781 |
+
lora_adapt = False,
|
| 782 |
+
rank = 16,
|
| 783 |
+
):
|
| 784 |
+
super().__init__()
|
| 785 |
+
|
| 786 |
+
self.context_length = context_length
|
| 787 |
+
|
| 788 |
+
if isinstance(vision_layers, (tuple, list)):
|
| 789 |
+
vision_heads = vision_width * 32 // 64
|
| 790 |
+
self.visual = ModifiedResNet(
|
| 791 |
+
layers=vision_layers,
|
| 792 |
+
output_dim=embed_dim,
|
| 793 |
+
heads=vision_heads,
|
| 794 |
+
input_resolution=image_resolution,
|
| 795 |
+
width=vision_width
|
| 796 |
+
)
|
| 797 |
+
else:
|
| 798 |
+
vision_heads = vision_width // 64
|
| 799 |
+
self.visual = VisionTransformer(
|
| 800 |
+
input_resolution=image_resolution,
|
| 801 |
+
patch_size=vision_patch_size,
|
| 802 |
+
width=vision_width,
|
| 803 |
+
layers=vision_layers,
|
| 804 |
+
heads=vision_heads,
|
| 805 |
+
output_dim=embed_dim,
|
| 806 |
+
lora_adapt=lora_adapt,
|
| 807 |
+
rank=rank
|
| 808 |
+
)
|
| 809 |
+
|
| 810 |
+
self.transformer = Transformer(
|
| 811 |
+
width=transformer_width,
|
| 812 |
+
layers=transformer_layers,
|
| 813 |
+
heads=transformer_heads,
|
| 814 |
+
attn_mask=self.build_attention_mask()
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
self.vocab_size = vocab_size
|
| 818 |
+
self.token_embedding = nn.Embedding(vocab_size, transformer_width)
|
| 819 |
+
self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
|
| 820 |
+
self.ln_final = LayerNorm(transformer_width)
|
| 821 |
+
self.hidden_size = vision_width
|
| 822 |
+
self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
|
| 823 |
+
self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
|
| 824 |
+
|
| 825 |
+
self.initialize_parameters()
|
| 826 |
+
|
| 827 |
+
def initialize_parameters(self):
|
| 828 |
+
nn.init.normal_(self.token_embedding.weight, std=0.02)
|
| 829 |
+
nn.init.normal_(self.positional_embedding, std=0.01)
|
| 830 |
+
|
| 831 |
+
if isinstance(self.visual, ModifiedResNet):
|
| 832 |
+
if self.visual.attnpool is not None:
|
| 833 |
+
std = self.visual.attnpool.c_proj.in_features ** -0.5
|
| 834 |
+
nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
|
| 835 |
+
nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
|
| 836 |
+
nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
|
| 837 |
+
nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
|
| 838 |
+
|
| 839 |
+
for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
|
| 840 |
+
for name, param in resnet_block.named_parameters():
|
| 841 |
+
if name.endswith("bn3.weight"):
|
| 842 |
+
nn.init.zeros_(param)
|
| 843 |
+
|
| 844 |
+
proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
|
| 845 |
+
attn_std = self.transformer.width ** -0.5
|
| 846 |
+
fc_std = (2 * self.transformer.width) ** -0.5
|
| 847 |
+
for block in self.transformer.resblocks:
|
| 848 |
+
nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
|
| 849 |
+
nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
|
| 850 |
+
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
|
| 851 |
+
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
|
| 852 |
+
|
| 853 |
+
if self.text_projection is not None:
|
| 854 |
+
nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
|
| 855 |
+
|
| 856 |
+
def build_attention_mask(self):
|
| 857 |
+
# lazily create causal attention mask, with full attention between the vision tokens
|
| 858 |
+
# pytorch uses additive attention mask; fill with -inf
|
| 859 |
+
mask = torch.empty(self.context_length, self.context_length)
|
| 860 |
+
mask.fill_(float("-inf"))
|
| 861 |
+
mask.triu_(1) # zero out the lower diagonal
|
| 862 |
+
return mask
|
| 863 |
+
|
| 864 |
+
@property
|
| 865 |
+
def dtype(self):
|
| 866 |
+
if not hasattr(self.visual, "conv1"):
|
| 867 |
+
return self.visual.module.conv1.weight.dtype
|
| 868 |
+
return self.visual.conv1.weight.dtype
|
| 869 |
+
@property
|
| 870 |
+
def device(self):
|
| 871 |
+
return torch.device("cuda")
|
| 872 |
+
|
| 873 |
+
def encode_image(self, image, alpha):
|
| 874 |
+
assert alpha is not None
|
| 875 |
+
return self.visual(image.type(self.dtype), alpha.type(self.dtype))
|
| 876 |
+
|
| 877 |
+
def encode_text(self, text):
|
| 878 |
+
x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
|
| 879 |
+
|
| 880 |
+
x = x + self.positional_embedding.type(self.dtype)
|
| 881 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
| 882 |
+
x = self.transformer(x)
|
| 883 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
| 884 |
+
x = self.ln_final(x).type(self.dtype)
|
| 885 |
+
|
| 886 |
+
# x.shape = [batch_size, n_ctx, transformer.width]
|
| 887 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
| 888 |
+
x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
|
| 889 |
+
|
| 890 |
+
return x
|
| 891 |
+
|
| 892 |
+
def our_encode_image(self,image, depth):
|
| 893 |
+
# import pdb;pdb.set_trace()
|
| 894 |
+
image_feature = self.visual(image, depth)
|
| 895 |
+
# 32. 577 . 768
|
| 896 |
+
return image_feature
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def forward(self, image, text, alpha):
|
| 900 |
+
image_features = self.encode_image(image, alpha)
|
| 901 |
+
text_features = self.encode_text(text)
|
| 902 |
+
|
| 903 |
+
# normalized features
|
| 904 |
+
image_features = image_features / image_features.norm(dim=1, keepdim=True)
|
| 905 |
+
text_features = text_features / text_features.norm(dim=1, keepdim=True)
|
| 906 |
+
|
| 907 |
+
# cosine similarity as logits
|
| 908 |
+
logit_scale = self.logit_scale.exp()
|
| 909 |
+
logits_per_image = logit_scale * image_features @ text_features.t()
|
| 910 |
+
logits_per_text = logits_per_image.t()
|
| 911 |
+
|
| 912 |
+
# shape = [global_batch_size, global_batch_size]
|
| 913 |
+
return logits_per_image, logits_per_text
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
def convert_weights(model: nn.Module):
|
| 917 |
+
"""Convert applicable model parameters to fp16"""
|
| 918 |
+
|
| 919 |
+
def _convert_weights_to_fp16(l):
|
| 920 |
+
if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
|
| 921 |
+
l.weight.data = l.weight.data.half()
|
| 922 |
+
if l.bias is not None:
|
| 923 |
+
l.bias.data = l.bias.data.half()
|
| 924 |
+
|
| 925 |
+
if isinstance(l, nn.MultiheadAttention):
|
| 926 |
+
for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
|
| 927 |
+
tensor = getattr(l, attr)
|
| 928 |
+
if tensor is not None:
|
| 929 |
+
tensor.data = tensor.data.half()
|
| 930 |
+
|
| 931 |
+
for name in ["text_projection", "proj"]:
|
| 932 |
+
if hasattr(l, name):
|
| 933 |
+
attr = getattr(l, name)
|
| 934 |
+
if attr is not None:
|
| 935 |
+
attr.data = attr.data.half()
|
| 936 |
+
|
| 937 |
+
model.apply(_convert_weights_to_fp16)
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
def build_model(state_dict: dict, lora_adapt=False, rank=16):
|
| 941 |
+
vit = "visual.proj" in state_dict
|
| 942 |
+
|
| 943 |
+
if vit:
|
| 944 |
+
vision_width = state_dict["visual.conv1.weight"].shape[0]
|
| 945 |
+
vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
|
| 946 |
+
vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
|
| 947 |
+
grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
|
| 948 |
+
image_resolution = vision_patch_size * grid_size
|
| 949 |
+
else:
|
| 950 |
+
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]]
|
| 951 |
+
vision_layers = tuple(counts)
|
| 952 |
+
vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
|
| 953 |
+
output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
|
| 954 |
+
vision_patch_size = None
|
| 955 |
+
assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
|
| 956 |
+
image_resolution = output_width * 32
|
| 957 |
+
|
| 958 |
+
embed_dim = state_dict["text_projection"].shape[1]
|
| 959 |
+
context_length = state_dict["positional_embedding"].shape[0]
|
| 960 |
+
vocab_size = state_dict["token_embedding.weight"].shape[0]
|
| 961 |
+
transformer_width = state_dict["ln_final.weight"].shape[0]
|
| 962 |
+
transformer_heads = transformer_width // 64
|
| 963 |
+
transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
|
| 964 |
+
|
| 965 |
+
# always load lora version
|
| 966 |
+
model = CLIP(
|
| 967 |
+
embed_dim,
|
| 968 |
+
image_resolution, vision_layers, vision_width, vision_patch_size,
|
| 969 |
+
context_length, vocab_size, transformer_width, transformer_heads, transformer_layers,
|
| 970 |
+
lora_adapt=lora_adapt, rank=rank,
|
| 971 |
+
)
|
| 972 |
+
|
| 973 |
+
model_configs = {
|
| 974 |
+
'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384]},
|
| 975 |
+
'vitb': {'encoder': 'vitb', 'features': 128, 'out_channels': [96, 192, 384, 768]},
|
| 976 |
+
'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]},
|
| 977 |
+
'vitg': {'encoder': 'vitg', 'features': 384, 'out_channels': [1536, 1536, 1536, 1536]}
|
| 978 |
+
}
|
| 979 |
+
encoder = 'vitb'
|
| 980 |
+
|
| 981 |
+
depth_model=DepthAnythingV2(**model_configs[encoder])
|
| 982 |
+
depth_model.load_state_dict(torch.load(f'/home/aiops/wangzh/zss/Depth-Anything-V2/checkpoints/depth_anything_v2_{encoder}.pth', map_location='cpu'))
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
for key in ["input_resolution", "context_length", "vocab_size"]:
|
| 986 |
+
if key in state_dict:
|
| 987 |
+
del state_dict[key]
|
| 988 |
+
# para_wb to linear
|
| 989 |
+
new_state_dict = collections.OrderedDict()
|
| 990 |
+
for k, v in state_dict.items():
|
| 991 |
+
if 'visual' in k:
|
| 992 |
+
if 'in_proj_weight' in k:
|
| 993 |
+
new_state_dict[k.replace('in_proj_weight', 'in_proj.weight')] = v
|
| 994 |
+
elif 'in_proj_bias' in k:
|
| 995 |
+
new_state_dict[k.replace('in_proj_bias', 'in_proj.bias')] = v
|
| 996 |
+
else:
|
| 997 |
+
new_state_dict[k] = v
|
| 998 |
+
else:
|
| 999 |
+
new_state_dict[k] = v
|
| 1000 |
+
|
| 1001 |
+
state_dict = new_state_dict
|
| 1002 |
+
# add rgba_conv_weight
|
| 1003 |
+
if 'visual.conv1_alpha.weight' not in state_dict.keys(): # zero initialization on alpha channel
|
| 1004 |
+
rgb_weight = state_dict['visual.conv1.weight'].clone().detach()
|
| 1005 |
+
rgba_weigth = torch.zeros_like(rgb_weight)[:, 0:1, :, :]
|
| 1006 |
+
state_dict['visual.conv1_alpha.weight'] = rgba_weigth
|
| 1007 |
+
convert_weights(model)
|
| 1008 |
+
model.load_state_dict(state_dict, strict=False)
|
| 1009 |
+
return model.eval(), depth_model
|
alpha_clip_final/simple_tokenizer.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gzip
|
| 2 |
+
import html
|
| 3 |
+
import os
|
| 4 |
+
from functools import lru_cache
|
| 5 |
+
|
| 6 |
+
import ftfy
|
| 7 |
+
import regex as re
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@lru_cache()
|
| 11 |
+
def default_bpe():
|
| 12 |
+
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@lru_cache()
|
| 16 |
+
def bytes_to_unicode():
|
| 17 |
+
"""
|
| 18 |
+
Returns list of utf-8 byte and a corresponding list of unicode strings.
|
| 19 |
+
The reversible bpe codes work on unicode strings.
|
| 20 |
+
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
|
| 21 |
+
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
|
| 22 |
+
This is a signficant percentage of your normal, say, 32K bpe vocab.
|
| 23 |
+
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
|
| 24 |
+
And avoids mapping to whitespace/control characters the bpe code barfs on.
|
| 25 |
+
"""
|
| 26 |
+
bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
|
| 27 |
+
cs = bs[:]
|
| 28 |
+
n = 0
|
| 29 |
+
for b in range(2**8):
|
| 30 |
+
if b not in bs:
|
| 31 |
+
bs.append(b)
|
| 32 |
+
cs.append(2**8+n)
|
| 33 |
+
n += 1
|
| 34 |
+
cs = [chr(n) for n in cs]
|
| 35 |
+
return dict(zip(bs, cs))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def get_pairs(word):
|
| 39 |
+
"""Return set of symbol pairs in a word.
|
| 40 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
| 41 |
+
"""
|
| 42 |
+
pairs = set()
|
| 43 |
+
prev_char = word[0]
|
| 44 |
+
for char in word[1:]:
|
| 45 |
+
pairs.add((prev_char, char))
|
| 46 |
+
prev_char = char
|
| 47 |
+
return pairs
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def basic_clean(text):
|
| 51 |
+
text = ftfy.fix_text(text)
|
| 52 |
+
text = html.unescape(html.unescape(text))
|
| 53 |
+
return text.strip()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def whitespace_clean(text):
|
| 57 |
+
text = re.sub(r'\s+', ' ', text)
|
| 58 |
+
text = text.strip()
|
| 59 |
+
return text
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class SimpleTokenizer(object):
|
| 63 |
+
def __init__(self, bpe_path: str = default_bpe()):
|
| 64 |
+
self.byte_encoder = bytes_to_unicode()
|
| 65 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
| 66 |
+
merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
|
| 67 |
+
merges = merges[1:49152-256-2+1]
|
| 68 |
+
merges = [tuple(merge.split()) for merge in merges]
|
| 69 |
+
vocab = list(bytes_to_unicode().values())
|
| 70 |
+
vocab = vocab + [v+'</w>' for v in vocab]
|
| 71 |
+
for merge in merges:
|
| 72 |
+
vocab.append(''.join(merge))
|
| 73 |
+
vocab.extend(['<|startoftext|>', '<|endoftext|>'])
|
| 74 |
+
self.encoder = dict(zip(vocab, range(len(vocab))))
|
| 75 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 76 |
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
| 77 |
+
self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
|
| 78 |
+
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)
|
| 79 |
+
|
| 80 |
+
def bpe(self, token):
|
| 81 |
+
if token in self.cache:
|
| 82 |
+
return self.cache[token]
|
| 83 |
+
word = tuple(token[:-1]) + ( token[-1] + '</w>',)
|
| 84 |
+
pairs = get_pairs(word)
|
| 85 |
+
|
| 86 |
+
if not pairs:
|
| 87 |
+
return token+'</w>'
|
| 88 |
+
|
| 89 |
+
while True:
|
| 90 |
+
bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
|
| 91 |
+
if bigram not in self.bpe_ranks:
|
| 92 |
+
break
|
| 93 |
+
first, second = bigram
|
| 94 |
+
new_word = []
|
| 95 |
+
i = 0
|
| 96 |
+
while i < len(word):
|
| 97 |
+
try:
|
| 98 |
+
j = word.index(first, i)
|
| 99 |
+
new_word.extend(word[i:j])
|
| 100 |
+
i = j
|
| 101 |
+
except:
|
| 102 |
+
new_word.extend(word[i:])
|
| 103 |
+
break
|
| 104 |
+
|
| 105 |
+
if word[i] == first and i < len(word)-1 and word[i+1] == second:
|
| 106 |
+
new_word.append(first+second)
|
| 107 |
+
i += 2
|
| 108 |
+
else:
|
| 109 |
+
new_word.append(word[i])
|
| 110 |
+
i += 1
|
| 111 |
+
new_word = tuple(new_word)
|
| 112 |
+
word = new_word
|
| 113 |
+
if len(word) == 1:
|
| 114 |
+
break
|
| 115 |
+
else:
|
| 116 |
+
pairs = get_pairs(word)
|
| 117 |
+
word = ' '.join(word)
|
| 118 |
+
self.cache[token] = word
|
| 119 |
+
return word
|
| 120 |
+
|
| 121 |
+
def encode(self, text):
|
| 122 |
+
bpe_tokens = []
|
| 123 |
+
text = whitespace_clean(basic_clean(text)).lower()
|
| 124 |
+
for token in re.findall(self.pat, text):
|
| 125 |
+
token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
|
| 126 |
+
bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
|
| 127 |
+
return bpe_tokens
|
| 128 |
+
|
| 129 |
+
def decode(self, tokens):
|
| 130 |
+
text = ''.join([self.decoder[token] for token in tokens])
|
| 131 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
|
| 132 |
+
return text
|
answer_check.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
# 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:
|
| 5 |
+
# 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:
|
| 6 |
+
# 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:
|
| 7 |
+
# 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:
|
| 8 |
+
# 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:
|
| 9 |
+
# 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:
|
| 10 |
+
# 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:
|
| 11 |
+
# 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:
|
| 12 |
+
# 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:
|
| 13 |
+
# 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:
|
| 14 |
+
|
| 15 |
+
#
|
| 16 |
+
# 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:
|
| 17 |
+
# 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:
|
| 18 |
+
# 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:
|
| 19 |
+
# 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:
|
| 20 |
+
# 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:
|
| 21 |
+
# 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:
|
| 22 |
+
|
| 23 |
+
# 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:
|
| 24 |
+
# 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:
|
| 25 |
+
# 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:
|
| 26 |
+
# 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:
|
| 27 |
+
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:
|
| 28 |
+
# 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:
|
| 29 |
+
# 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:
|
| 30 |
+
# 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:
|
| 31 |
+
# 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:
|
| 32 |
+
|
| 33 |
+
reader1 = json.load(reader1)
|
| 34 |
+
|
| 35 |
+
correct = 0
|
| 36 |
+
total = 0
|
| 37 |
+
for index, (line1, line2) in enumerate(zip(reader1, reader2), 1):
|
| 38 |
+
total += 1
|
| 39 |
+
|
| 40 |
+
answer = line2.strip()
|
| 41 |
+
ground_truth = line1['answer']
|
| 42 |
+
# ground_truth = json.loads(line1.strip())['answer']
|
| 43 |
+
# length = len(ground_truth)
|
| 44 |
+
flag = False
|
| 45 |
+
# choices = json.loads(line1.strip())['choices']
|
| 46 |
+
|
| 47 |
+
# if ground_truth in answer:
|
| 48 |
+
# correct += 1
|
| 49 |
+
# import pdb;pdb.set_trace()
|
| 50 |
+
# if ('A' in answer) and ('B' in answer) and ('C' in answer) and ('D' in answer):
|
| 51 |
+
# print('missed',index)
|
| 52 |
+
# continue
|
| 53 |
+
# if ground_truth == '(A)':
|
| 54 |
+
# if 'left' in answer:
|
| 55 |
+
# correct += 1
|
| 56 |
+
# print("yes",index)
|
| 57 |
+
# elif ground_truth == '(B)':
|
| 58 |
+
# if 'right' in answer:
|
| 59 |
+
# correct += 1
|
| 60 |
+
# print("yes",index)
|
| 61 |
+
# if ground_truth == '(A)':
|
| 62 |
+
# if 'second' in answer:
|
| 63 |
+
# correct += 1
|
| 64 |
+
# print("yes",index)
|
| 65 |
+
# elif ground_truth == '(B)':
|
| 66 |
+
# if 'third' in answer:
|
| 67 |
+
# correct += 1
|
| 68 |
+
# print("yes",index)
|
| 69 |
+
# count_sed = answer.count('sed')
|
| 70 |
+
# count_tird = answer.count('tird')
|
| 71 |
+
if ground_truth == 0:
|
| 72 |
+
if ('A' in answer) :
|
| 73 |
+
correct += 1
|
| 74 |
+
print("yes",index)
|
| 75 |
+
|
| 76 |
+
elif ground_truth == 1:
|
| 77 |
+
if ('B' in answer) :
|
| 78 |
+
correct += 1
|
| 79 |
+
print("yes",index)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
elif ground_truth == 2:
|
| 83 |
+
if ('C' in answer) :
|
| 84 |
+
correct += 1
|
| 85 |
+
print("yes",index)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
elif ground_truth == 3:
|
| 89 |
+
if ('D' in answer) :
|
| 90 |
+
correct += 1
|
| 91 |
+
print("yes",index)
|
| 92 |
+
# if ground_truth == answer:
|
| 93 |
+
# correct += 1
|
| 94 |
+
# print("yes",index)
|
| 95 |
+
|
| 96 |
+
# if ground_truth == '(A)':
|
| 97 |
+
# if 'A' in answer :
|
| 98 |
+
# correct += 1
|
| 99 |
+
# print("yes",index)
|
| 100 |
+
# elif ground_truth == '(B)':
|
| 101 |
+
# if 'B' in answer:
|
| 102 |
+
# correct += 1
|
| 103 |
+
# print("yes",index)
|
| 104 |
+
# elif ground_truth == '(C)':
|
| 105 |
+
# if 'C' in answer:
|
| 106 |
+
# correct += 1
|
| 107 |
+
# print("yes",index)
|
| 108 |
+
# elif ground_truth == '(D)':
|
| 109 |
+
# if 'D' in answer:
|
| 110 |
+
# correct += 1
|
| 111 |
+
# print("yes",index)
|
| 112 |
+
# if ground_truth == '(A)':
|
| 113 |
+
# if choices[2] in answer:
|
| 114 |
+
# correct += 1
|
| 115 |
+
# print("yes",index)
|
| 116 |
+
# elif ground_truth == '(B)':
|
| 117 |
+
# if choices[6] in answer:
|
| 118 |
+
# correct += 1
|
| 119 |
+
# print("yes",index)
|
| 120 |
+
# elif ground_truth == '(C)':
|
| 121 |
+
# if choices[10] in answer:
|
| 122 |
+
# correct += 1
|
| 123 |
+
# print("yes",index)
|
| 124 |
+
# elif ground_truth == '(D)':
|
| 125 |
+
# if choices[14] in answer:
|
| 126 |
+
# correct += 1
|
| 127 |
+
# print("yes",index)
|
| 128 |
+
|
| 129 |
+
print("correct =", correct)
|
| 130 |
+
print("total =", total)
|
| 131 |
+
print("acc =",correct/total)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# correct = 0
|
| 136 |
+
# total = 0
|
| 137 |
+
# for index, (line1, line2) in enumerate(zip(reader1, reader2), 1):
|
| 138 |
+
# total += 1
|
| 139 |
+
# answer = line2.strip()
|
| 140 |
+
# ground_truth = json.loads(line1.strip())['answer'].strip(".")[0]
|
| 141 |
+
# length = len(ground_truth)
|
| 142 |
+
# flag = False
|
| 143 |
+
# import pdb;pdb.set_trace()
|
| 144 |
+
# if length == 1 and ground_truth.isalpha():
|
| 145 |
+
# flag = True
|
| 146 |
+
# answer = answer.split(".")[0]
|
| 147 |
+
# elif length == 2 or length == 3:
|
| 148 |
+
# flag = True
|
| 149 |
+
# answer = answer.split(",")[0]
|
| 150 |
+
|
| 151 |
+
# if flag:
|
| 152 |
+
# if answer.lower() == ground_truth.lower():
|
| 153 |
+
# correct += 1
|
| 154 |
+
# else:
|
| 155 |
+
# print("->", index)
|
| 156 |
+
# print("correct =", correct)
|
| 157 |
+
# print("total =", total)
|
blink_check.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
# 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:
|
| 5 |
+
# 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:
|
| 6 |
+
# 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:
|
| 7 |
+
# 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:
|
| 8 |
+
# 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:
|
| 9 |
+
# 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:
|
| 10 |
+
# 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:
|
| 11 |
+
# 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:
|
| 12 |
+
# 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:
|
| 13 |
+
# 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:
|
| 14 |
+
|
| 15 |
+
# 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:
|
| 16 |
+
|
| 17 |
+
# 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:
|
| 18 |
+
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:
|
| 19 |
+
# 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:
|
| 20 |
+
# 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:
|
| 21 |
+
# 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:
|
| 22 |
+
# 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:
|
| 23 |
+
# 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:
|
| 24 |
+
# 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:
|
| 25 |
+
# 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:
|
| 26 |
+
# 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:
|
| 27 |
+
# 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:
|
| 28 |
+
|
| 29 |
+
# reader1 = json.load(reader1)
|
| 30 |
+
|
| 31 |
+
correct = 0
|
| 32 |
+
total = 0
|
| 33 |
+
for index, (line1, line2) in enumerate(zip(reader1, reader2), 1):
|
| 34 |
+
total += 1
|
| 35 |
+
|
| 36 |
+
answer = line2.strip()
|
| 37 |
+
# ground_truth = line1['answer']
|
| 38 |
+
ground_truth = json.loads(line1.strip())['answer']
|
| 39 |
+
# length = len(ground_truth)
|
| 40 |
+
flag = False
|
| 41 |
+
# choices = json.loads(line1.strip())['choices']
|
| 42 |
+
|
| 43 |
+
# if ground_truth in answer:
|
| 44 |
+
# correct += 1
|
| 45 |
+
# import pdb;pdb.set_trace()
|
| 46 |
+
# if ('A' in answer) and ('B' in answer) and ('C' in answer) and ('D' in answer):
|
| 47 |
+
# print('missed',index)
|
| 48 |
+
# continue
|
| 49 |
+
# if ground_truth == '(A)':
|
| 50 |
+
# if 'left' in answer:
|
| 51 |
+
# correct += 1
|
| 52 |
+
# print("yes",index)
|
| 53 |
+
# elif ground_truth == '(B)':
|
| 54 |
+
# if 'right' in answer:
|
| 55 |
+
# correct += 1
|
| 56 |
+
# print("yes",index)
|
| 57 |
+
# if ground_truth == '(A)':
|
| 58 |
+
# if 'second' in answer:
|
| 59 |
+
# correct += 1
|
| 60 |
+
# print("yes",index)
|
| 61 |
+
# elif ground_truth == '(B)':
|
| 62 |
+
# if 'third' in answer:
|
| 63 |
+
# correct += 1
|
| 64 |
+
# print("yes",index)
|
| 65 |
+
# count_sed = answer.count('sed')
|
| 66 |
+
# count_tird = answer.count('tird')
|
| 67 |
+
|
| 68 |
+
# if ground_truth == answer:
|
| 69 |
+
# correct += 1
|
| 70 |
+
# print("yes",index)
|
| 71 |
+
if ground_truth == 0:
|
| 72 |
+
if ('A' in answer) :
|
| 73 |
+
correct += 1
|
| 74 |
+
print("yes",index)
|
| 75 |
+
else:
|
| 76 |
+
fail+=1
|
| 77 |
+
elif ground_truth == 1:
|
| 78 |
+
if ('B' in answer) :
|
| 79 |
+
correct += 1
|
| 80 |
+
print("yes",index)
|
| 81 |
+
else:
|
| 82 |
+
fail+=1
|
| 83 |
+
|
| 84 |
+
elif ground_truth == 2:
|
| 85 |
+
if ('C' in answer) :
|
| 86 |
+
correct += 1
|
| 87 |
+
print("yes",index)
|
| 88 |
+
else:
|
| 89 |
+
fail+=1
|
| 90 |
+
|
| 91 |
+
elif ground_truth == 3:
|
| 92 |
+
if ('D' in answer) :
|
| 93 |
+
correct += 1
|
| 94 |
+
print("yes",index)
|
| 95 |
+
else:
|
| 96 |
+
fail+=1
|
| 97 |
+
# if ground_truth == '(A)':
|
| 98 |
+
# if 'A' in answer :
|
| 99 |
+
# correct += 1
|
| 100 |
+
# print("yes",index)
|
| 101 |
+
# elif ground_truth == '(B)':
|
| 102 |
+
# if 'B' in answer:
|
| 103 |
+
# correct += 1
|
| 104 |
+
# print("yes",index)
|
| 105 |
+
# elif ground_truth == '(C)':
|
| 106 |
+
# if 'C' in answer:
|
| 107 |
+
# correct += 1
|
| 108 |
+
# print("yes",index)
|
| 109 |
+
# elif ground_truth == '(D)':
|
| 110 |
+
# if 'D' in answer:
|
| 111 |
+
# correct += 1
|
| 112 |
+
# print("yes",index)
|
| 113 |
+
# if ground_truth == '(A)':
|
| 114 |
+
# if choices[2] in answer:
|
| 115 |
+
# correct += 1
|
| 116 |
+
# print("yes",index)
|
| 117 |
+
# elif ground_truth == '(B)':
|
| 118 |
+
# if choices[6] in answer:
|
| 119 |
+
# correct += 1
|
| 120 |
+
# print("yes",index)
|
| 121 |
+
# elif ground_truth == '(C)':
|
| 122 |
+
# if choices[10] in answer:
|
| 123 |
+
# correct += 1
|
| 124 |
+
# print("yes",index)
|
| 125 |
+
# elif ground_truth == '(D)':
|
| 126 |
+
# if choices[14] in answer:
|
| 127 |
+
# correct += 1
|
| 128 |
+
# print("yes",index)
|
| 129 |
+
|
| 130 |
+
print("correct =", correct)
|
| 131 |
+
print("total =", total)
|
| 132 |
+
print("acc =",correct/total)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# correct = 0
|
| 137 |
+
# total = 0
|
| 138 |
+
# for index, (line1, line2) in enumerate(zip(reader1, reader2), 1):
|
| 139 |
+
# total += 1
|
| 140 |
+
# answer = line2.strip()
|
| 141 |
+
# ground_truth = json.loads(line1.strip())['answer'].strip(".")[0]
|
| 142 |
+
# length = len(ground_truth)
|
| 143 |
+
# flag = False
|
| 144 |
+
# import pdb;pdb.set_trace()
|
| 145 |
+
# if length == 1 and ground_truth.isalpha():
|
| 146 |
+
# flag = True
|
| 147 |
+
# answer = answer.split(".")[0]
|
| 148 |
+
# elif length == 2 or length == 3:
|
| 149 |
+
# flag = True
|
| 150 |
+
# answer = answer.split(",")[0]
|
| 151 |
+
|
| 152 |
+
# if flag:
|
| 153 |
+
# if answer.lower() == ground_truth.lower():
|
| 154 |
+
# correct += 1
|
| 155 |
+
# else:
|
| 156 |
+
# print("->", index)
|
| 157 |
+
# print("correct =", correct)
|
| 158 |
+
# print("total =", total)
|
check.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
# 加载模型参数
|
| 4 |
+
model_path = '/home/aiops/wangzh/zss/AlphaCLIP/train/final-negative-large-wiseconv/ckpt/iter_10000.pth' # 你的模型路径
|
| 5 |
+
checkpoint = torch.load(model_path)
|
| 6 |
+
|
| 7 |
+
# 输出 checkpoint 内容
|
| 8 |
+
# print("Checkpoint content:", checkpoint)
|
| 9 |
+
import pdb;pdb.set_trace()
|
| 10 |
+
# 如果 checkpoint 是一个包含模型参数的字典(例如state_dict)
|
| 11 |
+
if isinstance(checkpoint, dict):
|
| 12 |
+
for key, value in checkpoint.items():
|
| 13 |
+
print(f"{key}: {value.shape}")
|
| 14 |
+
if 'cpe' in key:
|
| 15 |
+
print(value)
|
| 16 |
+
else:
|
| 17 |
+
print("The checkpoint does not contain a dictionary with parameters.")
|
cog.yaml
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Configuration for Cog ⚙️
|
| 2 |
+
# Reference: https://github.com/replicate/cog/blob/main/docs/yaml.md
|
| 3 |
+
|
| 4 |
+
build:
|
| 5 |
+
gpu: true
|
| 6 |
+
|
| 7 |
+
python_version: "3.11"
|
| 8 |
+
|
| 9 |
+
python_packages:
|
| 10 |
+
- "torch==2.0.1"
|
| 11 |
+
- "accelerate==0.21.0"
|
| 12 |
+
- "bitsandbytes==0.41.0"
|
| 13 |
+
- "deepspeed==0.9.5"
|
| 14 |
+
- "einops-exts==0.0.4"
|
| 15 |
+
- "einops==0.6.1"
|
| 16 |
+
- "gradio==3.35.2"
|
| 17 |
+
- "gradio_client==0.2.9"
|
| 18 |
+
- "httpx==0.24.0"
|
| 19 |
+
- "markdown2==2.4.10"
|
| 20 |
+
- "numpy==1.26.0"
|
| 21 |
+
- "peft==0.4.0"
|
| 22 |
+
- "scikit-learn==1.2.2"
|
| 23 |
+
- "sentencepiece==0.1.99"
|
| 24 |
+
- "shortuuid==1.0.11"
|
| 25 |
+
- "timm==0.6.13"
|
| 26 |
+
- "tokenizers==0.13.3"
|
| 27 |
+
- "torch==2.0.1"
|
| 28 |
+
- "torchvision==0.15.2"
|
| 29 |
+
- "transformers==4.31.0"
|
| 30 |
+
- "wandb==0.15.12"
|
| 31 |
+
- "wavedrom==2.0.3.post3"
|
| 32 |
+
- "Pygments==2.16.1"
|
| 33 |
+
run:
|
| 34 |
+
- curl -o /usr/local/bin/pget -L "https://github.com/replicate/pget/releases/download/v0.0.3/pget" && chmod +x /usr/local/bin/pget
|
| 35 |
+
|
| 36 |
+
# predict.py defines how predictions are run on your model
|
| 37 |
+
predict: "predict.py:Predictor"
|
cv_check.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
# 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:
|
| 5 |
+
# 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:
|
| 6 |
+
# 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:
|
| 7 |
+
# 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:
|
| 8 |
+
# 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:
|
| 9 |
+
# 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:
|
| 10 |
+
# 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:
|
| 11 |
+
# 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:
|
| 12 |
+
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:
|
| 13 |
+
# 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:
|
| 14 |
+
|
| 15 |
+
#
|
| 16 |
+
# 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:
|
| 17 |
+
# 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:
|
| 18 |
+
# 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:
|
| 19 |
+
# 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:
|
| 20 |
+
# 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:
|
| 21 |
+
# 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:
|
| 22 |
+
|
| 23 |
+
# 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:
|
| 24 |
+
# 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:
|
| 25 |
+
# 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:
|
| 26 |
+
# 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:
|
| 27 |
+
# 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:
|
| 28 |
+
# 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:
|
| 29 |
+
# 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:
|
| 30 |
+
# 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:
|
| 31 |
+
# 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:
|
| 32 |
+
|
| 33 |
+
# reader1 = json.load(reader1)
|
| 34 |
+
|
| 35 |
+
correct = 0
|
| 36 |
+
total = 0
|
| 37 |
+
for index, (line1, line2) in enumerate(zip(reader1, reader2), 1):
|
| 38 |
+
total += 1
|
| 39 |
+
|
| 40 |
+
answer = line2.strip()
|
| 41 |
+
# ground_truth = line1['answer']
|
| 42 |
+
ground_truth = json.loads(line1.strip())['answer']
|
| 43 |
+
# length = len(ground_truth)
|
| 44 |
+
flag = False
|
| 45 |
+
# choices = json.loads(line1.strip())['choices']
|
| 46 |
+
|
| 47 |
+
# if ground_truth in answer:
|
| 48 |
+
# correct += 1
|
| 49 |
+
# import pdb;pdb.set_trace()
|
| 50 |
+
# if ('A' in answer) and ('B' in answer) and ('C' in answer) and ('D' in answer):
|
| 51 |
+
# print('missed',index)
|
| 52 |
+
# continue
|
| 53 |
+
# if ground_truth == '(A)':
|
| 54 |
+
# if 'left' in answer:
|
| 55 |
+
# correct += 1
|
| 56 |
+
# print("yes",index)
|
| 57 |
+
# elif ground_truth == '(B)':
|
| 58 |
+
# if 'right' in answer:
|
| 59 |
+
# correct += 1
|
| 60 |
+
# print("yes",index)
|
| 61 |
+
# if ground_truth == '(A)':
|
| 62 |
+
# if 'second' in answer:
|
| 63 |
+
# correct += 1
|
| 64 |
+
# print("yes",index)
|
| 65 |
+
# elif ground_truth == '(B)':
|
| 66 |
+
# if 'third' in answer:
|
| 67 |
+
# correct += 1
|
| 68 |
+
# print("yes",index)
|
| 69 |
+
# count_sed = answer.count('sed')
|
| 70 |
+
# count_tird = answer.count('tird')
|
| 71 |
+
# if ground_truth == 0:
|
| 72 |
+
# if ('A' in answer) :
|
| 73 |
+
# correct += 1
|
| 74 |
+
# print("yes",index)
|
| 75 |
+
|
| 76 |
+
# elif ground_truth == 1:
|
| 77 |
+
# if ('B' in answer) :
|
| 78 |
+
# correct += 1
|
| 79 |
+
# print("yes",index)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# elif ground_truth == 2:
|
| 83 |
+
# if ('C' in answer) :
|
| 84 |
+
# correct += 1
|
| 85 |
+
# print("yes",index)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# elif ground_truth == 3:
|
| 89 |
+
# if ('D' in answer) :
|
| 90 |
+
# correct += 1
|
| 91 |
+
# print("yes",index)
|
| 92 |
+
# if ground_truth == answer:
|
| 93 |
+
# correct += 1
|
| 94 |
+
# print("yes",index)
|
| 95 |
+
|
| 96 |
+
if ground_truth == '(A)':
|
| 97 |
+
if 'A' in answer :
|
| 98 |
+
correct += 1
|
| 99 |
+
print("yes",index)
|
| 100 |
+
elif ground_truth == '(B)':
|
| 101 |
+
if 'B' in answer:
|
| 102 |
+
correct += 1
|
| 103 |
+
print("yes",index)
|
| 104 |
+
elif ground_truth == '(C)':
|
| 105 |
+
if 'C' in answer:
|
| 106 |
+
correct += 1
|
| 107 |
+
print("yes",index)
|
| 108 |
+
elif ground_truth == '(D)':
|
| 109 |
+
if 'D' in answer:
|
| 110 |
+
correct += 1
|
| 111 |
+
print("yes",index)
|
| 112 |
+
# if ground_truth == '(A)':
|
| 113 |
+
# if choices[2] in answer:
|
| 114 |
+
# correct += 1
|
| 115 |
+
# print("yes",index)
|
| 116 |
+
# elif ground_truth == '(B)':
|
| 117 |
+
# if choices[6] in answer:
|
| 118 |
+
# correct += 1
|
| 119 |
+
# print("yes",index)
|
| 120 |
+
# elif ground_truth == '(C)':
|
| 121 |
+
# if choices[10] in answer:
|
| 122 |
+
# correct += 1
|
| 123 |
+
# print("yes",index)
|
| 124 |
+
# elif ground_truth == '(D)':
|
| 125 |
+
# if choices[14] in answer:
|
| 126 |
+
# correct += 1
|
| 127 |
+
# print("yes",index)
|
| 128 |
+
|
| 129 |
+
print("correct =", correct)
|
| 130 |
+
print("total =", total)
|
| 131 |
+
print("acc =",correct/total)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# correct = 0
|
| 136 |
+
# total = 0
|
| 137 |
+
# for index, (line1, line2) in enumerate(zip(reader1, reader2), 1):
|
| 138 |
+
# total += 1
|
| 139 |
+
# answer = line2.strip()
|
| 140 |
+
# ground_truth = json.loads(line1.strip())['answer'].strip(".")[0]
|
| 141 |
+
# length = len(ground_truth)
|
| 142 |
+
# flag = False
|
| 143 |
+
# import pdb;pdb.set_trace()
|
| 144 |
+
# if length == 1 and ground_truth.isalpha():
|
| 145 |
+
# flag = True
|
| 146 |
+
# answer = answer.split(".")[0]
|
| 147 |
+
# elif length == 2 or length == 3:
|
| 148 |
+
# flag = True
|
| 149 |
+
# answer = answer.split(",")[0]
|
| 150 |
+
|
| 151 |
+
# if flag:
|
| 152 |
+
# if answer.lower() == ground_truth.lower():
|
| 153 |
+
# correct += 1
|
| 154 |
+
# else:
|
| 155 |
+
# print("->", index)
|
| 156 |
+
# print("correct =", correct)
|
| 157 |
+
# print("total =", total)
|
depth_anything_v2/dinov2.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the Apache License, Version 2.0
|
| 4 |
+
# found in the LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
# References:
|
| 7 |
+
# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
|
| 8 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
|
| 9 |
+
|
| 10 |
+
from functools import partial
|
| 11 |
+
import math
|
| 12 |
+
import logging
|
| 13 |
+
from typing import Sequence, Tuple, Union, Callable
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
import torch.utils.checkpoint
|
| 18 |
+
from torch.nn.init import trunc_normal_
|
| 19 |
+
|
| 20 |
+
from .dinov2_layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.getLogger("dinov2")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module:
|
| 27 |
+
if not depth_first and include_root:
|
| 28 |
+
fn(module=module, name=name)
|
| 29 |
+
for child_name, child_module in module.named_children():
|
| 30 |
+
child_name = ".".join((name, child_name)) if name else child_name
|
| 31 |
+
named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True)
|
| 32 |
+
if depth_first and include_root:
|
| 33 |
+
fn(module=module, name=name)
|
| 34 |
+
return module
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class BlockChunk(nn.ModuleList):
|
| 38 |
+
def forward(self, x):
|
| 39 |
+
for b in self:
|
| 40 |
+
x = b(x)
|
| 41 |
+
return x
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class DinoVisionTransformer(nn.Module):
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
img_size=224,
|
| 48 |
+
patch_size=16,
|
| 49 |
+
in_chans=3,
|
| 50 |
+
embed_dim=768,
|
| 51 |
+
depth=12,
|
| 52 |
+
num_heads=12,
|
| 53 |
+
mlp_ratio=4.0,
|
| 54 |
+
qkv_bias=True,
|
| 55 |
+
ffn_bias=True,
|
| 56 |
+
proj_bias=True,
|
| 57 |
+
drop_path_rate=0.0,
|
| 58 |
+
drop_path_uniform=False,
|
| 59 |
+
init_values=None, # for layerscale: None or 0 => no layerscale
|
| 60 |
+
embed_layer=PatchEmbed,
|
| 61 |
+
act_layer=nn.GELU,
|
| 62 |
+
block_fn=Block,
|
| 63 |
+
ffn_layer="mlp",
|
| 64 |
+
block_chunks=1,
|
| 65 |
+
num_register_tokens=0,
|
| 66 |
+
interpolate_antialias=False,
|
| 67 |
+
interpolate_offset=0.1,
|
| 68 |
+
):
|
| 69 |
+
"""
|
| 70 |
+
Args:
|
| 71 |
+
img_size (int, tuple): input image size
|
| 72 |
+
patch_size (int, tuple): patch size
|
| 73 |
+
in_chans (int): number of input channels
|
| 74 |
+
embed_dim (int): embedding dimension
|
| 75 |
+
depth (int): depth of transformer
|
| 76 |
+
num_heads (int): number of attention heads
|
| 77 |
+
mlp_ratio (int): ratio of mlp hidden dim to embedding dim
|
| 78 |
+
qkv_bias (bool): enable bias for qkv if True
|
| 79 |
+
proj_bias (bool): enable bias for proj in attn if True
|
| 80 |
+
ffn_bias (bool): enable bias for ffn if True
|
| 81 |
+
drop_path_rate (float): stochastic depth rate
|
| 82 |
+
drop_path_uniform (bool): apply uniform drop rate across blocks
|
| 83 |
+
weight_init (str): weight init scheme
|
| 84 |
+
init_values (float): layer-scale init values
|
| 85 |
+
embed_layer (nn.Module): patch embedding layer
|
| 86 |
+
act_layer (nn.Module): MLP activation layer
|
| 87 |
+
block_fn (nn.Module): transformer block class
|
| 88 |
+
ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"
|
| 89 |
+
block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
|
| 90 |
+
num_register_tokens: (int) number of extra cls tokens (so-called "registers")
|
| 91 |
+
interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings
|
| 92 |
+
interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings
|
| 93 |
+
"""
|
| 94 |
+
super().__init__()
|
| 95 |
+
norm_layer = partial(nn.LayerNorm, eps=1e-6)
|
| 96 |
+
|
| 97 |
+
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
|
| 98 |
+
self.num_tokens = 1
|
| 99 |
+
self.n_blocks = depth
|
| 100 |
+
self.num_heads = num_heads
|
| 101 |
+
self.patch_size = patch_size
|
| 102 |
+
self.num_register_tokens = num_register_tokens
|
| 103 |
+
self.interpolate_antialias = interpolate_antialias
|
| 104 |
+
self.interpolate_offset = interpolate_offset
|
| 105 |
+
|
| 106 |
+
self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
|
| 107 |
+
num_patches = self.patch_embed.num_patches
|
| 108 |
+
|
| 109 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
| 110 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
|
| 111 |
+
assert num_register_tokens >= 0
|
| 112 |
+
self.register_tokens = (
|
| 113 |
+
nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if drop_path_uniform is True:
|
| 117 |
+
dpr = [drop_path_rate] * depth
|
| 118 |
+
else:
|
| 119 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
|
| 120 |
+
|
| 121 |
+
if ffn_layer == "mlp":
|
| 122 |
+
logger.info("using MLP layer as FFN")
|
| 123 |
+
ffn_layer = Mlp
|
| 124 |
+
elif ffn_layer == "swiglufused" or ffn_layer == "swiglu":
|
| 125 |
+
logger.info("using SwiGLU layer as FFN")
|
| 126 |
+
ffn_layer = SwiGLUFFNFused
|
| 127 |
+
elif ffn_layer == "identity":
|
| 128 |
+
logger.info("using Identity layer as FFN")
|
| 129 |
+
|
| 130 |
+
def f(*args, **kwargs):
|
| 131 |
+
return nn.Identity()
|
| 132 |
+
|
| 133 |
+
ffn_layer = f
|
| 134 |
+
else:
|
| 135 |
+
raise NotImplementedError
|
| 136 |
+
|
| 137 |
+
blocks_list = [
|
| 138 |
+
block_fn(
|
| 139 |
+
dim=embed_dim,
|
| 140 |
+
num_heads=num_heads,
|
| 141 |
+
mlp_ratio=mlp_ratio,
|
| 142 |
+
qkv_bias=qkv_bias,
|
| 143 |
+
proj_bias=proj_bias,
|
| 144 |
+
ffn_bias=ffn_bias,
|
| 145 |
+
drop_path=dpr[i],
|
| 146 |
+
norm_layer=norm_layer,
|
| 147 |
+
act_layer=act_layer,
|
| 148 |
+
ffn_layer=ffn_layer,
|
| 149 |
+
init_values=init_values,
|
| 150 |
+
)
|
| 151 |
+
for i in range(depth)
|
| 152 |
+
]
|
| 153 |
+
if block_chunks > 0:
|
| 154 |
+
self.chunked_blocks = True
|
| 155 |
+
chunked_blocks = []
|
| 156 |
+
chunksize = depth // block_chunks
|
| 157 |
+
for i in range(0, depth, chunksize):
|
| 158 |
+
# this is to keep the block index consistent if we chunk the block list
|
| 159 |
+
chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize])
|
| 160 |
+
self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks])
|
| 161 |
+
else:
|
| 162 |
+
self.chunked_blocks = False
|
| 163 |
+
self.blocks = nn.ModuleList(blocks_list)
|
| 164 |
+
|
| 165 |
+
self.norm = norm_layer(embed_dim)
|
| 166 |
+
self.head = nn.Identity()
|
| 167 |
+
|
| 168 |
+
self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
|
| 169 |
+
|
| 170 |
+
self.init_weights()
|
| 171 |
+
|
| 172 |
+
def init_weights(self):
|
| 173 |
+
trunc_normal_(self.pos_embed, std=0.02)
|
| 174 |
+
nn.init.normal_(self.cls_token, std=1e-6)
|
| 175 |
+
if self.register_tokens is not None:
|
| 176 |
+
nn.init.normal_(self.register_tokens, std=1e-6)
|
| 177 |
+
named_apply(init_weights_vit_timm, self)
|
| 178 |
+
|
| 179 |
+
def interpolate_pos_encoding(self, x, w, h):
|
| 180 |
+
previous_dtype = x.dtype
|
| 181 |
+
npatch = x.shape[1] - 1
|
| 182 |
+
N = self.pos_embed.shape[1] - 1
|
| 183 |
+
if npatch == N and w == h:
|
| 184 |
+
return self.pos_embed
|
| 185 |
+
pos_embed = self.pos_embed.float()
|
| 186 |
+
class_pos_embed = pos_embed[:, 0]
|
| 187 |
+
patch_pos_embed = pos_embed[:, 1:]
|
| 188 |
+
dim = x.shape[-1]
|
| 189 |
+
w0 = w // self.patch_size
|
| 190 |
+
h0 = h // self.patch_size
|
| 191 |
+
# we add a small number to avoid floating point error in the interpolation
|
| 192 |
+
# see discussion at https://github.com/facebookresearch/dino/issues/8
|
| 193 |
+
# DINOv2 with register modify the interpolate_offset from 0.1 to 0.0
|
| 194 |
+
w0, h0 = w0 + self.interpolate_offset, h0 + self.interpolate_offset
|
| 195 |
+
# w0, h0 = w0 + 0.1, h0 + 0.1
|
| 196 |
+
|
| 197 |
+
sqrt_N = math.sqrt(N)
|
| 198 |
+
sx, sy = float(w0) / sqrt_N, float(h0) / sqrt_N
|
| 199 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 200 |
+
patch_pos_embed.reshape(1, int(sqrt_N), int(sqrt_N), dim).permute(0, 3, 1, 2),
|
| 201 |
+
scale_factor=(sx, sy),
|
| 202 |
+
# (int(w0), int(h0)), # to solve the upsampling shape issue
|
| 203 |
+
mode="bicubic",
|
| 204 |
+
antialias=self.interpolate_antialias
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
assert int(w0) == patch_pos_embed.shape[-2]
|
| 208 |
+
assert int(h0) == patch_pos_embed.shape[-1]
|
| 209 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 210 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
|
| 211 |
+
|
| 212 |
+
def prepare_tokens_with_masks(self, x, masks=None):
|
| 213 |
+
B, nc, w, h = x.shape
|
| 214 |
+
# import pdb;pdb.set_trace()
|
| 215 |
+
x = self.patch_embed(x)
|
| 216 |
+
if masks is not None:
|
| 217 |
+
x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
|
| 218 |
+
|
| 219 |
+
x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)
|
| 220 |
+
x = x + self.interpolate_pos_encoding(x, w, h)
|
| 221 |
+
|
| 222 |
+
if self.register_tokens is not None:
|
| 223 |
+
x = torch.cat(
|
| 224 |
+
(
|
| 225 |
+
x[:, :1],
|
| 226 |
+
self.register_tokens.expand(x.shape[0], -1, -1),
|
| 227 |
+
x[:, 1:],
|
| 228 |
+
),
|
| 229 |
+
dim=1,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
return x
|
| 233 |
+
|
| 234 |
+
def forward_features_list(self, x_list, masks_list):
|
| 235 |
+
x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]
|
| 236 |
+
for blk in self.blocks:
|
| 237 |
+
x = blk(x)
|
| 238 |
+
|
| 239 |
+
all_x = x
|
| 240 |
+
output = []
|
| 241 |
+
for x, masks in zip(all_x, masks_list):
|
| 242 |
+
x_norm = self.norm(x)
|
| 243 |
+
output.append(
|
| 244 |
+
{
|
| 245 |
+
"x_norm_clstoken": x_norm[:, 0],
|
| 246 |
+
"x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
|
| 247 |
+
"x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
|
| 248 |
+
"x_prenorm": x,
|
| 249 |
+
"masks": masks,
|
| 250 |
+
}
|
| 251 |
+
)
|
| 252 |
+
return output
|
| 253 |
+
|
| 254 |
+
def forward_features(self, x, masks=None):
|
| 255 |
+
if isinstance(x, list):
|
| 256 |
+
return self.forward_features_list(x, masks)
|
| 257 |
+
|
| 258 |
+
x = self.prepare_tokens_with_masks(x, masks)
|
| 259 |
+
|
| 260 |
+
for blk in self.blocks:
|
| 261 |
+
x = blk(x)
|
| 262 |
+
|
| 263 |
+
x_norm = self.norm(x)
|
| 264 |
+
return {
|
| 265 |
+
"x_norm_clstoken": x_norm[:, 0],
|
| 266 |
+
"x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
|
| 267 |
+
"x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
|
| 268 |
+
"x_prenorm": x,
|
| 269 |
+
"masks": masks,
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
def _get_intermediate_layers_not_chunked(self, x, n=1):
|
| 273 |
+
x = self.prepare_tokens_with_masks(x)
|
| 274 |
+
# If n is an int, take the n last blocks. If it's a list, take them
|
| 275 |
+
output, total_block_len = [], len(self.blocks)
|
| 276 |
+
blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
|
| 277 |
+
for i, blk in enumerate(self.blocks):
|
| 278 |
+
x = blk(x)
|
| 279 |
+
if i in blocks_to_take:
|
| 280 |
+
output.append(x)
|
| 281 |
+
assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
|
| 282 |
+
return output
|
| 283 |
+
|
| 284 |
+
def _get_intermediate_layers_chunked(self, x, n=1):
|
| 285 |
+
x = self.prepare_tokens_with_masks(x)
|
| 286 |
+
output, i, total_block_len = [], 0, len(self.blocks[-1])
|
| 287 |
+
# If n is an int, take the n last blocks. If it's a list, take them
|
| 288 |
+
blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
|
| 289 |
+
for block_chunk in self.blocks:
|
| 290 |
+
for blk in block_chunk[i:]: # Passing the nn.Identity()
|
| 291 |
+
x = blk(x)
|
| 292 |
+
if i in blocks_to_take:
|
| 293 |
+
output.append(x)
|
| 294 |
+
i += 1
|
| 295 |
+
assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
|
| 296 |
+
return output
|
| 297 |
+
|
| 298 |
+
def get_intermediate_layers(
|
| 299 |
+
self,
|
| 300 |
+
x: torch.Tensor,
|
| 301 |
+
n: Union[int, Sequence] = 1, # Layers or n last layers to take
|
| 302 |
+
reshape: bool = False,
|
| 303 |
+
return_class_token: bool = False,
|
| 304 |
+
norm=True
|
| 305 |
+
) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
|
| 306 |
+
if self.chunked_blocks:
|
| 307 |
+
outputs = self._get_intermediate_layers_chunked(x, n)
|
| 308 |
+
else:
|
| 309 |
+
outputs = self._get_intermediate_layers_not_chunked(x, n)
|
| 310 |
+
if norm:
|
| 311 |
+
outputs = [self.norm(out) for out in outputs]
|
| 312 |
+
class_tokens = [out[:, 0] for out in outputs]
|
| 313 |
+
outputs = [out[:, 1 + self.num_register_tokens:] for out in outputs]
|
| 314 |
+
if reshape:
|
| 315 |
+
B, _, w, h = x.shape
|
| 316 |
+
outputs = [
|
| 317 |
+
out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous()
|
| 318 |
+
for out in outputs
|
| 319 |
+
]
|
| 320 |
+
if return_class_token:
|
| 321 |
+
return tuple(zip(outputs, class_tokens))
|
| 322 |
+
return tuple(outputs)
|
| 323 |
+
|
| 324 |
+
def forward(self, *args, is_training=False, **kwargs):
|
| 325 |
+
ret = self.forward_features(*args, **kwargs)
|
| 326 |
+
if is_training:
|
| 327 |
+
return ret
|
| 328 |
+
else:
|
| 329 |
+
return self.head(ret["x_norm_clstoken"])
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def init_weights_vit_timm(module: nn.Module, name: str = ""):
|
| 333 |
+
"""ViT weight initialization, original timm impl (for reproducibility)"""
|
| 334 |
+
if isinstance(module, nn.Linear):
|
| 335 |
+
trunc_normal_(module.weight, std=0.02)
|
| 336 |
+
if module.bias is not None:
|
| 337 |
+
nn.init.zeros_(module.bias)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def vit_small(patch_size=16, num_register_tokens=0, **kwargs):
|
| 341 |
+
model = DinoVisionTransformer(
|
| 342 |
+
patch_size=patch_size,
|
| 343 |
+
embed_dim=384,
|
| 344 |
+
depth=12,
|
| 345 |
+
num_heads=6,
|
| 346 |
+
mlp_ratio=4,
|
| 347 |
+
block_fn=partial(Block, attn_class=MemEffAttention),
|
| 348 |
+
num_register_tokens=num_register_tokens,
|
| 349 |
+
**kwargs,
|
| 350 |
+
)
|
| 351 |
+
return model
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def vit_base(patch_size=16, num_register_tokens=0, **kwargs):
|
| 355 |
+
model = DinoVisionTransformer(
|
| 356 |
+
patch_size=patch_size,
|
| 357 |
+
embed_dim=768,
|
| 358 |
+
depth=12,
|
| 359 |
+
num_heads=12,
|
| 360 |
+
mlp_ratio=4,
|
| 361 |
+
block_fn=partial(Block, attn_class=MemEffAttention),
|
| 362 |
+
num_register_tokens=num_register_tokens,
|
| 363 |
+
**kwargs,
|
| 364 |
+
)
|
| 365 |
+
return model
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def vit_large(patch_size=16, num_register_tokens=0, **kwargs):
|
| 369 |
+
model = DinoVisionTransformer(
|
| 370 |
+
patch_size=patch_size,
|
| 371 |
+
embed_dim=1024,
|
| 372 |
+
depth=24,
|
| 373 |
+
num_heads=16,
|
| 374 |
+
mlp_ratio=4,
|
| 375 |
+
block_fn=partial(Block, attn_class=MemEffAttention),
|
| 376 |
+
num_register_tokens=num_register_tokens,
|
| 377 |
+
**kwargs,
|
| 378 |
+
)
|
| 379 |
+
return model
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs):
|
| 383 |
+
"""
|
| 384 |
+
Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
|
| 385 |
+
"""
|
| 386 |
+
model = DinoVisionTransformer(
|
| 387 |
+
patch_size=patch_size,
|
| 388 |
+
embed_dim=1536,
|
| 389 |
+
depth=40,
|
| 390 |
+
num_heads=24,
|
| 391 |
+
mlp_ratio=4,
|
| 392 |
+
block_fn=partial(Block, attn_class=MemEffAttention),
|
| 393 |
+
num_register_tokens=num_register_tokens,
|
| 394 |
+
**kwargs,
|
| 395 |
+
)
|
| 396 |
+
return model
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def DINOv2(model_name):
|
| 400 |
+
model_zoo = {
|
| 401 |
+
"vits": vit_small,
|
| 402 |
+
"vitb": vit_base,
|
| 403 |
+
"vitl": vit_large,
|
| 404 |
+
"vitg": vit_giant2
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
return model_zoo[model_name](
|
| 408 |
+
img_size=518,
|
| 409 |
+
patch_size=14,
|
| 410 |
+
init_values=1.0,
|
| 411 |
+
ffn_layer="mlp" if model_name != "vitg" else "swiglufused",
|
| 412 |
+
block_chunks=0,
|
| 413 |
+
num_register_tokens=0,
|
| 414 |
+
interpolate_antialias=False,
|
| 415 |
+
interpolate_offset=0.1
|
| 416 |
+
)
|
depth_anything_v2/dinov2_layers/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
from .mlp import Mlp
|
| 8 |
+
from .patch_embed import PatchEmbed
|
| 9 |
+
from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused
|
| 10 |
+
from .block import NestedTensorBlock
|
| 11 |
+
from .attention import MemEffAttention
|
depth_anything_v2/dinov2_layers/attention.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# References:
|
| 8 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 9 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
|
| 10 |
+
|
| 11 |
+
import logging
|
| 12 |
+
|
| 13 |
+
from torch import Tensor
|
| 14 |
+
from torch import nn
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger("dinov2")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
from xformers.ops import memory_efficient_attention, unbind, fmha
|
| 22 |
+
|
| 23 |
+
XFORMERS_AVAILABLE = True
|
| 24 |
+
except ImportError:
|
| 25 |
+
logger.warning("xFormers not available")
|
| 26 |
+
XFORMERS_AVAILABLE = False
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Attention(nn.Module):
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
dim: int,
|
| 33 |
+
num_heads: int = 8,
|
| 34 |
+
qkv_bias: bool = False,
|
| 35 |
+
proj_bias: bool = True,
|
| 36 |
+
attn_drop: float = 0.0,
|
| 37 |
+
proj_drop: float = 0.0,
|
| 38 |
+
) -> None:
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.num_heads = num_heads
|
| 41 |
+
head_dim = dim // num_heads
|
| 42 |
+
self.scale = head_dim**-0.5
|
| 43 |
+
|
| 44 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 45 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 46 |
+
self.proj = nn.Linear(dim, dim, bias=proj_bias)
|
| 47 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 48 |
+
|
| 49 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 50 |
+
B, N, C = x.shape
|
| 51 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 52 |
+
|
| 53 |
+
q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
|
| 54 |
+
attn = q @ k.transpose(-2, -1)
|
| 55 |
+
|
| 56 |
+
attn = attn.softmax(dim=-1)
|
| 57 |
+
attn = self.attn_drop(attn)
|
| 58 |
+
|
| 59 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 60 |
+
x = self.proj(x)
|
| 61 |
+
x = self.proj_drop(x)
|
| 62 |
+
return x
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class MemEffAttention(Attention):
|
| 66 |
+
def forward(self, x: Tensor, attn_bias=None) -> Tensor:
|
| 67 |
+
if not XFORMERS_AVAILABLE:
|
| 68 |
+
assert attn_bias is None, "xFormers is required for nested tensors usage"
|
| 69 |
+
return super().forward(x)
|
| 70 |
+
|
| 71 |
+
B, N, C = x.shape
|
| 72 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
|
| 73 |
+
|
| 74 |
+
q, k, v = unbind(qkv, 2)
|
| 75 |
+
|
| 76 |
+
x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
|
| 77 |
+
x = x.reshape([B, N, C])
|
| 78 |
+
|
| 79 |
+
x = self.proj(x)
|
| 80 |
+
x = self.proj_drop(x)
|
| 81 |
+
return x
|
| 82 |
+
|
| 83 |
+
|
depth_anything_v2/dinov2_layers/block.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# References:
|
| 8 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 9 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
|
| 10 |
+
|
| 11 |
+
import logging
|
| 12 |
+
from typing import Callable, List, Any, Tuple, Dict
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
from torch import nn, Tensor
|
| 16 |
+
|
| 17 |
+
from .attention import Attention, MemEffAttention
|
| 18 |
+
from .drop_path import DropPath
|
| 19 |
+
from .layer_scale import LayerScale
|
| 20 |
+
from .mlp import Mlp
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.getLogger("dinov2")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
from xformers.ops import fmha
|
| 28 |
+
from xformers.ops import scaled_index_add, index_select_cat
|
| 29 |
+
|
| 30 |
+
XFORMERS_AVAILABLE = True
|
| 31 |
+
except ImportError:
|
| 32 |
+
logger.warning("xFormers not available")
|
| 33 |
+
XFORMERS_AVAILABLE = False
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Block(nn.Module):
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
dim: int,
|
| 40 |
+
num_heads: int,
|
| 41 |
+
mlp_ratio: float = 4.0,
|
| 42 |
+
qkv_bias: bool = False,
|
| 43 |
+
proj_bias: bool = True,
|
| 44 |
+
ffn_bias: bool = True,
|
| 45 |
+
drop: float = 0.0,
|
| 46 |
+
attn_drop: float = 0.0,
|
| 47 |
+
init_values=None,
|
| 48 |
+
drop_path: float = 0.0,
|
| 49 |
+
act_layer: Callable[..., nn.Module] = nn.GELU,
|
| 50 |
+
norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
|
| 51 |
+
attn_class: Callable[..., nn.Module] = Attention,
|
| 52 |
+
ffn_layer: Callable[..., nn.Module] = Mlp,
|
| 53 |
+
) -> None:
|
| 54 |
+
super().__init__()
|
| 55 |
+
# print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")
|
| 56 |
+
self.norm1 = norm_layer(dim)
|
| 57 |
+
self.attn = attn_class(
|
| 58 |
+
dim,
|
| 59 |
+
num_heads=num_heads,
|
| 60 |
+
qkv_bias=qkv_bias,
|
| 61 |
+
proj_bias=proj_bias,
|
| 62 |
+
attn_drop=attn_drop,
|
| 63 |
+
proj_drop=drop,
|
| 64 |
+
)
|
| 65 |
+
self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
| 66 |
+
self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 67 |
+
|
| 68 |
+
self.norm2 = norm_layer(dim)
|
| 69 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
| 70 |
+
self.mlp = ffn_layer(
|
| 71 |
+
in_features=dim,
|
| 72 |
+
hidden_features=mlp_hidden_dim,
|
| 73 |
+
act_layer=act_layer,
|
| 74 |
+
drop=drop,
|
| 75 |
+
bias=ffn_bias,
|
| 76 |
+
)
|
| 77 |
+
self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
| 78 |
+
self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 79 |
+
|
| 80 |
+
self.sample_drop_ratio = drop_path
|
| 81 |
+
|
| 82 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 83 |
+
def attn_residual_func(x: Tensor) -> Tensor:
|
| 84 |
+
return self.ls1(self.attn(self.norm1(x)))
|
| 85 |
+
|
| 86 |
+
def ffn_residual_func(x: Tensor) -> Tensor:
|
| 87 |
+
return self.ls2(self.mlp(self.norm2(x)))
|
| 88 |
+
|
| 89 |
+
if self.training and self.sample_drop_ratio > 0.1:
|
| 90 |
+
# the overhead is compensated only for a drop path rate larger than 0.1
|
| 91 |
+
x = drop_add_residual_stochastic_depth(
|
| 92 |
+
x,
|
| 93 |
+
residual_func=attn_residual_func,
|
| 94 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
| 95 |
+
)
|
| 96 |
+
x = drop_add_residual_stochastic_depth(
|
| 97 |
+
x,
|
| 98 |
+
residual_func=ffn_residual_func,
|
| 99 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
| 100 |
+
)
|
| 101 |
+
elif self.training and self.sample_drop_ratio > 0.0:
|
| 102 |
+
x = x + self.drop_path1(attn_residual_func(x))
|
| 103 |
+
x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2
|
| 104 |
+
else:
|
| 105 |
+
x = x + attn_residual_func(x)
|
| 106 |
+
x = x + ffn_residual_func(x)
|
| 107 |
+
return x
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def drop_add_residual_stochastic_depth(
|
| 111 |
+
x: Tensor,
|
| 112 |
+
residual_func: Callable[[Tensor], Tensor],
|
| 113 |
+
sample_drop_ratio: float = 0.0,
|
| 114 |
+
) -> Tensor:
|
| 115 |
+
# 1) extract subset using permutation
|
| 116 |
+
b, n, d = x.shape
|
| 117 |
+
sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
|
| 118 |
+
brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
|
| 119 |
+
x_subset = x[brange]
|
| 120 |
+
|
| 121 |
+
# 2) apply residual_func to get residual
|
| 122 |
+
residual = residual_func(x_subset)
|
| 123 |
+
|
| 124 |
+
x_flat = x.flatten(1)
|
| 125 |
+
residual = residual.flatten(1)
|
| 126 |
+
|
| 127 |
+
residual_scale_factor = b / sample_subset_size
|
| 128 |
+
|
| 129 |
+
# 3) add the residual
|
| 130 |
+
x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
|
| 131 |
+
return x_plus_residual.view_as(x)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def get_branges_scales(x, sample_drop_ratio=0.0):
|
| 135 |
+
b, n, d = x.shape
|
| 136 |
+
sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
|
| 137 |
+
brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
|
| 138 |
+
residual_scale_factor = b / sample_subset_size
|
| 139 |
+
return brange, residual_scale_factor
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None):
|
| 143 |
+
if scaling_vector is None:
|
| 144 |
+
x_flat = x.flatten(1)
|
| 145 |
+
residual = residual.flatten(1)
|
| 146 |
+
x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
|
| 147 |
+
else:
|
| 148 |
+
x_plus_residual = scaled_index_add(
|
| 149 |
+
x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor
|
| 150 |
+
)
|
| 151 |
+
return x_plus_residual
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
attn_bias_cache: Dict[Tuple, Any] = {}
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def get_attn_bias_and_cat(x_list, branges=None):
|
| 158 |
+
"""
|
| 159 |
+
this will perform the index select, cat the tensors, and provide the attn_bias from cache
|
| 160 |
+
"""
|
| 161 |
+
batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list]
|
| 162 |
+
all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list))
|
| 163 |
+
if all_shapes not in attn_bias_cache.keys():
|
| 164 |
+
seqlens = []
|
| 165 |
+
for b, x in zip(batch_sizes, x_list):
|
| 166 |
+
for _ in range(b):
|
| 167 |
+
seqlens.append(x.shape[1])
|
| 168 |
+
attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens)
|
| 169 |
+
attn_bias._batch_sizes = batch_sizes
|
| 170 |
+
attn_bias_cache[all_shapes] = attn_bias
|
| 171 |
+
|
| 172 |
+
if branges is not None:
|
| 173 |
+
cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1])
|
| 174 |
+
else:
|
| 175 |
+
tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list)
|
| 176 |
+
cat_tensors = torch.cat(tensors_bs1, dim=1)
|
| 177 |
+
|
| 178 |
+
return attn_bias_cache[all_shapes], cat_tensors
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def drop_add_residual_stochastic_depth_list(
|
| 182 |
+
x_list: List[Tensor],
|
| 183 |
+
residual_func: Callable[[Tensor, Any], Tensor],
|
| 184 |
+
sample_drop_ratio: float = 0.0,
|
| 185 |
+
scaling_vector=None,
|
| 186 |
+
) -> Tensor:
|
| 187 |
+
# 1) generate random set of indices for dropping samples in the batch
|
| 188 |
+
branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list]
|
| 189 |
+
branges = [s[0] for s in branges_scales]
|
| 190 |
+
residual_scale_factors = [s[1] for s in branges_scales]
|
| 191 |
+
|
| 192 |
+
# 2) get attention bias and index+concat the tensors
|
| 193 |
+
attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)
|
| 194 |
+
|
| 195 |
+
# 3) apply residual_func to get residual, and split the result
|
| 196 |
+
residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore
|
| 197 |
+
|
| 198 |
+
outputs = []
|
| 199 |
+
for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors):
|
| 200 |
+
outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x))
|
| 201 |
+
return outputs
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class NestedTensorBlock(Block):
|
| 205 |
+
def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]:
|
| 206 |
+
"""
|
| 207 |
+
x_list contains a list of tensors to nest together and run
|
| 208 |
+
"""
|
| 209 |
+
assert isinstance(self.attn, MemEffAttention)
|
| 210 |
+
|
| 211 |
+
if self.training and self.sample_drop_ratio > 0.0:
|
| 212 |
+
|
| 213 |
+
def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
|
| 214 |
+
return self.attn(self.norm1(x), attn_bias=attn_bias)
|
| 215 |
+
|
| 216 |
+
def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
|
| 217 |
+
return self.mlp(self.norm2(x))
|
| 218 |
+
|
| 219 |
+
x_list = drop_add_residual_stochastic_depth_list(
|
| 220 |
+
x_list,
|
| 221 |
+
residual_func=attn_residual_func,
|
| 222 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
| 223 |
+
scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None,
|
| 224 |
+
)
|
| 225 |
+
x_list = drop_add_residual_stochastic_depth_list(
|
| 226 |
+
x_list,
|
| 227 |
+
residual_func=ffn_residual_func,
|
| 228 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
| 229 |
+
scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None,
|
| 230 |
+
)
|
| 231 |
+
return x_list
|
| 232 |
+
else:
|
| 233 |
+
|
| 234 |
+
def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
|
| 235 |
+
return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))
|
| 236 |
+
|
| 237 |
+
def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
|
| 238 |
+
return self.ls2(self.mlp(self.norm2(x)))
|
| 239 |
+
|
| 240 |
+
attn_bias, x = get_attn_bias_and_cat(x_list)
|
| 241 |
+
x = x + attn_residual_func(x, attn_bias=attn_bias)
|
| 242 |
+
x = x + ffn_residual_func(x)
|
| 243 |
+
return attn_bias.split(x)
|
| 244 |
+
|
| 245 |
+
def forward(self, x_or_x_list):
|
| 246 |
+
if isinstance(x_or_x_list, Tensor):
|
| 247 |
+
return super().forward(x_or_x_list)
|
| 248 |
+
elif isinstance(x_or_x_list, list):
|
| 249 |
+
assert XFORMERS_AVAILABLE, "Please install xFormers for nested tensors usage"
|
| 250 |
+
return self.forward_nested(x_or_x_list)
|
| 251 |
+
else:
|
| 252 |
+
raise AssertionError
|
depth_anything_v2/dinov2_layers/drop_path.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# References:
|
| 8 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 9 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
from torch import nn
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def drop_path(x, drop_prob: float = 0.0, training: bool = False):
|
| 16 |
+
if drop_prob == 0.0 or not training:
|
| 17 |
+
return x
|
| 18 |
+
keep_prob = 1 - drop_prob
|
| 19 |
+
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 20 |
+
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
|
| 21 |
+
if keep_prob > 0.0:
|
| 22 |
+
random_tensor.div_(keep_prob)
|
| 23 |
+
output = x * random_tensor
|
| 24 |
+
return output
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class DropPath(nn.Module):
|
| 28 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 29 |
+
|
| 30 |
+
def __init__(self, drop_prob=None):
|
| 31 |
+
super(DropPath, self).__init__()
|
| 32 |
+
self.drop_prob = drop_prob
|
| 33 |
+
|
| 34 |
+
def forward(self, x):
|
| 35 |
+
return drop_path(x, self.drop_prob, self.training)
|
depth_anything_v2/dinov2_layers/layer_scale.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110
|
| 8 |
+
|
| 9 |
+
from typing import Union
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from torch import Tensor
|
| 13 |
+
from torch import nn
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class LayerScale(nn.Module):
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
dim: int,
|
| 20 |
+
init_values: Union[float, Tensor] = 1e-5,
|
| 21 |
+
inplace: bool = False,
|
| 22 |
+
) -> None:
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.inplace = inplace
|
| 25 |
+
self.gamma = nn.Parameter(init_values * torch.ones(dim))
|
| 26 |
+
|
| 27 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 28 |
+
return x.mul_(self.gamma) if self.inplace else x * self.gamma
|
depth_anything_v2/dinov2_layers/mlp.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# References:
|
| 8 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 9 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
from typing import Callable, Optional
|
| 13 |
+
|
| 14 |
+
from torch import Tensor, nn
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Mlp(nn.Module):
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
in_features: int,
|
| 21 |
+
hidden_features: Optional[int] = None,
|
| 22 |
+
out_features: Optional[int] = None,
|
| 23 |
+
act_layer: Callable[..., nn.Module] = nn.GELU,
|
| 24 |
+
drop: float = 0.0,
|
| 25 |
+
bias: bool = True,
|
| 26 |
+
) -> None:
|
| 27 |
+
super().__init__()
|
| 28 |
+
out_features = out_features or in_features
|
| 29 |
+
hidden_features = hidden_features or in_features
|
| 30 |
+
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
|
| 31 |
+
self.act = act_layer()
|
| 32 |
+
self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
|
| 33 |
+
self.drop = nn.Dropout(drop)
|
| 34 |
+
|
| 35 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 36 |
+
x = self.fc1(x)
|
| 37 |
+
x = self.act(x)
|
| 38 |
+
x = self.drop(x)
|
| 39 |
+
x = self.fc2(x)
|
| 40 |
+
x = self.drop(x)
|
| 41 |
+
return x
|
depth_anything_v2/dinov2_layers/patch_embed.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# References:
|
| 8 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 9 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
|
| 10 |
+
|
| 11 |
+
from typing import Callable, Optional, Tuple, Union
|
| 12 |
+
|
| 13 |
+
from torch import Tensor
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
def make_2tuple(x):
|
| 18 |
+
if isinstance(x, tuple):
|
| 19 |
+
assert len(x) == 2
|
| 20 |
+
return x
|
| 21 |
+
|
| 22 |
+
assert isinstance(x, int)
|
| 23 |
+
return (x, x)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PatchEmbed(nn.Module):
|
| 27 |
+
"""
|
| 28 |
+
2D image to patch embedding: (B,C,H,W) -> (B,N,D)
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
img_size: Image size.
|
| 32 |
+
patch_size: Patch token size.
|
| 33 |
+
in_chans: Number of input image channels.
|
| 34 |
+
embed_dim: Number of linear projection output channels.
|
| 35 |
+
norm_layer: Normalization layer.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
img_size: Union[int, Tuple[int, int]] = 224,
|
| 41 |
+
patch_size: Union[int, Tuple[int, int]] = 16,
|
| 42 |
+
in_chans: int = 3,
|
| 43 |
+
embed_dim: int = 768,
|
| 44 |
+
norm_layer: Optional[Callable] = None,
|
| 45 |
+
flatten_embedding: bool = True,
|
| 46 |
+
) -> None:
|
| 47 |
+
super().__init__()
|
| 48 |
+
|
| 49 |
+
image_HW = make_2tuple(img_size)
|
| 50 |
+
patch_HW = make_2tuple(patch_size)
|
| 51 |
+
patch_grid_size = (
|
| 52 |
+
image_HW[0] // patch_HW[0],
|
| 53 |
+
image_HW[1] // patch_HW[1],
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
self.img_size = image_HW
|
| 57 |
+
self.patch_size = patch_HW
|
| 58 |
+
self.patches_resolution = patch_grid_size
|
| 59 |
+
self.num_patches = patch_grid_size[0] * patch_grid_size[1]
|
| 60 |
+
|
| 61 |
+
self.in_chans = in_chans
|
| 62 |
+
self.embed_dim = embed_dim
|
| 63 |
+
|
| 64 |
+
self.flatten_embedding = flatten_embedding
|
| 65 |
+
|
| 66 |
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW).to(torch.float16)
|
| 67 |
+
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
|
| 68 |
+
|
| 69 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 70 |
+
_, _, H, W = x.shape
|
| 71 |
+
patch_H, patch_W = self.patch_size
|
| 72 |
+
# x=x.bfloat16()
|
| 73 |
+
assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}"
|
| 74 |
+
assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}"
|
| 75 |
+
# import pdb;pdb.set_trace()
|
| 76 |
+
x = self.proj(x) # B C H W
|
| 77 |
+
H, W = x.size(2), x.size(3)
|
| 78 |
+
x = x.flatten(2).transpose(1, 2) # B HW C
|
| 79 |
+
x = self.norm(x)
|
| 80 |
+
if not self.flatten_embedding:
|
| 81 |
+
x = x.reshape(-1, H, W, self.embed_dim) # B H W C
|
| 82 |
+
return x
|
| 83 |
+
|
| 84 |
+
def flops(self) -> float:
|
| 85 |
+
Ho, Wo = self.patches_resolution
|
| 86 |
+
flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
|
| 87 |
+
if self.norm is not None:
|
| 88 |
+
flops += Ho * Wo * self.embed_dim
|
| 89 |
+
return flops
|
depth_anything_v2/dinov2_layers/swiglu_ffn.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
from typing import Callable, Optional
|
| 8 |
+
|
| 9 |
+
from torch import Tensor, nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SwiGLUFFN(nn.Module):
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
in_features: int,
|
| 17 |
+
hidden_features: Optional[int] = None,
|
| 18 |
+
out_features: Optional[int] = None,
|
| 19 |
+
act_layer: Callable[..., nn.Module] = None,
|
| 20 |
+
drop: float = 0.0,
|
| 21 |
+
bias: bool = True,
|
| 22 |
+
) -> None:
|
| 23 |
+
super().__init__()
|
| 24 |
+
out_features = out_features or in_features
|
| 25 |
+
hidden_features = hidden_features or in_features
|
| 26 |
+
self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
|
| 27 |
+
self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
|
| 28 |
+
|
| 29 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 30 |
+
x12 = self.w12(x)
|
| 31 |
+
x1, x2 = x12.chunk(2, dim=-1)
|
| 32 |
+
hidden = F.silu(x1) * x2
|
| 33 |
+
return self.w3(hidden)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
from xformers.ops import SwiGLU
|
| 38 |
+
|
| 39 |
+
XFORMERS_AVAILABLE = True
|
| 40 |
+
except ImportError:
|
| 41 |
+
SwiGLU = SwiGLUFFN
|
| 42 |
+
XFORMERS_AVAILABLE = False
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class SwiGLUFFNFused(SwiGLU):
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
in_features: int,
|
| 49 |
+
hidden_features: Optional[int] = None,
|
| 50 |
+
out_features: Optional[int] = None,
|
| 51 |
+
act_layer: Callable[..., nn.Module] = None,
|
| 52 |
+
drop: float = 0.0,
|
| 53 |
+
bias: bool = True,
|
| 54 |
+
) -> None:
|
| 55 |
+
out_features = out_features or in_features
|
| 56 |
+
hidden_features = hidden_features or in_features
|
| 57 |
+
hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
|
| 58 |
+
super().__init__(
|
| 59 |
+
in_features=in_features,
|
| 60 |
+
hidden_features=hidden_features,
|
| 61 |
+
out_features=out_features,
|
| 62 |
+
bias=bias,
|
| 63 |
+
)
|
depth_anything_v2/dpt.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torchvision.transforms import Compose
|
| 6 |
+
|
| 7 |
+
from .dinov2 import DINOv2
|
| 8 |
+
from .util.blocks import FeatureFusionBlock, _make_scratch
|
| 9 |
+
from .util.transform import Resize, NormalizeImage, PrepareForNet
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _make_fusion_block(features, use_bn, size=None):
|
| 13 |
+
return FeatureFusionBlock(
|
| 14 |
+
features,
|
| 15 |
+
nn.ReLU(False),
|
| 16 |
+
deconv=False,
|
| 17 |
+
bn=use_bn,
|
| 18 |
+
expand=False,
|
| 19 |
+
align_corners=True,
|
| 20 |
+
size=size,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ConvBlock(nn.Module):
|
| 25 |
+
def __init__(self, in_feature, out_feature):
|
| 26 |
+
super().__init__()
|
| 27 |
+
|
| 28 |
+
self.conv_block = nn.Sequential(
|
| 29 |
+
nn.Conv2d(in_feature, out_feature, kernel_size=3, stride=1, padding=1),
|
| 30 |
+
nn.BatchNorm2d(out_feature),
|
| 31 |
+
nn.ReLU(True)
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
def forward(self, x):
|
| 35 |
+
return self.conv_block(x)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class DPTHead(nn.Module):
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
in_channels,
|
| 42 |
+
features=256,
|
| 43 |
+
use_bn=False,
|
| 44 |
+
out_channels=[256, 512, 1024, 1024],
|
| 45 |
+
use_clstoken=False
|
| 46 |
+
):
|
| 47 |
+
super(DPTHead, self).__init__()
|
| 48 |
+
|
| 49 |
+
self.use_clstoken = use_clstoken
|
| 50 |
+
|
| 51 |
+
self.projects = nn.ModuleList([
|
| 52 |
+
nn.Conv2d(
|
| 53 |
+
in_channels=in_channels,
|
| 54 |
+
out_channels=out_channel,
|
| 55 |
+
kernel_size=1,
|
| 56 |
+
stride=1,
|
| 57 |
+
padding=0,
|
| 58 |
+
) for out_channel in out_channels
|
| 59 |
+
])
|
| 60 |
+
|
| 61 |
+
self.resize_layers = nn.ModuleList([
|
| 62 |
+
nn.ConvTranspose2d(
|
| 63 |
+
in_channels=out_channels[0],
|
| 64 |
+
out_channels=out_channels[0],
|
| 65 |
+
kernel_size=4,
|
| 66 |
+
stride=4,
|
| 67 |
+
padding=0),
|
| 68 |
+
nn.ConvTranspose2d(
|
| 69 |
+
in_channels=out_channels[1],
|
| 70 |
+
out_channels=out_channels[1],
|
| 71 |
+
kernel_size=2,
|
| 72 |
+
stride=2,
|
| 73 |
+
padding=0),
|
| 74 |
+
nn.Identity(),
|
| 75 |
+
nn.Conv2d(
|
| 76 |
+
in_channels=out_channels[3],
|
| 77 |
+
out_channels=out_channels[3],
|
| 78 |
+
kernel_size=3,
|
| 79 |
+
stride=2,
|
| 80 |
+
padding=1)
|
| 81 |
+
])
|
| 82 |
+
|
| 83 |
+
if use_clstoken:
|
| 84 |
+
self.readout_projects = nn.ModuleList()
|
| 85 |
+
for _ in range(len(self.projects)):
|
| 86 |
+
self.readout_projects.append(
|
| 87 |
+
nn.Sequential(
|
| 88 |
+
nn.Linear(2 * in_channels, in_channels),
|
| 89 |
+
nn.GELU()))
|
| 90 |
+
|
| 91 |
+
self.scratch = _make_scratch(
|
| 92 |
+
out_channels,
|
| 93 |
+
features,
|
| 94 |
+
groups=1,
|
| 95 |
+
expand=False,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
self.scratch.stem_transpose = None
|
| 99 |
+
|
| 100 |
+
self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
|
| 101 |
+
self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
|
| 102 |
+
self.scratch.refinenet3 = _make_fusion_block(features, use_bn)
|
| 103 |
+
self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
|
| 104 |
+
|
| 105 |
+
head_features_1 = features
|
| 106 |
+
head_features_2 = 32
|
| 107 |
+
|
| 108 |
+
self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1)
|
| 109 |
+
self.scratch.output_conv2 = nn.Sequential(
|
| 110 |
+
nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1),
|
| 111 |
+
nn.ReLU(True),
|
| 112 |
+
nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0),
|
| 113 |
+
nn.ReLU(True),
|
| 114 |
+
nn.Identity(),
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
def forward(self, out_features, patch_h, patch_w):
|
| 118 |
+
out = []
|
| 119 |
+
for i, x in enumerate(out_features):
|
| 120 |
+
if self.use_clstoken:
|
| 121 |
+
x, cls_token = x[0], x[1]
|
| 122 |
+
readout = cls_token.unsqueeze(1).expand_as(x)
|
| 123 |
+
x = self.readout_projects[i](torch.cat((x, readout), -1))
|
| 124 |
+
else:
|
| 125 |
+
x = x[0]
|
| 126 |
+
|
| 127 |
+
x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w))
|
| 128 |
+
|
| 129 |
+
x = self.projects[i](x)
|
| 130 |
+
x = self.resize_layers[i](x)
|
| 131 |
+
|
| 132 |
+
out.append(x)
|
| 133 |
+
|
| 134 |
+
layer_1, layer_2, layer_3, layer_4 = out
|
| 135 |
+
|
| 136 |
+
layer_1_rn = self.scratch.layer1_rn(layer_1)
|
| 137 |
+
layer_2_rn = self.scratch.layer2_rn(layer_2)
|
| 138 |
+
layer_3_rn = self.scratch.layer3_rn(layer_3)
|
| 139 |
+
layer_4_rn = self.scratch.layer4_rn(layer_4)
|
| 140 |
+
|
| 141 |
+
path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
|
| 142 |
+
path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:])
|
| 143 |
+
path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:])
|
| 144 |
+
path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
|
| 145 |
+
|
| 146 |
+
out = self.scratch.output_conv1(path_1)
|
| 147 |
+
out = F.interpolate(out, (int(patch_h * 14), int(patch_w * 14)), mode="bilinear", align_corners=True)
|
| 148 |
+
out = self.scratch.output_conv2(out)
|
| 149 |
+
|
| 150 |
+
return out
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class DepthAnythingV2(nn.Module):
|
| 154 |
+
def __init__(
|
| 155 |
+
self,
|
| 156 |
+
encoder='vitl',
|
| 157 |
+
features=256,
|
| 158 |
+
out_channels=[256, 512, 1024, 1024],
|
| 159 |
+
use_bn=False,
|
| 160 |
+
use_clstoken=False
|
| 161 |
+
):
|
| 162 |
+
super(DepthAnythingV2, self).__init__()
|
| 163 |
+
|
| 164 |
+
self.intermediate_layer_idx = {
|
| 165 |
+
'vits': [2, 5, 8, 11],
|
| 166 |
+
'vitb': [2, 5, 8, 11],
|
| 167 |
+
'vitl': [4, 11, 17, 23],
|
| 168 |
+
'vitg': [9, 19, 29, 39]
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
self.encoder = encoder
|
| 172 |
+
self.pretrained = DINOv2(model_name=encoder)
|
| 173 |
+
|
| 174 |
+
self.depth_head = DPTHead(self.pretrained.embed_dim, features, use_bn, out_channels=out_channels, use_clstoken=use_clstoken)
|
| 175 |
+
|
| 176 |
+
@torch.no_grad()
|
| 177 |
+
def forward(self, x, input_size=518):
|
| 178 |
+
# x, (h, w) = self.image2tensor(x, input_size)
|
| 179 |
+
b,c,h,w =x.shape
|
| 180 |
+
patch_h, patch_w = x.shape[-2] // 14, x.shape[-1] // 14
|
| 181 |
+
# import pdb;pdb.set_trace()
|
| 182 |
+
features = self.pretrained.get_intermediate_layers(x, self.intermediate_layer_idx[self.encoder], return_class_token=True)
|
| 183 |
+
|
| 184 |
+
depth = self.depth_head(features, patch_h, patch_w)
|
| 185 |
+
depth = F.relu(depth)
|
| 186 |
+
# depth=depth.squeeze(1)
|
| 187 |
+
# depth = F.interpolate(depth[:, None], (h, w), mode="bilinear", align_corners=True)[0, 0]
|
| 188 |
+
|
| 189 |
+
depth = depth.squeeze(1) # 确保深度维度减少为 (b, h', w')
|
| 190 |
+
depth = F.interpolate(depth[:, None], (h, w), mode="bilinear", align_corners=True)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
return depth
|
| 195 |
+
|
| 196 |
+
@torch.no_grad()
|
| 197 |
+
def infer_image(self, raw_image, input_size=518):
|
| 198 |
+
image, (h, w) = self.image2tensor(raw_image, input_size)
|
| 199 |
+
|
| 200 |
+
depth = self.forward(image)
|
| 201 |
+
|
| 202 |
+
depth = F.interpolate(depth[:, None], (h, w), mode="bilinear", align_corners=True)[0, 0]
|
| 203 |
+
|
| 204 |
+
return depth.cpu().numpy()
|
| 205 |
+
|
| 206 |
+
def image2tensor(self, raw_image, input_size=518):
|
| 207 |
+
transform = Compose([
|
| 208 |
+
Resize(
|
| 209 |
+
width=input_size,
|
| 210 |
+
height=input_size,
|
| 211 |
+
resize_target=False,
|
| 212 |
+
keep_aspect_ratio=True,
|
| 213 |
+
ensure_multiple_of=14,
|
| 214 |
+
resize_method='lower_bound',
|
| 215 |
+
image_interpolation_method=cv2.INTER_CUBIC,
|
| 216 |
+
),
|
| 217 |
+
NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 218 |
+
PrepareForNet(),
|
| 219 |
+
])
|
| 220 |
+
|
| 221 |
+
h, w = raw_image.shape[:2]
|
| 222 |
+
|
| 223 |
+
image = cv2.cvtColor(raw_image, cv2.COLOR_BGR2RGB) / 255.0
|
| 224 |
+
|
| 225 |
+
image = transform({'image': image})['image']
|
| 226 |
+
image = torch.from_numpy(image).unsqueeze(0)
|
| 227 |
+
|
| 228 |
+
DEVICE = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
|
| 229 |
+
image = image.to(DEVICE)
|
| 230 |
+
|
| 231 |
+
return image, (h, w)
|
depth_anything_v2/util/blocks.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
|
| 5 |
+
scratch = nn.Module()
|
| 6 |
+
|
| 7 |
+
out_shape1 = out_shape
|
| 8 |
+
out_shape2 = out_shape
|
| 9 |
+
out_shape3 = out_shape
|
| 10 |
+
if len(in_shape) >= 4:
|
| 11 |
+
out_shape4 = out_shape
|
| 12 |
+
|
| 13 |
+
if expand:
|
| 14 |
+
out_shape1 = out_shape
|
| 15 |
+
out_shape2 = out_shape * 2
|
| 16 |
+
out_shape3 = out_shape * 4
|
| 17 |
+
if len(in_shape) >= 4:
|
| 18 |
+
out_shape4 = out_shape * 8
|
| 19 |
+
|
| 20 |
+
scratch.layer1_rn = nn.Conv2d(in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
|
| 21 |
+
scratch.layer2_rn = nn.Conv2d(in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
|
| 22 |
+
scratch.layer3_rn = nn.Conv2d(in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
|
| 23 |
+
if len(in_shape) >= 4:
|
| 24 |
+
scratch.layer4_rn = nn.Conv2d(in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
|
| 25 |
+
|
| 26 |
+
return scratch
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ResidualConvUnit(nn.Module):
|
| 30 |
+
"""Residual convolution module.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, features, activation, bn):
|
| 34 |
+
"""Init.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
features (int): number of features
|
| 38 |
+
"""
|
| 39 |
+
super().__init__()
|
| 40 |
+
|
| 41 |
+
self.bn = bn
|
| 42 |
+
|
| 43 |
+
self.groups=1
|
| 44 |
+
|
| 45 |
+
self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
|
| 46 |
+
|
| 47 |
+
self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
|
| 48 |
+
|
| 49 |
+
if self.bn == True:
|
| 50 |
+
self.bn1 = nn.BatchNorm2d(features)
|
| 51 |
+
self.bn2 = nn.BatchNorm2d(features)
|
| 52 |
+
|
| 53 |
+
self.activation = activation
|
| 54 |
+
|
| 55 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 56 |
+
|
| 57 |
+
def forward(self, x):
|
| 58 |
+
"""Forward pass.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
x (tensor): input
|
| 62 |
+
|
| 63 |
+
Returns:
|
| 64 |
+
tensor: output
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
out = self.activation(x)
|
| 68 |
+
out = self.conv1(out)
|
| 69 |
+
if self.bn == True:
|
| 70 |
+
out = self.bn1(out)
|
| 71 |
+
|
| 72 |
+
out = self.activation(out)
|
| 73 |
+
out = self.conv2(out)
|
| 74 |
+
if self.bn == True:
|
| 75 |
+
out = self.bn2(out)
|
| 76 |
+
|
| 77 |
+
if self.groups > 1:
|
| 78 |
+
out = self.conv_merge(out)
|
| 79 |
+
|
| 80 |
+
return self.skip_add.add(out, x)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class FeatureFusionBlock(nn.Module):
|
| 84 |
+
"""Feature fusion block.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
def __init__(
|
| 88 |
+
self,
|
| 89 |
+
features,
|
| 90 |
+
activation,
|
| 91 |
+
deconv=False,
|
| 92 |
+
bn=False,
|
| 93 |
+
expand=False,
|
| 94 |
+
align_corners=True,
|
| 95 |
+
size=None
|
| 96 |
+
):
|
| 97 |
+
"""Init.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
features (int): number of features
|
| 101 |
+
"""
|
| 102 |
+
super(FeatureFusionBlock, self).__init__()
|
| 103 |
+
|
| 104 |
+
self.deconv = deconv
|
| 105 |
+
self.align_corners = align_corners
|
| 106 |
+
|
| 107 |
+
self.groups=1
|
| 108 |
+
|
| 109 |
+
self.expand = expand
|
| 110 |
+
out_features = features
|
| 111 |
+
if self.expand == True:
|
| 112 |
+
out_features = features // 2
|
| 113 |
+
|
| 114 |
+
self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1)
|
| 115 |
+
|
| 116 |
+
self.resConfUnit1 = ResidualConvUnit(features, activation, bn)
|
| 117 |
+
self.resConfUnit2 = ResidualConvUnit(features, activation, bn)
|
| 118 |
+
|
| 119 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 120 |
+
|
| 121 |
+
self.size=size
|
| 122 |
+
|
| 123 |
+
def forward(self, *xs, size=None):
|
| 124 |
+
"""Forward pass.
|
| 125 |
+
|
| 126 |
+
Returns:
|
| 127 |
+
tensor: output
|
| 128 |
+
"""
|
| 129 |
+
output = xs[0]
|
| 130 |
+
|
| 131 |
+
if len(xs) == 2:
|
| 132 |
+
res = self.resConfUnit1(xs[1])
|
| 133 |
+
output = self.skip_add.add(output, res)
|
| 134 |
+
|
| 135 |
+
output = self.resConfUnit2(output)
|
| 136 |
+
|
| 137 |
+
if (size is None) and (self.size is None):
|
| 138 |
+
modifier = {"scale_factor": 2}
|
| 139 |
+
elif size is None:
|
| 140 |
+
modifier = {"size": self.size}
|
| 141 |
+
else:
|
| 142 |
+
modifier = {"size": size}
|
| 143 |
+
|
| 144 |
+
output = nn.functional.interpolate(output, **modifier, mode="bilinear", align_corners=self.align_corners)
|
| 145 |
+
|
| 146 |
+
output = self.out_conv(output)
|
| 147 |
+
|
| 148 |
+
return output
|
depth_anything_v2/util/transform.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import cv2
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Resize(object):
|
| 6 |
+
"""Resize sample to given size (width, height).
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
def __init__(
|
| 10 |
+
self,
|
| 11 |
+
width,
|
| 12 |
+
height,
|
| 13 |
+
resize_target=True,
|
| 14 |
+
keep_aspect_ratio=False,
|
| 15 |
+
ensure_multiple_of=1,
|
| 16 |
+
resize_method="lower_bound",
|
| 17 |
+
image_interpolation_method=cv2.INTER_AREA,
|
| 18 |
+
):
|
| 19 |
+
"""Init.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
width (int): desired output width
|
| 23 |
+
height (int): desired output height
|
| 24 |
+
resize_target (bool, optional):
|
| 25 |
+
True: Resize the full sample (image, mask, target).
|
| 26 |
+
False: Resize image only.
|
| 27 |
+
Defaults to True.
|
| 28 |
+
keep_aspect_ratio (bool, optional):
|
| 29 |
+
True: Keep the aspect ratio of the input sample.
|
| 30 |
+
Output sample might not have the given width and height, and
|
| 31 |
+
resize behaviour depends on the parameter 'resize_method'.
|
| 32 |
+
Defaults to False.
|
| 33 |
+
ensure_multiple_of (int, optional):
|
| 34 |
+
Output width and height is constrained to be multiple of this parameter.
|
| 35 |
+
Defaults to 1.
|
| 36 |
+
resize_method (str, optional):
|
| 37 |
+
"lower_bound": Output will be at least as large as the given size.
|
| 38 |
+
"upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.)
|
| 39 |
+
"minimal": Scale as least as possible. (Output size might be smaller than given size.)
|
| 40 |
+
Defaults to "lower_bound".
|
| 41 |
+
"""
|
| 42 |
+
self.__width = width
|
| 43 |
+
self.__height = height
|
| 44 |
+
|
| 45 |
+
self.__resize_target = resize_target
|
| 46 |
+
self.__keep_aspect_ratio = keep_aspect_ratio
|
| 47 |
+
self.__multiple_of = ensure_multiple_of
|
| 48 |
+
self.__resize_method = resize_method
|
| 49 |
+
self.__image_interpolation_method = image_interpolation_method
|
| 50 |
+
|
| 51 |
+
def constrain_to_multiple_of(self, x, min_val=0, max_val=None):
|
| 52 |
+
y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 53 |
+
|
| 54 |
+
if max_val is not None and y > max_val:
|
| 55 |
+
y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 56 |
+
|
| 57 |
+
if y < min_val:
|
| 58 |
+
y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 59 |
+
|
| 60 |
+
return y
|
| 61 |
+
|
| 62 |
+
def get_size(self, width, height):
|
| 63 |
+
# determine new height and width
|
| 64 |
+
scale_height = self.__height / height
|
| 65 |
+
scale_width = self.__width / width
|
| 66 |
+
|
| 67 |
+
if self.__keep_aspect_ratio:
|
| 68 |
+
if self.__resize_method == "lower_bound":
|
| 69 |
+
# scale such that output size is lower bound
|
| 70 |
+
if scale_width > scale_height:
|
| 71 |
+
# fit width
|
| 72 |
+
scale_height = scale_width
|
| 73 |
+
else:
|
| 74 |
+
# fit height
|
| 75 |
+
scale_width = scale_height
|
| 76 |
+
elif self.__resize_method == "upper_bound":
|
| 77 |
+
# scale such that output size is upper bound
|
| 78 |
+
if scale_width < scale_height:
|
| 79 |
+
# fit width
|
| 80 |
+
scale_height = scale_width
|
| 81 |
+
else:
|
| 82 |
+
# fit height
|
| 83 |
+
scale_width = scale_height
|
| 84 |
+
elif self.__resize_method == "minimal":
|
| 85 |
+
# scale as least as possbile
|
| 86 |
+
if abs(1 - scale_width) < abs(1 - scale_height):
|
| 87 |
+
# fit width
|
| 88 |
+
scale_height = scale_width
|
| 89 |
+
else:
|
| 90 |
+
# fit height
|
| 91 |
+
scale_width = scale_height
|
| 92 |
+
else:
|
| 93 |
+
raise ValueError(f"resize_method {self.__resize_method} not implemented")
|
| 94 |
+
|
| 95 |
+
if self.__resize_method == "lower_bound":
|
| 96 |
+
new_height = self.constrain_to_multiple_of(scale_height * height, min_val=self.__height)
|
| 97 |
+
new_width = self.constrain_to_multiple_of(scale_width * width, min_val=self.__width)
|
| 98 |
+
elif self.__resize_method == "upper_bound":
|
| 99 |
+
new_height = self.constrain_to_multiple_of(scale_height * height, max_val=self.__height)
|
| 100 |
+
new_width = self.constrain_to_multiple_of(scale_width * width, max_val=self.__width)
|
| 101 |
+
elif self.__resize_method == "minimal":
|
| 102 |
+
new_height = self.constrain_to_multiple_of(scale_height * height)
|
| 103 |
+
new_width = self.constrain_to_multiple_of(scale_width * width)
|
| 104 |
+
else:
|
| 105 |
+
raise ValueError(f"resize_method {self.__resize_method} not implemented")
|
| 106 |
+
|
| 107 |
+
return (new_width, new_height)
|
| 108 |
+
|
| 109 |
+
def __call__(self, sample):
|
| 110 |
+
width, height = self.get_size(sample["image"].shape[1], sample["image"].shape[0])
|
| 111 |
+
|
| 112 |
+
# resize sample
|
| 113 |
+
sample["image"] = cv2.resize(sample["image"], (width, height), interpolation=self.__image_interpolation_method)
|
| 114 |
+
|
| 115 |
+
if self.__resize_target:
|
| 116 |
+
if "depth" in sample:
|
| 117 |
+
sample["depth"] = cv2.resize(sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST)
|
| 118 |
+
|
| 119 |
+
if "mask" in sample:
|
| 120 |
+
sample["mask"] = cv2.resize(sample["mask"].astype(np.float32), (width, height), interpolation=cv2.INTER_NEAREST)
|
| 121 |
+
|
| 122 |
+
return sample
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class NormalizeImage(object):
|
| 126 |
+
"""Normlize image by given mean and std.
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
def __init__(self, mean, std):
|
| 130 |
+
self.__mean = mean
|
| 131 |
+
self.__std = std
|
| 132 |
+
|
| 133 |
+
def __call__(self, sample):
|
| 134 |
+
sample["image"] = (sample["image"] - self.__mean) / self.__std
|
| 135 |
+
|
| 136 |
+
return sample
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class PrepareForNet(object):
|
| 140 |
+
"""Prepare sample for usage as network input.
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
def __init__(self):
|
| 144 |
+
pass
|
| 145 |
+
|
| 146 |
+
def __call__(self, sample):
|
| 147 |
+
image = np.transpose(sample["image"], (2, 0, 1))
|
| 148 |
+
sample["image"] = np.ascontiguousarray(image).astype(np.float32)
|
| 149 |
+
|
| 150 |
+
if "depth" in sample:
|
| 151 |
+
depth = sample["depth"].astype(np.float32)
|
| 152 |
+
sample["depth"] = np.ascontiguousarray(depth)
|
| 153 |
+
|
| 154 |
+
if "mask" in sample:
|
| 155 |
+
sample["mask"] = sample["mask"].astype(np.float32)
|
| 156 |
+
sample["mask"] = np.ascontiguousarray(sample["mask"])
|
| 157 |
+
|
| 158 |
+
return sample
|
docs/Customize_Component.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Customize Components in LLaVA
|
| 2 |
+
|
| 3 |
+
This is an initial guide on how to replace the LLMs, visual encoders, etc. with your choice of components.
|
| 4 |
+
|
| 5 |
+
## LLM
|
| 6 |
+
|
| 7 |
+
It is quite simple to swap out LLaMA to any other LLMs. You can refer to our implementation of [`llava_llama.py`](https://raw.githubusercontent.com/haotian-liu/LLaVA/main/llava/model/language_model/llava_llama.py) for an example of how to replace the LLM.
|
| 8 |
+
|
| 9 |
+
Although it may seem that it still needs ~100 lines of code, most of them are copied from the original `llama.py` from HF. The only part that is different is to insert some lines for processing the multimodal inputs.
|
| 10 |
+
|
| 11 |
+
In `forward` function, you can see that we call `self.prepare_inputs_labels_for_multimodal` to process the multimodal inputs. This function is defined in `LlavaMetaForCausalLM` and you just need to insert it into the `forward` function of your LLM.
|
| 12 |
+
|
| 13 |
+
In `prepare_inputs_for_generation` function, you can see that we add `images` to the `model_inputs`. This is because we need to pass the images to the LLM during generation.
|
| 14 |
+
|
| 15 |
+
These are basically all the changes you need to make to replace the LLM.
|
| 16 |
+
|
| 17 |
+
## Visual Encoder
|
| 18 |
+
|
| 19 |
+
You can check out [`clip_encoder.py`](https://github.com/haotian-liu/LLaVA/blob/main/llava/model/multimodal_encoder/clip_encoder.py) on how we implement the CLIP visual encoder.
|
| 20 |
+
|
docs/Data.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Data
|
| 2 |
+
|
| 3 |
+
| Data file name | Size |
|
| 4 |
+
| --- | ---: |
|
| 5 |
+
| [llava_instruct_150k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_150k.json) | 229 MB |
|
| 6 |
+
| [llava_instruct_80k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_80k.json) | 229 MB |
|
| 7 |
+
| [conversation_58k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/conversation_58k.json) | 126 MB |
|
| 8 |
+
| [detail_23k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/detail_23k.json) | 20.5 MB |
|
| 9 |
+
| [complex_reasoning_77k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/complex_reasoning_77k.json) | 79.6 MB |
|
| 10 |
+
|
| 11 |
+
### Pretraining Dataset
|
| 12 |
+
The pretraining dataset used in this release is a subset of CC-3M dataset, filtered with a more balanced concept coverage distribution. Please see [here](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K) for a detailed description of the dataset structure and how to download the images.
|
| 13 |
+
|
| 14 |
+
If you already have CC-3M dataset on your disk, the image names follow this format: `GCC_train_000000000.jpg`. You may edit the `image` field correspondingly if necessary.
|
| 15 |
+
|
| 16 |
+
| Data | Chat File | Meta Data | Size |
|
| 17 |
+
| --- | --- | --- | ---: |
|
| 18 |
+
| CC-3M Concept-balanced 595K | [chat.json](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/chat.json) | [metadata.json](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/metadata.json) | 211 MB
|
| 19 |
+
| LAION/CC/SBU BLIP-Caption Concept-balanced 558K | [blip_laion_cc_sbu_558k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain/blob/main/blip_laion_cc_sbu_558k.json) | [metadata.json](#) | 181 MB
|
| 20 |
+
|
| 21 |
+
**Important notice**: Upon the request from the community, as ~15% images of the original CC-3M dataset are no longer accessible, we upload [`images.zip`](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/images.zip) for better reproducing our work in research community. It must not be used for any other purposes. The use of these images must comply with the CC-3M license. This may be taken down at any time when requested by the original CC-3M dataset owner or owners of the referenced images.
|
| 22 |
+
|
| 23 |
+
### GPT-4 Prompts
|
| 24 |
+
|
| 25 |
+
We provide our prompts and few-shot samples for GPT-4 queries, to better facilitate research in this domain. Please check out the [`prompts`](https://github.com/haotian-liu/LLaVA/tree/main/playground/data/prompts) folder for three kinds of questions: conversation, detail description, and complex reasoning.
|
| 26 |
+
|
| 27 |
+
They are organized in a format of `system_message.txt` for system message, pairs of `abc_caps.txt` for few-shot sample user input, and `abc_conv.txt` for few-shot sample reference output.
|
| 28 |
+
|
| 29 |
+
Note that you may find them in different format. For example, `conversation` is in `jsonl`, and detail description is answer-only. The selected format in our preliminary experiments works slightly better than a limited set of alternatives that we tried: `jsonl`, more natural format, answer-only. If interested, you may try other variants or conduct more careful study in this. Contributions are welcomed!
|
docs/Evaluation.md
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evaluation
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
Currently, we mostly utilize the official toolkit or server for the evaluation.
|
| 6 |
+
|
| 7 |
+
## Evaluate on Custom Datasets
|
| 8 |
+
|
| 9 |
+
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).
|
| 10 |
+
|
| 11 |
+
Below we provide a general guideline for evaluating datasets with some common formats.
|
| 12 |
+
|
| 13 |
+
1. Short-answer (e.g. VQAv2, MME).
|
| 14 |
+
|
| 15 |
+
```
|
| 16 |
+
<question>
|
| 17 |
+
Answer the question using a single word or phrase.
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
2. Option-only for multiple-choice (e.g. MMBench, SEED-Bench).
|
| 21 |
+
|
| 22 |
+
```
|
| 23 |
+
<question>
|
| 24 |
+
A. <option_1>
|
| 25 |
+
B. <option_2>
|
| 26 |
+
C. <option_3>
|
| 27 |
+
D. <option_4>
|
| 28 |
+
Answer with the option's letter from the given choices directly.
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
3. Natural QA (e.g. LLaVA-Bench, MM-Vet).
|
| 32 |
+
|
| 33 |
+
No postprocessing is needed.
|
| 34 |
+
|
| 35 |
+
## Scripts
|
| 36 |
+
|
| 37 |
+
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.
|
| 38 |
+
|
| 39 |
+
### VQAv2
|
| 40 |
+
|
| 41 |
+
1. Download [`test2015`](http://images.cocodataset.org/zips/test2015.zip) and put it under `./playground/data/eval/vqav2`.
|
| 42 |
+
2. Multi-GPU inference.
|
| 43 |
+
```Shell
|
| 44 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/v1_5/eval/vqav2.sh
|
| 45 |
+
```
|
| 46 |
+
3. Submit the results to the [evaluation server](https://eval.ai/web/challenges/challenge-page/830/my-submission): `./playground/data/eval/vqav2/answers_upload`.
|
| 47 |
+
|
| 48 |
+
### GQA
|
| 49 |
+
|
| 50 |
+
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.
|
| 51 |
+
2. Multi-GPU inference.
|
| 52 |
+
```Shell
|
| 53 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/v1_5/eval/gqa.sh
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
### VisWiz
|
| 57 |
+
|
| 58 |
+
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`.
|
| 59 |
+
2. Single-GPU inference.
|
| 60 |
+
```Shell
|
| 61 |
+
CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/vizwiz.sh
|
| 62 |
+
```
|
| 63 |
+
3. Submit the results to the [evaluation server](https://eval.ai/web/challenges/challenge-page/2185/my-submission): `./playground/data/eval/vizwiz/answers_upload`.
|
| 64 |
+
|
| 65 |
+
### ScienceQA
|
| 66 |
+
|
| 67 |
+
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).
|
| 68 |
+
2. Single-GPU inference and evaluate.
|
| 69 |
+
```Shell
|
| 70 |
+
CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/sqa.sh
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
### TextVQA
|
| 74 |
+
|
| 75 |
+
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`.
|
| 76 |
+
2. Single-GPU inference and evaluate.
|
| 77 |
+
```Shell
|
| 78 |
+
CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/textvqa.sh
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
### POPE
|
| 82 |
+
|
| 83 |
+
1. Download `coco` from [POPE](https://github.com/AoiDragon/POPE/tree/e3e39262c85a6a83f26cf5094022a782cb0df58d/output/coco) and put under `./playground/data/eval/pope`.
|
| 84 |
+
2. Single-GPU inference and evaluate.
|
| 85 |
+
```Shell
|
| 86 |
+
CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/pope.sh
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
### MME
|
| 90 |
+
|
| 91 |
+
1. Download the data following the official instructions [here](https://github.com/BradyFU/Awesome-Multimodal-Large-Language-Models/tree/Evaluation).
|
| 92 |
+
2. Downloaded images to `MME_Benchmark_release_version`.
|
| 93 |
+
3. put the official `eval_tool` and `MME_Benchmark_release_version` under `./playground/data/eval/MME`.
|
| 94 |
+
4. Single-GPU inference and evaluate.
|
| 95 |
+
```Shell
|
| 96 |
+
CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mme.sh
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
### MMBench
|
| 100 |
+
|
| 101 |
+
1. Download [`mmbench_dev_20230712.tsv`](https://download.openmmlab.com/mmclassification/datasets/mmbench/mmbench_dev_20230712.tsv) and put under `./playground/data/eval/mmbench`.
|
| 102 |
+
2. Single-GPU inference.
|
| 103 |
+
```Shell
|
| 104 |
+
CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mmbench.sh
|
| 105 |
+
```
|
| 106 |
+
3. Submit the results to the [evaluation server](https://opencompass.org.cn/leaderboard-multimodal): `./playground/data/eval/mmbench/answers_upload/mmbench_dev_20230712`.
|
| 107 |
+
|
| 108 |
+
### MMBench-CN
|
| 109 |
+
|
| 110 |
+
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`.
|
| 111 |
+
2. Single-GPU inference.
|
| 112 |
+
```Shell
|
| 113 |
+
CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mmbench_cn.sh
|
| 114 |
+
```
|
| 115 |
+
3. Submit the results to the evaluation server: `./playground/data/eval/mmbench/answers_upload/mmbench_dev_cn_20231003`.
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
### SEED-Bench
|
| 119 |
+
|
| 120 |
+
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`.
|
| 121 |
+
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.
|
| 122 |
+
3. Multiple-GPU inference and evaluate.
|
| 123 |
+
```Shell
|
| 124 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/v1_5/eval/seed.sh
|
| 125 |
+
```
|
| 126 |
+
4. Optionally, submit the results to the leaderboard: `./playground/data/eval/seed_bench/answers_upload` using the official jupyter notebook.
|
| 127 |
+
|
| 128 |
+
### LLaVA-Bench-in-the-Wild
|
| 129 |
+
|
| 130 |
+
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`.
|
| 131 |
+
2. Single-GPU inference and evaluate.
|
| 132 |
+
```Shell
|
| 133 |
+
CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/llavabench.sh
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
### MM-Vet
|
| 137 |
+
|
| 138 |
+
1. Extract [`mm-vet.zip`](https://github.com/yuweihao/MM-Vet/releases/download/v1/mm-vet.zip) to `./playground/data/eval/mmvet`.
|
| 139 |
+
2. Single-GPU inference.
|
| 140 |
+
```Shell
|
| 141 |
+
CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mmvet.sh
|
| 142 |
+
```
|
| 143 |
+
3. Evaluate the predictions in `./playground/data/eval/mmvet/results` using the official jupyter notebook.
|
| 144 |
+
|
| 145 |
+
## More Benchmarks
|
| 146 |
+
|
| 147 |
+
Below are awesome benchmarks for multimodal understanding from the research community, that are not initially included in the LLaVA-1.5 release.
|
| 148 |
+
|
| 149 |
+
### Q-Bench
|
| 150 |
+
|
| 151 |
+
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`.
|
| 152 |
+
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`.
|
| 153 |
+
3. Single-GPU inference (change `dev` to `test` for evaluation on test set).
|
| 154 |
+
```Shell
|
| 155 |
+
CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/qbench.sh dev
|
| 156 |
+
```
|
| 157 |
+
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`.
|
| 158 |
+
|
| 159 |
+
### Chinese-Q-Bench
|
| 160 |
+
|
| 161 |
+
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`.
|
| 162 |
+
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`.
|
| 163 |
+
3. Single-GPU inference (change `dev` to `test` for evaluation on test set).
|
| 164 |
+
```Shell
|
| 165 |
+
CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/qbench_zh.sh dev
|
| 166 |
+
```
|
| 167 |
+
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`.
|
docs/Finetune_Custom_Data.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Finetune LLaVA on Custom Datasets
|
| 2 |
+
|
| 3 |
+
## Dataset Format
|
| 4 |
+
|
| 5 |
+
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).
|
| 6 |
+
|
| 7 |
+
A sample JSON for finetuning LLaVA for generating tag-style captions for Stable Diffusion:
|
| 8 |
+
|
| 9 |
+
```json
|
| 10 |
+
[
|
| 11 |
+
{
|
| 12 |
+
"id": "997bb945-628d-4724-b370-b84de974a19f",
|
| 13 |
+
"image": "part-000001/997bb945-628d-4724-b370-b84de974a19f.jpg",
|
| 14 |
+
"conversations": [
|
| 15 |
+
{
|
| 16 |
+
"from": "human",
|
| 17 |
+
"value": "<image>\nWrite a prompt for Stable Diffusion to generate this image."
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"from": "gpt",
|
| 21 |
+
"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. "
|
| 22 |
+
},
|
| 23 |
+
]
|
| 24 |
+
},
|
| 25 |
+
...
|
| 26 |
+
]
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
## Command
|
| 30 |
+
|
| 31 |
+
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).
|
| 32 |
+
|
| 33 |
+
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).
|
| 34 |
+
|
| 35 |
+
You may need to adjust the hyperparameters to fit each specific dataset and your hardware constraint.
|
| 36 |
+
|
| 37 |
+
|
docs/Intel.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Intel Platforms
|
| 2 |
+
|
| 3 |
+
* Support [Intel GPU Max Series](https://www.intel.com/content/www/us/en/products/details/discrete-gpus/data-center-gpu/max-series.html)
|
| 4 |
+
* Support [Intel CPU Sapphire Rapides](https://ark.intel.com/content/www/us/en/ark/products/codename/126212/products-formerly-sapphire-rapids.html)
|
| 5 |
+
* Based on [Intel Extension for Pytorch](https://intel.github.io/intel-extension-for-pytorch)
|
| 6 |
+
|
| 7 |
+
More details in [**intel branch**](https://github.com/haotian-liu/LLaVA/tree/intel/docs/intel)
|
docs/LLaVA_Bench.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLaVA-Bench [[Download](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild)]
|
| 2 |
+
|
| 3 |
+
**-Introduction-** Large commercial multimodal chatbots have been released in this week, including
|
| 4 |
+
- [Multimodal Bing-Chat by Microsoft](https://blogs.bing.com/search/july-2023/Bing-Chat-Enterprise-announced,-multimodal-Visual-Search-rolling-out-to-Bing-Chat) (July 18, 2023)
|
| 5 |
+
- [Multimodal Bard by Google](https://bard.google.com/).
|
| 6 |
+
|
| 7 |
+
These chatbots are presumably supported by proprietary large multimodal models (LMM). Compared with the open-source LMM such as LLaVA, proprietary LMM represent the scaling success upperbound of the current SoTA techniques. They share the goal of developing multimodal chatbots that follow human intents to complete various daily-life visual tasks in the wild. While it remains less 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.
|
| 8 |
+
|
| 9 |
+
## LLaVA-Bench (In-the-Wild *[Ongoing work]*)
|
| 10 |
+
|
| 11 |
+
To evaluate the model's capability in more challenging tasks and generalizability to novel domains, we collect a diverse set of 24 images with 60 questions in total, including indoor and outdoor scenes, memes, paintings, sketches, etc, and associate each image with a highly-detailed and manually-curated description and a proper selection of questions. Such design also assesses the model's robustness to different prompts. In this release, we also categorize questions into three categories: conversation (simple QA), detailed description, and complex reasoning. We continue to expand and improve the diversity of the LLaVA-Bench (In-the-Wild). We manually query Bing-Chat and Bard to get the responses.
|
| 12 |
+
|
| 13 |
+
### Results
|
| 14 |
+
|
| 15 |
+
The score is measured by comparing against a reference answer generated by text-only GPT-4. It is generated by feeding the question, along with the ground truth image annotations as the context. A text-only GPT-4 evaluator rates both answers. We query GPT-4 by putting the reference answer first, and then the answer generated by the candidate model. We upload images at their original resolution to Bard and Bing-Chat to obtain the results.
|
| 16 |
+
|
| 17 |
+
| Approach | Conversation | Detail | Reasoning | Overall |
|
| 18 |
+
|----------------|--------------|--------|-----------|---------|
|
| 19 |
+
| Bard-0718 | 83.7 | 69.7 | 78.7 | 77.8 |
|
| 20 |
+
| Bing-Chat-0629 | 59.6 | 52.2 | 90.1 | 71.5 |
|
| 21 |
+
| LLaVA-13B-v1-336px-0719 (beam=1) | 64.3 | 55.9 | 81.7 | 70.1 |
|
| 22 |
+
| LLaVA-13B-v1-336px-0719 (beam=5) | 68.4 | 59.9 | 84.3 | 73.5 |
|
| 23 |
+
|
| 24 |
+
Note that Bard sometimes refuses to answer questions about images containing humans, and Bing-Chat blurs the human faces in the images. We also provide the benchmark score for the subset without humans.
|
| 25 |
+
|
| 26 |
+
| Approach | Conversation | Detail | Reasoning | Overall |
|
| 27 |
+
|----------------|--------------|--------|-----------|---------|
|
| 28 |
+
| Bard-0718 | 94.9 | 74.3 | 84.3 | 84.6 |
|
| 29 |
+
| Bing-Chat-0629 | 55.8 | 53.6 | 93.5 | 72.6 |
|
| 30 |
+
| LLaVA-13B-v1-336px-0719 (beam=1) | 62.2 | 56.4 | 82.2 | 70.0 |
|
| 31 |
+
| LLaVA-13B-v1-336px-0719 (beam=5) | 65.6 | 61.7 | 85.0 | 73.6 |
|
docs/LLaVA_from_LLaMA2.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLaVA (based on Llama 2 LLM, Preview)
|
| 2 |
+
|
| 3 |
+
*NOTE: This is a technical preview. We are still running hyperparameter search, and will release the final model soon. If you'd like to contribute to this, please contact us.*
|
| 4 |
+
|
| 5 |
+
:llama: **-Introduction-** [Llama 2 is an open-source LLM released by Meta AI](https://about.fb.com/news/2023/07/llama-2/) today (July 18, 2023). Compared with its early version [Llama 1](https://ai.meta.com/blog/large-language-model-llama-meta-ai/), Llama 2 is more favored in ***stronger language performance***, ***longer context window***, and importantly ***commercially usable***! While Llama 2 is changing the LLM market landscape in the language space, its multimodal ability remains unknown. We quickly develop the LLaVA variant based on the latest Llama 2 checkpoints, and release it to the community for the public use.
|
| 6 |
+
|
| 7 |
+
You need to apply for and download the latest Llama 2 checkpoints to start your own training (apply [here](https://ai.meta.com/resources/models-and-libraries/llama-downloads/))
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
## Training
|
| 11 |
+
|
| 12 |
+
Please checkout [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain.sh), [`finetune.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune.sh), [`finetune_lora.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh).
|
| 13 |
+
|
| 14 |
+
## LLaVA (based on Llama 2), What is different?
|
| 15 |
+
|
| 16 |
+
:volcano: How is the new LLaVA based on Llama 2 different from Llama 1? The comparisons of the training process are described:
|
| 17 |
+
- **Pre-training**. The pre-trained base LLM is changed from Llama 1 to Llama 2
|
| 18 |
+
- **Language instruction-tuning**. The previous LLaVA model starts with Vicuna, which is instruct tuned on ShareGPT data from Llama 1; The new LLaVA model starts with Llama 2 Chat, which is an instruct tuned checkpoint on dialogue data from Llama 2.
|
| 19 |
+
- **Multimodal instruction-tuning**. The same LLaVA-Lighting process is applied.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
### Results
|
| 23 |
+
|
| 24 |
+
- Llama 2 is better at following the instructions of role playing; Llama 2 fails in following the instructions of translation
|
| 25 |
+
- The quantitative evaluation on [LLaVA-Bench](https://github.com/haotian-liu/LLaVA/blob/main/docs/LLaVA_Bench.md) demonstrates on-par performance between Llama 2 and Llama 1 in LLaVA's multimodal chat ability.
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
<img src="../images/llava_example_cmp.png" width="100%">
|
| 29 |
+
|
docs/LoRA.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLaVA (LoRA, Preview)
|
| 2 |
+
|
| 3 |
+
NOTE: This is a technical preview, and is not yet ready for production use. We are still running hyperparameter search for the LoRA model, and will release the final model soon. If you'd like to contribute to this, please contact us.
|
| 4 |
+
|
| 5 |
+
You need latest code base for LoRA support (instructions [here](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base))
|
| 6 |
+
|
| 7 |
+
## Demo (Web UI)
|
| 8 |
+
|
| 9 |
+
Please execute each of the 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)).
|
| 10 |
+
|
| 11 |
+
#### Launch a controller
|
| 12 |
+
```Shell
|
| 13 |
+
python -m llava.serve.controller --host 0.0.0.0 --port 10000
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
#### Launch a gradio web server.
|
| 17 |
+
```Shell
|
| 18 |
+
python -m llava.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload
|
| 19 |
+
```
|
| 20 |
+
You just launched the Gradio web interface. Now, you can open the web interface with the URL printed on the screen. You may notice that there is no model in the model list. Do not worry, as we have not launched any model worker yet. It will be automatically updated when you launch a model worker.
|
| 21 |
+
|
| 22 |
+
#### Launch a model worker
|
| 23 |
+
```Shell
|
| 24 |
+
python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path liuhaotian/llava-vicuna-7b-v1.1-lcs_558k-instruct_80k_3e-lora-preview-alpha --model-base /path/to/vicuna-v1.1
|
| 25 |
+
```
|
| 26 |
+
Wait until the process finishes loading the model and you see "Uvicorn running on ...". Now, refresh your Gradio web UI, and you will see the model you just launched in the model list.
|
| 27 |
+
|
| 28 |
+
You can launch as many workers as you want, and compare between different model checkpoints in the same Gradio interface. Please keep the `--controller` the same, and modify the `--port` and `--worker` to a different port number for each worker.
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
## Training
|
| 32 |
+
|
| 33 |
+
Please see sample training scripts for [LoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh) and [QLoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_qlora.sh).
|
| 34 |
+
|
| 35 |
+
We provide sample DeepSpeed configs, [`zero3.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3.json) is more like PyTorch FSDP, and [`zero3_offload.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3_offload.json) can further save memory consumption by offloading parameters to CPU. `zero3.json` is usually faster than `zero3_offload.json` but requires more GPU memory, therefore, we recommend trying `zero3.json` first, and if you run out of GPU memory, try `zero3_offload.json`. You can also tweak the `per_device_train_batch_size` and `gradient_accumulation_steps` in the config to save memory, and just to make sure that `per_device_train_batch_size` and `gradient_accumulation_steps` remains the same.
|
| 36 |
+
|
| 37 |
+
If you are having issues with ZeRO-3 configs, and there are enough VRAM, you may try [`zero2.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero2.json). This consumes slightly more memory than ZeRO-3, and behaves more similar to PyTorch FSDP, while still supporting parameter-efficient tuning.
|
| 38 |
+
|
| 39 |
+
## Create Merged Checkpoints
|
| 40 |
+
|
| 41 |
+
```Shell
|
| 42 |
+
python scripts/merge_lora_weights.py \
|
| 43 |
+
--model-path /path/to/lora_model \
|
| 44 |
+
--model-base /path/to/base_model \
|
| 45 |
+
--save-model-path /path/to/merge_model
|
| 46 |
+
```
|
docs/MODEL_ZOO.md
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Model Zoo
|
| 2 |
+
|
| 3 |
+
**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.**
|
| 4 |
+
|
| 5 |
+
If you are interested in including any other details in Model Zoo, please open an issue :)
|
| 6 |
+
|
| 7 |
+
The model weights below are *merged* weights. You do not need to apply delta. The usage of LLaVA checkpoints should comply with the base LLM's model license.
|
| 8 |
+
|
| 9 |
+
## LLaVA-v1.6
|
| 10 |
+
|
| 11 |
+
| 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 |
|
| 12 |
+
|----------|----------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| 13 |
+
| 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 |
|
| 14 |
+
| 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 |
|
| 15 |
+
| 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 |
|
| 16 |
+
| 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 |
|
| 17 |
+
|
| 18 |
+
*LLaVA-1.6-34B outperforms Gemini Pro on benchmarks like MMMU and MathVista.*
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
## LLaVA-v1.5
|
| 22 |
+
|
| 23 |
+
| Version | Size | Schedule | Checkpoint | VQAv2 | GQA | VizWiz | SQA | TextVQA | POPE | MME | MM-Bench | MM-Bench-CN | SEED | LLaVA-Bench-Wild | MM-Vet |
|
| 24 |
+
|----------|----------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---|
|
| 25 |
+
| 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 |
|
| 26 |
+
| 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 |
|
| 27 |
+
| 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 |
|
| 28 |
+
| 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 |
|
| 29 |
+
|
| 30 |
+
Base model: Vicuna v1.5. Training logs: [wandb](https://api.wandb.ai/links/lht/6orh56wc).
|
| 31 |
+
|
| 32 |
+
<p align="center">
|
| 33 |
+
<img src="../images/llava_v1_5_radar.jpg" width="500px"> <br>
|
| 34 |
+
LLaVA-1.5 achieves SoTA performance across 11 benchmarks.
|
| 35 |
+
</p>
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
## LLaVA-v1
|
| 39 |
+
|
| 40 |
+
*Note: We recommend using the most capable LLaVA-v1.6 series above for the best performance.*
|
| 41 |
+
|
| 42 |
+
| 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 |
|
| 43 |
+
|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|--------------------|---------------------|---------------------|---------------------|
|
| 44 |
+
| 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) |
|
| 45 |
+
| 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) |
|
| 46 |
+
| 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) |
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
## Projector weights
|
| 50 |
+
|
| 51 |
+
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).
|
| 52 |
+
|
| 53 |
+
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.
|
| 54 |
+
|
| 55 |
+
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.
|
| 56 |
+
|
| 57 |
+
When using these projector weights to instruction-tune your LMM, please make sure that these options are correctly set as follows,
|
| 58 |
+
|
| 59 |
+
```Shell
|
| 60 |
+
--mm_use_im_start_end False
|
| 61 |
+
--mm_use_im_patch_token False
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
| Base LLM | Vision Encoder | Projection | Pretrain Data | Pretraining schedule | Download |
|
| 65 |
+
|----------|----------------|---------------|----------------------|----------|----------|
|
| 66 |
+
| 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) |
|
| 67 |
+
| 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) |
|
| 68 |
+
| LLaMA-2-13B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-13b-chat) |
|
| 69 |
+
| LLaMA-2-7B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-7b-chat) |
|
| 70 |
+
| LLaMA-2-13B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-13b-chat) |
|
| 71 |
+
| LLaMA-2-7B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-7b-chat) |
|
| 72 |
+
| Vicuna-13B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-13b-v1.3) |
|
| 73 |
+
| Vicuna-7B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-7b-v1.3) |
|
| 74 |
+
| Vicuna-13B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-13b-v1.3) |
|
| 75 |
+
| Vicuna-7B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-7b-v1.3) |
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
## Science QA Checkpoints
|
| 79 |
+
|
| 80 |
+
| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
|
| 81 |
+
|----------|----------------|---------------|----------------------|-----------------|--------------------|---------------------|
|
| 82 |
+
| 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) |
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
## Legacy Models (merged weights)
|
| 86 |
+
|
| 87 |
+
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.
|
| 88 |
+
|
| 89 |
+
| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
|
| 90 |
+
|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|
|
| 91 |
+
| MPT-7B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | [preview](https://huggingface.co/liuhaotian/LLaVA-Lightning-MPT-7B-preview) |
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
## Legacy Models (delta weights)
|
| 95 |
+
|
| 96 |
+
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).
|
| 97 |
+
|
| 98 |
+
You can add our delta to the original LLaMA weights to obtain the LLaVA weights.
|
| 99 |
+
|
| 100 |
+
Instructions:
|
| 101 |
+
|
| 102 |
+
1. Get the original LLaMA weights in the huggingface format by following the instructions [here](https://huggingface.co/docs/transformers/main/model_doc/llama).
|
| 103 |
+
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).
|
| 104 |
+
|
| 105 |
+
```bash
|
| 106 |
+
python3 -m llava.model.apply_delta \
|
| 107 |
+
--base /path/to/llama-7b \
|
| 108 |
+
--target /output/path/to/LLaVA-7B-v0 \
|
| 109 |
+
--delta liuhaotian/LLaVA-7b-delta-v0
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
|
| 113 |
+
|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|
|
| 114 |
+
| 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) |
|
| 115 |
+
| 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) |
|
| 116 |
+
| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0) |
|
| 117 |
+
| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | ScienceQA | full_ft-12e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0-science_qa) |
|
| 118 |
+
| Vicuna-7B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-7b-delta-v0) |
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
## Legacy Projector weights
|
| 123 |
+
|
| 124 |
+
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.
|
| 125 |
+
|
| 126 |
+
**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.
|
| 127 |
+
|
| 128 |
+
When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows,
|
| 129 |
+
|
| 130 |
+
```Shell
|
| 131 |
+
--mm_use_im_start_end True
|
| 132 |
+
--mm_use_im_patch_token False
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download |
|
| 136 |
+
|----------|----------------|---------------|----------------------|----------|
|
| 137 |
+
| 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) |
|
| 138 |
+
| 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) |
|
| 139 |
+
| 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) |
|
| 140 |
+
|
| 141 |
+
When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows,
|
| 142 |
+
|
| 143 |
+
```Shell
|
| 144 |
+
--mm_use_im_start_end False
|
| 145 |
+
--mm_use_im_patch_token False
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download |
|
| 149 |
+
|----------|----------------|---------------|----------------------|----------|
|
| 150 |
+
| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-13b-pretrain-projector-v0-CC3M-595K-original_caption-no_im_token.bin) |
|
docs/ScienceQA.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
### ScienceQA
|
| 2 |
+
|
| 3 |
+
#### Prepare Data
|
| 4 |
+
1. Please see ScienceQA [repo](https://github.com/lupantech/ScienceQA) for setting up the dataset.
|
| 5 |
+
2. Generate ScienceQA dataset for LLaVA conversation-style format.
|
| 6 |
+
|
| 7 |
+
```Shell
|
| 8 |
+
python scripts/convert_sqa_to_llava.py \
|
| 9 |
+
convert_to_llava \
|
| 10 |
+
--base-dir /path/to/ScienceQA/data/scienceqa \
|
| 11 |
+
--prompt-format "QCM-LEA" \
|
| 12 |
+
--split {train,val,minival,test,minitest}
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
#### Training
|
| 16 |
+
|
| 17 |
+
1. Pretraining
|
| 18 |
+
|
| 19 |
+
You can download our pretrained projector weights from our [Model Zoo](), or train your own projector weights using [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain.sh).
|
| 20 |
+
|
| 21 |
+
2. Finetuning
|
| 22 |
+
|
| 23 |
+
See [`finetune_sqa.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_sqa.sh).
|
| 24 |
+
|
| 25 |
+
#### Evaluation
|
| 26 |
+
|
| 27 |
+
1. Multiple-GPU inference
|
| 28 |
+
You may evaluate this with multiple GPUs, and concatenate the generated jsonl files. Please refer to our script for [batch evaluation](https://github.com/haotian-liu/LLaVA/blob/main/scripts/sqa_eval_batch.sh) and [results gathering](https://github.com/haotian-liu/LLaVA/blob/main/scripts/sqa_eval_gather.sh).
|
| 29 |
+
|
| 30 |
+
2. Single-GPU inference
|
| 31 |
+
|
| 32 |
+
(a) Generate LLaVA responses on ScienceQA dataset
|
| 33 |
+
|
| 34 |
+
```Shell
|
| 35 |
+
python -m llava.eval.model_vqa_science \
|
| 36 |
+
--model-path liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3 \
|
| 37 |
+
--question-file /path/to/ScienceQA/data/scienceqa/llava_test_QCM-LEA.json \
|
| 38 |
+
--image-folder /path/to/ScienceQA/data/scienceqa/images/test \
|
| 39 |
+
--answers-file vqa/results/ScienceQA/test_llava-13b.jsonl \
|
| 40 |
+
--conv-mode llava_v1
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
(b) Evaluate the generated responses
|
| 44 |
+
|
| 45 |
+
```Shell
|
| 46 |
+
python eval_science_qa.py \
|
| 47 |
+
--base-dir /path/to/ScienceQA/data/scienceqa \
|
| 48 |
+
--result-file vqa/results/ScienceQA/test_llava-13b.jsonl \
|
| 49 |
+
--output-file vqa/results/ScienceQA/test_llava-13b_output.json \
|
| 50 |
+
--output-result vqa/results/ScienceQA/test_llava-13b_result.json \
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
For reference, we attach our prediction file [`test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/table/results/test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json) and [`test_sqa_llava_13b_v0.json`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/table/results/test_sqa_llava_13b_v0.json) for comparison when reproducing our results, as well as for further analysis in detail.
|
docs/Windows.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Run LLaVA on Windows
|
| 2 |
+
|
| 3 |
+
*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.*
|
| 4 |
+
|
| 5 |
+
## Installation
|
| 6 |
+
|
| 7 |
+
1. Clone this repository and navigate to LLaVA folder
|
| 8 |
+
```bash
|
| 9 |
+
git clone https://github.com/haotian-liu/LLaVA.git
|
| 10 |
+
cd LLaVA
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
2. Install Package
|
| 14 |
+
```Shell
|
| 15 |
+
conda create -n llava python=3.10 -y
|
| 16 |
+
conda activate llava
|
| 17 |
+
python -m pip install --upgrade pip # enable PEP 660 support
|
| 18 |
+
pip install torch==2.0.1+cu117 torchvision==0.15.2+cu117 torchaudio==2.0.2 --index-url https://download.pytorch.org/whl/cu117
|
| 19 |
+
pip install -e .
|
| 20 |
+
pip uninstall bitsandbytes
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
## Run demo
|
| 24 |
+
|
| 25 |
+
See instructions [here](https://github.com/haotian-liu/LLaVA#demo).
|
| 26 |
+
|
| 27 |
+
Note that quantization (4-bit, 8-bit) is *NOT* supported on Windows. Stay tuned for the 4-bit support on Windows!
|
docs/macOS.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Run LLaVA on macOS
|
| 2 |
+
|
| 3 |
+
*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.*
|
| 4 |
+
|
| 5 |
+
## Installation
|
| 6 |
+
|
| 7 |
+
1. Clone this repository and navigate to LLaVA folder
|
| 8 |
+
```bash
|
| 9 |
+
git clone https://github.com/haotian-liu/LLaVA.git
|
| 10 |
+
cd LLaVA
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
2. Install Package
|
| 14 |
+
```Shell
|
| 15 |
+
conda create -n llava python=3.10 -y
|
| 16 |
+
conda activate llava
|
| 17 |
+
python -mpip install --upgrade pip # enable PEP 660 support
|
| 18 |
+
pip install -e .
|
| 19 |
+
pip install torch==2.1.0 torchvision==0.16.0
|
| 20 |
+
pip uninstall bitsandbytes
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
## Run demo
|
| 24 |
+
|
| 25 |
+
Specify `--device mps` when launching model worker or CLI.
|
| 26 |
+
|
| 27 |
+
See instructions [here](https://github.com/haotian-liu/LLaVA#demo).
|
| 28 |
+
|
| 29 |
+
Note that quantization (4-bit, 8-bit) is *NOT* supported on macOS. Stay tuned for the 4-bit support on macOS!
|
eval.sh
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
source /home/aiops/wangzh/miniconda3/bin/activate
|
| 2 |
+
conda activate llava
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0 python -m rgbd_eval.py
|
| 4 |
+
python new_check.py
|
finetune.sh
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
deepspeed llava/train/train_mem.py \
|
| 4 |
+
--deepspeed ./scripts/zero2.json \
|
| 5 |
+
--lora_enable True --lora_r 128 --lora_alpha 256 --mm_projector_lr 2e-5 \
|
| 6 |
+
--model_name_or_path /home/aiops/wangzh/llava/vicuna-7b-v1.5 \
|
| 7 |
+
--version v1 \
|
| 8 |
+
--data_path /home/aiops/wangzh/llava/playground/data/llava_v1_5_mix665k.json \
|
| 9 |
+
--image_folder /home/aiops/wangzh/llava/playground/data \
|
| 10 |
+
--vision_tower openai/clip-vit-large-patch14-336 \
|
| 11 |
+
--pretrain_mm_mlp_adapter ./checkpoints/llava-v1.5-7b-pretrain-negfinal/mm_projector.bin \
|
| 12 |
+
--mm_projector_type mlp2x_gelu \
|
| 13 |
+
--mm_vision_select_layer -2 \
|
| 14 |
+
--mm_use_im_start_end False \
|
| 15 |
+
--mm_use_im_patch_token False \
|
| 16 |
+
--image_aspect_ratio pad \
|
| 17 |
+
--group_by_modality_length True \
|
| 18 |
+
--bf16 True \
|
| 19 |
+
--output_dir ./checkpoints/llava-v1.5-7b-final-neg-lora-newl \
|
| 20 |
+
--num_train_epochs 1 \
|
| 21 |
+
--per_device_train_batch_size 16\
|
| 22 |
+
--per_device_eval_batch_size 8 \
|
| 23 |
+
--gradient_accumulation_steps 1 \
|
| 24 |
+
--evaluation_strategy "no" \
|
| 25 |
+
--save_strategy "steps" \
|
| 26 |
+
--save_steps 10 \
|
| 27 |
+
--save_total_limit 1 \
|
| 28 |
+
--learning_rate 2e-4 \
|
| 29 |
+
--weight_decay 0. \
|
| 30 |
+
--warmup_ratio 0.03 \
|
| 31 |
+
--lr_scheduler_type "cosine" \
|
| 32 |
+
--logging_steps 1 \
|
| 33 |
+
--tf32 True \
|
| 34 |
+
--model_max_length 2048 \
|
| 35 |
+
--gradient_checkpointing True \
|
| 36 |
+
--dataloader_num_workers 4 \
|
| 37 |
+
--lazy_preprocess True \
|
| 38 |
+
--report_to wandb
|