Track II · DL Fundamentals · 02/07

역전파와 autogradBackpropagation and autograd

계산 그래프 위에서 연쇄 법칙을 출력 쪽부터 적용하는 역전파를 손으로, 스칼라 autograd(micrograd)로, 벡터화된 NumPy로 세 번 구현한다. 왜 역방향이 싼지(VJP), fan-out에서 왜 더하는지, 구현을 어떻게 검사하는지 설명할 수 있게 된다.Implement backpropagation — applying the chain rule on a computation graph starting from the output — three times: by hand, as a scalar autograd (micrograd), and in vectorised NumPy. You will be able to explain why the reverse direction is cheap (VJP), why gradients add up at a fan-out, and how to check an implementation.

40 분min backpropagation · autograd · chain rule · VJP · gradient check 먼저 볼 것:Before this: 퍼셉트론에서 MLP로From perceptron to MLP, 경사하강법Gradient descent

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, ∇θL\nabla_\theta L. With PP parameters, finite differences take P+1P+1 forward passes (2P2P for central differences). GPT-2 small alone has P≈1.24×108P \approx 1.24\times 10^8. 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 uu is computed from inputs v1,…,vkv_1, \dots, v_k as u=g(v1,…,vk)u = g(v_1, \dots, v_k). For the final output LL, the chain rule is

∂L∂vi  +=  ∂L∂u⏟upstream⋅∂u∂vi⏟local\frac{\partial L}{\partial v_i} \;\mathrel{+}=\; \underbrace{\frac{\partial L}{\partial u}}_{\text{upstream}} \cdot \underbrace{\frac{\partial u}{\partial v_i}}_{\text{local}}

