deep-learning · temario
3.8tema 8 de 17

PyTorch — nn.Module y capas

Módulos, Sequential, capas e inicialización

nn.Module es la clase base de toda arquitectura en PyTorch. Define dos métodos: __init__(self) donde declaras qué capas/módulos tienes, y forward(self, x) que describe cómo los datos fluyen. El framework maneja .backward() automáticamente. Piénsalo como un blueprint: __init__ lista los materiales, forward describe el ensamblaje. Un módulo puede contener submódulos (ej. un modelo que contiene Linear layers).

nn.Sequential es un contenedor que aplica módulos en secuencia: cada output es el input del siguiente. Es útil para redes simples y lineales. Para lógica compleja (branching, condicionales, skip connections), necesitas una clase nn.Module custom con forward() explícito. Sequential es syntactic sugar, pero tiene límites — úsalo cuando el flujo es realmente lineal.

Las capas comunes: nn.Linear (fully-connected, y = xW^T + b), nn.Conv2d/Conv1d (convolución), nn.RNN/LSTM/GRU (recurrentes), nn.Embedding (lookup table para índices), nn.Dropout, nn.BatchNorm1d/2d. Cada una es un nn.Module con parámetros aprendibles (excepto Dropout sin parameters). Componer estas capas en un módulo custom crea arquitecturas complejas.

La inicialización de pesos impacta convergencia. Por defecto, PyTorch inicializa Linear/Conv con valores uniformes distribuidos uniformemente. Para arquitecturas profundas, esto puede ser subóptimo. Xavier/Glorot initialization (mantiene varianza entre capas) es popular: nn.init.xavier_uniform_(tensor). Kaiming/He initialization es para ReLU: nn.init.kaiming_normal_(tensor, nonlinearity='relu'). Instancia manual en __init__: for layer in self.layers: nn.init....(layer.weight).

Los parámetros de un módulo se registran automáticamente cuando los asignas en __init__. model.parameters() itera sobre todos, model.state_dict() retorna un diccionario nombre→tensor. Esto es lo que guardas/cargas: torch.save(model.state_dict(), path), torch.load(path). Acceso a parámetros específicos: model.fc1.weight, model.fc1.bias. En __init__, asigna capas como self.fc1 = nn.Linear(...) — esto registra los parámetros automáticamente.

Las buenas prácticas: (1) mantén __init__ limpio, solo asigna capas, (2) toda lógica de red en forward(), (3) nombra capas descriptivamente (self.encoder, self.decoder), (4) inicializa weights después de crear capas si no es default, (5) siempre hereda de nn.Module, nunca crees arquitecturas ad-hoc con tensores sin registrar.

structure.txt
# NN.MODULE BASIC STRUCTURE
import torch
import torch.nn as nn
import torch.nn.init as init

# === CUSTOM MODULE ===
class SimpleNet(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super().__init__()  # call parent constructor
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.fc2 = nn.Linear(hidden_size, output_size)
        self.dropout = nn.Dropout(0.5)
        
        # Initialize weights (optional, defaults are OK)
        init.xavier_uniform_(self.fc1.weight)
        init.xavier_uniform_(self.fc2.weight)
    
    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = self.dropout(x)
        x = self.fc2(x)  # raw logits
        return x

# === SEQUENTIAL (LINEAR PIPELINE) ===
model_seq = nn.Sequential(
    nn.Linear(256, 128),
    nn.ReLU(),
    nn.Dropout(0.5),
    nn.Linear(128, 10)
)

# === ACCESSING PARAMETERS ===
model = SimpleNet(256, 128, 10)
print(model.fc1.weight.shape)  # (hidden_size, input_size)
print(model.fc1.bias.shape)    # (hidden_size,)

# List all parameters
for name, param in model.named_parameters():
    print(f'{name}: {param.shape}')

# Get state dict (for saving)
state = model.state_dict()
torch.save(state, 'model.pt')

# Load state dict
new_model = SimpleNet(256, 128, 10)
new_model.load_state_dict(torch.load('model.pt', weights_only=True))

# === COMMON LAYERS ===
linear = nn.Linear(10, 5)           # fully-connected
conv = nn.Conv2d(3, 64, kernel_size=3)  # 2D convolution
embedding = nn.Embedding(1000, 256) # token embedding lookup
lstm = nn.LSTM(256, 512, num_layers=2)

Katas (4)

Debugging lab

Detecta y corrige el error en el código.

0/8 tests passing0%
  1. 3.8.5.1

    # ERROR: creating network without nn.Module class BadNet: def __init__(self): self.fc1 = nn.Linear(256, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): return self.fc2(torch.relu(self.fc1(x))) net = BadNet() optimizer = torch.optim.Adam(net.parameters()) # ERROR: no .parameters()

  2. 3.8.5.2

    # Complex forward logic with Sequential (LIMITED) model = nn.Sequential( nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 10) ) # Can't do skip connections or branching

  3. 3.8.5.3

    # Saving entire model (not portable) torch.save(model, 'model.pt') # saves class definition too loaded_model = torch.load('model.pt') # breaks if class moved

  4. 3.8.5.4

    # Initialization with default values (may be suboptimal for deep nets) class DeepNet(nn.Module): def __init__(self): super().__init__() self.layers = nn.ModuleList([ nn.Linear(256, 256) for _ in range(10) # 10 layers, deep!

  5. 3.8.5.5

    # Parameter not registered because it's not assigned to self class BadNet(nn.Module): def __init__(self): super().__init__() fc1 = nn.Linear(256, 128) # not self.fc1 — NOT REGISTERED!

  6. 3.8.5.6

    # Accessing weights after forward net = SimpleNet(256, 128, 10) print(net.fc1.weight) # weight before forward pass

  7. 3.8.5.7

    # Batch normalization placement error model = nn.Sequential( nn.Linear(256, 128), nn.BatchNorm1d(128), nn.Linear(128, 10) # Missing BatchNorm after Linear

  8. 3.8.5.8

    # ModuleList vs nn.Sequential self.layers = [nn.Linear(256, 256) for _ in range(5)] # Wrong: list, not registered