PyTorch — nn.Module y capas
3.8.4kata 4 de 4

Sequential vs Custom Module Architecture

Cuándo usar Sequential y cuándo construir módulos custom

nn.Sequential es un contenedor que aplica módulos en secuencia: output de uno es input del siguiente. Es útil para redes lineales simples. Creas con nn.Sequential(layer1, layer2, ...) y itera automáticamente. El problema: sequential es inflexible. No puedes hacer skip connections, branching condicional, o lógica compleja.

Para cualquier flujo no-trivial (skip connections como en ResNet, branching multi-rama, residual connections, merging de paths), necesitas nn.Module custom. Define __init__() con todas las capas como self.name = nn.Layer(...), y forward(self, x) con lógica explícita. Es más verbose pero supremamente flexible.

Heurística: si forward() es 'capa1, luego capa2, luego capa3', usa Sequential. Si forward() tiene if/loops, múltiples inputs, skip connections, concatenations, o cualquier cosa no-lineal en el grafo, usa custom nn.Module.

structure.txt
# Sequential: linear pipeline
model = nn.Sequential(
    nn.Linear(256, 128),
    nn.ReLU(),
    nn.Linear(128, 64),
    nn.ReLU(),
    nn.Linear(64, 10)
)

# Custom: with skip connection
class ResidualNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(256, 256)
        self.fc2 = nn.Linear(256, 256)
    def forward(self, x):
        residual = x
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        x = x + residual  # skip connection
        return x

# Custom: with branching
class BranchingNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.branch1 = nn.Linear(64, 32)
        self.branch2 = nn.Linear(64, 32)
        self.merge = nn.Linear(64, 10)
    def forward(self, x):
        b1 = self.branch1(x)
        b2 = self.branch2(x)
        merged = torch.cat([b1, b2], dim=-1)  # concatenate
        return self.merge(merged)

Debugging lab

Detecta y corrige el error en el código.

0/1 tests passing0%
  1. 01

    # Skip connection: can Sequential do it? model = nn.Sequential( nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 256), # Can't add: output + input (skip)