A variational quantum eigensolver (VQE) is only useful when its energy estimate can be reproduced, explained, and compared with a trusted baseline. This practical VQE tutorial shows how to define a Hamiltonian, choose an ansatz, optimize parameters, monitor convergence, and decide whether a result is credible in a simulator or on quantum hardware.
Overview
VQE is a hybrid quantum-classical algorithm for estimating the ground-state energy of a system. The quantum circuit prepares a parameterized state and measures the expectation value of a Hamiltonian. A classical optimizer then updates the circuit parameters to reduce that expectation value. The loop continues until the energy stops improving or a defined budget is reached.
For a Hamiltonian written as a weighted sum of Pauli operators, the objective has the form:
E(θ) = ⟨ψ(θ)|H|ψ(θ)⟩
Here, θ contains the circuit parameters, ψ(θ) is the state prepared by the ansatz, and H is the problem Hamiltonian. In a chemistry workflow, the Hamiltonian is usually produced by mapping an electronic-structure problem to qubits. In a smaller software test, you can define it directly as a sum of Pauli terms.
The most important VQE habit is to separate implementation correctness from optimization performance. First verify that the Hamiltonian and measurements are correct. Then test whether the ansatz can represent a useful state. Only after that should you compare optimizers, shot counts, noise models, or hardware backends. A low energy from an incorrect Hamiltonian is not a successful result.
VQE also illustrates the broader pattern of parameterized quantum circuits and parameter sweeps: the quantum program evaluates an objective, while classical Python code manages the search. This makes VQE a practical example of hybrid quantum-classical application development.
Checklist by scenario
1. Before writing the circuit
- Define the target. Decide whether you need a ground-state energy, an approximate state, an energy difference, or a property derived from measured observables. These goals can require different validation steps.
- Write down the Hamiltonian convention. Record the qubit order, Pauli-string order, coefficient signs, units, and any constant energy offset. A constant term affects the reported energy even though it does not change the optimizer's circuit.
- Choose the smallest useful problem. Begin with a Hamiltonian that can be simulated exactly or nearly exactly. A small benchmark makes sign errors, wire-order mistakes, and measurement bugs easier to isolate.
- Set a classical reference. For a small matrix, diagonalize the Hamiltonian directly with a classical eigensolver. Treat this reference as the target for debugging, not as proof that a larger quantum result will be accurate.
2. Choosing an ansatz
- Match the ansatz to the problem. A hardware-efficient ansatz is convenient for circuit execution, while a problem-inspired ansatz can encode useful structure with fewer parameters. Neither is universally best.
- Respect known constraints. If particle number, spin, parity, or another symmetry is relevant, use an initial state and circuit construction that preserve it when practical.
- Start shallow. Add layers only when the current circuit cannot approach the reference energy. Extra layers increase parameter count, measurement cost, and exposure to noise.
- Check expressibility empirically. Run several initializations and inspect the best energy, convergence rate, and variability. A deeper ansatz that rarely optimizes successfully may be less useful than a simpler one.
3. Implementing the VQE loop in Python
SDK details change, but the algorithmic structure is stable. In either Qiskit or PennyLane, keep the objective function small and testable:
def objective(theta):
# Prepare the ansatz with parameters theta
# Measure each Hamiltonian term
# Return the weighted sum of expectation values
return energy
result = optimizer.minimize(objective, initial_theta)
energy = result.fun
For a real implementation, represent the Hamiltonian as explicit terms such as (coefficient, "ZIZ"), or use the operator type provided by the SDK. Test each term independently before summing them. A useful unit test prepares a known computational-basis state and checks that the measured expectation values have the expected signs.
Keep an optimization history containing the iteration number, energy, parameter norm, and—when available—evaluation count. A single final energy hides whether the run converged smoothly, stalled, or found a result by chance.
4. Selecting an optimizer
- Use a gradient-free method first when the objective is noisy, the parameter count is small, or analytic gradients are not yet working.
- Use a gradient-based method when gradients are reliable and the circuit is differentiable in the selected simulator or execution mode.
- Compare, do not assume. Run the same initial parameters and evaluation budget with more than one reasonable optimizer. Report the best energy and the number of objective evaluations, not just the optimizer name.
- Control initialization. Use fixed random seeds for debugging and several independent starts for a more honest assessment of optimizer stability.
5. Moving from an ideal simulator to shots or hardware
First establish an exact or high-shot simulator baseline. Then introduce finite shots, a noise model, transpilation, or a hardware backend one variable at a time. This isolates the source of any energy increase. Before execution, estimate qubits, circuit depth, two-qubit gates, and shots using a documented budget; the quantum circuit resource estimation checklist can help structure that review.
When using shots, repeat the final evaluation with fresh samples and report an uncertainty estimate or at least the observed variation. For noisy hardware, compare raw results with an appropriate mitigation experiment rather than silently replacing the raw number; see the practical guide to quantum error mitigation.
What to double-check
- Hamiltonian signs and offsets: Confirm every coefficient, especially negative interaction terms and identity contributions. Compare the operator matrix with the matrix used by the classical reference.
- Wire and bit ordering: SDKs can display or index qubits differently. Test a basis state with a known Pauli expectation before trusting a chemistry result.
- Measurement construction: Ensure that each Pauli term is measured in the correct basis. X and Y observables require basis changes before computational-basis measurement. For more background, review counts, probabilities, quasi-distributions, and expectation values.
- Initial-state validity: Verify that the starting state has the intended particle number or symmetry. A circuit can optimize correctly while exploring the wrong physical sector.
- Convergence criteria: Do not stop only because the optimizer reports success. Check the energy change over recent iterations, the gradient or parameter change when available, and whether independent starts reach similar values.
- Baseline comparison: Compare like with like. Include constant offsets, use the same Hamiltonian convention, and distinguish an absolute energy error from an error in an energy difference.
- Noise and sampling: Separate optimizer instability from measurement variance by evaluating the same parameters repeatedly. Increasing shots may reduce sampling variation but will not correct a wrong circuit or an unsuitable ansatz.
Common mistakes
Using a deep ansatz immediately. More layers increase flexibility, but they also make optimization and execution harder. Establish a shallow baseline first.
Trusting one optimizer run. Variational objectives can contain local minima, flat regions, and initialization-sensitive behavior. Use multiple starts and preserve the full optimization history.
Confusing a lower number with a better answer. The variational principle is meaningful only for the correctly defined Hamiltonian and state space. A suspiciously low energy can indicate a sign, offset, mapping, or measurement error.
Ignoring barren plateaus. If gradients are nearly zero across many random initializations, reduce circuit depth, use a structured initialization, or grow the ansatz gradually. Do not simply increase the optimizer iteration limit.
Changing too many variables at once. If you change the ansatz, optimizer, shot count, transpilation settings, and backend together, you cannot identify why the result changed. Keep an experiment log and alter one major factor at a time.
Reporting only the final energy. A reproducible VQE report should include the Hamiltonian definition, qubit count, ansatz, parameter initialization, optimizer, stopping rule, shots, backend or simulator settings, and classical reference.
When to revisit
Revisit this VQE checklist whenever the Hamiltonian, qubit mapping, ansatz, optimizer, SDK, simulator, or execution backend changes. A new SDK release can alter operator construction, gradient behavior, transpilation, or supported chemistry workflows, so rerun the small reference test before trusting a production experiment.
Recheck the workflow before a seasonal planning or research cycle if you are comparing candidate molecules, revising an application budget, or deciding whether a hardware run is justified. Also revisit it when moving from exact simulation to finite shots, from simulation to hardware, or from a toy Hamiltonian to a chemistry-derived one.
A practical closing sequence is:
- Freeze and record the Hamiltonian convention and classical reference.
- Run a shallow ansatz with fixed initialization and store the energy history.
- Repeat with several initializations and at least one alternative optimizer.
- Verify measurements term by term and inspect wire ordering.
- Introduce shots, noise, transpilation, or hardware one stage at a time.
- Report accuracy, variability, resource use, and limitations together.
That process turns a VQE tutorial into a reusable quantum software development workflow: build the smallest experiment that can fail visibly, validate it against a classical baseline, and expand only when each earlier result is understood.