MiniCPM-V 2.6:端侧最强多模态大模型探索【微调实战体验】

系列篇章💥

No.文章
1MiniCPM-V 2.6:端侧最强多模态大模型探索【本地部署实践】
2MiniCPM-V 2.6:端侧最强多模态大模型探索【推理实战大全】
3MiniCPM-V 2.6:端侧最强多模态大模型探索【微调实战体验】


引言

在先前的篇章中,我们已然沉浸式体验了 MiniCPM-V 2.6 模型的本地部署和推理实战,而在本篇中,我们将踏上一场更为深入的探索之旅 ——MiniCPM-V 2.6 的微调实践。这一实践不仅是对模型性能的进一步挖掘,更是为了满足各种特定应用场景的需求,开启多模态大模型的无限可能。

一、仓库代码下载

克隆git仓库代码

git clone https://github.com/OpenBMB/MiniCPM-V.git
cd MiniCPM-V

下载完成如下:
在这里插入图片描述

二、MiniCPM模型下载

请直接参考《MiniCPM-V 2.6:端侧最强多模态大模型探索之【本地部署实践】》篇章中**下载模型**的相关内容

使用 modelscope 中的 snapshot_download 函数下载模型(提前安装modelscope :pip install modelscope)。第一个参数为模型名称,参数 cache_dir 用于指定模型的下载路径。在 /root/autodl-tmp 路径下新建 download.py 文件,并在其中输入以下内容:

from modelscope import snapshot_download
model_dir = snapshot_download('OpenBMB/MiniCPM-V-2_6', cache_dir='/root/autodl-tmp', revision='master')

运行 python /root/autodl-tmp/download.py 执行下载。
在这里插入图片描述

三、微调数据集准备

1、数据集说明

处理数据集成以下形式:
1)首先,确保 “id” 值具有唯一性,不可重复出现。这就如同为每个数据赋予一个独一无二的标识,便于在后续的处理和调用中准确区分。
2)再者,“\n” 应当醒目地出现在每个数据集对话数据的开头位置,如同一个引导信号,为模型提示图像信息的即将到来。
3)同时,“image” 对应的地址必须真实存在对应图片,确保模型在读取数据时能够准确获取图像资源。
4)最后,每个 “conversations” 对应的列表中代表着一个多轮对话。其中,“content” 代表对话内容,“role” 对应 “user” 时代表用户输入,而 “role” 对应 “assistant” 时则代表模型输出。

2、单图数据样例

以下是单图数据的示例格式:

[
    { "id": "0",
      "conversations": [
        {
          "content": "<image>\nWho are they?",
          "role": "user"
        },
        {
          "content": "They're Kane and Gretzka from Bayern Munich.",
          "role": "assistant"
        },
        {
          "content": "What are they doing?",
          "role": "user"
        },
        {
          "content": "They are celebrating on the soccer field.",
          "role": "assistant"
        }
      ],
      "image": 
        "/root/ld/ld_project/LLaMA-Factory/data/mllm_demo_data/1.jpg"
      }
    ...以上是单条数据,列表中可存在多个相同格式的数据
    ]

3、多图数据样例

多图数据的呈现形式如下:

[
     {
       "id": "0",
       "image": {
         "<image_00>": "path/to/image_0.jpg",
         "<image_01>": "path/to/image_1.jpg",
         "<image_02>": "path/to/image_2.jpg",
         "<image_03>": "path/to/image_3.jpg"
       },
       "conversations": [
         {
           "role": "user", 
           "content": "How to create such text-only videos using CapCut?\n<image_00>\n<image_01>\n<image_02>\n<image_03>\n"
         }, 
         {
           "role": "assistant", 
           "content": "To create a text-only video as shown in the images, follow these steps in CapCut..."
         }
       ]
     }
   ]

四、Lora微调配置

