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://xiahunao.cn/news/3225156.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

VS Code 配置 C/C++ 编程运行环境(保姆级教程)

文章目录 一、软件下载1. 下载 VS Code 安装工具 2. 下载 MinGW-W64二、安装 VS Code三、安装 MinGW-W64 及配置环境变量四、配置 VS Code 的 C/C 编程运行环境1. 汉化 VS Code&#xff08;选做&#xff09;2. 安装 C/C 扩展包 五、测试 VS Code 的 C/C 编程环境1. 创建代码文件…

PowerShell install 一键部署mysql 9.0.0

mysql 前言 MySQL 是一个基于 SQL(Structured Query Language)的数据库系统,SQL 是一种用于访问和管理数据库的标准语言。MySQL 以其高性能、稳定性和易用性而闻名,它被广泛应用于各种场景,包括: Web 应用程序:许多动态网站和内容管理系统(如 WordPress)使用 MySQL 存…

14-65 剑和诗人39 - 打造你自己的 Devin

​​​​​ 绝密 Devin 架构 更具体地说,构建您自己的 AI 代理。 Devin 使用 GPT-4 ,而人们已经开始用 Claude-3-Opus 构建替代方案 Devin 的 UI 体验更好。 例如,它甚至看不到浏览器,但它确实存在于用户面前 此外,你可以随时与它“交谈”,就像与人交谈一样,它会在后…

基于单片机的温湿度感应智能晾衣杆系统设计

&#xff3b;摘 要&#xff3d; 本设计拟开发一种湿度感应智能晾衣杆系统 &#xff0c; 此新型晾衣杆是以单片机为主控芯片 来控制的实时检测系统 &#xff0e; 该系统使用 DHT11 温湿度传感器来检测大气的温湿度 &#xff0c; 然后通过单 片机处理信息来控制 28BYJ &…

Linux——多线程(五)

1.线程池 1.1初期框架 thread.hpp #include<iostream> #include <string> #include <unistd.h> #include <functional> #include <pthread.h>namespace ThreadModule {using func_t std::function<void()>;class Thread{public:void E…

申请商标用什么颜色:企业和个人申请注册商标攻略!

在申请注册商标到底要用什么颜色&#xff0c;许多初次申请注册主体都不是特别清楚&#xff0c;普推知产商标老杨建议&#xff0c;在一般情况下建议尽量用黑白色&#xff0c;因为商标用黑白色在使用时可以着任何色。 在用黑色申请注册成功&#xff0c;别的主体用其它颜色要在同…

区域特征检测工具的使用

区域特征检测工具的使用 选择区域-》右键-》工具->特征检测

C 语言中如何进行冒泡排序?

&#x1f345;关注博主&#x1f397;️ 带你畅游技术世界&#xff0c;不错过每一次成长机会&#xff01; &#x1f4d9;C 语言百万年薪修炼课程 通俗易懂&#xff0c;深入浅出&#xff0c;匠心打磨&#xff0c;死磕细节&#xff0c;6年迭代&#xff0c;看过的人都说好。 文章目…

华为od100问持续分享-1

我是一名软件开发培训机构老师&#xff0c;我的学生已经有上百人通过了华为OD机试&#xff0c;学生们每次考完试&#xff0c;会把题目拿出来一起交流分享。 重要&#xff1a;2024年5月份开始&#xff0c;考的都是OD统一考试&#xff08;D卷&#xff09;&#xff0c;题库已经整…

CentOS6用文件配置IP模板

CentOS6用文件配置IP模板 到 CentOS6.9 , 默认还不能用 systemctl , 能用 service chkconfig sshd on 对应 systemctl enable sshd 启用,开机启动该服务 ### chkconfig sshd on 对应 systemctl enable sshd 启用,开机启动该服务 sudo chkconfig sshd onservice sshd start …

grep对文件内容搜索(附重要拓展-正则表达式)

