第 1 步:安装环境
git clone https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
# 推荐使用 conda
conda create -n llama-factory python=3.10
conda activate llama-factory
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
pip install -r requirements.txt
pip install -e ".[torch,metrics]"
⚠️ 注意:推荐使用 CUDA 环境,GPU 显存建议 ≥24GB(如 3090/4090)
第 2 步:准备数据
支持多种格式,最常用的是 Alpaca 格式 JSON 文件:
[{"instruction":"写一首关于春天的诗","input":"","output":"春风拂面花自开,柳绿桃红映山川..."},{"instruction":"解释什么是机器学习","input":"","output":"机器学习是让计算机从数据中自动学习规律的技术..."}]
📌 存为 my_data.json,放在 data/ 目录下。
第 3 步:启动训练 - 多 GPU(以 LoRA 微调为例)
参考 examples/accelerate 下面的文件,准备自己的 yaml 文件。
compute_environment: LOCAL_MACHINE
debug: false
distributed_type: MULTI_GPU
downcast_bf16: 'no'
gpu_ids: 0,1,2,3
machine_rank: 0
main_training_function: main
mixed_precision: fp16
num_machines: 1
num_processes: 4
rdzv_backend: static
same_network: true
tpu_env: []
tpu_use_cluster: false
tpu_use_sudo: false
use_cpu: false
main_process_port: 29503
启用多 GPU 训练:
#!/bin/bash
CUDA_VISIBLE_DEVICES=4,5,6,7 accelerate launch --config_file config.yaml ../src/train.py \\
--stage sft \\
--do_train True \\
--template qwen3 \\
--finetuning_type lora \\
--model_name_or_path ../Qwen/Qwen3-0.6B \\
--dataset_dir ./vehicle_control_dataset \\
--dataset my_data \\
--output_dir ./saves \\
--overwrite_cache \\
--overwrite_output_dir \\
--cutoff_len 1024 \\
--per_device_train_batch_size 1 \\
--per_device_eval_batch_size 1 \\
--gradient_accumulation_steps 8 \\
--lr_scheduler_type cosine \\
--max_grad_norm 1.0 \\
--logging_steps 10 \\
--save_steps 200 \\
--warmup_steps 0 \\
--learning_rate 5e-5 \\
--num_train_epochs 3.0 \\
--max_samples 100000 \\
--fp16 True \\
--lora_rank 8 \\
--lora_dropout 0.1 \\
--lora_target all \\
--plot_loss True
