LLM 研究方向(一): LLM Prompts--p-tuning、LoRA

目录

1. prompt-tuning background

2. Prompt Tuning 模型介绍

2.1 2021 prefix-tuning 

2.2 2021 P-tuning v1

2.3 2021 Parameter-efficient prompt tuning (PET)

2.4 2022 P-tuning v2 

2.5 2019 Adapter 

​2.6 2021 LoRA (Low-Rank Adaptation) 

2.7 2024 DoRA (Weight-Decoupled Low-Rank Adaptation)

3. LoRA Implementation

3.1  LoRA 复现 01: MiniLoRA

3.1.1 core codes:torch.nn.utils.parametrize.register_parameterization 参数化应用函数

3.2 LoRA 复现 02: LoRA from Scratch on MNIST 

3.2.1 core codes: Lightning 深度学习框架 

3.3 LoRA 复现 03: Torch tutorial with torchtune

3.3.1 core codes:  torchtune package 介绍

3.4 LoRA 复现 04: peft implementation

3.4.1 core codes: AutoModelForSeq2SeqLM 介绍

3.4.2 code codes: peft package 介绍

3.5 *LoRA 05: Explanation

Reference: 


1. prompt-tuning background

problem: 之前的fune-tuning/model-tuning是对大模型进行下游任务re-training,即对whole模型参数进行微调!但由于LLM参数量太大,fine-tuning需要大量的数据、算力去更新学习参数,不够实用

solution:prompt-tuning (p-tuning),是一种通过提示词(prompt tokens)优化生成式预训练模型(e.g. GPT)的技术旨在通过调整prompts而不是整个模型参数来提高模型在特定任务上的表现,达到节省计算开销和资源消耗、保持甚至提升model performance的目的

按照时间顺序,prompt-tuning演进过程分别是:prefix-tuning、p-tuning v1、parameter-efficient prompt tuning、p-tuning v2。

2. Prompt Tuning 模型介绍

2.1 2021 prefix-tuning 

prefix-tuning, paper: Optimizing Continuous Prompts for Generation, 就是在input tokens前面加上几个与任务相关task-specific的tokens,并用MLP_{\theta}单独训练生成embeddings

Note:tokens不拼接!原有的input tokens依旧用transformer生成embeddings,并且保持transformer参数不变。The prefix tokens' embeddings \vee _i \in P_{idx}, hi are drawn from a trainable matrix MLP~P_\theta. Then remaining tokens' embeddings are computed by the Transformer.

  • 优点:实现简单、高效训练、任务一致性。
  • 缺点:适用性有限,prefix-tuning在一些特定任务中效果不如p-tuning,e.g. 上下文限制,由于prefix embeddings始终位于序列前端,可能无法充分利用输入序列的上下文信息。

2.2 2021 P-tuning v1

p-tuning v1, paper: GPT Understands, Too. 它通过在输入层提示模板固定位置插入可训练的提示词向量trainable prompt tokens embeddings,来提升模型性能。

problem: Previous prompts方法是离散discrete向量空间,主要是从词库V中选词vi作为提示词prompt来出入提示模板的第i个位置,并用prompt generator来生成提示词向量prompt embeddings。这种固定的提示词叫作hard prompt,只能用来微调整个模型的参数 pre-trained model parameters

solution: p-tuning v1是连续continuous向量空间,主要是通过prompt encoder生成trainable parameterized prompt embeddings来代替词库词vi插入输入层,这种generated trainable prompts称为soft prompt

  • 初始化 initialize prompts: <T1> <T2> The movie was fantastic <T3> <T4>. -> 训练优化 -> 推理 inference,这时不BP
  • 优点:少量参数、提高性能、通用性强。
  • 缺点:训练复杂;依赖提示词位置。

2.3 2021 Parameter-efficient prompt tuning (PET)

Parameter-efficient prompt tuning, paper: The power of scale for parameter-efficient prompt tuning, 可以在输入序列的任意位置插入trianable prompt embeddings

2.4 2022 P-tuning v2 

