﻿---
lang: zh-TW
title: "讀懂 LSTM：一條傳送帶怎樣讓迴圈網路記住遠處的字"
description: "“我在法國長大……我能說流利的___”，要填出“法語”，網路得記住很多個字以前的“法國”。我們以 colah 2015 年的《Understanding LSTM Networks》為主線，配合他寫的拓撲、表示學習、反向傳播和注意力幾篇文章，用一個只有一個單元、能手算的 LSTM 往下追：普通網路為什麼處理不了序列，迴圈網路為什麼記不住遠處的字，細胞狀態這條傳送帶和三道門怎樣讓梯度不再衰減，窺視孔、耦合門和 GRU 改了什麼；再看原文結尾那句“下一步是注意力”怎樣應驗成 Transformer，以及到了 2026 年，LSTM 還用在哪裡，xLSTM、Mamba 這些新的迴圈模型和它是什麼關係。"
pubDate: 2026-11-29
tags: ["AI", "神经网络", "机器学习", "入门"]
clc: "TP183"
hero: "./hero.zh-TW.svg"
refs:
  - id: colah-lstm
    title: "Understanding LSTM Networks"
    url: https://colah.github.io/posts/2015-08-Understanding-LSTMs/
    author: Christopher Olah
    site: colah's blog
    date: 2015-08-27
    note: "本文的主線。原文的公式都畫在圖裡；本文照抄圖中公式，只把 `C_t` 寫成 `c_t`、逐元素乘法 `*` 寫成 `⊙`。"
  - id: colah-topology
    title: "Neural Networks, Manifolds, and Topology"
    url: https://colah.github.io/posts/2014-03-NN-Manifolds-Topology/
    author: Christopher Olah
    site: colah's blog
    date: 2014-04-06
    note: "“每一層都在拉伸、擠壓空間，但從不剪開、撕裂或摺疊它。”"
  - id: colah-nlp
    title: "Deep Learning, NLP, and Representations"
    url: https://colah.github.io/posts/2014-07-NLP-RNNs-Representations/
    author: Christopher Olah
    site: colah's blog
    date: 2014-07-07
    note: "詞嵌入是訓練別的任務時順帶學出來的表示；W(woman) − W(man) ≃ W(queen) − W(king)。"
  - id: colah-backprop
    title: "Calculus on Computational Graphs: Backpropagation"
    url: https://colah.github.io/posts/2015-08-Backprop/
    author: Christopher Olah
    site: colah's blog
    date: 2015-08-31
    note: "反向傳播就是反向模式求導：沿路徑把邊上的導數相乘，再對所有路徑求和；結尾點名 RNN 的梯度消失。"
  - id: distill-attn
    title: "Attention and Augmented Recurrent Neural Networks"
    url: https://distill.pub/2016/augmented-rnns/
    author: Chris Olah, Shan Carter
    site: Distill
    date: 2016-09-08
    note: "神經圖靈機、注意力介面、自適應計算時間、神經程式設計器四種擴充，共用同一個底層技巧：注意力。"
  - id: karpathy
    title: "The Unreasonable Effectiveness of Recurrent Neural Networks"
    url: https://karpathy.github.io/2015/05/21/rnn-effectiveness/
    author: Andrej Karpathy
    site: Andrej Karpathy blog
    date: 2015-05-21
    note: "char-rnn：在莎士比亞、Linux 原始碼、LaTeX 上訓練多層 LSTM；約 5% 的單元學出了可解釋的行為，比如偵測引號。"
  - id: hochreiter91
    title: "Untersuchungen zu dynamischen neuronalen Netzen"
    author: Sepp Hochreiter
    site: "Diplomarbeit, TU München"
    date: "1991"
    note: "德文畢業論文，最早系統分析迴圈網路的梯度消失；colah 原文引用。本文未取得原文核對。"
  - id: bengio94
    title: "Learning long-term dependencies with gradient descent is difficult"
    url: https://doi.org/10.1109/72.279181
    author: Yoshua Bengio, Patrice Simard, Paolo Frasconi
    site: IEEE Transactions on Neural Networks 5(2)
    date: "1994"
  - id: lstm97
    title: "Long Short-Term Memory"
    url: https://doi.org/10.1162/neco.1997.9.8.1735
    author: Sepp Hochreiter, Jürgen Schmidhuber
    site: Neural Computation 9(8)
    date: "1997"
  - id: gers-forget
    title: "Learning to Forget: Continual Prediction with LSTM"
    url: https://doi.org/10.1162/089976600300015015
    author: Felix A. Gers, Jürgen Schmidhuber, Fred Cummins
    site: Neural Computation 12(10)
    date: "2000"
    note: "沒有遺忘門的 LSTM 在沒有明確結尾的連續輸入上，內部狀態會一直增長直到失效；遺忘門讓單元能自己重置。"
  - id: gers-peephole
    title: "Recurrent nets that time and count"
    url: https://doi.org/10.1109/IJCNN.2000.861302
    author: Felix A. Gers, Jürgen Schmidhuber
    site: IJCNN 2000
    date: "2000"
    note: "窺視孔連線的出處：讓門能看見細胞狀態，以便學會精確計時。"
  - id: greff
    title: "LSTM: A Search Space Odyssey"
    url: https://arxiv.org/abs/1503.04069
    author: Klaus Greff, Rupesh K. Srivastava, Jan Koutník, Bas R. Steunebrink, Jürgen Schmidhuber
    site: IEEE TNNLS 28(10)
    date: 2015-03-13
    note: "8 種變體、3 個任務、5400 次實驗：沒有一種變體顯著優於標準 LSTM；遺忘門和輸出啟用函式最關鍵。最早的 LSTM 沒有遺忘門和窺視孔。"
  - id: jozefowicz
    title: "An Empirical Exploration of Recurrent Network Architectures"
    url: https://proceedings.mlr.press/v37/jozefowicz15.html
    author: Rafal Jozefowicz, Wojciech Zaremba, Ilya Sutskever
    site: ICML 2015, PMLR 37
    date: "2015"
    note: "評估了一萬多種迴圈結構；給 LSTM 的遺忘門加 1 的偏置，就能追平 GRU。"
  - id: pascanu
    title: "On the difficulty of training Recurrent Neural Networks"
    url: https://arxiv.org/abs/1211.5063
    author: Razvan Pascanu, Tomas Mikolov, Yoshua Bengio
    site: ICML 2013
    date: 2012-11-21
    note: "從解析、幾何、動力系統三個角度分析梯度消失與爆炸，提出梯度範數裁剪。"
  - id: cho
    title: "Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation"
    url: https://arxiv.org/abs/1406.1078
    author: Kyunghyun Cho 等
    site: EMNLP 2014
    date: 2014-06-03
    note: "GRU 的出處。原文式 (7) 把更新門 z 乘在舊狀態上、1 − z 乘在候選值上，和 colah 圖裡的寫法正好互換。"
  - id: chung
    title: "Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling"
    url: https://arxiv.org/abs/1412.3555
    author: Junyoung Chung, Caglar Gulcehre, KyungHyun Cho, Yoshua Bengio
    site: arXiv 1412.3555
    date: 2014-12-11
  - id: sutskever
    title: "Sequence to Sequence Learning with Neural Networks"
    url: https://arxiv.org/abs/1409.3215
    author: Ilya Sutskever, Oriol Vinyals, Quoc V. Le
    site: NeurIPS 2014
    date: 2014-09-10
    note: "多層 LSTM 把整句編碼成固定長度的向量，WMT'14 英法 BLEU 34.8；把源句倒過來輸入明顯變好，因為引入了很多短距離依賴。"
  - id: bahdanau
    title: "Neural Machine Translation by Jointly Learning to Align and Translate"
    url: https://arxiv.org/abs/1409.0473
    author: Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio
    site: ICLR 2015
    date: 2014-09-01
    note: "推測固定長度向量是編碼器—解碼器的瓶頸，讓模型對源句做軟搜尋。"
  - id: xu
    title: "Show, Attend and Tell: Neural Image Caption Generation with Visual Attention"
    url: https://arxiv.org/abs/1502.03044
    author: Kelvin Xu 等
    site: ICML 2015
    date: 2015-02-10
    note: "colah 在 LSTM 原文結尾推薦的注意力入門例子：生成每個詞時看圖片的不同部位。"
  - id: gnmt
    title: "Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation"
    url: https://arxiv.org/abs/1609.08144
    author: Yonghui Wu 等
    site: arXiv 1609.08144
    date: 2016-09-26
    note: "8 層編碼器、8 層解碼器的 LSTM，加注意力和殘差連線。"
  - id: vaswani
    title: "Attention Is All You Need"
    url: https://arxiv.org/abs/1706.03762
    author: Ashish Vaswani 等
    site: NeurIPS 2017
    date: 2017-06-12
    note: "完全去掉迴圈和卷積；WMT 2014 英德 28.4 BLEU，英法 41.8 BLEU，8 張 GPU 訓練 3.5 天。"
  - id: katharopoulos
    title: "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention"
    url: https://arxiv.org/abs/2006.16236
    author: Angelos Katharopoulos, Apoorv Vyas, Nikolaos Pappas, François Fleuret
    site: ICML 2020
    date: 2020-06-29
    note: "把注意力寫成核特徵的線性點積，複雜度從 O(N²) 降到 O(N)，可以按 RNN 的方式逐步計算；長序列自迴歸生成最多快 4000 倍。"
  - id: mamba
    title: "Mamba: Linear-Time Sequence Modeling with Selective State Spaces"
    url: https://arxiv.org/abs/2312.00752
    author: Albert Gu, Tri Dao
    site: arXiv 2312.00752
    date: 2023-12-01
    note: "讓狀態空間模型的參數隨輸入變化（選擇機制）；不用注意力；推理吞吐量約為 Transformer 的 5 倍，序列長度線性擴展。"
  - id: mamba2
    title: "Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality"
    url: https://arxiv.org/abs/2405.21060
    author: Tri Dao, Albert Gu
    site: ICML 2024
    date: 2024-05-31
    note: "用半可分矩陣把狀態空間模型和注意力聯繫起來；Mamba-2 的核心層比 Mamba 快 2 到 8 倍。"
  - id: jamba
    title: "Jamba: A Hybrid Transformer-Mamba Language Model"
    url: https://arxiv.org/abs/2403.19887
    author: Opher Lieber 等
    site: arXiv 2403.19887
    date: 2024-03-28
    note: "Transformer 層和 Mamba 層交錯，部分層加 MoE；總參數 52B、啟用 12B，支援 256K 上下文，KV 快取比純 Transformer 小 8 倍。"
  - id: xlstm
    title: "xLSTM: Extended Long Short-Term Memory"
    url: https://arxiv.org/abs/2405.04517
    author: Maximilian Beck, Korbinian Pöppel 等（含 Sepp Hochreiter）
    site: NeurIPS 2024
    date: 2024-05-07
    note: "指數門控加正規化與穩定化；sLSTM 保留標量記憶和記憶混合，mLSTM 改用矩陣記憶、去掉隱狀態之間的迴圈連線，可以完全並行。"
  - id: xlstm7b
    title: "xLSTM 7B: A Recurrent LLM for Fast and Efficient Inference"
    url: https://arxiv.org/abs/2503.13427
    author: Maximilian Beck 等
    site: ICML 2025
    date: 2025-03-17
    note: "以 mLSTM 為主體、不含自注意力的 7B 模型；下游任務與同規模模型相當，推理比 Llama、Mamba 架構的模型更快、更省。"
  - id: minrnn
    title: "Were RNNs All We Needed?"
    url: https://arxiv.org/abs/2410.01201
    author: Leo Feng, Frederick Tung, Mohamed Osama Ahmed, Yoshua Bengio, Hossein Hajimirsadeghi
    site: arXiv 2410.01201
    date: 2024-10-02
    note: "把 LSTM 和 GRU 的門裡對上一步隱狀態的依賴去掉，就不再需要 BPTT，可以用平行掃描訓練；序列長度 512 時訓練快 175 倍。"
  - id: tirex
    title: "TiRex: Zero-Shot Forecasting Across Long and Short Horizons with Enhanced In-Context Learning"
    url: https://arxiv.org/abs/2505.23719
    author: Andreas Auer, Patrick Podest, Daniel Klotz, Sebastian Böck, Günter Klambauer, Sepp Hochreiter
    site: NeurIPS 2025
    date: 2025-05-29
    note: "基於 xLSTM、35M 參數的時間序列預測模型，在 GiftEval 和 Chronos-ZS 上零樣本預測達到當時最好；作者認為時間序列上迴圈模型常常比 Transformer 有優勢。"
  - id: nearing
    title: "Global prediction of extreme floods in ungauged watersheds"
    url: https://doi.org/10.1038/s41586-024-07145-1
    author: Grey Nearing 等
    site: Nature 627
    date: 2024-03-20
    note: "Google 的洪水預報模型：兩個依次銜接的 LSTM，分別讀歷史天氣和預報天氣，預測 7 天內的日流量；已接入超過 80 個國家的公開預警系統。"
---

colah（Christopher Olah）2015 年 8 月 27 日發表的《Understanding LSTM Networks》[^colah-lstm]，是流傳很廣、被反覆轉載和翻譯的一篇深度學習部落格。它出現在 [Ilya 的 30u30 清單](/blog/ilya-30u30/)裡，和 Karpathy 那篇講迴圈網路的部落格[^karpathy]挨在一起；[大模型為什麼最近才出現那篇](/blog/llm-why-now/)講梯度消失時，也只用了一句話帶過它：LSTM 給迴圈網路加了一條梯度能原樣透過的“傳送帶”。

這句話說得對，但留下的問題比回答的多。colah 原文裡有一個例子：

> 我在法國長大……我能說流利的 ___。

人一眼就能填出“法語”，因為記得很多個字以前的“法國”。可是讓一個神經網路來填，事情就沒那麼簡單了：

1. **普通的神經網路為什麼處理不了這種句子？** 迴圈網路又是怎麼處理的？
2. **迴圈網路明明能把前文帶下來，為什麼還是記不住幾十個字以前的“法國”？**
3. **LSTM 的“傳送帶”到底是什麼？** 遺忘門、輸入門、輸出門各管什麼，公式裡每個符號是什麼意思？
4. **LSTM 有那麼多變體，窺視孔、耦合門、GRU 各改了什麼？** 改了有沒有用？
5. **原文結尾說，下一步是注意力。** 這一步後來怎樣變成了 Transformer？到了 2026 年，LSTM 自己又去了哪裡？

本文就順著這幾個問題往下講。為了讓每一步都能手算，我們從頭到尾用同一個只有一個單元的 LSTM，數字全部可以用文末的程式重算。途中會用到 colah 的另外四篇文章：講拓撲的那篇幫我們理解“一層網路在做什麼”，講表示的那篇幫我們理解“隱狀態裡裝的是什麼”，講反向傳播的那篇幫我們算清“梯度為什麼會消失”，和 Shan Carter 合寫的注意力那篇，則是 LSTM 原文結尾那句話的續集。

## 一、迴圈網路：同一個網路按時間攤開

### 現象：普通網路只吃固定大小的輸入

colah 早一年寫的《Neural Networks, Manifolds, and Topology》[^colah-topology]，把一層網路看成對空間的一次變形：先做一個線性變換，再逐點套一個 tanh 這樣的非線性函式。他的原話是，每一層都在拉伸、擠壓空間，但從不剪開、撕裂或摺疊它。一個前饋網路就是一連串這樣的變形，把一個固定長度的向量變成另一個固定長度的向量。

句子不是這樣的東西。它長短不一，而且順序有意義：“法國”出現在前面，“法語”才填得出來。把整句硬塞成一個定長向量，要麼得截斷，要麼得給每個位置一套單獨的權重，而“法國”出現在第 3 個字和第 30 個字時，本該是同一件事。

### 解決：把同一個網路反覆用

迴圈網路（RNN）的做法是，**每讀一個字，就用同一套權重做一次更新**，把一個小向量 $h$ 一路帶下去：

$$
h_t = \tanh(W h_{t-1} + U x_t + b)
$$

$x_t$ 是第 $t$ 個字的向量；$h_{t-1}$ 是讀完前 $t-1$ 個字後留下的隱狀態；$W$ 決定舊狀態怎麼帶進來，$U$ 決定新字怎麼寫進去，$b$ 是偏置；$\tanh$ 把結果壓回 $-1$ 到 $1$ 之間。$W$、$U$、$b$ 在每一步都一樣，所以句子多長都能處理。colah 把它畫成一個帶迴圈的方框，再把迴圈按時間攤開：同一個網路的很多份複製，每一份把訊息傳給下一份[^colah-lstm]。

$h_t$ 裡裝的是什麼？colah 的《Deep Learning, NLP, and Representations》[^colah-nlp]給了一個很好的角度：詞向量並不是人設計的，而是網路為了完成別的任務（比如判斷一個五詞片語是否通順）順帶學出來的表示，學完之後相近的詞自然靠在一起，甚至“女人 − 男人”和“女王 − 國王”這兩個差向量也差不多。$h_t$ 也是這樣一種學出來的表示，只不過它表示的不是一個詞，而是“到目前為止讀到的全部內容”。Karpathy 在字元級 LSTM 裡就找到過一個專門追蹤“現在是否在引號裡”的單元，用他的話說，沒人教它，是它自己覺得這個量值得記[^karpathy]。

為了能手算，我們把網路縮到只有一個單元，令 $W = 0.9$、$U = 2$、$b = 0$，並且把句子簡化成 5 個詞：“法國”記作 $x = 1$，其餘普通詞記作 $x = 0$。圖 1 是它攤開後的樣子。

<figure class="dd dd-figure">
<div class="dd-scroll">
<svg class="dd-svg" viewBox="0 0 800 336" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="lstm-rnn-title lstm-rnn-desc">
<title id="lstm-rnn-title">按時間攤開的單元迴圈網路</title>
<desc id="lstm-rnn-desc">五個詞法國、長大、後來、我能說、流利的依次輸入同一個迴圈單元，x 分別是 1、0、0、0、0；隱狀態 h 依次是 0.964、0.700、0.558、0.464、0.395，最後一步要預測下一個詞法語。</desc>
<defs>
<marker id="lstm-rnn-arrow" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto"><path class="dd-head" d="M1 1 L7 4 L1 7"/></marker>
<marker id="lstm-rnn-arrow-acc" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto"><path class="dd-head-acc" d="M1 1 L7 4 L1 7"/></marker>
</defs>
<rect class="dd-frame" width="800" height="336" rx="10"/>
<rect class="dd-zone" x="16" y="16" width="768" height="304" rx="8"/>
<text class="t-zone" x="40" y="44">按時間攤開：每一步都用同一組 w = 0.9、u = 2</text>
<line class="dd-edge-acc" x1="152" y1="195" x2="188" y2="195" marker-end="url(#lstm-rnn-arrow-acc)"/>
<line class="dd-edge-acc" x1="304" y1="195" x2="340" y2="195" marker-end="url(#lstm-rnn-arrow-acc)"/>
<line class="dd-edge-acc" x1="456" y1="195" x2="492" y2="195" marker-end="url(#lstm-rnn-arrow-acc)"/>
<line class="dd-edge-acc" x1="608" y1="195" x2="644" y2="195" marker-end="url(#lstm-rnn-arrow-acc)"/>
<line class="dd-edge-acc" x1="704" y1="124" x2="704" y2="100" marker-end="url(#lstm-rnn-arrow-acc)"/>
<line class="dd-edge" x1="96" y1="244" x2="96" y2="212" marker-end="url(#lstm-rnn-arrow)"/>
<line class="dd-edge" x1="248" y1="244" x2="248" y2="212" marker-end="url(#lstm-rnn-arrow)"/>
<line class="dd-edge" x1="400" y1="244" x2="400" y2="212" marker-end="url(#lstm-rnn-arrow)"/>
<line class="dd-edge" x1="552" y1="244" x2="552" y2="212" marker-end="url(#lstm-rnn-arrow)"/>
<line class="dd-edge" x1="704" y1="244" x2="704" y2="212" marker-end="url(#lstm-rnn-arrow)"/>
<rect class="dd-derived" x="640" y="60" width="128" height="36" rx="6"/>
<text class="t-name" x="704" y="83" text-anchor="middle">下一個詞：法語？</text>
<rect class="dd-card" x="40" y="124" width="112" height="84" rx="6"/>
<path class="dd-card-head" d="M40 130 a6 6 0 0 1 6 -6 h100 a6 6 0 0 1 6 6 v26 h-112 z"/>
<text class="t-note" x="56" y="145">t = 1</text>
<text class="t-mono" x="56" y="173">x</text>
<text class="t-val" x="136" y="173" text-anchor="end">1</text>
<line class="dd-hair" x1="40" y1="182" x2="152" y2="182"/>
<text class="t-mono" x="56" y="199">h</text>
<text class="t-mono t-acc" x="136" y="199" text-anchor="end">0.964</text>
<rect class="dd-card" x="192" y="124" width="112" height="84" rx="6"/>
<path class="dd-card-head" d="M192 130 a6 6 0 0 1 6 -6 h100 a6 6 0 0 1 6 6 v26 h-112 z"/>
<text class="t-note" x="208" y="145">t = 2</text>
<text class="t-mono" x="208" y="173">x</text>
<text class="t-val" x="288" y="173" text-anchor="end">0</text>
<line class="dd-hair" x1="192" y1="182" x2="304" y2="182"/>
<text class="t-mono" x="208" y="199">h</text>
<text class="t-mono t-acc" x="288" y="199" text-anchor="end">0.700</text>
<rect class="dd-card" x="344" y="124" width="112" height="84" rx="6"/>
<path class="dd-card-head" d="M344 130 a6 6 0 0 1 6 -6 h100 a6 6 0 0 1 6 6 v26 h-112 z"/>
<text class="t-note" x="360" y="145">t = 3</text>
<text class="t-mono" x="360" y="173">x</text>
<text class="t-val" x="440" y="173" text-anchor="end">0</text>
<line class="dd-hair" x1="344" y1="182" x2="456" y2="182"/>
<text class="t-mono" x="360" y="199">h</text>
<text class="t-mono t-acc" x="440" y="199" text-anchor="end">0.558</text>
<rect class="dd-card" x="496" y="124" width="112" height="84" rx="6"/>
<path class="dd-card-head" d="M496 130 a6 6 0 0 1 6 -6 h100 a6 6 0 0 1 6 6 v26 h-112 z"/>
<text class="t-note" x="512" y="145">t = 4</text>
<text class="t-mono" x="512" y="173">x</text>
<text class="t-val" x="592" y="173" text-anchor="end">0</text>
<line class="dd-hair" x1="496" y1="182" x2="608" y2="182"/>
<text class="t-mono" x="512" y="199">h</text>
<text class="t-mono t-acc" x="592" y="199" text-anchor="end">0.464</text>
<rect class="dd-card" x="648" y="124" width="112" height="84" rx="6"/>
<path class="dd-card-head" d="M648 130 a6 6 0 0 1 6 -6 h100 a6 6 0 0 1 6 6 v26 h-112 z"/>
<text class="t-note" x="664" y="145">t = 5</text>
<text class="t-mono" x="664" y="173">x</text>
<text class="t-val" x="744" y="173" text-anchor="end">0</text>
<line class="dd-hair" x1="648" y1="182" x2="760" y2="182"/>
<text class="t-mono" x="664" y="199">h</text>
<text class="t-mono t-acc" x="744" y="199" text-anchor="end">0.395</text>
<rect class="dd-card" x="40" y="244" width="112" height="36" rx="6"/>
<text class="t-name" x="96" y="267" text-anchor="middle">法國</text>
<rect class="dd-card" x="192" y="244" width="112" height="36" rx="6"/>
<text class="t-name" x="248" y="267" text-anchor="middle">長大</text>
<rect class="dd-card" x="344" y="244" width="112" height="36" rx="6"/>
<text class="t-name" x="400" y="267" text-anchor="middle">後來</text>
<rect class="dd-card" x="496" y="244" width="112" height="36" rx="6"/>
<text class="t-name" x="552" y="267" text-anchor="middle">我能說</text>
<rect class="dd-card" x="648" y="244" width="112" height="36" rx="6"/>
<text class="t-name" x="704" y="267" text-anchor="middle">流利的</text>
<text class="t-say" x="40" y="304">“法國”只在第 1 步寫進 h；之後每一步 h 都先乘 0.9 再過 tanh，從 0.964 降到 0.395。</text>
<text class="t-note" x="560" y="83" text-anchor="end">虛線：要預測的詞</text>
</svg>
</div>
<figcaption>圖 1 · 迴圈網路是同一個單元按時間攤開；“法國”留在 h 裡的訊號，每過一步就被壓小一點</figcaption>
</figure>

