CUDA out of memory error during feature extraction

I’m trying to do some simple feature extraction using a pretrained ResNet50 on the CIFAR 100-20 dataset. It should be pretty straightforward, but after a certain number of batches the CUDA out of memory errors would appear. It seems very strange to me as something must have been accumulating across the batches and overwhelmed the GPU, but I could not locate the problem. Here’s a simple code snippet

import numpy as np

import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import ExponentialLR
import torchvision.datasets as datasets
from torchvision import transforms
from import TensorDataset, DataLoader, Dataset
from torchvision.models import resnet50

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = resnet50(pretrained=True)
model =

transform = transforms.Compose([transforms.ToTensor(),
                                transforms.Normalize((0.485, 0.456, 0.406),
                                                     (0.229, 0.224, 0.225))

trainset = datasets.CIFAR100(root='./', train=True,
                             download=True, transform=transform)
trainloader =, batch_size=8,

testset = datasets.CIFAR100(root='./', train=False,
                            download=True, transform=transform)
testloader =, batch_size=8,

train_f = []
train_l = []
for i,(im,label) in enumerate(testloader):
    im =
    im ='cpu')
train_f =
train_l ="features",train_f.detach().numpy())"labels",train_l.detach().numpy())

Any suggestions would be appreciated!

UPDATE: Even when I run the code above only on CPU, my laptop would kill the program after a certain number of batches.

You are storing the entire computation graph in each iteration in:


If you don’t want to backpropagate through the model outputs, .detach() them before appending to the list.

1 Like

It worked after I detach model(im), thanks so much!

Maybe a stupid question: so in normal batch optimization, how does PyTorch erase each batch’s computation graph after backprop? Is it in loss.backward() or optimization.zero_grad()?

In the backward() call PyTorch will release all intermediate tensors which are not referenced by other objects unless you explicitly use retain_graph=True.

1 Like