## AWS Quantum Technologies Blog

# Assessing performance of a variational algorithm in presence of noise and quantum error mitigation

Variational algorithms are considered among the leading candidates for finding some of the first useful applications of quantum computing. However, noise in quantum hardware limits the number of operations we can run in a quantum circuit before errors accumulate and invalidate the result.

Quantum error correction techniques will eventually resolve these errors in fault-tolerant quantum computers. But today, we need a practical approach to handle noise on noisy intermediate-scale quantum (NISQ) devices that are available.

In this post, we analyze the performance of the Variational Quantum Eigensolver (VQE) [1], a type of variational quantum algorithm, in the presence of noise. We determine molecular geometry for the trihydrogen cation (*H _{3}^{+}*) as an example case. A PennyLane tutorial and the accompanying paper [2] looking at the optimization of molecular geometries explored this problem using an ideal simulator without noise.

Building on that, we construct a noise model using calibration data from real quantum hardware, in this case IQM’s Garnet device, available on Amazon Braket. We test the *Zero Noise Extrapolation* error mitigation technique using Mitiq, which is an open-source library for quantum error mitigation. Note that the noise model and error mitigation technique demonstrated here are for illustrative purposes only.

## Constructing variational quantum algorithms

Variational algorithms work by combining classical and quantum computing [1]. Typically, the goal of a variational algorithm is to find the lowest energy state (ground state) of a quantum system. This system encodes an objective function related to the underlying problem. Here’s how a variational algorithm works:

- Build a parametrized quantum circuit that represents a guess (ansatz) for the ground state.
- Use a quantum device to compute the value of the objective function for an initial (guessed) value of the parameters of this ansatz.
- Use an optimization algorithm on the classical computer to incrementally improve the values of the parameters of the quantum circuit to gradually lower the energy.
- Repeat steps 2-4 until the algorithm converges to the ground state.

## Determining molecular geometry using variation quantum algorithm

One of the central problems in quantum chemistry is predicting the most stable geometric structure of a molecule, given by the relative spatial locations of its atoms. As discussed in a previous PennyLane blog post about this problem, this can be posed as a quantum variational optimization problem that uses the workflow described above. Essentially, we are looking for the optimal spatial configuration *‘x’* that minimizes the total energy of the molecule, defined as: E(θ, x) = ⟨ψ(θ)|H(x)|ψ(θ)⟩. Here, the state |ψ(θ)⟩ representing the ground state is obtained from a parameterized quantum circuit with parameters θ. H(x) represents the Hamiltonian for a given spatial geometry x. The task is to determine the optimal values of θ and x through joint optimization, considering the energy E(θ, x) as the objective function. In this hybrid quantum-classical workflow, the optimization runs on a classical computer. The objective function computation uses a quantum device from Amazon Braket. Optimization iterations repeat until convergence to find the minimum energy configuration.

In their paper about molecular geometry, Delgao et. al. considered the example of trihydrogen cation H_{3}^{+} which has 3 Hydrogen atoms sharing 2 electrons and one unit of overall positive charge. The equilibrium geometry of H_{3}^{+} is well known to be that of an equilateral triangle with bond angle of 60^{o}, bond length of 0.985 Angstrom, and ground state energy of -1.274 (Ha). References [2, 3] show that the VQE algorithm is successful in determining the correct equilibrium geometry and ground state energy of H_{3}^{+} in absence of noise. For a detailed explanation of implementing this approach and the code used in the noiseless case see reference [2, 3].

In the rest of this blog, we explore how noise present in quantum devices and quantum error mitigation techniques can impact a variational quantum algorithm’s ability to determine the correct molecular geometry. We use the same trihydrogen cation (H_{3}^{+}) example as Delgado et. al. In the next section, we start by building a noise model using Amazon Braket, Amazon Web Services’ (AWS) quantum computing service. Amazon Braket provides access to fully managed and embedded simulators and quantum computers from third-party quantum hardware providers. With these third-party systems available, you can explore real-world noise characteristics and cutting-edge mitigation approaches.

