Redes recurrentes (RNN/LSTM/GRU)
3.11.2kata 2 de 4

LSTM Cells and Gate Mechanisms

Puertas forget/input/output y estado celular

LSTM mantiene dos estados: c_t (estado celular, memoria de largo plazo) y h_t (estado oculto, memoria de corto plazo). El estado celular c_t fluye a través de la secuencia casi sin cambios, permitiendo que los gradientes fluyan fuertemente sin atenuación exponencial. Las tres puertas controlan cómo se actualiza c_t: forget gate (qué información descartar), input gate (qué información nueva añadir), output gate (qué parte de c_t se expone como h_t).

Matemáticamente en cada paso: forget_gate = sigmoid(W_f * [h_{t-1}, x_t] + b_f), input_gate = sigmoid(W_i * [h_{t-1}, x_t] + b_i), candidate = tanh(W_c * [h_{t-1}, x_t] + b_c), output_gate = sigmoid(W_o * [h_{t-1}, x_t] + b_o). Luego: c_t = forget_gate * c_{t-1} + input_gate * candidate (suma ponderada), h_t = output_gate * tanh(c_t). Las puertas (sigmoid) retornan valores en [0, 1], actuando como multiplicadores diferenciables que controlan flujo de información.

La clave es que el gradiente para c_t recorre principalmente a través de la multiplicación '*' en la actualización, no exponencialmente. Esto contrasta con RNN vanilla donde el Jacobiano tanh < 1 causa vanishing. LSTM permite capturar dependencias de decenas o incluso cientos de pasos.

structure.txt
import torch
import torch.nn as nn

# LSTM cell manual (for understanding)
def lstm_cell_forward(x_t, h_prev, c_prev, W_f, W_i, W_c, W_o, b_f, b_i, b_c, b_o):
    # Concatenate input and previous hidden state
    combined = torch.cat([h_prev, x_t], dim=1)

    # Compute gates
    forget_gate = torch.sigmoid(combined @ W_f + b_f)
    input_gate = torch.sigmoid(combined @ W_i + b_i)
    candidate_cell = torch.tanh(combined @ W_c + b_c)
    output_gate = torch.sigmoid(combined @ W_o + b_o)

    # Update cell state and hidden state
    c_t = forget_gate * c_prev + input_gate * candidate_cell
    h_t = output_gate * torch.tanh(c_t)

    return h_t, c_t

# PyTorch LSTM module
lstm = nn.LSTM(input_size=10, hidden_size=32, batch_first=True)
x = torch.randn(4, 20, 10)  # batch=4, seq=20, input=10
h_0 = torch.zeros(1, 4, 32)  # initial hidden
c_0 = torch.zeros(1, 4, 32)  # initial cell

output, (h_n, c_n) = lstm(x, (h_0, c_0))
print(output.shape)  # (4, 20, 32) - hidden at each step
print(h_n.shape)     # (1, 4, 32) - final hidden
print(c_n.shape)     # (1, 4, 32) - final cell

Debugging lab

Detecta y corrige el error en el código.

0/2 tests passing0%
  1. 01

    # LSTM initialization lstm = nn.LSTM(input_size=10, hidden_size=32, batch_first=True) x = torch.randn(4, 20, 10) # If not providing h_0 and c_0, what is the default?

  2. 02

    # Forget gate interpretation # forget_gate = sigmoid(combined @ W_f + b_f) retorna valores en [0, 1] # If forget_gate[0] = [0.1, 0.5, 0.9, ...] # What does this mean?