Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Hybrid Quantum Neural Network (HQNN)

Tags: algorithm machine-learning variational

This tutorial demonstrates how to build a Hybrid Quantum Neural Network (HQNN) on Fashion-MNIST that combines classical neural network layers with a quantum variational circuit layer. The quantum layer is defined using Qamomile’s @qkernel API and integrated into a PyTorch training pipeline via the parameter shift rule.

Architecture

The entire model — CNN feature extractor, quantum layer, and fusion classifier — is trained end-to-end from scratch:

Input Image → CNN → π·σ(·) → Quantum Layer → [CNN feats, Q output] → Classifier → Output

Here, π⋅σ(⋅)\pi \cdot \sigma(\cdot) denotes element-wise sigmoid scaling: the CNN output is passed through the sigmoid function σ\sigma and multiplied by π\pi, mapping each feature to the interval (0,π)(0, \pi). This ensures that the rotation angles fed into the quantum layer remain bounded, avoiding wrap-around artifacts that can hinder training.

The fusion classifier takes both classical CNN features and quantum expectation values, allowing the CNN and quantum layer to learn cooperatively from the start.

Imports and Setup

Qubits: 4, Layers: 2, Trainable weights: 24

Define the Variational Ansatz with qkernel [source]

We define a parameterized quantum circuit using Qamomile’s @qkernel decorator. The circuit consists of:

  1. Angle encoding: Each input feature is encoded as an RY rotation on the corresponding qubit.

  2. Variational layers: Each layer applies RZ–RY–RZ rotations using stdlib layer functions, followed by a CZ entanglement ladder.

The circuit computes the expectation value ⟨H⟩\langle H \rangle of a given observable.

Let’s visualize the circuit structure. With inline=False, the stdlib layer functions are shown as compact boxes:

<Figure size 4594.5x336 with 1 Axes>

Transpile and Estimate Resources

We build one observable per qubit (⟨Zi⟩\langle Z_i \rangle) and create an executable for each. Each observable must span all qubits in the circuit so that the Qiskit estimator can match qubit counts; we use Hamiltonian(num_qubits=...) to ensure proper padding. Qamomile’s estimate_resources() gives us gate counts without needing to access the engine circuit directly.

Resource Estimate:
  Qubits: 4
  Gates:
    Total: 34
    Single-qubit: 28
    Two-qubit: 6
    Multi-qubit: 0
    T gates: 0
    Clifford gates: 6
    Rotation gates: 28

Quantum Forward Pass

The forward pass binds concrete values to the circuit parameters and evaluates ⟨Zi⟩\langle Z_i \rangle for each qubit using Qamomile’s executor.

Expectation values: [-0.70960489  0.61071606  0.43586927  0.42650987]

Parameter Shift Rule for Gradients

To train the quantum layer with PyTorch’s autograd, we need gradients of the expectation values with respect to every parameter. The parameter shift rule gives us an exact gradient formula for gates of the form e−iθG/2e^{-i\theta G/2}:

∂∂θk⟨Zi⟩=12[⟨Zi⟩∣θk+π/2−⟨Zi⟩∣θk−π/2]\frac{\partial}{\partial \theta_k} \langle Z_i \rangle = \frac{1}{2} \Big[ \langle Z_i \rangle\big|_{\theta_k + \pi/2} - \langle Z_i \rangle\big|_{\theta_k - \pi/2} \Big]

We implement this as a custom torch.autograd.Function so that PyTorch can backpropagate through the quantum layer. The implementation uses in-place parameter shifts to avoid allocating copies on every iteration.

Quantum Layer as a PyTorch Module

We wrap the autograd function into a standard nn.Module so it can be composed with other layers.

Prepare Data (Fashion-MNIST)

We use a subset of Fashion-MNIST with 4 visually distinct classes. Fashion-MNIST consists of 28x28 grayscale clothing images.

To keep computation time reasonable, we select 4 classes (T-shirt, Trouser, Sandal, Bag) with 60 training and 30 test samples per class.

Train: torch.Size([240, 1, 28, 28]), Test: torch.Size([120, 1, 28, 28])
Classes: ['T-shirt', 'Trouser', 'Sandal', 'Bag']

End-to-End Hybrid Model

We define the full hybrid model and train it end-to-end from scratch. The CNN feature extractor and quantum layer learn cooperatively — gradients flow from the loss through the fusion classifier, through the quantum layer (via parameter shift rule), and back into the CNN.

Input Image → [CNN Feature Extractor] → π·σ(·) → [Quantum Layer] → [CNN feats, Q output] → [Classifier] → Output
  • Sigmoid scaling: π⋅σ(⋅)\pi \cdot \sigma(\cdot) maps CNN outputs to (0,π)(0, \pi), keeping angles bounded and avoiding wrap-around.

  • Fusion classifier: Concatenation of [CNN features, quantum outputs] gives the classifier access to both classical and quantum representations.

=== End-to-End Training (10 epochs) ===
  Epoch 1/10  loss=1.3356  test_acc=55.83%
  Epoch 2/10  loss=0.9415  test_acc=97.50%
  Epoch 3/10  loss=0.6617  test_acc=97.50%
  Epoch 4/10  loss=0.5081  test_acc=96.67%
  Epoch 5/10  loss=0.4143  test_acc=96.67%
  Epoch 6/10  loss=0.3461  test_acc=96.67%
  Epoch 7/10  loss=0.3025  test_acc=96.67%
  Epoch 8/10  loss=0.2675  test_acc=96.67%
  Epoch 9/10  loss=0.2436  test_acc=96.67%
  Epoch 10/10  loss=0.2324  test_acc=97.50%
feature_extractor first conv grad mean: 0.07927611470222473
quantum weights grad mean: 0.009609604254364967

Evaluation

End-to-end quantum model accuracy: 97.50%

  T-shirt: 96.67%
  Trouser: 100.00%
  Sandal: 100.00%
  Bag: 93.33%
<Figure size 1500x400 with 3 Axes>