圖 1 裡，“法國”確實被帶到了最後一步：$h_5 = 0.395$，仍然不是 0。訊號還在，只是越來越弱。**那麼問題出在哪？訊號弱一點，網路把它放大不就行了嗎？**

## 二、長期依賴與梯度消失

### 現象：近的能學會，遠的學不會

colah 用兩個句子對比了這件事[^colah-lstm]。“雲在___”，答案“天上”就在眼前，相關資訊和要預測的位置只隔兩三個字，普通 RNN 學得會。“我在法國長大……我能說流利的___”，中間隔了一大段，RNN 理論上能把“法國”帶過來，實際上卻學不會去用它。原因最早由 Hochreiter 1991 年的德文畢業論文[^hochreiter91]和 Bengio 等人 1994 年的論文[^bengio94]分析清楚。

關鍵在“學”這個字。網路的權重不是人設的，是用梯度下降一點點調出來的（[梯度下降那篇](/blog/gradient-descent-no-review/)講過整個過程）。要讓網路學會“看到法國就該說法語”，最後一步的誤差得能傳回第 1 步，告訴那時的權重該往哪邊調。**問題不在前向的訊號弱，而在反向的梯度弱。**

### 原因：梯度沿著時間連乘

訓練 RNN 用的是“沿時間反向傳播”（BPTT），聽起來像新演算法，其實就是把圖 1 那張攤開的圖當成普通的計算圖，再做一次反向傳播。colah 在 LSTM 文章四天後發表的《Calculus on Computational Graphs: Backpropagation》[^colah-backprop]把反向傳播講得很透：一條路徑上的導數，是路徑上每一條邊的導數相乘；多條路徑的導數再相加。他在那篇的結尾正好點名了 RNN 的梯度消失，作為“理解梯度怎樣在圖裡流動”的經典例子。

圖 1 裡，從 $h_1$ 到 $h_5$ 只有一條路徑，要經過 4 條邊。每一條邊 $h_{t-1} \to h_t$ 的導數是

$$
\frac{\partial h_t}{\partial h_{t-1}} = w \cdot (1 - h_t^2)
$$

前一個因子 $w = 0.9$ 來自權重，後一個 $1 - h_t^2$ 是 $\tanh$ 的導數，永遠不超過 1。把四條邊乘起來：

$$
\frac{\partial h_5}{\partial h_1} = \prod_{t=2}^{5} w\,(1-h_t^2) = 0.4587 \times 0.6196 \times 0.7062 \times 0.7597 \approx 0.1525
$$

才隔 4 個詞，梯度就只剩約 15%。每條邊的倍數最多是 $|w|$，所以隔 $T$ 步時梯度最多是 $0.9^T$：隔 50 步只剩 0.0052，隔 100 步只剩 $2.7 \times 10^{-5}$。這種逐步連乘，和 [Transformer 手算那篇](/blog/transformer-training-by-hand/)裡“沿途的倍數相乘”是同一條鏈式法則，只是 RNN 的鏈特別長，而且每一節都乘同一個小於 1 的數。

### 第一次嘗試：把 w 調大

既然是 $w$ 小於 1 惹的禍，把它調大到 1 以上呢？那就換成另一個問題：每一節都乘一個大於 1 的數，梯度會指數爆炸。Pascanu 等人 2013 年的分析把這兩件事放在一起講，並給爆炸開了一個簡單的藥方：梯度太大就按範數裁剪[^pascanu]。裁剪能管住爆炸，管不了消失。

讓 $w$ 剛好停在 1 也不行。一是 $\tanh$ 的導數 $1-h_t^2$ 只有在 $h_t$ 接近 0 時才接近 1，而 $h_t$ 一旦裝了有用的資訊就不會接近 0；二是同一個 $w$ 還要負責把新字混進來，每一步 $h_t$ 都被整個重算一遍，舊內容沒有“原樣保留”的選項。

**要讓梯度穿過很多步還不衰減，每一步的倍數必須穩定在 1 附近，而且不能依賴 tanh 的導數。有沒有一種結構，讓狀態預設就是“不變”的？**

## 三、細胞狀態：一條傳送帶

### 思路：把記憶和輸出分開，更新改成加法

LSTM 的回答是再開一條通道，叫細胞狀態 $c_t$，專門用來記東西；原來的 $h_t$ 只負責對外輸出。$c_t$ 的更新不是“整個重算”，而是“留下一部分舊的，再加上一點新的”：

$$
c_t = f_t \odot c_{t-1} + i_t \odot \tilde c_t
$$

$\odot$ 表示逐元素相乘。$f_t$ 決定舊內容留多少，$i_t$ 決定新內容寫多少，$\tilde c_t$ 是準備寫進去的新內容。這條式子裡沒有 $\tanh$ 包著 $c_{t-1}$，所以沿著 $c$ 這條路，每一步的導數就是

$$
\frac{\partial c_t}{\partial c_{t-1}} = f_t
$$

只要 $f_t$ 接近 1，梯度就能幾乎原樣穿過很多步。colah 的比喻是傳送帶：它沿著整條鏈筆直地跑過去，只有少量線性的互動，資訊很容易原封不動地沿著它流下去[^colah-lstm]。

### 歷史：最早的傳送帶上沒有遺忘門

有一點 colah 原文沒有展開：1997 年 Hochreiter 和 Schmidhuber 最早的 LSTM[^lstm97]，傳送帶上其實沒有 $f_t$，相當於 $f_t$ 恆等於 1，$c_t = c_{t-1} + i_t \odot \tilde c_t$。這個結構叫“恆定誤差傳送帶”（constant error carousel），沿它回傳的梯度正好是 1，一點不衰減[^greff]。

代價是只能加不能減。Gers、Schmidhuber 和 Cummins 2000 年發現，輸入是一條沒有明確結尾的連續資料流時，細胞狀態會一直累加，直到網路失效；他們加上遺忘門，讓單元學會在合適的時候把自己清空[^gers-forget]。colah 原文腳註裡列了一串把 LSTM “改進並推廣”的名字，Gers 是第一個；我們今天說的“標準 LSTM”，是帶遺忘門的這一版。

### 門：一個 sigmoid 層加一次逐元素乘法

$f_t$、$i_t$ 和後面的 $o_t$ 都叫“門”。colah 對門的定義很乾脆：一個 sigmoid 神經網路層，加一次逐元素乘法[^colah-lstm]。sigmoid 函式 $\sigma(z) = 1/(1+e^{-z})$ 把任何數壓到 0 和 1 之間，0 表示“什麼都不放過去”，1 表示“全部放過去”。門的值不是固定的，它看著當前的輸入和上一步的輸出，每一步重新算一次。

圖 2 是我們那個單元在第 1 步、剛讀到“法國”時的樣子，圖上的數都是實際算出來的。

<figure class="dd dd-figure">
<div class="dd-scroll">
<svg class="dd-svg" viewBox="0 0 800 392" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="lstm-cell-title lstm-cell-desc">
<title id="lstm-cell-title">讀到“法國”時的 LSTM 單元</title>
<desc id="lstm-cell-desc">細胞狀態 c 沿頂部的傳送帶從 0 流到 0.918，途中經過一次乘法和一次加法；下方四個層分別算出遺忘門 0.269、輸入門 0.953、候選值 0.964、輸出門 0.881；輸出 h 等於 0.881 乘以 tanh(0.918)，即 0.639。</desc>
<defs>
<marker id="lstm-cell-arrow" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto"><path class="dd-head" d="M1 1 L7 4 L1 7"/></marker>
<marker id="lstm-cell-arrow-acc" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto"><path class="dd-head-acc" d="M1 1 L7 4 L1 7"/></marker>
</defs>
<rect class="dd-frame" width="800" height="392" rx="10"/>
<rect class="dd-zone" x="16" y="16" width="768" height="360" rx="8"/>
<text class="t-zone" x="40" y="44">第 1 步：讀到“法國”時，單元裡的每個數</text>
<line class="dd-edge-acc" x1="40" y1="96" x2="756" y2="96" marker-end="url(#lstm-cell-arrow-acc)"/>
<line class="dd-edge" x1="40" y1="280" x2="592" y2="280"/>
<line class="dd-edge" x1="240" y1="280" x2="240" y2="248" marker-end="url(#lstm-cell-arrow)"/>
<line class="dd-edge" x1="352" y1="280" x2="352" y2="248" marker-end="url(#lstm-cell-arrow)"/>
<line class="dd-edge" x1="464" y1="280" x2="464" y2="248" marker-end="url(#lstm-cell-arrow)"/>
<line class="dd-edge" x1="592" y1="280" x2="592" y2="248" marker-end="url(#lstm-cell-arrow)"/>
<line class="dd-edge" x1="240" y1="196" x2="240" y2="113" marker-end="url(#lstm-cell-arrow)"/>
<path class="dd-edge" d="M352 196 V160 Q352 152 360 152 H392" marker-end="url(#lstm-cell-arrow)"/>
<path class="dd-edge" d="M464 196 V160 Q464 152 456 152 H424" marker-end="url(#lstm-cell-arrow)"/>
<line class="dd-edge-acc" x1="408" y1="140" x2="408" y2="113" marker-end="url(#lstm-cell-arrow-acc)"/>
<line class="dd-edge" x1="688" y1="96" x2="688" y2="132" marker-end="url(#lstm-cell-arrow)"/>
<line class="dd-edge" x1="688" y1="164" x2="688" y2="202" marker-end="url(#lstm-cell-arrow)"/>
<line class="dd-edge" x1="640" y1="220" x2="672" y2="220" marker-end="url(#lstm-cell-arrow)"/>
<path class="dd-edge" d="M688 230 V320 Q688 328 696 328 H756" marker-end="url(#lstm-cell-arrow)"/>
<circle class="dd-card" cx="240" cy="96" r="13"/>
<text class="t-name" x="240" y="101" text-anchor="middle">×</text>
<circle class="dd-card" cx="408" cy="96" r="13"/>
<text class="t-name" x="408" y="101" text-anchor="middle">+</text>
<circle class="dd-card" cx="408" cy="152" r="12"/>
<text class="t-name" x="408" y="157" text-anchor="middle">×</text>
<circle class="dd-card" cx="688" cy="218" r="12"/>
<text class="t-name" x="688" y="223" text-anchor="middle">×</text>
<rect class="dd-card" x="656" y="136" width="64" height="28" rx="6"/>
<text class="t-mono" x="688" y="154" text-anchor="middle">tanh</text>
<text class="t-mono" x="40" y="84">c₀ = 0</text>
<text class="t-mono t-acc" x="756" y="84" text-anchor="end">c₁ = 0.918</text>
<text class="t-note" x="248" y="150">0.269 × 0 = 0</text>
<text class="t-val" x="420" y="132">0.953 × 0.964 = 0.918</text>
<text class="t-note" x="648" y="154" text-anchor="end">0.725</text>
<rect class="dd-card" x="192" y="196" width="96" height="48" rx="6"/>
<text class="t-name" x="240" y="216" text-anchor="middle">遺忘門 f</text>
<text class="t-val" x="240" y="234" text-anchor="middle">σ → 0.269</text>
<rect class="dd-card" x="304" y="196" width="96" height="48" rx="6"/>
<text class="t-name" x="352" y="216" text-anchor="middle">輸入門 i</text>
<text class="t-val" x="352" y="234" text-anchor="middle">σ → 0.953</text>
<rect class="dd-card" x="416" y="196" width="96" height="48" rx="6"/>
<text class="t-name" x="464" y="216" text-anchor="middle">候選值 c̃</text>
<text class="t-val" x="464" y="234" text-anchor="middle">tanh→0.964</text>
<rect class="dd-card" x="544" y="196" width="96" height="48" rx="6"/>
<text class="t-name" x="592" y="216" text-anchor="middle">輸出門 o</text>
<text class="t-val" x="592" y="234" text-anchor="middle">σ → 0.881</text>
<text class="t-mono" x="40" y="304">[h₀, x₁] = [0, 1]</text>
<text class="t-mono" x="756" y="352" text-anchor="end">h₁ = 0.881 × 0.725 = 0.639</text>
<text class="t-say" x="40" y="352">傳送帶上只有一次乘法、一次加法。</text>
</svg>
</div>
<figcaption>圖 2 · LSTM 單元：記憶走頂上的傳送帶，四個小層只負責算出往帶上乘什麼、加什麼、往外輸出多少</figcaption>
</figure>

**圖 2 裡的 0.269、0.953 這些數是怎麼算出來的？每道門的公式裡，每個符號又是什麼？**

## 四、三道門逐步拆開

colah 原文的公式畫在圖裡，下面照抄，只把他的 $C_t$ 寫成 $c_t$，把逐元素乘法 $*$ 寫成 $\odot$[^colah-lstm]。

### 輸入：把上一步的輸出和這一步的字拼起來

四個小層吃的是同一個東西：$[h_{t-1}, x_t]$，即把上一步的輸出 $h_{t-1}$（長度 $n$）和這一步的輸入 $x_t$（長度 $m$）首尾拼成一個長度 $n+m$ 的向量。每個小層各有一個 $n \times (n+m)$ 的權重矩陣和一個長度 $n$ 的偏置，輸出長度都是 $n$，和細胞狀態一樣長，這樣才能逐元素地去乘、去加。

### 遺忘門：舊內容留多少

$$
f_t = \sigma\big(W_f \cdot [h_{t-1}, x_t] + b_f\big)
$$

$W_f$、$b_f$ 是遺忘門自己的權重和偏置，$\sigma$ 把結果壓到 0 到 1。$f_t$ 的每個分量對應 $c_{t-1}$ 的一個分量：1 是“完全保留”，0 是“完全丟掉”。colah 的例子是：細胞狀態裡可能記著當前主語的性別，好選對代名詞；看到一個新主語時，就該把舊主語的性別忘掉[^colah-lstm]。

我們的單元只有一個分量。為了手算方便，我們讓四個小層都不看 $h_{t-1}$（即權重裡對應 $h_{t-1}$ 的那一列取 0），只看 $x_t$，並直接設定權重：

$$
f_t = \sigma(-4x_t + 3),\quad i_t = \sigma(6x_t - 3),\quad \tilde c_t = \tanh(2x_t),\quad o_t = \sigma(2)
$$

讀到“法國”（$x=1$）時，$f_1 = \sigma(-1) = 0.269$，傳送帶上的舊內容大半被清掉，相當於“新的主語來了”；讀到普通詞（$x=0$）時，$f_t = \sigma(3) = 0.953$，舊內容幾乎全留下。

### 輸入門與候選值：寫什麼、寫多少

$$
i_t = \sigma\big(W_i \cdot [h_{t-1}, x_t] + b_i\big), \qquad \tilde c_t = \tanh\big(W_c \cdot [h_{t-1}, x_t] + b_c\big)
$$

寫入被拆成兩半。$\tilde c_t$ 是候選內容，用 $\tanh$ 是因為它要能取負值，才能把某個分量往下調；$i_t$ 是寫入的力度，用 $\sigma$ 是因為它只表示“多少”。為什麼不合成一個？因為“這一步有沒有值得記的東西”和“值得記的是什麼”是兩個問題：普通詞的候選內容可以是任何數，只要 $i_t$ 接近 0，它就寫不進去。

我們的單元讀到“法國”時，$i_1 = \sigma(3) = 0.953$，$\tilde c_1 = \tanh(2) = 0.964$；讀到普通詞時，$i_t = \sigma(-3) = 0.047$，$\tilde c_t = 0$。

### 更新傳送帶

$$
c_t = f_t \odot c_{t-1} + i_t \odot \tilde c_t
$$

第 1 步，$c_1 = 0.269 \times 0 + 0.953 \times 0.964 = 0.918$，“法國”寫上了傳送帶。第 2 步，$c_2 = 0.953 \times 0.918 + 0.047 \times 0 = 0.875$。之後每讀一個普通詞，$c$ 只乘一次 0.953。

### 輸出門：這一步對外說什麼

$$
o_t = \sigma\big(W_o \cdot [h_{t-1}, x_t] + b_o\big), \qquad h_t = o_t \odot \tanh(c_t)
$$

細胞狀態裡記的東西，不一定此刻都要說出來。$\tanh(c_t)$ 先把細胞狀態壓到 $-1$ 到 $1$，$o_t$ 再決定放出去多少。colah 的例子是：剛看到一個主語，下一個詞可能是動詞，這時該輸出的是“主語是單數還是複數”，好讓動詞變位正確[^colah-lstm]。我們的單元裡 $o_t = \sigma(2) = 0.881$ 是個常數，$h_1 = 0.881 \times \tanh(0.918) = 0.639$。$h_t$ 一方面是這一步的輸出，一方面又作為 $h_{t-1}$ 送進下一步的四個小層。

表 1 是整句話走完的結果，最後一欄是圖 1 那個普通 RNN，用來對照。

<figure class="dd dd-figure dt-figure">
<div class="dt-panel">
<div class="dt-title" id="lstm-trace-title">單元 LSTM 讀完五個詞</div>
<div class="dt-scroll">
<table class="dt dt-sticky" aria-labelledby="lstm-trace-title">
<colgroup><col><col><col><col><col><col class="hl"><col><col></colgroup>
<thead>
<tr><th scope="col" style="white-space:nowrap">詞</th><th scope="col" class="c">x</th><th scope="col" class="num">f</th><th scope="col" class="num">i</th><th scope="col" class="num">c̃</th><th scope="col" class="num acc">c</th><th scope="col" class="num">h</th><th scope="col" class="num">RNN 的 h</th></tr>
</thead>
<tbody>
<tr><th scope="row" style="white-space:nowrap">法國</th><td class="mono c">1</td><td class="mono num">0.2689</td><td class="mono num">0.9526</td><td class="mono num">0.9640</td><td class="mono num acc">0.9183</td><td class="mono num">0.6387</td><td class="mono num">0.9640</td></tr>
<tr><th scope="row" style="white-space:nowrap">長大</th><td class="mono c">0</td><td class="mono num">0.9526</td><td class="mono num">0.0474</td><td class="mono num">0</td><td class="mono num acc">0.8748</td><td class="mono num">0.6199</td><td class="mono num">0.7002</td></tr>
<tr><th scope="row" style="white-space:nowrap">後來</th><td class="mono c">0</td><td class="mono num">0.9526</td><td class="mono num">0.0474</td><td class="mono num">0</td><td class="mono num acc">0.8333</td><td class="mono num">0.6009</td><td class="mono num">0.5582</td></tr>
<tr><th scope="row" style="white-space:nowrap">我能說</th><td class="mono c">0</td><td class="mono num">0.9526</td><td class="mono num">0.0474</td><td class="mono num">0</td><td class="mono num acc">0.7938</td><td class="mono num">0.5818</td><td class="mono num">0.4640</td></tr>
<tr><th scope="row" style="white-space:nowrap">流利的</th><td class="mono c">0</td><td class="mono num">0.9526</td><td class="mono num">0.0474</td><td class="mono num">0</td><td class="mono num acc">0.7561</td><td class="mono num">0.5626</td><td class="mono num">0.3949</td></tr>
<tr class="dt-group"><th colspan="8" scope="rowgroup">從第 5 步回到第 1 步的梯度</th></tr>
<tr><th scope="row" style="white-space:nowrap">連乘</th><td colspan="5" class="mono acc">∂c₅/∂c₁ = 0.9526⁴ = 0.8234</td><td colspan="2" class="mono">∂h₅/∂h₁ = 0.1525</td></tr>
</tbody>
</table>
</div>
<p class="dt-note">四個小層只看 x，不看上一步的 h，這是為了手算而做的簡化；文末程式用自動求導核對了最後一行。</p>
</div>
<figcaption>表 1 · 同樣隔 4 個詞，傳送帶上的梯度還剩 82%，普通 RNN 只剩 15%</figcaption>
</figure>

