Where a CNN shares weights along the spatial axis, a recurrent neural network (RNN) shares them along the time axis. It reads sequences of arbitrary length one step at a time with the same function, carrying a summary of everything seen so far in a fixed-size hidden state vector. Machine translation, speech recognition and language models in 2014–2017 were almost all built this way (especially with LSTMs). This lesson looks precisely at why RNNs struggle to learn long dependencies, how the LSTM fixed that, and why it nevertheless gave way to attention.
RNNs and unrolling in time
The simplest (Elman) RNN is
are shared by every time step. Unroll this loop in time and a sequence of length becomes a feed-forward network of depth — a deep network that uses the same weights in every layer. So the multiplicative-chain problem of the last lesson shows up unchanged, and even worse: instead of a different random matrix per layer, the same matrix is multiplied times.
BPTT: backpropagating back through time
Applying backprop to the unrolled network is called BPTT (backpropagation through time). It is not a new algorithm. Only two points need noting.
Shared weights add their gradients over time. is a fan-out used at every step, so
The gradient to the distant past is a product of Jacobians. The effect of the loss at time on the hidden state steps earlier is
In the sum for , every term that lets the network learn “a dependency steps apart” passes through this product. If the product goes to 0, the learning signal for long dependencies is buried under the signal for short ones and disappears.
The eigenvalue story
First drop the tanh and look at a linear RNN. , so the product is . Diagonalising ,
the component along each eigenvector is multiplied by . If the spectral radius is below 1 the gradient vanishes exponentially; above 1 it explodes. Only at exactly 1 is it preserved. In a deep MLP each layer had a different matrix, so the factor fluctuated randomly; in an RNN it is the same matrix, so the factor is systematically raised to the -th power.
With tanh, , so . By the theorem of Pascanu et al. (2013), if the largest singular value of is below 1, vanishing (with tanh) must happen; conversely, exploding requires the largest singular value to exceed 1 (a necessary condition). But heading in the exploding direction saturates the tanh and makes small, so the gradient of a tanh RNN is eventually pulled towards shrinking.
CNN이 공간 축으로 가중치를 공유했다면, 순환 신경망(recurrent neural network, RNN)은 시간 축으로 공유한다. 길이가 제각각인 시퀀스를 같은 함수로 한 step씩 읽으면서, 지금까지 본 것을 고정 크기의 은닉 상태(hidden state) 벡터에 요약해 들고 다닌다. 2014–2017년의 기계번역, 음성인식, 언어 모델은 거의 모두 이 구조(특히 LSTM)였다. 이 레슨은 RNN이 왜 긴 의존성을 배우기 어려운지 정확히 보고, LSTM이 그것을 어떻게 고쳤는지, 그리고 그럼에도 왜 attention에 자리를 내줬는지를 본다.
RNN과 시간 방향 펼치기
가장 단순한(Elman) RNN은
이다. 는 모든 시점이 공유한다. 이 루프를 시간 방향으로 펼치면(unroll) 길이 의 시퀀스는 깊이 의 순전파 망 이 된다. 층마다 같은 가중치를 쓰는 깊은 망이다. 그러니 지난 레슨의 곱셈 사슬 문제가 그대로, 게다가 더 심하게 나타난다. 층마다 다른 무작위 행렬이 아니라 같은 행렬 가 번 곱해지기 때문이다.
BPTT: 시간을 거슬러 역전파
펼친 망에 역전파를 적용한 것을 BPTT(backpropagation through time)라 부른다. 새 알고리즘은 아니다. 두 가지만 짚으면 된다.
공유 가중치는 기울기를 시간에 걸쳐 더한다. 는 모든 시점에서 쓰이는 fan-out이므로
먼 과거로 가는 기울기는 야코비안의 곱이다. 시점 의 손실이 step 전의 은닉 상태에 주는 영향은
의 합에서 ” step 떨어진 의존성”을 배우게 해 주는 항들은 모두 이 곱을 거친다. 그 곱이 0으로 가면, 긴 의존성에 대한 학습 신호가 짧은 의존성의 신호에 묻혀 사라진다.
고유값 이야기
먼저 tanh를 빼고 선형 RNN을 보자. 이므로 곱은 이다. 로 대각화하면
고유벡터 방향의 성분은 배가 된다. 스펙트럼 반경 가 1보다 작으면 기울기가 지수적으로 사라지고, 1보다 크면 폭발한다. 정확히 1일 때만 유지된다. 깊은 MLP에서는 층마다 다른 행렬이라 배율이 무작위로 흔들렸지만, RNN은 같은 행렬이라 그 배율이 체계적으로 제곱된다.
tanh를 넣으면 이므로 다. Pascanu et al.(2013)의 정리대로, 의 최대 특잇값이 1보다 작으면 (tanh에서) 소실은 반드시 일어나고, 반대로 폭발하려면 최대 특잇값이 1보다 커야 한다(필요조건). 다만 폭발하는 방향으로 가면 tanh가 포화되어 가 작아지므로, tanh RNN의 기울기는 결국 줄어드는 쪽으로 끌려간다.
- At ρ = 0.9 the linear RNN gives , i.e. , after 50 steps. At ρ = 1.1 it blows up to .
- For the tanh RNN, even raising ρ to 1.3 the gradient eventually shrinks. Increase the input size and saturation gets worse, so it shrinks faster.
- The LSTM cell path (green) does not depend on . With = 0, , so it actually vanishes fastest, but raise to 4 or more and over 0.1 remains even after 50 steps. (In the figure we set . In reality is also learned as a function of the input.)
Exploding is relatively easy to handle. The standard remedy is gradient clipping: if the gradient norm exceeds a threshold , rescale (Pascanu et al., 2013). It keeps the direction and only limits the size. Vanishing cannot be fixed that way. There is no way to amplify a signal that has disappeared, so the architecture has to change.
import numpy as np
def make_batch(rng, B, T):
"""Input: T bits of ±1. Target: get the 'first bit' right at the last step."""
x = rng.choice([-1.0, 1.0], size=(T, B, 1))
y = (x[0, :, 0] > 0).astype(float)
return x, y
def init(rng, H, scale=1.0):
return {"Wx": rng.normal(size=(1, H)) * 1.0,
"Wh": rng.normal(size=(H, H)) * scale / np.sqrt(H),
"b": np.zeros(H), "v": rng.normal(size=H) / np.sqrt(H), "c": 0.0}
def forward_backward(p, x, y):
T, B, _ = x.shape
H = p["Wh"].shape[0]
hs = [np.zeros((B, H))]
for t in range(T): # forward: h_t = tanh(x_t Wx + h_{t-1} Wh + b)
hs.append(np.tanh(x[t] @ p["Wx"] + hs[-1] @ p["Wh"] + p["b"]))
logit = hs[-1] @ p["v"] + p["c"]
prob = 1 / (1 + np.exp(-logit))
loss = -np.mean(y * np.log(prob + 1e-9) + (1 - y) * np.log(1 - prob + 1e-9))
acc = np.mean((prob > 0.5) == (y > 0.5))
# BPTT: walk back through time, accumulating gradient into the same Wh
g = {k: np.zeros_like(v) for k, v in p.items()}
dlogit = (prob - y) / B
g["v"] = hs[-1].T @ dlogit
g["c"] = dlogit.sum()
dh = np.outer(dlogit, p["v"]) # ∂L/∂h_T
dh_norms = []
for t in range(T, 0, -1):
dh_norms.append(np.linalg.norm(dh))
dz = dh * (1 - hs[t] ** 2) # tanh'
g["Wx"] += x[t - 1].T @ dz
g["Wh"] += hs[t - 1].T @ dz # every step shares the same Wh → sum
g["b"] += dz.sum(0)
dh = dz @ p["Wh"].T # ∂L/∂h_{t-1} = (dz) Whᵀ : Jacobian product
return loss, acc, g, dh_norms[::-1]
rng = np.random.default_rng(0)
H, T = 16, 30
print("‖∂L/∂h_t‖ / ‖∂L/∂h_T‖ , t = 1, 7, 13, 19, 25 (T = 30)")
for scale in [0.5, 1.0, 1.5]:
p = init(rng, H, scale)
x, y = make_batch(rng, 256, T)
_, _, _, norms = forward_backward(p, x, y)
print(f"Wh scale {scale}: " + " ".join(f"{n/norms[-1]:.0e}" for n in norms[::6]))
def train(T, steps=300, H=16, lr=0.05, seed=0):
rng = np.random.default_rng(seed)
p = init(rng, H, 1.0)
m = {k: np.zeros_like(v) for k, v in p.items()}
s = {k: np.zeros_like(v) for k, v in p.items()}
for it in range(1, steps + 1): # Adam
x, y = make_batch(rng, 64, T)
loss, acc, g, _ = forward_backward(p, x, y)
for k in p:
gk = np.clip(g[k], -1, 1) # gradient clipping (guards against explosion)
m[k] = 0.9 * m[k] + 0.1 * gk
s[k] = 0.999 * s[k] + 0.001 * gk ** 2
p[k] = p[k] - lr * (m[k] / (1 - 0.9**it)) / (np.sqrt(s[k] / (1 - 0.999**it)) + 1e-8)
x, y = make_batch(rng, 1000, T)
loss, acc, _, _ = forward_backward(p, x, y)
return loss, acc
print("\nTraining 'remember the first bit' (300 steps, Adam)")
for T in [5, 15, 30]:
loss, acc = train(T)
print(f" T={T:2d}: test accuracy {acc:.0%} loss {loss:.3f}")The task itself is trivial: just keep the sign of the first input in the hidden state. Yet at the accuracy stays at 50% (guessing). The gradient reaching from 30 steps later shrinks below and is buried under the gradients from other (meaningless) correlations within the same batch. That the gradient shrinks rather than explodes even at Wh scale 1.5 is the tanh saturation effect from the figure above.
LSTM: remembering by addition instead of multiplication
The idea of the LSTM (Hochreiter & Schmidhuber, 1997) is to keep a cell state separate from the hidden state and to update it with elementwise addition rather than a matrix product. Today’s standard form (with forget gate, Gers et al., 2000) is
The gates take values between 0 and 1, so they are “soft switches”, and since they are differentiable, when to write, erase and read is learned by backprop. Below is a memory register built by hand-wiring an LSTM with hidden size 1.
- ρ = 0.9에서 선형 RNN은 50 step 뒤 , 즉 이다. ρ = 1.1이면 로 터진다.
- tanh RNN은 ρ를 1.3까지 올려도 기울기가 결국 줄어든다. 입력 크기를 키우면 포화가 심해져 더 빨리 준다.
- LSTM 셀 경로(초록)는 와 무관하다. = 0이면 라 오히려 가장 빨리 사라지지만, 를 4 이상으로 올리면 50 step 뒤에도 0.1 넘게 남는다. (그림에서 으로 두었다. 실제로는 도 입력에 따라 학습된다.)
폭발 은 상대적으로 쉽게 다룬다. 기울기 노름이 임계값 를 넘으면 로 잘라내는 gradient clipping 이 표준 처방이다(Pascanu et al., 2013). 방향은 유지하고 크기만 제한한다. 소실 은 그렇게 못 고친다. 사라진 신호를 증폭할 방법이 없으므로 구조를 바꿔야 한다.
import numpy as np
def make_batch(rng, B, T):
"""입력: ±1 비트 T개. 목표: '첫 번째 비트'를 마지막 step에서 맞히기."""
x = rng.choice([-1.0, 1.0], size=(T, B, 1))
y = (x[0, :, 0] > 0).astype(float)
return x, y
def init(rng, H, scale=1.0):
return {"Wx": rng.normal(size=(1, H)) * 1.0,
"Wh": rng.normal(size=(H, H)) * scale / np.sqrt(H),
"b": np.zeros(H), "v": rng.normal(size=H) / np.sqrt(H), "c": 0.0}
def forward_backward(p, x, y):
T, B, _ = x.shape
H = p["Wh"].shape[0]
hs = [np.zeros((B, H))]
for t in range(T): # 순전파: h_t = tanh(x_t Wx + h_{t-1} Wh + b)
hs.append(np.tanh(x[t] @ p["Wx"] + hs[-1] @ p["Wh"] + p["b"]))
logit = hs[-1] @ p["v"] + p["c"]
prob = 1 / (1 + np.exp(-logit))
loss = -np.mean(y * np.log(prob + 1e-9) + (1 - y) * np.log(1 - prob + 1e-9))
acc = np.mean((prob > 0.5) == (y > 0.5))
# BPTT: 시간을 거꾸로 거슬러 올라가며 같은 Wh에 기울기를 누적
g = {k: np.zeros_like(v) for k, v in p.items()}
dlogit = (prob - y) / B
g["v"] = hs[-1].T @ dlogit
g["c"] = dlogit.sum()
dh = np.outer(dlogit, p["v"]) # ∂L/∂h_T
dh_norms = []
for t in range(T, 0, -1):
dh_norms.append(np.linalg.norm(dh))
dz = dh * (1 - hs[t] ** 2) # tanh'
g["Wx"] += x[t - 1].T @ dz
g["Wh"] += hs[t - 1].T @ dz # 모든 시점이 같은 Wh를 공유 → 합
g["b"] += dz.sum(0)
dh = dz @ p["Wh"].T # ∂L/∂h_{t-1} = (dz) Whᵀ : 야코비안 곱
return loss, acc, g, dh_norms[::-1]
rng = np.random.default_rng(0)
H, T = 16, 30
print("‖∂L/∂h_t‖ / ‖∂L/∂h_T‖ , t = 1, 7, 13, 19, 25 (T = 30)")
for scale in [0.5, 1.0, 1.5]:
p = init(rng, H, scale)
x, y = make_batch(rng, 256, T)
_, _, _, norms = forward_backward(p, x, y)
print(f"Wh 배율 {scale}: " + " ".join(f"{n/norms[-1]:.0e}" for n in norms[::6]))
def train(T, steps=300, H=16, lr=0.05, seed=0):
rng = np.random.default_rng(seed)
p = init(rng, H, 1.0)
m = {k: np.zeros_like(v) for k, v in p.items()}
s = {k: np.zeros_like(v) for k, v in p.items()}
for it in range(1, steps + 1): # Adam
x, y = make_batch(rng, 64, T)
loss, acc, g, _ = forward_backward(p, x, y)
for k in p:
gk = np.clip(g[k], -1, 1) # gradient clipping (폭발 대비)
m[k] = 0.9 * m[k] + 0.1 * gk
s[k] = 0.999 * s[k] + 0.001 * gk ** 2
p[k] = p[k] - lr * (m[k] / (1 - 0.9**it)) / (np.sqrt(s[k] / (1 - 0.999**it)) + 1e-8)
x, y = make_batch(rng, 1000, T)
loss, acc, _, _ = forward_backward(p, x, y)
return loss, acc
print("\n'첫 비트 기억하기' 학습 (300 step, Adam)")
for T in [5, 15, 30]:
loss, acc = train(T)
print(f" T={T:2d}: 테스트 정확도 {acc:.0%} loss {loss:.3f}")과제 자체는 사소하다. 첫 입력의 부호를 은닉 상태에 담아 두기만 하면 된다. 그런데 에서는 정확도가 50%(찍기)에 머문다. 30 step 전 로 가는 기울기가 이하로 줄어, 같은 배치 안의 다른 (무의미한) 상관관계가 주는 기울기에 묻히기 때문이다. Wh 배율 1.5에서도 기울기가 폭발하지 않고 줄어드는 것은 위 그림의 tanh 포화 효과다.
LSTM: 곱 대신 덧셈으로 기억하기
LSTM(Hochreiter & Schmidhuber, 1997)의 아이디어는 은닉 상태와 별도로 셀 상태(cell state) 를 두고, 그 갱신을 행렬곱이 아니라 원소별 덧셈 으로 하는 것이다. 오늘날 표준형(forget gate 포함, Gers et al., 2000)은
게이트는 0과 1 사이 값이라 “부드러운 스위치”이고, 미분 가능하므로 언제 쓰고 지우고 읽을지를 역전파로 학습한다. 아래는 은닉 크기 1인 LSTM을 손으로 배선해 만든 기억 레지스터다.
The key is the Jacobian of the cell path. Differentiating with respect to (ignoring the indirect paths through the gates),
No is multiplied in, and nothing is squashed by a tanh. When the forget gate is close to 1, the gradient flows almost unchanged into the distant past. The original 1997 LSTM had no forget gate; its cell was , a “constant error carousel” with a factor of exactly 1. The forget gate was added later as the ability to erase memory that is no longer needed. That is why in practice the forget gate’s bias is initialised around 1, so the default early in training is “keep” (Jozefowicz et al., 2015 confirmed the effect of this initialisation experimentally).
The GRU (Cho et al., 2014) is a variant that merges the cell and hidden states and cuts the gates down to two.
Since is a convex combination of the past and a new candidate, it has the same additive path. Its performance trades places with the LSTM depending on the task.
A linear RNN's recurrent matrix is symmetric, and its eigenvalues have absolute value at most 0.9. Roughly by what factor does the gradient to a hidden state 50 steps back shrink?
The Jacobian product is , and since a symmetric matrix has orthogonal eigenvectors, the largest component becomes exactly times as large. The decrease is exponential in distance. With a non-symmetric matrix the eigenvectors are not orthogonal and it can grow temporarily, but for large enough it eventually follows .
Why attention replaced RNNs
The LSTM greatly eased vanishing gradients, but three structural limits remained.
- Sequential bottleneck: computing requires . A sequence of length needs sequential computations even in training, so the GPU’s parallelism cannot be used along the time axis. A Transformer computes all positions at once during training.
- Information bottleneck: the whole past is compressed into one fixed-size vector . The classic example is seq2seq translation, which handed an entire long sentence over through the encoder’s single final state. Bahdanau et al. (2015) let the decoder look again, at every step, at a weighted sum of all of the encoder’s hidden states (attention), greatly improving translation quality on long sentences.
- Path length: for information at position to reach , an RNN must go through updates, diluted by the product of the gates along the way. In self-attention any two positions are connected in one hop (path length 1).
There is a price. Self-attention uses compute and memory in the sequence length, and must carry the whole past (the KV cache) while generating. An RNN has compute and state. That is why state-space models (Mamba) and linear-attention variants aiming at long-context efficiency are once again looking for architectures that can “train in parallel and run recurrently at inference”. The ideas of the RNN have not disappeared; they are coming back in a different form.
→ Go deeper: Linear attention and SSMs shows how these models compress context into a fixed-size state and why recent hybrids interleave them with full attention.
import torch
import torch.nn as nn
H = 64
lstm = nn.LSTM(input_size=1, hidden_size=H, batch_first=True)
# PyTorch's gate order is (input, forget, cell, output): bias [H:2H] is the forget gate
with torch.no_grad():
lstm.bias_ih_l0[H:2 * H].fill_(1.0)
lstm.bias_hh_l0[H:2 * H].fill_(0.0) # the two biases are added, so their sum is 1
head = nn.Linear(H, 1)
opt = torch.optim.Adam([*lstm.parameters(), *head.parameters()], lr=1e-2)
def batch(B=64, T=50):
x = torch.randint(0, 2, (B, T, 1)).float() * 2 - 1
return x, (x[:, 0, 0] > 0).float()
for step in range(300):
x, y = batch()
out, (h_T, c_T) = lstm(x) # out: (B, T, H), h_T: (1, B, H)
loss = nn.functional.binary_cross_entropy_with_logits(head(h_T[0]).squeeze(-1), y)
opt.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(lstm.parameters(), max_norm=1.0) # guards against explosion
opt.step()
print(f"T=50 'remember the first bit' loss = {loss.item():.4f}") # clearly below log 2 ≈ 0.693 means it remembered
# try increasing T, or resetting the forget bias to 0 and comparing with a vanilla nn.RNNSummary
- An RNN is a deep network that shares its weights along time. BPTT is backprop on the unrolled graph, and the gradients of shared weights add up over time.
- The gradient to the distant past is . Because the same matrix repeats, it vanishes or explodes exponentially depending on the spectral radius.
- Explosion is handled by gradient clipping; vanishing by changing the architecture.
- The LSTM updates its cell state by gated addition, giving . The forget bias is initialised near 1. The GRU works on the same principle.
- Attention removed the sequential bottleneck, the fixed-size state and the long paths, at the price of cost and a KV cache.
핵심은 셀 경로의 야코비안이다. 를 로 미분하면(게이트를 통한 간접 경로를 빼면)
가 곱해지지 않고, tanh로 찌그러지지도 않는다. forget gate가 1에 가까우면 기울기가 거의 그대로 먼 과거까지 흐른다. 원래 1997년 LSTM에는 forget gate가 없었고 셀이 , 즉 배율이 정확히 1인 “상수 오차 회전목마(constant error carousel)“였다. forget gate는 필요 없는 기억을 지우는 능력으로 나중에 추가되었다. 그래서 실전에서는 forget gate의 편향을 1 정도로 초기화해, 학습 초기에 기본값이 “유지”가 되게 한다(Jozefowicz et al., 2015가 이 초기화의 효과를 실험으로 확인했다).
GRU (Cho et al., 2014)는 셀 상태와 은닉 상태를 합치고 게이트를 둘로 줄인 변형이다.
가 과거와 새 후보의 볼록 결합이라는 점에서 같은 덧셈 경로를 가진다. 성능은 과제에 따라 LSTM과 엎치락뒤치락한다.
선형 RNN의 순환 행렬이 대칭이고 고유값의 절댓값이 최대 0.9이다. 50 step 떨어진 은닉 상태로 가는 기울기의 크기는 대략 몇 배로 줄어드는가?
야코비안 곱이 이고, 대칭이면 고유벡터가 직교라서 가장 큰 성분이 정확히 배가 된다. 거리에 대해 지수적 감소다. 비대칭 행렬이면 고유벡터가 직교하지 않아 일시적으로 커질 수 있지만, 충분히 큰 에서는 결국 를 따른다.
왜 attention이 RNN을 대체했는가
LSTM은 기울기 소실을 크게 완화했지만 세 가지 구조적 한계가 남았다.
- 순차 병목: 를 계산하려면 이 있어야 한다. 길이 의 시퀀스는 학습 때도 번의 순차 계산이 필요하고, GPU의 병렬성을 시간 축으로 쓸 수 없다. Transformer는 학습 시 모든 위치를 한 번에 계산한다.
- 정보 병목: 과거 전체가 고정 크기 벡터 하나에 압축된다. seq2seq 번역에서 인코더의 마지막 상태 하나로 긴 문장 전체를 넘기던 것이 대표적이다. Bahdanau et al.(2015)은 디코더가 매 step 인코더의 모든 은닉 상태를 가중합으로 다시 보게 해(attention) 긴 문장의 번역 품질을 크게 올렸다.
- 경로 길이: 위치 의 정보가 에 닿으려면 RNN에서는 번의 갱신을 거쳐야 하고, 그 사이 게이트 곱만큼 희석된다. self-attention에서는 어떤 두 위치든 한 번에 연결된다(경로 길이 1).
대가도 있다. self-attention은 시퀀스 길이에 대해 의 계산과 메모리를 쓰고, 생성할 때 과거 전체(KV cache)를 들고 있어야 한다. RNN은 계산에 상태다. 그래서 긴 문맥 효율을 노리는 상태공간 모델(Mamba)이나 선형 attention 계열은 “학습은 병렬로, 추론은 순환으로” 할 수 있는 구조를 다시 찾는다. RNN의 아이디어는 사라진 것이 아니라 형태를 바꿔 돌아오고 있다.
→ 더 깊이: Linear attention과 SSM에서 이런 모델이 문맥을 고정 크기 상태로 압축하는 방식과, 최근 하이브리드가 이를 full attention과 섞어 쌓는 이유를 본다.
import torch
import torch.nn as nn
H = 64
lstm = nn.LSTM(input_size=1, hidden_size=H, batch_first=True)
# PyTorch의 게이트 순서는 (input, forget, cell, output): 편향 [H:2H]가 forget gate
with torch.no_grad():
lstm.bias_ih_l0[H:2 * H].fill_(1.0)
lstm.bias_hh_l0[H:2 * H].fill_(0.0) # 두 편향이 더해지므로 합이 1
head = nn.Linear(H, 1)
opt = torch.optim.Adam([*lstm.parameters(), *head.parameters()], lr=1e-2)
def batch(B=64, T=50):
x = torch.randint(0, 2, (B, T, 1)).float() * 2 - 1
return x, (x[:, 0, 0] > 0).float()
for step in range(300):
x, y = batch()
out, (h_T, c_T) = lstm(x) # out: (B, T, H), h_T: (1, B, H)
loss = nn.functional.binary_cross_entropy_with_logits(head(h_T[0]).squeeze(-1), y)
opt.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(lstm.parameters(), max_norm=1.0) # 폭발 대비
opt.step()
print(f"T=50 '첫 비트 기억하기' loss = {loss.item():.4f}") # log 2 ≈ 0.693보다 확실히 낮으면 기억한 것
# T를 늘리거나 forget bias를 0으로 되돌려 vanilla nn.RNN과 비교해 보자정리
- RNN은 시간 방향으로 가중치를 공유하는 깊은 망이다. BPTT는 펼친 그래프의 역전파이고, 공유 가중치의 기울기는 시간에 걸쳐 더해진다.
- 먼 과거로 가는 기울기는 . 같은 행렬이 반복되므로 스펙트럼 반경에 따라 지수적으로 소실·폭발한다.
- 폭발은 gradient clipping으로, 소실은 구조 변경으로 다룬다.
- LSTM은 셀 상태를 게이트된 덧셈 으로 갱신해 를 만든다. forget bias를 1 근처로 초기화한다. GRU도 같은 원리다.
- Attention은 순차 병목·고정 크기 상태·긴 경로를 없앴고, 대가로 비용과 KV cache를 얻었다.
더 읽을거리Further reading
- Hochreiter & Schmidhuber, Long Short-Term Memory (Neural Computation, 1997) — LSTM 원 논문. 상수 오차 회전목마(constant error carousel)로 기울기 소실을 우회The original LSTM paper. Bypasses vanishing gradients with the constant error carousel
- Gers, Schmidhuber, Cummins, Learning to Forget: Continual Prediction with LSTM (Neural Computation, 2000) — 오늘날 LSTM의 forget gate를 도입한 논문The paper that introduced the forget gate of today's LSTM
- Bengio, Simard, Frasconi, Learning Long-Term Dependencies with Gradient Descent is Difficult (IEEE TNN, 1994) — RNN 기울기 소실 문제의 고전적 분석The classic analysis of the vanishing-gradient problem in RNNs
- Pascanu, Mikolov, Bengio, On the Difficulty of Training Recurrent Neural Networks (ICML, 2013) — 소실·폭발의 고유값/특잇값 조건과 gradient norm clippingEigenvalue/singular-value conditions for vanishing and exploding, and gradient norm clipping
- Olah, Understanding LSTM Networks (colah's blog, 2015) — 이 레슨 셀 그림의 원형이 된 LSTM 도식 설명The LSTM diagrams that served as the model for this lesson's cell figure
- Cho et al., Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation (EMNLP, 2014) — GRU를 제안한 논문The paper that proposed the GRU
- Bahdanau, Cho, Bengio, Neural Machine Translation by Jointly Learning to Align and Translate (ICLR, 2015) — 고정 길이 은닉 상태의 병목을 attention으로 푼 논문. 다음 레슨의 출발점Solved the bottleneck of a fixed-length hidden state with attention; the starting point of the next lesson