## Noise in quantum computing

Noise can originate from various sources including impurities in device, interaction with the environment, and thermal noise etc. Fortunately, as discussed in a previous AWS blog post about noise in quantum computing, despite their varied origin, noise channels in a quantum devices can largely be represented using Kraus operators and predefined noise channels including bit flip, Pauli channel, amplitude damping, phase flip, qubit depolarization, and qubit dephasing. In this blog post, we analyze the impact of these pre-defined noise channels on the results of VQE algorithm and explore how Zero Noise Extrapolation (ZNE), one of the quantum error mitigation (QEM) techniques, can help mitigate effects of the noise. We use the most up-to-date device calibration parameters from IQM’s Garnet device available on Amazon Braket to determine noise probabilities for each noise channel.

We will use the following AWS services and tools:

- Amazon Braket and its hybrid jobs feature to build the noise model and perform quantum-classical simulations
- PennyLane to define the variational quantum algorithm and perform optimization
- Mitiq library to implement ZNE error mitigation

## Running a variational algorithm using Amazon Braket Hybrid Jobs

Amazon Braket Hybrid Jobs enables you to run hybrid quantum-classical algorithms like the Variational Quantum Eigensolver (VQE) mentioned earlier. These algorithms require frequent communication between classical and quantum resources.

Hybrid Jobs spins up classical compute resources as needed, so you only pay for what you use. It also provides priority access to quantum processing units (QPUs): Once a Hybrid Job instance initiates, it has dedicated access to the third-party QPU until job completion. This priority access is particularly beneficial for iterative hybrid algorithms where subsequent quantum tasks depend on prior results. Examples include the Quantum Approximation Optimization Algorithm (QAOA), Variational Quantum Eigensolver (VQE), and quantum machine learning (QML) workloads. With Hybrid Jobs and priority access to QPUs from you can cost-effectively run advanced quantum algorithms on Amazon Braket.

Let us begin by first running the noiseless simulation with Hybrid Jobs. The code available in references [2, 3] can be wrapped into a function with appropriate hyperparameters as:

` “vqe_noiseless(electrons, charge, symbols, coordinates, device, shots)”`

In the case of *H _{3}^{+} *the hyperparameters take the following values:

`electrons=2, charge=1, symbols = [‘H’, ‘H’, ‘H’], coordinates = “Initial Guess of the x, y and z coordiantes of three atoms in the form of a Python list ”, device=”The simulator or QPU backend used for execution”, and shots=”Number of shots”`

The following code snippet shows how to run the noiseless simulation using `@hybrid_jobs`

decorator on Amazon Braket:

```
import pennylane as qml
from braket.jobs import hybrid_job
@hybrid_job(device="local:braket/braket.local.qubit)
def run_vqe_hybrid_noiseless(electrons, charge, symbols, coordinates, n_qubits, shots):
device = qml.device("braket.local.qubit", wires=n_qubits, shots=shots)
return vqe_noiseless(electrons, charge, symbols, coordinates, device=device, shots=shots)
```

Note that the code snippets given here need various library imports and they are not meant to run just as they are presented here. Refer to the accompanying notebook for a complete code with appropriate imports. The function `run_vqe_hybrid_noiseless()`

above decorated with `@hybrid_job`

is designed to run on the default Braket `LocalSimulator(“braket_sv”)`

which simulates an ideal quantum computer in the State Vector mode. In order to execute it on a different simulator, for example PennyLane’s `lightning.qubit`

simulator, the hybrid jobs decorator can be modified as follows:

```
@hybrid_job(device="local:pennylane/lightning.qubit)
def run_vqe_hybrid_noiseless(electrons, charge, symbols, coordinates, n_qubits, shots):
device = qml.device("lightning.qubit",wires=n_qubits,shots=shots)
return vqe_noiseless(electrons, charge, symbols, coordinates, device=device, shots=shots)
```

The hybrid job instance can now be submitted to run by executing the following command:

