LLaMA-Factory 微调模型一

数据集选择

想要微调模型,首先就需要有合适的数据。本次微调模型的目标是训练出一个适合本地部署的翻译模型,因此我选用这个数据集:
WMT-Chinese-to-English-Machine-Translation-Training-Corpus
但是因为使用的微调工具是 LLaMA-Factory,它只支持 Alpacasharegpt 格式的训练集,因此我们还需要对原始数据集进行加工,将其转换为 Alpaca 格式。

数据集格式转换

Alpaca 格式

Alpaca 格式主要包含三个核心字段:

{
	"Instruction": "将以下内容翻译为中文",
	"input": "The weather is very nice today",
	"output": "今天的天气非常好"
}
  • instruction:明确的任务指令(必须存在)
  • input:任务输入内容(可以为空)
  • output:期望的输出结果(必须存在)

使用 python 脚本转换数据格式

WMT 中英机器翻译训练集为 CSV 格式,由两列构成,第一列为中文,第二列为英文。
使用下面的 python 脚本可以将 CSV 格式转换为 Alpaca 格式:

import pandas as pd
import json

# === 输入与输出路径 ===
input_csv = "path/to/your/train.csv" # 你的原始 CSV 文件
output_json = "wmt_zh_en_alpaca.json" # 输出的 Alpaca 格式 JSON 文件

# === 读取 CSV 文件 ===
df = pd.read_csv(input_csv)

# 检查列名
if not {'zh', 'en'}.issubset(df.columns):
	raise ValueError("CSV 文件应包含列名 'zh' 和 'en'")

data = []

# === 方向:英文 -> 中文 ===
for _, row in df.iterrows():
	zh, en = row['zh'], row['en']
	if isinstance(zh, str) and isinstance(en, str):
	data.append({
	"instruction": "Translate the following English sentence into Chinese",
	"input": en.strip(),
	"output": zh.strip()
	})

# === 保存为 JSON 格式 ===
with open(output_json, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)

print(f"✅ 转换完成,共 {len(data)} 条样本,已保存为:{output_json}")

因为我的目标是让这个模型能够将英文翻译为中文,因此脚本中调整了中英文本顺序。
最后会输出一个 .json 文件,这个文件将会在后面作为数据集使用。

使用 LLaMA-Factory 进行模型微调

下载 LLaMA-Factory

这里有两种方式下载并使用 LLaMA-Factory:

从源码安装

git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
pip install -e ".[torch,metrics]" --no-build-isolation

使用 Docker 安装

docker run -it --rm --gpus=all --ipc=host hiyouga/llamafactory:latest

不了解 Docker 的直接从源码安装就行。

添加数据集

将上面生成的 .json 文件复制到 data 文件夹中并编辑 data/dataset.json,在其中添加这几行:

  "wmt_zh_en_alpaca": {
    "file_name":  "wmt_zh_en_alpaca.json"
  },

下载模型权重

想要微调某个模型,就需要该模型的权重,本次微调以Qwen3:0.6B模型为基础模型:

modelscope download --model Qwen/Qwen3-0.6B --local_dir ./Qwen3-0.6B

配置训练脚本

编辑 examples/train_lora/qwen3-0.6b-lora-sft.yaml 文件

### model
model_name_or_path: ./Qwen3-0.6B
trust_remote_code: true

### method
stage: sft
do_train: true
finetuning_type: lora
deepspeed: ds_z3_config.json  # choices: [ds_z0_config.json, ds_z1_config.json, ds_z2_config.json, ds_z3_config.json]

### dataset
dataset: wmt_zh_en_alpaca
template: qwen
cutoff_len: 2048
#### 这里只选了1000个样本,可以根据需要适当调整
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 4
dataloader_num_workers: 2

### output
output_dir: saves/qwen3-0.6b/lora/sft
logging_steps: 1
save_steps: 1500
plot_loss: true
overwrite_output_dir: true
save_only_model: false
report_to: tensorboard  # choices: [none, wandb, tensorboard, swanlab, mlflow]
logging_dir: saves/qwen3-0.6b/lora/sft/tensorboard-log

### train
per_device_train_batch_size: 1
gradient_accumulation_steps: 4
learning_rate: 1.0e-5
#### 可以修改下面的数字改变训练轮数
num_train_epochs: 1.0
lr_scheduler_type: cosine
warmup_ratio: 0.1

#bf16: true
fp16: true
ddp_timeout: 180000000
resume_from_checkpoint: null

#gradient_checkpointing: true
use_unsloth_gc: true

模型微调训练

使用下面的命令进行模型训练:

nohup llamafactory-cli train examples/train_lora/qwen3-0.6b-lora-sft.yaml > train_lora_sft_qwen3-0.6B.log &

使用下面的命令实时监控训练过程:

tail -f train_lora_sft_qwen3-0.6B.log
posted @ 2025-11-25 15:48  Groot_Liu  阅读(0)  评论(0)    收藏  举报