跳转至

DeepQuantum 技术文档

1. 概述

脚本名称

DeepQuantum - 基于 PyTorch 的量子机器学习和光量子计算软件平台

一句话简介

DeepQuantum 是一个高效的人工智能与量子计算集成框架,支持量子比特电路和光量子电路的构建、模拟与训练,具备大规模分布式计算能力。

核心功能列表

  1. 量子比特电路模拟
  2. 支持状态向量、密度矩阵和矩阵乘积态(MPS)三种表示方法
  3. 提供完整的单比特、双比特和多比特量子门操作
  4. 支持量子测量和期望值计算
  5. 内置数据编码和参数化量子门

  6. 光量子电路模拟

  7. 支持 Fock、Gaussian 和 Bosonic 三种后端
  8. 提供光子数分辨测量和阈值检测
  9. 支持时分复用(TDM)架构
  10. 内置光子损失模拟和噪声模型

  11. 大规模量子计算

  12. 基于张量网络的 MPS 压缩算法
  13. 支持超过 100 量子比特的电路模拟
  14. 多节点、多 GPU 分布式并行计算
  15. 智能内存管理和通信优化

  16. 量子机器学习

  17. 与 PyTorch 深度学习平台无缝集成
  18. 支持自动微分和梯度计算
  19. 提供量子-经典混合模型训练
  20. 内置贝叶斯优化和 SPSA 优化器

  21. 测量基量子计算(MBQC)

  22. 支持图态和子图态构造
  23. 提供量子电路到 MBQC 模式的转换
  24. 实现完整的测量模式执行流程

适用场景

  1. 量子算法研究与开发
  2. 量子机器学习算法设计
  3. 变分量子算法(VQA)实现
  4. 量子神经网络训练

  5. 光量子计算实验

  6. 光子芯片设计和验证
  7. 高斯玻色采样模拟
  8. 连续变量量子计算

  9. 大规模量子系统模拟

  10. 100+ 量子比特电路模拟
  11. 量子纠缠和相干性研究
  12. 量子纠错协议验证

  13. 量子教育与实践

  14. 量子计算概念学习
  15. 量子算法可视化
  16. 实验仿真与验证

2. 环境要求与安装

Python 版本要求

最低版本: Python 3.9+

推荐版本: Python 3.10 - 3.12

版本说明: - Python 3.9: 基础功能支持 - Python 3.10+: 完整功能支持,推荐使用 - Python 3.12: 最新特性支持

依赖库

库名称 版本要求 用途说明
torch ≥ 2.4.0 深度学习框架,提供张量计算、自动微分和 GPU 加速
numpy 最新版 数值计算基础库
matplotlib 最新版 可视化和绘图
qiskit 最新版 量子计算工具,用于 QASM3 转换
scipy 最新版 科学计算,特殊函数和优化
sympy 最新版 符号计算
networkx 最新版 图算法,用于 MBQC
tqdm 最新版 进度条显示
psutil 最新版 系统资源监控

开发依赖(可选): - pytest: 单元测试 - perceval-quandela: 光量子计算参考实现 - strawberryfields: 光量子计算框架 - graphix==0.3.1: MBQC 参考实现

安装步骤

方式一:使用 pip 安装(推荐)

# 1. 创建虚拟环境
conda create -n deepquantum python=3.11
conda activate deepquantum

# 2. 安装 PyTorch(根据您的 CUDA 版本选择)
# CPU 版本
pip install torch

# CUDA 11.8 版本
pip install torch --index-url https://download.pytorch.org/whl/cu118

# CUDA 12.1 版本
pip install torch --index-url https://download.pytorch.org/whl/cu121

# 3. 安装 DeepQuantum
pip install deepquantum

# 使用清华镜像源(推荐国内用户)
pip install deepquantum -i https://pypi.tuna.tsinghua.edu.cn/simple

# 4. 开发者安装(包含测试依赖)
pip install deepquantum[dev]

方式二:从源码安装

# 1. 克隆仓库
git clone https://github.com/TuringQ/deepquantum.git
cd deepquantum

# 2. 创建虚拟环境
conda create -n deepquantum python=3.11
conda activate deepquantum

# 3. 安装 PyTorch(同方式一)

# 4. 安装 DeepQuantum(开发模式)
pip install -e .

# 使用清华镜像源
pip install -e . -i https://pypi.tuna.tsinghua.edu.cn/simple

# 5. 安装开发依赖
pip install -r requirements-dev.txt

验证安装

import deepquantum as dq
import torch

# 打印版本号
print(dq.__version__)  # 应输出: 4.4.0

# 测试基本功能
cir = dq.QubitCircuit(2)
cir.h(0)
cir.cnot(0, 1)
state = cir()
print(f"电路状态形状: {state.shape}")  # 应输出: torch.Size([4])

