LLaMA Factory 在国产 DCU 上微调 Llama 3 模型实战
在国产海光 DCU(K100-AI)上使用 LLaMA Factory 对 Llama 3-8B-Instruct 模型进行 LoRA 微调的完整流程。内容涵盖环境搭建、配置文件解析、训练日志解读、推理测试及模型导出步骤。通过详细分析关键日志和输出结果,帮助开发者掌握在大模型微调中的配置要点与常见问题处理。

在国产海光 DCU(K100-AI)上使用 LLaMA Factory 对 Llama 3-8B-Instruct 模型进行 LoRA 微调的完整流程。内容涵盖环境搭建、配置文件解析、训练日志解读、推理测试及模型导出步骤。通过详细分析关键日志和输出结果,帮助开发者掌握在大模型微调中的配置要点与常见问题处理。

本文基于前期实践,详细解读使用 LLaMA Factory 工具在国产 DCU(海光 K100-AI)上对 Meta-Llama-3-8B-Instruct 模型进行 LoRA 微调、推理及导出的关键日志输出和核心测试信息。
本次实践的环境基于国产海光 DCU K100-AI,DTK 版本为 25.04。核心软件栈包括 Python 3.10 以及针对 DCU 优化的 PyTorch (torch==2.4.1+das.opt2.dtk2504) 及其相关深度学习库。
conda create -n dcu_llm_fine python=3.10
conda activate dcu_llm_fine
根据文档指引,从开发者社区下载并安装适配 DCU K100-AI (DTK 25.04, Python 3.10) 的 PyTorch, lmslim, flash-attn, vllm, deepspeed 等 whl 包。确保各组件版本严格对应。
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 .。
我们以 Meta-Llama-3-8B-Instruct 模型为例,采用 LoRA (Low-Rank Adaptation) 方法进行监督式微调 (SFT)。
以下是核心配置参数:
### 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
llamafactory-cli train examples/train_lora/llama3_lora_sft.yaml
Setting ds_accelerator to cuda (auto detect)Initializing 8 distributed tasks at: 127.0.0.1:54447size: 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.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"。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)。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: LoRAFound 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 引入的可训练参数量和占比。***** Running training *****Num examples = 1,091, Num Epochs = 3Instantaneous batch size per device = 1, Total train batch size (w. parallel, distributed & accumulation) = 64Gradient Accumulation steps = 8, Total optimization steps = 51logging_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.)Saving model checkpoint to saves/llama3-8b/lora/sft/checkpoint-51***** train metrics *****:
epoch = 2.9781train_loss = 1.0481train_runtime = 0:04:56.32 (即 296.3281 秒)train_samples_per_second = 11.045train_steps_per_second = 0.172Figure saved at: saves/llama3-8b/lora/sft/training_loss.png微调完成后,我们加载 LoRA 适配器进行推理测试。
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
llamafactory-cli chat examples/inference/llama3_lora_sft.yaml
torch_dtype: "bfloat16", use_cache: true) 和权重 (model.safetensors.index.json, 4 个分片)。KV cache is enabled for faster generation.Loaded adapter(s): saves/llama3-8b/lora/sft。Merged 1 adapter(s).,确认 LoRA 权重已合并到基础模型。all params: 8,030,261,248。plaintext 你是谁我是 {{name}},由 {{author}} 训练的 AI 助手。我旨在为您提供帮助,回答问题和完成任务。{{name}} 和 {{author}} 占位符,表明模型学习了微调数据 identity.json 中的模板格式。将微调后的 LoRA 权重与基础模型合并,并导出为独立模型。
### 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 适配器时不应使用已量化的模型。
llamafactory-cli export examples/merge_lora/llama3_lora_sft.yaml
torch_dtype: "bfloat16") 和权重 (4 个分片)。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 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 微调的门槛。通过对各阶段关键日志输出和测试信息的详细解读,我们可以更直观地把握模型在训练中的学习动态、在推理中的行为表现以及导出后的结构。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 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