首页 > 其他分享 >LLaMA-Factory微调入门个人重制版

LLaMA-Factory微调入门个人重制版

时间:2024-08-30 09:53:48浏览次数:3  
标签:8B predict 制版 Factory -- LLaMA path model root

LLaMA-Factory微调入门个人重制版

说明:

关于

本文是对LLaMA-Factory入门教程 https://zhuanlan.zhihu.com/p/695287607 的个人重制版,记录一下学习过程,省略掉了很多文字部分,建议直接阅读 https://zhuanlan.zhihu.com/p/695287607

准备环境

git clone https://github.com/hiyouga/LLaMA-Factory.git
conda create -n llama_factory python=3.10
conda activate llama_factory
cd LLaMA-Factory
# 使用清华pypi源
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install -e '.[torch,metrics]'

校验环境

import torch
torch.cuda.current_device()
torch.cuda.get_device_name(0)
torch.__version__
# 获取训练相关的参数指导
llamafactory-cli train -h

下载模型

apt update
apt install git-lfs
mkdir models-modelscope
cd models-modelscope

git lfs install
git clone https://www.modelscope.cn/LLM-Research/Meta-Llama-3-8B-Instruct.git

下载模型时也可以先下载小文件,然后手动pull需要的大文件,参考 https://blog.csdn.net/flyingluohaipeng/article/details/130788293

# git lfs install
GIT_LFS_SKIP_SMUDGE=1 git clone https://www.modelscope.cn/LLM-Research/Meta-Llama-3-8B-Instruct.git
cd Meta-Llama-3-8B-Instruct
git lfs pull --include="*.safetensors:

查看文件大小和数量是否正确:

cd Meta-Llama-3-8B-Instruct
ls -al --block-size=M

运行推理DEMO

运行模型的README中的推理DEMO,验证文件的正确性和transformers等依赖库正常可用:

import transformers
import torch

# 切换为你下载的模型文件目录, 这里的demo是Llama-3-8B-Instruct
# 如果是其他模型,比如qwen,chatglm,请使用其对应的官方demo
model_id = "/root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct"

pipeline = transformers.pipeline(
    "text-generation",
    model=model_id,
    model_kwargs={"torch_dtype": torch.bfloat16},
    device="cuda",
)

messages = [
    {"role": "system", "content": "You are a pirate chatbot who always responds in pirate speak!"},
    {"role": "user", "content": "Who are you?"},
]

prompt = pipeline.tokenizer.apply_chat_template(
		messages, 
		tokenize=False, 
		add_generation_prompt=True
)

terminators = [
    pipeline.tokenizer.eos_token_id,
    pipeline.tokenizer.convert_tokens_to_ids("<|eot_id|>")
]

outputs = pipeline(
    prompt,
    max_new_tokens=256,
    eos_token_id=terminators,
    do_sample=True,
    temperature=0.6,
    top_p=0.9,
)
print(outputs[0]["generated_text"][len(prompt):])

输出:

Loading checkpoint shards: 100%|██████████| 4/4 [00:00<00:00, 16.01it/s]
Setting `pad_token_id` to `eos_token_id`:128009 for open-end generation.
Arrrr, shiver me timbers! Me name be Captain Chatbot, the scurviest pirate to ever sail the Seven Seas! Me be a chatbot of great renown, feared and respected by all who cross me digital path. Me specialty be spinnin' yarns, swabbin' decks, and plunderin' knowledge to share with me hearties. So hoist the colors, me matey, and let's set sail fer a swashbucklin' adventure o' conversation!

验证一下LLaMA-Factory的推理部分是否正常(会启动基于gradio开发的ChatBot推理页面):

# 一般不需要,我的环境需要,GRADIO_ROOT_PATH说明见 https://www.gradio.app/guides/environment-variables#7-gradio-root-path
export GRADIO_ROOT_PATH=/proxy/7860/

CUDA_VISIBLE_DEVICES=0 llamafactory-cli webchat \
    --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
    --template llama3

