LLM | 正在尝试使用 LLaMA-Factory
正在看的博客:知乎 | LLaMA-Factory QuickStart
好像是作者写的博客:单卡 3 小时训练专属大模型 Agent:基于 LLaMA Factory 实战
其他博客:
- LLaMA-Factory 全参 SFT 训练 Qwen-2.5-7B-Instruct 踩坑记
- LLaMA-Factory微调Qwen2.5-VL记录
- 基于 LLaMA-Factory 的大模型微调技巧与实践
- 自建数据集,利用LLama-Factory微调大模型
如何从 HuggingFace 上下载模型:
- 感觉很全的参考博客:知乎 | 如何快速下载 huggingface 模型 —— 全方法总结
简单记录配置 LLaMA-Factory 的流程:
1 安装
git clone https://github.com/hiyouga/LLaMA-Factory.git
conda create -n <env_name> python=3.11
conda activate <env_name>
cd LLaMA-Factory
pip install -e '.[torch,metrics]'
2 下载一个大模型,并测试大模型是否正常
下载一个大模型:
export HF_ENDPOINT=https://hf-mirror.com # 换成国内源
export HF_HUB_ENABLE_HF_TRANSFER=0 # 好像是提升下载速度的工具,但开了之后卡死了,所以不敢开了
huggingface-cli download deepseek-ai/DeepSeek-R1-Distill-Qwen-7B \
--local-dir ~/<model_dir>/DeepSeek-R1-Distill-Qwen-7B \ # 换成自己要存 model 的目录
--local-dir-use-symlinks False \
--resume-download
测试下载的模型是否正常:运行 CUDA_VISIBLE_DEVICES=0 python test.py
# test.py 的内容
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
model_path = "<model_dir>/DeepSeek-R1-Distill-Qwen-7B"
# 加载
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_path,
trust_remote_code=True,
torch_dtype=torch.float16,
device_map="auto"
)
# 准备测试问题
question = "你好,请介绍一下你自己。"
print(f"\n问题: {question}")
print("正在生成回答...")
inputs = tokenizer(question, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=200,
temperature=0.7, # 控制随机性(0-1之间)
do_sample=True, # 启用采样
top_p=0.9, # 核采样参数
pad_token_id=tokenizer.eos_token_id # 设置pad_token
)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(f"\n回答: {response}")
# 清理显存
if torch.cuda.is_available():
torch.cuda.empty_cache()
3 LoRA SFT 微调
对各种训练 LLM 的数据形式的介绍:GitHub · Llama-Factory | data/README_zh.md
直接魔改了 identity 数据集;造好数据集后,跑了这个命令,好像跑的很快,不到两分钟就跑完了()
能训到效果,但是给模型训 repeat 了()
CUDA_VISIBLE_DEVICES=0 llamafactory-cli train \
--stage sft \
--do_train \
--model_name_or_path <model_dir>/DeepSeek-R1-Distill-Qwen-7B \
--dataset identity_moonout \
--dataset_dir ./data \
--template deepseek \
--finetuning_type lora \
--output_dir ./saves/DS-Qwen-7B/lora/sft \
--lora_target all \
--overwrite_cache \
--overwrite_output_dir \
--cutoff_len 1024 \
--preprocessing_num_workers 16 \
--per_device_train_batch_size 2 \
--per_device_eval_batch_size 1 \
--gradient_accumulation_steps 8 \
--lr_scheduler_type cosine \
--logging_steps 10 \
--warmup_steps 20 \
--save_steps 100 \
--eval_steps 50 \
--eval_strategy steps \
--load_best_model_at_end \
--learning_rate 5e-5 \
--num_train_epochs 20.0 \
--max_samples 2000 \
--val_size 0.1 \
--plot_loss \
--fp16
一个测试脚本:
CUDA_VISIBLE_DEVICES=0 llamafactory-cli chat \
--model_name_or_path <model_dir>/DeepSeek-R1-Distill-Qwen-7B \
--template deepseek \
--adapter_name_or_path ./saves/DS-Qwen-7B/lora/sft \
--finetuning_type lora

浙公网安备 33010602011771号