文件搜索是搜索查找符合条件的某文件的目录&#xff0c;若要编辑文件或对文件的某配置进行修改&#xff0c;就需要对文件内容进行搜索。 grep 命令是 Linux 及类 Unix 操作系统中的一个强大的文本搜索工具&#xff0c;用于搜索一个或多个文件中匹配给定模式的行。grep 代表“Gl…

Linux进程管理Part2

Linux进程控制Part2 文章目录 Linux进程控制Part2Fork()函数详解简单描述 fork函数的使用进程退出的方式_exit函数exit函数return 退出 进程等待进程等待的方法 kill的使用进程替换简单描述命名原理 END Fork()函数详解 FORK(2) Linux Programmer’s Manual FORK(2) NAME for…

53-4 内网代理6 - frp搭建三层代理

前提:53-3 内网代理5 - frp搭建二级代理-CSDN博客 三级网络代理 在办公区入侵后,发现需要进一步渗透核心区网络(192.168.60.0/24),并登录域控制器的远程桌面。使用FRP在EDMZ区、办公区与核心区之间建立三级网络的SOCKS5代理,以便访问核心区的域控制器。 VPS上的FRP服…

科研训练课程2--论文格式修改+endnote使用

科研训练课程2–论文格式修改endnote使用 文章目录 前言修改论文格式图表endnote 使用&#xff08;补充&#xff09; 总结 前言 第二天 2024/7/9 所属目录&#xff1a;科研训练课程创建时间&#xff1a;2024/7/9作者&#xff1a;星云<XingYun>更新时间&#xff1a;xxxUR…

[高频 SQL 50 题(基础版)]第一千七百五十七题,可回收且低脂产品

题目&#xff1a; 表&#xff1a;Products ---------------------- | Column Name | Type | ---------------------- | product_id | int | | low_fats | enum | | recyclable | enum | ---------------------- product_id 是该表的主键&#xff08;具有唯…

中职网络安全B模块渗透测试system0016

访问http://靶机IP/web1/,获取flag值&#xff0c;Flag格式为flag{xxx}&#xff1b; 可能会跳转8000端口删除进入80端口 进入后点击侦查一下&#xff0c;这里乱码了&#xff0c;我们点击查看是一个柯南&#xff0c;web但这是一个web题目肯定不是隐写术&#xff0c;所以说题目的…

17集 如何用ESP-IDF编译ESP-DL深度学习工程-《MCU嵌入式AI开发笔记》

17集 如何用ESP-IDF编译ESP-DL深度学习工程-《MCU嵌入式AI开发笔记》 参考文档&#xff1a;ESP-DL 用户指南&#xff1a; https://docs.espressif.com/projects/esp-dl/zh_CN/latest/esp32/index.html 和https://docs.espressif.com/projects/esp-dl/zh_CN/latest/esp32/get-s…

Qt 线程同步机制 互斥锁 信号量 条件变量 读写锁

qt线程同步 Qt提供了丰富的线程同步机制来帮助开发者更高效和安全地进行多线程编程。其主要包括: QMutex:为共享数据提供互斥访问能力,避免同时写入导致的数据冲突。利用lock()/unlock()方法实现锁定和解锁。 QReadWriteLock:读写锁,允许多个读线程同时访问,但写操作需要独占…

uniapp+vue3嵌入Markdown格式

使用的库是towxml 第一步&#xff1a;下载源文件&#xff0c;那么可以git clone&#xff0c;也可以直接下载压缩包 git clone https://github.com/sbfkcel/towxml.git 第二步&#xff1a;设置文件夹内的config.js&#xff0c;可以选择自己需要的格式 第三步&#xff1a;安装…

人与机器的协同是强弱系统的互补行为

人与机器的协同可以被视作强弱系统的互补行为&#xff0c;这也强调了人类和机器之间在处理问题、执行任务或创造价值时各自的优势与角色。 人类在认知、创造力、情感和伦理等方面具有独特优势。我们能够进行高级的抽象思维、创新和复杂决策&#xff0c;能够处理不确定性和动态环…