3. 使用指南

3.1 基本用法

量子比特电路示例

import deepquantum as dq

# 创建 2 量子比特电路
cir = dq.QubitCircuit(nqubit=2, init_state='zeros')

# 添加量子门
cir.h(0)        # 在第 0 个量子比特上添加 Hadamard 门
cir.cnot(0, 1)  # 添加 CNOT 门(控制比特 0,目标比特 1)
cir.rx(1, 0.2)  # 在第 1 个量子比特上添加旋转门

# 添加观测
cir.observable(wires=0, basis='z')  # 观测第 0 个量子比特的 Z 分量

# 执行电路
state = cir()  # 获取最终量子态
print(state)

# 测量
result = cir.measure(shots=1024)
print(f"测量结果: {result}")

# 计算期望值
exp_val = cir.expectation()
print(f"期望值: {exp_val}")

光量子电路示例(Fock 后端)

import deepquantum as dq

# 创建 2 模光量子电路(Fock 后端)
cir = dq.QumodeCircuit(nmode=2, init_state=[1, 1], cutoff=5)

# 添加光量子门
cir.dc([0, 1])           # 离散位移(位移条件态)
cir.ps(0, 0.1)           # 相移门
cir.bs([0, 1], [0.2, 0.3])  # 分束器

# 执行电路
state = cir()
print(f"光量子态形状: {state.shape}")

# 测量
result = cir.measure(shots=1024)
print(f"光子数测量结果: {result}")

使用 MPS 表示的大规模电路

import deepquantum as dq

# 创建 50 量子比特电路,使用 MPS 表示
cir = dq.QubitCircuit(nqubit=50, mps=True, chi=16)

# 添加量子门层
cir.hlayer()       # Hadamard 层
cir.rylayer()      # Ry 旋转层
cir.cnot_ring()    # CNOT 环形连接

# 添加观测
cir.observable(wires=[0, 1, 2], basis='zzz')

# 执行电路
state = cir()
print(f"MPS 张量列表长度: {len(state)}")

# 计算期望值
exp_val = cir.expectation()
print(f"期望值: {exp_val}")

3.2 参数/接口详解

QubitCircuit 类参数

参数名 类型 必填 默认值 说明
nqubit int - 量子比特数量
init_state Any 'zeros' 初始状态,可选:'zeros'(全零)、'equal'(均匀叠加)、'entangle'(GHZ 态)、QubitState 对象、张量
name str/None None 电路名称
den_mat bool False 是否使用密度矩阵表示
reupload bool False 是否启用数据重上传
mps bool False 是否使用矩阵乘积态(MPS)表示
chi int/None None MPS 的键维度(压缩参数),越大越精确但计算成本越高
shots int 1024 测量次数

QumodeCircuit 类参数

参数名 类型 必填 默认值 说明
nmode int - 模式数量(相当于量子比特数)
init_state Any - 初始状态,可选:'vac'(真空态)、Fock 基态 [n1,n2,...]、Fock 态张量、高斯态 [cov,mean]、玻色态列表
cutoff int/None None Fock 空间截断维度(光子数上限)
backend str 'fock' 后端类型:'fock'、'gaussian'、'bosonic'
basis bool True 是否使用 Fock 基态表示(仅 Fock 后端)
den_mat bool False 是否使用密度矩阵表示
detector str 'pnrd' 探测器类型:'pnrd'(光子数分辨)、'threshold'(阈值探测器)
mps bool False 是否使用 MPS 表示
chi int/None None MPS 键维度
noise bool False 是否添加高斯噪声
mu float 0.0 噪声均值
sigma float 0.1 噪声标准差

主要方法说明

量子门操作方法: - h(wire): Hadamard 门 - x(wire), y(wire), z(wire): Pauli 门 - rx(wire, theta), ry(wire, theta), rz(wire, theta): 旋转门 - cnot(control, target): CNOT 门 - swap(wire1, wire2): SWAP 门 - u3(wire, theta, phi, lambda): 通用单比特门

编码方法: - encode(data, encode=True): 编码数据到参数化门 - amplitude_encoding(vec): 幅度编码

测量方法: - observable(wires, basis='z'): 添加可观测量 - measure(shots=1024, with_prob=False): 测量量子态 - expectation(shots=None): 计算期望值(shots=None 为精确计算)

工具方法: - get_unitary(): 获取电路的酉矩阵 - get_amplitude(bits): 获取特定比特串的概率幅 - get_prob(bits): 获取特定比特串的概率 - to(device): 移动电路到指定设备(CPU/GPU)

3.3 使用示例

示例 1:变分量子分类器

import torch
import deepquantum as dq