对于 lora 微调,需对 “MiniCPM-V/finetue/finetune_lora.sh” 进行修改。这一步骤犹如为微调过程定制专属的工具,确保模型能够按照我们期望的方式进行训练。

注意:如果你想微调int4模型,首先下载int4模型,然后在以下脚本--use_lora true \ 下面一行增加 q_lora true \

#!/bin/bash
GPUS_PER_NODE=8 # 改成你的机器每个节点共有多少张显卡,如果是单机八卡就是8
NNODES=1 # 改成你的机器有多少个节点,如果就是一台服务器就是1
NODE_RANK=0 # 使用第几个服务器训练
MASTER_ADDR=localhost
MASTER_PORT=6001

MODEL="/root/ld/ld_model_pretrained/Minicpmv2_6" # 本地模型路径 or openbmb/MiniCPM-V-2.5
# ATTENTION: specify the path to your training data, which should be a json file consisting of a list of conversations.
# See the section for finetuning in README for more information.
DATA="/root/ld/ld_project/MiniCPM-V/finetune/mllm_demo.json" # 训练数据文件地址
EVAL_DATA="/root/ld/ld_project/MiniCPM-V/finetune/mllm_demo.json" # 验证集数据文件地址
LLM_TYPE="qwen2" # if use openbmb/MiniCPM-V-2, please set LLM_TYPE=minicpm

export NCCL_P2P_DISABLE=1 # a100等支持nccl_p2p的显卡去掉此行
export NCCL_IB_DISABLE=1 # a100等显卡去掉此行

DISTRIBUTED_ARGS="
    --nproc_per_node $GPUS_PER_NODE \
    --nnodes $NNODES \
    --node_rank $NODE_RANK \
    --master_addr $MASTER_ADDR \
    --master_port $MASTER_PORT
"
torchrun $DISTRIBUTED_ARGS finetune.py  \
    --model_name_or_path $MODEL \
    --llm_type $LLM_TYPE \
    --data_path $DATA \
    --eval_data_path $EVAL_DATA \
    --remove_unused_columns false \ 
    --label_names "labels" \ # 数据构造,不要动
    --prediction_loss_only false \ 
    --bf16 false \ # 使用bf16精度训练,4090,a100,h100等可以开启
    --bf16_full_eval false \ # 使用bf16精度测试
    --fp16 true \ # 使用fp16精度训练
    --fp16_full_eval true \ # 使用pf16精度测试
    --do_train \ # 是否训练
    --do_eval \ # 训练过程中是否做验证
    --tune_vision true \ # 是否微调siglip(vit)模块
    --tune_llm false \ # 是否微调大语言模型模块
    --use_lora true \ # 是否lora微调
    --lora_target_modules "llm\..*layers\.\d+\.self_attn\.(q_proj|k_proj|v_proj)" \ #lora插入的层,这里写的是正则表达式,建议不改
    --model_max_length 2048 \ # 模型训练的最大长度
    --max_slice_nums 9 \ # 模型最大切分次数
    --max_steps 10000 \ # 最多训练步数
    --eval_steps 1000 \ # 每多少步验证一次
    --output_dir output/output_minicpmv2_lora \ # 模型lora保存地址
    --logging_dir output/output_minicpmv2_lora \ # 日志保存地址
    --logging_strategy "steps" \ # 日志输出策略(可选epoch)
    --per_device_train_batch_size 2 \ # 每张卡训练的batch_size
    --per_device_eval_batch_size 1 \ # 每张卡验证的batch_size
    --gradient_accumulation_steps 8 \ # 梯度累积,当显存少时可以增大这个参数从而减少per_device_train_batch_size
    --evaluation_strategy "steps" \ # 验证策略(可选epoch)
    --save_strategy "steps" \ # 保存策略(可选epoch)与save_steps同时起作用
    --save_steps 10 \ # 10个step保存一次
    --save_total_limit 10 \ # 最大储存总数
    --learning_rate 1e-6 \ # 学习率
    --weight_decay 0.1 \ # 权重正则化参数
    --adam_beta2 0.95 \ # 
    --warmup_ratio 0.01 \ # 总步数的预热率,即:总训练步数*warmup_ratio=预热步数
    --lr_scheduler_type "cosine" \ # 学习率调整器
    --logging_steps 1 \
    --gradient_checkpointing true \ # 梯度检查点,建议开启,极大减少显存使用
    --deepspeed ds_config_zero3.json \ # 使用zero3,显存充足建议使用ds_config_zero2.json
    --report_to "tensorboard" # wandb # tensorboard或者wandb记录损失

