# Quantum Natural Gradient Descent

**URL:** <https://discuss.pennylane.ai/t/quantum-natural-gradient-descent/351>\
**Category:** PennyLane Help\
**Created:** [March 2, 2020, 8:40pm UTC](https://discuss.pennylane.ai/t/quantum-natural-gradient-descent/351 "2020-03-02T20:40:44Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![josh](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/josh/32/100_2.png) [@josh](https://discuss.pennylane.ai/u/josh)\
**Post date:** [March 3, 2020, 12:44pm UTC](https://discuss.pennylane.ai/t/quantum-natural-gradient-descent/351/2 "2020-03-03T12:44:45Z")

</div>

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](https://pennylane.ai/qml/demos/tutorial_quantum_natural_gradient.html) 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](http://mcneela.github.io/machine_learning/2019/09/03/Writing-Your-Own-Optimizers-In-Pytorch.html) that implements the QNG update rule as above:

```python
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):

```python
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))

```

---

_[View the full topic](https://discuss.pennylane.ai/t/quantum-natural-gradient-descent/351)._
