llama-factory使用教程

目标:借助llama-factory仓库使用lora微调自己的大模型
llama-factory:https://github.com/hiyouga/LLaMA-Factory/tree/main

下载llama-factory仓库

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

若后续不想继续追踪GitHub文件变化,可通过删除.git文件实现:

rm -rf .git

安装llama-factory环境

llama-factory官方推荐:
在这里插入图片描述
此处坑比较多,如果python、cuda、torch、transformers和vllm不匹配,会运行出错
个人尝试有效环境搭配:

python=3.10
cuda=12.1
torch=2.3.0-cu121
transformers=4.43.4
vllm=0.4.3
  1. 使用conda创建环境:
conda create -n tor230 python=3.10
  1. 下载torch相关离线包,然后本地安装 torch离线包下载
pip install torch-2.3.0+cu121-cp310-cp310-linux_x86_64.whl
pip install torchaudio-2.3.0+cu121-cp310-cp310-linux_x86_64.whl
pip install torchvision-0.18.0+cu121-cp310-cp310-linux_x86_64.whl
  1. pip安装相关第三方库
pip install transformers==4.43.4
pip install vllm==0.4.3
pip install datasets
pip install accelerate
pip install peft
  1. 安装llama-factory
cd /data/yangjun/LLM/LLaMA-Factory
pip install -e ".[torch,metrics]"

登录huggingface

  1. 安装huggingface:
pip install --upgrade huggingface_hub
  1. 如果能使用代理,直接登录huggingface账号:
huggingface-cli login

在输入token时直接输入自己huggingface账户的token
“setting”-“Access Tokens”
在这里插入图片描述
如果token为空,则新建;不为空,则点击刷新
3. 如果不能使用代理,则直接login会出错,那么需要使用国内huggingface镜像
设置环境变量,在~/.bashrc中写入命令:

export HF_ENDPOINT=https://hf-mirror.com

然后source ~/.bashrc
再重复步骤2登录账户

使用自定义数据lora微调llama

了解我们需要自定义微调时需要修改的llama-factory文件夹设置:

LLaMA-Factory/
│
├── data/
│   ├── dataset_info.json
│   └── [your_dataset].json
│
├── examples/
│   └── train_lora/
│   │   └── llama3_lora_sft.yaml
│	├── train_qlora/
│   │   └── llama3_lora_sft.yaml
│	├── train_full/
│   │   └── llama3_lora_sft.yaml
│	└── inference/
│       └── llama3_lora_sft.yaml
└── saves/

其中data文件夹下面的 [your_dataset].json 是自定义微调任务中训练集,dataset_info.json用于定义数据集名称
examples文件夹下面的train_lora、train_qlora和train_full表示不同的微调方式,相应文件夹下面存在微调任务的配置文件;inference表示使用训练好的模型来进行推理
saves文件夹需要自己新建,用于保存微调后的模型

具体介绍微调大模型的使用方法

微调

以事实核查(英文名:fact-checking,根据claim和evidence判断claim的真实性,其标签包括:supports(证据支持声明),refutes(证据反驳声明)和not enough information(证据对于判断声明真实性信息不足))任务为例,使用lora微调LLaMA-3-8B

  1. 构造训练数据,保存在 ./data/fact_checking.json
    数据格式:
{
    "instruction": "Analyze whether the evidence supports the claim, refutes the statement, or is not enough information to verify the claim's truthfulness. Provide your final conclusion.",
    "input": "Claim: 新疆棉花生产已实现高度机械化,不需要强迫劳动。 Evidence: 新疆棉花生产早已经实现高度机械化,即使在忙碌的采摘季节,也不需要大量的“采棉工”。 【事实三】新疆棉花:生产早已高度机械化,不需要大量的“采棉工”据新疆农业部门发布的2020年数据显示,新疆棉花机械采摘率已达69.83%,其中北疆95%的棉花是通过机械采摘的。 近年来,一方面是机器生产减少劳力需求,另一方面随着内地农村劳动力收入不断提高,新疆采棉人数不断减少,这完全是劳动力市场行为所致,与“政府强迫本地劳动力”毫无联系。 针对新疆教培中心等同于“集中营”,中方对维族人实施“种族灭绝”、“强迫劳动”,对维族妇女强迫绝育,将维族儿童与父母分离的提问,杨代办指出,中方已多次阐明,新疆根本不存在所谓“种族灭绝”“强迫劳动”“大规模绝育”。 同时,从过去到现在,新疆根本不存在、也根本不需要强制性动员采棉。 ",
    "output": "supports"
},
  1. 在dataset_info.json文件中新增一项
"fact_checking":
{
  "file_name":"fact_checking.json"
}

其中fact_checking.json名称和1中构造数据集名称对应
3. 在./examples/train_lora文件夹下修改llama3_lora_sft_fact_checking.yaml:

model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct
finetuning_type: lora
dataset: fact_checking
output_dir: saves/llama3-8b-lora-sft-fact-checking/

其中,dataset名称和dataset_info.json中key值对应
4. 微调

CUDA_VISIBLE_DEVICES=0,1 llamafactory-cli train examples/train_lora/llama3_lora_sft_fact_checking.yaml

推理

调用API进行推理
  1. 在./examples/inference文件夹下修改llama3_lora_sft.yaml构造推理api:
model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct
adapter_name_or_path: saves/llama3-8b-lora-sft
template: llama3
infer_backend: vllm
vllm_enforce_eager: true
finetuning_type: lora

其中adapter_name_or_path后面改成3中output_dir对应名称
然后部署api:

CUDA_VISIBLE_DEVICES=0 API_PORT=8000 llamafactory-cli api examples/inference/llama3_lora_sft.yaml
  1. 调用api,使用微调后的大模型进行推理:
from openai import OpenAI
from tqdm import tqdm 
openai_api_key = "EMPTY"
openai_api_base = "http://localhost:8000/v1"
client = OpenAI(
    api_key=openai_api_key,
    base_url=openai_api_base
)
predictions = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    messages=[
        {"role": "user", "content": input},
    ],
    temperature=0.95,
)
直接进行推理

调用API进行推理时部署API的过程可能无法使用多卡,下面直接进行推理,这种方式可以采用多卡的方式,且推理速度要比调用API的方式快。直接推理的过程和微调过程类似。

  1. 构造推理数据,构造方式和构造微调数据集类似。构造推理数据,保存在 ./data/inference_fact_checking.json
    数据格式:
{
    "instruction": "Analyze whether the evidence supports the claim, refutes the statement, or is not enough information to verify the claim's truthfulness. Provide your final conclusion.",
    "input": "Claim: 新疆棉花生产已实现高度机械化,不需要强迫劳动。 Evidence: 新疆棉花生产早已经实现高度机械化,即使在忙碌的采摘季节,也不需要大量的“采棉工”。 【事实三】新疆棉花:生产早已高度机械化,不需要大量的“采棉工”据新疆农业部门发布的2020年数据显示,新疆棉花机械采摘率已达69.83%,其中北疆95%的棉花是通过机械采摘的。 近年来,一方面是机器生产减少劳力需求,另一方面随着内地农村劳动力收入不断提高,新疆采棉人数不断减少,这完全是劳动力市场行为所致,与“政府强迫本地劳动力”毫无联系。 针对新疆教培中心等同于“集中营”,中方对维族人实施“种族灭绝”、“强迫劳动”,对维族妇女强迫绝育,将维族儿童与父母分离的提问,杨代办指出,中方已多次阐明,新疆根本不存在所谓“种族灭绝”“强迫劳动”“大规模绝育”。 同时,从过去到现在,新疆根本不存在、也根本不需要强制性动员采棉。 ",
    "output": ""
},
  1. 在dataset_info.json文件中新增一项
"inference_fact_checking":
{
  "file_name":"inference_fact_checking.json"
}

其中inference_fact_checking.json名称和1中构造数据集名称对应

  1. 在./examples/train_lora文件夹下新增llama3_lora_sft_inference_fact_checking.yaml:
### model
model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct
predict_with_generate: true
adapter_name_or_path: saves/llama3-8b-lora-sft-fact-checking/

### method
stage: sft
do_predict: true
finetuning_type: lora
lora_target: all

### dataset
eval_dataset: inference_question_with_context_answer
template: llama3
cutoff_len: 1024
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 16

### output
output_dir: saves/llama3-8b-lora-sft-fact-checking/predict
logging_steps: 10
save_steps: 500
plot_loss: true
overwrite_output_dir: true

其中,eval_dataset名称和dataset_info.json中key值对应(对应推理数据集)。adapter_name_or_path对应微调后保存的模型路径。output_dir表示推理结果保存路径
4. 推理

CUDA_VISIBLE_DEVICES=0,1 llamafactory-cli train examples/train_lora/llama3_lora_sft_fact_checking.yaml
### 启动 Docker Image 并配置 `/dev/shm` 大小 为了确保能够顺利运行 DeepSpeed 的多 GPU 训练命令,需要适当增加 Docker 容器中的 `/dev/shm` 内存大小。这可以通过指定 `--shm-size` 参数来实现[^1]。 ```bash docker run --shm-size=8g ... ``` ### 准备环境 首先拉取并设置 LLaMA-Factory 项目: ```bash git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git cd LLaMA-Factory pip install -e ".[torch,metrics]" ``` 确保 PyTorch 已经根据 CUDA 版本正确安装。如果默认安装的是 CPU 支持版本,则需手动下载适合的 GPU 加速版 PyTorch[^4]。 ### 使用 DeepSpeed 微调模型 假设已经准备好数据集以及预处理脚本,在执行微调之前应该确认所有依赖项都已妥善安装,并且硬件资源充足。接着可以编写或修改现有的 Python 脚本来利用 DeepSpeed 库进行分布式训练。这里给出一个简单的例子说明如何在代码中集成 DeepSpeed: ```python import deepspeed from transformers import TrainerCallback class DeepspeedCallback(TrainerCallback): def __init__(self, ds_config_path="ds_config.json"): self.ds_config_path = ds_config_path def on_init_end(self, args, state, control, **kwargs): model_engine, optimizer, _, _ = deepspeed.initialize( model=self.model, config_params=self.ds_config_path) # 配置文件路径指向自定义的 DeepSpeed JSON 文件 trainer.add_callback(DeepspeedCallback()) ``` 其中 `ds_config.json` 是一个包含优化选项和其他必要参数的 JSON 文件,具体可以根据实际需求定制化调整。 对于更详细的指导和更多高级特性,请参阅官方文档或其他社区贡献者分享的经验贴。 ### 启动 Web UI 界面辅助调试 除了命令行操作外,还可以考虑使用可视化界面帮助理解和管理整个流程。通过如下指令启动 Web UI 可视化工具[^3]: ```bash llamafactory-cli webui ``` 这样可以在浏览器端查看到当前状态以及其他有用的信息,有助于更好地控制实验进程。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值