使用 LoRA 在 vi​​ggo 数据集上微调 Microsoft phi-2 小语言模型

news2024/9/21 20:26:36

一、说明

        Microsoft 的基于 Transformer 的小语言模型。它可以根据 MIT 许可在HuggingFace上使用。

        它在 96 个 A100 GPU 上使用 1.4T 令牌进行了 14 天的训练。Phi-2 是一个 27 亿个参数的预训练 Transformer,不使用 RLHF 或指示微调。它进行下一个标记预测,并可用于问答、聊天格式和代码生成中的文本生成。

        事实证明,phi-2 在多个基准测试和编码和数学等任务上优于许多具有 7B 和 13B 参数的模型。

        小语言模型之所以具有优异的性能,是因为使用了经过提炼的高质量训练数据或“教科书质量”的数据。小语言模型使用知识蒸馏。也就是说,他们接受了从 LLMS 中提取的核心/基本知识的培训。然后采用剪枝和量化技术来删除模型的非必要部分。训练数据通常是综合数据集的混合物,这些数据集是专门创建的,旨在教导模型执行科学、日常活动、心理理论等领域的常识推理和一般知识。它还可能包含具有高教育意义的选择性网络数据价值和质量。小语言模型使用创新技术进行扩展。

        接下来,我们将看到有关如何使用 HuggingFace 中的 phi-2 进行提示的分步 Python 代码,然后我们将在 veggo 数据集上对其进行微调。我使用 T4 GPU 在 Google Colab 免费层上运行了此代码笔记本。

二、安装依赖库

        我的代码借鉴自 GitHub 上Harper Carrol 的这篇优秀教程。

  1. 安装所需的库
#@title Install required libraries
!pip install accelerate==0.25.0
!pip install bitsandbytes==0.41.1
!pip install datasets==2.14.6
!pip install peft==0.6.2
!pip install transformers==4.36.2
!pip install torch==2.1.0
!pip install einops==0.4.1  
!pip install huggingface_hub

2.所需进口

import torch
import transformers
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TrainingArguments, pipeline, logging
from datasets import Dataset

3.我们将使用Google Colab Free tier(T4)上的cuda设备来运行模型

torch.set_default_device("cuda")

4.创建模型和分词器

#create the model object and the corresponding tokenizer
model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2", torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-2", trust_remote_code=True)

5. 让我们运行一些提示并查看模型响应

# https://huggingface.co/microsoft/phi-2
# This prompt is for code completion
# here the prompt is written within the tokenizer()
inputs = tokenizer('''def fibonacci(n):
   """
   This function prints the terms in Fibonacci series upto n
   """''', return_tensors="pt", return_attention_mask=False)

outputs = model.generate(**inputs, max_length=100)
text = tokenizer.batch_decode(outputs)[0]
print(text)
#https://huggingface.co/microsoft/phi-2
# here a string containing the prompt is defined separately from the tokenizer() and then passed to it
prompt = '''def fibonacci(n):
   """
   This function prints the terms in Fibonacci series upto n
   """'''
inputs = tokenizer(prompt, return_tensors="pt", return_attention_mask=False)
outputs = model.generate(**inputs, max_length=100)
text = tokenizer.batch_decode(outputs)[0]
print(text)
# here we see the output of phi-2 for a question-answering prompt
prompt = 'What is thee relevance of mathematics for understanding physics?'
inputs = tokenizer(prompt, return_tensors="pt", return_attention_mask=False)
outputs = model.generate(**inputs, max_length=200)
text = tokenizer.batch_decode(outputs)[0]
print(text)

三、在HuggingFace的veggo微调 phi-2 模型 

现在我们将在HuggingFace 的“veggo”数据集上

ViGGO是视频游戏领域的英文数据到文本生成数据集。目标响应以会话形式以意义表示形式呈现。该数据集大约有 5,000 个非常干净的数据点,因此该数据集可用于评估神经模型的迁移学习、低资源或少样本能力。

