Since this thread is still the first google hit when searching for “pytorch calculate gradient for input”, a small update:
Variables have been deprecated for a while now: https://pytorch.org/docs/stable/autograd.html#variable-deprecated 9
In order to calculate the gradient of the loss with respect to the input data (tensor), that is calculate dloss/ddata, simply do… (based on https://github.com/pytorch/examples/blob/master/mnist/main.py 50)
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        data.requires_grad = True  ### CRUCIAL LINE !!!
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward() # Calculates x.grad = dloss/dx for every x with x.requires_grad=True

–> Afterwards, you can easily access dloss/ddata via data.grad=dloss/ddata