Hybrid Quantum Machine Learning with PennyLane and PyTorch: A Practical End-to-End Tutorial
PennyLanePyTorchquantum machine learninghybrid AIvariational quantum circuitsPython

Hybrid Quantum Machine Learning with PennyLane and PyTorch: A Practical End-to-End Tutorial

SSharp Qbit Editorial Team
2026-11-04
7 min read

Build a reproducible PennyLane and PyTorch workflow with data encoding, variational training, baselines, debugging, and experiment tracking.

This practical PennyLane and PyTorch tutorial shows how to build a small, reproducible hybrid quantum-classical machine learning workflow: prepare classical data, encode it into a variational quantum circuit, train the circuit with PyTorch, compare it with a classical baseline, and record enough information to debug or repeat the experiment later.

Overview

Hybrid quantum AI combines a classical machine learning framework with a parameterized quantum circuit. PyTorch handles the familiar parts of the workflow—tensors, optimization, and metrics—while PennyLane provides a differentiable interface to the quantum device. The result is not a purely quantum model. It is a hybrid pipeline in which classical preprocessing and optimization surround a quantum layer.

The most useful starting point is a deliberately small binary classification problem. Small datasets and short circuits make it easier to answer practical questions: Did the data encoding work? Are the circuit parameters changing? Is the quantum model learning anything beyond a simple classical baseline? Can the same code run on a simulator and, later, on available hardware?

This tutorial uses a two-feature classification example. The feature count is intentionally limited because a basic angle-encoding circuit commonly maps one feature to one qubit. Larger datasets require an explicit design for dimensionality reduction, feature reuse, amplitude encoding, or a different circuit layout.

Target workflow

  1. Pin or record the Python, PennyLane, PyTorch, and related package versions.
  2. Create and normalize a small, labeled dataset.
  3. Define a classical baseline before evaluating the quantum model.
  4. Encode features into qubit rotations.
  5. Apply trainable variational layers and measure an expectation value.
  6. Train the model with a PyTorch optimizer and inspect validation behavior.
  7. Track configuration, seeds, metrics, and circuit assumptions.

For broader context on the design choices, compare this workflow with the hybrid quantum machine learning workflow guide and the PennyLane, Qiskit, and Cirq comparison.

Checklist by scenario

Scenario 1: Setting up a local experiment

Start in an isolated virtual environment rather than installing quantum and machine learning packages into a general-purpose Python environment. Package interfaces and supported combinations can change, so record the versions that successfully ran your experiment.

python -m venv .venv
# Activate the environment using the command for your operating system
python -m pip install --upgrade pip
python -m pip install pennylane torch scikit-learn
python -m pip freeze > requirements-lock.txt

The exact installation command is less important than reproducibility. If a package changes its device names, interfaces, or tensor behavior, a version record makes the result easier to reproduce and troubleshoot. Before coding, also check the current PennyLane and PyTorch documentation for the supported integration pattern.

Scenario 2: Building the smallest useful model

The following example uses two input features, two qubits, one variational layer, and a single expectation-value output. It is a teaching model, not a claim that a quantum circuit is preferable to a classical neural network for this task.

import pennylane as qml
import torch
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# Reproducibility for this demonstration
torch.manual_seed(7)

X, y = make_moons(n_samples=240, noise=0.12, random_state=7)
X = StandardScaler().fit_transform(X)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=7, stratify=y
)

X_train = torch.tensor(X_train, dtype=torch.float32)
X_test = torch.tensor(X_test, dtype=torch.float32)
y_train = torch.tensor(y_train, dtype=torch.float32)
y_test = torch.tensor(y_test, dtype=torch.float32)

n_qubits = 2
n_layers = 2
dev = qml.device("default.qubit", wires=n_qubits)

@qml.qnode(dev, interface="torch")
def quantum_layer(x, weights):
    # One rotation per feature: the feature dimension must match the qubit count.
    for wire in range(n_qubits):
        qml.RY(x[wire], wires=wire)

    for layer in range(n_layers):
        for wire in range(n_qubits):
            qml.RY(weights[layer, wire, 0], wires=wire)
            qml.RZ(weights[layer, wire, 1], wires=wire)
        qml.CNOT(wires=[0, 1])

    return qml.expval(qml.PauliZ(0))

class HybridClassifier(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.weights = torch.nn.Parameter(
            0.01 * torch.randn(n_layers, n_qubits, 2)
        )
        self.bias = torch.nn.Parameter(torch.zeros(1))

    def forward(self, X):
        outputs = torch.stack([quantum_layer(x, self.weights) for x in X])
        return outputs + self.bias

model = HybridClassifier()
optimizer = torch.optim.Adam(model.parameters(), lr=0.05)
loss_fn = torch.nn.BCEWithLogitsLoss()

for epoch in range(80):
    optimizer.zero_grad()
    logits = model(X_train)
    loss = loss_fn(logits, y_train)
    loss.backward()
    optimizer.step()

    if (epoch + 1) % 10 == 0:
        with torch.no_grad():
            predictions = (torch.sigmoid(logits) >= 0.5).float()
            accuracy = (predictions == y_train).float().mean()
        print(epoch + 1, float(loss), float(accuracy))

The circuit returns values between the natural range of the measured observable. The trainable bias and the binary-cross-entropy loss convert that output into a classification score. This is a useful arrangement for learning, but the output convention must remain consistent: do not silently switch between probabilities, logits, and expectation values without changing the loss and evaluation code accordingly.

Scenario 3: Adding a classical baseline

A baseline is part of the experiment, not an optional appendix. Train a small classical model on the same split, preprocessing, labels, and evaluation metric. A logistic regression model is often a reasonable first comparison for a two-feature demonstration; a small multilayer perceptron can be added if the problem calls for a nonlinear classical comparator.

Compare at least training loss, validation or test accuracy, and the number of trainable parameters. Keep the data split fixed. If the quantum model is changed while the baseline is not rerun, the comparison becomes difficult to interpret.

Scenario 4: Moving from a simulator to hardware

First verify the circuit and training loop on a simulator. Then separate software validation from hardware evaluation. A hardware run introduces sampling, noise, execution constraints, and device-specific behavior, so it should be treated as a new experiment with its own configuration and results.

Before submitting jobs, reduce the circuit to the smallest version that still tests your question. Record the device or simulator name, shots or sampling settings, circuit depth, transpilation or compilation choices where applicable, and the date of the run. The guide to running quantum circuits on real hardware covers the operational considerations that follow this local prototype.

What to double-check

  • Feature shape: Confirm that every input sample has the number of features expected by the encoding function. If the dataset has more features than qubits, choose and document a reduction or re-uploading strategy.
  • Scaling: Standardize or otherwise constrain features before using them as rotation angles. Unscaled inputs can make the initial circuit behavior difficult to interpret.
  • Labels and loss: Check whether labels are integers, floating-point values, probabilities, or logits. Match their representation to the selected PyTorch loss.
  • Gradient interface: Confirm that the PennyLane QNode uses the intended interface and differentiation method for the installed versions. A model that runs forward but produces no usable gradients is not a trainable workflow.
  • Initialization: Inspect initial outputs and gradients before a long run. Near-identical outputs, zero gradients, or rapidly diverging values are signals to investigate.
  • Evaluation split: Never tune circuit depth, learning rate, or preprocessing repeatedly against the final test set. Reserve it for the final comparison.
  • Sampling assumptions: A noiseless analytic simulator and a finite-shot hardware execution do not measure exactly the same thing. Label results clearly.
  • Experiment record: Save the seed, package versions, dataset construction, preprocessing, circuit structure, optimizer settings, number of epochs, and metrics.

For local development decisions, the quantum simulator comparison can help you separate a framework question from a device-model question.

Common mistakes

Calling a circuit quantum without defining the comparison

A variational circuit is only one component of a complete model. State which part is quantum, what the classical baseline is, and whether the comparison measures predictive performance, resource use, educational value, or hardware behavior.

Increasing circuit size before validating the small case

More layers and qubits add debugging variables. First confirm that a single sample produces the expected output, gradients are nonzero where appropriate, and a tiny batch can reduce its loss. Scale only after those checks pass.

Mixing data leakage with impressive-looking results

Fit preprocessing steps using training data only when the workflow requires it. Keep test data out of model selection. A high score is not useful evidence if the split or preprocessing leaks information across the evaluation boundary.

Assuming simulator success predicts hardware success

Simulation is excellent for circuit logic and integration testing. It does not automatically account for all hardware effects. Use a staged plan: noiseless simulation, optional noise model, then hardware, with results reported separately.

Ignoring framework changes

PennyLane devices, PyTorch interfaces, differentiation settings, and third-party plugin behavior may evolve. Avoid relying on undocumented behavior. Pin working versions for a project and revisit the official documentation when upgrading.

When to revisit

Return to this checklist before a new experiment cycle, after upgrading PennyLane or PyTorch, when changing the simulator or hardware target, and whenever the dataset or feature count changes. These are the points at which an apparently small modification can alter tensor types, gradients, circuit depth, runtime, or evaluation fairness.

A practical update routine is:

  1. Recreate the environment from the recorded dependency file or update it deliberately.
  2. Run a smoke test on one sample and one short training loop.
  3. Compare the updated model with the same classical baseline and data split.
  4. Review warnings, device defaults, differentiation behavior, and output conventions.
  5. Record what changed before interpreting new results.

Once the local workflow is stable, use the project’s research question to decide whether to add noise modeling, a different encoding, more expressive layers, or real hardware. For reporting and comparison, consult the guide to benchmarking quantum algorithms. The objective is not to make the circuit larger by default; it is to make each experiment easier to explain, reproduce, and improve.

Related Topics

#PennyLane#PyTorch#quantum machine learning#hybrid AI#variational quantum circuits#Python
S

Sharp Qbit Editorial Team

Quantum Computing Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.