Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ZNE demo using catalyst #1207

Open
wants to merge 56 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
e00303d
Stub for ZNE Catalyst tutorial
cosenal Aug 22, 2024
1db073f
add description of protocol
natestemen Sep 5, 2024
9038c94
flush out initial workflow; lead into comparison
natestemen Sep 6, 2024
faa3c18
Suggestions from @vprusso
natestemen Sep 7, 2024
771d508
Add tutorial (#1075)
minhtriet Aug 28, 2024
25e95e1
fix-tutorial-vqe-vqd-metadata (#1200)
ashishks0522 Aug 28, 2024
1a2ccf1
Fixing incorrect title of Demo in metadata file. (#1197)
ikurecic Aug 28, 2024
7d91d08
sc-70154-update-qml-readme-to-highlight-image-standards (#1184)
ashishks0522 Aug 29, 2024
645e763
Landscape of qem techniques in pennylane
cosenal Sep 7, 2024
bfefdf5
Merge branch 'master' into zne-catalyst-tutorial
cosenal Sep 9, 2024
af5773b
example with mirror circuits
cosenal Sep 9, 2024
b6aa337
zne in non-catalyst pennylane
cosenal Sep 9, 2024
6fd8aa4
measure running time
cosenal Sep 18, 2024
231c26e
better explanations
cosenal Sep 19, 2024
dea771a
Merge branch 'master' into zne-catalyst-tutorial
cosenal Sep 19, 2024
2e64d80
reformat demo with black
cosenal Sep 19, 2024
5d44c20
lock poetry file
cosenal Sep 19, 2024
297bee1
opencl in github build
cosenal Sep 19, 2024
292d20f
Merge branch 'master' into zne-catalyst-tutorial
cosenal Sep 23, 2024
6ff56aa
disable opencl on qrack device
cosenal Sep 24, 2024
b9478dc
Merge branch 'zne-catalyst-tutorial' of https://github.com/unitaryfun…
cosenal Sep 24, 2024
149dddd
update torch dependency options on mac
cosenal Sep 24, 2024
f7e1e90
resolve conflicts
cosenal Sep 24, 2024
a352984
bump qrack
cosenal Sep 26, 2024
9236c62
update poetry lock
cosenal Sep 26, 2024
e2233ff
bump qrack again
cosenal Sep 26, 2024
bc929d8
new day, new run
cosenal Sep 27, 2024
f595a35
Merge branch 'master' into zne-catalyst-tutorial
cosenal Sep 30, 2024
7cb3206
pin pyqrack version
cosenal Sep 30, 2024
c6f704e
Update demonstrations/tutorial_zne_catalyst.py
cosenal Oct 3, 2024
b5e4158
Update demonstrations/tutorial_zne_catalyst.py
cosenal Oct 3, 2024
09c2728
Apply suggestions from Josh's code review
cosenal Oct 3, 2024
84ee6fe
Merge branch 'master' into zne-catalyst-tutorial
cosenal Oct 3, 2024
e5359ad
add myself as an author
cosenal Oct 3, 2024
19db775
fix bio
cosenal Oct 3, 2024
14d83a3
Numeric noise constructor param. for Qrack
WrathfulSpatula Oct 5, 2024
3e5eb5e
Fix poetry.lock
WrathfulSpatula Oct 5, 2024
0fc80c4
Merge branch 'master' into zne-catalyst-tutorial
cosenal Oct 7, 2024
dbc7c19
address more review comments
cosenal Oct 7, 2024
ed564f4
Merge branch 'master' into zne-catalyst-tutorial
ikurecic Oct 9, 2024
f6d2aa7
adding thumbnail images
ikurecic Oct 9, 2024
4e5c221
Apply suggestions from Ivana's code review
cosenal Oct 9, 2024
7db6373
correct thumbnails
ikurecic Oct 9, 2024
aa2e265
address more reviewers comments
cosenal Oct 9, 2024
65cb5a2
migrate info to pennylane.ai
natestemen Oct 9, 2024
da89e5d
Apply suggestions from code review
cosenal Oct 10, 2024
2cb1176
clarify some sentences
cosenal Oct 10, 2024
bc166cf
addressing more review comments
cosenal Oct 10, 2024
17735ba
one-shot mode for ZNE tutorial noisy device
WrathfulSpatula Oct 28, 2024
aad4b47
Merge branch 'master' into zne-catalyst-tutorial
ikurecic Nov 6, 2024
527e9be
poetry lock hash
ikurecic Nov 6, 2024
34c11a4
Merge branch 'master' into zne-catalyst-tutorial
ikurecic Nov 7, 2024
c3ad24f
poetry
ikurecic Nov 7, 2024
e9711ac
Apply suggestions from code review
ikurecic Nov 7, 2024
e016da8
Merge branch 'master' into zne-catalyst-tutorial
ikurecic Nov 7, 2024
02f9541
poetry
ikurecic Nov 7, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/build-branch.yml
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,11 @@ jobs:
source ${{ steps.venv.outputs.location }}/bin/activate
make POETRY_BIN="${{ steps.poetry.outputs.poetry_bin }}" UPGRADE_PL="${{ needs.compute-build-strategy-matrix.outputs.build-environment == 'dev' }}" environment

- name: Install OpenCL
run: |
sudo apt update
sudo apt install ocl-icd-opencl-dev

- name: Download Worker Load Data Artifact
uses: actions/download-artifact@v3
with:
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
57 changes: 57 additions & 0 deletions demonstrations/tutorial_zne_catalyst.metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"title": "Digital zero-noise extrapolation with Catalyst",
"authors": [
{
"username": "cosenal"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cosenal , if you add a Headline to your profile, it will also show up in the author bio summary under the Demo.

},
{
"username": "natestemen"
}
],
"dateOfPublication": "2024-09-09T00:00:00+00:00",
"dateOfLastModification": "2024-09-09T00:00:00+00:00",
Comment on lines +11 to +12
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tk

"categories": [
"Algorithms",
"Quantum Computing"
],
"tags": [],
"previewImages": [
{
"type": "thumbnail",
"uri": "/_static/demo_thumbnails/regular_demo_thumbnails/thumbnail_zne_catalyst.png"
},
{
"type": "large_thumbnail",
"uri": "/_static/demo_thumbnails/large_demo_thumbnails/thumbnail_large_zne_catalyst.png"
}
],
"seoDescription": "Learn to use error mitigation and the digital zero-noise extrapolation (ZNE) technique with Catalyst, the PennyLane framework for quantum JIT compilation.",
"doi": "",
"references": [
{
"id": "DZNEpaper",
"type": "preprint",
"title": "Digital zero noise extrapolation for quantum error mitigation",
"authors": "Tudor Giurgica-Tiron, Yousef Hindy, Ryan LaRose, Andrea Mari, and William J. Zeng",
"year": "2020",
"publisher": "",
"journal": "",
"doi": "10.48550/arXiv.2005.10921",
"url": "https://arxiv.org/abs/2005.10921v2"
}
],
"basedOnPapers": [],
"referencedByPapers": [],
"relatedContent": [
{
"type": "demonstration",
"id": "tutorial_error_mitigation",
"weight": 1.0
},
{
"type": "demonstration",
"id": "qrack",
"weight": 1.0
}
]
}
274 changes: 274 additions & 0 deletions demonstrations/tutorial_zne_catalyst.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,274 @@
r"""
Digital zero-noise extrapolation with Catalyst
==============================================
Comment on lines +2 to +3
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Digital zero-noise extrapolation with Catalyst
==============================================
Digital zero-noise extrapolation (ZNE) with Catalyst
====================================================


In this tutorial, you will learn how to use error mitigation, and in particular
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
In this tutorial, you will learn how to use error mitigation, and in particular
In this tutorial, you will learn how to use :doc:`error mitigation <tutorial_error_mitigation>`, and in particular

This is just a suggestion.

the zero-noise extrapolation (ZNE) technique, in combination with
`Catalyst <https://docs.pennylane.ai/projects/catalyst>`_, a framework for quantum
just-in-time (JIT) compilation with PennyLane.
We'll demonstrate how to generate noise-scaled circuits, execute them on a noisy quantum
simulator, and use extrapolation techniques to estimate the zero-noise result, all while
leveraging JIT compilation through Catalyst.

.. image:: ../_static/demo_thumbnails/regular_demo_thumbnails/thumbnail_zne_catalyst.png
:width: 65%
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
:width: 65%
:width: 70%

To fit the intended design.

:align: center

The demo :doc:`Error mitigation with Mitiq and PennyLane <tutorial_error_mitigation>`
shows how ZNE, along with other error mitigation techniques, can be carried out in PennyLane
by using `Mitiq <https://github.com/unitaryfund/mitiq>`__, a Python library developed by `Unitary Fund <https://unitary.fund/>`__.

ZNE in particular is also offered out of the box in PennyLane as a *differentiable* error mitigation technique,
for usage in combination with variational workflows. More on this in the tutorial
:doc:`Differentiating quantum error mitigation transforms <tutorial_diffable-mitigation>`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you want to add this as a related Demo, as well?


On top of the error mitigation routines offered in PennyLane, ZNE is also available for just-in-time
(JIT) compilation. In this tutorial we see how an error mitigation routine can be
integrated in a Catalyst workflow.

At the end of the tutorial, we will compare the execution time of ZNE routines in
pure PennyLane vs. PennyLane and Catalyst with JIT.

What is zero-noise extrapolation (ZNE)
-----------
Comment on lines +32 to +33
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
What is zero-noise extrapolation (ZNE)
-----------
What is zero-noise extrapolation (ZNE)
--------------------------------------

Zero-noise extrapolation (ZNE) is a technique used to mitigate the effect of noise on quantum
computations. First introduced in [#temme2017zne]_, it helps improve the accuracy of quantum
results by running circuits at varying noise levels and extrapolating back to a hypothetical
zero-noise case. While this tutorial won't delve into the theory behind ZNE in detail (for which we
recommend reading the `Mitiq docs <https://mitiq.readthedocs.io/en/stable/guide/zne-5-theory.html>`_
and the references therein), let's first review what happens when using the protocol in practice.
Comment on lines +38 to +39
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
and the references therein), let's first review what happens when using the protocol in practice.
and the references therein), let's first review what happens when using the protocol in practice, in three stages.

Could we set the expectations like this or in a similar way? As a first-time reader, the structure confused me a bit.


Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is a great way to explain the steps, but I'm a bit confused by how these three stages related to the following sections. Could we maybe align those two a bit better? Even if you just refer to specific stages within the text/code, that would already be valuable.

Stage 1: Generating noise-scaled circuits
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

ZNE works by generating circuits with **increased** noise. Catalyst implements the unitary folding
framework introduced in [#DZNEpaper]_ for generating noise-scaled circuits. In particular,
the following two methods are available:

1. **Global folding**: If a circuit implements a global unitary :math:`U`, global folding applies
:math:`U(U^\dagger U)^n` for some integer :math:`n`,
effectively scaling the noise in the entire circuit.
2. **Local folding**: Individual gates are repeated (or folded) in contrast with the entire
circuit.

Stage 2: Running the circuits
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Once noise-scaled circuits are created, they need to be run! These can be executed on either real
quantum hardware or a noisy quantum simulator. In this tutorial, we'll use the
`Qrack quantum simulator <https://qrack.readthedocs.io/>`_, which is both compatible with Catalyst,
and implements a noise model. For more about the integration of Qrack and Catalyst, see
ikurecic marked this conversation as resolved.
Show resolved Hide resolved
the demo :doc:`QJIT compilation with Qrack and Catalyst <qrack>`.

Stage 3: Combining the results
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

After executing the noise-scaled circuits, an extrapolation on the results is performed
to estimate the zero-noise limit---the result we would expect in a noise-free scenario.
Catalyst provides **polynomial** and **exponential** extrapolation methods.

Defining the mirror circuit
---------------------------

The first step for demoing an error mitigation routine is to define a circuit.
Here we build a simple mirror circuit starting off a unitary 2-design.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Here we build a simple mirror circuit starting off a unitary 2-design.
Here we build a simple mirror circuit starting off a `unitary 2-design <https://en.wikipedia.org/wiki/Quantum_t-design>`__.

Let's include a web reference.

This is a typical construction for a randomized benchmarking circuit, which is used in many tasks
in quantum computing. Given such circuit, we measure the expectation value :math:`\langle Z\rangle`
on the state of the first qubit, and by construction of the circuit, we expect this value to be
equal to 1.
"""

import timeit

import numpy as np
import pennylane as qml
from catalyst import mitigate_with_zne

n_wires = 5

np.random.seed(42)

n_layers = 10
template = qml.SimplifiedTwoDesign
weights_shape = template.shape(n_layers, n_wires)
w1, w2 = [2 * np.pi * np.random.random(s) for s in weights_shape]


def circuit(w1, w2):
template(w1, w2, wires=range(n_wires))
qml.adjoint(template)(w1, w2, wires=range(n_wires))
return qml.expval(qml.PauliZ(0))


##############################################################################
# As a sanity check, we first execute the circuit on the Qrack simulator without any noise.

noiseless_device = qml.device("qrack.simulator", n_wires, noise=0)

ideal_value = qml.QNode(circuit, device=noiseless_device)(w1, w2)
print(f"Ideal value: {ideal_value}")

##############################################################################
# In the noiseless scenario, the expectation value of the Pauli-Z measurement
# is equal to 1, since the first qubit is back in the :math:`|0\rangle` state.
#
cosenal marked this conversation as resolved.
Show resolved Hide resolved
# Mitigating the noisy circuit
# ----------------------------
# Let's now run the circuit through a noisy scenario. The Qrack simulator models noise by
# applying single-qubit depolarizing noise channels to all qubits in all gates of the circuit.
# The probability of error is specified by the value of the ``noise`` constructor argument.

NOISE_LEVEL = 0.01
noisy_device = qml.device("qrack.simulator", n_wires, shots=1000, noise=NOISE_LEVEL)

noisy_qnode = qml.QNode(circuit, device=noisy_device, mcm_method="one-shot")
noisy_value = noisy_qnode(w1, w2)
print(f"Error without mitigation: {abs(ideal_value - noisy_value):.3f}")

##############################################################################
# Again expected, we obtain a noisy value that diverges from the ideal value we obtained above.
# Fortunately, we have error mitigation to the rescue! We can apply ZNE, however we are still
# missing some necessary parameters. In particular we still need to specify:
#
# 1. The method for scaling this noise up (in Catalyst there are two options: ``global`` and
# ``local``).
# 2. The noise scaling factors (i.e. how much to increase the depth of the circuit).
# 3. The extrapolation technique used to estimate the ideal value (available in Catalyst are
# polynomial and exponential extrapolation).
#
# First, we choose a method to scale the noise. This needs to be specified as a Python string.

folding_method = "global"

##############################################################################
# Next, we pick a list of scale factors. At the time of writing this tutorial,
# Catalyst supports only odd integer scale factors. In the global folding setting,
# a scale factor :math:`s` correspond to the circuit being folded
# :math:`\frac{s - 1}{2}` times.
scale_factors = [1, 3, 5]

##############################################################################
# Finally, we'll choose the extrapolation technique. Both exponential and polynomial extrapolation
# is available in the :mod:`qml.transforms <pennylane.transforms>` module, and both of these functions can be passed directly
# into Catalyst's :func:`catalyst.mitigate_with_zne` function. In this tutorial we use polynomial extrapolation,
# which we hypothesize best models the behavior of the noise scenario we are considering.

from pennylane.transforms import poly_extrapolate
from functools import partial

extrapolation_method = partial(poly_extrapolate, order=3)

##############################################################################
# We're now ready to run our example using ZNE with Catalyst! Putting these all together we're able
# to define a very simple :func:`~.QNode`, which represents the mitigated version of the original circuit.


@qml.qjit
def mitigated_circuit_qjit(w1, w2):
return mitigate_with_zne(
noisy_qnode,
scale_factors=scale_factors,
extrapolate=extrapolation_method,
folding=folding_method,
)(w1, w2)


zne_value = mitigated_circuit_qjit(w1, w2)

print(f"Error with ZNE in Catalyst: {abs(ideal_value - zne_value):.3f}")

##############################################################################
# It's crucial to note that we can use the :func:`~.qjit` decorator here, as all the functions used
# to define the node are compatible with Catalyst, and we can therefore
# exploit the potential of just-in-time compilation.
#
# Benchmarking
# ------------
# For comparison, let's define a very similar :func:`~.qnode`, but this time we don't decorate the node
# as just-in-time compilable.
# When it comes to the parameters, the only difference here (due to an implementation technicality)
# is the type of the ``folding`` argument. Despite the type being different, however,
# the value of the folding method is the same, i.e., global folding.


def mitigated_circuit(w1, w2):
return qml.transforms.mitigate_with_zne(
noisy_qnode,
scale_factors=scale_factors,
extrapolate=extrapolation_method,
folding=qml.transforms.fold_global,
)(w1, w2)


zne_value = mitigated_circuit(w1, w2)

print(f"Error with ZNE in PennyLane: {abs(ideal_value - zne_value):.3f}")

##############################################################################
# To showcase the impact of JIT compilation, let's use Python's ``timeit`` module
# to measure execution time of ``mitigated_circuit_qjit`` vs. ``mitigated_circuit``:

repeat = 5 # number of timing runs
number = 5 # number of loops executed in each timing run

times = timeit.repeat("mitigated_circuit(w1, w2)", globals=globals(), number=number, repeat=repeat)

print(f"mitigated_circuit running time (best of {repeat}): {min(times):.3f}s")

times = timeit.repeat(
"mitigated_circuit_qjit(w1, w2)", globals=globals(), number=number, repeat=repeat
)

print(f"mitigated_circuit_qjit running time (best of {repeat}): {min(times):.3f}s")

##############################################################################
# Already with the simple circuit we started with, and with the simple parameters in our example,
# we can appreciate the performance differences. That was at the cost of very minimal syntax change.
#
# There are still reasons to use ZNE in PennyLane without :func:`~.qjit`, for instance,
# whenever the device of choice is not supported by Catalyst. To help,
# we conclude with a landscape of the QEM techniques available on PennyLane.
#
# .. list-table::
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The resultant table doesn't look super perfect in the preview, in case you want to tweak something with the widths? Or even use an image instead.
image

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding this table, Romain mentioned on Discord that those zne functions in Catalyst are not yet differentiable. @rmoyard is that still the case? In which case, should I remove the checkmark from the Catalyst/Differentiable cell?

# :widths: 30 20 20 20 20 30
# :header-rows: 1
#
# * - **Framework**
# - **ZNE folding**
# - **ZNE extrapolation**
# - **Differentiable**
# - **JIT**
# - **Other QEM techniques**
# * - PennyLane + Mitiq
# - global, local, random
# - polynomial, exponential
# -
# -
# - PEC, CDR, DDD, REM
# * - PennyLane transforms
# - global, local
# - polynomial, exponential
# - ✅
# -
# -
# * - Catalyst (experimental)
# - global, local
# - polynomial, exponential
# - ✅
# - ✅
# -


##############################################################################
#
# References
# ----------
#
# .. [#temme2017zne] K. Temme, S. Bravyi, J. M. Gambetta
# `"Error Mitigation for Short-Depth Quantum Circuits" <https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.119.180509>`_,
# Phys. Rev. Lett. 119, 180509 (2017).
#
# .. [#DZNEpaper]
# Tudor Giurgica-Tiron, Yousef Hindy, Ryan LaRose, Andrea Mari, and William J. Zeng
# "Digital zero noise extrapolation for quantum error mitigation"
# `arXiv:2005.10921v2 <https://arxiv.org/abs/2005.10921v2>`__, 2020.
Loading
Loading