QAOA in Python: Build, Optimize, and Evaluate Quantum Approximate Optimization Circuits
QAOAquantum algorithmsquantum optimizationQiskitPennyLanePython

QAOA in Python: Build, Optimize, and Evaluate Quantum Approximate Optimization Circuits

UUpqubit Editorial Team
2026-11-21
8 min read

A practical QAOA in Python guide covering Hamiltonians, circuit depth, optimization, sampling, approximation ratios, and classical baselines.

This QAOA in Python tutorial walks through a repeatable workflow for turning a small combinatorial optimization problem into a quantum circuit, optimizing its parameters, measuring candidate solutions, and deciding whether the result is useful against a classical baseline. The examples use MaxCut because its cost function maps cleanly to a QAOA Hamiltonian, but the same process applies to other binary optimization problems.

Overview

The Quantum Approximate Optimization Algorithm, or QAOA, is a hybrid quantum-classical method. A quantum circuit prepares a parameterized state, while a classical optimizer adjusts the circuit parameters to improve an objective. The quantum processor or simulator evaluates the objective repeatedly; the optimizer uses those evaluations to choose the next parameters.

For a problem instance, a QAOA experiment has five core stages:

  1. Define the feasible solutions and objective function.
  2. Encode the objective as a cost Hamiltonian.
  3. Build alternating cost and mixer layers.
  4. Optimize the angles that control those layers.
  5. Sample, score, and compare the resulting bitstrings with a classical reference.

QAOA does not automatically produce an advantage over classical optimization. A useful experiment therefore measures more than the best bitstring observed. Record the objective value, approximation ratio, number of circuit evaluations, shot budget, runtime, and the quality of a classical baseline. For debugging the resulting quantum states and measurements, see this quantum state debugging guide.

How to estimate

1. Start with a binary optimization model

In MaxCut, each graph vertex receives a binary label. An edge contributes to the cut when its endpoints receive different labels. For a bitstring x, a simple classical score is:

cut_value(x) = sum(1 for (u, v) in edges if x[u] != x[v])

This function is the ground truth for evaluating sampled results. Keep it in ordinary Python even after you construct the quantum circuit. It gives you a transparent way to validate Hamiltonian signs, decode measurements, and compare against a classical solver.

2. Map the objective to a cost Hamiltonian

Use a qubit for each graph vertex and associate the computational-basis value with a Pauli-Z eigenvalue. For an edge connecting qubits u and v, a common MaxCut contribution can be written as:

C(u, v) = (I - Z_u Z_v) / 2

The identity term shifts the energy, while the Z_u Z_v term distinguishes equal from different assignments. Depending on the SDK and whether the optimizer minimizes an energy or maximizes a score, you may use the cost Hamiltonian directly or negate the objective. This sign convention is a frequent source of apparently poor QAOA results.

3. Build the alternating circuit

QAOA starts with every qubit in an equal superposition. Each layer applies a cost unitary controlled by a parameter gamma and a mixer unitary controlled by a parameter beta. In abstract form:

|psi(gamma, beta)> = U_M(beta_p) U_C(gamma_p) ... U_M(beta_1) U_C(gamma_1) |+>

The cost layer encodes the problem. The standard X mixer explores computational-basis assignments by rotating each qubit around the X axis. The depth p is the number of cost-mixer pairs. Increasing p adds expressive power, but also increases circuit depth, optimization work, and exposure to noise.

4. Optimize expectation values before sampling

A practical workflow usually optimizes an expectation value first, then runs a larger sampling job with the best parameters. In PennyLane-style pseudocode, the circuit structure looks like this:

import pennylane as qml
from pennylane import numpy as np

n_qubits = 4
edges = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)]
p = 2

dev = qml.device("default.qubit", wires=n_qubits)

def qaoa_layer(gamma, beta):
    for u, v in edges:
        qml.IsingZZ(2 * gamma, wires=[u, v])
    for wire in range(n_qubits):
        qml.RX(2 * beta, wires=wire)

@qml.qnode(dev)
def objective(params):
    for wire in range(n_qubits):
        qml.Hadamard(wires=wire)
    for layer in range(p):
        qaoa_layer(params[0, layer], params[1, layer])
    return qml.expval(cost_hamiltonian)

The exact observable construction and parameter layout vary between SDK versions. Treat the circuit above as a structural template: prepare the uniform state, apply an edge operation for every problem term, apply the mixer, and return an observable that matches your optimization direction. Check the current SDK documentation before moving from a simulator to a hardware backend. The quantum SDK comparison and migration guide can help when translating the same experiment between Qiskit, Cirq, PennyLane, and Braket.

5. Convert measurements into a decision

After optimization, sample the circuit and count bitstrings. Decode each bitstring using one consistent qubit-to-variable convention, evaluate it with the classical cut_value function, and retain both the most frequent result and the best result observed. They are not always the same.

For a maximization problem, a simple approximation ratio is:

approximation_ratio = best_quantum_value / best_known_value

