qalgora-Q Docs Hub量子文档 ✦ Ask AI✦ 问问文档

Hybrid Quantum Neural Networks

◐ Design-level API
This page documents qalgora-Q API design, architecture, or adaptation workflows. Code examples illustrate intended usage and are not guaranteed to run in the current reference implementation.

Embed a parameterized quantum circuit as a layer inside a classical PyTorch network and train the whole model end-to-end. It treats a quantum circuit as a "special layer" of a neural network, stitched seamlessly together with classical layers.

The core idea — a quantum circuit as a layer

A modern neural network is a stack of "layers": each takes the previous layer's tensor, applies a differentiable transformation, and passes it on. The key insight of a hybrid quantum neural network is that a parameterized quantum circuit can itself serve as such a layer. It takes a numeric vector, encodes it into qubits, applies trainable rotations, and outputs a set of observable expectation values. From the outside, it is just a layer that "takes a tensor in, puts a tensor out, and holds trainable parameters" — no different from a Linear or Conv2d.

This gives a hybrid stack: classical layers handle efficient feature extraction and dimensionality reduction, the quantum layer provides a different non-linear feature map and inductive bias, and a classical layer reads it back out — whether that helps over a purely classical layer must be validated task by task. The whole pipeline is trained end-to-end together.

Inside the quantum layer — encoding plus trainable weights

Inside, the quantum layer reuses the standard two-part structure of a variational quantum model:

  • Data encoding: use the input components as rotation angles (e.g. ry(x0, q0)) to write the classical data into the quantum state.
  • Trainable rotations: a set of rotation gates with learnable parameters w, forming the layer's "weights".

The layer's output is the expectation value of some observable, e.g. ⟨Z0 — a real number in [−1, 1] that can be fed directly to a following classical layer.

The hybrid training loop — how gradients flow through

End-to-end training requires gradients to flow through both the classical and quantum layers simultaneously. Classical layers use ordinary backpropagation; the difficulty is the quantum layer — there is no classical automatic differentiation on a circuit. The solution is again the parameter-shift rule: for each parameter of the quantum layer, run the circuit once with that parameter shifted by +π/2 and once by −π/2, and half the difference of the two expectation values is the exact analytic gradient (exact for the Pauli-generated rotations used here, such as ry; gates with other generators need adapted shift values). When the quantum layer sits after a classical layer, the same rule applied to the input encoding angles also yields the gradient with respect to the layer's inputs, so the upstream classical layer receives gradients too.

Once this gradient is connected into the framework's computation graph by the chain rule, a classical optimizer (such as Adam) can update the quantum-layer parameters just like any ordinary weight. The whole hybrid model thus forms one unified, differentiable training loop: the forward pass runs through both classical and quantum layers to a prediction, and the backward pass sends gradients seamlessly back to every layer.

What it is good at — and what it isn't

  • Flexible architecture. The quantum layer can be placed anywhere in the network and freely combined with mature classical components, making it easy to run controlled experiments inside existing deep-learning pipelines.
  • Constrained by the same hard problems. The quantum layer still meets barren plateaus, sampling noise, and the data-encoding bottleneck; wrapping it in PyTorch does not remove these fundamental constraints.
  • Expensive to simulate. Every step and every sample in training must execute the quantum circuit (multiple times); on a classical simulator this is often far slower than a comparable purely classical network.
  • Advantage not yet proven. Consistent with QML as a whole: when and for which tasks a hybrid model truly surpasses a purely classical network is an open research question, not a settled fact.
An honest positioning
A hybrid quantum neural network is a convenient testbed for exploring whether a quantum layer can add value, not a verified production architecture. Treat it as a research and teaching tool, and stay cautious about claims of its performance.

The algorithm, step by step

  1. Define the quantum layer: encode with rotations from the input components, then apply rotations with trainable parameters, and output an observable's expectation value.
  2. Wrap the layer as a standard framework module (e.g. torch.nn.Module) and declare its trainable parameters.
  3. Stack the quantum layer with classical layers into a hybrid model.
  4. Forward pass: data flows through the layers in turn to a prediction and a loss.
  5. Backward pass: classical layers use automatic differentiation, the quantum layer uses the parameter-shift rule, and gradients flow through the whole stack.
  6. The optimizer updates all parameters uniformly; repeat until convergence.

