一、为什么这篇论文改变了一切
2017年之前,序列建模被RNN和LSTM统治。它们必须逐步处理序列,无法并行,训练慢,长距离依赖难捕获。Vaswani等人提出了一个大胆的想法:完全抛弃循环和卷积,只用注意力机制。
这个看似简单的决定,引爆了整个AI领域——GPT、BERT、ChatGPT、Midjourney、Sora……几乎所有现代AI模型都建立在Transformer之上。可以说,没有这篇论文,就没有今天的AI革命。
二、核心创新:缩放点积注意力
自注意力(Self-Attention)让序列中每个位置都能直接"看到"所有其他位置:
Attention(Q, K, V) = softmax(QK^T / √d_k) · V
其中:
- Q(Query):当前位置发出的"查询"——"我在找什么?"
- K(Key):每个位置提供的"键"——"我有什么?"
- V(Value):每个位置提供的"值"——"我的内容是……"
- √d_k:缩放因子,防止点积过大导致softmax梯度消失
直觉理解:Q是"我要找什么",K是"这里有什么",Q·K计算匹配度,再用匹配度加权V,得到融合全局信息的表示。
三、多头注意力(Multi-Head Attention)
单次注意力只能关注一种模式。多头注意力让模型同时关注多种关系:
MultiHead(Q,K,V) = Concat(head_1, ..., head_h) · W^O
where head_i = Attention(Q·W_i^Q, K·W_i^K, V·W_i^V)
原论文使用8个头,每个头维度 d_k = d_model/h = 512/8 = 64。不同的头可以分别关注语法关系、语义关系、位置关系等。
四、Transformer完整架构
编码器(Encoder):6层,每层包含多头自注意力 + 前馈网络 + 残差连接 + LayerNorm
解码器(Decoder):6层,额外增加交叉注意力层(关注编码器输出)+ 掩码自注意力(防止看到未来信息)
# 编码器单层
x = LayerNorm(x + MultiHeadSelfAttention(x))
x = LayerNorm(x + FFN(x))
# FFN(Position-wise前馈网络)
FFN(x) = max(0, x·W_1 + b_1)·W_2 + b_2 # 维度 512 → 2048 → 512
五、位置编码(Positional Encoding)
注意力机制本身没有位置概念,需要注入位置信息。原论文使用正弦/余弦函数:
PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))
选择三角函数的原因:1)可以让模型学习相对位置关系;2)对未见过的序列长度有泛化能力。
六、实验结果
| 任务 | 指标 | Transformer成绩 | 之前最佳 |
| WMT14 英→德 | BLEU | 28.4 | 26.1(集模型) |
| WMT14 英→法 | BLEU | 41.8 | 40.5 |
关键:训练仅需3.5天(8 GPU),远少于之前模型所需的数周。
七、影响与遗产
- GPT系列:只使用Transformer Decoder的自回归语言模型
- BERT:只使用Transformer Encoder的双向编码模型
- T5/BART:完整的Encoder-Decoder架构
- ViT:将Transformer应用于图像,Patch代替Token
- 多模态模型:CLIP、GPT-4V等均基于Transformer
2024年,Transformer论文引用量突破12万次,成为计算机科学史上最具影响力的论文之一。
八、原文摘要
The dominant sequence transduction models are based on complex recurrent or convolutional neural networks in an encoder-decoder configuration. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task, improving over the existing best results, including ensembles by over 2 BLEU.