p-tuning v2, paper: Prompt tuning can be comparable to fine-tuning universally across scale and tasks,  多层提示prompt,在每一层加上prefix prompt embeddings。 

problem: 在模型参数量小于10B的训练中,prompt training效果要低于fine-tuning。

solution:p-tuning v2在每一层都加上了layer prefix prompt embeddings,不同任务可以共享相同的网络参数,支持多任务学习。 

  • 优点:可以更好地捕捉和利用上下文信息,进一步提高模型性能、更好泛化、灵活性强。
  • 缺点:实现复杂;计算开销增加。

2.5 2019 Adapter 

paper: Parameter-Efficient transfer learning for NLP.

2.6 2021 LoRA (Low-Rank Adaptation) 

paper: Low-Rank Adaptation of Large Language Models.

W_{LoRA} = W_{orig} + \Delta W = W_{orig} + B*A 

LoRA保持pre-trained model参数冻结,只在原始矩阵中添加一个\Delta W参数,其参数比原始矩阵少。 

problem: 如果我们构造一个与Worig具有相同维度nxm的新\Delta W矩阵来对模型进行微调,模型performance没有提升!还会将参数加倍!

solution:所以设计鬼才提出了低秩概念r,通过基于低秩r的低维矩阵乘法来构造\Delta W = B_{n\times r}A_{r\times m}, r << n和r << m,B和A相乘会产生一个与\Delta W具有相同维度的矩阵,但由更少的参数构成。因为我们希望训练开始时增量为零,让微调像原始模型一样开始。因此,B通常被初始化为零矩阵,而A被初始化为随机值(即正态分布)。

For example,input dim=1024,那origin W参数量=1024*1024\approx100万,而低秩参数量=1024*4+4*1024 \approx8k。

优点:

  • 效率高,使用更少的参数。 
  • 提高泛化性能 《-- 通过限制模型复杂性,防止过拟合。
  • 可以无缝集成到现有的神经网络中。

2.7 2024 DoRA (Weight-Decoupled Low-Rank Adaptation)

核心:每个权重矩阵W通过多个低秩矩阵Ai和Bi的乘积进行近似,可以表示为:W \approx \sum_{i=1}^k A_i B_i

3. LoRA Implementation

LoRA实现公式:W_{LoRA} = W_{orig} + \frac{\alpha}{r} \Delta W

my github link: GitHub - yuyongsheng1990/LLM_Prompts

3.1  LoRA 复现 01: MiniLoRA

简单、通俗、易懂、powerful

reference:minLoRA/demo.ipynb at main · cccntu/minLoRA · GitHub

3.1.1 core codes:torch.nn.utils.parametrize.register_parameterization 参数化应用函数
from functools import partial  # 用于固定某些函数的参数,从而创建一个新的函数。这个新函数会记住被固定的参数,并在调用时使用这些固定参数。
'''
simple example: torch.nn.utils.parametrize.register_parametrizationoutput: 原始参数(weight或bias)会被替换为一个通过指定参数模块生成的参数。Linear((weight): ParametrizationList((0): MyParametrization())(bias): Parameter containing: [torch.FloatTensor of size 5])
'''
# -----------------single lora parameters---------------
linear = nn.Linear(5, 5)
print(linear)
class LowRankParametrization(nn.Module):def __init__(self, original_weight, rank=4):super().__init__()self.rank = rankself.U = nn.Parameter(torch.randn(original_weight.size(0), rank))self.V = nn.Parameter(torch.randn(rank, original_weight.size(1)))def forward(self, x):return self.U @ self.V# 注册低秩参数化
'''torch.nn.utils.parametrize.register_parametrization函数用于在模型的参数上注册新的参数化方法。这个功能允许你在现有参数layer.weight上应用一些变换LoRAParametrization,特别适用于LoRA
'''
parametrize.register_parametrization(linear, 'weight', LowRankParametrization(linear.weight))
# ----------------multiple lora parameters-------------------
# 可以顺序应用多个参数化方法,继续加就行 <--对应DoRA
# 定义第二个参数化方法
class MultiplyByTwoParametrization(nn.Module):def __init__(self, original_weight, rank=4):super().__init__()self.rank = rankself.U = nn.Parameter(torch.randn(original_weight.size(0), rank))self.V = nn.Parameter(torch.randn(rank, original_weight.size(1)))def forward(self, x):return self.U @ self.V
parametrize.register_parametrization(linear, 'weight', MultiplyByTwoParametrization(linear.weight, rank=3))# 打印线性层,查看参数化后的结果
print(linear)
'''
output:Linear(in_features=5, out_features=5, bias=True)  # 原始linear层-------------------------------------------------ParametrizedLinear(                          # 替换后的参数化线性层para linearin_features=5, out_features=5, bias=True   # 这表示layer原始参数original weight(parametrizations): ModuleDict(            # parametrizations表示应用参数化方法,新模型参数会存储在ModuleDict中,ModuleDict是一个module容器,它像一个dict一样工作。(weight): ParametrizationList(           # 这表示weight原始参数现在被替换/应用了ParametrizationList中一个或多个参数化方法.(0): LowRankParametrization()          # (0)表示ParametrizationList的第一个参数化方法。# (1): MultiplyByTwoParametrization()    # 顺序应用:当ParametrizationList存储多个参数化方法时,所有方法会按顺序应用到weight参数上。)                                        ))
'''

3.2 LoRA 复现 02: LoRA from Scratch on MNIST 

reference: lora_from_scratch/lora_on_mnist.ipynb at main · sunildkumar/lora_from_scratch · GitHub

3.2.1 core codes: Lightning 深度学习框架 
import lightning as L  # lightning是一个高层次的深度学习框架,建立在pytorch之上,用于简化和加速模型的开发和训练过程。
from lightning.pytorch.loggers import CSVLogger  # 用于将训练日志记录到csv文件中,便于之后的分析和可视化。
from lightning.pytorch.callbacks import LearningRateFinder  # 通过在training过程中调整学习率lr来找到最优的学习率,以提升模型性能
from lightning.pytorch.callbacks.early_stopping import EarlyStopping  # 用于在validation loss不再改善时提前停止,防止模型过拟合。from pytorch_lightning import Callback # 用于实现自定义的回调函数,在training过程中的特定时间点执行特定的操作,比如记录日志、保存model、调整lr。

3.3 LoRA 复现 03: Torch tutorial with torchtune

reference: Finetuning Llama2 with LoRA — TorchTune documentation

3.3.1 core codes:  torchtune package 介绍
from torchtune.models.llama2 import llama2_7b, lora_llama2_7b  # torchtune是一个torch库,用于轻松创作、微调和试验LLM。
'''torchtune, https://pytorch.org/torchtune/stable/index.html- Llama3 in torchtune- Finetuning with LoRA in torchtune- Understanding QLoRA in TorchTune- End-to-End Workflow with torchtune
'''

3.4 LoRA 复现 04: peft implementation

reference:  LoRA-Implementation/prepare_data.py at main · hahuyhoang411/LoRA-Implementation · GitHub

