ValueError: Cannot differentiate wrt parameter(s) {2}

Hi, I tried to write a classifier code with PennyLane and PyTorch, but I got this error.

import torch
import pennylane as qml
from pennylane import expval

dev = qml.device("default.qubit", wires=3)

@qml.qnode(dev, interface="torch")
def circuit(var1, var2, x): 
    
    qml.BasisState(x, wires=[0, 1, 2])
    qml.CRY(var2[0], wires = [2, 0])
    
    return expval(qml.PauliZ(0)), expval(qml.PauliZ(1)), expval(qml.PauliZ(2))


def cost(var1, var2, X, Y):
    res= (2.0-0)/(1-(-1))*(circuit(var1, var2, X)-1)+2
    loss = torch.nn.functional.binary_cross_entropy_with_logits(res, Y)
    return loss
  
    
var1 = torch.tensor([-1.0], requires_grad=True)
var2 = torch.tensor([1.0], requires_grad=True)

X    = torch.DoubleTensor([0, 1, 0])
    
Y    = torch.DoubleTensor([-1, -1, -1])
    
opt = torch.optim.Adam([var1, var2], lr=0.5)

for i in range(100):
    opt.zero_grad()
    loss = cost(var1, var2, X,  Y)
    loss.backward()
    opt.step()
    print("Cost:", loss.item())

Hi @EMY91,

It looks like you are trying to pass a (non-parameterized) initial state as a parameter to the circuit? Perhaps you could try passing this as a keyword argument (e.g., circuit(var1, var2, x=None)? By default, PennyLane will try to differentiate through regular arguments, and uses keyword arguments to pass non-differentiable arguments.

Nathan

1 Like