Two things are key.

  • Locality: node uu only needs the derivative of its own operation gg (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 "1−tanh⁡21 - \tanh^2".
  • Sum (+=): if viv_i is used by several nodes (fan-out), there are several paths through which it affects LL. 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 ∂L/∂(⋅)\partial L/\partial(\cdot) 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.

지난 레슨의 결론은 “첫 층의 꺾임 위치까지 학습해야 유닛을 낭비하지 않는다”였다. 그러려면 모든 매개변수에 대한 손실의 기울기 ∇θL\nabla_\theta L이 필요하다. 매개변수가 PP개일 때 유한 차분으로 구하면 순전파를 P+1P+1번(중심 차분이면 2P2P번) 해야 한다. GPT-2 small만 해도 P≈1.24×108P \approx 1.24\times 10^8이다. 역전파(backpropagation) 는 같은 기울기를 순전파 한 번의 상수 배 비용으로 정확히 구한다. 이 레슨은 그것이 어떻게 가능한지를 그림, 스칼라 구현, 벡터 구현 순으로 본다.

계산 그래프와 연쇄 법칙

어떤 계산이든 기본 연산(덧셈, 곱셈, tanh …)의 합성으로 쪼갤 수 있고, 그 의존 관계는 방향 비순환 그래프(DAG)다. 노드 uu가 입력 v1,…,vkv_1, \dots, v_k로부터 u=g(v1,…,vk)u = g(v_1, \dots, v_k)로 계산된다고 하자. 최종 출력 LL에 대해 연쇄 법칙(chain rule)은

∂L∂vi  +=  ∂L∂u⏟upstream⋅∂u∂vi⏟local\frac{\partial L}{\partial v_i} \;\mathrel{+}=\; \underbrace{\frac{\partial L}{\partial u}}_{\text{upstream}} \cdot \underbrace{\frac{\partial u}{\partial v_i}}_{\text{local}}

이다. 두 가지가 핵심이다.

  • 국소성: 노드 uu는 자기 연산 gg의 미분(local gradient)만 알면 된다. 그래프 전체를 알 필요가 없다. 덧셈 노드는 “1”, 곱셈 노드는 “상대 입력값”, tanh 노드는 "1−tanh⁡21 - \tanh^2"만 안다.
  • 합(+=): viv_i가 여러 노드에서 쓰이면(fan-out), LL에 영향을 주는 경로가 여럿이다. 다변수 연쇄 법칙에 따라 경로별 기여를 더한다.

출력 쪽부터 위상 정렬의 역순으로 각 노드를 한 번씩 방문하며 이 규칙을 적용하면, 모든 노드의 ∂L/∂(⋅)\partial L/\partial(\cdot)가 채워진다. 방문할 때 그 노드로 들어올 기울기는 이미 모두 도착해 있다(그 노드를 쓰는 노드들이 모두 먼저 처리되었으므로). 이것이 역전파의 전부다.

L = – 역전파backprop ∂L/∂a = ? 수치미분finite difference (L(a+h) − L(a−h))/2h = –
Grey numbers are forward values; red numbers are ∂L/∂(node), filled in by backpropagation. Press ▶ to step from the output back towards the inputs one node at a time. Each node only multiplies the gradient it receives by its own local derivative and passes it towards its inputs. a is used in two places (d and L), so its two gradients add up. Pick relu and push c negative: e < 0, and the gradient is cut off at f. 회색 숫자는 순전파 값, 빨간 숫자는 역전파로 채워지는 ∂L/∂(노드). ▶를 눌러 출력에서 입력 쪽으로 한 노드씩 진행해 보세요. 각 노드는 받은 기울기에 자기 국소 미분을 곱해 입력 쪽으로 보낼 뿐이다. a는 두 곳(d와 L)에서 쓰이므로 기울기 두 개가 더해진다. relu를 고르고 c를 음수로 내리면 e < 0이 되어 기울기가 f에서 끊긴다.

Things to check in the figure.

  1. Addition is a distributor: the gradient arriving at e=d+ce = d + c is copied unchanged to dd and cc.
  2. Multiplication is a swapper: in d=a⋅bd = a\cdot b, the gradient going to aa is multiplied by bb, and the gradient going to bb by aa. If one input is large, the other’s gradient is large — one of the reasons input normalisation matters.
  3. Nonlinearities are gates: in relu, if e<0e < 0 the local derivative is 0, so no gradient reaches anything below it. tanh is also nearly 0 when ∣e∣|e| is large (saturation).
  4. Fan-out is a sum: aa is used in two places, dd and LL, so two gradients arrive. In the last step a.grad becomes 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 x∈Rn→h1→⋯→hk→y∈Rmx \in \mathbb{R}^n \to h_1 \to \dots \to h_{k} \to y \in \mathbb{R}^m, the chain rule is a product of Jacobians.

∂y∂x=JkJk−1⋯J1,Ji=∂hi∂hi−1\frac{\partial y}{\partial x} = J_k J_{k-1} \cdots J_1, \qquad J_i = \frac{\partial h_i}{\partial h_{i-1}}

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 vv and push Jk(⋯(J1v))J_k(\cdots(J_1 v)), a Jacobian–vector product (JVP), along with the forward pass. Getting the full Jacobian takes nn repetitions, one per input dimension.
  • Reverse mode: from the left. Feed an output-side vector u⊤u^\top and push ((u⊤Jk)Jk−1)⋯J1((u^\top J_k) J_{k-1})\cdots J_1, a vector–Jacobian product (VJP), backwards. It takes mm repetitions, one per output dimension.

In training the output is a scalar loss (m=1m = 1) and the input is hundreds of millions of parameters (n=Pn = P). One reverse pass (u=1u = 1) 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 JiJ_i as a matrix; they only have functions that compute the VJP directly. The common ones (rows = batch, G=∂L/∂(output)G = \partial L/\partial(\text{output})):

OperationForwardBackward (VJP)
LinearY=XWY = XW∂L/∂X=GW⊤\partial L/\partial X = G W^\top,   ∂L/∂W=X⊤G\;\partial L/\partial W = X^\top G
BiasY=X+1b⊤Y = X + \mathbf{1}b^\top∂L/∂b=∑batchG\partial L/\partial b = \sum_{\text{batch}} G (fan-out along the batch → sum)
ElementwiseY=ϕ(X)Y = \phi(X)∂L/∂X=G⊙ϕ′(X)\partial L/\partial X = G \odot \phi'(X) (the Jacobian is diagonal, so one multiplication)
softmax + CEℓ=−log⁡softmax⁡(z)y\ell = -\log \operatorname{softmax}(z)_y∂ℓ/∂z=softmax⁡(z)−ey\partial \ell/\partial z = \operatorname{softmax}(z) - e_y

You don’t need to memorise the linear-layer formulas as long as you match dimensions: ∂L/∂W\partial L/\partial W must have the same shape as WW, and the only product that gives it is X⊤GX^\top G. The Jacobian of an elementwise op is n×nn\times n but diagonal, so what would have been O(n2)O(n^2) as a matrix takes O(n)O(n).

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.

NumPy A micrograd-style Value class
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 tanh⁡(w⊤x+b)\tanh(w^\top x + b), a layer is a list of neurons, an MLP is a list of layers.

NumPy Training an MLP with Value
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 L(θ+ϵei)−L(θ−ϵei)2ϵ\frac{L(\theta + \epsilon e_i) - L(\theta - \epsilon e_i)}{2\epsilon} is O(ϵ2)O(\epsilon^2) (the odd-order terms of the Taylor expansion cancel). In float64 with ϵ=10−5\epsilon = 10^{-5} the relative error should come out below 10−910^{-9}; anything above 10−410^{-4} is almost certainly a bug. In float32 rounding error makes this check unreliable, so always do it in float64.

NumPy NumPy MLP: hand-written backprop + gradient check
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.

PyTorch The same graph and VJP with torch.autograd 로컬에서 실행run locally (pip install torch)
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))           # True
 