# 定义参数化量子电路
class QuantumClassifier(torch.nn.Module):
    def __init__(self, n_qubits, n_classes):
        super().__init__()
        self.circuit = dq.QubitCircuit(nqubit=n_qubits)

        # 数据编码层
        for i in range(n_qubits):
            self.circuit.ry(i, encode=True)

        # 变分层
        for i in range(n_qubits):
            self.circuit.rx(i, encode=True)
        self.circuit.cnot_ring()
        for i in range(n_qubits):
            self.circuit.ry(i, encode=True)

        # 观测层
        for i in range(n_classes):
            self.circuit.observable(wires=i, basis='z')

    def forward(self, x):
        return self.circuit(x).expectation()

# 创建模型
model = QuantumClassifier(n_qubits=4, n_classes=2)

# 模拟数据
data = torch.randn(10, 4)  # 10 个样本,4 个特征

# 前向传播
output = model(data)
print(f"分类输出形状: {output.shape}")  # torch.Size([10, 2])

示例 2:高斯玻色采样

import deepquantum as dq
import torch

# 创建高斯玻色采样电路
nmode = 4
squeezing_param = 1.0

# 初始化挤压态
init_state = []
for i in range(nmode):
    init_state.append({'s': squeezing_param, 'r': 0.0})

cir = dq.QumodeCircuit(
    nmode=nmode,
    init_state='vac',
    backend='gaussian',
    cutoff=5
)

# 添加挤压门
for i in range(nmode):
    cir.s(i, squeezing_param)

# 添加线性光学网络(随机酉矩阵)
cir.random_ua()

# 测量
result = cir.measure(shots=10000)
print(f"采样结果(前 10 个): {result[:10]}")

# 计算光子数分布
photon_nums = [sum(r) for r in result]
from collections import Counter
distribution = Counter(photon_nums)
print(f"光子数分布: {dict(distribution)}")

示例 3:分布式量子电路模拟

import torch
import deepquantum as dq

# 设置分布式环境(使用 4 个进程)
# 命令行运行:torchrun --nproc_per_node=4 your_script.py
backend = 'nccl'  # GPU 使用 'nccl',CPU 使用 'gloo'
rank, world_size, local_rank = dq.setup_distributed(backend)

# 根据后端选择设备
if backend == 'nccl':
    device = f'cuda:{local_rank}'
else:
    device = 'cpu'

# 创建分布式量子电路
nqubits = 100
cir = dq.DistributedQubitCircuit(nqubits)

# 添加量子门
cir.rylayer(encode=True)
cir.cnot_ring()
cir.observable(wires=[0, 1, 2], basis='zzz')

# 移动到 GPU
if backend == 'nccl':
    cir.to(device)

# 准备数据
data = torch.arange(nqubits, dtype=torch.float32, device=device)

# 执行电路
state = cir(data).amps
result = cir.measure(shots=1024)
exp_val = cir.expectation()

# 仅在主进程打印结果
if rank == 0:
    print(f"分布式计算完成!")
    print(f"状态形状: {state.shape}")
    print(f"期望值: {exp_val}")

# 清理分布式环境
dq.cleanup_distributed()

示例 4:量子电路到 MBQC 模式转换

import deepquantum as dq

# 创建标准量子电路
cir = dq.QubitCircuit(3)
cir.h(0)
cir.cnot(0, 1)
cir.cnot(1, 2)
cir.rz(2, 0.5)

# 转换为 MBQC 模式
pattern = cir.pattern()

# 执行原始电路
state_circuit = cir()

# 执行 MBQC 模式
state_pattern = pattern()

# 验证结果一致性
ratio = state_circuit / state_pattern.full_state
print(f"状态比例(应全为 1): {ratio.abs()}")

# 手动构建 MBQC 模式
pattern2 = dq.Pattern(3)
pattern2.n(3)
pattern2.e(0, 1)
pattern2.e(1, 2)
pattern2.m(0)
pattern2.x(1, domain=0)
pattern2.m(1)
pattern2.x(2, domain=1)
state_pattern2 = pattern2()
print(f"自定义模式状态: {state_pattern2.full_state}")

4. 核心逻辑与架构

4.1 工作流程

量子比特电路执行流程

1. 初始化阶段
   ├── 创建 QubitCircuit 对象
   ├── 设置量子比特数量和初始状态
   ├── 选择状态表示方法(向量/密度矩阵/MPS)
   └── 初始化操作序列和观测器

2. 电路构建阶段
   ├── 添加量子门操作(调用 h(), cnot() 等方法)
   ├── 添加编码层(可选,用于数据编码)
   ├── 添加可观测量
   └── 记录电路深度和参数数量

3. 前向传播阶段
   ├── 从初始状态开始
   ├── 按顺序应用所有量子门操作
   │   ├── 对于状态向量:直接矩阵-向量乘法
   │   ├── 对于密度矩阵:矩阵-矩阵乘法
   │   └── 对于 MPS:张量网络缩并和 SVD 压缩
   ├── 应用编码层(如果提供数据)
   └── 返回最终量子态

4. 测量和计算阶段
   ├── 执行测量(sample_sc_mcmc 或直接采样)
   ├── 计算期望值(精确或采样)
   └── 返回测量结果或期望值

光量子电路执行流程

1. 初始化阶段
   ├── 创建 QumodeCircuit 对象
   ├── 选择后端(Fock/Gaussian/Bosonic)
   ├── 设置初始状态和截断维度
   └── 初始化操作序列和测量器

2. 电路构建阶段
   ├── 添加光量子门(分束器、相移器、挤压器等)
   ├── 添加延迟操作(TDM 模式)
   ├── 添加损失通道
   └── 添加测量操作

3. 前向传播阶段
   ├── Fock 后端:
   │   ├── Fock 基态:直接张量操作
   │   └── Fock 态张量:MPS 表示和压缩
   ├── Gaussian 后端:
   │   ├── 协方差矩阵和位移向量变换
   │   └── 辛变换应用
   └── Bosonic 后端:
       ├── 高斯态线性组合
       └── 光子损失模拟

4. 测量阶段
   ├── 光子数测量(Fock)或同位测量(Gaussian/Bosonic)
   ├── 采样(MCMC 或拒绝采样)
   └── 返回测量结果

4.2 关键函数/类说明

1. QubitCircuit 类(circuit.py)

作用: 量子比特电路的核心实现类,提供电路构建、执行和测量的完整功能。

输入: - nqubit: 量子比特数量 - init_state: 初始状态(字符串或状态对象) - den_mat: 是否使用密度矩阵 - mps: 是否使用 MPS 表示 - chi: MPS 键维度

输出: - 量子态(张量或张量列表) - 测量结果(字典) - 期望值(张量)

核心方法:

def forward(self, data=None, state=None):
    """执行电路前向传播

    工作流程:
    1. 检查输入数据和状态
    2. 对于批数据:使用 vmap 并行化
    3. 对于 MPS:逐个应用门并进行 SVD 压缩
    4. 应用编码层(如果有)
    5. 返回最终状态
    """

def _forward_helper(self, data=None, state=None):
    """前向传播的核心逻辑

    对于每个操作:
    - Gate: 调用门操作
    - Layer: 调用层操作
    - Channel: 应用量子通道
    - 编码器: 编码数据到参数
    """

设计重要性: - 提供统一的接口,屏蔽底层状态表示的差异 - 支持批处理和并行化,提高计算效率 - 灵活的数据编码机制,支持量子机器学习

2. MatrixProductState 类(state.py)

作用: 实现矩阵乘积态(MPS)表示,用于大规模量子系统的压缩存储和高效计算。

输入: - nsite: 量子比特数量 - state: 初始状态 - chi: 键维度(控制压缩程度) - qudit: 每个位置的维度(默认 2)

输出: - MPS 张量列表 - 奇异值列表

核心功能:

def compress(self, chi):
    """压缩 MPS

    算法:
    1. 从左到右进行 QR 分解
    2. 从右到左进行 SVD 分解
    3. 截断奇异值到 chi
    4. 返回压缩后的张量列表
    """

def canonicalize(self, center, normalize=True):
    """中心正交化

    将 MPS 转换为中心正则形式:
    1. 从中心向左进行正交化
    2. 从中心向右进行正交化
    3. 归一化中心张量
    """

设计重要性: - 突破内存限制,支持 100+ 量子比特模拟 - 通过 SVD 压缩保持关键量子纠缠信息 - 为分布式计算提供基础

3. QumodeCircuit 类(photonic/circuit.py)

作用: 光量子电路的核心实现,支持三种后端和时分复用架构。

输入: - nmode: 模式数量 - init_state: 初始状态(因后端而异) - backend: 后端类型 - cutoff: Fock 空间截断

输出: - 光量子态(张量或字典) - 测量结果

核心功能:

def set_init_state(self, init_state):
    """设置初始状态

    根据 backend 选择状态类型:
    - 'fock': FockState(基态或张量)
    - 'gaussian': GaussianState(协方差矩阵 + 位移向量)
    - 'bosonic': BosonicState(高斯态线性组合)
    """

def forward(self, data=None, state=None):
    """执行光量子电路

    对于不同后端:
    - Fock: 张量操作或 MPS 缩并
    - Gaussian: 辛变换
    - Bosonic: 高斯态叠加和损失模拟
    """

设计重要性: - 统一的接口支持多种光量子计算模型 - 时分复用支持,减少硬件资源需求 - 完整的噪声和损失模拟

4. Gate 类层次结构(gate.py)

作用: 实现各种量子门操作,提供统一的门操作接口。

继承层次:

Gate (基类)
├── SingleGate (单比特门基类)
│   ├── U3Gate, PauliX/Y/Z, Hadamard 等
│   └── ParametricSingleGate
│       └── Rx, Ry, Rz 等
├── DoubleGate (双比特门基类)
│   ├── CNOT, Swap
│   └── Rxx, Ryy, Rzz 等
└── TripleGate (三比特门)
    └── Toffoli, Fredkin

核心方法:

def get_unitary(self):
    """获取全局酉矩阵

    算法:
    1. 计算门的本地矩阵
    2. 与单位矩阵张积,扩展到全局空间
    3. 如果有控制比特,添加控制逻辑
    4. 返回全局酉矩阵
    """

def op_dist_state(self, x):
    """分布式状态上的门操作

    对于分布式 MPS:
    1. 确定目标张量的位置
    2. 进程间通信交换必要数据
    3. 应用门操作
    4. 返回更新后的状态
    """

设计重要性: - 模块化设计,易于扩展新门 - 统一的接口,支持多种状态表示 - 内置分布式支持


5. 扩展与定制

5.1 可扩展点

1. 自定义量子门

位置: gate.py

扩展方式: 继承 SingleGateDoubleGateArbitraryGate

示例:

import torch
from deepquantum.gate import SingleGate
from deepquantum.qmath import multi_kron

class CustomRotationGate(SingleGate):
    """自定义旋转门 R(θ) = exp(-iθ/2 * (nx*X + ny*Y + nz*Z))"""

    def __init__(self, wires, nqubit, theta, nx=0, ny=0, nz=1):
        super().__init__(name='CustomR', nqubit=nqubit, wires=[wires])
        self.theta = theta
        self.nx = nx
        self.ny = ny
        self.nz = nz

    def update_matrix(self):
        """计算旋转矩阵"""
        # 实现自定义旋转矩阵
        half_theta = self.theta / 2
        cos_t = torch.cos(half_theta)
        sin_t = torch.sin(half_theta)

        # 泡利矩阵的线性组合
        matrix = torch.eye(2, dtype=torch.complex128)
        # 添加你的矩阵计算逻辑
        return matrix

# 使用自定义门
cir = dq.QubitCircuit(2)
custom_gate = CustomRotationGate(wires=0, nqubit=2, theta=0.5)
cir.operators.append(custom_gate)

2. 新的状态表示方法

位置: state.py

扩展方式: 创建新的状态类,实现必要的方法

示例:

import torch
from deepquantum.state import QubitState

class TreeState(QubitState):
    """树状张量网络状态表示"""

    def __init__(self, nqubit, state='zeros', tree_degree=3):
        super().__init__(nqubit, state)
        self.tree_degree = tree_degree
        self.tree_structure = self._build_tree()

    def _build_tree(self):
        """构建树状结构"""
        # 实现树状张量网络结构
        tree = {}
        # 添加你的树构建逻辑
        return tree

    def apply_gate(self, gate, wires):
        """在树上应用量子门"""
        # 实现树状网络上的门操作
        pass

    def compress(self, max_bond_dim):
        """压缩树状网络"""
        # 实现压缩算法
        pass

# 使用自定义状态
tree_state = TreeState(nqubit=8, state='zeros', tree_degree=3)

3. 新的优化器

位置: optimizer.py

扩展方式: 继承 Optimizer 基类

示例:

import torch
from deepquantum.optimizer import Optimizer

class CustomOptimizer(Optimizer):
    """自定义优化器,例如遗传算法"""

    def __init__(self, target_func, param_init, random_state=0,
                 population_size=50, mutation_rate=0.1):
        super().__init__(target_func, param_init, random_state)
        self.population_size = population_size
        self.mutation_rate = mutation_rate

    def optimize(self, n_iter=100):
        """遗传算法优化"""
        # 初始化种群
        population = self._init_population()

        for i in range(n_iter):
            # 计算适应度
            fitness = [self.target_func(ind) for ind in population]

            # 选择
            selected = self._selection(population, fitness)

            # 交叉
            offspring = self._crossover(selected)

            # 变异
            population = self._mutate(offspring)

            # 更新最佳参数
            best_idx = torch.argmax(torch.tensor(fitness))
            self.best_params = population[best_idx]

        return self.best_params

    def _init_population(self):
        """初始化种群"""
        pass

    def _selection(self, population, fitness):
        """选择操作"""
        pass

    def _crossover(self, selected):
        """交叉操作"""
        pass

    def _mutate(self, offspring):
        """变异操作"""
        pass

# 使用自定义优化器
def objective(params):
    cir = dq.QubitCircuit(2)
    cir.ry(0, params[0])
    cir.rx(1, params[1])
    cir.cnot(0, 1)
    return -cir.expectation()  # 最小化负期望值

