Eager vs Graph Execution — Dynamic Graphs
Ejecución dinámica, debugging y traza de operaciones
Eager execution significa que el código se ejecuta línea por línea, como Python normal. PyTorch siempre fue eager: llamas model(x) y obtienes resultados inmediatamente. Puedes usar print(), debuggers, condicionales if/for normales. TensorFlow comenzó con graph execution: defines un grafo de cálculo declarativamente, luego lo ejecutas como unidad. Desde TF 2.0 (2019), ambos soportan eager, pero la filosofía sigue siendo diferente.
Ventaja de eager: debugging es directo. Puedes poner un breakpoint en el forward pass, inspeccionar tensores, usar print() normalmente. El código es Python natural. Desventaja: no hay oportunidad para optimización global (el grafo no existe como entidad). Ventaja de graph execution (TensorFlow clásico): el framework ve todo el cálculo y puede optimizar (fusionar operaciones, compilar para GPU/TPU). Desventaja: debugging es difícil (código no se ejecuta línea por línea, está compilado en la gráfica).
En la práctica (2025): PyTorch es eager, punto. TensorFlow soporta eager pero @tf.function compila selectively a graph para optimización. Para la mayoría, eager (PyTorch) es más simple de aprender y debuggear.
# PyTorch: Eager execution
import torch
import torch.nn as nn
class Model(nn.Module):
def forward(self, x):
print(x.shape) # This prints immediately
x = torch.relu(x)
return x
model = Model()
x = torch.randn(4, 10)
y = model(x) # Executes immediately, prints executed
# Can use breakpoint()
class ModelDebug(nn.Module):
def forward(self, x):
if x.shape[0] > 2:
breakpoint() # Actually breaks here
return x
# TensorFlow: @tf.function compiles to graph (optional)
import tensorflow as tf
class TFModel(tf.Module):
@tf.function
def __call__(self, x):
print(x.shape) # This DOES NOT print (graph compiled)
x = tf.nn.relu(x)
return x
model = TFModel()
x = tf.random.normal([4, 10])
y = model(x) # No print output (executed as graph)
# To enable eager for debugging:
tf.config.run_functions_eagerly(True)
y = model(x) # Now printsDebugging lab
Detecta y corrige el error en el código.
- 01
# PyTorch: eager execution with print class Model(nn.Module): def forward(self, x): print(f'Input shape: {x.shape}') x = torch.relu(x) return x model = Model() x = torch.randn(2, 5) y = model(x) # Does it print?
- 02
# TensorFlow: graph compilation prevents print @tf.function def model_fn(x): print(f'Input shape: {x.shape}') # Will this print?
- 03
# Debugging conditionals # PyTorch class Model(nn.Module): def forward(self, x): if x.shape[0] > 2: x = x * 2 # Conditional execution return x