확인 문제Check yourself

f = a·b + a with a = 3 and b = 2. What is ∂f/∂a as computed by backpropagation?

aa is used in two places. Through the multiplication node b=2b = 2 arrives, through the addition node 11 arrives, and since it is a fan-out they are added: ∂f/∂a=b+1=3\partial f/\partial a = b + 1 = 3. Implement it with = instead of += and only the path processed last survives, giving 2 or 1.

확인 문제Check yourself

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 (ei⊤Je_i^\top J) per output-side basis vector ei⊤e_i^\top. 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 × local into 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: GW⊤GW^\top, X⊤GX^\top G, G⊙ϕ′G\odot\phi', p−eyp - e_y.
  • Check hand-written backprop with float64 central differences. A relative error near 10−910^{-9} is normal.

그림에서 확인할 것.

  1. 덧셈은 분배기: e=d+ce = d + c에서 받은 기울기가 dd와 cc에 그대로 복사된다.
  2. 곱셈은 교환기: d=a⋅bd = a\cdot b에서 aa로 가는 기울기에는 bb가, bb로 가는 기울기에는 aa가 곱해진다. 한쪽 입력이 크면 다른 쪽 기울기가 커진다. 입력 정규화가 중요한 이유 중 하나다.
  3. 비선형은 게이트: relu에서 e<0e < 0이면 국소 미분이 0이라 그 아래 전체로 기울기가 가지 않는다. tanh도 ∣e∣|e|가 크면 거의 0이다(포화).
  4. fan-out은 합: aa는 dd와 LL 두 곳에 쓰여서 기울기 두 개가 도착한다. 마지막 단계에서 a.grad가 두 기여의 합이 되고, 오른쪽 아래의 수치 미분과 일치한다.

왜 역방향인가: VJP와 JVP

계산이 x∈Rn→h1→⋯→hk→y∈Rmx \in \mathbb{R}^n \to h_1 \to \dots \to h_{k} \to y \in \mathbb{R}^m 의 합성이라면, 연쇄 법칙은 야코비안(Jacobian)의 곱이다.

∂y∂x=JkJk−1⋯J1,Ji=∂hi∂hi−1\frac{\partial y}{\partial x} = J_k J_{k-1} \cdots J_1, \qquad J_i = \frac{\partial h_i}{\partial h_{i-1}}

행렬곱은 결합법칙이 성립하므로 어느 쪽부터 곱해도 결과는 같지만 비용이 다르다.

  • Forward mode: 오른쪽부터. 입력 방향 벡터 vv를 넣어 Jk(⋯(J1v))J_k(\cdots(J_1 v)), 즉 야코비안–벡터 곱(JVP)을 순전파와 함께 흘린다. 전체 야코비안을 얻으려면 입력 차원 nn번 반복해야 한다.
  • Reverse mode: 왼쪽부터. 출력 쪽 벡터 u⊤u^\top를 넣어 ((u⊤Jk)Jk−1)⋯J1((u^\top J_k) J_{k-1})\cdots J_1, 즉 벡터–야코비안 곱(VJP)을 거꾸로 흘린다. 출력 차원 mm번이면 된다.

학습에서 출력은 스칼라 손실(m=1m = 1), 입력은 매개변수 수억 개(n=Pn = P)다. 역방향 한 번(u=1u = 1)으로 기울기 전체가 나온다. 각 VJP는 해당 층의 순전파와 비슷한 비용이므로, 역전파 전체는 순전파의 작은 상수 배(행렬곱 기준 약 2배: 입력에 대한 기울기와 가중치에 대한 기울기 각각 행렬곱 하나)다. 이론적으로도 기울기 계산 비용은 함수 계산 비용의 상수 배로 묶인다(cheap gradient principle, Baur–Strassen 정리).

대가는 메모리다. VJP를 계산하려면 순전파의 중간값(그림의 회색 숫자)이 필요하므로, 역전파가 끝날 때까지 모든 층의 활성화를 저장해야 한다. 거대 모델 학습에서 활성화 메모리가 매개변수 메모리보다 커지는 일이 흔하고, 일부 활성화를 버렸다가 역전파 때 다시 계산하는 activation checkpointing 이 그 해법이다.

야코비안을 만들지 않는다

실제 구현은 JiJ_i를 행렬로 만들지 않고, VJP를 직접 계산하는 함수만 가진다. 자주 쓰는 것들(행 = 배치, G=∂L/∂(출력)G = \partial L/\partial(\text{출력})):

