目录
引言
Llama - Factory 训练框架简介:
Meta - Llama - 3 - 8B - Instruct 模型概述:
Lora 方法原理及优势:
原理
优势
环境准备:
部署环境测试:
数据准备:
模型准备:
模型配置与训练:
微调效果展示与分析
模型导出:
基于sglang进行服务搭建:
服务测试:
总结:
参考链接:
引言
在自然语言处理领域,大语言模型不断演进,Meta 的 Llama 系列模型备受瞩目。其中 Meta - Llama - 3 - 8B - Instruct 模型具有 80 亿参数,在基础的语言理解和生成方面展现出了一定的能力。然而,为了使其更好地适应特定领域或任务,微调成为了关键步骤。Llama - Factory 作为一个强大的开源低代码大模型训练框架,集成了众多先进的微调方法和优化技术,为我们微调 Meta - Llama - 3 - 8B - Instruct 模型提供了便利。同时,Lora(Low - Rank Adaptation)方法因其在不改变预训练模型原始权重参数的情况下,通过引入小的可训练矩阵来实现模型微调,有效缓解内存和计算资源限制的优势,成为了我们本次微调的首选方法。
Llama - Factory 训练框架简介:
Llama - Factory 是由北航开源的低代码大模型训练框架,它在大模型训练领域有着显著的优势和丰富的功能。参考文章LLAMAFACTORY: Unified Efficient Fine-Tuning of 100+ Language Models(https://arxiv.org/pdf/2403.13372)
支持多种开源模型:该框架支持包括 Yuan2.0、Llama、LLaVA、Mistral、Mixtral - MOE、Qwen、Yi、Gemma、Baichuan、ChatGLM、Phi 等多种开源大语言模型,具有广泛的适用性。
高效微调技术集成:集成了如 Lora、QLora 等高效微调技术,这些技术极大地优化了微调过程。以 Lora 为例,它通过在模型的某些层添加可训练的低秩矩阵,在几乎不增加计算复杂度的前提下,实现了对模型的有效微调。
可视化训练与推理平台:为开发者提供了可视化训练、推理平台,通过一键配置模型训练,能够实现零代码微调 LLM。这一特性使得非专业开发者也能轻松上手,进行模型的定制开发,大大降低了技术门槛。
多种训练模式:支持增量预训练、有监督微调、基于人类反馈的强化学习(RLHF)、直接偏好优化(DPO)等多种训练模式,满足不同场景下的需求。无论是想要对模型进行简单的领域适配,还是进行复杂的强化学习优化,Llama - Factory 都能提供相应的支持。
先进算法与实用技巧集成:集成了 GALORE、BADAM、DORA、LongLora、LlamaPro 等先进算法,以及 FlashAttention - 2、Unsloth、RoPEscaling 等实用技巧,提升训练效率和模型性能。这些算法和技巧从不同角度对训练过程进行优化,如提高计算效率、减少内存占用等。
实验监控与评估:提供 LlamaBoard、TensorBoard、WandB、MLflow 等多种实验监控工具,帮助开发者实时监控训练过程,评估模型性能。通过这些工具,开发者可以直观地看到模型在训练过程中的各项指标变化,如损失值、准确率等,从而及时调整训练策略。
Meta - Llama - 3 - 8B - Instruct 模型概述:
Meta - Llama - 3 - 8B - Instruct 是 Meta 开发的具有 80 亿参数的语言模型,它在经过预训练后,已经具备了对自然语言的基本理解和生成能力。该模型在多种自然语言处理任务上表现出了一定的潜力,如文本生成、问答系统、文本分类等。然而,由于其预训练数据和目标的通用性,在面对特定领域的专业任务时,往往需要进一步的微调来提升性能。例如,在医疗领域,它可能无法准确理解和回答专业的医学问题;在法律领域,对于法律条文的解读和应用也可能不够精准。因此,通过微调使其适应特定领域需求是充分发挥该模型潜力的重要途径。
Lora 方法原理及优势:
原理
Lora 方法的核心思想是在不改变预训练模型权重的基础上,为模型的每一层添加两个可训练的低秩矩阵。具体来说,对于模型中的每一个线性层,假设其输入为\(x\),原始的线性变换为\(y = Wx\),在应用 Lora 方法后,线性变换变为\(y = Wx + \Delta Wx\),其中\(\Delta W = BA\),\(A\)是一个从输入维度映射到低维空间的矩阵,\(B\)是一个从低维空间映射回输出维度的矩阵。通过这种方式,在训练过程中只需要更新\(A\)和\(B\)这两个低秩矩阵的参数,而不需要更新原始模型的权重\(W\),大大减少了需要训练的参数数量。
优势
减少内存占用:由于只需要存储和更新少量的低秩矩阵参数,相比于直接微调整个模型,Lora 方法显著减少了内存的占用。这对于在资源有限的设备上进行模型微调非常关键,使得开发者可以在普通的 GPU 甚至 CPU 上进行大模型的微调操作。
降低计算复杂度:在训练过程中,只对低秩矩阵进行计算和更新,计算量大幅降低。这不仅加快了训练速度,还降低了对计算资源的要求,使得微调过程更加高效。
快速部署:因为微调后的模型只增加了少量的低秩矩阵参数,模型的大小增加有限,这有利于模型的快速部署,特别是在对部署时间和资源有限制的场景中。
环境准备:
1.克隆 Llama - Factory 的 GitHub 仓库:在终端中使用以下命令将 Llama - Factory 的代码克隆到本地。
git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
2.创建虚拟环境:建议使用 Python 的虚拟环境来管理项目依赖,以避免不同项目之间的依赖冲突。可以使用venv或conda来创建虚拟环境。使用conda创建虚拟环境的命令如下:
conda create -n llama-factory python = 3.12
3.激活虚拟环境:
conda activate llama-factory
4.安装必要的依赖库:进入 Llama - Factory 项目目录,安装项目所需的依赖库。通常可以通过项目根目录下的requirements.txt文件来安装。
cd LLaMA-Factory
pip install -e ".[torch,metrics]"
pip install -r requirements.txt
部署环境测试:
llamafactory-cli webui
数据准备:
训练主要用到2个开源数据集,分别是identity、alpaca_en_demo。
数据集保存在data目录下。
#identity.json数据格式,{"instruction": "hi","input": "","output": "Hello! I am {{name}}, an AI assistant developed by {{author}}. How can I assist you today?"},{"instruction": "hello","input": "","output": "Hello! I am {{name}}, an AI assistant developed by {{author}}. How can I assist you today?"},
#alpaca_en_demo数据格式
{"instruction": "Describe a process of making crepes.","input": "","output": "Making crepes is an easy and delicious process! Here are step-by-step instructions on how to make them:\n\n1. Assemble your ingredients. For basic crepes, you'll need: 1 cup all-purpose flour, 2 eggs, 1/2 cup milk, 1/2 cup water, 1/4 teaspoon salt, and 2 tablespoons melted butter.\n\n2. Mix the batter: In a large mixing bowl, whisk together the flour and the eggs. Gradually add the milk and water, stirring constantly to ensure that there are no lumps. Add salt and melted butter, and mix well.\n\n3. Let the batter rest: If you can, let the batter sit for an hour or so. This will help the flour to absorb the liquid and make the crepes more tender.\n\n4. Heat your pan: Preheat a non-stick pan over medium heat. Lightly butter the pan or use cooking spray to prevent the crepes from sticking.\n\n5. Pour the batter: Using a ladle or a measuring cup, pour a small amount of batter (about 1/4 cup) onto the center of the pan. Immediately tilt the pan in a circular motion to spread the batter evenly and thinly over the bottom of the pan.\n\n6. Cook the crepe: Cook the crepe for 1-2 minutes until the bottom is lightly golden. Carefully loosen the edges with a spatula and flip the crepe over to cook the other side for another minute.\n\n7. Remove and repeat: Gently slide the crepe onto a plate, and then repeat the process with the remaining batter. Remember to re-butter the pan between each crepe if necessary.\n\n8. Fill and serve: Fill your cooked crepes with your desired filling, such as fresh fruit, whipped cream, Nutella, or ham and cheese. Roll or fold, and serve immediately. Enjoy!"},{"instruction": "Transform the following sentence using a synonym: The car sped quickly.","input": "","output": "The car accelerated rapidly."},
模型准备:
基于魔塔社区下载模型文件,下载链接魔搭社区
模型配置与训练:
修改examples/train_lora/llama3_lora_sft.yaml配置文件中的模型路径,
启动训练,
llamafactory-cli train examples/train_lora/llama3_lora_sft.yaml
微调效果展示与分析
llamafactory-cli chat examples/inference/llama3_lora_sft.yaml
在微调前,Meta - Llama - 3 - 8B - Instruct 模型生成的文本可能在特定领域的专业性和准确性上有所欠缺。例如,当要求生成关于心脏病治疗方案的文本时,原始模型可能生成一些比较通用但缺乏专业细节的内容。而经过基于医疗领域数据集的微调后,模型能够生成更专业、详细的内容,如具体的药物名称、治疗流程等。
模型导出:
llamafactory-cli export examples/merge_lora/llama3_lora_sft.yaml
基于sglang进行服务搭建:
python3 -m sglang.launch_server --model output/llama3_lora_sft --trust-remote-code --tp 2 --host 0.0.0.0
服务测试:
测试采用openai接口,包括正常请求测试和流式请求测试
import openaiclient = openai.Client(base_url="http://10.1.12.10:30000/v1", api_key="None")#正常请求
response = client.chat.completions.create(model="./output/llama3_lora_sft/",messages=[{"role": "user", "content": "如何预防肺癌?"},],temperature=0,max_tokens=4096,
)
print(response.choices[0].message.content)#流式请求
stream = client.chat.completions.create(model="./output/llama3_lora_sft/",messages=[{"role": "user", "content": "如何预防肺癌?"}],stream=True,
)
for chunk in stream:if chunk.choices[0].delta.content is not None:print(chunk.choices[0].delta.content, end="")
总结:
通过在 Llama - Factory 训练框架下使用 Lora 方法对 Meta - Llama - 3 - 8B - Instruct 模型进行微调,我们能够充分发挥该模型的潜力,使其更好地适应特定领域或任务的需求。Llama - Factory 提供的丰富功能和便捷的操作流程,以及 Lora 方法在减少内存占用和计算复杂度方面的优势,为模型微调提供了高效、可行的解决方案。在实际应用中,开发者可以根据具体需求,灵活运用这一技术,开发出更具针对性和高性能的语言模型。未来,随着技术的不断发展,我们期待能够看到更多基于此类方法的创新应用和更强大的模型出现。
参考链接:
https://github.com/hiyouga/LLaMA-Factory
LLaMA3微调实战:解锁Meta-Llama-3-8B-Instruct的无限潜力-百度开发者中心