6. 让我们设置加速器来加速训练/微调

#@title Set up accelerator to speed up the training/finetuning
from accelerate import FullyShardedDataParallelPlugin, Accelerator
from torch.distributed.fsdp.fully_sharded_data_parallel import FullOptimStateDictConfig, FullStateDictConfig

fsdp_plugin = FullyShardedDataParallelPlugin(
    state_dict_config=FullStateDictConfig(offload_to_cpu=True, rank0_only=False),
    optim_state_dict_config=FullOptimStateDictConfig(offload_to_cpu=True, rank0_only=False),
)

accelerator = Accelerator(fsdp_plugin=fsdp_plugin)

7. 使用有效的 HuggingFace 访问令牌登录您的 Huggingface 帐户。

        您应该在 HuggingFace 上有一个帐户,然后您可以创建一个免费的访问令牌。

#@title login to your huggingface account using your access token
# you can find your access token at https://huggingface.co/settings/tokens
from huggingface_hub import notebook_login
notebook_login()

8.加载viggo数据集

#@title load viggo dataset
from datasets import load_dataset

train_dataset = load_dataset('gem/viggo', split='train')
eval_dataset = load_dataset('gem/viggo', split='validation')
test_dataset = load_dataset('gem/viggo', split='test')

9. 加载基础模型phi-2

#@title load base model microsoft/phi-2 
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, DataCollatorForLanguageModeling

base_model_id = "microsoft/phi-2"
model = AutoModelForCausalLM.from_pretrained(base_model_id, 
                                             load_in_8bit=True, 
                                             torch_dtype=torch.float16, 
                                             trust_remote_code=True)

10. 在下面的代码单元中,我们设置 tokenizer 对象, tokenize() 函数将 tokenizer 应用于每个提示,并创建一个“labels”列,其值与数据中的“input_ids”列相同。

        generate_and_tokenize_prompt() 函数将每个数据点转换为适合传递给 phi-2 模型的提示格式。它从数据点中提取“目标”和“含义表示”。最后,我们使用 map() 函数将此函数应用于 train 和 val 数据集中的每个数据点。

#@title set up the tokenizer for base model
tokenizer = AutoTokenizer.from_pretrained(
    base_model_id,
    add_eos_token=True,
    add_bos_token=True, 
    use_fast=False, # needed for now, should be fixed soon
)

#@title setup tokenize function to make labels and input_ids the same for the self-supervised fine-tuning.
def tokenize(prompt):
    result = tokenizer(prompt)
    result["labels"] = result["input_ids"].copy()
    return result

#@title convert each sample into a prompt
 
def generate_and_tokenize_prompt(data_point):
    full_prompt =f"""Given a target sentence construct the underlying meaning representation of the input sentence as a single function with attributes and attribute values.
                This function should describe the target string accurately and the function must be one of the following ['inform', 'request', 'give_opinion', 'confirm', 'verify_attribute', 'suggest', 'request_explanation', 'recommend', 'request_attribute'].
                   The attributes must be one of the following: ['name', 'exp_release_date', 'release_year', 'developer', 'esrb', 'rating', 'genres', 'player_perspective', 'has_multiplayer', 'platforms', 'available_on_steam', 'has_linux_release', 'has_mac_release', 'specifier']

                 ### Target sentence:
                 {data_point["target"]}

                  ### Meaning representation:
                  {data_point["meaning_representation"]}
                 """
    return tokenize(full_prompt)




#@title Reformat the prompt and tokenize each sample:

tokenized_train_dataset = train_dataset.map(generate_and_tokenize_prompt)
tokenized_val_dataset = eval_dataset.map(generate_and_tokenize_prompt)

11. 模型的输入张量通常使用 max_length 参数将每个输入填充到统一长度。

        为了确定该参数的值,我们可以绘制每个 input_id 的长度分布,并将 max_length 设置为等于最长 input_id 的长度。在本例中,选择的 max_length 为 320。

