PyTorch vs TensorFlow/Keras
3.17.3kata 3 de 4

Debugging & Developer Experience — Print, Breakpoints, Visibility

Inspección de tensores, logging, accesibilidad

Debugging en PyTorch es fácil: usa print() como Python normal, poner breakpoint() y Debugger ve el valor de cada tensor. Puedes inspeccionar shapes, valores, gradientes. TensorFlow hace debugging más difícil con graph compilation: print() no funciona, los breakpoints pueden ser confusos porque el grafo se ejecuta como unidad optimizada. Para TensorFlow, necesitas desactivar @tf.function o usar tf.print().

PyTorch es superior para aprender DL: puedes ver exactamente qué sucede en cada paso. TensorFlow abstrae más, es conveniente para producción pero menos educativo durante desarrollo.

structure.txt
# PyTorch debugging
import torch
import torch.nn as nn

class DebugModel(nn.Module):
    def forward(self, x):
        print(f'Input: {x.shape}')
        x = torch.relu(x)
        print(f'After ReLU: {x.shape}')
        # Breakpoint for inspection
        breakpoint()  # Debugger opens here
        return x

# Inspect gradients
x = torch.randn(4, 10, requires_grad=True)
y = model(x).sum()
y.backward()
print(f'Gradient shape: {x.grad.shape}')
print(f'Gradient values: {x.grad[:2, :2]}')

# TensorFlow debugging
import tensorflow as tf

# Option 1: remove @tf.function for eager execution
@tf.function is removed during debugging
def model_fn(x):
    print(f'Input: {x.shape}')  # Now prints
    x = tf.nn.relu(x)
    return x

# Option 2: use tf.print() in graph
@tf.function
def model_fn(x):
    tf.print(f'Input: {x.shape}')  # Works in graph
    x = tf.nn.relu(x)
    return x

Debugging lab

Detecta y corrige el error en el código.

0/2 tests passing0%
  1. 01

    # Debugging PyTorch: inspect intermediate values class Model(nn.Module): def forward(self, x): x = torch.relu(self.fc1(x)) x = torch.relu(self.fc2(x)) return self.fc3(x) # How to see values at each step?

  2. 02

    # TensorFlow graph debugging @tf.function def model_fn(x): print('Processing...') # Will this print?