LLaMA-Factory 入门(一):Mac 中验证微调大模型部署效果的全流程

准备工作与环境配置

确保 Mac 系统版本为 macOS 10.13 或更高版本,并安装最新版 Python(推荐 3.8 以上)。通过 Homebrew 安装基础依赖:

brew install cmake git-lfs

克隆 LLaMA-Factory 项目仓库至本地:

git clone https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory

创建 Python 虚拟环境并激活:

python -m venv venv
source venv/bin/activate

安装必要的 Python 依赖包:

pip install -r requirements.txt

模型下载与微调配置

从 Hugging Face 下载基础模型(如 LLaMA-7B),需提前申请权限并配置 Hugging Face token:

huggingface-cli login

修改 train_args.yaml 文件配置微调参数,例如:

model_name_or_path: "meta-llama/Llama-2-7b-hf"
dataset_path: "data/example.json"
output_dir: "output"
per_device_train_batch_size: 4

启动微调任务

运行以下命令开始微调:

python src/train_bash.py --config train_args.yaml

监控显存使用情况,若显存不足可启用梯度累积(gradient_accumulation_steps)或量化训练(load_in_4bit: true)。

验证部署效果

微调完成后,使用以下命令启动本地推理服务:

python src/web_demo.py --model_name_or_path output --port 7860

访问 http://localhost:7860 进入交互界面,输入测试文本观察生成结果。通过对比微调前后的输出差异,验证模型效果提升。

性能优化与调试

若推理速度较慢,可尝试以下优化:

  • 启用 8-bit 量化加载:
    model = AutoModelForCausalLM.from_pretrained("output", load_in_8bit=True)
    

  • 使用 flash_attention_2 加速注意力计算(需安装 flash-attn)。

通过日志分析显存占用和耗时,进一步调整批量大小或模型精度。

Logo

更多推荐