拓冰建站拓冰建站
首页 / 资讯中心 / 正文

深入解析 Transformers 中的 ProphetNet:面向序列到序列预训练的 Future N-gram 预测与 N-Stream 自注意力

深入解析 Transformers 中的 ProphetNet面向序列到序列预训练的 Future N-gram 预测与 N-Stream 自注意力【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformersProphetNet 是微软研究团队于 2020 年初提出的序列到序列Seq2Seq预训练模型其核心创新是用未来 n-gram 同时预测替代传统只预测下一个 token的训练目标。本文以当前仓库中 ProphetNet 模型文档 为主线结合 模型实现、配置类 与 分词器 等源码系统讲解其设计原理、配置参数、Tokenizer、模型家族 API、输出结构以及生成与微调用法帮助读者在 Transformers 生态中正确加载、配置与使用 ProphetNet。一、ProphetNet 是什么从单步预测到n-gram 未来预测ProphetNet 由 Yu Yan、Weizhen Qi、Yeyun Gong、Dayiheng Liu、Nan Duan、Jiusheng Chen、Ruofei Zhang、Ming Zhou 于 2020 年 1 月 13 日发表并在 2020 年 11 月 16 日被贡献进本仓库。它是一个标准的 encoder-decoder 结构模型但与经典的 Seq2Seq Transformer 关键区别在于传统模型每个时刻只优化下一步预测one-step ahead prediction而 ProphetNet 在每个时刻同时预测接下来连续的 n 个 tokenn-step ahead prediction即论文提出的future n-gram prediction自监督目标与之配套的是一种n-stream self-attentionn 流自注意力机制。根据论文摘要这种未来 n-gram 预测显式鼓励模型为后续 token 做规划plan for the future tokens并避免过拟合强局部相关性overfitting on strong local correlations。论文分别在 16GB 的基础数据集和 160GB 的大规模数据集上预训练 ProphetNet并在 CNN/DailyMail、Gigaword生成式摘要与 SQuAD 1.1问题生成基准上验证论文报告称相较使用同等规模预训练语料的模型取得了当时的新最优结果。在本仓库的 API 页面中ProphetNet 相关的核心模块完整可见文档结构覆盖ProphetNetConfig配置、ProphetNetTokenizer分词、四个专用输出类ProphetNetSeq2SeqLMOutput/ProphetNetSeq2SeqModelOutput/ProphetNetDecoderModelOutput/ProphetNetDecoderLMOutput以及五个模型入口类ProphetNetModel/ProphetNetEncoder/ProphetNetDecoder/ProphetNetForConditionalGeneration/ProphetNetForCausalLM。下文逐一展开。二、Usage Tips绝对位置编码与右侧 Padding模型文档给出两条关键的实用建议理解它们对正确使用 ProphetNet 至关重要绝对位置嵌入 右侧 paddingProphetNet 使用绝对位置嵌入absolute position embeddings因此通常建议在序列右侧而非左侧做 padding。这一点与代码实现吻合——ProphetNetPositionalEmbeddings 继承自nn.Embedding并通过padding_idx与torch.cumsum(attention_mask)的方式从 attention mask 推导位置 id同时将位置 clamp 在max_position_embeddings - 1以内右 padding 能保证真实 token 获得稳定连续的位置编码。解码器注意力机制的改造模型整体架构仍基于原始 Transformer但解码器中的标准自注意力被替换为main self-attention主流自注意力与self and n-stream (predict) self-attention自身与 n 流预测自注意力的组合——这正是 ProphetNet 解码器的精髓所在详见第六节源码解析。此外文档还列出了适用任务指南供做下游应用时参考因果语言建模任务指南、翻译任务指南、摘要任务指南。三、ProphetNetConfig核心配置参数详解ProphetNetConfig定义于 configuration_prophetnet.pymodel_type prophetnet。除了继承自PreTrainedConfig的通用字段外它还有四个对模型行为影响最大的ProphetNet 专属参数参数类型默认值含义ngramint2要同时预测的未来 token 数量。设为1时退化为传统语言模型只预测下一个 tokennum_bucketsint32每层注意力用于相对位置计算的分桶数量relative_max_distanceint128相对距离大于该值的会被放入最后一个桶截断策略disable_ngram_lossboolFalse若为True训练时只预测下一个 token仅计算主流损失epsfloat0.0损失计算中标签平滑的 epsilon 参数为0时不做标签平滑num_buckets与relative_max_distance共同决定相对位置注意力中桶的划分方式其分桶算法近距线性分桶、远距对数分桶与 T5 相对位置编码同源具体实现在建模源码的compute_relative_buckets中见第六节。除了上述专属字段配置文件还给出了与microsoft/prophetnet-large-uncased检查点对应的完整默认结构全部为类字段默认值词表与嵌入vocab_size30522、hidden_size1024、max_position_embeddings512、init_std0.02编码器num_encoder_layers12、num_encoder_attention_heads16、encoder_ffn_dim4096解码器num_decoder_layers12、num_decoder_attention_heads16、decoder_ffn_dim4096正则与激活dropout0.1、attention_dropout0.1、activation_dropout0.1、activation_functiongelu结构开关is_encoder_decoderTrue、add_cross_attentionTrue、tie_word_embeddingsTrue、use_cacheTrue特殊 token idpad_token_id0、bos_token_id1、eos_token_id2、decoder_start_token_id0。有一个易踩坑的设计配置类通过property暴露num_hidden_layers它只是num_encoder_layers的别名其 setter 会直接抛出NotImplementedError。也就是说不要试图用num_hidden_layers去修改层数必须分别设置num_encoder_layers与num_decoder_layers。另外attribute_map将通用别名num_attention_heads映射到num_encoder_attention_heads方便与其他模型配置保持接口一致。四、ProphetNetTokenizer基于 WordPiece 的分词器ProphetNetTokenizer定义于 tokenization_prophetnet.py其文档字符串明确说明它基于 WordPiece这与vocab_size30522的配置默认值彼此呼应。词表文件VOCAB_FILES_NAMES {vocab_file: prophetnet.tokenizer}即检查点中词表文件名固定为prophetnet.tokenizer由load_vocab加载大小写do_lower_case默认为True与 uncased 检查点一致如需保留大小写信息可显式传do_lower_caseFalse保存行为save_vocabulary在词表索引不连续时会写入告警信息提示vocabulary indices are not consecutive这是保存/重载词表时需要留意的边界情况。典型使用方式与其他PreTrainedTokenizer完全一致from transformers import AutoTokenizer tokenizer AutoTokenizer.from_pretrained(microsoft/prophetnet-large-uncased) inputs tokenizer(Studies have been shown that owning a dog is good for you, return_tensorspt) print(inputs.input_ids.shape)五、模型家族与输出类从通用模型到因果 LM5.1 五个模型入口类模型文档罗列了五个可直接实例化的类全部位于 modeling_prophetnet.py类定位说明ProphetNetModel完整 Encoder-Decoder同时包含编码器与解码器解码器含 n-gram 流返回主流与预测流隐藏态ProphetNetEncoder独立编码器可作为独立编码器使用例如加载patrickvonplaten/prophetnet-large-uncased-standalone检查点ProphetNetDecoder独立解码器独立解码器可携带或不携带cross-attention例如ProphetNetDecoder.from_pretrained(microsoft/prophetnet-large-uncased, add_cross_attentionFalse)ProphetNetForConditionalGeneration条件生成叠加语言建模头用于序列生成摘要、翻译、问题生成支持GenerationMixin与labels训练ProphetNetForCausalLM因果语言建模纯解码器因果 LM 形态其中ProphetNetEncoder/ProphetNetDecoder/ProphetNetModel/ProphetNetForConditionalGeneration/ProphetNetForCausalLM各自的forward均有完整文档字符串doc-builder 的[[autodoc]]自动抽取可直接在类上查看每个参数如input_ids、attention_mask、decoder_input_ids、decoder_attention_mask、encoder_outputs、past_key_values、labels等的完整说明与可运行示例。5.2 四个 ProphetNet 专用输出类由于解码器内部同时维护主流与ngram 预测流ProphetNet 的输出结构也与其他 Seq2Seq 模型不同专门定义了四个输出 dataclassProphetNetSeq2SeqLMOutput完整序列到序列 LM 头的输出。包含loss、logits主流的语言建模分数形状(batch_size, decoder_sequence_length, vocab_size)、logits_ngram预测流的分数形状(batch_size, ngram * decoder_sequence_length, vocab_size)以及两类各自独立的隐藏态与注意力权重decoder_hidden_states/decoder_ngram_hidden_states、decoder_attentions/decoder_ngram_attentions外加cross_attentions与编码器侧输出ProphetNetSeq2SeqModelOutput无 LM 头的纯模型输出核心是last_hidden_state主流与last_hidden_state_ngram预测流可选ProphetNetDecoderModelOutput独立解码器输出字段包含last_hidden_state、last_hidden_state_ngram、hidden_states/hidden_states_ngram、attentions/ngram_attentions、cross_attentionsProphetNetDecoderLMOutput解码器 LM 头输出包含loss、logits、logits_ngram及对应的隐藏态/注意力元组。可以看到一个贯穿全局的规律凡与 n-gram 预测流相关的张量其序列维度都会被放大 ngram 倍形状中出现ngram * decoder_sequence_length。预测流张量最终由前向函数统一 reshape/切分参与 loss 计算详见第六节。5.3 完整模型的最小使用示例ProphetNetModel的 docstring 给出了可运行的最小示例对应 modeling_prophetnet.pyfrom transformers import AutoTokenizer, ProphetNetModel tokenizer AutoTokenizer.from_pretrained(microsoft/prophetnet-large-uncased) model ProphetNetModel.from_pretrained(microsoft/prophetnet-large-uncased) # 编码器输入 input_ids tokenizer( Studies have been shown that owning a dog is good for you, return_tensorspt ).input_ids # Batch size 1 # 解码器输入部分译文前缀 decoder_input_ids tokenizer(Studies show that, return_tensorspt).input_ids # Batch size 1 outputs model(input_idsinput_ids, decoder_input_idsdecoder_input_ids) last_hidden_states outputs.last_hidden_state # 主流隐藏状态 last_hidden_states_ngram outputs.last_hidden_state_ngram # 预测流隐藏状态条件生成任务则用ProphetNetForConditionalGenerationfrom transformers import AutoTokenizer, ProphetNetForConditionalGeneration tokenizer AutoTokenizer.from_pretrained(microsoft/prophetnet-large-uncased) model ProphetNetForConditionalGeneration.from_pretrained(microsoft/prophetnet-large-uncased) input_ids tokenizer( Studies have been shown that owning a dog is good for you, return_tensorspt ).input_ids decoder_input_ids tokenizer(Studies show that, return_tensorspt).input_ids outputs model(input_idsinput_ids, decoder_input_idsdecoder_input_ids) logits_next_token outputs.logits # 用于预测下一个 token 的常规 logits logits_ngram_next_tokens outputs.logits_ngram # 用于预测第 2、3、… 个未来 token 的 logits从源码看ProphetNetForConditionalGeneration.forward会把解码器预测流的隐藏态先 reshape 为(batch_size, ngram, sequence_length, hidden_size)再过 LM 头lm_headnn.Linear(hidden_size, vocab_size, biasFalse)权重与词嵌入通过_tied_weights_keys绑定随后取第 0 个流作为主流的logits第 1 及以后的流拼接为logits_ngram当ngram 1时这正是多流并行预测在 API 层的体现。若传入labels则_compute_loss会在 ngram 维上同时优化多个预测流的损失利用ignore_index-100掩码并在disable_ngram_lossTrue时只回传下一 token 预测的主损失。六、源码级解析n-gram 掩码、双流注意力与相对位置桶原模型文档提到解码器把标准自注意力替换为main self-attention n-stream predict self-attention。在 modeling_prophetnet.py 中可以用三个关键函数/模块印证这一机制6.1ngram_attention_bias主从流注意力掩码的构造ngram_attention_bias(sequence_length, ngram, device, dtype)见 L44-L63一次性构造主流与预测流两部分的注意力偏置语义非常清晰主流掩码left_blockstream s只允许严格位于对角线下方的位置可见——源码注释直接写明Main-stream mask: streamsallows positions strictly below the1 - sdiagonal即主流保持因果/自回归可见性预测流掩码right_block每个流只允许关注各自的未来位置对角线上rows ! cols处被置为-inf从而让第 i 个流只学习从当前位置预测未来第 i 个位置这一专用职责两部分经torch.cat(..., dim2)拼接与解码器输入中主流 ngram 预测流的张量排布严格对齐。6.2ProphetNetNgramSelfAttention主从双流的前向计算解码器第 1 个残差块使用 ProphetNetNgramSelfAttention其forwardL563 起演示了双流注意力的完整数据流对输入做 Q/K/V 投影并除以head_dim ** 0.5归一化沿序列维把张量chunk为1 ngram份得到主流main_*与 ngram 个预测流predict_*主流按标准方式计算main_attn_weights叠加相对位置嵌入与因果attention_mask后 softmax得到主流注意力输出预测流则把每个流自己的 key/value 与主流 key/value 沿序列维拼接predict_key_states/predict_value_states长度为2 * sequence_length使得每个预测流既能看主流历史、又能看自己的专属未来位置注意力分数叠加predict_relative_pos_embeddings与extended_predict_attention_mask后 softmax最后把主流输出与 ngram 个预测流输出cat回(batch_size, (1ngram)*sequence_length, hidden_size)的单一张量向下层传递。6.3compute_relative_buckets相对位置桶编码相对位置注意力同样服务于主流与预测流两套位置关系compute_relative_bucketsL66-L90负责单个相对位置的分桶距离小于num_buckets // 2时线性精确分桶超过后改用对数分桶并截断到relative_max_distance对应桶——这就是num_buckets32、relative_max_distance128两个配置的落点compute_all_stream_relative_bucketsL93-L113为解码器同时计算两套桶主流基于position_ids两两相减预测流则基于cat((position_ids - 1, position_ids))与position_ids的差分别喂给get_main_relative_pos_embeddings与get_predict_relative_pos_embeddings通过torch.gather从relative_pos_embeddings形状含num_buckets维取出对应桶的嵌入。6.4 解码器的层结构与 ngram 流嵌入ProphetNetDecoderLayer 展示了三个残差块的经典排布第 1 个残差块ProphetNetNgramSelfAttentionLayerNorm自注意力含双流第 2 个残差块ProphetNetAttention作 cross-attention LayerNorm在add_cross_attentionTrue时启用负责编码器信息交互第 3 个残差块ProphetNetFeedForwardLayerNorm。值得注意的是 ProphetNetDecoder 初始化时除了word_embeddings与position_embeddings还会建立一个ngram_embeddings nn.Embedding(ngram, hidden_size, None)——它把当前处于第几个预测流这一序号也编码成向量参与计算是模型理解多流身份的直接证据。此外ProphetNetPreTrainedModel中supports_gradient_checkpointing True即支持梯度检查点以节省显存推理缓存上则使用Cachepast_key_values配合config.use_cacheTrue可加速自回归解码。七、工程周边检查点转换、注册表与测试权重转换脚本convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py 用于把 ProphetNet 原始实现产出的 PyTorch 检查点转换为 Transformers 的格式并保持与 WordPiece 词表、token id 体系的兼容自动映射与加载通过模型注册表与AutoConfig/AutoModel/AutoTokenizerdocstring 示例均用AutoTokenizer加载microsoft/prophetnet-large-uncased即可按model_typeprophetnet自动路由测试验证仓库提供了完整的测试覆盖——模型前向/生成行为见 test_modeling_prophetnet.py分词行为见 test_tokenization_prophetnet.py。若需修改或研究 ProphetNet 相关代码运行这两组测试可快速验证核心逻辑。八、应用建议与注意事项面向的任务形态ProphetNet 论文重点验证了生成式摘要CNN/DailyMail、Gigaword与问题生成SQuAD 1.1因此它最自然的落地形态是ProphetNetForConditionalGeneration而在纯解码器设定下可退化为ProphetNetForCausalLM。文档推荐配套阅读摘要、翻译、因果语言建模三份任务指南summarization.md、translation.md、language_modeling.md。ngram 参数的权衡ngram2是默认值可理解为当前 token 与下一 token并行预测加大 ngram 会带来更强的远期规划信号但会把注意力/损失计算量按1ngram放大。若只想按传统方式训练可设ngram1或disable_ngram_lossTrue。padding 位置由于绝对位置编码的特性输入应统一右侧 padding左侧 padding 会破坏位置编码的语义稳定性。不要设置num_hidden_layers如需调整网络规模请显式设置num_encoder_layers与num_decoder_layers否则会触发NotImplementedError。推理与训练的输出差异训练阶段logits_ngram提供多步预测的监督信号自回归生成GenerationMixin阶段以主流logits为主逐 token 采样同时预测流张量仍可被取出用于诊断或自定义损失。结语ProphetNet 用同时预测未来 n 个 token的预训练目标为 Seq2Seq 预训练提供了一个区别于next-token prediction的思路。在本文所述仓库中它已被完整地组件化从可配置 ngram 流数的 ProphetNetConfig到以 WordPiece 为基础的 ProphetNetTokenizer再到由ngram_attention_bias、双流自注意力、相对位置桶共同支撑的 modeling_prophetnet.py以及配套的转换脚本与测试。理解 main-stream 与 predict-stream 的协同关系是深入掌握 ProphetNet 推理与训练行为的关键。【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门