首页
/ Transformers 中 BigBirdPegasus 全解析:面向超长文本摘要的稀疏注意力序列到序列模型

Transformers 中 BigBirdPegasus 全解析:面向超长文本摘要的稀疏注意力序列到序列模型

2026-09-06 18:41:33作者:江焘钦

BigBirdPegasus 是 🤗 Transformers 内置的一个 encoder-decoder(sequence-to-sequence)Transformer 模型,专为长输入文本摘要设计。它把 BigBird 的稀疏注意力机制与 Pegasus 的"整句掩码式缺口序列生成(Gap Sentence Generation, GSG)"预训练目标相结合,使模型能够在内存可控的前提下捕捉超长文档的全局上下文。读完本文,你将掌握该模型的架构设计动机、全部关键配置参数及其底层实现细节,并能直接用 AutoModel、bitsandbytes 量化等 API 完成大文档摘要推理。

本文以仓库文档 docs/source/en/model_doc/bigbird_pegasus.md 为主线,并对照核心源码 configuration_bigbird_pegasus.pymodeling_bigbird_pegasus.py 与测试套件 test_modeling_bigbird_pegasus.py 逐一展开,帮助你既"会用"又"懂原理"。

模型概览与设计动机

BigBirdPegasus 本质上是一条"长文档友好"的 Pegasus 流水线:

  • 骨架继承自 BigBird:编码器中的自注意力使用 block-sparse(块稀疏)模式,将原本 O(n2) 的全注意力复杂度大幅降低,从而能处理更长的输入序列。BigBird 自身的完整介绍可参考 docs/source/en/model_doc/big_bird.md
  • 预训练目标来自 Pegasus:Pegasus 提出 GSG——训练时把文档中的整句掩码掉,让模型在文档中"填空",从而学会区分冗余与核心信息。Pegasus 模型家族参见 docs/source/en/model_doc/pegasus.md

正是"长上下文记忆能力 + 摘要预训练目标"的组合,使 BigBirdPegasus 在处理超长输入摘要时能超越同规模的 base Pegasus 模型。

  • 该模型由 vasudevgupta 贡献到本仓库,原始论文于 2020-07-28 发布,模型于 2021-05-07 合入 Transformers。
  • 全部原始 BigBirdPegasus 检查点由 Google 组织发布,可在 google/bigbird-pegasus-* 命名空间下找到;例如 google/bigbird-pegasus-large-arxivgoogle/bigbird-pegasus-large-pubmed(后者被用作本仓库集成测试的模型 ID,见 test_modeling_bigbird_pegasus.py 中的 MODEL_ID)。

BigBirdPegasusConfig:核心配置参数与默认值

BigBirdPegasus 的配置类定义于 configuration_bigbird_pegasus.pymodel_typebigbird_pegasus。它复用了 BART 风格的 encoder-decoder 通用结构(attribute_maphidden_size 映射到 d_modelnum_hidden_layers 映射到 encoder_layers 等),因此很多参数命名沿袭 BART/Pegasus。

默认架构超参(large 检查点基线)

下表来自配置类的类属性默认值:

参数 默认值 含义
vocab_size 96103 词表大小
d_model 1024 隐藏层维度
encoder_layers / decoder_layers 16 / 16 编码器/解码器层数
encoder_attention_heads / decoder_attention_heads 16 / 16 注意力头数
encoder_ffn_dim / decoder_ffn_dim 4096 / 4096 FFN 中间维度
max_position_embeddings 4096 绝对位置嵌入的最大位置数
activation_function gelu_new 激活函数
dropout 0.1 全连接隐藏层 dropout
attention_dropout 0.0 注意力概率 dropout
activation_dropout 0.0 FFN 激活后 dropout
init_std 0.02 初始化标准差
scale_embedding True 是否对嵌入乘以 dmodel\sqrt{d_{model}}
use_cache True 解码时是否缓存 K/V
is_encoder_decoder True 标记为 seq2seq 模型
tie_word_embeddings True 编码器/解码器/输出层共享词嵌入
decoder_start_token_id 2 解码起始 token
pad_token_id / bos_token_id / eos_token_id 0 / 2 / 1 特殊 token ID

稀疏注意力专属参数

与普通 seq2seq 模型最关键的差异是下面三个仅作用于编码器的参数:

参数 默认值 说明
attention_type "block_sparse" 编码器注意力模式。可选 "original_full"O(n2)O(n^2) 全注意力)或 "block_sparse"(论文提出的 O(n)O(n) 稀疏注意力)
block_size 64 每个块的 token 数,仅在 block_sparse 模式下生效
num_random_blocks 3 每个 query 额外关注的随机块数量,仅在 block_sparse 模式下生效
use_bias False Q/K/V 线性投影是否带 bias(当前配置类默认值为 False

一个值得注意的工程细节:当序列长度较长、需要做自回归或大 batch 推理时,keys_to_ignore_at_inference = ["past_key_values"] 保证配置序列化不受 KV 缓存干扰。创建配置与随机初始化模型的快速方式如下(配置类 docstring 中的官方示例):

from transformers import BigBirdPegasusConfig, BigBirdPegasusModel

# 初始化一个 bigbird-pegasus 风格配置
configuration = BigBirdPegasusConfig()

# 用该配置初始化随机权重模型
model = BigBirdPegasusModel(configuration)

# 取回配置
configuration = model.config

源码视角:block-sparse 注意力是如何实现的

若想真正理解 BigBirdPegasus 的 Note 约束,需要进入 modeling_bigbird_pegasus.py(约 2390 行)一探究竟。编码器层 BigBirdPegasusEncoderLayer 内部根据 attention_type 在普通全注意力 BigBirdPegasusSelfAttention 与块稀疏注意力 BigBirdPegasusBlockSparseAttention(从 BigBird 模块复制改写而来)之间切换。

每个 query 关注的三种 token 集合

bigbird_block_sparse_attention 方法(modeling 文件 L276 起)注释中明确了 ITC(Individual Token Component,原论文实现)的配置:

  • global tokens(全局 token):序列最前 2 个块,与全序列交互;
  • window tokens(滑窗 token):每侧 3 个块(相邻窗口,即当前块 + 前后各 1 块,配合移位技巧实现滑窗),窗口大小只能通过 block_size 调整;
  • random tokens(随机 token)num_random_blocks 个随机挑选的块(默认 3)。

代码按 q[0]、q[1]、q[2:-2]、q[-2]、q[-1] 分成了 5 个计算段,分别处理首/尾全局块、滑窗段与倒数第二个块,这也是块稀疏注意力的核心实现技巧。

随机块方案是按层种子(seed)与块索引规划生成的:_get_rand_attn_plan 规划每个块的随机邻居数,_bigbird_block_rand_mask/_bigbird_block_rand_mask_with_head 生成掩码。若序列长度为论文中的 1024 / 3072 / 4096,则直接复用论文中的随机注意力计划,保证与原版结果一致。模型内部还通过 _pad_to_block_size 自动把序列补齐到 block_size 的整数倍再切块计算,前向结束后再裁掉补零部分。

何时自动退化为全注意力

编码器前向中存在一个隐式的安全阀(modeling 文件 L1532-L1551):要正确使用 block-sparse,序列至少需要覆盖全部全局 token(2 × block_size)、最小滑窗 token(3 × block_size)以及随机 token(2 × num_random_blocks × block_size),即

max_tokens_to_attend = (5 + 2 * config.num_random_blocks) * config.block_size

input_shape[1] <= max_tokens_to_attend 时,模型会打印 warning 并调用 set_attention_type("original_full") 自动切换到全注意力——默认配置下该阈值为 (5+2×3)×64=704(5+2\times3)\times64=704 个 token。这就是官方文档"输入序列小于 1024 时推荐使用 original_full,稀疏模式在小输入上收益有限"这条建议的底层原因。

解码器:仍是标准因果注意力

稀疏化只作用于编码器(配置注释明确写着 # only for encoder)。解码器的自注意力与交叉注意力 BigBirdPegasusDecoderAttention 依旧是标准实现,因为解码是逐 token 自回归的,序列较短,稀疏化收益有限。此外:

  • 编码器与解码器共享词嵌入 shared = BigBirdPegasusScaledWordEmbedding(...)scale_embedding=True 时嵌入会乘以 dmodel\sqrt{d_{model}}
  • 位置编码使用 BigBirdPegasusLearnedPositionalEmbedding(可学习绝对位置嵌入),这也正是"输入必须右侧 padding"约束的来源;
  • 训练时若未显式传入 decoder_input_idsBigBirdPegasusModel.forward 会调用 shift_tokens_right 自动把 input_ids 右移一位、首位填入 decoder_start_token_id(modeling 文件 L60-L73 与 L1868-L1880)。

快速上手:用 AutoModel 完成长文档摘要

官方文档给出了最简洁的推理路径——用 AutoModelForSeq2SeqLM 加载大模型检查点并配合 device_map="auto" 自动分配设备:

from transformers import AutoModelForSeq2SeqLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("google/bigbird-pegasus-large-arxiv")
model = AutoModelForSeq2SeqLM.from_pretrained(
    "google/bigbird-pegasus-large-arxiv",
    device_map="auto",
)

input_text = """Plants are among the most remarkable and essential life forms on Earth, possessing a unique ability to produce their own food through a process known as photosynthesis. This complex biochemical process is fundamental not only to plant life but to virtually all life on the planet.
Through photosynthesis, plants capture energy from sunlight using a green pigment called chlorophyll, which is located in specialized cell structures called chloroplasts. In the presence of light, plants absorb carbon dioxide from the atmosphere through small pores in their leaves called stomata, and take in water from the soil through their root systems.
These ingredients are then transformed into glucose, a type of sugar that serves as a source of chemical energy, and oxygen, which is released as a byproduct into the atmosphere. The glucose produced during photosynthesis is not just used immediately; plants also store it as starch or convert it into other organic compounds like cellulose, which is essential for building their cellular structure.
This energy reserve allows them to grow, develop leaves, produce flowers, bear fruit, and carry out various physiological processes throughout their lifecycle."""
input_ids = tokenizer(input_text, return_tensors="pt").to(model.device)

output = model.generate(**input_ids, cache_implementation="static")
print(tokenizer.decode(output[0], skip_special_tokens=True))

要点解读:

  • 分词器必须使用 PegasusTokenizer(BigBirdPegasus 与其共享 SentencePiece 词表);
  • 文本通过 tokenizer 转为张量后直接喂给 generate,其中 cache_implementation="static" 使用静态缓存来减少解码期的缓存分配开销;
  • 该模型文档同时展示了通过 Pipeline(如 summarization 任务)与命令行两种方式调用;使用 AutoModel 系列(见 model_doc/auto.md)的好处是可以按 AutoModelForSeq2SeqLM 自动匹配架构。

此外,文档导航中的模型页面大列表里挂载了 BigBirdPegasusConfigBigBirdPegasusModelBigBirdPegasusForConditionalGenerationBigBirdPegasusForSequenceClassificationBigBirdPegasusForQuestionAnsweringBigBirdPegasusForCausalLM 等完整 API 的 autodoc 说明,每个类的 forward 签名与返回对象都可在对应源码与页面中找到。

量化加载:用 bitsandbytes 降低显存占用

large 级别检查点(d_model=1024、16 层、双塔结构)权重较大,量化是把权重表示为更低精度以缓解内存压力的直接手段。官方文档给出的 bitsandbytes int4 示例(完整量化后端列表参见 docs/source/en/quantization/overview.md,bitsandbytes 详细用法见 docs/source/en/quantization/bitsandbytes.md):

import torch

from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_quant_type="nf4",
)
model = AutoModelForSeq2SeqLM.from_pretrained(
    "google/bigbird-pegasus-large-arxiv",
    device_map="auto",
    quantization_config=quantization_config,
)

tokenizer = AutoTokenizer.from_pretrained("google/bigbird-pegasus-large-arxiv")

input_text = """Plants are among the most remarkable and essential life forms on Earth, possessing a unique ability to produce their own food through a process known as photosynthesis. This complex biochemical process is fundamental not only to plant life but to virtually all life on the planet.
Through photosynthesis, plants capture energy from sunlight using a green pigment called chlorophyll, which is located in specialized cell structures called chloroplasts. In the presence of light, plants absorb carbon dioxide from the atmosphere through small pores in their leaves called stomata, and take in water from the soil through their root systems.
These ingredients are then transformed into glucose, a type of sugar that serves as a source of chemical energy, and oxygen, which is released as a byproduct into the atmosphere. The glucose produced during photosynthesis is not just used immediately; plants also store it as starch or convert it into other organic compounds like cellulose, which is essential for building their cellular structure.
This energy reserve allows them to grow, develop leaves, produce flowers, bear fruit, and carry out various physiological processes throughout their lifecycle."""
input_ids = tokenizer(input_text, return_tensors="pt").to(model.device)

output = model.generate(**input_ids, cache_implementation="static")
print(tokenizer.decode(output[0], skip_special_tokens=True))

其中 load_in_4bit=True 把权重压到 4bit,bnb_4bit_quant_type="nf4" 使用 NormalFloat4 数据类型,bnb_4bit_compute_dtype=torch.bfloat16 指定反量化后的计算精度,配合 device_map="auto" 即可在较小显存上完成长文摘要。

使用注意事项(官方 Notes 精读)

官方文档明确列出以下工程约束,对照源码可以逐条验证:

  1. 分词器:BigBirdPegasus 使用 [PegasusTokenizer],不要混用其他 BPE/Unigram 分词器;
  2. 右侧 padding:由于模型采用绝对位置嵌入,padding 必须追加在序列右侧,否则位置信号会错乱(tokenizer 默认右填充即可满足);
  3. 注意力模式选择:编码器支持 original_fullblock_sparse 两种模式;若输入序列长度不足 1024,推荐 original_full——此时稀疏带来的计算收益很小,而全注意力实现更简单稳定(源码中也会在序列过短时自动退化,见上文 max_tokens_to_attend 阈值);
  4. 稀疏配置固定:当前实现窗口固定为 3 个块、全局块固定为 2 个,只支持 ITC 实现,并且不支持 num_random_blocks=0(该参数为 0 时无法生成随机块规划);
  5. 块对齐:使用 block-sparse 时序列长度必须是 block_size 的整数倍(实现层面 create_masks_for_block_sparse_attn 会对非对齐长度抛错,而前向内部先经 _pad_to_block_size 补齐,因此直接走模型前向一般无需手工 pad,但理解这一约束对自定义 batch 组装仍然重要)。

派生任务模型:一架构多用途

本仓库为 BigBirdPegasus 提供了 6 个入口类,均由 modeling_bigbird_pegasus.py 导出:

用途 输出
BigBirdPegasusModel 基础 encoder-decoder 主干 Seq2SeqModelOutput
BigBirdPegasusForConditionalGeneration 摘要/生成,带 LM head Seq2SeqLMOutput
BigBirdPegasusForSequenceClassification 长文本分类(encoder 表示 + 分类头) Seq2SeqSequenceClassifierOutput
BigBirdPegasusForQuestionAnswering 长文档抽取式问答 Seq2SeqQuestionAnsweringModelOutput
BigBirdPegasusForCausalLM 以 decoder 为骨干的因果语言建模(仅用解码器) CausalLMOutputWithCrossAttentions

其中 BigBirdPegasusForConditionalGenerationlm_head 权重与共享词嵌入绑定(_tied_weights_keys 声明 lm_head.weight ↔ model.shared.weight),并实现了 resize_token_embeddings 后对 final_logits_bias 的同步裁剪。测试套件通过 BigBirdPegasusModelTester(见 test_modeling_bigbird_pegasus.py)逐项覆盖了上述类的前向、生成(GenerationTesterMixin)、pipeline(PipelineTesterMixin)与配置一致性检查,验证用的微型配置 block_size=16attention_type="block_sparse" 等参数也可作为本地复现时的参考。

进一步学习路径

登录后查看全文
热门项目推荐
相关项目推荐