PyTorch — training loop
3.9.4kata 4 de 4

Device Management and Memory Optimization

GPU/CPU, memory handling y optimización para entrenamientos largos

Los dispositivos (CPU, CUDA GPU, MPS en Apple Silicon) deben ser consistentes: modelo y datos deben vivir en el mismo device. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') define automáticamente disponibilidad. model.to(device) mueve modelo, batch.to(device) mueve datos. Mismatch produce RuntimeError inmediato. En producción, almacena device en config para consistencia a través del código.

La memoria GPU es limitada. Para modelos grandes, técnicas como gradient accumulation acumulan gradientes sobre múltiples batches antes de actualizar, simulando un batch_size más grande sin allocar memoria extra. Otra técnica es gradient checkpointing: descarta activaciones intermedias durante forward y recalcula durante backward, reduc memoria a costa de más cálculo. mixed precision (FP16) reduce memoria en ~50% con pérdida mínima de precisión.

Para debugging de memoria, usa torch.cuda.memory_allocated() y torch.cuda.max_memory_allocated() para monitorear consumo. Si la memoria explota, reduce batch_size, usa gradient checkpointing, o reduce num_workers en DataLoader. Para entrenamientos de larga duración (>1 día), implementa periodic checkpointing y validación para evitar pérdida de progreso.

structure.txt
import torch
import torch.cuda as cuda

# Device setup
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'Device: {device}')
if torch.cuda.is_available():
    print(f'GPU Name: {torch.cuda.get_device_name()}')
    print(f'Memory Available: {torch.cuda.get_device_properties(0).total_memory / 1e9:.2f} GB')

model = MyModel().to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

# Memory monitoring
def print_gpu_memory():
    allocated = torch.cuda.memory_allocated() / 1e9
    cached = torch.cuda.memory_reserved() / 1e9
    print(f'Allocated: {allocated:.2f} GB, Cached: {cached:.2f} GB')

# Gradient accumulation for large batch simulation
accumulation_steps = 4
optimizer.zero_grad()
for i, (batch_x, batch_y) in enumerate(train_loader):
    batch_x, batch_y = batch_x.to(device), batch_y.to(device)
    logits = model(batch_x)
    loss = criterion(logits, batch_y) / accumulation_steps
    loss.backward()

    if (i + 1) % accumulation_steps == 0:
        optimizer.step()
        optimizer.zero_grad()

# Gradient checkpointing (save memory)
from torch.utils.checkpoint import checkpoint
def forward_with_checkpoint(model, x):
    return checkpoint(model, x, use_reentrant=False)

# Mixed precision training (FP16)
from torch.amp import autocast
scaler = torch.cuda.amp.GradScaler()

with autocast(device_type='cuda', dtype=torch.float16):
    logits = model(batch_x)
    loss = criterion(logits, batch_y)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()

Debugging lab

Detecta y corrige el error en el código.

0/2 tests passing0%
  1. 01

    # Memory issue: model on GPU, batch on CPU model = MyModel().to('cuda') for batch_x, batch_y in train_loader: logits = model(batch_x) # RuntimeError: mat1 and mat2 on different devices

  2. 02

    # Out of memory during training # batch_size = 256 on GPU with 8GB memory # Solution?