### 手算核對：梯度留下了多少

因為我們讓門不看 $h_{t-1}$，沿傳送帶從 $c_5$ 回到 $c_1$ 的導數就是四個遺忘門相乘：$0.9526^4 = 0.8234$。同樣的距離，普通 RNN 是 0.1525。真實的 LSTM 裡，門也看 $h_{t-1}$，梯度還會沿“$c \to h \to$ 門 $\to c$”這些旁路走，那些路徑照樣會衰減；但傳送帶這一條始終在，只要遺忘門接近 1，它就不衰減。

這也說明了遺忘門偏置的重要。圖 3 把“隔 $T$ 步後梯度剩下的倍數”畫在對數座標上：普通 RNN 的上限是 $0.9^T$；遺忘門停在 $\sigma(3) = 0.953$ 時，50 步後剩 8.8%；把偏置再調大到讓 $\sigma(5) = 0.993$，50 步後還剩 71%。Jozefowicz、Zaremba 和 Sutskever 2015 年在一萬多種結構裡做搜尋，最實用的發現之一就是：把 LSTM 遺忘門的偏置初始化為 1，就能追平 GRU；這個做法 Gers 等人 2000 年就提過，只是後來的論文很少再提[^jozefowicz]。

<figure class="dd dd-figure">
<div class="dd-scroll">
<svg class="dd-svg" viewBox="0 0 800 360" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="lstm-grad-title lstm-grad-desc">
<title id="lstm-grad-title">隔 T 步後梯度剩下的倍數</title>
<desc id="lstm-grad-desc">對數座標下三條直線：普通 RNN 的上限 0.9 的 T 次方在 50 步時是 0.0052；遺忘門 0.953 的 LSTM 在 50 步時是 0.088；遺忘門 0.993 的 LSTM 在 50 步時是 0.71。</desc>
<rect class="dd-frame" width="800" height="360" rx="10"/>
<rect class="dd-zone" x="16" y="16" width="768" height="328" rx="8"/>
<text class="t-zone" x="40" y="44">梯度往回傳 T 步後剩下的倍數（對數座標）</text>
<line class="dd-hair" x1="96" y1="72" x2="640" y2="72"/>
<line class="dd-hair" x1="96" y1="112" x2="640" y2="112"/>
<line class="dd-hair" x1="96" y1="152" x2="640" y2="152"/>
<line class="dd-hair" x1="96" y1="192" x2="640" y2="192"/>
<line class="dd-hair" x1="96" y1="232" x2="640" y2="232"/>
<line class="dd-hair" x1="368" y1="72" x2="368" y2="272"/>
<line class="dd-edge" x1="96" y1="272" x2="640" y2="272"/>
<text class="t-note" x="88" y="76" text-anchor="end">1</text>
<text class="t-note" x="88" y="116" text-anchor="end">0.1</text>
<text class="t-note" x="88" y="156" text-anchor="end">0.01</text>
<text class="t-note" x="88" y="196" text-anchor="end">10⁻³</text>
<text class="t-note" x="88" y="236" text-anchor="end">10⁻⁴</text>
<text class="t-note" x="88" y="276" text-anchor="end">10⁻⁵</text>
<text class="t-note" x="96" y="292" text-anchor="middle">0</text>
<text class="t-note" x="232" y="292" text-anchor="middle">25</text>
<text class="t-note" x="368" y="292" text-anchor="middle">50</text>
<text class="t-note" x="504" y="292" text-anchor="middle">75</text>
<text class="t-note" x="640" y="292" text-anchor="middle">100</text>
<text class="t-note" x="368" y="314" text-anchor="middle">往回隔了幾步 T</text>
<line class="dd-edge dd-dash" x1="96" y1="72" x2="640" y2="255"/>
<line class="dd-edge" x1="96" y1="72" x2="640" y2="156.4"/>
<line class="dd-edge-acc" x1="96" y1="72" x2="640" y2="83.7"/>
<circle class="dd-dot" cx="368" cy="163.5" r="4"/>
<circle class="dd-dot" cx="368" cy="114.2" r="4"/>
<circle class="dd-fill-acc" cx="368" cy="77.8" r="4"/>
<text class="t-mono t-acc" x="376" y="96">0.71</text>
<text class="t-mono" x="376" y="134">0.088</text>
<text class="t-mono" x="360" y="184" text-anchor="end">0.0052</text>
<text class="t-mono t-acc" x="648" y="88">LSTM f = 0.993</text>
<text class="t-mono" x="648" y="160">LSTM f = 0.953</text>
<text class="t-mono" x="648" y="259">RNN 上限 0.9^T</text>
<text class="t-say" x="40" y="336">每步乘同一個數，在對數座標上就是一條直線；斜率只由那個數決定。</text>
</svg>
</div>
<figcaption>圖 3 · 遺忘門從 0.953 提到 0.993，隔 50 步後剩下的梯度從 9% 變成 71%；普通 RNN 最多剩 0.5%</figcaption>
</figure>

圖 3 也提醒我們一件事：LSTM 不是無限記憶。遺忘門只要不是恰好等於 1，梯度照樣按指數衰減，只是衰減得慢得多。這一點到第六節會再用上。

**標準 LSTM 有四個小層、三道門。這些設計是不是都必要？能不能少一點？**

## 五、變體：窺視孔、耦合門與 GRU

colah 說，幾乎每篇用到 LSTM 的論文，用的版本都略有不同[^colah-lstm]。他挑了三種最常見的。

### 窺視孔：讓門看見細胞狀態

標準 LSTM 的門只看 $h_{t-1}$ 和 $x_t$，看不見細胞狀態本身；如果上一步輸出門關著，$h_{t-1}$ 裡就幾乎沒有 $c_{t-1}$ 的資訊。Gers 和 Schmidhuber 2000 年加了“窺視孔”連線，讓門直接看細胞狀態[^gers-peephole]，colah 圖裡的寫法是

$$
f_t = \sigma\big(W_f \cdot [c_{t-1}, h_{t-1}, x_t] + b_f\big),\quad i_t = \sigma\big(W_i \cdot [c_{t-1}, h_{t-1}, x_t] + b_i\big),\quad o_t = \sigma\big(W_o \cdot [c_t, h_{t-1}, x_t] + b_o\big)
$$

注意輸出門看的是更新後的 $c_t$。他們的動機是讓網路學會精確計時和計數，這需要門知道細胞裡已經數到了幾[^greff]。colah 也提到，很多論文只給一部分門加窺視孔。

### 耦合門：忘多少，就寫多少

另一種想法是把遺忘和寫入綁在一起：只在要寫新東西時才忘，忘掉多少就補進多少：

$$
c_t = f_t \odot c_{t-1} + (1 - f_t) \odot \tilde c_t
$$

輸入門沒了，少一個小層。放回我們的單元，第 1 步 $c_1 = (1 - 0.269) \times 0.964 = 0.705$；之後讀普通詞時 $1 - f_t = 0.047$，和原來的 $i_t$ 恰好相同，所以衰減方式不變。$c_t$ 這時是新舊內容的加權平均，不會無限增長。

### GRU：把細胞狀態和輸出合成一個

Cho 等人 2014 年提出的門控迴圈單元（GRU）[^cho]走得更遠。colah 圖裡的公式是

$$
z_t = \sigma\big(W_z \cdot [h_{t-1}, x_t]\big),\quad r_t = \sigma\big(W_r \cdot [h_{t-1}, x_t]\big)
$$

$$
\tilde h_t = \tanh\big(W \cdot [r_t \odot h_{t-1}, x_t]\big),\quad h_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde h_t
$$

逐個看：$z_t$ 叫更新門，它就是耦合門，同時扮演遺忘門（$1-z_t$）和輸入門（$z_t$）；$r_t$ 叫重置門，決定算候選值 $\tilde h_t$ 時要參考多少舊狀態，$r_t$ 接近 0 時，候選值幾乎只看當前輸入，相當於“從頭開始”；最後一行就是傳送帶，只是帶上跑的直接是 $h_t$，沒有單獨的 $c_t$，也沒有輸出門。colah 的圖裡省略了偏置。

有一個容易踩的坑：Cho 等人原文把 $z$ 乘在舊狀態上，寫成 $h_t = z_t \odot h_{t-1} + (1 - z_t) \odot \tilde h_t$[^cho]，和 colah 的圖正好互換。兩種寫法等價，只是 $z$ 的含義反過來；讀程式碼或論文時要先看清楚是哪一種。

### 哪個更好

表 2 把三種變體放在一起，參數量按每個小層一組權重和偏置計，取隱狀態 $n = 128$、輸入 $m = 64$。

<figure class="dd dd-figure dt-figure">
<div class="dt-panel">
<div class="dt-title" id="lstm-var-title">LSTM 的三種常見變體</div>
<div class="dt-scroll">
<table class="dt" aria-labelledby="lstm-var-title">
<colgroup><col style="width:22%"><col><col style="width:26%"></colgroup>
<thead>
<tr><th scope="col">結構</th><th scope="col">相對標準 LSTM 改了什麼</th><th scope="col" class="num">每層參數（n=128, m=64）</th></tr>
</thead>
<tbody>
<tr><th scope="row">標準 LSTM</th><td>四個小層：f、i、c̃、o</td><td class="mono num">98,816</td></tr>
<tr><th scope="row">窺視孔</th><td>門額外看細胞狀態；常見做法是每道門一個對角權重</td><td class="mono num">99,200</td></tr>
<tr><th scope="row">耦合門</th><td>用 1 − f 代替 i，去掉輸入門</td><td class="mono num">74,112</td></tr>
<tr><th scope="row">GRU</th><td>合併 c 和 h；更新門兼任遺忘和寫入；去掉輸出門，另加重置門</td><td class="mono num">74,112</td></tr>
</tbody>
</table>
</div>
<p class="dt-note">標準 LSTM：4 × (128 × 192 + 128)；耦合門和 GRU：3 × (128 × 192 + 128)。實際框架的偏置數可能不同，例如 PyTorch 的 GRU 每個門有兩組偏置。</p>
</div>
<figcaption>表 2 · 變體之間的差別主要在省掉哪個門，參數量最多差四分之一</figcaption>
</figure>

改了這麼多，效果差多少？colah 引了兩篇大規模比較[^colah-lstm]。Greff 等人 2015 年比較了 8 種變體，在語音辨識、手寫辨識和復調音樂建模三個任務上跑了 5400 次實驗，結論是沒有一種變體顯著優於標準 LSTM，最關鍵的兩個部件是遺忘門和輸出啟用函式[^greff]。Jozefowicz 等人搜尋了一萬多種結構，找到在部分任務上比 LSTM 和 GRU 都好的，但不是全部任務；他們給的實用建議是先把遺忘門偏置調到 1，再考慮換結構[^jozefowicz]。Chung 等人同年的對比也發現 GRU 和 LSTM 大體相當[^chung]。

這些結果放在一起，說的是同一件事：**真正起作用的是“帶遺忘門的加法傳送帶”這個骨架**，其餘部件怎麼增減，影響都不大。

**骨架已經定型。那 LSTM 剩下的瓶頸在哪裡？**

## 六、下一步是注意力

### 原文結尾那句話

colah 在結尾寫道：LSTM 是 RNN 能力上的一大步，很自然要問，還有沒有下一大步？研究者的普遍看法是：有，下一步是注意力。它的想法是讓 RNN 的每一步都從一個更大的資訊集合裡挑出要看的部分；比如用 RNN 給圖片寫說明時，每輸出一個詞，就挑圖片的一個部位去看。他推薦的入門例子是 Xu 等人 2015 年的工作[^colah-lstm][^xu]。

### 瓶頸：整句話擠在一個固定大小的向量裡

LSTM 在 2014 年迎來了機器翻譯上的成功。Sutskever、Vinyals 和 Le 用一個多層 LSTM 把整個英文句子讀成一個固定長度的向量，再用另一個多層 LSTM 從這個向量生成法文，在 WMT'14 英法翻譯上拿到 34.8 BLEU，超過了片語式統計翻譯的 33.3[^sutskever]。

但這篇論文裡有一個耐人尋味的技巧：把源句的詞序整個倒過來輸入，效果明顯變好。作者的解釋是，倒過來之後，源句開頭的詞和譯文開頭的詞離得近了，引入了很多短距離依賴，最佳化變容易了[^sutskever]。換句話說，即使有了傳送帶，**距離仍然是個問題**。這和第四節的結論一致：遺忘門不等於 1，記憶就會衰減；而且整句話不管多長，都要擠進同一個大小的 $c$ 裡。

Bahdanau、Cho 和 Bengio 同年把這個問題直接點破：他們推測，固定長度向量是編碼器—解碼器結構的瓶頸，於是讓解碼器每生成一個詞，都對源句做一次“軟搜尋”，自己決定看哪幾個位置[^bahdanau]。

### 注意力怎樣繞開距離

colah 和 Shan Carter 2016 年在 Distill 上發表的《Attention and Augmented Recurrent Neural Networks》，就是 LSTM 那篇結尾的續集[^distill-attn]。他們介紹了四種給 RNN 加能力的辦法：能讀寫外部記憶的神經圖靈機、能聚焦輸入局部的注意力介面、每步計算量可變的自適應計算時間、能邊跑邊呼叫函式的神經程式設計器，並指出這四種都依賴同一個底層技巧：注意力。其中基於內容的注意力是這樣算的：拿一個查詢向量 $q$ 和每個位置的向量 $k$ 做點積打分，再用 softmax 把分數變成權重。

圖 4 用我們那句話對比兩種做法。為了能手算，我們給“法國”一個和查詢對得上的向量，讓 $q \cdot k = 3$，其餘四個詞 $q \cdot k = 0$。

<figure class="dd dd-figure">
<div class="dd-scroll">
<svg class="dd-svg" viewBox="0 0 800 420" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="lstm-attn-title lstm-attn-desc">
<title id="lstm-attn-title">迴圈與注意力的資訊路徑</title>
<desc id="lstm-attn-desc">上半：法國的資訊要經過長大、後來、我能說、流利的四次狀態更新才到達預測位置。下半：預測法語時直接回看五個位置，打分 3、0、0、0、0，softmax 後權重是 0.83、0.04、0.04、0.04、0.04。</desc>
<defs>
<marker id="lstm-attn-arrow" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto"><path class="dd-head" d="M1 1 L7 4 L1 7"/></marker>
<marker id="lstm-attn-arrow-acc" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto"><path class="dd-head-acc" d="M1 1 L7 4 L1 7"/></marker>
</defs>
<rect class="dd-frame" width="800" height="420" rx="10"/>
<rect class="dd-zone" x="16" y="16" width="768" height="180" rx="8"/>
<rect class="dd-zone" x="16" y="212" width="768" height="192" rx="8"/>
<text class="t-zone" x="40" y="44">迴圈：法國的資訊要一站一站傳過去</text>
<line class="dd-edge-acc" x1="136" y1="114" x2="164" y2="114" marker-end="url(#lstm-attn-arrow-acc)"/>
<line class="dd-edge-acc" x1="264" y1="114" x2="292" y2="114" marker-end="url(#lstm-attn-arrow-acc)"/>
<line class="dd-edge-acc" x1="392" y1="114" x2="420" y2="114" marker-end="url(#lstm-attn-arrow-acc)"/>
<line class="dd-edge-acc" x1="520" y1="114" x2="548" y2="114" marker-end="url(#lstm-attn-arrow-acc)"/>
<line class="dd-edge-acc" x1="648" y1="114" x2="676" y2="114" marker-end="url(#lstm-attn-arrow-acc)"/>
<rect class="dd-card" x="40" y="96" width="96" height="36" rx="6"/>
<text class="t-name t-acc" x="88" y="119" text-anchor="middle">法國</text>
<rect class="dd-card" x="168" y="96" width="96" height="36" rx="6"/>
<text class="t-name" x="216" y="119" text-anchor="middle">長大</text>
<rect class="dd-card" x="296" y="96" width="96" height="36" rx="6"/>
<text class="t-name" x="344" y="119" text-anchor="middle">後來</text>
<rect class="dd-card" x="424" y="96" width="96" height="36" rx="6"/>
<text class="t-name" x="472" y="119" text-anchor="middle">我能說</text>
<rect class="dd-card" x="552" y="96" width="96" height="36" rx="6"/>
<text class="t-name" x="600" y="119" text-anchor="middle">流利的</text>
<rect class="dd-derived" x="680" y="96" width="96" height="36" rx="6"/>
<text class="t-name" x="728" y="119" text-anchor="middle">法語？</text>
<text class="t-note" x="40" y="80">每個箭頭是一次狀態更新：c 乘 f，再加 i·c̃</text>
<text class="t-note" x="776" y="80" text-anchor="end">虛線：要預測的詞</text>
<text class="t-say" x="40" y="172">從法國到法語隔著 5 次更新，所有內容都擠在同一個固定大小的 c 裡。</text>
<text class="t-zone" x="40" y="240">注意力：預測法語時，直接回看每一個位置</text>
<path class="dd-edge-acc" d="M744 332 V276 Q744 268 736 268 H96 Q88 268 88 276 V328" marker-end="url(#lstm-attn-arrow-acc)"/>
<path class="dd-edge" d="M712 332 V292 Q712 284 704 284 H224 Q216 284 216 292 V328" marker-end="url(#lstm-attn-arrow)"/>
<line class="dd-edge" x1="344" y1="284" x2="344" y2="328" marker-end="url(#lstm-attn-arrow)"/>
<line class="dd-edge" x1="472" y1="284" x2="472" y2="328" marker-end="url(#lstm-attn-arrow)"/>
<line class="dd-edge" x1="600" y1="284" x2="600" y2="328" marker-end="url(#lstm-attn-arrow)"/>
<text class="t-mono t-acc" x="96" y="312">q·k=3 → 0.83</text>
<text class="t-mono" x="222" y="312">q·k=0 → 0.04</text>
<text class="t-mono" x="350" y="312">0.04</text>
<text class="t-mono" x="478" y="312">0.04</text>
<text class="t-mono" x="606" y="312">0.04</text>
<rect class="dd-card" x="40" y="332" width="96" height="36" rx="6"/>
<text class="t-name t-acc" x="88" y="355" text-anchor="middle">法國</text>
<rect class="dd-card" x="168" y="332" width="96" height="36" rx="6"/>
<text class="t-name" x="216" y="355" text-anchor="middle">長大</text>
<rect class="dd-card" x="296" y="332" width="96" height="36" rx="6"/>
<text class="t-name" x="344" y="355" text-anchor="middle">後來</text>
<rect class="dd-card" x="424" y="332" width="96" height="36" rx="6"/>
<text class="t-name" x="472" y="355" text-anchor="middle">我能說</text>
<rect class="dd-card" x="552" y="332" width="96" height="36" rx="6"/>
<text class="t-name" x="600" y="355" text-anchor="middle">流利的</text>
<rect class="dd-derived" x="680" y="332" width="96" height="36" rx="6"/>
<text class="t-name" x="728" y="355" text-anchor="middle">法語？</text>
<text class="t-say" x="40" y="392">權重 = softmax(q·k)：法國到法語只隔一步，代價是每個位置都要和前面所有位置打一次分。</text>
</svg>
</div>
<figcaption>圖 4 · 迴圈要把資訊一站一站傳過去；注意力讓預測位置直接回看，路徑長度和距離無關</figcaption>
</figure>

softmax 的計算是 $e^3 / (e^3 + 4) = 20.09 / 24.09 \approx 0.83$，其餘四個各約 0.04。不管“法國”在 5 個詞之前還是 500 個詞之前，路徑都只有一步，不用經過任何遺忘門。Distill 那篇也說清了代價：注意力每一步都要碰所有記憶位置，計算量隨長度線性增長[^distill-attn]；放到每個位置都這樣做，整句就是平方級。

### 從 LSTM 加注意力，到只要注意力

接下來兩年，“LSTM + 注意力”成了主流。2016 年 Google 的神經機器翻譯系統用的是 8 層編碼器、8 層解碼器的 LSTM，中間用注意力連起來，層間加殘差連線[^gnmt]。這大概是 LSTM 在工業界最風光的時候。

2017 年的《Attention Is All You Need》把迴圈整個拿掉，只留注意力。論文摘要寫得很直接：當時最好的序列模型是帶注意力的迴圈或卷積網路，而他們的 Transformer 完全不用迴圈和卷積，品質更好，更容易並行，訓練時間少得多；WMT 2014 英德翻譯 28.4 BLEU，英法 41.8 BLEU，在 8 張 GPU 上訓練 3.5 天[^vaswani]。

“更容易並行”是關鍵。LSTM 的第 $t$ 步要等第 $t-1$ 步的 $h_{t-1}$ 算完，整句話是一條鏈；Transformer 的注意力分數可以寫成一次矩陣乘法，一起算完。[大模型為什麼最近才出現那篇](/blog/llm-why-now/)的圖 11 畫的就是這個區別，以及它為什麼正好中了 GPU 的“硬體彩票”。注意力的每一步具體怎樣算、梯度怎樣傳，可以看 [Transformer 手算那篇](/blog/transformer-training-by-hand/)。而 Karpathy 的 char-rnn 用的訓練目標，和今天的大模型一樣，都是逐字的交叉熵，也就是[困惑度那篇](/blog/perplexity-explained/)裡那個數的對數。

**注意力用“每步看全部”換掉了“一站一站傳”。到了 2026 年回頭看，這筆交換是不是一邊倒？**

## 七、2026 年回看：LSTM 在哪裡，新的迴圈又是什麼

先把三十多年的脈絡放在一張圖上。

<figure class="dd dd-figure">
<div class="dd-scroll">
<svg class="dd-svg" viewBox="0 0 800 400" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="lstm-time-title lstm-time-desc">
<title id="lstm-time-title">從梯度消失到新的迴圈模型</title>
<desc id="lstm-time-desc">1991 年 Hochreiter 分析梯度消失，1994 年 Bengio 等指出長期依賴難學，1997 年 LSTM，2000 年遺忘門；2014 年 GRU、seq2seq 和 Bahdanau 注意力，2015 年 colah 的文章，2016 年 GNMT，2017 年 Transformer，2020 年線性注意力，2023 年 Mamba，2024 年 xLSTM 和 minGRU、minLSTM，2025 年 xLSTM 7B 和 TiRex。</desc>
<rect class="dd-frame" width="800" height="400" rx="10"/>
<rect class="dd-zone" x="16" y="16" width="768" height="132" rx="8"/>
<rect class="dd-zone" x="16" y="164" width="768" height="220" rx="8"/>
<text class="t-zone" x="40" y="44">1991–2000：發現問題，修補迴圈</text>
<line class="dd-edge" x1="64" y1="72" x2="760" y2="72"/>
<circle class="dd-dot" cx="112" cy="72" r="5"/>
<circle class="dd-dot" cx="296" cy="72" r="5"/>
<circle class="dd-dot" cx="480" cy="72" r="5"/>
<circle class="dd-fill-acc" cx="664" cy="72" r="5"/>
<text class="t-mono" x="112" y="96" text-anchor="middle">1991</text>
<text class="t-note" x="112" y="114" text-anchor="middle">Hochreiter 畢業論文</text>
<text class="t-note" x="112" y="130" text-anchor="middle">分析梯度消失</text>
<text class="t-mono" x="296" y="96" text-anchor="middle">1994</text>
<text class="t-note" x="296" y="114" text-anchor="middle">Bengio 等</text>
<text class="t-note" x="296" y="130" text-anchor="middle">長期依賴難以學習</text>
<text class="t-mono" x="480" y="96" text-anchor="middle">1997</text>
<text class="t-note" x="480" y="114" text-anchor="middle">LSTM</text>
<text class="t-note" x="480" y="130" text-anchor="middle">Hochreiter &amp; Schmidhuber</text>
<text class="t-mono t-acc" x="664" y="96" text-anchor="middle">2000</text>
<text class="t-note" x="664" y="114" text-anchor="middle">遺忘門</text>
<text class="t-note" x="664" y="130" text-anchor="middle">Gers、Schmidhuber、Cummins</text>
<text class="t-zone" x="40" y="192">2014–2025：注意力取代迴圈，迴圈又換了形式回來</text>
<line class="dd-edge" x1="64" y1="284" x2="760" y2="284"/>
<circle class="dd-dot" cx="88" cy="284" r="5"/>
<circle class="dd-dot" cx="184" cy="284" r="5"/>
<circle class="dd-dot" cx="280" cy="284" r="5"/>
<circle class="dd-dot" cx="376" cy="284" r="5"/>
<circle class="dd-dot" cx="472" cy="284" r="5"/>
<circle class="dd-fill-acc" cx="568" cy="284" r="5"/>
<circle class="dd-fill-acc" cx="664" cy="284" r="5"/>
<circle class="dd-dot" cx="760" cy="284" r="5"/>
<text class="t-mono" x="88" y="268" text-anchor="middle">2014</text>
<text class="t-note" x="88" y="232" text-anchor="middle">GRU · seq2seq</text>
<text class="t-note" x="88" y="250" text-anchor="middle">Bahdanau 注意力</text>
<text class="t-mono" x="280" y="268" text-anchor="middle">2016</text>
<text class="t-note" x="280" y="232" text-anchor="middle">GNMT：8+8 層</text>
<text class="t-note" x="280" y="250" text-anchor="middle">LSTM + 注意力</text>
<text class="t-mono" x="472" y="268" text-anchor="middle">2020</text>
<text class="t-note" x="472" y="232" text-anchor="middle">線性注意力</text>
<text class="t-note" x="472" y="250" text-anchor="middle">可寫成 RNN</text>
<text class="t-mono t-acc" x="664" y="268" text-anchor="middle">2024</text>
<text class="t-note" x="664" y="232" text-anchor="middle">xLSTM</text>
<text class="t-note" x="664" y="250" text-anchor="middle">minGRU / minLSTM</text>
<text class="t-mono" x="184" y="308" text-anchor="middle">2015</text>
<text class="t-note" x="184" y="328" text-anchor="middle">colah</text>
<text class="t-note" x="184" y="346" text-anchor="middle">Understanding LSTMs</text>
<text class="t-mono" x="376" y="308" text-anchor="middle">2017</text>
<text class="t-note" x="376" y="328" text-anchor="middle">Transformer</text>
<text class="t-note" x="376" y="346" text-anchor="middle">去掉迴圈</text>
<text class="t-mono t-acc" x="568" y="308" text-anchor="middle">2023</text>
<text class="t-note" x="568" y="328" text-anchor="middle">Mamba</text>
<text class="t-note" x="568" y="346" text-anchor="middle">選擇性狀態空間</text>
<text class="t-mono" x="776" y="308" text-anchor="end">2025</text>
<text class="t-note" x="776" y="328" text-anchor="end">xLSTM 7B</text>
<text class="t-note" x="776" y="346" text-anchor="end">TiRex</text>
<text class="t-say" x="40" y="372">強調色：用隨輸入變化的遺忘（衰減）來控制記憶的遞推。事件等距排列，不按年份比例。</text>
</svg>
</div>
<figcaption>圖 5 · 遺忘門在 2000 年加進 LSTM；二十多年後，“隨輸入變化的衰減”又成了新一代迴圈模型的核心</figcaption>
</figure>

### 還在用 LSTM 的地方

在語言模型上，LSTM 早已讓位給 Transformer，但在一些資料量不大、需要逐步讀入、對延遲和記憶體敏感的地方，它還在幹活。兩個有公開文獻的例子：

**洪水預報。** Google 2024 年發表在 Nature 上的全球洪水預報模型，核心就是 LSTM：兩個依次銜接的 LSTM，一個讀歷史天氣，一個讀預報天氣，預測未來 7 天的日流量。論文說，在沒有水文站的流域，它對極端洪水的預報在 5 天提前量內達到或超過歐盟 GloFAS 系統的即時預報水準，並已接入覆蓋 80 多個國家的公開預警系統[^nearing]。

**時間序列預測。** NXAI 2025 年發布的 TiRex 只有 35M 參數，基於 xLSTM，在 GiftEval 和 Chronos-ZS 兩個基準上的零樣本預測超過了 Amazon、Google、Salesforce 等更大的模型。作者在論文裡的判斷是：Transformer 在語言上很成功，在時間序列預測上卻常常不如預期，迴圈模型在這裡往往更有優勢[^tirex]。

為什麼這些地方還用迴圈？我們的推斷是：時間序列天然是一步一步到達的，迴圈模型的狀態大小固定，來一個點更新一次，記憶體和每步計算都不隨歷史長度增長；而這類任務的訓練資料通常沒有大到需要 Transformer 那樣的並行訓練。這是推斷，上面兩篇論文沒有這樣概括。

### 推理時的帳

這引出了 Transformer 的軟肋。訓練時它能並行，生成時卻要一個 token 一個 token 地出，而且每出一個，都要回看前面所有 token 的 key 和 value（KV 快取），快取隨長度增長。迴圈模型生成時只帶一個固定大小的狀態。

2020 年 Katharopoulos 等人指出，如果把注意力裡的 softmax 換成核函式的線性點積，注意力就可以按 RNN 的方式逐步計算，複雜度從 $O(N^2)$ 降到 $O(N)$，長序列的自迴歸生成最多快 4000 倍；論文標題直接就叫《Transformers are RNNs》[^katharopoulos]。這種線性注意力的狀態是一個矩陣，每步加上 $v_t k_t^\top$，但沒有遺忘：寫進去的東西永遠留著。這正是 1997 年沒有遺忘門的 LSTM 遇到過的問題。

### Mamba：會遺忘的狀態空間模型

Gu 和 Dao 2023 年的 Mamba 來自另一條路線：狀態空間模型。它的遞推寫成

$$
h_t = \bar A_t\, h_{t-1} + \bar B_t\, x_t, \qquad y_t = C_t\, h_t
$$

$h_t$ 是狀態，$\bar A_t$ 決定舊狀態衰減多少，$\bar B_t$ 決定新輸入寫進多少，$C_t$ 決定讀出什麼。早期的狀態空間模型裡這些矩陣是固定的；Mamba 的關鍵改動是“選擇機制”：讓步長 $\Delta$ 和 $B$、$C$ 隨當前輸入變化，$\bar A_t$ 由 $\Delta$ 和 $A$ 算出，因此也隨輸入變。這樣模型就能根據內容決定記住什麼、忘掉什麼。論文報告推理吞吐量約為 Transformer 的 5 倍，序列長度線性擴展[^mamba]。

把它和第三節的傳送帶並排：$c_t = f_t \odot c_{t-1} + i_t \odot \tilde c_t$。$\bar A_t$ 的角色就是遺忘門，$\bar B_t x_t$ 的角色就是“輸入門乘候選值”。這是我們的類比，不是 Mamba 論文的表述，兩者在初始化、參數化和計算方式上都有很大差別；但“隨輸入變化的衰減乘舊狀態，加上隨輸入變化的寫入”這個骨架，確實是同一個形狀。2024 年的 Mamba-2 更進一步，用一類結構化矩陣把狀態空間模型和注意力統一起來，核心層比 Mamba 快 2 到 8 倍[^mamba2]。

### xLSTM：LSTM 原班人馬的回答

2024 年，Hochreiter 參與的團隊發表了 xLSTM[^xlstm]，問題很直接：把 LSTM 放大到今天大模型的規模，再用上現代技術，能走多遠？它做了兩處改動。

一是**指數門控**：輸入門和遺忘門可以用指數函式代替 sigmoid，讓模型能更大幅度地改寫記憶，同時另外維護一個正規化狀態，並做數值穩定，防止指數溢位。

二是**新的記憶結構**。sLSTM 保留標量記憶和“記憶混合”（隱狀態之間的迴圈連線），因此不能沿序列並行；mLSTM 把細胞狀態從向量換成矩陣，更新方式是 $C_t = f_t C_{t-1} + i_t v_t k_t^\top$，並去掉隱狀態之間的迴圈連線，於是可以完全並行。

注意 mLSTM 的更新式：它就是“線性注意力的狀態更新，加上一個遺忘門”。2025 年的 xLSTM 7B 以 mLSTM 為主體，不含自注意力，論文報告下游任務和同規模模型相當，推理比 Llama 和 Mamba 架構的模型更快、更省[^xlstm7b]；前面的 TiRex 也建在 xLSTM 上。

### minLSTM：我們的手算簡化，恰好是一篇論文

還記得第四節為了手算，我們讓門“不看 $h_{t-1}$”嗎？2024 年 Feng、Bengio 等人的《Were RNNs All We Needed?》做的正是這件事：把 LSTM 和 GRU 的門對上一步隱狀態的依賴去掉，遞推就變成了“係數只由輸入決定的線性遞推”，不再需要逐步做 BPTT，可以用平行掃描演算法一次算完整條序列；序列長度 512 時，訓練快了 175 倍[^minrnn]。

為什麼去掉 $h_{t-1}$ 就能並行？因為 $c_t = f_t c_{t-1} + i_t \tilde c_t$ 裡的 $f_t$ 和 $i_t \tilde c_t$ 如果都能事先從輸入算好，這條遞推就是一連串“乘一個數再加一個數”，而這種操作滿足結合律，可以像求前綴和那樣分治並行。表 1 那一列 $c$，就可以不按順序算出來。

表 3 把這一族放在一起。

<figure class="dd dd-figure dt-figure">
<div class="dt-panel">
<div class="dt-title" id="lstm-family-title">傳送帶的後代</div>
<div class="dt-scroll">
<table class="dt dt-sticky" aria-labelledby="lstm-family-title">
<colgroup><col style="width:20%"><col><col style="width:18%"><col class="hl" style="width:20%"></colgroup>
<thead>
<tr><th scope="col">模型</th><th scope="col">狀態怎麼更新</th><th scope="col">係數看上一步的 h 嗎</th><th scope="col" class="acc">訓練能沿序列並行嗎</th></tr>
</thead>
<tbody>
<tr><th scope="row">LSTM（1997/2000）</th><td class="mono">c = f⊙c + i⊙c̃</td><td>看</td><td class="bad">不能，要逐步 BPTT</td></tr>
<tr><th scope="row">GRU（2014）</th><td class="mono">h = (1−z)⊙h + z⊙h̃</td><td>看</td><td class="bad">不能</td></tr>
<tr><th scope="row">線性注意力（2020）</th><td class="mono">S = S + v kᵀ</td><td>不看，且沒有遺忘</td><td class="good">能</td></tr>
<tr><th scope="row">Mamba（2023）</th><td class="mono">h = Ā⊙h + B̄x</td><td>不看，Δ、B、C 只由 x 決定</td><td class="good">能，用平行掃描</td></tr>
<tr><th scope="row">xLSTM：sLSTM（2024）</th><td class="mono">c = f⊙c + i⊙z，指數門</td><td>看（記憶混合）</td><td class="bad">不能</td></tr>
<tr><th scope="row">xLSTM：mLSTM（2024）</th><td class="mono">C = f·C + i·v kᵀ</td><td>不看</td><td class="good">能</td></tr>
<tr><th scope="row">minLSTM / minGRU（2024）</th><td class="mono">同 LSTM / GRU 的形式</td><td>不看</td><td class="good">能，用平行掃描</td></tr>
</tbody>
</table>
</div>
<p class="dt-note">“看不看上一步的 h”決定了能不能並行：係數只依賴輸入，遞推就滿足結合律。</p>
</div>
<figcaption>表 3 · 新一代迴圈模型保留了遺忘門，去掉了門對上一步輸出的依賴，換來了並行訓練</figcaption>
</figure>

### 混合：注意力和迴圈一起用

實際落地時，很多團隊選擇兩者都要。AI21 2024 年的 Jamba 把 Transformer 層和 Mamba 層交錯堆疊，部分層再加 MoE，總參數 52B、每個 token 啟用 12B，支援 256K 上下文，KV 快取比同等純 Transformer 小 8 倍[^jamba]。思路很直觀：少數注意力層負責“精確回看”，多數迴圈層負責便宜地帶著狀態往前走。

把表 3 和圖 5 放在一起，我們的讀法是：從 LSTM 到 Mamba、xLSTM，留下來的是**帶遺忘門的加法遞推**，被拿掉的是**門對上一步輸出的依賴**，因為後者讓訓練沒法並行。這是本文的歸納，不是上述任何一篇論文的結論；至於純迴圈、純注意力還是混合結構會成為下一代大模型的主流，到 2026 年底還沒有定論。

## 八、回到開頭那句話

現在可以回答開頭的五個問題了，最後再回到“我在法國長大……我能說流利的___”。

在我們的單元裡，“法國”在第 1 步被寫上傳送帶，$c_1 = 0.918$；之後每讀一個普通詞，只乘一次 0.953，4 個詞後還剩 0.756，從這裡回傳到第 1 步的梯度還有 82%。普通 RNN 在同一位置的梯度只剩 15%。網路能學會“看到法國，就說法語”，靠的是這 82%。

可是如果中間隔的不是 4 個詞，而是 50 個，0.953 的遺忘門只能留下 8.8% 的梯度，要靠更接近 1 的偏置才撐得住；隔得再遠，或者中間有很多事情要記，固定大小的傳送帶總會不夠用。這就是 colah 在 2015 年說“下一步是注意力”的原因：讓預測“法語”的那一步，直接回頭去看“法國”。

## 小結

1. **為什麼需要迴圈網路？** 前饋網路只把定長向量變成定長向量；RNN 每一步用同一套權重更新隱狀態 $h_t$，能處理任意長度的序列，$h_t$ 是學出來的、對前文的表示。
2. **為什麼 RNN 記不住遠處的字？** 訓練用 BPTT，梯度沿時間連乘，每一步乘 $w(1-h_t^2)$；我們的例子隔 4 個詞只剩 0.1525，隔 50 步最多剩 $0.9^{50} = 0.0052$。$w$ 調大會爆炸，裁剪只治爆炸不治消失。
3. **傳送帶是什麼？** 單獨開一條細胞狀態 $c_t = f_t \odot c_{t-1} + i_t \odot \tilde c_t$，沿它的導數就是 $f_t$；遺忘門接近 1，梯度就不衰減。最早的 LSTM 沒有遺忘門，2000 年才加上。
4. **三道門各做什麼？** 遺忘門決定舊內容留多少，輸入門和候選值決定寫什麼、寫多少，輸出門決定對外輸出多少；四個小層都吃 $[h_{t-1}, x_t]$。
5. **變體改了什麼？** 窺視孔讓門看細胞狀態，耦合門用 $1-f$ 代替 $i$，GRU 合併 $c$ 和 $h$、用更新門和重置門；大規模比較顯示它們差別不大，關鍵是遺忘門和它的偏置。
6. **為什麼下一步是注意力？** 傳送帶仍會衰減，整句也要擠進固定大小的狀態；注意力讓每一步直接回看所有位置，Transformer 再去掉迴圈，換來了並行訓練。
7. **2026 年 LSTM 在哪？** 洪水預報、時間序列等場景還在用；Mamba、xLSTM、minLSTM 這些新的迴圈模型保留了帶遺忘門的加法遞推，去掉了門對上一步輸出的依賴，以便並行訓練、在推理時保持固定大小的狀態。

## 自己跑一遍

下面的程式只用 Python 標準函式庫，把本文的單元 LSTM 和普通 RNN 逐步算一遍，列出表 1 和圖 3 的數，再用一個二十多行的反向模式自動求導（就是 colah 反向傳播那篇講的方法），從計算圖上把兩個梯度重新求一次，和手算的連乘核對。

```python
# lstm_by_hand.py -- pure Python, no dependencies. Run: python3 lstm_by_hand.py
import math

def sig(z): return 1 / (1 + math.exp(-z))

# Part 1: the hand-set 1-unit LSTM and RNN.
# Token 1 = "France" (worth remembering), token 0 = an ordinary word.
seq = [1, 0, 0, 0, 0]

def lstm_step(x, c_prev):
    f = sig(-4 * x + 3)        # forget gate
    i = sig(6 * x - 3)         # input gate
    c_hat = math.tanh(2 * x)   # candidate value
    o = sig(2)                 # output gate (constant here)
    c = f * c_prev + i * c_hat
    h = o * math.tanh(c)
    return f, i, c_hat, c, h

def rnn_step(x, h_prev, w=0.9, u=2.0):
    return math.tanh(w * h_prev + u * x)

print("t  x  f      i      c_hat  c      h      | RNN h")
c, h_rnn, dc, dh = 0.0, 0.0, 1.0, 1.0
for t, x in enumerate(seq, 1):
    f, i, c_hat, c, h = lstm_step(x, c)
    h_rnn = rnn_step(x, h_rnn)
    if t > 1:
        dc *= f                         # dc_t/dc_{t-1} = f_t
        dh *= 0.9 * (1 - h_rnn ** 2)    # dh_t/dh_{t-1} = w * (1 - h_t^2)
    print(f"{t}  {x}  {f:.4f} {i:.4f} {c_hat:.4f} {c:.4f} {h:.4f} | {h_rnn:.4f}")
print(f"LSTM dc5/dc1 = {dc:.4f}    RNN dh5/dh1 = {dh:.4f}")

# Part 2: the same products over longer gaps.
for T in (10, 20, 50, 100):
    print(f"gap {T:3d}:  0.9^T = {0.9 ** T:.1e}   "
          f"sig(3)^T = {sig(3) ** T:.1e}   sig(5)^T = {sig(5) ** T:.1e}")

# Part 3: check Part 1 with a tiny reverse-mode autodiff
# (the idea of colah's "Calculus on Computational Graphs").
class V:
    def __init__(self, v, parents=()):
        self.v, self.g, self.parents = v, 0.0, parents  # (parent, local derivative)
    def __add__(a, b): return V(a.v + b.v, ((a, 1.0), (b, 1.0)))
    def __mul__(a, b): return V(a.v * b.v, ((a, b.v), (b, a.v)))
    def tanh(a):
        t = math.tanh(a.v)
        return V(t, ((a, 1 - t * t),))
    def backward(self):
        order, seen = [], set()
        def visit(n):
            if id(n) not in seen:
                seen.add(id(n))
                for p, _ in n.parents: visit(p)
                order.append(n)
        visit(self)
        self.g = 1.0
        for n in reversed(order):       # walk the graph from the output back
            for p, local in n.parents:
                p.g += local * n.g

c1 = V(lstm_step(1, 0.0)[3])
c = c1
for x in seq[1:]:
    f, i, c_hat, _, _ = lstm_step(x, 0.0)
    c = V(f) * c + V(i * c_hat)
c.backward()

h1 = V(rnn_step(1, 0.0))
h = h1
for x in seq[1:]:
    h = (V(0.9) * h + V(2.0 * x)).tanh()
h.backward()
print(f"autodiff:  LSTM dc5/dc1 = {c1.g:.4f}    RNN dh5/dh1 = {h1.g:.4f}")
```

在 Python 3 下執行，輸出應該是：

```text
t  x  f      i      c_hat  c      h      | RNN h
1  1  0.2689 0.9526 0.9640 0.9183 0.6387 | 0.9640
2  0  0.9526 0.0474 0.0000 0.8748 0.6199 | 0.7002
3  0  0.9526 0.0474 0.0000 0.8333 0.6009 | 0.5582
4  0  0.9526 0.0474 0.0000 0.7938 0.5818 | 0.4640
5  0  0.9526 0.0474 0.0000 0.7561 0.5626 | 0.3949
LSTM dc5/dc1 = 0.8234    RNN dh5/dh1 = 0.1525
gap  10:  0.9^T = 3.5e-01   sig(3)^T = 6.2e-01   sig(5)^T = 9.4e-01
gap  20:  0.9^T = 1.2e-01   sig(3)^T = 3.8e-01   sig(5)^T = 8.7e-01
gap  50:  0.9^T = 5.2e-03   sig(3)^T = 8.8e-02   sig(5)^T = 7.1e-01
gap 100:  0.9^T = 2.7e-05   sig(3)^T = 7.8e-03   sig(5)^T = 5.1e-01
autodiff:  LSTM dc5/dc1 = 0.8234    RNN dh5/dh1 = 0.1525
```

可以試著改幾個數：把 `lstm_step` 裡遺忘門的 `+ 3` 改成 `+ 5`，看 `dc5/dc1` 怎麼變；把 `seq` 加長到 50 個詞；或者讓遺忘門也看上一步的 `h`，看自動求導和連乘還對不對得上。

## 參考資料
