前言
前面那篇微调入门讲了概念和决策框架。这篇是纯操作——用 LLaMA-Factory 这个工具,不用写多少代码,就能完成 LoRA 微调。
选 LLaMA-Factory 的原因是它把模型加载、数据预处理、训练配置、评估、导出这些步骤全封装好了,支持 Web UI 操作,对新手友好。
一、安装
1 2 3
| git clone https://github.com/hiyouga/LLaMA-Factory.git cd LLaMA-Factory pip install -e ".[torch,metrics]"
|
如果下载慢或者报依赖冲突,创建新的 conda 环境再装:
1 2 3
| conda create -n llama-factory python=3.11 -y conda activate llama-factory pip install -e ".[torch,metrics]"
|
验证:
1
| llamafactory-cli version
|
二、准备数据
数据格式(Alpaca 格式)
在 data/ 目录下创建 my_data.json:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| [ { "instruction": "你是一个运维工程师,请根据用户描述给出 Linux 命令", "input": "查看占用 8080 端口的进程", "output": "sudo lsof -i :8080\n或者\nsudo ss -tlnp | grep 8080" }, { "instruction": "你是一个运维工程师,请根据用户描述给出 Linux 命令", "input": "查看磁盘使用情况", "output": "df -h" }, { "instruction": "你是一个运维工程师,请根据用户描述给出 Linux 命令", "input": "查找 /var/log 下大于 100MB 的文件", "output": "find /var/log -type f -size +100M -exec ls -lh {} \\;" } ]
|
然后在 data/dataset_info.json 中注册:
1 2 3 4 5 6 7 8 9 10
| { "my_linux_data": { "file_name": "my_data.json", "columns": { "prompt": "instruction", "query": "input", "response": "output" } } }
|
数据量建议
- 最少 100 条才能看到效果
- 300-1000 条能获得不错的微调效果
- 1000-3000 条效果稳定
三、开始微调(Web UI 方式)
浏览器打开 http://localhost:7860。
关键配置步骤:
模型选择 → 选你要微调的基座模型,如 Qwen2.5-7B-Instruct
微调方法 → 选 lora,量化等级选 none(显存不够选 4-bit QLoRA)
数据集 → 选择上一步注册的 my_linux_data
超参数设置:
- 学习率:
5e-5(7B 模型的常用值)
- 训练轮数(epochs):
3(先试 3 轮看效果)
- 批大小(batch_size):
4(显存不够就减到 2 或 1)
- 梯度累积(gradient_accumulation):
4(等效 batch = 4×4 = 16)
- 最大长度(max_length):
1024
LoRA 参数:
- rank (r):
8(rank 越大 LoRA 能力越强但也越多参数。8-16 够了)
- alpha:
16(通常是 rank 的 2 倍)
- target:
all(对所有线性层做 LoRA)
点击”开始训练”
四、命令行方式微调(不用 Web UI)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| llamafactory-cli train \ --model_name_or_path Qwen/Qwen2.5-7B-Instruct \ --dataset my_linux_data \ --output_dir ./output/linux-expert \ --stage sft \ --finetuning_type lora \ --lora_rank 8 \ --lora_alpha 16 \ --lora_target all \ --learning_rate 5e-5 \ --num_train_epochs 3 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 4 \ --lr_scheduler_type cosine \ --warmup_ratio 0.1 \ --logging_steps 10 \ --save_steps 200 \ --plot_loss \ --bf16
|
训练完成后,./output/linux-expert 下会有 LoRA 权重文件。
五、测试微调后的模型
微调后不要覆盖原始模型,先加载 LoRA 权重试效果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| from transformers import AutoModelForCausalLM, AutoTokenizer from peft import PeftModel
base_model = "Qwen/Qwen2.5-7B-Instruct" lora_path = "./output/linux-expert"
model = AutoModelForCausalLM.from_pretrained( base_model, device_map="auto", torch_dtype="auto" ) model = PeftModel.from_pretrained(model, lora_path) tokenizer = AutoTokenizer.from_pretrained(base_model)
def test_model(prompt): messages = [ {"role": "system", "content": "你是一个运维工程师,根据用户描述给出 Linux 命令"}, {"role": "user", "content": prompt} ] text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) inputs = tokenizer(text, return_tensors="pt").to(model.device) outputs = model.generate(**inputs, max_new_tokens=256, temperature=0.3) return tokenizer.decode(outputs[0], skip_special_tokens=True)
test_cases = [ "如何查看系统内存使用情况", "找出最近 7 天内修改过的配置文件", "批量杀死所有包含 'python' 的进程", ] for case in test_cases: print(f"Q: {case}") print(f"A: {test_model(case)}") print()
|
六、合并并导出模型
测试满意后,把 LoRA 权重合并进原模型,方便部署:
1 2 3 4 5 6 7 8
| llamafactory-cli export \ --model_name_or_path Qwen/Qwen2.5-7B-Instruct \ --adapter_name_or_path ./output/linux-expert \ --template qwen \ --finetuning_type lora \ --export_dir ./output/linux-expert-merged \ --export_size 2 \ --export_legacy_format false
|
./output/linux-expert-merged 就是一个完整的、支持 HuggingFace 或 vLLM 直接加载的 Safetensors 精度模型。
接入 Ollama:
由于 Ollama 无法直接加载 HuggingFace 的 Safetensors 格式文件夹,我们需要在导出时将其直接转化为 GGUF 格式。
LLaMA-Factory 提供了非常方便的内置 GGUF 导出机制(会自动合并 LoRA 权重并进行量化):
1 2 3 4 5 6 7 8 9 10
| llamafactory-cli export \ --model_name_or_path Qwen/Qwen2.5-7B-Instruct \ --adapter_name_or_path ./output/linux-expert \ --template qwen \ --finetuning_type lora \ --export_dir ./output/linux-expert-gguf \ --export_quantization_bit 4 \ --export_quantization_device cpu \ --export_legacy_format false
|
导出成功后,在 ./output/linux-expert-gguf 文件夹下会生成一个 .gguf 文件。接着我们创建 Modelfile:
1 2 3 4 5 6 7 8
| cat > Modelfile << EOF FROM ./output/linux-expert-gguf/qwen-7b-sft-q4_k_m.gguf EOF
ollama create linux-expert -f Modelfile ollama run linux-expert
|
七、常见问题
训练过程中 loss 不下降:
- 学习率太大或太小(先试 5e-5)
- 数据量太少或数据质量差
- 检查一下 instruction 和 output 是否匹配
显存不够:
- 开启 4-bit 量化(QLoRA)
- 减小 batch_size,增大 gradient_accumulation
- 减小 max_length
- 换更小的基座模型(7B → 1.5B 或 3B)
过拟合(训练 loss 很低但测试效果差):
- 减少 epochs
- 增加数据多样性
- 增大 LoRA dropout(默认 0,可以设 0.05~0.1)
微调后模型原来的能力丢了:
- 数据中加一些通用对话样本(占 5~10%)
- 减少 epochs
- 降低学习率
LLaMA-Factory 是目前入门微调最省力的选择。GUI 点点就能跑起来,不需要手写训练循环。