Derivative of statevector

Hi, can someone please tell me if there is an in-build strategy in pennylane to calculate the derivative of a quantum state (not any expectation value) obtained from a parametrized quantum circuit or do I need to tackle this issue manually?

Hi @Arun, you could try something like the following:

dev = qml.device('default.qubit', wires=2)

@qml.qnode(dev, diff_method="backprop")
def test(x):
    qml.RY(x, wires=[0])
    return qml.state()

def cost(x):
    return np.abs(test(x)[0])

x = np.array(0.1, requires_grad=True)


Here we create a qnode that returns the state and then we can build a cost function from that state.

The crucial thing here is that differentiating the state is only supported using the ‘backprop’ differentiation method on a compatible device.

You can learn more in the docs entry for qml.state.

Let me know if this answers your question and feel free to ask any other questions you may have.

Thanks, @CatalinaAlbornoz for your response. However, a more proper example would be

dev = qml.device(‘default.qubit’, wires=2)

@qml.qnode(dev, diff_method=“backprop”)
def test(x):
qml.RY(x[0], wires=[0])
qml.RY(x[1], wires=[1])
return qml.state()

def cost(x):
return np.abs(test(x))

x = np.random.rand(2, requires_grad=True)

qml.grad(cost, argnum=0)(x)

However, it shows error every time. Let me know if there is a solution to that problem!

Hi @Arun, the issue here is that your cost function has a size larger than 1. If you change the return in your cost function to something like np.abs(np.sum(test(x))) or np.abs(test(x)[0]) then it will work.

Let me know if this helps!