What are conditions that cause AttributeError: no attribute 'requires_grad'

I was getting this error AttributeError: ‘int’ object has no attribute ‘requires_grad’ even hit and trialed i’m not getting over it. I want to know the ground truth , of how does this error occur?

What are the list of undesirable conditions that this type of error happens?

Thank you for your kind help :slight_smile: :heart:

Well that error is kind of self explanatory, the code you are running is dealing with a python integer, followed by some pytorch operation on it, which needs its .requires_grad attribute.
Since python integer don’t have this attribute it’s showing you that attribution error.

Could you provide some code? So that we can provide you with actual solutions.

oh . Thanks. I was not able to debug it where the error is.
Please check my code. :slight_smile:

def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):
    valid_loss_min = np.Inf 
    for epoch in range(1, n_epochs+1):
        train_loss = 0.0
        valid_loss = 0.0
        for batch_idx, (data, target) in enumerate(loaders['train']):
            output = model(data.unsqueeze_(0) )
            loss = criterion(output ,target)
            train_loss = train_loss + (1/(batch_idx+1)) + (loss.data - train_loss)
        for batch_idx, (data, target) in enumerate(loaders['valid']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## update the average validation loss
            output = model(data.unsqueeze_(0) )
            loss = criterion(output, target)
            valid_loss = valid_loss + (1/(batch_idx+1)) + (loss.data - valid_loss)
    return model

Which line is showing that error

having error in
loss = criterion(output, target) which does not runs.

but loss previously made is not an integer
here is my criterion

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model_scratch.parameters())

Oh problem was solved. What i was doing was

After loading data from Imagefolder as
train_data = datasets.ImageFolder('images/train')

and directly passing through the for loop enumerate

for batch, (data, target) in enumerate(train_data):
            output  = model(data, target)

And find out that target type was int

So in order to enumerate it I had to use DataLoader then use it in for loop .
train_loader = torch.utils.data.DataLoader(train_data, shuffle=True)

Thanks for helping anyway. :slight_smile: