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

LCU + Block encoding demo #888

Merged
merged 49 commits into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
50fe29c
First draft of text sans code
ixfoduap Aug 11, 2023
53cd64b
fix typo to build preview
DSGuala Aug 17, 2023
9c250eb
Merge branch 'master' into lcu_blockencoding
DSGuala Aug 17, 2023
40f3537
Apply suggestions from code review
ixfoduap Aug 17, 2023
cc63a4a
First complete draft sans images
ixfoduap Aug 22, 2023
32e0de7
Update demonstrations/tutorial_lcu_blockencoding.py
ixfoduap Aug 23, 2023
e6b79cc
small edits
ixfoduap Aug 28, 2023
78c0ad2
Merge branch 'lcu_blockencoding' of https://github.com/PennyLaneAI/qm…
ixfoduap Aug 28, 2023
d15aa5b
First polished draft
ixfoduap Aug 28, 2023
cfad768
Merge branch 'master' into lcu_blockencoding
DSGuala Aug 29, 2023
4c64eea
update code to work with latest release
DSGuala Aug 29, 2023
6036659
change PL version, add placeholder images
DSGuala Aug 31, 2023
fae6234
update poetry.lock as suggested by CI
DSGuala Aug 31, 2023
1dfbb7c
Fix image paths
DSGuala Aug 31, 2023
bc5a30a
fix image paths again
DSGuala Aug 31, 2023
1271fe4
Merge branch 'master' into lcu_blockencoding
DSGuala Aug 31, 2023
1e00920
Apply suggestions from code review
DSGuala Sep 7, 2023
21717cc
don't steal credit
DSGuala Sep 7, 2023
e4d352a
add new images
DSGuala Sep 7, 2023
e42db64
Merge branch 'master' into lcu_blockencoding
DSGuala Sep 7, 2023
0db85b3
move images and change paths
DSGuala Sep 7, 2023
f301af9
Merge branch 'master' into lcu_blockencoding
DSGuala Sep 8, 2023
82cc912
Apply suggestions from code review
DSGuala Sep 8, 2023
a9cbb9a
address review comments
DSGuala Sep 8, 2023
dfa3644
Merge branch 'master' into lcu_blockencoding
Jaybsoni Sep 28, 2023
5d67fc1
Added projector LCU
Jaybsoni Sep 28, 2023
bed99c4
Merge branch 'dev' into lcu_blockencoding
DSGuala Oct 4, 2023
a92e1c5
revert changes to poetry.lock
DSGuala Oct 4, 2023
cf6f7d7
fix example to build
Jaybsoni Oct 5, 2023
df6ab35
updates, address comments
DSGuala Oct 11, 2023
47c6e7f
fixes and copyediting
DSGuala Oct 11, 2023
fc7fc72
Merge branch 'lcu_blockencoding' of https://github.com/PennyLaneAI/qm…
DSGuala Oct 11, 2023
0a910c2
update equations
DSGuala Oct 13, 2023
75ecf85
add small corrections
soranjh Oct 13, 2023
4da576a
update applications
soranjh Oct 17, 2023
096b8c7
add review comments
soranjh Oct 17, 2023
fd9c61f
add review comments
soranjh Oct 17, 2023
82840af
add review comments
soranjh Oct 19, 2023
7214065
add review comments
soranjh Oct 19, 2023
8c3fc6d
Update demonstrations/tutorial_lcu_blockencoding.py
KetpuntoG Oct 20, 2023
fdb3dd5
Update demonstrations/tutorial_lcu_blockencoding.py
KetpuntoG Oct 20, 2023
71da7cd
Update demonstrations/tutorial_lcu_blockencoding.py
KetpuntoG Oct 20, 2023
5bb2737
Update demonstrations/tutorial_lcu_blockencoding.py
KetpuntoG Oct 20, 2023
a129a3f
Update demonstrations/tutorial_lcu_blockencoding.metadata.json
KetpuntoG Oct 20, 2023
1835bb7
Merge branch 'dev' into lcu_blockencoding
KetpuntoG Oct 20, 2023
131e367
Merge branch 'dev' into lcu_blockencoding
KetpuntoG Oct 20, 2023
b53172a
links to codebook + remove meta in .py
KetpuntoG Oct 20, 2023
f9eab6e
correct typos
soranjh Oct 23, 2023
82ee2bf
update date + small typo in other demo
KetpuntoG Oct 26, 2023
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
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.
60 changes: 60 additions & 0 deletions demonstrations/tutorial_lcu_blockencoding.metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"title": "Linear combination of unitaries and block encodings",
"authors": [
{
"id": "juan_miguel_arrazola"
},
{
"id": "diego_guala"
},
{
"id": "jay_soni"
}
],
"dateOfPublication": "2023-08-31T00:00:00+00:00",
"dateOfLastModification": "2023-08-31T00:00:00+00:00",
KetpuntoG marked this conversation as resolved.
Show resolved Hide resolved
"categories": [
"Algorithms",
"Quantum Computing"
],
"tags": [],
"previewImages": [
{
"type": "thumbnail",
"uri": "/_images/thumbnail_tutorial_here_comes_the_sun.png"
},
{
"type": "large_thumbnail",
"uri": "/_static/large_demo_thumbnails/thumbnail_large_here_comes_the_sun.png"
}
],
"seoDescription": "Master the basics of LCUs and their applications",
"doi": "",
"canonicalURL": "/qml/demos/tutorial_lcu_blockencoding",
"references": [
{
"id": "qsvt",
"type": "article",
"title": "Quantum singular value transformation and beyond: exponential improvements for quantum matrix arithmetics",
"authors": "András Gilyén, Yuan Su, Guang Hao Low, Nathan Wiebe",
"year": "2019",
"publisher": "",
"journal": "",
"url": "https://dl.acm.org/doi/abs/10.1145/3313276.3316366"
}
],
"basedOnPapers": [],
"referencedByPapers": [],
"relatedContent": [
{
"type": "demonstration",
"id": "tutorial_intro_qsvt",
"weight": 1.0
},
{
"type": "demonstration",
"id": "tutorial_apply_qsvt",
"weight": 1.0
}
]
}
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
264 changes: 264 additions & 0 deletions demonstrations/tutorial_lcu_blockencoding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
r"""Linear combination of unitaries and block encodings
=============================================================

.. meta::
:property="og:description": Master the basics of LCUs and their applications
:property="og:image": https://pennylane.ai/qml/_images/thumbnail_lcu_blockencoding.png

.. related::

tutorial_intro_qsvt Intro to QSVT

*Author: Juan Miguel Arrazola, Diego Guala, and Jay Soni — Posted: August, 2023.*
soranjh marked this conversation as resolved.
Show resolved Hide resolved

If I (Juan Miguel) had to summarize quantum computing in one sentence, it would be this: information is
soranjh marked this conversation as resolved.
Show resolved Hide resolved
encoded in quantum states, and information is processed using `unitary operations <https://en.wikipedia.org/wiki/Unitary_operator>`_.
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
The challenge of quantum algorithms is to design and build these unitaries to perform interesting and
useful tasks. Now consider this. My colleague `Nathan Wiebe <https://scholar.google.ca/citations?user=DSgKHOQAAAAJ&hl=en>`_
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
once told me that some of his early research was motivated by a simple
question: Quantum computers can implement products of unitaries --- after all
soranjh marked this conversation as resolved.
Show resolved Hide resolved
soranjh marked this conversation as resolved.
Show resolved Hide resolved
that's how we build circuits from a `universal gate set <https://en.wikipedia.org/wiki/Quantum_logic_gate#Universal_quantum_gates>`_.
soranjh marked this conversation as resolved.
Show resolved Hide resolved
But what about **sums of unitaries**? 🤔
DSGuala marked this conversation as resolved.
Show resolved Hide resolved

In this tutorial you will learn the basics of one of the most versatile tools in quantum algorithms:
soranjh marked this conversation as resolved.
Show resolved Hide resolved
linear combinations of unitaries; or LCUs for short. You will also understand how to
soranjh marked this conversation as resolved.
Show resolved Hide resolved
use LCUs to create another powerful building block of quantum algorithms: block encodings.
Among their many uses, they allow us to transform quantum states by non-unitary operators.
Block encodings are useful in a variety of contexts, perhaps most famously in `qubitization <https://arxiv.org/abs/1610.06546)>`_ and the `quantum
soranjh marked this conversation as resolved.
Show resolved Hide resolved
singular value transformation (QSVT) <https://pennylane.ai/qml/demos/tutorial_intro_qsvt>`_.

[Main Tarik image here]
ixfoduap marked this conversation as resolved.
Show resolved Hide resolved

LCUs
----
The concept of an LCU is straightforward --- it’s basically already explained in the name: we
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
decompose operators as a weighted sum of unitaries. Mathematically, this means expresssing
soranjh marked this conversation as resolved.
Show resolved Hide resolved
an operator :math:`A` in terms of coefficients $\alpha_k$ and unitaries $U_k$ as
DSGuala marked this conversation as resolved.
Show resolved Hide resolved

.. math:: A = \sum_{k=1}^N \alpha_k U_k.

A general way to build LCUs is to employ properties of the **Pauli basis**.
This is the set of all products of Pauli matrices $I, X, Y, Z$. It forms a complete basis
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
for the space of operators on $n$ qubits, so any operator can be expressed in the Pauli basis,
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
which immediately gives an LCU decomposition. PennyLane allows you to compute Pauli-basis LCUs using the
:func:`~.pennylane.pauli_decompose` function. The coefficients :math:`\alpha_k` and the unitaries
ikurecic marked this conversation as resolved.
Show resolved Hide resolved
:math:`U_k` from the decomposition can be accessed directly from the result. We show how to do this
in the code below for a simple example.
DSGuala marked this conversation as resolved.
Show resolved Hide resolved

"""
import numpy as np
import pennylane as qml

a = 0.25
b = 0.75

# matrix to be decomposed
A = np.array(
[[a, 0, 0, b],
[0, -a, b, 0],
[0, b, a, 0],
[b, 0, 0, -a]]
)

LCU = qml.pauli_decompose(A)

print(f"LCU decomposition = {LCU}")
print(f"coefficients = {LCU.coeffs}")
print(f"Unitaries = {LCU.ops}")
DSGuala marked this conversation as resolved.
Show resolved Hide resolved


##############################################################################
# PennyLane uses a smart Pauli decomposition based on vectorizing the matrix and exploiting properties of
# the Walsh-Hadamard transform, as described `here <https://quantumcomputing.stackexchange.com/questions/31788/how-to-write-the-iswap-unitary-as-a-linear-combination-of-tensor-products-betw/31790#31790>`_,
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
# but the cost still scales as :math:`n 4^n` for :math:`n` qubits. Be careful.
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
#
# It's good to remember that many types of Hamiltonians are already compactly expressed
# in the Pauli basis, for example in various `Ising models <https://en.wikipedia.org/wiki/Ising_model>`_
# and molecular Hamiltonians using the `Jordan-Wigner transformation <https://en.wikipedia.org/wiki/Jordan%E2%80%93Wigner_transformation>`_.
soranjh marked this conversation as resolved.
Show resolved Hide resolved
# This is very useful since we get an LCU decomposition for free.
#
# Block Encodings
# ---------------
# Going from an LCU to a quantum circuit that applies the associated operator is also straightforward
# once you know the trick: To prepare, select, and unprepare.
#
# Starting from the LCU decomposition :math:`A = \sum_{k=1}^N \alpha_k U_k`, we define the prepare
# (PREP) operator
#
# .. math:: PREP|0\rangle = \sum_k \sqrt{\frac{|\alpha|_k}{\lambda}}|k\rangle,
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
#
# and the select (SEL) operator
#
# .. math:: SEL|k\rangle |\psi\rangle = |k\rangle U_k |\psi\rangle.
#
# They are aptly named: PREP is preparing a state whose amplitudes
# are determined by the coefficients of the LCU, and SEL is selecting which unitary is applied.
# In case you're wondering, :math:`\lambda = \sum_k |\alpha_k|` is a normalization
# constant, SEL acts this way on any state :math:`|\psi\rangle`, and we have added auxiliary
# qubits where PREP acts. We are also using :math:`|0\rangle` as shorthand to denote the all-zero
# state of the auxiliary qubits.
#
# The final trick is to combine PREP and SEL to make :math:`A` appear 🪄:
soranjh marked this conversation as resolved.
Show resolved Hide resolved
#
# .. math:: \langle 0| \text{PREP}^\dagger \cdot \text{SEL} \cdot \text{PREP} |0\rangle|\psi\rangle = A/\lambda |\psi\rangle.
soranjh marked this conversation as resolved.
Show resolved Hide resolved
#
# The way to understand this equation is that we apply PREP, SEL, and then invert PREP. If
# we measure :math:`|0\rangle` in the auxiliary qubits, the input state will be transformed by
# :math:`A` (up to normalization). It's illuminating to go through the math if you're up for it.
# (Tip: calculate the action of :math:`\text{PREP}^\dagger on :math:`|0\rangle`, not on the output
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
# state after :math:`\text{SEL} \cdot \text{PREP}`).
#
# The circuit
#
# .. math:: U = \text{PREP}^\dagger \cdot \text{SEL} \cdot \text{PREP},
#
# is a **block encoding** of :math:`A`, up to normalization. Below is a schematic figure showing
# a block encoding circuit with four unitaries:
#
# |
#
# .. figure:: ../demonstrations/lcu_blockencoding/thumbnail_lcu_blockencoding.png
# :align: center
# :width: 50%
# :target: javascript:void(0)
#
# |
#
# The reason for this name is that if we write down
# as a matrix, the operator :math:`A` is encoded inside a block of :math:`U`
# defined by the subspace of all states where the auxiliary qubits are in state :math:`|0\rangle`.
soranjh marked this conversation as resolved.
Show resolved Hide resolved
#
# PennyLane supports direct implementation of `prepare <https://docs.pennylane.ai/en/latest/code/api/pennylane.StatePrep.html>`_
# and `select <https://docs.pennylane.ai/en/latest/code/api/pennylane.Select.html?highlight=select>`_
# operators. We'll go through them individually and use them to construct a block encoding circuit.
# Prepare circuits can be constructed using the :func:`~.pennylane.StatePrep` operation, which takes
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
# the normalized target state as input:

dev1 = qml.device("default.qubit", wires=1)

# normalized square roots of coefficients
alphas = (np.sqrt(LCU.coeffs) / np.linalg.norm(np.sqrt(LCU.coeffs)))


@qml.qnode(dev1)
def prep_circuit():
qml.StatePrep(alphas, wires=0)
return qml.state()


print("Target state: ", alphas)
print("Output state: ", np.real(prep_circuit()))

##############################################################################
# Similarly, select circuits can be implemented using :func:`~.pennylane.Select`, which takes the
# target unitaries as input. We specify the control wires directly, but the system wires are inherited
# from the unitaries. Since :func:`~.pennylane.pauli_decompose` uses a canonical wire ordering, we
# first map the wires to those used for the system register in our circuit:
#

dev2 = qml.device("default.qubit", wires=3)
KetpuntoG marked this conversation as resolved.
Show resolved Hide resolved

# unitaries
ops = LCU.ops
# relabeling wires 0 --> 1, and 1 --> 2
soranjh marked this conversation as resolved.
Show resolved Hide resolved
unitaries = [qml.map_wires(op, {0: 1, 1: 2}) for op in ops]


@qml.qnode(dev2)
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
def sel_circuit(state):
soranjh marked this conversation as resolved.
Show resolved Hide resolved
qml.BasisState(state, wires=0)
qml.Select(unitaries, control=0)
return qml.expval(qml.PauliZ(2))


# Select flips the last qubit if control is |1>
print(sel_circuit([0]), sel_circuit([1]))

soranjh marked this conversation as resolved.
Show resolved Hide resolved
##############################################################################
# We can now combine these to construct a full LCU circuit. Here we make use of :fun:`~.pennylane.adjoint`
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
# as a convenient way to invert the prepare circuit. We have chosen an input matrix that is already
# normalized, so it can be seen appearing directly in the top-left block of the unitary describing
# the full circuit --- the mark of a successful block encoding.


@qml.qnode(dev2)
def lcu_circuit(): # block_encode
# PREP
qml.StatePrep(alphas, wires=0)

# SEL
qml.Select(unitaries, control=0)

# PREP_dagger
qml.adjoint(qml.StatePrep(alphas, wires=0))
return qml.state()


output_matrix = qml.matrix(lcu_circuit)()
print(np.real(np.round(output_matrix)))
print(A)
DSGuala marked this conversation as resolved.
Show resolved Hide resolved

soranjh marked this conversation as resolved.
Show resolved Hide resolved
##############################################################################
soranjh marked this conversation as resolved.
Show resolved Hide resolved
# Application to QSVT
# -------------------
#
# The QSVT algorithm is a method to transform block-encoded operators. You can learn more about it in
# our demos `Intro to QSVT <https://pennylane.ai/qml/demos/tutorial_intro_qsvt>`_ and
# `QSVT in practice <https://pennylane.ai/qml/demos/tutorial_apply_qsvt>`_. Here we show how to
# implement the QSVT algorithm using an explicit construction of the block encoding operator. We also
# need to define projector-controlled phase shifts, which can be done using :func:`~pennylane.PCPhase`.
# The :class:`.~pennylane.QSVT` uses these as input to build the full algorithm.
soranjh marked this conversation as resolved.
Show resolved Hide resolved

dev2 = qml.device('default.qubit', wires=3)


@qml.qnode(dev2)
def qsvt_circuit(phis):
# projector-controlled phase shifts
projectors = [qml.PCPhase(phi, dim=2, wires=[0, 1, 2]) for phi in phis]

# block encoding operator
block_encode_op = qml.prod(qml.StatePrep(alphas, wires=0),
*qml.Select(unitaries, control=0).decomposition(),
qml.adjoint(qml.StatePrep(alphas, wires=0)))
soranjh marked this conversation as resolved.
Show resolved Hide resolved

qml.QSVT(block_encode_op, projectors)

return qml.state()

##############################################################################
# We can do an illustrative check that the algorithm works correctly by choosing angles that start
# small and increase gradually. When angles are all equal to zero, we should retrieve the block encoding
# circuit. The output should change only slightly for small angles, with more pronounced differences
# for larger values.


# top-left block of circuit with angles of same magnitude and alternating sign
def out_matrix(theta):
return np.real(qml.matrix(qsvt_circuit)([theta, -theta, theta, -theta]))[:4, :4]


# angles are zero
print(out_matrix(0))
# angles are small
print(out_matrix(0.1))
# angles are big
print(out_matrix(np.pi / 2))
soranjh marked this conversation as resolved.
Show resolved Hide resolved


##############################################################################
# Final thoughts
# -------------------
# LCUs and block encodings are often associated with advanced algorithms that require the full power
# of fault-tolerant quantum computers. The truth is that they are basic constructions with
# broad applicability that can be useful for all kinds of hardware and simulators. If you're working
# on quantum algorithms and applications in any capacity, these are techniques that you should
# probably master. PennyLane is equipped with the tools to help you get there.
DSGuala marked this conversation as resolved.
Show resolved Hide resolved


##############################################################################
# About the authors
# ----------------
# .. include:: ../_static/authors/juan_miguel_arrazola.txt
# ..include::../ _static / authors / jay_soni.txt
# ..include::../ _static / authors / diego_guala.txt
DSGuala marked this conversation as resolved.
Show resolved Hide resolved
6 changes: 3 additions & 3 deletions demonstrations/tutorial_learning_few_data.metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
"title": "Generalization in QML from few training data",
"authors": [
{
"id": "korbinian_kottmann"
"id": "juan_miguel"
},
{
"id": "luis_mantilla_calderon"
"id": "diego_guala"
},
{
"id": "maurice_weber"
"id": "jay_soni"
}
],
"dateOfPublication": "2022-08-29T00:00:00+00:00",
Expand Down
7 changes: 7 additions & 0 deletions demos_quantum-computing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,12 @@ such as benchmarking and characterizing quantum processors.
:figure: demonstrations/apply_qsvt/thumbnail_tutorial_QSVT_for_Matrix_Inversion.png
:description: :doc:`demos/tutorial_apply_qsvt`
:tags: quantumcomputing qsvt optimization

.. gallery-item::
:tooltip: Linear combinations of unitaries and block encodings
:figure: demonstrations/lcu_blockencoding/thumbnail_lcu_blockencoding.png
:description: :doc:`demos/tutorial_lcu_blockencoding`
:tags: quantumcomputing LCU algorithms qsvt

:html:`</div></div><div style='clear:both'>`

Expand Down Expand Up @@ -205,5 +211,6 @@ such as benchmarking and characterizing quantum processors.
demos/tutorial_intro_qsvt
demos/tutorial_grovers_algorithm
demos/tutorial_apply_qsvt
demos/tutorial_lcu_blockencoding


Loading