Backward() function is not computing gradients!

Hi! i’m new in Pytorch and to the Pytorch community.
I just started working with RNN and already ran some examples. Now i’m trying to train a RNN based on This RNN tutorial but with my own data.
The inputs are time series with 12 features in each time step, with continuous values in the [0 ,1] range. The goal is to detect when a certain event occurs, so each time step has a target associated that can be 0 (no event) and 1 (event).

My problem is that loss.backard() is not working, the grads of every parameter of the model remains None and thus the model is not learning…

I’ve read a lot of discussions in the post, looked at a lot of examples but i can’t make it work and i can’t figure out what’s wrong…

My code:

class RNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(RNN, self).__init__()

        self.hidden_size = hidden_size

        self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
        self.i2o = nn.Linear(input_size + hidden_size, output_size)
        self.softmax = nn.LogSoftmax(dim=1)

    def forward(self, input, hidden):
        
        combined = torch.cat((input, hidden), 1)
        #print('input.size: {}, hidden.size {}, combined: {}'.format(input.size(), hidden.size(), combined.size()))

        hidden = self.i2h(combined)
        output = self.i2o(combined)
        output = self.softmax(output)
        return output, hidden

    def initHidden(self):
        return torch.zeros(1, self.hidden_size)


n_hidden = 128
rnn = RNN(12, n_hidden, 2)



learning_rate = 0.005 

criterion = nn.NLLLoss()


def train(label, sample):
    hidden = rnn.initHidden()

    for i in range(sample.size()[1]):
        rnn.zero_grad()
        curr_sample = sample[:,i].view(1,sample.size()[0])
        output, hidden = rnn(curr_sample, hidden)

        loss = criterion(output, label[i])
        loss.backward()

    # Add parameters' gradients to their values, multiplied by learning rate
        for p in rnn.parameters():
            p.data.add_(-learning_rate, p.grad.data)

    return output, loss.item()


n_iters = 1
print_every = 1
plot_every = 10

current_loss = 0
all_losses = []

for iter in range(1, n_iters + 1):
    output, loss = train(label, sample)
    print(' sale output {} y loss {}'.format(output.size(), loss))
    current_loss += loss

    # Print iter number, loss, name and guess
    if iter % print_every == 0:
        print('en iteracion {}, error acumulado es: {} y error actual {}'.format(iter, current_loss, loss))
        
    # Add current loss avg to list of losses
    if iter % plot_every == 0:
        all_losses.append(current_loss / plot_every)
        current_loss = 0

sample has size [12, 16588] and label has size [1, 16588]

The error i get is:

AttributeError: ‘NoneType’ object has no attribute ‘data’

because p.grad is none.

I’ve already tried out working with optimizers and performing optimizer.step() but i get the same result.

Thanks!!

You have two layers: i2h and i2o. In the first loop through, the loss only depends on i2o – the “hidden” output doesn’t affect the loss so it doesn’t get a gradient.

In general, you don’t want to call loss.backward() every time step of an RNN. You want to compute a few timesteps and the compute the loss across all the outputs

Thanks! I haven’t thought about the i2h and h2o thing.

In general, you don’t want to call loss.backward() every time step of an RNN. You want to compute a few timesteps and the compute the loss across all the outputs

I know that this implementation is not optimal, in fact i tried the same but with batches (and computing the loss at each mini batch), but i tried to keep it as simple as i could to see if the gradients changed (which have not).

I will try it again, implementing batches and see if it works.