微调大模型(Finetuning Large Language Models)—Data_preparation(四)

news2024/9/28 6:01:24

1. 数据的质量

在这里插入图片描述
数据准备的步骤:
在这里插入图片描述
什么是tokenizing?
在这里插入图片描述
其实就是将文本数据转换为代表文本的数字,一般是基于字符出现的频率。需要注意的,编码和解码的tokenizer需保持一致,一般训练的模型有自己专属匹配的tokenizer。

2. 准备数据

2.1 准备环境

import pandas as pd
import datasets

from pprint import pprint
from transformers import AutoTokenizer

2.2 对文本进行标记化处理

# 调用预训练模型的分词器
tokenizer = AutoTokenizer.from_pretrained("EleutherAI/pythia-70m")
text = "Hi, how are you?"
encoded_text = tokenizer(text)["input_ids"]
print(encoded_text)

输出如下:

[12764, 13, 849, 403, 368, 32]

尝试对编码的数据进行解码

decoded_text = tokenizer.decode(encoded_text)
print("Decoded tokens back into text: ", decoded_text)

输出如下:

Decoded tokens back into text:  Hi, how are you?

可以看到数据又被还原了。在尝试对多个数据进行编码解码。

list_texts = ["Hi, how are you?", "I'm good", "Yes"]
encoded_texts = tokenizer(list_texts)
print("Encoded several texts: ", encoded_texts["input_ids"])

输出如下:

Encoded several texts:  [[12764, 13, 849, 403, 368, 32], [42, 1353, 1175], [4374]]

2.3 填充或者截断

实际上,对于模型来说,非常重要的一点是批处理中的所有
内容长度相同,因为你正在使用固定大小的张量进行操作
所以文本需要是相同的。因此采用填充策略来处理变长编码文本内容。对于我们的填充标记,您必须指定要用于填充的数字,具体来说,我们使用的是零,它实际上也是句子结束标记。因此,
当我们通过分词器运行填充时,您可以看到是”字符串右侧填充了许多零。

tokenizer.pad_token = tokenizer.eos_token 
encoded_texts_longest = tokenizer(list_texts, padding=True)
print("Using padding: ", encoded_texts_longest["input_ids"])

输出如下:

Using padding:  [[12764, 13, 849, 403, 368, 32], [42, 1353, 1175, 0, 0, 0], [4374, 0, 0, 0, 0, 0]]

当然也可以使用截断来保持定长

encoded_texts_truncation = tokenizer(list_texts, max_length=3, truncation=True)
print("Using truncation: ", encoded_texts_truncation["input_ids"])

输出如下:

Using truncation:  [[12764, 13, 849], [42, 1353, 1175], [4374]]

我们可以看到上述字符是从右侧进行截断的。当然我们也可以从左侧进行截断处理。

tokenizer.truncation_side = "left"
encoded_texts_truncation_left = tokenizer(list_texts, max_length=3, truncation=True)
print("Using left-side truncation: ", encoded_texts_truncation_left["input_ids"])

输出如下:

Using left-side truncation:  [[403, 368, 32], [42, 1353, 1175], [4374]]

采用截断和填充的方式保持一致的策略

encoded_texts_both = tokenizer(list_texts, max_length=3, truncation=True, padding=True)
print("Using both padding and truncation: ", encoded_texts_both["input_ids"])

输出如下:

Using both padding and truncation:  [[403, 368, 32], [42, 1353, 1175], [4374, 0, 0]]

2.4 准备指令数据集

import pandas as pd

filename = "lamini_docs.jsonl"
instruction_dataset_df = pd.read_json(filename, lines=True)
examples = instruction_dataset_df.to_dict()

if "question" in examples and "answer" in examples:
  text = examples["question"][0] + examples["answer"][0]
elif "instruction" in examples and "response" in examples:
  text = examples["instruction"][0] + examples["response"][0]
elif "input" in examples and "output" in examples:
  text = examples["input"][0] + examples["output"][0]
else:
  text = examples["text"][0]

prompt_template = """### Question:
{question}

### Answer:"""

num_examples = len(examples["question"])
finetuning_dataset = []
for i in range(num_examples):
  question = examples["question"][i]
  answer = examples["answer"][i]
  text_with_prompt_template = prompt_template.format(question=question)
  finetuning_dataset.append({"question": text_with_prompt_template, "answer": answer})

from pprint import pprint
print("One datapoint in the finetuning dataset:")
pprint(finetuning_dataset[0])

输出如下:

One datapoint in the finetuning dataset:
{'answer': 'Lamini has documentation on Getting Started, Authentication, '
           'Question Answer Model, Python Library, Batching, Error Handling, '
           'Advanced topics, and class documentation on LLM Engine available '
           'at https://lamini-ai.github.io/.',
 'question': '### Question:\n'
             'What are the different types of documents available in the '
             'repository (e.g., installation guide, API documentation, '
             "developer's guide)?\n"
             '\n'
             '### Answer:'}

2.5 对单个示例进行标记化

text = finetuning_dataset[0]["question"] + finetuning_dataset[0]["answer"]
tokenized_inputs = tokenizer(
    text,
    return_tensors="np",
    padding=True
)
print(tokenized_inputs["input_ids"])

输出如下:

[[ 4118 19782    27   187  1276   403   253  1027  3510   273  7177  2130
    275   253 18491   313    70    15    72   904 12692  7102    13  8990
  10097    13 13722   434  7102  6177   187   187  4118 37741    27    45
   4988    74   556 10097   327 27669 11075   264    13  5271 23058    13
  19782 37741 10031    13 13814 11397    13   378 16464    13 11759 10535
   1981    13 21798 12989    13   285   966 10097   327 21708    46 10797
   2130   387  5987  1358    77  4988    74    14  2284    15  7280    15
    900 14206]]

对数据保持一致长度。

max_length = 2048
max_length = min(
    tokenized_inputs["input_ids"].shape[1],
    max_length,
)

tokenized_inputs = tokenizer(
    text,
    return_tensors="np",
    truncation=True,
    max_length=max_length
)

tokenized_inputs["input_ids"]

输出如下:

array([[ 4118, 19782,    27,   187,  1276,   403,   253,  1027,  3510,
          273,  7177,  2130,   275,   253, 18491,   313,    70,    15,
           72,   904, 12692,  7102,    13,  8990, 10097,    13, 13722,
          434,  7102,  6177,   187,   187,  4118, 37741,    27,    45,
         4988,    74,   556, 10097,   327, 27669, 11075,   264,    13,
         5271, 23058,    13, 19782, 37741, 10031,    13, 13814, 11397,
           13,   378, 16464,    13, 11759, 10535,  1981,    13, 21798,
        12989,    13,   285,   966, 10097,   327, 21708,    46, 10797,
         2130,   387,  5987,  1358,    77,  4988,    74,    14,  2284,
           15,  7280,    15,   900, 14206]])

2.6 对指令数据集进行标记化

def tokenize_function(examples):
    if "question" in examples and "answer" in examples:
      text = examples["question"][0] + examples["answer"][0]
    elif "input" in examples and "output" in examples:
      text = examples["input"][0] + examples["output"][0]
    else:
      text = examples["text"][0]

    tokenizer.pad_token = tokenizer.eos_token
    tokenized_inputs = tokenizer(
        text,
        return_tensors="np",
        padding=True,
    )

    max_length = min(
        tokenized_inputs["input_ids"].shape[1],
        2048
    )
    tokenizer.truncation_side = "left"
    tokenized_inputs = tokenizer(
        text,
        return_tensors="np",
        truncation=True,
        max_length=max_length
    )

    return tokenized_inputs

对数据进行标记

finetuning_dataset_loaded = datasets.load_dataset("json", data_files=filename, split="train")

tokenized_dataset = finetuning_dataset_loaded.map(
    tokenize_function,
    batched=True,
    batch_size=1,
    drop_last_batch=True
)