12. 接下来,我们将再次应用 tokenize(),并将 max_length 参数设置为 320。

max_length = 320 # appropriate max length for this dataset

# redefine the tokenize function and tokenizer

tokenizer = AutoTokenizer.from_pretrained(
    base_model_id,
    padding_side="left",
    add_eos_token=True,  
    add_bos_token=True,  
    trust_remote_code=True,
    use_fast=False, # needed for now, should be fixed soon
)
tokenizer.pad_token = tokenizer.eos_token


def tokenize(prompt):
    result = tokenizer(
        prompt,
        truncation=True,
        max_length=max_length,
        padding="max_length",
    )
    result["labels"] = result["input_ids"].copy()
    return result


#@title tokenize train and validation datasets using generate_and_tokenize_prompt function
tokenized_train_dataset = train_dataset.map(generate_and_tokenize_prompt)
tokenized_val_dataset = eval_dataset.map(generate_and_tokenize_prompt)

四、使用LoRA来微调phi-2

        13.让我们使用LoRA(低阶适应)来微调phi-2

        低秩适应是一种快速微调大型语言模型的技术。它冻结预训练的模型权重,并将可训练的秩分解矩阵注入到 Transformer 架构的每一层中,从而减少下游任务的可训练参数的数量。它可以将可训练参数的数量减少10000倍,将GPU内存需求减少3倍。

        要使用 LoRA 微调模型,您需要:

  1. 实例化基本模型。
  2. 创建一个配置 ( LoraConfig),在其中定义 LoRA 特定参数。
  3. 用 包裹基本模型get_peft_model()以获得可训练的PeftModel.
  4. PeftModel像平常训练基本模型一样训练。

   LoraConfig允许您通过以下参数控制 LoRA 如何应用于基础模型:

  • r:更新矩阵的秩,以 表示int。较低的秩会导致较小的更新矩阵和较少的可训练参数。
  • target_modules:应用 LoRA 更新矩阵的模块(例如,注意力块)。
  • alpha:LoRA 比例因子。
  • bias:指定是否bias应训练参数。可以是'none''all'或者'lora_only'
  • modules_to_save:除了 LoRA 层之外的模块列表,要设置为可训练并保存在最终检查点中。这些通常包括模型的自定义头,该头是为微调任务随机初始化的。
  • layers_to_transform:LoRA 转换的层列表。如果未指定,target_modules则变换中的所有图层。
  • layers_patterntarget_modules:如果layers_to_transform指定,则匹配 中图层名称的模式。默认情况下,PeftModel将查看公共层模式(layershblocks等),将其用于奇异和自定义模型。
  • rank_pattern:从图层名称或正则表达式到与 指定的默认排名不同的排名的映射r
  • alpha_pattern:从图层名称或正则表达式到 alpha 的映射,与 指定的默认 alpha 不同lora_alpha

        我们将把 LoRA 应用到模型的 Wqkv、fc1、fc2 层。

from peft import LoraConfig, get_peft_model

config = LoraConfig(
    r=8,
    lora_alpha=16,
    target_modules=[
        "Wqkv",
        "fc1",
        "fc2",
    ],
    bias="none",
    lora_dropout=0.05,  # Conventional
    task_type="CAUSAL_LM",
)

model = get_peft_model(model, config)


# Apply the acceleratort to the model for faster traning. 
model = accelerator.prepare_model(model)

