跳转至

Transformer 架构

Self-Attention / 多头注意力 / 位置编码 / Transformer Block

演进路径

  1. Seq2Seq + Attention — 编码器-解码器 + 对齐
  2. Self-Attention — Q/K/V 矩阵、缩放点积
  3. Multi-Head Attention — 多头并行,捕获不同模式
  4. Transformer Block — Attention → Add&Norm → FFN → Add&Norm

核心公式

  • 缩放点积注意力:\(\text{Attention}(Q,K,V) = \text{softmax}(\frac{QK^T}{\sqrt{d_k}})V\)
  • 多头注意力:\(\text{MultiHead} = \text{Concat}(\text{head}_1, ..., \text{head}_h)W^O\)
  • FFN:\(\text{FFN}(x) = \max(0, xW_1 + b_1)W_2 + b_2\)

位置编码

方法 特点 适用
正弦余弦 原始 Transformer 任意长度
可学习 BERT 使用 固定长度
RoPE 旋转位置编码,相对位置 Qwen/Llama
ALiBi 线性偏置,外推性好 BLOOM

KV Cache

  • 推理时缓存已计算的 K/V,避免重复计算
  • PagedAttention (vLLM) — 分页管理 KV Cache 内存

练习

  • 手推多头注意力公式
  • 用 PyTorch 从零实现 Transformer Encoder
  • 参考 Annotated Transformer 完整实现
  • 从零实现 GPT-2 (参考 nanoGPT)

资源

资源 链接
Attention Is All You Need https://arxiv.org/abs/1706.03762
李沐 Transformer 精读 https://www.bilibili.com/video/BV1pu411o7BE
Annotated Transformer http://nlp.seas.harvard.edu/annotated-transformer/
nanoGPT https://github.com/karpathy/nanoGPT
Jay Alammar 图解 https://jalammar.github.io/illustrated-transformer/
Lilian Weng Attention 博客 https://lilianweng.github.io/posts/2018-01-27-attention/