Help with VQE cost function

Hello, everyone! I am starting a VQE project in Pennylane and I have encountered a problem with the cost function. I defined my parameterized circuit as:

L = 4
N = 2

def circuit(params, wires):
pl.BasisState(pl.qchem.hf_state(N,2*L), wires=wires)
for i in range(0,2*L,4):
    pl.DoubleExcitation(params[int(i/4)], wires=[i,i+1,i+2,i+3])

such that in this case the length of params is 2. But after defining cost_fn:

dev = pl.device("default.qubit",wires=2*L)
cost_fn = pl.ExpvalCost(circuit, hamiltonian, dev)

I cannot call cost_fn as:


as I get an error regarding array shapes:

ValueError: shapes (2,) and (256,) not aligned: 2 (dim 0) != 256 (dim 0)

What did I do wrong? The hamiltonian is a bit long so I will just paste the output from the notebook:

<Hamiltonian: terms=61, wires=[0, 1, 2, 3, 4, 5, 6, 7]>

Hi @Dinu_Danut-Valentin,

Welcome to the PennyLane community! I saw your question at the end of my work day, but I’ll take a look tomorrow and get back to you since I’m not 100% what the problem is from a quick look.


Juan Miguel

Hi @Dinu_Danut-Valentin,

I’m not sure what the problem is in your case, but it could be in how the Hamiltonian is defined. Alternatively, the way you pasted the definition of the circuit is missing an indentation. This could be something to check in your code.

To test your code, I created my own Hamiltonian on 8 qubits and run the same code as you without any issues. More concretely, the following script works well for me:

import pennylane as qml
import numpy as np

L = 4
N = 2

def circuit(params, wires):
    qml.BasisState(pl.qchem.hf_state(N,2*L), wires=wires)
    for i in range(0,2*L,4):
        qml.DoubleExcitation(params[int(i/4)], wires=[i,i+1,i+2,i+3])


circuit([0,0], range(8))

symbols = ["H", "H"]
coordinates = np.array([0.0, 0.0, -0.6614, 0.0, 0.0, 0.6614])

H, qubits = qml.qchem.molecular_hamiltonian(symbols, coordinates, basis='6-31g')

dev = qml.device("default.qubit",wires=2*L)
cost_fn = qml.ExpvalCost(circuit, H, dev)

print(cost_fn([0, 0]))

My advice is:
1. check that your circuit is properly indented
2. check that your Hamiltonian is properly defined

If the problem persists, then it will be useful for me to see how you’re building the Hamiltonian.

Let me know!

Juan Miguel