Pytorch gradient accumulation implementation results in inplace operation error?

42 Views Asked by At

Does anyone know why I am getting this error?

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [84, 10]], which is output 0 of AsStridedBackward0, is at version 2524; expected version 2523 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!

My code is here. I am taking the pytorch train a classifier tutorial as the simplified example import torch import torchvision import torchvision.transforms as transforms transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

batch_size = 4

trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                        download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
                                          shuffle=True, num_workers=2)

testset = torchvision.datasets.CIFAR10(root='./data', train=False,
                                       download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
                                         shuffle=False, num_workers=2)

classes = ('plane', 'car', 'bird', 'cat',
           'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = torch.flatten(x, 1) # flatten all dimensions except batch
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


net = Net()



import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
inp = torch.empty(0, 10)
lab = torch.empty(0, dtype=torch.int64)

with torch.autograd.set_detect_anomaly(True):
    for epoch in range(2):  # loop over the dataset multiple times
        for i, data in enumerate(trainloader, 0):
            # get the inputs; data is a list of [inputs, labels]
            inputs, labels = data

            outputs = net(inputs)
            inp = torch.cat((inp, outputs), dim=0)
            lab = torch.cat((lab, labels), dim=0)
            if i % 101 == 100:
                # zero the parameter gradients
                optimizer.zero_grad()
                # forward + backward + optimize
                loss = criterion(inp, lab)
                loss.backward(retain_graph=True)
                optimizer.step()
                print(loss)


print('Finished Training')
2

There are 2 best solutions below

1
Karl On

You shouldn't be concatenating inputs/outputs together. To implement gradient accumulation, you call backward every iteration as usual, but stagger the optimizer step.

accum_iter = 4 # ie to accumulate 4 batches

for i, data in enumerate(trainloader):
    inputs, labels = data
    
    outputs = net(inputs)
    
    loss = criterion(outputs, labels)
    
    loss = loss / accum_iter # normalize loss for accumulation
    
    loss.backward()
    
    if ((i + 1) % accum_iter == 0) or (i + 1 == len(data_loader)):
        # optimizer step every `accum_iter` iterations
        optimizer.step()
        optimizer.zero_grad()
0
JobHunter69 On

Forgot to reset in the training loop:

inp = torch.empty(0, 10)
lab = torch.empty(0, dtype=torch.int64)