当前位置:   article > 正文

LLMs之Llama3:基于Colab平台(免费T4-GPU)利用LLaMA-Factory的GUI界面(底层采用unsloth优化框架【加速训练5~30倍+减少50%的内存占用】)对llama-3-_llamafactory-cli

llamafactory-cli

LLMs之Llama3:基于Colab平台(免费T4-GPU)利用LLaMA-Factory的GUI界面(底层采用unsloth优化框架【加速训练5~30倍+减少50%的内存占用】)对llama-3-8b-Instruct-bnb-4bit模型采用alpaca数据集实现CLI方式/GUI傻瓜可视化方式进行LoRA指令微调→模型推理测试→CLI方式合并权重

目录

基于colab平台(免费T4-GPU)利用LLaMA-Factory的GUI界面(底层采用unsloth优化框架【加速训练5倍~30+减少50%的内存占用】)对llama-3-8b-Instruct-bnb-4bit模型采用alpaca数据集实现CLI方式/GUI傻瓜可视化方式进行LoRA指令微调→模型推理测试→CLI方式合并权重

# 1、安装依赖

# 1.1、克隆 LLaMA-Factory 仓库并安装必要的 Python 包,包括 unsloth、xformers 和 bitsandbytes。

# 1.2、检查 GPU 环境,确保可以使用 Colab 的 Tesla T4 GPU。

# 2、更新身份数据集:

# 3、模型微调

# T1、通过 LLaMA Board 微调模型:

# T2、通过命令行微调模型:It takes ~30min for training.

# 4、模型推理

# 5、合并 LoRA 适配器并可选地上传模型:

实现代码


基于colab平台(免费T4-GPU)利用LLaMA-Factory的GUI界面(底层采用unsloth优化框架【加速训练5倍~30+减少50%的内存占用】)对llama-3-8b-Instruct-bnb-4bit模型采用alpaca数据集实现CLI方式/GUI傻瓜可视化方式进行LoRA指令微调→模型推理测试→CLI方式合并权重

# 1、安装依赖

# 1.1、克隆 LLaMA-Factory 仓库并安装必要的 Python 包,包括 unsloth、xformers 和 bitsandbytes。

# 1.2、检查 GPU 环境,确保可以使用 Colab 的 Tesla T4 GPU。

# 2、更新身份数据集:

# 读取并修改 identity.json 文件,替换其中的占位符为 “Llama-3” 和 “LLaMA Factory”。

# 这一步骤是为了个性化训练数据,确保模型能够生成与特定身份相关的回复。

# 3、模型微调

# T1、通过 LLaMA Board 微调模型:

# 使用 llamafactory-cli 命令行工具启动一个 Web UI 界面,可能用于监控和调整微调过程。

# T2、通过命令行微调模型:It takes ~30min for training.

# 定义微调参数,包括使用的模型、数据集、模板、微调类型(此处使用 LoRA 适配器)、输出目录、批处理大小、学习率调度器、日志步骤等。

# 使用 llamafactory-cli 命令行工具开始微调过程。

# 这一步使用的技术包括 LoRA 适配器(用于节省内存)、4位量化、LoRA+ 算法以及浮点16混合精度训练。

# 4、模型推理

# 推断微调后的模型:用于测试和验证微调后的模型性能。

# 设置模型参数,加载微调时使用的 LoRA 适配器,并初始化一个 ChatModel 实例。

# 通过 CLI 应用程序与模型交互,输入查询并接收模型的生成文本。

f

# 5、合并 LoRA 适配器并可选地上传模型:

# 定义参数以合并 LoRA 适配器到原始模型,并指定输出目录。

# 使用 llamafactory-cli 命令行工具执行导出操作。

# 注意,由于 Colab 免费版本内存限制,无法在此环境中合并 8B 的模型。

实现代码

