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

[复制链接]
发表于 2024-9-27 14:53:09 来自手机 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

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

说明:



  • 初次发表日期:2024-08-30
  • LLaMA-Factory 官方Github仓库: https://github.com/hiyouga/LLaMA-Factory
关于

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

  1. git clone https://github.com/hiyouga/LLaMA-Factory.git
  2. conda create -n llama_factory python=3.10
  3. conda activate llama_factory
  4. cd LLaMA-Factory
  5. # 使用清华pypi源
  6. pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
  7. pip install -e '.[torch,metrics]'
复制代码
校验环境
  1. import torch
  2. torch.cuda.current_device()
  3. torch.cuda.get_device_name(0)
  4. torch.__version__
复制代码
  1. # 获取训练相关的参数指导
  2. llamafactory-cli train -h
复制代码
下载模型

  1. apt update
  2. apt install git-lfs
复制代码
  1. mkdir models-modelscope
  2. cd models-modelscope
  3. git lfs install
  4. git clone https://www.modelscope.cn/LLM-Research/Meta-Llama-3-8B-Instruct.git
复制代码
下载模型时也可以先下载小文件,然后手动pull须要的大文件,参考 https://blog.csdn.net/flyingluohaipeng/article/details/130788293
  1. # git lfs install
  2. GIT_LFS_SKIP_SMUDGE=1 git clone https://www.modelscope.cn/LLM-Research/Meta-Llama-3-8B-Instruct.git
  3. cd Meta-Llama-3-8B-Instruct
  4. git lfs pull --include="*.safetensors:
复制代码
查看文件巨细和数目是否精确:
  1. cd Meta-Llama-3-8B-Instruct
  2. ls -al --block-size=M
复制代码
运行推理DEMO

运行模型的README中的推理DEMO,验证文件的精确性和transformers等依赖库正常可用:
  1. import transformers
  2. import torch
  3. # 切换为你下载的模型文件目录, 这里的demo是Llama-3-8B-Instruct
  4. # 如果是其他模型,比如qwen,chatglm,请使用其对应的官方demo
  5. model_id = "/root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct"
  6. pipeline = transformers.pipeline(
  7.     "text-generation",
  8.     model=model_id,
  9.     model_kwargs={"torch_dtype": torch.bfloat16},
  10.     device="cuda",
  11. )
  12. messages = [
  13.     {"role": "system", "content": "You are a pirate chatbot who always responds in pirate speak!"},
  14.     {"role": "user", "content": "Who are you?"},
  15. ]
  16. prompt = pipeline.tokenizer.apply_chat_template(
  17.                 messages,
  18.                 tokenize=False,
  19.                 add_generation_prompt=True
  20. )
  21. terminators = [
  22.     pipeline.tokenizer.eos_token_id,
  23.     pipeline.tokenizer.convert_tokens_to_ids("<|eot_id|>")
  24. ]
  25. outputs = pipeline(
  26.     prompt,
  27.     max_new_tokens=256,
  28.     eos_token_id=terminators,
  29.     do_sample=True,
  30.     temperature=0.6,
  31.     top_p=0.9,
  32. )
  33. print(outputs[0]["generated_text"][len(prompt):])
复制代码
输出:
  1. Loading checkpoint shards: 100%|██████████| 4/4 [00:00<00:00, 16.01it/s]
  2. Setting `pad_token_id` to `eos_token_id`:128009 for open-end generation.
  3. 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推理页面):
  1. # 一般不需要,我的环境需要,GRADIO_ROOT_PATH说明见 https://www.gradio.app/guides/environment-variables#7-gradio-root-path
  2. export GRADIO_ROOT_PATH=/proxy/7860/
  3. CUDA_VISIBLE_DEVICES=0 llamafactory-cli webchat \
  4.     --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
  5.     --template llama3
复制代码
构建自界说数据集(指令微调)

