拓冰建站拓冰建站
首页 / 资讯中心 / 正文

Qwen3 系列微调实践指南:使用 MS-SWIFT 完成 SFT、GRPO 与 Megatron 并行训练

Qwen3 系列微调实践指南使用 MS-SWIFT 完成 SFT、GRPO 与 Megatron 并行训练【免费下载链接】Qwen1.5Qwen3 is the large language model series developed by Qwen team, Alibaba Cloud.项目地址: https://gitcode.com/GitHub_Trending/qw/Qwen1.5MS-SWIFTModelScope Swift是 ModelScope 社区提供的大模型与多模态大模型训练、部署一体化框架本指南以当前 Qwen3 开源仓库中的 ms_swift.md 文档为核心系统讲解如何使用 ms-swift 对 Qwen3-8B 进行监督微调SFT与 GRPO 强化学习训练并通过 Megatron-SWIFT 对 MoE 架构的 Qwen3-30B-A3B 进行大规模全参数微调。读完本文你将掌握 ms-swift 的完整 CLI 工作流、自定义数据集格式、思考模型微调的数据处理技巧以及多卡、多机并行训练的关键参数配置。MS-SWIFT 框架概览MS-SWIFT 是 ModelScope 社区提供的大模型与多模态大模型训练和部署框架其核心价值在于一套框架覆盖全流程。结合官方文档与当前 Qwen3 仓库的 README.md 可以确认Qwen3 系列包含 dense 与 MoE 两种架构、从 0.6B 到 235B-A22B 多个规格的模型且支持思考模式thinking与非思考模式non-thinking的自由切换——这为微调带来了特殊的数据处理需求ms-swift 对此提供了针对性的解决方案。ms-swift 训练 LLM 的核心能力包括模型类型支持 500 纯文本大模型与 200 多模态大模型覆盖从训练到部署的完整流程硬件支持兼容 CPU、RTX 系列 GPU、T4/V100、A10/A100/H100、昇腾 NPU、MPS 等训练方法支持全参数微调full、LoRA、QLoRA、DoRA 等多种技术分布式训练支持 DDP、device_map、DeepSpeed ZeRO-2/ZeRO-3、FSDP 等并集成 Megatron 的张量并行TP、流水线并行PP、序列并行SP与专家并行EPRLHF 训练支持 DPO、GRPO、DAPO、RM、PPO、KTO 等人齐对齐方法覆盖纯文本与多模态大模型。本仓库的 examples/README.md 明确标注其示例目录已针对 Qwen3 弃用因此训练 Qwen3 系列应以 ms-swift、Axolotl、LLaMA-Factory、verl 等外部框架的最新文档为准本仓库对应指南见 training 目录这也是本指南聚焦 ms-swift 的原因。环境准备开始微调前请确保环境就绪。安装 ms-swift 及其核心依赖pip install ms-swift -U # 从源码安装 pip install githttps://github.com/modelscope/ms-swift.git pip install transformers -U # 可选依赖 pip install deepspeed # 多卡训练 pip install liger-kernel # 节省 GPU 显存资源 pip install flash-attn --no-build-isolation三个可选依赖分别服务于不同的训练场景deepspeed用于多卡分布式训练liger-kernel通过融合算子降低显存占用flash-attn提供高效的注意力算子注意需要--no-build-isolation以适配本机 CUDA 环境。后续多卡 SFT 与 GRPO 示例中会看到--use_liger_kernel true、--attn_impl flash_attn等参数与这些依赖的对应关系。监督微调SFT数据准备ms-swift 的 SFT 自定义数据集以messages字段为核心系统字段system可选可组织为 JSON、JSONL 或 CSV 格式并在训练脚本中通过--dataset dataset_path指定。通用格式{messages: [ {role: system, content: system-prompt}, {role: user, content: query1}, {role: assistant, content: response1} ]}带思考过程的格式assistant 内容中包含think.../think思维块{messages: [ {role: user, content: Where is the capital of Zhejiang?}, {role: assistant, content: think\n...\n/think\n\nThe capital of Zhejiang is Hangzhou.} ]}这里的思考块结构与 Qwen3 模型的思考/非思考模式机制直接相关。Qwen3 默认在回答前会进行思考可通过enable_thinkingFalse或用户消息中的/think、/no_think指令控制详见仓库 README.md 的Switching Thinking/Non-thinking Modes说明ms-swift 的数据格式正是对这一机制的完整映射。使用无思考链数据训练并保留推理能力如果你希望使用不含思维链的数据进行训练又不想破坏模型原有的推理能力ms-swift 提供两种最小化干扰的方案方案一训练时忽略空思考块损失在训练脚本中指定--loss_scale ignore_empty_think即可忽略对think\n\n/think\n\n的损失计算防止推理能力丢失。对应数据集格式{messages: [ {role: user, content: Where is the capital of Zhejiang?}, {role: assistant, content: think\n\n/think\n\nThe capital of Zhejiang is Hangzhou.} ]}方案二在 query 中追加/no_think在数据集 query 末尾添加/no_think同样可以避免推理能力损失。这与 Qwen3 原生支持的/no_think指令机制一一对应{messages: [ {role: user, content: Where is the capital of Zhejiang? /no_think}, {role: assistant, content: think\n\n/think\n\nThe capital of Zhejiang is Hangzhou.} ]}提示本仓库 thinking_budget.md 对 Qwen3 思考长度thinking budget的控制方式有专门说明微调数据处理时可参考其关于思维链长度的设计思路。30 分钟自认知微调Qwen3-8B本节演示一个约 30 分钟的 Qwen3-8B 自认知微调流程所需 GPU 显存为 22GB可在 ModelScope 免费算力提供的 A10 上运行。训练完成后模型会将自身认知从Qwen、由阿里云训练改为swift-robot、由 swift 训练。CUDA_VISIBLE_DEVICES0 \ swift sft \ --model Qwen/Qwen3-8B \ --train_type lora \ --dataset swift/Qwen3-SFT-Mixin#2000 \ swift/self-cognition:qwen3#600 \ --torch_dtype bfloat16 \ --num_train_epochs 1 \ --per_device_train_batch_size 1 \ --per_device_eval_batch_size 1 \ --learning_rate 1e-4 \ --lora_rank 8 \ --lora_alpha 32 \ --target_modules all-linear \ --gradient_accumulation_steps 16 \ --eval_steps 50 \ --save_steps 50 \ --save_total_limit 2 \ --logging_steps 5 \ --max_length 2048 \ --output_dir output \ --warmup_ratio 0.05 \ --dataloader_num_workers 4 \ --model_author swift \ --model_name swift-robot关键参数解读--train_type lora使用 LoRA 参数高效微调而非全参数微调--dataset swift/Qwen3-SFT-Mixin#2000 swift/self-cognition:qwen3#600#后数字表示从该数据集采样的样本数量两个数据集会自动拼接混用self-cognition数据集即自认知数据其中以qwen3为 key 的子集采样 600 条--lora_rank 8与--lora_alpha 32LoRA 的秩与缩放因子alpha 常取 rank 的倍数32/84 是常见配置--target_modules all-linear对模型所有线性层施加 LoRA 适配器--torch_dtype bfloat16以 bf16 精度训练A10 等 Ampere 及以上 GPU 原生支持--model_author swift与--model_name swift-robot直接改写模型的自认知字段是本次自认知微调的核心参数。离线训练如需在离线环境训练可手动下载模型与数据集然后分别通过--model model-path与--dataset dataset-dir指定本地路径self-cognition数据集可在 ModelScope Hub 上获取。推理测试微调结果训练完成后用swift infer测试效果。注意--adapters需要修改为最后一次保存的 checkpoint 目录路径CUDA_VISIBLE_DEVICES0 \ swift infer \ --adapters output/vx-xxx/checkpoint-xxx \ --stream true \ --temperature 0 \ --max_new_tokens 2048--stream true开启流式输出--temperature 0使用贪婪解码保证结果可复现。微调后模型的对话效果示例 who are you? think Okay, the user asked, who are you? I need to introduce myself. Let me start by stating my name, swift-robot. Then, I should mention that Im an AI assistant developed by swift. I should explain my purpose, which is to provide information and assistance. I should also highlight my capabilities, like answering questions, generating text, and engaging in conversation. Its important to keep the tone friendly and approachable. Maybe add something about being here to help and encourage the user to ask anything. Let me check if I covered all the key points: name, developer, purpose, capabilities, and a welcoming statement. Yeah, that should do it. Now, let me put that into a concise and friendly response. /think Hello! I am swift-robot, an artificial intelligence assistant developed by swift. My purpose is to provide information and assistance to users like you. I can answer questions, generate text, and engage in conversations on a wide range of topics. I am here to help, so feel free to ask me anything you need!可以看到模型已经建立了swift-robot / developed by swift的自我认知同时保留了完整的思考链能力。权重合并与模型推送默认情况下ms-swift 从 ModelScope 社区下载模型与数据集如需使用 HuggingFace 社区需额外指定--use_hf true。合并 LoRA 权重将 LoRA 适配器合并回基础模型swift export \ --adapters output/checkpoint-xxx \ --merge_lora true推送模型到 ModelScope/HuggingFace# 若推送的是完整权重需将 --adapters 改为 --model swift export \ --adapters output/checkpoint-xxx \ --push_to_hub true \ --hub_model_id hub-model-id \ --hub_token hub-token \ --use_hf false多 GPU 训练当需要更大吞吐时可扩展为多卡训练。以下示例在 4 × 60GB GPU 上以全参数微调--train_type full方式训练 Qwen3-8B可使用AI-ModelScope/alpaca-gpt4-data-en数据集复现实验NPROC_PER_NODE4 \ CUDA_VISIBLE_DEVICES0,1,2,3 \ swift sft \ --model Qwen/Qwen3-8B \ --train_type full \ --dataset your-dataset \ --torch_dtype bfloat16 \ --per_device_train_batch_size 1 \ --per_device_eval_batch_size 1 \ --learning_rate 1e-5 \ --gradient_accumulation_steps 4 \ --packing true \ --eval_steps 100 \ --save_steps 100 \ --logging_steps 5 \ --max_length 8192 \ --warmup_ratio 0.05 \ --dataloader_num_workers 8 \ --dataset_num_proc 8 \ --save_total_limit 2 \ --save_only_model true \ --output_dir output \ --deepspeed zero3 \ --use_liger_kernel true \ --attn_impl flash_attn相比单卡 LoRA 示例这里的关键差异包括NPROC_PER_NODE4CUDA_VISIBLE_DEVICES0,1,2,3在 4 张 GPU 上启动分布式训练--packing true将多个短样本打包进一个序列以提升训练效率。注意若指定--packing true必须同时设置--attn_impl flash_attn即安装 flash-attn否则无法正确计算 packed 序列的注意力掩码--deepspeed zero3启用 DeepSpeed ZeRO-3 分片策略使全参数微调的大模型权重分布到多卡--use_liger_kernel true启用 liger-kernel 融合算子节省显存--save_only_model true仅保存模型权重不保存优化器状态减少存储占用--dataset_num_proc 8多进程进行数据集预处理加速数据流水线。强化学习RLGRPO 训练ms-swift 支持 DPO、GRPO、DAPO、PPO、KTO 等 RLHF 方法。本节以 Qwen3-8B 的 GRPO 训练为例。GRPOGroup Relative Policy Optimization通过一组采样回复的相对优势来更新策略不需要 Critic 模型显存与算力开销远低于 PPO非常适合在 ms-swift 中与 vLLM 采样引擎配合使用。环境准备除前述 ms-swift 相关依赖外GRPO 训练还需额外安装pip install math_verify0.5.2 pip install vllm其中math_verify用于数学答案的精确校验配合 accuracy 奖励函数vllm作为采样加速引擎。数据准备GRPO 数据集格式与 SFT 类似区别在于最后一轮对话不需要 assistant 回复模型需要自己生成回复以供奖励计算。若使用准确率作为奖励还需solution列用于计算回复正确性。示例数据集格式{messages: [{role: user, content: Tell me tomorrows weather}]} {messages: [{role: user, content: What is 1 1?}, {role: assistant, content: It equals 2}, {role: user, content: What about adding 1?}]} {messages: [{role: user, content: What is your name?}]}关于数据集要求的补充说明奖励函数计算数据集格式取决于所使用的奖励函数可能需要额外列来支撑特定奖励计算。例如使用内置的准确率accuracy或余弦相似度cosine similarity奖励时数据集必须包含solution列来计算回复准确率自定义奖励函数数据集中的其他列会以**kwargs形式传递给奖励函数供自定义奖励逻辑使用。可参考 ms-swift 仓库examples/train/grpo/plugin目录下的外部奖励插件示例与模板。GRPO 训练命令训练过程中使用 vLLM 加速采样通过num_infer_workers8为每个设备部署一个 vLLM 引擎加速采样过程。完整命令8 × 70GB GPU 配置如下CUDA_VISIBLE_DEVICES0,1,2,3,4,5,6,7 \ NPROC_PER_NODE8 \ swift rlhf \ --rlhf_type grpo \ --model Qwen/Qwen3-8B \ --train_type full \ --dataset AI-MO/NuminaMath-TIR#5000 \ --torch_dtype bfloat16 \ --num_train_epochs 1 \ --per_device_train_batch_size 2 \ --per_device_eval_batch_size 2 \ --learning_rate 1e-6 \ --save_total_limit 2 \ --logging_steps 5 \ --output_dir output \ --gradient_accumulation_steps 1 \ --warmup_ratio 0.05 \ --dataloader_num_workers 4 \ --max_completion_length 4096 \ --vllm_max_model_len 8192 \ --reward_funcs accuracy \ --num_generations 16 \ --use_vllm true \ --vllm_gpu_memory_utilization 0.4 \ --sleep_level 1 \ --offload_model true \ --offload_optimizer true \ --gc_collect_after_offload true \ --deepspeed zero3 \ --num_infer_workers 8 \ --tensor_parallel_size 1 \ --temperature 1.0 \ --top_p 0.85 \ --log_completions true \ --overlong_filter true关键参数解读--rlhf_type grpo指定 RLHF 算法为 GRPO--reward_funcs accuracy使用准确率奖励函数因此数据集需要solution列--num_generations 16每组 prompt 采样 16 条回复用于计算组内相对优势GRPO 的核心机制--use_vllm true与--num_infer_workers 8启用 vLLM 加速采样并为每张卡部署一个 vLLM 引擎--max_completion_length 4096限制生成回复的最大长度控制采样阶段计算量--vllm_max_model_len 8192与--vllm_gpu_memory_utilization 0.4vLLM 引擎的最大序列长度与 GPU 显存利用率保留显存给训练侧--offload_model true/--offload_optimizer true/--gc_collect_after_offload true将模型与优化器状态卸载到 CPU 并在卸载后回收显存是 8 卡训练 8B 模型时缓解显存压力的关键配置--sleep_level 1控制训练与采样阶段的交错调度--temperature 1.0与--top_p 0.85采样多样性参数GRPO 阶段通常比推理阶段使用更高的温度以鼓励探索--overlong_filter true过滤超长样本防止生成超过 vLLM 最大长度而截断--log_completions true记录采样回复便于人工检查奖励质量。Megatron-SWIFTMoE 模型的大规模并行训练ms-swift 融合了 Megatron 并行技术以加速大模型训练即 Megatron-SWIFT。它通过将 HFHuggingFace/ModelScope权重转换为 MCoreMegatron Core格式并施加张量并行TP、专家并行EP、序列并行SP等策略可显著提升 MoE 模型的训练吞吐。以下示例在阿里云 DLC 上启动训练环境为 2 台机器 × 8 × 80GiB A800 GPU使用专家并行技术对 MoE 架构的 Qwen3-30B-A3B 进行 SFT。# 使用 DLC 通用环境变量RANK、WORLD_SIZE推导多机配置 # 注意两台节点上的权重保存路径必须一致 NNODES$WORLD_SIZE \ NODE_RANK$RANK \ megatron sft \ --load Qwen3-30B-A3B-Base-mcore \ --dataset liucong/Chinese-DeepSeek-R1-Distill-data-110k-SFT \ --tensor_model_parallel_size 2 \ --expert_model_parallel_size 8 \ --moe_grouped_gemm true \ --moe_shared_expert_overlap true \ --moe_aux_loss_coeff 0.01 \ --micro_batch_size 1 \ --global_batch_size 16 \ --packing true \ --recompute_granularity full \ --recompute_method uniform \ --recompute_num_layers 1 \ --train_iters 2000 \ --eval_iters 50 \ --finetune true \ --cross_entropy_loss_fusion true \ --lr 1e-5 \ --lr_warmup_iters 100 \ --min_lr 1e-6 \ --save megatron_output/Qwen3-30B-A3B-Base \ --eval_interval 200 \ --save_interval 200 \ --max_length 8192 \ --num_workers 8 \ --dataset_num_proc 8 \ --no_save_optim true \ --no_save_rng true \ --sequence_parallel true \ --use_flash_attn trueMoE 与并行相关参数解读--tensor_model_parallel_size 2张量并行度设为 2将单层权重切分到 2 张卡--expert_model_parallel_size 8专家并行度设为 8。MoE 模型的 FFN 专家分布在 8 张卡上这是加速 Qwen3-30B-A3B 这类 MoE 模型的核心手段——训练吞吐可从 DeepSpeed 的约 91.2s/it 提升至 9.6s/it即近 10 倍加速--moe_grouped_gemm true对 MoE 专家采用 grouped GEMM 合并计算提升专家计算的访存效率--moe_shared_expert_overlap true共享专家计算与 Token 调度重叠隐藏通信开销--moe_aux_loss_coeff 0.01MoE 负载均衡辅助损失的系数防止专家路由失衡--micro_batch_size 1与--global_batch_size 16微批量大小 1、全局批量大小 16global micro × DP × grad accumulation--recompute_granularity full--recompute_method uniform--recompute_num_layers 1以每 1 层为单位均匀地全量重计算激活用算力换显存--sequence_parallel true序列并行与张量并行配合进一步切分激活--cross_entropy_loss_fusion true融合交叉熵损失计算减少通信与 kernel 开销--no_save_optim true/--no_save_rng trueSFT 阶段不保存优化器与 RNG 状态大幅减少 checkpoint 体积--finetune true以微调模式加载权重不从头训练。数据集格式与swift sft完全一致见上文 SFT 数据准备只需指定--dataset dataset_path即可。Megatron-SWIFT 与 DeepSpeed 性能对比下图为对 Qwen3-30B-A3B 进行全参数微调时megatron sft与swift sftDeepSpeed ZeRO-2/ZeRO-3在训练速度与显存占用上的对比Megatron-LMDeepSpeed-ZeRO2DeepSpeed-ZeRO3Training Speed9.6s/it-91.2s/itGPU Memory Usage16 × 60GiBOOM16 × 80GiB结论清晰对于 MoE 架构模型Megatron 的专家并行EP策略在 16 卡 A800 上仅需 60GiB/卡即可完成训练且吞吐约为 DeepSpeed-ZeRO3 的9.5 倍91.2 / 9.6而 DeepSpeed-ZeRO2 在该规模下直接显存溢出OOM。总结通过本文你已掌握使用 ms-swift 训练 Qwen3 系列模型的完整路径SFT掌握messages通用/带思考链两种数据集格式学会用--loss_scale ignore_empty_think与/no_think两种技巧在无思维链数据上微调时保留推理能力通过 30 分钟自认知微调示例跑通训练 → 推理测试 → 合并权重 → 推送 Hub全流程并可扩展到多卡全参数微调GRPO RLHF掌握以 vLLM 加速采样的 GRPO 训练配置理解 accuracy 奖励对solution列的要求、num_generations组内采样机制以及模型/优化器卸载对显存压力的缓解作用Megatron-SWIFT掌握 MoE 模型的专家并行、张量并行、序列并行配置理解了专家并行将 MoE 训练吞吐提升近 10 倍9.6s/it vs 91.2s/it的底层原理。后续可结合仓库中的 ms_swift.md 原文档与其他训练框架指南如 verl.md、axolotl.md、llama_factory.md对比选择适合自身场景的训练方案遇到使用问题可参考 ms-swift 官方 issue 讨论区。【免费下载链接】Qwen1.5Qwen3 is the large language model series developed by Qwen team, Alibaba Cloud.项目地址: https://gitcode.com/GitHub_Trending/qw/Qwen1.5创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门