2. 单卡全参数微调LLaMA-7B
任务目标
本案例使用单张GPU(建议显存≥24GB)对LLaMA-7B进行全参数微调(Full Fine-tuning),目标是让模型在自定义的短文本情感二分类任务上学会输出positive或negative标签。全参数微调意味着更新模型全部权重,而非仅更新适配器层。
环境与依赖
- Python 3.10+,PyTorch 2.1+,CUDA 11.8+
- 安装 LLaMA-Factory:
git clone https://github.com/hiyouga/LLaMA-Factory.git && cd LLaMA-Factory && pip install -e . - 模型权重:HuggingFace格式的LLaMA-7B(如
huggyllama/llama-7b),需提前下载或使用HF镜像
数据准备
构建一个极简的情感分类训练集(JSON格式),每条数据包含指令、输入和输出。训练时模型将学习根据文本输出对应标签。
// train.json
[
{"instruction": "判断情感倾向", "input": "这部电影太精彩了,值得二刷", "output": "positive"},
{"instruction": "判断情感倾向", "input": "服务态度很差,不会再来了", "output": "negative"},
{"instruction": "判断情感倾向", "input": "产品质量一般,性价比不高", "output": "negative"},
{"instruction": "判断情感倾向", "input": "快递很快,包装也很完好", "output": "positive"},
{"instruction": "判断情感倾向", "input": "客服回复及时,问题解决了", "output": "positive"},
{"instruction": "判断情感倾向", "input": "商品与描述不符,很失望", "output": "negative"}
]
完整微调配置与启动命令
LLaMA-Factory使用YAML配置文件驱动训练。以下配置启用全参数微调,批大小和梯度累积已按单卡24GB显存调低。
# llama7b_full.yaml
model_name_or_path: huggyllama/llama-7b
dataset: train.json
dataset_dir: ./data
template: llama2
finetuning_type: full
output_dir: ./output/llama7b-full
per_device_train_batch_size: 1
gradient_accumulation_steps: 8
learning_rate: 2e-5
num_train_epochs: 3
lr_scheduler_type: cosine
warmup_ratio: 0.03
logging_steps: 1
save_steps: 100
fp16: true
将train.json放入./data目录后,执行以下命令启动训练:
cd LLaMA-Factory
CUDA_VISIBLE_DEVICES=0 llamafactory-cli train llama7b_full.yaml
验证方法
训练完成后,使用LLaMA-Factory提供的推理脚本加载微调后的模型,输入测试文本观察输出:
CUDA_VISIBLE_DEVICES=0 llamafactory-cli chat \
--model_name_or_path ./output/llama7b-full \
--template llama2 \
--finetuning_type full
在交互界面输入判断情感倾向:这个手机电池续航很给力,模型应输出positive;输入判断情感倾向:屏幕用两天就碎了,质量太差,模型应输出negative。由于训练数据极少,此案例仅验证全参数微调流程能跑通且模型能学会简单映射,不追求泛化精度。若显存不足,可降低gradient_accumulation_steps至4并开启gradient_checkpointing: true。
常见问题
- CUDA OOM:确认使用单卡且显存≥24GB;若仍不足,将
per_device_train_batch_size保持为1并开启gradient_checkpointing。 - 数据集格式报错:LLaMA-Factory要求数据集文件位于
dataset_dir指定的目录中,且JSON为合法数组格式。 - 模型下载慢:设置环境变量
HF_ENDPOINT=https://hf-mirror.com加速下载。