Variational quantum algorithms are hybrid programs: a classical optimizer updates circuit parameters while a quantum circuit estimates the objective. This tutorial explains the shared pattern behind VQE and QAOA, shows compact Python examples, and provides a reusable checklist for testing convergence, circuit depth, noise, and classical baselines.
Overview
A variational quantum algorithm has four moving parts:
- Parameterized circuit: a quantum circuit contains adjustable angles or other trainable parameters.
- Measurement objective: the circuit produces an expectation value or sampled cost that can be evaluated.
- Classical optimizer: a classical routine proposes new parameters based on the current objective.
- Stopping and evaluation rules: the workflow decides when to stop and how to compare the result with a reference.
VQE, or the Variational Quantum Eigensolver, is commonly used to estimate a low-energy state of a problem Hamiltonian. QAOA, the Quantum Approximate Optimization Algorithm, uses alternating problem and mixer layers to search for good solutions to a discrete optimization problem. Both are useful examples of hybrid quantum-AI or hybrid quantum-classical development because most of the workflow remains ordinary Python: data preparation, optimization, logging, validation, and reporting.
The examples below use PennyLane-style Python syntax because it makes parameter differentiation and device selection explicit. The same design can be implemented with other quantum SDKs. If you are deciding between frameworks, compare their circuit model, automatic differentiation support, simulator interfaces, hardware integrations, and testing tools rather than choosing solely by API familiarity.
Checklist by scenario
Scenario 1: Build a minimal VQE experiment
Start with a small Hamiltonian whose expected behavior is easy to inspect. The following example uses a two-qubit Hamiltonian and a shallow ansatz. It is intended as a learning and testing circuit, not as a chemistry result.
import pennylane as qml
from pennylane import numpy as np
n_qubits = 2
dev = qml.device('default.qubit', wires=n_qubits)
coeffs = [0.5, 0.8, -0.3]
observables = [qml.Identity(0), qml.PauliZ(0), qml.PauliZ(1)]
hamiltonian = qml.Hamiltonian(coeffs, observables)
@qml.qnode(dev)
def energy(theta):
for wire in range(n_qubits):
qml.RY(theta[wire], wires=wire)
qml.CNOT(wires=[0, 1])
return qml.expval(hamiltonian)
theta = np.array([0.2, -0.1], requires_grad=True)
optimizer = qml.GradientDescentOptimizer(stepsize=0.1)
for step in range(100):
theta, previous = optimizer.step_and_cost(energy, theta)
current = energy(theta)
if step % 10 == 0:
print(step, float(current))
print('final parameters:', theta)
print('final energy:', float(energy(theta)))
Before interpreting the final value, establish a reference. For a tiny Hamiltonian, you can use an exact classical eigensolver or a dense matrix calculation. Record the initial energy, final energy, number of optimizer steps, and the reference value. A decreasing objective alone does not prove that the circuit reached the best state.
VQE checklist: define the Hamiltonian clearly; verify the signs and coefficients; choose an ansatz that can represent a useful state; fix a random seed when initialization is random; log every objective evaluation; compare against an exact or classical baseline; and repeat with several initializations.
Scenario 2: Build a small QAOA experiment
QAOA requires a cost operator and a mixer. For a simple graph problem, the cost operator can encode whether connected vertices receive different binary assignments. A compact two-qubit demonstration can use a single cost term and one QAOA layer.
import pennylane as qml
from pennylane import numpy as np
n_qubits = 2
dev = qml.device('default.qubit', wires=n_qubits)
@qml.qnode(dev)
def qaoa_cost(params):
gamma, beta = params
for wire in range(n_qubits):
qml.Hadamard(wires=wire)
# Problem unitary for one edge in a two-node MaxCut example.
qml.IsingZZ(2 * gamma, wires=[0, 1])
for wire in range(n_qubits):
qml.RX(2 * beta, wires=wire)
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
params = np.array([0.1, 0.1], requires_grad=True)
optimizer = qml.AdamOptimizer(stepsize=0.05)
for step in range(80):
params, old_cost = optimizer.step_and_cost(qaoa_cost, params)
if step % 10 == 0:
print(step, float(qaoa_cost(params)))
Sign conventions vary between cost Hamiltonians and optimization objectives. Decide whether your optimizer should minimize or maximize the returned value, then test the convention on all bitstrings for the smallest graph. After optimization, add a sampled circuit that measures computational-basis outcomes. The expectation value is useful during training, but a practical optimization workflow also needs the distribution of candidate solutions and the best observed bitstring.
QAOA checklist: write down the objective for every candidate bitstring; verify the cost operator on a hand-worked graph; distinguish expectation values from sampled solutions; test multiple layer counts; track the best feasible solution, not only the average objective; and compare with a classical heuristic or exact solver on the same instance.
Scenario 3: Move from a simulator to a device
Do not begin with a full production-sized problem. First freeze a small experiment that passes on a simulator. Then separate device configuration from algorithm code, reduce the shot count only when appropriate for development, and record the backend, shots, transpilation or compilation settings, circuit depth, and measurement strategy. A cloud run should be treated as a new experiment with its own logs, not as a drop-in replacement for an ideal simulator.
What to double-check
- Convergence: plot objective value against optimizer steps and objective evaluations. A flat curve can indicate convergence, poor initialization, an unsuitable ansatz, or gradients that are difficult to estimate.
- Parameter handling: confirm parameter shapes, differentiability settings, and whether the optimizer receives the current cost rather than a stale value.
- Objective direction: VQE normally minimizes energy, while an optimization encoding may be written as either a minimization or maximization problem. Make the transformation explicit.
- Sampling noise: finite shots make measured objectives noisy. Repeat promising parameters and report variability instead of presenting one sampled value as exact.
- Circuit depth: count layers, two-qubit gates, measurements, and parameters. More expressive circuits can also be harder to optimize and more sensitive to hardware noise.
- Baseline quality: use the simplest credible classical baseline first. For small instances, exact enumeration is often more informative than a complicated heuristic.
- Reproducibility: save source code, dependency versions, parameter initialization, problem instances, device settings, and raw measurement results.
For noisy experiments, distinguish algorithmic error from execution error. A poor result may come from the ansatz, optimizer, finite sampling, calibration conditions, compilation, or an incorrect cost function. Error-mitigation methods can be useful, but they should be evaluated against an unmitigated run and a classical reference rather than assumed to improve every workload.
Common mistakes
Using an arbitrary circuit and calling it a benchmark. A benchmark needs a defined problem family, instance size, metric, and baseline. A single attractive output is an experiment, not a performance conclusion.
Optimizing only one initialization. Variational landscapes can depend strongly on starting parameters. Use several seeds and report the spread of final objectives.
Comparing unequal workloads. A quantum circuit evaluated with exact expectation values and a classical algorithm evaluated with noisy samples are not automatically comparable. Align the objective, accuracy target, runtime accounting, and instance.
Ignoring feasibility. In QAOA and other optimization tasks, the best measured bitstring may violate constraints. Add a feasibility check and decide how invalid solutions are scored before running the experiment.
Changing too many variables at once. When debugging, keep the Hamiltonian, ansatz, optimizer, shots, and device fixed while changing one factor. This makes failures easier to localize.
Reporting only the final number. Preserve the training curve, parameter values, shot settings, circuit metadata, and baseline result. These details make the experiment reviewable and repeatable.
When to revisit
Revisit this checklist before each new experiment, planning cycle, or change in the development stack. The most important triggers are a new SDK or device interface, a change from simulation to hardware, a larger problem size, a new ansatz, a different optimizer, or a change in shot budget.
Before acting, use this short release checklist:
- Can you state the optimization objective and whether it is minimized or maximized?
- Does a hand-worked or exact small case validate the circuit encoding?
- Is there a classical baseline using the same instance and metric?
- Have you tested more than one initialization or random seed?
- Are convergence, circuit depth, shots, noise, and feasibility logged?
- Can another developer rerun the experiment from the saved environment and inputs?
Once these checks pass, expand one dimension at a time: graph size, Hamiltonian complexity, circuit depth, hardware execution, or integration with a larger hybrid workflow. For related SDK and cloud workflow guidance, see Qiskit vs Cirq vs PennyLane, how to run quantum circuits in the cloud, and quantum notebook to production.