源码地址https://colab.research.google.com/drive/1eRTPn37ltBbYsISy9Aw2NuI2Aq5CQrD9?usp=sharing#scrollTo=kTESHaFvbNTr

  1. '''
  2. Finetune Llama-3 with LLaMA Factory
  3. Please use a free Tesla T4 Colab GPU to run this!
  4. 4月22日
  5. 源码地址:https://colab.research.google.com/drive/1eRTPn37ltBbYsISy9Aw2NuI2Aq5CQrD9?usp=sharing#scrollTo=kTESHaFvbNTr
  6. '''
  7. # 1、安装依赖
  8. # 1.1、克隆 LLaMA-Factory 仓库并安装必要的 Python 包,包括 unsloth、xformers 和 bitsandbytes。
  9. %cd /content/
  10. %rm -rf LLaMA-Factory
  11. !git clone https://github.com/hiyouga/LLaMA-Factory.git
  12. %cd LLaMA-Factory
  13. %ls
  14. !pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
  15. !pip install --no-deps xformers==0.0.25
  16. !pip install .[bitsandbytes]
  17. # 1.2、检查 GPU 环境,确保可以使用 Colab 的 Tesla T4 GPU。
  18. import torch
  19. try:
  20. assert torch.cuda.is_available() is True
  21. except AssertionError:
  22. print("Please set up a GPU before using LLaMA Factory: https://medium.com/mlearning-ai/training-yolov4-on-google-colab-316f8fff99c6")
  23. # 2、更新身份数据集:
  24. # 读取并修改 identity.json 文件,替换其中的占位符为 “Llama-3” 和 “LLaMA Factory”。
  25. # 这一步骤是为了个性化训练数据,确保模型能够生成与特定身份相关的回复。
  26. import json
  27. NAME = "Llama-3"
  28. AUTHOR = "LLaMA Factory"
  29. with open("data/identity.json", "r", encoding="utf-8") as f:
  30. dataset = json.load(f)
  31. for sample in dataset:
  32. sample["output"] = sample["output"].replace("{{"+ "name" + "}}", NAME).replace("{{"+ "author" + "}}", AUTHOR)
  33. with open("data/identity.json", "w", encoding="utf-8") as f:
  34. json.dump(dataset, f, indent=2, ensure_ascii=False)
  35. # 3、模型微调
  36. # T1、通过 LLaMA Board 微调模型:
  37. # 使用 llamafactory-cli 命令行工具启动一个 Web UI 界面,可能用于监控和调整微调过程。
  38. %cd /content/LLaMA-Factory/
  39. !GRADIO_SHARE=1 llamafactory-cli webui
  40. # T2、通过命令行微调模型:It takes ~30min for training.
  41. # 定义微调参数,包括使用的模型、数据集、模板、微调类型(此处使用 LoRA 适配器)、输出目录、批处理大小、学习率调度器、日志步骤等。
  42. # 使用 llamafactory-cli 命令行工具开始微调过程。
  43. # 这一步使用的技术包括 LoRA 适配器(用于节省内存)、4位量化、LoRA+ 算法以及浮点16混合精度训练。
  44. import json
  45. args = dict(
  46. stage="sft", # do supervised fine-tuning
  47. do_train=True,
  48. model_name_or_path="unsloth/llama-3-8b-Instruct-bnb-4bit", # use bnb-4bit-quantized Llama-3-8B-Instruct model
  49. dataset="identity,alpaca_gpt4_en", # use alpaca and identity datasets
  50. template="llama3", # use llama3 prompt template
  51. finetuning_type="lora", # use LoRA adapters to save memory
  52. lora_target="all", # attach LoRA adapters to all linear layers
  53. output_dir="llama3_lora", # the path to save LoRA adapters
  54. per_device_train_batch_size=2, # the batch size
  55. gradient_accumulation_steps=4, # the gradient accumulation steps
  56. lr_scheduler_type="cosine", # use cosine learning rate scheduler
  57. logging_steps=10, # log every 10 steps
  58. warmup_ratio=0.1, # use warmup scheduler
  59. save_steps=1000, # save checkpoint every 1000 steps
  60. learning_rate=5e-5, # the learning rate
  61. num_train_epochs=3.0, # the epochs of training
  62. max_samples=500, # use 500 examples in each dataset
  63. max_grad_norm=1.0, # clip gradient norm to 1.0
  64. quantization_bit=4, # use 4-bit QLoRA
  65. loraplus_lr_ratio=16.0, # use LoRA+ algorithm with lambda=16.0
  66. use_unsloth=True, # use UnslothAI's LoRA optimization for 2x faster training
  67. fp16=True, # use float16 mixed precision training
  68. )
  69. json.dump(args, open("train_llama3.json", "w", encoding="utf-8"), indent=2)
  70. %cd /content/LLaMA-Factory/
  71. !llamafactory-cli train train_llama3.json
  72. # 4、模型推理
  73. # 推断微调后的模型:用于测试和验证微调后的模型性能。
  74. # 设置模型参数,加载微调时使用的 LoRA 适配器,并初始化一个 ChatModel 实例。
  75. # 通过 CLI 应用程序与模型交互,输入查询并接收模型的生成文本。
  76. from llmtuner.chat import ChatModel
  77. from llmtuner.extras.misc import torch_gc
  78. %cd /content/LLaMA-Factory/
  79. args = dict(
  80. model_name_or_path="unsloth/llama-3-8b-Instruct-bnb-4bit", # use bnb-4bit-quantized Llama-3-8B-Instruct model
  81. adapter_name_or_path="llama3_lora", # load the saved LoRA adapters
  82. template="llama3", # same to the one in training
  83. finetuning_type="lora", # same to the one in training
  84. quantization_bit=4, # load 4-bit quantized model
  85. use_unsloth=True, # use UnslothAI's LoRA optimization for 2x faster generation
  86. )
  87. chat_model = ChatModel(args)
  88. messages = []
  89. print("Welcome to the CLI application, use `clear` to remove the history, use `exit` to exit the application.")
  90. while True:
  91. query = input("\nUser: ")
  92. if query.strip() == "exit":
  93. break
  94. if query.strip() == "clear":
  95. messages = []
  96. torch_gc()
  97. print("History has been removed.")
  98. continue
  99. messages.append({"role": "user", "content": query})
  100. print("Assistant: ", end="", flush=True)
  101. response = ""
  102. for new_text in chat_model.stream_chat(messages):
  103. print(new_text, end="", flush=True)
  104. response += new_text
  105. print()
  106. messages.append({"role": "assistant", "content": response})
  107. torch_gc()
  108. # 5、合并 LoRA 适配器并可选地上传模型:
  109. # 定义参数以合并 LoRA 适配器到原始模型,并指定输出目录。
  110. # 使用 llamafactory-cli 命令行工具执行导出操作。
  111. # 注意,由于 Colab 免费版本内存限制,无法在此环境中合并 8B 的模型。
  112. # NOTE: the Colab free version has merely 12GB RAM, where merging LoRA of a 8B model needs at least 18GB RAM, thus you cannot perform it in the free version.
  113. # !huggingface-cli login
  114. import json
  115. args = dict(
  116. model_name_or_path="meta-llama/Meta-Llama-3-8B-Instruct", # use official non-quantized Llama-3-8B-Instruct model
  117. adapter_name_or_path="llama3_lora", # load the saved LoRA adapters
  118. template="llama3", # same to the one in training
  119. finetuning_type="lora", # same to the one in training
  120. export_dir="llama3_lora_merged", # the path to save the merged model
  121. export_size=2, # the file shard size (in GB) of the merged model
  122. export_device="cpu", # the device used in export, can be chosen from `cpu` and `cuda`
  123. #export_hub_model_id="your_id/your_model", # the Hugging Face hub ID to upload model
  124. )
  125. json.dump(args, open("merge_llama3.json", "w", encoding="utf-8"), indent=2)
  126. %cd /content/LLaMA-Factory/
  127. !llamafactory-cli export merge_llama3.json

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/874392
推荐阅读
相关标签
  

闽ICP备14008679号