optimizer = CustomOptimizer(objective, param_init=[0.0, 0.0])
best_params = optimizer.optimize(n_iter=100)

4. 新的后端支持

位置: photonic/

扩展方式: 创建新的状态类和门类

示例: 添加 "stabilizer" 后端

# 1. 创建 StabilizerState 类
from deepquantum.photonic.state import FockState

class StabilizerState(FockState):
    """稳定子态表示"""

    def __init__(self, nmode, state='zeros'):
        super().__init__(nmode=nmode, state=state, basis=True)
        self.stabilizers = self._init_stabilizers()

    def _init_stabilizers(self):
        """初始化稳定子生成元"""
        # 实现稳定子初始化
        pass

    def apply_clifford(self, gate):
        """应用 Clifford 门"""
        # 实现稳定子更新规则
        pass

# 2. 创建对应的门类
from deepquantum.photonic.gate import PhaseShift

class StabilizerGate(PhaseShift):
    """稳定子后端的门"""

    def forward(self, state):
        """在稳定子态上应用门"""
        if isinstance(state, StabilizerState):
            state.apply_clifford(self)
        return state

# 3. 在 QumodeCircuit 中注册后端
from deepquantum.photonic.circuit import QumodeCircuit

# 修改 set_init_state 方法
def set_init_state(self, init_state):
    if isinstance(init_state, StabilizerState):
        self.backend = 'stabilizer'
        self.init_state = init_state
    # ... 其他后端逻辑

5. 自定义测量策略

位置: qmath.pyphotonic/qmath.py

扩展方式: 创建新的采样或测量函数

示例:

import torch
from deepquantum.qmath import measure

def adaptive_measure(state, nqubit, shots=1024, threshold=0.01):
    """自适应测量:优先测量高概率态"""

    # 获取所有概率
    probs = state.abs() ** 2

    # 筛选高概率态
    significant_indices = torch.where(probs > threshold)[0]

    if len(significant_indices) == 0:
        # 如果没有显著态,使用标准测量
        return measure(state, nqubit, shots)

    # 归一化概率
    significant_probs = probs[significant_indices]
    significant_probs /= significant_probs.sum()

    # 从显著态中采样
    samples = torch.multinomial(significant_probs, shots, replacement=True)

    # 转换为比特串
    results = []
    for idx in samples:
        bit_idx = significant_indices[idx]
        bits = [(bit_idx >> i) & 1 for i in range(nqubit)]
        results.append(bits)

    return results

# 使用自定义测量
cir = dq.QubitCircuit(4)
cir.h(0)
cir.cnot(0, 1)
cir.rylayer()

# 替换标准测量
result = adaptive_measure(cir().state, cir.nqubit, shots=1000)

5.2 插件化设计

DeepQuantum 支持插件式扩展,通过以下方式集成新功能:

1. 创建插件模块

# my_plugin/__init__.py
from .gates import CustomGate
from .optimizers import CustomOptimizer

__all__ = ['CustomGate', 'CustomOptimizer']

2. 注册插件

# 在主程序中导入
import deepquantum as dq
import my_plugin

# 使用插件功能
cir = dq.QubitCircuit(2)
cir.operators.append(my_plugin.CustomGate(...))

3. 子类化电路

from deepquantum import QubitCircuit

class MyCustomCircuit(QubitCircuit):
    """自定义电路,添加特定功能"""

    def __init__(self, nqubit, **kwargs):
        super().__init__(nqubit, **kwargs)
        self.custom_layers = []

    def custom_layer(self, params):
        """添加自定义层"""
        # 实现你的自定义层逻辑
        self.custom_layers.append(params)
        return self

    def custom_operation(self):
        """自定义操作"""
        # 实现特殊的量子操作
        pass

# 使用自定义电路
cir = MyCustomCircuit(3)
cir.h(0)
cir.custom_layer(params=[0.1, 0.2, 0.3])
cir.custom_operation()

6. 常见问题与故障排除

6.1 常见问题

问题 1: 导入错误 - ModuleNotFoundError: No module named 'deepquantum'

症状:

>>> import deepquantum as dq
ModuleNotFoundError: No module named 'deepquantum'

可能原因: 1. DeepQuantum 未正确安装 2. 安装在了错误的虚拟环境中 3. Python 路径配置问题

解决方法:

# 1. 检查当前环境
which python
python --version

# 2. 重新安装 DeepQuantum
pip install deepquantum --force-reinstall

# 3. 如果从源码安装
cd deepquantum
pip install -e .

# 4. 验证安装
python -c "import deepquantum; print(deepquantum.__version__)"

问题 2: CUDA 版本不兼容

症状:

>>> cir.to('cuda:0')
RuntimeError: CUDA error: no kernel image is available for execution on the device