`job = run_vqe_hybrid_noiseless(electrons=2, charge=1, symbols=[‘H’, ‘H’, ‘H’], coordinates= [0.028, 0.054, 0.0, 0.986, 0.610, 0.0, 1.855, 0.002, 0.0], n_qubits=6, shots=1000)`

… for 1000 shots. Here we have used a random set of values as initial coordinates.

## Adding noise to the Braket circuit

Let’s now construct a noise model using the latest calibration data from the IQM Garnet device, a third-party quantum computer available through Amazon Braket. Of course, you can choose a different quantum device and build your own noise model. We’re using Garnet’s calibration data as a proof-of-concept example here.

As shown in the following code snippet, we use the `braket.circuits.noises`

module to import predefined single and two-qubit noise channels, and `braket.circuits.noise_model`

to build a noise model on Amazon Braket. Although we’re using calibration data from real quantum hardware, the noise model only approximately represents, rather than exactly replicating, the actual device’s noisy behavior. Nonetheless, we can obtain a qualitative picture and an order-of-magnitude estimate of how noisy execution and error mitigation techniques like Zero Noise Extrapolation affect the results when running hybrid quantum algorithms on Amazon Braket.

With access to real quantum systems through Amazon Braket and support for error mitigation, you can explore the frontiers of quantum computing while accounting for real-world noise:

```
from braket.aws import AwsDevice
from pennylane import numpy as np
from braket.circuits import Circuit, Gate
from braket.devices import Devices, LocalSimulator
from braket.circuits.noise_model import GateCriteria, NoiseModel, ObservableCriteria
from braket.circuits.noises import AmplitudeDamping, BitFlip, Depolarizing, PhaseDamping, TwoQubitDepolarizing
# Import Garnet's caliberation data
garnet = AwsDevice(Devices.IQM.Garnet)
one_qubit_specs = garnet.properties.dict()['provider']['properties']['one_qubit']
two_qubit_specs = garnet.properties.dict()['provider']['properties']['two_qubit']
# Instantiate a Noise Model
noise_model = NoiseModel()
# Implement single qubit noise
for key, specs in one_qubit_specs.items():
i = int(key)
specs = one_qubit_specs[str(i+1)]
depol_rate = 1 - specs["f1Q_simultaneous_RB"]
noise_model.add_noise(Depolarizing(depol_rate), GateCriteria(qubits=i))
readout_rate = 1 - specs["fRO"]
noise_model.add_noise(BitFlip(readout_rate), ObservableCriteria(qubits=i))
# Implement two qubit noise for the native Gate 'CZ'
two_qubit_pairs = list(two_qubit_specs.keys())
for pair, params in two_qubit_specs.items():
q0, q1 = (int(item) for item in two_qubit_pairs[0].split("-"))
if "fCZ" in params:
cz_rate = 1 - params["fCZ"]
noise_model.add_noise(
TwoQubitDepolarizing(cz_rate), GateCriteria(Gate.CZ, [(q0, q1), (q1, q0)])
)
```

We can now attach the noise model defined above to Amazon Braket Hybrid Jobs. To do this, we add the `backend="braket_dm"`

option to select the Density Matrix backend and use the `noise_model=noise_model`

parameter to pass-in the Braket noise model to `qml.device`

. Note that the `vqe_noiseless(...)`

function implementing the underlying VQE algorithm defines a parameterized quantum circuit. This circuit may contain two-qubit gates other than the controlled-Z (“CZ”) gate. To introduce the two-qubit noise from Garnet’s calibration data, we first need to decompose gates like CNOT into CZ gates. The following code snippet shows how to define a custom decomposition rule for CNOT in terms of CZ. While there are other strategies to include two-qubit noise, we take this exploratory approach for demonstration purposes using calibration data from IQM’s Garnet device available on Amazon Braket.

