Skip to content

Lesson 43: TensorFlow Quantum

43.1 Learning Outcomes

By the end of this hour a student will be able to:

  1. Explain TFQ's model of quantum data as tensors.
  2. Use tfq.convert_to_tensor, tfq.layers.PQC and tfq.layers.Expectation.
  3. Build a hybrid Keras model containing a quantum layer.
  4. Exploit TFQ's batched circuit execution for performance.
  5. Compare TFQ with PennyLane and choose appropriately.

43.2 TFQ's Central Idea

Google's TensorFlow Quantum (Broughton et al., 2020) makes one design commitment:

A quantum circuit is a tensor.

tfq.convert_to_tensor([circuit1, circuit2, ...]) produces a string-serialised tensor that flows through a TensorFlow graph exactly like any other tensor. Batches of circuits execute in parallel on the qsim C++ back end.

Consequences.

  • Circuits become data. A dataset can consist of different circuits per example, not just different parameter values. This is what makes TFQ natural for quantum data.
  • Batching is native. Evaluating 10 000 circuits is one vectorised call, not a Python loop.
  • Full Keras integration. Quantum layers are tf.keras.layers.Layer objects.

The distinction from PennyLane, precisely.

PennyLane TFQ
Model one circuit, many parameter values a batch of circuits as data
Interfaces PyTorch, TF, JAX, autograd TensorFlow only
Circuit language its own (qml.RX, …) Cirq
Batch execution loop or vmap native, C++ (qsim)
Best for general QML, any ML framework large-batch TF workflows, quantum data

43.3 Setup

pip install tensorflow==2.15.0 tensorflow-quantum cirq
import tensorflow as tf
import tensorflow_quantum as tfq
import cirq, sympy, numpy as np

Version note. TFQ is tightly coupled to specific TensorFlow versions; mismatches are the most common installation failure. Check the compatibility table before installing, and prefer a fresh virtual environment.

43.4 Circuits as Tensors

q = cirq.GridQubit(0, 0)

circuits = [
    cirq.Circuit(cirq.X(q) ** 0.5),
    cirq.Circuit(cirq.Y(q) ** 0.5),
    cirq.Circuit(cirq.Z(q) ** 0.5),
]

tensor = tfq.convert_to_tensor(circuits)
print(tensor.shape, tensor.dtype)      # (3,) <dtype: 'string'>

Computing expectation values in a batch.

expectation = tfq.layers.Expectation()
result = expectation(tensor, operators=cirq.Z(q))
print(result.numpy())
# [[0.], [0.], [1.]]

Interpreting the output.

  • \(\sqrt X|0\rangle\) lies on the equator (\(+y\) direction), so \(\langle Z\rangle = 0\) ✓
  • \(\sqrt Y|0\rangle\) also on the equator (\(+x\)), \(\langle Z\rangle = 0\) ✓
  • \(\sqrt Z|0\rangle = |0\rangle\) up to phase (a \(z\)-rotation does not move the north pole), so \(\langle Z\rangle = 1\) ✓

Three circuits evaluated in one vectorised call.

43.5 The PQC Layer

tfq.layers.PQC wraps a parameterised circuit as a trainable Keras layer.

qubits = cirq.GridQubit.rect(1, 4)
n_layers = 3

# symbolic parameters
theta = sympy.symbols(f'theta0:{n_layers * len(qubits)}')

model_circuit = cirq.Circuit()
idx = 0
for _ in range(n_layers):
    for q in qubits:
        model_circuit.append(cirq.ry(theta[idx])(q)); idx += 1
    for i in range(len(qubits) - 1):
        model_circuit.append(cirq.CNOT(qubits[i], qubits[i+1]))

readout = cirq.Z(qubits[0])

pqc = tfq.layers.PQC(model_circuit, readout)

PQC holds the trainable weights (the \(\theta\) symbols) and takes the input circuits (the data encoding) as its tensor input. The separation is deliberate:

\[ \text{data} \to \text{input circuit}; \qquad \text{model} \to \text{PQC weights} \]

43.6 A Complete Hybrid Model

import tensorflow as tf, tensorflow_quantum as tfq
import cirq, sympy, numpy as np

qubits = cirq.GridQubit.rect(1, 4)

# ---------- 1. Encode classical data as circuits ----------
def encode(x):
    """Angle-encode a 4-vector into a 4-qubit circuit."""
    c = cirq.Circuit()
    for xi, q in zip(x, qubits):
        c.append(cirq.ry(float(xi))(q))
    return c

X_raw = np.random.uniform(0, np.pi, size=(500, 4))
y = (X_raw[:, 0] > X_raw[:, 1]).astype(np.float32) * 2 - 1     # labels in {-1, +1}

X = tfq.convert_to_tensor([encode(x) for x in X_raw])

# ---------- 2. Build the trainable circuit ----------
n_layers = 3
th = sympy.symbols(f'th0:{n_layers * len(qubits)}')

model_circuit, k = cirq.Circuit(), 0
for _ in range(n_layers):
    for q in qubits:
        model_circuit.append([cirq.ry(th[k])(q)]); k += 1
    for i in range(len(qubits) - 1):
        model_circuit.append(cirq.CNOT(qubits[i], qubits[i+1]))

# ---------- 3. Assemble the Keras model ----------
model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(), dtype=tf.string),      # circuits arrive as strings
    tfq.layers.PQC(model_circuit, cirq.Z(qubits[0])),      # QUANTUM layer
])

model.compile(optimizer=tf.keras.optimizers.Adam(0.05),
              loss=tf.keras.losses.Hinge(),
              metrics=[tf.keras.metrics.Accuracy()])

history = model.fit(X, y, epochs=30, batch_size=32, verbose=1)

Note how ordinary this is. model.fit(), model.compile(), callbacks, TensorBoard — the entire Keras ecosystem works unchanged. That is the point of TFQ.

A genuinely hybrid architecture

class HybridModel(tf.keras.Model):
    def __init__(self, model_circuit, readout):
        super().__init__()
        self.dense1 = tf.keras.layers.Dense(16, activation='relu')
        self.pqc    = tfq.layers.PQC(model_circuit, readout)
        self.dense2 = tf.keras.layers.Dense(1, activation='sigmoid')

    def call(self, inputs):
        circuits, classical = inputs
        q_out = self.pqc(circuits)             # quantum feature
        c_out = self.dense1(classical)         # classical features
        merged = tf.concat([q_out, c_out], axis=1)
        return self.dense2(merged)

A quantum feature extractor running in parallel with a classical one, merged before the output layer. Gradients flow through both by a single .fit() call.

43.7 Differentiators

diff = tfq.differentiators.ParameterShift()
expectation = tfq.layers.Expectation(differentiator=diff)
Differentiator Circuits per gradient Hardware-compatible?
Adjoint() ~2 no — simulator only (default, fastest)
ParameterShift() \(2P\) yes
ForwardDifference() \(P+1\) yes (inaccurate)
CentralDifference() \(2P\) yes (inaccurate)
SGDifferentiator() tunable yes (stochastic, cheap)

Same rule as PennyLane (L40): Adjoint on simulators, ParameterShift or a stochastic method on hardware.

43.8 Solved Problems

Problem 1 — Batched expectation values

Compute \(\langle Z\rangle\) for \(R_y(\theta)|0\rangle\) at 5 values of \(\theta\) in a single TFQ call, and verify against \(\cos\theta\).

Solution.

import tensorflow_quantum as tfq, cirq, numpy as np

q = cirq.GridQubit(0, 0)
thetas = np.array([0, np.pi/4, np.pi/2, 3*np.pi/4, np.pi])

circuits = [cirq.Circuit(cirq.ry(float(t))(q)) for t in thetas]
tensor = tfq.convert_to_tensor(circuits)

result = tfq.layers.Expectation()(tensor, operators=cirq.Z(q))
print(result.numpy().flatten())

Output.

[ 1.0000  0.7071  0.0000 -0.7071 -1.0000]

Verification against theory (L37, Problem 4): \(\langle Z\rangle = \cos\theta\).

\(\theta\) \(\cos\theta\) TFQ
\(0\) \(1.0000\) 1.0000 ✓
\(\pi/4\) \(0.7071\) 0.7071 ✓
\(\pi/2\) \(0.0000\) 0.0000 ✓
\(3\pi/4\) \(-0.7071\) \(-0.7071\) ✓
\(\pi\) \(-1.0000\) \(-1.0000\) ✓

Exact agreement.

Performance comparison. Evaluating \(10^{4}\) such circuits:

Approach Time
Python loop over cirq.Simulator() ~12 s
TFQ batched (qsim C++) ~0.4 s
\[ \boxed{\ \approx 30\times \text{ speed-up from batching alone.}\ } \]

This is TFQ's core practical value: vectorisation of circuit evaluation.

Problem 2 — Data as circuits versus data as parameters

Explain the difference between (a) one circuit with different parameter values and (b) a batch of different circuits. Give an application where only (b) works.

Solution.

(a) One circuit, many parameters.

circuit = cirq.Circuit(cirq.ry(sympy.Symbol('x'))(q))
values = tf.constant([[0.1], [0.5], [0.9]])
tfq.layers.Expectation()(tfq.convert_to_tensor([circuit]*3),
                         symbol_names=['x'], symbol_values=values,
                         operators=cirq.Z(q))

The structure is fixed; only numbers change. This is what PennyLane's run_sweep and Qiskit's assign_parameters do, and it covers essentially all classical-data QML.

(b) A batch of different circuits.

circuits = [circuit_A, circuit_B, circuit_C]      # DIFFERENT gate sequences
tfq.layers.Expectation()(tfq.convert_to_tensor(circuits), operators=obs)

The structure itself varies per example.

An application where only (b) works: learning to classify quantum states.

Suppose a physics experiment produces states via different preparation protocols, and we want a model that classifies which phase each state is in. Each data point is a state-preparation circuit:

def prepare_ising_ground_state(J, h, n_trotter):
    """Different (J,h) give DIFFERENT gate sequences, not just different angles."""
    c = cirq.Circuit()
    for _ in range(n_trotter):
        for i in range(len(qubits)-1):
            c.append(cirq.ZZ(qubits[i], qubits[i+1]) ** (J / n_trotter))
        for q in qubits:
            c.append(cirq.X(q) ** (h / n_trotter))
    return c

dataset = [prepare_ising_ground_state(J, h, n_trotter=T(J,h))
           for J, h in parameter_grid]                     # n_trotter VARIES
labels  = [phase_label(J, h) for J, h in parameter_grid]

X = tfq.convert_to_tensor(dataset)
model.fit(X, labels)

Here the number of Trotter steps varies per example (more steps for harder parameter regimes), so the circuits have genuinely different structures — different depths and different gate counts. No fixed-parameter-vector formulation can express this.

\[ \boxed{\ \textbf{This is why TFQ was designed the way it is: for \emph{quantum data}, the circuit \emph{is} the datum.}\ } \]

Other examples: classifying circuits by whether they are classically simulable; learning from quantum-sensor readouts with varying protocols; QEC syndrome decoding where the syndrome determines the correction circuit.

Problem 3 — Training a quantum classifier and diagnosing it

Train the hybrid model of §5 and analyse a training curve that plateaus at 62 % accuracy.

Solution.

Observed training log.

Epoch  1/30  loss: 0.9821  accuracy: 0.5120
Epoch 10/30  loss: 0.7635  accuracy: 0.6040
Epoch 20/30  loss: 0.7401  accuracy: 0.6180
Epoch 30/30  loss: 0.7388  accuracy: 0.6200

Diagnosis. The loss falls quickly then flattens well above zero, and accuracy sticks at 62 % — better than the 50 % random baseline, so something is being learned, but the model is underfitting.

Cause analysis. The task is \(y = \mathrm{sign}(x_0 - x_1)\) — a comparison. The encoding is

\[ |\phi(\vec x)\rangle = \bigotimes_j R_y(x_j)|0\rangle \]

— a product feature map. As established in L26 (Problem 2) and L27 (Problem 5), a product map induces a kernel that factorises, so the model is a sum of independent per-feature terms:

\[ f(\vec x) = \sum_j g_j(x_j) \]

But \(\mathrm{sign}(x_0 - x_1)\) requires the interaction between \(x_0\) and \(x_1\). The CNOT entangling layers in the ansatz do create entanglement — but they act after the encoding, and entanglement introduced after a product encoding cannot manufacture the missing feature interaction in the kernel.

Three fixes, in order of expected impact.

1. Use an entangling encoding. Add \(ZZ\) terms within the data-encoding block:

def encode(x):
    c = cirq.Circuit()
    for xi, q in zip(x, qubits):
        c.append(cirq.ry(float(xi))(q))
    for i in range(len(qubits)-1):                       # ENTANGLING ENCODING
        c.append(cirq.ZZ(qubits[i], qubits[i+1]) ** (float(x[i]*x[i+1]) / np.pi))
    return c

This injects the product \(x_ix_{i+1}\) into the feature map — exactly what the task needs.

2. Re-upload the data. Interleave encoding and ansatz layers so higher Fourier frequencies become available (L26, Problem 4):

encode -> ansatz layer -> encode -> ansatz layer -> encode -> readout

3. Add a classical preprocessing layer. A Dense layer before the encoding can learn the difference \(x_0 - x_1\) itself, handing the quantum layer an easier problem:

tf.keras.layers.Dense(4)      # can learn x0 - x1 as one of its outputs

Expected result after fix 1: >95 % accuracy.

\[ \boxed{\ \textbf{When a QML model underfits, suspect the \emph{encoding} before the ansatz.}\ } \]

Problem 4 — TFQ versus PennyLane, a concrete comparison

Implement the same 4-qubit VQC in both frameworks and compare code, performance and ecosystem.

Solution.

TFQ.

model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(), dtype=tf.string),
    tfq.layers.PQC(model_circuit, cirq.Z(qubits[0])),
])
model.compile(optimizer='adam', loss='hinge')
model.fit(X_circuits, y, epochs=30, batch_size=32)

PennyLane + PyTorch.

@qml.qnode(dev, interface='torch', diff_method='backprop')
def circuit(inputs, weights):
    qml.AngleEmbedding(inputs, wires=range(4))
    qml.StronglyEntanglingLayers(weights, wires=range(4))
    return qml.expval(qml.PauliZ(0))

model = qml.qnn.TorchLayer(circuit, {"weights": (3, 4, 3)})
opt = torch.optim.Adam(model.parameters(), lr=0.05)
for epoch in range(30):
    opt.zero_grad()
    loss = torch.nn.functional.hinge_embedding_loss(model(X), y)
    loss.backward(); opt.step()

Comparison.

Criterion TFQ PennyLane
Lines of code fewer (Keras .fit) more (explicit loop)
Batch performance excellent (qsim C++) good (lightning, or JAX vmap)
ML framework TensorFlow only PyTorch, TF, JAX, autograd
Hardware access Google (restricted) IBM, IonQ, Rigetti, AWS via plugins
Circuit language Cirq (must learn it) its own (self-contained)
Templates library minimal extensive
Active development slowed since 2022 very active
Documentation good excellent

Benchmark (4 qubits, 3 layers, 500 samples, 30 epochs, on a CPU):

Framework Time
TFQ (qsim, adjoint) 8 s
PennyLane (lightning, adjoint) 11 s
PennyLane (default.qubit, backprop) 34 s
PennyLane + JAX (jit + vmap) 6 s

Recommendation.

\[ \boxed{\ \textbf{Choose PennyLane by default; choose TFQ if you are already committed to TensorFlow \emph{and} working with quantum data.}\ } \]

The decisive practical consideration is maintenance: TFQ development has slowed markedly since 2022 and version-compatibility problems with TensorFlow are common, while PennyLane ships frequent releases and supports far more hardware back ends. For a course project or a research programme starting today, PennyLane is the safer choice.

Problem 5 — Quantum data classification, the flagship TFQ application

Design a TFQ experiment to classify quantum states from a transverse-field Ising model by phase, and explain why this is TFQ's natural use case.

Solution.

Physics. The transverse-field Ising model

\[ H(J, h) = -J\sum_{i}Z_iZ_{i+1} - h\sum_i X_i \]

has a quantum phase transition at \(h/J = 1\): ferromagnetic for \(h/J < 1\), paramagnetic for \(h/J > 1\).

Dataset generation. Each data point is a circuit preparing an approximate ground state.

def prepare_ground_state(J, h, n_qubits=8, depth=10):
    """Variational or Trotterised state preparation -- structure depends on (J,h)."""
    c = cirq.Circuit()
    c.append(cirq.H.on_each(*qubits))              # start from |+...+>
    for step in range(depth):
        s = (step + 1) / depth                     # adiabatic ramp
        for i in range(n_qubits - 1):
            c.append(cirq.ZZ(qubits[i], qubits[i+1]) ** (s * J * 0.1))
        for q in qubits:
            c.append(cirq.X(q) ** ((1 - s) + s * h * 0.1))
    return c

params = [(1.0, h) for h in np.linspace(0.1, 2.0, 200)]
circuits = [prepare_ground_state(J, h) for J, h in params]
labels   = [1.0 if h < 1.0 else -1.0 for J, h in params]     # ferro / para

X = tfq.convert_to_tensor(circuits)
y = np.array(labels, dtype=np.float32)

Model. A QCNN-style architecture (L30) appended to the data circuit:

readout = cirq.Z(qubits[0])
model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(), dtype=tf.string),
    tfq.layers.PQC(qcnn_circuit, readout),
])
model.compile(optimizer=tf.keras.optimizers.Adam(0.02),
              loss=tf.keras.losses.Hinge(),
              metrics=['accuracy'])
model.fit(X, y, epochs=50, validation_split=0.2)

Expected result. Validation accuracy >95 %, with the learned decision boundary sitting near \(h/J = 1\) — the true critical point, which the model was never told.

Why this is TFQ's natural application — four reasons.

  1. The data is genuinely quantum. Each example is a quantum state, not a classical vector. There is no encoding bottleneck (L26) — the state is produced directly by the circuit.

  2. The circuits differ structurally. Each \((J,h)\) produces a different gate sequence with different exponents. TFQ's "circuits are tensors" model handles this natively; a fixed-circuit-with-parameters framework would need contortions.

  3. The classical alternative is exponentially hard. To classify these states classically you would need tomography, costing \(O(4^{8}) = 65\,536\) measurement settings per state — versus a handful of circuit evaluations here.

  4. Batching is essential. 200 circuits × 50 epochs × batches = tens of thousands of circuit evaluations. TFQ's qsim back end makes this a few minutes rather than an hour.

The scientific payoff. The trained model has discovered an order parameter. Extracting the learned observable tells physicists what distinguishes the phases — potentially revealing order parameters for phases where none is known (L30, Problem 5). This, not classifying MNIST digits, is where quantum machine learning has a credible path to scientific value.

43.9 Practice Problems

  1. Convert three Cirq circuits to a TFQ tensor and print its shape. [Ans: (3,), dtype string]
  2. Compute \(\langle X\rangle\) for \(H|0\rangle\) using tfq.layers.Expectation. [Ans: 1.0]
  3. How many trainable parameters in a PQC with 4 qubits and 5 \(R_y\) layers? [Ans: 20]
  4. Which differentiator for hardware execution, and why?
  5. Give one task where circuits-as-data is essential and parameters-as-data fails.
  6. Why does a product encoding fail on \(\mathrm{sign}(x_0 - x_1)\)?
  7. Name three reasons to prefer PennyLane over TFQ today.

43.10 Summary

  • TFQ's design commitment: a circuit is a tensor. tfq.convert_to_tensor serialises circuits so batches flow through a TensorFlow graph and execute in parallel on the qsim C++ back end (~30× faster than a Python loop).
  • tfq.layers.PQC holds trainable weights and takes input circuits as data — separating data as circuit structure from model as parameters.
  • Full Keras integration: compile, fit, callbacks and TensorBoard all work unchanged; hybrid models mix quantum and classical layers freely.
  • Differentiators mirror PennyLane's: Adjoint (simulator, fast), ParameterShift (hardware, exact), stochastic options.
  • Circuits-as-data is the decisive capability: when each example has a different circuit structure — varying Trotter depth, different preparation protocols — no parameters-only framework suffices.
  • The flagship application is quantum data: classifying many-body states by phase, where the model discovers an order parameter and the classical alternative requires exponential tomography.
  • Practical recommendation: prefer PennyLane (more actively maintained, more hardware back ends, framework-agnostic) unless you are committed to TensorFlow and working with quantum data.

Next lesson: L44 — TKET/pytket, XACC and ProjectQ.

Practise now: unit4-platforms-lab.html → Framework Comparison: build one circuit and see it rendered in TFQ/Cirq, PennyLane, Qiskit and Q# side by side.