3.4.1 core codes: AutoModelForSeq2SeqLM 介绍
'''from transformers import AutoModelForSeq2SeqLM, AutoTokenizer# 指定模型名称或路径model_name = "t5-small"# 加载预训练模型和分词器model = AutoModelForSeq2SeqLM.from_pretrained(model_name)tokenizer = AutoTokenizer.from_pretrained(model_name)# 输入文本input_text = "Translate English to French: How are you?"# 编码文本--成模型可接受的输入格式inputs = tokenizer(input_text, return_tensors="pt")# 生成输出outputs = model.generate(**inputs)# 解码输出文本output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)print(f"Input: {input_text}")print(f"Output: {output_text}")
'''
3.4.2 code codes: peft package 介绍
'''
peft (Parameter-Efficient Fine-Tuning) package introduction:Fine-tuning large pretrained models is often prohibitively costly due to their scale. PEFT methods enable efficient adaptation of large pretrained models to various downstream applications by only fine-tuning a 
small number of (extra) model parameters instead of all the model's parameters. This significantly decreases the computational and storage costs. Recent state-of-the-art PEFT techniques achieve performance comparable to fully fine-tuned models.PEFT is integrated with Transformers for easy model training and inference, 
peft简化了LLM-finetuning 模型配置和加载功能,特别是使用LoRA等技术。- LoraConfig,用于配置LoRA参数。- TaskType,用于定义任务类型, e.g. task_type = TaskType.TEXT_GENERATION- get_peft_config,用于获取peft配置- get_peft_model,用于获取pretrained peft模型。
''''''
----------------peft翻译模型---------------------
# 翻译模型bigscience/mt0-large: English -> French
'''
# prepare a model for training with a PEFT method such as LoRA by wrapping the base model and PEFT configuration with get_peft_model.
# For the bigscience/mt0-large model, you are only training 0.19% of the parameters!
from transformers import AutoModelForSeq2SeqLM  # 用于加载和处理pre-trained seq2seq模型,用于处理nlp任务
from peft import get_peft_config, get_peft_model, LoraConfig, TaskType# 加载预训练模型和分词器 
model_name = 'bigscience/mt0-large'
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)# 定义lora配置
lora_config = LoraConfig(task_type = TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1
)# 获取peft model
peft_model = get_peft_model(model, peft_config)
print(peft_model.print_trainable_parameters())  # 输出peft mode可训练参数# 准备输入数据
input_text = "Translate English to French: How are you?"
inputs = tokenizer(input_text, return_tensors="pt")# 使用 PEFT 模型生成输出
outputs = peft_model.generate(**inputs)
output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)  # 解码
print(outputs)
print(output_text)'''
------------peft因果推理模型----------------------
因果推理模型 ybelkada/opt-350m-lora; gpt2
'''
from peft import AutoPeftModelForCausalLM  # 用于加载和配置因果语言模型Causal LM,并进行高效微调参数
from transformers import AutoTokenizer
import torchdevice = 'cuda' if torch.cuda.is_available() else 'cpu'
model = AutoPeftModelForCausalLM.from_pretrained('ybelkada/opt-350m-lora').to(device) 
tokenizer = AutoTokenizer.from_pretrained('facebook/opt-350m')model.eval()
inputs = tokenizer('Preheat the oven to 350 degrees and place the cookie dough', return_tensors='pt')outputs = model.generate(input_ids=inputs['input_ids'].to(device), max_new_tokens=50)  # 生成输出
outputs_text = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]  # tokenizer解码输出文本
print(outputs)
print(outputs_text)

3.5 *LoRA 05: Explanation

***选看:太难、太复杂,不做实现喽

reference: 使用Pytorch从零开始构建LoRA_torch lora 使用 nn-CSDN博客

3.5 *LoRA 06: huanhuan chat

***选看:太难、太复杂,不做实现喽

reference: https://github.com/datawhalechina/self-llm/blob/master/GLM-4/05-GLM-4-9B-chat%20Lora%20%E5%BE%AE%E8%B0%83.ipynb

Reference: 

[1] He J, Zhou C, Ma X, Berg-Kirkpatrick T, Neubig G. Towards a unified view of parameter-efficient transfer learning. arXiv preprint arXiv:2110.04366. 2021 Oct 8.

[2] https://mltalks.medium.com/%E8%AF%A6%E8%A7%A3%E5%A4%A7%E6%A8%A1%E5%9E%8B%E5%BE%AE%E8%B0%83%E6%96%B9%E6%B3%95prompt-tuning-%E5%86%85%E9%99%84%E5%AE%9E%E7%8E%B0%E4%BB%A3%E7%A0%81-7e4276927729

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/44210.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

详解[USACO07OPEN] Cheapest Palindrome G(洛谷PP2890)(区间DP经典题)