```
import pennylane as qml
from braket.jobs import hybrid_job
device_arn = "local:braket/braket.local.qubit"
@hybrid_job(device=device_arn, include_modules="algorithm")
def run_vqe_hybrid(hyperparams=hyperparams, n_qubits, shots):
def custom_cnot(wires):
return [qml.Hadamard(wires=wires[1]),
qml.CZ(wires=[wires[0], wires[1]]),
qml.Hadamard(wires=wires[1])]
custom_decomps = {qml.CNOT: custom_cnot}
device = qml.device("braket.local.qubit", device_arn=device_arn,
backend="braket_dm", wires=n_qubits,
noise_model=noise_model, shots=shots, custom_decomps=custom_decomps)
return vqe_noiseless(electrons, charge, symbols, coordinates, device=device, shots=shots)
```

## Error mitigation with Zero Noise Extrapolation (ZNE)

To counter the noise in our model, we will now use the Zero Noise Extrapolation (ZNE) error mitigation technique implemented by the Mitiq package. This earlier blog describes how to use Mitiq on Braket to mitigate error using ZNE for an example of mirror circuit. In this blog, we take a slightly different approach and use the Mitiq error mitigation module that comes integrated with the PennyLane plugin. As shown in the code snippet below, after the circuit has been defined, one can call `qml.transforms.mitigate_with_zne`

to add ZNE while leaving rest of the code in `vqe_noiseless(…)`

rest of the same:

```
from mitiq.zne.inference import RichardsonFactory
from mitiq.zne.scaling import fold_global as folding
@qml.qnode(device, interface="autograd")
def circuit(theta, obs, wires):
qml.BasisState(hf_state, wires=wires)
qml.DoubleExcitation(theta[0], wires=[0, 1, 2, 3])
qml.DoubleExcitation(theta[1], wires=[0, 1, 4, 5])
return qml.expval(obs)
extrapolate = RichardsonFactory.extrapolate
scale_factors = [1, 3, 5]
circuit = qml.transforms.mitigate_with_zne(circuit, scale_factors, folding, extrapolate)
```

The Mitiq package does not come preinstalled in Amazon Braket. To install it along with dependencies, we provide the list of required packages in the “requirements” field of the decorator as `@hybrid_jobs(..., requirements=["mitiq","pennylane_qiskit", "ply”]`

. Alternatively, the user can create a custom container as described in Hybrid Jobs documentation. We have used the latter approached in the accompanying notebook.

## Finding the equilibrium geometry of the H_{3}^{+} molecule

Figures 1, 2, and 3 show the evolution of estimated energy, bond length, and bond angle with the number of iterations during optimization. The noiseless simulations converge to the true values whereas the results for noisy simulations show large deviation from the true values. ZNE is able to mitigate the effect of noise to some extent.

## Conclusion

In this post, we studied the effect of noise in quantum computing and added a well-known quantum error mitigation technique, Zero Noise Extrapolation (ZNE), to our experiment on Braket to see if we could improve the results.

We modeled the noise characteristics based on the calibration data available for IQM’s Garnet devices, which is accessible as a quantum device at Amazon Braket, and then tested the approach by determining the molecular geometry of the *H _{3}^{+}* molecule.

We find that Zero Noise Extrapolation can mitigate the effect of noise in VQE execution to some extent.

The code blocks provided in this blog are available in a complete accompanying Jupyter notebook. With Amazon Braket, AWS’s comprehensive services for quantum computing, and access to third-party quantum hardware, and software tools, you can explore cutting-edge techniques at the forefront of quantum computing.

### References

[1] Jules Tilly, Hongxiang Chen, Shuxiang Cao, Dario Picozzi, Kanav Setia, Ying Li, Edward Grant, Leonard Wossnig, Ivan Rungger, George H. Booth, Jonathan Tennyson, “The Variational Quantum Eigensolver: A review of methods and best practices”, Physics Reports, Volume 986, 2022, Pages 1-128.

[2] Alain Delgado, Juan Miguel Arrazola, Soran Jahangiri, Zeyue Niu, Josh Izaac, Chase Roberts, and Nathan Killora, “Variational quantum algorithm for molecular geometry optimization” Phys. Rev. A 104, 052402 – Published 2 November 2021.

[3] Alain Degado, “Optmization of molecular geometries”