系列篇章💥
| No. | 文章 |
|---|---|
| 1 | MiniCPM-V 2.6:端侧最强多模态大模型探索【本地部署实践】 |
| 2 | MiniCPM-V 2.6:端侧最强多模态大模型探索【推理实战大全】 |
| 3 | MiniCPM-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的探索之旅,一起开启智能时代的大门!
865

被折叠的 条评论
为什么被折叠?



