terminal
Docs

Get started with TensorFlow Quantum

Last updated: January 31, 2024
IonQ Staff

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 API key to actually submit programs to IonQ hardware or simulators. The easiest way to do this is to use our Google Cloud integration. Detailed instructions on how to create an IonQ Quantum Cloud account and generate a key using Google Cloud can be found here.

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: Tensorflow Quantum must be built from source for Windows support. Alternatively, you can try running these inside WSL or a docker container.

We recommend using a Python venv (or other environment management systems) to configure Python, so as to avoid this fate. The below instructions first create a venv and then install our above requirements using pip, but we encourage you to what makes the most sense for your setup and context.

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 on IonQ Hardware

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

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

service = ionq.Service(api_key="YOUR_SECRET_KEY")

# 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 miscalibration 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()

Run this as a python program or in a Jupyter notebook, making sure to update YOUR_SECRET_KEY to your actual secret key, and you’re off to the races!

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 or by dropping us a line.

Licensing for TensorFlow Quantum and all code samples in this document are Apache 2.0. API keys and access to IonQ services must be obtained under separate terms from IonQ.

The IonQ logo and Q mark are trademarks of IonQ, Inc. Copyright IonQ © 2022. All rights reserved.