Skip Connections & Residual Networks
Conexiones de salto, identidad, profundidad
Una skip connection (también residual connection) añade la entrada de una capa directamente a su salida: output = f(x) + x. Esto permite que gradientes fluyan directamente a través de capas sin ser multiplicados tantas veces. En redes profundas (50+ capas), skip connections son CRÍTICAS para entrenar porque evitan vanishing gradients que de otra forma harían que capas tempranas no aprendan.
La idea clave: en lugar de aprender la función completa f(x), la red aprende el residuo (diferencia): f(x) = desired_output - x. Si la identidad ya es buena, el residuo puede ser pequeño, lo que facilita el aprendizaje. ResNet (Residual Network) popularizó esto y permitió redes de 152 capas donde previo era imposible entrenar más de ~20 sin vanishing gradients.
Las skip connections deben tener compatibilidad dimensional: si f(x) cambia la dimensión, necesitas una proyección: output = f(x) + W*x o output = f(x) + x (si dimensiones coinciden). En PyTorch, es simple: x = self.fc1(x); x = x + self.fc2(x) (si formas coinciden) o x = x + self.proj(x).
import torch
import torch.nn as nn
# Simple skip connection (identity)
class ResidualBlock(nn.Module):
def __init__(self, dim):
super().__init__()
self.fc1 = nn.Linear(dim, dim)
self.fc2 = nn.Linear(dim, dim)
def forward(self, x):
# Skip connection: output = f(x) + x
return x + self.fc2(torch.relu(self.fc1(x)))
# With dimension mismatch: use projection
class ResidualBlockProjection(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
self.fc1 = nn.Linear(in_dim, out_dim)
self.fc2 = nn.Linear(out_dim, out_dim)
self.proj = nn.Linear(in_dim, out_dim) # projection for skip
def forward(self, x):
# output = f(x) + proj(x)
return self.proj(x) + self.fc2(torch.relu(self.fc1(x)))
# Deep network using residual blocks
class DeepResNet(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, num_blocks=10):
super().__init__()
self.input_proj = nn.Linear(input_dim, hidden_dim)
self.blocks = nn.ModuleList([ResidualBlock(hidden_dim) for _ in range(num_blocks)])
self.output_proj = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
x = self.input_proj(x)
for block in self.blocks:
x = block(x) # skip connections prevent vanishing gradients
return self.output_proj(x)Debugging lab
Detecta y corrige el error en el código.
- 01
# Deep network without skip connections, difficult to train class DeepNet(nn.Module): def __init__(self): super().__init__() self.layers = nn.Sequential(*[nn.Linear(256, 256) for _ in range(20)]) def forward(self, x): return self.layers(x) # gradients vanish in deep networks
- 02
# Dimension mismatch in skip connection class BadResBlock(nn.Module): def forward(self, x): # x shape (batch, 256) x = self.fc1(x) # output shape (batch, 512) return x + x # ERROR: shape mismatch (512 vs 256)