什么是 PennyLane?
PennyLane 是 Xanadu 推出的开源量子机器学习框架。它将量子电路视为可微分函数,从而能够直接通过量子计算进行基于梯度的优化。你可以使用参数移位规则(parameter-shift rules)、伴随微分(adjoint differentiation)或反向传播来计算量子电路的梯度,并将其接入 PyTorch 或 JAX 的训练循环。所有这些功能都是免费且可在本地运行的。
PennyLane is the go-to SDK for variational circuits and VQE, the most practical class of hybrid algorithms on today's hardware.
安装
terminal
# Core with default.qubit (pure NumPy, always free)
pip install pennylane
# Fast C++ simulator (10-100x speedup)
pip install pennylane-lightning
# GPU simulator (requires NVIDIA GPU)
pip install pennylane-lightning-gpu
# For JAX or PyTorch integration
pip install pennylane jax jaxlib # JAX
pip install pennylane torch # PyTorch第一个量子电路
pennylane_basic.py
import pennylane as qml
import numpy as np
# Choose your device (all free, local)
dev = qml.device("default.qubit", wires=2)
# dev = qml.device("lightning.qubit", wires=2) # Faster C++ version
@qml.qnode(dev)
def bell_state():
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
return qml.probs(wires=[0, 1])
result = bell_state()
print(result) # [0.5, 0. , 0. , 0.5]
# Draw the circuit
print(qml.draw(bell_state)())
# 0: ──H─╭●──┤ ╭Probs
# 1: ────╰X──┤ ╰Probs量子机器学习——变分分类器
qml_classifier.py
import pennylane as qml
import numpy as np
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def variational_circuit(params, x):
# Encode input data
qml.AngleEmbedding(x, wires=[0, 1])
# Variational ansatz
qml.BasicEntanglerLayers(params, wires=[0, 1])
return qml.expval(qml.PauliZ(0))
# Initialize random parameters
params = np.random.uniform(0, np.pi, size=(3, 2))
# Compute gradient with parameter-shift rule (exact!)
grad_fn = qml.grad(variational_circuit)
x_sample = np.array([0.1, 0.2])
gradients = grad_fn(params, x_sample)
print(f"Parameters shape: {params.shape}")
print(f"Gradient shape: {gradients.shape}")
# Training loop
optimizer = qml.AdamOptimizer(stepsize=0.01)
for step in range(100):
params, cost = optimizer.step_and_cost(
lambda p: variational_circuit(p, x_sample), params
)
if step % 20 == 0:
print(f"Step {step}: cost = {cost:.4f}")使用 JAX 后端提升速度
pennylane_jax.py
import pennylane as qml
import jax
import jax.numpy as jnp
dev = qml.device("default.qubit", wires=4)
@qml.qnode(dev, interface="jax")
def circuit(params):
for i in range(4):
qml.RY(params[i], wires=i)
for i in range(3):
qml.CNOT(wires=[i, i+1])
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(3))
# JIT compile the circuit for massive speedup
jit_circuit = jax.jit(circuit)
# Automatic differentiation with JAX
grad_circuit = jax.grad(jit_circuit)
params = jnp.array([0.1, 0.2, 0.3, 0.4])
print(jit_circuit(params)) # Fast JIT-compiled execution
print(grad_circuit(params)) # Automatic gradient连接到其他后端
pennylane_backends.py
import pennylane as qml
# Local simulators (all free)
qml.device("default.qubit", wires=4) # NumPy
qml.device("lightning.qubit", wires=4) # C++ (fast)
qml.device("lightning.gpu", wires=4) # NVIDIA GPU
# IBM Quantum (free tier — needs account)
# pip install pennylane-qiskit
qml.device("qiskit.ibmq", wires=4, backend="ibm_sherbrooke")
# Amazon Braket
# pip install amazon-braket-pennylane-plugin
qml.device("braket.local.qubit", wires=4) # Free local
qml.device("braket.aws.qubit", wires=4,
device_arn="arn:aws:braket:::device/quantum-simulator/amazon/sv1")Keep exploring
💡
Also available via HLQuantum
Want to run the same circuit on multiple backends without rewriting your code? HLQuantum abstracts this SDK (and 5 others) behind a single unified API.
python
import hlquantum as hlq
qc = hlq.Circuit(2)
qc.h(0).cx(0, 1).measure_all()
# One line to switch between any backend
result = hlq.run(qc, shots=1024) # auto-detect
result = hlq.run(qc, shots=1024, backend="pennylane") # explicit