QAOA for Max-Cut in Practice: From Graph Input to Classical Optimization and Result Checks
QAOAMax-Cutquantum optimizationvariational algorithmsquantum circuitsPython

QAOA for Max-Cut in Practice: From Graph Input to Classical Optimization and Result Checks

SSharp Qbit Lab
2026-11-09
8 min read

Implement QAOA for Max-Cut with Python: prepare the graph, optimize parameters, sample solutions, and validate against a classical baseline.

This practical QAOA Max-Cut tutorial takes you from a small graph to a repeatable experiment: prepare the graph, encode its objective as a cost Hamiltonian, build a parameterized circuit, optimize its angles, sample candidate solutions, and check the result against a classical baseline. The examples use Python-style pseudocode and Qiskit-oriented concepts so you can adapt them to the SDK and execution target you use.

Overview

Max-Cut asks you to divide the vertices of a graph into two groups so that as many edges as possible cross between the groups. A bit string represents a partition: bit 0 places a vertex in one group and bit 1 places it in the other. An edge contributes one point when its endpoint bits differ.

For a graph G = (V, E) and bit string x, the classical objective is:

C(x) = Σ(i,j)∈E [xᵢ ≠ xⱼ]

QAOA, the Quantum Approximate Optimization Algorithm, does not remove the need for classical optimization. It alternates quantum cost and mixer operations, measures candidate bit strings, and uses a classical optimizer to adjust the circuit parameters. The useful unit of work is therefore a hybrid loop:

  1. Build a parameterized circuit from the graph.
  2. Evaluate the circuit for current parameters.
  3. Convert samples into an objective value.
  4. Let a classical optimizer propose new parameters.
  5. Repeat, then validate the best observed bit string.

For a first implementation, use a small graph that you can solve exactly by enumeration. This gives you a trustworthy reference while you debug the quantum circuit and optimization code. QAOA depth is commonly represented by p, the number of cost-and-mixer layers. Start with p = 1 before testing deeper circuits.

How to estimate

Instead of judging a QAOA run by whether it produces one visually attractive bit string, estimate several quantities from the same run. These measurements make results comparable when you change the graph, simulator, shot count, optimizer, or hardware target.

1. Compute the classical reference

For a graph with n vertices, enumerate the 2ⁿ bit strings when n is small. For each string, calculate its cut value. The largest value is the exact optimum for that test graph. You can also retain every optimal string because Max-Cut usually has symmetries: flipping every bit leaves the cut value unchanged.

def cut_value(bits, edges):
    return sum(bits[i] != bits[j] for i, j in edges)

best_value = -1
best_strings = []
for bits in all_bitstrings(number_of_vertices):
    value = cut_value(bits, edges)
    if value > best_value:
        best_value = value
        best_strings = [bits]
    elif value == best_value:
        best_strings.append(bits)

2. Convert samples into an estimated objective

Suppose measurement produces bit strings x₁, x₂, ..., xₘ. The sample-average cut value is:

Ċ = (1/m) Σₖ C(xₖ)

This is usually more informative than only reporting the most frequent string. Also report the best sampled cut value, the frequency of optimal strings, and the probability that a sample reaches the classical optimum when that optimum is known.

3. Track approximation quality

For a graph whose exact optimum is available, calculate:

approximation ratio = best sampled cut value / exact optimum

If the exact optimum is zero, do not divide by it; report the raw values instead. For larger graphs where exact enumeration is impractical, compare with a clearly identified classical heuristic or solver and label the comparison accordingly. A heuristic reference is not automatically a proof of optimality.

4. Estimate sampling uncertainty

Shot-based results fluctuate. If a string appears with frequency k / m, its observed frequency is an estimate, not a fixed probability. Repeat the same experiment with a fixed random seed where supported, or run several independent repetitions and report the spread. Keep the graph, circuit depth, optimizer budget, and shot count fixed when comparing two configurations.

Inputs and assumptions

Keep the problem definition separate from the quantum execution code. This makes it easier to move between a statevector simulator, a shot-based simulator, and real quantum hardware.

Graph input

Represent vertices with consecutive indices from 0 to n - 1. Store each undirected edge once, for example:

edges = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)]

Validate that endpoints are in range and that duplicate edges are handled deliberately. A duplicate can unintentionally give one connection more weight. If your application has weighted edges, replace each contribution with its weight when the endpoint bits differ.

Cost Hamiltonian

Using Pauli-Z eigenvalues, an edge term can be written in a form proportional to (I - ZᵢZⱼ). The constant and scale factor depend on the convention used by your implementation. The important engineering rule is consistency: the Hamiltonian expectation, the sampled bit-string score, and the classical baseline must represent the same Max-Cut objective.

Many SDKs provide an operator or sparse-observable representation for this construction. If you build it manually, map every graph edge to a two-qubit Z-Z term and keep a separate classical scoring function as the final source of truth.

QAOA circuit

