A python SDK for interacting with quantum devices on Amazon Braket

Overview

Amazon Braket Python SDK

Latest Version Supported Python Versions Build Status codecov Documentation Status Code Style: Black

The Amazon Braket Python SDK is an open source library that provides a framework that you can use to interact with quantum computing hardware devices through Amazon Braket.

Prerequisites

Before you begin working with the Amazon Braket SDK, make sure that you've installed or configured the following prerequisites.

Python 3.7.2 or greater

Download and install Python 3.7.2 or greater from Python.org.

Git

Install Git from https://git-scm.com/downloads. Installation instructions are provided on the download page.

IAM user or role with required permissions

As a managed service, Amazon Braket performs operations on your behalf on the AWS hardware that is managed by Amazon Braket. Amazon Braket can perform only operations that the user permits. You can read more about which permissions are necessary in the AWS Documentation.

The Braket Python SDK should not require any additional permissions aside from what is required for using Braket. However, if you are using an IAM role with a path in it, you should grant permission for iam:GetRole.

To learn more about IAM user, roles, and policies, see Adding and Removing IAM Identity Permissions.

Boto3 and setting up AWS credentials

Follow the installation instructions for Boto3 and setting up AWS credentials.

Note: Make sure that your AWS region is set to one supported by Amazon Braket. You can check this in your AWS configuration file, which is located by default at ~/.aws/config.

Configure your AWS account with the resources necessary for Amazon Braket

If you are new to Amazon Braket, onboard to the service and create the resources necessary to use Amazon Braket using the AWS console.

Installing the Amazon Braket Python SDK

The Amazon Braket Python SDK can be installed with pip as follows:

pip install amazon-braket-sdk

You can also install from source by cloning this repository and running a pip install command in the root directory of the repository:

git clone https://github.com/aws/amazon-braket-sdk-python.git
cd amazon-braket-sdk-python
pip install .

Check the version you have installed

You can view the version of the amazon-braket-sdk you have installed by using the following command:

pip show amazon-braket-sdk

You can also check your version of amazon-braket-sdk from within Python:

>>> import braket._sdk as braket_sdk
>>> braket_sdk.__version__

Updating the Amazon Braket Python SDK

You can update the version of the amazon-braket-sdk you have installed by using the following command:

pip install amazon-braket-sdk --upgrade --upgrade-strategy eager

Usage

Running a circuit on an AWS simulator

import boto3
from braket.aws import AwsDevice
from braket.circuits import Circuit

device = AwsDevice("arn:aws:braket:::device/quantum-simulator/amazon/sv1")
s3_folder = ("amazon-braket-Your-Bucket-Name", "folder-name") # Use the S3 bucket you created during onboarding

bell = Circuit().h(0).cnot(0, 1)
task = device.run(bell, s3_folder, shots=100)
print(task.result().measurement_counts)

The code sample imports the Amazon Braket framework, then defines the device to use (the SV1 AWS simulator). The s3_folder statement defines the Amazon S3 bucket for the task result and the folder in the bucket to store the task result. This folder is created when you run the task. It then creates a Bell Pair circuit, executes the circuit on the simulator and prints the results of the job. This example can be found in ../examples/bell.py.

Running multiple tasks at once

Many quantum algorithms need to run multiple independent circuits, and submitting the circuits in parallel can be faster than submitting them one at a time. In particular, parallel task processing provides a significant speed up when using simulator devices. The following example shows how to run a batch of tasks on SV1:

circuits = [bell for _ in range(5)]
batch = device.run_batch(circuits, s3_folder, shots=100)
print(batch.results()[0].measurement_counts)  # The result of the first task in the batch

Running a hybrid job

from braket.aws import AwsQuantumJob

job = AwsQuantumJob.create(
    device="arn:aws:braket:::device/quantum-simulator/amazon/sv1",
    source_module="job.py",
    entry_point="job:run_job",
    wait_until_complete=True,
)
print(job.result())

where run_job is a function in the file job.py.

The code sample imports the Amazon Braket framework, then creates a hybrid job with the entry point being the run_job function. The hybrid job creates quantum tasks against the SV1 AWS Simulator. The job runs synchronously, and prints logs until it completes. The complete example can be found in ../examples/job.py.

Available Simulators

Amazon Braket provides access to two types of simulators: fully managed simulators, available through the Amazon Braket service, and the local simulators that are part of the Amazon Braket SDK.

  • Fully managed simulators offer high-performance circuit simulations. These simulators can handle circuits larger than circuits that run on quantum hardware. For example, the SV1 state vector simulator shown in the previous examples requires approximately 1 or 2 hours to complete a 34-qubit, dense, and square circuit (circuit depth = 34), depending on the type of gates used and other factors.
  • The Amazon Braket Python SDK includes an implementation of quantum simulators that can run circuits on your local, classic hardware. For example the braket_sv local simulator is well suited for rapid prototyping on small circuits up to 25 qubits, depending on the hardware specifications of your Braket notebook instance or your local environment. An example of how to execute the task locally is included in the repository ../examples/local_bell.py.

For a list of available simulators and their features, consult the Amazon Braket Developer Guide.

