如何微调Phi-3-medium-128k-instruct:使用LLaMa Factory的完整指南

【免费下载链接】Phi-3-medium-128k-instruct 【免费下载链接】Phi-3-medium-128k-instruct 项目地址: https://ai.gitcode.com/hf_mirrors/AI-Research/Phi-3-medium-128k-instruct

Phi-3-medium-128k-instruct是一款由微软开发的140亿参数轻量级开源大模型,具备128K超长上下文处理能力和强大的推理性能。本教程将详细介绍如何使用LLaMa Factory工具对该模型进行高效微调,帮助开发者快速定制符合特定场景需求的AI应用。

准备工作:环境搭建与依赖安装

在开始微调前,需要确保系统已安装必要的依赖库和工具。以下是完整的环境配置步骤:

基础依赖安装

首先安装openMind Hub Client和核心依赖库:

pip install openmind_hub
pip install openmind[pt]  # 包含PyTorch框架
pip install decorator

获取模型文件

通过Git克隆Phi-3-medium-128k-instruct项目仓库:

git clone https://gitcode.com/hf_mirrors/AI-Research/Phi-3-medium-128k-instruct
cd Phi-3-medium-128k-instruct

项目目录中包含模型权重文件(如model-00001-of-00006.safetensors)、配置文件(config.jsontokenizer_config.json)和微调示例脚本(sample_finetune.py)。

LLaMa Factory安装与配置

LLaMa Factory是一个功能强大的大模型微调框架,支持多种微调方法和模型类型。以下是安装和配置步骤:

安装LLaMa Factory

git clone -b v0.9.0 https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
pip install -e .

数据集准备

推荐使用Stanford Alpaca英文数据集进行微调,下载地址:

https://github.com/tatsu-lab/stanford_alpaca/blob/main/alpaca_data.json

下载后将数据集文件保存到本地,并在LLaMa Factory的data/dataset_info.json中添加以下配置:

"alpaca": {
  "file_name": "alpaca_data.json"  // 修改为实际数据集路径
}

微调配置文件设置

在LLaMa Factory目录下创建examples/train_lora/phi3_medium_128k_instruct.yaml配置文件,关键参数说明如下:

### model
model_name_or_path: /path/to/Phi-3-medium-128k-instruct  # 本地模型路径

### method
stage: sft
do_train: true
finetuning_type: lora  # 使用LoRA低秩适配技术
lora_target: all  # 目标模块

### dataset
dataset: alpaca  # 使用的数据集名称
template: phi  # 采用Phi系列模型的对话模板
cutoff_len: 2048  # 文本截断长度

### 训练参数
per_device_train_batch_size: 8
gradient_accumulation_steps: 2
learning_rate: 1.0e-6
num_train_epochs: 3.0
max_steps: 5000
lr_scheduler_type: cosine
bf16: true  # 启用混合精度训练

提示:根据硬件配置调整batch_sizegradient_accumulation_steps,确保GPU内存使用合理。

启动微调训练

使用以下命令启动微调过程:

llamafactory-cli train examples/train_lora/phi3_medium_128k_instruct.yaml

训练过程中,模型会定期保存检查点到output_dir指定的路径(默认为saves/yi_1.5_6b/lora/sft)。可通过logging_stepssave_steps参数调整日志输出和模型保存频率。

进阶技巧:内存优化与性能提升

对于显存有限的设备,可采用以下优化策略:

  1. 梯度检查点:在sample_finetune.py中启用梯度检查点技术:
training_config = {
    "gradient_checkpointing": True,
    "gradient_checkpointing_kwargs": {"use_reentrant": False},
}
  1. LoRA参数调整:减小LoRA秩(r)和目标模块数量:
peft_config = {
    "r": 8,  # 降低秩从16到8
    "lora_alpha": 16,
    "target_modules": ["q_proj", "v_proj"]  # 仅微调注意力模块
}
  1. DeepSpeed零冗余优化:配置DeepSpeed ZeRO-3实现内存优化,详细设置可参考sample_finetune.py中的说明。

模型评估与推理

微调完成后,可使用以下代码进行推理测试:

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_path = "./checkpoint_dir"  # 微调后的模型路径
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    device_map="auto",
    torch_dtype="auto",
    trust_remote_code=True
)
tokenizer = AutoTokenizer.from_pretrained(model_path)

messages = [
    {"role": "user", "content": "如何使用Phi-3模型进行文本生成?"}
]
inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)
outputs = model.generate(inputs, max_new_tokens=512, temperature=0.7)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))

常见问题解决

1. 训练过程中出现CUDA内存不足

  • 降低per_device_train_batch_size
  • 启用梯度检查点(gradient_checkpointing: true
  • 使用更小的LoRA秩(如r=8)

2. 模型加载时报错"trust_remote_code=True"

确保安装最新版本的transformers库:

pip install --upgrade transformers

3. 微调后模型性能未提升

  • 检查数据集质量和数量
  • 调整学习率(推荐范围:1e-5 ~ 1e-6)
  • 增加训练轮次或调整LoRA目标模块

总结

通过LLaMa Factory微调Phi-3-medium-128k-instruct模型,开发者可以在保持128K长上下文优势的同时,快速适配特定领域任务。结合LoRA等参数高效微调技术,即使在消费级GPU上也能完成训练。建议根据实际应用场景调整数据集和超参数,以获得最佳性能。

完整微调示例代码可参考项目中的sample_finetune.pyexamples/finetune.md文件,更多技术细节请查阅Phi-3 Technical Report

【免费下载链接】Phi-3-medium-128k-instruct 【免费下载链接】Phi-3-medium-128k-instruct 项目地址: https://ai.gitcode.com/hf_mirrors/AI-Research/Phi-3-medium-128k-instruct

Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