用 SWIFT 对 MiniCPM-V 系列进行推理与微调:安装、CLI/Python 推理、LoRA 与全参训练实战
发布时间:2026/9/12 7:17:24来源:尧图网络
用 SWIFT 对 MiniCPM-V 系列进行推理与微调安装、CLI/Python 推理、LoRA 与全参训练实战【免费下载链接】MiniCPM-VA Pocket-Sized MLLM for Ultra-Efficient Image and Video Understanding on Your Phone项目地址: https://gitcode.com/GitHub_Trending/mi/MiniCPM-V本篇技术指南以 docs/swift_train_and_infer.md 为骨架系统讲解如何使用魔搭社区的开源工具 SWIFT 对MiniCPM-Llama3-V-2_5以及同系列 MiniCPM-V 模型完成环境安装、命令行/ Python 双通道推理、LoRA 与全参数微调以及 LoRA 权重合并与加载推理。读完本文你将能独立搭建 SWIFT 环境跑通图文多模态推理并基于自定义数据集完成一次完整的 SFT 微调闭环文末还对照仓库官方 finetune 脚本补充了数据格式、参数语义与 OOM 排查的源码级细节。SWIFT 安装SWIFTScalable lightWeight Infrastructure for Fine-Tuning是魔搭社区ModelScope开源的训练与推理框架对 MiniCPM-V 系列多模态模型提供开箱即用的支持。安装方式非常直接基于 git 源码安装即可git clone https://github.com/modelscope/swift.git cd swift pip install -r requirements.txt pip install -e .[llm]其中pip install -e .[llm]为可编辑模式安装并引入 LLM 推理与微调所需的依赖包若只需基础功能可只执行前两条命令。SWIFT Infer两种推理方式SWIFT 的推理能力可通过**命令行接口CLI**与Python 代码两种途径调用。两种方式底层共用同一套模型加载、模板构造与生成参数体系读者可按场景选用命令行适合快速验证Python 适合集成到业务代码或做批量实验。快速开始一行命令完成推理CUDA_VISIBLE_DEVICES0 swift infer --model_type minicpm-v-v2_5-chat执行后 SWIFT 会自动下载MiniCPM-Llama3-V-2_5模型对应--model_type minicpm-v-v2_5-chat并进入交互式推理界面。CUDA_VISIBLE_DEVICES0用于指定使用的 GPU 编号。常用推理参数swift infer支持丰富的命令行参数以下为文档给出的核心参数及其含义参数说明model_id_or_path模型来源可以是 Hugging Face 模型 ID也可以是本地模型路径infer_backend [AUTO, vllm, pt]推理后端默认AUTO自动选择可选 vLLM 或原生 PyTorchdtype [bf16, fp16, fp32, AUTO]计算精度默认AUTOmax_length最大序列长度max_new_tokens: int 2048最大生成 token 数默认 2048do_sample: bool True是否采样生成temperature: float 0.3生成温度系数top_k: int 20top-k 采样参数top_p: float 0.7top-p核采样参数repetition_penalty: float 1.重复惩罚系数num_beams: int 1束搜索束宽stop_words: List[str] None停止词列表quant_method [bnb, hqq, eetq, awq, gptq, aqlm]量化方法用于低显存推理quantization_bit [0, 1, 2, 3, 4, 8]量化位宽默认 0 表示不量化其中quantization_bit为 0 时不做量化显存受限时可配合quant_method使用 BitsAndBytesbnb等量化方案降低显存占用。组合参数示例指定本地模型路径并设置计算精度的完整示例CUDA_VISIBLE_DEVICES01 swift infer \ --model_type minicpm-v-v2_5-chat \ --model_id_or_path /root/ld/ld_model_pretrain/MiniCPM-Llama3-V-2_5 \ --dtype bf16该命令使用0,1两张 GPU多卡时 SWIFT 会自动进行设备分配从本地路径/root/ld/ld_model_pretrain/MiniCPM-Llama3-V-2_5加载模型并以bf16精度推理。注意model_id_or_path是覆盖默认模型下载逻辑的关键参数只要本地已有完整模型目录即可完全离线推理。Python 代码调用 SWIFT 推理Python 方式适合脚本化、集成化场景。以下代码完整演示了加载 MiniCPM-Llama3-V-2_5、构造模板、普通推理与流式推理的完整流程import os os.environ[CUDA_VISIBLE_DEVICES] 0,1 # Set the number of GPUs to use from swift.llm import ( get_model_tokenizer, get_template, inference, ModelType, get_default_template_type, inference_stream ) # Import necessary modules from swift.utils import seed_everything # Set random seed import torch model_type ModelType.minicpm_v_v2_5_chat template_type get_default_template_type(model_type) # Obtain the template type, primarily used for constructing special tokens and image processing workflow print(ftemplate_type: {template_type}) model, tokenizer get_model_tokenizer(model_type, torch.bfloat16, model_id_or_path/root/ld/ld_model_pretrain/MiniCPM-Llama3-V-2_5, model_kwargs{device_map: auto}) # Load the model, set model type, model path, model parameters, device allocation, etc., computation precision, etc. model.generation_config.max_new_tokens 256 template get_template(template_type, tokenizer) # Construct the template based on the template type seed_everything(42) images [http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/road.png] # Image URL query 距离各城市多远 # Note: Query is still in Chinese, consider translating if needed response, history inference(model, template, query, imagesimages) # Obtain results through inference print(fquery: {query}) print(fresponse: {response}) # Streaming output query 距离最远的城市是哪 # Note: Query is still in Chinese, consider translating if needed gen inference_stream(model, template, query, history, imagesimages) # Call the streaming output interface print_idx 0 print(fquery: {query}\nresponse: , end) for response, history in gen: delta response[print_idx:] print(delta, end, flushTrue) print_idx len(response) print() print(fhistory: {history})逐段要点get_default_template_type(model_type)根据模型类型自动推导模板类型。模板负责特殊 token 的拼接与图像预处理流程是多模态推理的关键一环代码中已将其打印输出便于排查。get_model_tokenizer(model_type, torch.bfloat16, model_id_or_path..., model_kwargs{device_map: auto})以bf16精度加载模型device_mapauto让模型自动分布到可见 GPU 上model_id_or_path传入本地路径可避免重复下载。get_template(template_type, tokenizer)按模板类型构造对话模板。inference(model, template, query, imagesimages)单轮推理返回(response, history)history保留多轮上下文。inference_stream(...)流式接口逐 token 增量返回代码中用response[print_idx:]只打印新增部分实现打字机效果同时持续维护history供多轮对话使用。SWIFT train数据准备与微调SWIFT 支持在本地数据集上进行训练。训练数据采用jsonl格式每个样本为一行 JSON核心字段为query、response与images。以下三种形态覆盖了单轮、多轮与带历史上下文的场景{query: What does this picture describe?, response: This picture has a giant panda., images: [local_image_path]} {query: What does this picture describe?, response: This picture has a giant panda., history: [], images: [image_path]} {query: Is bamboo tasty?, response: It seems pretty tasty judging by the pandas expression., history: [[Whats in this picture?, Theres a giant panda in this picture.], [What is the panda doing?, Eating bamboo.]], images: [image_url]}query用户提问response期望模型输出的标准答案history可选多轮对话的历史记录为[提问, 回答]二元组的列表images图像路径列表既支持本地路径也支持图片 URLSWIFT 会自动下载。与原文档配套的官方微调体系可参考仓库 finetune/readme.md官方脚本使用 transformers Trainer DeepSpeed数据以{id, image, conversations}的 JSON 数组组织并在对话文本中显式插入image单图或image_00/image_01等占位符多图来指定图像嵌入插入位置——这与 SWIFT 的query/response/images字段是两种等价但字段命名不同的数据协议可互为参照。LoRA 微调LoRALow-Rank Adaptation只训练一小部分低秩适配参数显存占用小、速度快。针对 MiniCPM-Llama3-V-2_5LoRA 的目标模块是 LLM 中的k 与 v 权重投影k_proj、v_proj。# Experimental environment: A100 # 32GB GPU memory CUDA_VISIBLE_DEVICES0 swift sft \ --model_type minicpm-v-v2_5-chat \ --dataset coco-en-2-mini \--dataset coco-en-2-mini是 SWIFT 内置的英文 COCO 图像描述微型数据集用于快速验证训练链路。训练过程中需要注意eval_steps的取值在评估eval阶段 SWIFT 可能出现显存错误memory bug因此建议将eval_steps设置得足够大例如200000让训练过程基本跳过中途评估只依赖最终保存的 checkpoint。全参数微调当lora_target_modules设为ALL时模型所有参数均参与微调full-parameter finetune效果上限更高但显存与算力开销也更大CUDA_VISIBLE_DEVICES0,1 swift sft \ --model_type minicpm-v-v2_5-chat \ --dataset coco-en-2-mini \ --lora_target_modules ALL \ --eval_steps 200000--lora_target_modules ALL的含义是以 LoRA 的方式覆盖所有模块SWIFT 会为全部线性层注入 LoRA 适配器若显存充足且追求全量更新可改为直接全参微调。文档实验环境为 A10032GB 显存即可运行 LoRA 微调。LoRA 权重合并与推理LoRA 训练产出的是轻量 adapter 权重不能直接独立推理。有两种使用方式直接加载 adapter与合并回基座模型。方式一直接加载 LoRA 权重推理CUDA_VISIBLE_DEVICES0 swift infer \ --ckpt_dir /your/lora/save/checkpointSWIFT 会读取ckpt_dir中保存的 LoRA adapter自动找到其关联的基座模型完成加载与推理。方式二合并 LoRA 权重到基座模型CUDA_VISIBLE_DEVICES0 swift infer \ --ckpt_dir your/lora/save/checkpoint \ --merge_lora true加入--merge_lora true后SWIFT 会加载并合并 LoRA 权重到基座模型将合并后的完整模型保存到 LoRA 的保存路径下随后直接加载合并后的模型进行推理。合并产物是一个标准的、不依赖 adapter 的完整模型可直接用于后续部署或二次微调。对照仓库官方 LoRA 微调脚本 finetune/finetune_lora.sh 可以看到同等的目标模块定义--lora_target_modules llm\..*layers\.\d\.self_attn\.(q_proj|k_proj|v_proj|o_proj)官方脚本覆盖 Q/K/V/O 四类投影并额外训练embed_tokens与resampler其 LoRA 超参为lora_r64、lora_alpha64、lora_dropout0.05可作为自定义 LoRA 训练的参考起点。源码级补充官方 finetune 脚本的核心实现为帮助读者更深入地理解 SWIFT 微调背后的机制这里对照仓库中的官方微调实现做关键解读。官方脚本与 SWIFT 是两条并行的训练通道官方默认 transformers Trainer DeepSpeedSWIFT 为魔社框架但数据语义与参数语义高度一致。训练入口与参数解析finetune/finetune.py 使用HfArgumentParser解析四组参数ModelArgumentsmodel_name_or_path、DataArgumentsdata_path/eval_data_path、TrainingArguments继承自 transformers新增model_max_length默认 2048、tune_vision默认 True、tune_llm默认 True、use_lora默认 False、max_slice_nums默认 9以及LoraArguments。其中tune_vision是否训练视觉感知模块VPM置false可显著省显存tune_llm与use_lora互斥——finetune.py中显式校验当use_loraTrue且tune_llmTrue时抛出ValueError见 finetune/finetune.py 第 220-221 行即 LoRA 模式下 LLM 主干冻结只训练低秩适配器与modules_to_save指定的[embed_tokens, resampler]tune_vision时追加vpm。数据格式与占位符机制finetune/dataset.py 中的SupervisedDataset.__getitem__支持两种图像声明方式image为字符串时映射为image占位符为字典时按image_00、image_01等键逐一映射对应多图输入。训练样本以conversations列表按user/assistant角色交替组织具体格式示例见 finetune/readme.md。data_collator会将超过max_length的序列截断、并按-100填充 label 以屏蔽非监督位置的损失见 finetune/dataset.py 第 88-115 行。训练目标与 DeepSpeed 配置finetune/trainer.py 的CPMTrainer.compute_loss将 logits 展平后与 label 计算CrossEntropyLossLoRA 模式下通过model._enable_peft_forward_hooks(**inputs)走 PEFT 前向钩子。多卡训练默认使用 finetune/ds_config_zero2.jsonZeRO Stage 2 optimizer offload 到 CPUallgather_bucket_size/reduce_bucket_size均为 2e8更省显存可切换 finetune/ds_config_zero3.jsonStage 3同时 offload 参数与优化器状态。依赖版本方面finetune/requirements.txt 锁定了torch2.2.0、transformers4.51.2、peft0.14.0、deepspeed等关键版本复现时建议保持一致。OOM 排查建议结合 finetune/readme.md 的 FAQ训练中遇到显存不足OOM时可按优先级尝试降低序列长度--model_max_length 1200默认 2048多图 SFT 建议反而上调到 4096并相应评估显存减小 batch--batch_size 1并用gradient_accumulation_steps维持等效总 batch减少图像切片--max_slice_nums 9是图像高分辨率切片的数量上限2.6 版本中单图基础为 64 tokenslice9时最大 1344×1344 图像约消耗 64×(91) token对纯低分辨率任务可设为 1冻结视觉模块--tune_vision false启用 DeepSpeed offloadStage 2 / Stage 3 将优化器甚至模型参数卸载到 CPU。总结本文围绕 SWIFT 完整覆盖了 MiniCPM-Llama3-V-2_5 的安装 → CLI 推理 → Python 推理 → 数据准备 → LoRA/全参微调 → LoRA 合并与推理全流程命令行侧掌握swift infer/swift sft的核心参数精度、采样、量化、LoRA 目标模块等Python 侧掌握get_model_tokenizerget_templateinference/inference_stream的调用范式训练侧理解 jsonl 数据协议与eval_steps的坑位。同时以仓库官方 finetune 脚本finetune/finetune.py、finetune/finetune_lora.sh、finetune/readme.md为参照补齐了占位符机制、LoRA 目标模块、DeepSpeed ZeRO 配置与 OOM 排查等源码级细节。读者可在此基础上将coco-en-2-mini替换为自有业务数据快速完成领域化多模态模型微调。【免费下载链接】MiniCPM-VA Pocket-Sized MLLM for Ultra-Efficient Image and Video Understanding on Your Phone项目地址: https://gitcode.com/GitHub_Trending/mi/MiniCPM-V创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
网站建设高端定制企业官网