Skip to main content

08 - QAOA for Combinatorial Optimization

QAOA on a six-node MaxCut simulated in numpy: the ratio to the optimum rises from 0.85 to 0.98 for p from 1 to 3, and what this does not prove.

What do you think about this article?

08 - QAOA for Combinatorial Optimization
Quantum Computingfedericocalo.dev

At a Glance

QAOA on a six-node MaxCut simulated in numpy: the ratio to the optimum rises from 0.85 to 0.98 for p from 1 to 3, and what this does not prove.

You have six nodes connected by nine edges and you want to split them into two groups so that as many edges as possible join nodes of different groups. This is the MaxCut problem, and it serves as a test bench because it is easy to state, hard in general and directly translatable into a Hamiltonian. The Quantum Approximate Optimization Algorithm (QAOA) tries to tackle it with a circuit of p layers and 2p parameters: a VQE with a fixed ansatz, in which the Hamiltonian to minimise, or maximise, is the value of the cut. It answers a precise question: given a depth budget p, what quality of solution do you get?

The answer in this article comes from a numpy simulator that you can rerun: on the chosen graph the quality rises with p, from about 85% of the optimum to about 98%. But on six nodes the enumeration of all 64 assignments is instantaneous, so the result tells you how the algorithm behaves, not that it beats anyone. You need the variational circuits of article 07, of which QAOA is a variant; article 05 on Grover is the other quantum way to search for a maximum, with a different theoretical guarantee.

The problem: the maximum cut of a triangular prism

The graph is a prism: two triangles (nodes 0-1-2 and 3-4-5) joined by three vertical edges (0-3, 1-4, 2-5). Assigning a bit to each node says which group it belongs to, and an edge is "cut" if its two endpoints have different bits. A triangle cannot be cut entirely, because with three nodes and two groups at least two nodes stay together; so each triangle loses at least one edge, and the maximum is 9 minus 2, that is 7. The enumeration in the listing confirms it. A random assignment cuts on average half of the edges, 4.5, which is the floor against which to measure.

The function taglio(z) counts the edges with different endpoints and C is the vector of the 64 possible values. In quantum terms C is the diagonal of the cost Hamiltonian: the state |z⟩ has energy C[z], and QAOA looks for a state in which the assignments with high C have high probability.

The layers: cost phase and mixing

You start from the uniform superposition |+⟩^n, in which every assignment has the same probability. Each layer applies two operations. The first, exp(-iγC), is diagonal: it multiplies each |z⟩ by a phase that depends on its cut, and by itself it changes no probability. The second, exp(-iβ ΣX), rotates each qubit around X and makes neighbouring assignments interfere: it is the interference, after the phase, that moves probability toward the large cuts. The two operations alternate p times, and the two angles of each layer are the parameters that the classical optimiser has to find.

In the listing stato builds |ψ(γ, β)⟩. The line with np.exp(-1j * gamma * C) is the phase layer. The loop over the qubits applies the rotation RX(2β) by rearranging the vector as a tensor with one index per qubit, with np.take to separate the 0 and 1 components of that qubit. attesa returns the mean value of the cut. In __main__ the maximum of ⟨C⟩ is searched, for p from 1 to 3, with BFGS from 30 random starts (fixed seed), and the listing also reports the total probability of the assignments with cut 7 and how many starts reached the maximum. If you removed the phase layer and kept the mixer, the state would remain |+⟩^n and the distribution would be uniform.

import itertools
import numpy as np
from scipy.optimize import minimize

