Hello, I have a similar problem here. And I don’t know how to solve it.
model = models.resnet50(pretrained=True)
num_in_features = model.fc.in_features
cls_num = 5
model.fc.out_features = cls_num

for param in model.parameters():
    param.requires_grad = False

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)

best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0

phase = 'train'
for epoch in range(30):
    print('Epoch {}/{}'.format(epoch+1, 30))
    print('-' * 10)

    # Each epoch has a training and validation phase
    for phase in ['train', 'valid']:
        if phase == 'train':
            model.train()  # Set model to training mode
        else:
            model.eval()   # Set model to evaluate mode

        running_loss = 0.0
        running_corrects = 0

        # Iterate over data.
        for inputs, labels in dataloaders[phase]:
            inputs = inputs.to(device)
            labels = labels.to(device)
            
            # zero the parameter gradients
            optimizer.zero_grad()

            # forward
            # track history if only in train
            with torch.set_grad_enabled(phase == 'train'):
                outputs = model(inputs)
                _, preds = torch.max(outputs, 1)
                loss = criterion(outputs, labels)

                # backward + optimize only if in training phase
                if phase == 'train':
                    #sched.step()
                    loss.backward()
                    optimizer.step()
                    ...

and it shows
RuntimeError                              Traceback (most recent call last)
<ipython-input-11-4b93aa6367ee> in <module>
      1 epochs = 40
      2 model.to(device)
----> 3 model = train_model(model, criterion, optimizer, epochs)

<ipython-input-10-608674d4de7a> in train_model(model, criterion, optimizer, num_epochs)
     37                     if phase == 'train':
     38                         #sched.step()
---> 39                         loss.backward()
     40                         optimizer.step()
     41 

D:\Anaconda\lib\site-packages\torch\tensor.py in backward(self, gradient, retain_graph, create_graph)
    105                 products. Defaults to ``False``.
    106         """
--> 107         torch.autograd.backward(self, gradient, retain_graph, create_graph)
    108 
    109     def register_hook(self, hook):

D:\Anaconda\lib\site-packages\torch\autograd\__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables)
     91     Variable._execution_engine.run_backward(
     92         tensors, grad_tensors, retain_graph, create_graph,
---> 93         allow_unreachable=True)  # allow_unreachable flag
     94 
     95 

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

many thanks