연산순전파역전파(VJP)
선형Y=XWY = XW∂L/∂X=GW⊤\partial L/\partial X = G W^\top,   ∂L/∂W=X⊤G\;\partial L/\partial W = X^\top G
편향Y=X+1b⊤Y = X + \mathbf{1}b^\top∂L/∂b=∑배치G\partial L/\partial b = \sum_{\text{배치}} G (배치 방향 fan-out → 합)
원소별Y=ϕ(X)Y = \phi(X)∂L/∂X=G⊙ϕ′(X)\partial L/\partial X = G \odot \phi'(X) (야코비안이 대각이라 곱셈 하나)
softmax + CEℓ=−log⁡softmax⁡(z)y\ell = -\log \operatorname{softmax}(z)_y∂ℓ/∂z=softmax⁡(z)−ey\partial \ell/\partial z = \operatorname{softmax}(z) - e_y

선형층의 공식은 차원만 맞추면 외울 필요가 없다. ∂L/∂W\partial L/\partial W는 WW와 같은 모양이어야 하고, 만들 수 있는 곱은 X⊤GX^\top G뿐이다. 원소별 연산의 야코비안은 n×nn\times n이지만 대각이라, 행렬로 만들었다면 O(n2)O(n^2)였을 일을 O(n)O(n)에 한다.

직접 만들기 1: 스칼라 autograd

Karpathy의 micrograd와 같은 구조로 만든다. Value는 숫자 하나와 .grad, 그리고 “나를 만든 연산의 국소 연쇄 법칙”인 _backward 클로저를 가진다. 연산자를 오버로딩해서, 평범한 파이썬 식을 쓰기만 해도 그래프가 기록된다(define-by-run, PyTorch와 같은 방식). 그림과 같은 그래프로 검증한다.

NumPy micrograd 스타일 Value 클래스
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줄이면 신경망을 학습시킬 수 있다. 뉴런은 tanh⁡(w⊤x+b)\tanh(w^\top x + b), 층은 뉴런의 목록, MLP는 층의 목록이다.

NumPy Value로 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).

중심 차분 L(θ+ϵei)−L(θ−ϵei)2ϵ\frac{L(\theta + \epsilon e_i) - L(\theta - \epsilon e_i)}{2\epsilon}의 오차는 O(ϵ2)O(\epsilon^2)이다(테일러 전개에서 홀수 차항이 상쇄). float64에서 ϵ=10−5\epsilon = 10^{-5}이면 상대오차가 10−910^{-9} 이하로 나와야 하고, 10−410^{-4}보다 크면 거의 확실히 버그다. float32에서는 반올림 오차 때문에 이 검사가 잘 안 되므로 꼭 float64로 한다.

NumPy NumPy MLP: 손으로 쓴 역전파 + 기울기 검사
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를 역순으로 호출한다.

PyTorch 같은 그래프와 VJP를 torch.autograd로 로컬에서 실행run locally (pip install torch)
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))           # True
 
확인 문제Check yourself

f = a·b + a 이고 a = 3, b = 2 이다. 역전파로 구한 ∂f/∂a 는?

aa는 두 곳에 쓰인다. 곱셈 노드를 통해 b=2b = 2, 덧셈 노드를 통해 11이 도착하고, fan-out이므로 더해서 ∂f/∂a=b+1=3\partial f/\partial a = b + 1 = 3이다. += 대신 =로 구현하면 나중에 처리된 경로 하나만 남아 2나 1이 나온다.

확인 문제Check yourself

함수 f: R^1000 → R^10 의 야코비안 전체(10×1000)를 autodiff로 구하려 한다. 어느 모드가 몇 번의 패스로 끝나는가?

Reverse mode는 출력 쪽 기저벡터 ei⊤e_i^\top 하나당 야코비안의 한 행(ei⊤Je_i^\top J)을 준다. 출력이 10차원이니 10번이다. Forward mode는 입력 기저벡터 하나당 한 열을 주므로 1000번이 필요하다. 손실처럼 출력이 1차원이면 reverse mode 한 번으로 끝난다.

정리

  • 역전파 = 계산 그래프를 위상 정렬 역순으로 돌며 upstream × local을 입력에 더해 주는 것. 각 노드는 자기 국소 미분만 안다.
  • 덧셈은 분배, 곱셈은 상대값 곱하기, 비선형은 게이트, fan-out은 합.
  • 스칼라 출력에 대해 reverse mode(VJP)는 순전파의 상수 배 비용으로 모든 기울기를 준다. 대가는 활성화 저장 메모리다.
  • 실제 구현은 야코비안을 만들지 않고 VJP 함수만 가진다: GW⊤GW^\top, X⊤GX^\top G, G⊙ϕ′G\odot\phi', p−eyp - e_y.
  • 손으로 쓴 역전파는 float64 중심 차분으로 검사한다. 상대오차 10−910^{-9} 근처가 정상이다.

더 읽을거리Further reading