Residual Connection
Residual Connection / Skip Connection
A skip connection that adds the input to the output. Stabilizes training of deep networks. A core structure of ResNet and Transformers.
Residual Connection / Skip Connection
A skip connection that adds the input to the output. Stabilizes training of deep networks. A core structure of ResNet and Transformers.
A Residual Connection is a structure in a neural network that adds the input directly to the transformed output. Expressed as a formula, output = F(x) + x, meaning the layer outputs the sum of the original input (x) and the learned transformation (F(x)). This makes training easier because the network only has to learn "what needs to be learned."
It was first introduced in the ResNet paper published in 2015 by Kaiming He of Microsoft Research. By solving the "degradation problem" that occurred in deep networks (50 layers or more) at the time, a 152-layer ResNet surpassed human-level performance for the first time in the ImageNet competition.
The core principle is the gradient highway. During backpropagation, gradients can flow directly through the addition operation, which alleviates the vanishing gradient problem. Even networks deeper than 100 layers can be trained stably. In addition, because the identity mapping is the default, the input is passed through unchanged even in the worst case.
It is used in almost all modern deep learning architectures. Both the Multi-Head Attention and Feed-Forward blocks of the Transformer use residual connections, and they are an essential part of most recent models such as Vision Transformer (ViT), BERT, and GPT.
import torch
import torch.nn as nn
class ResidualBlock(nn.Module):
"""기본 Residual Block (ResNet 스타일)"""
def __init__(self, channels: int):
super().__init__()
self.conv1 = nn.Conv2d(channels, channels, 3, padding=1)
self.bn1 = nn.BatchNorm2d(channels)
self.conv2 = nn.Conv2d(channels, channels, 3, padding=1)
self.bn2 = nn.BatchNorm2d(channels)
self.relu = nn.ReLU(inplace=True)
def forward(self, x: torch.Tensor) -> torch.Tensor:
identity = x # 원본 입력 저장
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out += identity # 잔차 연결: F(x) + x
out = self.relu(out)
return out
class TransformerResidual(nn.Module):
"""Transformer 스타일 Residual + LayerNorm"""
def __init__(self, d_model: int, dropout: float = 0.1):
super().__init__()
self.norm = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x: torch.Tensor, sublayer_output: torch.Tensor) -> torch.Tensor:
# Pre-LayerNorm 방식 (GPT 스타일)
return x + self.dropout(sublayer_output)
# 사용 예시
block = ResidualBlock(64)
x = torch.randn(1, 64, 32, 32)
output = block(x)
print(f"입력: {x.shape}, 출력: {output.shape}") # 동일한 shape
"To stack layers deeper, a Residual Connection is essential. Beyond 20 layers, without residual connections the model won't train, or performance actually drops. As in Transformer blocks, the Pre-LN + Residual combination is stable."
"A Residual Connection lets gradients flow directly through the skip path, which solves the vanishing gradient problem. It was first introduced in ResNet and is now used in every block of the Transformer. Since the form is output = F(x) + x and the identity mapping is the default, there is no loss even in the worst case."
"The loss isn't converging — could the residual connection be missing? Without a residual in a deep network, gradients don't propagate properly to the later layers. Check the += identity part in the code."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
If the input and output shapes differ, direct addition is impossible. You must match the dimensions using a projection layer (1x1 conv or Linear).
Pre-LN (normalization before the residual) and Post-LN (normalization after the residual) differ greatly in training stability. GPT uses Pre-LN, while the original Transformer uses Post-LN.
When dimensions change, project with a 1x1 Conv or Linear layer, and for deep networks the Pre-LN approach is more stable for training.