HuggingFace peft LoRA 微调 LLaMA

1. 安装必要库

复制代码
pip install transformers peft accelerate

2. 加载 LLaMA 模型和分词器

Hugging Face Transformers 加载预训练的 LLaMA 模型和分词器。

python 复制代码
from transformers import AutoModelForCausalLM, AutoTokenizer

# 加载 LLaMA 模型和分词器
model_name = "meta-llama/Llama-2-7b-hf"  # 替换为适合的模型
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_8bit=True)

# 设置 pad_token 为 eos_token(如果模型没有 pad_token)
tokenizer.pad_token = tokenizer.eos_token
model.resize_token_embeddings(len(tokenizer))  # 调整词汇表大小

3. 配置 LoRA 微调

使用 PEFT 配置 LoRA 参数。

python 复制代码
from peft import get_peft_model, LoraConfig, TaskType

# 定义 LoRA 配置
lora_config = LoraConfig(
    task_type=TaskType.CAUSAL_LM,  # 因果语言模型任务
    inference_mode=False,
    r=8,  # LoRA 的秩
    lora_alpha=16,
    lora_dropout=0.05
)

# 将 LoRA 应用于模型
model = get_peft_model(model, lora_config)

# 检查模型被正确标记为 trainable
print(model)

4. 定义数据集加载器

使用自定义数据集加载器和 Hugging Face 提供的 DataCollator 进行批量处理。

数据集预处理流程及其代码如下链接:训练数据格式为<input,output>,为什么微调大模型时,模型所需的输入数据input_ids有时仅包含了input,而有时包含了input和output呢?-CSDN博客

python 复制代码
from torch.utils.data import DataLoader
from transformers import DataCollatorForSeq2Seq

# 自定义数据集(之前定义的 FineTuneDataset)
dataset = FineTuneDataset(data_path="./train.jsonl", tokenizer=tokenizer, max_length=1024)

# 定义数据批处理器
data_collator = DataCollatorForSeq2Seq(tokenizer, padding=True)

5. 配置 TrainingArguments

设置训练超参数,包括学习率、批次大小、保存频率等。

python 复制代码
from transformers import TrainingArguments

training_args = TrainingArguments(
    output_dir="./llama_lora_finetuned",   # 输出模型路径
    evaluation_strategy="steps",          # 每隔多少步进行验证
    save_strategy="steps",                # 保存检查点的策略
    logging_dir="./logs",                 # 日志文件路径
    per_device_train_batch_size=8,        # 每个设备的训练批次大小
    gradient_accumulation_steps=4,        # 梯度累积
    learning_rate=2e-4,                   # 学习率
    num_train_epochs=3,                   # 训练轮数
    save_steps=500,                       # 每隔多少步保存模型
    logging_steps=100,                    # 日志记录频率
    fp16=True,                            # 使用混合精度训练
    push_to_hub=False                     # 如果需要保存到 Hugging Face Hub
)

6. 定义模型和 Trainer

python 复制代码
from transformers import Trainer

# 定义 Trainer
trainer = Trainer(
    model=model,                          # 微调的模型
    args=training_args,                   # 训练参数
    train_dataset=dataset,                # 训练数据集
    data_collator=data_collator,          # 数据批处理器
)

7. 启动训练

python 复制代码
trainer.train()
trainer.save_model("./llama_lora_finetuned")
tokenizer.save_pretrained("./llama_lora_finetuned")
相关推荐
忧郁的橙子.2 天前
07-大模型微调-LLama Factor微调Qwen -- 局部微调/训练医疗问答模型
llama·llama factor·微调qwen
南宫乘风3 天前
LLaMA-Factory 给 Qwen1.5 做 LoRA 微调 实战
人工智能·深度学习·llama
华农DrLai3 天前
什么是自动Prompt优化?为什么需要算法来寻找最佳提示词?
人工智能·算法·llm·nlp·prompt·llama
jjinl4 天前
1.1 llama.cpp 编译
llama
serve the people4 天前
macbook m4 LLaMA-Factory入门级微调
llama
WiSirius5 天前
LLM:基于 AgentScope + Streamlit 的 AI Agent脑暴室
人工智能·深度学习·自然语言处理·大模型·llama
掘金安东尼5 天前
llama.cpp、Ollama、LM Studio:背后是谁在做?为什么会出现?要什么机器才能跑?
llama
海天一色y5 天前
LLaMA-Factory PPO 训练实战:从 SFT 到 RLHF 完整指南
llama
接着奏乐接着舞。5 天前
5分钟本地跑起大模型
人工智能·llama
liuze4086 天前
Ollama安装
llama