五、 使用 LoRA 微调/训练模型

        您将需要设置训练参数或配置参数,例如保存模型的输出目录。我正在将微调后的模型保存/推送到我的 HuggingFace 帐户,您也可以将微调后的模型保存在本地目录或 Colab 目录中。

        其他训练参数包括warmup_steps、per_device_train_batch_size、gradient_accumulation_steps、max_steps、learning_rate、logging_steps、optim、logging_dir、save_strategy、save_steps、evaluation_strategy、eval_steps、do_eval、push_to_hub、report_to、run_name等。

        maz_steps 确定要执行的最大训练步骤,越长,您的模型就越精细,完成训练所需的时间也越长。当 max_steps = 1000 时,我花了 90 分钟在免费的 Google Colab 上进行训练。学习率也会影响训练时间。

#Train the model and push each check point to Huggingface
import transformers


tokenizer.pad_token = tokenizer.eos_token

trainer = transformers.Trainer(
    model=model,
    train_dataset=tokenized_train_dataset,
    eval_dataset=tokenized_val_dataset,
    args=transformers.TrainingArguments(
        output_dir="./phi2-finetunedonviggodataset",
        warmup_steps=5,
        per_device_train_batch_size=1,
        gradient_accumulation_steps=4,
        max_steps=500,
        learning_rate=2.5e-5, 
        logging_steps=50,
        optim="paged_adamw_8bit",
        logging_dir="./logs",        # Directory for storing logs
        save_strategy="steps",       # Save the model checkpoint every logging step
        save_steps=50,                # Save checkpoints every 50 steps
        evaluation_strategy="steps", # Evaluate the model every logging step
        eval_steps=50,               # Evaluate and save checkpoints every 50 steps
        do_eval=True,                # Perform evaluation at the end of training
        push_to_hub=True,

    ),
    data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),
)

model.config.use_cache = False  
trainer.train()

        现在您已经在 viggo 数据集上微调了 phi-2,并将其保存在 output_dir 或您的 Huggingface 帐户中。

16.接下来,我们将比较基本模型(没有微调)和微调模型(上面训练过的)上示例提示的性能

#Load the base model
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

base_model_id = "microsoft/phi-2"

base_model = AutoModelForCausalLM.from_pretrained(
    base_model_id,
    load_in_8bit=True,
    device_map="auto",
    trust_remote_code=True,
    torch_dtype=torch.float16,
)

eval_tokenizer = AutoTokenizer.from_pretrained(
    base_model_id,
    add_bos_token=True,
    trust_remote_code=True,
    use_fast=False,
)

#create a sample prompt for evaluation on base model
eval_prompt = """Given a target sentence construct the underlying meaning representation of the input sentence as a single function with attributes and attribute values.
This function should describe the target string accurately and the function must be one of the following ['inform', 'request', 'give_opinion', 'confirm', 'verify_attribute', 'suggest', 'request_explanation', 'recommend', 'request_attribute'].
The attributes must be one of the following: ['name', 'exp_release_date', 'release_year', 'developer', 'esrb', 'rating', 'genres', 'player_perspective', 'has_multiplayer', 'platforms', 'available_on_steam', 'has_linux_release', 'has_mac_release', 'specifier']

### Target sentence:
Earlier, you stated that you didn't have strong feelings about PlayStation's Little Big Adventure. Is your opinion true for all games which don't have multiplayer?

### Meaning representation:
"""

# tokenize the above prompt and generate the response from base model
model_input = eval_tokenizer(eval_prompt, return_tensors="pt").to('cuda')
base_model.eval()
with torch.no_grad():
    print(eval_tokenizer.decode(base_model.generate(**model_input, max_new_tokens=100)[0], skip_special_tokens=True))

17. 现在让我们从我的 HuggingFace 帐户加载经过微调的模型,并在其上测试相同的提示。

from peft import PeftModel
ft_model = PeftModel.from_pretrained(base_model, "nimrita/phi2-finetunedonviggodataset", force_download=True)