Debugging logs

Tasks sent to QPUs don't always run right away. To view task status, you can enable debugging logs. An example of how to enable these logs is included in repo: ../examples/debug_bell.py. This example enables task logging so that status updates are continuously printed to the terminal after a quantum task is executed. The logs can also be configured to save to a file or output to another stream. You can use the debugging example to get information on the tasks you submit, such as the current status, so that you know when your task completes.

Running a Quantum Algorithm on a Quantum Computer

With Amazon Braket, you can run your quantum circuit on a physical quantum computer.

The following example executes the same Bell Pair example described to validate your configuration on a Rigetti quantum computer.

import boto3
from braket.circuits import Circuit
from braket.aws import AwsDevice

device = AwsDevice("arn:aws:braket:::device/qpu/rigetti/Aspen-8")
s3_folder = ("amazon-braket-Your-Bucket-Name", "RIGETTI") # Use the S3 bucket you created during onboarding

bell = Circuit().h(0).cnot(0, 1)
task = device.run(bell, s3_folder) 
print(task.result().measurement_counts)

When you execute your task, Amazon Braket polls for a result. By default, Braket polls for 5 days; however, it is possible to change this by modifying the poll_timeout_seconds parameter in AwsDevice.run, as in the example below. Keep in mind that if your polling timeout is too short, results may not be returned within the polling time, such as when a QPU is unavailable, and a local timeout error is returned. You can always restart the polling by using task.result().

task = device.run(bell, s3_folder, poll_timeout_seconds=86400)  # 1 day 
print(task.result().measurement_counts)

To select a quantum hardware device, specify its ARN as the value of the device_arn argument. A list of available quantum devices and their features can be found in the Amazon Braket Developer Guide.

Important Tasks may not run immediately on the QPU. The QPUs only execute tasks during execution windows. To find their execution windows, please refer to the AWS console in the "Devices" tab.

Using Amazon Braket with D-Wave QPU

If you want to use Ocean with the D-Wave QPU, you can install the amazon-braket-ocean-plugin-python. Information about how to install the plugin is provided in the README for the repo.

Sample Notebooks

Sample Jupyter notebooks can be found in the amazon-braket-examples repo.

Braket Python SDK API Reference Documentation

The API reference, can be found on Read the Docs.

To generate the API Reference HTML in your local environment

To generate the HTML, first change directories (cd) to position the cursor in the amazon-braket-sdk-python directory. Then, run the following command to generate the HTML documentation files:

pip install tox
tox -e docs

To view the generated documentation, open the following file in a browser: ../amazon-braket-sdk-python/build/documentation/html/index.html

Testing

This repository has both unit and integration tests.

To run the tests, make sure to install test dependencies first:

pip install -e "amazon-braket-sdk-python[test]"

Unit Tests

To run the unit tests:

tox -e unit-tests

You can also pass in various pytest arguments to run selected tests:

tox -e unit-tests -- your-arguments

For more information, please see pytest usage.

To run linters and doc generators and unit tests:

tox

Integration Tests

First, configure a profile to use your account to interact with AWS. To learn more, see Configure AWS CLI.

After you create a profile, use the following command to set the AWS_PROFILE so that all future commands can access your AWS account and resources.

export AWS_PROFILE=YOUR_PROFILE_NAME

To run the integration tests for local jobs, you need to have Docker installed and running. To install Docker follow these instructions: Install Docker

Run the tests:

tox -e integ-tests

As with unit tests, you can also pass in various pytest arguments:

tox -e integ-tests -- your-arguments

Support

Issues and Bug Reports

If you encounter bugs or face issues while using the SDK, please let us know by posting the issue on our Github issue tracker.
For issues with the Amazon Braket service in general, please use the Developer Forum.

Feedback and Feature Requests

If you have feedback or features that you would like to see on Amazon Braket, we would love to hear from you!
Github issues is our preferred mechanism for collecting feedback and feature requests, allowing other users to engage in the conversation, and +1 issues to help drive priority.

License

This project is licensed under the Apache-2.0 License.

