Time: 1-2 Hours
Expected knowledge: Basic familiarity with Google Cloud is strongly encouraged. Some knowledge of machine learning and quantum circuits and algorithms is helpful
System requirements: Internet access, Python 3.6 or later

One of the most exciting applications of quantum computing today is its application to machine learning algorithms. Equivalently-sized quantum kernels have been proved to provide measurable improvements in learning on the identical training data.

With the latest major release of TensorFlow Quantum (>= 0.6.0), it’s now possible to use the quantum machine learning spinoff of one of the world’s most well-known machine learning libraries with IonQ’s devices. Whether you’re struggling with barren plateaus, or doing full-fledged reinforcement learning, this guide can help you take the first step on the path of becoming a quantum machine learning (QML) expert.


Before you begin

You’ll need an account on the IonQ Quantum Cloud, and you’ll need to create an API key. We also have a guide about setting up and managing your API keys if you need some help.

This guide assumes that you have followed these instructions and have saved your API key as a local environment variable named IONQ_API_KEY.


About Tensorflow Quantum

TensorFlow Quantum (TFQ) is part of TensorFlow, a popular library for prototyping, training and deploying machine learning models. TFQ’s quantum machine learning tools help users of a variety of skill levels prototype and build machine learning models that use a hybrid quantum-classical approach by combining the quantum computing tools and logic designed in Cirq, with TensorFlow APIs, and inbuilt quantum circuit simulators.

The TensorFlow Quantum whitepaper and TensorFlow Quantum website provide more details on the motivation and philosophy behind the project, as well as full API documentation and example code for a variety of common ML application.


Installing and Setting up TensorFlow Quantum

You can install TensorFlow Quantum from PyPI, the Python Package Index, using pip.

We recommend creating a requirements.txt file and then installing from that:

echo "cirq-google>=0.13.1
cirq-ionq>=0.13.1
pydot==1.4.2
tensorflow>=2.7.0
tensorflow-quantum>=0.6.0" > requirements.txt

Note about Windows: Tensorflow Quantum must be built from source for Windows support. Alternatively, you can try running these inside WSL or a docker container.

Note about Python: We encourage doing this inside an environment management system like virtualenv or conda so as to avoid this fate, but do what makes the most sense for you.

To set up a virtual environment with venv and install our above requirements in to it, run the following:

python3 -m venv tfq-ionq
source tfq-ionq/bin/activate
pip install -r requirements

That’s it! Because TensorFlow quantum uses Cirq under the hood and IonQ works with Cirq, you’re now ready to use TensorFlow Quantum with IonQ hardware.


Running your first TensorFlow Quantum program

Here is an adaptation of TFQ’s Hello, many worlds tutorial, which uses the IonQ simulator backend to train a simple parameterized circuit.

Run the following as a Python script or in a Jupyter notebook, and you’re off to the races:

import tensorflow as tf
import tensorflow_quantum as tfq

import cirq
import sympy
import numpy as np

a, b = sympy.symbols('a b')

import cirq_ionq as ionq

# API key is assumed to be stored as an env var named IONQ_API_KEY
service = ionq.Service()

# Parameters that the classical NN will feed values into.
control_params = sympy.symbols('theta_1 theta_2 theta_3')

# Create the parameterized circuit.
qubit = cirq.LineQubit.range(1)[0]
model_circuit = cirq.Circuit(
    cirq.rz(control_params[0])(qubit),
    cirq.ry(control_params[1])(qubit),
    cirq.rx(control_params[2])(qubit))

controller = tf.keras.Sequential([
    tf.keras.layers.Dense(10, activation='elu'),
    tf.keras.layers.Dense(3)
])

# This input is the simulated mis-calibration that the model will learn to correct.
circuits_input = tf.keras.Input(shape=(),
                # The circuit-tensor has dtype `tf.string`
                dtype=tf.string,
                name='circuits_input')

# Commands will be either `0` or `1`, specifying the state to set the qubit to.
commands_input =    tf.keras.Input(shape=(1,),
                    dtype=tf.dtypes.float32,
                    name='commands_input')

dense_2 = controller(commands_input)

# TFQ layer for classically controlled circuits.
expectation_layer = tfq.layers.ControlledPQC(model_circuit,
                    backend=service.sampler('simulator'),
                    repetitions=3000,
                    # Observe Z
                    operators = cirq.Z(qubit))
expectation = expectation_layer([circuits_input, dense_2])

model = tf.keras.Model(inputs=[circuits_input, commands_input],
    outputs=expectation)
tf.keras.utils.plot_model(model, show_shapes=True, dpi=70)
commands = np.array([[0], [1]], dtype=np.float32)
expected_outputs = np.array([[1], [-1]], dtype=np.float32)
random_rotations = np.random.uniform(0, 2 * np.pi, 3)
noisy_preparation = cirq.Circuit(
    cirq.rx(random_rotations[0])(qubit),
    cirq.ry(random_rotations[1])(qubit),
    cirq.rz(random_rotations[2])(qubit)
)
datapoint_circuits = tfq.convert_to_tensor([
    noisy_preparation
] * 2)  # Make two copies of this circuit

print("Fitting with tfq... this may take some time...")

optimizer = tf.keras.optimizers.Adam(learning_rate=0.05)
loss = tf.keras.losses.MeanSquaredError()
model.compile(optimizer=optimizer, loss=loss)
history = model.fit(x=[datapoint_circuits, commands],
        y=expected_outputs,
        epochs=30,
        verbose=0)
print ("Plotting now")

import matplotlib.pyplot as plt
plt.plot(history.history['loss'])
plt.title("Learning to Control a Qubit")
plt.xlabel("Iterations")
plt.ylabel("Error in Control")
plt.show()

Once you’ve seen what it can do, simply switch the backend to service.sampler(‘qpu’) to run the above code on actual IonQ Hardware.

We’re very excited to see what our users do with this new functionality. Are you blazing a trail into the QML future? Have you used IonQ hardware for something interesting in the quantum machine learning space? Let us know at @IonQ_Inc.


Licensing for TensorFlow Quantum and all code samples in this document are Apache 2.0.