Seeing it in code

The q_layer below is exactly the quantum layer described above: ry(x[0], …) and ry(x[1], …) are the data encoding, ry(w[0], …) and ry(w[1], …) are the trainable weights; quantum_forward takes ⟨Z0 as the layer's output.

import qalgora
from qalgora import spin

@qalgora.kernel
def q_layer(features: list[float], w: list[float]):
    q = qalgora.qvector(2)
    ry(features[0], q[0]); ry(features[1], q[1])     # data encoding
    x.ctrl(q[0], q[1])
    ry(w[0], q[0]); ry(w[1], q[1])     # trainable weights

def quantum_forward(features, w):
    return qalgora.observe(q_layer, spin.z(0), features, w).expectation()

Now wrap the quantum layer as a standard torch.nn.Module: self.w is the weight declared as a trainable parameter, and forward calls quantum_forward sample by sample; then Sequential sandwiches it between two classical Linear layers to form the shape of an end-to-end hybrid stack. (The torch.tensor(…, requires_grad=True) line shown is a forward-pass stub — it does not produce correct gradients for self.w, and xi.tolist() likewise detaches the input x, so upstream classical layers receive no gradient either; a true backward pass needs a custom torch.autograd.Function implementing the parameter-shift gradient above.)

import torch

class QuantumLayer(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.w = torch.nn.Parameter(torch.rand(2))
    def forward(self, x):
        outs = [quantum_forward(xi.tolist(), self.w.tolist()) for xi in x]
        return torch.tensor(outs, requires_grad=True).unsqueeze(1)   # (batch, 1) for the next Linear

# Linear(4, 2) -> 2 encoding angles -> 1 expectation per sample -> Linear(1, 1)
model = torch.nn.Sequential(torch.nn.Linear(4, 2), QuantumLayer(),
                            torch.nn.Linear(1, 1))
Specification API — not in the open reference build yet
This example shows a qalgora-Q specification API (or a third-party library) that the open reference build does not bundle today. It documents the intended interface; to run code now, use the reference build’s supported core API.
Gradients
Use the parameter-shift rule for exact quantum-layer gradients so backprop flows through both the classical and quantum parts.
Try it yourself
Move the quantum layer to different positions in the Sequential, or change its qubit count, and observe how the hybrid model's training dynamics change. The quantum machine learning page discusses data encoding, the parameter-shift rule, and barren plateaus in more detail.

混合量子神经网络

◐ 设计接口
本页描述的是 qalgora-Q 的接口设计、架构设计或适配工作流。相关代码用于说明预期用法,当前参考实现不保证可以直接运行。

将参数化量子线路作为一层嵌入经典 PyTorch 网络中,对整个模型进行端到端训练。它把量子线路当作神经网络里的一种"特殊层",与经典层无缝拼接。

核心思路 把量子线路当作一层

现代神经网络是若干"层"的堆叠:每层接收上一层的张量,做一次可微变换,再传给下一层。混合量子神经网络的关键洞见是——参数化量子线路本身就可以充当这样一层。它接收一个数值向量、把它编码进量子比特、施加可训练旋转、最后输出一组可观测量的期望值。从外部看,它就是一个"输入张量、输出张量、含可训练参数"的层,与 LinearConv2d 别无二致。

于是我们得到一个混合栈:经典层负责高效的特征提取与降维,量子层提供一种不同的非线性特征映射和归纳偏置(是否优于纯经典层需逐任务验证),再由经典层读出。整条流水线端到端一起训练。

量子层的内部 编码加可训练权重

量子层内部复用了变分量子模型的标准两段式结构:

  • 数据编码:用输入分量作旋转转角(如 ry(x0, q0)),把经典数据写进量子态。
  • 可训练旋转:一组带可学习参数 w 的旋转门,构成该层的"权重"。

层的输出是某可观测量的期望值,例如 ⟨Z0——一个落在 [−1, 1] 的实数,可直接喂给后续的经典层。

混合训练循环 梯度如何贯穿

端到端训练要求梯度能同时流过经典层和量子层。经典层用常规反向传播;难点在量子层——线路上没有经典自动微分。解法仍是参数移位规则:对量子层的每个参数,把线路在该参数加 π/2 与减 π/2 两处各跑一遍,二者期望值之差的一半就是精确解析梯度(对这里使用的、由 Pauli 生成元产生的旋转门如 ry 是精确的;生成元不同的门需相应调整移位值)。当量子层位于经典层之后时,对输入编码角施加同样的规则即可得到对该层输入的梯度,从而让上游经典层也能收到梯度。

把这个梯度按链式法则接入框架的计算图后,经典优化器(如 Adam)就能像更新任何普通权重一样更新量子层参数。整个混合模型于是构成一条统一的、可微的训练回路:前向传播穿过经典与量子层得到预测,反向传播把梯度无缝送回每一层。

它擅长什么 又不擅长什么

  • 架构灵活。量子层可放在网络任意位置,与成熟的经典组件自由组合,便于在已有深度学习流水线中做受控实验。
  • 受同样的难题制约。量子层照样会遭遇贫瘠高原、采样噪声与数据编码瓶颈;把它包进 PyTorch 并不能消除这些根本约束。
  • 仿真开销大。训练中每一步、每个样本都要(多次)执行量子线路;在经典模拟器上,这往往比等规模的纯经典网络慢得多。
  • 优势尚未得到证明。与 QML 整体一致:混合模型何时、对哪些任务能真正超越纯经典网络,仍是开放的研究问题,而非既成事实。
诚实的定位
混合量子神经网络是探索"量子层能否带来增益"的便利试验台,而非已被验证的生产架构。把它当作研究与教学工具来对待,对其性能主张保持审慎。

算法逐步拆解

  1. 定义量子层:用输入分量做编码旋转,再施加带可训练参数的旋转,输出某可观测量的期望值。
  2. 把该层封装为框架的标准模块(如 torch.nn.Module),并声明其可训练参数。
  3. 将量子层与经典层堆叠成一个混合模型。
  4. 前向传播:数据依次穿过各层,得到预测与损失。
  5. 反向传播:经典层用自动微分,量子层用参数移位规则,梯度贯穿全栈。
  6. 优化器统一更新所有参数;重复直至收敛。

对照代码理解

下面的 q_layer 正是上文描述的量子层:ry(x[0], …)ry(x[1], …) 是数据编码,ry(w[0], …)ry(w[1], …) 是可训练权重;quantum_forward⟨Z0 作为该层的输出。

import qalgora
from qalgora import spin

@qalgora.kernel
def q_layer(features: list[float], w: list[float]):
    q = qalgora.qvector(2)
    ry(features[0], q[0]); ry(features[1], q[1])     # data encoding
    x.ctrl(q[0], q[1])
    ry(w[0], q[0]); ry(w[1], q[1])     # trainable weights

def quantum_forward(features, w):
    return qalgora.observe(q_layer, spin.z(0), features, w).expectation()

下面把量子层包成标准的 torch.nn.Moduleself.w 是声明为可训练参数的权重,forward 逐样本调用 quantum_forward;随后用 Sequential 把它夹在两个经典 Linear 层之间,构成端到端混合栈的结构形状。(示例中 torch.tensor(…, requires_grad=True) 仅为前向占位,不会self.w 产生正确梯度;xi.tolist() 同样切断了对输入 x 的梯度,因此前级经典层也收不到梯度;真正的反向传播需用自定义 torch.autograd.Function 实现上文的参数移位梯度。)

import torch

class QuantumLayer(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.w = torch.nn.Parameter(torch.rand(2))
    def forward(self, x):
        outs = [quantum_forward(xi.tolist(), self.w.tolist()) for xi in x]
        return torch.tensor(outs, requires_grad=True).unsqueeze(1)   # (batch, 1),供下一层 Linear

model = torch.nn.Sequential(torch.nn.Linear(4, 2), QuantumLayer(),
                            torch.nn.Linear(1, 1))
规范接口 · 参考实现暂未包含
此示例展示的是 qalgora-Q 规范中的接口(或第三方库),开放参考实现目前尚未内置,仅用于说明预期用法;如需立即运行,请使用参考实现已支持的核心 API。
梯度
对量子层梯度使用参数移位规则以获得精确结果,从而让反向传播同时流过经典部分和量子部分。
动手试试
把量子层在 Sequential 中移到不同位置,或增减其量子比特数,观察混合模型的训练动态如何变化。量子机器学习页面更细致地讨论了数据编码、参数移位规则与贫瘠高原。