News

日本語 · English · 中文

【投稿】使用PyTorch和NetworkX构建量子计算模拟器及VQE入门

本文介绍了一种使用 PyTorch 的 einsum 进行量子态张量计算、并使用 NetworkX 可视化电路拓扑的实现方法。后半部分展示了如何利用 PyTorch 的自动微分和优化器实现变分量子本征求解器(VQE)的学习过程。

1. 引言

在量子计算机算法开发中,将电路视为张量进行处理的方法备受关注。本文将介绍一种实现方法:使用 PyTorch 的 einsum(爱因斯坦求和约定) 计算量子态,并利用 NetworkX 可视化电路拓扑结构。后半部分将展示如何应用此方法实现量子-经典混合算法 VQE(变分量子本征求解器) 的训练过程。

2. 核心技术:为何选择 PyTorch?

  • 基于张量的状态表示:将量子比特作为多维数组处理,可实现 GPU 高速计算。
  • einsum 的灵活性:通过 torch.einsum,可以用直观的索引指定来描述复杂的门操作。
  • 自动微分 (Autograd):若将门的参数定义为可训练变量,即可像 AI 学习一样优化量子电路。

3. 基础篇:量子纠缠电路与 NetworkX 可视化

首先实现生成“贝尔态(量子纠缠)”的电路。这里不仅进行计算,还使用图论库 NetworkX 绘制电路的结构图。

import torch
import networkx as nx
import matplotlib.pyplot as plt

# 1. 准备:定义量子门 (PyTorch Tensor)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# H门(哈达玛门)
H_gate = torch.tensor([[1, 1], [1, -1]], dtype=torch.complex64, device=device) / (2**0.5)

# CX门(受控非门): 4阶张量 [out_target, out_control, in_target, in_control]
CX_gate = torch.zeros((2, 2, 2, 2), dtype=torch.complex64, device=device)
CX_gate[0, 0, 0, 0] = 1
CX_gate[1, 0, 1, 0] = 1
CX_gate[1, 1, 0, 1] = 1 # 当控制位为(1)时,0 -> 1
CX_gate[0, 1, 1, 1] = 1 # 当控制位为(1)时,1 -> 0

# 2. 创建初始状态 (2量子比特 |00>)
state = torch.zeros((2, 2), dtype=torch.complex64, device=device)
state[0, 0] = 1.0

# 3. 执行量子计算 (torch.einsum)
# 步骤1: 对 Q0 应用 H门 ('ki, ij -> kj' : 将 i 转换为 k)
state = torch.einsum('ki, ij -> kj', H_gate, state)
# 步骤2: 应用 CX门 ('lmij, ij -> lm' : 将输入 ij 转换为输出 lm)
state = torch.einsum('lmij, ij -> lm', CX_gate, state)

# 4. 采样(测量)
probs = torch.abs(state)**2
probs_flat = probs.flatten()
samples = torch.multinomial(probs_flat, num_samples=1024, replacement=True)
counts = torch.bincount(samples, minlength=4)

print("--- 测量结果 (00, 01, 10, 11) ---")
print(counts)

# 5. 使用 NetworkX 绘制电路拓扑
def draw_circuit():
    G = nx.DiGraph()
    nodes = {
        "Q0_in": (0, 1), "Q1_in": (0, 0),
        "H": (1, 1), "CX": (2, 0.5),
        "Q0_out": (3, 1), "Q1_out": (3, 0)
    }
    G.add_nodes_from(nodes.keys())
    edges = [("Q0_in", "H"), ("H", "CX"), ("CX", "Q0_out"), ("Q1_in", "CX"), ("CX", "Q1_out")]
    G.add_edges_from(edges)
    plt.figure(figsize=(8, 4))
    nx.draw(G, pos=nodes, with_labels=True, node_color='plum', node_size=2500, font_weight='bold', arrows=True)
    plt.title("Quantum Circuit Topology via NetworkX")
    plt.show()

draw_circuit()

--- 测量结果 (00, 01, 10, 11) ---
tensor([512, 0, 512, 0])


4. 应用篇:基于 PyTorch 的 VQE 参数学习

接下来,在此仿真平台上实现 VQE,通过学习使电路角度“最小化能量”。PyTorch 的 Optimizer 将寻找量子电路的最佳参数。

import torch.optim as optim

# 1. 定义可微分的 RY 门
def get_RY(theta):
    t = theta.squeeze()
    gate = torch.stack([
        torch.stack([torch.cos(t/2), -torch.sin(t/2)]),
        torch.stack([torch.sin(t/2), torch.cos(t/2)])
    ])
    return gate.to(torch.complex64)

# 2. 目标哈密顿量 (示例: Z 门)
H = torch.tensor([[1.0, 0.0], [0.0, -1.0]], dtype=torch.complex64)

# 3. 参数学习设置
theta = torch.tensor([0.1], requires_grad=True)
optimizer = optim.Adam([theta], lr=0.1)

print("\n--- 开始 VQE 学习 ---")
for step in range(101):
    optimizer.zero_grad()
    
    # 从 |0> 状态开始
    state_in = torch.tensor([1.0, 0.0], dtype=torch.complex64)
    
    # 应用门并计算期望值
    RY = get_RY(theta)
    state_out = RY @ state_in
    energy = torch.real(torch.vdot(state_out, H @ state_out))
    
    # 反向传播
    energy.backward()
    optimizer.step()
    
    if step % 20 == 0:
        print(f"Step {step:3}: Energy = {energy.item():.4f}, Theta = {theta.item():.4f}")

print(f"优化完成: Theta = {theta.item():.4f} (目标值: 3.1416)")

--- VQE 学习开始 ---
Step 0: Energy = 0.9950, Theta = 0.2000
Step 20: Energy = -0.5598, Theta = 2.2736
Step 40: Energy = -0.9378, Theta = 3.4935
Step 60: Energy = -0.9972, Theta = 3.0556
Step 80: Energy = -0.9999, Theta = 3.1590
Step 100: Energy = -1.0000, Theta = 3.1375
优化完成: Theta = 3.1375 (目标值: 3.1416)


5. 总结

通过使用 PyTorch,可以将量子电路的计算解释为数值运算,从而利用强大的优化引擎。此外,结合 NetworkX 可以直观地管理日益复杂的量子比特间连线。

这种方法对于理解小规模量子电路的行为以及开发生子机器学习原型非常有效。

本文译自日文原文。 日本語で読む

← 最新文章