OA0
OA0 是一个探索 AI 的社区
现在注册
已注册用户请  登录
OA0  ›  代码  ›  OpenBMB TinyLLaVA Factory — 轻量多模态模型训练与微调工厂

OpenBMB TinyLLaVA Factory — 轻量多模态模型训练与微调工厂

 
  vault ·  2026-07-20 11:00:22 · 22 次点击  · 0 条评论  

TinyLLaVA Factory

[![hf_space](https://img.shields.io/badge/🤗-%20Open%20In%20HF-blue.svg)](https://huggingface.co/tinyllava) [![arXiv](https://img.shields.io/badge/Arxiv-2402.14289-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2402.14289) [![arXiv](https://img.shields.io/badge/Arxiv-2405.11788-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2405.11788)[![License](https://img.shields.io/badge/License-Apache%202.0-yellow)](https://github.com/TinyLLaVA/TinyLLaVA_Factory/blob/main/LICENSE) [![Doc](https://img.shields.io/badge/Doc-Document-logo=read%20the%20docs&logoColor=white&label=Doc)](https://tinyllava-factory.readthedocs.io/en/latest/) [![Demo](https://img.shields.io/badge/Demo-Demo-red.svg)](http://8843843nmph5.vicp.fun/#/) ![架构概览](./assets/architecture.jpg) ## 🎉 新闻 - **[2025.01]** 新项目 [TinyLLaVA-Video](https://github.com/ZhangXJ199/TinyLLaVA-Video) 已发布。 - **[2024.08.13]** 新增了一个简易的[可视化工具](https://github.com/TinyLLaVA/TinyLLaVA_Factory/tree/main/tinyllava_visualizer),用于解释 TinyLLaVA 的预测结果。 - **[2024.05.21]** 论文:[TinyLLaVA Factory: A Modularized Codebase for Small-scale Large Multimodal Models](https://arxiv.org/abs/2405.11788) 已发布! - **[2024.05.15** 新版代码库 [TinyLLaVA Factory](https://github.com/TinyLLaVA/TinyLLaVA_Factory) 发布!**注意:旧版代码库 TinyLLaVABench 已迁移至 [tinyllava_bench](https://github.com/TinyLLaVA/TinyLLaVA_Factory/tree/tinyllava_bench) 分支。** - **[2024.05.04]** [TinyLLaVA Demo](http://8843843nmph5.vicp.fun/#/) 已上线!(访问密码:'1234') - **[2024.02.21]** 论文:[TinyLLaVA: A Framework of Small-scale Large Multimodal Models](https://arxiv.org/abs/2402.14289) 已发布! ## 🔥 要点 - 我们的最佳模型 [TinyLLaVA-Phi-2-SigLIP-3.1B](https://huggingface.co/tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B) 在整体性能上优于现有的 7B 模型,如 LLaVA-1.5 和 Qwen-VL。 - TinyLLaVA Factory 是一个面向小型大规模多模态模型(LMM)的开源模块化代码库,基于 PyTorch 和 HuggingFace 实现,重点在于代码实现的简洁性、新功能的可扩展性以及训练结果的可复现性。 - 使用 TinyLLaVA Factory,您可以用更少的编码工作和更少的编码错误来定制自己的大型多模态模型。 - TinyLLaVA Factory 集成了一系列前沿模型和方法。 - 大语言模型(LLM)目前支持 **OpenELM**、**TinyLlama**、**StableLM**、**Qwen**、**Gemma** 和 **Phi**。 - 视觉编码器(Vision tower)目前支持 **CLIP**、**SigLIP**、**Dino** 以及 **CLIP 与 Dino 的组合**。 - 连接器(Connector)目前支持 **MLP**、**Qformer** 和 **Resampler**。 - 训练策略(Training Recipe)目前支持**冻结/全量/部分微调**以及 **LoRA/QLoRA 微调**。 ## 目录 - [🎉 新闻](#-新闻) - [🔥 要点](#-要点) - [目录](#目录) - [安装与环境要求](#安装与环境要求) - [升级到最新代码库](#升级到最新代码库) - [快速开始](#快速开始) - [1. 数据准备](#1-数据准备) - [2. 训练](#2-训练) - [3. 评估](#3-评估) - [模型动物园](#模型动物园) - [已训练模型](#已训练模型) - [模型性能](#模型性能) - [旧版模型](#旧版模型) - [本地启动 Demo](#本地启动-demo) - [Gradio Web 演示](#gradio-web-演示) - [命令行推理](#命令行推理) - [快速推理脚本](#快速推理脚本) - [自定义微调](#自定义微调) - [定制您自己的大型多模态模型](#定制您自己的大型多模态模型) - [大语言模型 (LLM)](#大语言模型-llm) - [视觉编码器 (Vision Tower)](#视觉编码器-vision-tower) - [连接器 (Connector)](#连接器-connector) - [致谢](#致谢) - [联系方式](#联系方式) - [✏️ 引用](#️-引用) - [❤️ 社区贡献](#️-社区贡献) ## 安装与环境要求 请注意,我们的环境要求与 LLaVA 的环境要求不同。我们强烈建议您按以下步骤从头创建环境。 1. 克隆此仓库并进入文件夹
git clone https://github.com/TinyLLaVA/TinyLLaVA_Factory.git
cd TinyLLaVA_Factory
2. 创建 conda 环境,激活并安装软件包
conda create -n tinyllava_factory python=3.10 -y
conda activate tinyllava_factory
pip install --upgrade pip  # 启用 PEP 660 支持
pip install -e .
3. 安装额外的软件包
pip install flash-attn==2.5.7 --no-build-isolation
#### 升级到最新代码库
git pull
pip install -e .
## 快速开始 #### 1. 数据准备 请参考我们的[文档](https://tinyllava-factory.readthedocs.io/en/latest/)中的[数据准备](https://tinyllava-factory.readthedocs.io/en/latest/Prepare%20Datasets.html)部分。 #### 2. 训练 以下是使用 Phi-2 训练 LMM 的示例。 - 在 `scripts/train/train_phi.sh` 中将数据路径替换为您自己的路径 - 在 `scripts/train/pretrain.sh` 中将 `output_dir` 替换为您自己的路径 - 在 `scripts/train/finetune.sh` 中将 `pretrained_model_path` 和 `output_dir` 替换为您自己的路径 - 在 `scripts/train/pretrain.sh` 和 `scripts/train/finetune.sh` 中调整您的 GPU 编号(localhost)和 `per_device_train_batch_size`
bash scripts/train/train_phi.sh
预训练和微调中使用的重要超参数如下。 | 训练阶段 | 全局批次大小 (Global Batch Size) | 学习率 (Learning rate) | conv_version | | --------- | :------------------------------: | :--------------------: | :----------: | | 预训练 | 256 | 1e-3 | pretrain | | 微调 | 128 | 2e-5 | phi | **提示:** 全局批次大小 = GPU 数量 * `per_device_train_batch_size` * `gradient_accumulation_steps`,我们建议您在进行模型微调(LoRA 除外)时,始终将全局批次大小和学习率保持为上述值。 `conv_version` 是一个用于为不同 LLM 选择不同聊天模板的超参数。在预训练阶段,所有 LLM 的 `conv_version` 相同,均为 `pretrain`。在微调阶段,我们使用: - `phi` 对应 Phi-2、StableLM、Qwen-1.5 - `llama` 对应 TinyLlama、OpenELM - `gemma` 对应 Gemma #### 3. 评估 请参考我们的[文档](https://tinyllava-factory.readthedocs.io/en/latest/)中的[评估](https://tinyllava-factory.readthedocs.io/en/latest/Evaluation.html)部分。 ## 模型动物园 ### 已训练模型 这些模型是使用 TinyLLaVA Factory 训练的。 - [TinyLLaVA-Phi-2-SigLIP-3.1B](https://huggingface.co/tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B) - [TinyLLaVA-Gemma-SigLIP-2.4B](https://huggingface.co/tinyllava/TinyLLaVA-Gemma-SigLIP-2.4B) - [TinyLLaVA-OpenELM-450M-SigLIP-0.89B](https://huggingface.co/jiajunlong/TinyLLaVA-0.89B) - [TinyLLaVA-Qwen2-0.5B-SigLIP](https://huggingface.co/Zhang199/TinyLLaVA-Qwen2-0.5B-SigLIP) - [TinyLLaVA-Qwen2.5-3B-SigLIP](https://huggingface.co/Zhang199/TinyLLaVA-Qwen2.5-3B-SigLIP) #### 模型性能 | 视觉编码器 (HF 路径) | 大语言模型 (HF 路径) | 训练策略 | VQA-v2 | GQA | SQA-image | TextVQA | MM-Vet | POPE | MME | MMMU-val | | :-- | :-- | :-- | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | | openai/clip-vit-large-patch14-336 | apple/OpenELM-450M-Instruct | 基础 | 69.5 | 52.1 | 50.6 | 40.4 | 20.0 | 83.6 | 1052.9 | 23.9 | | google/siglip-so400m-patch14-384 | apple/OpenELM-450M-Instruct | 基础 | 71.7 | 53.9 | 54.1 | 44.0 | 20.0 | 85.4 | 1118.8 | 24.0 | | google/siglip-so400m-patch14-384 | Qwen/Qwen2-0.5B | 基础 | 72.3 | 55.8 | 60.1 | 45.2 | 19.5 | 86.6 | 1153.0 | 29.7 | | google/siglip-so400m-patch14-384 | Qwen/Qwen2.5-0.5B | 基础 | 75.3 | 59.5 | 60.3 | 48.3 | 23.9 | 86.1 | 1253.0 | 33.3 | | google/siglip-so400m-patch14-384 | Qwen/Qwen2.5-3B | 基础 | 79.4 | 62.5 | 74.1 | 58.3 | 34.8 | 87.4 | 1438.7 | 39.9 | | openai/clip-vit-large-patch14-336 | TinyLlama/TinyLlama-1.1B-Chat-v1.0 | 基础 | 73.7 | 58.0 | 59.9 | 46.3 | 23.2 | 85.5 | 1284.6 | 27.9 | | google/siglip-so400m-patch14-384 | TinyLlama/TinyLlama-1.1B-Chat-v1.0 | 基础 | 75.5 | 58.6 | 64.0 | 49.6 | 23.5 | 86.3 | 1256.5 | 28.3 | | openai/clip-vit-large-patch14-336 | stabilityai/stablelm-2-zephyr-1_6b | 基础 | 75.9 | 59.5 | 64.6 | 50.5 | 27.3 | 86.1 | 1368.1 | 31.8 | | google/siglip-so400m-patch14-384 | stabilityai/stablelm-2-zephyr-1_6b | 基础 | 78.2 | 60.7 | 66.7 | 56.0 | 29.4 | 86.3 | 1319.3 | 32.6 | | google/siglip-so400m-patch14-384 | google/gemma-2b-it | 基础 | 78.4 | 61.6 | 64.4 | 53.6 | 26.9 | 86.4 | 1339.0 | 31.7 | | openai/clip-vit-large-patch14-336 | microsoft/phi-2 | 基础 | 76.8 | 59.4 | 71.2 | 53.4 | 31.7 | 86.8 | 1448.6 | 36.3 | | google/siglip-so400m-patch14-384 | microsoft/phi-2 | 基础 | 79.2 | 61.6 | 71.9 | 57.4 | 35.0 | 87.2 | 1462.4 | 38.2 | | google/siglip-so400m-patch14-384 | microsoft/phi-2 | 基础&lora | 77.6 | 59.7 | 71.6 | 53.8 | 33.3 | 87.9 | 1413.2 | 35.6 | | google/siglip-so400m-patch14-384 | microsoft/phi-2 | 共享 | 80.1 | 62.1 | 73.0 | 60.3 | 37.5 | 87.2 | 1466.4 | 38.4 | ### 旧版模型 这些模型是使用旧版代码库 TinyLLaVABench 训练的。 - [TinyLLaVA-3.1B](https://huggingface.co/bczhou/TinyLLaVA-3.1B) - [TinyLLaVA-2.0B](https://huggingface.co/bczhou/TinyLLaVA-2.0B) - [TinyLLaVA-1.5B](https://huggingface.co/bczhou/TinyLLaVA-1.5B) - [tiny-llava-hf](https://huggingface.co/bczhou/tiny-llava-v1-hf) 如果您有使用旧版代码库 TinyLLaVABench 训练的模型并且仍想使用它们,我们提供了一个关于如何使 [TinyLLaVA-3.1B](https://huggingface.co/bczhou/TinyLLaVA-3.1B) 的示例。
使用旧版模型的示例
from tinyllava.eval.run_tiny_llava import eval_model
from tinyllava.model.convert_legecy_weights_to_tinyllavafactory import *

model = convert_legecy_weights_to_tinyllavafactory('bczhou/TinyLLaVA-3.1B')

prompt = "What are the things I should be cautious about when I visit here?"
image_file = "https://llava-vl.github.io/static/images/view.jpg"

args = type('Args', (), {
    "model_path": None,
    "model": model,
    "query": prompt,
    "conv_mode": "phi", # 与训练阶段的 conv_version 相同。不同的 LLM 有不同的 conv_mode/conv_version,请替换
    "image_file": image_file,
    "sep": ",",
    "temperature": 0,
    "top_p": None,
    "num_beams": 1,
    "max_new_tokens": 512
})()

eval_model(args)

"""
输出结果:
When visiting this serene lakeside location with a wooden dock, there are a few things to be cautious about. First, ensure that the dock is stable and secure before stepping onto it, as it might be slippery or wet, especially if it's a wooden structure. Second, be mindful of the surrounding water, as it can be deep or have hidden obstacles, such as rocks or debris, that could pose a risk. Additionally, be aware of the weather conditions, as sudden changes in weather can make the area more dangerous. Lastly, respect the natural environment and wildlife, and avoid littering or disturbing the ecosystem.
"""
## 本地启动 Demo ### Gradio Web 演示 通过运行以下命令启动本地 Web 演示:
python tinyllava/serve/app.py --model-path tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B
### 命令行推理 我们还支持使用 CLI 运行推理。使用我们的模型,运行:
python -m tinyllava.serve.cli \
   --model-path tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B \
   --image-file "./tinyllava/serve/examples/extreme_ironing.jpg"
### 快速推理脚本 如果您想在本地启动自己或我们训练的模型,这里有一个示例。
使用自己训练或从 HuggingFace 下载的模型运行推理
from tinyllava.eval.run_tiny_llava import eval_model

model_path = "/absolute/path/to/your/model/"
prompt = "What are the things I should be cautious about when I visit here?"
image_file = "https://llava-vl.github.io/static/images/view.jpg"
conv_mode = "phi" # 或 llama、gemma 等

args = type('Args', (), {
    "model_path": model_path,
    "model": None,
    "query": prompt,
    "conv_mode": conv_mode,
    "image_file": image_file,
    "sep": ",",
    "temperature": 0,
    "top_p": None,
    "num_beams": 1,
    "max_new_tokens": 512
})()

eval_model(args)
使用 HuggingFace transformers 运行我们训练的模型进行推理
from transformers import AutoTokenizer, AutoModelForCausalLM

hf_path = 'tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B'
model = AutoModelForCausalLM.from_pretrained(hf_path, trust_remote_code=True)
model.cuda()
config = model.config
tokenizer = AutoTokenizer.from_pretrained(hf_path, use_fast=False, model_max_length = config.tokenizer_model_max_length,padding_side = config.tokenizer_padding_side)
prompt="What are these?"
image_url="http://images.cocodataset.org/val2017/000000039769.jpg"
output_text, genertaion_time = model.chat(prompt=prompt, image=image_url, tokenizer=tokenizer)

print('模型输出:', output_text)
print('运行时间:', genertaion_time)
## 自定义微调 如果您想使用自定义数据集微调 TinyLLaVA,请参考[此处](https://github.com/TinyLLaVA/TinyLLaVA_Factory/blob/main/CUSTOM_FINETUNE.md)。 ## 定制您自己的大型多模态模型 ### 大语言模型 (LLM) 如果您想自己添加一个新的 LLM,您需要在 `tinyllava/data/template/` 和 `tinyllava/model/llm/` 文件夹下创建两个文件:一个用于聊天模板,另一个用于语言模型。 以下是一个添加 Gemma 模型的示例。 首先,创建 `tinyllava/data/template/gemma_template.py`,这将用于微调阶段。
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union
from packaging import version

from .formatter import EmptyFormatter, StringFormatter
from .base import Template
from .formatter import Formatter
from . import register_template
from ...utils.constants import *

from transformers import PreTrainedTokenizer
import torch
import tokenizers


system = "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions."

@register_template('gemma') # 使 TemplateFactory 能够通过此字符串 ('gemma') 获取添加的模板。
@dataclass
class GemmaTemplate(Template):
    format_image_token: "Formatter" = StringFormatter(slot="<image>\n{{content}}")
    format_user: "Formatter" = StringFormatter(slot="USER" + ": " + "{{content}}" + " ")
    format_assistant: "Formatter" = StringFormatter(slot="ASSISTANT" + ": " + "{{content}}" + "<eos>") # 根据您选择的 tokenizer 进行修改
    system: "Formatter" = EmptyFormatter(slot=system+" ")
    separator: "Formatter" = EmptyFormatter(slot=[' ASSISTANT: ', '<eos>']) # 根据您选择的 tokenizer 进行修改

    def _make_masks(self, labels, tokenizer, sep, eos_token_length, rounds):
        # 您的代码在此处
        return labels, cur_len
**提示:** 请确保 `labels`(由 `_make_masks` 函数返回)遵循此格式:答案和 eos 令牌 ID 不被遮蔽,其他令牌被 `-100` 遮蔽。 其次,创建 `tinyllava/model/llm/gemma.py`。
from transformers import GemmaForCausalLM, AutoTokenizer
# 您要添加的 LLM 及其对应的 tokenizer。

from . import register_llm

# 添加 GemmaForCausalLM 及其对应的 tokenizer,并处理特殊令牌。
@register_llm('gemma') # 使 LLMFactory 能够通过此字符串 ('gemma') 获取添加的 LLM。
def return_gemmaclass(): 
    def tokenizer_and_post_load(tokenizer):
        tokenizer.pad_token = tokenizer.unk_token
        return tokenizer
    return (GemmaForCausalLM, (AutoTokenizer, tokenizer_and_post_load))
最后,创建 `scripts/train/train_gemma.sh`,并设置相应的 `LLM_VERSION` 和 `CONV_VERSION`。 ### 视觉编码器 (Vision Tower) 如果您想添加新的视觉编码器,您需要实现一个新的视觉编码器类,该类应继承自基类 `VisionTower`。以下是一个 MoF 视觉编码器的示例。 首先,创建 `tinyllava/model/vision_tower/mof.py`
@register_vision_tower('mof')      
class MoFVisionTower(VisionTower):
    def __init__(self, cfg):
        super().__init__(cfg)

        self._vision_tower = MoF(cfg)
        self._image_processor = # 您的图像处理器

    def _load_model(self, vision_tower_name, **kwargs):
        # 您的代码在此处,确保您的模型能够通过 huggingface 或 pytorch 加载方式正确加载预训练参数

    def forward(self, x, **kwargs):
        # 您的代码在此处
然后,在您的训练脚本中修改相应的 `VT_VERSION`。 ### 连接器 (Connector) 如果您想添加新的连接器,您需要实现一个新的连接器类,该类应继承自基类 `Connector`。以下是一个线性连接器的示例。 首先,创建 `tinyllava/model/connector/linear.py`
import torch.nn as nn

from . import register_connector
from .base import Connector

@register_connector('linear') # 使 ConnectorMFactory 能够通过此字符串 ('linear') 获取添加的连接器。     
class LinearConnector(Connector):
    def __init__(self, config):
        super().__init__()
        self._connector =  nn.Linear(config.vision_hidden_size, config.hidden_size) # 定义您的连接器模型
然后,在您的训练脚本中修改相应的 `CN_VERSION`。 ## 致谢 我们特别感谢赵磊、王路彻、罗开军和王俊晨构建了 [Demo](http://8843843nmph5.vicp.fun/#/)。 ## 联系方式 如果您有任何问题,请随时发起一个 *Issue* 或通过微信联系我们(微信号:*TinyLLaVA*)。 ## ✏️ 引用 如果您发现我们的论文和代码在您的研究中有用,请考虑给一颗星 :star: 和引用 :pencil:。
@misc{zhou2024tinyllava,
      title={TinyLLaVA: A Framework of Small-scale Large Multimodal Models}, 
      author={Baichuan Zhou and Ying Hu and Xi Weng and Junlong Jia and Jie Luo and Xien Liu and Ji Wu and Lei Huang},
      year={2024},
      eprint={2402.14289},
      archivePrefix={arXiv},
      primaryClass={cs.LG}
}
@article{jia2024tinyllava,
  title={TinyLLaVA Factory: A Modularized Codebase for Small-scale Large Multimodal Models},
  author={Jia, Junlong and Hu, Ying and Weng, Xi and Shi, Yiming and Li, Miao and Zhang, Xingjian and Zhou, Baichuan and Liu, Ziyu and Luo, Jie and Huang, Lei and Wu, Ji},
  journal={arXiv preprint arXiv:2405.11788},
  year={2024}
}
## ❤️ 社区贡献 * 我们的代码库基于 [LLaVA](https://github.com/haotian-liu/LLaVA) 项目构建。出色的工作! * 我们的项目使用了 [ShareGPT4V](https://github.com/InternLM/InternLM-XComposer/tree/main/projects/ShareGPT4V) 项目的数据。出色的工作!
22 次点击  ∙  0 人收藏  
登录后收藏  
0 条回复
关于 ·  帮助 ·  PING ·  隐私 ·  条款   
OA0 - Omni AI 0 一个探索 AI 的社区
沪ICP备2024103595号-2
耗时 17 ms
Developed with Cursor