Hi @James_Ellis! Let me go through your two questions one by one.
Is applying quantum natural gradient descent something you could do to a hybrid neural network?
Yes definitely! The natural gradient descent optimizer that comes with PennyLane performs the following update step:
\theta_{t+1} = \theta_t - \eta g^{+}(\theta_t)\nabla \mathcal{L}(\theta)
where g^{+}(\theta_t) is the pseudo-inverse of the metric tensor at the current value of the quantum parameters.
In PennyLane currently, this works if your cost function is a single QNode. The metric tensor is available via the qnode.metric_tensor(params) method, and the QNGOptimizer uses this to apply the update step when using the autograd/numpy interface. You can check out quantum natural gradient tutorial for more details on inner-workings.
Note that the built-in optimizer currently will only accept cost functions which consist of a single QNode. This optimization process however should continue to work for models consisting of multiple QNodes, as long as:
- Each parameter in the model is used in a single QNode,
- The parameter update step for each parameter uses the corresponding metric tensor (i.e., if parameters x[4] to x[6] are used in QNode b, than the metric tensor for QNode b must be used when updating these parameters),
- If classical processing is performed on the QNode outputs, this must be taken into account via the chain rule.
If so, how would this be applied in pytorch?
This can be done by simply defining a PyTorch custom optimizer that implements the QNG update rule as above:
class QNGOptimizer(torch.optim.Optimizer):
def __init__(self, params, lr=0.01, diag_approx=False, lam=0):
defaults = dict(lr=0.01, diag_approx=False, lam=0)
super().__init__(params, defaults)
def step(self, closure=None):
loss = None
if closure is not None:
loss, metric_tensor = closure()
for group in self.param_groups:
for p in group["params"]:
if p.grad is None:
continue
grad = p.grad.data
state = self.state[p]
# State initialization
if len(state) == 0:
state["step"] = 0
g = metric_tensor([p.data.numpy()], diag_approx=group["diag_approx"])
g += group["lam"] * np.identity(g.shape[0])
state["step"] += 1
d_p = torch.tensor(-group['lr'] * np.linalg.solve(g, grad))
p.data.add_(d_p)
return loss
This can then be used as any other PyTorch optimizer, however in this case, the closure function should also return the metric tensor function (not just the loss):
import torch
from torch.autograd import Variable
import pennylane as qml
import numpy as np
dev = qml.device("default.qubit", wires=3)
@qml.qnode(dev, interface="torch")
def circuit(params):
# |psi_0>: state preparation
qml.RY(np.pi / 4, wires=0)
qml.RY(np.pi / 3, wires=1)
qml.RY(np.pi / 7, wires=2)
# V0(theta0, theta1): Parametrized layer 0
qml.RZ(params[0], wires=0)
qml.RZ(params[1], wires=1)
# W1: non-parametrized gates
qml.CNOT(wires=[0, 1])
qml.CNOT(wires=[1, 2])
# V_1(theta2, theta3): Parametrized layer 1
qml.RY(params[2], wires=1)
qml.RX(params[3], wires=2)
# W2: non-parametrized gates
qml.CNOT(wires=[0, 1])
qml.CNOT(wires=[1, 2])
return qml.expval(qml.PauliY(0))
steps = 200
init_params = Variable(torch.tensor([0.432, -0.123, 0.543, 0.233]), requires_grad=True)
opt = QNGOptimizer([init_params], lr=0.01)
def closure():
opt.zero_grad()
loss = circuit(init_params)
loss.backward()
return loss, circuit.metric_tensor
for i in range(steps):
opt.step(closure)
p_final = opt.param_groups[0]['params'][0]
print("Final parameters:", p_final)
print("Final circuit value:", circuit(p_final))