1. 环境安装
在开始之前,请确保您的开发环境已配置好 Python 和 CUDA。建议使用国内镜像源加速依赖下载。
如何使用 MS-Swift 框架对 Qwen 大模型进行微调。内容涵盖环境安装、微调前推理验证、LoRA 微调流程(含 Python 与 CLI 方式)、微调后推理及 Web-UI 部署。重点讲解了关键参数配置、DeepSpeed 多卡训练、自定义数据集准备以及常见问题排查与性能优化方案,帮助用户快速实现个性化大模型的构建与应用。

在开始之前,请确保您的开发环境已配置好 Python 和 CUDA。建议使用国内镜像源加速依赖下载。
# 设置 pip 全局镜像 (加速下载)
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
# 安装 ms-swift 框架
pip install 'ms-swift[llm]' -U
# 环境对齐 (通常不需要运行,如果你运行错误,可以跑下面的代码,仓库使用最新环境测试)
pip install -r requirements/framework.txt -U
pip install -r requirements/llm.txt -U
在安装完成后,首先需要验证环境是否正常工作,并测试基座模型的推理能力。
使用 Python 脚本:
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
from swift.llm import ModelType, InferArguments, infer_main
infer_args = InferArguments(model_type=ModelType.qwen1half_4b_chat)
result = infer_main(infer_args)
使用命令行 (CLI):
CUDA_VISIBLE_DEVICES=0 swift infer --model_type qwen1half-4b-chat
此时模型会输出默认的系统设定,例如自我介绍为阿里云通义千问。
微调是改变模型行为、知识或风格的关键步骤。本示例使用 LoRA 技术进行高效微调,适合显存有限的场景。
提示:因为自我认知训练涉及到知识编辑,建议对 MLP 加 lora_target_modules。你可以通过指定 --lora_target_modules ALL 在所有的 linear 层 (包括 qkvo 以及 mlp) 加 lora。这通常是效果最好的。
关键参数解释:
learning_rate: 学习率,建议从 5e-5 开始尝试。warmup_ratio: 预热比例,防止初期梯度震荡。max_length: 最大序列长度,根据显存大小调整,显存不足可降低此值。dataset: 数据集名称及数量,支持内置数据集如 alpaca_zh, self_cognition 等。# Experimental environment: A10, 3090, V100, ...
# 22GB GPU memory
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
from swift.llm import DatasetName, ModelType, SftArguments, sft_main
sft_args = SftArguments(
model_type=ModelType.qwen1half_4b_chat,
dataset=[f'{DatasetName.alpaca_zh}#500', f'{DatasetName.alpaca_en}#500',
f'{DatasetName.self_cognition}#500'],
logging_steps=5,
max_length=2048,
learning_rate=5e-5,
warmup_ratio=0.4,
output_dir='output',
lora_target_modules=['ALL'],
model_name=['小黄', 'Xiao Huang'],
model_author=['魔搭', 'ModelScope'])
output = sft_main(sft_args)
best_model_checkpoint = output['best_model_checkpoint']
print(f'best_model_checkpoint: {best_model_checkpoint}')
# Experimental environment: A10, 3090, V100, ...
# 22GB GPU memory
CUDA_VISIBLE_DEVICES=0 \
swift sft \
--model_type qwen1half-4b-chat \
--dataset alpaca-zh#500 alpaca-en#500 self-cognition#500 \
--logging_steps 5 \
--max_length 2048 \
--learning_rate 5e-5 \
--warmup_ratio 0.4 \
--output_dir output \
--lora_target_modules ALL \
--model_name 小黄 'Xiao Huang' \
--model_author 魔搭 ModelScope \
如果你使用的是 3090 等卡,可以降低
max_length来减少显存消耗。
# Experimental environment: 4 * 3090
# 4 * 24GB GPU memory
CUDA_VISIBLE_DEVICES=0,1,2,3 \
NPROC_PER_NODE=4 \
swift sft \
--model_type qwen1half-4b-chat \
--dataset alpaca-zh#500 alpaca-en#500 self-cognition#500 \
--logging_steps 5 \
--max_length 2048 \
--learning_rate 5e-5 \
--warmup_ratio 0.4 \
--output_dir output \
--lora_target_modules ALL \
--model_name 小黄 'Xiao Huang' \
--model_author 魔搭 ModelScope \
--deepspeed default-zero2 \
若需使用私有数据,请将数据整理为 JSONL 格式,包含 instruction, input, output 字段,并注册到 Swift 的数据集中,或在脚本中直接加载本地路径。
你需要设置 best_model_checkpoint 的值,该值会在 sft 的最后被打印出来。
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
from swift.llm import InferArguments, merge_lora, infer_main
best_model_checkpoint = 'qwen1half-4b-chat/vx-xxx/checkpoint-xxx'
infer_args = InferArguments(ckpt_dir=best_model_checkpoint)
merge_lora(infer_args, device_map='cpu')
result = infer_main(infer_args)
# 直接推理
CUDA_VISIBLE_DEVICES=0 swift infer --ckpt_dir 'qwen1half-4b-chat/vx-xxx/checkpoint-xxx'
# Merge LoRA 增量权重并推理
# 如果你需要量化,可以指定`--quant_bits 4`.
CUDA_VISIBLE_DEVICES=0 swift export \
--ckpt_dir 'qwen1half-4b-chat/vx-xxx/checkpoint-xxx' --merge_lora true
CUDA_VISIBLE_DEVICES=0 swift infer --ckpt_dir 'qwen1half-4b-chat/vx-xxx/checkpoint-xxx-merged'
为了方便交互,可以使用 Swift 提供的 Web UI 界面进行测试。
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
from swift.llm import AppUIArguments, merge_lora, app_ui_main
best_model_checkpoint = 'qwen1half-4b-chat/vx-xxx/checkpoint-xxx'
app_ui_args = AppUIArguments(ckpt_dir=best_model_checkpoint)
merge_lora(app_ui_args, device_map='cpu')
result = app_ui_main(app_ui_args)
# 直接使用 app-ui
CUDA_VISIBLE_DEVICES=0 swift app-ui --ckpt_dir 'qwen1half-4b-chat/vx-xxx/checkpoint-xxx'
# Merge LoRA 增量权重并使用 app-ui
# 如果你需要量化,可以指定`--quant_bits 4`.
CUDA_VISIBLE_DEVICES=0 swift export \
--ckpt_dir 'qwen1half-4b-chat/vx-xxx/checkpoint-xxx' --merge_lora true
CUDA_VISIBLE_DEVICES=0 swift app-ui --ckpt_dir 'qwen1half-4b-chat/vx-xxx/checkpoint-xxx-merged'
如果在训练过程中出现 OOM 错误,可以尝试以下方法:
max_length 参数。batch_size (通过 gradient_accumulation_steps 间接控制)。如果微调后模型表现未达预期:
lora_target_modules 的范围,尝试覆盖更多层。model_name 和 model_author 等系统指令是否正确注入。merge_lora 将 LoRA 权重合并到主模型,可提升推理速度。--quant_bits 4) 以牺牲少量精度换取显存和速度优势。
微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online