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

Quantum Machine Learning

◐ 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.

Treat a parameterized quantum circuit as a trainable model: encode classical data into qubits, apply learnable rotations, then optimize the parameters against a loss. It carries machine learning's "model–loss–gradient" paradigm into a quantum circuit.

The core idea — the circuit is the model

In classical machine learning, a model is a function fw(x) with tunable weights, and we adjust the weights so it performs better on the data. Quantum machine learning (QML) replaces that function with a quantum circuit: the input x determines how the front of the circuit encodes, the weights w determine how the back of the circuit rotates, and the model's output is the expectation value of some observable. The whole "forward pass — compute loss — adjust parameters" loop stays exactly the same; only the function in the middle has become quantum.

Encoding classical data into a quantum state

A quantum circuit only understands quantum states, not arrays of floats, so the first step must be data encoding (also called a feature map): writing the classical vector x into the qubits. The most common angle encoding uses the components of x as the rotation angles of rotation gates, e.g. ry(x0, q0).

The encoding matters enormously: it determines what data geometry the model can "see". Some encodings map the input into highly nonlinear regions of state space — precisely where QML hopes to gain expressive power. Encoding that is too weak leaves different inputs hard to tell apart; encoding that is too strong, or too high-dimensional, can instead cause poor generalization, concentration of kernel values, or unstable training. The choice of encoding is a central part of QML model design, not a detail.

The parameterized circuit as a trainable layer

After encoding comes a variational layer with tunable parameters: a series of parameterized rotation gates, often alternating with entangling gates. These parameters w are the model's "weights". Given an input x, the circuit prepares a state |ψ(x, w)⟩, and the model's prediction is taken from the expectation value of some observable, e.g. ⟨Z0:

f(x, w) = ⟨ψ(x, w)| Z0 |ψ(x, w)⟩

Training means adjusting w so that f(x, w) matches the target labels on the training data — exactly like a classical neural network.

Where the gradient comes from — the parameter-shift rule

To train with a gradient-based optimizer we need the partial derivative of f(x, w) with respect to each parameter. Classical automatic differentiation cannot be done directly on a quantum circuit, but there is an elegant result: the parameter-shift rule. For a rotation gate of the form e−iθP/2, the exact analytic gradient of its expectation value equals half the difference of the expectation values evaluated at the parameter plus π/2 and minus π/2:

∂⟨O⟩/∂θ = ½ · [ ⟨O⟩θ+π/2 − ⟨O⟩θ−π/2 ]

Note: this is the exact gradient, not a finite-difference approximation — you just run the same circuit once at each of the two shifted points. It lets a quantum layer plug seamlessly into standard optimizers like Adam and SGD.

This holds for rotation gates of the form e−iθP/2 whose generator satisfies P² = I (such as a Pauli generator): the parameter-shift rule then gives the exact analytic gradient. For more general parameterized gates or pulse-level parameters, a different shift, more evaluation points, or an approximate method may be required, and the simple two-point ±π/2 formula does not necessarily apply.

Barren plateaus — a real obstacle

QML faces a distinctive and stubborn training obstacle — barren plateaus. For many randomly initialized, sufficiently "expressive" circuits, the gradient of the loss landscape vanishes exponentially with the number of qubits. In other words, the loss surface is nearly flat across most of the space, the optimizer receives almost no directional signal, and training stalls.

Mitigations include: structured ansätze (with problem priors), carefully designed initialization, local rather than global losses, and layer-wise training. But barren plateaus are one of the fundamental constraints on QML scalability, and any serious practice must confront them.

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

  • The advantage is not yet proven. This is the most important point to be honest about: for the vast majority of practical data tasks, whether QML beats mature classical machine learning is not currently established. Many seemingly leading results do not hold up against stronger classical baselines.
  • Training can be hard. Barren plateaus, sampling noise, and the encoding–expressivity trade-off together make training far more fragile than for classical networks.
  • Data in and out is a bottleneck. Efficiently loading large-scale classical data into a quantum state is itself expensive and can cancel any potential speedup.
  • There are theoretically interesting special cases. For data that is itself quantum in structure (quantum states, quantum processes), or for certain kernel methods, there are provable hints of advantage — and that is the most worthwhile direction to explore right now.
An honest positioning
Treat QML as a promising but still-exploratory research paradigm, not a production tool ready to deploy. Its most valuable use today is in understanding the expressive power and trainability of quantum models, not in claiming to beat classical methods on general tasks.

Seeing it in code

The circuit below stitches the two structures above together: the first half — ry(x[0], …), ry(x[1], …) plus an entangling gate — is the data encoding (feature map); the second half — ry(weights[0], …), ry(weights[1], …) — is the trainable variational layer; and observable = spin.z(0) sets the model's prediction to ⟨Z0.

import qalgora
from qalgora import spin

@qalgora.kernel
def classifier(features: list[float], weights: list[float]):
    q = qalgora.qvector(2)
    # feature map: encode the input
    ry(features[0], q[0])
    ry(features[1], q[1])
    x.ctrl(q[0], q[1])
    # trainable layer
    ry(weights[0], q[0])
    ry(weights[1], q[1])

observable = spin.z(0)   # prediction = <Z_0>

The training loop is a standard machine-learning workflow: predict takes the circuit's output expectation value as the prediction; loss is the mean squared error; the Adam optimizer adjusts weights to drive the loss down. The gradient is wired in explicitly via qalgora.gradients.ParameterShift(), so the parameter-shift rule above is what computes the gradients with respect to weights.

规范接口·参考实现暂未包含 — specification interface
qalgora.optimizers.* and qalgora.gradients.* are specification interfaces; the open reference build does not bundle them yet, so the optimizer block below is a spec sketch rather than a runnable script.
import numpy as np

# 4-point parity dataset; labels encoded as -1/+1 because <Z_0> in [-1, 1]
train_x = np.array([[0.0, 0.0], [0.0, np.pi], [np.pi, 0.0], [np.pi, np.pi]])
train_y = np.array([1.0, -1.0, -1.0, 1.0])

def predict(x, w):
    return qalgora.observe(classifier, observable, x, w).expectation()

def loss(w, data, labels):
    return np.mean([(predict(x, w) - y) ** 2 for x, y in zip(data, labels)])

grad = qalgora.gradients.ParameterShift()
opt = qalgora.optimizers.Adam(gradient=grad)
weights, _ = opt.optimize(dimensions=2,
                          function=lambda w: loss(w, train_x, train_y))
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.

Because ⟨Z0⟩ ∈ [−1, 1], the binary-classification labels can be encoded as −1 / +1.

Gradients
Use the parameter-shift rule for exact analytic gradients of circuit expectation values — qalgora.gradients.ParameterShift() plugs straight into the optimizers.

Where it helps

  • Quantum kernels — circuits as feature maps for classical SVMs.
  • Variational classifiers — end-to-end trainable quantum models.
  • Generative models — Born-machine sampling of distributions.
Try it yourself
Increase the number of qubits and the number of variational layers, and watch how training gets harder with scale — the most direct hands-on taste of barren plateaus. The hybrid quantum neural networks page embeds such a quantum layer into a full PyTorch training stack.

量子机器学习

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

将参数化量子线路当作一个可训练模型:把经典数据编码进量子态,施加可学习的旋转,再针对损失函数优化参数。它把机器学习的"模型—损失—梯度"范式搬进了量子线路。

核心思路 线路即模型

经典机器学习里,模型是一个带可调权重的函数 fw(x),我们调权重让它在数据上表现更好。量子机器学习 (QML) 把这个函数替换成一段量子线路:输入 x 决定线路前段如何编码,权重 w 决定线路后段如何旋转,模型的输出则是某个可观测量的期望值。整套"前向传播—算损失—调参数"的循环原封不动,只是中间那个函数变成了量子的。

把经典数据编码进量子态

量子线路只认量子态,不认浮点数组,所以第一步必须是数据编码(也叫特征映射):把经典向量 x 写进量子比特。最常见的角度编码,是用 x 的各分量作为旋转门的转角,例如 ry(x0, q0)

编码方式至关重要,它决定了模型能"看见"怎样的数据几何。某些编码会把输入映射到态空间里高度非线性的区域——这正是 QML 期望带来表达力的地方。编码过弱会使不同输入难以区分;编码过强或维度过高又可能导致泛化困难、核值集中或训练不稳定。编码的选择是 QML 模型设计的核心一环,而非细枝末节。

参数化线路作为可训练层

编码之后,接上一段带可调参数的变分层:一系列参数化旋转门,常与纠缠门交替。这些参数 w 就是模型的"权重"。给定输入 x,线路制备出态 |ψ(x, w)⟩,模型的预测取自某可观测量的期望值,例如 ⟨Z0

f(x, w) = ⟨ψ(x, w)| Z0 |ψ(x, w)⟩

训练就是调节 w,使 f(x, w) 在训练数据上逼近目标标签——与经典神经网络如出一辙。

梯度从何而来 参数移位规则

要用基于梯度的优化器训练,就得知道 f(x, w) 对每个参数的偏导。量子线路上无法直接做经典自动微分,但有一个优雅的结果:参数移位规则。对形如 e−iθP/2 的旋转门,其期望值的精确解析梯度等于在该参数加 π/2 与减 π/2 两处期望值之差的一半:

∂⟨O⟩/∂θ = ½ · [ ⟨O⟩θ+π/2 − ⟨O⟩θ−π/2 ]

注意:这是精确梯度,不是有限差分近似——只需把同一线路在两个移位点各跑一遍即可。它让量子层无缝接入 Adam、SGD 等标准优化器。