自带的identity.json数据集

  1. cd LLaMA-Factory
  2. # 其中的NAME 和 AUTHOR ,替换成我们需要的内容
  3. sed -i 's/{{name}}/PonyBot/g'  data/identity.json
  4. sed -i 's/{{author}}/LLaMA Factory/g'  data/identity.json
复制代码
商品文案生成数据集

下载并解压数据:
  1. cd data
  2. # 部分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
  3. 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
  4. tar -xvf AdvertiseGen.tar.gz
复制代码
查抄数据集格式:
  1. tail -n 3 AdvertiseGen/train.json
复制代码
输出:
  1. {"content": "类型#裙*版型#宽松*版型#显瘦*颜色#黑色*图案#撞色*裙型#直筒裙*裙款式#拼接", "summary": "采用简洁大体的黑色格调,宽松舒适的裙子内里,配上落肩的袖子拼接,不惧夏日的炎热,穿出清凉舒适。用时尚的英文字母,加上撞色的红白搭配,呈现大气时尚的款式。直筒的裙子轮廓,前短后长的长度裁剪,上身拉长宝宝的身体比例,挑高显瘦。"}
  2. {"content": "类型#上衣*颜色#黑色*颜色#紫色*风格#性感*图案#字母*图案#文字*图案#线条*图案#刺绣*衣样式#卫衣*衣长#短款*衣袖型#落肩袖*衣款式#连帽", "summary": "卫衣的短款长度设计能够适当地露出腰线,打造出纤瘦的身材十分性感。衣身的字母刺绣图案有着小巧的样式,黑色的绣线在紫色的衣身上显得很出挑显眼。落肩袖的设计柔化了肩部的线条衬托得人很温柔可爱。紫色的颜色彰显出优雅的气质也不失年轻活力感。连帽的设计让卫衣更加丰满造型感很足,长长的帽绳直到腰际处,有着延长衣身的效果显得身材<UNK>。"}
  3. {"content": "类型#上衣*颜色#黑白*风格#简约*风格#休闲*图案#条纹*衣样式#风衣*衣样式#外套", "summary": "设计师以条纹作为风衣外套的主要设计元素,以简约点缀了外套,带来大气休闲的视觉效果。因为采用的是黑白的经典色,所以有着颇为出色的耐看性与百搭性,可以帮助我们更好的驾驭日常的穿着,而且不容易让人觉得它过时。"}
复制代码
修改data/dataset_info.json文件:添加自界说数据集adgen_local,添加后文件尾部看起来如下:
  1.   },
  2.   "adgen_local": {
  3.     "file_name": "AdvertiseGen/train.json",
  4.     "columns": {
  5.       "prompt": "content",
  6.       "response": "summary"
  7.     }
  8.   }
  9. }
复制代码
此中columns部门将AdvertiseGen/train.json中的"content"映射为"prompt",将"summary"映射为"response"
数据集说明见: https://github.com/hiyouga/LLaMA-Factory/blob/main/data/README_zh.md#%E6%8C%87%E4%BB%A4%E7%9B%91%E7%9D%A3%E5%BE%AE%E8%B0%83%E6%95%B0%E6%8D%AE%E9%9B%86
基于LoRA的sft指令微调

设置从魔搭社区下载数据集
  1. # 回到LLaMA-Factory文件夹
  2. cd ..
  3. # 安装依赖
  4. pip install modelscope oss2 addict
  5. # 从魔搭社区下载
  6. export USE_MODELSCOPE_HUB=1
复制代码
开始sft指令微调
  1. CUDA_VISIBLE_DEVICES=0 llamafactory-cli train \
  2.     --stage sft \
  3.     --do_train \
  4.     --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
  5.     --dataset alpaca_gpt4_zh,identity,adgen_local \
  6.     --dataset_dir ./data \
  7.     --template llama3 \
  8.     --finetuning_type lora \
  9.     --output_dir ./saves/LLaMA3-8B/lora/sft \
  10.     --overwrite_cache \
  11.     --overwrite_output_dir \
  12.     --cutoff_len 1024 \
  13.     --preprocessing_num_workers 16 \
  14.     --per_device_train_batch_size 2 \
  15.     --per_device_eval_batch_size 1 \
  16.     --gradient_accumulation_steps 8 \
  17.     --lr_scheduler_type cosine \
  18.     --logging_steps 50 \
  19.     --warmup_steps 20 \
  20.     --save_steps 100 \
  21.     --eval_steps 50 \
  22.     --evaluation_strategy steps \
  23.     --load_best_model_at_end \
  24.     --learning_rate 5e-5 \
  25.     --num_train_epochs 5.0 \
  26.     --max_samples 1000 \
  27.     --val_size 0.1 \
  28.     --plot_loss \
  29.     --fp16
