Skip to content

Commit

Permalink
Update "Using PennyLane with IBM’s quantum devices and Qiskit" (#1143)
Browse files Browse the repository at this point in the history
**Title:**
"Using PennyLane with IBM’s quantum devices and Qiskit"

**Summary:**
This demo has been not functional ever since vqe_runner was removed and
deprecated. This PR aims to update the demo to allow users to run VQE
with IBM hardware by utilizing the pennylane-qiskit plugin.

**Relevant references:**

https://app.shortcut.com/xanaduai/story/67063/update-using-pennylane-with-ibm-s-quantum-devices-and-qiskit

**Possible Drawbacks:**

**Related GitHub Issues:**

---------

Co-authored-by: Utkarsh <[email protected]>
  • Loading branch information
austingmhuang and obliviateandsurrender authored Aug 8, 2024
1 parent 3503e94 commit 8d32177
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 89 deletions.
4 changes: 2 additions & 2 deletions demonstrations/ibm_pennylane.metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
}
],
"dateOfPublication": "2023-06-20T00:00:00+00:00",
"dateOfLastModification": "2024-08-05T00:00:00+00:00",
"dateOfLastModification": "2024-08-08T00:00:00+00:00",
"categories": [
"Devices and Performance"
],
Expand Down Expand Up @@ -45,4 +45,4 @@
"weight": 1.0
}
]
}
}
169 changes: 82 additions & 87 deletions demonstrations/ibm_pennylane.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@
quantum_volume Quantum Volume
tutorial_vqe A brief overview of VQE
*Authors: Kaur Kristjuhan, Clara Ferreira Cores, Mark Nicholas Jones; Molecular Quantum Solutions (MQS) — Posted: 20 June 2023. Last updated: 20 June 2023.*
.. warning::
This demo currently does not work as the Qiskit Runtime VQE program has been retired.
*Authors: Kaur Kristjuhan, Clara Ferreira Cores, Mark Nicholas Jones; Molecular Quantum Solutions (MQS) — Posted: 20 June 2023. Last updated: 8 Aug 2024.*
Bigger and better quantum computers are built every year. Instead of waiting for the perfect quantum computer to be
released, we can already try out the best hardware that exists today. Experimenting on cutting-edge devices helps us
Expand All @@ -26,7 +23,7 @@
platform. We will learn how to:
* discover what kind of devices IBM offers;
* connect to IBM devices through Pennylane's device class;
* connect to IBM devices through PennyLane's device class;
* use Qiskit Runtime to run hybrid algorithms;
* compare different devices to improve our quantum algorithms.
"""
Expand All @@ -36,38 +33,41 @@
# -----------------
# IBM offers access to a variety of devices, both classical simulators and real quantum hardware.
# By default, these devices are not included in PennyLane, but after installing the
# pennylane-qiskit plugin with the command ``pip install pennylane-qiskit``, they can be used just like any other device offered in PennyLane!
# Currently, there are three devices available — Aer, BasicAer and IBMQ — that can be initialized
# `PennyLane-Qiskit plugin <https://docs.pennylane.ai/projects/qiskit/en/stable/>`__ with the command ``pip install pennylane-qiskit``,
# they can be used just like any other device offered in PennyLane!
# Currently, there are three devices available — ``Aer``, ``BasicSim`` and ``Remote`` — that can be initialized
# as follows:
import pennylane as qml
import qiskit
from qiskit_aer import AerSimulator

qubits = 4
dev_aer = qml.device("qiskit.aer", wires=qubits)
dev_basicaer = qml.device("qiskit.basicaer", wires=qubits)
dev_basicsim = qml.device("qiskit.basicsim", wires=qubits)
try:
dev_ibmq = qml.device("qiskit.ibmq", wires=qubits)
dev_remote = qml.device("qiskit.remote", wires=qubits, backend=AerSimulator())
except Exception as e:
print(e)

##############################################################################
# The last device (qiskit.ibmq) can cause an error if we don't provide a valid account
# token through Qiskit. The IBMQ device is used to access quantum hardware, so it also requires access to an IBMQ
# account, which can be specified using an identifying token. You can find your token by creating
# or logging into your `IBMQ account <https://quantum-computing.ibm.com>`__. Be careful not to
# publish code that reveals your token to other people! One way to avoid this is by saving your
# token in a `PennyLane configuration file <https://docs.pennylane.ai/en/stable/introduction/configuration.html>`__.
# The last device (``qiskit.remote``) can cause an error if we don't provide a valid account
# token through Qiskit. The Remote device is used to access quantum hardware, so it also requires
# an IBM Quantum account, which can be specified using an identifying token. You can find your
# token by creating or logging into your `IBM Quantum account <https://quantum-computing.ibm.com>`__.
# Be careful not to publish code that reveals your token to other people! One way to avoid this
# is by saving your token in a `PennyLane configuration file <https://docs.pennylane.ai/en/stable/introduction/configuration.html>`__.
# To specify which machine or computational framework these devices actually connect to, we can
# use the ``backend`` argument.

dev_aer = qml.device("qiskit.aer", wires=qubits, backend="aer_simulator_statevector")
dev_aer = qml.device("qiskit.aer", wires=qubits)

##############################################################################
# For the IBMQ device, different quantum computers can be used by changing the backend to the name
# of the specific quantum computer, such as ``'ibmq_manila'`` or ``'ibm_nairobi'``. To see which
# backends exist, we can call the ``capabilities`` function:
# For the Aer device, different quantum computers can be used by changing the backend to the name
# of the specific simulator method. To see which backends exist, we can call the
# ``capabilities`` function:

print(dev_aer.capabilities()["backend"])
from qiskit_aer import Aer

print(Aer.backends())

##############################################################################
# .. rst-class:: sphx-glr-script-out
Expand All @@ -81,12 +81,12 @@
# 'qasm_simulator', 'statevector_simulator', 'unitary_simulator', 'pulse_simulator']

##############################################################################
# You can find even more details about these devices directly from the IBMQ platform. You can find
# information about the size, topology, quantum volume and noise profile of all the devices that they
# have available. Currently, the smallest device has 5 qubits and the largest has 127. On the IBMQ
# platform you can also check which devices are free to use and whether any of them are temporarily
# unavailable. You can even check your active jobs and estimated time in the queue for any programs
# you execute.
# You can find even more details about these devices directly from the IBM Quantum platform. You can
# find information about the size, topology, quantum volume and noise profile of all the devices
# that they have available. Currently, the smallest device has 5 qubits and the largest has 127. On
# the IBM Quantum platform you can also check which devices are free to use and whether any of them
# are temporarily unavailable. You can even check your active jobs and estimated time in the queue
# for any programs you execute.

##############################################################################
# Qiskit Runtime
Expand All @@ -113,30 +113,30 @@
##############################################################################
# Using Qiskit Runtime
# --------------------
# The pennylane-qiskit plugin includes some tools to help create a Qiskit Runtime job. Since using
# Qiskit Runtime only makes sense when using real quantum hardware, we must again specify our IBMQ
# account details to run these jobs.
# The PennyLane-Qiskit plugin includes some tools to help create a Qiskit Runtime job. Since using
# Qiskit Runtime only makes sense when using real quantum hardware, we must again specify our IBM
# Quantum account details to run these jobs.
#
# First, we set up our problem as usual, and then retrieve a program ID from IBM, which gives us a
# place to upload our job
# place to upload our job:

from pennylane_qiskit import vqe_runner
from pennylane import qchem
from pennylane import numpy as np
from pennylane import numpy as pnp
from qiskit_ibm_runtime import QiskitRuntimeService

symbols = ["H", "H"]
coordinates = np.array([0.0, 0.0, -0.6614, 0.0, 0.0, 0.6614])
basis_set = "sto-3g"
electrons = 2
import pennylane as qml

H, qubits = qchem.molecular_hamiltonian(
symbols,
coordinates,
basis=basis_set,
)
# Obtaining the Hamiltonian for H2 from PennyLane QChem dataset
[dataset] = qml.data.load("qchem", molname="H2", bondlength=0.742, basis="STO-3G")
H = dataset.hamiltonian
qubits = 4

service = QiskitRuntimeService()
# Gets a 127 qubit device from IBM
backend = service.least_busy(n_qubits=127, simulator=False, operational=True)

try:
dev = qml.device("qiskit.ibmq.circuit_runner", wires=4)
# Although we only need 4 qubits, our device has 127 qubits, therefore we initialize with wires=127
dev = qml.device("qiskit.remote", wires=127, backend=backend)
except Exception as e:
print(e)

Expand All @@ -149,7 +149,7 @@
# more parameters when the transpiler attempts to decompose a complicated gate, such as
# :class:`~pennylane.AllSinglesDoubles`. These types of issues will likely be fixed in the future, but, when in doubt,
# it is preferable to use simpler gates where possible. We will use a simple four-qubit circuit
# with one parameter that is designed specifically for the H2 molecule:
# with one parameter that is designed specifically for the :math:`H_2` molecule:


def four_qubit_ansatz(theta):
Expand All @@ -158,7 +158,7 @@ def four_qubit_ansatz(theta):
qml.PauliX(wires=1)

# change of basis
qml.RX(np.pi / 2, wires=0)
qml.RX(pnp.pi / 2, wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
qml.Hadamard(wires=3)
Expand All @@ -174,51 +174,44 @@ def four_qubit_ansatz(theta):
qml.CNOT(wires=[3, 2])

# invert change of basis
qml.RX(-np.pi / 2, wires=0)
qml.RX(-pnp.pi / 2, wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
qml.Hadamard(wires=3)


##############################################################################
# Finally, we can run our example VQE algorithm, by using the ``vqe_runner`` function. It has many
# options that you can specify, such as the number of shots, the maximum number of iterations
# and the initial values of the parameters.
# Finally, we can run our example VQE algorithm. In order to query the quantum computer iteratively
# we need to initialize a `Qiskit Session <https://docs.quantum.ibm.com/guides/sessions>`__, which
# allows multiple jobs from a single algorithm to be ran sequentially without interruptions. We
# also need to provide our VQE algorithm an optimizer. In this case, we will be using the :class:`~.pennylane.GradientDescentOptimizer`.

try:
job = vqe_runner(
backend="ibmq_qasm_simulator",
hamiltonian=H,
ansatz=four_qubit_ansatz,
x0=[0.0],
shots=8000,
optimizer="SPSA",
optimizer_config={"maxiter": 30},
kwargs={"hub": "ibm-q", "group": "open", "project": "main"},
)
print(job.result())
from pennylane_qiskit import qiskit_session

except Exception as e:
print(e)

##############################################################################
# .. rst-class:: sphx-glr-script-out
#
#
# .. code-block:: none
#
# {aux_operator_eigenvalues: None
# cost_function_evals: 60
# eigenstate: {'0011': 0.10781929326423913, '1100': 0.9941705085145103}
# eigenvalue: (-1.1317596845378903+0j)
# optimal_parameters: None
# optimal_point: array([2.9219612])
# optimal_value: -1.1317596845378903
# optimizer_evals: None
# optimizer_time: 16.73882269859314}
@qml.qnode(dev)
def cost_fn(theta):
four_qubit_ansatz(theta)
return qml.expval(H)

##############################################################################
# The results are saved in the ``job`` variable in SciPy optimization format. You can also check the
# results produced by any IBM device by logging in to your IBMQ account.

max_iterations = 40
theta = pnp.array(0.0, requires_grad=True)
opt = qml.GradientDescentOptimizer(stepsize=0.4)
energies = []

with qiskit_session(dev) as session:
for n in range(max_iterations):
theta, prev_energy = opt.step_and_cost(cost_fn, theta)
energies.append(prev_energy)

######################################################################
# .. note ::
#
# This may take a long time depending on how busy the hardware is. Depending on the tier of
# your IBM plan, your session may also be interrupted before the optimization can finish.
# Luckily, the rest of the workflow demonstrates how to run VQE with a simulator instead, which
# has no such restrictions at all.

##############################################################################
# Benchmarking
Expand All @@ -236,7 +229,7 @@ def four_qubit_ansatz(theta):

dev1 = qml.device("default.qubit", wires=4)
shots = 8000
dev2 = qml.device("qiskit.aer", wires=4, backend="aer_simulator", shots=shots)
dev2 = qml.device("qiskit.aer", wires=4, shots=shots)


@qml.qnode(dev1)
Expand All @@ -250,9 +243,11 @@ def cost_fn_2(theta):
four_qubit_ansatz(theta)
return qml.expval(H)


# we can also use the qnode to draw the circuit
import matplotlib.pyplot as plt
qml.draw_mpl(cost_fn_1, decimals=2)(theta=1.)

qml.draw_mpl(cost_fn_1, decimals=2)(theta=1.0)
plt.show()

##############################################################################
Expand All @@ -266,8 +261,8 @@ def cost_fn_2(theta):
stepsize = 0.4
max_iterations = 40
opt = qml.GradientDescentOptimizer(stepsize=stepsize)
theta_1 = np.array(0., requires_grad=True)
theta_2 = np.array(0., requires_grad=True)
theta_1 = pnp.array(0.0, requires_grad=True)
theta_2 = pnp.array(0.0, requires_grad=True)
energies_1 = []
energies_2 = []
for n in range(max_iterations):
Expand Down Expand Up @@ -358,7 +353,7 @@ def cost_fn_2(theta):
# topology and readout errors.
#
# This tutorial has demonstrated how and why to use quantum computing hardware provided by IBM using PennyLane. To read
# more about the details and possibilities of the Qiskit plugin for PennyLane, `read the documentation <https://docs.pennylane.ai/projects/qiskit/en/latest/index.html>`__
# more about the details and possibilities of the PennyLane-Qiskit plugin, `read the documentation <https://docs.pennylane.ai/projects/qiskit/en/latest/index.html>`__.
#
# About the authors
# ----------------
Expand Down

0 comments on commit 8d32177

Please sign in to comment.