Repository navigation
Add compiled single-GPU execution with cuQuantum and ixquantum - #179
Shaobo-Zhou wants to merge 9 commits into
Conversation
Introduce QubitCircuitGPU with optional first-use native compilation, automatic vendor gate dispatch, terminal readout, and adjoint gradients. Preserve DeepQuantum wire semantics, shared parameters, and fixed gate inverses, with exception-safe resource ownership and explicit limitations. Document CoreX and ixquantum dependencies, provide a CPU compatibility workflow, and validate numerical behavior against DeepQuantum on Iluvatar hardware. Keep the scope to single-GPU execution.
sansiro77
left a comment
There was a problem hiding this comment.
- 把“共享存储”误当成“同一个可训练参数”,会错误合并梯度。例如:
initial = torch.tensor(0.37)
rx = dq.Rx(inputs=initial, requires_grad=True)
ry = dq.Ry(inputs=initial, requires_grad=True)| 检查项 | 原有 DeepQuantum | 本 PR |
|---|---|---|
| 参数数量 | 2 | 被合并成 1 |
| Rx 参数梯度 | −0.337144 | −0.674288 |
| Ry 参数梯度 | −0.337144 | 没有梯度 |
- 参数解冻后,编译缓存没有失效。先 requires_grad_(False) 并执行线路,参数会被编译成常量,随后 requires_grad_(True) 再修改参数,会沿用旧的固定值
- GPU 测试需要区分“有 CUDA”和“装了可选后端”。现在 test_circuit_gpu.py 只根据 torch.cuda.is_available() 决定是否跳过。因此普通 NVIDIA 开发环境即使没有安装 cuQuantum,执行完整 pytest 也会进入这些测试,随后因缺 SDK 失败
- 建议文档从 ixquantum.md 改成 gpu_simulation.md,实现目录从 backends/gpu/ 收成一层 custatevec/
- 现在的 Markdown 对已经配好 GPU 开发环境的人够用,对从空环境开始的用户还不够。建议两个 GPU 后端各给一套从全新 conda 环境到跑通 GHZ 示例的步骤
- Matplotlib本来就会带入'packaging',应该不用额外写
- test-gpu-backend.yml 实际检查的是无 GPU、无厂商 SDK 时,打出来的 wheel 能否安装和使用,建议改名 test-cpu-compatibility.yml
- C++/CUDA 格式建议用固定版本的 clang-format 接入现有 pre-commit,并加到dev依赖里。用 20.1.8 检查,_gpu_executor.cpp 有 5 处格式不通过
sansiro77
left a comment
There was a problem hiding this comment.
-
调用
init_para()后,线路仍用旧参数计算,梯度也写回旧参数。import deepquantum as dq import torch c = dq.QubitCircuit(1) # 对比时换成 dq.QubitCircuitGPU(1) ry = dq.Ry(inputs=0.37, requires_grad=True) c.add(ry) c.observable(0, 'z') old = ry.theta c() # 第一次用 0.37 执行 c.init_para() # 创建新参数,不是在 old 上改值 new = ry.theta with torch.no_grad(): new.fill_(0.90) c() # 两种实现都重新执行 z = c.expectation().sum() z.backward()
原因是缓存只检查旧参数的
requires_grad有没有变,不检查门里的参数是不是换了对象。init_para()换了参数,CompiledCircuitPlan也应该更新。 -
通过
inputs传入的参数,先冻结再解冻,仍然不能求导。theta = torch.tensor(0.37) c.ry(0, inputs=theta) c.observable(0, 'z') c() # 此时 theta 不求导,被编译成常量 theta.requires_grad_(True) c() c.expectation().requires_grad # 原有 DeepQuantum 是 True,本 PR 是 False
这次
theta没换对象,变的是requires_grad。但通过inputs传入的张量在门里注册为buffer,不在c.parameters()里,所以缓存检查漏掉了它。应该检查门实际使用的theta。 -
把
psi.conj()传给expectation_from_state(),算出来的是原态psi的期望值。c.observable(0, 'y') psi = torch.tensor([1, 1j], device='cuda') / 2**0.5 c.expectation_from_state(psi, c.observables) # +1 c.expectation_from_state(psi.conj(), c.observables) # 应为 -1,当前实现仍按 +1 计算
原因是 PyTorch 的
conj()默认只加一个“取共轭”的标记,不改底层数据。C++ 直接把data_ptr()交给 SDK,两次读到的是同一份数据。传给 SDK 前需要调用resolve_conj()。 -
同一条线路第一次在
inference_mode()里执行,退出后再执行就会报错。(如果是之前说的为了多模拟一个qubit的缓存优化,感觉可以不管)with torch.inference_mode(): c() # 第一次执行,在这个模式下分配状态缓冲区 c() # 普通前向就会报错,不需要调用 backward()
原因是执行器要复用第一次分配的
state_,第二次运行时会先调用state_.zero_()。但 PyTorch 不允许在inference_mode()外原地修改这个模式里创建的张量。跨调用复用的缓冲区应按普通张量分配。 -
文档里的 GHZ 示例,建议直接检查态矢
sansiro77
left a comment
There was a problem hiding this comment.
- 用 set_wires() 或 set_controls() 改门后,GPU 后端仍按原来的 wire 执行,不报错。
c = dq.QubitCircuitGPU(2)
x = dq.PauliX(nqubit=2, wires=0)
c.add(x)
c() # |10⟩
x.set_wires(1)
c() # 原版得到 |01⟩,本 PR 仍得到 |10⟩- 已有 QubitCircuit 的权重不能直接加载到默认初态的 QubitCircuitGPU。原因是原版保存了初态,GPU 版用占位对象表示零态,没有这个key
- GPU 扩展写死了 -std=c++17,在 PyTorch 2.14、2.15 下首次使用会编译失败。
sansiro77
left a comment
There was a problem hiding this comment.
目前的前提是不要求 QubitCircuitGPU 和 QubitCircuit 可以互相加载 checkpoint。
下面各段共用:
import torch
import deepquantum as dq
gpu = dq.QubitCircuitGPU
x, z = dq.PauliX().matrix, dq.PauliZ().matrix-
a.add(b)会丢掉b的矩阵可观测量。a, b = gpu(1), gpu(1) b.x(0) b.observable_matrix(x, 0) a.add(b) a() a.expectation() # ValueError: There is no compiled observable
把
b.observable_matrix(x, 0)换成等价的b.observable(0, 'x'),就能正常得到0。更容易漏掉的是:如果a在拼接前已经用observable_matrix(z, 0)注册了 Z,原例不会报错,而是继续测 Z,得到-1,不是测 X 应得的0。 -
同一次前向得到两个期望值,保留计算图后,第二个仍然不能求梯度。
c = gpu(1) c.ry(0) c.observable(0, 'z') c.observable(0, 'x') theta = torch.tensor([0.0], device='cuda', requires_grad=True) exp_z, exp_x = c.expectation(parameters=theta) torch.autograd.grad(exp_z, theta, retain_graph=True) # 应为 0 torch.autograd.grad(exp_x, theta) # 应为 1,却报前向态已失效
这里
exp_z = cos(theta),exp_x = sin(theta)。两次求的都是一阶导,中间没有改线路、改参数或重新前向。当前第一次反传就把前向态标记为失效,第二次会报prepared adjoint state is stale。 -
默认设备设为 CUDA 后,单个 X 门也不能执行。
with torch.device('cuda:0'): c = gpu(1) c.x(0) c() # 预期得到 |1⟩
处理 X 门时,门矩阵已经转到 CPU,但
matrix[torch.arange(len(columns)), columns]中的行索引跟随默认设备创建在 CUDA 上,不能用它索引 CPU 矩阵。 -
GPU 线路恢复不了自己保存的默认零态,却能把同一份存档严格加载到比特数不同的 GPU 线路。
c = gpu(1) saved = c.state_dict() # 保存一比特的 |0⟩ gpu(2).load_state_dict(saved, strict=True) # 比特数不同,却加载成功 c.set_init_state('equal') # 改成 |+⟩ c.load_state_dict(saved, strict=True) # 缺少 init_state.state
改成
strict=False也没有恢复,初态仍是|+⟩。这里不要求保存完整态矢:同尺寸要能恢复为|0⟩,不同尺寸要能识别不匹配;恢复默认零态并执行后,memory_report()['initial_snapshot_bytes']应仍为0。 -
两个 GPU 线路之间严格加载成功,矩阵可观测量却没有恢复。
a, b = gpu(1), gpu(1) a.observable_matrix(z, 0) b.observable_matrix(-z, 0) b.load_state_dict(a.state_dict(), strict=True) # 所有键都匹配 b() print(b.expectation().item()) # -1,预期是 +1
两条线路的初态都是
|0⟩,唯一区别是a测 Z、b测 −Z。加载后b仍在测 −Z。当前注册的矩阵和它对应的 wire 都没有进入存档。 -
把 CNOT 的矩阵改成单位阵后,按文档调用
invalidate(),实际执行的仍是 CNOT。c = gpu(2) c.x(0) c.cnot(0, 1) c() # |11⟩ c.operators[1].matrix.copy_(torch.eye(4)) c.invalidate() print(c().flatten()) # 仍是 |11⟩,预期是 |10⟩
第二个门已经是单位阵,不应该再翻转第 1 位。当前执行指令按门名生成,忽略了修改后的矩阵;Toffoli、Fredkin 也走这一分支。
-
同一个 GPU 线路,同样从
|0⟩开始,pattern()只能处理显式写成张量的零态。for initial in (torch.tensor([1, 0], dtype=torch.complex64), 'zeros'): c = gpu(1, init_state=initial) c.h(0) c.pattern()
第一次正常返回
Pattern;第二次报AttributeError: '_ZeroState' object has no attribute 'state'。两次转换的是同一条 H 门线路,唯一差别是零态的表示方式。 -
同一个 GPU 类里,等价的两比特
rzz和multirz,只有前者能取幺正矩阵。a, b = gpu(2), gpu(2) a.rzz([0, 1], inputs=0.37) b.multirz([0, 1], inputs=0.37) a.get_unitary() # 返回 4×4 矩阵 b.get_unitary() # NotImplementedError
Add
QubitCircuitGPU, an optional compiled single-GPU statevector backend supporting NVIDIA cuQuantum and Iluvatar ixquantum through one shared cuStateVec API executor and adjoint kernel implementation.Behavior
backend='auto'|'cuquantum'|'ixquantum'. Auto selection follows the installed PyTorch build; explicit mismatches and missing SDKs raise errors without fallback.diff_methodargument is needed. Inference reads the existing state after a forward pass; explicit parameters trigger a fresh forward.Installation
For NVIDIA, install CUDA-enabled PyTorch and
deepquantum[cuquantum], plus a matching CUDA development toolkit with NVCC and a C++17 compiler. SDK discovery uses the installed cuStateVec wheel orCUQUANTUM_ROOT.For Iluvatar, install CoreX-compatible PyTorch and
deepquantum[ixquantum], and obtain the matching CoreX toolkit and ixquantum SDK from Iluvatar's developer downloads page; contact information is available at the bottom of that page. ConfigureIXQUANTUM_ROOT.See the installation and usage guide. Extensions compile on first GPU use with separate backend caches; normal package import does not require either SDK.
Example
Validation
Current limitations
Single-card pure statevector only; no runtime encoding/reupload, batching, noise, mid-circuit measurements, differentiable initial states, or higher-order gradients. Matrix observables support non-differentiable readout only.