print(tokenized_dataset)

输出如下:

Dataset({
    features: ['question', 'answer', 'input_ids', 'attention_mask'],
    num_rows: 1400
})

对数据增加列标签

tokenized_dataset = tokenized_dataset.add_column("labels", tokenized_dataset["input_ids"])

2.7 对数据集进行划分

split_dataset = tokenized_dataset.train_test_split(test_size=0.1, shuffle=True, seed=123)
print(split_dataset)

输出如下:

DatasetDict({
    train: Dataset({
        features: ['question', 'answer', 'input_ids', 'attention_mask', 'labels'],
        num_rows: 1260
    })
    test: Dataset({
        features: ['question', 'answer', 'input_ids', 'attention_mask', 'labels'],
        num_rows: 140
    })
})

2.8 测试自己的数据集加载

finetuning_dataset_path = "lamini/lamini_docs"
finetuning_dataset = datasets.load_dataset(finetuning_dataset_path)
print(finetuning_dataset)

输出如下:

DatasetDict({
    train: Dataset({
        features: ['question', 'answer', 'input_ids', 'attention_mask', 'labels'],
        num_rows: 1260
    })
    test: Dataset({
        features: ['question', 'answer', 'input_ids', 'attention_mask', 'labels'],
        num_rows: 140
    })
})

尝试taylor_swift数据集

taylor_swift_dataset = "lamini/taylor_swift"
bts_dataset = "lamini/bts"
open_llms = "lamini/open_llms"

dataset_swiftie = datasets.load_dataset(taylor_swift_dataset)
print(dataset_swiftie["train"][1])

输出如下:

{'question': 'What is the most popular Taylor Swift song among millennials? How does this song relate to the millennial generation? What is the significance of this song in the millennial culture?', 'answer': 'Taylor Swift\'s "Shake It Off" is the most popular song among millennials. This song relates to the millennial generation as it is an anthem of self-acceptance and embracing one\'s individuality. The song\'s message of not letting others bring you down and to just dance it off resonates with the millennial culture, which is often characterized by a strong sense of individuality and a rejection of societal norms. Additionally, the song\'s upbeat and catchy melody makes it a perfect fit for the millennial generation, which is known for its love of pop music.', 'input_ids': [1276, 310, 253, 954, 4633, 11276, 24619, 4498, 2190, 24933, 8075, 32, 1359, 1057, 436, 4498, 14588, 281, 253, 24933, 451, 5978, 32, 1737, 310, 253, 8453, 273, 436, 4498, 275, 253, 24933, 451, 4466, 32, 37979, 24619, 434, 346, 2809, 640, 733, 5566, 3, 310, 253, 954, 4633, 4498, 2190, 24933, 8075, 15, 831, 4498, 7033, 281, 253, 24933, 451, 5978, 347, 352, 310, 271, 49689, 273, 1881, 14, 14764, 593, 285, 41859, 581, 434, 2060, 414, 15, 380, 4498, 434, 3935, 273, 417, 13872, 2571, 3324, 368, 1066, 285, 281, 816, 11012, 352, 745, 8146, 684, 342, 253, 24933, 451, 4466, 13, 534, 310, 2223, 7943, 407, 247, 2266, 3282, 273, 2060, 414, 285, 247, 18235, 273, 38058, 22429, 15, 9157, 13, 253, 4498, 434, 598, 19505, 285, 5834, 90, 40641, 2789, 352, 247, 3962, 4944, 323, 253, 24933, 451, 5978, 13, 534, 310, 1929, 323, 697, 2389, 273, 1684, 3440, 15], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 'labels': [1276, 310, 253, 954, 4633, 11276, 24619, 4498, 2190, 24933, 8075, 32, 1359, 1057, 436, 4498, 14588, 281, 253, 24933, 451, 5978, 32, 1737, 310, 253, 8453, 273, 436, 4498, 275, 253, 24933, 451, 4466, 32, 37979, 24619, 434, 346, 2809, 640, 733, 5566, 3, 310, 253, 954, 4633, 4498, 2190, 24933, 8075, 15, 831, 4498, 7033, 281, 253, 24933, 451, 5978, 347, 352, 310, 271, 49689, 273, 1881, 14, 14764, 593, 285, 41859, 581, 434, 2060, 414, 15, 380, 4498, 434, 3935, 273, 417, 13872, 2571, 3324, 368, 1066, 285, 281, 816, 11012, 352, 745, 8146, 684, 342, 253, 24933, 451, 4466, 13, 534, 310, 2223, 7943, 407, 247, 2266, 3282, 273, 2060, 414, 285, 247, 18235, 273, 38058, 22429, 15, 9157, 13, 253, 4498, 434, 598, 19505, 285, 5834, 90, 40641, 2789, 352, 247, 3962, 4944, 323, 253, 24933, 451, 5978, 13, 534, 310, 1929, 323, 697, 2389, 273, 1684, 3440, 15]}

