Quantum Computing Experimentation with Amazon Braket - Alex Khan - E-Book

Quantum Computing Experimentation with Amazon Braket E-Book

Alex Khan

0,0
38,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Amazon Braket is a cloud-based pay-per-use platform for executing quantum algorithms on cutting-edge quantum computers and simulators. It is ideal for developing robust apps with the latest quantum devices.
With this book, you'll take a hands-on approach to learning how to take real-world problems and run them on quantum devices. You'll begin with an introduction to the Amazon Braket platform and learn about the devices currently available on the platform, their benefits, and their purpose. Then, you'll review key quantum concepts and algorithms critical to converting real-world problems into a quantum circuit or binary quadratic model based on the appropriate device and its capability. The book also covers various optimization use cases, along with an explanation of the code. Finally, you'll work with a framework using code examples that will help to solve your use cases with quantum and quantum-inspired technologies. Later chapters cover custom-built functions and include almost 200 figures and diagrams to visualize key concepts. You’ll be able to scan the capabilities provided by Amazon Braket and explore the functions to adapt them for specific use cases.
By the end of this book, you’ll have the tools to integrate your current business apps and AWS data with Amazon Braket to solve constrained and multi-objective optimization problems.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 441

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Quantum Computing Experimentation with Amazon Braket

Explore Amazon Braket quantum computing to solve combinatorial optimization problems

Alex Khan

BIRMINGHAM—MUMBAI

Quantum Computing Experimentation with Amazon Braket

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Pavan Ramchandani

Publishing Product Manager: Kushal Dave

Senior Editor: Keagan Carneiro

Content Development Editor: Adrija Mitra

Technical Editor: Saurabh Kadave

Copy Editor: Safis Editing

Project Coordinator: Rashika Ba

Proofreader: Safis Editing

Indexer: Tejal Daruwale Soni

Production Designer: Jyoti Chauhan

Marketing Coordinator: Sonakshi Bubbar

First published: July 2022

Production reference: 2060423

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

978-1-80056-526-5

www.packtpub.com

To my family and friends who have suffered through my crazy ideas and tangents; believe it or not, it is you who inspire me to take risks and be myself.

To the authors, researchers, and entrepreneurs in quantum computing who have taken the time to share their wisdom and stories with the rest of us.

And, to you, my reader, since you are curious and taking a chance. It is my hope that this book will help to clarify some aspects of a complicated discipline.

– Alex Khan

Foreword

It is truly an honor to receive a request to write a foreword for a book like this, in this particular space, at this specific time in history, and by a colleague whom I believe will make significant contributions to this industry during his tenure. That book is Quantum Computing Experimentation with Amazon Braket, the space is quantum computing, the time in history is the infancy of an advanced technology that realistically expects the change the world, and my colleague is Alex Khan.

Alex and I got involved with quantum computing at roughly the same time, and with connections and collaborations with other esteemed colleagues in the domain, such as Dr. Keeper Lane Sharkey, we all began our journey in this space, making contributions where our respective talents best positioned us to: Alex in the quantum start-up, education, and consultancy space; Keeper in the quantum chemistry space; and I brought quantum computing to a fortune-five health company with 350,000 global employees and continue to lead the quantum efforts there.

It’s not surprising to see contributions by industry leaders such as Alex manifested in books of this nature and undergirded by quantum vendors such as AWS, who bring significant and diverse computational capabilities to the table. The fusion of these two actors in the wild brings a richness to both the educational process and the process of developing valued industry skills, resulting in a far better outcome for the individual, and this is likely to be a key training model in the quantum space moving forward.

The book’s focus is as the title suggests: it’s a journey to explore and experiment with quantum computing using the Amazon Braket experience. This is appealing to both the neophyte and the experienced practitioner, as the latter will procure a solid tactical vendor education through a digestible and methodical pedagogy, and the former will get that plus an introduction to quantum basics as well. Readers will explore advanced topics in the later chapters, which is the ultimate commission of the book: to show real-world applications.

The book begins with the mechanics and specifics of the AWS platform, which is both necessary and wise since AWS brings an “infrastructure as code” approach to quantum computing, in addition to being the only vendor to make multiple quantum hardware architectures available under one cost-effective platform. This is important to industries in the wild seeking to get into quantum because experimentation now becomes an OpEx (operational expenditure) as opposed to a CapEx (capital expenditure), and that significantly lowers the entry price to quantum experimentation and increases the potential for senior leadership buy-in. Practitioners developing quantum capabilities on that framework will have more highly valued skill sets in the marketplace because of the exposure to multiple hardware platforms, as each platform brings something unique and different to the table when it comes to solving problems.

This book also provides a solid introduction to and overview of the two different quantum architectures (gate-based and annealing) and how to use them. The differences between the architectural variants within the gate-based architectures are significant, but nuanced. The differences between the annealing and the gate-based architectures are significant and glaring. The practitioner who gets hands-on experience in comparing and contrasting these two significantly different architectures and how they relate to specific use cases will have developed valuable capabilities. To this end, the book provides a solid journey through the D-Wave, OQC, IonQ, and Rigetti quantum architectures.

This book does a great job of weaving together specific use cases with general quantum education in the flow of its content. That’s a non-trivial task since the annealing architecture is so different than the gate-based architectures, and the ways of conceptualizing the problems (and solutions) vary significantly between any architecture being used, particularly at the algorithm level.

