The previous lesson concluded that “units are only not wasted if we also learn where the first layer’s kinks go”. For that we need the gradient of the loss with respect to every parameter, . With parameters, finite differences take forward passes ( for central differences). GPT-2 small alone has . Backpropagation computes the same gradient exactly at a constant multiple of the cost of one forward pass. This lesson shows how that is possible: first as a picture, then as a scalar implementation, then as a vector implementation.
Computation graphs and the chain rule
Any computation can be broken into a composition of elementary operations (addition, multiplication, tanh …), and their dependencies form a directed acyclic graph (DAG). Say node is computed from inputs as . For the final output , the chain rule is
Two things are key.
- Locality: node only needs the derivative of its own operation (the local gradient). It does not need to know the whole graph. An addition node only knows “1”, a multiplication node “the other input’s value”, a tanh node "".
- Sum (+=): if is used by several nodes (fan-out), there are several paths through which it affects . By the multivariable chain rule, the per-path contributions are added.
Visit each node once, from the output in reverse topological order, applying this rule, and every node’s gets filled in. When a node is visited, all the gradient flowing into it has already arrived (every node that uses it was processed first). That is all there is to backpropagation.
지난 레슨의 결론은 “첫 층의 꺾임 위치까지 학습해야 유닛을 낭비하지 않는다”였다. 그러려면 모든 매개변수에 대한 손실의 기울기 이 필요하다. 매개변수가 개일 때 유한 차분으로 구하면 순전파를 번(중심 차분이면 번) 해야 한다. GPT-2 small만 해도 이다. 역전파(backpropagation) 는 같은 기울기를 순전파 한 번의 상수 배 비용으로 정확히 구한다. 이 레슨은 그것이 어떻게 가능한지를 그림, 스칼라 구현, 벡터 구현 순으로 본다.
계산 그래프와 연쇄 법칙
어떤 계산이든 기본 연산(덧셈, 곱셈, tanh …)의 합성으로 쪼갤 수 있고, 그 의존 관계는 방향 비순환 그래프(DAG)다. 노드 가 입력 로부터 로 계산된다고 하자. 최종 출력 에 대해 연쇄 법칙(chain rule)은
이다. 두 가지가 핵심이다.
- 국소성: 노드 는 자기 연산 의 미분(local gradient)만 알면 된다. 그래프 전체를 알 필요가 없다. 덧셈 노드는 “1”, 곱셈 노드는 “상대 입력값”, tanh 노드는 ""만 안다.
- 합(+=): 가 여러 노드에서 쓰이면(fan-out), 에 영향을 주는 경로가 여럿이다. 다변수 연쇄 법칙에 따라 경로별 기여를 더한다.
출력 쪽부터 위상 정렬의 역순으로 각 노드를 한 번씩 방문하며 이 규칙을 적용하면, 모든 노드의 가 채워진다. 방문할 때 그 노드로 들어올 기울기는 이미 모두 도착해 있다(그 노드를 쓰는 노드들이 모두 먼저 처리되었으므로). 이것이 역전파의 전부다.
Things to check in the figure.
- Addition is a distributor: the gradient arriving at is copied unchanged to and .
- Multiplication is a swapper: in , the gradient going to is multiplied by , and the gradient going to by . If one input is large, the other’s gradient is large — one of the reasons input normalisation matters.
- Nonlinearities are gates: in relu, if the local derivative is 0, so no gradient reaches anything below it. tanh is also nearly 0 when is large (saturation).
- Fan-out is a sum: is used in two places, and , so two gradients arrive. In the last step
a.gradbecomes the sum of both contributions and matches the numerical derivative in the bottom right.
Why reverse: VJP and JVP
If the computation is a composition , the chain rule is a product of Jacobians.
Matrix multiplication is associative, so the result is the same whichever end you start from, but the cost is not.
- Forward mode: from the right. Feed an input-direction vector and push , a Jacobian–vector product (JVP), along with the forward pass. Getting the full Jacobian takes repetitions, one per input dimension.
- Reverse mode: from the left. Feed an output-side vector and push , a vector–Jacobian product (VJP), backwards. It takes repetitions, one per output dimension.
In training the output is a scalar loss () and the input is hundreds of millions of parameters (). One reverse pass () yields the entire gradient. Each VJP costs about as much as the corresponding layer’s forward pass, so all of backprop is a small constant multiple of the forward pass (about 2× for matrix products: one matrix product for the gradient with respect to the input and one for the weights). In theory too, the cost of computing a gradient is bounded by a constant multiple of the cost of computing the function (the cheap gradient principle, the Baur–Strassen theorem).
The price is memory. Computing a VJP needs the intermediate values from the forward pass (the grey numbers in the figure), so every layer’s activations must be stored until backprop finishes. In large-model training, activation memory often exceeds parameter memory; activation checkpointing, which discards some activations and recomputes them during backprop, is the fix.
We never build the Jacobian
Real implementations never form as a matrix; they only have functions that compute the VJP directly. The common ones (rows = batch, ):
| Operation | Forward | Backward (VJP) |
|---|---|---|
| Linear | , | |
| Bias | (fan-out along the batch → sum) | |
| Elementwise | (the Jacobian is diagonal, so one multiplication) | |
| softmax + CE |
You don’t need to memorise the linear-layer formulas as long as you match dimensions: must have the same shape as , and the only product that gives it is . The Jacobian of an elementwise op is but diagonal, so what would have been as a matrix takes .
Build it 1: a scalar autograd
We follow the structure of Karpathy’s micrograd. A Value holds one number, its .grad, and a _backward closure — “the local chain rule of the operation that made me”. Operators are overloaded, so just writing ordinary Python expressions records the graph (define-by-run, the same approach as PyTorch). We check it on the same graph as in the figure.
import math
class Value:
"""A single scalar and its gradient. Records the computation graph on every operation."""
def __init__(self, data, _children=(), _op=''):
self.data = float(data)
self.grad = 0.0
self._backward = lambda: None # this node's local chain rule
self._prev = set(_children)
self._op = _op
def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other), '+')
def _backward():
self.grad += out.grad # addition: pass it through unchanged
other.grad += out.grad
out._backward = _backward
return out
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other), '*')
def _backward():
self.grad += other.data * out.grad # multiplication: scale by the other value
other.grad += self.data * out.grad
out._backward = _backward
return out
def __pow__(self, k): # k is a constant
out = Value(self.data ** k, (self,), f'**{k}')
def _backward():
self.grad += k * self.data ** (k - 1) * out.grad
out._backward = _backward
return out
def tanh(self):
t = math.tanh(self.data)
out = Value(t, (self,), 'tanh')
def _backward():
self.grad += (1 - t * t) * out.grad
out._backward = _backward
return out
def relu(self):
out = Value(max(0.0, self.data), (self,), 'relu')
def _backward():
self.grad += (out.data > 0) * out.grad
out._backward = _backward
return out
def backward(self):
# topological sort: every node is processed after all nodes that use it
topo, seen = [], set()
def build(v):
if v not in seen:
seen.add(v)
for c in v._prev:
build(c)
topo.append(v)
build(self)
self.grad = 1.0
for v in reversed(topo):
v._backward()
__radd__ = __add__
__rmul__ = __mul__
def __neg__(self): return self * -1
def __sub__(self, other): return self + (-other)
def __rsub__(self, other): return other + (-self)
def __truediv__(self, other): return self * other ** -1
def __repr__(self): return f"Value(data={self.data:.4f}, grad={self.grad:.4f})"
# the same graph as the figure: d = a·b, e = d + c, f = tanh(e), L = f·a
a, b, c = Value(0.8), Value(-1.5), Value(1.6)
d = a * b; e = d + c; f = e.tanh(); L = f * a
L.backward()
for name, v in zip("abcdefL", [a, b, c, d, e, f, L]):
print(f"{name}: {v}")
# check against a numerical derivative
def Lof(a_, b_=-1.5, c_=1.6):
return math.tanh(a_ * b_ + c_) * a_
h = 1e-6
print(f"\nnumerical dL/da = {(Lof(0.8 + h) - Lof(0.8 - h)) / (2*h):.6f} (backprop {a.grad:.6f})")Notice that every _backward uses +=, not =. That is the fan-out sum. With =, an expression like a = b + b would get a gradient of 1 instead of 2 — a bug. For the same reason, a training loop must reset .grad to 0 every step (PyTorch’s optimizer.zero_grad()).
These 40 lines are enough to train a neural network. A neuron is , a layer is a list of neurons, an MLP is a list of layers.
import random
random.seed(1)
class Neuron:
def __init__(self, nin, nonlin=True):
self.w = [Value(random.uniform(-1, 1)) for _ in range(nin)]
self.b = Value(0.0)
self.nonlin = nonlin
def __call__(self, x):
act = sum((wi * xi for wi, xi in zip(self.w, x)), self.b)
return act.tanh() if self.nonlin else act
def parameters(self):
return self.w + [self.b]
class Layer:
def __init__(self, nin, nout, **kw):
self.neurons = [Neuron(nin, **kw) for _ in range(nout)]
def __call__(self, x):
out = [n(x) for n in self.neurons]
return out[0] if len(out) == 1 else out
def parameters(self):
return [p for n in self.neurons for p in n.parameters()]
class MLP:
def __init__(self, nin, nouts):
sz = [nin] + nouts
self.layers = [Layer(sz[i], sz[i+1], nonlin=(i != len(nouts) - 1))
for i in range(len(nouts))]
def __call__(self, x):
for layer in self.layers:
x = layer(x)
return x
def parameters(self):
return [p for l in self.layers for p in l.parameters()]
# a 4-example dataset: 3-D inputs, targets ±1
xs = [[2.0, 3.0, -1.0], [3.0, -1.0, 0.5], [0.5, 1.0, 1.0], [1.0, 1.0, -1.0]]
ys = [1.0, -1.0, -1.0, 1.0]
model = MLP(3, [4, 4, 1])
print("number of parameters:", len(model.parameters()))
for step in range(30):
preds = [model(x) for x in xs]
loss = sum((p - y) ** 2 for p, y in zip(preds, ys)) * (1 / len(xs))
for p in model.parameters():
p.grad = 0.0 # gradients accumulate, so zero them every step!
loss.backward()
for p in model.parameters():
p.data -= 0.05 * p.grad
if step % 5 == 0 or step == 29:
print(f"step {step:2d} loss {loss.data:.5f}")
print("predictions:", [round(model(x).data, 3) for x in xs], " targets:", ys)Since every single scalar is a Python object, this is extremely slow (the graph of this tiny MLP alone has hundreds of nodes). In a real framework one node is one tensor operation, and _backward is a VJP formula from the table above. The structure is exactly the same.
Build it 2: a vectorised MLP and a gradient check
This time we work with tensors, writing the VJP formulas by hand to implement backprop for a 2-layer MLP + softmax cross-entropy. Then we do what must always be done: a finite-difference gradient check.
The error of the central difference is (the odd-order terms of the Taylor expansion cancel). In float64 with the relative error should come out below ; anything above is almost certainly a bug. In float32 rounding error makes this check unreliable, so always do it in float64.
import numpy as np
rng = np.random.default_rng(0)
# 2-layer MLP: X(B,D) → tanh(X W1 + b1)(B,H) → logits(B,K) → softmax cross-entropy
B, D, H, K = 8, 5, 16, 3
X = rng.normal(size=(B, D))
y = rng.integers(0, K, size=B)
params = {
"W1": rng.normal(size=(D, H)) / np.sqrt(D), "b1": np.zeros(H),
"W2": rng.normal(size=(H, K)) / np.sqrt(H), "b2": np.zeros(K),
}
def forward(p, X, y):
Z1 = X @ p["W1"] + p["b1"]
A1 = np.tanh(Z1)
logits = A1 @ p["W2"] + p["b2"]
logits = logits - logits.max(axis=1, keepdims=True) # numerical stability
P = np.exp(logits) / np.exp(logits).sum(axis=1, keepdims=True)
loss = -np.log(P[np.arange(len(y)), y]).mean()
return loss, (X, A1, P)
def backward(p, cache, y):
X, A1, P = cache
B = len(y)
dlogits = P.copy()
dlogits[np.arange(B), y] -= 1 # softmax+CE: p − onehot
dlogits /= B
g = {}
g["W2"] = A1.T @ dlogits # (H,B)(B,K)
g["b2"] = dlogits.sum(axis=0) # fan-out along the batch axis → sum
dA1 = dlogits @ p["W2"].T # VJP: multiply by Wᵀ to go back
dZ1 = dA1 * (1 - A1 ** 2) # elementwise: multiply by tanh'
g["W1"] = X.T @ dZ1
g["b1"] = dZ1.sum(axis=0)
return g
loss, cache = forward(params, X, y)
grads = backward(params, cache, y)
# finite-difference gradient check (central difference, float64)
def num_grad(p, name, eps=1e-5):
G = np.zeros_like(p[name])
it = np.nditer(p[name], flags=["multi_index"])
for _ in it:
i = it.multi_index
old = p[name][i]
p[name][i] = old + eps; lp, _ = forward(p, X, y)
p[name][i] = old - eps; lm, _ = forward(p, X, y)
p[name][i] = old
G[i] = (lp - lm) / (2 * eps)
return G
print(f"loss = {loss:.6f}")
for name in params:
num = num_grad(params, name)
rel = np.abs(num - grads[name]).max() / max(1e-12, np.abs(num).max())
print(f"{name:3s} shape={str(params[name].shape):8s} max relative error = {rel:.2e}")
# a deliberately wrong backward: what if b2's sum becomes a mean?
wrong = grads["b2"] / B
print(f"\nbuggy b2 relative error = {np.abs(num_grad(params, 'b2') - wrong).max() / np.abs(grads['b2']).max():.2e} ← the check catches it")Checking with PyTorch
PyTorch’s autograd works on the same principle as the Value above, except that a node is a tensor operation. Operations starting from a tensor with requires_grad=True record the graph through grad_fn, and .backward() calls the VJPs in reverse order.
import torch
# 1) the figure's graph: must match the values computed by hand
a = torch.tensor(0.8, dtype=torch.float64, requires_grad=True)
b = torch.tensor(-1.5, dtype=torch.float64, requires_grad=True)
c = torch.tensor(1.6, dtype=torch.float64, requires_grad=True)
L = torch.tanh(a * b + c) * a
L.backward()
print(a.grad.item(), b.grad.item(), c.grad.item()) # -0.6468 0.5476 0.6845
# 2) the VJP directly: grad_outputs is the u (output-side vector) in the formula above
W = torch.randn(3, 5, dtype=torch.float64)
x = torch.randn(5, dtype=torch.float64, requires_grad=True)
y = torch.tanh(W @ x)
u = torch.randn(3, dtype=torch.float64)
(vjp,) = torch.autograd.grad(y, x, grad_outputs=u)
J = torch.autograd.functional.jacobian(lambda x: torch.tanh(W @ x), x)
print(torch.allclose(vjp, u @ J)) # True: VJP = uᵀJ
# 3) compare a whole 2-layer MLP against finite differences
def mlp(X, W1, b1, W2, b2):
return torch.tanh(X @ W1 + b1) @ W2 + b2
inputs = [torch.randn(8, 5, dtype=torch.float64)] + [
torch.randn(*s, dtype=torch.float64, requires_grad=True)
for s in [(5, 16), (16,), (16, 3), (3,)]
]
print(torch.autograd.gradcheck(mlp, inputs)) # Truef = a·b + a with a = 3 and b = 2. What is ∂f/∂a as computed by backpropagation?
is used in two places. Through the multiplication node arrives, through the addition node arrives, and since it is a fan-out they are added: . Implement it with = instead of += and only the path processed last survives, giving 2 or 1.
You want the full Jacobian (10×1000) of a function f: R^1000 → R^10 by autodiff. Which mode finishes, and in how many passes?
Reverse mode yields one row of the Jacobian () per output-side basis vector . The output is 10-dimensional, so 10 passes. Forward mode yields one column per input basis vector, so it needs 1000. When the output is 1-dimensional, as with a loss, a single reverse-mode pass suffices.
Summary
- Backpropagation = walking the computation graph in reverse topological order and adding
upstream × localinto each input. Each node only knows its own local derivative. - Addition distributes, multiplication multiplies by the other value, nonlinearities gate, fan-out sums.
- For a scalar output, reverse mode (VJP) gives every gradient at a constant multiple of the forward pass’s cost. The price is the memory to store activations.
- Real implementations never build the Jacobian; they only have VJP functions: , , , .
- Check hand-written backprop with float64 central differences. A relative error near is normal.
그림에서 확인할 것.
- 덧셈은 분배기: 에서 받은 기울기가 와 에 그대로 복사된다.
- 곱셈은 교환기: 에서 로 가는 기울기에는 가, 로 가는 기울기에는 가 곱해진다. 한쪽 입력이 크면 다른 쪽 기울기가 커진다. 입력 정규화가 중요한 이유 중 하나다.
- 비선형은 게이트: relu에서 이면 국소 미분이 0이라 그 아래 전체로 기울기가 가지 않는다. tanh도 가 크면 거의 0이다(포화).
- fan-out은 합: 는 와 두 곳에 쓰여서 기울기 두 개가 도착한다. 마지막 단계에서
a.grad가 두 기여의 합이 되고, 오른쪽 아래의 수치 미분과 일치한다.
왜 역방향인가: VJP와 JVP
계산이 의 합성이라면, 연쇄 법칙은 야코비안(Jacobian)의 곱이다.
행렬곱은 결합법칙이 성립하므로 어느 쪽부터 곱해도 결과는 같지만 비용이 다르다.
- Forward mode: 오른쪽부터. 입력 방향 벡터 를 넣어 , 즉 야코비안–벡터 곱(JVP)을 순전파와 함께 흘린다. 전체 야코비안을 얻으려면 입력 차원 번 반복해야 한다.
- Reverse mode: 왼쪽부터. 출력 쪽 벡터 를 넣어 , 즉 벡터–야코비안 곱(VJP)을 거꾸로 흘린다. 출력 차원 번이면 된다.
학습에서 출력은 스칼라 손실(), 입력은 매개변수 수억 개()다. 역방향 한 번()으로 기울기 전체가 나온다. 각 VJP는 해당 층의 순전파와 비슷한 비용이므로, 역전파 전체는 순전파의 작은 상수 배(행렬곱 기준 약 2배: 입력에 대한 기울기와 가중치에 대한 기울기 각각 행렬곱 하나)다. 이론적으로도 기울기 계산 비용은 함수 계산 비용의 상수 배로 묶인다(cheap gradient principle, Baur–Strassen 정리).
대가는 메모리다. VJP를 계산하려면 순전파의 중간값(그림의 회색 숫자)이 필요하므로, 역전파가 끝날 때까지 모든 층의 활성화를 저장해야 한다. 거대 모델 학습에서 활성화 메모리가 매개변수 메모리보다 커지는 일이 흔하고, 일부 활성화를 버렸다가 역전파 때 다시 계산하는 activation checkpointing 이 그 해법이다.
야코비안을 만들지 않는다
실제 구현은 를 행렬로 만들지 않고, VJP를 직접 계산하는 함수만 가진다. 자주 쓰는 것들(행 = 배치, ):
| 연산 | 순전파 | 역전파(VJP) |
|---|---|---|
| 선형 | , | |
| 편향 | (배치 방향 fan-out → 합) | |
| 원소별 | (야코비안이 대각이라 곱셈 하나) | |
| softmax + CE |
선형층의 공식은 차원만 맞추면 외울 필요가 없다. 는 와 같은 모양이어야 하고, 만들 수 있는 곱은 뿐이다. 원소별 연산의 야코비안은 이지만 대각이라, 행렬로 만들었다면 였을 일을 에 한다.
직접 만들기 1: 스칼라 autograd
Karpathy의 micrograd와 같은 구조로 만든다. Value는 숫자 하나와 .grad, 그리고 “나를 만든 연산의 국소 연쇄 법칙”인 _backward 클로저를 가진다. 연산자를 오버로딩해서, 평범한 파이썬 식을 쓰기만 해도 그래프가 기록된다(define-by-run, PyTorch와 같은 방식). 그림과 같은 그래프로 검증한다.
import math
class Value:
"""스칼라 하나와 그 기울기. 연산할 때마다 계산 그래프를 기록한다."""
def __init__(self, data, _children=(), _op=''):
self.data = float(data)
self.grad = 0.0
self._backward = lambda: None # 이 노드의 국소 연쇄 법칙
self._prev = set(_children)
self._op = _op
def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other), '+')
def _backward():
self.grad += out.grad # 덧셈: 그대로 전달
other.grad += out.grad
out._backward = _backward
return out
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other), '*')
def _backward():
self.grad += other.data * out.grad # 곱셈: 상대 값을 곱해 전달
other.grad += self.data * out.grad
out._backward = _backward
return out
def __pow__(self, k): # k는 상수
out = Value(self.data ** k, (self,), f'**{k}')
def _backward():
self.grad += k * self.data ** (k - 1) * out.grad
out._backward = _backward
return out
def tanh(self):
t = math.tanh(self.data)
out = Value(t, (self,), 'tanh')
def _backward():
self.grad += (1 - t * t) * out.grad
out._backward = _backward
return out
def relu(self):
out = Value(max(0.0, self.data), (self,), 'relu')
def _backward():
self.grad += (out.data > 0) * out.grad
out._backward = _backward
return out
def backward(self):
# 위상 정렬: 어떤 노드든 그것을 쓰는 모든 노드보다 나중에 처리되도록
topo, seen = [], set()
def build(v):
if v not in seen:
seen.add(v)
for c in v._prev:
build(c)
topo.append(v)
build(self)
self.grad = 1.0
for v in reversed(topo):
v._backward()
__radd__ = __add__
__rmul__ = __mul__
def __neg__(self): return self * -1
def __sub__(self, other): return self + (-other)
def __rsub__(self, other): return other + (-self)
def __truediv__(self, other): return self * other ** -1
def __repr__(self): return f"Value(data={self.data:.4f}, grad={self.grad:.4f})"
# 그림과 같은 그래프: d = a·b, e = d + c, f = tanh(e), L = f·a
a, b, c = Value(0.8), Value(-1.5), Value(1.6)
d = a * b; e = d + c; f = e.tanh(); L = f * a
L.backward()
for name, v in zip("abcdefL", [a, b, c, d, e, f, L]):
print(f"{name}: {v}")
# 수치 미분으로 확인
def Lof(a_, b_=-1.5, c_=1.6):
return math.tanh(a_ * b_ + c_) * a_
h = 1e-6
print(f"\n수치미분 dL/da = {(Lof(0.8 + h) - Lof(0.8 - h)) / (2*h):.6f} (역전파 {a.grad:.6f})")모든 _backward가 =가 아니라 +=라는 점에 주목하자. 이것이 fan-out의 합이다. a = b + b 같은 식에서 =로 쓰면 기울기가 2가 아니라 1이 되는 버그가 생긴다. 같은 이유로 학습 루프에서는 매 step .grad를 0으로 되돌려야 한다(PyTorch의 optimizer.zero_grad()).
이 40줄이면 신경망을 학습시킬 수 있다. 뉴런은 , 층은 뉴런의 목록, MLP는 층의 목록이다.
import random
random.seed(1)
class Neuron:
def __init__(self, nin, nonlin=True):
self.w = [Value(random.uniform(-1, 1)) for _ in range(nin)]
self.b = Value(0.0)
self.nonlin = nonlin
def __call__(self, x):
act = sum((wi * xi for wi, xi in zip(self.w, x)), self.b)
return act.tanh() if self.nonlin else act
def parameters(self):
return self.w + [self.b]
class Layer:
def __init__(self, nin, nout, **kw):
self.neurons = [Neuron(nin, **kw) for _ in range(nout)]
def __call__(self, x):
out = [n(x) for n in self.neurons]
return out[0] if len(out) == 1 else out
def parameters(self):
return [p for n in self.neurons for p in n.parameters()]
class MLP:
def __init__(self, nin, nouts):
sz = [nin] + nouts
self.layers = [Layer(sz[i], sz[i+1], nonlin=(i != len(nouts) - 1))
for i in range(len(nouts))]
def __call__(self, x):
for layer in self.layers:
x = layer(x)
return x
def parameters(self):
return [p for l in self.layers for p in l.parameters()]
# 4개짜리 데이터셋: 입력 3차원, 목표 ±1
xs = [[2.0, 3.0, -1.0], [3.0, -1.0, 0.5], [0.5, 1.0, 1.0], [1.0, 1.0, -1.0]]
ys = [1.0, -1.0, -1.0, 1.0]
model = MLP(3, [4, 4, 1])
print("매개변수 수:", len(model.parameters()))
for step in range(30):
preds = [model(x) for x in xs]
loss = sum((p - y) ** 2 for p, y in zip(preds, ys)) * (1 / len(xs))
for p in model.parameters():
p.grad = 0.0 # 누적되므로 매 step 0으로!
loss.backward()
for p in model.parameters():
p.data -= 0.05 * p.grad
if step % 5 == 0 or step == 29:
print(f"step {step:2d} loss {loss.data:.5f}")
print("예측:", [round(model(x).data, 3) for x in xs], " 목표:", ys)스칼라 하나하나가 파이썬 객체이므로 극도로 느리다(이 작은 MLP의 그래프 노드만 수백 개다). 실제 프레임워크는 노드 하나가 텐서 연산 하나 이고, _backward가 위 표의 VJP 공식이다. 구조는 완전히 같다.
직접 만들기 2: 벡터화된 MLP와 기울기 검사
이번에는 텐서 단위로, VJP 공식을 손으로 써서 2층 MLP + softmax cross-entropy의 역전파를 구현한다. 그리고 반드시 해야 하는 일을 한다. 유한 차분 기울기 검사(gradient check).
중심 차분 의 오차는 이다(테일러 전개에서 홀수 차항이 상쇄). float64에서 이면 상대오차가 이하로 나와야 하고, 보다 크면 거의 확실히 버그다. float32에서는 반올림 오차 때문에 이 검사가 잘 안 되므로 꼭 float64로 한다.
import numpy as np
rng = np.random.default_rng(0)
# 2층 MLP: X(B,D) → tanh(X W1 + b1)(B,H) → logits(B,K) → softmax cross-entropy
B, D, H, K = 8, 5, 16, 3
X = rng.normal(size=(B, D))
y = rng.integers(0, K, size=B)
params = {
"W1": rng.normal(size=(D, H)) / np.sqrt(D), "b1": np.zeros(H),
"W2": rng.normal(size=(H, K)) / np.sqrt(H), "b2": np.zeros(K),
}
def forward(p, X, y):
Z1 = X @ p["W1"] + p["b1"]
A1 = np.tanh(Z1)
logits = A1 @ p["W2"] + p["b2"]
logits = logits - logits.max(axis=1, keepdims=True) # 수치 안정성
P = np.exp(logits) / np.exp(logits).sum(axis=1, keepdims=True)
loss = -np.log(P[np.arange(len(y)), y]).mean()
return loss, (X, A1, P)
def backward(p, cache, y):
X, A1, P = cache
B = len(y)
dlogits = P.copy()
dlogits[np.arange(B), y] -= 1 # softmax+CE: p − onehot
dlogits /= B
g = {}
g["W2"] = A1.T @ dlogits # (H,B)(B,K)
g["b2"] = dlogits.sum(axis=0) # 배치 축으로 fan-out → 합
dA1 = dlogits @ p["W2"].T # VJP: Wᵀ를 곱해 되돌린다
dZ1 = dA1 * (1 - A1 ** 2) # 원소별: tanh' 를 곱한다
g["W1"] = X.T @ dZ1
g["b1"] = dZ1.sum(axis=0)
return g
loss, cache = forward(params, X, y)
grads = backward(params, cache, y)
# 유한 차분 기울기 검사 (중심 차분, float64)
def num_grad(p, name, eps=1e-5):
G = np.zeros_like(p[name])
it = np.nditer(p[name], flags=["multi_index"])
for _ in it:
i = it.multi_index
old = p[name][i]
p[name][i] = old + eps; lp, _ = forward(p, X, y)
p[name][i] = old - eps; lm, _ = forward(p, X, y)
p[name][i] = old
G[i] = (lp - lm) / (2 * eps)
return G
print(f"loss = {loss:.6f}")
for name in params:
num = num_grad(params, name)
rel = np.abs(num - grads[name]).max() / max(1e-12, np.abs(num).max())
print(f"{name:3s} shape={str(params[name].shape):8s} 최대 상대오차 = {rel:.2e}")
# 일부러 틀린 backward: b2의 합을 평균으로 바꾸면?
wrong = grads["b2"] / B
print(f"\n버그 넣은 b2 상대오차 = {np.abs(num_grad(params, 'b2') - wrong).max() / np.abs(grads['b2']).max():.2e} ← 검사가 잡아낸다")PyTorch로 확인하기
PyTorch의 autograd는 위 Value와 같은 원리로, 노드 하나가 텐서 연산이다. requires_grad=True인 텐서에서 시작한 연산은 grad_fn으로 그래프를 기록하고, .backward()가 VJP를 역순으로 호출한다.
import torch
# 1) 그림의 그래프: 손으로 구한 값과 같아야 한다
a = torch.tensor(0.8, dtype=torch.float64, requires_grad=True)
b = torch.tensor(-1.5, dtype=torch.float64, requires_grad=True)
c = torch.tensor(1.6, dtype=torch.float64, requires_grad=True)
L = torch.tanh(a * b + c) * a
L.backward()
print(a.grad.item(), b.grad.item(), c.grad.item()) # -0.6468 0.5476 0.6845
# 2) VJP를 직접: grad_outputs가 위 식의 u (출력 쪽 벡터)
W = torch.randn(3, 5, dtype=torch.float64)
x = torch.randn(5, dtype=torch.float64, requires_grad=True)
y = torch.tanh(W @ x)
u = torch.randn(3, dtype=torch.float64)
(vjp,) = torch.autograd.grad(y, x, grad_outputs=u)
J = torch.autograd.functional.jacobian(lambda x: torch.tanh(W @ x), x)
print(torch.allclose(vjp, u @ J)) # True: VJP = uᵀJ
# 3) 2층 MLP 전체를 유한 차분과 비교
def mlp(X, W1, b1, W2, b2):
return torch.tanh(X @ W1 + b1) @ W2 + b2
inputs = [torch.randn(8, 5, dtype=torch.float64)] + [
torch.randn(*s, dtype=torch.float64, requires_grad=True)
for s in [(5, 16), (16,), (16, 3), (3,)]
]
print(torch.autograd.gradcheck(mlp, inputs)) # Truef = a·b + a 이고 a = 3, b = 2 이다. 역전파로 구한 ∂f/∂a 는?
는 두 곳에 쓰인다. 곱셈 노드를 통해 , 덧셈 노드를 통해 이 도착하고, fan-out이므로 더해서 이다. += 대신 =로 구현하면 나중에 처리된 경로 하나만 남아 2나 1이 나온다.
함수 f: R^1000 → R^10 의 야코비안 전체(10×1000)를 autodiff로 구하려 한다. 어느 모드가 몇 번의 패스로 끝나는가?
Reverse mode는 출력 쪽 기저벡터 하나당 야코비안의 한 행()을 준다. 출력이 10차원이니 10번이다. Forward mode는 입력 기저벡터 하나당 한 열을 주므로 1000번이 필요하다. 손실처럼 출력이 1차원이면 reverse mode 한 번으로 끝난다.
정리
- 역전파 = 계산 그래프를 위상 정렬 역순으로 돌며
upstream × local을 입력에 더해 주는 것. 각 노드는 자기 국소 미분만 안다. - 덧셈은 분배, 곱셈은 상대값 곱하기, 비선형은 게이트, fan-out은 합.
- 스칼라 출력에 대해 reverse mode(VJP)는 순전파의 상수 배 비용으로 모든 기울기를 준다. 대가는 활성화 저장 메모리다.
- 실제 구현은 야코비안을 만들지 않고 VJP 함수만 가진다: , , , .
- 손으로 쓴 역전파는 float64 중심 차분으로 검사한다. 상대오차 근처가 정상이다.
더 읽을거리Further reading
- Karpathy, micrograd (GitHub) and 'The spelled-out intro to neural networks and backpropagation' (Neural Networks: Zero to Hero, 2022) — 이 레슨의 Value 클래스가 따르는 원형. 영상은 2시간 반 동안 같은 것을 손으로 쌓는다The model for this lesson's Value class. The video builds the same thing by hand over two and a half hours
- Rumelhart, Hinton, Williams, Learning Representations by Back-propagating Errors (Nature, 1986) — 역전파로 은닉층 표현을 학습할 수 있음을 보여 대중화한 논문The paper that popularised backpropagation by showing it can learn hidden-layer representations
- Baydin, Pearlmutter, Radul, Siskind, Automatic Differentiation in Machine Learning: a Survey (JMLR, 2018) — forward/reverse mode, 비용, 구현 방식을 정리한 표준 서베이The standard survey of forward/reverse mode, their costs and how they are implemented
- Olah, Calculus on Computational Graphs: Backpropagation (colah's blog, 2015) — 경로 합으로 보는 연쇄 법칙과 forward vs reverse mode의 그림 설명Pictures of the chain rule as a sum over paths, and of forward vs reverse mode
- Goodfellow, Bengio, Courville, Deep Learning §6.5 (MIT Press, 2016) — 일반 계산 그래프에서의 역전파 알고리즘과 메모리·계산 비용The backpropagation algorithm on general computation graphs, with its memory and compute costs
- Stanford CS231n, Backpropagation, Intuitions — 덧셈·곱셈·max 게이트의 기울기 흐름 패턴, 행렬곱 역전파의 차원 맞추기Gradient-flow patterns of add, multiply and max gates, and matching dimensions when backpropagating through a matrix product