复制代码
动态归并LoRA的推理

启动WebUI(Gradio):
  1. # export GRADIO_ROOT_PATH=/proxy/7860/
  2. CUDA_VISIBLE_DEVICES=0 llamafactory-cli webchat \
  3.     --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
  4.     --adapter_name_or_path ./saves/LLaMA3-8B/lora/sft  \
  5.     --template llama3 \
  6.     --finetuning_type lora
复制代码
使用命令行进行交互式推理:
  1. CUDA_VISIBLE_DEVICES=0 llamafactory-cli chat \
  2.     --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
  3.     --adapter_name_or_path ./saves/LLaMA3-8B/lora/sft  \
  4.     --template llama3 \
  5.     --finetuning_type lora
复制代码
效果如下:
  1. User: 你是谁?
  2. Assistant: 您好,我是 PonyBot,一个由 LLaMA Factory 开发的人工智能助手。我可以帮助回答问题,提供信息,或者进行其他支持性任务。
  3. User: 类型#裙*版型#宽松*版型#显瘦*颜色#黑色*图案#撞色*裙型#直筒裙*裙款式#拼接
  4. Assistant: 这款裙子采用黑色和暗棕色拼接的撞色设计,很有设计感。宽松的直筒版型,适合任何身材的女人穿着。撞色拼接的裙摆,显得活泼有趣。裙身的撞色拼接,很有设计感。
复制代码
批量预测和训练效果评估

  1. pip install jieba
  2. pip install rouge-chinese
  3. pip install nltk
复制代码
  1. CUDA_VISIBLE_DEVICES=0 llamafactory-cli train \
  2.     --stage sft \
  3.     --do_predict \
  4.     --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
  5.     --adapter_name_or_path ./saves/LLaMA3-8B/lora/sft  \
  6.     --eval_dataset alpaca_gpt4_zh,identity,adgen_local \
  7.     --dataset_dir ./data \
  8.     --template llama3 \
  9.     --finetuning_type lora \
  10.     --output_dir ./saves/LLaMA3-8B/lora/predict \
  11.     --overwrite_cache \
  12.     --overwrite_output_dir \
  13.     --cutoff_len 1024 \
  14.     --preprocessing_num_workers 16 \
  15.     --per_device_eval_batch_size 1 \
  16.     --max_samples 20 \
  17.     --predict_with_generate
复制代码
与训练脚本主要的参数区别如下两个
参数名称参数说明do_predict现在是预测模式predict_with_generate现在用于生成文本max_samples每个数据集采样多少用于预测对比 运行后输出的尾部:
  1. ***** predict metrics *****
  2.   predict_bleu-4                 =    27.9112
  3.   predict_model_preparation_time =     0.0037
  4.   predict_rouge-1                =     48.432
  5.   predict_rouge-2                =    27.0109
  6.   predict_rouge-l                =    41.2608
  7.   predict_runtime                = 0:01:46.62
  8.   predict_samples_per_second     =      0.563
  9.   predict_steps_per_second       =      0.563
  10. 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和原始的大模型进行融合,输出一个完备的模型文件的话,可以使用如下命令。归并后的模型可以自由地像使用原始的模型一样应用到其他卑鄙环节,固然也可以递归地继续用于训练。
  1. CUDA_VISIBLE_DEVICES=0 llamafactory-cli export \
  2.     --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
  3.     --adapter_name_or_path ./saves/LLaMA3-8B/lora/sft  \
  4.     --template llama3 \
  5.     --finetuning_type lora \
  6.     --export_dir megred-model-path \
  7.     --export_size 2 \
  8.     --export_device cpu \
  9.     --export_legacy_format False
