自监督方法已经成功应用于许多不同类型的 NLP 任务。通过随机屏蔽一部分单词子集并训练去噪自动编码器来恢复文本,这种方法已被证明是最有效的。最近的研究通过增强掩蔽分布、调整掩蔽预测顺序以及替换掩蔽标记的上下文进一步提升了模型的性能。
尽管这些方法很有前景,但通常它们只适用于少数特定的任务(如跨度预测、跨度创建等)。
准备工作
为了跟上本文的内容,你需要具备一定的 Python 编程经验,并对深度学习有基础了解。我们假设所有读者都可以使用性能足够强大的机器,以便运行提供的代码。
如果你没有 GPU 资源,我们建议通过云服务获取支持。很多云服务提供商都提供 GPU 资源。例如,DigitalOcean 的H100 GPU 云服务器。
如果你是初学者并想开始使用 Python 代码,我们建议参考这份初学者指南来设置系统并准备运行教程。
NLP 中的 BART Transformer 模型是什么?
本文介绍了 BART,一种结合双向和自回归 Transformer 的预训练方法。BART 是使用序列到序列范式的去噪自动编码器,能够用于多种应用。BART 的预训练过程包括两个阶段:(1)使用任意噪声函数对文本进行破坏,(2)学习序列到序列模型来重建原始文本。
BART 基于 Transformer 的神经机器翻译架构,可以被看作是 BERT(由于其双向编码器)、GPT(使用从左到右的解码器)以及其他当代预训练方法的泛化版本。
除了在理解任务中的优势外,BART 的效率随着文本生成的微调而提高。它在各种抽象对话、问答和摘要任务中产生了新的最先进结果,与 RoBERTa 的性能相当,并且在 GLUE 和 SQuAD 上具有可比的训练资源。
架构
除了将 ReLU 激活函数更改为 GeLU 并将参数初始化为 (0, 0.02) 之外,BART 基本遵循了标准的序列到序列 Transformer 设计 (Vaswani 等人,2017)。基础模型的编码器和解码器各有六层,而大型模型中则各有十二层。
与 BERT 架构类似,但有两个主要区别:(1) 在 BART 中,解码器的每一层都会对编码器的最终隐藏层执行交叉注意,这与典型的 Transformer 序列到序列模型相同;(2) 在 BART 中,在单词预测之前没有额外的前馈网络,而 BERT 中有。
预训练 BART
为了训练 BART,我们首先对文档进行扰乱,然后优化重建损失,即解码器输出与原始文档之间的交叉熵。与传统的去噪自动编码器不同,BART 适用于各种类型的文档扰乱。
在最极端的情况下,BART 可能会丢失所有源信息,这类似于语言模型。研究者尝试了多种旧有和新颖的转换方法,并认为在此基础上仍有很大的创新空间。在下文中,我们将概述他们使用的转换方法并提供一些示例。下方是转换方法的摘要,并附有一些结果图示。
- 标记掩码:参考 BERT 的方法,随机采样标记并将其替换为 MASK 元素。
- 标记删除:随机删除输入中的标记。与标记掩码不同,模型必须预测哪些位置缺少标记。
- 文本填充:采样一些文本跨度,跨度长度根据泊松分布(λ = 3)确定。每个跨度都用 MASK 标记替换。该方法教会模型预测缺失的标记数量。
- 句子排列:根据句号将文档分割为句子,然后将这些句子随机排列。
- 文档旋转:随机选择一个标记,并将文档旋转,使其以该标记开头。此任务训练模型识别文档的开头。
微调 BART
BART 在后续处理步骤中生成的表示有几种潜在用途:
- 序列分类任务:对于序列分类问题,相同的输入被提供给编码器和解码器,最后一个解码器标记的最终隐藏状态被输入到新的多类线性分类器中。
- 标记分类任务:在标记分类任务中,编码器和解码器都将整个文档作为输入,解码器的顶部隐藏状态用来推导出每个单词的表示。标记的分类依赖于这些表示进行操作。
- 序列生成任务:对于像抽象问题回答和文本摘要这样的序列生成任务,BART 的自回归解码器可以直接进行微调。这些任务与去噪预训练目标密切相关,因为它们都涉及对输入数据的复制和随后操作。在这种情况下,输入序列被送入编码器,而解码器则以自回归的方式生成输出序列。
- 机器翻译:研究者还探讨了使用 BART 增强机器翻译解码器,将外语翻译为英语的可能性。使用预训练的编码器已被证明有助于改进模型,但将预训练的语言模型应用于解码器的效果较为有限。通过使用从双语文本中学到的一组编码器参数,研究人员展示了如何将整个 BART 模型用作机器翻译的预训练解码器。具体来说,他们用一个随机初始化的全新编码器替换了 BART 编码器的嵌入层。当模型从头开始训练时,新编码器会学习将外语词汇映射到 BART 可以翻译成英语的输入格式。训练的两个阶段中,交叉熵损失会从 BART 模型的输出反向传播到源编码器。在第一阶段,他们固定了 BART 的大部分参数,只更新随机初始化的源编码器、BART 的位置嵌入,以及 BART 编码器第一层的自注意力输入投影矩阵。接下来,他们对所有模型参数进行了有限次数的训练迭代。
用于文本摘要的 BART 模型
研究人员或记者往往需要花费大量时间筛选互联网上的长篇信息,以找到所需内容。使用摘要或释义提要,可以快速浏览长篇文献的重点内容,从而节省时间和精力。
借助 Transformer 模型,可以自动完成文本摘要这一 NLP 任务。实现这一目标有两种方法:提取式和抽象式摘要。提取式摘要是指从文本中找到最重要的陈述并将其提取出来,这可以看作是一种信息检索。相比之下,抽象式摘要更具挑战性,它试图理解整个材料,并通过释义文本来概括其要点。抽象式摘要任务通常由像 BART 这样的 Transformer 模型执行。
通过 HuggingFace 平台,你可以快速轻松地访问数千个预训练和微调过的 Transformer 模型(包括 BART)。在 HuggingFace 模型探索器网站上,你可以为文本摘要任务选择一个量身定制的 BART 模型。每个模型都包含其配置和训练的详细说明。对于初学者来说,bart-large-cnn 模型是一个不错的选择。让我们来看一下如何使用它。你可以通过访问 HuggingFace 安装页面或运行 pip install transformers 来开始。接下来,我们将按照以下三个简单步骤创建文本摘要:
from transformers import pipeline
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
首先应加载 Transformers 模型管道。管道中的模块通过命名任务和模型来定义。使用术语“摘要”,模型称为“facebook/bart-large-xsum”。如果我们想尝试与标准新闻数据集不同的东西,我们可以使用 Extreme Summary (XSum) 数据集。该模型经过专门训练以生成单句摘要。
最后一步是构建输入序列并使用 summaryr() 管道对其进行测试。就标记而言,还可以使用函数的可选 max_length 和 min_length 参数调整摘要长度。
from transformers import pipeline
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
ARTICLE = """ New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York.
A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.
Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared "I do" five more times, sometimes only within two weeks of each other.
In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her "first and only" marriage.
Barrientos, now 39, is facing two criminal counts of "offering a false instrument for filing in the first degree," referring to her false statements on the
2010 marriage license application, according to court documents.
Prosecutors said the marriages were part of an immigration scam.
On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further.
After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective
Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.
All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say.
Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.
Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted.
The case was referred to the Bronx District Attorney\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\'s
Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt, Turkey, Georgia, Pakistan and Mali.
Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force.
If convicted, Barrientos faces up to four years in prison. Her next court appearance is scheduled for May 18.
"""
print(summarizer(ARTICLE, max_length=130, min_length=30, do_sample=False))
Output:
[{'summary_text': 'Liana Barrientos, 39, is charged with two counts of "offering a false instrument for filing in the first degree" In total, she has been married 10 times, with nine of her marriages occurring between 1999 and 2002. She is believed to still be married to four men.'}]
另一种选择是使用 BartTokenizer 从文本序列生成标记,并使用BartForConditionalGeneration 进行总结。
# Importing the model
from transformers import BartForConditionalGeneration, BartTokenizer, BartConfig
As a pre-trained model, " bart-large-cnn" is optimized for the summary job.
The **from_pretrained()** function is used to load the model, as seen below.
# Tokenizer and model loading for bart-large-cnn
tokenizer=BartTokenizer.from_pretrained('facebook/bart-large-cnn')
model=BartForConditionalGeneration.from_pretrained('facebook/bart-large-cnn')
假设你需要对上述示例的文本进行摘要。你可以使用 tokenizer 的 batch_encode_plus() 功能来实现。调用时,该方法会生成一个字典,用于存储编码序列或序列对,以及任何提供的附加信息。
如何限制返回的最短序列?
你可以通过在 batch_encode_plus() 中设置 max_length 参数来限制返回的序列长度。为了获取摘要的输出 ID,我们将 input_ids 提供给 model.generate() 函数。
# Transmitting the encoded inputs to the model.generate() function
inputs = tokenizer.batch_encode_plus([ARTICLE],return_tensors='pt')
summary_ids = model.generate(inputs['input_ids'], num_beams=4, max_length=150, early_stopping=True)
原文摘要已通过 model.generate() 方法生成为 id 序列。函数 model.generate() 有许多参数,其中包括:
- input_ids:用于生成提示的序列。
- max_length:要生成的序列的最大长度。介于 min_length 和无穷大之间。默认为 20。
- min_length:要生成的序列的最小长度。介于 0 和无穷大之间。默认为 0。
- num_beams:用于波束搜索的波束数。必须介于 1 和无穷大之间。1 表示无波束搜索。默认为 1。
- early_stopping:如果设置为 True,则当每个批次至少完成 num_beams 个句子时,波束搜索将停止。
可以使用 decrypt() 函数将 ids 序列转换为纯文本。
# Decoding and printing the summary
summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
print(summary)
解码函数会将一串 token id 列表转换为一串字符串。它接受多个参数,其中我们将提到两个:
- token_ids:标记化输入 id 列表。
- skip_special_tokens:是否在解码过程中删除特殊 token。
结果,我们得到:
Liana Barrientos, 39, is charged with two counts of offering a false instrument for filing in the first degree. In total, she has been married 10 times, with nine of her marriages occurring between 1999 and 2002. At one time, she was married to eight men at once, prosecutors say.
使用 ktrain 通过 BART 汇总文档
ktrain 是一个 Python 包,可减少实现机器学习所需的代码量。它封装了 TensorFlow 和其他库,旨在让非专家也能使用尖端的 ML 模型,同时满足该领域专家的需求。借助 ktrain 的精简界面,您只需三四个“命令”或几行代码即可处理各种各样的问题,无论处理的数据是文本、视觉、图形还是表格。
使用 transformers 库中预先训练的 BART 模型,ktrain 可以汇总文本。首先,我们将创建 TransformerSummarizer 实例来执行实际的汇总。(请注意,使用此功能需要安装 PyTorch。)
from ktrain.text.summarization import TransformerSummarizer
ts = TransformerSummarizer()
让我们继续写一篇文章:
article = """ Saturn orbiter and Titan atmosphere probe. Cassini is a joint
NASA/ESA project designed to accomplish an exploration of the Saturnian
system with its Cassini Saturn Orbiter and Huygens Titan Probe. Cassini
is scheduled for launch aboard a Titan IV/Centaur in October of 1997.
After gravity assists of Venus, Earth and Jupiter in a VVEJGA
trajectory, the spacecraft will arrive at Saturn in June of 2004. Upon
arrival, the Cassini spacecraft performs several maneuvers to achieve an
orbit around Saturn. Near the end of this initial orbit, the Huygens
Probe separates from the Orbiter and descends through the atmosphere of
Titan. The Orbiter relays the Probe data to Earth for about 3 hours
while the Probe enters and traverses the cloudy atmosphere to the
surface. After the completion of the Probe mission, the Orbiter
continues touring the Saturnian system for three and a half years. Titan
synchronous orbit trajectories will allow about 35 flybys of Titan and
targeted flybys of Iapetus, Dione and Enceladus. The objectives of the
mission are threefold: conduct detailed studies of Saturn's atmosphere,
rings and magnetosphere; conduct close-up studies of Saturn's
satellites, and characterize Titan's atmosphere and surface."""
We can now summarize this article by using TransformerSummarizer instance:
ts.summarize(article)
结论
在深入研究 BART 架构和训练数据之前,本文概述了 BART 试图解决的挑战以及导致其出色表现的方法。我们还查看了使用 HuggingFace、ktrain 和 BART 的 Python 实现的演示推理示例。这篇理论和代码回顾将为您提供一个很好的开端,让您能够在 Python 中构建一个强大的基于 Transformer 的 seq2seq 模型。
DigitalOcean GPU 云服务是专注 AI 模型训练的云 GPU 服务器租用平台,提供了包括 A5000、A6000、H100 等强大的 GPU 和 IPU 实例,以及透明的定价,可以比其他公共云节省高达70%的计算成本。如果你感兴趣,希望了解更多可以 联系 DigitalOcean 中国区独家战略合作伙伴卓普云。