deep-learning · temario
3.17tema 17 de 17

PyTorch vs TensorFlow/Keras

Comparación y cuándo usar cada uno

PyTorch y TensorFlow/Keras son los dos frameworks más populares para deep learning en 2025. PyTorch fue desarrollado por Meta y es el favorito de researchers; TensorFlow por Google está orientado a producción y servicio a escala. La diferencia histórica más importante fue eager vs graph execution: PyTorch siempre fue eager (dynamic graphs, ejecuta código Python normalmente), TensorFlow comenzó con graph estático (def compute_graph, luego execute) pero desde TF 2.0 (2019) también soporta eager execution. Hoy ambos soportan eager, pero el ecosistema y filosofía siguen siendo distintos.

PyTorch tiene un model.forward() que es simplemente una función Python. Puedes usar debuggers normales, print statements, condicionales (if/for normales). La curva de aprendizaje es menor porque escribes Python sin barreras conceptuales. El código se siente 'natural'. Esto lo hace ideal para research (experimentación rápida, prototipado) y es por eso que PyTorch domina papers ICCV/ICML/NeurIPS. TensorFlow/Keras abstraen más; models se definen declarativamente, lo que es elegante pero menos flexible. TF luego ejecuta el grafo con optimizaciones de backend, lo que permite servir en edge devices y mobile más fácilmente.

PyTorch tiene un echo-system robusto: PyTorch Lightning (wrapper con best practices), torchvision (visión), torchtext (NLP), PyTorch Geometric (grafos). La instalación es simple y el debugging es directo. TensorFlow/Keras es single-package (todo incluido), con buena documentación oficial y soporte de Google. El trade-off: PyTorch es menos 'opinionated' (libertad, pero requiere disciplina), TensorFlow/Keras guía más pero es menos flexible.

Diferencias clave en código: PyTorch escribe loops de entrenamiento manuales (más control, más código), TensorFlow.Keras usa model.fit() (menos código, menos control). PyTorch requiere torch.no_grad() en evaluación, TensorFlow lo hace automático. Ecosistema: transformers de Hugging Face es agnóstico (soporta ambos) pero PyTorch-first. Modelos pre-entrenados (ResNet, BERT, GPT): en PyTorch vía torchvision/transformers; en TF vía keras.applications/transformers. Ambos acceden a Hugging Face Hub.

Producción: TensorFlow tiene TFServing (servir modelos escalable), TFLite (mobile/edge), TFX (MLOps), integración con Google Cloud. PyTorch tiene TorchServe (servir), pero la historia de mobile es más joven (TorchMobile existe pero es menos maduro). Entrenamiento distribuido: TensorFlow.distribute.Strategy es más automático; PyTorch requiere torch.distributed o frameworks como PyTorch Lightning. Para equipos enfocados en modelo único + servicio escalable, TF. Para research + prototipado rápido, PyTorch.

En la práctica (2025): si trabajas en un lab de research, academia o startup, elige PyTorch. Si trabajas en Google o necesitas producción enterprise con mobile, TensorFlow. Si necesitas máxima flexibilidad y debugging fácil, PyTorch. Si prefieres 'batteries included' con convenciones fuertes, Keras. Para aprender DL conceptualmente, ambos funcionan; PyTorch permite ver qué está pasando más fácilmente. Los errores comunes: asumir que TF es siempre más rápido (no, depende), que Keras es más simple (sí, pero menos flexible), o que PyTorch es lento en producción (no, con optimizaciones como TorchScript es comparable).

structure.txt
# PyTorch: Eager Execution, Manual Training Loop

import torch
import torch.nn as nn
import torch.optim as optim

class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(10, 64)
        self.fc2 = nn.Linear(64, 1)

    def forward(self, x):  # Regular Python function
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = SimpleModel()
optimizer = optim.Adam(model.parameters(), lr=1e-3)
criterion = nn.MSELoss()

# Training loop (manual, explicit control)
for epoch in range(10):
    model.train()  # Set to training mode
    for x, y in train_loader:
        output = model(x)  # Forward pass
        loss = criterion(output, y)
        optimizer.zero_grad()  # Clear gradients
        loss.backward()  # Backward pass (compute gradients)
        optimizer.step()  # Update weights

    # Evaluation (no gradients needed)
    model.eval()  # Set to eval mode
    with torch.no_grad():  # Disable gradient computation
        val_loss = 0
        for x, y in val_loader:
            output = model(x)
            val_loss += criterion(output, y).item()

# === TensorFlow/Keras: High-Level API, model.fit() ===

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    layers.Dense(64, activation='relu', input_shape=(10,)),
    layers.Dense(1)
])

model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=1e-3),
    loss=keras.losses.MeanSquaredError()
)

# Training (one-liner)
model.fit(
    x=x_train, y=y_train,
    batch_size=32,
    epochs=10,
    validation_data=(x_val, y_val)
)

# Evaluation
model.evaluate(x_test, y_test)

# Prediction (no .eval() needed, TF handles it)
predictions = model.predict(x_test)

# === Custom Training Loop in TensorFlow (if needed) ===

@tf.function  # Graph compilation (optional optimization)
def train_step(x, y):
    with tf.GradientTape() as tape:  # Record operations
        logits = model(x, training=True)  # Forward pass
        loss_value = loss_fn(y, logits)
    grads = tape.gradient(loss_value, model.trainable_weights)
    optimizer.apply_gradients(zip(grads, model.trainable_weights))
    return loss_value

for epoch in range(10):
    for x, y in train_loader:
        train_step(x, y)

Katas (4)

Debugging lab

Detecta y corrige el error en el código.

0/6 tests passing0%
  1. 3.17.5.1

    # PyTorch training without eval mode model = MyModel() for epoch in range(10): for x, y in train_loader: output = model(x) loss = criterion(output, y) loss.backward() optimizer.step() optimizer.zero_grad() # Validation WITHOUT model.eval() for x, y in val_loader: output = model(x) val_loss += criterion(output, y).item()

  2. 3.17.5.2

    # TensorFlow/Keras: are model.fit() layers frozen correctly? model = keras.Sequential([...]) # Load pre-trained model for layer in model.layers[:-1]: layer.trainable = False # Freeze all but last layer model.compile(optimizer='adam', loss='mse') model.fit(x_train, y_train, epochs=10)

  3. 3.17.5.3

    # PyTorch vs TensorFlow: distributed training # PyTorch: how do you do distributed training?

  4. 3.17.5.4

    # Custom training loop: PyTorch vs TensorFlow # PyTorch version for x, y in train_loader: output = model(x) loss = criterion(output, y) loss.backward() optimizer.step() optimizer.zero_grad() # What is the TensorFlow equivalent?

  5. 3.17.5.5

    # Transfer learning: freeze backbone, train only head # PyTorch: for param in model.backbone.parameters(): param.requires_grad = False # Freeze for param in model.head.parameters(): param.requires_grad = True # Train # TensorFlow equivalent?

  6. 3.17.5.6

    # Debugging: where is the bug? # TensorFlow graph execution (can't print inside model) @tf.function # Graph compilation def model_fn(x): x = tf.keras.layers.Dense(64, activation='relu')(x) print(x) # This won't print during execution!