Comments
  • feature: Add noise operations and methods to add noise to circuits

    feature: Add noise operations and methods to add noise to circuits

    Description of changes: Add operations and a result type (density matrix) that are related to noise simulation. Add add_noise method to Circuits class.

    Build directory: build_files.tar.gz

    Merge Checklist

    Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request.

    General

    • [ x ] I have read the CONTRIBUTING doc
    • [ x ] I used the commit message format described in CONTRIBUTING
    • [ x ] I have updated any necessary documentation, including READMEs and API docs (if appropriate)

    Tests

    • [ x ] I have added tests that prove my fix is effective or that my feature works (if appropriate)
    • [ x ] I have checked that my tests are not configured for a specific region or account (if appropriate)

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by yitinche 15
  • QPU_REGIONS does not have a key for Rigetti Aspen-9

    QPU_REGIONS does not have a key for Rigetti Aspen-9

    Describe the bug

    In [1]: import braket.aws                                       
    
    In [2]: ionq_arn, rigetti_arn = "arn:aws:braket:::device/qpu/ionq/ionQdevice", "arn:aws:braket:::device/qpu/rigetti/Aspen-9"                                                                                                                                      
                                                                    
    In [3]: braket.aws.aws_device.AwsDevice(ionq_arn)  # no problems                                                                 
    Out[3]: Device('name': IonQ Device, 'arn': arn:aws:braket:::device/qpu/ionq/ionQdevice)
                                                                    
    In [4]: braket.aws.aws_device.AwsDevice(rigetti_arn)  # problems!                                                                
    ---------------------------------------------------------------------------
    NoRegionError                             Traceback (most recent call last)                                                                                                                                                                                       
    <ipython-input-4-330bf07a097a> in <module>
    ----> 1 braket.aws.aws_device.AwsDevice(rigetti_arn)  # problems!
    

    Additional context QPU_REGIONS does not have an entry for the new Aspen-9 device (active while Aspen-8 in maintenance). (Eventually, it would be preferable to not hardcode the regions of course)

    I'm currently fixing it by re-initializing the QPU_REGIONS of the AwsDevice class and including the missing arn. I imagine there is also a way to instead configure the region via an AwsSession but I got stuck trying to do that (please let me know if there is a nice way to do it).

    Screenshots or logs Full stacktrace:

    In [4]: braket.aws.aws_device.AwsDevice(rigetti_arn)  # problems!                                                                
    ---------------------------------------------------------------------------
    NoRegionError                             Traceback (most recent call last)
    <ipython-input-4-330bf07a097a> in <module>
    ----> 1 braket.aws.aws_device.AwsDevice(rigetti_arn)  # problems!
    
    ~/miniconda3/lib/python3.7/site-packages/braket/aws/aws_device.py in __init__(self, arn, aws_session)
         86         super().__init__(name=None, status=None)
         87         self._arn = arn
    ---> 88         self._aws_session = AwsDevice._aws_session_for_device(arn, aws_session)
         89         self._properties = None
         90         self._provider_name = None
    
    ~/miniconda3/lib/python3.7/site-packages/braket/aws/aws_device.py in _aws_session_for_device(device_arn, aws_session)
        315         """AwsSession: Returns an AwsSession for the device ARN."""
        316         if "qpu" in device_arn:
    --> 317             return AwsDevice._aws_session_for_qpu(device_arn, aws_session)
        318         else:
        319             return aws_session or AwsSession()
    
    ~/miniconda3/lib/python3.7/site-packages/braket/aws/aws_device.py in _aws_session_for_qpu(device_arn, aws_session)
        328         AWS Regions the devices are located in.
        329         """
    --> 330         return AwsDevice._copy_aws_session(aws_session, AwsDevice.QPU_REGIONS.get(device_arn), None)
        331 
        332     @staticmethod
    
    ~/miniconda3/lib/python3.7/site-packages/braket/aws/aws_device.py in _copy_aws_session(aws_session, region, max_connections)
        353         else:
        354             boto_session = boto3.Session(region_name=region) if region else None
    --> 355             return AwsSession(boto_session=boto_session, config=config)
        356 
        357     def __repr__(self):
    
    ~/miniconda3/lib/python3.7/site-packages/braket/aws/aws_session.py in __init__(self, boto_session, braket_client, config)
         38             self.braket_client = braket_client
         39         else:
    ---> 40             self.braket_client = self.boto_session.client("braket", config=self._config)
         41 
         42     #
    
    ~/miniconda3/lib/python3.7/site-packages/boto3/session.py in client(self, service_name, region_name, api_version, use_ssl, verify, endpoint_url, aws_access_key_id, aws_secret_access_key, aws_session_token, config)
        261             aws_access_key_id=aws_access_key_id,
        262             aws_secret_access_key=aws_secret_access_key,
    --> 263             aws_session_token=aws_session_token, config=config)
        264 
        265     def resource(self, service_name, region_name=None, api_version=None,
    
    ~/miniconda3/lib/python3.7/site-packages/botocore/session.py in create_client(self, service_name, region_name, api_version, use_ssl, verify, endpoint_url, aws_access_key_id, aws_secret_access_key, aws_session_token, config)
        836             is_secure=use_ssl, endpoint_url=endpoint_url, verify=verify,
        837             credentials=credentials, scoped_config=self.get_scoped_config(),
    --> 838             client_config=config, api_version=api_version)
        839         monitor = self._get_internal_component('monitor')
        840         if monitor is not None:
    
    ~/miniconda3/lib/python3.7/site-packages/botocore/client.py in create_client(self, service_name, region_name, is_secure, endpoint_url, verify, credentials, scoped_config, api_version, client_config)
         85         client_args = self._get_client_args(
         86             service_model, region_name, is_secure, endpoint_url,
    ---> 87             verify, credentials, scoped_config, client_config, endpoint_bridge)
         88         service_client = cls(**client_args)
         89         self._register_retries(service_client)
    
    ~/miniconda3/lib/python3.7/site-packages/botocore/client.py in _get_client_args(self, service_model, region_name, is_secure, endpoint_url, verify, credentials, scoped_config, client_config, endpoint_bridge)
        326         return args_creator.get_client_args(
        327             service_model, region_name, is_secure, endpoint_url,
    --> 328             verify, credentials, scoped_config, client_config, endpoint_bridge)
        329 
        330     def _create_methods(self, service_model):
    
    ~/miniconda3/lib/python3.7/site-packages/botocore/args.py in get_client_args(self, service_model, region_name, is_secure, endpoint_url, verify, credentials, scoped_config, client_config, endpoint_bridge)
         71         final_args = self.compute_client_args(
         72             service_model, client_config, endpoint_bridge, region_name,
    ---> 73             endpoint_url, is_secure, scoped_config)
         74 
         75         service_name = final_args['service_name']
    
    ~/miniconda3/lib/python3.7/site-packages/botocore/args.py in compute_client_args(self, service_model, client_config, endpoint_bridge, region_name, endpoint_url, is_secure, scoped_config)
        152             is_secure=is_secure,
        153             endpoint_bridge=endpoint_bridge,
    --> 154             s3_config=s3_config,
        155         )
        156         # Create a new client config to be passed to the client based
    
    ~/miniconda3/lib/python3.7/site-packages/botocore/args.py in _compute_endpoint_config(self, service_name, region_name, endpoint_url, is_secure, endpoint_bridge, s3_config)
        218         if service_name == 'sts':
        219             return self._compute_sts_endpoint_config(**resolve_endpoint_kwargs)
    --> 220         return self._resolve_endpoint(**resolve_endpoint_kwargs)
        221 
        222     def _compute_s3_endpoint_config(self, s3_config,
    
    ~/miniconda3/lib/python3.7/site-packages/botocore/args.py in _resolve_endpoint(self, service_name, region_name, endpoint_url, is_secure, endpoint_bridge)
        301                           endpoint_url, is_secure, endpoint_bridge):
        302         return endpoint_bridge.resolve(
    --> 303             service_name, region_name, endpoint_url, is_secure)
        304 
        305     def _compute_socket_options(self, scoped_config):
    
    ~/miniconda3/lib/python3.7/site-packages/botocore/client.py in resolve(self, service_name, region_name, endpoint_url, is_secure)
        400         region_name = self._check_default_region(service_name, region_name)
        401         resolved = self.endpoint_resolver.construct_endpoint(
    --> 402             service_name, region_name)
        403 
        404         # If we can't resolve the region, we'll attempt to get a global
    
    ~/miniconda3/lib/python3.7/site-packages/botocore/regions.py in construct_endpoint(self, service_name, region_name, partition_name)
        132         for partition in self._endpoint_data['partitions']:
        133             result = self._endpoint_for_partition(
    --> 134                 partition, service_name, region_name)
        135             if result:
        136                 return result
    
    ~/miniconda3/lib/python3.7/site-packages/botocore/regions.py in _endpoint_for_partition(self, partition, service_name, region_name, force_partition)
        146                 region_name = service_data['partitionEndpoint']
        147             else:
    --> 148                 raise NoRegionError()
        149         # Attempt to resolve the exact region for this partition.
        150         if region_name in service_data['endpoints']:
    
    NoRegionError: You must specify a region.
    
    bug 
    opened by singular-value 10
  • feature: Always accept identity observable factors

    feature: Always accept identity observable factors

    This enables simultaneous measurement of qubit-wise commuting Pauli words.

    Issue #, if available:

    Description of changes:

    Testing done:

    Merge Checklist

    Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request.

    General

    • [x] I have read the CONTRIBUTING doc
    • [x] I used the commit message format described in CONTRIBUTING
    • [x] I have updated any necessary documentation, including READMEs and API docs (if appropriate)

    Tests

    • [x] I have added tests that prove my fix is effective or that my feature works (if appropriate)
    • [x] I have checked that my tests are not configured for a specific region or account (if appropriate)

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by speller26 10
  • `calculate_unitary` raises error for one-qubit circuits on non-`q0` register

    `calculate_unitary` raises error for one-qubit circuits on non-`q0` register

    Describe the bug Calling calculate_unitary on a one-qubit circuit where the register is not q0 raises an error.

    To reproduce

    import numpy as np
    from braket.circuits import Circuit, Instruction, gates
    from braket.circuits.unitary_calculation import calculate_unitary
    
    qubit_index = 1
    circuit = Circuit()
    pgates = [
        gates.Rx,
        gates.Ry,
        gates.Rz,
        gates.PhaseShift,
    ]
    angles = np.random.RandomState(11).random(len(pgates))
    instructions = [
        Instruction(rot(a), target=qubit_index)
        for rot, a in zip(pgates, angles)
    ]
    for instr in instructions:
        circuit.add_instruction(instr)
    
    unitary = calculate_unitary(circuit.qubit_count, circuit.instructions)
    

    The above works fine for qubit_index=0 but raises an IndexError for any qubit_index!=0

    Expected behavior The calculate_unitary function should account for the empty/unused registers and calculate the unitary of the circuit.

    Screenshots or logs

    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    /var/folders/nm/_31bsg9s76v7_cxbkkw9f20w0000gn/T/ipykernel_35500/857523477.py in <module>
    ----> 1 unitary = calculate_unitary(circuit.qubit_count, circuit.instructions)
    
    ~/opt/miniconda3/envs/braket-env/lib/python3.9/site-packages/braket/circuits/unitary_calculation.py in calculate_unitary(qubit_count, instructions)
         71         targets = instr.target
         72 
    ---> 73         gate_indexes, un_indexes, result_indexes = _einsum_subscripts(targets, qubit_count)
         74         gate_matrix = np.reshape(matrix, len(targets) * [2, 2])
         75 
    
    ~/opt/miniconda3/envs/braket-env/lib/python3.9/site-packages/braket/circuits/unitary_calculation.py in _einsum_subscripts(targets, qubit_count)
         28     un_right_indexes = list(range(target_count + qubit_count, target_count + 2 * qubit_count))
         29 
    ---> 30     gate_right_indexes = [un_left_indexes[-1 - target] for target in targets]
         31 
         32     result_left_indexes = un_left_indexes.copy()
    
    ~/opt/miniconda3/envs/braket-env/lib/python3.9/site-packages/braket/circuits/unitary_calculation.py in <listcomp>(.0)
         28     un_right_indexes = list(range(target_count + qubit_count, target_count + 2 * qubit_count))
         29 
    ---> 30     gate_right_indexes = [un_left_indexes[-1 - target] for target in targets]
         31 
         32     result_left_indexes = un_left_indexes.copy()
    
    IndexError: list index out of range
    

    System information

    • Amazon Braket Python SDK version: 1.11.1
    • Python version: 3.9.7
    bug 
    opened by ryanhill1 9
  • feature: Add support for batch execution

    feature: Add support for batch execution

    Issue #, if available:

    Description of changes:

    Added methods to support running multiple tasks in parallel.

    Testing done:

    Merge Checklist

    Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request.

    General

    • [x] I have read the CONTRIBUTING doc
    • [x] I used the commit message format described in CONTRIBUTING
    • [x] I have updated any necessary documentation, including READMEs and API docs (if appropriate)

    Tests

    • [x] I have added tests that prove my fix is effective or that my feature works (if appropriate)
    • [x] I have checked that my tests are not configured for a specific region or account (if appropriate)

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by speller26 9
  • 'Braket' object has no attribute 'get_device'

    'Braket' object has no attribute 'get_device'

    Describe the bug When executing the example bell.py, the following error appears:


    AttributeError Traceback (most recent call last) in 19 aws_account_id = boto3.client("sts").get_caller_identity()["Account"] 20 ---> 21 device = AwsDevice("arn:aws:braket:::device/quantum-simulator/amazon/sv1") 22 s3_folder = (f"amazon-braket-output-{aws_account_id}", "folder-name") 23

    ~/braketvirtenv/lib/python3.7/site-packages/braket/aws/aws_device.py in init(self, arn, aws_session) 74 self._provider_name = None 75 self._type = None ---> 76 self.refresh_metadata() 77 78 def run(

    ~/braketvirtenv/lib/python3.7/site-packages/braket/aws/aws_device.py in refresh_metadata(self) 153 Refresh the AwsDevice object with the most recent Device metadata. 154 """ --> 155 metadata = self._aws_session.get_device(self._arn) 156 self._name = metadata.get("deviceName") 157 self._status = metadata.get("deviceStatus")

    ~/braketvirtenv/lib/python3.7/site-packages/braket/aws/aws_session.py in get_device(self, arn) 116 Dict[str, Any]: Device metadata 117 """ --> 118 return self.braket_client.get_device(deviceArn=arn)

    ~/braketvirtenv/lib/python3.7/site-packages/botocore/client.py in getattr(self, item) 573 raise AttributeError( 574 "'%s' object has no attribute '%s'" % ( --> 575 self.class.name, item) 576 ) 577

    AttributeError: 'Braket' object has no attribute 'get_device'

    To reproduce Execute bell.py

    Expected behavior Get the result of the experiment

    System information A description of your system. Please provide:

    • Amazon Braket Python SDK version: v1.0.0.post1
    • Amazon Braket Python Schemas version: v1.0.0.post1
    • Amazon Braket Python Default Simulator version: v1.0.0.post1
    • Python version: 3.7.5
    opened by NicoSchwaller 9
  • Aspen-10 programs with a verbatim_box pass validation but fail to execute

    Aspen-10 programs with a verbatim_box pass validation but fail to execute

    Hi, it seems like the new Rigetti machine is not able to accept the verbatim_box instruction. This behavior interferes with certain procedures, such as the noise mitigation tool Mitiq. Additionally, the validator does not error out early, so there is instead a failure at the device compiler I think, which returns very little information about what the problem could be. It wasn't too easy to isolate this problem from within a more complicated procedure when I thought this feature was working.

    To reproduce Here is a full program (less redactions) to run the same simple circuit without and then with a verbatim box.

    import boto3
    from braket.aws import AwsDevice, AwsSession
    from braket.circuits import Circuit
    from braket.circuits.gates import *
    
    session = boto3.Session(profile_name="REDACTED", region_name="us-west-1")
    s3 = session.client("s3")
    brkt = session.client("braket")
    braket_aws_session = AwsSession(session, brkt)
    
    BUCKET = "amazon-braket-REDACTED-us-west-1"
    device = AwsDevice("arn:aws:braket:::device/qpu/rigetti/Aspen-10", aws_session=braket_aws_session)
    
    print("Native gates for this device:", device.properties.paradigm.nativeGateSet)
    
    # SAME ACROSS REGIONS
    KEY_PREFIX = "REDACTED"
    s3_folder = AwsSession.S3DestinationFolder(BUCKET, KEY_PREFIX)
    
    repro_ckt_1q = Circuit().rx(0, np.pi/2).z(0).rz(0, 0.76543)
    verbatim_ckt = Circuit().add_verbatim_box(repro_ckt_1q)
    print("circuits:")
    print("normal:")
    print(repro_ckt_1q)
    print()
    print("verbatim:")
    print(verbatim_ckt)
    
    print("\n##########")
    print("normal task, force qubit 0")
    task = device.run(repro_ckt_1q, s3_folder, disable_qubit_rewiring=True, shots=10)
    res = task.result()
    print("program compiled for device:")
    print(res.additional_metadata.rigettiMetadata.compiledProgram)
    print()
    print("measurement probs:")
    print(res.measurement_probabilities)
    
    print("\n##########")
    print("verbatim task")
    task = device.run(verbatim_ckt, s3_folder, disable_qubit_rewiring=True, shots=10)
    res = task.result()
    print(res.additional_metadata.rigettiMetadata.compiledProgram)
    print(res.measurement_probabilities)
    

    Screenshots or logs If applicable, add screenshots or logs to help explain your problem.

    Native gates for this device: ['RX', 'RZ', 'CZ', 'CPHASE', 'XY']
    circuits:
    normal:
    T  : |   0    |1|    2    |
                               
    q0 : -Rx(1.57)-Z-Rz(0.765)-
    
    T  : |   0    |1|    2    |
    
    verbatim:
    T  : |      0      |   1    |2|    3    |     4     |
                                                         
    q0 : -StartVerbatim-Rx(1.57)-Z-Rz(0.765)-EndVerbatim-
    
    T  : |      0      |   1    |2|    3    |     4     |
    
    ##########
    normal task, force qubit 0
    program compiled for device:
    DECLARE ro BIT[1]
    PRAGMA INITIAL_REWIRING "NAIVE"
    RESET
    RX(pi/2) 0
    RZ(-2.376162653589793) 0
    MEASURE 0 ro[0]
    
    measurement probs:
    {'0': 0.6, '1': 0.4}
    
    ##########
    verbatim task
    
    Task is in terminal state FAILED and no result is available.
    Task failure reason is: Failed to compile task; device: Aspen-10.
    
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-5-3205fae90de1> in <module>
         39 task = device.run(verbatim_ckt, s3_folder, disable_qubit_rewiring=True, shots=10)
         40 res = task.result()
    ---> 41 print(res.additional_metadata.rigettiMetadata.compiledProgram)
         42 print(res.measurement_probabilities)
    
    AttributeError: 'NoneType' object has no attribute 'additional_metadata'
    

    Expected behavior I would expect any of: correct execution of both tasks, the validator to fail when the submitted circuit has a verbatim box (or any other instruction that is disallowed, if any others are missing), or more complete error information (task failure: failed to compile was almost a dead end for me when I was debugging).

    A natural followup question is whether verbatim boxes are still supposed to be supported on the Aspen-10 device. Otherwise, no currently available machine supports these instructions, right?

    System information A description of your system. Please provide:

    • Amazon Braket Python SDK version: 1.11.0
    • Amazon Braket Python Schemas version: 1.5.0
    • Amazon Braket Python Default Simulator version: n/a
    • Python version: 3.8.11

    Thank you!

    bug 
    opened by eth-n 8
  • fix: Add ability to use cached `GetDevice` value

    fix: Add ability to use cached `GetDevice` value

    Issue #, if available:

    Description of changes:

    Testing done:

    Merge Checklist

    Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request.

    General

    • [ ] I have read the CONTRIBUTING doc
    • [ ] I used the commit message format described in CONTRIBUTING
    • [ ] I have updated any necessary documentation, including READMEs and API docs (if appropriate)

    Tests

    • [ ] I have added tests that prove my fix is effective or that my feature works (if appropriate)
    • [ ] I have checked that my tests are not configured for a specific region or account (if appropriate)

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by speller26 8
  • fix: LocalQuantumJob.create() fails  on Windows

    fix: LocalQuantumJob.create() fails on Windows

    *Issue #440 *

    Description of changes: Updated Path calls to PurePosixPath for the destination directory. Testing done: Tested the fix as described in the issue in Windows and WSL.

    Merge Checklist

    Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request.

    General

    • [x] I have read the CONTRIBUTING doc
    • [x] I used the commit message format described in CONTRIBUTING
    • [x] I have updated any necessary documentation, including READMEs and API docs (if appropriate)

    Tests

    • [x] I have added tests that prove my fix is effective or that my feature works (if appropriate)
    • [x] I have checked that my tests are not configured for a specific region or account (if appropriate)

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. integ-aws-win-20220916T1742.log integ-aws-wsl-20220916T1758.log

    opened by marcianomoreno 7
  • feature: Enable retries when retrieving results from AwsQuantumTaskBatch.

    feature: Enable retries when retrieving results from AwsQuantumTaskBatch.

    Issue #, if available:

    Description of changes: Enable retries when retrieving results from AwsQuantumTaskBatch.

    Note this changes the behavior of AwsQuantumTaskBatch.results() when called with fail_unsuccessful=True, use_cached_value=True. Previously if there were any missing results, the method would still pass; now it will fail like it should.

    Testing done: Tested with manual batch runs by setting poll_timeout_seconds to be very low.

    Merge Checklist

    Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request.

    General

    • [x] I have read the CONTRIBUTING doc
    • [x] I used the commit message format described in CONTRIBUTING
    • [x] I have updated any necessary documentation, including READMEs and API docs (if appropriate)

    Tests

    • [x] I have added tests that prove my fix is effective or that my feature works (if appropriate)
    • [x] I have checked that my tests are not configured for a specific region or account (if appropriate)

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by licedric 7
  • Failing to manage multiple profiles

    Failing to manage multiple profiles

    Describe the bug AwsSession fails to manage multiple profiles for QPU-related tasks. It only works if I move the credentials to the default profile.

    QPUs = AwsDevice.get_devices(types=["QPU"], aws_session=aws_session) is failing but simulators = AwsDevice.get_devices(types=["SIMULATOR"], aws_session=aws_session) is working. We created aws_session using the instruction provided in the docs. The only workaround is to move the credentials to default profile.

    Error message: ClientError: An error occurred (UnrecognizedClientException) when calling the SearchDevices operation: The security token included in the request is invalid

    bug 
    opened by Boniface316 6
  • feature: change aspen m-series cost tracking to common name.

    feature: change aspen m-series cost tracking to common name.

    Issue #, if available:

    Description of changes:

    Testing done:

    Merge Checklist

    Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request.

    General

    • [ ] I have read the CONTRIBUTING doc
    • [ ] I used the commit message format described in CONTRIBUTING
    • [ ] I have updated any necessary documentation, including READMEs and API docs (if appropriate)

    Tests

    • [ ] I have added tests that prove my fix is effective or that my feature works (if appropriate)
    • [ ] I have checked that my tests are not configured for a specific region or account (if appropriate)

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by krneta 0
  • CVE-2007-4559 Patch

    CVE-2007-4559 Patch

    Patching CVE-2007-4559

    Hi, we are security researchers from the Advanced Research Center at Trellix. We have began a campaign to patch a widespread bug named CVE-2007-4559. CVE-2007-4559 is a 15 year old bug in the Python tarfile package. By using extract() or extractall() on a tarfile object without sanitizing input, a maliciously crafted .tar file could perform a directory path traversal attack. We found at least one unsantized extractall() in your codebase and are providing a patch for you via pull request. The patch essentially checks to see if all tarfile members will be extracted safely and throws an exception otherwise. We encourage you to use this patch or your own solution to secure against CVE-2007-4559. Further technical information about the vulnerability can be found in this blog.

    If you have further questions you may contact us through this projects lead researcher Kasimir Schulz.

    opened by TrellixVulnTeam 1
  • Update getting-started.rst

    Update getting-started.rst

    I still need to add the picture that I wanted to, but I am prevented because I do not have push access.

    Issue #, if available:

    Description of changes:

    Testing done:

    Merge Checklist

    Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request.

    General

    • [ ] I have read the CONTRIBUTING doc
    • [ ] I used the commit message format described in CONTRIBUTING
    • [ ] I have updated any necessary documentation, including READMEs and API docs (if appropriate)

    Tests

    • [ ] I have added tests that prove my fix is effective or that my feature works (if appropriate)
    • [ ] I have checked that my tests are not configured for a specific region or account (if appropriate)

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by tichrisl137 1
  • testing 3.10 and 3.11 builds

    testing 3.10 and 3.11 builds

    Issue #, if available:

    Description of changes:

    Testing done:

    Merge Checklist

    Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request.

    General

    • [ ] I have read the CONTRIBUTING doc
    • [ ] I used the commit message format described in CONTRIBUTING
    • [ ] I have updated any necessary documentation, including READMEs and API docs (if appropriate)

    Tests

    • [ ] I have added tests that prove my fix is effective or that my feature works (if appropriate)
    • [ ] I have checked that my tests are not configured for a specific region or account (if appropriate)

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

    opened by krneta 1
  • Support for Python 3.10 and 3.11

    Support for Python 3.10 and 3.11

    Describe the feature you'd like The Amazon Braket SDK is officially supported and tested on Python version 3.7-3.9. Support for newer versions 3.10 and 3.11 would allow integration with newer projects.

    How would this feature be used? Please describe. The SDK would be available to any project based on Python 3.10 or 3.11.

    Describe alternatives you've considered

    Additional context

    opened by shahakL 2
  • tracker should work behind HTTP proxy

    tracker should work behind HTTP proxy

    In contrast to the rest of the SDK functions, the tracker does not work behind a web proxy.

    If I get it right, it's because the http.request in line 37 of tracking/pricing.py will only get a response if a direct connection to https://pricing.us-east-1.amazonaws.com is available. In our company environment my dev machine where I run the Jupyter notebook has to go out via HTTP(S)_PROXY.

    enhancement 
    opened by arthurhobspice 1
Releases(v1.35.2)
qualysclient - a python SDK for interacting with the Qualys API

qualysclient - a python SDK for interacting with the Qualys API

null 5 Oct 28, 2022
Python SDK for interacting with the Frame.io API.

python-frameio-client Frame.io Frame.io is a cloud-based collaboration hub that allows video professionals to share files, comment on clips real-time,

Frame.io 37 Dec 21, 2022
A simple library for interacting with Amazon S3.

BucketStore is a very simple Amazon S3 client, written in Python. It aims to be much more straight-forward to use than boto3, and specializes only in

Jacobi Petrucciani 219 Oct 3, 2022
Discord Bot that leverages the idea of nested containers using podman, runs untrusted user input, executes Quantum Circuits, allows users to refer to the Qiskit Documentation, and provides the ability to search questions on the Quantum Computing StackExchange.

Discord Bot that leverages the idea of nested containers using podman, runs untrusted user input, executes Quantum Circuits, allows users to refer to the Qiskit Documentation, and provides the ability to search questions on the Quantum Computing StackExchange.

Mehul 23 Oct 18, 2022
Graviti-python-sdk - Graviti Data Platform Python SDK

Graviti Python SDK Graviti Python SDK is a python library to access Graviti Data

Graviti 13 Dec 15, 2022
Live Coding - Mensageria na AWS com Amazon SNS e Amazon SQS

Live Coding - Mensageria na AWS com Amazon SNS e Amazon SQS Repositório para o Live Coding do dia 08/12/2021 Serviços utilizados Amazon SNS Amazon SQS

Cassiano Ricardo de Oliveira Peres 3 Mar 1, 2022
A Python SDK for connecting devices to Microsoft Azure IoT services

V2 - We are now GA! This repository contains code for the Azure IoT SDKs for Python. This enables python developers to easily create IoT device soluti

Microsoft Azure 381 Dec 30, 2022
Python library for interacting with the Wunderlist 2 REST API

Overview Wunderpy2 is a thin Python library for accessing the official Wunderlist 2 API. What does a thin library mean here? Only the bare minimum of

mieubrisse 24 Dec 29, 2020
A python wrapper for interacting with the LabArchives API.

LabArchives API wrapper for Python A python wrapper for interacting with the LabArchives API. This very simple package makes it easier to make arbitra

Marek Cmero 3 Aug 1, 2022
Python 3 tools for interacting with Notion API

NotionDB Python 3 tools for interacting with Notion API: API client Relational database wrapper Installation pip install notiondb API client from noti

Viet Hoang 14 Nov 24, 2022
Popcorn-time-api - Python API for interacting with the Popcorn Time Servers

Popcorn Time API ?? CONTRIBUTIONS Before doing any contribution read CONTRIBUTIN

Antonio 3 Oct 31, 2022
A napari plugin for visualising and interacting with electron cryotomograms

napari-subboxer A napari plugin for visualising and interacting with electron cryotomograms. Installation You can install napari-subboxer via pip: pip

null 3 Nov 25, 2021
Example code for interacting with solana anchor programs - candymachine

candypy example code for interacting with solana anchor programs - candymachine THIS IS PURELY SAMPLE CODE TO FORK, MODIFY, UNDERSTAND AND INTERACT WI

dubbelosix 3 Sep 18, 2022
Client library for accessing IQM quantum computers

IQM Client Client-side library for connecting to an IQM quantum computer. Installation IQM client is not intended to be used directly by human users.

IQM 10 Dec 21, 2022
A wrapper for aqquiring Choice Coin directly through a Python Terminal. Leverages the TinyMan Python-SDK.

CHOICE_TinyMan_Wrapper A wrapper that allows users to acquire Choice Coin directly through their Terminal using ALGO and various Algorand Standard Ass

Choice Coin 16 Sep 24, 2022
A simple Python wrapper for the Amazon.com Product Advertising API ⛺

Amazon Simple Product API A simple Python wrapper for the Amazon.com Product Advertising API. Features An object oriented interface to Amazon products

Yoav Aviram 789 Dec 26, 2022
The unofficial Amazon search CLI & Python API

amzSear The unofficial Amazon Product CLI & API. Easily search the amazon product directory from the command line without the need for an Amazon API k

Asher Silvers 95 Nov 11, 2022
An Amazon Product Scraper built using scapy module of python

Amazon Product Scraper This is an Amazon Product Scraper built using scapy module of python Features it scrape various things Product Title Product Im

Sudhanshu Jha 1 Dec 13, 2021
A complete Python application to automatize the process of uploading files to Amazon S3

Upload files or folders (even with subfolders) to Amazon S3 in a totally automatized way taking advantage of: Amazon S3 Multipart Upload: The uploaded

Pol Alzina 1 Nov 20, 2021