Many new Transformer architecture improvements have been proposed since my 2020 post. Version 2.0 is a big refactoring and enrichment—restructured hierarchy, improved with more recent papers, about twice the length of the old version. This is a systematic survey of 100+ Transformer variants.
自 2020 年的旧文以来,许多新的 Transformer 架构改进被提出。2.0 版是对旧文的大重构与丰富——重新组织章节层级、用更多近期论文充实,篇幅约为旧版两倍。这是一份对 100+ 种 Transformer 变体的系统综述,是理解现代大模型架构演进的最佳地图之一。
The Transformer has an encoder-decoder architecture. Self-attention is permutation-invariant—an operation on sets. It relies on scaled dot-product attention: attn(Q,K,V) = softmax(QKᵀ/√d_k)V. The multi-head mechanism splits inputs into smaller chunks and computes attention over each subspace in parallel, then concatenates. Positional encoding is essential because self-attention is permutation invariant.
Transformer 是编码器-解码器架构。自注意力是置换不变的——它是对集合的操作。它依赖缩放点积注意力:attn(Q,K,V) = softmax(QKᵀ/√d_k)V。多头机制把输入切成小块,在每个子空间并行计算注意力后拼接。位置编码至关重要,因为自注意力本身置换不变。
"自注意力是置换不变的"是理解 Transformer 一切改进的钥匙。它意味着如果不额外注入顺序信息,模型把"猫追狗"和"狗追猫"视为完全相同。所以位置编码不是装饰,而是把"顺序"这个维度硬塞进去的必要手段。所有 Transformer 变体本质上都在回答三个问题:怎么注入顺序、怎么处理长上下文、怎么降低注意力的二次开销。把握这三条主线,就能看懂 100+ 变体背后的统一逻辑——它们不过是这三条主线的不同组合。
Sinusoidal positional encoding uses sine/cosine of different wavelengths. Learned positional encoding assigns a learned vector per position. Relative position encoding (Shaw et al. 2018; Transformer-XL, Dai et al. 2019) incorporates relative positional info into W^k and W^v, reparameterizing the attention score into content-based addressing, content-dependent positional bias, global content bias, and global positional bias.
正弦位置编码用不同波长的正弦/余弦。可学习位置编码为每个位置分配一个学习向量。相对位置编码(Shaw 等 2018;Transformer-XL,Dai 等 2019)把相对位置信息融入 W^k 和 W^v,把注意力分数重新参数化为:基于内容的寻址、内容依赖的位置偏置、全局内容偏置、全局位置偏置。
Rotary Position Embedding (RoPE; Su et al. 2021) encodes absolute position with a rotation matrix and multiplies key/value matrices with it to inject relative positional info at every layer. It frames relative position embedding as rotating the feature matrix by an angle proportional to its position index. RoPE is essentially equivalent to sinusoidal encoding but formulated as a rotation matrix—making the inner product depend only on relative position i-j.
旋转位置编码(RoPE)(Su 等 2021)用旋转矩阵编码绝对位置,并与每层的键/值矩阵相乘以注入相对位置信息。它把相对位置编码表述为把特征矩阵旋转一个与位置索引成正比的角度。RoPE 本质上等价于正弦编码,但表述为旋转矩阵——使内积只依赖相对位置 i-j。
位置编码的演进是一部"从绝对到相对"的进化史。正弦/可学习编码都是绝对位置——位置 5 和位置 10 是两个独立编码,模型要自己学会它们差 5。问题:绝对编码无法泛化到训练时没见过的长度。相对编码的突破在于直接编码"两个 token 相距多远",这对泛化友好得多。RoPE 是这条路线的集大成者,也是今天 Llama、Qwen 等主流模型的事实标准。RoPE 的巧妙:用旋转把"绝对位置"变成"相对位置"——q_i 和 k_j 的内积自然只依赖 i-j,因为旋转矩阵 R_iᵀR_j = R_{j-i}。理解 RoPE 是理解长上下文外推(NTK-aware、YaRN)的前提。
Naively increasing context length leads to high consumption in both time O(L²d) and memory O(L²). Several improvements: Context memory—Transformer-XL reuses hidden states between segments with an additional memory; Compressive Transformer extends it by compressing past memories. Non-differentiable external memory—kNN-LM enhances a pretrained LM with a kNN key-value store; Memorizing Transformer adds a kNN-augmented attention layer.
朴素增加上下文长度会导致时间 O(L²d) 和内存 O(L²) 的高消耗。几类改进:上下文记忆——Transformer-XL 用额外内存在段间复用隐状态;Compressive Transformer 通过压缩旧记忆来扩展它。不可微外部记忆——kNN-LM 用 kNN 键值存储增强预训练 LM;Memorizing Transformer 加入 kNN 增强的注意力层。
Distance-Enhanced Attention: DA-Transformer multiplies attention scores by a learnable bias function of key-query distance. ALiBi (Press et al. 2022) adds a constant bias term proportional to pairwise distances, introducing a strong recency preference. ALiBi trained a 1.3B model on context length 1024 and extrapolated to 2046 at inference—enabling length extrapolation.
距离增强注意力:DA-Transformer 用键-查询距离的可学习偏置函数乘注意力分数。ALiBi(Press 等 2022)加一个与成对距离成正比的常数偏置项,引入强烈的近因偏好。ALiBi 在上下文长度 1024 上训练 1.3B 模型,推理时外推到 2046——实现了长度外推。
长上下文是 Transformer 最持久的战场,技术分两大派:"多记一点"(外部记忆)和"算少一点"(稀疏/高效注意力)。Transformer-XL 的洞察是"段间接力"——本段注意力不仅看本段,还看上一段的隐状态,等于免费扩展了记忆。kNN-LM 走得更激进:直接接一个外部数据库,用最近邻检索注入预训练数据的知识。ALiBi 的"长度外推"是个里程碑——它证明了只要给注意力一个"距离越远惩罚越大"的归纳偏置,模型就能在短上下文训练、长上下文推理。这个思路今天仍影响着 RoPE 的各种外推缩放方案(位置插值、NTK-aware)。
Universal Transformer (Dehghani et al. 2019) combines self-attention with the recurrent mechanism in RNN, dynamically adjusting the number of steps using Adaptive Computation Time (ACT). If the number of steps is fixed, it's equivalent to a multi-layer Transformer with shared parameters across layers. Each position is equipped with a dynamic ACT halting mechanism—once halted, it stops taking more recurrent updates.
Universal Transformer(Dehghani 等 2019)把自注意力与 RNN 的循环机制结合,用自适应计算时间(ACT)动态调整步数。若步数固定,它等价于层间共享参数的多层 Transformer。每个位置配备动态 ACT 停止机制——一旦停止,就不再接受更多循环更新。
Adaptive modeling adjusts the amount of computation according to different inputs. Adaptive Attention Span (Sukhbaatar et al. 2019) learns an optimal attention span per head—lower layers don't need very long spans, while a few heads in higher layers use exceptionally long spans. Depth-Adaptive Transformer (Elabyad et al. 2020) and CALM (Schuster et al. 2022) learn to predict optimal numbers of layers needed per token, allowing early exit—softmax responses resulted in best inference speedup.
自适应建模根据不同输入调整计算量。自适应注意力跨度(Sukhbaatar 等 2019)为每个头学习最优注意力跨度——低层不需要很长跨度,而高层少数头会用极长跨度。深度自适应 Transformer(Elabyad 等 2020)和 CALM(Schuster 等 2022)学习为每个 token 预测所需层数,允许提前退出——softmax 响应带来最佳推理加速。
"自适应"是个深刻的思想:不是所有 token 都需要同样的算力。简单 token 早退出(少过几层),难 token 多想(多过几层)。这与人类阅读异曲同工——熟悉的内容一扫而过,生涩的内容反复咀嚼。实验发现"低层短跨度、高层长跨度"也很反直觉但合理:低层抓局部语法(短语级),高层抓长程语义(段落级)。这些思想在今天是 Mixture-of-Depths(MoD)等技术的前身——把"按需计算"做到极致,是降低推理成本的前沿方向。
Image Transformer (Parmar et al. 2018) restricts attention span to local context via 1D/2D local attention, so self-attention grows linearly with sequence length.
Image Transformer(Parmar 等 2018)通过 1D/2D 局部注意力把注意力跨度限制在局部上下文,使自注意力随序列长度线性增长。
Sparse Transformer (Child et al. 2019) introduces factorized self-attention, making it possible to train on sequences up to 16,384. Strided attention: each token attends to previous ℓ pixels and same-column tokens. Fixed attention: a small set of tokens summarize previous locations. Blockwise Attention partitions the L×L matrix into n×n smaller blocks.
Sparse Transformer(Child 等 2019)引入因式分解自注意力,能在长达 16,384 的序列上训练。跨步注意力:每个 token 关注前 ℓ 个像素及同列 token。固定注意力:少数 token 汇总先前位置的信息。Blockwise Attention 把 L×L 矩阵分成 n×n 个小块。
ETC, Longformer and Big Bird combine local and global context. Longformer has sliding-window local attention, global attention on preselected tokens (e.g. [CLS]), and dilated attention. Big Bird is similar but replaces dilated with random attention—motivated by the fact that a random graph allows rapid information flow between any node pair. Longformer uses smaller windows at lower layers, larger at higher layers.
ETC、Longformer、Big Bird 结合局部与全局上下文。Longformer 有滑动窗口局部注意力、对预选 token(如 [CLS])的全局注意力、以及膨胀注意力。Big Bird 类似但用随机注意力替代膨胀——动机是随机图能让信息在任意节点对间快速流动。Longformer 在低层用小窗口、高层用大窗口。
Reformer (Kitaev et al. 2020) solves quadratic complexity via two changes: locality-sensitive hashing (LSH) attention, reducing O(L²) to O(L log L)—queries only attend to positions in the same hash bucket; and reversible residual layers, storing activations only once instead of N times. Routing Transformer uses online k-means clustering, reducing O(L²) to O(L^1.5).
Reformer(Kitaev 等 2020)通过两点解决二次复杂度:局部敏感哈希(LSH)注意力,把 O(L²) 降到 O(L log L)——查询只关注同一哈希桶的位置;可逆残差层,激活值只存一次而非 N 次。Routing Transformer 用在线 k-means 聚类,把 O(L²) 降到 O(L^1.5)。
Linformer (Wang et al. 2020) approximates the full attention matrix with a low-rank matrix via two linear projections E, F, reducing dimensions from L×d to k×d—linear complexity as long as k≪L. Random Feature Attention (RFA; Peng et al. 2021) and Performer (Choromanski et al. 2021) use random feature methods to approximate softmax with low-rank feature maps. The key insight: causal RFA tracks a running state (S_t, z_t) like an RNN, enabling significant autoregressive decoding speedup.
Linformer(Wang 等 2020)通过两个线性投影 E、F 用低秩矩阵近似全注意力矩阵,把维度从 L×d 降到 k×d——只要 k≪L 就是线性复杂度。随机特征注意力(RFA)(Peng 等 2021)和 Performer(Choromanski 等 2021)用随机特征方法以低秩特征图近似 softmax。关键洞察:因果 RFA 像 RNN 一样跟踪运行状态 (S_t, z_t),实现显著的自回归解码加速。
高效注意力是 Transformer 研究最拥挤的赛道,思路可分三派:稀疏派(只算一部分注意力,如 Longformer 的局部+全局)——简单可控,是工程上最实用的;聚类派(让相关 token 聚到一起再算,如 Reformer 的 LSH)——理论优雅但哈希不稳定;低秩/核方法派(Linformer 投影、Performer 随机特征)——数学最漂亮但近似误差难控制。历史的最大教训:很多花哨方法被 FlashAttention 打败了。FlashAttention 没有改变复杂度,只是把稠密注意力的 IO 优化到极致,反而比大多数"线性注意力"更快更准。这说明在 GPU 时代,IO 模式和硬件亲和力往往比理论复杂度更决定胜负。不过随模型变长,Mamba/线性 RNN 等"亚二次"路线正在复兴。
The Gated Transformer-XL (GTrXL; Parisotto et al. 2019) stabilizes Transformer for RL with two changes: layer normalization only on the input stream (not the shortcut), and a GRU-style gating mechanism replacing the residual connection, initialized close to identity. Decision Transformer (DT; Chen et al. 2021) formulates RL as conditional sequence modeling: it feeds desired future return (return-to-go) R̂, past states and actions, and predicts optimal actions—a Transformer on offline trajectories.
门控 Transformer-XL(GTrXL;Parisotto 等 2019)用两点让 Transformer 在 RL 中稳定:层归一化只加在输入流(不加在捷径流),以及用 GRU 风格门控机制替代残差连接并初始化为接近恒等映射。Decision Transformer(DT;Chen 等 2021)把 RL 表述为条件序列建模:喂入期望未来回报(return-to-go)R̂、过去状态和动作,预测最优动作——一个跑在离线轨迹上的 Transformer。
Decision Transformer 是 RL 领域的范式革命——它把"强化学习"重新定义为"在轨迹数据上的序列建模"。传统 RL(Q-learning、policy gradient)是在线试错、估计价值函数;DT 则是离线的、生成式的:给定"我想要高回报",模型直接生成能达到高回报的动作序列。这呼应了 GPT 的成功——只要把问题转化为"下一个 token 预测",Transformer 就能解决。GTrXL 的两个稳定化技巧(门控、层归一化重排)则揭示了 Transformer 在 RL 中难训练的根源:残差通路上的归一化会阻断梯度流,而 RL 的奖励信号本就稀疏 noisy。这些洞察今天仍影响着基于 Transformer 的世界模型和决策架构。
100+ 变体看似纷繁,实则围绕三条主线展开:①如何注入顺序(位置编码:绝对→相对→RoPE);②如何突破长度限制(外部记忆、长度外推、稀疏注意力);③如何降低二次开销(稀疏、聚类、低秩、自适应)。这些 2023 年前的探索,最终沉淀为今天的几个事实标准:RoPE 做位置编码、FlashAttention 做稠密注意力工程优化、MoE 做条件计算、RoPE 缩放做长上下文。理解这份"全家桶",就能看懂从 BERT 到 Llama、从 Attention 到 Mamba 的完整技术脉络——大多数"新架构"其实都是这些旧思想的重新组合。