Initialize every qubit in the equal superposition state with a Hadamard gate. Each QAOA layer then applies:

  1. A cost unitary whose angle is controlled by γ and the graph edges.
  2. A mixer unitary, usually an X rotation on each qubit, controlled by β.

At p layers, the parameter vector contains p gamma values and p beta values, or an equivalent ordering chosen by the framework. Document that ordering. A large fraction of QAOA debugging errors come from passing parameters in an order different from the circuit's declared order.

Execution assumptions

For local development, begin with an ideal statevector or shot-based simulator. Use the statevector path to inspect probabilities and verify the circuit on tiny graphs, then use finite shots to reproduce the statistics that matter for hardware. Before submitting to hardware, transpile or compile for the target's connectivity and native gates, then record the resulting depth and two-qubit gate count. These values can materially change the experiment.

Worked examples

A five-edge test graph

Consider the graph with edges (0,1), (1,2), (2,3), (3,0), and (0,2). It has four vertices, so exhaustive classical checking is straightforward. One valid partition is represented by 0101. Its cut value is obtained by checking each edge independently; do not assume that a visually alternating string is optimal until the scoring function confirms it.

A practical implementation can expose three functions:

def build_qaoa_circuit(edges, p, parameters):
    # Create n qubits, apply H gates, then p cost/mixer layers.
    # Return the parameterized circuit and its parameter ordering.
    pass

def objective(parameters, edges, shots):
    circuit = build_qaoa_circuit(edges, p, parameters)
    samples = run_sampler(circuit, shots=shots)
    return -average(cut_value(bits, edges) for bits in samples)

result = classical_optimizer(objective, initial_parameters)
final_samples = run_sampler(
    build_qaoa_circuit(edges, p, result.parameters),
    shots=4096
)

The negative sign is used because many classical optimizers minimize. If your optimizer maximizes, return the average cut value directly. The sampler interface and optimizer names differ between Qiskit releases and other frameworks, so treat the calls above as a stable workflow rather than a promise of unchanged import syntax. Pin your environment and check the installed SDK documentation before copying provider-specific code.

What to report

For this graph, report the exact classical optimum, the best bit string found by QAOA, its cut value, the sample-average cut value, and the frequency of strings reaching the optimum. Include p, shots, optimizer name, initialization method, number of objective evaluations, simulator or hardware target, and whether the displayed bit strings use the framework's little-endian or big-endian convention.

A compact results table might look like this:

graph_edges: 5
vertices: 4
qaoa_depth_p: 1
shots: 4096
exact_optimum: [fill from enumeration]
best_sampled_value: [fill from samples]
mean_sampled_value: [fill from samples]
optimal_sample_probability: [count / shots]
execution_target: [simulator or hardware name]
transpiled_depth: [record after compilation]

Scaling the experiment

After the four-vertex test passes, change one variable at a time: increase p, alter the graph density, change the optimizer, or move from an ideal simulator to noisy execution. Save raw counts rather than only the final score. Raw counts allow you to recalculate the best-string frequency and inspect whether the optimizer is concentrating probability on several near-optimal solutions.

When to recalculate

Recalculate the baseline and QAOA metrics whenever the graph changes, because the optimum and the distribution of near-optimal strings can change even when the circuit code does not. Re-run the full experiment when you change the QAOA depth, parameter initialization, optimizer settings, shot count, noise model, transpilation options, or execution target.

SDK updates are another reason to revisit the implementation. Primitive interfaces, sampler options, parameter binding, backend names, and transpilation behavior can change across releases. Keep a small regression test that checks: the graph has the expected number of qubits, the classical scorer returns known values, the circuit contains the expected parameter count, and an ideal small-graph run can reach a known optimum. Consult this guide to testing quantum programs for a broader validation pattern.

Before comparing hardware results, record queue or execution conditions only when they affect reproducibility, and separate algorithmic changes from noise-suppression changes. Readout mitigation and zero-noise extrapolation may improve an estimate, but they introduce their own assumptions; document whether results are raw or mitigated. See the practical discussion of quantum error mitigation techniques.

Finally, use this checklist before treating a run as successful:

  • Does the classical scorer agree with manually checked bit strings?
  • Does the Hamiltonian convention match the cut-value convention?
  • Are parameter names and ordering passed correctly?
  • Was the bit-order convention checked after measurement?
  • Was the QAOA result compared with an exact or clearly labeled classical baseline?
  • Were shots, depth, optimizer evaluations, and execution target recorded?
  • Were raw counts retained for later analysis?

Once these checks pass, the workflow is reusable: replace the edge list, recompute the classical reference when feasible, rerun the same measurement pipeline, and compare results under explicitly matched assumptions. That discipline is more valuable than a single impressive-looking bit string because it turns a QAOA demonstration into a testable quantum programming experiment.

Related Topics

#QAOA#Max-Cut#quantum optimization#variational algorithms#quantum circuits#Python
S

Sharp Qbit Lab

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.