Backpropagation
Backpropagation
A neural network training algorithm that propagates the output error backward and updates the weights.
Backpropagation
A neural network training algorithm that propagates the output error backward and updates the weights.
Backpropagation (also called backward propagation of errors) is a core algorithm for training neural networks that propagates the output error backward through the network to compute the gradient of each weight. By using these gradients to update the weights, it trains the model in the direction that minimizes the loss.
Published in 1986 by Rumelhart, Hinton, and Williams, this algorithm is based on the Chain Rule. By using the principle of decomposing the derivative of a composite function into the product of the derivatives of its component functions, it can efficiently compute gradients even in deep networks with hundreds of layers.
The computation process is divided into two stages. In the Forward Pass, input data passes through the layers to generate predictions, and in the Backward Pass, starting from the loss function, the gradient for each parameter is computed in the reverse direction. PyTorch's autograd and TensorFlow's GradientTape automate this process.
As of 2024, backpropagation is the foundation for training models with hundreds of billions of parameters, such as GPT-4, Claude, and Gemini. Combined with optimization techniques such as Gradient Checkpointing and Mixed Precision Training, it enables efficient training of large-scale models.
# PyTorch에서 백프로파게이션 이해하기
import torch
import torch.nn as nn
# 간단한 신경망 정의
class SimpleNetwork(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = nn.Linear(10, 20)
self.relu = nn.ReLU()
self.layer2 = nn.Linear(20, 1)
def forward(self, x):
x = self.layer1(x)
x = self.relu(x)
x = self.layer2(x)
return x
# 모델, 손실 함수, 옵티마이저 설정
model = SimpleNetwork()
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# 데이터 준비
x = torch.randn(32, 10) # 배치 크기 32, 특성 10개
y_true = torch.randn(32, 1)
# === Forward Pass ===
# 입력이 네트워크를 통과하며 예측값 생성
y_pred = model(x)
loss = criterion(y_pred, y_true)
print(f"Loss: {loss.item():.4f}")
# === Backward Pass (역전파) ===
# 손실로부터 각 파라미터의 기울기 계산
optimizer.zero_grad() # 기존 기울기 초기화 (필수!)
loss.backward() # 역전파 수행 - 모든 .grad 속성 업데이트
# 기울기 확인
print(f"layer1 weight gradient shape: {model.layer1.weight.grad.shape}")
print(f"layer1 weight gradient mean: {model.layer1.weight.grad.mean():.6f}")
# === 가중치 업데이트 ===
optimizer.step() # w = w - lr * gradient
# 수동으로 역전파 이해하기 (교육용)
def manual_backprop_demo():
"""
연쇄 법칙 시각화: dL/dw = dL/dy * dy/dz * dz/dw
"""
w = torch.tensor([2.0], requires_grad=True)
x = torch.tensor([3.0])
# Forward: z = w*x, y = z^2, L = y
z = w * x # z = 6
y = z ** 2 # y = 36
L = y # L = 36
# Backward (연쇄 법칙)
L.backward()
# dL/dw = dL/dy * dy/dz * dz/dw
# = 1 * 2z * x = 2 * 6 * 3 = 36
print(f"자동 기울기: {w.grad.item()}")
print(f"수동 계산: {2 * (w.item() * x.item()) * x.item()}")
manual_backprop_demo()
"The gradient becomes NaN during model training. It seems that gradient explosion occurred during backpropagation, so we should apply Gradient Clipping or lower the learning rate. I'll try setting max_grad_norm=1.0."
"Backpropagation uses the chain rule to compute the gradient of the loss function with respect to each parameter. In the forward pass, intermediate activation values are stored, and in the backward pass, they are used to propagate the gradients in the reverse direction. The autograd of deep learning frameworks automates this."
"With large models, memory runs short during backpropagation, but if you use Gradient Checkpointing, you can save a lot of memory by not storing intermediate activation values and recomputing them when needed. Computation increases by about 30%, but memory drops to half or less."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
In PyTorch, if you do not call zero_grad(), gradients accumulate. Unless you are intentionally using gradient accumulation, you must call it every iteration. If you omit this, training diverges.
In deep networks, gradients can converge to 0 (vanishing) or diverge to infinity (exploding). Without using the ReLU activation function, BatchNorm, and Residual Connection, training fails in networks with 50 or more layers.
Monitor the gradient distribution with TensorBoard, and apply Gradient Clipping (max_norm=1.0), appropriate weight initialization (He/Xavier), and residual connections (ResNet). A learning rate scheduler is also important for stable training.