This QAOA tutorial in Python shows how to turn a small MaxCut problem into a cost Hamiltonian, construct and tune a parameterized circuit, estimate its objective value, and compare the result with a classical baseline. The workflow is deliberately repeatable: change the graph, depth, shot count, or optimizer settings and rerun the same evaluation steps before moving to quantum hardware.
Overview
The quantum approximate optimization algorithm (QAOA) is a hybrid quantum-classical method for discrete optimization. A quantum circuit prepares candidate bit strings, while a classical optimizer adjusts circuit parameters to increase the probability of measuring good solutions.
For a MaxCut problem, each vertex receives a binary value. An edge is cut when its two endpoints receive different values. The objective is to maximize the number, or total weight, of cut edges.
For a graph with edge set E, the MaxCut cost Hamiltonian is commonly written as:
C = Σ(i,j)∈E (1 - ZᵢZⱼ) / 2
Here, Zᵢ and Zⱼ are Pauli-Z operators acting on the qubits associated with the edge endpoints. The term evaluates to one when the corresponding classical bits differ and zero when they are equal.
At depth p, QAOA alternates two parameterized operators:
- Cost unitary:
U(C, γ) = exp(-iγC), which encodes the optimization problem. - Mixer unitary:
U(B, β) = exp(-iβΣXᵢ), which explores different bit strings.
The starting state is usually an equal superposition, prepared with a Hadamard gate on every qubit. The parameters γ and β are then optimized using measured or simulated expectation values.
|+> ── cost(γ) ── mixer(β) ── measure
|+> ── cost(γ) ── mixer(β) ── measure
|+> ── cost(γ) ── mixer(β) ── measure
This is not a promise that QAOA will outperform a classical solver on every instance. The useful engineering question is whether the chosen circuit, optimizer, and execution method produce a solution of acceptable quality for the problem size and resource budget.
How to estimate
A reliable QAOA experiment separates four tasks: represent the problem, build the circuit, optimize the parameters, and evaluate the final samples. Keeping these stages separate makes it easier to identify whether a weak result comes from the model, the circuit, the optimizer, or measurement noise.
1. Represent the graph and objective
Begin with a small weighted or unweighted graph. For an unweighted graph, define each edge as a pair of integer vertex indices. The classical objective for a bit string x is:
cut(x) = Σ(i,j)∈E [xᵢ ≠ xⱼ]
Use this function independently of the quantum code. It becomes the reference used to score measured bit strings and to verify the Hamiltonian implementation.
2. Create the QAOA state
Prepare all qubits in the |+⟩ state. For every edge, apply the cost interaction associated with ZᵢZⱼ. Then apply an X-axis rotation to each qubit for the mixer layer. Repeat these two layers p times.
In a Qiskit, Cirq, or another quantum SDK implementation, the exact primitive names can change between releases. The mathematical structure is more stable than any single API: Hadamards, two-qubit cost interactions, single-qubit mixer rotations, measurement, and a classical objective function.
3. Optimize an expectation value
For parameters θ = (γ₁, β₁, …, γₚ, βₚ), estimate:
F(θ) = Σx Pθ(x) cut(x)
The optimizer minimizes -F(θ) or maximizes F(θ), depending on the library convention. On an ideal statevector simulator, the expectation can be calculated without sampling noise. On a shot-based simulator or hardware backend, it is estimated from counts and will vary between evaluations.
4. Decode and evaluate samples
After optimization, run the best parameter set with a larger evaluation shot count. Convert each measured bit string into a graph assignment, calculate its cut value classically, and report at least three quantities:
- The best sampled objective value.
- The mean objective value across all samples.
- The probability of sampling a solution at or above a chosen quality threshold.
These measures distinguish a circuit that occasionally finds an excellent answer from one that consistently produces useful answers.
Inputs and assumptions
QAOA results depend strongly on inputs that are easy to overlook. Record them with every experiment so that results remain comparable.
| Input | Practical starting point | Why it matters |
|---|---|---|
| Graph | Three to six vertices for initial tests | Small instances make circuit and objective bugs easier to inspect. |
Depth p | Start at 1, then test 2 or 3 | More layers add expressiveness, gates, runtime, and noise exposure. |
| Initialization | Several random parameter sets plus a simple fixed start | Variational objectives can have local optima and flat regions. |
| Shots | Use fewer shots during search and more for final evaluation | Optimization needs speed; reporting needs a more stable estimate. |
| Optimizer | Compare a noise-tolerant method with a gradient-based method when appropriate | Shot noise and parameter landscapes affect optimizer behavior. |
| Constraints | Encode them in the objective or use a feasible-state strategy | An unconstrained circuit can return invalid solutions. |
A compact Python reference for the classical part of the workflow is:
def cut_value(bits, edges):
return sum(bits[i] != bits[j] for i, j in edges)
edges = [(0, 1), (1, 2), (0, 2)]
for bits in [(0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0)]:
print(bits, cut_value(bits, edges))
The quantum circuit should be tested against this function before optimization. For each computational-basis bit string, verify that the implemented cost Hamiltonian assigns the same score as the classical objective. This catches reversed bit order, missing edges, and incorrect rotation angles early.
For a weighted graph, replace each Boolean edge contribution with weight * (bits[i] != bits[j]). Keep weights in a documented numeric range during early tests; large differences can cause one edge to dominate the objective and make tuning less informative.
Worked examples
Triangle graph
Consider a three-vertex triangle with edges (0,1), (1,2), and (0,2). The all-zero assignment cuts no edges. An assignment such as 001 cuts two edges, which is the best possible value for this graph. The complement assignment 110 has the same cut value, illustrating the symmetry that often appears in MaxCut.
A practical experiment can use the following sequence:
- Build a three-qubit circuit with
p = 1. - Initialize
γandβseveral times rather than trusting one starting point. - For each parameter set, execute the circuit and calculate the sampled mean cut value.
- Keep the parameter set with the highest objective value, then rerun it with a larger evaluation sample.
- Compare the best measured bit strings with an exhaustive classical enumeration of all eight assignments.
For a statevector implementation, the expectation is deterministic up to numerical precision. For shot-based execution, use the same parameter set for repeated evaluations and report the spread between runs rather than presenting one sample as definitive.
Parameter-tuning plan
| Experiment | Change one factor | Record |
|---|---|---|
| Baseline | p = 1, fixed shot count, one optimizer | Best and mean cut values |
| Initialization | Run multiple starting parameters | Best value and optimizer evaluations |
| Depth | Increase from p = 1 to p = 2 | Objective improvement versus added circuit cost |
| Shots | Increase evaluation shots | Variation in expectation and solution frequency |
| Noise | Compare ideal simulation with a noisy or hardware run | Change in mean value and best-solution probability |
For larger graphs, do not rely only on the best bit string. Compare against a classical baseline such as exhaustive search for very small instances, or an appropriate classical heuristic for larger ones. The ratio between the QAOA result and the classical reference is more informative than an isolated objective value.
If you are implementing QAOA with Qiskit, consult the current primitive and sampler documentation before adapting code from an older example. The same caution applies to Cirq, PennyLane, and cloud execution services: circuit construction concepts persist, while estimator, sampler, backend, and result APIs may change. A related QAOA in Python guide can be used alongside this workflow, while the quantum simulator selection guide helps match the simulator to the experiment.
When to recalculate
Recalculate QAOA results whenever an input that affects the objective, circuit, or execution environment changes. This includes adding or removing graph edges, changing weights, increasing depth, changing the shot count, switching optimizers, or moving from an ideal simulator to a noisy backend.
Before a hardware run, repeat the classical validation and inspect the compiled circuit. Count two-qubit gates, confirm qubit mapping, and check that measurement-bit order is decoded correctly. Hardware noise can make a deeper circuit worse even when the ideal simulation improves. Use the quantum program debugging checklist and document the backend, transpilation settings, parameters, shots, and random seeds where available.
Use this short checklist for each new problem instance:
- Validate every Hamiltonian term against the classical objective.
- Confirm the graph’s vertex-to-qubit mapping and bit-string order.
- Run a classical baseline before interpreting quantum results.
- Try more than one parameter initialization.
- Separate optimization shots from final evaluation shots.
- Report best value, mean value, and solution frequency.
- Compare depth increases against gate count and noise exposure.
- Recheck SDK primitives and backend execution guidance after framework updates.
QAOA becomes a useful developer experiment when it is treated as a measured hybrid workflow rather than a circuit-only exercise. Keep the problem definition, parameter search, sampling, and classical evaluation reproducible. Then each new graph or backend becomes a controlled comparison instead of a one-off demonstration.