A hybrid quantum-classical model does not replace a machine-learning stack; it adds a trainable quantum circuit to one part of it. This PennyLane and PyTorch workflow shows how to encode data, connect a variational quantum circuit to a PyTorch training loop, manage gradients and batches, compare against a classical baseline, and record enough information to reproduce the experiment.
Overview
The practical pattern is straightforward:
- Prepare and split a classical dataset.
- Scale features into a range suitable for the chosen quantum gates.
- Encode each example into a quantum circuit.
- Apply trainable variational layers.
- Measure one or more expectation values.
- Pass the quantum output to a classical loss function.
- Use PyTorch's optimizer to update the circuit parameters and any classical parameters.
PennyLane acts as the connection between the circuit and the automatic-differentiation system. PyTorch supplies the familiar model, loss, optimizer, and data-loading abstractions. The circuit can run on a simulator during development and, where the selected interface supports it, be adapted later for hardware experiments.
Dataset -> preprocessing -> feature encoding -> variational circuit
|
measurements
|
classical output layer or loss
|
PyTorch optimizerThis architecture is useful for small, controlled experiments, but it does not guarantee an advantage over a classical model. The first objective should be a correct, reproducible training loop. Treat the quantum component as an experimental model layer and compare it with a classical model using the same data split and evaluation metric.
Checklist by scenario
Scenario 1: Building the smallest working example
Start with a binary classification problem and a small number of input features. A compact circuit makes it easier to inspect shapes, gradients, and outputs before adding complexity.
- Choose the feature-to-qubit mapping: decide whether one feature maps to one qubit or whether features will be compressed first.
- Normalize deliberately: rotation gates are angle-based, so document the transformation from the original feature range to circuit angles.
- Select a device: use a differentiable simulator for the first implementation and specify the number of wires and shots explicitly.
- Define the measurement: an expectation value provides a continuous output that can feed a loss function.
- Keep the ansatz modest: begin with one or two layers of single-qubit rotations and entangling gates.
- Set a seed: use deterministic initialization where the framework and device configuration allow it.
A minimal model can look like this. Interfaces and argument details may vary across PennyLane and PyTorch releases, so verify the installed versions before running the example.
import pennylane as qml
import torch
from torch import nn
n_qubits = 2
n_layers = 2
device = qml.device("default.qubit", wires=n_qubits)
@qml.qnode(device, interface="torch", diff_method="backprop")
def circuit(x, weights):
qml.AngleEmbedding(x, wires=range(n_qubits), rotation="Y")
qml.StronglyEntanglingLayers(weights, wires=range(n_qubits))
return qml.expval(qml.PauliZ(0))
class QuantumClassifier(nn.Module):
def __init__(self):
super().__init__()
shape = qml.StronglyEntanglingLayers.shape(
n_layers=n_layers, n_wires=n_qubits
)
self.weights = nn.Parameter(0.01 * torch.randn(shape))
self.readout = nn.Linear(1, 1)
def forward(self, x):
values = torch.stack([circuit(row, self.weights) for row in x])
values = values.reshape(-1, 1)
return self.readout(values).squeeze(1)The list comprehension is intentionally clear rather than optimized. Once correctness is established, investigate batching and vectorization options supported by the installed device and interface. Do not assume that a circuit written for one execution mode will behave identically under another.
Scenario 2: Connecting the circuit to a training loop
Use the same discipline as for any PyTorch model. Convert labels to the shape and data type expected by the loss, separate training and validation data, and log both loss and a task metric.
model = QuantumClassifier()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.BCEWithLogitsLoss()
for epoch in range(20):
model.train()
optimizer.zero_grad()
logits = model(x_train)
loss = loss_fn(logits, y_train.float())
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
val_logits = model(x_val)
val_loss = loss_fn(val_logits, y_val.float())
val_pred = (torch.sigmoid(val_logits) >= 0.5).int()
val_accuracy = (val_pred == y_val).float().mean()
print(epoch, loss.item(), val_loss.item(), val_accuracy.item())This example uses a classical readout after one measured quantum value. Another design is to measure several observables and feed the resulting vector into a small classical layer. Choose the design based on the question being tested, not on circuit size alone.
Scenario 3: Scaling to batches and experiments
For a reusable project, separate the workflow into modules:
data.pyfor loading, splitting, scaling, and label validation.circuit.pyfor the device, embedding, ansatz, and measurements.model.pyfor the PennyLane-PyTorch module.train.pyfor optimization and checkpointing.evaluate.pyfor held-out metrics and plots.configs/for qubit count, layers, shots, learning rate, seed, and device name.
Use a data loader when the model and device support the required batching behavior. Otherwise, process examples in a controlled loop and record the effective batch size. For more guidance on parameter sweeps and result organization, see Parameterized Quantum Circuits: Efficient Sweeps, Batching, and Result Management Across SDKs.
Scenario 4: Moving beyond a simulator
Do not send the first unvalidated circuit to real hardware. First confirm that the circuit produces sensible outputs on an ideal simulator, then test a noisy simulation if appropriate, and only then plan a hardware run. Record the backend, compilation or transformation settings, shots, circuit depth, queue or execution identifiers, and measurement-processing choices. The guide to accessing real quantum hardware provides a broader platform comparison.
What to double-check
Data encoding
Feature scaling is part of the model definition. If one dataset is mapped to angles in one experiment and another uses a different range, the results are not directly comparable. Preserve the scaler fitted on the training set and apply it unchanged to validation and test data.
Gradient method
Gradient behavior depends on the device, interface, circuit operations, and execution mode. Confirm that the selected differentiation method is supported by the installed configuration. A successful forward pass does not prove that parameter gradients are available or numerically useful. Inspect gradients during a small test run before starting a long experiment.
Shots and noise
An analytic simulator and a finite-shot execution answer different questions. Finite shots introduce sampling variation, while hardware adds device-specific noise and compilation effects. Keep shot count and noise settings in the experiment record. If training becomes unstable, test whether the issue appears with exact expectations, finite-shot simulation, or both.
Baselines and splits
Compare the quantum model with at least one appropriately sized classical baseline, such as logistic regression or a small multilayer perceptron. Use identical train, validation, and test partitions. Report the metric that matches the task, not only training loss. A quantum circuit that fits a training set but fails on held-out data has not demonstrated useful generalization.
For a fuller evaluation checklist, see the Quantum Machine Learning Evaluation Guide. Also record circuit depth, qubit count, shots, runtime, and memory requirements using the quantum resource estimation worksheet.
Common mistakes
- Changing too many variables at once: vary the ansatz, optimizer, encoding, and dataset independently where possible.
- Using a large circuit before validating shapes: begin with one example and print input, output, label, and gradient shapes.
- Leaking preprocessing information: fit scaling or feature selection only on training data.
- Ignoring output conventions: verify whether the model returns logits, probabilities, expectation values, or sampled counts before selecting a loss.
- Assuming more layers are better: deeper circuits increase optimization and execution costs and may make training harder.
- Reporting a single run: initialization and sampling can affect results. Repeat important experiments with documented seeds or initialization settings.
- Comparing unlike budgets: compare models using clearly stated parameter counts, training duration, circuit executions, and evaluation procedures.
- Skipping regression tests: add small tests for circuit shape, output range, gradient availability, and preprocessing. The quantum software testing guide covers how to structure these checks.
When to revisit
Revisit this workflow before a new experiment cycle, after changing the dataset, or whenever PennyLane, PyTorch, a plugin, or a backend interface changes. Compatibility updates can affect device names, differentiation methods, batching behavior, measurement handling, and supported argument types.
Use this short pre-run checklist:
- Pin or record the installed package versions.
- Confirm that the selected device and differentiation method work together.
- Run a one-example forward pass and verify the output shape.
- Run one backward pass and confirm non-null, finite gradients.
- Check that preprocessing is fitted only on training data.
- Run the classical baseline using the same split and metric.
- Record qubits, layers, shots, batch size, optimizer, learning rate, seed, and runtime.
- Compare simulator results before interpreting hardware results.
Once the basic loop is reliable, make one controlled change at a time: a different embedding, ansatz, readout, optimizer, or execution device. That approach turns a quantum neural network tutorial into a maintainable hybrid quantum AI workflow rather than a one-off circuit demonstration.