题目 思路 考虑区间DP。 设dp[i][j]为从i到j这段区间被修正为回文串的最小花费 c[cc][1]为添加字符cc的花费 c[cc][2]为删去字符cc的花费 s为题目给出的字符串。 用[i 1,j]区间转移&#xff1a;这种转移相当于在[i1,j]区间的左边加入一个字符&#xff0c;让[i,j]变为回文的方…

云仓适合什么商家?

1、电商平台和网店&#xff1a; 对于拥有大量在线订单但没有自建仓储和物流能力的小型和中型电商企业&#xff0c;云仓可以在成本和效率上提供显著优势&#xff0c;帮助快速处理订单并缩短配送时间。 —————————————————————————————————— …

【独家揭秘】视频号矩阵系统火爆上线,一键式多平台管理,你的内容营销神器!

在信息爆炸的时代&#xff0c;内容创作者们面临着前所未有的挑战与机遇。如何让自己的内容在众多平台中脱颖而出&#xff0c;快速传播并吸引大量观众&#xff0c;成为了每个创作者关注的焦点。近日&#xff0c;一款名为“迅狐视频号矩阵系统”的神器震撼来袭&#xff0c;它以其…

UV胶,它是否有毒?如同那些隐藏在黑暗中的危险之物?

UV胶&#xff0c;它是否有毒&#xff1f;如同那些隐藏在黑暗中的危险之物&#xff1f; 关于uv胶的毒性问题&#xff0c;或许我们可以这样深入探讨。UV胶&#xff0c;如同一位戴着神秘面纱的访客&#xff0c;在我们的生活中悄然出现&#xff0c;却带着诸多疑问。那么&#xff0…

二维码生成需知:名片二维码尺寸多少合适?电子名片二维码制作方法?

随着数字化时代的到来&#xff0c;二维码在各个领域的应用越来越广泛&#xff0c;名片作为商业交流的重要工具之一&#xff0c;也开始逐渐融入二维码的元素。通过在名片上添加二维码&#xff0c;我们可以轻松实现信息的快速传递和分享。然而&#xff0c;名片二维码的尺寸选择成…

Monorepo仓库管理策略之 Lerna

这里写目录标题 前言&#xff1a;一、简介二、新建项目使用安装生成结构 三、复用现有项目执行命令查看包 四、配置package相互引用导入现有的包 五、发布包确定项目版本发布项目添加项目到到git发布包到NPM包发布出错解决方案 五、实例代码 前言&#xff1a; 将大型代码仓库分…

文心一言的流式接口数据进行处理 增加属性

需求&#xff1a;需要对文心一言的流式接口数据进行处理 增加属性 return ResponseEntity.ok().header("Access-Control-Allow-Origin", "*").contentType(org.springframework.http.MediaType.TEXT_EVENT_STREAM).cacheControl(org.springframework.http…

python调用串口收发数据

1、确认串口信息 2、安装pyserial库 打开终端或命令行&#xff0c;敲入这行命令&#xff1a;pip install pyserial 3、python编程 import serial def main(): #创建串口对象 ser serial.Serial(COM4, 9600, timeout1) if not ser.isOpen(): print("串…

飞睿智能6公里WiFi图传接收模块,低延迟、抗干扰、高速稳定传输数据,无人机、农田远距离WiFi模块

在科技日新月异的今天&#xff0c;无线通信技术正以前所未有的速度发展&#xff0c;不仅改变了我们的生活方式&#xff0c;还为企业带来了前所未有的商业机遇。今天&#xff0c;我要向大家介绍一款飞睿智能的产品——6公里WiFi图传接收模块&#xff0c;它以其高性能、稳定的传输…

【React】基础数据回填--useForm与setFieldsValue详解

相关属性 1.form 2.setFieldsValue 代码 import{Form }from"antd";const Publish =

体积大的快递怎么寄便宜?如何寄件寄包裹更省钱?

大学毕业了&#xff0c;面对即将到来的工作生活&#xff0c;小李不得不把宿舍里的大包小包打包寄回家。可是&#xff0c;当他真正开始打包行李时&#xff0c;才发现这可不是一件简单的事&#xff1a;衣服、被子、书籍、杂物……这些东西加起来体积不小&#xff0c;想要省钱寄快…

