昇思25天学习打卡营第23天|基于MindSpore的GPT2文本摘要

这节课主要学习基于MindSpore的GPT2文本摘要。主要包括环境安装、数据集加载与处理、模型构建、模型训练、模型推理五部分内容。

1.首先介绍环境安装

%%capture captured_output
# 实验环境已经预装了mindspore==2.2.14,如需更换mindspore版本,可更改下面mindspore的版本号
!pip uninstall mindspore -y
!pip install -i https://pypi.mirrors.ustc.edu.cn/simple mindspore==2.2.14
!pip install tokenizers==0.15.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
# 该案例在 mindnlp 0.3.1 版本完成适配,如果发现案例跑不通,可以指定mindnlp版本,执行`!pip install mindnlp==0.3.1`
!pip install mindnlp

搭建mindspore深度学习环境。

2.数据集加载与处理
2.1 数据集加载
实验使用的是nlpcc2017摘要数据,内容为新闻正文及其摘要,总计50000个样本。

from mindnlp.utils import http_get# download dataset
url = 'https://download.mindspore.cn/toolkits/mindnlp/dataset/text_generation/nlpcc2017/train_with_summ.txt'
path = http_get(url, './')
from mindspore.dataset import TextFileDataset# load dataset
dataset = TextFileDataset(str(path), shuffle=False)
dataset.get_dataset_size()
# split into training and testing dataset
train_dataset, test_dataset = dataset.split([0.9, 0.1], randomize=False)

2.2 数据预处理

原始数据格式:
article: [CLS] article_context [SEP]
summary: [CLS] summary_context [SEP]
预处理后的数据格式:
[CLS] article_context [SEP] summary_context [SEP]

import json
import numpy as np# preprocess dataset
def process_dataset(dataset, tokenizer, batch_size=6, max_seq_len=1024, shuffle=False):def read_map(text):data = json.loads(text.tobytes())return np.array(data['article']), np.array(data['summarization'])def merge_and_pad(article, summary):# tokenization# pad to max_seq_length, only truncate the articletokenized = tokenizer(text=article, text_pair=summary,padding='max_length', truncation='only_first', max_length=max_seq_len)return tokenized['input_ids'], tokenized['input_ids']dataset = dataset.map(read_map, 'text', ['article', 'summary'])# change column names to input_ids and labels for the following trainingdataset = dataset.map(merge_and_pad, ['article', 'summary'], ['input_ids', 'labels'])dataset = dataset.batch(batch_size)if shuffle:dataset = dataset.shuffle(batch_size)return dataset

因GPT2无中文的tokenizer,我们使用BertTokenizer替代。

from mindnlp.transformers import BertTokenizer# We use BertTokenizer for tokenizing chinese context.
tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')
len(tokenizer)
train_dataset = process_dataset(train_dataset, tokenizer, batch_size=4)
next(train_dataset.create_tuple_iterator())

3.模型构建
3.1构建GPT2ForSummarization模型,注意shift right的操作。

from mindspore import ops
from mindnlp.transformers import GPT2LMHeadModelclass GPT2ForSummarization(GPT2LMHeadModel):def construct(self,input_ids = None,attention_mask = None,labels = None,):outputs = super().construct(input_ids=input_ids, attention_mask=attention_mask)shift_logits = outputs.logits[..., :-1, :]shift_labels = labels[..., 1:]# Flatten the tokensloss = ops.cross_entropy(shift_logits.view(-1, shift_logits.shape[-1]), shift_labels.view(-1), ignore_index=tokenizer.pad_token_id)return loss

3.2.动态学习率

from mindspore import ops
from mindspore.nn.learning_rate_schedule import LearningRateScheduleclass LinearWithWarmUp(LearningRateSchedule):"""Warmup-decay learning rate."""def __init__(self, learning_rate, num_warmup_steps, num_training_steps):super().__init__()self.learning_rate = learning_rateself.num_warmup_steps = num_warmup_stepsself.num_training_steps = num_training_stepsdef construct(self, global_step):if global_step < self.num_warmup_steps:return global_step / float(max(1, self.num_warmup_steps)) * self.learning_ratereturn ops.maximum(0.0, (self.num_training_steps - global_step) / (max(1, self.num_training_steps - self.num_warmup_steps))) * self.learning_rate

4.模型训练

num_epochs = 1
warmup_steps = 2000
learning_rate = 1.5e-4num_training_steps = num_epochs * train_dataset.get_dataset_size()
from mindspore import nn
from mindnlp.transformers import GPT2Config, GPT2LMHeadModelconfig = GPT2Config(vocab_size=len(tokenizer))
model = GPT2ForSummarization(config)lr_scheduler = LinearWithWarmUp(learning_rate=learning_rate, num_warmup_steps=warmup_steps, num_training_steps=num_training_steps)
optimizer = nn.AdamWeightDecay(model.trainable_params(), learning_rate=lr_scheduler)
# 记录模型参数数量
print('number of model parameters: {}'.format(model.num_parameters()))

from mindnlp._legacy.engine import Trainer
from mindnlp._legacy.engine.callbacks import CheckpointCallback

ckpoint_cb = CheckpointCallback(save_path=‘checkpoint’, ckpt_name=‘gpt2_summarization’,
epochs=1, keep_checkpoint_max=2)

trainer = Trainer(network=model, train_dataset=train_dataset,
epochs=1, optimizer=optimizer, callbacks=ckpoint_cb)
trainer.set_amp(level=‘O1’) # 开启混合精度
5.、模型推理

数据处理,将向量数据变为中文数据

def process_test_dataset(dataset, tokenizer, batch_size=1, max_seq_len=1024, max_summary_len=100):def read_map(text):data = json.loads(text.tobytes())return np.array(data['article']), np.array(data['summarization'])def pad(article):tokenized = tokenizer(text=article, truncation=True, max_length=max_seq_len-max_summary_len)return tokenized['input_ids']dataset = dataset.map(read_map, 'text', ['article', 'summary'])dataset = dataset.map(pad, 'article', ['input_ids'])dataset = dataset.batch(batch_size)return dataset`
test_dataset = process_test_dataset(test_dataset, tokenizer, batch_size=1)
print(next(test_dataset.create_tuple_iterator(output_numpy=True)))
model = GPT2LMHeadModel.from_pretrained('./checkpoint/gpt2_summarization_epoch_0.ckpt', config=config)
model.set_train(False)
model.config.eos_token_id = model.config.sep_token_id
i = 0
for (input_ids, raw_summary) in test_dataset.create_tuple_iterator():output_ids = model.generate(input_ids, max_new_tokens=50, num_beams=5, no_repeat_ngram_size=2)output_text = tokenizer.decode(output_ids[0].tolist())print(output_text)i += 1if i == 1:break

这节内容就学习到这里~

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

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

相关文章

go 编译ollama的时候报错:open /dev/null: no such file or directory

go 编译ollama的时候报错&#xff1a;open /dev/null: no such file or directory github.com/xtgo/set: /root/work/go/pkg/tool/linux_amd64/compile: open /dev/null: no such file or directory gonum.org/v1/gonum/blas/gonum: /root/work/go/pkg/tool/linux_amd64/compi…

Spark中的JOIN机制

Spark中的JOIN机制 1、Hash Join概述2、影响JOIN的因素3、Spark中的JOIN策略3.1、Shuffle Hash Join3.2、Broadcast Hash Join3.3、Sort Merge Join3.4、Cartesian Product Join2.5、Broadcast Nested Loop Join1、Hash Join概述 Apache Spark共提供了五种JOIN机制,其中常用的…

Laravel Horizon:任务队列的智能指挥官

Laravel Horizon&#xff1a;任务队列的智能指挥官 在现代Web应用中&#xff0c;处理耗时的任务通常需要异步执行&#xff0c;以避免阻塞主线程和影响用户体验。Laravel的Horizon任务系统是一个强大的后台工作管理器&#xff0c;它不仅优化了队列任务的处理&#xff0c;还提供…

【论文阅读】MCTformer+:弱监督语义分割的多类令牌转换器

【论文阅读】MCTformer:弱监督语义分割的多类令牌转换器 文章目录 【论文阅读】MCTformer:弱监督语义分割的多类令牌转换器一、介绍1.1 WSSS背景1.2 WSSS策略 二、联系工作2.1 弱监督语义分割2.2 transformers的可视化应用 三、MULTI-CLASS TOKEN TRANSFORMER3.1 Multi-class t…

读人工智能全传15意向立场

1. 物理立场 1.1. 可以解释一个实体行为 1.2. 在物理立场中&#xff0c;我们使用自然法则(物理、化学等)来预测系统的行为结果 1.3. 虽然物理立场在解释这种行为的时候非常有效&#xff0c;但无法应用于理解或者预测人类行为 1.3.1. …

java基础学习:序列化之 - hessian2

文章目录 一、介绍二、主要特点三、应用场景四、使用方式五、与其他序列化协议的比较六、总结 一、介绍 Hessian2是Hessian协议的一个更新版本&#xff0c;由Caucho Technology公司开发。Hessian是一种基于二进制的轻量级、高效的跨语言序列化协议。Hessian2相较于原始Hessian…

迭代器+反向迭代器

接上节内容&#xff0c;反向迭代器&#xff08;aoto的价值显示的更明显&#xff09; int main() {string s1("hello world");//string::reverse_iterator rit s1.rbegin();auto rit s1.rbegin();while (rit ! s1.rend()){(*rit) 3;cout << *rit << &…

解决 Vscode不支持c++11的语法

问题&#xff1a; 解决方案&#xff1a; 1、按 CtrlShiftP 调出命令面板&#xff0c;输入 C/C: Edit Configurations (UI) 并选择它。这将打开 C/C 配置界面 2、打开 c_cpp_properties.json 文件 3、编辑 c_cpp_properties.json 4、保存 c_cpp_properties.json 文件。 关闭并…

软设之模板方法模式

设计模式中模板方法模式的意图是:定义一个操作中的算法骨架&#xff0c;而将一些步骤延迟到子类中&#xff0c;使得子类可以不改变一个算法的结构即可重新定义算法的某些特定步骤。 打个比方&#xff0c;比如要制作蛋糕&#xff0c;有准备材料&#xff0c;搅拌材料&#xff0c…

防火墙---带宽管理

防火墙的带宽管理&#xff1a;是指对防火墙设备的带宽进行管理和控制&#xff0c;以确保网络流量的合理分配和优化网络性能 带宽管理&#xff1a;是指限制网络流量的速率或控制网络流量的优先级&#xff0c;以确保网络的性能和可用性 核心&#xff1a; 带宽限制&#xff1a;…

在ArcGIS Pro中新建空图层的最快方法

01常规方法 一般情况下&#xff0c;如果我们想新建一个要素图层&#xff0c;常规方法是&#xff1a; 在目录框中&#xff0c;找一个gdb数据库&#xff0c;右键——新建——要素类&#xff1a; 设置好各种属性&#xff1a; 创建结果如下&#xff1a; 最后将要素类拖入地图中即…

Android 音频通道切换HDMI,蓝牙,喇叭

Android 音频通道切换HDMI,蓝牙,喇叭 private void speakerSound() {if (soundOutput.equals("speaker")) {return;}soundOutput "speaker";audoManager (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);audoManager.setMode(AudioMa…

GPU租赁教程/云主机使用教程/在线GPU环境部署/免费GPU/免费算力||运用云服务器,跑自己的深度学习模型(保姆级教程)

一、环境准备 pycharm professional&#xff08;需要pycharm专业版&#xff0c;社区版不行&#xff09;潞晨云账号访问链接&#xff0c;目前应该是最便宜的GPU租赁平台了&#xff0c;不知道之后会不会涨价&#xff0c;点我链接注册送10元代金券&#xff0c;能跑6个小时的4090w…

Java中的类加载机制详解

Java中的类加载机制详解 大家好&#xff0c;我是微赚淘客系统3.0的小编&#xff0c;是个冬天不穿秋裤&#xff0c;天冷也要风度的程序猿&#xff01; 1. 类加载机制概述 在Java中&#xff0c;类加载机制是Java虚拟机&#xff08;JVM&#xff09;运行时的重要组成部分&#x…

python-基础篇-运算符

文章目录 六、运算符相关的魔术方法1、比较运算符2、算术运算符 六、运算符相关的魔术方法 1、比较运算符 魔术方法说明__cmp__(self, other)如果该方法返回负数&#xff0c;说明 self < other; 返回正数&#xff0c;说明 self > other; 返回 0 说明 self other 。强烈…

所有权与生命周期:Rust 内存管理的哲学

所有权与生命周期&#xff1a;Rust内存管理的哲学 博主寄语引言&#xff1a;编程语言的内存管理困境与 Rust 的解决方案。所有权基本概念&#xff1a;资源的绝对主权生命周期的理解与应用&#xff1a;编译时的守护神借用与引用的精妙设计&#xff1a;安全与效率的和谐共舞Rust …

无人机之图传距离的决定因素

一、发射功率&#xff1a;图传设备的发射功率越大&#xff0c;信号能够传播的距离就越远 二、工作频段&#xff1a;不同频段具有不同的传播特性&#xff0c;一些频段在相同条件下可能具有更远的传输距离。 三、天线性能&#xff1a;优质的天线可以增强信号的发送和接收能力&a…

actual combat 35 —— es

一、windows中es执行步骤 参考&#xff1a;https://blog.csdn.net/qq_21197507/article/details/115076913 下es安装包下es前端gitHub代码&#xff0c;然后npm -i安装&#xff0c;npm run start 启动 二、遇到的问题 1. 第二步安装前端代码依赖报错 npm ERR! code ELIFECY…

【Harmony】SCU暑期实训鸿蒙开发学习日记Day1

关于ArkTS和ArkUI&#xff0c;基础语法请看&#x1f449;官方开发手册 系统学习后&#xff0c;聊聊几个点&#xff0c;面向刚学习这门语言的小白&#xff0c;用于巩固和回顾&#x1f60b; 目录 类型推断应用 函数相关 布局方式 线性布局 堆叠布局 网格布局 弹性布局 …

Python | Leetcode Python题解之第240题搜索二维矩阵II

题目&#xff1a; 题解&#xff1a; class Solution:def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:m, n len(matrix), len(matrix[0])x, y 0, n - 1while x < m and y > 0:if matrix[x][y] target:return Trueif matrix[x][y] > tar…