T5模型简介

引言

本文我们先学习一个T5(T ext-T o-T ext T ransfer T
ransformer)模型的基本概念,最后应用到文本摘要任务上作为实战。

T5模型

文本到文本Transformer模型的兴起

Colin
Raffel
1等人用统一的文本到文本Transformer探索迁移学习的极限。这次,T5团队想知道Transfomer能在多大程度上理解一门语言。

人类学会一门语言后,通过迁移学习可以应用到各种各样的NLP任务上。T5模型的核心想法是找到一个能像人类这样的抽象模型。

当我们人类交流时,我们总是从一个序列(A)开始,然后是另一个序列(B)。反过来,B成为另一个序列的起始序列,如图所示:

![](https://img-
blog.csdnimg.cn/img_convert/f7637e21686f6ae2630ade339a91254f.png)

我们通过语言与我们称之为“文本的一个词或一组词交流。当我们试图理解一篇文章时,我们注意到句子中所有方向的单词。我们试图衡量每个单词的重要性。当我们不理解一个句子时,我们关注一个单词,然后查询句子中的其他关键词,以确定它们的意义和我们必须注意的地方。这就定义了Transoformer的注意力层。

T5模型可以总结为文本到文本迁移的Transformer,这样,所有的NLP任务都可以被描述为文本到文本问题来解决。

前缀而不是任务特定的格式

Raffel 等人仍然有一个问题需要解决:
统一任务特定的格式。这个想法是为每个提交给Transformer的任务找到一种输入格式。这样,使用一种文本到文本的格式对所有类型的任务训练模型参数。

T5团队想到一个简单的解决方法:为输入序列增加前缀。这种前缀不仅仅是一个标签或像[CLS]这种用于分类的指示器。T5前缀包含Transformer需要解决的任务的本质。如下面的例子所示,前缀表达的意思包括:

  • translate English to German: + [sequence]:翻译任务
  • cola sentence: + [sequence]: CoLA语料库,微调BERT模型。
  • stsb sentence 1:+[sequence]:语义文本相似基准。自然语言推理和蕴涵是类似的问题。
  • summarize + [sequence]:文本摘要问题。

这样,我们得到了一种为广泛的NLP任务的统一格式:

![](https://img-
blog.csdnimg.cn/img_convert/66564eb7378c16f0b90d4081e5d1195c.png)

统一的输入格式让一个Transformer模型产生一个结果序列,无论它是什么问题。许多 NLP 任务的输入和输出是统一的,如图所示:

![](https://img-
blog.csdnimg.cn/img_convert/68fcc70d18d5937a5a4360aa0750a1aa.png)

这个统一的过程使得我们可以对广泛的任务使用相同的模型、超参数和优化器。

模型架构

T5团队着重于设计一个标准的输入格式来获取文本输出。而不想尝试从原始 Transformer衍生出新架构,例如像BERT的只有编码器或像GPT只有解码器。

![](https://img-
blog.csdnimg.cn/img_convert/9e0dafc7c7a0e698bd1d23c011edc27e.png)

T5使用的就是原始的Transformer架构,如上图。

T5保留了原始Transformer的大多数架构。但强调了一些关键的方面。此外,还对词汇和功能做了一些细微的改变。下面列出了T5模式的一些主要概念:

  • 编码器和解码器仍保留在模型中。编码器和解码器层成为块(block),子层成为包含自注意层和前馈络的子组件(subcomponent)。像乐高一样,可以组装块和子组件来建立模型。Transformer组件是标准构件,可以用多种方式组装。
  • 自注意是顺序无关的。使用矩阵的点积,而不是递归。它探索了一个序列中每个单词和其他单词之间的关系。在进行点积之前,将位置编码添加到单词的嵌入中。
  • 原来的Transformer采用正弦和余弦习得位置嵌入。而T5使用相对位置嵌入。在 T5中,位置编码依赖于自注意的扩展来对成对关系进行比较。
  • 位置编码是共享的,同时在模型的所有层中重新评估。

T5实现文本摘要

文本摘要抽取文本中的重要部分。我们会使用Hugging Face的包来进行实践。

![image-20220527105946297](https://img-
blog.csdnimg.cn/img_convert/af1bdd186b55a6009e1e4ed0ae6f45c4.png)

我们可以搜索T5,得到上面的结果。有:

  • base:基准模型,类似于 BERT BASE \text{BERT}_\text{BASE} BERTBASE​,包含12层和200M参数
  • small:更小的模型,6层和60M参数
  • large:12层和770M参数

这里我们选择t5-large。

初始化T5-large模型

首先安装需要的包:

pip install transformers
pip install sentencepiece==0.1.94

然后,导入需要的包:

from transformers import T5Tokenizer, T5ForConditionalGeneration, T5Config
import torch
import json

下载并加载模型和分词器:

model = T5ForConditionalGeneration.from_pretrained('t5-large')
tokenizer = T5Tokenizer.from_pretrained('t5-large')

探索T5模型

print(model.config)



T5Config {
  "_name_or_path": "t5-large",
  "architectures": [
    "T5WithLMHeadModel"
  ],
  "d_ff": 4096,
  "d_kv": 64,
  "d_model": 1024,
  "decoder_start_token_id": 0,
  "dropout_rate": 0.1,
  "eos_token_id": 1,
  "feed_forward_proj": "relu",
  "initializer_factor": 1.0,
  "is_encoder_decoder": true,
  "layer_norm_epsilon": 1e-06,
  "model_type": "t5",
  "n_positions": 512,
  "num_decoder_layers": 24,
  "num_heads": 16,
  "num_layers": 24,
  "output_past": true,
  "pad_token_id": 0,
  "relative_attention_max_distance": 128,
  "relative_attention_num_buckets": 32,
  "task_specific_params": {
    "summarization": {
      "early_stopping": true,
      "length_penalty": 2.0,
      "max_length": 200,
      "min_length": 30,
      "no_repeat_ngram_size": 3,
      "num_beams": 4,
      "prefix": "summarize: "
    },
    "translation_en_to_de": {
      "early_stopping": true,
      "max_length": 300,
      "num_beams": 4,
      "prefix": "translate English to German: "
    },
    "translation_en_to_fr": {
      "early_stopping": true,
      "max_length": 300,
      "num_beams": 4,
      "prefix": "translate English to French: "
    },
    "translation_en_to_ro": {
      "early_stopping": true,
      "max_length": 300,
      "num_beams": 4,
      "prefix": "translate English to Romanian: "
    }
  },
  "transformers_version": "4.19.2",
  "use_cache": true,
  "vocab_size": 32128
}

  "num_heads": 16,
  "num_layers": 24,

可以看到模型的基本参数,有16个头和24层。

我们也可以看到T5的实现,增加了什么前缀到输入序列。在这里 我们关注的文本摘要的前缀为"prefix": "summarize: "

我们还可以看到:

  • 使用了束搜索算法

  • 应用了早停法

  • 通过min_lengthmax_length控制样本长度

  • 应用长度惩罚

  • 确保不重复等于no_repeat_ngram_size的ngram

  • 词典大小:32128

我们也可以打印出模型:

print(model)



(5): T5Block(
        (layer): ModuleList(
          (0): T5LayerSelfAttention(
            (SelfAttention): T5Attention(
              (q): Linear(in_features=1024, out_features=1024, bias=False)
              (k): Linear(in_features=1024, out_features=1024, bias=False)
              (v): Linear(in_features=1024, out_features=1024, bias=False)
              (o): Linear(in_features=1024, out_features=1024, bias=False)
            )
            (layer_norm): T5LayerNorm()
            (dropout): Dropout(p=0.1, inplace=False)
          )
          (1): T5LayerCrossAttention(
            (EncDecAttention): T5Attention(
              (q): Linear(in_features=1024, out_features=1024, bias=False)
              (k): Linear(in_features=1024, out_features=1024, bias=False)
              (v): Linear(in_features=1024, out_features=1024, bias=False)
              (o): Linear(in_features=1024, out_features=1024, bias=False)
            )
            (layer_norm): T5LayerNorm()
            (dropout): Dropout(p=0.1, inplace=False)
          )
          (2): T5LayerFF(
            (DenseReluDense): T5DenseReluDense(
              (wi): Linear(in_features=1024, out_features=4096, bias=False)
              (wo): Linear(in_features=4096, out_features=1024, bias=False)
              (dropout): Dropout(p=0.1, inplace=False)
              (relu_act): ReLU()
            )
            (layer_norm): T5LayerNorm()
            (dropout): Dropout(p=0.1, inplace=False)
          )
        )
      )

比如,我们查看第5个块。

使用T5-large进行文本摘要

我们会创建一个摘要函数,只要传入任何文本就能得到摘要。然后通过几个例子进行实验。

创建摘要函数
device = torch.device('cuda')
model.to(device)

def summarize(text, max_length):
  '''
  text: 要生成摘要的文本
  max_length: 摘要的最大长度
  '''
  # 去掉多余的空格和换行符
  preprocess_text = text.strip().replace('\n','')
  # 准备前缀+文本
  t5_prepared_text = 'summarize: ' + preprocess_text
  print("Preprocessed and prepared text: \n", t5_prepared_text)

  # 分词
  tokenized_text = tokenizer.encode(t5_prepared_text, return_tensors="pt").to(device)
  # 进行文本摘要
  summary_ids = model.generate(tokenized_text,
                  num_beams=4,
                  no_repeat_ngram_size=2,
                  min_length=30,
                  max_length=max_length,
                  early_stopping=True)
  # 将id转换为输出 summary_ids.shape = [1, 50]
  output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
  return output
一般主题样本
text ="""
The United States Declaration of Independence was the first Etext
released by Project Gutenberg, early in 1971.  The title was stored
in an emailed instruction set which required a tape or diskpack be
hand mounted for retrieval.  The diskpack was the size of a large
cake in a cake carrier, cost $1500, and contained 5 megabytes, of
which this file took 1-2%.  Two tape backups were kept plus one on
paper tape.  The 10,000 files we hope to have online by the end of
2001 should take about 1-2% of a comparably priced drive in 2001.
"""
print("Number of characters:",len(text))
summary=summarize(text,50)
print ("\n\nSummarized text: \n",summary)



Number of characters: 534
Preprocessed and prepared text: 
 summarize: The United States Declaration of Independence was the first Etextreleased by Project Gutenberg, early in 1971.  The title was storedin an emailed instruction set which required a tape or diskpack behand mounted for retrieval.  The diskpack was the size of a largecake in a cake carrier, cost $1500, and contained 5 megabytes, ofwhich this file took 1-2%.  Two tape backups were kept plus one onpaper tape.  The 10,000 files we hope to have online by the end of2001 should take about 1-2% of a comparably priced drive in 2001.


Summarized text: 
 the united states declaration of independence was the first etext published by project gutenberg, early in 1971. the 10,000 files we hope to have online by the end of2001 should take about 1-2% of a comparably priced drive in
权利法案样本
#Bill of Rights,V
text ="""
No person shall be held to answer for a capital, or otherwise infamous crime,
unless on a presentment or indictment of a Grand Jury, except in cases arising
 in the land or naval forces, or in the Militia, when in actual service
in time of War or public danger; nor shall any person be subject for
the same offense to be twice put in jeopardy of life or limb;
nor shall be compelled in any criminal case to be a witness against himself,
nor be deprived of life, liberty, or property, without due process of law;
nor shall private property be taken for public use without just compensation.
"""
print("Number of characters:",len(text))
summary=summarize(text,50)
print ("\n\nSummarized text: \n",summary)



Number of characters: 591
Preprocessed and prepared text: 
 summarize: No person shall be held to answer for a capital, or otherwise infamous crime,unless on a presentment or indictment of a Grand Jury, except in cases arising in the land or naval forces, or in the Militia, when in actual servicein time of War or public danger; nor shall any person be subject forthe same offense to be twice put in jeopardy of life or limb;nor shall be compelled in any criminal case to be a witness against himself,nor be deprived of life, liberty, or property, without due process of law;nor shall private property be taken for public use without just compensation.


Summarized text: 
 no person shall be held to answer for a capital, or otherwise infamous crime, unless ona presentment or indictment ofa Grand Jury. nor shall any person be subject for the same offense to be twice put

这个样本非常重要,因为它显示了任何Transformer模型或其他 NLP
模型在面对这样的文本时所面临的限制。我们不能仅仅提供总是有效的样本,并让用户相信Transformer已经解决了我们所面临的所有 NLP
挑战,不管它们有多么创新。

也许我们应该提供更长的文本来总结,使用其他参数,或使用更大的模型,或改变T5模型的结构。然而,无论多么努力地尝试使用 NLP
模型来总结一个复杂的文本,总是会发现模型无法总结的文档。

所以需要更多的耐心去优化模型2。

👉AI大模型学习路线汇总👈

大模型学习路线图,整体分为7个大的阶段:(全套教程文末领取哈)

第一阶段: 从大模型系统设计入手,讲解大模型的主要方法;

第二阶段: 在通过大模型提示词工程从Prompts角度入手更好发挥模型的作用;

第三阶段: 大模型平台应用开发借助阿里云PAI平台构建电商领域虚拟试衣系统;

第四阶段: 大模型知识库应用开发以LangChain框架为例,构建物流行业咨询智能问答系统;

第五阶段: 大模型微调开发借助以大健康、新零售、新媒体领域构建适合当前领域大模型;

第六阶段: 以SD多模态大模型为主,搭建了文生图小程序案例;

第七阶段: 以大模型平台应用与开发为主,通过星火大模型,文心大模型等成熟大模型构建大模型行业应用。

👉大模型实战案例👈

光学理论是没用的,要学会跟着一起做,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

在这里插入图片描述

👉大模型视频和PDF合集👈

观看零基础学习书籍和视频,看书籍和视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
在这里插入图片描述
在这里插入图片描述

👉学会后的收获:👈

• 基于大模型全栈工程实现(前端、后端、产品经理、设计、数据分析等),通过这门课可获得不同能力;

• 能够利用大模型解决相关实际项目需求: 大数据时代,越来越多的企业和机构需要处理海量数据,利用大模型技术可以更好地处理这些数据,提高数据分析和决策的准确性。因此,掌握大模型应用开发技能,可以让程序员更好地应对实际项目需求;

• 基于大模型和企业数据AI应用开发,实现大模型理论、掌握GPU算力、硬件、LangChain开发框架和项目实战技能, 学会Fine-tuning垂直训练大模型(数据准备、数据蒸馏、大模型部署)一站式掌握;

• 能够完成时下热门大模型垂直领域模型训练能力,提高程序员的编码能力: 大模型应用开发需要掌握机器学习算法、深度学习框架等技术,这些技术的掌握可以提高程序员的编码能力和分析能力,让程序员更加熟练地编写高质量的代码。

👉获取方式:

😝有需要的小伙伴,可以保存图片到wx扫描二v码免费领取【保证100%免费】🆓

在这里插入图片描述

  • 13
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值