可能原因: 1. PyTorch CUDA 版本与系统 CUDA 版本不匹配 2. GPU 驱动版本过旧

解决方法:

# 1. 检查系统 CUDA 版本
nvcc --version
nvidia-smi

# 2. 检查 PyTorch CUDA 版本
python -c "import torch; print(torch.version.cuda)"

# 3. 重新安装匹配的 PyTorch 版本
# CUDA 11.8
pip install torch --upgrade --index-url https://download.pytorch.org/whl/cu118

# CUDA 12.1
pip install torch --upgrade --index-url https://download.pytorch.org/whl/cu121

# CPU 版本
pip install torch --upgrade --index-url https://download.pytorch.org/whl/cpu

问题 3: 内存不足 - CUDA out of memory

症状:

>>> cir = dq.QubitCircuit(50, mps=True)
>>> state = cir()
RuntimeError: CUDA out of memory. Tried to allocate 2.5 GiB

可能原因: 1. 量子比特数量过多 2. MPS 键维度 chi 过大 3. 批处理大小过大 4. GPU 内存不足

解决方法:

# 方法 1: 降低 MPS 键维度
cir = dq.QubitCircuit(nqubit=50, mps=True, chi=8)  # 从默认值降低

# 方法 2: 使用梯度检查点
import torch
from torch.utils.checkpoint import checkpoint

def forward_with_checkpoint(circuit, data):
    return checkpoint(circuit.forward, data)

# 方法 3: 减小批大小
data = torch.randn(100, 50)  # 大批量
# 改为小批量
for i in range(0, 100, 10):
    batch = data[i:i+10]
    output = circuit(batch)

# 方法 4: 混合精度训练
from torch.cuda.amp import autocast

with autocast():
    output = circuit(data)

# 方法 5: 使用 CPU 或分布式计算
cir.to('cpu')  # 移动到 CPU
# 或使用分布式
cir = dq.DistributedQubitCircuit(50)

问题 4: 收敛问题 - 量子电路训练不收敛

症状:

# 损失函数不下降或振荡
Loss: 0.500, 0.512, 0.498, 0.525, 0.490, ...

可能原因: 1. 梯度消失或爆炸(贫瘠高原现象) 2. 学习率过大或过小 3. 量子电路深度不足或过深 4. 初始化参数不合适

解决方法:

# 方法 1: 使用参数初始化策略
import torch.nn as nn

def init_quantum_params(circuit):
    for name, param in circuit.named_parameters():
        if 'weight' in name:
            nn.init.xavier_uniform_(param)
        elif 'bias' in name:
            nn.init.zeros_(param)

# 方法 2: 调整学习率
optimizer = torch.optim.Adam(circuit.parameters(), lr=0.001)  # 降低学习率

# 方法 3: 使用学习率调度器
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
    optimizer, mode='min', factor=0.5, patience=10
)

# 方法 4: 梯度裁剪
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(circuit.parameters(), max_norm=1.0)
optimizer.step()

# 方法 5: 使用参数化层结构
cir = dq.QubitCircuit(10)
# 使用浅层但重复的结构
for _ in range(3):
    cir.rylayer()
    cir.cnot_ring()
    cir.rzlayer()

# 方法 6: 添加噪声以提高鲁棒性
from deepquantum.channel import Depolarizing

cir = dq.QubitCircuit(10, den_mat=True)
# 添加量子通道
for i in range(10):
    cir.operators.append(Depolarizing(nqubit=10, wires=[i], p=0.01))

问题 5: MPS 压缩误差

症状:

# 使用 MPS 的结果与精确解差异较大
cir_exact = dq.QubitCircuit(20)
cir_mps = dq.QubitCircuit(20, mps=True, chi=4)
# 状态差异 > 0.1

可能原因: 1. MPS 键维度 chi 过小 2. 电路纠缠度过高 3. 压缩策略不当

解决方法:

# 方法 1: 增大键维度
cir = dq.QubitCircuit(nqubit=20, mps=True, chi=16)  # 从 4 增加到 16

# 方法 2: 自适应键维度
class AdaptiveMPS(QubitCircuit):
    def forward(self, data=None, state=None):
        # 根据纠缠熵自适应调整 chi
        result = super().forward(data, state)
        # 监控奇异值分布
        if self.mps:
            entanglement = self._compute_entanglement()
            if entanglement.max() > 0.9:  # 高纠缠阈值
                self.chi = min(self.chi * 2, 64)  # 增大 chi
        return result

# 方法 3: 使用两步压缩
def forward_two_step(circuit, data):
    # 第一步:使用大 chi 保证精度
    circuit.chi = 32
    state = circuit(data)

    # 第二步:压缩到合理大小
    circuit.chi = 16
    state.compress(circuit.chi)

    return state

# 方法 4: 分区计算(针对局部纠缠)
# 将电路分成若干子区域,分别使用 MPS

问题 6: 光子数截断误差

症状:

# Fock 后端计算结果不准确
cir = dq.QumodeCircuit(2, [1, 1], cutoff=3)
# 概率和不等于 1

可能原因: 1. cutoff 设置过小 2. 挤压参数过大导致高光子数态 3. 分束器参数产生高阶模

解决方法:

# 方法 1: 估计所需 cutoff
import math

def estimate_cutoff(squeezing_params):
    """根据挤压参数估计 cutoff"""
    # 平均光子数 = sinh²(r)
    mean_photon = sum([math.sinh(p)**2 for p in squeezing_params])
    # cutoff ≈ 3 × 平均光子数 + 5
    return int(3 * mean_photon + 5)

# 使用估计的 cutoff
r = 1.5
cutoff = estimate_cutoff([r, r])
cir = dq.QumodeCircuit(2, 'vac', cutoff=cutoff)
cir.s(0, r)
cir.s(1, r)

# 方法 2: 动态检测
def check_cutoff_convergence(circuit, data=None):
    """检测 cutoff 是否足够"""
    # 逐步增加 cutoff,直到结果收敛
    old_result = None
    for cutoff in range(5, 30, 5):
        circuit.cutoff = cutoff
        result = circuit(data)
        if old_result is not None:
            diff = (result - old_result).abs().max()
            if diff < 1e-6:  # 收敛阈值
                print(f"收敛于 cutoff = {cutoff}")
                return result, cutoff
        old_result = result
    return result, cutoff

# 方法 3: 使用 Gaussian 后端(避免截断)
cir_gaussian = dq.QumodeCircuit(2, 'vac', backend='gaussian')
# Gaussian 后端无截断误差

6.2 调试技巧

1. 启用详细日志

import logging

# 设置日志级别
logging.basicConfig(level=logging.DEBUG)

# 或只显示 DeepQuantum 的日志
logger = logging.getLogger('deepquantum')
logger.setLevel(logging.DEBUG)

2. 检查中间状态

cir = dq.QubitCircuit(3)

# 添加门
cir.h(0)
state_after_h = cir()  # 检查中间状态
print(f"Hadamard 后的状态: {state_after_h}")

cir.cnot(0, 1)
state_after_cnot = cir()
print(f"CNOT 后的状态: {state_after_cnot}")

# 检查酉矩阵
unitary = cir.get_unitary()
print(f"电路酉矩阵:\n{unitary}")

3. 验证量子门

# 检查门的酉性
from deepquantum.qmath import is_unitary

gate = dq.Rx(wires=0, nqubit=2, theta=0.5)
matrix = gate.get_unitary()
print(f"是否为酉矩阵: {is_unitary(matrix)}")

# 检查门的性质
import torch
assert torch.allclose(matrix @ matrix.T.conj(), torch.eye(4))

4. 性能分析

import time
import torch.profiler as profiler

cir = dq.QubitCircuit(20, mps=True)
cir.rylayer()
cir.cnot_ring()

# 方法 1: 简单计时
start = time.time()
state = cir()
end = time.time()
print(f"执行时间: {end - start:.4f} 秒")

# 方法 2: 使用 profiler
with profiler.profile(
    activities=[profiler.ProfilerActivity.CPU, profiler.ProfilerActivity.CUDA],
    record_shapes=True
) as prof:
    state = cir()

print(prof.key_averages().table(sort_by="cuda_time_total"))

附录

A. 速查表

量子门速查

描述 方法
Hadamard 叠加态 cir.h(wire)
Pauli-X 比特翻转 cir.x(wire)
Pauli-Y Y 翻转 cir.y(wire)
Pauli-Z 相位翻转 cir.z(wire)
CNOT 控制非 cir.cnot(control, target)
Rx X 旋转 cir.rx(wire, theta)
Ry Y 旋转 cir.ry(wire, theta)
Rz Z 旋转 cir.rz(wire, theta)
SWAP 交换 cir.swap(wire1, wire2)

光量子门速查

描述 方法
PhaseShift 相移 cir.ps(wire, theta)
BeamSplitter 分束器 cir.bs(wires, [theta, phi])
Squeezing 挤压 cir.s(wire, r)
Displacement 位移 cir.d(wire, alpha)

B. 参考资源

  • 官方文档: https://dqapi.turingq.com/
  • GitHub 仓库: https://github.com/TuringQ/deepquantum
  • 论文: https://arxiv.org/abs/2512.18995
  • PyTorch 文档: https://pytorch.org/docs/

C. 联系方式

  • Email: Algorithms-Applications@turingq.com
  • Issues: https://github.com/TuringQ/deepquantum/issues

文档版本: 1.0 最后更新: 2025-01-08 适用于 DeepQuantum 版本: 4.4.0+