基于stm32单片机的智能手环的设计

摘 要 随着科技的飞速发展和人们生活水平的提高&#xff0c;健康与科技日益融合&#xff0c;智能可穿戴设备已成为现代人生活中不可或缺的一部分。智能手环&#xff0c;作为一种便携、实用且功能丰富的可穿戴设备&#xff0c;受到越来越多用户的喜爱。它不仅能够实时监测用户的…

特殊的“user profile service服务登录失”情况

记录一下比较特殊的user profile service服务登录失败情况 公司电脑&#xff0c;某次之后每次来公司电脑开机后就会出现这个情况&#xff0c;后来发现只要是关机后再开机百分百出现&#xff0c;重启就不会&#xff0c;一开始也百度、google了&#xff0c;网上有很多解决方式&am…

DropNotch for Mac v1.0.1 在 Mac 刘海快速使用 AirDrop

应用介绍 DropNotch 是一款专为Mac设计的应用程序&#xff0c;可以将MacBook的凹口区域&#xff08;刘海&#xff09;转换为文件放置区。 功能特点 文件共享: 用户可以将文件拖放到MacBook的凹口区域&#xff0c;并通过AirDrop、邮件、消息等方式轻松共享。多显示器支持: 即…

.Net C#执行JavaScript脚本

文章目录 前言一、安装二、执行 JavaScript 脚本三、与脚本交互四、JS 调用 C# 方法五、多线程使用总结 前言 ClearScript 是一个 .NET 平台下的开源库&#xff0c;用于在 C# 和其他 .NET 语言中执行脚本代码。它提供了一种方便和安全的方法来将脚本与应用程序集成&#xff0c;…

PHP酒店宾馆民宿多商户版系统小程序源码

解锁酒店新境界&#xff01;揭秘多商户版系统的无限可能&#x1f3e8;✨ &#x1f680; 开篇&#xff1a;酒店业的新革命&#xff0c;多商户版系统来袭&#xff01; 你是否梦想过将你的酒店打造成一个集餐饮、娱乐、购物于一体的综合型休闲空间&#xff1f;现在&#xff0c;这…

【linux】服务器卸载cuda

【linux】服务器卸载cuda 文章目录 【linux】服务器卸载cuda1、查找已安装的 CUDA 包&#xff1a;2、卸载 CUDA&#xff1a;3、删除残留文件4、更新系统的包索引&#xff1a;5、检查是否卸载干净&#xff1a; 1、查找已安装的 CUDA 包&#xff1a; dpkg -l | grep cuda2、卸载…

【JavaScript】深入理解Promise:从基础概念到进阶用法、手写promise

&#x1f525; 个人主页&#xff1a;空白诗 文章目录 一、引言二、Promise概述1. Promise的定义2. Promise的用途3. Promise的三种状态4. Promise的构造函数和基础结构5. Promise的优点6. Promise的实例方法7. Promise的静态方法 三、Promise的基本用法1. 创建一个Promise2. th…

The First项目报告:引领L2解决方案新纪元的模块化协议AltLayer

在区块链演进中&#xff0c;可扩展性与定制化成为开发者核心诉求。ZK Rollups与Optimistic Rollups虽显著提升以太坊等区块链性能&#xff0c;却面临访问性、定制难、中心化风险及流动性分散等挑战。AltLayer以Rollups-as-a-Service创新模式&#xff0c;赋予开发者直接管理roll…

【漏洞复现】飞企互联-FE企业运营管理平台——uploadAttachmentServlet——文件上传

声明&#xff1a;本文档或演示材料仅供教育和教学目的使用&#xff0c;任何个人或组织使用本文档中的信息进行非法活动&#xff0c;均与本文档的作者或发布者无关。 文章目录 漏洞描述漏洞复现测试工具 漏洞描述 飞企互联-FE企业运营管理平台是一个基于云计算、智能化、大数据…