Add files using upload-large-folder tool
Browse files- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/Dockerfile +76 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/Dockerfile.legacy +72 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/LICENSE +201 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/init +1 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/pyproject.toml +39 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/init +1 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava.egg-info/PKG-INFO +299 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava.egg-info/SOURCES.txt +175 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava.egg-info/dependency_links.txt +1 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava.egg-info/requires.txt +41 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava.egg-info/top_level.txt +3 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/__init__.py +0 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/cli.py +111 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/controller.py +287 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/gradio_multi_image.py +448 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/gradio_web_server.py +442 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/model_worker.py +271 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/register_worker.py +26 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/sglang_worker.py +237 -0
- 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/test_message.py +59 -0
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/Dockerfile
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10)
|
| 2 |
+
# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html
|
| 3 |
+
FROM nvcr.io/nvidia/pytorch:24.08-py3
|
| 4 |
+
|
| 5 |
+
# Define environments
|
| 6 |
+
ENV MAX_JOBS=32
|
| 7 |
+
ENV VLLM_WORKER_MULTIPROC_METHOD=spawn
|
| 8 |
+
ENV DEBIAN_FRONTEND=noninteractive
|
| 9 |
+
ENV NODE_OPTIONS=""
|
| 10 |
+
ENV PIP_ROOT_USER_ACTION=ignore
|
| 11 |
+
ENV HF_HUB_ENABLE_HF_TRANSFER="1"
|
| 12 |
+
|
| 13 |
+
# Define installation arguments
|
| 14 |
+
ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/
|
| 15 |
+
ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
|
| 16 |
+
|
| 17 |
+
# Set apt source
|
| 18 |
+
RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \
|
| 19 |
+
{ \
|
| 20 |
+
echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \
|
| 21 |
+
echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \
|
| 22 |
+
echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \
|
| 23 |
+
echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \
|
| 24 |
+
} > /etc/apt/sources.list
|
| 25 |
+
|
| 26 |
+
# Install systemctl
|
| 27 |
+
RUN apt-get update && \
|
| 28 |
+
apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \
|
| 29 |
+
apt-get clean
|
| 30 |
+
|
| 31 |
+
# Install tini
|
| 32 |
+
RUN apt-get update && \
|
| 33 |
+
apt-get install -y tini && \
|
| 34 |
+
apt-get clean
|
| 35 |
+
|
| 36 |
+
# Change pip source
|
| 37 |
+
RUN pip config set global.index-url "${PIP_INDEX}" && \
|
| 38 |
+
pip config set global.extra-index-url "${PIP_INDEX}" && \
|
| 39 |
+
python -m pip install --upgrade pip
|
| 40 |
+
|
| 41 |
+
# Uninstall nv-pytorch fork
|
| 42 |
+
RUN pip uninstall -y torch torchvision torchaudio \
|
| 43 |
+
pytorch-quantization pytorch-triton torch-tensorrt \
|
| 44 |
+
transformer_engine flash_attn apex megatron-core \
|
| 45 |
+
xgboost opencv grpcio
|
| 46 |
+
|
| 47 |
+
# Fix cv2
|
| 48 |
+
RUN rm -rf /usr/local/lib/python3.10/dist-packages/cv2
|
| 49 |
+
|
| 50 |
+
# Install torch-2.6.0+cu124 + vllm-0.8.4
|
| 51 |
+
# torch-2.6.0+cu124: cxx11abi=False
|
| 52 |
+
# torch-2.6.0+cu126: cxx11abi=True
|
| 53 |
+
# see https://github.com/flashinfer-ai/flashinfer/issues/911
|
| 54 |
+
RUN pip install --no-cache-dir "vllm==0.8.4" "torch==2.6.0" "torchvision==0.21.0" "torchaudio==2.6.0" tensordict torchdata \
|
| 55 |
+
"transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \
|
| 56 |
+
"numpy<2.0.0" "pyarrow>=15.0.0" pandas \
|
| 57 |
+
ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb liger-kernel mathruler \
|
| 58 |
+
pytest yapf py-spy pyext pre-commit ruff
|
| 59 |
+
|
| 60 |
+
# Install flash-attn-2.7.4.post1 (cxx11abi=False)
|
| 61 |
+
RUN wget -nv https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl && \
|
| 62 |
+
pip install --no-cache-dir flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
|
| 63 |
+
|
| 64 |
+
# Install flashinfer-0.2.2.post1+cu124 (cxx11abi=False)
|
| 65 |
+
# vllm-0.8.3 does not support flashinfer>=0.2.3
|
| 66 |
+
# see https://github.com/vllm-project/vllm/pull/15777
|
| 67 |
+
RUN wget -nv https://github.com/flashinfer-ai/flashinfer/releases/download/v0.2.2.post1/flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl && \
|
| 68 |
+
pip install --no-cache-dir flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl
|
| 69 |
+
|
| 70 |
+
# Fix packages
|
| 71 |
+
RUN pip uninstall -y pynvml nvidia-ml-py && \
|
| 72 |
+
pip install --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1"
|
| 73 |
+
|
| 74 |
+
# Reset pip config
|
| 75 |
+
RUN pip config unset global.index-url && \
|
| 76 |
+
pip config unset global.extra-index-url
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/Dockerfile.legacy
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10)
|
| 2 |
+
# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html
|
| 3 |
+
FROM nvcr.io/nvidia/pytorch:24.08-py3
|
| 4 |
+
|
| 5 |
+
# Define environments
|
| 6 |
+
ENV MAX_JOBS=32
|
| 7 |
+
ENV VLLM_WORKER_MULTIPROC_METHOD=spawn
|
| 8 |
+
ENV DEBIAN_FRONTEND=noninteractive
|
| 9 |
+
ENV NODE_OPTIONS=""
|
| 10 |
+
ENV PIP_ROOT_USER_ACTION=ignore
|
| 11 |
+
ENV HF_HUB_ENABLE_HF_TRANSFER="1"
|
| 12 |
+
|
| 13 |
+
# Define installation arguments
|
| 14 |
+
ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/
|
| 15 |
+
ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
|
| 16 |
+
ARG VLLM_COMMIT=227578480d71fc94ef46ca77fb69496412158d68
|
| 17 |
+
|
| 18 |
+
# Set apt source
|
| 19 |
+
RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \
|
| 20 |
+
{ \
|
| 21 |
+
echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \
|
| 22 |
+
echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \
|
| 23 |
+
echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \
|
| 24 |
+
echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \
|
| 25 |
+
} > /etc/apt/sources.list
|
| 26 |
+
|
| 27 |
+
# Install systemctl
|
| 28 |
+
RUN apt-get update && \
|
| 29 |
+
apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \
|
| 30 |
+
apt-get clean
|
| 31 |
+
|
| 32 |
+
# Install tini
|
| 33 |
+
RUN apt-get update && \
|
| 34 |
+
apt-get install -y tini && \
|
| 35 |
+
apt-get clean
|
| 36 |
+
|
| 37 |
+
# Change pip source
|
| 38 |
+
RUN pip config set global.index-url "${PIP_INDEX}" && \
|
| 39 |
+
pip config set global.extra-index-url "${PIP_INDEX}" && \
|
| 40 |
+
python -m pip install --upgrade pip
|
| 41 |
+
|
| 42 |
+
# Uninstall nv-pytorch fork
|
| 43 |
+
RUN pip uninstall -y torch torchvision torchaudio \
|
| 44 |
+
pytorch-quantization pytorch-triton torch-tensorrt \
|
| 45 |
+
transformer_engine flash_attn apex megatron-core \
|
| 46 |
+
xgboost opencv grpcio
|
| 47 |
+
|
| 48 |
+
# Fix cv2
|
| 49 |
+
RUN rm -rf /usr/local/lib/python3.10/dist-packages/cv2
|
| 50 |
+
|
| 51 |
+
# Install vllm-0.7.4-nightly
|
| 52 |
+
RUN pip install --no-cache-dir vllm --pre --extra-index-url "https://wheels.vllm.ai/${VLLM_COMMIT}" && \
|
| 53 |
+
git clone -b verl_v1 https://github.com/hiyouga/vllm.git && \
|
| 54 |
+
cp -r vllm/vllm/ /usr/local/lib/python3.10/dist-packages/
|
| 55 |
+
|
| 56 |
+
# Install torch-2.5.1
|
| 57 |
+
RUN pip install --no-cache-dir "torch==2.5.1" "torchvision==0.20.1" "torchaudio==2.5.1" tensordict torchdata \
|
| 58 |
+
"transformers>=4.49.0" accelerate datasets peft hf-transfer \
|
| 59 |
+
ray[default] codetiming hydra-core pandas "pyarrow>=15.0.0" pylatexenc qwen-vl-utils wandb liger-kernel mathruler \
|
| 60 |
+
pytest yapf py-spy pyext pre-commit ruff
|
| 61 |
+
|
| 62 |
+
# Install flash_attn-2.7.4.post1
|
| 63 |
+
RUN wget -nv https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.5cxx11abiFALSE-cp310-cp310-linux_x86_64.whl && \
|
| 64 |
+
pip install --no-cache-dir flash_attn-2.7.4.post1+cu12torch2.5cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
|
| 65 |
+
|
| 66 |
+
# Fix packages
|
| 67 |
+
RUN pip uninstall -y pynvml nvidia-ml-py && \
|
| 68 |
+
pip install --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1"
|
| 69 |
+
|
| 70 |
+
# Reset pip config
|
| 71 |
+
RUN pip config unset global.index-url && \
|
| 72 |
+
pip config unset global.extra-index-url
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/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.
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/init
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/pyproject.toml
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=61.0"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "verl"
|
| 7 |
+
dynamic = [
|
| 8 |
+
"version",
|
| 9 |
+
"dependencies",
|
| 10 |
+
"optional-dependencies",
|
| 11 |
+
"requires-python",
|
| 12 |
+
"authors",
|
| 13 |
+
"description",
|
| 14 |
+
"readme",
|
| 15 |
+
"license"
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
[tool.ruff]
|
| 19 |
+
target-version = "py39"
|
| 20 |
+
line-length = 119
|
| 21 |
+
indent-width = 4
|
| 22 |
+
|
| 23 |
+
[tool.ruff.lint]
|
| 24 |
+
ignore = ["C901", "E501", "E741", "W605", "C408"]
|
| 25 |
+
select = ["C", "E", "F", "I", "W", "RUF022"]
|
| 26 |
+
|
| 27 |
+
[tool.ruff.lint.per-file-ignores]
|
| 28 |
+
"__init__.py" = ["E402", "F401", "F403", "F811"]
|
| 29 |
+
|
| 30 |
+
[tool.ruff.lint.isort]
|
| 31 |
+
lines-after-imports = 2
|
| 32 |
+
known-first-party = ["verl"]
|
| 33 |
+
known-third-party = ["torch", "transformers", "wandb"]
|
| 34 |
+
|
| 35 |
+
[tool.ruff.format]
|
| 36 |
+
quote-style = "double"
|
| 37 |
+
indent-style = "space"
|
| 38 |
+
skip-magic-trailing-comma = false
|
| 39 |
+
line-ending = "auto"
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava-critic-r1/init
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava.egg-info/PKG-INFO
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: llava
|
| 3 |
+
Version: 1.7.0.dev0
|
| 4 |
+
Summary: LLaVA OneVision: The Next Generation of LLaVA with Better Image and Video Understanding Capabilities
|
| 5 |
+
Project-URL: Homepage, https://llava-vl.github.io
|
| 6 |
+
Project-URL: Bug Tracker, https://github.com/haotian-liu/LLaVA/issues
|
| 7 |
+
Classifier: Programming Language :: Python :: 3
|
| 8 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
| 9 |
+
Requires-Python: >=3.8
|
| 10 |
+
Description-Content-Type: text/markdown
|
| 11 |
+
License-File: LICENSE
|
| 12 |
+
Provides-Extra: standalone
|
| 13 |
+
Requires-Dist: shortuuid; extra == "standalone"
|
| 14 |
+
Requires-Dist: httpx==0.24.0; extra == "standalone"
|
| 15 |
+
Requires-Dist: einops; extra == "standalone"
|
| 16 |
+
Requires-Dist: ftfy; extra == "standalone"
|
| 17 |
+
Provides-Extra: train
|
| 18 |
+
Requires-Dist: llava[standalone]; extra == "train"
|
| 19 |
+
Requires-Dist: numpy==1.26.1; extra == "train"
|
| 20 |
+
Requires-Dist: open_clip_torch; extra == "train"
|
| 21 |
+
Requires-Dist: fastapi; extra == "train"
|
| 22 |
+
Requires-Dist: markdown2[all]; extra == "train"
|
| 23 |
+
Requires-Dist: numpy; extra == "train"
|
| 24 |
+
Requires-Dist: requests; extra == "train"
|
| 25 |
+
Requires-Dist: sentencepiece; extra == "train"
|
| 26 |
+
Requires-Dist: torch==2.1.2; extra == "train"
|
| 27 |
+
Requires-Dist: torchvision==0.16.2; extra == "train"
|
| 28 |
+
Requires-Dist: uvicorn; extra == "train"
|
| 29 |
+
Requires-Dist: wandb; extra == "train"
|
| 30 |
+
Requires-Dist: deepspeed==0.14.4; extra == "train"
|
| 31 |
+
Requires-Dist: peft==0.4.0; extra == "train"
|
| 32 |
+
Requires-Dist: accelerate>=0.29.1; extra == "train"
|
| 33 |
+
Requires-Dist: tokenizers~=0.15.2; extra == "train"
|
| 34 |
+
Requires-Dist: transformers @ git+https://github.com/huggingface/transformers.git@1c39974a4c4036fd641bc1191cc32799f85715a4 ; extra == "train"
|
| 35 |
+
Requires-Dist: bitsandbytes==0.41.0; extra == "train"
|
| 36 |
+
Requires-Dist: scikit-learn==1.2.2; extra == "train"
|
| 37 |
+
Requires-Dist: sentencepiece~=0.1.99; extra == "train"
|
| 38 |
+
Requires-Dist: einops==0.6.1; extra == "train"
|
| 39 |
+
Requires-Dist: einops-exts==0.0.4; extra == "train"
|
| 40 |
+
Requires-Dist: gradio_client==0.2.9; extra == "train"
|
| 41 |
+
Requires-Dist: urllib3<=2.0.0; extra == "train"
|
| 42 |
+
Requires-Dist: datasets==2.16.1; extra == "train"
|
| 43 |
+
Requires-Dist: pydantic==1.10.8; extra == "train"
|
| 44 |
+
Requires-Dist: timm; extra == "train"
|
| 45 |
+
Requires-Dist: hf_transfer; extra == "train"
|
| 46 |
+
Requires-Dist: opencv-python; extra == "train"
|
| 47 |
+
Requires-Dist: av; extra == "train"
|
| 48 |
+
Requires-Dist: decord; extra == "train"
|
| 49 |
+
Requires-Dist: tyro; extra == "train"
|
| 50 |
+
Requires-Dist: scipy; extra == "train"
|
| 51 |
+
Dynamic: license-file
|
| 52 |
+
|
| 53 |
+
<p align="center" width="100%">
|
| 54 |
+
<img src="https://i.postimg.cc/pL17YtG4/WX20240508-220230-2x.png" width="80%" height="80%">
|
| 55 |
+
</p>
|
| 56 |
+
|
| 57 |
+
# LLaVA-NeXT: Open Large Multimodal Models
|
| 58 |
+
[](http://arxiv.org/abs/2410.02713)
|
| 59 |
+
[](https://arxiv.org/abs/2408.03326)
|
| 60 |
+
[](https://llava-vl.github.io/blog/)
|
| 61 |
+
|
| 62 |
+
[](https://llava-onevision.lmms-lab.com/)
|
| 63 |
+
[](https://huggingface.co/spaces/WildVision/vision-arena)
|
| 64 |
+
[](https://huggingface.co/spaces/lmms-lab/LLaVA-NeXT-Interleave-Demo)
|
| 65 |
+
[](https://openbayes.com/console/public/tutorials/gW0ng9jKXfO)
|
| 66 |
+
|
| 67 |
+
[](https://huggingface.co/collections/lmms-lab/llava-next-video-661e86f5e8dabc3ff793c944)
|
| 68 |
+
[](https://huggingface.co/collections/lmms-lab/llava-onevision-66a259c3526e15166d6bba37)
|
| 69 |
+
[](https://huggingface.co/collections/lmms-lab/llava-next-interleave-66763c55c411b340b35873d1)
|
| 70 |
+
[](https://huggingface.co/lmms-lab)
|
| 71 |
+
|
| 72 |
+
## Release Notes
|
| 73 |
+
- **[2025/08/29] 🔥 LLaVA-Critic-R1** We release LLaVA-Critic-R1, a family of generative critic VLM trained through GRPO using pairwise critic data. LLaVA-Critic-R1 not only demonstrates strong critic capability, but also achieves state-of-the-art policy performance at the 7B scale. Refer to [LLaVA-Critic-R1](llava-critic-r1/EasyR1/README.md) for more training details.
|
| 74 |
+
|
| 75 |
+
📄 **Explore more**:
|
| 76 |
+
- [LLaVA-Critic-GRPO Dataset](https://huggingface.co/datasets/lmms-lab/LLaVA-Critic-GRPO-dataset): Download the dataset.
|
| 77 |
+
- [LLaVA-Critic-R1-7B](https://huggingface.co/lmms-lab/LLaVA-Critic-R1-7B): LLaVA-Critic-R1 trained based on Qwen-2.5-VL-7B.
|
| 78 |
+
- [LLaVA-Critic-R1-7B-Plus-Qwen](https://huggingface.co/lmms-lab/LLaVA-Critic-R1-7B-Plus-Qwen): LLaVA-Critic-R1+ trained based on ThinkLite-VL-7B.
|
| 79 |
+
- [LLaVA-Critic-R1-7B-Plus-Mimo](https://huggingface.co/lmms-lab/LLaVA-Critic-R1-7B-Plus-Mimo): LLaVA-Critic-R1+ trained based on MiMo-VL-7B-RL-2508.
|
| 80 |
+
- [LLaVA-Critic-R1-7B-Plus-LLaMA32v](https://huggingface.co/lmms-lab/LLaVA-Critic-R1-7B-LLaMA32v): LLaVA-Critic-R1+ trained based on Llama-3.2-11B-Vision-Instruct.
|
| 81 |
+
- [Paper](https://arxiv.org/abs/2509.00676): Detailed information about LLaVA-Critic-R1.
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
- **[2024/10/04] 🔥 LLaVA-Video** (formerly LLaVA-NeXT-Video) has undergone a major upgrade! We are excited to release **LLaVA-Video-178K**, a high-quality synthetic dataset for video instruction tuning. This dataset includes:
|
| 85 |
+
|
| 86 |
+
- 178,510 caption entries
|
| 87 |
+
- 960,792 open-ended Q&A pairs
|
| 88 |
+
- 196,198 multiple-choice Q&A items
|
| 89 |
+
|
| 90 |
+
Along with this, we’re also releasing the **LLaVA-Video 7B/72B models**, which deliver competitive performance on the latest video benchmarks, including [Video-MME](https://video-mme.github.io/home_page.html#leaderboard), [LongVideoBench](https://longvideobench.github.io/), and [Dream-1K](https://tarsier-vlm.github.io/).
|
| 91 |
+
|
| 92 |
+
📄 **Explore more**:
|
| 93 |
+
- [LLaVA-Video-178K Dataset](https://huggingface.co/datasets/lmms-lab/LLaVA-Video-178K): Download the dataset.
|
| 94 |
+
- [LLaVA-Video Models](https://huggingface.co/collections/lmms-lab/llava-video-661e86f5e8dabc3ff793c944): Access model checkpoints.
|
| 95 |
+
- [Paper](http://arxiv.org/abs/2410.02713): Detailed information about LLaVA-Video.
|
| 96 |
+
- [LLaVA-Video Documentation](https://github.com/LLaVA-VL/LLaVA-NeXT/blob/main/docs/LLaVA_Video_1003.md): Guidance on training, inference and evaluation.
|
| 97 |
+
|
| 98 |
+
- [2024/09/13] 🔥 **🚀 [LLaVA-OneVision-Chat](docs/LLaVA_OneVision_Chat.md)**. The new LLaVA-OV-Chat (7B/72B) significantly improves the chat experience of LLaVA-OV. 📄
|
| 99 |
+
|
| 100 |
+

|
| 101 |
+
|
| 102 |
+
- [2024/08/06] 🔥 **🚀 [LLaVA-OneVision (OV)](https://llava-vl.github.io/blog/2024-08-05-llava-onevision/)!** The new LLaVA-OV models (0.5B/7B/72B) achieve new state-of-the-art performance across single-image, multi-image, and video benchmarks, sometimes rivaling top commercial models on 47 diverse benchmarks. 📄 Explore More:
|
| 103 |
+
* [[Paper]](https://arxiv.org/abs/2408.03326): In-depth insights, new emegerging scenarios, ie, strong video understadning through task transfer from images.
|
| 104 |
+
* [[LLaVA-OV Doc]](https://github.com/LLaVA-VL/LLaVA-NeXT/blob/main/docs/LLaVA_OneVision.md): Model inference and evaluation guidance.
|
| 105 |
+
* [[Scripts]](https://github.com/LLaVA-VL/LLaVA-NeXT/blob/main/scripts/train): Start training models on your single-image/multi-image/video data.
|
| 106 |
+
|
| 107 |
+
- [2024/07/16] 🔥 **LLaVA-NeXT-Video** has been upgraded. The new 32B model achieves the best open-source performance on several video benchmarks, including [Video-MME](https://video-mme.github.io/home_page.html#leaderboard). Please refer to [this page](docs/LLaVA-NeXT-Video_0716.md) for details, refer to [llava_next-video_demo](https://huggingface.co/spaces/WildVision/vision-arena) for demo.
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
- [2024/06/23] 🔥 **LLaVA-NeXT-Interleave** is released. We utilize image-text interleaved format to unify multi-image, video, and 3D tasks in one LLM and achieve **SoTA** performance on a wide range of benchmarks. Check out [paper](https://arxiv.org/pdf/2407.07895), [blog](https://llava-vl.github.io/blog/2024-06-16-llava-next-interleave/), and [checkpoints](https://huggingface.co/collections/lmms-lab/llava-next-interleave-66763c55c411b340b35873d1) to see new capabilities and improved performance! We have released 0.5b, 7b, and 7b-dpo models.
|
| 111 |
+
* An all-round LLM for multi-image, video, and 3D with strong performance \[[demo](https://huggingface.co/spaces/lmms-lab/LLaVA-NeXT-Interleave-Demo)\]
|
| 112 |
+
* Construct interleave training data [**M4-Instruct**](https://huggingface.co/datasets/lmms-lab/M4-Instruct-Data)
|
| 113 |
+
* Construct multi-image benchmark [**LLaVA-Interleave Bench**](https://huggingface.co/datasets/lmms-lab/LLaVA-NeXT-Interleave-Bench)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
- [2024/05/25] 🔥 Wondering "[What Else Influences Visual Instruction Tuning Beyond Data?](https://llava-vl.github.io/blog/2024-05-25-llava-next-ablations/)" Our new [blog](https://llava-vl.github.io/blog/2024-05-25-llava-next-ablations/) summarizes empirical explorations to ablate the various design choices in improving LMMs except instruct data itself. Meanwhile, open-source the recapioned high-quality data using LLaVA-NeXT-34B on [[COCO]](https://huggingface.co/datasets/lmms-lab/LLaVA-ReCap-118K) [[LCS]](https://huggingface.co/datasets/lmms-lab/LLaVA-ReCap-558K) [[CC3M]](https://huggingface.co/datasets/lmms-lab/LLaVA-ReCap-CC3M).
|
| 117 |
+
* Architectures (LMM & Vision Encoder)
|
| 118 |
+
* Visual Representations (Resolution & # Tokens)
|
| 119 |
+
* Training Strategies (High-quality data & Trainable modules)
|
| 120 |
+
|
| 121 |
+
- [2024/05/10] 🔥 **LLaVA-NeXT** (Stronger) models are released, with support of stronger LMM inlcuding LLama-3 (8B) and Qwen-1.5 (72B/110B) Check out [[blog](https://llava-vl.github.io/blog/2024-05-10-llava-next-stronger-llms/)] and [[checkpoints](https://huggingface.co/lmms-lab)] to see improved performance!
|
| 122 |
+
- [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)] and [[sglang](https://github.com/sgl-project/sglang)]
|
| 123 |
+
- [2024/01/30] 🔥 **LLaVA-NeXT** 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.
|
| 124 |
+
<details>
|
| 125 |
+
<summary>More</summary>
|
| 126 |
+
|
| 127 |
+
- [2024/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)]
|
| 128 |
+
|
| 129 |
+
- [2023/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)]
|
| 130 |
+
- [2023/11/02] [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)]
|
| 131 |
+
- [2023/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.
|
| 132 |
+
- [2023/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)]
|
| 133 |
+
- [2023/10/05] 🔥 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)!
|
| 134 |
+
- [2023/09/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/)
|
| 135 |
+
- [2023/09/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**.
|
| 136 |
+
- [2023/11/06] Support **Intel** dGPU and CPU platforms. [More details here.](https://github.com/haotian-liu/LLaVA/tree/intel/docs/intel)
|
| 137 |
+
- [2023/10/12] LLaVA is now supported in [llama.cpp](https://github.com/ggerganov/llama.cpp/pull/3436) with 4-bit / 5-bit quantization support!
|
| 138 |
+
- [2023/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)!
|
| 139 |
+
- [2023/10/10] [Roboflow Deep Dive](https://blog.roboflow.com/first-impressions-with-llava-1-5/): First Impressions with LLaVA-1.5.
|
| 140 |
+
- [2023/09/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)
|
| 141 |
+
<p align="center">
|
| 142 |
+
<img src="https://github.com/Computer-Vision-in-the-Wild/CVinW_Readings/blob/main/images/mfm_evolution.jpeg?raw=true" width=50%/>
|
| 143 |
+
</p>
|
| 144 |
+
|
| 145 |
+
- [2023/07/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)!
|
| 146 |
+
- [2023/06/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/)].
|
| 147 |
+
- [2023/06/11] We released the preview for the most requested feature: DeepSpeed and LoRA support! Please see documentations [here](./docs/LoRA.md).
|
| 148 |
+
- [2023/06/01] 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).
|
| 149 |
+
- [2023/05/06] 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.
|
| 150 |
+
- [2023/05/02] 🔥 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.
|
| 151 |
+
- [2023/04/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).
|
| 152 |
+
- [2023/04/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/).
|
| 153 |
+
|
| 154 |
+
</details>
|
| 155 |
+
|
| 156 |
+
<!-- <a href="https://llava.hliu.cc/"><img src="assets/demo.gif" width="70%"></a> -->
|
| 157 |
+
|
| 158 |
+
**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-1/2 community license](https://ai.meta.com/llama/license/) for LLaMA-2 and Vicuna-v1.5, [Tongyi Qianwen RESEARCH LICENSE AGREEMENT](https://huggingface.co/Qwen/Qwen1.5-0.5B-Chat/blob/main/LICENSE) and [Llama-3 Research License](https://llama.meta.com/llama3/license/)). 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.
|
| 159 |
+
|
| 160 |
+
## Models & Scripts
|
| 161 |
+
|
| 162 |
+
### Installation
|
| 163 |
+
|
| 164 |
+
#### 1. **Clone this repository and navigate to the LLaVA folder:**
|
| 165 |
+
```bash
|
| 166 |
+
git clone https://github.com/LLaVA-VL/LLaVA-NeXT
|
| 167 |
+
cd LLaVA-NeXT
|
| 168 |
+
```
|
| 169 |
+
|
| 170 |
+
#### 2. **Install the inference package:**
|
| 171 |
+
```bash
|
| 172 |
+
conda create -n llava python=3.10 -y
|
| 173 |
+
conda activate llava
|
| 174 |
+
pip install --upgrade pip # Enable PEP 660 support.
|
| 175 |
+
pip install -e ".[train]"
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
### Project Navigation
|
| 179 |
+
Please checkout the following page for more inference & evaluation details.
|
| 180 |
+
|
| 181 |
+
#### - **LLaVA-OneVision: Easy Task Transfer**
|
| 182 |
+
- [LLaVA-OneVision](https://github.com/LLaVA-VL/LLaVA-NeXT/blob/main/docs/LLaVA_OneVision.md): for demo inference. The evaluation code is in [lmms-eval](https://github.com/EvolvingLMMs-Lab/lmms-eval).
|
| 183 |
+
|
| 184 |
+
#### - **LLaVA-NeXT: Stronger LLMs Supercharge Multimodal Capabilities in the Wild**
|
| 185 |
+
- [LLaVA-NeXT-Image](./docs/LLaVA-NeXT.md): for image demo inference and evaluation of stronger LMMs using [lmms-eval](https://github.com/EvolvingLMMs-Lab/lmms-eval).
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
#### - LLaVA-NeXT: A Strong Zero-shot Video Understanding Model
|
| 189 |
+
- [LLaVA-NeXT-Video](./docs/LLaVA-NeXT-Video.md): for video inference and evaluation scripts. We recommend to use [LMMs-video](https://lmms-lab.github.io/posts/lmms-eval-0.2/) for evaluation.
|
| 190 |
+
|
| 191 |
+
#### - LLaVA-NeXT: Tackling Multi-image, Video, and 3D in Large Multimodal Models
|
| 192 |
+
- [LLaVA-NeXT-Interleave](./docs/LLaVA-NeXT-Interleave.md): for multi-image demo and evaluation scripts.
|
| 193 |
+
|
| 194 |
+
## SGLang for SpeedUp Inference and Deployment
|
| 195 |
+
|
| 196 |
+
We use [SGLang](https://github.com/sgl-project/sglang) to speed up inference and deployment of LLaVA-NeXT. You could make LLaVA-NeXT as a backend API service with SGLang.
|
| 197 |
+
|
| 198 |
+
**Prepare Environment**:
|
| 199 |
+
Following the instruction in the [sglang](https://github.com/sgl-project/sglang?tab=readme-ov-file#install)
|
| 200 |
+
|
| 201 |
+
### LLaVA-NeXT/OneVision
|
| 202 |
+
|
| 203 |
+
Checkout the HTTP Post/Get and SRT usage at [sglang/examples/runtime/llava_onevision](https://github.com/sgl-project/sglang/tree/main/examples/runtime/llava_onevision)
|
| 204 |
+
|
| 205 |
+
### LLaVA-NeXT (Video)
|
| 206 |
+
|
| 207 |
+
**Launch and Run on (K) Nodes**:
|
| 208 |
+
- Go to sglang project
|
| 209 |
+
```
|
| 210 |
+
cd PATH_TO/sglang
|
| 211 |
+
```
|
| 212 |
+
- First node:
|
| 213 |
+
```sh
|
| 214 |
+
bash examples/usage/llava_video/srt_example_llava_v.sh K 0 YOUR_VIDEO_PATH YOUR_MODEL_PATH FRAMES_PER_VIDEO
|
| 215 |
+
(e.g. bash examples/usage/llava_video/srt_example_llava_v.sh K 0 examples/usage/llava_video/videos/Q98Z4OTh8RwmDonc.mp4 lmms-lab/LLaVA-NeXT-Video-7B-DPO 16)
|
| 216 |
+
```
|
| 217 |
+
- Second node:
|
| 218 |
+
```sh
|
| 219 |
+
bash examples/usage/llava_video/srt_example_llava_v.sh K 1 YOUR_VIDEO_PATH YOUR_MODEL_PATH FRAMES_PER_VIDEO
|
| 220 |
+
```
|
| 221 |
+
- The K node:
|
| 222 |
+
```sh
|
| 223 |
+
bash examples/usage/llava_video/srt_example_llava_v.sh K K-1 YOUR_VIDEO_PATH YOUR_MODEL_PATH FRAMES_PER_VIDEO
|
| 224 |
+
```
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
## Citation
|
| 228 |
+
|
| 229 |
+
If you find it useful for your research and applications, please cite related papers/blogs using this BibTeX:
|
| 230 |
+
```bibtex
|
| 231 |
+
@article{li2024llava,
|
| 232 |
+
title={LLaVA-NeXT-Interleave: Tackling Multi-image, Video, and 3D in Large Multimodal Models},
|
| 233 |
+
author={Li, Feng and Zhang, Renrui and Zhang, Hao and Zhang, Yuanhan and Li, Bo and Li, Wei and Ma, Zejun and Li, Chunyuan},
|
| 234 |
+
journal={arXiv preprint arXiv:2407.07895},
|
| 235 |
+
year={2024}
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
@misc{li2024llavanext-ablations,
|
| 239 |
+
title={LLaVA-NeXT: What Else Influences Visual Instruction Tuning Beyond Data?},
|
| 240 |
+
url={https://llava-vl.github.io/blog/2024-05-25-llava-next-ablations/},
|
| 241 |
+
author={Li, Bo and Zhang, Hao and Zhang, Kaichen and Guo, Dong and Zhang, Yuanhan and Zhang, Renrui and Li, Feng and Liu, Ziwei and Li, Chunyuan},
|
| 242 |
+
month={May},
|
| 243 |
+
year={2024}
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
@misc{li2024llavanext-strong,
|
| 247 |
+
title={LLaVA-NeXT: Stronger LLMs Supercharge Multimodal Capabilities in the Wild},
|
| 248 |
+
url={https://llava-vl.github.io/blog/2024-05-10-llava-next-stronger-llms/},
|
| 249 |
+
author={Li, Bo and Zhang, Kaichen and Zhang, Hao and Guo, Dong and Zhang, Renrui and Li, Feng and Zhang, Yuanhan and Liu, Ziwei and Li, Chunyuan},
|
| 250 |
+
month={May},
|
| 251 |
+
year={2024}
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
@misc{zhang2024llavanext-video,
|
| 255 |
+
title={LLaVA-NeXT: A Strong Zero-shot Video Understanding Model},
|
| 256 |
+
url={https://llava-vl.github.io/blog/2024-04-30-llava-next-video/},
|
| 257 |
+
author={Zhang, Yuanhan and Li, Bo and Liu, haotian and Lee, Yong jae and Gui, Liangke and Fu, Di and Feng, Jiashi and Liu, Ziwei and Li, Chunyuan},
|
| 258 |
+
month={April},
|
| 259 |
+
year={2024}
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
@misc{liu2024llavanext,
|
| 263 |
+
title={LLaVA-NeXT: Improved reasoning, OCR, and world knowledge},
|
| 264 |
+
url={https://llava-vl.github.io/blog/2024-01-30-llava-next/},
|
| 265 |
+
author={Liu, Haotian and Li, Chunyuan and Li, Yuheng and Li, Bo and Zhang, Yuanhan and Shen, Sheng and Lee, Yong Jae},
|
| 266 |
+
month={January},
|
| 267 |
+
year={2024}
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
@misc{liu2023improvedllava,
|
| 271 |
+
title={Improved Baselines with Visual Instruction Tuning},
|
| 272 |
+
author={Liu, Haotian and Li, Chunyuan and Li, Yuheng and Lee, Yong Jae},
|
| 273 |
+
publisher={arXiv:2310.03744},
|
| 274 |
+
year={2023},
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
@misc{liu2023llava,
|
| 278 |
+
title={Visual Instruction Tuning},
|
| 279 |
+
author={Liu, Haotian and Li, Chunyuan and Wu, Qingyang and Lee, Yong Jae},
|
| 280 |
+
publisher={NeurIPS},
|
| 281 |
+
year={2023},
|
| 282 |
+
}
|
| 283 |
+
```
|
| 284 |
+
|
| 285 |
+
## Acknowledgement
|
| 286 |
+
|
| 287 |
+
- [Vicuna](https://github.com/lm-sys/FastChat): the codebase we built upon, and our base model Vicuna-13B that has the amazing language capabilities!
|
| 288 |
+
- The LLaVA-NeXT project is currently maintained by the team along with our contributors (listed alphabetically by the first names): [Bo Li](https://brianboli.com/), [Dong Guo](https://www.linkedin.com/in/dongguoset/), [Feng Li](https://scholar.google.com/citations?hl=zh-CN&user=ybRe9GcAAAAJ&view_op=list_works&sortby=pubdate), [Hao Zhang](https://scholar.google.com/citations?user=B8hPxMQAAAAJ&hl=en), [Kaichen Zhang](https://www.linkedin.com/in/kaichen-zhang-014b17219/?originalSubdomain=sg), [Renrui Zhang](https://zrrskywalker.github.io/), [Yuanhan Zhang](https://zhangyuanhan-ai.github.io/), led by [Chunyuan Li](https://chunyuan.li/) and with the guidance and help from [Haotian Liu](https://hliu.cc/).
|
| 289 |
+
- The `lmms-eval` framework and its core contributors, including Peiyuan Zhang, Fanyi Pu, Joshua Adrian Cahyono, and Kairui Hu, for their support on the evaluation side.
|
| 290 |
+
|
| 291 |
+
## Related Projects
|
| 292 |
+
|
| 293 |
+
- [Instruction Tuning with GPT-4](https://github.com/Instruction-Tuning-with-GPT-4/GPT-4-LLM)
|
| 294 |
+
- [LLaVA-Med: Training a Large Language-and-Vision Assistant for Biomedicine in One Day](https://github.com/microsoft/LLaVA-Med)
|
| 295 |
+
- [Otter: In-Context Multi-Modal Instruction Tuning](https://github.com/Luodian/Otter)
|
| 296 |
+
|
| 297 |
+
For future project ideas, please check out:
|
| 298 |
+
- [SEEM: Segment Everything Everywhere All at Once](https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once)
|
| 299 |
+
- [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).
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava.egg-info/SOURCES.txt
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
LICENSE
|
| 2 |
+
README.md
|
| 3 |
+
pyproject.toml
|
| 4 |
+
llava/__init__.py
|
| 5 |
+
llava/constants.py
|
| 6 |
+
llava/conversation.py
|
| 7 |
+
llava/mm_utils.py
|
| 8 |
+
llava/utils.py
|
| 9 |
+
llava-critic-r1/EasyR1/setup.py
|
| 10 |
+
llava-critic-r1/EasyR1/examples/reward_function/caption.py
|
| 11 |
+
llava-critic-r1/EasyR1/examples/reward_function/math.py
|
| 12 |
+
llava-critic-r1/EasyR1/examples/reward_function/r1v.py
|
| 13 |
+
llava-critic-r1/EasyR1/scripts/model_merger.py
|
| 14 |
+
llava-critic-r1/EasyR1/verl/__init__.py
|
| 15 |
+
llava-critic-r1/EasyR1/verl/protocol.py
|
| 16 |
+
llava-critic-r1/EasyR1/verl/models/__init__.py
|
| 17 |
+
llava-critic-r1/EasyR1/verl/models/monkey_patch.py
|
| 18 |
+
llava-critic-r1/EasyR1/verl/models/transformers/__init__.py
|
| 19 |
+
llava-critic-r1/EasyR1/verl/models/transformers/flash_attention_utils.py
|
| 20 |
+
llava-critic-r1/EasyR1/verl/models/transformers/qwen2_vl.py
|
| 21 |
+
llava-critic-r1/EasyR1/verl/single_controller/__init__.py
|
| 22 |
+
llava-critic-r1/EasyR1/verl/single_controller/base/__init__.py
|
| 23 |
+
llava-critic-r1/EasyR1/verl/single_controller/base/decorator.py
|
| 24 |
+
llava-critic-r1/EasyR1/verl/single_controller/base/worker.py
|
| 25 |
+
llava-critic-r1/EasyR1/verl/single_controller/base/worker_group.py
|
| 26 |
+
llava-critic-r1/EasyR1/verl/single_controller/base/register_center/__init__.py
|
| 27 |
+
llava-critic-r1/EasyR1/verl/single_controller/base/register_center/ray.py
|
| 28 |
+
llava-critic-r1/EasyR1/verl/single_controller/ray/__init__.py
|
| 29 |
+
llava-critic-r1/EasyR1/verl/single_controller/ray/base.py
|
| 30 |
+
llava-critic-r1/EasyR1/verl/trainer/__init__.py
|
| 31 |
+
llava-critic-r1/EasyR1/verl/trainer/config.py
|
| 32 |
+
llava-critic-r1/EasyR1/verl/trainer/core_algos.py
|
| 33 |
+
llava-critic-r1/EasyR1/verl/trainer/data_loader.py
|
| 34 |
+
llava-critic-r1/EasyR1/verl/trainer/main.py
|
| 35 |
+
llava-critic-r1/EasyR1/verl/trainer/metrics.py
|
| 36 |
+
llava-critic-r1/EasyR1/verl/trainer/ray_trainer.py
|
| 37 |
+
llava-critic-r1/EasyR1/verl/utils/__init__.py
|
| 38 |
+
llava-critic-r1/EasyR1/verl/utils/dataset.py
|
| 39 |
+
llava-critic-r1/EasyR1/verl/utils/flops_counter.py
|
| 40 |
+
llava-critic-r1/EasyR1/verl/utils/fsdp_utils.py
|
| 41 |
+
llava-critic-r1/EasyR1/verl/utils/model_utils.py
|
| 42 |
+
llava-critic-r1/EasyR1/verl/utils/py_functional.py
|
| 43 |
+
llava-critic-r1/EasyR1/verl/utils/seqlen_balancing.py
|
| 44 |
+
llava-critic-r1/EasyR1/verl/utils/tokenizer.py
|
| 45 |
+
llava-critic-r1/EasyR1/verl/utils/torch_dtypes.py
|
| 46 |
+
llava-critic-r1/EasyR1/verl/utils/torch_functional.py
|
| 47 |
+
llava-critic-r1/EasyR1/verl/utils/ulysses.py
|
| 48 |
+
llava-critic-r1/EasyR1/verl/utils/checkpoint/__init__.py
|
| 49 |
+
llava-critic-r1/EasyR1/verl/utils/checkpoint/checkpoint_manager.py
|
| 50 |
+
llava-critic-r1/EasyR1/verl/utils/checkpoint/fsdp_checkpoint_manager.py
|
| 51 |
+
llava-critic-r1/EasyR1/verl/utils/logger/__init__.py
|
| 52 |
+
llava-critic-r1/EasyR1/verl/utils/logger/gen_logger.py
|
| 53 |
+
llava-critic-r1/EasyR1/verl/utils/logger/logger.py
|
| 54 |
+
llava-critic-r1/EasyR1/verl/workers/__init__.py
|
| 55 |
+
llava-critic-r1/EasyR1/verl/workers/config.py
|
| 56 |
+
llava-critic-r1/EasyR1/verl/workers/fsdp_workers.py
|
| 57 |
+
llava-critic-r1/EasyR1/verl/workers/actor/__init__.py
|
| 58 |
+
llava-critic-r1/EasyR1/verl/workers/actor/base.py
|
| 59 |
+
llava-critic-r1/EasyR1/verl/workers/actor/config.py
|
| 60 |
+
llava-critic-r1/EasyR1/verl/workers/actor/dp_actor.py
|
| 61 |
+
llava-critic-r1/EasyR1/verl/workers/critic/__init__.py
|
| 62 |
+
llava-critic-r1/EasyR1/verl/workers/critic/base.py
|
| 63 |
+
llava-critic-r1/EasyR1/verl/workers/critic/config.py
|
| 64 |
+
llava-critic-r1/EasyR1/verl/workers/critic/dp_critic.py
|
| 65 |
+
llava-critic-r1/EasyR1/verl/workers/reward/__init__.py
|
| 66 |
+
llava-critic-r1/EasyR1/verl/workers/reward/config.py
|
| 67 |
+
llava-critic-r1/EasyR1/verl/workers/reward/function.py
|
| 68 |
+
llava-critic-r1/EasyR1/verl/workers/rollout/__init__.py
|
| 69 |
+
llava-critic-r1/EasyR1/verl/workers/rollout/base.py
|
| 70 |
+
llava-critic-r1/EasyR1/verl/workers/rollout/config.py
|
| 71 |
+
llava-critic-r1/EasyR1/verl/workers/rollout/vllm_rollout_spmd.py
|
| 72 |
+
llava-critic-r1/EasyR1/verl/workers/sharding_manager/__init__.py
|
| 73 |
+
llava-critic-r1/EasyR1/verl/workers/sharding_manager/base.py
|
| 74 |
+
llava-critic-r1/EasyR1/verl/workers/sharding_manager/fsdp_ulysses.py
|
| 75 |
+
llava-critic-r1/EasyR1/verl/workers/sharding_manager/fsdp_vllm.py
|
| 76 |
+
llava.egg-info/PKG-INFO
|
| 77 |
+
llava.egg-info/SOURCES.txt
|
| 78 |
+
llava.egg-info/dependency_links.txt
|
| 79 |
+
llava.egg-info/requires.txt
|
| 80 |
+
llava.egg-info/top_level.txt
|
| 81 |
+
llava/eval/evaluate_interleave.py
|
| 82 |
+
llava/eval/model_vqa.py
|
| 83 |
+
llava/model/__init__.py
|
| 84 |
+
llava/model/apply_delta.py
|
| 85 |
+
llava/model/builder.py
|
| 86 |
+
llava/model/consolidate.py
|
| 87 |
+
llava/model/llava_arch.py
|
| 88 |
+
llava/model/make_delta.py
|
| 89 |
+
llava/model/utils.py
|
| 90 |
+
llava/model/language_model/llava_gemma.py
|
| 91 |
+
llava/model/language_model/llava_llama.py
|
| 92 |
+
llava/model/language_model/llava_mistral.py
|
| 93 |
+
llava/model/language_model/llava_mixtral.py
|
| 94 |
+
llava/model/language_model/llava_mpt.py
|
| 95 |
+
llava/model/language_model/llava_qwen.py
|
| 96 |
+
llava/model/language_model/llava_qwen_moe.py
|
| 97 |
+
llava/model/language_model/modeling_llama.py
|
| 98 |
+
llava/model/multimodal_encoder/builder.py
|
| 99 |
+
llava/model/multimodal_encoder/clip_encoder.py
|
| 100 |
+
llava/model/multimodal_encoder/hf_vision.py
|
| 101 |
+
llava/model/multimodal_encoder/imagebind.py
|
| 102 |
+
llava/model/multimodal_encoder/mlcd_encoder.py
|
| 103 |
+
llava/model/multimodal_encoder/open_clip_encoder.py
|
| 104 |
+
llava/model/multimodal_encoder/siglip_encoder.py
|
| 105 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_vit.py
|
| 106 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/__init__.py
|
| 107 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/constants.py
|
| 108 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/eva_vit_model.py
|
| 109 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/factory.py
|
| 110 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/hf_configs.py
|
| 111 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/hf_model.py
|
| 112 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/loss.py
|
| 113 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model.py
|
| 114 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/modified_resnet.py
|
| 115 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/openai.py
|
| 116 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/pretrained.py
|
| 117 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/rope.py
|
| 118 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/timm_model.py
|
| 119 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/tokenizer.py
|
| 120 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/transform.py
|
| 121 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/transformer.py
|
| 122 |
+
llava/model/multimodal_encoder/dev_eva_clip/eva_clip/utils.py
|
| 123 |
+
llava/model/multimodal_encoder/eva_clip/eva_clip_encoder.py
|
| 124 |
+
llava/model/multimodal_encoder/eva_clip/eva_clip_processors.py
|
| 125 |
+
llava/model/multimodal_encoder/eva_clip/eva_vit.py
|
| 126 |
+
llava/model/multimodal_encoder/eva_clip/factory.py
|
| 127 |
+
llava/model/multimodal_encoder/mlcd/vit_rope2d_hf.py
|
| 128 |
+
llava/model/multimodal_projector/builder.py
|
| 129 |
+
llava/model/multimodal_projector/pooler_projector.py
|
| 130 |
+
llava/model/multimodal_resampler/builder.py
|
| 131 |
+
llava/model/multimodal_resampler/masked_drop.py
|
| 132 |
+
llava/model/multimodal_resampler/perceiver.py
|
| 133 |
+
llava/model/multimodal_resampler/qformer.py
|
| 134 |
+
llava/model/multimodal_resampler/spatial_pool.py
|
| 135 |
+
llava/serve/__init__.py
|
| 136 |
+
llava/serve/cli.py
|
| 137 |
+
llava/serve/controller.py
|
| 138 |
+
llava/serve/gradio_multi_image.py
|
| 139 |
+
llava/serve/gradio_web_server.py
|
| 140 |
+
llava/serve/model_worker.py
|
| 141 |
+
llava/serve/register_worker.py
|
| 142 |
+
llava/serve/sglang_worker.py
|
| 143 |
+
llava/serve/test_message.py
|
| 144 |
+
llava/train/llama_flash_attn_monkey_patch.py
|
| 145 |
+
llava/train/llava_trainer.py
|
| 146 |
+
llava/train/llava_trainer_eval.py
|
| 147 |
+
llava/train/train.py
|
| 148 |
+
llava/train/train_dpo.py
|
| 149 |
+
llava/train/train_mem.py
|
| 150 |
+
trl/__init__.py
|
| 151 |
+
trl/core.py
|
| 152 |
+
trl/import_utils.py
|
| 153 |
+
trl/environment/__init__.py
|
| 154 |
+
trl/environment/base_environment.py
|
| 155 |
+
trl/extras/__init__.py
|
| 156 |
+
trl/extras/best_of_n_sampler.py
|
| 157 |
+
trl/extras/dataset_formatting.py
|
| 158 |
+
trl/models/__init__.py
|
| 159 |
+
trl/models/modeling_base.py
|
| 160 |
+
trl/models/modeling_sd_base.py
|
| 161 |
+
trl/models/modeling_value_head.py
|
| 162 |
+
trl/models/utils.py
|
| 163 |
+
trl/trainer/__init__.py
|
| 164 |
+
trl/trainer/base.py
|
| 165 |
+
trl/trainer/ddpo_config.py
|
| 166 |
+
trl/trainer/ddpo_trainer.py
|
| 167 |
+
trl/trainer/dpo_trainer.py
|
| 168 |
+
trl/trainer/iterative_sft_trainer.py
|
| 169 |
+
trl/trainer/model_config.py
|
| 170 |
+
trl/trainer/ppo_config.py
|
| 171 |
+
trl/trainer/ppo_trainer.py
|
| 172 |
+
trl/trainer/reward_config.py
|
| 173 |
+
trl/trainer/reward_trainer.py
|
| 174 |
+
trl/trainer/sft_trainer.py
|
| 175 |
+
trl/trainer/utils.py
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava.egg-info/dependency_links.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava.egg-info/requires.txt
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
[standalone]
|
| 3 |
+
shortuuid
|
| 4 |
+
httpx==0.24.0
|
| 5 |
+
einops
|
| 6 |
+
ftfy
|
| 7 |
+
|
| 8 |
+
[train]
|
| 9 |
+
llava[standalone]
|
| 10 |
+
numpy==1.26.1
|
| 11 |
+
open_clip_torch
|
| 12 |
+
fastapi
|
| 13 |
+
markdown2[all]
|
| 14 |
+
numpy
|
| 15 |
+
requests
|
| 16 |
+
sentencepiece
|
| 17 |
+
torch==2.1.2
|
| 18 |
+
torchvision==0.16.2
|
| 19 |
+
uvicorn
|
| 20 |
+
wandb
|
| 21 |
+
deepspeed==0.14.4
|
| 22 |
+
peft==0.4.0
|
| 23 |
+
accelerate>=0.29.1
|
| 24 |
+
tokenizers~=0.15.2
|
| 25 |
+
transformers @ git+https://github.com/huggingface/transformers.git@1c39974a4c4036fd641bc1191cc32799f85715a4
|
| 26 |
+
bitsandbytes==0.41.0
|
| 27 |
+
scikit-learn==1.2.2
|
| 28 |
+
sentencepiece~=0.1.99
|
| 29 |
+
einops==0.6.1
|
| 30 |
+
einops-exts==0.0.4
|
| 31 |
+
gradio_client==0.2.9
|
| 32 |
+
urllib3<=2.0.0
|
| 33 |
+
datasets==2.16.1
|
| 34 |
+
pydantic==1.10.8
|
| 35 |
+
timm
|
| 36 |
+
hf_transfer
|
| 37 |
+
opencv-python
|
| 38 |
+
av
|
| 39 |
+
decord
|
| 40 |
+
tyro
|
| 41 |
+
scipy
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava.egg-info/top_level.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
llava
|
| 2 |
+
llava-critic-r1
|
| 3 |
+
trl
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/__init__.py
ADDED
|
File without changes
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/cli.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 5 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
| 6 |
+
from llava.model.builder import load_pretrained_model
|
| 7 |
+
from llava.utils import disable_torch_init
|
| 8 |
+
from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
|
| 9 |
+
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
import requests
|
| 13 |
+
from PIL import Image
|
| 14 |
+
from io import BytesIO
|
| 15 |
+
from transformers import TextStreamer
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def load_image(image_file):
|
| 19 |
+
if image_file.startswith("http") or image_file.startswith("https"):
|
| 20 |
+
response = requests.get(image_file)
|
| 21 |
+
image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 22 |
+
else:
|
| 23 |
+
image = Image.open(image_file).convert("RGB")
|
| 24 |
+
return image
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main(args):
|
| 28 |
+
# Model
|
| 29 |
+
disable_torch_init()
|
| 30 |
+
|
| 31 |
+
model_name = get_model_name_from_path(args.model_path)
|
| 32 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit)
|
| 33 |
+
|
| 34 |
+
if "llama-2" in model_name.lower():
|
| 35 |
+
conv_mode = "llava_llama_2"
|
| 36 |
+
elif "v1" in model_name.lower():
|
| 37 |
+
conv_mode = "llava_v1"
|
| 38 |
+
elif "mpt" in model_name.lower():
|
| 39 |
+
conv_mode = "mpt"
|
| 40 |
+
else:
|
| 41 |
+
conv_mode = "llava_v0"
|
| 42 |
+
|
| 43 |
+
if args.conv_mode is not None and conv_mode != args.conv_mode:
|
| 44 |
+
print("[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}".format(conv_mode, args.conv_mode, args.conv_mode))
|
| 45 |
+
else:
|
| 46 |
+
args.conv_mode = conv_mode
|
| 47 |
+
|
| 48 |
+
conv = conv_templates[args.conv_mode].copy()
|
| 49 |
+
if "mpt" in model_name.lower():
|
| 50 |
+
roles = ("user", "assistant")
|
| 51 |
+
else:
|
| 52 |
+
roles = conv.roles
|
| 53 |
+
|
| 54 |
+
image = load_image(args.image_file)
|
| 55 |
+
image_tensor = image_processor.preprocess(image, return_tensors="pt")["pixel_values"].half().cuda()
|
| 56 |
+
|
| 57 |
+
while True:
|
| 58 |
+
try:
|
| 59 |
+
inp = input(f"{roles[0]}: ")
|
| 60 |
+
except EOFError:
|
| 61 |
+
inp = ""
|
| 62 |
+
if not inp:
|
| 63 |
+
print("exit...")
|
| 64 |
+
break
|
| 65 |
+
|
| 66 |
+
print(f"{roles[1]}: ", end="")
|
| 67 |
+
|
| 68 |
+
if image is not None:
|
| 69 |
+
# first message
|
| 70 |
+
if model.config.mm_use_im_start_end:
|
| 71 |
+
inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + "\n" + inp
|
| 72 |
+
else:
|
| 73 |
+
inp = DEFAULT_IMAGE_TOKEN + "\n" + inp
|
| 74 |
+
conv.append_message(conv.roles[0], inp)
|
| 75 |
+
image = None
|
| 76 |
+
else:
|
| 77 |
+
# later messages
|
| 78 |
+
conv.append_message(conv.roles[0], inp)
|
| 79 |
+
conv.append_message(conv.roles[1], None)
|
| 80 |
+
prompt = conv.get_prompt()
|
| 81 |
+
|
| 82 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
|
| 83 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
| 84 |
+
keywords = [stop_str]
|
| 85 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
| 86 |
+
streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 87 |
+
|
| 88 |
+
with torch.inference_mode():
|
| 89 |
+
output_ids = model.generate(input_ids, images=image_tensor, do_sample=True, temperature=0.2, max_new_tokens=1024, streamer=streamer, use_cache=True, stopping_criteria=[stopping_criteria])
|
| 90 |
+
|
| 91 |
+
outputs = tokenizer.decode(output_ids[0, input_ids.shape[1] :]).strip()
|
| 92 |
+
conv.messages[-1][-1] = outputs
|
| 93 |
+
|
| 94 |
+
if args.debug:
|
| 95 |
+
print("\n", {"prompt": prompt, "outputs": outputs}, "\n")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
parser = argparse.ArgumentParser()
|
| 100 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
| 101 |
+
parser.add_argument("--model-base", type=str, default=None)
|
| 102 |
+
parser.add_argument("--image-file", type=str, required=True)
|
| 103 |
+
parser.add_argument("--num-gpus", type=int, default=1)
|
| 104 |
+
parser.add_argument("--conv-mode", type=str, default=None)
|
| 105 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
| 106 |
+
parser.add_argument("--max-new-tokens", type=int, default=512)
|
| 107 |
+
parser.add_argument("--load-8bit", action="store_true")
|
| 108 |
+
parser.add_argument("--load-4bit", action="store_true")
|
| 109 |
+
parser.add_argument("--debug", action="store_true")
|
| 110 |
+
args = parser.parse_args()
|
| 111 |
+
main(args)
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/controller.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A controller manages distributed workers.
|
| 3 |
+
It sends worker addresses to clients.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import asyncio
|
| 8 |
+
import dataclasses
|
| 9 |
+
from enum import Enum, auto
|
| 10 |
+
import json
|
| 11 |
+
import logging
|
| 12 |
+
import time
|
| 13 |
+
from typing import List, Union
|
| 14 |
+
import threading
|
| 15 |
+
|
| 16 |
+
from fastapi import FastAPI, Request
|
| 17 |
+
from fastapi.responses import StreamingResponse
|
| 18 |
+
import numpy as np
|
| 19 |
+
import requests
|
| 20 |
+
import uvicorn
|
| 21 |
+
|
| 22 |
+
from llava.constants import CONTROLLER_HEART_BEAT_EXPIRATION
|
| 23 |
+
from llava.utils import build_logger, server_error_msg
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = build_logger("controller", "controller.log")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class DispatchMethod(Enum):
|
| 30 |
+
LOTTERY = auto()
|
| 31 |
+
SHORTEST_QUEUE = auto()
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def from_str(cls, name):
|
| 35 |
+
if name == "lottery":
|
| 36 |
+
return cls.LOTTERY
|
| 37 |
+
elif name == "shortest_queue":
|
| 38 |
+
return cls.SHORTEST_QUEUE
|
| 39 |
+
else:
|
| 40 |
+
raise ValueError(f"Invalid dispatch method")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclasses.dataclass
|
| 44 |
+
class WorkerInfo:
|
| 45 |
+
model_names: List[str]
|
| 46 |
+
speed: int
|
| 47 |
+
queue_length: int
|
| 48 |
+
check_heart_beat: bool
|
| 49 |
+
last_heart_beat: str
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def heart_beat_controller(controller):
|
| 53 |
+
while True:
|
| 54 |
+
time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION)
|
| 55 |
+
controller.remove_stable_workers_by_expiration()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class Controller:
|
| 59 |
+
def __init__(self, dispatch_method: str):
|
| 60 |
+
# Dict[str -> WorkerInfo]
|
| 61 |
+
self.worker_info = {}
|
| 62 |
+
self.dispatch_method = DispatchMethod.from_str(dispatch_method)
|
| 63 |
+
|
| 64 |
+
self.heart_beat_thread = threading.Thread(target=heart_beat_controller, args=(self,))
|
| 65 |
+
self.heart_beat_thread.start()
|
| 66 |
+
|
| 67 |
+
logger.info("Init controller")
|
| 68 |
+
|
| 69 |
+
def register_worker(self, worker_name: str, check_heart_beat: bool, worker_status: dict):
|
| 70 |
+
if worker_name not in self.worker_info:
|
| 71 |
+
logger.info(f"Register a new worker: {worker_name}")
|
| 72 |
+
else:
|
| 73 |
+
logger.info(f"Register an existing worker: {worker_name}")
|
| 74 |
+
|
| 75 |
+
if not worker_status:
|
| 76 |
+
worker_status = self.get_worker_status(worker_name)
|
| 77 |
+
if not worker_status:
|
| 78 |
+
return False
|
| 79 |
+
|
| 80 |
+
self.worker_info[worker_name] = WorkerInfo(worker_status["model_names"], worker_status["speed"], worker_status["queue_length"], check_heart_beat, time.time())
|
| 81 |
+
|
| 82 |
+
logger.info(f"Register done: {worker_name}, {worker_status}")
|
| 83 |
+
return True
|
| 84 |
+
|
| 85 |
+
def get_worker_status(self, worker_name: str):
|
| 86 |
+
try:
|
| 87 |
+
r = requests.post(worker_name + "/worker_get_status", timeout=5)
|
| 88 |
+
except requests.exceptions.RequestException as e:
|
| 89 |
+
logger.error(f"Get status fails: {worker_name}, {e}")
|
| 90 |
+
return None
|
| 91 |
+
|
| 92 |
+
if r.status_code != 200:
|
| 93 |
+
logger.error(f"Get status fails: {worker_name}, {r}")
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
return r.json()
|
| 97 |
+
|
| 98 |
+
def remove_worker(self, worker_name: str):
|
| 99 |
+
del self.worker_info[worker_name]
|
| 100 |
+
|
| 101 |
+
def refresh_all_workers(self):
|
| 102 |
+
old_info = dict(self.worker_info)
|
| 103 |
+
self.worker_info = {}
|
| 104 |
+
|
| 105 |
+
for w_name, w_info in old_info.items():
|
| 106 |
+
if not self.register_worker(w_name, w_info.check_heart_beat, None):
|
| 107 |
+
logger.info(f"Remove stale worker: {w_name}")
|
| 108 |
+
|
| 109 |
+
def list_models(self):
|
| 110 |
+
model_names = set()
|
| 111 |
+
|
| 112 |
+
for w_name, w_info in self.worker_info.items():
|
| 113 |
+
model_names.update(w_info.model_names)
|
| 114 |
+
|
| 115 |
+
return list(model_names)
|
| 116 |
+
|
| 117 |
+
def get_worker_address(self, model_name: str):
|
| 118 |
+
if self.dispatch_method == DispatchMethod.LOTTERY:
|
| 119 |
+
worker_names = []
|
| 120 |
+
worker_speeds = []
|
| 121 |
+
for w_name, w_info in self.worker_info.items():
|
| 122 |
+
if model_name in w_info.model_names:
|
| 123 |
+
worker_names.append(w_name)
|
| 124 |
+
worker_speeds.append(w_info.speed)
|
| 125 |
+
worker_speeds = np.array(worker_speeds, dtype=np.float32)
|
| 126 |
+
norm = np.sum(worker_speeds)
|
| 127 |
+
if norm < 1e-4:
|
| 128 |
+
return ""
|
| 129 |
+
worker_speeds = worker_speeds / norm
|
| 130 |
+
if True: # Directly return address
|
| 131 |
+
pt = np.random.choice(np.arange(len(worker_names)), p=worker_speeds)
|
| 132 |
+
worker_name = worker_names[pt]
|
| 133 |
+
return worker_name
|
| 134 |
+
|
| 135 |
+
# Check status before returning
|
| 136 |
+
while True:
|
| 137 |
+
pt = np.random.choice(np.arange(len(worker_names)), p=worker_speeds)
|
| 138 |
+
worker_name = worker_names[pt]
|
| 139 |
+
|
| 140 |
+
if self.get_worker_status(worker_name):
|
| 141 |
+
break
|
| 142 |
+
else:
|
| 143 |
+
self.remove_worker(worker_name)
|
| 144 |
+
worker_speeds[pt] = 0
|
| 145 |
+
norm = np.sum(worker_speeds)
|
| 146 |
+
if norm < 1e-4:
|
| 147 |
+
return ""
|
| 148 |
+
worker_speeds = worker_speeds / norm
|
| 149 |
+
continue
|
| 150 |
+
return worker_name
|
| 151 |
+
elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE:
|
| 152 |
+
worker_names = []
|
| 153 |
+
worker_qlen = []
|
| 154 |
+
for w_name, w_info in self.worker_info.items():
|
| 155 |
+
if model_name in w_info.model_names:
|
| 156 |
+
worker_names.append(w_name)
|
| 157 |
+
worker_qlen.append(w_info.queue_length / w_info.speed)
|
| 158 |
+
if len(worker_names) == 0:
|
| 159 |
+
return ""
|
| 160 |
+
min_index = np.argmin(worker_qlen)
|
| 161 |
+
w_name = worker_names[min_index]
|
| 162 |
+
self.worker_info[w_name].queue_length += 1
|
| 163 |
+
logger.info(f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}")
|
| 164 |
+
return w_name
|
| 165 |
+
else:
|
| 166 |
+
raise ValueError(f"Invalid dispatch method: {self.dispatch_method}")
|
| 167 |
+
|
| 168 |
+
def receive_heart_beat(self, worker_name: str, queue_length: int):
|
| 169 |
+
if worker_name not in self.worker_info:
|
| 170 |
+
logger.info(f"Receive unknown heart beat. {worker_name}")
|
| 171 |
+
return False
|
| 172 |
+
|
| 173 |
+
self.worker_info[worker_name].queue_length = queue_length
|
| 174 |
+
self.worker_info[worker_name].last_heart_beat = time.time()
|
| 175 |
+
logger.info(f"Receive heart beat. {worker_name}")
|
| 176 |
+
return True
|
| 177 |
+
|
| 178 |
+
def remove_stable_workers_by_expiration(self):
|
| 179 |
+
expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION
|
| 180 |
+
to_delete = []
|
| 181 |
+
for worker_name, w_info in self.worker_info.items():
|
| 182 |
+
if w_info.check_heart_beat and w_info.last_heart_beat < expire:
|
| 183 |
+
to_delete.append(worker_name)
|
| 184 |
+
|
| 185 |
+
for worker_name in to_delete:
|
| 186 |
+
self.remove_worker(worker_name)
|
| 187 |
+
|
| 188 |
+
def worker_api_generate_stream(self, params):
|
| 189 |
+
worker_addr = self.get_worker_address(params["model"])
|
| 190 |
+
if not worker_addr:
|
| 191 |
+
logger.info(f"no worker: {params['model']}")
|
| 192 |
+
ret = {
|
| 193 |
+
"text": server_error_msg,
|
| 194 |
+
"error_code": 2,
|
| 195 |
+
}
|
| 196 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 197 |
+
|
| 198 |
+
try:
|
| 199 |
+
response = requests.post(worker_addr + "/worker_generate_stream", json=params, stream=True, timeout=5)
|
| 200 |
+
for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
|
| 201 |
+
if chunk:
|
| 202 |
+
yield chunk + b"\0"
|
| 203 |
+
except requests.exceptions.RequestException as e:
|
| 204 |
+
logger.info(f"worker timeout: {worker_addr}")
|
| 205 |
+
ret = {
|
| 206 |
+
"text": server_error_msg,
|
| 207 |
+
"error_code": 3,
|
| 208 |
+
}
|
| 209 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 210 |
+
|
| 211 |
+
# Let the controller act as a worker to achieve hierarchical
|
| 212 |
+
# management. This can be used to connect isolated sub networks.
|
| 213 |
+
def worker_api_get_status(self):
|
| 214 |
+
model_names = set()
|
| 215 |
+
speed = 0
|
| 216 |
+
queue_length = 0
|
| 217 |
+
|
| 218 |
+
for w_name in self.worker_info:
|
| 219 |
+
worker_status = self.get_worker_status(w_name)
|
| 220 |
+
if worker_status is not None:
|
| 221 |
+
model_names.update(worker_status["model_names"])
|
| 222 |
+
speed += worker_status["speed"]
|
| 223 |
+
queue_length += worker_status["queue_length"]
|
| 224 |
+
|
| 225 |
+
return {
|
| 226 |
+
"model_names": list(model_names),
|
| 227 |
+
"speed": speed,
|
| 228 |
+
"queue_length": queue_length,
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
app = FastAPI()
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@app.post("/register_worker")
|
| 236 |
+
async def register_worker(request: Request):
|
| 237 |
+
data = await request.json()
|
| 238 |
+
controller.register_worker(data["worker_name"], data["check_heart_beat"], data.get("worker_status", None))
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
@app.post("/refresh_all_workers")
|
| 242 |
+
async def refresh_all_workers():
|
| 243 |
+
models = controller.refresh_all_workers()
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
@app.post("/list_models")
|
| 247 |
+
async def list_models():
|
| 248 |
+
models = controller.list_models()
|
| 249 |
+
return {"models": models}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@app.post("/get_worker_address")
|
| 253 |
+
async def get_worker_address(request: Request):
|
| 254 |
+
data = await request.json()
|
| 255 |
+
addr = controller.get_worker_address(data["model"])
|
| 256 |
+
return {"address": addr}
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@app.post("/receive_heart_beat")
|
| 260 |
+
async def receive_heart_beat(request: Request):
|
| 261 |
+
data = await request.json()
|
| 262 |
+
exist = controller.receive_heart_beat(data["worker_name"], data["queue_length"])
|
| 263 |
+
return {"exist": exist}
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@app.post("/worker_generate_stream")
|
| 267 |
+
async def worker_api_generate_stream(request: Request):
|
| 268 |
+
params = await request.json()
|
| 269 |
+
generator = controller.worker_api_generate_stream(params)
|
| 270 |
+
return StreamingResponse(generator)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
@app.post("/worker_get_status")
|
| 274 |
+
async def worker_api_get_status(request: Request):
|
| 275 |
+
return controller.worker_api_get_status()
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
if __name__ == "__main__":
|
| 279 |
+
parser = argparse.ArgumentParser()
|
| 280 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 281 |
+
parser.add_argument("--port", type=int, default=21001)
|
| 282 |
+
parser.add_argument("--dispatch-method", type=str, choices=["lottery", "shortest_queue"], default="shortest_queue")
|
| 283 |
+
args = parser.parse_args()
|
| 284 |
+
logger.info(f"args: {args}")
|
| 285 |
+
|
| 286 |
+
controller = Controller(args.dispatch_method)
|
| 287 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/gradio_multi_image.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import datetime
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import requests
|
| 9 |
+
|
| 10 |
+
from llava.conversation import default_conversation, conv_templates, SeparatorStyle
|
| 11 |
+
from llava.constants import LOGDIR
|
| 12 |
+
from llava.utils import build_logger, server_error_msg, violates_moderation, moderation_msg
|
| 13 |
+
import hashlib
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
logger = build_logger("gradio_web_server", "gradio_web_server.log")
|
| 17 |
+
|
| 18 |
+
headers = {"User-Agent": "LLaVA Client"}
|
| 19 |
+
|
| 20 |
+
no_change_btn = gr.Button.update()
|
| 21 |
+
enable_btn = gr.Button.update(interactive=True)
|
| 22 |
+
disable_btn = gr.Button.update(interactive=False)
|
| 23 |
+
|
| 24 |
+
priority = {
|
| 25 |
+
"vicuna-13b": "aaaaaaa",
|
| 26 |
+
"koala-13b": "aaaaaab",
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_conv_log_filename():
|
| 31 |
+
t = datetime.datetime.now()
|
| 32 |
+
name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
|
| 33 |
+
return name
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_model_list():
|
| 37 |
+
ret = requests.post(args.controller_url + "/refresh_all_workers")
|
| 38 |
+
assert ret.status_code == 200
|
| 39 |
+
ret = requests.post(args.controller_url + "/list_models")
|
| 40 |
+
models = ret.json()["models"]
|
| 41 |
+
models.sort(key=lambda x: priority.get(x, x))
|
| 42 |
+
logger.info(f"Models: {models}")
|
| 43 |
+
return models
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
get_window_url_params = """
|
| 47 |
+
function() {
|
| 48 |
+
const params = new URLSearchParams(window.location.search);
|
| 49 |
+
url_params = Object.fromEntries(params);
|
| 50 |
+
console.log(url_params);
|
| 51 |
+
return url_params;
|
| 52 |
+
}
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def load_demo(url_params, request: gr.Request):
|
| 57 |
+
logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
|
| 58 |
+
|
| 59 |
+
dropdown_update = gr.Dropdown.update(visible=True)
|
| 60 |
+
if "model" in url_params:
|
| 61 |
+
model = url_params["model"]
|
| 62 |
+
if model in models:
|
| 63 |
+
dropdown_update = gr.Dropdown.update(value=model, visible=True)
|
| 64 |
+
|
| 65 |
+
state = default_conversation.copy()
|
| 66 |
+
return (state, dropdown_update, gr.Chatbot.update(visible=True), gr.Textbox.update(visible=True), gr.Button.update(visible=True), gr.Row.update(visible=True), gr.Accordion.update(visible=True))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def load_demo_refresh_model_list(request: gr.Request):
|
| 70 |
+
logger.info(f"load_demo. ip: {request.client.host}")
|
| 71 |
+
models = get_model_list()
|
| 72 |
+
state = default_conversation.copy()
|
| 73 |
+
return (
|
| 74 |
+
state,
|
| 75 |
+
gr.Dropdown.update(choices=models, value=models[0] if len(models) > 0 else ""),
|
| 76 |
+
gr.Chatbot.update(visible=True),
|
| 77 |
+
gr.Textbox.update(visible=True),
|
| 78 |
+
gr.Button.update(visible=True),
|
| 79 |
+
gr.Row.update(visible=True),
|
| 80 |
+
gr.Accordion.update(visible=True),
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def vote_last_response(state, vote_type, model_selector, request: gr.Request):
|
| 85 |
+
with open(get_conv_log_filename(), "a") as fout:
|
| 86 |
+
data = {
|
| 87 |
+
"tstamp": round(time.time(), 4),
|
| 88 |
+
"type": vote_type,
|
| 89 |
+
"model": model_selector,
|
| 90 |
+
"state": state.dict(),
|
| 91 |
+
"ip": request.client.host,
|
| 92 |
+
}
|
| 93 |
+
fout.write(json.dumps(data) + "\n")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def upvote_last_response(state, model_selector, request: gr.Request):
|
| 97 |
+
logger.info(f"upvote. ip: {request.client.host}")
|
| 98 |
+
vote_last_response(state, "upvote", model_selector, request)
|
| 99 |
+
return ("",) + (disable_btn,) * 3
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def downvote_last_response(state, model_selector, request: gr.Request):
|
| 103 |
+
logger.info(f"downvote. ip: {request.client.host}")
|
| 104 |
+
vote_last_response(state, "downvote", model_selector, request)
|
| 105 |
+
return ("",) + (disable_btn,) * 3
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def flag_last_response(state, model_selector, request: gr.Request):
|
| 109 |
+
logger.info(f"flag. ip: {request.client.host}")
|
| 110 |
+
vote_last_response(state, "flag", model_selector, request)
|
| 111 |
+
return ("",) + (disable_btn,) * 3
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def regenerate(state, image_process_mode, request: gr.Request):
|
| 115 |
+
logger.info(f"regenerate. ip: {request.client.host}")
|
| 116 |
+
state.messages[-1][-1] = None
|
| 117 |
+
prev_human_msg = state.messages[-2]
|
| 118 |
+
if type(prev_human_msg[1]) in (tuple, list):
|
| 119 |
+
prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
|
| 120 |
+
state.skip_next = False
|
| 121 |
+
return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def clear_history(request: gr.Request):
|
| 125 |
+
logger.info(f"clear_history. ip: {request.client.host}")
|
| 126 |
+
state = default_conversation.copy()
|
| 127 |
+
return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def add_text(state, text, image, image2, image_process_mode, request: gr.Request):
|
| 131 |
+
logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
|
| 132 |
+
if len(text) <= 0 and image is None:
|
| 133 |
+
state.skip_next = True
|
| 134 |
+
return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
|
| 135 |
+
if args.moderate:
|
| 136 |
+
flagged = violates_moderation(text)
|
| 137 |
+
if flagged:
|
| 138 |
+
state.skip_next = True
|
| 139 |
+
return (state, state.to_gradio_chatbot(), moderation_msg, None) + (no_change_btn,) * 5
|
| 140 |
+
|
| 141 |
+
text = text[:3072] # Hard cut-off
|
| 142 |
+
images = [x for x in [image, image2] if x is not None]
|
| 143 |
+
num_images = len(images)
|
| 144 |
+
if num_images > 0:
|
| 145 |
+
text = text.replace("<image>", "").strip()
|
| 146 |
+
text = text[: 3072 - 512 * num_images]
|
| 147 |
+
text = "<image>\n" * num_images + text
|
| 148 |
+
text = (text, images, image_process_mode)
|
| 149 |
+
if len(state.get_images(return_pil=True)) > 0:
|
| 150 |
+
state = default_conversation.copy()
|
| 151 |
+
state.append_message(state.roles[0], text)
|
| 152 |
+
state.append_message(state.roles[1], None)
|
| 153 |
+
state.skip_next = False
|
| 154 |
+
return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request):
|
| 158 |
+
logger.info(f"http_bot. ip: {request.client.host}")
|
| 159 |
+
start_tstamp = time.time()
|
| 160 |
+
model_name = model_selector
|
| 161 |
+
|
| 162 |
+
if state.skip_next:
|
| 163 |
+
# This generate call is skipped due to invalid inputs
|
| 164 |
+
yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
|
| 165 |
+
return
|
| 166 |
+
|
| 167 |
+
if len(state.messages) == state.offset + 2:
|
| 168 |
+
# First round of conversation
|
| 169 |
+
if "llava" in model_name.lower():
|
| 170 |
+
if "llama-2" in model_name.lower():
|
| 171 |
+
if "sharegpt" in model_name.lower():
|
| 172 |
+
if "mmtag" in model_name.lower():
|
| 173 |
+
template_name = "v1_mmtag"
|
| 174 |
+
elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
|
| 175 |
+
template_name = "v1_mmtag"
|
| 176 |
+
else:
|
| 177 |
+
template_name = "llava_v1"
|
| 178 |
+
else:
|
| 179 |
+
if "mmtag" in model_name.lower():
|
| 180 |
+
template_name = "llava_llama_2_mmtag"
|
| 181 |
+
elif "simple" in model_name.lower():
|
| 182 |
+
template_name = "llava_llama_2_simple"
|
| 183 |
+
elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
|
| 184 |
+
template_name = "llava_llama_2_mmtag"
|
| 185 |
+
elif "simple" in model_name.lower():
|
| 186 |
+
template_name = "llava_llama_2_simple"
|
| 187 |
+
else:
|
| 188 |
+
template_name = "llava_llama_2"
|
| 189 |
+
elif "v1" in model_name.lower():
|
| 190 |
+
if "mmtag" in model_name.lower():
|
| 191 |
+
template_name = "v1_mmtag"
|
| 192 |
+
elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
|
| 193 |
+
template_name = "v1_mmtag"
|
| 194 |
+
else:
|
| 195 |
+
template_name = "llava_v1"
|
| 196 |
+
elif "mpt" in model_name.lower():
|
| 197 |
+
template_name = "mpt"
|
| 198 |
+
else:
|
| 199 |
+
if "mmtag" in model_name.lower():
|
| 200 |
+
template_name = "v0_mmtag"
|
| 201 |
+
elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
|
| 202 |
+
template_name = "v0_mmtag"
|
| 203 |
+
else:
|
| 204 |
+
template_name = "llava_v0"
|
| 205 |
+
elif "mpt" in model_name.lower():
|
| 206 |
+
template_name = "mpt_text"
|
| 207 |
+
elif "llama-2" in model_name.lower():
|
| 208 |
+
if "sharegpt" in model_name.lower():
|
| 209 |
+
template_name = "vicuna_v1"
|
| 210 |
+
else:
|
| 211 |
+
template_name = "llama_2"
|
| 212 |
+
else:
|
| 213 |
+
template_name = "vicuna_v1"
|
| 214 |
+
new_state = conv_templates[template_name].copy()
|
| 215 |
+
new_state.append_message(new_state.roles[0], state.messages[-2][1])
|
| 216 |
+
new_state.append_message(new_state.roles[1], None)
|
| 217 |
+
state = new_state
|
| 218 |
+
|
| 219 |
+
# Query worker address
|
| 220 |
+
controller_url = args.controller_url
|
| 221 |
+
ret = requests.post(controller_url + "/get_worker_address", json={"model": model_name})
|
| 222 |
+
worker_addr = ret.json()["address"]
|
| 223 |
+
logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
|
| 224 |
+
|
| 225 |
+
# No available worker
|
| 226 |
+
if worker_addr == "":
|
| 227 |
+
state.messages[-1][-1] = server_error_msg
|
| 228 |
+
yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
| 229 |
+
return
|
| 230 |
+
|
| 231 |
+
# Construct prompt
|
| 232 |
+
prompt = state.get_prompt()
|
| 233 |
+
|
| 234 |
+
all_images = state.get_images(return_pil=True)
|
| 235 |
+
all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
|
| 236 |
+
for image, hash in zip(all_images, all_image_hash):
|
| 237 |
+
t = datetime.datetime.now()
|
| 238 |
+
filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
|
| 239 |
+
if not os.path.isfile(filename):
|
| 240 |
+
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
| 241 |
+
image.save(filename)
|
| 242 |
+
|
| 243 |
+
# Make requests
|
| 244 |
+
pload = {
|
| 245 |
+
"model": model_name,
|
| 246 |
+
"prompt": prompt,
|
| 247 |
+
"temperature": float(temperature),
|
| 248 |
+
"top_p": float(top_p),
|
| 249 |
+
"max_new_tokens": min(int(max_new_tokens), 1536),
|
| 250 |
+
"stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
|
| 251 |
+
"images": f"List of {len(state.get_images())} images: {all_image_hash}",
|
| 252 |
+
}
|
| 253 |
+
logger.info(f"==== request ====\n{pload}")
|
| 254 |
+
|
| 255 |
+
pload["images"] = state.get_images()
|
| 256 |
+
|
| 257 |
+
state.messages[-1][-1] = "▌"
|
| 258 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
| 259 |
+
|
| 260 |
+
try:
|
| 261 |
+
# Stream output
|
| 262 |
+
response = requests.post(worker_addr + "/worker_generate_stream", headers=headers, json=pload, stream=True, timeout=10)
|
| 263 |
+
for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
|
| 264 |
+
if chunk:
|
| 265 |
+
data = json.loads(chunk.decode())
|
| 266 |
+
if data["error_code"] == 0:
|
| 267 |
+
output = data["text"][len(prompt) :].strip()
|
| 268 |
+
state.messages[-1][-1] = output + "▌"
|
| 269 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
| 270 |
+
else:
|
| 271 |
+
output = data["text"] + f" (error_code: {data['error_code']})"
|
| 272 |
+
state.messages[-1][-1] = output
|
| 273 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
| 274 |
+
return
|
| 275 |
+
time.sleep(0.03)
|
| 276 |
+
except requests.exceptions.RequestException as e:
|
| 277 |
+
state.messages[-1][-1] = server_error_msg
|
| 278 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
| 279 |
+
return
|
| 280 |
+
|
| 281 |
+
state.messages[-1][-1] = state.messages[-1][-1][:-1]
|
| 282 |
+
yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
|
| 283 |
+
|
| 284 |
+
finish_tstamp = time.time()
|
| 285 |
+
logger.info(f"{output}")
|
| 286 |
+
|
| 287 |
+
with open(get_conv_log_filename(), "a") as fout:
|
| 288 |
+
data = {
|
| 289 |
+
"tstamp": round(finish_tstamp, 4),
|
| 290 |
+
"type": "chat",
|
| 291 |
+
"model": model_name,
|
| 292 |
+
"start": round(start_tstamp, 4),
|
| 293 |
+
"finish": round(start_tstamp, 4),
|
| 294 |
+
"state": state.dict(),
|
| 295 |
+
"images": all_image_hash,
|
| 296 |
+
"ip": request.client.host,
|
| 297 |
+
}
|
| 298 |
+
fout.write(json.dumps(data) + "\n")
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
title_markdown = """
|
| 302 |
+
# 🌋 LLaVA: Large Language and Vision Assistant
|
| 303 |
+
[[Project Page](https://llava-vl.github.io)] [[Code](https://github.com/haotian-liu/LLaVA)] [[Model](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)] | 📚 [[LLaVA](https://arxiv.org/abs/2304.08485)] [[LLaVA-v1.5](https://arxiv.org/abs/2310.03744)]
|
| 304 |
+
"""
|
| 305 |
+
|
| 306 |
+
tos_markdown = """
|
| 307 |
+
### Terms of use
|
| 308 |
+
By using this service, users are required to agree to the following terms:
|
| 309 |
+
The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
|
| 310 |
+
Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
|
| 311 |
+
For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
learn_more_markdown = """
|
| 316 |
+
### License
|
| 317 |
+
The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
block_css = """
|
| 321 |
+
|
| 322 |
+
#buttons button {
|
| 323 |
+
min-width: min(120px,100%);
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
#chatbot img {
|
| 327 |
+
display: inline-block;
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
"""
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def build_demo(embed_mode):
|
| 334 |
+
textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
|
| 335 |
+
with gr.Blocks(title="LLaVA", theme=gr.themes.Default(), css=block_css) as demo:
|
| 336 |
+
state = gr.State()
|
| 337 |
+
|
| 338 |
+
if not embed_mode:
|
| 339 |
+
gr.Markdown(title_markdown)
|
| 340 |
+
|
| 341 |
+
with gr.Row():
|
| 342 |
+
with gr.Column(scale=3):
|
| 343 |
+
with gr.Row(elem_id="model_selector_row"):
|
| 344 |
+
model_selector = gr.Dropdown(choices=models, value=models[0] if len(models) > 0 else "", interactive=True, show_label=False, container=False)
|
| 345 |
+
|
| 346 |
+
with gr.Row(elem_id="images"):
|
| 347 |
+
imagebox = gr.Image(type="pil")
|
| 348 |
+
imagebox_2 = gr.Image(type="pil")
|
| 349 |
+
image_process_mode = gr.Radio(["Crop", "Resize", "Pad", "Default"], value="Default", label="Preprocess for non-square image", visible=False)
|
| 350 |
+
|
| 351 |
+
cur_dir = os.path.dirname(os.path.abspath(__file__))
|
| 352 |
+
gr.Examples(
|
| 353 |
+
examples=[
|
| 354 |
+
[f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image?"],
|
| 355 |
+
[f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"],
|
| 356 |
+
],
|
| 357 |
+
inputs=[imagebox, textbox],
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
with gr.Accordion("Parameters", open=False, visible=False) as parameter_row:
|
| 361 |
+
temperature = gr.Slider(
|
| 362 |
+
minimum=0.0,
|
| 363 |
+
maximum=1.0,
|
| 364 |
+
value=0.2,
|
| 365 |
+
step=0.1,
|
| 366 |
+
interactive=True,
|
| 367 |
+
label="Temperature",
|
| 368 |
+
)
|
| 369 |
+
top_p = gr.Slider(
|
| 370 |
+
minimum=0.0,
|
| 371 |
+
maximum=1.0,
|
| 372 |
+
value=0.7,
|
| 373 |
+
step=0.1,
|
| 374 |
+
interactive=True,
|
| 375 |
+
label="Top P",
|
| 376 |
+
)
|
| 377 |
+
max_output_tokens = gr.Slider(
|
| 378 |
+
minimum=0,
|
| 379 |
+
maximum=1024,
|
| 380 |
+
value=512,
|
| 381 |
+
step=64,
|
| 382 |
+
interactive=True,
|
| 383 |
+
label="Max output tokens",
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
with gr.Column(scale=8):
|
| 387 |
+
chatbot = gr.Chatbot(elem_id="chatbot", label="LLaVA Chatbot", visible=False, height=550)
|
| 388 |
+
with gr.Row():
|
| 389 |
+
with gr.Column(scale=8):
|
| 390 |
+
textbox.render()
|
| 391 |
+
with gr.Column(scale=1, min_width=50):
|
| 392 |
+
submit_btn = gr.Button(value="Submit", visible=False)
|
| 393 |
+
with gr.Row(visible=False) as button_row:
|
| 394 |
+
upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
|
| 395 |
+
downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
|
| 396 |
+
flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
|
| 397 |
+
# stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False)
|
| 398 |
+
regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
|
| 399 |
+
clear_btn = gr.Button(value="🗑️ Clear", interactive=False)
|
| 400 |
+
|
| 401 |
+
if not embed_mode:
|
| 402 |
+
gr.Markdown(tos_markdown)
|
| 403 |
+
gr.Markdown(learn_more_markdown)
|
| 404 |
+
url_params = gr.JSON(visible=False)
|
| 405 |
+
|
| 406 |
+
# Register listeners
|
| 407 |
+
btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
|
| 408 |
+
upvote_btn.click(upvote_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
|
| 409 |
+
downvote_btn.click(downvote_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
|
| 410 |
+
flag_btn.click(flag_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
|
| 411 |
+
regenerate_btn.click(regenerate, [state, image_process_mode], [state, chatbot, textbox, imagebox, imagebox_2] + btn_list).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list)
|
| 412 |
+
clear_btn.click(clear_history, None, [state, chatbot, textbox, imagebox, imagebox_2] + btn_list)
|
| 413 |
+
|
| 414 |
+
textbox.submit(add_text, [state, textbox, imagebox, imagebox_2, image_process_mode], [state, chatbot, textbox, imagebox, imagebox_2] + btn_list).then(
|
| 415 |
+
http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list
|
| 416 |
+
)
|
| 417 |
+
submit_btn.click(add_text, [state, textbox, imagebox, imagebox_2, image_process_mode], [state, chatbot, textbox, imagebox, imagebox_2] + btn_list).then(
|
| 418 |
+
http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
if args.model_list_mode == "once":
|
| 422 |
+
demo.load(load_demo, [url_params], [state, model_selector, chatbot, textbox, submit_btn, button_row, parameter_row], _js=get_window_url_params)
|
| 423 |
+
elif args.model_list_mode == "reload":
|
| 424 |
+
demo.load(load_demo_refresh_model_list, None, [state, model_selector, chatbot, textbox, submit_btn, button_row, parameter_row])
|
| 425 |
+
else:
|
| 426 |
+
raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
|
| 427 |
+
|
| 428 |
+
return demo
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
if __name__ == "__main__":
|
| 432 |
+
parser = argparse.ArgumentParser()
|
| 433 |
+
parser.add_argument("--host", type=str, default="0.0.0.0")
|
| 434 |
+
parser.add_argument("--port", type=int)
|
| 435 |
+
parser.add_argument("--controller-url", type=str, default="http://localhost:21001")
|
| 436 |
+
parser.add_argument("--concurrency-count", type=int, default=8)
|
| 437 |
+
parser.add_argument("--model-list-mode", type=str, default="once", choices=["once", "reload"])
|
| 438 |
+
parser.add_argument("--share", action="store_true")
|
| 439 |
+
parser.add_argument("--moderate", action="store_true")
|
| 440 |
+
parser.add_argument("--embed", action="store_true")
|
| 441 |
+
args = parser.parse_args()
|
| 442 |
+
logger.info(f"args: {args}")
|
| 443 |
+
|
| 444 |
+
models = get_model_list()
|
| 445 |
+
|
| 446 |
+
logger.info(args)
|
| 447 |
+
demo = build_demo(args.embed)
|
| 448 |
+
demo.queue(concurrency_count=args.concurrency_count, status_update_rate=10, api_open=False).launch(server_name=args.host, server_port=args.port, share=args.share)
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/gradio_web_server.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import datetime
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import requests
|
| 9 |
+
|
| 10 |
+
from llava.conversation import default_conversation, conv_templates, SeparatorStyle
|
| 11 |
+
from llava.constants import LOGDIR
|
| 12 |
+
from llava.utils import build_logger, server_error_msg, violates_moderation, moderation_msg
|
| 13 |
+
import hashlib
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
logger = build_logger("gradio_web_server", "gradio_web_server.log")
|
| 17 |
+
|
| 18 |
+
headers = {"User-Agent": "LLaVA Client"}
|
| 19 |
+
|
| 20 |
+
no_change_btn = gr.Button.update()
|
| 21 |
+
enable_btn = gr.Button.update(interactive=True)
|
| 22 |
+
disable_btn = gr.Button.update(interactive=False)
|
| 23 |
+
|
| 24 |
+
priority = {
|
| 25 |
+
"vicuna-13b": "aaaaaaa",
|
| 26 |
+
"koala-13b": "aaaaaab",
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_conv_log_filename():
|
| 31 |
+
t = datetime.datetime.now()
|
| 32 |
+
name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
|
| 33 |
+
return name
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_model_list():
|
| 37 |
+
ret = requests.post(args.controller_url + "/refresh_all_workers")
|
| 38 |
+
assert ret.status_code == 200
|
| 39 |
+
ret = requests.post(args.controller_url + "/list_models")
|
| 40 |
+
models = ret.json()["models"]
|
| 41 |
+
models.sort(key=lambda x: priority.get(x, x))
|
| 42 |
+
logger.info(f"Models: {models}")
|
| 43 |
+
return models
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
get_window_url_params = """
|
| 47 |
+
function() {
|
| 48 |
+
const params = new URLSearchParams(window.location.search);
|
| 49 |
+
url_params = Object.fromEntries(params);
|
| 50 |
+
console.log(url_params);
|
| 51 |
+
return url_params;
|
| 52 |
+
}
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def load_demo(url_params, request: gr.Request):
|
| 57 |
+
logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
|
| 58 |
+
|
| 59 |
+
dropdown_update = gr.Dropdown.update(visible=True)
|
| 60 |
+
if "model" in url_params:
|
| 61 |
+
model = url_params["model"]
|
| 62 |
+
if model in models:
|
| 63 |
+
dropdown_update = gr.Dropdown.update(value=model, visible=True)
|
| 64 |
+
|
| 65 |
+
state = default_conversation.copy()
|
| 66 |
+
return state, dropdown_update
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def load_demo_refresh_model_list(request: gr.Request):
|
| 70 |
+
logger.info(f"load_demo. ip: {request.client.host}")
|
| 71 |
+
models = get_model_list()
|
| 72 |
+
state = default_conversation.copy()
|
| 73 |
+
dropdown_update = gr.Dropdown.update(choices=models, value=models[0] if len(models) > 0 else "")
|
| 74 |
+
return state, dropdown_update
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def vote_last_response(state, vote_type, model_selector, request: gr.Request):
|
| 78 |
+
with open(get_conv_log_filename(), "a") as fout:
|
| 79 |
+
data = {
|
| 80 |
+
"tstamp": round(time.time(), 4),
|
| 81 |
+
"type": vote_type,
|
| 82 |
+
"model": model_selector,
|
| 83 |
+
"state": state.dict(),
|
| 84 |
+
"ip": request.client.host,
|
| 85 |
+
}
|
| 86 |
+
fout.write(json.dumps(data) + "\n")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def upvote_last_response(state, model_selector, request: gr.Request):
|
| 90 |
+
logger.info(f"upvote. ip: {request.client.host}")
|
| 91 |
+
vote_last_response(state, "upvote", model_selector, request)
|
| 92 |
+
return ("",) + (disable_btn,) * 3
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def downvote_last_response(state, model_selector, request: gr.Request):
|
| 96 |
+
logger.info(f"downvote. ip: {request.client.host}")
|
| 97 |
+
vote_last_response(state, "downvote", model_selector, request)
|
| 98 |
+
return ("",) + (disable_btn,) * 3
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def flag_last_response(state, model_selector, request: gr.Request):
|
| 102 |
+
logger.info(f"flag. ip: {request.client.host}")
|
| 103 |
+
vote_last_response(state, "flag", model_selector, request)
|
| 104 |
+
return ("",) + (disable_btn,) * 3
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def regenerate(state, image_process_mode, request: gr.Request):
|
| 108 |
+
logger.info(f"regenerate. ip: {request.client.host}")
|
| 109 |
+
state.messages[-1][-1] = None
|
| 110 |
+
prev_human_msg = state.messages[-2]
|
| 111 |
+
if type(prev_human_msg[1]) in (tuple, list):
|
| 112 |
+
prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
|
| 113 |
+
state.skip_next = False
|
| 114 |
+
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def clear_history(request: gr.Request):
|
| 118 |
+
logger.info(f"clear_history. ip: {request.client.host}")
|
| 119 |
+
state = default_conversation.copy()
|
| 120 |
+
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def add_text(state, text, image, image_process_mode, request: gr.Request):
|
| 124 |
+
logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
|
| 125 |
+
if len(text) <= 0 and image is None:
|
| 126 |
+
state.skip_next = True
|
| 127 |
+
return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
|
| 128 |
+
if args.moderate:
|
| 129 |
+
flagged = violates_moderation(text)
|
| 130 |
+
if flagged:
|
| 131 |
+
state.skip_next = True
|
| 132 |
+
return (state, state.to_gradio_chatbot(), moderation_msg, None) + (no_change_btn,) * 5
|
| 133 |
+
|
| 134 |
+
text = text[:1536] # Hard cut-off
|
| 135 |
+
if image is not None:
|
| 136 |
+
text = text[:1200] # Hard cut-off for images
|
| 137 |
+
if "<image>" not in text:
|
| 138 |
+
# text = '<Image><image></Image>' + text
|
| 139 |
+
text = text + "\n<image>"
|
| 140 |
+
text = (text, image, image_process_mode)
|
| 141 |
+
if len(state.get_images(return_pil=True)) > 0:
|
| 142 |
+
state = default_conversation.copy()
|
| 143 |
+
state.append_message(state.roles[0], text)
|
| 144 |
+
state.append_message(state.roles[1], None)
|
| 145 |
+
state.skip_next = False
|
| 146 |
+
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request, template_name=None):
|
| 150 |
+
logger.info(f"http_bot. ip: {request.client.host}")
|
| 151 |
+
start_tstamp = time.time()
|
| 152 |
+
model_name = model_selector
|
| 153 |
+
|
| 154 |
+
if state.skip_next:
|
| 155 |
+
# This generate call is skipped due to invalid inputs
|
| 156 |
+
yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
|
| 157 |
+
return
|
| 158 |
+
|
| 159 |
+
if len(state.messages) == state.offset + 2:
|
| 160 |
+
# First round of conversation
|
| 161 |
+
if "llava" in model_name.lower():
|
| 162 |
+
if "llama-2" in model_name.lower():
|
| 163 |
+
template_name = "llava_llama_2"
|
| 164 |
+
elif "mistral" in model_name.lower() or "mixtral" in model_name.lower():
|
| 165 |
+
if "orca" in model_name.lower():
|
| 166 |
+
template_name = "mistral_orca"
|
| 167 |
+
elif "hermes" in model_name.lower():
|
| 168 |
+
template_name = "mistral_direct"
|
| 169 |
+
else:
|
| 170 |
+
template_name = "mistral_instruct"
|
| 171 |
+
elif "zephyr" in model_name.lower():
|
| 172 |
+
template_name = "mistral_zephyr"
|
| 173 |
+
elif "hermes" in model_name.lower():
|
| 174 |
+
template_name = "mistral_direct"
|
| 175 |
+
elif "v1" in model_name.lower():
|
| 176 |
+
if "mmtag" in model_name.lower():
|
| 177 |
+
template_name = "llava_v1_mmtag"
|
| 178 |
+
elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
|
| 179 |
+
template_name = "llava_v1_mmtag"
|
| 180 |
+
else:
|
| 181 |
+
template_name = "llava_v1"
|
| 182 |
+
elif "mpt" in model_name.lower():
|
| 183 |
+
template_name = "mpt"
|
| 184 |
+
else:
|
| 185 |
+
if "mmtag" in model_name.lower():
|
| 186 |
+
template_name = "v0_plain"
|
| 187 |
+
elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
|
| 188 |
+
template_name = "v0_plain"
|
| 189 |
+
else:
|
| 190 |
+
template_name = "llava_v0"
|
| 191 |
+
elif "mistral" in model_name.lower() or "mixtral" in model_name.lower():
|
| 192 |
+
if "orca" in model_name.lower():
|
| 193 |
+
template_name = "mistral_orca"
|
| 194 |
+
elif "hermes" in model_name.lower():
|
| 195 |
+
template_name = "mistral_direct"
|
| 196 |
+
else:
|
| 197 |
+
template_name = "mistral_instruct"
|
| 198 |
+
elif "hermes" in model_name.lower():
|
| 199 |
+
template_name = "mistral_direct"
|
| 200 |
+
elif "zephyr" in model_name.lower():
|
| 201 |
+
template_name = "mistral_zephyr"
|
| 202 |
+
elif "mpt" in model_name:
|
| 203 |
+
template_name = "mpt_text"
|
| 204 |
+
elif "llama-2" in model_name:
|
| 205 |
+
template_name = "llama_2"
|
| 206 |
+
else:
|
| 207 |
+
template_name = "vicuna_v1"
|
| 208 |
+
new_state = conv_templates[template_name].copy()
|
| 209 |
+
new_state.append_message(new_state.roles[0], state.messages[-2][1])
|
| 210 |
+
new_state.append_message(new_state.roles[1], None)
|
| 211 |
+
state = new_state
|
| 212 |
+
|
| 213 |
+
# Query worker address
|
| 214 |
+
controller_url = args.controller_url
|
| 215 |
+
ret = requests.post(controller_url + "/get_worker_address", json={"model": model_name})
|
| 216 |
+
worker_addr = ret.json()["address"]
|
| 217 |
+
logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
|
| 218 |
+
|
| 219 |
+
# No available worker
|
| 220 |
+
if worker_addr == "":
|
| 221 |
+
state.messages[-1][-1] = server_error_msg
|
| 222 |
+
yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
| 223 |
+
return
|
| 224 |
+
|
| 225 |
+
# Construct prompt
|
| 226 |
+
prompt = state.get_prompt()
|
| 227 |
+
|
| 228 |
+
all_images = state.get_images(return_pil=True)
|
| 229 |
+
all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
|
| 230 |
+
for image, hash in zip(all_images, all_image_hash):
|
| 231 |
+
t = datetime.datetime.now()
|
| 232 |
+
filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
|
| 233 |
+
if not os.path.isfile(filename):
|
| 234 |
+
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
| 235 |
+
image.save(filename)
|
| 236 |
+
|
| 237 |
+
# Make requests
|
| 238 |
+
pload = {
|
| 239 |
+
"model": model_name,
|
| 240 |
+
"prompt": prompt,
|
| 241 |
+
"temperature": float(temperature),
|
| 242 |
+
"top_p": float(top_p),
|
| 243 |
+
"max_new_tokens": min(int(max_new_tokens), 1536),
|
| 244 |
+
"stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
|
| 245 |
+
"images": f"List of {len(state.get_images())} images: {all_image_hash}",
|
| 246 |
+
}
|
| 247 |
+
logger.info(f"==== request ====\n{pload}")
|
| 248 |
+
|
| 249 |
+
pload["images"] = state.get_images()
|
| 250 |
+
|
| 251 |
+
state.messages[-1][-1] = "▌"
|
| 252 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
| 253 |
+
|
| 254 |
+
try:
|
| 255 |
+
# Stream output
|
| 256 |
+
response = requests.post(worker_addr + "/worker_generate_stream", headers=headers, json=pload, stream=True, timeout=100)
|
| 257 |
+
last_print_time = time.time()
|
| 258 |
+
for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
|
| 259 |
+
if chunk:
|
| 260 |
+
data = json.loads(chunk.decode())
|
| 261 |
+
if data["error_code"] == 0:
|
| 262 |
+
output = data["text"][len(prompt) :].strip()
|
| 263 |
+
state.messages[-1][-1] = output + "▌"
|
| 264 |
+
if time.time() - last_print_time > 0.05:
|
| 265 |
+
last_print_time = time.time()
|
| 266 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
| 267 |
+
else:
|
| 268 |
+
output = data["text"] + f" (error_code: {data['error_code']})"
|
| 269 |
+
state.messages[-1][-1] = output
|
| 270 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
| 271 |
+
return
|
| 272 |
+
time.sleep(0.03)
|
| 273 |
+
except requests.exceptions.RequestException as e:
|
| 274 |
+
state.messages[-1][-1] = server_error_msg
|
| 275 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
| 276 |
+
return
|
| 277 |
+
|
| 278 |
+
state.messages[-1][-1] = state.messages[-1][-1][:-1]
|
| 279 |
+
yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
|
| 280 |
+
|
| 281 |
+
finish_tstamp = time.time()
|
| 282 |
+
logger.info(f"{output}")
|
| 283 |
+
|
| 284 |
+
with open(get_conv_log_filename(), "a") as fout:
|
| 285 |
+
data = {
|
| 286 |
+
"tstamp": round(finish_tstamp, 4),
|
| 287 |
+
"type": "chat",
|
| 288 |
+
"model": model_name,
|
| 289 |
+
"start": round(start_tstamp, 4),
|
| 290 |
+
"finish": round(start_tstamp, 4),
|
| 291 |
+
"state": state.dict(),
|
| 292 |
+
"images": all_image_hash,
|
| 293 |
+
"ip": request.client.host,
|
| 294 |
+
}
|
| 295 |
+
fout.write(json.dumps(data) + "\n")
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
title_markdown = """
|
| 299 |
+
# 🌋 LLaVA: Large Language and Vision Assistant
|
| 300 |
+
[[Project Page](https://llava-vl.github.io)] [[Code](https://github.com/haotian-liu/LLaVA)] [[Model](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)] | 📚 [[LLaVA](https://arxiv.org/abs/2304.08485)] [[LLaVA-v1.5](https://arxiv.org/abs/2310.03744)]
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
tos_markdown = """
|
| 304 |
+
### Terms of use
|
| 305 |
+
By using this service, users are required to agree to the following terms:
|
| 306 |
+
The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
|
| 307 |
+
Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
|
| 308 |
+
For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
|
| 309 |
+
"""
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
learn_more_markdown = """
|
| 313 |
+
### License
|
| 314 |
+
The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation.
|
| 315 |
+
"""
|
| 316 |
+
|
| 317 |
+
block_css = """
|
| 318 |
+
|
| 319 |
+
#buttons button {
|
| 320 |
+
min-width: min(120px,100%);
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
"""
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def build_demo(embed_mode):
|
| 327 |
+
textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
|
| 328 |
+
with gr.Blocks(title="LLaVA", theme=gr.themes.Default(), css=block_css) as demo:
|
| 329 |
+
state = gr.State()
|
| 330 |
+
|
| 331 |
+
if not embed_mode:
|
| 332 |
+
gr.Markdown(title_markdown)
|
| 333 |
+
|
| 334 |
+
with gr.Row():
|
| 335 |
+
with gr.Column(scale=3):
|
| 336 |
+
with gr.Row(elem_id="model_selector_row"):
|
| 337 |
+
model_selector = gr.Dropdown(choices=models, value=models[0] if len(models) > 0 else "", interactive=True, show_label=False, container=False)
|
| 338 |
+
|
| 339 |
+
imagebox = gr.Image(type="pil")
|
| 340 |
+
image_process_mode = gr.Radio(["Crop", "Resize", "Pad", "Default"], value="Default", label="Preprocess for non-square image", visible=False)
|
| 341 |
+
|
| 342 |
+
cur_dir = os.path.dirname(os.path.abspath(__file__))
|
| 343 |
+
gr.Examples(
|
| 344 |
+
examples=[
|
| 345 |
+
[f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image?"],
|
| 346 |
+
[f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"],
|
| 347 |
+
],
|
| 348 |
+
inputs=[imagebox, textbox],
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
with gr.Accordion("Parameters", open=False) as parameter_row:
|
| 352 |
+
temperature = gr.Slider(
|
| 353 |
+
minimum=0.0,
|
| 354 |
+
maximum=1.0,
|
| 355 |
+
value=0.2,
|
| 356 |
+
step=0.1,
|
| 357 |
+
interactive=True,
|
| 358 |
+
label="Temperature",
|
| 359 |
+
)
|
| 360 |
+
top_p = gr.Slider(
|
| 361 |
+
minimum=0.0,
|
| 362 |
+
maximum=1.0,
|
| 363 |
+
value=0.7,
|
| 364 |
+
step=0.1,
|
| 365 |
+
interactive=True,
|
| 366 |
+
label="Top P",
|
| 367 |
+
)
|
| 368 |
+
max_output_tokens = gr.Slider(
|
| 369 |
+
minimum=0,
|
| 370 |
+
maximum=1024,
|
| 371 |
+
value=512,
|
| 372 |
+
step=64,
|
| 373 |
+
interactive=True,
|
| 374 |
+
label="Max output tokens",
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
with gr.Column(scale=8):
|
| 378 |
+
chatbot = gr.Chatbot(elem_id="chatbot", label="LLaVA Chatbot", height=550)
|
| 379 |
+
with gr.Row():
|
| 380 |
+
with gr.Column(scale=8):
|
| 381 |
+
textbox.render()
|
| 382 |
+
with gr.Column(scale=1, min_width=50):
|
| 383 |
+
submit_btn = gr.Button(value="Send", variant="primary")
|
| 384 |
+
with gr.Row(elem_id="buttons") as button_row:
|
| 385 |
+
upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
|
| 386 |
+
downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
|
| 387 |
+
flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
|
| 388 |
+
# stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False)
|
| 389 |
+
regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
|
| 390 |
+
clear_btn = gr.Button(value="🗑️ Clear", interactive=False)
|
| 391 |
+
|
| 392 |
+
if not embed_mode:
|
| 393 |
+
gr.Markdown(tos_markdown)
|
| 394 |
+
gr.Markdown(learn_more_markdown)
|
| 395 |
+
url_params = gr.JSON(visible=False)
|
| 396 |
+
|
| 397 |
+
# Register listeners
|
| 398 |
+
btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
|
| 399 |
+
upvote_btn.click(upvote_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn], queue=False)
|
| 400 |
+
downvote_btn.click(downvote_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn], queue=False)
|
| 401 |
+
flag_btn.click(flag_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn], queue=False)
|
| 402 |
+
|
| 403 |
+
regenerate_btn.click(regenerate, [state, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list, queue=False).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list)
|
| 404 |
+
|
| 405 |
+
clear_btn.click(clear_history, None, [state, chatbot, textbox, imagebox] + btn_list, queue=False)
|
| 406 |
+
|
| 407 |
+
textbox.submit(add_text, [state, textbox, imagebox, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list, queue=False).then(
|
| 408 |
+
http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
submit_btn.click(add_text, [state, textbox, imagebox, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list, queue=False).then(
|
| 412 |
+
http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
if args.model_list_mode == "once":
|
| 416 |
+
demo.load(load_demo, [url_params], [state, model_selector], _js=get_window_url_params, queue=False)
|
| 417 |
+
elif args.model_list_mode == "reload":
|
| 418 |
+
demo.load(load_demo_refresh_model_list, None, [state, model_selector], queue=False)
|
| 419 |
+
else:
|
| 420 |
+
raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
|
| 421 |
+
|
| 422 |
+
return demo
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
if __name__ == "__main__":
|
| 426 |
+
parser = argparse.ArgumentParser()
|
| 427 |
+
parser.add_argument("--host", type=str, default="0.0.0.0")
|
| 428 |
+
parser.add_argument("--port", type=int)
|
| 429 |
+
parser.add_argument("--controller-url", type=str, default="http://localhost:21001")
|
| 430 |
+
parser.add_argument("--concurrency-count", type=int, default=10)
|
| 431 |
+
parser.add_argument("--model-list-mode", type=str, default="once", choices=["once", "reload"])
|
| 432 |
+
parser.add_argument("--share", action="store_true")
|
| 433 |
+
parser.add_argument("--moderate", action="store_true")
|
| 434 |
+
parser.add_argument("--embed", action="store_true")
|
| 435 |
+
args = parser.parse_args()
|
| 436 |
+
logger.info(f"args: {args}")
|
| 437 |
+
|
| 438 |
+
models = get_model_list()
|
| 439 |
+
|
| 440 |
+
logger.info(args)
|
| 441 |
+
demo = build_demo(args.embed)
|
| 442 |
+
demo.queue(concurrency_count=args.concurrency_count, api_open=False).launch(server_name=args.host, server_port=args.port, share=args.share)
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/model_worker.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import asyncio
|
| 7 |
+
import json
|
| 8 |
+
import time
|
| 9 |
+
import threading
|
| 10 |
+
import uuid
|
| 11 |
+
|
| 12 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 13 |
+
from fastapi.responses import StreamingResponse
|
| 14 |
+
import requests
|
| 15 |
+
import torch
|
| 16 |
+
import uvicorn
|
| 17 |
+
from functools import partial
|
| 18 |
+
|
| 19 |
+
from llava.constants import WORKER_HEART_BEAT_INTERVAL
|
| 20 |
+
from llava.utils import build_logger, server_error_msg, pretty_print_semaphore
|
| 21 |
+
from llava.model.builder import load_pretrained_model
|
| 22 |
+
from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, KeywordsStoppingCriteria
|
| 23 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 24 |
+
from transformers import TextIteratorStreamer
|
| 25 |
+
from threading import Thread
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
GB = 1 << 30
|
| 29 |
+
|
| 30 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 31 |
+
logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
|
| 32 |
+
global_counter = 0
|
| 33 |
+
|
| 34 |
+
model_semaphore = None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def heart_beat_worker(controller):
|
| 38 |
+
|
| 39 |
+
while True:
|
| 40 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 41 |
+
controller.send_heart_beat()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ModelWorker:
|
| 45 |
+
def __init__(self, controller_addr, worker_addr, worker_id, no_register, model_path, model_base, model_name, load_8bit, load_4bit):
|
| 46 |
+
self.controller_addr = controller_addr
|
| 47 |
+
self.worker_addr = worker_addr
|
| 48 |
+
self.worker_id = worker_id
|
| 49 |
+
if model_path.endswith("/"):
|
| 50 |
+
model_path = model_path[:-1]
|
| 51 |
+
if model_name is None:
|
| 52 |
+
model_paths = model_path.split("/")
|
| 53 |
+
if model_paths[-1].startswith("checkpoint-"):
|
| 54 |
+
self.model_name = model_paths[-2] + "_" + model_paths[-1]
|
| 55 |
+
else:
|
| 56 |
+
self.model_name = model_paths[-1]
|
| 57 |
+
else:
|
| 58 |
+
self.model_name = model_name
|
| 59 |
+
|
| 60 |
+
logger.info(f"Loading the model {self.model_name} on worker {worker_id} ...")
|
| 61 |
+
self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model(model_path, model_base, self.model_name, load_8bit, load_4bit)
|
| 62 |
+
self.is_multimodal = "llava" in self.model_name.lower()
|
| 63 |
+
|
| 64 |
+
if not no_register:
|
| 65 |
+
self.register_to_controller()
|
| 66 |
+
self.heart_beat_thread = threading.Thread(target=heart_beat_worker, args=(self,))
|
| 67 |
+
self.heart_beat_thread.start()
|
| 68 |
+
|
| 69 |
+
def register_to_controller(self):
|
| 70 |
+
logger.info("Register to controller")
|
| 71 |
+
|
| 72 |
+
url = self.controller_addr + "/register_worker"
|
| 73 |
+
data = {"worker_name": self.worker_addr, "check_heart_beat": True, "worker_status": self.get_status()}
|
| 74 |
+
r = requests.post(url, json=data)
|
| 75 |
+
assert r.status_code == 200
|
| 76 |
+
|
| 77 |
+
def send_heart_beat(self):
|
| 78 |
+
logger.info(f"Send heart beat. Models: {[self.model_name]}. " f"Semaphore: {pretty_print_semaphore(model_semaphore)}. " f"global_counter: {global_counter}")
|
| 79 |
+
|
| 80 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 81 |
+
|
| 82 |
+
while True:
|
| 83 |
+
try:
|
| 84 |
+
ret = requests.post(url, json={"worker_name": self.worker_addr, "queue_length": self.get_queue_length()}, timeout=5)
|
| 85 |
+
exist = ret.json()["exist"]
|
| 86 |
+
break
|
| 87 |
+
except requests.exceptions.RequestException as e:
|
| 88 |
+
logger.error(f"heart beat error: {e}")
|
| 89 |
+
time.sleep(5)
|
| 90 |
+
|
| 91 |
+
if not exist:
|
| 92 |
+
self.register_to_controller()
|
| 93 |
+
|
| 94 |
+
def get_queue_length(self):
|
| 95 |
+
if model_semaphore is None:
|
| 96 |
+
return 0
|
| 97 |
+
else:
|
| 98 |
+
return args.limit_model_concurrency - model_semaphore._value + (len(model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
|
| 99 |
+
|
| 100 |
+
def get_status(self):
|
| 101 |
+
return {
|
| 102 |
+
"model_names": [self.model_name],
|
| 103 |
+
"speed": 1,
|
| 104 |
+
"queue_length": self.get_queue_length(),
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
@torch.inference_mode()
|
| 108 |
+
def generate_stream(self, params):
|
| 109 |
+
tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor
|
| 110 |
+
|
| 111 |
+
prompt = params["prompt"]
|
| 112 |
+
ori_prompt = prompt
|
| 113 |
+
images = params.get("images", None)
|
| 114 |
+
num_image_tokens = 0
|
| 115 |
+
if images is not None and len(images) > 0 and self.is_multimodal:
|
| 116 |
+
if len(images) > 0:
|
| 117 |
+
if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
|
| 118 |
+
raise ValueError("Number of images does not match number of <image> tokens in prompt")
|
| 119 |
+
|
| 120 |
+
images = [load_image_from_base64(image) for image in images]
|
| 121 |
+
image_sizes = [image.size for image in images]
|
| 122 |
+
images = process_images(images, image_processor, model.config)
|
| 123 |
+
|
| 124 |
+
if type(images) is list:
|
| 125 |
+
images = [image.to(self.model.device, dtype=torch.float16) for image in images]
|
| 126 |
+
else:
|
| 127 |
+
images = images.to(self.model.device, dtype=torch.float16)
|
| 128 |
+
|
| 129 |
+
replace_token = DEFAULT_IMAGE_TOKEN
|
| 130 |
+
if getattr(self.model.config, "mm_use_im_start_end", False):
|
| 131 |
+
replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
|
| 132 |
+
prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
|
| 133 |
+
|
| 134 |
+
num_image_tokens = prompt.count(replace_token) * model.get_vision_tower().num_patches
|
| 135 |
+
else:
|
| 136 |
+
images = None
|
| 137 |
+
image_sizes = None
|
| 138 |
+
image_args = {"images": images, "image_sizes": image_sizes}
|
| 139 |
+
else:
|
| 140 |
+
images = None
|
| 141 |
+
image_args = {}
|
| 142 |
+
|
| 143 |
+
temperature = float(params.get("temperature", 1.0))
|
| 144 |
+
top_p = float(params.get("top_p", 1.0))
|
| 145 |
+
max_context_length = getattr(model.config, "max_position_embeddings", 2048)
|
| 146 |
+
max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
|
| 147 |
+
stop_str = params.get("stop", None)
|
| 148 |
+
do_sample = True if temperature > 0.001 else False
|
| 149 |
+
|
| 150 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
|
| 151 |
+
keywords = [stop_str]
|
| 152 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
| 153 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15)
|
| 154 |
+
|
| 155 |
+
max_new_tokens = min(max_new_tokens, max_context_length - input_ids.shape[-1] - num_image_tokens)
|
| 156 |
+
|
| 157 |
+
if max_new_tokens < 1:
|
| 158 |
+
yield json.dumps({"text": ori_prompt + "Exceeds max token length. Please start a new conversation, thanks.", "error_code": 0}).encode() + b"\0"
|
| 159 |
+
return
|
| 160 |
+
|
| 161 |
+
thread = Thread(
|
| 162 |
+
target=model.generate,
|
| 163 |
+
kwargs=dict(
|
| 164 |
+
inputs=input_ids,
|
| 165 |
+
do_sample=do_sample,
|
| 166 |
+
temperature=temperature,
|
| 167 |
+
top_p=top_p,
|
| 168 |
+
max_new_tokens=max_new_tokens,
|
| 169 |
+
streamer=streamer,
|
| 170 |
+
# stopping_criteria=[stopping_criteria],
|
| 171 |
+
use_cache=True,
|
| 172 |
+
**image_args,
|
| 173 |
+
),
|
| 174 |
+
)
|
| 175 |
+
thread.start()
|
| 176 |
+
|
| 177 |
+
start_time = time.time()
|
| 178 |
+
generated_text = ori_prompt
|
| 179 |
+
for new_text in streamer:
|
| 180 |
+
generated_text += new_text
|
| 181 |
+
if generated_text.endswith(stop_str):
|
| 182 |
+
generated_text = generated_text[: -len(stop_str)]
|
| 183 |
+
yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0"
|
| 184 |
+
|
| 185 |
+
end_time = time.time()
|
| 186 |
+
|
| 187 |
+
new_generated = generated_text[len(ori_prompt) :]
|
| 188 |
+
new_generated_tokens = tokenizer(new_generated).input_ids
|
| 189 |
+
token_per_second = len(new_generated_tokens) / (end_time - start_time)
|
| 190 |
+
print(f"token_per_second: {token_per_second}")
|
| 191 |
+
|
| 192 |
+
def generate_stream_gate(self, params):
|
| 193 |
+
try:
|
| 194 |
+
for x in self.generate_stream(params):
|
| 195 |
+
yield x
|
| 196 |
+
except ValueError as e:
|
| 197 |
+
print("Caught ValueError:", e)
|
| 198 |
+
ret = {
|
| 199 |
+
"text": server_error_msg,
|
| 200 |
+
"error_code": 1,
|
| 201 |
+
}
|
| 202 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 203 |
+
except torch.cuda.CudaError as e:
|
| 204 |
+
print("Caught torch.cuda.CudaError:", e)
|
| 205 |
+
ret = {
|
| 206 |
+
"text": server_error_msg,
|
| 207 |
+
"error_code": 1,
|
| 208 |
+
}
|
| 209 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 210 |
+
except Exception as e:
|
| 211 |
+
print("Caught Unknown Error", e)
|
| 212 |
+
ret = {
|
| 213 |
+
"text": server_error_msg,
|
| 214 |
+
"error_code": 1,
|
| 215 |
+
}
|
| 216 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
app = FastAPI()
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def release_model_semaphore(fn=None):
|
| 223 |
+
model_semaphore.release()
|
| 224 |
+
if fn is not None:
|
| 225 |
+
fn()
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
@app.post("/worker_generate_stream")
|
| 229 |
+
async def generate_stream(request: Request):
|
| 230 |
+
global model_semaphore, global_counter
|
| 231 |
+
global_counter += 1
|
| 232 |
+
params = await request.json()
|
| 233 |
+
|
| 234 |
+
if model_semaphore is None:
|
| 235 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 236 |
+
await model_semaphore.acquire()
|
| 237 |
+
worker.send_heart_beat()
|
| 238 |
+
generator = worker.generate_stream_gate(params)
|
| 239 |
+
background_tasks = BackgroundTasks()
|
| 240 |
+
background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat))
|
| 241 |
+
return StreamingResponse(generator, background=background_tasks)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
@app.post("/worker_get_status")
|
| 245 |
+
async def get_status(request: Request):
|
| 246 |
+
return worker.get_status()
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
if __name__ == "__main__":
|
| 250 |
+
parser = argparse.ArgumentParser()
|
| 251 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 252 |
+
parser.add_argument("--port", type=int, default=21002)
|
| 253 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21002")
|
| 254 |
+
parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
|
| 255 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
| 256 |
+
parser.add_argument("--model-base", type=str, default=None)
|
| 257 |
+
parser.add_argument("--model-name", type=str)
|
| 258 |
+
parser.add_argument("--multi-modal", action="store_true", help="Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.")
|
| 259 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 260 |
+
parser.add_argument("--stream-interval", type=int, default=1)
|
| 261 |
+
parser.add_argument("--no-register", action="store_true")
|
| 262 |
+
parser.add_argument("--load-8bit", action="store_true")
|
| 263 |
+
parser.add_argument("--load-4bit", action="store_true")
|
| 264 |
+
args = parser.parse_args()
|
| 265 |
+
logger.info(f"args: {args}")
|
| 266 |
+
|
| 267 |
+
if args.multi_modal:
|
| 268 |
+
logger.warning("Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.")
|
| 269 |
+
|
| 270 |
+
worker = ModelWorker(args.controller_address, args.worker_address, worker_id, args.no_register, args.model_path, args.model_base, args.model_name, args.load_8bit, args.load_4bit)
|
| 271 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/register_worker.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Manually register workers.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
python3 -m fastchat.serve.register_worker --controller http://localhost:21001 --worker-name http://localhost:21002
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
|
| 12 |
+
if __name__ == "__main__":
|
| 13 |
+
parser = argparse.ArgumentParser()
|
| 14 |
+
parser.add_argument("--controller-address", type=str)
|
| 15 |
+
parser.add_argument("--worker-name", type=str)
|
| 16 |
+
parser.add_argument("--check-heart-beat", action="store_true")
|
| 17 |
+
args = parser.parse_args()
|
| 18 |
+
|
| 19 |
+
url = args.controller_address + "/register_worker"
|
| 20 |
+
data = {
|
| 21 |
+
"worker_name": args.worker_name,
|
| 22 |
+
"check_heart_beat": args.check_heart_beat,
|
| 23 |
+
"worker_status": None,
|
| 24 |
+
}
|
| 25 |
+
r = requests.post(url, json=data)
|
| 26 |
+
assert r.status_code == 200
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/sglang_worker.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import asyncio
|
| 7 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 8 |
+
import json
|
| 9 |
+
import time
|
| 10 |
+
import threading
|
| 11 |
+
import uuid
|
| 12 |
+
|
| 13 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 14 |
+
from fastapi.responses import StreamingResponse
|
| 15 |
+
import requests
|
| 16 |
+
import re
|
| 17 |
+
import uvicorn
|
| 18 |
+
from functools import partial
|
| 19 |
+
|
| 20 |
+
from llava.constants import WORKER_HEART_BEAT_INTERVAL
|
| 21 |
+
from llava.utils import build_logger, server_error_msg, pretty_print_semaphore
|
| 22 |
+
from llava.model.builder import load_pretrained_model
|
| 23 |
+
from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, expand2square
|
| 24 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 25 |
+
from transformers import AutoTokenizer
|
| 26 |
+
|
| 27 |
+
import sglang as sgl
|
| 28 |
+
from sglang.test.test_utils import add_common_sglang_args_and_parse, select_sglang_backend
|
| 29 |
+
from sglang.backend.runtime_endpoint import RuntimeEndpoint
|
| 30 |
+
from sglang.utils import read_jsonl, dump_state_text
|
| 31 |
+
from sglang.lang.interpreter import ProgramState
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
GB = 1 << 30
|
| 35 |
+
|
| 36 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 37 |
+
logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
|
| 38 |
+
global_counter = 0
|
| 39 |
+
|
| 40 |
+
model_semaphore = None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def heart_beat_worker(controller):
|
| 44 |
+
while True:
|
| 45 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 46 |
+
controller.send_heart_beat()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@sgl.function
|
| 50 |
+
def pipeline(s, prompt, max_tokens):
|
| 51 |
+
for p in prompt:
|
| 52 |
+
if type(p) is str:
|
| 53 |
+
s += p
|
| 54 |
+
else:
|
| 55 |
+
s += sgl.image(p)
|
| 56 |
+
s += sgl.gen("response", max_tokens=max_tokens)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class ModelWorker:
|
| 60 |
+
def __init__(self, controller_addr, worker_addr, sgl_endpoint, worker_id, no_register, model_name):
|
| 61 |
+
self.controller_addr = controller_addr
|
| 62 |
+
self.worker_addr = worker_addr
|
| 63 |
+
self.worker_id = worker_id
|
| 64 |
+
|
| 65 |
+
# Select backend
|
| 66 |
+
backend = RuntimeEndpoint(sgl_endpoint)
|
| 67 |
+
sgl.set_default_backend(backend)
|
| 68 |
+
model_path = backend.model_info["model_path"]
|
| 69 |
+
|
| 70 |
+
if model_path.endswith("/"):
|
| 71 |
+
model_path = model_path[:-1]
|
| 72 |
+
if model_name is None:
|
| 73 |
+
model_paths = model_path.split("/")
|
| 74 |
+
if model_paths[-1].startswith("checkpoint-"):
|
| 75 |
+
self.model_name = model_paths[-2] + "_" + model_paths[-1]
|
| 76 |
+
else:
|
| 77 |
+
self.model_name = model_paths[-1]
|
| 78 |
+
else:
|
| 79 |
+
self.model_name = model_name
|
| 80 |
+
|
| 81 |
+
logger.info(f"Loading the SGLANG model {self.model_name} on worker {worker_id} ...")
|
| 82 |
+
|
| 83 |
+
if not no_register:
|
| 84 |
+
self.register_to_controller()
|
| 85 |
+
self.heart_beat_thread = threading.Thread(target=heart_beat_worker, args=(self,))
|
| 86 |
+
self.heart_beat_thread.start()
|
| 87 |
+
|
| 88 |
+
def register_to_controller(self):
|
| 89 |
+
logger.info("Register to controller")
|
| 90 |
+
|
| 91 |
+
url = self.controller_addr + "/register_worker"
|
| 92 |
+
data = {"worker_name": self.worker_addr, "check_heart_beat": True, "worker_status": self.get_status()}
|
| 93 |
+
r = requests.post(url, json=data)
|
| 94 |
+
assert r.status_code == 200
|
| 95 |
+
|
| 96 |
+
def send_heart_beat(self):
|
| 97 |
+
logger.info(f"Send heart beat. Models: {[self.model_name]}. " f"Semaphore: {pretty_print_semaphore(model_semaphore)}. " f"global_counter: {global_counter}")
|
| 98 |
+
|
| 99 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 100 |
+
|
| 101 |
+
while True:
|
| 102 |
+
try:
|
| 103 |
+
ret = requests.post(url, json={"worker_name": self.worker_addr, "queue_length": self.get_queue_length()}, timeout=5)
|
| 104 |
+
exist = ret.json()["exist"]
|
| 105 |
+
break
|
| 106 |
+
except requests.exceptions.RequestException as e:
|
| 107 |
+
logger.error(f"heart beat error: {e}")
|
| 108 |
+
time.sleep(5)
|
| 109 |
+
|
| 110 |
+
if not exist:
|
| 111 |
+
self.register_to_controller()
|
| 112 |
+
|
| 113 |
+
def get_queue_length(self):
|
| 114 |
+
if model_semaphore is None:
|
| 115 |
+
return 0
|
| 116 |
+
else:
|
| 117 |
+
return args.limit_model_concurrency - model_semaphore._value + (len(model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
|
| 118 |
+
|
| 119 |
+
def get_status(self):
|
| 120 |
+
return {
|
| 121 |
+
"model_names": [self.model_name],
|
| 122 |
+
"speed": 1,
|
| 123 |
+
"queue_length": self.get_queue_length(),
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
async def generate_stream(self, params):
|
| 127 |
+
ori_prompt = prompt = params["prompt"]
|
| 128 |
+
images = params.get("images", None)
|
| 129 |
+
if images is not None and len(images) > 0:
|
| 130 |
+
if len(images) > 0:
|
| 131 |
+
if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
|
| 132 |
+
raise ValueError("Number of images does not match number of <image> tokens in prompt")
|
| 133 |
+
|
| 134 |
+
images = [load_image_from_base64(image) for image in images]
|
| 135 |
+
# FIXME: hacky padding
|
| 136 |
+
images = [expand2square(image, tuple(int(x * 255) for x in [0.48145466, 0.4578275, 0.40821073])) for image in images]
|
| 137 |
+
|
| 138 |
+
# FIXME: for image-start/end token
|
| 139 |
+
# replace_token = DEFAULT_IMAGE_TOKEN
|
| 140 |
+
# if getattr(self.model.config, 'mm_use_im_start_end', False):
|
| 141 |
+
# replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
|
| 142 |
+
# prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
|
| 143 |
+
prompt = prompt.replace(" " + DEFAULT_IMAGE_TOKEN + "\n", DEFAULT_IMAGE_TOKEN)
|
| 144 |
+
prompt_split = prompt.split(DEFAULT_IMAGE_TOKEN)
|
| 145 |
+
prompt = []
|
| 146 |
+
for i in range(len(prompt_split)):
|
| 147 |
+
prompt.append(prompt_split[i])
|
| 148 |
+
if i < len(images):
|
| 149 |
+
prompt.append(images[i])
|
| 150 |
+
else:
|
| 151 |
+
prompt = [prompt]
|
| 152 |
+
|
| 153 |
+
temperature = float(params.get("temperature", 1.0))
|
| 154 |
+
top_p = float(params.get("top_p", 1.0))
|
| 155 |
+
# max_context_length = getattr(model.config, 'max_position_embeddings', 2048)
|
| 156 |
+
max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
|
| 157 |
+
stop_str = params.get("stop", None)
|
| 158 |
+
stop_str = [stop_str] if stop_str is not None else None
|
| 159 |
+
|
| 160 |
+
if max_new_tokens < 1:
|
| 161 |
+
yield json.dumps({"text": ori_prompt + "Exceeds max token length. Please start a new conversation, thanks.", "error_code": 0}).encode() + b"\0"
|
| 162 |
+
return
|
| 163 |
+
|
| 164 |
+
# print(prompt)
|
| 165 |
+
state = pipeline.run(prompt, max_new_tokens, temperature=temperature, top_p=top_p, stream=True)
|
| 166 |
+
|
| 167 |
+
generated_text = ori_prompt
|
| 168 |
+
async for text_outputs in state.text_async_iter(var_name="response"):
|
| 169 |
+
generated_text += text_outputs
|
| 170 |
+
yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0"
|
| 171 |
+
|
| 172 |
+
async def generate_stream_gate(self, params):
|
| 173 |
+
try:
|
| 174 |
+
async for x in self.generate_stream(params):
|
| 175 |
+
yield x
|
| 176 |
+
except ValueError as e:
|
| 177 |
+
print("Caught ValueError:", e)
|
| 178 |
+
ret = {
|
| 179 |
+
"text": server_error_msg,
|
| 180 |
+
"error_code": 1,
|
| 181 |
+
}
|
| 182 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 183 |
+
except Exception as e:
|
| 184 |
+
print("Caught Unknown Error", e)
|
| 185 |
+
ret = {
|
| 186 |
+
"text": server_error_msg,
|
| 187 |
+
"error_code": 1,
|
| 188 |
+
}
|
| 189 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
app = FastAPI()
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def release_model_semaphore(fn=None):
|
| 196 |
+
model_semaphore.release()
|
| 197 |
+
if fn is not None:
|
| 198 |
+
fn()
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@app.post("/worker_generate_stream")
|
| 202 |
+
async def generate_stream(request: Request):
|
| 203 |
+
global model_semaphore, global_counter
|
| 204 |
+
global_counter += 1
|
| 205 |
+
params = await request.json()
|
| 206 |
+
|
| 207 |
+
if model_semaphore is None:
|
| 208 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 209 |
+
await model_semaphore.acquire()
|
| 210 |
+
worker.send_heart_beat()
|
| 211 |
+
generator = worker.generate_stream_gate(params)
|
| 212 |
+
background_tasks = BackgroundTasks()
|
| 213 |
+
background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat))
|
| 214 |
+
return StreamingResponse(generator, background=background_tasks)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@app.post("/worker_get_status")
|
| 218 |
+
async def get_status(request: Request):
|
| 219 |
+
return worker.get_status()
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
if __name__ == "__main__":
|
| 223 |
+
parser = argparse.ArgumentParser()
|
| 224 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 225 |
+
parser.add_argument("--port", type=int, default=21002)
|
| 226 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21002")
|
| 227 |
+
parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
|
| 228 |
+
parser.add_argument("--model-name", type=str)
|
| 229 |
+
parser.add_argument("--sgl-endpoint", type=str)
|
| 230 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 231 |
+
parser.add_argument("--stream-interval", type=int, default=1)
|
| 232 |
+
parser.add_argument("--no-register", action="store_true")
|
| 233 |
+
args = parser.parse_args()
|
| 234 |
+
logger.info(f"args: {args}")
|
| 235 |
+
|
| 236 |
+
worker = ModelWorker(args.controller_address, args.worker_address, args.sgl_endpoint, worker_id, args.no_register, args.model_name)
|
| 237 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/serve/test_message.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
import requests
|
| 5 |
+
|
| 6 |
+
from llava.conversation import default_conversation
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main():
|
| 10 |
+
if args.worker_address:
|
| 11 |
+
worker_addr = args.worker_address
|
| 12 |
+
else:
|
| 13 |
+
controller_addr = args.controller_address
|
| 14 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 15 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 16 |
+
models = ret.json()["models"]
|
| 17 |
+
models.sort()
|
| 18 |
+
print(f"Models: {models}")
|
| 19 |
+
|
| 20 |
+
ret = requests.post(controller_addr + "/get_worker_address", json={"model": args.model_name})
|
| 21 |
+
worker_addr = ret.json()["address"]
|
| 22 |
+
print(f"worker_addr: {worker_addr}")
|
| 23 |
+
|
| 24 |
+
if worker_addr == "":
|
| 25 |
+
return
|
| 26 |
+
|
| 27 |
+
conv = default_conversation.copy()
|
| 28 |
+
conv.append_message(conv.roles[0], args.message)
|
| 29 |
+
prompt = conv.get_prompt()
|
| 30 |
+
|
| 31 |
+
headers = {"User-Agent": "LLaVA Client"}
|
| 32 |
+
pload = {
|
| 33 |
+
"model": args.model_name,
|
| 34 |
+
"prompt": prompt,
|
| 35 |
+
"max_new_tokens": args.max_new_tokens,
|
| 36 |
+
"temperature": 0.7,
|
| 37 |
+
"stop": conv.sep,
|
| 38 |
+
}
|
| 39 |
+
response = requests.post(worker_addr + "/worker_generate_stream", headers=headers, json=pload, stream=True)
|
| 40 |
+
|
| 41 |
+
print(prompt.replace(conv.sep, "\n"), end="")
|
| 42 |
+
for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False, delimiter=b"\0"):
|
| 43 |
+
if chunk:
|
| 44 |
+
data = json.loads(chunk.decode("utf-8"))
|
| 45 |
+
output = data["text"].split(conv.sep)[-1]
|
| 46 |
+
print(output, end="\r")
|
| 47 |
+
print("")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
parser = argparse.ArgumentParser()
|
| 52 |
+
parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
|
| 53 |
+
parser.add_argument("--worker-address", type=str)
|
| 54 |
+
parser.add_argument("--model-name", type=str, default="facebook/opt-350m")
|
| 55 |
+
parser.add_argument("--max-new-tokens", type=int, default=32)
|
| 56 |
+
parser.add_argument("--message", type=str, default="Tell me a story with more than 1000 words.")
|
| 57 |
+
args = parser.parse_args()
|
| 58 |
+
|
| 59 |
+
main()
|