
实战 LLaMA Factory:在国产DCU上高效微调 Llama 3 模型
一、前言
随着大语言模型(LLM)的飞速发展,如何在特定领域或任务上对预训练模型进行高效微调,已成为业界关注的焦点。LLaMA Factory 作为一个功能强大且易于上手的 LLM 微调框架,受到了广泛关注。本文将聚焦于在国产 DCU 平台上,利用 LLaMA Factory 对 Llama 3 模型进行 LoRA 微调的实践过程,并分享其中的关键步骤与经验。
🚀 海光DCU实战项目来了!助您轻松驾驭大模型与HPC开发 🚀
为帮助开发者更便捷在海光DCU上进行大模型(训练、微调、推理)及科学计算,我依托海光DCU开发者社区,精心打造了一个开箱即用的实战项目 —— “dcu-in-action”!
旨在为您提供:
• 🔧 直接上手的代码示例与实践指南
• ⚡ 加速您在海光DCU上的开发与部署流程
欢迎各位开发者:
• 访问项目GitHub仓库,深入体验、参与贡献,共同完善: https://github.com/FlyAIBox/dcu-in-action
• 如果项目对您有帮助,请我们点亮一个宝贵的 Star 🌟
二、环境准备与 LLaMA Factory 安装
本次实践的环境基于国产海光 DCU K100-AI,DTK 版本为 25.04。核心软件栈包括 Python 3.10 以及针对 DCU 优化的 PyTorch (torch==2.4.1+das.opt2.dtk2504) 及其相关深度学习库(如 lmslim, flash-attn,vllm,deepspeed 的特定版本)。
1. 创建虚拟环境
conda create -n dcu_llm_fine python=3.10
conda activate dcu_llm_fine
2. 安装 DCU 特定深度学习库
根据文档指引,从光合开发者社区下载并安装适配 DCUK100-AI (DTK 25.04, Python 3.10) 的 PyTorch, lmslim,flash-attn, vllm deepspeed 等 whl 包。确保各组件版本严格对应。
3. 安装 LLaMA Factory
git clone http://developer.hpccube.com/codes/OpenDAS/llama-factory.git
cd /your_code_path/llama_factory
pip install -e ".[torch,metrics]"
注意:如遇包冲突,可尝试 pip install --no-deps -e .。
三、Llama 3 LoRA 微调实战
我们以 Meta-Llama-3-8B-Instruct 模型为例,采用 LoRA (Low-Rank Adaptation) 方法进行监督式微调 (SFT)。
1. 微调配置文件解析 (llama3_lora_sft.yaml)
以下是核心配置参数:
### model
model_name_or_path:/root/.cache/modelscope/hub/models/LLM-Research/Meta-Llama-3-8B-Instruct# 模型路径
trust_remote_code:true
### method
stage:sft # 微调阶段:监督式微调
do_train:true
finetuning_type:lora # 微调方法:LoRA
lora_rank:8 # LoRA 秩
lora_target:all # LoRA 应用目标:所有线性层
### dataset
dataset:identity,alpaca_en_demo# 使用的数据集
template:llama3 # 对话模板
cutoff_len:2048 # 序列截断长度
max_samples:1000 # 每个数据集最大样本数
overwrite_cache:true
preprocessing_num_workers:16 # 预处理进程数
### output
output_dir:saves/llama3-8b/lora/sft# 输出目录
logging_steps:10
save_steps:500
plot_loss:true
overwrite_output_dir:true
save_only_model:false # 保存完整checkpoint而非仅模型
### train
per_device_train_batch_size:1# 每GPU批大小
gradient_accumulation_steps:8# 梯度累积步数
learning_rate:1.0e-4 # 学习率
num_train_epochs:3.0 # 训练轮次
lr_scheduler_type:cosine # 学习率调度器
warmup_ratio:0.1 # 预热比例
bf16:true # 使用bf16混合精度
ddp_timeout:180000000
resume_from_checkpoint: null
2. 启动微调
llamafactory-cli train examples/train_lora/llama3_lora_sft.yaml
3. 微调过程关键日志输出与解读
环境初始化与分布式设置 (日志时间: 21:16:40 - 21:16:51)
• Setting ds_accelerator to cuda (auto detect)
• Initializing 8 distributed tasks at: 127.0.0.1:54447
• 各 GPU 进程 (如 [PG 0 Rank 2]) 初始化 NCCL,日志显示 size: 8, global rank: 2, TIMEOUT(ms): 180000000000。
• 各进程确认信息,例如 Process rank: 2, world size: 8, device: cuda:2, distributed training: True, compute dtype: torch.bfloat16,表明已启用 bf16 混合精度。
• Set ddp_find_unused_parameters to False in DDP training since LoRA is enabled.
Tokenizer 与模型配置加载 (日志时间: 21:16:51 - 21:16:52)
• 加载 tokenizer.json, tokenizer.model 等文件。
• 加载模型配置文件 /root/.cache/modelscope/hub/models/LLM-Research/Meta-Llama-3-8B-Instruct/config.json,确认模型架构如 hidden_size: 4096, num_hidden_layers: 32, torch_dtype: "bfloat16"。
数据集加载与预处理 (日志时间: 21:16:52 - 21:17:01)
• Add pad token: <|eot_id|>,Add <|eot_id|>,<|eom_id|> to stop words.
• 加载数据集 identity.json (91条样本) 和 alpaca_en_demo.json (1000条样本)。
• Converting format of dataset (num_proc=16) 和 Running tokenizer on dataset (num_proc=16),共处理 1091 条样本。
• 展示了处理后的一个训练样本 training example,包括 input_ids, inputs (已格式化模板) 和 label_ids (prompt部分为-100)。
基础模型权重加载与 LoRA 适配器设置 (日志时间: 21:17:01 - 21:17:16)
• KV cache is disabled during training.
• 加载模型权重 /root/.cache/modelscope/hub/models/LLM-Research/Meta-Llama-3-8B-Instruct/model.safetensors.index.json,共4个分片。
• 出现警告: Using the SDPA attention implementation on multi-gpu setup with ROCM may lead to performance issues due to the FA backend. Disabling it to use alternative backends.
• Gradient checkpointing enabled.
• Fine-tuning method: LoRA
• Found linear modules: v_proj,q_proj,k_proj,down_proj,o_proj,gate_proj,up_proj (这些是 lora_target: all 选中的层)。
• trainable params: 20,971,520 || all params: 8,051,232,768 || trainable%: 0.2605,明确了 LoRA 引入的可训练参数量和占比。
Trainer 初始化与训练循环 (日志时间: 21:17:16 - 21:22:15)
• ***** Running training *****
• Num examples = 1,091, Num Epochs = 3
• Instantaneous batch size per device = 1, Total train batch size (w. parallel, distributed & accumulation) = 64
• Gradient Accumulation steps = 8, Total optimization steps = 51
• 训练日志周期性输出 (每 logging_steps: 10次迭代,但日志中是按优化步聚合后展示的):
{'loss': 1.4091, 'grad_norm': 1.0385..., 'learning_rate': 9.8063...e-05, 'epoch': 0.58}
{'loss': 1.0404, 'grad_norm': 0.6730..., 'learning_rate': 7.7959...e-05, 'epoch': 1.17}
{'loss': 0.9658, 'grad_norm': 0.4174..., 'learning_rate': 4.4773...e-05, 'epoch': 1.75}
{'loss': 0.9389, 'grad_norm': 0.3942..., 'learning_rate': 1.4033...e-05, 'epoch': 2.34}
{'loss': 0.894, 'grad_norm': 0.4427..., 'learning_rate': 1.2179...e-07, 'epoch': 2.92}
• 训练过程中反复出现 UserWarning: 1Torch was not compiled with memory efficient attention. (Triggered internally at /home/pytorch/aten/src/ATen/native/transformers/hip/sdp_utils.cpp:627.)
训练完成与模型保存 (日志时间: 15:22:15 - 15:22:17)
• Saving model checkpoint to saves/llama3-8b/lora/sft/checkpoint-51
• 最终训练指标 ***** train metrics *****:
epoch = 2.9781
train_loss = 1.0481
train_runtime = 0:04:56.32 (即 296.3281秒)
train_samples_per_second = 11.045
train_steps_per_second = 0.172
• Figure saved at: saves/llama3-8b/lora/sft/training_loss.png
• NCCL 通信器关闭,各进程资源清理。
四、模型推理测试
微调完成后,我们加载 LoRA 适配器进行推理测试。
1. 推理配置文件 (llama3_lora_sft.yaml for inference)
model_name_or_path: /root/.cache/modelscope/hub/models/LLM-Research/Meta-Llama-3-8B-Instruct
adapter_name_or_path: saves/llama3-8b/lora/sft # 加载微调后的LoRA适配器
template: llama3
infer_backend: huggingface # 推理后端
trust_remote_code: true
2. 启动推理
llamafactory-cli chat examples/inference/llama3_lora_sft.yaml
3. 推理过程关键日志输出与测试结果
模型加载 (日志时间: 17:30:16 - 17:31:18)
• 加载基础模型 Tokenizer, config (torch_dtype: "bfloat16", use_cache: true) 和权重 (model.safetensors.index.json, 4个分片)。
• KV cache is enabled for faster generation.
• 再次出现 SDPA on ROCm 性能警告。
• 加载 LoRA 适配器: Loaded adapter(s): saves/llama3-8b/lora/sft。
• Merged 1 adapter(s).,确认 LoRA 权重已合并到基础模型。
• 加载后模型参数量 all params: 8,030,261,248。
交互测试结果
• User:
你是谁
- Assistant:
我是 {{name}},由 {{author}} 训练的 AI 助手。我旨在为您提供帮助,回答问题和完成任务。
评析:输出中的 {{name}} 和 {{author}} 占位符,表明模型学习了微调数据 identity.json 中的模板格式。
五、模型导出
将微调后的 LoRA 权重与基础模型合并,并导出为独立模型。
1. 导出配置文件 (llama3_lora_sft.yaml for export)
### Note: DO NOT use quantized model or quantization_bit when merging lora adapters
### model
model_name_or_path:/root/.cache/modelscope/hub/models/LLM-Research/Meta-Llama-3-8B-Instruct
adapter_name_or_path:saves/llama3-8b/lora/sft
template:llama3
trust_remote_code:true
### export
export_dir:output/llama3_lora_sft# 导出目录
export_size:5 # 模型分片大小上限 (GB)
export_device:cpu # 导出时使用的设备
export_legacy_format:false # 不使用旧格式,优先safetensors
重要提示:配置文件中明确指出,合并 LoRA 适配器时不应使用已量化的模型。
2. 启动导出
llamafactory-cli export examples/merge_lora/llama3_lora_sft.yaml
3. 导出过程关键日志输出 (日志时间: 18:06:54 - 18:08:22)
• 加载基础模型 Tokenizer, config (torch_dtype: "bfloat16") 和权重 (4个分片)。
• 加载 LoRA 适配器: Loaded adapter(s): saves/llama3-8b/lora/sft。
• Merged 1 adapter(s).,LoRA 权重与基础模型合并。
• Convert model dtype to: torch.bfloat16.
• 配置文件保存: Configuration saved in output/llama3_lora_sft/config.json 和 output/llama3_lora_sft/generation_config.json。
• 模型权重保存: The model is bigger than the maximum size per checkpoint (5GB) and is going to be split in 4 checkpoint shards. You can find where each parameters has been saved in the index located at output/llama3_lora_sft/model.safetensors.index.json. (根据配置 export_size: 5)
• Tokenizer 文件保存: tokenizer config file saved in output/llama3_lora_sft/tokenizer_config.json 和 special_tokens_map.json。
• 额外功能: Ollama modelfile saved in output/llama3_lora_sft/Modelfile。
七、总结与展望
本次实践完整地展示了使用 LLaMA Factory 在国产 DCU 平台上对 Llama 3 模型进行 LoRA 微调、推理和导出的流程。LLaMA Factory 凭借其清晰的配置和便捷的命令行工具,显著降低了 LLM 微调的门槛。 通过对各阶段关键日志输出和测试信息的详细解读,我们可以更直观地把握模型在训练中的学习动态、在推理中的行为表现以及导出后的结构。
本文转载自 萤火AI百宝箱,作者: 萤火AI百宝箱
