T5模型简介
引言
本文我们先学习一个T5(Text-To-Text Transfer Transformer)模型的基本概念,最后应用到文本摘要任务上作为实战。
T5模型
文本到文本Transformer模型的兴起
Colin Raffel1等人用统一的文本到文本Transformer探索迁移学习的极限。这次,T5团队想知道Transfomer能在多大程度上理解一门语言。
人类学会一门语言后,通过迁移学习可以应用到各种各样的NLP任务上。T5模型的核心想法是找到一个能像人类这样的抽象模型。
当我们人类交流时,我们总是从一个序列(A)开始,然后是另一个序列(B)。反过来,B成为另一个序列的起始序列,如图所示:
我们通过语言与我们称之为“文本的一个词或一组词交流。当我们试图理解一篇文章时,我们注意到句子中所有方向的单词。我们试图衡量每个单词的重要性。当我们不理解一个句子时,我们关注一个单词,然后查询句子中的其他关键词,以确定它们的意义和我们必须注意的地方。这就定义了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任务的统一格式:
统一的输入格式让一个Transformer模型产生一个结果序列,无论它是什么问题。许多 NLP 任务的输入和输出是统一的,如图所示:
这个统一的过程使得我们可以对广泛的任务使用相同的模型、超参数和优化器。
模型架构
T5团队着重于设计一个标准的输入格式来获取文本输出。而不想尝试从原始 Transformer衍生出新架构,例如像BERT的只有编码器或像GPT只有解码器。
T5使用的就是原始的Transformer架构,如上图。
T5保留了原始Transformer的大多数架构。但强调了一些关键的方面。此外,还对词汇和功能做了一些细微的改变。下面列出了T5模式的一些主要概念:
- 编码器和解码器仍保留在模型中。编码器和解码器层成为块(block),子层成为包含自注意层和前馈络的子组件(subcomponent)。像乐高一样,可以组装块和子组件来建立模型。Transformer组件是标准构件,可以用多种方式组装。
- 自注意是顺序无关的。使用矩阵的点积,而不是递归。它探索了一个序列中每个单词和其他单词之间的关系。在进行点积之前,将位置编码添加到单词的嵌入中。
- 原来的Transformer采用正弦和余弦习得位置嵌入。而T5使用相对位置嵌入。在 T5中,位置编码依赖于自注意的扩展来对成对关系进行比较。
- 位置编码是共享的,同时在模型的所有层中重新评估。
T5实现文本摘要
文本摘要抽取文本中的重要部分。我们会使用Hugging Face的包来进行实践。
我们可以搜索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_length
和max_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。
References
Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer ↩︎
Transformers for Natural Language Processing ↩︎
更多推荐
所有评论(0)