Skip to content

Add compiled single-GPU execution with cuQuantum and ixquantum - #179

Open
Shaobo-Zhou wants to merge 9 commits into
TuringQ:mainfrom
Shaobo-Zhou:feat/qubit-circuit-gpu
Open

Shaobo-Zhou wants to merge 9 commits into
TuringQ:mainfrom
Shaobo-Zhou:feat/qubit-circuit-gpu

Conversation

@Shaobo-Zhou

@Shaobo-Zhou Shaobo-Zhou commented Nov 13, 2026 •

Copy link
Copy Markdown

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

  • Reuse DeepQuantum's gate construction API with backend='auto'|'cuquantum'|'ixquantum'. Auto selection follows the installed PyTorch build; explicit mismatches and missing SDKs raise errors without fallback.
  • Compile reusable plans and select generalized permutation, Pauli rotation, or dense matrix APIs according to gate structure.
  • Preserve DeepQuantum's wire-0-as-MSB ordering and complex64 statevectors.
  • Support terminal sampling, exact expectations, and first-order adjoint differentiation through PyTorch autograd.
  • Automatically use adjoint when gradients are enabled and parameters require gradients; no diff_method argument is needed. Inference reads the existing state after a forward pass; explicit parameters trigger a fresh forward.
  • Keep existing inverse-matrix and stream/sampling workarounds in the shared executor. No separate gradient algorithm is introduced for NVIDIA.

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 or CUQUANTUM_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. Configure IXQUANTUM_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

import deepquantum as dq

circuit = dq.QubitCircuitGPU(3, backend='auto', device='cuda:0')
circuit.h(0)
circuit.cnot(0, 1)
circuit.cnot(1, 2)
state = circuit()                  # complex64 CUDA tensor, shape (8, 1)
counts = circuit.measure(shots=1024)
circuit.close()

Validation

  • NVIDIA A100: PyTorch 2.7.1/cu126, CUDA Toolkit 12.6, cuStateVec 1.14.0.
  • The loader and GPU regression suite had 91 passes and one skip with one NVIDIA A100 visible. An earlier run with two A100 GPUs passed all 92 tests, including the device-restoration test. Coverage includes independent gradients for shared-storage parameters, parameter replacement and unfreezing, MultiRZ checkpoints, conjugated state readout, cross-stream execution, inference-mode buffer reuse, and stale backward rejection.
  • Four benchmark circuits additionally matched small CPU reference states; 15-qubit forward/sampling and gradient timing smoke checks completed.
  • The GHZ quick-start statevector assertion, Ruff checks, and clang-format 20.1.8 checks passed.
  • Original Iluvatar hardware validation used a BI-V150 with CoreX 5.0.0, CoreX PyTorch 2.10.0, and ixquantum 1.8.0. The current review fixes still need validation on CoreX hardware.

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.

Shaobo-Zhou and others added 4 commits November 13, 2026 16:56
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
sansiro77 self-requested a review November 16, 2026 07:26
@sansiro77 sansiro77 self-assigned this Nov 16, 2026
@sansiro77 sansiro77 added the enhancement New feature or request label Nov 16, 2026
@Shaobo-Zhou Shaobo-Zhou changed the title Add optional ixquantum GPU backend with QubitCircuitGPU Add compiled single-GPU execution with cuQuantum and ixquantum Nov 17, 2026

@sansiro77 sansiro77 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. 把“共享存储”误当成“同一个可训练参数”,会错误合并梯度。例如:
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 没有梯度
  1. 参数解冻后,编译缓存没有失效。先 requires_grad_(False) 并执行线路,参数会被编译成常量,随后 requires_grad_(True) 再修改参数,会沿用旧的固定值
  2. GPU 测试需要区分“有 CUDA”和“装了可选后端”。现在 test_circuit_gpu.py 只根据 torch.cuda.is_available() 决定是否跳过。因此普通 NVIDIA 开发环境即使没有安装 cuQuantum,执行完整 pytest 也会进入这些测试,随后因缺 SDK 失败
  3. 建议文档从 ixquantum.md 改成 gpu_simulation.md,实现目录从 backends/gpu/ 收成一层 custatevec/
  4. 现在的 Markdown 对已经配好 GPU 开发环境的人够用,对从空环境开始的用户还不够。建议两个 GPU 后端各给一套从全新 conda 环境到跑通 GHZ 示例的步骤
  5. Matplotlib本来就会带入'packaging',应该不用额外写
  6. test-gpu-backend.yml 实际检查的是无 GPU、无厂商 SDK 时,打出来的 wheel 能否安装和使用,建议改名 test-cpu-compatibility.yml
  7. C++/CUDA 格式建议用固定版本的 clang-format 接入现有 pre-commit,并加到dev依赖里。用 20.1.8 检查,_gpu_executor.cpp 有 5 处格式不通过

@sansiro77 sansiro77 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. 调用 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也应该更新。

  2. 通过 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。

  3. 把 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()。

  4. 同一条线路第一次在 inference_mode() 里执行,退出后再执行就会报错。(如果是之前说的为了多模拟一个qubit的缓存优化,感觉可以不管)

    with torch.inference_mode():
        c()    # 第一次执行,在这个模式下分配状态缓冲区
    
    c()        # 普通前向就会报错,不需要调用 backward()

    原因是执行器要复用第一次分配的 state_,第二次运行时会先调用 state_.zero_()。但 PyTorch 不允许在 inference_mode() 外原地修改这个模式里创建的张量。跨调用复用的缓冲区应按普通张量分配。

  5. 文档里的 GHZ 示例,建议直接检查态矢

@sansiro77 sansiro77 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. 用 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⟩
  1. 已有 QubitCircuit 的权重不能直接加载到默认初态的 QubitCircuitGPU。原因是原版保存了初态,GPU 版用占位对象表示零态,没有这个key
  2. GPU 扩展写死了 -std=c++17,在 PyTorch 2.14、2.15 下首次使用会编译失败。

@sansiro77 sansiro77 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

目前的前提是不要求 QubitCircuitGPU 和 QubitCircuit 可以互相加载 checkpoint。
下面各段共用:

import torch
import deepquantum as dq

gpu = dq.QubitCircuitGPU
x, z = dq.PauliX().matrix, dq.PauliZ().matrix
  1. 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。

  2. 同一次前向得到两个期望值,保留计算图后,第二个仍然不能求梯度。

    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。

  3. 默认设备设为 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 矩阵。

  4. 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。

  5. 两个 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 都没有进入存档。

  6. 把 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 也走这一分支。

  7. 同一个 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 门线路,唯一差别是零态的表示方式。

  8. 同一个 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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants