Skip to content

Commit fb548ef

Browse files
AWS Braket service backend (#388)
* Add AWS Braket service devices as backends * Add AWS Braket service devices as backends. Correct a braket in README * Add AWS Braket service devices as backends. Pass pycodestyle * AWS Braket service backend. Corrections as per the review * AWS Braket service backend. Correct test to use approx instead of == * AWS Braket service backend. Add tests to raise the coverage * AWS Braket service backend. Second review adjustments * Fix import errors when boto3 is not installed + use warnings.warn() * Fix condition when setting the number of controls * Minor adjustments in _awsbraket.py - Better handling of daggered gates - Some minor code cleanup * Make sure that unit tests are skipped if boto3 is not installed * Rapid fix to make sure that tests can be repeated without errors * Fixes for _awsbraket.py and its associated tests - Minor code cleanup - Modify functional tests to work with and without mapper - Fix issue when repeating some tests more than once - Add missing test for case where AWS Braket backend is used as a compiler engine * Minor adjustments to _awsbraket_boto3_client.py and related tests - Tweak user messages slightly - Add test to cover missing execution paths * Remove mapper in Jupyter notebook * Cleanup tests for _awsbraket.py + remove unneeded catch of TypeError * Adjust .coveragerc * Cleanup tests for _awsbraket_boto3_client.py * Fix erroneous license header * Mention installing ProjectQ with the 'braket' extra in README * Remove unneeded call to is_available in AWSBraketBackend + ... ... improve basic functional test. * Re-indent _awsbraket_boto3_client.py * Some more cleanup for _awsbraket.py * Some more cleanup for _awsbraket_boto3_client.py * Remove trivial mapper in default setup for AWS Braket backend * Fix test failure Co-authored-by: Damien Nguyen <[email protected]>
1 parent cee4688 commit fb548ef

16 files changed

+2900
-2
lines changed

.coveragerc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
[run]
22

33
omit = *_test.py
4+
*_fixtures.py

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ jobs:
5959
install:
6060
- env
6161
- python3 -m pip install -U pip setuptools wheel
62-
- python3 -m pip install -U pybind11 dormouse revkit flaky pytest-cov coveralls
62+
- python3 -m pip install -U pybind11 dormouse revkit flaky pytest-cov coveralls boto3
6363
- python3 -m pip install -r requirements.txt
6464
- python3 -m pip install -ve .
6565

README.rst

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ targeting various types of hardware, a high-performance quantum computer
2424
simulator with emulation capabilities, and various compiler plug-ins.
2525
This allows users to
2626

27-
- run quantum programs on the IBM Quantum Experience chip
27+
- run quantum programs on the IBM Quantum Experience chip, AQT devices or AWS Braket service provided devices
2828
- simulate quantum programs on classical computers
2929
- emulate quantum programs at a higher level of abstraction (e.g.,
3030
mimicking the action of large oracles instead of compiling them to
@@ -134,6 +134,44 @@ To run a program on the AQT trapped ion quantum computer, choose the `AQTBackend
134134
engine_list=compiler_engines)
135135
136136
137+
**Running a quantum program on a AWS Braket provided device**
138+
139+
To run a program on some of the devices provided by the AWS Braket service,
140+
choose the `AWSBraketBackend`. The currend devices supported are Aspen-8 from Rigetti,
141+
IonQ from IonQ and the state vector simulator SV1:
142+
143+
.. code-block:: python
144+
145+
from projectq.backends import AWSBraketBackend
146+
147+
creds = {
148+
'AWS_ACCESS_KEY_ID': 'your_aws_access_key_id',
149+
'AWS_SECRET_KEY': 'your_aws_secret_key',
150+
}
151+
152+
s3_folder = ['S3Bucket', 'S3Directory']
153+
device='IonQ'
154+
eng = MainEngine(AWSBraketBackend(use_hardware=True, credentials=creds, s3_folder=s3_folder,
155+
num_runs=1024, verbose=False, device=device),
156+
engine_list=[])
157+
158+
159+
.. note::
160+
161+
In order to use the AWSBraketBackend, you need to install ProjectQ with the 'braket' extra requirement:
162+
163+
.. code-block:: bash
164+
165+
python3 -m pip install projectq[braket]
166+
167+
or
168+
169+
.. code-block:: bash
170+
171+
cd /path/to/projectq/source/code
172+
python3 -m pip install -ve .[braket]
173+
174+
137175
**Classically simulate a quantum program**
138176

139177
ProjectQ has a high-performance simulator which allows simulating up to about 30 qubits on a regular laptop. See the `simulator tutorial <https://github.com/ProjectQ-Framework/ProjectQ/blob/feature/update-readme/examples/simulator_tutorial.ipynb>`__ for more information. Using the emulation features of our simulator (fast classical shortcuts), one can easily emulate Shor's algorithm for problem sizes for which a quantum computer would require above 50 qubits, see our `example codes <http://projectq.readthedocs.io/en/latest/examples.html#shor-s-algorithm-for-factoring>`__.

docs/tutorials.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ ProjectQ comes with a high-performance quantum simulator written in C++. Please
4444
.. note::
4545
ProjectQ should be installed on each computer individually as the C++ simulator compilation creates binaries which are optimized for the specific hardware on which it is being installed (potentially using our AVX version and `-march=native`). Therefore, sharing the same ProjectQ installation across different hardware may cause some problems.
4646

47+
**Install AWS Braket Backend requirement**
48+
49+
AWS Braket Backend requires the use of the official AWS SDK for Python, Boto3. This is an extra requirement only needed if you plan to use the AWS Braket Backend. To install ProjectQ inluding this requirement you can include it in the installation instruction as
50+
51+
.. code-block:: bash
52+
53+
python -m pip install --user projectq[braket]
54+
4755
4856
Detailed instructions and OS-specific hints
4957
-------------------------------------------

examples/awsbraket.ipynb

Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
{
2+
"metadata": {
3+
"language_info": {
4+
"codemirror_mode": {
5+
"name": "ipython",
6+
"version": 3
7+
},
8+
"file_extension": ".py",
9+
"mimetype": "text/x-python",
10+
"name": "python",
11+
"nbconvert_exporter": "python",
12+
"pygments_lexer": "ipython3",
13+
"version": "3.7.10-final"
14+
},
15+
"orig_nbformat": 2,
16+
"kernelspec": {
17+
"name": "python3",
18+
"display_name": "Python 3.7.10 64-bit",
19+
"metadata": {
20+
"interpreter": {
21+
"hash": "fd69f43f58546b570e94fd7eba7b65e6bcc7a5bbc4eab0408017d18902915d69"
22+
}
23+
}
24+
}
25+
},
26+
"nbformat": 4,
27+
"nbformat_minor": 2,
28+
"cells": [
29+
{
30+
"source": [
31+
"# Running ProjectQ code on AWS Braket service provided devices\n",
32+
"## Compiling code for AWS Braket Service\n",
33+
"\n",
34+
"In this tutorial we will see how to run code on some of the devices provided by the Amazon AWS Braket service. The AWS Braket devices supported are: the State Vector Simulator 'SV1', the Rigetti device 'Aspen-8' and the IonQ device 'IonQ'\n",
35+
"\n",
36+
"You need to have a valid AWS account, created a pair of access key/secret key, and have activated the braket service. As part of the activation of the service, a specific S3 bucket and folder associated to the service should be configured.\n",
37+
"\n",
38+
"First we need to do the required imports. That includes the mail compiler engine (MainEngine), the backend (AWSBraketBackend in this case) and the operations to be used in the cicuit"
39+
],
40+
"cell_type": "markdown",
41+
"metadata": {}
42+
},
43+
{
44+
"cell_type": "code",
45+
"execution_count": null,
46+
"metadata": {},
47+
"outputs": [],
48+
"source": [
49+
"from projectq import MainEngine\n",
50+
"from projectq.backends import AWSBraketBackend\n",
51+
"from projectq.ops import Measure, H, C, X, All\n"
52+
]
53+
},
54+
{
55+
"source": [
56+
"Prior to the instantiation of the backend we need to configure the credentials, the S3 storage folder and the device to be used (in the example the State Vector Simulator SV1)"
57+
],
58+
"cell_type": "markdown",
59+
"metadata": {}
60+
},
61+
{
62+
"cell_type": "code",
63+
"execution_count": null,
64+
"metadata": {},
65+
"outputs": [],
66+
"source": [
67+
"creds = {\n",
68+
" 'AWS_ACCESS_KEY_ID': 'aws_access_key_id',\n",
69+
" 'AWS_SECRET_KEY': 'aws_secret_key',\n",
70+
" } # replace with your Access key and Secret key\n",
71+
"\n",
72+
"s3_folder = ['S3Bucket', 'S3Directory'] # replace with your S3 bucket and directory\n",
73+
"\n",
74+
"device = 'SV1' # replace by the device you want to use"
75+
]
76+
},
77+
{
78+
"source": [
79+
"Next we instantiate the engine with the AWSBraketBackend including the credentials and S3 configuration. By setting the 'use_hardware' parameter to False we indicate the use of the Simulator. In addition we set the number of times we want to run the circuit and the interval in secons to ask for the results. For a complete list of parameters and descriptions, please check the documentation."
80+
],
81+
"cell_type": "markdown",
82+
"metadata": {}
83+
},
84+
{
85+
"cell_type": "code",
86+
"execution_count": null,
87+
"metadata": {},
88+
"outputs": [],
89+
"source": [
90+
"eng = MainEngine(AWSBraketBackend(use_hardware=False,\n",
91+
" credentials=creds,\n",
92+
" s3_folder=s3_folder,\n",
93+
" num_runs=10,\n",
94+
" interval=10))"
95+
]
96+
},
97+
{
98+
"source": [
99+
"We can now allocate the required qubits and create the circuit to be run. With the last instruction we ask the backend to run the circuit."
100+
],
101+
"cell_type": "markdown",
102+
"metadata": {}
103+
},
104+
{
105+
"cell_type": "code",
106+
"execution_count": null,
107+
"metadata": {},
108+
"outputs": [],
109+
"source": [
110+
"# Allocate the required qubits\n",
111+
"qureg = eng.allocate_qureg(3)\n",
112+
"\n",
113+
"# Create the circuit. In this example a quantum teleportation algorithms that teleports the first qubit to the third one.\n",
114+
"H | qureg[0]\n",
115+
"H | qureg[1]\n",
116+
"C(X) | (qureg[1], qureg[2])\n",
117+
"C(X) | (qureg[0], qureg[1])\n",
118+
"H | qureg[0]\n",
119+
"C(X) | (qureg[1], qureg[2])\n",
120+
"\n",
121+
"# At the end we measure the qubits to get the results; should be all-0 or all-1\n",
122+
"All(Measure) | qureg\n",
123+
"\n",
124+
"# And run the circuit\n",
125+
"eng.flush()\n"
126+
]
127+
},
128+
{
129+
"source": [
130+
"The backend will automatically create the task and generate a unique identifier (the task Arn) that can be used to recover the status of the task and results later on.\n",
131+
"\n",
132+
"Once the circuit is executed the indicated number of times, the results are stored in the S3 folder configured previously and can be recovered to obtain the probabilities of each of the states."
133+
],
134+
"cell_type": "markdown",
135+
"metadata": {}
136+
},
137+
{
138+
"cell_type": "code",
139+
"execution_count": null,
140+
"metadata": {},
141+
"outputs": [],
142+
"source": [
143+
"# Obtain and print the probabilies of the states\n",
144+
"prob_dict = eng.backend.get_probabilities(qureg)\n",
145+
"print(\"Probabilites for each of the results: \", prob_dict)"
146+
]
147+
},
148+
{
149+
"source": [
150+
"## Retrieve results form a previous execution\n",
151+
"\n",
152+
"We can retrieve the result later on (of this job or a previously executed one) using the task Arn provided when it was run. In addition, you have to remember the amount of qubits involved in the job and the order you used. The latter is required since we need to set up a mapping for the qubits when retrieving results of a previously executed job.\n",
153+
"\n",
154+
"To retrieve the results we need to configure the backend including the parameter 'retrieve_execution' set to the Task Arn of the job. To be able to get the probabilities of each state we need to configure the qubits and ask the backend to get the results."
155+
],
156+
"cell_type": "markdown",
157+
"metadata": {}
158+
},
159+
{
160+
"cell_type": "code",
161+
"execution_count": null,
162+
"metadata": {},
163+
"outputs": [],
164+
"source": [
165+
"# Set the Task Arn of the job to be retrieved and instantiate the engine with the AWSBraketBackend\n",
166+
"task_arn = 'your_task_arn' # replace with the actual TaskArn you want to use\n",
167+
"\n",
168+
"eng1 = MainEngine(AWSBraketBackend(retrieve_execution=task_arn, credentials=creds, num_retries=2, verbose=True))\n",
169+
"\n",
170+
"# Configure the qubits to get the states probabilies\n",
171+
"qureg1 = eng1.allocate_qureg(3)\n",
172+
"\n",
173+
"# Ask the backend to retrieve the results\n",
174+
"eng1.flush()\n",
175+
"\n",
176+
"# Obtain and print the probabilities of the states\n",
177+
"prob_dict1 = eng1.backend.get_probabilities(qureg1)\n",
178+
"print(\"Probabilities \", prob_dict1)\n"
179+
]
180+
},
181+
{
182+
"source": [
183+
"We can plot an histogram with the probabilities as well."
184+
],
185+
"cell_type": "markdown",
186+
"metadata": {}
187+
},
188+
{
189+
"cell_type": "code",
190+
"execution_count": null,
191+
"metadata": {},
192+
"outputs": [],
193+
"source": [
194+
"import matplotlib.pyplot as plt\n",
195+
"%matplotlib inline\n",
196+
"from projectq.libs.hist import histogram\n",
197+
"\n",
198+
"histogram(eng1.backend, qureg1)\n",
199+
"plt.show()"
200+
]
201+
},
202+
{
203+
"cell_type": "code",
204+
"execution_count": null,
205+
"metadata": {},
206+
"outputs": [],
207+
"source": []
208+
}
209+
]
210+
}

projectq/backends/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,12 @@
2525
circuit)
2626
* an interface to the IBM Quantum Experience chip (and simulator).
2727
* an interface to the AQT trapped ion system (and simulator).
28+
* an interface to the AWS Braket service decives (and simulators)
2829
"""
2930
from ._printer import CommandPrinter
3031
from ._circuits import CircuitDrawer, CircuitDrawerMatplotlib
3132
from ._sim import Simulator, ClassicalSimulator
3233
from ._resource import ResourceCounter
3334
from ._ibm import IBMBackend
3435
from ._aqt import AQTBackend
36+
from ._awsbraket import AWSBraketBackend
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Copyright 2021 ProjectQ-Framework (www.projectq.ch)
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
try:
16+
from ._awsbraket import AWSBraketBackend
17+
except ImportError: # pragma: no cover
18+
import warnings
19+
warnings.warn("Failed to import one of the dependencies required to use "
20+
"the Amazon Braket Backend.\n"
21+
"Did you install ProjectQ using the [braket] extra? "
22+
"(python3 -m pip install projectq[braket])")
23+
24+
# Make sure that the symbol is defined
25+
class AWSBraketBackend:
26+
pass

0 commit comments

Comments
 (0)