Variational Quantum Eigensolver (VQE) is a hybrid algorithm: a quantum circuit estimates an energy, while a classical optimizer adjusts the circuit parameters. This tutorial shows how to implement a small VQE in Python, choose a Hamiltonian and ansatz, estimate measurement cost, validate the result, and diagnose common failures in simulators or on noisy hardware.
Overview
VQE is commonly introduced for quantum chemistry, but the workflow applies to any problem that can be expressed as minimizing the expectation value of a Hamiltonian. The objective is:
E(θ) = ⟨ψ(θ)|H|ψ(θ)⟩
Here, H is a weighted sum of Pauli operators, |ψ(θ)⟩ is the state prepared by a parameterized circuit, and θ is the vector of trainable parameters. For each optimizer step, the program prepares the circuit, measures the Hamiltonian terms, combines their expectation values, and returns an energy estimate.
The algorithm has five moving parts:
- Hamiltonian: the operator whose lowest eigenvalue you want to estimate.
- Ansatz: a parameterized circuit that defines the states the optimizer can explore.
- Measurement strategy: the number of shots and the way commuting terms are grouped.
- Classical optimizer: the method that proposes new parameter values.
- Validation: checks that distinguish a genuine improvement from sampling noise or an implementation error.
VQE does not guarantee that an optimizer will find the ground state. The result depends on the Hamiltonian encoding, initial parameters, ansatz expressiveness, optimizer settings, and measurement noise. Treat the first implementation as an experiment with explicit assumptions rather than as a black-box solver.
How to estimate
A useful first estimate is the number of circuit executions required for one optimization run. Suppose the Hamiltonian contains T measured terms, the optimizer performs I iterations, each iteration evaluates the objective F times, and each term uses S shots. A simple upper-bound estimate is:
Estimated shots = T × I × F × S
This estimate assumes that every term is measured separately and that every objective evaluation uses the same shot count. It is deliberately conservative. If terms that commute are measured in the same basis, the number of circuit executions can be closer to the number of measurement groups rather than the number of terms. Conversely, gradient evaluations, optimizer line searches, retries, calibration overhead, and validation runs can increase the total.
For example, consider a Hamiltonian with six Pauli terms, 80 optimizer iterations, two objective evaluations per iteration, and 1,000 shots per term:
6 × 80 × 2 × 1,000 = 960,000 term shots
If the six terms can be organized into three compatible measurement groups, the circuit-execution estimate may be closer to 480,000 shots under the same assumptions. The exact reduction depends on the SDK, grouping implementation, basis-rotation circuits, and backend behavior.
Use this calculation before moving to hardware. It helps you compare ansätze and optimizers on equal terms. A deeper ansatz may reduce the number of iterations but increase circuit depth and parameter count. A lower shot count may reduce runtime while making the objective noisier. There is no universally best setting; the right trade-off depends on whether your priority is debugging, accuracy, or hardware feasibility.
Inputs and assumptions
Construct the Hamiltonian
Start with a small, known operator before attempting a molecular Hamiltonian. For example:
H = 0.5 I - 0.2 Z + 0.3 X
This is not a chemistry model; it is a compact test case that lets you verify the VQE loop. In a chemistry workflow, a classical preprocessing step usually maps a molecular problem to qubits and produces coefficients for Pauli strings. Keep that mapping separate from the optimizer so you can test each stage independently.
Select an ansatz
For a one-qubit example, a general rotation is enough. For multiple qubits, begin with a shallow hardware-efficient circuit: single-qubit rotations followed by entangling gates. Increase depth only after you have confirmed that the shallow circuit cannot reach a sufficiently low energy.
An overly expressive ansatz can create unnecessary parameters, deeper circuits, and harder optimization. An overly restrictive ansatz produces a stable but inaccurate result. Compare at least two initializations or ansatz depths when the answer matters.
Choose the optimizer and shots
Gradient-free methods are often convenient for an initial noisy experiment because they do not require a separate gradient circuit. Gradient-based methods can be effective when derivatives are reliable and the parameter count is manageable. Start with modest iteration limits, record the full energy history, and increase the budget only after the implementation behaves as expected.
Use exact expectation values on a statevector simulator to debug circuit logic. Then introduce finite shots to test sampling effects. Finally, add a noise model or hardware execution. Changing all three variables at once makes failures difficult to localize.
A compact PennyLane implementation
The following example uses a one-qubit Hamiltonian and a simple parameterized state. PennyLane API names and device capabilities can change, so pin and test the version used by your project.
import pennylane as qml
from pennylane import numpy as np
coeffs = [0.5, -0.2, 0.3]
observables = [qml.Identity(0), qml.PauliZ(0), qml.PauliX(0)]
H = qml.Hamiltonian(coeffs, observables)
dev = qml.device("default.qubit", wires=1, shots=None)
@qml.qnode(dev)
def energy(theta):
qml.RY(theta[0], wires=0)
qml.RZ(theta[1], wires=0)
return qml.expval(H)
opt = qml.AdamOptimizer(stepsize=0.1)
theta = np.array([0.2, -0.1], requires_grad=True)
for step in range(100):
theta, value = opt.step_and_cost(energy, theta)
if step % 10 == 0:
print(step, float(value))
print("Estimated energy:", float(energy(theta)))
For finite-shot testing, create the device with a chosen shot count, such as shots=1_000. Expect the reported energy to fluctuate between evaluations. For reproducible debugging, set random seeds where supported and record the SDK version, device configuration, Hamiltonian, initial parameters, optimizer, and shot count.
Qiskit implementation principles
A Qiskit version follows the same separation of concerns: represent the Hamiltonian with a Pauli-operator object such as SparsePauliOp, build a parameterized circuit, evaluate its expectation with a supported estimator primitive, and pass the returned value to a classical optimizer. Qiskit primitives and result structures have changed across releases, so avoid copying an older Estimator example without checking the installed version. The algorithmic contract remains stable even when the surrounding API changes.
For a current project, write a small adapter with one function such as evaluate_energy(parameters). Keep Qiskit-specific primitive calls inside that function. This makes it easier to compare Qiskit with PennyLane, replace a simulator, or add a real backend without rewriting the optimization loop.
Worked examples
Example 1: Validate the objective before optimizing
First evaluate the Hamiltonian at three deliberately chosen parameter vectors. Confirm that the output is numeric, finite, and within the operator's plausible eigenvalue range. If the value changes when parameters change, the circuit is connected to the objective. If it never changes, check that parameters are actually bound and that the measured observable is included in the return value.
Next, compare the optimized energy with a classical reference for the same small matrix. You do not need a large benchmark: diagonalizing a one- or two-qubit Hamiltonian locally is enough to determine whether VQE approaches the known minimum. The variational estimate should not be interpreted as lower than the exact ground-state energy when both calculations use the same Hamiltonian and exact arithmetic; such a result usually indicates a sign, coefficient, basis, or measurement error.
Example 2: Move from exact simulation to shots
Run the exact simulator until the energy curve is sensible. Then repeat with 100, 1,000, and 10,000 shots. Track the final energy and the standard deviation across repeated runs. A lower shot count may make the optimizer stop early or wander because it is responding to measurement noise rather than a meaningful energy difference.
When comparing settings, hold the Hamiltonian, initialization, iteration limit, and stopping rule constant. Record both the final energy and the number of evaluations. A slightly better result that requires several times more circuit executions may not be the better engineering choice.
Debugging checklist
- Energy is constant: verify parameter binding, trainable flags, and wire indexing.
- Energy is below the exact minimum: compare coefficient order, Pauli-string conventions, and measurement normalization.
- Optimization oscillates: reduce the learning rate or optimizer step size, increase shots, or use a more conservative optimizer.
- Results vary widely: increase shots, average repeated runs, or test with an exact simulator.
- Hardware results are poor: inspect circuit depth, two-qubit gates, transpilation, readout effects, and noise before changing the optimizer.
- Different SDKs disagree: compare the Hamiltonian matrix and a single fixed parameter vector before comparing complete optimization runs.
For broader simulator choices, see the quantum simulator comparison. If you are deciding where to run hardware jobs, the IBM Quantum, AWS Braket, and Azure Quantum platform guide provides useful deployment context.
When to recalculate
Recalculate the VQE cost and revalidate the implementation whenever one of the important inputs changes. The most obvious triggers are a new Hamiltonian, a different number of Pauli terms, a deeper ansatz, a new optimizer, a different shot count, or a new backend. SDK releases can also change primitive interfaces, default transpilation behavior, supported observables, or device limitations.
Before each substantial run, use this short procedure:
- Save the Hamiltonian and count its terms or measurement groups.
- Record ansatz depth, parameter count, and two-qubit gate count.
- Estimate executions with
terms × iterations × evaluations × shots. - Run a fixed-parameter sanity check on an exact simulator.
- Compare the optimized result with a classical reference when the problem is small enough.
- Repeat with finite shots, then test noise or hardware.
- Store SDK versions, backend settings, seeds, optimizer settings, and energy history.
Revisit the estimate after an early pilot run rather than waiting for a full experiment. The pilot reveals the actual number of optimizer evaluations, whether measurement grouping is active, and whether sampling noise is dominating progress. This makes VQE a repeatable engineering workflow: define the operator, measure the cost, validate each layer, and recalculate whenever the inputs or execution environment change.