核心参数:

MODEL="/root/ld/ld_model_pretrained/MiniCPM-Llama3-V-2_5" # 本地模型路径 or huggingface id
DATA="/root/ld/ld_project/MiniCPM-V/finetune/mllm_demo.json" # 训练数据文件
EVAL_DATA="/root/ld/ld_project/MiniCPM-V/finetune/mllm_demo.json" # 验证集数据文件

--tune_vision true \ # 是否微调siglip(vit)模块
--lora_target_modules "llm\..*layers\.\d+\.self_attn\.(q_proj|k_proj|v_proj|o_proj)" \ #lora插入的层,这里写的是正则表达式,建议不改
--tune_vision true \ # 是否微调siglip(vit)模块
--tune_llm false \ # 是否微调大语言模型模块
--use_lora true \ # 是否lora微调

--model_max_length 2048 \ # 模型训练的最大长度 #1000+文字数/1.5
--per_device_train_batch_size 2 \ # 每张卡训练的batch_size
--per_device_eval_batch_size 1 \ # 每张卡验证的batch_size
--gradient_accumulation_steps 1 \ # 梯度累积,当显存少时可以增大这个参数从而减少per_device_train_batch_size
--learning_rate 1e-6 \ # 学习率
--gradient_checkpointing true \ # 梯度检查点,建议开启,极大减少显存使用
--deepspeed ds_config_zero3.json \ # 使用zero3,显存充足建议使用ds_config_zero2.json

五、开始模型训练

首先,切换到 “MiniCPM-V/finetune” 目录。接着,执行 “bash finetune_lora.sh” 命令,正式开启训练之旅。在这个过程中,模型将不断学习和优化,以适应特定的数据集和任务需求。

cd MiniCPM-V/finetune
bash finetune_lora.sh

六、微调模型合并

最后,进行 lora 与模型的合并并保存。这一步骤将微调后的 lora 与原始模型进行融合,使得模型能够充分发挥微调的效果,为实际应用提供更强大的性能支持。

from peft import PeftModel
from transformers import AutoModel, AutoTokenizer
import os
import shutil

model_type = "/root/ld/ld_model_pretrained/Minicpmv2_6"  # Local model path or huggingface id
path_to_adapter = "/root/ld/ld_project/minicpmv2_6/MiniCPM-V/finetune/output/output_minicpmv2_lora/checkpoint-30"  # Path to the saved LoRA adapter
merge_path = "/root/ld/ld_project/minicpmv2_6/MiniCPM-V/finetune/output/merge_minicpmv"  # Path to save the merged model

# 保证原始模型的各个文件不遗漏保存到merge_path中
def copy_files_not_in_B(A_path, B_path):
    """
    Copies files from directory A to directory B if they exist in A but not in B.

    :param A_path: Path to the source directory (A).
    :param B_path: Path to the destination directory (B).
    """
    # 保证路径存在
    if not os.path.exists(A_path):
        raise FileNotFoundError(f"The directory {A_path} does not exist.")
    if not os.path.exists(B_path):
        os.makedirs(B_path)

    # 获取路径A中所有非权重文件
    files_in_A = os.listdir(A_path)
    files_in_A = set([file for file in files_in_A if not (".bin" in file or "safetensors" in file)])
    # List all files in directory B
    files_in_B = set(os.listdir(B_path))

    # 找到所有A中存在但B中不存在的文件
    files_to_copy = files_in_A - files_in_B

    # 将这些文件复制到B路径下
    for file in files_to_copy:
        src_file = os.path.join(A_path, file)
        dst_file = os.path.join(B_path, file)
        shutil.copy2(src_file, dst_file)

# 加载原始模型
model = AutoModel.from_pretrained(
    model_type,
    trust_remote_code=True
)

# 加载lora模块到原始模型中
lora_model = PeftModel.from_pretrained(
    model,
    path_to_adapter,
    device_map="auto",
    trust_remote_code=True
).eval()

# 将加载的lora模块合并到原始模型中
merge_model = lora_model.merge_and_unload()

# 将新合并的模型进行保存
merge_model.save_pretrained(merge_path, safe_serialization=False)

# 加载分词器
tokenizer = AutoTokenizer.from_pretrained(model_type, trust_remote_code=True)
tokenizer.save_pretrained(merge_path)

copy_files_not_in_B(model_type,merge_path)

结语

通过以上的步骤,我们探索了MiniCPM-V 2.6 模型的微调实践。这一过程不仅让我们更加深入地了解了多模态大模型的工作原理和潜力,也为我们在实际应用中提供了更多的可能性。在未来的探索中,我们可以继续优化和改进微调方法,以适应不断变化的需求和挑战。

在这里插入图片描述

🎯🔖更多专栏系列文章:AI大模型提示工程完全指南AI大模型探索之路(零基础入门)AI大模型预训练微调进阶AI大模型开源精选实践AI大模型RAG应用探索实践🔥🔥🔥 其他专栏可以查看博客主页📑

😎 作者介绍:我是寻道AI小兵,资深程序老猿,从业10年+、互联网系统架构师,目前专注于AIGC的探索。
📖 技术交流:欢迎关注【小兵的AI视界】公众号或扫描下方👇二维码,加入技术交流群,开启编程探索之旅。
💘精心准备📚500本编程经典书籍、💎AI专业教程,以及高效AI工具。等你加入,与我们一同成长,共铸辉煌未来。
如果文章内容对您有所触动,别忘了点赞、⭐关注,收藏!加入我,让我们携手同行AI的探索之旅,一起开启智能时代的大门!

