Hi,
I was trying to use the quantum natural gradient (QNG) optimizer on a toy VQE problem where the ansatz employs user-defined gates ‘XX’ and ‘YY’ (defined below).
When trying to take an optimizer step, I got the following error: “ValueError: solve1: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (m,m),(m)->(m) (size 3 is different from 4)” coming from
np.linalg.solve(self.metric_tensor, grad_flat)
I didn’t encounter this error when using a circuit with Pennylane-defined gates. I think the error might be because I use the same parameter for both XX and YY gates but wasn’t sure how to fix this error.
This was my code:
from pennylane import numpy as np
import pennylane as qml
dev = qml.device("default.qubit", wires=2)
dev.operations.update({"XX", "YY"})
def circuit(params, wires=[0, 1]):
qml.PauliX(wires=wires[1])
qml.RZ(params[0], wires=wires[0])
qml.RZ(params[1], wires=wires[1])
XX(params[2], wires=wires)
YY(params[2], wires=wires)
coeffs = [1, 1]
obs = [qml.PauliX(0), qml.PauliZ(1)]
H = qml.Hamiltonian(coeffs, obs)
cost_fn = qml.ExpvalCost(circuit, H, dev)
init_params = np.random.uniform(size=3)
opt = qml.QNGOptimizer(stepsize=0.01, diag_approx=False)
params, prev_energy = opt.step_and_cost(cost_fn, init_params)
And the two user-defined gates are:
class XX(qml.operation.Operation):
num_params = 1
num_wires = 2
par_domain = "R"
grad_method = "A"
generator = [np.kron(X, X), -0.5]
@staticmethod
def _matrix(*params):
return np.cos(params[0]/2)*np.eye(4) + 1.j*np.sin(params[0]/2)*np.kron(X,X)
class YY(qml.operation.Operation):
num_params = 1
num_wires = 2
par_domain = "R"
grad_method = "A"
generator = [np.kron(Y, Y), -0.5]
@staticmethod
def _matrix(*params):
return np.cos(params[0]/2)*np.eye(4) + 1.j*np.sin(params[0]/2)*np.kron(Y,Y)