N = 6
ARCHI = [(0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (5, 3), (0, 3), (1, 4), (2, 5)]   # triangular prism

def taglio(z):
    """Cut value for the assignment z (one bit per node)."""
    return sum(1 for u, v in ARCHI if (z >> u & 1) != (z >> v & 1))

C = np.array([taglio(z) for z in range(2**N)], dtype=float)   # diagonal of the cost Hamiltonian

def stato(params):
    """|psi(gamma, beta)>: p layers of exp(-i*gamma*C) and of the mixer exp(-i*beta*sum X)."""
    p = len(params) // 2
    psi = np.full(2**N, 2 ** (-N / 2), dtype=complex)         # |+>^N
    for gamma, beta in zip(params[:p], params[p:]):
        psi = psi * np.exp(-1j * gamma * C)                    # phases: diagonal cost
        t = psi.reshape([2] * N)
        c, s = np.cos(beta), -1j * np.sin(beta)
        for q in range(N):                                     # RX(2*beta) on every qubit
            a, b = np.take(t, 0, axis=q), np.take(t, 1, axis=q)
            t = np.stack([c * a + s * b, s * a + c * b], axis=q)
        psi = t.reshape(-1)
    return psi

def attesa(params):
    return float((np.abs(stato(params)) ** 2 @ C))

if __name__ == "__main__":
    ottimo = C.max()
    print(f"edges={len(ARCHI)}  maximum cut (enumeration)={ottimo:.0f}  mean cut of a random assignment={C.mean():.2f}")
    rng = np.random.default_rng(11)
    for p in (1, 2, 3):
        migliore, valori = None, []
        for _ in range(30):                                    # 30 random starts with a fixed seed
            x0 = rng.uniform(0, np.pi, 2 * p)
            r = minimize(lambda x: -attesa(x), x0, method="BFGS")
            valori.append(-r.fun)
            if migliore is None or r.fun < migliore.fun:
                migliore = r
        arrivate = sum(v > max(valori) - 1e-4 for v in valori)
        prob = np.abs(stato(migliore.x)) ** 2
        p_ott = prob[C == ottimo].sum()
        print(f"p={p}: <C>={-migliore.fun:.4f}  ratio={-migliore.fun / ottimo:.4f}  "
              f"P(optimal cut)={p_ott:.3f}  evaluations of the best start={migliore.nfev}  "
              f"starts that reached the maximum: {arrivate}/30")

# Output:
# edges=9  maximum cut (enumeration)=7  mean cut of a random assignment=4.50
# p=1: <C>=5.9392  ratio=0.8485  P(optimal cut)=0.401  evaluations of the best start=39  starts that reached the maximum: 28/30
# p=2: <C>=6.6029  ratio=0.9433  P(optimal cut)=0.721  evaluations of the best start=125  starts that reached the maximum: 8/30
# p=3: <C>=6.8780  ratio=0.9826  P(optimal cut)=0.923  evaluations of the best start=161  starts that reached the maximum: 10/30

With p = 1 the mean value is 5.94 out of a maximum of 7, that is a ratio of 0.8485, and it is already above the 4.5 of chance. With each added layer the ratio grows (0.9433 for p = 2, 0.9826 for p = 3) and the probability of drawing an optimal cut goes from about 40% to 72% to 92%. The ratio rises because each layer gives the ansatz more parameters with which to concentrate the probability. The cost is twofold: a deeper circuit, and a longer optimisation, as the last column shows, where the best start required 39, 125 and 161 evaluations of the function. On a processor each evaluation requires many measurement shots, as in the previous article.

The mean value is not what you read from the device: QAOA produces a distribution of assignments, and the result of the algorithm is the best among those sampled. This is why the probability of an optimal cut matters more than the mean ratio: with 40% per shot, a handful of shots is enough to see a cut of 7.

A second calculation: the closed formula for p = 1

For p = 1 the mean value can be computed without simulating the state. Wang and collaborators derive an analytical expression for any graph, a sum over the edges of a term that depends on the degrees of the two endpoints and on the number of triangles that contain the edge. The listing implements it and compares it with the simulator on 1000 random pairs of angles. The prism is a good test bench: the edges of the triangles have λ = 1, the vertical edges λ = 0, so both branches of the formula are exercised. The formula in the listing is the one from the cited paper; the comparison with the simulator verifies it numerically, but it is not a derivation.

import numpy as np
from qaoa import ARCHI, attesa

def grado(nodo):
    return sum(nodo in e for e in ARCHI)

def triangoli(u, v):
    return sum(1 for w in range(6) if w not in (u, v) and {(u, w), (w, u)} & set(ARCHI) and {(v, w), (w, v)} & set(ARCHI))

def attesa_formula(gamma, beta):
    """<C> for p=1 as a sum over the edges of the closed formula (nodes of degree d, lambda triangles on the edge)."""
    tot = 0.0
    for u, v in ARCHI:
        du, dv, lam = grado(u) - 1, grado(v) - 1, triangoli(u, v)
        tot += (0.5 + 0.25 * np.sin(4 * beta) * np.sin(gamma) * (np.cos(gamma) ** du + np.cos(gamma) ** dv)
                - 0.25 * np.sin(2 * beta) ** 2 * np.cos(gamma) ** (du + dv - 2 * lam) * (1 - np.cos(2 * gamma) ** lam))
    return tot

rng = np.random.default_rng(5)
scarto = 0.0
for _ in range(1000):
    g, b = rng.uniform(-np.pi, np.pi, 2)
    scarto = max(scarto, abs(attesa([g, b]) - attesa_formula(g, b)))
print("1000 random (gamma, beta) pairs: simulator and formula agree within 1e-9:", bool(scarto < 1e-9))

griglia = np.linspace(0, np.pi, 181)
best = max((attesa_formula(g, b), g, b) for g in griglia for b in griglia)
print(f"maximum of the formula on a 181x181 grid: <C>={best[0]:.4f} (optimised p=1 simulator: 5.9392)")

# Output:
# 1000 random (gamma, beta) pairs: simulator and formula agree within 1e-9: True
# maximum of the formula on a 181x181 grid: <C>=5.9391 (optimised p=1 simulator: 5.9392)

The two routes coincide to within 10-9 on all 1000 pairs, and the maximum of the formula on a grid of 181 × 181 angles (5.9391) is practically that of the optimiser (5.9392), the difference being due to the grid step. The advantage of the formula is also its limit: it exists for p = 1, and already for p = 2 the number of terms becomes unmanageable, as the authors themselves observe in the abstract. For larger p you go back to simulation, which costs exponential memory: a vector of n qubits takes 2^n complex numbers of 16 bytes, so 16 GiB already at 30 qubits.

What the theory guarantees, and what it does not

Farhi, Goldstone and Gutmann, who proposed the algorithm, state in the abstract that for p = 1 on 3-regular graphs (every node has three edges, as in the prism) QAOA finds a cut at least 0.6924 times the optimum. It is a worst-case guarantee: our 0.8485 respects it with a wide margin, which is consistent, but does not prove it. On the classical side, Goemans and Williamson showed in 1995 a randomised polynomial-time algorithm with expected value at least 0.87856 times the optimum, for any graph. So the honest comparison is not between 0.8485 and 0.87856: the first figure concerns a six-node graph with p = 1, the second is a guarantee on any graph.

To claim that QAOA beats a classical solver, several things would be needed together, and an experiment of this kind does not have them:

  • instances large enough that they are not solved by enumeration or by a good local heuristic;
  • a comparison with the best known classical method, not with the random assignment;
  • a budget measured in total computing time, including the optimiser's evaluations and the measurement shots;
  • a run on noisy hardware, not on a perfect simulator.

All four conditions must be met, not one of your choosing: it takes only one missing for a result to say more than it proves. Farhi's abstract also fixes another measure of cost, the circuit depth, which grows linearly with p times the number of constraints in the worst case, and so on a noisy device a large p is ruled out even before the optimiser becomes a problem.

What can go wrong

Three reproducible traps can be drawn from the listing. The first is the optimiser: with p = 1 28 starts out of 30 reach the same maximum, with p = 2 only 8 out of 30 and with p = 3 10 out of 30, so the landscape of ⟨C⟩ has local maxima and a single start may stop on a poor one. The "maximum" reported is also only the best found in 30 trials, not a proven global maximum; on hardware each start would be paid for in shots. Wang and collaborators observe that as p grows the optimisation of the parameters becomes inefficient because of the curse of dimensionality. The second is the reading of the result: counting the mean instead of the best sample undervalues the algorithm, and counting the best of a few shots on a small graph overvalues it. The third is the choice of the baseline: the average case of 4.5 is too generous a comparison.

What you can do now

You can write the cost Hamiltonian of a MaxCut, build the QAOA layers and simulate them, and evaluate the quality with the approximation ratio and with the probability of the optimal cut. You can check a result with an independent closed formula and read a theoretical guarantee distinguishing the worst case from the single graph. You can also list what is missing for a comparison with a classical solver to hold. The next article leaves optimisation and uses the same parametrised circuits for learning: quantum machine learning. The complete sequence is on the series page.

Frequently asked questions

What does QAOA do?

It looks for approximate solutions of combinatorial optimisation problems, such as MaxCut, with a circuit of p layers that alternate a phase tied to the cost function and a mixing step, with angles chosen by a classical optimiser.

What does the parameter p of QAOA indicate?

The number of layers, hence the circuit depth and the number of angles, which are 2p. In the example of this article the ratio between the mean cut and the optimum goes from 0.85 to 0.94 to 0.98 for p from 1 to 3.

Does QAOA beat classical algorithms?

It has not been shown. On small graphs enumeration finds the optimum instantly, and for MaxCut there is a classical polynomial-time algorithm with a guarantee of 0.87856 on the expected value of the cut.

Sources

The two listings were run twice with Python 3.14, numpy 2.5.4 and scipy 1.18.1, with identical outputs (fixed seed, 30 random starts). The outputs reported are the real ones. The simulator does not include hardware noise.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects