变分量子本征求解器(VQE)是最重要的近期量子算法之一。它可以求出分子或材料的基态能量——这是一项对经典计算机而言呈指数级困难、但在 NISQ 设备上却可行的计算。本指南将带你完成一个完整的 PennyLane VQE 实现。
VQE 的作用
VQE 用于求出哈密顿量 H(通常表示分子的能量)的最小本征值。其工作方式如下:
- 使用量子电路制备参数化试探态 |ψ(θ)⟩
- 在 QPU 上测量期望值 ⟨ψ(θ)|H|ψ(θ)⟩
- 使用经典优化器更新 θ 以最小化能量
- 重复上述步骤直至收敛
变分原理保证对于任意态都有 ⟨ψ(θ)|H|ψ(θ)⟩ ≥ E₀——因此最小化这个量便给出了真实基态能量 E₀ 的一个上界。
环境设置
安装 PennyLane 及其化学插件:
pip install pennylane pennylane-qchem
对于氢分子(H₂)——这个经典的 VQE 基准——我们需要两个电子和四个自旋轨道(4 个量子比特):
import pennylane as qml
from pennylane import numpy as np
import pennylane.qchem as qchem
# H2 at equilibrium bond length (Angstrom)
symbols = ["H", "H"]
coordinates = np.array([[0.0, 0.0, -0.6614], [0.0, 0.0, 0.6614]])
# Build the qubit Hamiltonian
H, qubits = qchem.molecular_hamiltonian(
symbols,
coordinates,
basis="sto-3g"
)
print(f"Hamiltonian: {len(H.ops)} terms, {qubits} qubits")
# Hamiltonian: 15 terms, 4 qubits
定义拟设
**拟设(ansatz)**是用于制备试探态的参数化电路。对于化学问题,UCCSD(酉耦合簇单激发与双激发,Unitary Coupled-Cluster Singles and Doubles)拟设是标准选择:
# Get UCCSD circuit parameters
electrons = 2
singles, doubles = qchem.excitations(electrons, qubits)
s_wires, d_wires = qchem.excitations_to_wires(singles, doubles, wires=range(qubits))
# Initial Hartree-Fock state (reference state)
hf_state = qchem.hf_state(electrons, qubits)
dev = qml.device("default.qubit", wires=qubits)
@qml.qnode(dev)
def circuit(weights, wires, s_wires=[], d_wires=[], hf_state=hf_state):
# Prepare HF reference state
qml.BasisState(hf_state, wires=wires)
# Apply UCCSD excitations
qml.UCCSD(weights, wires, s_wires=s_wires, d_wires=d_wires, init_state=hf_state)
return qml.expval(H)
运行 VQE 优化
借助 PennyLane 的自动微分功能,我们可以直接使用基于梯度的优化器:
# Initial parameters (all zeros = Hartree-Fock state)
init_params = np.zeros(len(singles) + len(doubles), requires_grad=True)
# Adam optimizer (works well for VQE)
opt = qml.AdamOptimizer(stepsize=0.4)
# Optimization loop
energy_history = []
params = init_params.copy()
for step in range(200):
params, energy = opt.step_and_cost(
lambda p: circuit(p, range(qubits), s_wires=s_wires, d_wires=d_wires),
params
)
energy_history.append(energy)
if step % 20 == 0:
print(f"Step {step:3d}: E = {energy:.6f} Ha")
print(f"\nVQE ground state energy: {energy:.6f} Ha")
print(f"Reference (exact): -1.136189 Ha")
典型输出:
Step 0: E = -1.117498 Ha
Step 20: E = -1.133254 Ha
Step 40: E = -1.135901 Ha
Step 60: E = -1.136140 Ha
...
VQE ground state energy: -1.136174 Ha
Reference (exact): -1.136189 Ha
VQE 达到了与精确能量相差约 0.015 mHa 的水平——这对 H₂ 而言即为化学精度。
使用无梯度优化器
对于有噪声的硬件,由于硬件梯度带有噪声,像 COBYLA 或 SPSA 这样的无梯度优化器往往表现更好:
from scipy.optimize import minimize
# Objective function (no gradient needed)
def objective(params):
return float(circuit(params, range(qubits), s_wires=s_wires, d_wires=d_wires))
result = minimize(
objective,
x0=init_params,
method="COBYLA",
options={"maxiter": 500, "rhobeg": 0.1}
)
print(f"COBYLA energy: {result.fun:.6f} Ha")
使用 HLQuantum 运行 VQE
HLQuantum 内置了一个可跨所有后端运行的 VQE 实现:
import hlquantum as hlq
# Define the Hamiltonian in HLQuantum's format
H = hlq.hamiltonians.h2_molecule(bond_length=1.32)
# Run VQE on any backend
result = hlq.algorithms.vqe(
hamiltonian=H,
ansatz="uccsd",
optimizer="adam",
max_iterations=200,
backend="pennylane", # or "qiskit", "cudaq"
)
print(f"Ground state energy: {result.energy:.6f} Ha")
print(f"Optimal parameters: {result.params}")
print(f"Converged in {result.iterations} iterations")
真实硬件使用技巧
在真实 QPU(IBM Quantum、IonQ)上运行 VQE 时,还需考虑以下几点:
每步使用较少的采样次数(shots)。 每个优化步骤 1000 次采样通常足以进行梯度估计。不要在每一步都使用 10,000 次采样——那会浪费 QPU 时间。
从浅层电路开始。 CNOT 门越少 = 噪声越小。对于硬件,可以考虑使用硬件高效拟设电路,而非 UCCSD。
启用误差缓解。 HLQuantum 的 error_mitigation="zne" 会应用零噪声外推(Zero Noise Extrapolation),这可以显著改善有噪声硬件上的结果:
result = hlq.run(vqe_circuit, backend="qiskit", device="ibm_sherbrooke",
error_mitigation="zne", shots=2048)
有关量子化学模拟的更多细节,请查看完整的 PennyLane guide 以及 HLQuantum algorithms reference。