How to use lightning.gpu to solve parameter optimization problems

I recently did an experiment on quantum machine learning, but I wanted to use GPU to accelerate the parameter optimization problem of quantum machine learning, so I used lightning.gpu, but reported the following errors:

ValueError: Computing the gradient of circuits that return the state with the parameter-shift rule gradient transform is not supported, as it is a hardware-compatible method.

So I’d like to ask a few questions here:
(1) lightning.gpu does not support solving the problem of using the optimizer for gradient descent to optimize parameters
(2) How to use ansatz built on pennylane platform and combined with gpu to use gradient descent method for quantum machine learning? Can you give me an example, thank you,lol

Hey @sun! Welcome to the forum :sunglasses:

This error message doesn’t have anything to do with PennyLane lightning actually :slight_smile:. The same error happens with default.qubit:

import pennylane as qml
from pennylane import numpy as np

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

@qml.qnode(dev, diff_method="parameter-shift")
def circuit(params):
    qml.RX(params[0], wires=0)
    qml.RY(params[1], wires=0)
    return qml.state()

params = np.array([0.1, 0.2], requires_grad=True)
qml.jacobian(circuit)(params)
ValueError: Computing the gradient of circuits that return the state with the parameter-shift rule gradient transform is not supported, as it is a hardware-compatible method.

The incompatibility here is due to the fact that the parameter-shift rule is intrinsically hardware compatible; it relies on the measurement being something that a real quantum computer can churn out, and the full quantum state is not one of those things :slight_smile:. Check out this page for more info: qml.gradients.param_shift — PennyLane 0.32.0 documentation

If you return, say, an expectation value, then using the parameter-shift rule is all fine and dandy!

import pennylane as qml
from pennylane import numpy as np

dev = qml.device("lightning.qubit", wires=2)
@qml.qnode(dev, diff_method="parameter-shift")
def circuit(params):
    qml.RX(params[0], wires=0)
    qml.RY(params[1], wires=0)
    qml.RX(params[2], wires=0)
    return qml.expval(qml.PauliZ(0))
    
params = np.array([0.1, 0.2, 0.3], requires_grad=True)
qml.jacobian(circuit)(params)
array([-0.3875172 , -0.18884787, -0.38355704])

Let me know if this helps :slight_smile:

I really appreciate your reply. I’ll look into it

1 Like

My pleasure! Let me know if you have any more questions :slight_smile: