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

如何系统的去学习大模型LLM ?

大模型时代,火爆出圈的LLM大模型让程序员们开始重新评估自己的本领。 “AI会取代那些行业?”“谁的饭碗又将不保了?”等问题热议不断。

事实上,抢你饭碗的不是AI,而是会利用AI的人。

科大讯飞、阿里、华为等巨头公司发布AI产品后,很多中小企业也陆续进场!超高年薪,挖掘AI大模型人才! 如今大厂老板们,也更倾向于会AI的人,普通程序员,还有应对的机会吗?

与其焦虑……

不如成为「掌握AI工具的技术人」,毕竟AI时代,谁先尝试,谁就能占得先机!

但是LLM相关的内容很多,现在网上的老课程老教材关于LLM又太少。所以现在小白入门就只能靠自学,学习成本和门槛很高。

针对所有自学遇到困难的同学们,我帮大家系统梳理大模型学习脉络,将这份 LLM大模型资料 分享出来:包括LLM大模型书籍、640套大模型行业报告、LLM大模型学习视频、LLM大模型学习路线、开源大模型学习教程等, 😝有需要的小伙伴,可以 扫描下方二维码领取🆓↓↓↓

👉CSDN大礼包🎁:全网最全《LLM大模型入门+进阶学习资源包》免费分享(安全链接,放心点击)👈

一、LLM大模型经典书籍

AI大模型已经成为了当今科技领域的一大热点,那以下这些大模型书籍就是非常不错的学习资源。

在这里插入图片描述

二、640套LLM大模型报告合集

这套包含640份报告的合集,涵盖了大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师,还是对AI大模型感兴趣的爱好者,这套报告合集都将为您提供宝贵的信息和启示。(几乎涵盖所有行业)

在这里插入图片描述

三、LLM大模型系列视频教程

在这里插入图片描述

四、LLM大模型开源教程(LLaLA/Meta/chatglm/chatgpt)

在这里插入图片描述

LLM大模型学习路线

阶段1:AI大模型时代的基础理解

  • 目标:了解AI大模型的基本概念、发展历程和核心原理。

  • 内容

    • L1.1 人工智能简述与大模型起源
    • L1.2 大模型与通用人工智能
    • L1.3 GPT模型的发展历程
    • L1.4 模型工程
    • L1.4.1 知识大模型
    • L1.4.2 生产大模型
    • L1.4.3 模型工程方法论
    • L1.4.4 模型工程实践
    • L1.5 GPT应用案例

阶段2:AI大模型API应用开发工程

  • 目标:掌握AI大模型API的使用和开发,以及相关的编程技能。

  • 内容

    • L2.1 API接口
    • L2.1.1 OpenAI API接口
    • L2.1.2 Python接口接入
    • L2.1.3 BOT工具类框架
    • L2.1.4 代码示例
    • L2.2 Prompt框架
    • L2.3 流水线工程
    • L2.4 总结与展望

阶段3:AI大模型应用架构实践

  • 目标:深入理解AI大模型的应用架构,并能够进行私有化部署。

  • 内容

    • L3.1 Agent模型框架
    • L3.2 MetaGPT
    • L3.3 ChatGLM
    • L3.4 LLAMA
    • L3.5 其他大模型介绍

阶段4:AI大模型私有化部署

  • 目标:掌握多种AI大模型的私有化部署,包括多模态和特定领域模型。

  • 内容

    • L4.1 模型私有化部署概述
    • L4.2 模型私有化部署的关键技术
    • L4.3 模型私有化部署的实施步骤
    • L4.4 模型私有化部署的应用场景

这份 LLM大模型资料 包括LLM大模型书籍、640套大模型行业报告、LLM大模型学习视频、LLM大模型学习路线、开源大模型学习教程等, 😝有需要的小伙伴,可以 扫描下方二维码领取🆓↓↓↓

👉CSDN大礼包🎁:全网最全《LLM大模型入门+进阶学习资源包》免费分享(安全链接,放心点击)👈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值