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

Initial state preparation demo #950

Merged
merged 76 commits into from
Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
76 commits
Select commit Hold shift + click to select a range
ae28709
first draft of initial state demo
Chiffafox Oct 5, 2023
0224d75
very rough draft of the initial state demo
Chiffafox Oct 5, 2023
c6adb66
wip on the VQE part of demo
Chiffafox Oct 13, 2023
ab25ec1
new draft of initial state demo
Chiffafox Oct 13, 2023
4bd11b6
add header for vqe section
Chiffafox Oct 13, 2023
d37e40d
Merge branch 'dev' into qml_isp_demo
Chiffafox Oct 13, 2023
a04ff4b
[skip ci] text edits
Chiffafox Oct 13, 2023
eb8ccb0
Merge branch 'qml_isp_demo' of github.com:PennyLaneAI/qml into qml_is…
Chiffafox Oct 13, 2023
b24b4e7
trigger build
Chiffafox Oct 13, 2023
f532439
fixes to metadata
Chiffafox Oct 13, 2023
f817918
fixes to metadata
Chiffafox Oct 13, 2023
6345c47
fix metadata and add author data
Chiffafox Oct 13, 2023
7795c36
turn dmrg part into a note to avoid dependency
Chiffafox Oct 13, 2023
2a2c17c
final dmrg reference removed
Chiffafox Oct 13, 2023
cb01d13
fix previewimage metadata
Chiffafox Oct 13, 2023
9fc415d
remove printing from vqe execution and fix images not showing up
Chiffafox Oct 13, 2023
eacbc99
update demos qchem rst file
Chiffafox Oct 13, 2023
df9dcb2
update demos qchem rst file
Chiffafox Oct 13, 2023
b93c675
rearrange text and code
soranjh Oct 13, 2023
cbe6db2
Merge branch 'qml_isp_demo' of https://github.com/PennyLaneAI/qml int…
soranjh Oct 13, 2023
19b7b7e
Update _static/authors/stepan_fomichev.txt
Chiffafox Oct 16, 2023
270d876
typos
Chiffafox Oct 16, 2023
e5dafb2
Merge branch 'qml_isp_demo' of github.com:PennyLaneAI/qml into qml_is…
Chiffafox Oct 16, 2023
13d4faa
typos and use StatePrep
Chiffafox Oct 16, 2023
7582f2d
fix italicize
Chiffafox Oct 16, 2023
220891d
update block2 install, new release has all funcs we need
Chiffafox Oct 16, 2023
fa4a97b
visual edits
Chiffafox Oct 16, 2023
25c4657
links for all external packages
Chiffafox Oct 16, 2023
88dbacf
improve the overlap section
Chiffafox Oct 16, 2023
cb3576e
light style edits and changed to h3+ example with printing
Chiffafox Oct 17, 2023
8da4859
style edits
Chiffafox Oct 17, 2023
4c3ab86
move tol description higher
Chiffafox Oct 17, 2023
0c231de
style edits
Chiffafox Oct 17, 2023
696808a
style edits from code review
Chiffafox Oct 17, 2023
4d711a4
clarify dmrg code block
Chiffafox Oct 17, 2023
7204149
add dmrg and shci output as text
Chiffafox Oct 17, 2023
561824c
added text output for shci and dmrg
Chiffafox Oct 17, 2023
f458913
final stylistic edits and finish h3+
Chiffafox Oct 17, 2023
f2be96f
print tot iterations and generate figure
Chiffafox Oct 17, 2023
7250f50
modify overlap section to reflect new example
Chiffafox Oct 17, 2023
3aa940c
remove pre-computed figures
Chiffafox Oct 17, 2023
4c0debd
replace header image
Chiffafox Oct 17, 2023
4bb2738
point to new image
Chiffafox Oct 17, 2023
f8f5e18
stylistic edits
Chiffafox Oct 17, 2023
addba50
style edits
Chiffafox Oct 17, 2023
c2408fa
style edits
Chiffafox Oct 17, 2023
55a63a6
style edits to overlap output
Chiffafox Oct 17, 2023
acb039f
style edits
Chiffafox Oct 17, 2023
905eeee
final stylistic changes
Chiffafox Oct 17, 2023
b583155
Apply suggestions from code review
Chiffafox Oct 17, 2023
f50d1db
Update demonstrations/tutorial_initial_state_preparation.py
KetpuntoG Oct 18, 2023
f8c5e20
thumbnails + black
KetpuntoG Oct 18, 2023
b58d9bc
Merge branch 'qml_isp_demo' of https://github.com/PennyLaneAI/qml int…
KetpuntoG Oct 18, 2023
fb01731
random space in the name
KetpuntoG Oct 18, 2023
afcd9b5
fixing uri
KetpuntoG Oct 18, 2023
75e909d
stylistic edits
Chiffafox Oct 18, 2023
823c3b9
style edits
Chiffafox Oct 18, 2023
fa4f1b9
comments on best initial state options
Chiffafox Oct 18, 2023
23d5f67
Merge branch 'dev' into qml_isp_demo
Chiffafox Oct 18, 2023
cd9c239
shci and application:vqe headers style edit
Chiffafox Oct 18, 2023
5bae116
bold text edit
Chiffafox Oct 18, 2023
1d1e118
final style edits
Chiffafox Oct 18, 2023
6cf7cc4
Apply suggestions from code review
Chiffafox Oct 18, 2023
c360578
Merge branch 'qml_isp_demo' of github.com:PennyLaneAI/qml into qml_is…
Chiffafox Oct 18, 2023
04fa37d
Apply suggestions from code review
Chiffafox Oct 18, 2023
6583bac
final visual edits
Chiffafox Oct 18, 2023
7dd1aa7
combine with github edits
Chiffafox Oct 18, 2023
4bb9e26
remove blank lines
soranjh Oct 19, 2023
b0793f1
style edits
Chiffafox Oct 19, 2023
57e0732
Merge branch 'qml_isp_demo' of github.com:PennyLaneAI/qml into qml_is…
Chiffafox Oct 19, 2023
3fb43db
remove bold font
Chiffafox Oct 19, 2023
d91252a
Merge branch 'dev' into qml_isp_demo
Chiffafox Oct 19, 2023
bb2679a
CCSD header fix
Chiffafox Oct 19, 2023
a884e30
cisd paragraph render error
Chiffafox Oct 19, 2023
145c7b3
split big VQE codeblock
Chiffafox Oct 20, 2023
0620b90
final text edits and typo fixes
Chiffafox Oct 20, 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
Binary file added _static/authors/stepan_fomichev.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions _static/authors/stepan_fomichev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.. bio:: Stepan Fomichev
:photo: ../_static/authors/stepan_fomichev.jpg


Stepan Fomichev is a quantum scientist working at Xanadu. His background is in condesned matter physics, with a focus on lattice vibrations and electron-phonon coupling. As part of the Algorithms team, he focuses on researching and developing prospective applications for quantum algorithms.
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added demonstrations/initial_state_preparation/stub.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 39 additions & 0 deletions demonstrations/tutorial_initial_state_preparation.metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"title": "Initial State Preparation for Quantum Chemistry",
"authors": [
{
"id": "stepan_fomichev"
}
],
"dateOfPublication": "2023-10-20T00:00:00+00:00",
"dateOfLastModification": "2023-10-20T00:00:00+00:00",
"categories": [
"Quantum Chemistry"
],
"tags": [],
"previewImages": [
{
"type": "thumbnail",
"uri": "/_images/NOON.png"
}
],
"seoDescription": "Prepare initial states for quantum algorithms from output of traditional quantum chemistry methods.",
"doi": "",
"canonicalURL": "/qml/demos/tutorial_initial_state_preparation",
"references": [
],
"basedOnPapers": [],
"referencedByPapers": [],
"relatedContent": [
{
"type": "demonstration",
"id": "tutorial_quantum_chemistry",
"weight": 1.0
},
{
"type": "demonstration",
"id": "tutorial_vqe",
"weight": 1.0
}
]
}
237 changes: 237 additions & 0 deletions demonstrations/tutorial_initial_state_preparation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
r"""

Initial state preparation for quantum chemistry
===============================================

.. meta::
:property="og:description": Understand the concept of the initial state, and learn how to prepare it with PennyLane
:property="og:image": https://pennylane.ai/qml/_images/thumbnail_tutorial_initial_state_preparation.png

.. related::
tutorial_quantum_chemistry Building molecular Hamiltonians
tutorial_vqe A brief overview of VQE

*Author: Stepan Fomichev — Posted: 20 October 2023. Last updated: 20 October 2023.*
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved

A high-quality initial state can significantly reduce the runtime of many quantum algorithms. From
the variational quantum eigensolver (VQE) to quantum phase estimation (QPE), to even the recent
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
intermediate-scale quantum (ISQ) algorithms, obtaining the ground state of a chemical system require
a good initial state. For instance, in the case of VQE, a good initial state directly translates into fewer
optimization steps. In QPE, the probability of measuring the ground-state energy is directly
proportional to the overlap of the initial and ground states. Even beyond quantum phase estimation,
good initial guesses are important for algorithms like quantum approximate optimization (QAOA)
and Grover search.

Much like searching for a needle in a haystack, there are a lot of things you might try
to prepare a good guess for the ground-state in the large-dimensional Hilbert space. In this
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
tutorial, we show how to use traditional computational chemistry techniques to
get us _most of the way_ to an initial state. Such an initial state will not be the
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
ground-state, but it will certainly be better than the standard guess of a computational
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
basis state :math:`\ket{0}^{\otimes N}` or the Hartree-Fock state.

Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
Importing initial states
------------------------
We can import initial states obtained from several post-Hartree-Fock quantum chemistry calculations
to PennyLane. These methods are incredibly diverse in terms of their outputs, not always returning
an object that can be turned into a PennyLane statevector. We have already done this hard
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
work of conversion: all that you need to do is run these methods and pass their outputs
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
to PennyLane's :func:`~.pennylane.qchem.import_state` function. The currently supported methods are
configuration interaction with singles and doubles (CISD), coupled cluster (CCSD), Density-matrix
renormalization group (DMRG) and Semistochastic heat-bath configuration interaction (SHCI).

CISD states
^^^^^^^^^^^
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
The first line of attack for initial state preparation is CISD calculations performed with the PySCF
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
library.It is unsophisticated but fast. It will not be much help for strongly correlated molecules,
but it is better than Hartree-Fock. Here is the code example based on the restricted Hartree-Fock
orbitals, but the unrestricted version is available too.
soranjh marked this conversation as resolved.
Show resolved Hide resolved
"""

from pyscf import gto, scf, ci
from pennylane.qchem import import_state
R = 0.71
mol = gto.M(atom=[['H', (0, 0, 0)], ['H', (0,0,R)]], basis='sto6g', symmetry='d2h')
myhf = scf.RHF(mol).run()
myci = ci.CISD(myhf).run()
wf_cisd = import_state(myci, tol=1e-1)
print(f"CISD-based statevector\n{wf_cisd}")

##############################################################################
# The final object, PennyLane's statevector `wf_cisd`, is ready to be used as an
# initial state in a quantum circuit in PennyLane -- we will showcase this below for VQE.
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# Conversion for CISD is straightforward: simply assign the PySCF-stored CI coefficients
# to appropriate determinants.
#
# CCSD states
# ^^^^^^^^^^^
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# The function `import_state` is general, and can automatically detect the input type
# and apply the appropriate conversion protocol. It works similarly to the above for CCSD.

from pyscf import cc
mycc = cc.CCSD(myhf).run()
wf_ccsd = import_state(mycc, tol=1e-1)
print(f"CCSD-based statevector\n{wf_ccsd}")

##############################################################################
# For CCSD conversion, the exponential form is expanded and terms are collected to
# second order to obtain the CI coefficients.
#
# The second attribute `tol` specifies the cutoff beyond which contributions to the
# wavefunctions are neglected. Internally, wavefunctions are stored in their Slater
# determinant representation, and if their prefactor coefficient is below `tol`, those
# determinants are dropped from the expression.
#
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# DMRG states
# ^^^^^^^^^^^
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# The DMRG calculations involve running the library Block2. To install the Block2 library with
# functionality needed for this demo, execute
#
# .. code-block:: bash
#
# pip install block2==0.5.2rc10 --extra-index-url=https://block-hczhai.github.io/block2-preview/pypi/
#
# The DMRG calculation is run on top of the molecular orbitals obtained by Hartree-Fock,
# stored in `myhf` object, which we can re-use from before.
#
# .. code-block::python
#
# from pyscf import mcscf
# from pyblock2.driver.core import DMRGDriver, SymmetryTypes
# from pyblock2._pyscf.ao2mo import integrals as itg
# mc = mcscf.CASCI(myhf, 2, 2)
# ncas, n_elec, spin, ecore, h1e, g2e, orb_sym = \
# itg.get_rhf_integrals(myhf, mc.ncore, mc.ncas, g2e_symm=8)
# driver = DMRGDriver(scratch="./dmrg_temp", symm_type=SymmetryTypes.SZ)
# driver.initialize_system(n_sites=ncas, n_elec=n_elec, spin=spin, orb_sym=orb_sym)
# mpo = driver.get_qc_mpo(h1e=h1e, g2e=g2e, ecore=ecore, iprint=0)
# ket = driver.get_random_mps(tag="GS")
# driver.dmrg(mpo, ket, n_sweeps=30,bond_dims=[100,200],\
# noises=[1e-3,1e-5],thrds=[1e-6,1e-7],tol=1e-6)
# dets, coeffs = driver.get_csf_coefficients(ket, iprint=0)
# dets = dets.tolist()
# wf_dmrg = import_state((dets, coeffs), tol=1e-1)
# print(f"DMRG-based statevector\n{wf_dmrg}")
#
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# The crucial part is calling `get_csf_coefficients()` on the solution stored in
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# MPS form in the `ket`. This triggers an internal reconstruction calculation that
# converts the MPS to the sum of Slater determinants form, returning the output
# as a tuple `(list([int]), array(float])). The first element expresses a given Slater
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# determinant using Fock occupation vectors of length equal to the number of spatial
# orbitals in Block2 notation, where `0` is unoccupied, `1` is occupied with spin-up
# electron, `2` is occupied with spin-down, and `3` is doubly occupied. The first
# element must be converted to `list` for `import_state` to accept it. The second
# element stores the CI coefficients.
#
# In principle, this functionality can be used to generate any initial state, provided
# the user specifies a list of Slater determinants and their coefficients in this form.
#
# SHCI states
# ^^^^^^^^^^^
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# The SHCI calculations involve running the library Dice. For Dice, the installation process is more
# complicated but the execution process is similar:
#
# .. code-block:: bash
#
# from pyscf.shciscf import shci
# ncas, nelecas_a, nelecas_b = mol.nao, mol.nelectron // 2, mol.nelectron // 2
# myshci = mcscf.CASCI(myhf, ncas, (nelecas_a, nelecas_b))
# output_file = f"shci_output.out"
# myshci.fcisolver = shci.SHCI(myhf.mol)
# myshci.fcisolver.outputFile = output_file
# e_tot, e_ci, ss, mo_coeff, mo_energies =
# myshci.kernel(verbose=5)
# wavefunction = get_dets_coeffs_output(output_file)
# print(type(wavefunction[0][0]))
# print(dets, coeffs)
# (dets, coeffs) = [post-process shci_output.out to get tuple of
soranjh marked this conversation as resolved.
Show resolved Hide resolved
# dets (list of strs) and coeffs (list of floats)]
# wf_shci = import_state((dets, coeffs), tol=1e-1)
# print(f"SHCI-based statevector\n{wf_shci}")
#
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# If you are interested in a library that wraps all these methods and makes it easy to
# generate initial states from them, you should try Overlapper, our internal
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# package built specifically for using traditional quantum chemistry methods
# to construct initial states.
#
# Application: speed up VQE
# -------------------------
#
# Let us now demonstrate how the choice of a better initial state shortens the runtime
# of VQE for obtaining the ground-state energy of a molecule. As a first step, create a
# molecule, a device and a simple VQE circuit with double excitations
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved

import pennylane as qml
from pennylane import qchem
from pennylane import numpy as np
H2mol, qubits = qchem.molecular_hamiltonian(["H", "H"],\
np.array([0,0,0,0,0,R/0.529]),basis="sto-3g")

dev = qml.device("default.qubit", wires=qubits)

def circuit_VQE(theta, wires, initstate):
qml.QubitStateVector(initstate, wires=wires)
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
qml.DoubleExcitation(theta, wires=wires)

@qml.qnode(dev, interface="autograd")
soranjh marked this conversation as resolved.
Show resolved Hide resolved
def cost_fn(theta, initstate=None, ham=H2mol):
circuit_VQE(theta, wires=list(range(qubits)), initstate=initstate)
return qml.expval(ham)
soranjh marked this conversation as resolved.
Show resolved Hide resolved

##############################################################################
# The `initstate` variable is where we can insert different initial states. Next, create a
# function to execute VQE

def run_VQE(initstate, ham=H2mol, conv_tol=1e-4, max_iterations=30):
opt = qml.GradientDescentOptimizer(stepsize=0.4)
theta = np.array(0.0, requires_grad=True)
delta_E, iteration = 10, 0
while abs(delta_E) > conv_tol and iteration < max_iterations:
theta, prev_energy = opt.step_and_cost(cost_fn, theta, initstate=initstate, ham=ham)
new_energy = cost_fn(theta, initstate=initstate, ham=ham)
delta_E = new_energy - prev_energy
iteration += 1
energy_VQE = cost_fn(theta, initstate=initstate, ham=ham)
theta_opt = theta
return energy_VQE, theta_opt
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved

##############################################################################
# Now let's compare the number of iterations to convergence for the Hartree-Fock state
# versus the CCSD state

wf_hf = np.zeros(2**qubits)
wf_hf[3] = 1.
energy_hf, theta_hf = run_VQE(wf_hf)
energy_ccsd, theta_ccsd = run_VQE(wf_ccsd)

##############################################################################
# We can also consider what happens when you make the molecule more correlated, for example
# by stretching its bonds. Simpler methods like HF will require even more VQE iterations,
# while SHCI and DMRG will continue to provide good starting points for the algorithm.

H2mol_corr, qubits = qchem.molecular_hamiltonian(["H", "H"],\
np.array([0,0,0,0,0,R*2/0.529]),basis="sto-3g")
energy_hf, theta_hf = run_VQE(wf_hf, ham=H2mol_corr)
energy_ccsd, theta_ccsd = run_VQE(wf_ccsd, ham=H2mol_corr)
# energy_dmrg, theta_dmrg = run_VQE(wf_dmrg, ham=H2mol_corr)
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved

##############################################################################
# Finally, it is straightforward to compare the initial states through overlap -- the main
# metric of success for initial states in quantum algorithms. Because in PennyLane these
# are statevectors, computing an overlap is as easy as computing a dot product

ovlp = np.dot(wf_ccsd, wf_hf)
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved

##############################################################################
# Summary
# -------
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# This demo explains the concept of the initial state for quantum algorithms. Using the
# example of VQE, it demonstrates how a better choice of state -- obtained, for example
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# from a sophisticated computational chemistry method like CCSD, SHCI or DMRG -- can lead
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
# to much better algorithmic performance. It also shows simple workflows for how to run
# these computational chemistry methods, from libraries such as PySCF, Block2 and Dice,
# to generate outputs that can then be converted to PennyLane's statevector format
# with a single line of code.
#
# About the author
# ----------------
# .. include:: ../_static/authors/stepan_fomichev.txt
7 changes: 7 additions & 0 deletions demos_quantum-chemistry.rst
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,12 @@ Quantum chemistry is one of the leading application areas of quantum computers.
:description: :doc:`demos/tutorial_fermionic_operators`
:tags: chemistry

.. gallery-item::
:tooltip: Initial State Preparation for Quantum Chemistry
:figure: demonstrations/resource_estimation/resource_estimation.jpeg
Chiffafox marked this conversation as resolved.
Show resolved Hide resolved
:description: :doc:`demos/tutorial_initial_state_preparation`
:tags: chemistry

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


Expand All @@ -127,4 +133,5 @@ Quantum chemistry is one of the leading application areas of quantum computers.
demos/tutorial_classically_boosted_vqe
demos/tutorial_qchem_external
demos/tutorial_resource_estimation
demos/tutorial_initial_state_preparation