A variational quantum eigensolver (VQE) workflow combines a parameterized quantum circuit with a classical optimizer to estimate the lowest eigenvalue of a Hamiltonian. This VQE tutorial shows how to define the problem, estimate measurement cost, track convergence, diagnose weak optimization, and prepare the same workflow for Qiskit, PennyLane, or quantum hardware.
Overview
VQE is a hybrid quantum-classical algorithm. The quantum processor or quantum simulator prepares a trial state and measures the expectation value of a Hamiltonian. A classical optimizer then changes the circuit parameters to reduce that measured energy. The loop continues until the result stops improving or reaches a predefined budget.
For a Hamiltonian written as a weighted sum of Pauli operators, the objective is:
E(θ) = ⟨ψ(θ)|H|ψ(θ)⟩
Here, θ is the vector of trainable circuit parameters, |ψ(θ)⟩ is the state produced by the ansatz, and H is the problem Hamiltonian. VQE seeks parameters that make E(θ) as small as possible. For a suitable physical problem, that minimum approximates the ground-state energy.
The algorithm is useful as a compact example of hybrid quantum-classical computing, but its practical value depends on the details of the workflow. Circuit depth, ansatz design, optimizer behavior, measurement variance, and hardware noise can matter as much as the choice of SDK.
A useful VQE implementation separates five concerns:
- Represent the Hamiltonian as measurable terms.
- Build an ansatz that can express a useful range of states.
- Evaluate the energy for a parameter vector.
- Use a classical optimizer to propose new parameters.
- Record energy, parameters, measurements, and stopping conditions.
For circuit inspection, a quantum circuit visualizer can help reveal unnecessary gates, entangling structure, and changes introduced during compilation.
How to estimate
The most useful estimate is not simply “how long will VQE run?” Instead, estimate the number of objective evaluations and the measurement work inside each evaluation.
Start with this planning equation:
total circuit executions ≈ iterations × Hamiltonian terms × shots per term
This is a first-order estimate. An implementation may group compatible observables, reuse measurements, evaluate several parameter points during an optimizer step, or use exact statevector expectations. Those choices change the actual workload.
Suppose a Hamiltonian has 6 Pauli terms, the optimizer performs 80 iterations, and each term uses 1,000 shots. A simple shot-based estimate is:
80 × 6 × 1,000 = 480,000 circuit executions
If the same experiment uses an exact statevector simulator, “shots” may not be the limiting input. The cost instead depends on state dimension, simulator implementation, circuit depth, and the number of objective evaluations. Statevector results are useful for debugging and noiseless baselines, but they do not reproduce sampling noise or all hardware effects.
Estimate optimizer evaluations separately from iterations. Gradient-based methods may require additional circuit evaluations for gradients, depending on the differentiation method. A conservative planning formula is:
total evaluations ≈ iterations × (1 + gradient evaluations per step)
Then multiply by the number of measured Hamiltonian terms and shots. For example, if each of 60 optimization steps requires the objective plus two additional gradient-related evaluations, and the Hamiltonian has 8 terms at 500 shots per term:
60 × 3 × 8 × 500 = 720,000 circuit executions
Treat this as a workload estimate rather than a runtime promise. Queueing, compilation, batching, device availability, and measurement grouping can all change elapsed time.
Inputs and assumptions
Hamiltonian representation
Begin with a small Hamiltonian that is easy to verify. A two-qubit example is:
H = 0.5 Z₀ + 0.5 Z₁ + 0.2 X₀X₁
The coefficients are illustrative. The important structure is that the Hamiltonian is decomposed into measurable Pauli strings. Each term contributes a coefficient multiplied by an expectation value:
E(θ) = 0.5⟨Z₀⟩ + 0.5⟨Z₁⟩ + 0.2⟨X₀X₁⟩
Ansatz and initialization
An ansatz is a parameterized circuit. A practical starting point is a layer of single-qubit rotations followed by an entangling gate. Keep the first circuit shallow enough to inspect. More parameters can increase expressivity, but they also increase optimization and measurement work.
Initialization is an experimental input, not a detail to hide. Try more than one seed when the result is sensitive to the starting point. Record the seed, initial energy, final energy, and number of evaluations so that runs can be compared.
Optimizer settings
Record the optimizer name, learning rate or step size where applicable, maximum iterations, convergence tolerance, and gradient settings. A stopping rule should include both an energy change threshold and a maximum evaluation budget. Stopping only because the plot looks flat can conceal a failed optimization.
Measurement model
Choose between exact expectation values and shot-based measurements deliberately. Exact expectations are appropriate for an initial logic check. Shot-based simulation introduces sampling variance and is a better test of how the optimizer behaves with finite measurements. Hardware runs add device-specific noise and compilation effects.
Track at least these fields for every objective evaluation:
- Iteration or evaluation number.
- Energy and, where available, term-by-term expectations.
- Parameter vector or a reproducible reference to it.
- Shots, backend, circuit depth, and compilation settings.
- Optimizer status and stopping reason.
Worked examples
PennyLane-style implementation
The following compact example uses a two-qubit Hamiltonian and an exact expectation-value simulator. API details can vary by installed version, so pin the environment in a reproducible notebook.
import pennylane as qml
from pennylane import numpy as np
n_qubits = 2
dev = qml.device("default.qubit", wires=n_qubits)
coeffs = np.array([0.5, 0.5, 0.2])
obs = [qml.PauliZ(0), qml.PauliZ(1), qml.PauliX(0) @ qml.PauliX(1)]
H = qml.Hamiltonian(coeffs, obs)
def ansatz(weights):
for wire in range(n_qubits):
qml.RY(weights[wire], wires=wire)
qml.CNOT(wires=[0, 1])
@qml.qnode(dev)
def energy(weights):
ansatz(weights)
return qml.expval(H)
opt = qml.AdamOptimizer(stepsize=0.1)
weights = np.zeros(n_qubits, requires_grad=True)
history = []
for step in range(80):
weights, cost = opt.step_and_cost(energy, weights)
value = float(energy(weights))
history.append(value)
if step % 10 == 0:
print(step, value)
The history can be plotted as energy versus evaluation number. A downward trend followed by a plateau suggests convergence, but it is not proof of the ground state. Compare the final value with a classically calculated reference for this small Hamiltonian before interpreting the result.
Qiskit-style adaptation
In Qiskit, the same design maps to an observable object, a parameterized circuit, an estimator primitive or compatible backend, and a classical optimizer. Keep the objective function explicit: bind parameters, evaluate the observable, append the value to a history list, and return the scalar energy. The exact class names and primitive interfaces depend on the installed Qiskit version, so consult the version-matched documentation rather than copying an outdated import block.
The algorithmic structure remains the same:
def objective(theta):
bound_circuit = ansatz.assign_parameters(theta)
result = estimator.run(bound_circuit, hamiltonian).result()
value = float(result.values[0])
history.append(value)
return value
result = optimizer.minimize(fun=objective, x0=initial_parameters)
For either framework, compare three runs before moving to hardware: exact expectations, finite-shot simulation, and a second initialization. If the exact run converges but the shot-based run is unstable, first inspect shot count, observable grouping, optimizer step size, and parameter scaling.
Diagnosing barren plateaus and weak convergence
A flat energy curve can have several causes. The ansatz may be too expressive for the optimizer, gradients may be very small, measurements may be too noisy, or the circuit may not encode useful problem structure. Do not label every plateau a barren plateau without testing alternatives.
- Plot the absolute energy change between evaluations.
- Inspect gradient magnitudes for several parameters and seeds.
- Reduce ansatz depth and compare the result.
- Try a problem-informed initialization.
- Increase shots only after confirming that sampling noise is the issue.
- Compare the optimizer with a simple baseline such as a smaller step size.
When to recalculate
Recalculate the VQE workload whenever an input that affects evaluations, variance, or circuit execution changes. In practice, revisit the estimate when you:
- Add or remove Hamiltonian terms.
- Increase ansatz depth or parameter count.
- Change the optimizer, gradient method, or stopping tolerance.
- Move from exact expectations to shot-based simulation.
- Change shots, observable grouping, batching, or error-mitigation settings.
- Switch simulators, SDK versions, transpilers, or hardware targets.
- Observe more optimizer evaluations than the original plan allowed.
Before a hardware run, use this checklist:
- Validate the Hamiltonian and ansatz on a small classical reference.
- Save a noiseless convergence curve.
- Repeat with finite shots and record the variance.
- Inspect the compiled circuit for depth and connectivity overhead using a circuit visualizer.
- Set a maximum measurement budget as well as a maximum iteration count.
- Log backend, shots, seeds, software versions, and stopping reason.
- Compare the final energy with the best known reference available for the test problem.
VQE becomes easier to evaluate when every result is tied to explicit assumptions. Treat the Hamiltonian, ansatz, optimizer, shot model, and budget as versioned inputs. When any of them changes, rerun the estimate and preserve the old convergence record for comparison. That discipline turns a small VQE tutorial into a repeatable workflow for quantum algorithm experiments and research-to-application decisions.