eval_prompt = """Given a target sentence construct the underlying meaning representation of the input sentence as a single function with attributes and attribute values.
This function should describe the target string accurately and the function must be one of the following ['inform', 'request', 'give_opinion', 'confirm', 'verify_attribute', 'suggest', 'request_explanation', 'recommend', 'request_attribute'].
The attributes must be one of the following: ['name', 'exp_release_date', 'release_year', 'developer', 'esrb', 'rating', 'genres', 'player_perspective', 'has_multiplayer', 'platforms', 'available_on_steam', 'has_linux_release', 'has_mac_release', 'specifier']

### Target sentence:
Earlier, you stated that you didn't have strong feelings about PlayStation's Little Big Adventure. Is your opinion true for all games which don't have multiplayer?

### Meaning representation:
"""

model_input = eval_tokenizer(eval_prompt, return_tensors="pt").to('cuda')
ft_model = ft_model.to('cuda')
ft_model.eval()
with torch.no_grad():
    print(eval_tokenizer.decode(ft_model.generate(**model_input, max_new_tokens=100)[0], skip_special_tokens=True))

        您刚刚微调了 phi-2。

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

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

相关文章

RNN(神经网络)

目录 介绍: 数据: 模型: 预测: 介绍: RNN,全称为循环神经网络(Recurrent Neural Network),是一种深度学习模型,它主要用于处理和分析序列数据。与传统…

Python入门:生成器迭代器

一、列表生成式 现在有个需求,列表[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],要求你把列表里的每个值加1,怎么实现?你可能会想到2种方式 二逼青年版 1 2 3 4 a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b [] for i in a:b.append(i1) print(b) …

如果通过浏览器调试?

背景:博主是一个有丰富经验的后端开发人员,在前端开发中感觉总是有种力不从心的感觉,因为没有后端debug调试的清晰感。 解决办法:掌握chorm浏览器调试技巧。 F12, F5 打上断点之后,这不就是梦寐之中的调试…

Linux驱动 SPI子系统

1、SPI协议 SPI(Serial Peripheral Interface)是一种同步串行数据通信协议,通常用于连接微控制器和外部设备,如传感器、存储器、显示器等。SPI协议使用四根线进行通信,包括时钟线(SCLK)、数据输…

第十二篇【传奇开心果系列】Python的OpenCV技术点案例示例:视频流处理

传奇开心果短博文系列 系列短博文目录Python的OpenCV技术点案例示例短博文系列短博文目录一、前言二、视频流处理介绍三、实时视频流处理示例代码四、视频流分析示例代码五、归纳总结系列短博文目录 Python的OpenCV技术点案例示例短博文系列 短博文目录 一、前言 OpenCV视频…

【面试官问】Redis 持久化

目录 【面试官问】Redis 持久化 Redis 持久化的方式RDB(Redis DataBase)AOF(Append Only File)混合持久化:RDB + AOF 混合方式的持久化持久化最佳方式控制持久化开关主从部署使用混合持久化使用配置更高的机器参考文章所属专区

OfficeWeb365 Readfile 任意文件读取漏洞

免责声明:文章来源互联网收集整理,请勿利用文章内的相关技术从事非法测试,由于传播、利用此文所提供的信息或者工具而造成的任何直接或者间接的后果及损失,均由使用者本人负责,所产生的一切不良后果与文章作者无关。该…

Qt|实现时间选择小功能

在软件开发过程中,QtDesigner系统给出的控件很多时候都无法满足炫酷的效果,前一段时间需要用Qt实现选择时间的小功能,今天为大家分享一下! 首先看一下时间效果吧! 如果有需要继续往下看下去哟~ 功能 1:开…

池化技术的总结

文章目录 1.什么是池化技术2.池化技术的应用一、连接池二、线程池三、内存池 3.池化技术的总结 1.什么是池化技术 池化技术指的是提前准备一些资源,在需要时可以重复使用这些预先准备的资源。 在系统开发过程中,我们经常会用到池化技术。通俗的讲&am…

xlsx xlsx-style 使用和坑记录

