Use this file to discover all available pages before exploring further.
View on GitHub
Open this notebook in GitHub to run it yourself
The Variational Quantum Linear Solver (VQLS) is a quantum algorithm that harnesses the power of Variational Quantum Eigensolvers (VQE) to solve systems of linear equations efficiently:
Input: A matrix A and a known vector ∣b⟩.
Output: An approximation of a normalized solution ∣x⟩ proportional to ∣x⟩, satisfying the equation A∣x⟩=∣b⟩.
While the output of VQLS mirrors that of the HHL Quantum Linear-Solving Algorithm, VQLS distinguishes itself by its ability to operate on Noisy Intermediate-Scale Quantum (NISQ) computers. In contrast, HHL necessitates more robust quantum hardware and a larger qubit count, despite offering a faster computation speedup.This tutorial covers an implementation example of a Variational Quantum Linear Solver [1] using block encoding. In particular, we use linear combinations of unitaries (LCUs) for the block encoding.As with all variational algorithms, the VQLS is a hybrid algorithm in which we apply a classical optimization on the results of a parametrized (ansatz) quantum program.
Given a block encoding of the matrix A:U=[A⋅⋅⋅](1)we can prepare the state∣Ψ⟩:=A∣x⟩/⟨x∣A†A∣x⟩.We can approximate the solution ∣x⟩ with a variational quantum
circuit, i.e., a unitary circuit V, depending on a finite number of classical real parameters w=(w0,w1,…):∣x⟩=V(w)∣0⟩.Our objective is to address the task of preparing a quantum state ∣x⟩ such that A∣x⟩ is proportional to ∣b⟩; or, equivalently, ensuring that∣Ψ⟩:=⟨x∣A†A∣x⟩A∣x⟩≈∣b⟩.The state ∣b⟩ arises from a unitary operation Ub applied to the ground state of n qubits; i.e.,∣b⟩=Ub∣0⟩.To maximize the overlap between the quantum states ∣Ψ⟩ and ∣b⟩, we optimize the parameters, defining a cost function:C=1−∣⟨b∣Ψ⟩∣2.At a high level, the above could be implemented as follows:We construct a quantum model as depicted in the figure below.When measuring the circuit in the computational basis, the probability of
finding the system qubits in the ground state (given the ancillary qubits measured
in their ground state) is
∣⟨0∣Ub†∣Ψ⟩∣2=∣⟨b∣Ψ⟩∣2.To block encode a Variational Quantum Linear Solver as explained above, we can define a high-level block_encoding_vqls function as follows:
from typing import Listimport numpy as npfrom classiq import *
From here, we only need to define ansatz, block_encoding, and prepare_b_state to fit the specific example above.Now we are ready to build our model, synthesize it, execute it, and analyze the results.
To estimate the overlap of the ground state with the post-selected
state, we could directly make use of the measurement samples. However,
since we want to optimize the cost function, it is useful to express
everything in terms of expectation values through Bayes’ theorem:∣⟨b∣Ψ⟩∣2=P(sys=ground∣anc=ground)=P(all=ground)/P(anc=ground)To evaluate the conditional probability from the above equation, we construct the following utility function to operate on the measurement results:To variationally solve our linear problem, we define the
cost function C=1−∣⟨b∣Ψ⟩∣2 that we are going to
minimize. As explained above, we express it in terms of expectation
values through Bayes’ theorem.We define a classical function that gets the quantum program, minimizes the cost function using the COBYLA optimizer, and returns the optimal parameters.
import randomimport matplotlib.pyplot as pltfrom scipy.optimize import minimizeclass VqlsOptimizer: def __init__( self, qprog, ansatz_param_count, ansatz_var_name, aux_var_name, exe_prefs=None ): self.qprog = qprog self.ansatz_param_count = ansatz_param_count self.ansatz_var_name = ansatz_var_name self.aux_var_name = aux_var_name if exe_prefs is None: self.es = ExecutionSession(qprog) else: self.es = ExecutionSession(qprog, exe_prefs) self.intermediate = {} def get_cond_prop(self, res): aux_prob_0 = 0 all_prob_0 = 0 for s in res: if s.state[self.aux_var_name] == 0: aux_prob_0 += s.shots if s.state[self.ansatz_var_name] == 0: all_prob_0 = s.shots return all_prob_0 / aux_prob_0 def my_cost(self, params): results = self.es.sample(params) return 1 - self.get_cond_prop( results.parsed_counts_of_outputs([self.ansatz_var_name, self.aux_var_name]) ) def f(self, x): cost = self.my_cost( {"params_" + str(k): x[k] for k in range(self.ansatz_param_count)} ) self.intermediate[tuple(x)] = cost return cost def optimize(self): random.seed(1000) self._out = out = minimize( self.f, x0=[ float(random.randint(0, 3000)) / 1000 for i in range(0, self.ansatz_param_count) ], method="COBYLA", options={"maxiter": 2000}, ) print(out) self._out_f = out_f = [out["x"][0 : self.ansatz_param_count]] print(out_f) plt.plot( [l for l in range(len(self.intermediate))], list(self.intermediate.values()) ) return { "params_" + str(k): list(self.intermediate.keys())[-1][k] for k in range(self.ansatz_param_count) }
Once the optimal variational weights w are found, we
can generate the quantum state ∣x⟩. By measuring ∣x⟩ in
the computational basis we can estimate the probability of each basis
state.
We treat a specific example based on a system of three qubits:A∣b⟩=c0A0+c1A1+c2A2=0.55I+0.225Z1+0.225Z2=Ub∣0⟩=H0H1H2∣0⟩,where Zj,Xj,Hj represent the Pauli Z, Pauli X, and Hadamard
gates applied to the qubit with index j.To block encode the matrix A we use the LCU method.This can be done with the lcu_paulis library function.Note that this function can get a unnormalized Pauli operator, thus we calculate the normalization factor for the post-process analysis.The LCU quantum circuit looks as follows:
Let’s consider our ansatz V(w), such that∣x⟩=V(w)∣0⟩.This allows us to “search” the state space by varying a set of parameters, w.The ansatz that we use for this three-qubit system implementation takes in nine parameters as defined in the apply_fixed_3_qubit_system_ansatz function:
Quantum program link: https://platform.classiq.io/circuit/32pWjH6oUwpzhB9OZFVtHUvCXBA
This is called a fixed hardware ansatz in that the configuration of quantum gates remains the same for each run of the circuit, and all that changes are the parameters.Unlike the QAOA ansatz, it is not composed solely of Trotterized Hamiltonians.The applications of Ry gates allow us to search the state space, while the CZ gates create “interference” between the different qubit states.
with ExecutionSession(qprog_3, execution_preferences) as es: results = es.sample()df = results.dataframe
amplitudes = np.zeros(2**num_system_qubits).astype(complex)amplitudes[df.io] = df.amplitude# Preprocessed quantum solution: we know the solution is real, and that the last point is positiveglobal_phase = np.angle(amplitudes[-1])amplitudes = np.real(amplitudes / np.exp(1j * global_phase))if ( amplitudes[-1] < 0): # we can extract the solution up to a sign, align with the expected amplitudes *= -1print(amplitudes)
Since the specific problem considered in this tutorial has a small size,
we can also solve it in a classical way and then compare the results
with our quantum solution.We use the explicit matrix representation in terms of numerical NumPy arrays.Classical calculation:
To compare the classical to the quantum results we compute the post-processing by applying A to our optimal vector ∣ψ⟩o, normalizing it, then calculating the inner product squared of this vector and the solution vector, ∣b⟩! We can put this all into code as follows: