Skip to content

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

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

Shaobo-Zhou wants to merge 7 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.
  • Focused loader and GPU regression tests: 71 passed, 1 skipped (two-GPU test with one GPU exposed). Covers forward states, expectations, sampling, automatic adjoint, shared/inverse parameters, state lifecycle, and non-default streams.
  • Four benchmark circuits additionally matched small CPU reference states; 15-qubit forward/sampling and gradient timing smoke checks completed.
  • Ruff checks and GPU Python formatting checks passed.
  • Original Iluvatar validation: BI-V150, CoreX 5.0.0, CoreX PyTorch 2.10.0, ixquantum 1.8.0. The latest shared changes have not been rerun on Iluvatar 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 示例,建议直接检查态矢

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