Use the best known value from an exact solver for small instances or a documented heuristic for larger ones. Label the denominator clearly. If it is only a heuristic result, the ratio is relative to that reference, not a proof of closeness to the global optimum.

Inputs and assumptions

QAOA outcomes depend on experimental choices as much as on the graph or objective. Record the following inputs so that another run can be compared fairly.

InputPractical choiceWhat changes
Problem instanceGraph, weights, constraints, and variable orderingDefines the Hamiltonian and the classical score
InitializationRandom, small random, or problem-informed anglesCan affect local optima and run-to-run variation
Depth pBegin with a small value, then increase deliberatelyExpressivity, circuit depth, optimizer difficulty, and noise exposure
OptimizerGradient-based or gradient-free methodEvaluation count, sensitivity to shot noise, and convergence behavior
ShotsMore shots for stable estimates; fewer for quick iterationMeasurement uncertainty and sampling cost
BackendExact simulator, shot-based simulator, or hardwareNoise, runtime, supported gates, and reproducibility

For initial development, an exact statevector simulator can expose encoding mistakes without measurement noise. A shot-based simulator is a better test of sampling behavior, and a noisy simulator can reveal whether a promising circuit survives realistic imperfections. See the quantum simulator selection guide for a fuller comparison of simulator methods.

Common failure modes include optimizing the wrong sign, reversing bit order during decoding, omitting an edge term, using too few shots to distinguish close candidates, and comparing a quantum result with an unfair classical baseline. Add unit tests for the classical objective and Hamiltonian terms before tuning parameters; the quantum circuit testing guide provides useful patterns.

Worked examples

A small MaxCut experiment

Consider a four-vertex graph with edges (0,1), (1,2), (2,3), (3,0), and (0,2). Use four qubits, start with p = 1, and evaluate a small set of parameter initializations. For every run:

  1. Build the cost Hamiltonian from the five edges.
  2. Initialize all qubits with Hadamard gates.
  3. Apply one cost layer and one X-mixer layer.
  4. Optimize gamma and beta against the chosen expectation-value convention.
  5. Sample the optimized circuit and score every returned bitstring classically.

Suppose the classical reference finds a cut value of 5 and the best sampled QAOA bitstring also scores 5. Report the best-known value, the best sampled value, and an approximation ratio of 1.0 for that run. Also report the probability or count of that bitstring, because a correct answer that appears rarely may be less useful than a slightly lower-scoring answer that is sampled consistently.

Next, repeat the experiment with p = 2, the same graph, and the same shot budget. Do not interpret a different result as evidence that greater depth is always better. Compare objective evaluations, convergence across several initializations, the distribution of scores, and circuit resource estimates. If the deeper circuit improves the noiseless expectation but performs worse under noise, that trade-off is itself an important result.

Parameter and method comparison

A compact experiment matrix makes QAOA parameter optimization easier to audit:

ConfigurationRecommended useTypical risk
Small random angles, low pFast baseline and circuit validationVariation between initializations
Warm-start angles from a lower-depth runTesting a deeper circuitInherited parameters may not suit the new landscape
Gradient-based optimizationHigh-quality simulator experiments with differentiable circuitsShot noise or flat gradients can reduce stability
Gradient-free optimizationHardware-oriented or noisy objective evaluationsMay require many circuit evaluations
Low shot budgetRapid prototypingNoisy objective estimates and unstable rankings
Higher shot budgetFinal comparison of close candidatesGreater execution cost and longer experiments

Use repeated seeds and preserve raw counts rather than saving only the winning score. A small result log containing graph ID, SDK version, backend, depth, optimizer, initialization seed, shots, final parameters, best bitstring, and objective values will make later comparisons much more reliable.

When to recalculate

Re-run the QAOA workflow whenever an input that affects interpretation changes. That includes the graph or weights, constraint encoding, circuit depth, parameter initialization, optimizer, shot budget, SDK implementation, transpilation settings, simulator model, or hardware backend. A result from one depth or backend should not be treated as a transferable result for another.

For a practical refresh, use this checklist:

  • Verify the classical objective on known bitstrings, including complementary assignments where applicable.
  • Check that Hamiltonian signs, constant offsets, qubit ordering, and measurement decoding agree.
  • Run a noiseless or exact reference before introducing shot noise or hardware noise.
  • Evaluate multiple parameter seeds and retain the full score distribution.
  • Compare the best sampled value and sampling frequency with a clearly described classical baseline.
  • Repeat the final candidate with a larger shot budget before drawing a conclusion.
  • Record software and backend details so the experiment can be reproduced after framework updates.

QAOA is most useful as a disciplined experiment rather than a single circuit run. Start with a small, testable instance, establish a classical reference, vary one resource at a time, and report both solution quality and execution cost. That approach turns a QAOA Python tutorial into a reusable quantum optimization workflow for new problem instances.

Related Topics

#QAOA#quantum algorithms#quantum optimization#Qiskit#PennyLane#Python
U

Upqubit Editorial Team

Quantum Computing Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.