<think>好的,用户想对MiniCPM-o 2.6模型进行int4精度的微调,我需要根据提供的引用资料来给出指导。首先,我需要确认用户提到的模型是否正确,因为在提供的引用中,提到的是MiniCPM-V-2.6,而不是MiniCPM-o 2.6,可能用户可能有笔误,或者模型名称有变化,但暂时假设是同一个模型的变体。 接下来,根据引用3和引用4,用户需要下载模型文件和配置环境。引用3提到了模型微调的方法,包括qlora微调int4版本,还有lora微调以及合并lora后的量化步骤。因此,int4的微调可能需要先进行量化处理,或者使用已经量化好的模型进行微调。 引用3中明确提到了“qlora微调minicpm-v-int4”和“lora微调后量化int4”,所以可能有两种方法:一种是直接使用已经量化为int4的模型进行微调,另一种是在微调后进行量化。需要明确步骤。 此外,引用5提到ms-swift框架支持多模态大模型微调,包括MiniCPM-V-2.6,所以可能需要使用swift工具来进行微调。同时,引用2给出了运行int4量化版本的命令行示例,可能涉及加载量化后的模型文件和mmproj文件。 用户的问题是关于int4精度微调的步骤,需要结合这些信息。可能的步骤包括:下载int4量化模型,准备数据集,配置微调环境(如安装swift),使用qlora或lora方法进行微调,然后合并lora权重,或者直接微调量化后的模型。 需要注意的是,是否支持直接对int4模型微调,或者是否需要先微调全精度模型再量化。根据引用3中的“lora微调后量化int4”,可能是在全精度模型上进行lora微调,之后再进行量化。而qlora可能允许在量化模型上直接微调,但需要查阅具体步骤。 另外,用户可能需要准备数据集,根据引用4中的微调数据集准备部分,包括单图和多图数据样例,可能涉及多模态数据。但用户的问题可能更关注于int4的微调方法,而不是数据准备的具体内容。 综合以上信息,回答的步骤可能包括: 1. 下载int4量化模型文件和相关配置文件(如ggml-model-Q4_K_M.gguf和mmproj-model-f16.gguf),如引用2所示。 2. 安装必要的环境,如ms-swift框架(引用5),以及可能的依赖库。 3. 使用qlora方法进行微调,如引用3提到的“qlora微调minicpm-v-int4”,可能需要配置相应的参数。 4. 合并lora权重到基础模型(如果需要),如引用3中的“merge_lora”步骤。 5. 验证微调后的模型性能,使用提供的推理命令进行测试。 需要注意,具体的命令和步骤可能需要参考官方文档或引用中的指导,例如引用3中的详细步骤。同时,要确保用户正确理解模型名称和版本,避免混淆不同的模型变体。</think>对MiniCPM-V-2.6(可能笔误为MiniCPM-o 2.6)进行int4精度微调的步骤如下: ### 一、环境准备 1. **安装ms-swift框架** 通过魔搭社区提供的ms-swift框架实现量化微调,该框架支持MiniCPM-V-2.6的量化训练和部署[^5]。执行以下命令: ```bash pip install ms-swift ``` 2. **下载模型文件** 从官方仓库获取int4量化模型文件: - 基础模型:`ggml-model-Q4_K_M.gguf` - 多模态投影文件:`mmproj-model-f16.gguf`[^2] ```bash git clone https://github.com/OpenBMB/MiniCPM-V-2_6 ``` ### 二、微调流程 #### 方法1:QLoRA微调int4量化模型 1. **加载量化模型** 使用`bitsandbytes`库加载4bit量化配置: ```python from swift import LoRAConfig, Swift model = AutoModelForVision2Seq.from_pretrained( "OpenBMB/MiniCPM-V-2_6", load_in_4bit=True, quantization_config=BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4") ) ``` 2. **添加LoRA适配器** ```python lora_config = LoRAConfig( r=8, target_modules=["q_proj", "v_proj"], lora_alpha=32 ) model = Swift.prepare_model(model, lora_config) ``` 3. **启动训练** ```python trainer = Trainer( model=model, train_dataset=dataset, args=TrainingArguments( output_dir="./output", per_device_train_batch_size=4, gradient_accumulation_steps=2 ) ) trainer.train() ``` #### 方法2:先微调后量化 1. **全精度模型微调** 使用LoRA进行常规微调: ```bash python train.py \ --model_name OpenBMB/MiniCPM-V-2_6 \ --use_lora True \ --lora_rank 8 ``` 2. **后训练量化** 微调完成后执行量化: ```bash ./llama-minicpmv-cli \ -m merged_model.gguf \ --mmproj mmproj-model-f16.gguf \ --quantize Q4_K_M ``` ### 三、合并与部署 1. **合并LoRA权重** ```python from swift import merge_lora_to_base_model merge_lora_to_base_model( "./lora_weights", "./merged_model" ) ``` 2. **推理验证** ```bash ./llama-minicpmv-cli \ -m merged_model-Q4_K_M.gguf \ --mmproj mmproj-model-f16.gguf \ --image test.jpg \ -p "描述图片内容" ``` ### 注意事项 1. 显存需求:int4微调时建议使用至少16GB显存的GPU 2. 数据集格式:需准备图文对数据,支持单图和多图输入格式[^4] 3. 量化精度:Q4_K_M在精度和推理速度间提供最佳平衡
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寻道AI小兵

🐳 感谢你的巨浪支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值