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
### LLaMA-Factory 使用教程及文档 LLaMA-Factory 是一个用于微调和部署大语言模型(LLM)的开源工具包。它支持多种模型格式,并提供了丰富的功能来简化模型训练、推理和服务化的过程。以下是关于 LLaMA-Factory使用教程及相关内容。 #### 1. 安装 LLaMA-Factory 首先,需要克隆 LLaMA-Factory 的仓库并安装依赖项: ```bash git clone https://github.com/hiyouga/LLaMA-Factory.git cd LLaMA-Factory pip install -e .[metrics] ``` 上述命令会将 LLaMA-Factory 克隆到本地,并安装必要的依赖项[^1]。 #### 2. 创建 Conda 环境 为了确保兼容性,建议创建一个新的 Conda 环境: ```bash conda create -n llama_factory python=3.10 conda activate llama_factory ``` 这一步确保了 Python 版本与 LLaMA-Factory 的要求一致[^1]。 #### 3. 启动 WebUI LLaMA-Factory 提供了一个基于 Web 的用户界面,可以方便地进行模型微调和测试。启动 WebUI 的命令如下: ```bash #!/bin/bash eval "$(/root/miniconda3/bin/conda shell.bash hook)" conda activate llama_factory DISABLE_VERSION_CHECK=1 \ PYTORCH_NVML_BASED_CUDA_CHECK=1 \ CUDA_VISIBLE_DEVICES=3,1,0,2 \ llamafactory-cli webui ``` 此脚本会激活 Conda 环境并设置必要的环境变量以启动 WebUI[^2]。 #### 4. 部署模型为 OpenAI 兼容 API 通过 `vllm` 工具,可以将微调后的模型作为 OpenAI 兼容的 API 对外提供服务。以下是一个示例命令: ```bash VLLM_WORKER_MULTIPROC_METHOD=spawn vllm serve /root/HuggingFaceCache/models--Qwen--Qwen2.5-7B-SFT-Instruct --trust-remote-code --served-model-name gpt-4 --gpu-memory-utilization 0.98 --tensor-parallel-size 4 --port 8000 --api-key sk-123456 --max-model-len 32768 ``` 该命令指定了模型路径、GPU 资源分配以及 API 服务端口等参数[^2]。 #### 5. 官方文档与教程 除了上述内容,用户还可以参考以下资源进一步了解 LLaMA-Factory 的功能: - **GitHub 仓库**: [https://github.com/hiyouga/LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory) 提供了详细的 README 文件和示例代码。 - **官方文档**: 如果存在单独的文档页面,请查阅其提供的教程和 API 参考。 #### 注意事项 在使用 LLaMA-Factory 时,请确保 GPU 驱动和 CUDA 工具链版本符合要求。此外,根据模型大小调整 `gpu-memory-utilization` 和 `tensor-parallel-size` 参数以优化性能[^2]。 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值