![]() |
![]() |
![]() |
![]() |
Setup
try:
import cirq
import cirq_google as cg
except ImportError:
print("installing cirq-google...")
!pip install --quiet cirq-google --pre
print("installed cirq-google.")
import cirq
import cirq_google as cg
Quantum Computing Service enables researchers to run quantum programs on Google's quantum processors. This notebook is a tutorial to get you started with the typical setup, using the open source Python framework Cirq, in the free cloud Jupyter notebook environment, Google Colab.
Access is currently restricted to those in an approved group, and you must be in that group before running this tutorial.
You can find more about running this in colaboratory in the Colab documentation or in our Cirq-specific guide to running in Colab. You can download this notebook from the GitHub repository.
Before you begin
- First, decide which project you will use the Quantum Computing Services from. All of your quantum programs and results will live under a project which you specify when creating and running these programs using Quantum Engine. You can use an existing project or create a new project. Learn more about creating a project.
- Log in and agree to Terms of Service.
- Follow this link to enable the Quantum Engine API in your Google Cloud Platform project.
After the API is enabled, you should be redirected to the Quantum Engine console and it should look like the following screenshot.
Enter your project id into the input text box below. To find your project id, click on the project menu in the blue bar at the top of the console. This will open a menu that displays your project name (e.g. "My project") and unique project id (e.g. my-project-1234). Enter the project id into the input below. (Help on finding your project id.)
Run the code in the next block (the one with the text box), which will prompt you to authenticate Google Cloud SDK to use your project. You can run the code by either clicking the play button (pointed by arrow below) or by selecting the block and pressing CTRL-ENTER. After running the block you will see a link which you should click. This will open a new browser window. Follow the authentication flow for this window. After you authenticate and allow access to your project, you will be given a string which you should enter into the text box that appears in the run area (and then press return). If you see "Authentication complete" you have done this step successfully. If this fails, make sure that you have cut and paste the string correctly (e.g. the clipboard button seems to not work for some browser/OS combinations).
# The Google Cloud Project id to use.
project_id = ""
processor_id = ""
from cirq_google.engine.qcs_notebook import get_qcs_objects_for_notebook
# For real engine instances, delete 'virtual=True' below.
qcs_objects = get_qcs_objects_for_notebook(project_id, processor_id, virtual=True)
project_id = qcs_objects.project_id
processor_id = qcs_objects.processor_id
engine = qcs_objects.engine
if not qcs_objects.signed_in:
print("ERROR: Please setup project_id in this cell or set the `GOOGLE_CLOUD_PROJECT` env var to your project id.")
print("Using noisy simulator instead.")
Available processors: ['rainbow', 'weber'] Using processor: rainbow ERROR: Please setup project_id in this cell or set the `GOOGLE_CLOUD_PROJECT` env var to your project id. Using noisy simulator instead.
Authentication details Double clicking on the project_id block above should expose the code that is run when you run this code block. This code uses the colabtools auth module to ensure that Application Default Credentials are set and then creates a variable colab_auth
which can be used in Cirq to authenticate your calls to Quantum Computing Service.
If you are going to run code outside of colab and want to authenticate, see the below section on running from the command-line. (Note that this colab's automated outputs use a noisy simulator instead of authenticating to the production service).
Create a circuit
Now that you've enabled Quantum Computing Service and configured the notebook, let's create a basic program with Cirq. After reviewing the code, run this block to run a circuit, and print a circuit diagram and results. To learn more, refer to the Cirq overview and Cirq basics pages.
# Define a qubit at an arbitrary grid location.
qubit = cirq.GridQubit(0, 0)
# Create a circuit (qubits start in the |0> state).
circuit = cirq.Circuit(
cirq.X(qubit), # NOT gate.
cirq.measure(qubit, key='result') # Measurement.
)
print("Circuit:")
print(circuit)
Circuit: (0, 0): ───X───M('result')───
Simulate the circuit using Cirq
Let's quickly use Cirq to simulate the circuit above.
# Simulate the circuit, repeating 1000 times.
print("Simulating circuit using Cirq...\n")
results = cirq.sample(circuit, repetitions=1000)
print("Measurement results:")
print(results)
Simulating circuit using Cirq... Measurement results: result=1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
Run on quantum hardware
Approved users can access quantum hardware in two modes. First, all approved users have access to a processor in "open-swim" which is a first-in-first-out queue with fairness algorithm that balances jobs across users in the queue. Secondly, processors can be reserved in hourly blocks if the user is approved. You can learn more about the reservation system on the concepts page. We'll use the processor pacific
in this demo.
Create a Quantum Engine client
Interactions with hardware are facilitated by the Quantum Computing Service. A client must first be initialized with your Google Cloud project to perform these interactions.
There are two ways to create the engine client:
cg.Engine(project_id=YOUR_PROJECT_ID)
or you can use:
engine = cg.get_engine()
View the processor's topology
Each processor has a set of available qubits laid out on a grid with limited couplings between qubits. The device specification can be printed to inspect the topology of a processor.
processor = engine.get_processor(processor_id)
# Print the device showing qubit connectivity.
device = processor.get_device()
print(device)
(3, 2) │ │ (4, 1)───(4, 2)───(4, 3) │ │ │ │ │ │ (5, 0)───(5, 1)───(5, 2)───(5, 3)───(5, 4) │ │ │ │ │ │ │ │ (6, 1)───(6, 2)───(6, 3)───(6, 4)───(6, 5) │ │ │ │ │ │ │ │ (7, 2)───(7, 3)───(7, 4)───(7, 5)───(7, 6) │ │ │ │ │ │ (8, 3)───(8, 4)───(8, 5) │ │ (9, 4)
Note that the qubit that we used for the simulation above, (0, 0)
, does not exist on the hardware. Since the grid of available qubits may change over time, we'll programatically select a valid qubit by inspecting device.qubits
. We then use the transform_qubits()
method to remap the circuit onto that qubit.
In order to run on hardware, we must also ensure that the circuit only contains gates that the hardware supports. The basic gates used here are always available, so this circuit can be run without any further changes, but in general you may need to apply additional transformations before running arbitrary circuits. See the best practices guide for more information about running circuits on hardware.
valid_qubit = sorted(device.metadata.qubit_set)[0]
# Transform circuit to use an available hardware qubit.
hw_circuit = circuit.transform_qubits(lambda q: valid_qubit)
print(hw_circuit)
(3, 2): ───X───M('result')───
Create a job on the Quantum Engine
Cirq circuits are represented in the Quantum Computing Service as Programs. To run a Program, you must create a Job that specifies details about the execution, e.g. the processor to use and the number of times to repeat the experiment. This enables a single circuit to be run multiple times in different configurations. For a one-off use, these steps can be done together by using the engine.run_sweep
utility to create both a Program and a Job.
A new Job will be scheduled on the requested hardware as it becomes available. The execution of your Job will likely be completed within a few seconds and the results will be displayed below. The output will include a link to the console, where you can view the status and results of your jobs.
print("Uploading program and scheduling job on the Quantum Engine...\n")
# Upload the program and submit jobs to run in one call.
job = processor.run_sweep(
program=hw_circuit,
repetitions=1000)
print("Scheduled. View the job at: https://console.cloud.google.com/quantum/"
"programs/{}?&project={}".format(job.id(), project_id))
# Print out the results. This blocks until the results are returned.
results = job.results()
print("\nMeasurement results:")
for result in results:
print(result)
Uploading program and scheduling job on the Quantum Engine... Scheduled. View the job at: https://console.cloud.google.com/quantum/programs/projects/fake_project/processors/rainbow/job/2?&project=fake_project Measurement results: result=1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
Running from the command line
If you are planning to access Quantum Computing Service from the command line, follow these instructions to get started. If you plan on executing all of your programs from an ipython notebook, you can skip this section.
Setup Cirq
Follow the Cirq Install page to install Cirq locally. We highly recommend that you setup a virtual environment for this installation to isolate your development stack from your overall system installations. Make sure to setup the virtual environment for Python 3 and not Python 2.
Setup Google Cloud authentication
In this quickstart we will authenticate using the gcloud command line cool. To do this, one must first install gcloud. Follow the instructions for this at https://cloud.google.com/sdk/install We will authenticate using Application Default Credentials. To do this simply run the following on your shell command line
gcloud auth application-default login
This will open up a browser window or give you a link to a webpage you can navigate to in order to go through an authentication flow. Complete this using your Google account. After this command is run, credentials will be stored on your local machine. If at any point you want to revoke these credentials you can run gcloud auth application-default revoke
.
Write and run a short quantum program
Using your favorite IDE or editor, read and then paste the following hello_qubit program into a file called hello_qubit.py
. Make sure to replace the 'your-project-id'
string with the project id you created above.
import cirq
import cirq_google as cg
def example(engine, processor_id, project_id):
"""Hello qubit example run against a quantum processor."""
# Define a qubit.
qubit = cirq.GridQubit(5, 2)
# Create a circuit (qubits start in the |0> state).
circuit = cirq.Circuit(
cirq.X(qubit)**0.5, # Square root of NOT.
cirq.measure(qubit, key='result') # Measurement.
)
print("Uploading program and scheduling job on Quantum Engine...\n")
processor = engine.get_processor(processor_id)
# Upload the program and submit jobs to run in one call.
job = processor.run_sweep(
program=circuit,
repetitions=1000)
print("Scheduled. View the job at: https://console.cloud.google.com/quantum/"
f"programs/{job.program().id()}/jobs/{job.id()}"
f"/overview?project={project_id}")
# Print out the results. This blocks until the results are returned.
results = job.results()
print("\nMeasurement results:")
for result in results:
print(result)
if __name__ == '__main__':
virtual = False
# Needed for colab only. Can remove in stand-alone.
import os
if 'COLAB_GPU' in os.environ:
print("Running on Colab, using a virtual engine instead.")
virtual = True
# Set up QCS objects.
from cirq_google.engine.qcs_notebook import get_qcs_objects_for_notebook
qcs_objects = get_qcs_objects_for_notebook(virtual=True)
processor_id = qcs_objects.processor_id
project_id = qcs_objects.project_id
engine = qcs_objects.engine
example(engine, processor_id, project_id)
Available processors: ['rainbow', 'weber'] Using processor: rainbow Uploading program and scheduling job on Quantum Engine... Scheduled. View the job at: https://console.cloud.google.com/quantum/programs/projects/fake_project/processors/rainbow/program/1/jobs/projects/fake_project/processors/rainbow/job/2/overview?project=fake_project Measurement results: result=0110100000101000100000111110110010111110010110100110010011111110010001011111001001111111010110101010010110100110111011011100110010100101010010011010001000100000101011011011111000010011001011101100001100101111011100110010111100000100000011111111100001101100001100011001100000101110111010100011000010111111101110111010101011100010101100111111011011100111101010110110000001100100110111101111100001101110011010011011000100000000010100011011001011011011011110101011010001100001001101011101011010101010110101100001101000111001001001010011011110010110101010101100110011110101110110011000100000001011110101011100000111111001110011110101110110101000000010011000001001110010100010111110010110000110001110100001001011111001011010100001010001111111001010010001000000010010001011011010101000010101111110001101110000010111000110010010001000000111111011000010111001101001110011010001000011110100111000001001111101001010010111101001100111001010110000001010000101000001000010101011111010000111111101010100110011101011
You should then be able to run this program from your command line using:
python hello_qubit.py
You should be able to see output like that shown above.
Next steps
- Use this template colab as a base for your own explorations.
- Explore best practices for getting circuits to run on hardware.