3. 总结

本节讲述了大模型微调前的数据准备工作,最重要的是模型的tokenizer以及截断策略和数据的划分,自己的数据集在制作过程中,仅需遵照上述流程即可,剩下的数据质量自行把握。

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

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

相关文章

实习结帖(flask加上AIGC实现设计符合OpenAPI要求的OpenAPI Schema,让AIGC运行时可以调用api,协助公司门后迁移新后端等)

终于,笔者的实习生活也要告一段落了,最后的几天都在忙着和公司做AIGC的项目,在搞api的设计以及公司门户网站的迁移。 牛马搬运工(牛马了3天) 先说这个门户网站的迁移,我原本以为只是换个后端(若…

新版本Android Studio如何新建Java code工程

新版本Android Studio主推Kotlin,很多同学以为无法新建Java工程了,其实是可以的,如果要新建Java代码的Android工程,在New Project的时候需要选择Empty Views Activity,如图所示,gradle也建议选为build.grad…

RP2040 C SDK GPIO和IRQ 唤醒功能使用

RP2040 C SDK GPIO和中断功能使用 SIO介绍 手册27页: The Single-cycle IO block (SIO) contains several peripherals that require low-latency, deterministic access from the processors. It is accessed via each processor’s IOPORT: this is an auxiliary…

MyBatis——Plus

MyBatis——Plus怎么知道他是访问哪张表

48 旋转图像

解题思路: \qquad 这道题同样需要用模拟解决,原地算法要求空间复杂度尽量小,最好为 O ( 1 ) O(1) O(1)。模拟的关键是找到旋转的内在规律,即旋转前后的位置坐标的变化规律。 \qquad 正方形矩阵类似洋葱,可以由不同大小…

计算机毕业设计 在线问诊系统的设计与实现 Java实战项目 附源码+文档+视频讲解

博主介绍:✌从事软件开发10年之余,专注于Java技术领域、Python人工智能及数据挖掘、小程序项目开发和Android项目开发等。CSDN、掘金、华为云、InfoQ、阿里云等平台优质作者✌ 🍅文末获取源码联系🍅 👇🏻 精…

又一条地铁无人线开通!霞智科技智能清洁机器人正式“上岗”

2024年9月26日12时,又一条无人线开通运营,这是陕西省首条全自动无人驾驶地铁线路。该线路作为北跨战略的先行工程,是连接主城区与渭北地区的轨道交通快线,对优化城市总体空间布局、推动区域融合发展、促进沿线产业升级具有十分重要…

电脑上数据丢了怎么找回来 Win系统误删文件如何恢复

无论是在工作中,还是生活中,电脑都是不可缺少的重要工具,尤其是在工作中,电脑不仅可以高效的完成工作,还可以存储工作中的重要资料。不过在使用电脑的时候,也会遇到数据丢失的情况。针对这一问题&#xff0…

渗透测试--文件上传常用绕过方式

文件上传常用绕过方式 1.前端代码,限制只允许上传图片。修改png为php即可绕过前端校验。 2.后端校验Content-Type 校验文件格式 前端修改,抓取上传数据包,并且修改 Content-Type 3.服务端检测(目录路径检测) 对目…

在Java中使用GeoTools解析POI数据并存储到PostGIS实战

目录 前言 一、POI数据相关介绍 1、原始数据说明 2、空间数据库表设计 二、POI数据存储的设计与实现 1、对应的数据模型对象的设计 2、属性表数据和空间信息的读取 3、实际运行结果 三、总结 前言 POI点,全称为Point of Interest(兴趣点&#xf…

大数据技术:Hadoop、Spark与Flink的框架演进

大数据技术,特别是Hadoop、Spark与Flink的框架演进,是过去二十年中信息技术领域最引人注目的发展之一。这些技术不仅改变了数据处理的方式,而且还推动了对数据驱动决策和智能化的需求。在大数据处理领域,选择合适的大数据平台是确…

git 清除二进制文件的 changes 状态

问题:某个分支上修改了二进制文件,导致 changes 一直存在,切换到主分支也仍然存在,点击 Discard 也没用 使用 git reset --hard 还原到初始状态,也不行,不过输出结果会给出错误信息 Encountered 7 file(s) …

raise Exception(“IPAdapter model not found.“)

IPAdapter模型文件太多了,而节点IPAdapter Unified Loader是通过函数(get_ipadapter_file与get_clipvision_file)预设来加载模型文件,当发生错误“IPAdapter model not found.“时并不指明模型文件名,导致想要有针对性…

C语言 | Leetcode C语言题解之第438题找到字符串中所有字母异位词

题目: 题解: /*** Note: The returned array must be malloced, assume caller calls free().*/ /* *int strCmpn:比较滑动窗口和字符串的相同值 char * s:字符串s,滑动窗口的位置 char * p:字符串p&#…

【Python】Flask-Admin:构建强大、灵活的后台管理界面

在 Web 应用开发中,构建一个直观且功能丰富的后台管理系统对于处理数据和维护应用至关重要。虽然构建一个完全自定义的管理后台界面非常耗时,但 Flask-Admin 提供了一个简洁、灵活的解决方案,可以让开发者快速集成一个功能齐全的后台管理系统…

【移植】轻量系统STM32F407芯片移植案例

往期知识点记录: 鸿蒙(HarmonyOS)应用层开发(北向)知识点汇总 鸿蒙(OpenHarmony)南向开发保姆级知识点汇总~ 持续更新中…… 介绍基于 STM32F407IGT6 芯片在拓维信息 Niobe407 开发板上移植 Op…

Linux操作系统中MongoDB

1、什么是MongoDB 1、非关系型数据库 NoSQL,泛指非关系型的数据库。随着互联网web2.0网站的兴起,传统的关系数据库在处理web2.0网站,特别是超大规模和高并发的SNS类型的web2.0纯动态网站已经显得力不从心,出现了很多难以克服的问…

改变安全策略的五大实践

随着网络威胁形势的加剧,网络安全计划必须不断发展以保护组织的使命。 为了管理这种持续的网络安全发展,应遵循五项关键的安全计划变更管理实践: 1. 识别并吸引受安全风险影响的业务利益相关者 随着新的网络安全风险被发现,受影…

HEITRONICS TC13红外辐射高温计CT13 INFRARED RADIATION PYROMETER CT13

HEITRONICS TC13红外辐射高温计CT13 INFRARED RADIATION PYROMETER CT13

山海优选电商平台卷轴模式订单系统核心架构解析

山海优选卷轴模式的订单核心源码是涉及订单处理、支付、搜索、状态管理等关键功能的代码部分。由于直接提供完整的源代码可能涉及版权和隐私保护问题,我将基于参考文章中的信息,概述该模式订单核心源码的主要结构和功能点。 一、订单核心源码概述 在山海…