ValueError: Cannot differentiate with respect to parameter

Hi, when I implement a quantum classifier using pennylane, it reported error: ValueError: Cannot differentiate with respect to parameter. This is the example code:

dev = qml.device('qiskit.aer', wires=6, shots=10)

def cost(param, feat, label, model):
    loss = []
    for m in range(len(feat)):
        predict = model(param, data=feat[m])
        loss.append((label[m] - predict)**2)
    return np.mean(np.array(loss))

# @qml.qnode(dev, interface='torch')
def circuit3(weights, data=None):
    qml.templates.AmplitudeEmbedding(features=data, wires=range(6), normalize=True)
    n_layers, n_qubits = weights.shape[0], weights.shape[1]
    for i in range(n_layers):
        for j in range(n_qubits):
            qml.Rot(weights[i, j, 0], weights[i, j, 1], weights[i, j, 2], wires=j)
    return qml.expval(qml.PauliZ(0))

weights = np.random.random([4, 6, 3])
data = np.random.random([2, 64], requires_grad=False)
label = np.array([1, -1], requires_grad=False)
qnode = qml.QNode(circuit3, dev)

optimizer = GradientDescentOptimizer(1e-2)
weights = optimizer.step(lambda v: cost(v, data, label, qnode), weights)

I notice that function AmplitudeEmbedding doesn’t support gradient calculation, does it cause the error? But I don’t need to calculate the gradient with respect to input feature. I am quite confused.

Any help and suggestions are welcome.
Thank you in advance!

Hey @Yang,

You are right to be suspicious, since you are setting the data to requires_grad=False, so PennyLane should not try to differentiate through it.

I tried to adjust your code example so I can run it, which meant adding import statements and deleting the CNOT_layer line. I tried with default.qubit and it runs fine.

Could you please turn your code snipet into a fully independent code example, which one can just copy-paste and run? Maybe you can also reduce it a lot - there is hardly ever a case where you couldn’t minimize a code example to a few lines, cutting out all the clutter. I’ll then try to have a look!

PS: And make sure you have the latest PennyLane version installed!

1 Like

Hi @Maria_Schuld,

Thank you for your suggestions. I just run this piece of code on another computer., and it works fine too. Maybe there is something wrong with the installation of pennylane 0.15.1 on this machine. I will try to uninstall and install it again.

Perfect, happy to hear that!