对形如 exp(−iθP/2)、且 P²=I(如 Pauli 生成元)的旋转门,参数移位规则给出精确解析梯度;对更一般的参数化门或脉冲参数,可能需要不同的 shift、多个评估点或近似方法,二点 ±π/2 公式不一定适用。

贫瘠高原 一个真实的拦路虎

QML 面对一个独特而棘手的训练障碍——贫瘠高原。对许多随机初始化、且足够"表达力强"的线路,损失景观的梯度会随量子比特数指数级趋近于零。换言之,损失曲面在绝大部分区域近乎平坦,优化器几乎收不到任何方向信号,训练举步维艰。

缓解之道包括:使用结构化(含问题先验)的拟设、精心设计的初始化、局域而非全局的损失、以及层级化训练。但贫瘠高原是 QML 可扩展性的根本性约束之一,任何认真的实践都必须正视它。

它擅长什么 又不擅长什么

  • 优势尚未得到证明。这是最该诚实的一点:对绝大多数实际数据任务,QML 是否优于成熟的经典机器学习,目前并无确证。许多看似领先的结果在更强经典基线下并不稳健。
  • 训练可能很难。贫瘠高原、采样噪声、编码—表达力之间的权衡,叠加在一起使训练远比经典网络脆弱。
  • 数据进出是瓶颈。把大规模经典数据高效装载进量子态本身就代价高昂,可能抵消任何潜在加速。
  • 有理论上有趣的特例。对某些本身就具量子结构的数据(量子态、量子过程),或特定核方法,存在可证明的优势线索——这才是当前最值得探索的方向。
诚实的定位
把 QML 当作一个充满潜力、但仍在探索期的研究范式,而非已落地的生产工具。它最有价值的用途,眼下是理解量子模型的表达力与可训练性,而非声称在通用任务上超越经典方法。

对照代码理解

下面的线路把上文的两段结构拼在一起:前半 ry(x[0], …)ry(x[1], …) 加纠缠门是数据编码(特征映射);后半 ry(weights[0], …)ry(weights[1], …)可训练变分层observable = spin.z(0) 则把模型预测定为 ⟨Z0

import qalgora
from qalgora import spin

@qalgora.kernel
def classifier(features: list[float], weights: list[float]):
    q = qalgora.qvector(2)
    # feature map: encode the input
    ry(features[0], q[0])
    ry(features[1], q[1])
    x.ctrl(q[0], q[1])
    # trainable layer
    ry(weights[0], q[0])
    ry(weights[1], q[1])

observable = spin.z(0)   # prediction = <Z_0>

训练循环则是标准的机器学习流程:predict 取线路输出的期望值作预测;loss 是均方误差;Adam 优化器调节 weights 使损失下降。梯度通过 qalgora.gradients.ParameterShift() 显式接入,因此正是上文的参数移位规则在计算对 weights 的梯度。

规范接口·参考实现暂未包含 — specification interface
qalgora.optimizers.*qalgora.gradients.* 属于规范接口;开源参考实现尚未内置,故下面的优化器代码块仅作规范示意,而非可直接运行的脚本。
import numpy as np

# 四点奇偶数据集;因为  在 [-1, 1],标签编码为 -1/+1
train_x = np.array([[0.0, 0.0], [0.0, np.pi], [np.pi, 0.0], [np.pi, np.pi]])
train_y = np.array([1.0, -1.0, -1.0, 1.0])

def predict(x, w):
    return qalgora.observe(classifier, observable, x, w).expectation()

def loss(w, data, labels):
    return np.mean([(predict(x, w) - y) ** 2 for x, y in zip(data, labels)])

grad = qalgora.gradients.ParameterShift()
opt = qalgora.optimizers.Adam(gradient=grad)
weights, _ = opt.optimize(dimensions=2,
                          function=lambda w: loss(w, train_x, train_y))
规范接口 · 参考实现暂未包含
此示例展示的是 qalgora-Q 规范中的接口(或第三方库),开放参考实现目前尚未内置,仅用于说明预期用法;如需立即运行,请使用参考实现已支持的核心 API。

因为 ⟨Z₀⟩∈[−1,1],二分类标签可编码为 −1/+1。

梯度
使用参数移位规则可精确解析计算电路期望值的梯度——qalgora.gradients.ParameterShift() 可直接与优化器集成。

适用场景

  • 量子内核——将电路作为经典 SVM 的特征映射。
  • 变分分类器——端到端可训练的量子模型。
  • 生成模型——基于 Born 机的概率分布采样。
动手试试
增加量子比特数与变分层的层数,观察训练如何随规模变得更难——这是对贫瘠高原最直接的动手体会。混合量子神经网络页面把这样的量子层嵌入了完整的 PyTorch 训练栈。