Usage estimate: 8 minutes on IBM Sherbrooke (NOTE: This is an estimate only. Your runtime may vary.)
BackgroundThis tutorial demonstrates how to implement the Quantum Approximate Optimization Algorithm (QAOA) – a hybrid (quantum-classical) iterative method – within the context of Qiskit patterns. You will first solve the Maximum-Cut (or Max-Cut) problem for a small graph and then learn how to execute it at utility scale. All the hardware executions in the notebook should run within the time limit for the freely-accessible Open Plan.
The Max-Cut problem is an optimization problem that is hard to solve (more specifically, it is an NP-hard problem) with a number of different applications in clustering, network science, and statistical physics. This tutorial considers a graph of nodes connected by vertices, and aims to partition it into separate graphs such that they are both as large as possible. Put another way, the goal of this problem is to partition the nodes of a graph into two sets such that the number of edges traversed by this cut is maximized.
RequirementsBefore starting this tutorial, be sure you have the following installed:
pip install 'qiskit[visualization]'
)pip install qiskit-ibm-runtime
)pip install rustworkx
)The first part of this tutorial uses a small-scale Max-Cut problem to illustrate the steps to solve an optimization problem using a quantum computer.
To give some context before mapping this problem to a quantum algorithm, you can better understand how the Max-Cut problem becomes a classical combinatorial optimization problem by first considering the minimization of a function f ( x ) f(x) f(x)
min x ∈ { 0 , 1 }n f ( x ) , \min_{x\in \{0, 1\}^n}f(x), x∈{0,1}nminf(x),where the input x x x is a vector whose components correspond to each node of a graph. Then, constrain each of these components to be either 0 0 0 or 1 1 1 (which represent being included or not included in the cut). This small-scale example case uses a graph with n = 5 n=5 n=5 nodes.
You could write a function of a pair of nodes i , j i,j i,j which indicates whether the corresponding edge ( i , j ) (i,j) (i,j) is in the cut. For example, the function x i + x j − 2 x i x j x_i + x_j - 2 x_i x_j xi+xj−2xixj is 1 only if one of either x i x_i xi or x j x_j xj are 1 (which means that the edge is in the cut) and zero otherwise. The problem of maximizing the edges in the cut can be formulated as
max x ∈ { 0 , 1 }n ∑ ( i , j ) x i + x j − 2 x i x j , \max_{x\in \{0, 1\}^n} \sum_{(i,j)} x_i + x_j - 2 x_i x_j, x∈{0,1}nmax(i,j)∑xi+xj−2xixj,which can be rewritten as a minimization of the form
min x ∈ { 0 , 1 }n ∑ ( i , j ) 2 x i x j − x i − x j . \min_{x\in \{0, 1\}^n} \sum_{(i,j)} 2 x_i x_j - x_i - x_j. x∈{0,1}nmin(i,j)∑2xixj−xi−xj.The minimum of f ( x ) f(x) f(x) in this case is when the number of edges traversed by the cut is maximal. As you can see, there is nothing relating to quantum computing yet. You need to reformulate this problem into something that a quantum computer can understand.
Initialize your problem by creating a graph with n = 5 n=5 n=5 nodes.
Output:
Step 1: Map classical inputs to a quantum problemThe first step of the pattern is to map the classical problem (graph) into quantum circuits and operators. To do this, there are three main steps to take:
Note: In the QAOA methodology, you ultimately want to have an operator (Hamiltonian) that represents the cost function of our hybrid algorithm, as well as a parametrized circuit (Ansatz) that represents quantum states with candidate solutions to the problem. You can sample from these candidate states and then evaluate them using the cost function.
Graph → optimization problemThe first step of the mapping is a notation change, The following expresses the problem in QUBO notation:
min x ∈ { 0 , 1 }n xT Q x , \min_{x\in \{0, 1\}^n}x^T Q x, x∈{0,1}nminxTQx,where Q Q Q is a n × n n\times n n×n matrix of real numbers, n n n corresponds to the number of nodes in your graph, x x x is the vector of binary variables introduced above, and xT x^T xT indicates the transpose of the vector x x x.
Optimization problem → HamiltonianYou can then reformulate the QUBO problem as a Hamiltonian (here, a matrix that represents the energy of a system):
H C = ∑ i j Q i j Z i Z j + ∑ i b i Z i . H_C=\sum_{ij}Q_{ij}Z_iZ_j + \sum_i b_iZ_i. HC=ij∑QijZiZj+i∑biZi.Reformulation steps from the QAOA problem to the Hamiltonian
To demonstrate how the QAOA problem can be rewritten in this way, first replace the binary variables x i x_i xi to a new set of variables z i ∈ { − 1 , 1 } z_i\in\{-1, 1\} zi∈{−1,1} via
x i = 1 − z i 2 . x_i = \frac{1-z_i}{2}. xi=21−zi.Here you can see that if x i x_i xi is 0 0 0, then z i z_i zi must be 1 1 1. When the x i x_i xi's are substituted for the z i z_i zi's in the optimization problem ( xT Q x x^TQx xTQx), an equivalent formulation can be obtained.
xT Q x = ∑ i j Q i j x i x j = 1 4 ∑ i j Q i j ( 1 − z i ) ( 1 − z j ) = 1 4 ∑ i j Q i j z i z j − 1 4 ∑ i j ( Q i j + Q j i ) z i + n2 4 . x^TQx=\sum_{ij}Q_{ij}x_ix_j \\ =\frac{1}{4}\sum_{ij}Q_{ij}(1-z_i)(1-z_j) \\=\frac{1}{4}\sum_{ij}Q_{ij}z_iz_j-\frac{1}{4}\sum_{ij}(Q_{ij}+Q_{ji})z_i + \frac{n^2}{4}. xTQx=ij∑Qijxixj=41ij∑Qij(1−zi)(1−zj)=41ij∑Qijzizj−41ij∑(Qij+Qji)zi+4n2.Now if we define b i = − ∑ j ( Q i j + Q j i ) b_i=-\sum_{j}(Q_{ij}+Q_{ji}) bi=−∑j(Qij+Qji), remove the prefactor, and the constant n2 n^2 n2 term, we arrive at the two equivalent formulations of the same optimization problem.
min x ∈ { 0 , 1 }n xT Q x ⟺ min z ∈ { − 1 , 1 }n zT Q z + bT z \min_{x\in\{0,1\}^n} x^TQx\Longleftrightarrow \min_{z\in\{-1,1\}^n}z^TQz + b^Tz x∈{0,1}nminxTQx⟺z∈{−1,1}nminzTQz+bTzHere, b b b depends on Q Q Q. Note that to obtain zT Q z + bT z z^TQz + b^Tz zTQz+bTz we dropped the factor of 1/4 and a constant offset of n2 n^2 n2 which do not play a role in the optimization.
Now, to obtain a quantum formulation of the problem, promote the z i z_i zi variables to a Pauli Z Z Z matrix, such as a 2 × 2 2\times 2 2×2 matrix of the form
Z i = ( 1 0 0 − 1 ) . Z_i = \begin{pmatrix}1 & 0 \\ 0 & -1\end{pmatrix}. Zi=(100−1).When you substitute these matrices in the optimization problem above, you obtain the following Hamiltonian
H C = ∑ i j Q i j Z i Z j + ∑ i b i Z i . H_C=\sum_{ij}Q_{ij}Z_iZ_j + \sum_i b_iZ_i. HC=ij∑QijZiZj+i∑biZi.Also recall that the Z Z Z matrices are embedded in the quantum computer's computational space, i.e., a Hilbert space of size 2n × 2n 2^n\times 2^n 2n×2n. Therefore, you should understand terms such as Z i Z j Z_iZ_j ZiZj as the tensor product Z i ⊗ Z j Z_i\otimes Z_j Zi⊗Zj embedded in the 2n × 2n 2^n\times 2^n 2n×2n Hilbert space. For example, in a problem with five decision variables the term Z 1 Z 3 Z_1Z_3 Z1Z3 is understood to mean I ⊗ Z 3 ⊗ I ⊗ Z 1 ⊗ I I\otimes Z_3\otimes I\otimes Z_1\otimes I I⊗Z3⊗I⊗Z1⊗I where I I I is the 2 × 2 2\times 2 2×2 identity matrix.
This Hamiltonian is called the cost function Hamiltonian. It has the property that its ground state corresponds to the solution that minimizes the cost function f ( x ) f(x) f(x). Therefore, to solve your optimization problem you now need to prepare the ground state of H C H_C HC (or a state with a high overlap with it) on the quantum computer. Then, sampling from this state will, with a high probability, yield the solution to m i n f ( x ) min~f(x) min f(x).
Now let us consider the Hamiltonian H C H_C HC for the Max-Cut problem. Let each vertex of the graph be associated with a qubit in state ∣ 0 ⟩ |0\rangle ∣0⟩ or ∣ 1 ⟩ |1\rangle ∣1⟩, where the value denotes the set the vertex is in. The goal of the problem is to maximize the number of edges ( v 1 , v 2 ) (v_1, v_2) (v1,v2) for which v 1 = ∣ 0 ⟩ v_1 = |0\rangle v1=∣0⟩ and v 2 = ∣ 1 ⟩ v_2 = |1\rangle v2=∣1⟩, or vice-versa. If we associate the Z Z Z operator with each qubit, where
Z ∣ 0 ⟩ = ∣ 0 ⟩ Z ∣ 1 ⟩ = − ∣ 1 ⟩ Z|0\rangle = |0\rangle \qquad Z|1\rangle = -|1\rangle Z∣0⟩=∣0⟩Z∣1⟩=−∣1⟩then an edge ( v 1 , v 2 ) (v_1, v_2) (v1,v2) belongs to the cut if the eigenvalue of ( Z 1 ∣ v 1 ⟩ ) ⋅ ( Z 2 ∣ v 2 ⟩ ) = − 1 (Z_1|v_1\rangle) \cdot (Z_2|v_2\rangle) = -1 (Z1∣v1⟩)⋅(Z2∣v2⟩)=−1; in other words, the qubits associated with v 1 v_1 v1 and v 2 v_2 v2 are different. Similarly, ( v 1 , v 2 ) (v_1, v_2) (v1,v2) does not belong to the cut if the eigenvalue of ( Z 1 ∣ v 1 ⟩ ) ⋅ ( Z 2 ∣ v 2 ⟩ ) = 1 (Z_1|v_1\rangle) \cdot (Z_2|v_2\rangle) = 1 (Z1∣v1⟩)⋅(Z2∣v2⟩)=1. Note that, we do not care about the exact qubit state associated with each vertex, rather we care only whether they are same or not across an edge. The Max-Cut problem requires us to find an assignment of the qubits on the vertices such that the eigenvalue of the following Hamiltonian is minimized
H C = ∑ ( i , j ) ∈ e Q i j ⋅ Z i Z j . H_C = \sum_{(i,j) \in e} Q_{ij} \cdot Z_i Z_j. HC=(i,j)∈e∑Qij⋅ZiZj.In other words, b i = 0 b_i = 0 bi=0 for all i i i in the Max-Cut problem. The value of Q i j Q_{ij} Qij denotes the weight of the edge. In this notebook we consider unweighted graph, i.e., Q i j = 1.0 Q_{ij} = 1.0 Qij=1.0 for all i , j i, j i,j.
Output:
Hamiltonian → quantum circuitThe Hamiltonian H C H_C HC contains the quantum definition of your problem. Now you can create a quantum circuit that will help sample good solutions from the quantum computer. The QAOA is inspired by quantum annealing and applies alternating layers of operators in the quantum circuit.
The general idea is to start in the ground state of a known system, H ⊗ n ∣ 0 ⟩ H^{\otimes n}|0\rangle H⊗n∣0⟩ above, and then steer the system into the ground state of the cost operator that you are interested in. This is done by applying the operators exp { − i γ k H C } \exp\{-i\gamma_k H_C\} exp{−iγkHC} and exp { − i β k H m } \exp\{-i\beta_k H_m\} exp{−iβkHm} with angles γ 1 , . . . , γ p \gamma_1,...,\gamma_p γ1,...,γp and β 1 , . . . , β p \beta_1,...,\beta_p~ β1,...,βp .
The quantum circuit that you generate is parametrized by γ i \gamma_i γi and β i \beta_i βi, so you can try out different values of γ i \gamma_i γi and β i \beta_i βi and sample from the resulting state.
In this case, you will try an example with one QAOA layer that contains two parameters: γ 1 \gamma_1 γ1 and β 1 \beta_1 β1.
Output:
Output:
Step 2: Optimize problem for quantum hardware executionThe circuit above contains a series of abstractions useful to think about quantum algorithms, but not possible to run on the hardware. To be able to run on a QPU, the circuit needs to undergo a series of operations that make up the transpilation or circuit optimization step of the pattern.
The Qiskit library offers a series of transpilation passes that cater to a wide range of circuit transformations. You need to make sure that your circuit is optimized for your purpose.
Transpilation may involves several steps, such as:
More information about transpilation is available in our documentation.
The following code transforms and optimizes the abstract circuit into a format that is ready for execution on one of devices accessible through the cloud using the Qiskit IBM Runtime service.
Output:
Step 3: Execute using Qiskit primitivesIn the QAOA workflow, the optimal QAOA parameters are found in an iterative optimization loop, which runs a series of circuit evaluations and uses a classical optimizer to find the optimal β k \beta_k βk and γ k \gamma_k γk parameters. This execution loop is executed via the following steps:
Session
containing the optimization loop and the primitive used to sample the circuitWe start with arbitrary chosen parameters.
Define backend and execution primitiveUse the Qiskit Runtime primitives to interact with IBM® backends. The two primitives are Sampler and Estimator, and the choice of primitive depends on what type of measurement you want to run on the quantum computer. For the minimization of H C H_C HC, use the Estimator since the measurement of the cost function is simply the expectation value of ⟨ H C ⟩ \langle H_C \rangle ⟨HC⟩.
RunThe primitives offer a variety of execution modes to schedule workloads on quantum devices, and a QAOA workflow runs iteratively in a session.
You can plug the sampler-based cost function into the SciPy minimizing routine to find the optimal parameters.
The optimizer was able to reduce the cost and find better parameters for the circuit.
Output:
Once you have found the optimal parameters for the circuit, you can assign these parameters and sample the final distribution obtained with the optimized parameters. Here is where the Sampler primitive should be used since it is the probability distribution of bitstring measurements which correspond to the optimal cut of the graph.
Note: This means preparing a quantum state ψ \psi ψ in the computer and then measuring it. A measurement will collapse the state into a single computational basis state - for example, 010101110000...
- which corresponds to a candidate solution x x x to our initial optimization problem ( max f ( x ) \max f(x) maxf(x) or min f ( x ) \min f(x) minf(x) depending on the task).
Output:
Output:
Step 4: Post-process and return result in desired classical formatThe post-processing step interprets the sampling output to return a solution for your original problem. In this case, you are interested in the bitstring with the highest probability as this determines the optimal cut. The symmetries in the problem allow for four possible solutions, and the sampling process will return one of them with a slightly higher probability, but you can see in the plotted distribution below that four of the bitstrings are distinctively more likely than the rest.
Output:
Output:
Visualize best cutFrom the optimal bit string, you can then visualize this cut on the original graph.
Output:
And calculate the value of the cut
Output:
Part II. scale it up!You have access to many devices with over 100 qubits on IBM Quantum Platform. Select one on which to solve Max-Cut on a 100-node weighted graph. This is a "utility-scale" problem. The steps to build the workflow are followed the same as above, but with a much larger graph.
Output:
Step 1: Map classical inputs to a quantum problem Graph → HamiltonianFirst, convert the graph you want to solve directly into a Hamiltonian that is suited for QAOA.
Output:
Hamiltonian → quantum circuitOutput:
Step 2: Optimize problem for quantum executionTo scale the circuit optimization step to utility-scale problems, you can take advantage of the high performance transpilation strategies introduced in Qiskit SDK v1.0. Other tools include the new transpiler service with AI enhanced transpiler passes.
Output:
Step 3: Execute using Qiskit primitivesTo run QAOA, you must know the optimal parameters γ k \gamma_k γk and β k \beta_k βk to put in the variational circuit. Optimize these parameters by running an optimization loop on the device. The cell submits jobs until the cost function value has converged and the optimal parameters for γ k \gamma_k γk and β k \beta_k βk are determined.
Find candidate solution by running the optimization on the deviceFirst, run the optimization loop for the circuit parameters on a device.
Output:
Once the optimal parameters from running QAOA on the device have been found, assign the parameters to the circuit
Output:
Finally, execute the circuit with the optimal parameters to sample from the corresponding distribution.
Check that the cost minimized in the optimization loop has converged to a certain value.
Output:
Step 4: Post-process and return result in desired classical formatGiven that the likelihood of each solution is low, extract the solution that corresponds to the lowest cost.
Output:
Next, visualize the cut. Nodes of the same color belong to the same group.
Output:
And calculate the the value of the cut
Output:
Now you need to compute the objective value of each sample that you measured on the quantum computer. The sample with the lowest objective value is the solution returned by the quantum computer.
Finally, you can plot the cumulative distribution function to visualize how each sample contributes to the total probability distribution and the corresponding objective value. The horizontal spread shows the range of objective values of the samples in the final distribution. Ideally, you would see that the cumulative distribution function has "jumps" at the lower end of the objective function value axis. This would mean that few solutions with low cost have high probability of being sampled. A smooth, wide curve indicates that each sample is similarly likely, and they can have very different objective values, low or high.
Output:
ConclusionThis tutorial demonstrated how to solve an optimization problem with a quantum computer using the Qiskit patterns framework. The demonstration included a utility-scale example, with circuit sizes that cannot be exactly simulated classically. Currently, quantum computers do not outperform classical computers for combinatorial optimization because of noise. However, the hardware is steadily improving, and new algorithms for quantum computers are continually being developed. Indeed, much of the research working on quantum heuristics for combinatorial optimization is tested with classical simulations that only allow for a small number of qubits, typically around 20 qubits. Now, with larger qubit counts and devices with less noise, researchers will be able to start benchmarking these quantum heuristics at large problem sizes on quantum hardware.
Tutorial surveyPlease take one minute to provide feedback on this tutorial. Your insights will help us improve our content offerings and user experience.
© IBM Corp. 2024
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4