构建自定义数据集(指令微调)

自带的identity.json数据集

cd LLaMA-Factory
# 其中的NAME 和 AUTHOR ,替换成我们需要的内容
sed -i 's/{{name}}/PonyBot/g'  data/identity.json 
sed -i 's/{{author}}/LLaMA Factory/g'  data/identity.json 

商品文案生成数据集

下载并解压数据:

cd data
# 部分wget参数说明见 https://stackoverflow.com/questions/53189651/capture-a-download-link-redirected-by-a-page-wget 和 https://unix.stackexchange.com/questions/453465/wget-how-to-download-a-served-file-keeping-its-name
wget -r -l 1 --span-hosts --accept-regex='.*cloud.tsinghua.edu.cn/.*.exe' -erobots=off -nH --content-disposition -nd https://cloud.tsinghua.edu.cn/f/b3f119a008264b1cabd1/?dl=1
tar -xvf AdvertiseGen.tar.gz

检查数据集格式:

tail -n 3 AdvertiseGen/train.json

输出:

{"content": "类型#裙*版型#宽松*版型#显瘦*颜色#黑色*图案#撞色*裙型#直筒裙*裙款式#拼接", "summary": "采用简洁大体的黑色格调,宽松舒适的裙子内里,配上落肩的袖子拼接,不惧夏日的炎热,穿出清凉舒适。用时尚的英文字母,加上撞色的红白搭配,呈现大气时尚的款式。直筒的裙子轮廓,前短后长的长度裁剪,上身拉长宝宝的身体比例,挑高显瘦。"}
{"content": "类型#上衣*颜色#黑色*颜色#紫色*风格#性感*图案#字母*图案#文字*图案#线条*图案#刺绣*衣样式#卫衣*衣长#短款*衣袖型#落肩袖*衣款式#连帽", "summary": "卫衣的短款长度设计能够适当地露出腰线,打造出纤瘦的身材十分性感。衣身的字母刺绣图案有着小巧的样式,黑色的绣线在紫色的衣身上显得很出挑显眼。落肩袖的设计柔化了肩部的线条衬托得人很温柔可爱。紫色的颜色彰显出优雅的气质也不失年轻活力感。连帽的设计让卫衣更加丰满造型感很足,长长的帽绳直到腰际处,有着延长衣身的效果显得身材<UNK>。"}
{"content": "类型#上衣*颜色#黑白*风格#简约*风格#休闲*图案#条纹*衣样式#风衣*衣样式#外套", "summary": "设计师以条纹作为风衣外套的主要设计元素,以简约点缀了外套,带来大气休闲的视觉效果。因为采用的是黑白的经典色,所以有着颇为出色的耐看性与百搭性,可以帮助我们更好的驾驭日常的穿着,而且不容易让人觉得它过时。"}

修改data/dataset_info.json文件:添加自定义数据集adgen_local,添加后文件尾部看起来如下:

  },
  "adgen_local": {
    "file_name": "AdvertiseGen/train.json",
    "columns": {
      "prompt": "content",
      "response": "summary"
    }
  }
}

其中columns部分将AdvertiseGen/train.json中的"content"映射为"prompt",将"summary"映射为"response"

数据集说明见: https://github.com/hiyouga/LLaMA-Factory/blob/main/data/README_zh.md#指令监督微调数据集

基于LoRA的sft指令微调

设置从魔搭社区下载数据集

# 回到LLaMA-Factory文件夹
cd ..
# 安装依赖
pip install modelscope oss2 addict
# 从魔搭社区下载
export USE_MODELSCOPE_HUB=1

开始sft指令微调

CUDA_VISIBLE_DEVICES=0 llamafactory-cli train \
    --stage sft \
    --do_train \
    --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
    --dataset alpaca_gpt4_zh,identity,adgen_local \
    --dataset_dir ./data \
    --template llama3 \
    --finetuning_type lora \
    --output_dir ./saves/LLaMA3-8B/lora/sft \
    --overwrite_cache \
    --overwrite_output_dir \
    --cutoff_len 1024 \
    --preprocessing_num_workers 16 \
    --per_device_train_batch_size 2 \
    --per_device_eval_batch_size 1 \
    --gradient_accumulation_steps 8 \
    --lr_scheduler_type cosine \
    --logging_steps 50 \
    --warmup_steps 20 \
    --save_steps 100 \
    --eval_steps 50 \
    --evaluation_strategy steps \
    --load_best_model_at_end \
    --learning_rate 5e-5 \
    --num_train_epochs 5.0 \
    --max_samples 1000 \
    --val_size 0.1 \
    --plot_loss \
    --fp16

动态合并LoRA的推理

启动WebUI(Gradio):

# export GRADIO_ROOT_PATH=/proxy/7860/
CUDA_VISIBLE_DEVICES=0 llamafactory-cli webchat \
    --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
    --adapter_name_or_path ./saves/LLaMA3-8B/lora/sft  \
    --template llama3 \
    --finetuning_type lora

使用命令行进行交互式推理:

CUDA_VISIBLE_DEVICES=0 llamafactory-cli chat \
    --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
    --adapter_name_or_path ./saves/LLaMA3-8B/lora/sft  \
    --template llama3 \
    --finetuning_type lora

效果如下:

User: 你是谁?
Assistant: 您好,我是 PonyBot,一个由 LLaMA Factory 开发的人工智能助手。我可以帮助回答问题,提供信息,或者进行其他支持性任务。

User: 类型#裙*版型#宽松*版型#显瘦*颜色#黑色*图案#撞色*裙型#直筒裙*裙款式#拼接
Assistant: 这款裙子采用黑色和暗棕色拼接的撞色设计,很有设计感。宽松的直筒版型,适合任何身材的女人穿着。撞色拼接的裙摆,显得活泼有趣。裙身的撞色拼接,很有设计感。

批量预测和训练效果评估

pip install jieba
pip install rouge-chinese
pip install nltk
CUDA_VISIBLE_DEVICES=0 llamafactory-cli train \
    --stage sft \
    --do_predict \
    --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
    --adapter_name_or_path ./saves/LLaMA3-8B/lora/sft  \
    --eval_dataset alpaca_gpt4_zh,identity,adgen_local \
    --dataset_dir ./data \
    --template llama3 \
    --finetuning_type lora \
    --output_dir ./saves/LLaMA3-8B/lora/predict \
    --overwrite_cache \
    --overwrite_output_dir \
    --cutoff_len 1024 \
    --preprocessing_num_workers 16 \
    --per_device_eval_batch_size 1 \
    --max_samples 20 \
    --predict_with_generate

与训练脚本主要的参数区别如下两个

参数名称 参数说明
do_predict 现在是预测模式
predict_with_generate 现在用于生成文本
max_samples 每个数据集采样多少用于预测对比

运行后输出的尾部:

***** predict metrics *****
  predict_bleu-4                 =    27.9112
  predict_model_preparation_time =     0.0037
  predict_rouge-1                =     48.432
  predict_rouge-2                =    27.0109
  predict_rouge-l                =    41.2608
  predict_runtime                = 0:01:46.62
  predict_samples_per_second     =      0.563
  predict_steps_per_second       =      0.563
08/29/2024 16:06:36 - INFO - llamafactory.train.sft.trainer - Saving prediction results to ./saves/LLaMA3-8B/lora/predict/generated_predictions.jsonl

其中

  • saves/LLaMA3-8B/lora/predict/generated_predictions.jsonl 输出了要预测的数据集的原始label和模型predict的结果
  • saves/LLaMA3-8B/lora/predict/predict_results.json 给出了原始label和模型predict的结果,用自动计算的指标数据

LoRA模型合并导出

如果想把训练的LoRA和原始的大模型进行融合,输出一个完整的模型文件的话,可以使用如下命令。合并后的模型可以自由地像使用原始的模型一样应用到其他下游环节,当然也可以递归地继续用于训练。

CUDA_VISIBLE_DEVICES=0 llamafactory-cli export \
    --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
    --adapter_name_or_path ./saves/LLaMA3-8B/lora/sft  \
    --template llama3 \
    --finetuning_type lora \
    --export_dir megred-model-path \
    --export_size 2 \
    --export_device cpu \
    --export_legacy_format False

查看merge后的文件:

ls -al --block-size=M megred-model-path/
total 15326M
drwxr-xr-x  2 root root    1M Aug 29 16:18 .
drwxr-xr-x 15 root root    1M Aug 29 16:18 ..
-rw-r--r--  1 root root    1M Aug 29 16:18 config.json
-rw-r--r--  1 root root    1M Aug 29 16:18 generation_config.json
-rw-r--r--  1 root root 1883M Aug 29 16:18 model-00001-of-00009.safetensors
-rw-r--r--  1 root root 1809M Aug 29 16:18 model-00002-of-00009.safetensors
-rw-r--r--  1 root root 1889M Aug 29 16:18 model-00003-of-00009.safetensors
-rw-r--r--  1 root root 1857M Aug 29 16:18 model-00004-of-00009.safetensors
-rw-r--r--  1 root root 1889M Aug 29 16:18 model-00005-of-00009.safetensors
-rw-r--r--  1 root root 1857M Aug 29 16:18 model-00006-of-00009.safetensors
-rw-r--r--  1 root root 1889M Aug 29 16:18 model-00007-of-00009.safetensors
-rw-r--r--  1 root root 1249M Aug 29 16:18 model-00008-of-00009.safetensors
-rw-r--r--  1 root root 1003M Aug 29 16:18 model-00009-of-00009.safetensors
-rw-r--r--  1 root root    1M Aug 29 16:18 model.safetensors.index.json
-rw-r--r--  1 root root    1M Aug 29 16:18 special_tokens_map.json
-rw-r--r--  1 root root    9M Aug 29 16:18 tokenizer.json
-rw-r--r--  1 root root    1M Aug 29 16:18 tokenizer_config.json

API Server的启动与调用

使用merge前的LoRA模型推理:

# export FASTAPI_ROOT_PATH=/proxy/8000/
CUDA_VISIBLE_DEVICES=0 API_PORT=8000 llamafactory-cli api \
    --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
    --adapter_name_or_path ./saves/LLaMA3-8B/lora/sft \
    --template llama3 \
    --finetuning_type lora

使用merge后的完整版模型基于VLLM推理:

pip install vllm>=0.4.3
# export FASTAPI_ROOT_PATH=/proxy/8000/
CUDA_VISIBLE_DEVICES=0 API_PORT=8000 llamafactory-cli api \
    --model_name_or_path megred-model-path \
    --template llama3 \
    --infer_backend vllm \
    --vllm_enforce_eager

我的环境(云)需要设置root_path(见FastAPI文档 https://fastapi.tiangolo.com/zh/advanced/behind-a-proxy/ ),故设置了环境变量FASTAPI_ROOT_PATH,详见我在LLaMA-Factory官方仓库上提的Issue(感谢快速修复)

转换为gguf模型文件格式

git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp/gguf-py
pip install --editable .
cd ..
python convert_hf_to_gguf.py /root/workspace/LLaMA-Factory/megred-model-path

输出(最后一行):

INFO:hf-to-gguf:Model successfully exported to /root/workspace/LLaMA-Factory/megred-model-path/Megred-Model-Path-8.0B-F16.gguf

标签:8B,predict,制版,Factory,--,LLaMA,path,model,root
From: https://www.cnblogs.com/shizidushu/p/18388071

相关文章

  • ollama 最快方式部署管理大模型
    github:https://github.com/ollama/ollama模型地址:https://ollama.com/library/llama3.1linux:安装1.下载安装脚本curl-fsSLhttps://ollama.com/install.sh|sh2.修改启动环境变量如果是root用户记得改为rootvim/etc/systemd/system/ollama.service[Unit]Descri......
  • 首次发一篇文章,0元领定制版大鼠标垫!(3步领取,7日到手)
    51CTO博客首发福利来啦!现在,首次发一篇文章,0元领定制版大鼠标垫!一、3步领取,7日到手发布文章——>等待审核(99%通过率)——>填邮寄信息①发布文章戳此直达>>②等待审核(99%通过率)发一篇不水文的原创技术文章必有奖。例如:刷题笔记、代码记录...技术分享。若审核不通过,可加下方小助手微信,......
  • 深入浅出LLamaSharp:打造智能.NET应用,不需GPU也能玩转LLaMA模型
            在如今的.NET社区中,机器学习和人工智能的应用越来越普遍。今天我要给大家推荐一个名叫LLamaSharp的开源项目。这是llama.cpp的C#/.NET绑定,提供了高级的API,使得我们能在本地设备上使用C#/.NET推理LLaMA模型,并且部署它。        LLamaSharp支持在Windo......
  • 英伟达玩转剪枝、蒸馏:把Llama 3.1 8B参数减半,性能同尺寸更强
    前言 小模型崛起了。欢迎关注公众号CV技术指南,专注于计算机视觉的技术总结、最新技术跟踪、经典论文解读、CV招聘信息。本文转载自机器之心仅用于学术分享,若侵权请联系删除CV方向的准研究生们,未来三年如何度过?招聘高光谱图像、语义分割、diffusion等方向论文指导老师上个月......
  • 数字验证:一文弄懂UVM的factory机制
            如果我们用SystemVerilog构建验证平台,构建好了之后,想改变平台中的某个组件,例如将driver改成driver_new,我们需要重新定义一下driver_new,当然也可以直接从driver继承。但是我们还需要在driver对象例化的地方将driverdrv;改成driver_newdrv;,如果需要多个组件的......
  • VMware ESXi 8.0U3 macOS Unlocker & OEM BIOS Dell (戴尔) 定制版
    VMwareESXi8.0U3macOSUnlocker&OEMBIOSDell(戴尔)定制版ESXi8.0U3标准版,Dell(戴尔)、HPE(慧与)、Lenovo(联想)、Inspur(浪潮)、Cisco(思科)、Hitachi(日立)、Fujitsu(富士通)、NEC(日电)、Huawei(华为)、xFusion(超聚变)OEM定制版请访问原文链接:h......
  • Docker下使用llama.cpp部署带Function calling和Json Mode功能的Mistral 7B模型
    Docker下使用llama.cpp部署带Functioncalling和JsonMode功能的Mistral7B模型说明:首次发表日期:2024-08-27参考:https://www.markhneedham.com/blog/2024/06/23/mistral-7b-function-calling-llama-cpp/https://github.com/abetlen/llama-cpp-python?tab=readme-ov-file#fu......
  • Llama3技术文档
    Introduction基础模型开发包含两个阶段:预训练阶段(apre-trainingstage)。以简单的任务如预测下一个字的方式大规模训练。后训练阶段(apost-trainingstage)。调优为来指令跟随(followinstructions),对齐人类偏好(alignwithhumanpreferences),提高特定能力(如编程和推理)我们相信在......
  • 探索 graphrag-local-ollama:项目优势及实战应用
    目录引言一、项目背景与意义二、项目核心特性与优势三、详细的安装与使用步骤1.环境准备2.安装ollama3.下载所需模型4.克隆项目并安装依赖5.数据准备与初始化6.配置与构建索引7.执行查询四、项目的应用场景与未来展望结语引言在当今科技飞速发展的时代,人工......
  • Flink系列-SQL connector扩展以及DataGenTableSourceFactory源码走读
    一、说明    通常我们直接使用Flink的sql进行实时任务开发,经常会遇到扩展新的数据源端或者目标端的场景,或者需要了解connector的一些源码机制,方便开发和定位问题。    如何扩展新增Sqlconnector呢?扩展ApacheFlink的新SQLConnector主要涉及以下几个步骤:......