This book spends a decent amount of time on advanced subjects such as QAOA, QUBO, and hybrid algorithms, doing a solid job of laying out the use cases under consideration and how the various architectures would be used to address those subjects at a tactical level. This approach is particularly helpful when addressing the single versus multiple objective optimization use case as it highlights the differences between the annealing approach and the gate-based approach, something that’s found in later chapters.

The quantum computing space is following a very similar maturation trajectory to the classical computing space in that it begins in the lab and ends in the hands of the consumer. We call that the producer/consumer difference. The producers make the technology, and the consumers use it to solve real problems in the wild. The consumers can only make proper use of the technology when both it and their understanding of how to effectively use it reach a certain level of maturity. The time between when producers mature the technology enough for consumers to effectively engage it can be viewed as eras, and certain seminal events have to occur before computation moves from one era to another. The classical illustration of one of those seminal events of this is when Dennis Ritchie invented C and UNIX, which enabled classical computing to move out from the labs and into the hands of the consumer.

While we are all still firmly in the producer era of the quantum adventure, we can (and should) expect a series of tactical improvements (or small victories) that help move the maturity of the whole just a little bit forward, and when added up over time, can move the overall industry’s maturity a great deal.

I think this book is one of those victories; it educates, inspires, and motivates quantum practitioners of the consumer stripe to enrich and broaden their experience in the quantum space, and that has great value to that type of individual who’ll make the greatest impact in the wild when fully enabled with mature tools.

Matthew R. Versaggi, MS, MBA – Optum Technology / United Health Care

Senior Director of Artificial Intelligence and Cognitive TechnologyDistinguished EngineerAcademy of Technology Appointee

Contributor: O’Reilly Report: State of Healthcare Technology

Quantum Computing and HealthcareCognitive Technology and Healthcare

Minneapolis, MN, 2022

Reviews

“Informative, interesting, understandable, practical, comprehensive, thorough, effective – just excellent!” – Terrill Frantz, Professor at Harrisburg University of Science and Technology, USA

“Alex has done wonders by blending storytelling techniques with a crisp and clear explanation of the technical aspects of a complex quantum technology. Every element of the technological advances that service providers achieved inside Amazon Braket is well chronicled. On top of that, every piece of code is written in an optimized and self-explanatory manner. The managerial aspects of using quantum computers to solve real-life problems are also discussed, which will help users properly evaluate the tool. Overall, this book is a fantastic treasure trove to get you started on quantum computing, and on Amazon Braket in particular.” – Anshul Saxena, Christ University - India

“Quantum Computing Experimentation with Amazon Braket is an essential resource for businesses and developers preparing for how quantum computers will impact their respective industries. Alex provides practical examples of familiar optimization problems accompanied by easy-to-understand coding guides for multiple available systems on Amazon Braket. Comforting hints, links to additional resources, and pre-execution cost estimation methods bring necessary clarity in what is a new frontier for many readers.” – Mike Heiner, Information Systems Professional

“An easily digestible guide for quantum-based cloud computing. Khan leverages Amazon Braket to take complex topics and simplify them for those interested in quantum computing. Readers familiar with AWS will recognize parallels between existing cloud services, while those familiar with quantum will be exposed to cloud fundamentals through a guided journey.” – Zia K. Mohammad, Senior Product Manager, AWS Quantum

“Alex Khan’s book provides a detailed step-by-step insight into Amazon’s quantum computing environment. The book is very insightful to both novices and experienced quantum computing software developers, with an examination into all the options available in Amazon Braket. Well done, Alex!” – John P. Cummings, Quantum Computing Engineer

“Well done! I thought the book was very well laid out and contained thoughtful code and explanations of how to solve optimization problems using Braket. Overall, I think this book will be very helpful to a wide variety of people, especially AWS users who want to experiment with QC. Congratulations!” – Salvatore Certo, Quantum Computing Technical Manager

Contributors

About the author

Alex Khan is an advisor, entrepreneur, and educator in quantum computing. He is CEO of ZebraKet, a Canadian startup in supply chain optimization using quantum methods. He has had roles at Chicago Quantum, where he co-authored papers on portfolio optimization using D-Wave, Harrisburg University where he taught quantum computing, and at QuantFi. He continues to be an advisor at QuSecure.

Alex is an experienced Health IT executive. He is an engineering/physics dual major and received his BSME from Purdue University, MSME from KSU, MBA with Health Sector Management from Duke University, and a certificate in quantum computing from MITxPro. He has been recognized by The Quantum Daily as one of the 126 advisors shaping the Quantum Computing Industry.

I would like to thank Michael Brett, whose support allowed me to experiment with Amazon Braket, eventually making this book possible. I am grateful to the Packt Publishing team, who trusted me to bring a unique book into the quantum computing ecosystem and have helped and guided me at every step. I am also indebted to the technical reviewers, who over the year have diligently given me very constructive feedback leading to many improvements.

About the reviewers

Rakshit Jain is a certified IBM Associate Quantum Developer who is very passionate about operating systems, quantum computing, and cyber security (white hat, obviously). He’s currently in the penultimate year of his studies at The Hong Kong Polytechnic University, where he leads the Google Developer Student Club as the Vice-President. Driven by curiosity, he experiments with (and breaks) any bleeding edge technology he can get his hands on. When he’s not writing scripts, he is DJing at events or climbing mountains.

Gopal Mahadevan is an optimization software engineer/quantum algorithms researcher and consultant to financial institutions, to help them apply quantum and quantum-inspired solutions to solve their computationally intractable problems and prepare for (inevitable) quantum disruption. He recently completed a master’s degree in Quantum Computing Technologies and is an IBM Certified Associate Quantum Developer (Qiskit).

Table of Contents

Preface

Introduction

Section 1: Getting Started with Amazon Braket

1

Setting Up Amazon Braket

Technical requirements

The overall Amazon Braket landscape

Creating an AWS account

Starting the Amazon Braket service

Configuring the AWS S3 service

Working with the notebook service

Starting the notebook service in Braket

Using notebooks and examples in Braket

Shutting down the notebook service in Braket

Remote access to Amazon Braket using Boto3

Validating if SDK installation is working

Signing in to the AWS account

Summary

Further reading

2

Braket Devices Explained

Annealing-based quantum devices

Introducing D-Wave quantum devices

Gate-based quantum devices

An overview of IonQ's quantum device

Introducing Rigetti quantum devices

Oxford Quantum Circuits

Neutral atom based quantum devices

QuEra

Amazon Braket simulators

Simulators executing on a local device

Simulators executing on Amazon resources

Summary

Further reading

3

User Setup, Tasks, and Understanding Device Costs

Technical requirements

Setting up user groups and users

Creating a user group

Setting up users

Creating a policy for users

Running test code

Finding your tasks and results

Understanding device costs and billing

QPU versus simulator devices

Viewing your charges

Summary

Further reading

4

Writing Your First Amazon Braket Code Sample

Technical requirements

Finding active devices

Assigning a device

Using the local simulator

Using Amazon simulators or quantum devices

Estimating the cost of the device

Creating a simple quantum circuit

Putting together a simple quantum circuit example

Representing a binary value using a quantum circuit

Running a circuit on the Amazon simulator

Actual cost of using the Amazon simulator

Summary

Further reading

Concluding Section 1

Section 2: Building Blocks for Real-World Use Cases

5

Using a Quantum Annealer – Developing a QUBO Function and Applying Constraints

Technical requirement

Solving optimization problems

Simulated annealing

Quantum annealing

Quadratic Unconstrained Binary Optimization (QUBO) problems

A simple conceptual model for D-Wave

A QUBO example using three variables and ExactSolver()

Running the three-variable problem on D-Wave annealer

A party optimization example

A team selection example

A simple process for solving problems using D-Wave

Reviewing data

Representing the problem in graph form

Summarizing the problem

The traditional formulation

A tool to visualize the energy landscape

A simple penalty function to implement the constraint

Running the problem on classical and quantum solvers

Summary

Further reading

6

Using Gate-Based Quantum Computers – Qubits and Quantum Circuits

Technical requirements

What is a quantum circuit?

Understanding the basics of a qubit

Using matrix mathematics

Using matrix mathematics to represent single-qubit gates

Using quantum gates in a quantum circuit

Single-qubit gate rotation example – the Bloch Clock

Representing the hour of the day using θ

Representing the minutes and seconds using φ

Building multiple qubit quantum circuits

Three-qubit circuit example

Example inspired by the Google Supremacy experiment

The actual Google experiment

Circuit implementation on Amazon Braket

Execution results for a single 7x2 circuit

Summary

Further reading

7

Using Gate Quantum Computers – Basic Quantum Algorithms

Technical requirements

What is a quantum Oracle?

Observing the effect of amplitude amplification

Grover's operator using unitary matrices

Grover's search algorithm using quantum circuits

Repetitions of the Grover diffuser operator

Using Grover's algorithm in searches

Working with phases

Translating between the Computational basis and the Fourier basis

Adding phase information to a qubit

How the phase adder circuit is used in quantum circuits

Using Quantum Fourier Transform and its inverse

Adding numbers using the phase adder

Summary

Further reading

8

Using Hybrid Algorithms – Optimization Using Gate-Based Quantum Computers

Technical requirements

Representing a binary quadratic function using a phase adder

Introduction to QAOA concepts

Experimentally validating QAOA concepts

Fine-tuning parameters for QAOA

Implementing QAOA for optimization

Summary

Further reading

9

Running QAOA on Simulators and Amazon Braket Devices

Technical requirements

Further QAOA considerations

Full QAOA hybrid algorithm using a classical parameter optimizer

Multiple-step parameter optimization in QAOA

Benchmarking QAOA on Amazon Braket devices

Optimizing an 11x11 matrix

Optimizing a 34x34 matrix

Optimizing a 38x38 sparse matrix

Summary of results

Summary

Further reading

Concluding section 2

Section 3: Real-World Use Cases

10

Amazon Braket Hybrid Jobs, PennyLane, and other Braket Features

Technical requirement

Utilizing Amazon Braket Hybrid Jobs

Permissions

Using Amazon Braket Hybrid Jobs

A QAOA example using Amazon Braket Hybrid Jobs

Job Control Code

Job Source Module

Xanadu PennyLane

Calling Amazon Braket devices from PennyLane

Using PennyLane within Amazon Braket Hybrid Jobs

Xanadu Borealis

IBM Qiskit

Other Amazon Braket Hybrid Jobs features

Controlling the region of the environment

Hardware configuration

Multiple parallel device execution

Debugging failed jobs

Containers

Summary

Further reading

11

Single-Objective Optimization Use Case

Technical requirements

Introduction to the knapsack problem

Visualizing the knapsack problem

QUBO formulation for the knapsack problem

Implementing the knapsack QUBO in code

Stitching the QUBO matrices together

Getting results from different QUBO samplers

Using the probabilistic sampler

Running the knapsack problem on a D-Wave device

Running the knapsack problem on Amazon Braket simulator SV1

Running the knapsack optimization problem on a Rigetti Aspen 11 device

Running on a Rigetti Aspen M-1 device

A process for solving constrained optimization problems

Summary

Further reading

12

Multi-Objective Optimization Use Case

Technical requirements

Looking into a mock inventory management problem

Setting up the multi-objective problem

Evaluating the best product mix based on scenario A

Determining the conflict based on the opposing objectives

Evaluating the results with the probabilistic solver

Evaluating the optimal values using the D-Wave annealer

Determining a better global solution

Evaluating with the classical probabilistic solver

Evaluating the best solution using D-Wave

Summary

Further reading

Concluding section 3

Appendix: Knapsack BQM Derivation

Getting started with the derivation

Creating the required matrices

Conclusion

Other Books You May Enjoy

Preface

Thank you for showing interest in this book, Quantum Computing Experimentation Using Amazon Braket. This is a niche topic; however, over the last few years, quantum computing has received considerable attention from governments who want to win the quantum race, investors who have poured massive amounts of money into quantum computing start-ups, and early adopters who are seeing it as a potential strategic advantage in the future. Accessing quantum computers through Amazon Braket is useful and important for several reasons. In the case of many quantum computing devices, either direct access is not possible or requires contract negotiations or minimum monthly payments. Amazon Braket removes all these issues by providing a relatively easy-to-learn integrated platform with pay-per-use access to popular quantum computing hardware.

The goal of this book is to help the reader gradually understand key concepts in quantum computing and get comfortable with experimenting with quantum circuits and practical optimization use cases through the Amazon Braket platform. We will also cover quantum annealing and get familiar with how to convert an optimization problem into a format or structure to run on a quantum annealer and gate-based quantum computer.

Reasons to get into Amazon Braket

Like some other platforms, Amazon Braket provides quantum circuit designers convenient access to a number of quantum computing devices through one framework. In the past, we had to use different SDKs and methods to access each device.You might have an application that utilizes elastic compute resources, such as EC2, and want to extend that application to quantum computing in the future. Amazon Braket allows you to build extensions to your existing code that uses other Amazon services.Amazon Braket contains some exclusive simulators, such as TN1, SV1, and DM1.The Amazon Braket pay-per-use model can be useful when experimenting with and scaling quantum device usage.

There is a personal reason I have chosen to write this book. I have been teaching quantum computing and have had the opportunity to explain quantum computing concepts to many students. I want to share basic concepts with you that I hope will give you a practical understanding of how to eventually tackle business use cases through quantum computing by the end of this book.

Who this book is for

This book is for the following people:

Students who have already taken some introductory quantum computing courses and are ready to learn how to use both quantum annealing and gate-based quantum computing for optimization problems in real-world use cases.Industry professionals and technologists such as systems analysts, business analysts, architects, and developers who want to be introduced to practical skills in using quantum computers through Amazon Braket for practical optimization use cases.Entrepreneurs who want to create a quantum start-up and want to experience some of the tools and capabilities quantum computing has to offer.Vice-presidents of IT, CIOs, vice-presidents of architecture, chief architects, solution architects, actuarial fellows, and other practitioners and professionals who want to evaluate quantum computing for future strategic advantage and to differentiate their companies.Companies already utilizing other AWS capabilities, such as Lambda and EC2, who want to expand to quantum computing within the AWS platform.

What this book covers

Chapter 1, Setting Up Amazon Braket, gives you the basic information to get started with Amazon Braket and get familiar with the components on the platform that you will be interacting with and using.

Chapter 2, Braket Devices Explained, goes beyond just listing the devices that are available. You will be introduced to the architecture and use of the quantum computing systems that are available in the Amazon Braket service.

Chapter 3, User Setup, Tasks, and Understanding Device Costs, is more applicable for the system administrator, or the root user. However, you will also get an understanding of what is available and will be able to have informed conversations with the systems administrator.

Chapter 4, Writing Your First Amazon Braket Code Sample, gets you started with some basic code in Amazon Braket that determines information about the quantum devices or simulators and explains how to use them through code and determine some of their properties and costs.

Chapter 5, Using a Quantum Annealer – Developing a QUBO Function and Applying Constraints, covers quantum annealing and how the D-Wave quantum annealer works. This method is quite different from gate quantum computers, and this chapter will introduce you to the basic structure in which information is prepared to send to the D-Wave quantum annealer.

Chapter 6, Using Gate-Based Quantum Computers – Qubits and Quantum Circuits, starts with a simple introduction of the Qubit and the matrix representation of quantum gates and goes over simple quantum circuits using Amazon Braket code. In all cases, attempts are made to show the process of scaling a circuit to utilize Amazon Braket quantum devices and simulators.

Chapter 7, Using Gate Quantum Computers – Basic Quantum Algorithms, goes over the concept of an Oracle in a quantum circuit and introduce a few basic quantum algorithms, including Amplitude Amplification. The concept of a phase adder is introduced leading to the detailed development of the Quantum Fourier Transform circuit.

Chapter 8, Using Hybrid Algorithms – Optimization Using Gate-Based Quantum Computers, develops the binary quadratic function using a phase adder and introduces the concept of amplifying the probability of finding the minimum value through the Quantum Approximate Optimization Algorithm. The fine-tuning of parameters and the implementation of the algorithm are shown in detail.

Chapter 9, Running QAOA on Simulators and Amazon Braket Devices, explores advanced considerations in the implementation of QAOA and the evaluation of the performance of this algorithm on various Amazon Braket devices.

Chapter 10, Amazon Braket Hybrid Jobs, PennyLane, and Other Braket Features, explains how to set up a more efficient hybrid algorithm through the implementation of QAOA using Amazon Hybrid Jobs. The chapter briefly introduces the integration of PennyLane and other features in Amazon Braket.

Chapter 11, Single Objective Optimization Use Case, covers an example of implementing the knapsack problem on both quantum annealing and gate-based quantum computers through mapping this real-world use case into a binary quadratic model.

Chapter 12, Multi-Objective Optimization Use Case, shows you how to find solutions to real-world use cases that have conflicting objectives using the D-Wave quantum annealer.

Appendix – Knapsack BQM Derivation, contains a detailed derivation of converting the knapsack problem into an equivalent quadratic unconstrained binary optimization problem. This is a critical technique for using quantum computers for real-world optimization problems.

To get the most out of this book

The majority of the development can be done within the Amazon Braket Notebooks environment. However, the book will go over setting up the Amazon Braket SDK and Boto 3 so that the reader can run code remotely. It is expected the user is familiar with Jupyter Notebook and Python 3. This book only shows screenshots and steps in the Microsoft Windows environment.

Before getting started, please ensure you have working installations of Python and Jupyter Notebook. This can be done by installing the latest version of Anaconda from anaconda.org. Also, you will need to be comfortable creating a new environment either using Anaconda Navigator or directly from Anaconda Prompt.

What should you know before starting this book?

A basic awareness of quantum computing is helpful before reading this book. I have written this book for someone who has already taken some introductory quantum computing courses. Having said that, I will be going over all the necessary concepts and building blocks at a simple-to-understand and gradual pace to progress to optimization use cases using both quantum annealing and gate-based quantum computing.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Quantum-Computing-Experimentation-with-Amazon-Braket. In case there’s an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/4tYx3.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “Replace amazon-braket-Your-Bucket-Name with the bucket instance name and Your-Folder-Name with the folder name you created in the S3 bucket instance. Keep the quotes.”

A block of code is set as follows:

device_name_list=[] for device in device_list: device_name_list.append(device.name) print('Valid device names: ',device_name_list)

Output generated by the code is set as follows:

Output

Valid device names: ['Advantage_system4.1', 'Advantage_ system6.1', 'Aspen-M-1', 'DW_2000Q_6', 'IonQ Device', 'SV1', 'TN1', 'dm1']]

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[default] exten => s,1,Dial(Zap/1|30) exten => s,2,Voicemail(u100) exten => s,102,Voicemail(b100) exten => i,1,Voicemail(s0)

Any command-line input or output is written as follows:

pip install jupyterlab pip install notebook

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: “Now select the Access keys section and then click on Create new Access Key to create a unique security key.”

Italics: Indicates references to figures, tables, or chapters in the book along with any term that would be in quotes. Here is an example: “While the service is running, it incurs a small charge, which is covered in Chapter 3, User Setup, Tasks, and Understanding Device Costs.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Quantum Computing Experimentation with Amazon Braket, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Introduction

In the last few years, the discussion of quantum computers has escaped from the research universities and labs into the mainstream. This is an excellent development. As a physics-engineering dual major who has spent most of his career implementing cutting-edge technology in medium-sized organizations, I got excited when I heard about quantum computing and the D-Wave Leap program in 2018. In 2019, I shifted my career to quantum computing and jumped in with both feet. I found the concepts, achievements, and the whole discipline fascinating. This discipline called upon so much of my past background in mathematics, materials, entropy, quantum mechanics, and so on. A lot of the scientific work in bringing quantum computing out of the laboratory and onto the cloud was accomplished by D-Wave Systems, Inc., and IBM. Now, people like me could jump in and start using these systems. We were told the drive was towards commercializing the technology, using quantum computers in real-world use cases, creating a quantum workforce, making the technology accessible to non-PhDs, and seeking public investment. I started working with other companies to learn and develop an appreciation of the technology and later created my own start-up in quantum computing. I have learned from many in the industry, and hope I contributed to the learning of others. Over the last three years, I have learned some lessons and had some times when the fog cleared, and I have gained some insights. In this book, I hope to bring those insights to you in the simplest way possible.

Each chapter is laid out with a set of experiments using the quantum computing devices available in Amazon Braket. Each chapter builds on the last chapter’s code or experiments. The code steps have been simplified and, in many cases, after the basics of the theory, equation, or code have been covered, that portion is wrapped in a function for later use. Thus, the reader can continue to gain an understanding of the type of results achieved with the theory and code explained in an efficient manner.

I have tried to write all my own functions and minimize the use of libraries outside of Amazon Braket, Python, NumPy, and Matplotlib. In this regard, I was forced to write my own function to visualize the single-qubit Bloch sphere. My goal was to give the reader all the code in the most accessible format using very simple Python functions. I have also not tried to make the code efficient or fast as I believe it takes away from the readability and accessibility of the code from non-developers. Jupyter Notebook has become a common tool for explaining and testing code. Therefore, I have provided all the code in Jupyter Notebook, except one module which required a Python file. I hope that this will allow those who are somewhat familiar with programming or have learned programming in college to understand the basic structure required for quantum computing. If you are an experienced developer, please feel free to make your own enhancements.

I have also had to exclude many topics that one might expect to be in a standard book on quantum computing and did not want to repeat or duplicate content that is already described in detail in other books. Please check the references in the Further reading section at the end of each chapter.

This book might almost seem like a tour through the quantum computing landscape. However, I try not to drop the reader into the many topics of quantum computing, from machine learning to cryptography to simulations. This book will blaze a trail that leads to optimization. I go over how quantum gates are unitary matrices and show how quantum circuits are a combination of matrix multiplications. I show various quantum circuits and give the user ample experiments to gain an intuition for more complicated quantum algorithms, such as the Quantum Fourier Transform (QFT) and Quantum Approximate Optimization Algorithm (QAOA). I also show how a binary quadratic model (BQM) can be solved on both the quantum annealer by D-Wave and on gate quantum computers using QAOA. I, however, do not cover some of the commonly discussed quantum algorithms, such as Simons, Deutsch–Jozsa, Bernstein-Vazirani, Shor’s, and the Variational Quantum Eigensolver (VQE). There are several reasons for this. Firstly, these are covered at length in various introductory quantum computing books and the Qiskit textbook online. Secondly, even though these algorithms show unique and interesting properties of quantum circuits and even indicate quantum advantage, my focus was to build on the necessary areas of quantum computing to get to optimization use cases. As such, I had to make considerable compromises in scope.

When you run the code, your results will most likely differ from mine. This is because quantum computers are probabilistic and even if the probability profile or distribution is the same, the act of limited sampling and noise will produce varying results. For example, if we both have unbiased coins that are supposed to theoretically produce 50% heads and 50% tails, that does not mean that you will get the same sequence or count of heads versus tails as I would if we sample a few times.

Quantum computing is a rapidly evolving field with large investments and a massive amount of development. Every day something new and interesting comes up, and the Amazon Braket team has been enhancing and adding features to the platform. As such, systems are being improved and old systems are being replaced on Amazon Braket on a regular basis. During the writing of this book, Rigetti Aspen-11 (38 qubits) was replaced by M-1 (80 qubits) for a period and Oxford Quantum Circuits Lucy was added. D-Wave Advantage 1.0 was replaced by Advantage 4.1 and 6.1. On August 12, 2022, M-1 was replaced by M-2, on November 1, 2022, the first Neutral Atom system by QuEra called Aquila was added and on November 18, 2022, D-Wave devices were transitioned off Amazon Braket to the AWS Marketplace. In addition, these devices can be turned off for maintenance. Therefore, I suggest you check on the currently available devices, use the book to familiarize yourself with the technology, make appropriate code changes to use the latest devices available, and re-run the code to evaluate the new capabilities.

Getting the best results from the current devices requires considerable knowledge of the technology, settings, and even the research. There are advanced techniques and native gates that leverage this knowledge and can produce better results than I have shown in this book. My goal has been to introduce you to the basic methods and concepts that you should be aware of, and I have not used advanced techniques. For this reason, your results from this book will likely be inferior to results from advanced libraries, benchmark studies, and technical research papers.

I have had discussions with other educators regarding what should be included in such a book and what should not. We have debated how various concepts in quantum computing should be described so that it makes things easy for readers who are new to the industry but is not misleading about the technology. I will admit that some of my simplifications might not be mathematically or scientifically 100% accurate nor use the standard or technical quantum computing terminology used by PhDs in the field. I have done this to minimize the volume of new terms that you have to get familiar with, as well as the syntax and notation that becomes a hurdle in just getting a view of the landscape. I will encourage the reader to seek out other books and literature if they decide to dig deeper into this subject and realize that there will be some re-learning of concepts from the ground up. However, I have still exposed you to some important linear algebra concepts, Kronecker product, matrix multiplication, simple Dirac notation, and mathematical equations related to describing binary quadratic models. I would consider this treatment the minimum to understand the concepts.

The results in this book cannot be used to benchmark the performance of one quantum computer against another or with classical computers. Firstly, none of the algorithms have been optimized for the hardware, and secondly, each quantum device has different characteristics that require specific adjustments for that device. For example, IonQ uses specific gate operations, which are slightly different from Rigetti’s quantum processor. In addition, specific gate rotations have fewer errors than others. Single-qubit and two-qubit gate operations have different levels of errors depending on the qubit and qubit pairs they are applied to. This requires experts in that quantum computer to suggest optimal techniques to achieve a specific result. Finally, there is a lot of research going into finding specific theoretical and actual advantages of using quantum computers. An advantage in one part of the algorithm can easily vanish if another part of the algorithm scales poorly. I have not attempted to review the quantum computer fidelity, single and two-qubit gate errors, or mathematical scaling to optimize the execution of the circuits. These topics are well outside the scope of this book.

In the end, however, I hope I have been able to bring out the key essence of using quantum computers for optimization problems. Quantum computing can become a full career for some, just as information technology became a career for many no matter what subject they studied in college. To purchase new quantum computing technology, to put it to practical use, to extract competitive advantage, to innovate, to communicate ideas with different departments on how to bring this technology into everyday use, or to tease out use cases where it could improve existing processes, it is important to have a hands-on appreciation of what is involved. This book aims to provide you with this kind of knowledge and is only a start, but I am glad you have taken that step.

I thank you for purchasing this book, and hope that you enjoy it.

– Alex Khan

Section 1: Getting Started with Amazon Braket

In this first section, you will learn how to get started in Amazon Braket, set up the environment, review devices and their costs, and start Jupyter Notebook within the console. We will look at some Amazon Braket examples. You will learn how the various components in the Amazon Braket environment work, and what to watch out for. This includes how to find example notebooks, list of tasks submitted and where to find the results. We will cover some administrative tasks as well to ensure you understand how to set up user permissions and where to find billing and utilization information. You will learn how to set up a remote connection to Amazon Braket, and you will learn how to switch devices in the code and walk through the process in a starter application that incorporates key Braket API functions.

This section contains the following chapters:

Chapter 1, Setting Up Amazon BraketChapter 2, Braket Devices ExplainedChapter 3, User Setup, Tasks, and Understanding Device CostsChapter 4, Writing Your First Amazon Braket Code Sample

1

Setting Up Amazon Braket

Amazon Braket is a new offering on the AWS platform that started in August 2020. The service allows users to experiment with various quantum processors and simulators. Users are able to program their quantum circuits or develop their optimization problems and submit them to various quantum devices in Amazon Braket. These devices include various quantum processing units (QPUs), quantum simulators, and the D-Wave quantum annealer.

Before we can get started with Amazon Braket, it is necessary to take a few steps. Typically, these steps would be done by a system administrator; however, if you are setting up your own account, it will be helpful to follow along. As a system administrator, you will need to create a root account, set up the users, and enable and configure their access to the Amazon Braket service through permission policies.

This chapter will begin with signing into AWS and starting the Amazon Braket service. First, we will go over the key components of Amazon Braket that you should be familiar with. Then, we will review how to set up remote access with Amazon Braket. This is necessary for users who will not be entering the AWS console and will instead be executing jobs from their local development environment.

Both users and administrators should be aware of the options, setup process, and devices available in Amazon Braket, which will make the setup more appropriate for both administrative and user needs.

In this chapter, we’ll cover the following topics:

The overall Amazon Braket landscapeCreating an AWS account as an administrator Starting the Amazon Braket serviceConfiguring the AWS S3 serviceWorking with the notebook service in BraketRemote access to Amazon Braket using Boto3Validating if SDK installation is workingSigning into the AWS account as a user

Technical requirements

The source code for this chapter can be found in the following GitHub repository:

https://github.com/PacktPublishing/Quantum-Computing-Experimentation-with-Amazon-Braket/tree/main/Chapter01

The overall Amazon Braket landscape

The overall setup in Amazon Braket is shown in Figure 1.1. The middle section shows the components within AWS. On the left-hand side, you can see the optional local system (remote user environment), and on the right-hand side, you can see the quantum devices that are accessible through Amazon Braket as of May 2022.

Note: Amazon Braket Changes

New devices are being added and outdated devices are being removed from the Amazon Braket service on a regular basis. Please refer to the devices section in Amazon Braket for information about the latest devices, and watch out for notifications of any changes to the Amazon Braket service.

Figure 1.1 – The components of Amazon Braket as of December 26, 2022

Next, let’s create our AWS account!

Creating an AWS account

This section is for setting up a root account in AWS by a system administrator. We will go over the fundamental steps needed to set up an AWS account and start the Amazon Braket service.

To set up a new AWS Braket account, perform the following steps:

Navigate to http://aws.amazon.com/braket.

This will give you more information about Amazon Braket before you sign up.

Now, you can click on Get Started with Amazon Braket.

Alternatively, you click on Sign In to the Console. In either case, you should see the following screen:

Figure 1.2 – The console's sign-in screen

Select Create a new AWS account.The following dialog box will appear:

Figure 1.3 – The Sign up for AWS screen

Now you can sign up with a new account. There will be five steps, and you will be asked to add your credit card information and select the level of the account. This varies from the basic account, which has no monthly charge, to an enterprise version.

Note: When Are Charges Incurred?

You will be billed for services that you have turned on and are running or if you submit any job to a quantum device. New users might receive special promotional free tier services and free monthly simulator usage. Please carefully read the information on the screen as you set up your account.

More information regarding account setup, policies, charges, and the billing of quantum device usage will be explained in Chapter 3, User Setup, Tasks, and Understanding Device Costs.

After you have created your account and signed back into your account, you should be able to see your AWS console. In this chapter, the screenshots are from the new console version, where you can click on the Switch to the New Console Home option. Your console might not have any items in Recently visited services. However, as you navigate to these services, they will be added to the list as follows:

Figure 1.4 – The AWS Management Console services list

Note that you can always return to this console by clicking on the AWS logo in the upper-left corner of the screen:

Figure 1.5 – Using the AWS logo to return to the console Home

Alternatively, if you have logged out, you can also return by typing http://console.aws.amazon.com/ into your browser window.

You have now created your new AWS account. In the next section, we will go over how to start the Amazon Braket service.

Starting the Amazon Braket service

The Amazon Braket service provides users with an integrated platform from which they can write their code, submit jobs to quantum devices, and view any results that are returned. Depending on how the administrator decides to set up user accounts, the users may or may not have access to the console and might only access the Braket service using code running on their own local computer. This additional step will be covered in the Remote access to Amazon Braket using Boto3 section.

If this is the first time you are accessing Amazon Braket, let’s get the service started:

Now that you are on the AWS Management Console interface, you can click on or locate the Amazon Braket service. After clicking on the Amazon Braket link, you will see the Getting started with Amazon Braket page, as shown in Figure 1.6:

Figure 1.6 – Getting started with Amazon Braket

From this screen, you can create new data storage where your job data will be stored. A bucket is a file storage location created by the Amazon S3 (or storage) service. This is where the results of your quantum compute jobs are stored by Amazon Braket.

The ID portion of the bucket name in Figure 1.6 has been removed, but you will see your own unique ID. You can keep this name or specify a new one, as described in the following two options:

Create New should already be selected. This will generate a new S3 bucket instance with the name created by default. Additionally, you can click on the Specify New button to give the bucket a customized name. Please bear in mind that the bucket name has to be unique to Amazon and must start with amazon-braket-. Please write down the name, as you will need this later.Next, we review the permissions and continue:

Figure 1.7 – Account permissions

Then, we can accept the Terms & conditions section by clicking on the checkbox:

Figure 1.8 – Terms & conditions

Now, click on Enable Amazon Braket. There are no charges for enabling the Amazon Braket service.

You should now see a screen with the Amazon Braket menu on the left-hand side, as shown in Figure 1.9:

Figure 1.9 – The Amazon Braket menu

Additionally, you will see the Amazon Braket devices that are available, as shown in Figure 1.10. The following screenshot only shows the QPU devices. If you scroll down, you will also see the simulators:

Figure 1.10 – The QPU devices available in Amazon Braket (as of December 26,2022)

We will go into more detail about the devices in Chapter 2, Braket Devices Explained.

Now if you click on Notebooks from the menu. You will see the following screen with an empty list of notebooks:

Figure 1.11 – Notebook instances

We will come back to this later in the Working with the notebook service section.

If you click on Tasks in the left-hand menu, you will see the following screen with an empty list of tasks:

Figure 1.12 – The list of tasks submitted to quantum devices

We still have a few more items to review and set up before we can use AWS Braket.

After the Amazon Braket service has been started, we can review the key components within the service. These include the devices, the notebook instances, and the job list.

Now we need to further review the S3 storage service and create any folders for the user to use.

Configuring the AWS S3 service

When the Amazon Braket account was created, it automatically created a bucket in the S3 service. In the previous section, you might have also decided to rename the default bucket with a different name. Let’s go back to the S3 service and complete the setup:

Select the AWS logo button from the upper-left corner of the screen.Then, find the S3 service link by searching in the search box at the top of the screen:

Figure 1.13 – Searching for the S3 service

Clicking on S3 will take you to the S3 service. In the future, you will see this in the Recently visited services section of the AWS Management Console interface:

Figure 1.14 – Bucket assigned to Amazon Braket

You will see your bucket name listed with its unique ID or the name you assigned, along with your region.

Click on the amazon-braket-[id] bucket name to open the details screen:

Figure 1.15 – The Amazon Braket bucket details

Now, create a new folder using the Create folder button. The folder is the location where the job files are stored. Additionally, you can let your users know the folder they will be sending their jobs to. How you organize the folders is up to you. You can also skip this step and not assign folder names. In this case, users can send jobs with any folder name and the S3 bucket service will create a new folder if it does not already exist.Enter a folder name. Then, click on the Create Folder button.

Note: Saving the Bucket and Folder Names

It is helpful to copy and paste the bucket name and the folder name in a notepad file, as you will need them later.

We have reviewed the S3 service and decided on the folder structure for our users. Additionally, we have saved the bucket and folder names since we will need to give this information to the users.

In the next section, we will review the notebook service. This section is useful for users who are going to access the AWS console and use Jupyter Notebook or JupyterLab from within Amazon Braket.

Note: Jupyter Notebook

Jupyter Notebook allows users to review existing code examples to run on Amazon Braket, or they can create their own code and save it. In the next section, we will review the notebook service that is available within Amazon Braket. After that, we will look at how to set up a remote instance of Jupyter Notebook and use with the Amazon Braket service.

Working with the notebook service

Amazon Braket provides Jupyter Notebook and JupyterLab within the notebook section. For those not familiar with programming in Python, Jupyter Notebook provides an easy-to-use interface where you can clearly identify code and rich text sections to explain your code clearly.

Some users will find using Braket notebooks easy to use as they are integrated with the Braket service and do not require the creation of an environment and loading of software libraries to get started. Additionally, the notebooks include Amazon Braket code examples for those who are already familiar with Python and quantum computing.

Starting the notebook service in Braket

The administrator must decide whether users are going to access the notebooks from within AWS Braket or only submit jobs using the remote method via Boto3. Amazon Braket examples are available when the Jupyter Notebook or JupyterLab is created. These notebooks can also be found on GitHub at https://github.com/aws/amazon-braket-examples.

Note: Notebooks and SageMaker

It is helpful to know that the notebooks in Amazon Braket are part of the SageMaker service. Even though we will not go into SageMaker, the notebooks created in Amazon Braket are also visible in the SageMaker service.

If users are given permission to enter the AWS console and access Amazon Braket and its components, then care must be given in terms of how the permissions are set up and which policies are utilized. More details on policies and permissions are given in Chapter 3, User Setup, Tasks, and Understanding Device Costs.

Note: When Do You Not Need to Start the Notebook Instance?