RNN 和 Transformer 有什么区别?
Transformer 为什么取代了 RNN?

英文问法Compare RNNs and Transformers. · Why did Transformers replace LSTMs? · What are the complexity trade-offs?

考过★ 作者本人微软 AS 电面 · 面经:微软 D&AS Bing Ads 2022 R2("Transformer 为什么比 LSTM 好",LeetCode)

先弄清楚:每个概念是什么

RNN(LSTM / GRU)
逐个 token 往后读,每步把读到的东西压进固定大小的 hidden state \(h_t = f(h_{t-1}, x_t)\),像传话游戏。
Sequential operations(串行步数)
必须一步接一步算的步数。RNN 算 \(h_t\) 要等 \(h_{t-1}\),n 个 token 就是 n 步。
Path length(路径长度)
第 1 个 token 的信息传到第 n 个要经过几步。例:n = 1000,RNN 要传 999 步,attention 1 步直达。
Inductive bias
模型自带的假设。RNN 天生按顺序、偏重近处,Transformer 几乎不假设。

30 秒回答

An RNN reads tokens one by one and compresses the past into a fixed-size hidden state. Training takes O(n) sequential steps that can't be parallelized, and a signal between distant tokens passes through O(n) steps, so gradients tend to vanish; LSTM gating only mitigates this. Self-attention connects every pair of tokens directly: O(1) sequential operations and O(1) path length, so it trains in parallel and captures long-range dependencies. The cost is O(n²·d) per layer versus O(n·d²), and at inference a KV cache that grows with length, while an RNN keeps constant memory. Transformers also need positional encodings and more data, but scale much better.

对比(前三行是 Vaswani et al. Table 1)

RNN(LSTM / GRU)Transformer(self-attention)
每层 compute\(O(n\cdot d^2)\)\(O(n^2\cdot d)\)
串行步数\(O(n)\):不能沿时间并行\(O(1)\):所有位置并行
最长路径\(O(n)\)\(O(1)\)
推理每个 token每层 \(O(d^2)\),state 大小固定每层 \(O(nd + d^2)\),KV cache 随长度线性涨
位置信息顺序计算天然带要 positional encoding(如 RoPE)
数据bias 强,小数据可能够用bias 弱,要大数据,scaling 更好

推导 / 关键公式

为什么 RNN 学不到远距离依赖

\[ \frac{\partial h_n}{\partial h_1} = \prod_{t=2}^{n} \frac{\partial h_t}{\partial h_{t-1}} \]

n − 1 个 Jacobian 连乘,范数小于 1 就指数衰减(vanishing gradient)。

谁更省算力

RNN 每步做一次 \(d\times d\) 矩阵乘,共 \(O(nd^2)\)。self-attention 每对 token 做一次 d 维点积,共 \(O(n^2d)\)。\(n < d\) 时 self-attention 更便宜。FLOPs 推导和长序列的办法见 Transformer 复杂度。

Transformer base 的 \(d = 512\):

必答点

追问

LSTM 不是解决了 vanishing gradient 吗?

只是缓解。cell state 是加法更新,直接路径上只乘 forget gate(见 vanishing gradient),但路径还是 \(O(n)\),训练也还是串行。

Transformer 生成时也是一个一个 token,并行在哪?

在训练。整句已知,用 causal mask 一次算出所有位置的 loss,RNN 训练和推理都得逐步算。

RNN 现在还有用吗?

推理时 state 固定、每 token 常数开销的优点没变。Mamba 这类 selective SSM 训练能并行、推理像 RNN,论文报告推理 throughput 是 Transformer 的 5 倍。

来源Vaswani et al. 2017 §1(p.2)、§3.1(p.3)、Table 1 与 §4(pp.6–7)· Gu & Dao 2023, Mamba Abstract