1 安装之后报错 npm install xlsx --savenpm install xlsx-style --save Umi运行会报错 自己代码 import XLSX from "xlsx"; import XLSXStyle from "xlsx-style";const data [["demo1","demo2","demo3","demo4&quo…

电路设计(9)——八路智力抢答器的proteus仿真

1.设计要求 运用模拟电路、数字电路知识,设计、制作一个8路智力竞赛抢答器,要求有优先锁存、数显、声响及复位电路。 主要元器件:CD4511,IN4148,共阴数码管,NPN三极管9013,NE555,喇叭…

在工业制造方面,如何更好地实现数字化转型?

实现工业制造的数字化转型涉及利用数字技术来增强流程、提高效率并推动创新。以下是工业制造领域更好实现数字化转型的几个关键步骤: 1.定义明确的目标: 清楚地概述您的数字化转型目标。确定需要改进的领域,例如运营效率、产品质量或供应链…

[SWPUCTF 2021 新生赛]Do_you_know_http

我们看到它让我们用WLLM浏览器登录 那我们修改User-Agent的值即可 发现有一个a.php的我们进入该目录 它提示我们不在本地服务器上 发现有一个/secretttt.php的目录 我进入即可获得flag

Netflix Mac(奈飞mac客户端) v2.13.0激活版

Clicker for Netflix Mac版是一款适用于Mac的最佳独立Netflix播放器,具有直接从从Dock启动Netflix,从触摸栏控制Netflix,支持画中画等多种功能,让你拥有更好的观看体验。 软件特色 •直接从Dock启动Netflix •从触摸栏控制Netflix…

何以穿越产业周期?解读蓝思科技2023年增长密码

1月30日晚,蓝思科技发布了2023年业绩预告,2023年预计实现归母净利润29.38亿元-30.60亿元,同比增长20%-25%。 松果财经注意到,蓝思科技通过垂直整合,构筑了更具竞争力的产业链条。一方面,公司打造了包含ODM…

[349. 两个数组的交集](C语言)(两种解法:双指针+排序,哈希)

✨欢迎来到脑子不好的小菜鸟的文章✨ 🎈创作不易,麻烦点点赞哦🎈 所属专栏:刷题 我的主页:脑子不好的小菜鸟 文章特点:关键点和步骤讲解放在 代码相应位置 前提: 看本文章之前,建…

php微信退款:订单金额或退款金额与之前请求不一致,请核实后再试问题

bug出现情况&#xff1a; 微信支付退款 解决方案 php将float转换成int类型&#xff0c;在要转换的变量之前加上用括号括起来的目标类型 <?php $a 16.90; echo (int)($a * 100); echo "<br/>"; echo (int)strval($a * 100);

2024年土木工程与环境科学国际会议(ICCEES2024)

2024年土木工程与环境科学国际会议(ICCEES2024) 会议简介 土木工程与环境科学是国民经济中的基础性、先导性、战略性产业&#xff0c;本次会议主要围绕土木工程与环保科学等研究领域&#xff0c;旨在吸引土木工程与生态环境工程专家学者、科技人员、&#xff0c;为广大工程师…

SSL证书的验证过程

HTTPS是工作于SSL层之上的HTTP协议&#xff0c;SSL&#xff08;安全套接层&#xff09;工作于TCP层之上&#xff0c;向应用层提供了两个基本安全服务&#xff1a;认证和保密。SSL有三个子协议&#xff1a;握手协议&#xff0c;记录协议和警报协议。其中握手协议实现服务器与客户…

嵌入式学习第十六天!(Linux文件查看、查找命令、标准IO)

Linux软件编程 1. Linux&#xff1a; 操作系统的内核&#xff1a; 1. 管理CPU 2. 管理内存 3. 管理硬件设备 4. 管理文件系统 5. 任务调度 2. Shell&#xff1a; 1. 保护Linux内核&#xff08;用户和Linux内核不直接操作&#xff0c;通过操作Shell&#xff0c;Shell和内核交互…