This QAOA tutorial shows how to turn a small Max-Cut graph into a variational quantum circuit, tune its parameters in Python, sample candidate solutions, and judge the result against a classical baseline. The workflow is deliberately small enough to run on a simulator and clear enough to adapt to scheduling, routing, and other binary optimization problems.
Overview
QAOA, or the Quantum Approximate Optimization Algorithm, alternates two operations: a problem-dependent cost layer and a mixing layer. A classical optimizer changes the layer angles until the circuit’s measured objective improves. The quantum circuit is therefore only one part of the process; the optimizer, shot count, simulator settings, and evaluation method all affect the result.
Max-Cut is a useful first example. Given an undirected graph, the goal is to divide its vertices into two groups so that as many edges as possible cross between the groups. Represent each vertex with one qubit. A measured bitstring assigns each vertex to group 0 or group 1. An edge contributes one point when its endpoints have different bits.
For an edge connecting vertices u and v, the corresponding cost term is:
C(u,v) = (1 - ZuZv) / 2
The total cost is the sum of this term over all edges. QAOA attempts to produce bitstrings with high cost, but it does not guarantee the optimum—especially at low circuit depth or on noisy hardware. A meaningful evaluation therefore compares the quantum result with the exact classical optimum for the same graph.
If you want to compare statevector, shot-based, and cloud execution before running this experiment, see Sharp Qubit’s quantum simulator comparison. The same discipline used in a VQE Python example also applies here: define the objective clearly, separate optimization from measurement, and record the assumptions.
How to estimate
Use four repeatable quantities to estimate whether a QAOA run is useful:
- Best observed cut: the highest-scoring bitstring seen in the samples.
- Expected cut value: the average objective value over the output distribution.
- Classical optimum: the best cut found by exhaustive enumeration or another trusted solver.
- Approximation ratio:
best observed cut / classical optimum, or the same ratio using the expected value.
For a small graph, exhaustive enumeration is preferable to an informal baseline. With n vertices, there are 2n bitstrings, although a cut and its complemented assignment have the same value. Enumeration is practical for the small demonstrations used in this tutorial and provides an unambiguous reference.
Do not use only the single best sample to describe the run. A rare optimal bitstring may appear by chance, while the expected value can reveal that most of the distribution is poor. Report both the highest observed cut and the probability mass assigned to optimal solutions when possible.
For circuit depth p, QAOA uses p cost layers and p mixer layers, with two trainable parameters per layer: gamma and beta. Increasing p gives the circuit more expressive power but also increases optimization and hardware demands. Begin with p=1, establish a baseline, and then increase depth only when the comparison justifies it.
Inputs and assumptions
The example below uses PennyLane and a small four-vertex cycle. The graph edges are (0,1), (1,2), (2,3), and (3,0). Its classical optimum is four: assign alternating vertices to opposite groups.
The code uses an ideal simulator for parameter optimization and a finite-shot circuit for sampling. This separates two questions:
- Can the chosen ansatz and optimizer find useful parameters under ideal evaluation?
- What candidate solutions appear when the final circuit is measured with a realistic shot budget?
Install PennyLane in the environment used for the experiment, then adapt the imports or device syntax if your installed release has changed its APIs.
import itertools
import pennylane as qml
from pennylane import numpy as np
# A four-vertex cycle: the Max-Cut optimum is 4.
edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
n_qubits = 4
p = 1
# Ideal device for optimization.
opt_dev = qml.device("default.qubit", wires=n_qubits, shots=None)
def cost_value(bits, edges):
"""Return the number of edges crossing the proposed cut."""
return sum(bits[u] != bits[v] for u, v in edges)
def classical_baseline(n, edges):
results = []
for bits in itertools.product([0, 1], repeat=n):
results.append((cost_value(bits, edges), bits))
optimum = max(value for value, _ in results)
best = [bits for value, bits in results if value == optimum]
return optimum, best
def apply_cost_layer(gamma, edges):
# IsingZZ(-gamma) implements the required ZZ phase up to a
# global phase, which does not change measurement probabilities.
for u, v in edges:
qml.IsingZZ(-gamma, wires=[u, v])
def apply_mixer_layer(beta, n):
# RX(2 beta) implements exp(-i beta X).
for wire in range(n):
qml.RX(2 * beta, wires=wire)
@qml.qnode(opt_dev, interface="autograd")
def objective(params):
gammas = params[:p]
betas = params[p:]
for wire in range(n_qubits):
qml.Hadamard(wires=wire)
for layer in range(p):
apply_cost_layer(gammas[layer], edges)
apply_mixer_layer(betas[layer], n_qubits)
# Sum the Max-Cut cost terms as expectation values.
return sum(
0.5 * (1 - qml.expval(qml.PauliZ(u) @ qml.PauliZ(v)))
for u, v in edges
)
params = np.array([0.2] * p + [0.1] * p, requires_grad=True)
optimizer = qml.AdamOptimizer(stepsize=0.08)
for step in range(150):
params, value = optimizer.step_and_cost(objective, params)
if step % 25 == 0:
print(f"step={step:3d}, expected_cut={value:.6f}")
print("optimized parameters:", params)
print("optimized expected cut:", float(objective(params)))
The signs and angle conventions deserve attention. Different SDKs expose equivalent rotations with different parameter definitions. Rather than copying angles between frameworks, verify the convention by checking one edge: the cost term should reward opposite computational-basis bits. A sign mistake can still produce a smooth optimization trace while targeting the wrong objective.
Worked examples
1. Compute the classical reference
Run this immediately after defining the graph:
classical_optimum, optimal_bits = classical_baseline(n_qubits, edges)
print("classical optimum:", classical_optimum)
print("optimal assignments:", optimal_bits)
For the four-cycle, assignments such as (0,1,0,1) and its complement cut every edge. Because group labels are arbitrary, complementary bitstrings represent the same partition.
2. Sample the optimized circuit
Optimization used an ideal expectation value. Now create a finite-shot QNode to obtain a distribution of measured assignments:
sample_dev = qml.device("default.qubit", wires=n_qubits, shots=10000)
@qml.qnode(sample_dev)
def sample_distribution(params):
gammas = params[:p]
betas = params[p:]
for wire in range(n_qubits):
qml.Hadamard(wires=wire)
for layer in range(p):
apply_cost_layer(gammas[layer], edges)
apply_mixer_layer(betas[layer], n_qubits)
return qml.probs(wires=range(n_qubits))
probabilities = sample_distribution(params)
rows = []
for index, probability in enumerate(probabilities):
bits = tuple(int(bit) for bit in format(index, f"0{n_qubits}b"))
rows.append((float(probability), cost_value(bits, edges), bits))
rows.sort(reverse=True)
for probability, cut, bits in rows[:8]:
print(f"bits={bits}, cut={cut}, probability={probability:.4f}")
best_observed = max(cut for _, cut, _ in rows if _ > 0)
expected_from_samples = sum(probability * cut for probability, cut, _ in rows)
ratio = best_observed / classical_optimum
print("best observed cut:", best_observed)
print("sampled expected cut:", expected_from_samples)
print("best-sample approximation ratio:", ratio)
The line that filters rows is not needed mathematically and can be removed if zero-probability outcomes should also be considered. More importantly, keep the bit-order convention consistent. SDKs can display the most significant qubit first, while circuit diagrams may number wires in the opposite visual direction. The cut value is unaffected if the same convention is used throughout, but mislabeled output makes debugging difficult.
3. Compare depth and optimizer settings
To make the experiment informative, repeat it with a small table of settings rather than relying on one run:
p=1andp=2;- two or three parameter initializations;
- the same number of optimization steps;
- the same shot count for final sampling.
Record the final expected cut, best observed cut, approximation ratio, optimization steps, and runtime. If a deeper circuit improves the ideal expectation but performs worse with finite shots, that is a useful result: the extra expressivity may not compensate for estimation noise or execution cost.
For hardware experiments, add transpilation, connectivity, gate counts, and repeated trials to the record. QAOA uses interactions that may not match the device’s native coupling map. Review the quantum hardware connectivity guide before interpreting a hardware result as an algorithmic result.
When to recalculate
Recalculate the baseline and rerun the experiment whenever the graph changes. Adding one edge, changing a weight, or relabeling a constrained problem changes the cost Hamiltonian and invalidates conclusions drawn from the previous instance. For weighted Max-Cut, replace each unit contribution with its edge weight and compare against the weighted classical optimum.
Also revisit the workflow after any of these changes:
- Circuit depth changes: re-optimize all parameters; do not append a layer and assume the old angles remain appropriate.
- Shot budget changes: rerun sampling because a low-probability optimum may appear or disappear through statistical variation.
- Device or noise model changes: repeat with calibration-aware settings and distinguish noisy optimization from noisy final sampling.
- SDK updates: verify rotation conventions, wire ordering, optimizer interfaces, and measurement behavior.
- Optimizer changes: use multiple initializations and compare convergence traces rather than only final values.
If the result is unexpectedly poor, use this checklist:
- Confirm that the classical baseline returns the expected optimum.
- Evaluate a few explicit bitstrings and verify their cut values by hand.
- Check the sign and angle convention for the cost and mixer gates.
- Increase shots before concluding that two configurations differ.
- Try several initial parameters; one failed run is not evidence that QAOA cannot solve the instance.
- Compare expected value with best observed value.
- Inspect circuit depth and hardware connectivity before adding more QAOA layers.
Once this four-vertex example is reproducible, change one input at a time: graph structure, edge weights, depth, optimizer, or backend. That controlled approach makes the QAOA tutorial a reusable benchmark rather than a one-off circuit demonstration. For broader portability between tools, the OpenQASM 3 guide can help you separate the circuit description from the SDK-specific execution layer.