Skip to content

Commit

Permalink
Merge pull request #400 from Quantum-TII/simtfrename
Browse files Browse the repository at this point in the history
refactoring for qibotf
  • Loading branch information
scarrazza committed May 2, 2021
2 parents be16503 + 544f87c commit 8cdcdcd
Show file tree
Hide file tree
Showing 40 changed files with 423 additions and 324 deletions.
56 changes: 0 additions & 56 deletions .github/scripts/build-linux.sh

This file was deleted.

40 changes: 0 additions & 40 deletions .github/scripts/retry.sh

This file was deleted.

9 changes: 8 additions & 1 deletion .github/workflows/rules.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,18 @@ jobs:
with:
brew: libomp
- name: Install package
if: startsWith(matrix.os, 'windows') == 0
run: |
python -m pip install --upgrade pip
pip install pylint
pip install pytest-cov
pip install .[qibotf,docs,tests]
- name: Install package on Windows
if: startsWith(matrix.os, 'windows')
run: |
python -m pip install --upgrade pip
pip install pylint
pip install pytest-cov
pip install -r requirements.txt
pip install .[docs,tests]
- name: Test with pylint
run: |
Expand Down
29 changes: 11 additions & 18 deletions .github/workflows/wheels.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,33 +24,26 @@ jobs:
uses: mstksg/get-package@v1
with:
brew: libomp
- name: Build linux wheels
if: startsWith(matrix.os, 'ubuntu')
run: docker run --rm -e PYTHON_VERSION -v `pwd`:/io quay.io/pypa/manylinux2010_x86_64 /io/.github/scripts/build-linux.sh
env:
PYTHON_VERSION: ${{ matrix.python-version }}
- name: Build macos wheels
if: startsWith(matrix.os, 'macos')
- name: Build wheels
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
python setup.py bdist_wheel
pip install delocate
cd dist
delocate-wheel -v `ls`
- name: Build windows wheels
if: startsWith(matrix.os, 'windows')
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
python setup.py bdist_wheel
pip install wheel
python setup.py sdist bdist_wheel
- name: Store wheels as artifacts
uses: actions/upload-artifact@v2
with:
name: wheels
path: dist
- name: Test wheels
if: startsWith(matrix.os, 'windows') == 0
run: |
python -m pip install --upgrade pip
pip install qibotf pytest cirq ply sklearn
pip install -r requirements.txt
pip install qibo --no-index --find-links ./dist/
pytest --pyargs qibo
- name: Test wheels on windows
if: startsWith(matrix.os, 'windows')
run: |
python -m pip install --upgrade pip
pip install pytest cirq ply sklearn
Expand Down
3 changes: 2 additions & 1 deletion doc/source/applications.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ problems.
tutorials/shor/README.md
tutorials/qPDF/qPDF.ipynb
tutorials/bell-variational/README.md
tutorials/grover/README.md
tutorials/falqon/README.md
tutorials/grover/README.md
1 change: 1 addition & 0 deletions doc/source/tutorials/falqon/README.md
1 change: 1 addition & 0 deletions doc/source/tutorials/falqon/images
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ physics problems.
- [Shor's factorization algorithm](shor/README.md)
- [Determining the proton content with proton with a quantum computer](qPDF/qPDF.ipynb)
- [Maximal violation of Bell inequalities variationally](bell-variational/README.md)
- [Feedback-based ALgorithm for Quantum OptimizatioN - FALQON](falqon/README.md)
- [A general Grover model](grover/README.md)

In the `benchmarks` folder we have included examples concerning:
Expand Down
50 changes: 50 additions & 0 deletions examples/falqon/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Feedback-based ALgorithm for Quantum OptimizatioN - FALQON

Code at: [https://github.com/Quantum-TII/qibo/tree/master/examples/falqon](https://github.com/Quantum-TII/qibo/tree/master/examples/falqon)

Quantum Approximate Optimisation Algorithm (QAOA) is considered as one of the most important algorithms for optimisation in Quantum Computers, see [arXiv:1411.4028](https://arxiv.org/abs/1411.4028) by Farhi, Goldstone and Gutmann for more information.

In this QAOA algorithm, the aim is to have a problem Hamiltonian H_P and a mixer Hamiltonian H_B. Then, starting with the ground state of H_B, the goal is to repeatedly apply e^(i H_P c) and e^(i H_B b), where c and b are tunable parameters. The values of such parameters are to be found via classical optimization

In the FALQON algorithm, [arXiv:2103.08619](https://arxiv.org/abs/2103.08619) by Magann, Rudinger, Grace and Sarovan, they propose a similar although conceptually different algorithm. The proposal consists in evolving the initial state using the Schrödinger equation

![schrodingerequation](images/schrodinger_equation.png)

This equation satisfies that the expectation value of H_P is monotonically decreasing. This feature is used to create a Hamiltonian evolution with 1 layer using e^(i H_P c) and e^(i H_B b). In the first layer, b=0, and c is a parameter to be defined. Then, the quantity A = i[H_P, H_B] is measured. Its expectation value is then taken to be the parameter b for the next layer. As more layers are added, the
approximation to the ground state of the problem Hamiltonian H_P is more and more accurate.

![scheme](images/scheme.png)

### Running the code

This example contains just one file
- `main.py` is the file where the algorithm is run. The main class `FALQON` is now introduced in `QIBO`

The `FALQON` class behaves similarly to the `QAOA` one. It admits the following parameters:
- `hamiltonian`: problem Hamiltonian
whose ground state is sought.
- `mixer`: mixer Hamiltonian.
If ``None``, `qibo.hamiltonians.X` is used.
- `solver`: solver used to apply the exponential operators.
Default solver is 'exp'.
- `callbacks`: List of callbacks to calculate during evolution.
- `accelerators`: Dictionary of devices to use for distributed
execution. See `qibo.tensorflow.distcircuit.DistributedCircuit`
for more details. This option is available only when ``hamiltonian``
is a `qibo.abstractions.hamiltonians.TrotterHamiltonian`.
- `memory_device`: Name of device where the full state will be saved.
Relevant only for distributed execution (when ``accelerators`` is
given).

When performing the execution of the problem, the following variables are to be set:

- `delta_t`: initial guess for the time step. A too large delta_t will make the algorithm fail.
- `max_layers`: maximum number of layers allowed for the FALQON.
- `initial_state`: initial state vector of the FALQON.
- `tol`: Tolerance of energy change. If not specified, no check is done.
- `callback`: Called after each iteration for scipy optimizers.
- `options`: a dictionary with options for the different optimizers.
- `compile`: whether the TensorFlow graph should be compiled.
- `processes`: number of processes when using the paralle BFGS method.

The attached example provides an easy implementation of the FALQON method for a Heisenberg XXZ model.
Binary file added examples/falqon/images/scheme.png
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 examples/falqon/images/schrodinger_equation.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 24 additions & 0 deletions examples/falqon/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import argparse
from qibo import models, hamiltonians


def main(nqubits, delta_t=.1, max_layers=100):
# create XXZ Hamiltonian for nqubits qubits
hamiltonian = hamiltonians.XXZ(nqubits)
# create FALQON model for this Hamiltonian
falqon = models.FALQON(hamiltonian)

best_energy, final_parameters = falqon.minimize(delta_t, max_layers)[:2]

print('The optimal energy found is', best_energy)

return best_energy, final_parameters


if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--nqubits", default=5, type=int, help="Number of qubits.")
parser.add_argument("--delta_t", default=.1, type=float, help="Optimization parameter, time step for the first layer")
parser.add_argument("--max_layers", default=100, type=int, help="Maximum number of layers")
args = vars(parser.parse_args())
main(**args)
3 changes: 3 additions & 0 deletions examples/reuploading_classifier/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ def create_target(name):
* np.sqrt(2 / 3)], dtype=complex),
np.array([1 / np.sqrt(3), np.exp(-1j * 2 * np.pi / 3) * np.sqrt(2 / 3)], dtype=complex)]

else:
raise NotImplementedError('This dataset is not implemented')

return targets


Expand Down
15 changes: 10 additions & 5 deletions examples/reuploading_classifier/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# /usr/bin/env python
import datasets as ds
import numpy as np
from qlassifier import single_qubit_classifier
import pickle
import argparse

#TODO: fix issue with .pkl

parser = argparse.ArgumentParser()
parser.add_argument("--dataset", default='tricrown',
help="Name of the example", type=str)
Expand All @@ -20,9 +20,13 @@ def main(dataset, layers):
layers (int): Number of layers to use in the classifier
"""
ql = single_qubit_classifier(dataset, layers) # Define classifier
with open('saved_parameters.pkl', 'rb') as f:
# Load previous results. Have we ever run these problem?
data = pickle.load(f)
try:
with open('saved_parameters.pkl', 'rb') as f:
# Load previous results. Have we ever run these problem?
data = pickle.load(f)
except:
data = {dataset: {}}

try:
parameters = data[dataset][layers]
print('Problem solved before, obtaining parameters from file...')
Expand All @@ -31,6 +35,7 @@ def main(dataset, layers):
print('Problem never solved, finding optimal parameters...')
result, parameters = ql.minimize(
method='l-bfgs-b', options={'disp': True})

data[dataset][layers] = parameters
with open('saved_parameters.pkl', 'wb') as f:
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
Expand Down
Binary file modified examples/reuploading_classifier/saved_parameters.pkl
Binary file not shown.
14 changes: 14 additions & 0 deletions examples/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,19 @@ def test_shor(N, times, A, semiclassical, enhance):
run_script(args)


@pytest.mark.parametrize("nqubits", [4, 5])
@pytest.mark.parametrize("delta_t", [0.5, 0.1])
@pytest.mark.parametrize("max_layers", [10, 100])
def test_falqon(nqubits, delta_t, max_layers):
if "functions" in sys.modules:
del sys.modules["functions"]
args = locals()
path = os.path.join(base_dir, "falqon")
sys.path[-1] = path
os.chdir(path)
run_script(args)


@pytest.mark.parametrize("nqubits", [5, 6, 7])
def test_grover_example1(nqubits):
args = locals()
Expand Down Expand Up @@ -274,3 +287,4 @@ def test_grover_example3(nqubits, num_1):
sys.path[-1] = path
os.chdir(path)
run_script(args, script_name="example3.py")

2 changes: 0 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# Runtime requirements for qibo

# numpy (included in tf)
tensorflow==2.4.1
scipy
sympy
cma
Expand Down
Loading

0 comments on commit 8cdcdcd

Please sign in to comment.