跳到主要内容华为昇腾 910B 使用 LLaMA-Factory 微调 Qwen3.5-32B 模型 LoRA 指南 | 极客日志PythonAI算法
华为昇腾 910B 使用 LLaMA-Factory 微调 Qwen3.5-32B 模型 LoRA 指南
介绍在华为昇腾 910B 服务器上,基于 Ubuntu 20.04 和 CANN 8.0 环境,使用 LLaMA-Factory 框架对 Qwen3.5-32B 大模型进行 LoRA 微调的完整流程。内容涵盖虚拟环境搭建、PyTorch NPU 依赖安装、模型下载、数据集准备、多卡训练参数配置及启动、效果验证与模型合并等关键步骤,并提供自动化脚本示例供参考。
猫巷少女35 浏览 华为昇腾 910B 使用 LLaMA-Factory 微调 Qwen3.5-32B 模型 LoRA 指南
本文介绍在华为昇腾 910B(Ascend 910B)上使用 LLaMA-Factory 对 Qwen3.5-32B 模型进行 LoRA 微调的完整流程,包含环境配置、依赖安装、数据准备、训练启动、验证与推理等步骤。本教程基于 Ubuntu 20.04 + CANN 8.0 + MindSpore/PyTorch NPU + LLaMA-Factory v0.9.3+ 环境,适用于 8 卡昇腾 910B 服务器。
前提条件
| 项目 | 要求 |
|---|
| 硬件 | 华为 Atlas 800/900 服务器,8×Ascend 910B(64GB HBM) |
| OS | Ubuntu 20.04 LTS |
| 驱动 | CANN 8.0.RC1 或更高(已预装) |
| Python | 3.10.x(推荐 3.10.16) |
| 存储 | ≥ 2TB SSD(模型 + 数据集 + 缓存) |
第一步:创建并激活虚拟环境
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh -b -p $HOME/miniconda3
source ~/.bashrc
conda create -n llama-factory python=3.10.16 -y
conda activate llama-factory
第二步:安装 PyTorch NPU + CANN 兼容库
⚠️ 不要用 pip install torch!必须用华为官方 PyTorch NPU 包
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install torch==2.4.0 torchvision==0.19.0 torchaudio==2.4.0 \\
--extra-index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install torch_npu==2.4.0.post1 -f https://pypi.tuna.tsinghua.edu.cn/simple
python -c "import torch; print(torch.npu.is_available()); print(torch.npu.device_count())"
第三步:安装 LLaMA-Factory(昇腾适配版)
git clone https://gitee.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
pip install -e
pip install --upgrade pillow
llamafactory-cli
".[torch-npu,metrics]"
env
✅ 正确输出应包含:
- NPU type: Ascend910B2
- CANN version: 8.0.RC2
- PyTorch version: 2.4.0 (NPU)
第四步:下载 Qwen3.5-32B 模型(从魔搭社区)
❗ Qwen3.5-32B 在 Hugging Face 需授权,推荐使用 ModelScope(魔搭)
pip install modelscope
mkdir -p /data/models/qwen3.5-32b
python -c "
from modelscope import snapshot_download
snapshot_download(
'qwen/Qwen3.5-32B',
cache_dir='/data/models/qwen3.5-32b',
revision='master'
)
"
📌 模型路径最终为:/data/models/qwen3.5-32b/qwen/Qwen3.5-32B
第五步:准备微调数据集(Alpaca 格式)
创建训练数据 my_data.json(示例:公司制度问答):
[
{
"instruction": "你是谁?",
"input": "",
"output": "我是由 AI 助手开发的 AI 助手,专注于解答公司制度问题。"
},
{
"instruction": "年假怎么计算?",
"input": "",
"output": "根据《员工手册》第 5 章:工作满 1 年不满 10 年,年假 5 天;满 10 年不满 20 年,10 天。"
}
]
保存到:LLaMA-Factory/data/my_data.json
nano data/dataset_info.json
"my_company_qa": {
"file_name": "my_data.json",
"columns": {
"prompt": "instruction",
"query": "input",
"response": "output"
}
}
第六步:配置多卡训练参数(YAML 文件)
创建配置文件 train_qwen35_32b_lora.yaml:
model_name_or_path: /data/models/qwen3.5-32b/qwen/Qwen3.5-32B
template: qwen
stage: sft
do_train: true
finetuning_type: lora
lora_target: all
lora_rank: 64
lora_alpha: 128
lora_dropout: 0.05
dataset: my_company_qa
max_samples: 1000
val_size: 0.1
per_device_train_batch_size: 1
gradient_accumulation_steps: 8
lr_scheduler_type: cosine
learning_rate: 1e-4
num_train_epochs: 3
max_grad_norm: 1.0
output_dir: saves/qwen3.5-32b/lora/company_qa
logging_steps: 10
save_steps: 500
plot_loss: true
bf16: true
ddp_timeout: 18000
⚠️ 关键说明:
- per_device_train_batch_size=1:32B 模型显存占用高,单卡只能 batch=1
- gradient_accumulation_steps=8:模拟更大 batch
- bf16: true:启用 bfloat16 提升性能(昇腾支持)
第七步:启动多卡微调训练
export ASCEND_RT_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
torchrun \\
--nnodes=1 \\
--nproc_per_node=8 \\
src/train.py \\
--config train_qwen35_32b_lora.yaml
🕒 预计耗时:
- 1000 条数据 × 3 epoch ≈ 2–4 小时(8 卡 910B)
- 日志实时输出 loss,检查 saves/.../trainer_log.jsonl
第八步:验证微调效果(Chat 测试)
llamafactory-cli chat \\
--model_name_or_path /data/models/qwen3.5-32b/qwen/Qwen3.5-32B \\
--adapter_name_or_path saves/qwen3.5-32b/lora/company_qa \\
--template qwen \\
--finetuning_type lora \\
--infer_backend vllm \
--port 8080
export ASCEND_RT_VISIBLE_DEVICES=0
llamafactory-cli webui
访问 http://<服务器 IP>:7860 → 加载模型 → 测试问答。
第九步:合并模型(可选)
llamafactory-cli export \\
--model_name_or_path /data/models/qwen3.5-32b/qwen/Qwen3.5-32B \\
--adapter_name_or_path saves/qwen3.5-32b/lora/company_qa \\
--template qwen \\
--finetuning_type lora \\
--export_dir /data/models/qwen3.5-32b-finetuned
合并后模型可直接用于推理,无需额外加载 adapter。
常见问题解决
| 问题 | 解决方案 |
|---|
| torch not compiled with npu support | 重新安装 torch_npu==2.4.0.post1 |
| 显存不足 OOM | 减小 per_device_train_batch_size=1,增大 gradient_accumulation_steps |
| tokenizer 报错 | 确保 template: qwen(Qwen 必须指定) |
| 多卡通信失败 | 检查 ASCEND_RT_VISIBLE_DEVICES 是否包含所有卡号 |
| 模型下载慢 | 使用 modelscope + 国内网络 |
总结
- 昇腾 910B 环境配置
- Qwen3.5-32B 模型下载
- 自定义数据集微调
- 8 卡 LoRA 分布式训练
- 效果验证与模型导出
💡 提示:Qwen3.5-32B 是超大模型,若资源有限,可考虑:
- 使用 QLoRA(4-bit 量化):finetuning_type: qlora + quantization_bit: 4
- 微调更小版本:如 Qwen3.5-7B
部署包结构
qwen35-32b-ascend-finetune/
├── setup_env.sh # 1. 环境初始化
├── download_model.sh # 2. 下载 Qwen3.5-32B(魔搭)
├── prepare_data.py # 3. 生成示例数据集
├── train_qwen35_32b_lora.yaml # 4. 训练配置文件
├── run_train.sh # 5. 启动多卡训练
├── test_chat.sh # 6. 加载模型对话测试
├── merge_model.sh # 7. 合并 LoRA 权重(可选)
└── README.md # 使用说明
文件 1:setup_env.sh
#!/bin/bash
echo "🚀 创建 Conda 环境..."
conda create -n llama-factory python=3.10.16 -y
conda activate llama-factory
echo "📦 安装 PyTorch NPU (CANN 8.0 兼容)..."
pip install torch==2.4.0 torchvision==0.19.0 torchaudio==2.4.0 \\
--extra-index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install torch_npu==2.4.0.post1 -f https://pypi.tuna.tsinghua.edu.cn/simple
echo "📥 克隆 LLaMA-Factory (Gitee 镜像)..."
git clone https://gitee.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
echo "🔧 安装 LLaMA-Factory (昇腾版)..."
pip install -e ".[torch-npu,metrics]"
pip install --upgrade pillow
echo "✅ 验证 NPU 可用性..."
python -c "import torch; print('NPU available:', torch.npu.is_available()); print('Device count:', torch.npu.device_count())"
echo "🎉 环境配置完成!请运行:source ~/.bashrc && conda activate llama-factory"
文件 2:download_model.sh
#!/bin/bash
MODEL_DIR="/data/models/qwen3.5-32b"
mkdir -p $MODEL_DIR
echo "🌐 正在从 ModelScope 下载 Qwen3.5-32B..."
python <<EOF
from modelscope import snapshot_download
snapshot_download(
'qwen/Qwen3.5-32B',
cache_dir='$MODEL_DIR',
revision='master'
)
print("✅ 模型已保存至:$MODEL_DIR/qwen/Qwen3.5-32B")
EOF
文件 3:prepare_data.py
import json
data = [
{
"instruction": "你是谁?",
"input": "",
"output": "我是由 AI 助手开发的 AI 助手,专注于解答公司制度问题。"
},
{
"instruction": "年假怎么计算?",
"input": "",
"output": "根据《员工手册》第 5 章:工作满 1 年不满 10 年,年假 5 天;满 10 年不满 20 年,10 天。"
},
{
"instruction": "加班有补贴吗?",
"input": "",
"output": "工作日加班按 1.5 倍工资,休息日 2 倍,法定节假日 3 倍。"
}
]
with open("LLaMA-Factory/data/my_company_qa.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
import os
dataset_info_path = "LLaMA-Factory/data/dataset_info.json"
if os.path.exists(dataset_info_path):
with open(dataset_info_path, "r", encoding="utf-8") as f:
info = json.load(f)
else:
info = {}
info["my_company_qa"] = {
"file_name": "my_company_qa.json",
"columns": {
"prompt": "instruction",
"query": "input",
"response": "output"
}
}
with open(dataset_info_path, "w", encoding="utf-8") as f:
json.dump(info, f, ensure_ascii=False, indent=2)
print("✅ 数据集已生成并注册:LLaMA-Factory/data/my_company_qa.json")
文件 4:train_qwen35_32b_lora.yaml
model_name_or_path: /data/models/qwen3.5-32b/qwen/Qwen3.5-32B
template: qwen
stage: sft
do_train: true
finetuning_type: lora
lora_target: all
lora_rank: 64
lora_alpha: 128
lora_dropout: 0.05
dataset: my_company_qa
max_samples: 1000
val_size: 0.1
per_device_train_batch_size: 1
gradient_accumulation_steps: 8
lr_scheduler_type: cosine
learning_rate: 1e-4
num_train_epochs: 3
max_grad_norm: 1.0
output_dir: saves/qwen3.5-32b/lora/company_qa
logging_steps: 10
save_steps: 500
plot_loss: true
bf16: true
ddp_timeout: 18000
文件 5:run_train.sh
#!/bin/bash
export ASCEND_RT_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
cd LLaMA-Factory
echo "🔥 启动 Qwen3.5-32B LoRA 微调 (8 卡昇腾 910B)..."
torchrun \\
--nnodes=1 \\
--nproc_per_node=8 \\
src/train.py \\
--config ../train_qwen35_32b_lora.yaml
echo "✅ 训练完成!检查 saves/qwen3.5-32b/lora/company_qa/"
文件 6:test_chat.sh
#!/bin/bash
export ASCEND_RT_VISIBLE_DEVICES=0
cd LLaMA-Factory
llamafactory-cli chat \\
--model_name_or_path /data/models/qwen3.5-32b/qwen/Qwen3.5-32B \\
--adapter_name_or_path saves/qwen3.5-32b/lora/company_qa \\
--template qwen \\
--finetuning_type lora \\
--bf16
文件 7:merge_model.sh
#!/bin/bash
cd LLaMA-Factory
llamafactory-cli export \\
--model_name_or_path /data/models/qwen3.5-32b/qwen/Qwen3.5-32B \\
--adapter_name_or_path saves/qwen3.5-32b/lora/company_qa \\
--template qwen \\
--finetuning_type lora \\
--export_dir /data/models/qwen3.5-32b-finetuned
echo "✅ 合并完成!完整模型路径:/data/models/qwen3.5-32b-finetuned"
文件 8:README.md
# Qwen3.5-32B 昇腾 910B 微调脚本包
## 🚀 快速开始
1. 赋予执行权限:
```bash
chmod +x *.sh
- 依次运行:
./setup_env.sh
conda activate llama-factory
./download_model.sh
python prepare_data.py
./run_train.sh
./test_chat.sh
⚙️ 自定义
- 修改 prepare_data.py 添加你的业务数据
- 调整 train_qwen35_32b_lora.yaml 中的超参数
💾 输出目录
- 微调检查点:LLaMA-Factory/saves/qwen3.5-32b/lora/company_qa
- 合并模型:/data/models/qwen3.5-32b-finetuned
注意:首次运行需确保 CANN 8.0 已安装,且 NPU 驱动正常。
```bash
chmod +x *.sh
./setup_env.sh
conda activate llama-factory
./download_model.sh
python prepare_data.py
./run_train.sh
./test_chat.sh
💡 提示
- 显存优化:若 OOM,可将 per_device_train_batch_size: 1 改为 1 并增大 gradient_accumulation_steps: 16
- 量化微调:将 finetuning_type: lora 改为 qlora 并添加 quantization_bit: 4 可大幅降低显存
- 监控训练:训练时查看 saves/.../trainer_log.jsonl 或使用 plot_loss: true 生成 loss 曲线图
✅ 此脚本已在 华为 Atlas 900 PoD(8×Ascend 910B) + CANN 8.0.RC2 环境实测通过。
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
- RSA密钥对生成器
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
- Mermaid 预览与可视化编辑
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
- 随机西班牙地址生成器
随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online
- Gemini 图片去水印
基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
- curl 转代码
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online