Previous chatper, we briefly introduced AWS Breket.

In this tutorial, we will learn how to access and use the quantum devices and simulators provided by AWS Braket using the Command Line Interface (CLI).

Accessing Quantum Devices and Simulators

AWS Braket offers several paths to access its quantum devices and simulators, as shown in the flowchart below:

Amazon Braket Python SDK

You can use the Amazon Braket Python SDK to run your quantum circuits either on your local computer or on AWS Braket’s simulators, and then execute them on the available Quantum Processing Units (QPUs).

Setting Up the Command Line Interface

Before the installation, following this linkto create and get the AWS Access Key ID and AWS Secret Access Key.

  1. Install AWS CLI

First, you need to install the AWS Command Line Interface (CLI) on your system. Follow the instructions provided in the tutorial to download and install the AWS CLI.

1
2
3
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install
  1. Configure AWS CLI

After installing the AWS CLI, you need to configure it with your AWS Access Key ID, AWS Secret Access Key, and the desired AWS Region. This information is required for authenticating your requests to AWS services.

1
2
3
4
5
$ aws configure
AWS Access Key ID [None]: ********************
AWS Secret Access Key [None]: ********************
Default region name [None]: us-west-1
Default output format [None]: json

Note

  • Access keys consist of an access key ID and secret access key, which are used to sign programmatic requests that you make to AWS.
  • The Default region name identifies the AWS Region whose servers you want to send your requests to by default. This is typically the Region closest to you, but it is recommended that you pick one of the 3 regions in which Amazon Braket is available: us-east-1, us-west-1, us-west-2.
  • The Default output format specifies how the results are formatted. The value can be any of the values in the following list. If you don’t specify an output format, json is used as the default.
  1. Install Anaconda or Miniconda (Optional)

Next, you need to install Anaconda or Miniconda, which are open-source distribution platforms for Python and other programming languages. This step ensures that you have a consistent Python environment for running your quantum computing experiments.

1
2
3
$ wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh
$ bash ~/miniconda.sh -b -p $HOME/miniconda
$ ~/miniconda/bin/conda init
  1. Create a Conda Environment

Create a new Conda environment specifically for working with AWS Braket. This isolates your Python dependencies and packages from other environments.

1
2
(base) $ conda create --name braket python
(braket) $ conda activate braket
  1. Install the Amazon Braket SDK

Within the newly created Conda environment, install the Amazon Braket SDK, which provides Python bindings for interacting with AWS Braket services.

1
(braket) $ pip install amazon-braket-sdk

Running Quantum Circuits

Local Simulator

You can run a simple quantum circuit on your local computer using the LocalSimulator provided by the Amazon Braket SDK.

  1. Create a local_bell.py file
1
2
3
4
5
from braket.circuits import Circuit
from braket.devices import LocalSimulator
device = LocalSimulator()
bell = Circuit().h(0).cnot(0, 1)
print(device.run(bell, shots=100).result().measurement_counts)
  1. Run it and get the output
1
2
$ python3 local_bell.py
Counter({'00': 55, '11': 45})

Braket Simulator

AWS Braket offers its own simulators, such as the sv1 simulator, which you can use to run more complex quantum circuits in the cloud.

Assuming you’ve already run the above code successfully. Now we’re using Braket’s simulator to run a sample (Here using sv1).

  1. Create a aws_bell.py file
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from braket.aws import AwsDevice
from braket.circuits import Circuit

device = AwsDevice("arn:aws:braket:::device/quantum-simulator/amazon/sv1")

# Choose S3 bucket to store results
bucket = # <<Update with your actual bucket name>> #eg: "amazon-braket-unique-aabbcdd"
prefix = "results"
s3_folder = (bucket, prefix)

bell = Circuit().h(0).cnot(0, 1)
print(bell)

task = device.run(bell, s3_folder, shots=100)
print("Measurement Results")
print(task.result().measurement_counts)
  1. Run it and get the output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$ python3 aws_bell.py
T  : │  01      ┌───┐
q0 : ─┤ H ├───●───
      └───┘   │
            ┌─┴─┐
q1 : ───────┤ X ├─
            └───┘
T  : │  01Measurement Results
Counter({'00': 50, '11': 50})

Note

Remember that add a prefix “amazon-breket-” before your s3 bucket name to avoid access error.

Braket QPU

AWS Braket offers its own simulators, such as the sv1 simulator, which you can use to run more complex quantum circuits in the cloud.

  1. Check the status of the QPU
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
(braket)$ aws braket --region us-east-1 get-device --device-arn arn:aws:braket:us-east-1::device/qpu/ionq/Aria-1 --output yaml

deviceArn: arn:aws:braket:us-east-1::device/qpu/ionq/Aria-1
deviceCapabilities: '{"service": {"braketSchemaHeader": {"name": "braket.device_schema.device_service_properties",
  "version": "1"}, "executionWindows": [{"executionDay": "Weekdays", "windowStartHour":
  "12:00:00", "windowEndHour": "03:00:00"}], "shotsRange": [1, 5000], "deviceCost":
  {"price": 0.03, "unit": "shot"}, "deviceDocumentation": {"imageUrl": "http://d1.awsstatic.com/re19/Braket/IonQ%20Logo.59ea92b40cff5a2c2e90d9d981b864c2f424c5a8.png",
  "summary": "Universal gate-model QPU based on trapped ions", "externalDocumentationUrl":
  "https://ionq.com/quantum-systems/aria"}, "deviceLocation": "Maryland, USA", "updatedAt":
  "2024-05-23T00:30:39+00:00"}, "action": {}, "deviceParameters": {"title": "IonqDeviceParameters",
  "description": "This defines the parameters common to all the IonQ devices.", "type":
  "object", "properties": {"braketSchemaHeader": {"title": "Braketschemaheader", "default":
  {"name": "braket.device_schema.ionq.ionq_device_parameters", "version": "1"}, "const":
  {"name": "braket.device_schema.ionq.ionq_device_parameters", "version": "1"}}, "paradigmParameters":
  {"$ref": "#/definitions/GateModelParameters"}, "errorMitigation": {"title": "Errormitigation",
  "type": "array", "items": {"$ref": "#/definitions/ErrorMitigationScheme"}}}, "required":
  ["paradigmParameters"], "definitions": {"GateModelParameters": {"title": "GateModelParameters",
  "description": "Defines parameters common to all gate model devices.", "type": "object",
  "properties": {"braketSchemaHeader": {"title": "Braketschemaheader", "default":
  {"name": "braket.device_schema.gate_model_parameters", "version": "1"}, "const":
  {"name": "braket.device_schema.gate_model_parameters", "version": "1"}}, "qubitCount":
  {"title": "Qubitcount", "minimum": 0, "type": "integer"}, "disableQubitRewiring":
  {"title": "Disablequbitrewiring", "default": false, "type": "boolean"}}, "required":
  ["qubitCount"]}, "ErrorMitigationScheme": {"title": "ErrorMitigationScheme", "description":
  "Base class for an error mitigation scheme.", "type": "object", "properties": {}}}},
  "braketSchemaHeader": {"name": "braket.device_schema.ionq.ionq_device_capabilities",
  "version": "1"}, "paradigm": {"braketSchemaHeader": {"name": "braket.device_schema.gate_model_qpu_paradigm_properties",
  "version": "1"}, "connectivity": {"fullyConnected": true, "connectivityGraph": {}},
  "qubitCount": 25, "nativeGateSet": ["GPI", "GPI2", "MS"]}, "provider": {"braketSchemaHeader":
  {"name": "braket.device_schema.ionq.ionq_provider_properties", "version": "1"},
  "fidelity": {"1Q": {"mean": 0.9995}, "2Q": {"mean": 0.9723}, "spam": {"mean": 0.9941}},
  "timing": {"T1": 100.0, "T2": 1.0, "1Q": 0.000135, "2Q": 0.0006, "readout": 0.0003,
  "reset": 2e-05}, "errorMitigation": {"braket.device_schema.error_mitigation.debias.Debias":
  {"minimumShots": 2500}}}}'
deviceName: Aria 1
deviceQueueInfo:
- queue: QUANTUM_TASKS_QUEUE
  queuePriority: Normal
  queueSize: '1'
- queue: QUANTUM_TASKS_QUEUE
  queuePriority: Priority
  queueSize: '1'
- queue: JOBS_QUEUE
  queueSize: 0 (1 prioritized hybrid job running)
deviceStatus: ONLINE
deviceType: QPU
providerName: IonQ
  1. Create a ionq_bell.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from braket.aws import AwsDevice
from braket.circuits import Circuit
device = AwsDevice("arn:aws:braket:us-east-1::device/qpu/ionq/Aria-1")

# Choose S3 bucket to store results
bucket =  <<Update with you actual bucket name>> #eg: "amazon-braket-unique-aabbcdd"
prefix = "results"
s3_folder = (bucket, prefix)
bell = Circuit().h(0).cnot(0, 1)
print(bell)
task = device.run(bell, s3_folder, shots=100)
print("Task submitted. Task ARN is: ",task.id)
  1. Run it
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
(braket)$ python3 ionq_bell.py
T : |0|1|

q0 : -H-C-
|
q1 : ---X-

T : |0|1|

Task submitted.
Task ARN is: arn:aws:braket:us-west-1:83xxxxxx862:quantum-task/321c7904-a07b-4aa9-945e-daec329ed1cd

Once you successfully run the code, it would return Task ARN and then we can use it to track the status or the result.

  1. Create a new file called get_result.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from braket.aws import AwsQuantumTask

# replace with your actual task arn
ionq_task_id = "arn:aws:braket:us-west-1:83xxxxxxx862:quantum-task/321c7904-a07b-4aa9-945e-daec329ed1cd"

# recover task
task_load = AwsQuantumTask(arn=ionq_task_id)

# print status
status = task_load.state()
print('Status of (reconstructed) task:', status)
print('\n')
if status == 'COMPLETED':
    # get results
    ionq_results = task_load.result()

    # get all metadata of submitted task
    metadata = task_load.metadata()
    # example for metadata
    shots = metadata['shots']
    machine = metadata['deviceArn']
    # print example metadata
    print("{} shots taken on machine {}.\n".format(shots, machine))

    # get measurement counts
    ionq_counts = ionq_results.measurement_counts
    print('Measurement counts:', rigetti_counts)

elif status in ['FAILED', 'CANCELLED']:
    # print terminal message
    print('Your task is in terminal status, but has not completed.')

else:
    # print current status
    print('Sorry, your task is still being processed and has not been finalized yet.')
  1. Run it and Get result
1
2
3
4
5
6
(braket)$ python3 get_result.py
Status of (reconstructed) task: COMPLETED

100 shots taken on machine arn:aws:braket:us-east-1::device/qpu/ionq/Aria-1.

Measurement counts: Counter({'00': 52, '11': 41, '01': 5, '10': 2})

Conclusion

So far, the steps walks you through the steps to create Python scripts, submit tasks to the QPUs, and retrieve the results.

By following this AWS Braket note, you can now start to set up the Command Line Interface (CLI) for AWS, install the required dependencies, and run quantum circuits on various platforms, including local simulators, AWS Braket simulators, and real Quantum Processing Units (QPUs).