复制代码
查看merge后的文件:
  1. ls -al --block-size=M megred-model-path/
复制代码
  1. total 15326M
  2. drwxr-xr-x  2 root root    1M Aug 29 16:18 .
  3. drwxr-xr-x 15 root root    1M Aug 29 16:18 ..
  4. -rw-r--r--  1 root root    1M Aug 29 16:18 config.json
  5. -rw-r--r--  1 root root    1M Aug 29 16:18 generation_config.json
  6. -rw-r--r--  1 root root 1883M Aug 29 16:18 model-00001-of-00009.safetensors
  7. -rw-r--r--  1 root root 1809M Aug 29 16:18 model-00002-of-00009.safetensors
  8. -rw-r--r--  1 root root 1889M Aug 29 16:18 model-00003-of-00009.safetensors
  9. -rw-r--r--  1 root root 1857M Aug 29 16:18 model-00004-of-00009.safetensors
  10. -rw-r--r--  1 root root 1889M Aug 29 16:18 model-00005-of-00009.safetensors
  11. -rw-r--r--  1 root root 1857M Aug 29 16:18 model-00006-of-00009.safetensors
  12. -rw-r--r--  1 root root 1889M Aug 29 16:18 model-00007-of-00009.safetensors
  13. -rw-r--r--  1 root root 1249M Aug 29 16:18 model-00008-of-00009.safetensors
  14. -rw-r--r--  1 root root 1003M Aug 29 16:18 model-00009-of-00009.safetensors
  15. -rw-r--r--  1 root root    1M Aug 29 16:18 model.safetensors.index.json
  16. -rw-r--r--  1 root root    1M Aug 29 16:18 special_tokens_map.json
  17. -rw-r--r--  1 root root    9M Aug 29 16:18 tokenizer.json
  18. -rw-r--r--  1 root root    1M Aug 29 16:18 tokenizer_config.json
复制代码
API Server的启动与调用

使用merge前的LoRA模型推理:
  1. # export FASTAPI_ROOT_PATH=/proxy/8000/
  2. CUDA_VISIBLE_DEVICES=0 API_PORT=8000 llamafactory-cli api \
  3.     --model_name_or_path /root/workspace/models-modelscope/Meta-Llama-3-8B-Instruct \
  4.     --adapter_name_or_path ./saves/LLaMA3-8B/lora/sft \
  5.     --template llama3 \
  6.     --finetuning_type lora
复制代码
使用merge后的完备版模型基于VLLM推理:
  1. pip install vllm>=0.4.3
复制代码
  1. # export FASTAPI_ROOT_PATH=/proxy/8000/
  2. CUDA_VISIBLE_DEVICES=0 API_PORT=8000 llamafactory-cli api \
  3.     --model_name_or_path megred-model-path \
  4.     --template llama3 \
  5.     --infer_backend vllm \
  6.     --vllm_enforce_eager
复制代码
  我的环境(云)须要设置root_path(见FastAPI文档 https://fastapi.tiangolo.com/zh/advanced/behind-a-proxy/ ),故设置了环境变量FASTAPI_ROOT_PATH,详见我在LLaMA-Factory官方仓库上提的Issue(感谢快速修复)
  转换为gguf模型文件格式

  1. git clone https://github.com/ggerganov/llama.cpp.git
  2. cd llama.cpp/gguf-py
  3. pip install --editable .
复制代码
  1. cd ..
  2. python convert_hf_to_gguf.py /root/workspace/LLaMA-Factory/megred-model-path
复制代码
输出(最后一行):
  1. INFO:hf-to-gguf:Model successfully exported to /root/workspace/LLaMA-Factory/megred-model-path/Megred-Model-Path-8.0B-F16.gguf
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表