diff --git a/.github/workflows/test-cpu-compatibility.yml b/.github/workflows/test-cpu-compatibility.yml new file mode 100644 index 00000000..30f384be --- /dev/null +++ b/.github/workflows/test-cpu-compatibility.yml @@ -0,0 +1,46 @@ +name: CPU wheel compatibility + +on: + pull_request: + paths: + - 'src/deepquantum/custatevec/**' + - 'src/deepquantum/*.py' + - 'tests/test_circuit_gpu.py' + - 'tests/test_gpu_loader.py' + - 'pyproject.toml' + - '.github/workflows/test-cpu-compatibility.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + cpu-install: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install CPU PyTorch and build tools + run: | + python -m pip install torch==2.10.0 --index-url https://download.pytorch.org/whl/cpu + python -m pip install build pytest ruff==0.15.9 + - name: Check style and build distributions + run: | + ruff check . + ruff format --check src/deepquantum/custatevec tests/test_circuit_gpu.py tests/test_gpu_loader.py + python -m build + - name: Install the wheel without the vendor SDK + run: python -m pip install dist/*.whl + - name: Test the installed package outside the checkout + working-directory: ${{ runner.temp }} + env: + OMP_NUM_THREADS: '2' + run: | + python -c "import sys, torch, deepquantum; assert not torch.cuda.is_available(); assert 'torch.utils.cpp_extension' not in sys.modules" + python -m pytest -q \ + "${{ github.workspace }}/tests/test_gpu_loader.py" \ + "${{ github.workspace }}/tests/test_circuit_gpu.py" \ + "${{ github.workspace }}/tests/test_circuit.py" \ + "${{ github.workspace }}/tests/test_module.py" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 12214e7a..16bfbf52 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -17,6 +17,12 @@ repos: - id: ruff-format exclude: ^(docs/source/demos/.*|tutorials/.*|examples/[^/]*)\.py$ + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: v20.1.8 + hooks: + - id: clang-format + files: ^src/deepquantum/custatevec/.*\.(cpp|cu)$ + - repo: https://github.com/mwouts/jupytext rev: v1.19.1 hooks: diff --git a/README.md b/README.md index 7a14ec41..ab0350fb 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,9 @@ The first framework to support algorithm design and mapping for time-domain-mult # Installation +For compiled single-GPU execution on NVIDIA or Iluvatar (天数), see the +[QubitCircuitGPU installation and usage guide](docs/source/quick_start/gpu_simulation.md). + ## 1. Prerequisites (PyTorch) DeepQuantum requires **PyTorch 2**. diff --git a/docs/source/index.md b/docs/source/index.md index 2d4fd50e..b54c37a4 100644 --- a/docs/source/index.md +++ b/docs/source/index.md @@ -20,6 +20,7 @@ quick_start/basic_examples.md quick_start/introduction_cn.md quick_start/basic_usage_cn.md quick_start/basic_examples_cn.md +quick_start/gpu_simulation.md ``` ```{toctree} diff --git a/docs/source/quick_start/gpu_simulation.md b/docs/source/quick_start/gpu_simulation.md new file mode 100644 index 00000000..6db0b099 --- /dev/null +++ b/docs/source/quick_start/gpu_simulation.md @@ -0,0 +1,126 @@ +# Single-GPU simulation + +`QubitCircuitGPU` runs quantum circuits on one NVIDIA GPU with cuQuantum or one Iluvatar GPU with ixquantum. +It uses the same gate construction methods as `QubitCircuit` and supports statevector simulation, measurement sampling, and adjoint gradients. + +## Installation + +Run the commands from a DeepQuantum source checkout. Choose the section for your GPU, then run the GHZ example below in that Conda environment. +Both examples use Python 3.10. For CoreX, match the Python version to the PyTorch wheel from Iluvatar (`cp310` for Python 3.10 or `cp311` for Python 3.11). + +### NVIDIA cuQuantum + +This example requires a compatible NVIDIA driver, the [CUDA 12.6 Toolkit](https://docs.nvidia.com/cuda/archive/12.6.3/cuda-installation-guide-linux/index.html) with `nvcc`, and a C++17 compiler. + +```bash +conda create -n dq-cuquantum python=3.10 pip -y +conda activate dq-cuquantum +python -m pip install torch==2.7.1 --index-url https://download.pytorch.org/whl/cu126 +python -m pip install -e '.[cuquantum]' 'custatevec-cu12==1.14.0' +export CUDA_HOME=/usr/local/cuda-12.6 # Adjust to your CUDA Toolkit path. +``` + +### Iluvatar ixquantum + +Install the GPU driver and CoreX toolkit from Iluvatar (天数智芯). Obtain the CoreX PyTorch wheel and the ixquantum SDK files from Iluvatar as well. + +- `custatevec.h` is the C API header used to compile the DeepQuantum GPU extension. +- `libcustatevec.so.1.8.0` is the ixquantum shared library that DeepQuantum links to and calls at runtime. + +Please contact Iluvatar for the ixquantum SDK files using the contact details at the bottom of its [developer downloads page](https://developer.iluvatar.com/downloads). +This backend has been tested on Linux x86_64 with a BI-V150 GPU, CoreX 5.0.0, CoreX PyTorch 2.10.0, and ixquantum 1.8.0. +A C++17 compiler and Python development headers are also required. + +Set `IXQUANTUM_ROOT` to the directory containing the ixquantum SDK files. +Replace `/path/to/corex-torch.whl` with the path to the CoreX PyTorch wheel. +The commands assume CoreX is installed at `/usr/local/corex`. + +```bash +conda create -n dq-ixquantum python=3.10 pip -y +conda activate dq-ixquantum +export PATH="/usr/local/corex/bin:$PATH" +export LD_LIBRARY_PATH="/usr/local/corex/lib64:/usr/local/corex/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +export IXQUANTUM_ROOT=/path/to/ixquantum +python -m pip install /path/to/corex-torch.whl +python -m pip install -e '.[ixquantum]' +python -c "import torch; assert getattr(torch, 'corex', False) and torch.cuda.is_available()" +``` + +The extension compiles on first use and is cached for subsequent runs. + +## Build and run a circuit + +Choose the GPU with `device` when constructing the circuit. +By default, the backend is selected from the installed PyTorch build. +You can also set `backend='cuquantum'` or `backend='ixquantum'` explicitly. + +Run the following Python example in the environment you just configured. It prepares a three-qubit GHZ state and checks the measurement counts. + +```python +import deepquantum as dq + +circuit = dq.QubitCircuitGPU(3, device='cuda:0') +circuit.h(0) +circuit.cnot(0, 1) +circuit.cnot(1, 2) + +state = circuit() +counts = circuit.measure(shots=1024) +assert state.shape == (8, 1) +assert set(counts) <= {'000', '111'} and sum(counts.values()) == 1024 +print(counts) # Approximately equal '000' and '111' counts. +circuit.close() +``` + +The state is a `complex64` tensor, with qubit 0 as the most significant bit, matching `QubitCircuit`. +Its storage is reused by later executions; use `state.clone()` to keep an independent copy. +`close()` releases the circuit's GPU resources. +To use a different GPU, construct a new circuit on that device. + +## Train a circuit + +Gates added without fixed inputs have trainable parameters. +For Pauli observables, when gradients are enabled and parameters require gradients, `expectation()` computes the forward result and uses adjoint differentiation during `backward()`. + +```python +import torch +import deepquantum as dq + +circuit = dq.QubitCircuitGPU(2, device='cuda:0') +circuit.ry(0) +circuit.cnot(0, 1) +circuit.observable(1, 'z') + +optimizer = torch.optim.Adam(circuit.parameters(), lr=0.05) +for _ in range(10): + optimizer.zero_grad() + loss = circuit.expectation().sum() + loss.backward() + optimizer.step() + +# Read the trained circuit without computing gradients. +with torch.no_grad(): + circuit() + value = circuit.expectation() + +circuit.close() +``` + +Complete `backward()` before running or modifying the same circuit again. +For inference, call `circuit()` before `expectation()`, as shown above. + +## Supported operations + +Supported gates include fixed unitary matrices, controlled gates, Pauli rotations, and phase gates. +Gradients are available for supported scalar rotations and phase gates with Pauli observables, to first order only. +The returned statevector is not differentiable. + +`measure()` returns sampled bit-string counts without changing the final state. +Use `observable()` for Pauli observables or `observable_matrix(matrix, wires)` for a general fixed Hermitian observable. +Matrix observables currently support expectation values without gradients and must be used separately from Pauli observables. + +Runtime data encoding, batches, density matrices, noise, mid-circuit measurements, and conditional operations are currently not supported. +Individual inverse gates are supported; whole-circuit `inverse()` and circuit addition with `+` are not. + +Updating trainable parameter values does not require recompilation. +After directly changing a fixed gate parameter or matrix, call `circuit.invalidate()` before the next execution. diff --git a/pyproject.toml b/pyproject.toml index 28f93849..27a0f074 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,7 +47,10 @@ classifiers = [ ] [project.optional-dependencies] +ixquantum = ['ninja', 'setuptools'] +cuquantum = ['ninja', 'setuptools', 'custatevec-cu12'] dev = [ + 'clang-format==20.1.8', 'graphix==0.3.1', 'jupytext', 'pennylane-sf', @@ -78,6 +81,7 @@ version = { attr = 'deepquantum.__version__' } [tool.setuptools.package-data] 'deepquantum.photonic' = ['cache/*'] +'deepquantum.custatevec' = ['*.cpp', '*.cu'] [tool.jupytext] formats = 'ipynb,py:percent' diff --git a/requirements-dev.txt b/requirements-dev.txt index c0ad0b66..5731c7bf 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,3 +1,4 @@ +clang-format==20.1.8 graphix==0.3.1 jupytext pennylane-sf diff --git a/src/deepquantum/__init__.py b/src/deepquantum/__init__.py index 32404fbd..cab3c35a 100644 --- a/src/deepquantum/__init__.py +++ b/src/deepquantum/__init__.py @@ -52,6 +52,7 @@ ) from .circuit import DistributedQubitCircuit, QubitCircuit from .communication import cleanup_distributed, setup_distributed +from .custatevec import QubitCircuitGPU from .gate import ( Barrier, CNOT, diff --git a/src/deepquantum/custatevec/.clang-format b/src/deepquantum/custatevec/.clang-format new file mode 100644 index 00000000..bfd118eb --- /dev/null +++ b/src/deepquantum/custatevec/.clang-format @@ -0,0 +1,2 @@ +BasedOnStyle: Google +ColumnLimit: 120 diff --git a/src/deepquantum/custatevec/__init__.py b/src/deepquantum/custatevec/__init__.py new file mode 100644 index 00000000..d39f2238 --- /dev/null +++ b/src/deepquantum/custatevec/__init__.py @@ -0,0 +1,5 @@ +"""Compiled single-GPU statevector execution with cuQuantum or ixquantum.""" + +from .circuit import QubitCircuitGPU + +__all__ = ['QubitCircuitGPU'] diff --git a/src/deepquantum/custatevec/_gpu_executor.cpp b/src/deepquantum/custatevec/_gpu_executor.cpp new file mode 100644 index 00000000..4837a6cc --- /dev/null +++ b/src/deepquantum/custatevec/_gpu_executor.cpp @@ -0,0 +1,747 @@ +// Shared cuStateVec API executor for cuQuantum and ixquantum. +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +// Adjoint kernels defined in adjoint_kernels.cu. +extern "C" void dq_pauli_action(const void*, void*, uint64_t, uint64_t, uint64_t, int, const float*, cudaStream_t); +extern "C" void dq_pauli_contract(const void*, const void*, float*, uint64_t, uint64_t, uint64_t, int, uint64_t, + cudaStream_t); + +namespace py = pybind11; +namespace { +void check_cuda(cudaError_t status, const char* operation) { + if (status != cudaSuccess) + throw std::runtime_error(std::string(operation) + ": CUDA status " + std::to_string(static_cast(status)) + + " (" + cudaGetErrorString(status) + ")"); +} +void check_custatevec(custatevecStatus_t status, const char* operation) { + if (status != CUSTATEVEC_STATUS_SUCCESS) + // ixquantum 1.8.0 does not implement custatevecGetErrorString reliably. + throw std::runtime_error(std::string(operation) + ": cuStateVec status " + + std::to_string(static_cast(status))); +} + +// Own native resources independently of executor construction and tensor allocation. +struct NativeResources { + explicit NativeResources(int device) : device(device) {} + NativeResources(const NativeResources&) = delete; + NativeResources& operator=(const NativeResources&) = delete; + ~NativeResources() { + try { + const c10::cuda::CUDAGuard guard(device); + close(); + } catch (...) { + // Destructors cannot report runtime shutdown errors. + } + } + + void initialize() { + const c10::cuda::CUDAGuard guard(device); + check_custatevec(custatevecCreate(&handle), "custatevecCreate"); + check_cuda(cudaEventCreateWithFlags(&torch_to_custatevec, cudaEventDisableTiming), + "create torch-to-cuStateVec event"); + check_cuda(cudaEventCreateWithFlags(&custatevec_to_torch, cudaEventDisableTiming), + "create cuStateVec-to-torch event"); + } + + void close() { + // Attempt every release before reporting an error; subsequent calls are harmless. + const auto sampler_status = + sampler ? custatevecSamplerDestroy(std::exchange(sampler, nullptr)) : CUSTATEVEC_STATUS_SUCCESS; + const auto handle_status = handle ? custatevecDestroy(std::exchange(handle, nullptr)) : CUSTATEVEC_STATUS_SUCCESS; + const auto input_status = + torch_to_custatevec ? cudaEventDestroy(std::exchange(torch_to_custatevec, nullptr)) : cudaSuccess; + const auto output_status = + custatevec_to_torch ? cudaEventDestroy(std::exchange(custatevec_to_torch, nullptr)) : cudaSuccess; + check_custatevec(sampler_status, "custatevecSamplerDestroy"); + check_custatevec(handle_status, "custatevecDestroy"); + check_cuda(input_status, "destroy torch-to-cuStateVec event"); + check_cuda(output_status, "destroy cuStateVec-to-torch event"); + } + + int device; + custatevecHandle_t handle{nullptr}; + custatevecSamplerDescriptor_t sampler{nullptr}; + cudaEvent_t torch_to_custatevec{nullptr}, custatevec_to_torch{nullptr}; +}; + +// Values match the plan constants in compiler.py. +enum class OpCode { Matrix = 0, PauliRotation = 1, Phase = 2, Permutation = 3 }; +enum class GradientKind { None = 0, PauliGenerator = 1, Phase = 2 }; + +struct Op { + OpCode opcode{}; + std::vector targets, controls, values; + torch::Tensor matrix, inverse_matrix; + bool diagonal_only = false, permutation_only = false; + std::vector permutations[2]; + std::vector> diagonals[2]; + double angle{}; + std::vector paulis; + int parameter_index{-1}; + double parameter_scale{1.0}; + GradientKind gradient_kind{}; + double generator_coeff{}; +}; + +class GPUCircuitExecutor { + // Lease scratch from the PyTorch allocator for the current stream. + struct WorkspaceLease { + c10::cuda::CUDAGuard guard; + GPUCircuitExecutor& owner; + bool acquired = false; + explicit WorkspaceLease(GPUCircuitExecutor& value) : guard(value.device_), owner(value) { + owner.bind_current_stream(); + if (owner.workspace_bytes_ && !owner.workspace_.defined()) { + acquired = true; + owner.workspace_ = + torch::empty({static_cast(owner.workspace_bytes_)}, + torch::TensorOptions().dtype(torch::kUInt8).device(torch::kCUDA, owner.device_)); + } + } + ~WorkspaceLease() { + if (acquired) owner.workspace_ = torch::Tensor(); + } + }; + + public: + GPUCircuitExecutor(int nqubit, int device) : nqubit_(nqubit), device_(device), resources_(device) { + if (nqubit < 1 || nqubit > 30) throw std::invalid_argument("nqubit must be in [1, 30]"); + resources_.initialize(); + } + ~GPUCircuitExecutor() { + try { + close(); + } catch (...) { + } + } + + void compile(const std::vector& codes, const std::vector>& targets, + const std::vector>& controls, const py::list& matrices, + const std::vector>& permutations, + const std::vector>>& diagonals, const std::vector& angles, + const std::vector>& paulis, const std::vector& parameter_indices, + const std::vector& parameter_scales, const std::vector& gradient_kinds, + const std::vector& generator_coeffs, const std::vector>& obs_p, + const std::vector>& obs_b, const py::object& observable_matrix, + const std::vector& observable_matrix_bits, const py::object& initial_state) { + if (closed_) throw std::runtime_error("executor is closed"); + const c10::cuda::CUDAGuard guard(device_); + ++generation_; + ++plan_version_; + state_ready_ = false; + compiled_ = false; + const auto n = codes.size(); + if (permutations.size() != n || diagonals.size() != n || targets.size() != n || controls.size() != n || + matrices.size() != n || angles.size() != n || paulis.size() != n || parameter_indices.size() != n || + parameter_scales.size() != n || gradient_kinds.size() != n || generator_coeffs.size() != n) + throw std::invalid_argument("inconsistent plan lengths"); + ops_.clear(); + workspace_bytes_ = 0; + parameter_count_ = 0; + + prepared_generation_ = -1; + last_parameter_values_.clear(); + initial_state_ = torch::Tensor(); + if (!initial_state.is_none()) { + initial_state_ = py::cast(initial_state); + if (!initial_state_.is_cuda() || initial_state_.scalar_type() != torch::kComplexFloat || + !initial_state_.is_contiguous() || initial_state_.numel() != (int64_t{1} << nqubit_)) + throw std::invalid_argument("initial_state must be contiguous CUDA complex64 with 2**n amplitudes"); + initial_state_ = initial_state_.clone(); + } + + for (size_t i = 0; i < n; ++i) { + Op op; + op.opcode = static_cast(codes[i]); + op.angle = angles[i]; + op.paulis = paulis[i]; + op.parameter_index = parameter_indices[i]; + op.parameter_scale = parameter_scales[i]; + op.gradient_kind = static_cast(gradient_kinds[i]); + op.generator_coeff = generator_coeffs[i]; + parameter_count_ = std::max(parameter_count_, op.parameter_index + 1); + for (int value : targets[i]) op.targets.push_back(value); + for (int value : controls[i]) { + op.controls.push_back(value); + op.values.push_back(1); + } + if (op.targets.empty()) throw std::invalid_argument("operation has no targets"); + size_t size = 0; + if (op.opcode == OpCode::Matrix) { + if (matrices[i].is_none()) throw std::invalid_argument("MATRIX op has no matrix"); + op.matrix = py::cast(matrices[i]); + if (!op.matrix.is_cuda() || op.matrix.scalar_type() != torch::kComplexFloat || !op.matrix.is_contiguous()) + throw std::invalid_argument("matrices must be contiguous CUDA complex64"); + const int64_t dim = int64_t{1} << op.targets.size(); + if (op.matrix.dim() != 2 || op.matrix.size(0) != dim || op.matrix.size(1) != dim) + throw std::invalid_argument("matrix shape does not match target count"); + // Current ixquantum does not reliably round-trip non-symmetric ROW matrices + // with adjoint=1. Cache U^dagger explicitly and always dispatch adjoint=0. + op.inverse_matrix = op.matrix.conj().transpose(0, 1).contiguous(); + + check_custatevec( + custatevecApplyMatrixGetWorkspaceSize(resources_.handle, CUDA_C_32F, nqubit_, op.matrix.data_ptr(), + CUDA_C_32F, CUSTATEVEC_MATRIX_LAYOUT_ROW, 0, op.targets.size(), + op.controls.size(), CUSTATEVEC_COMPUTE_32F, &size), + "matrix workspace"); + } else if (op.opcode == OpCode::Permutation) { + const auto dim = size_t{1} << op.targets.size(); + if (permutations[i].size() != dim || diagonals[i].size() != dim) + throw std::invalid_argument("invalid permutation descriptor size"); + op.permutations[0].assign(permutations[i].begin(), permutations[i].end()); + op.permutations[1].resize(dim); + op.diagonals[0].resize(dim); + op.diagonals[1].resize(dim); + std::vector seen(dim, false); + for (size_t row = 0; row < dim; ++row) { + auto col = op.permutations[0][row]; + if (col < 0 || size_t(col) >= dim || seen[col]) throw std::invalid_argument("invalid permutation"); + seen[col] = true; + op.diagonals[0][row] = c10::complex(diagonals[i][row].real(), diagonals[i][row].imag()); + op.permutations[1][col] = row; + op.diagonals[1][col] = c10::complex(diagonals[i][row].real(), -diagonals[i][row].imag()); + } + op.diagonal_only = true; + op.permutation_only = true; + for (size_t row = 0; row < dim; ++row) { + op.diagonal_only &= op.permutations[0][row] == static_cast(row); + op.permutation_only &= op.diagonals[0][row] == c10::complex(1, 0); + } + if (op.diagonal_only && op.permutation_only) continue; + for (int inverse = 0; inverse < 2; ++inverse) { + size_t bytes = 0; + check_custatevec( + custatevecApplyGeneralizedPermutationMatrixGetWorkspaceSize( + resources_.handle, CUDA_C_32F, nqubit_, op.permutations[inverse].data(), op.diagonals[inverse].data(), + CUDA_C_32F, op.targets.data(), op.targets.size(), op.controls.size(), &bytes), + "permutation workspace"); + size = std::max(size, bytes); + } + } else if (op.opcode == OpCode::PauliRotation) { + if (op.paulis.size() != op.targets.size()) + throw std::invalid_argument("PauliRotation requires one Pauli per target"); + for (int pauli : op.paulis) + if (pauli < 1 || pauli > 3) throw std::invalid_argument("invalid Pauli generator"); + if (op.parameter_index >= 0 && op.gradient_kind != GradientKind::PauliGenerator) + throw std::invalid_argument("trainable Pauli rotations require generator gradients"); + } else if (op.opcode == OpCode::Phase) { + if (op.targets.size() != 1) throw std::invalid_argument("phase requires one target"); + c10::complex diagonal[2] = {{1, 0}, {1, 0}}; + check_custatevec(custatevecApplyGeneralizedPermutationMatrixGetWorkspaceSize( + resources_.handle, CUDA_C_32F, nqubit_, nullptr, diagonal, CUDA_C_32F, op.targets.data(), + 1, op.controls.size(), &size), + "phase workspace"); + } else + throw std::invalid_argument("unknown opcode"); + + workspace_bytes_ = std::max(workspace_bytes_, size); + ops_.push_back(std::move(op)); + } + + obs_p_ = obs_p; + obs_b_ = obs_b; + if (obs_p_.size() != obs_b_.size()) throw std::invalid_argument("inconsistent Pauli observable plan"); + observable_matrix_ = torch::Tensor(); + observable_matrix_bits_.clear(); + if (!observable_matrix.is_none()) { + if (!obs_p_.empty()) throw std::invalid_argument("cannot mix Pauli and matrix observables"); + observable_matrix_ = py::cast(observable_matrix); + if (!observable_matrix_.is_cuda() || observable_matrix_.scalar_type() != torch::kComplexFloat || + !observable_matrix_.is_contiguous()) + throw std::invalid_argument("observable matrix must be contiguous CUDA complex64"); + if (observable_matrix_bits.empty()) throw std::invalid_argument("matrix observable has no target bits"); + const int64_t dim = int64_t{1} << observable_matrix_bits.size(); + if (observable_matrix_.dim() != 2 || observable_matrix_.size(0) != dim || observable_matrix_.size(1) != dim) + throw std::invalid_argument("matrix observable has invalid shape"); + for (int bit : observable_matrix_bits) observable_matrix_bits_.push_back(bit); + size_t size = 0; + check_custatevec(custatevecComputeExpectationGetWorkspaceSize( + resources_.handle, CUDA_C_32F, nqubit_, observable_matrix_.data_ptr(), CUDA_C_32F, + CUSTATEVEC_MATRIX_LAYOUT_ROW, observable_matrix_bits_.size(), CUSTATEVEC_COMPUTE_32F, &size), + "ComputeExpectation workspace query"); + workspace_bytes_ = std::max(workspace_bytes_, size); + } + workspace_ = torch::Tensor(); + + state_ready_ = false; + compiled_ = true; + } + + torch::Tensor execute(const torch::Tensor& parameters) { + WorkspaceLease lease(*this); + run_forward(parameters); + return state_; + } + torch::Tensor forward_expectation(const torch::Tensor& parameters) { + WorkspaceLease lease(*this); + run_forward(parameters); + if (obs_p_.empty() || observable_matrix_.defined()) + throw std::runtime_error("adjoint requires one or more Pauli observables"); + return expectation(); + } + + torch::Tensor expectation() { + WorkspaceLease lease(*this); + ready(); + if (!state_ready_) throw std::runtime_error("expectation requires a completed forward pass"); + bind_current_stream(); + if (observable_matrix_.defined()) { + cuDoubleComplex output = make_cuDoubleComplex(0.0, 0.0); + double residual = 0.0; + torch_to_custatevec(); + check_custatevec(custatevecComputeExpectation( + resources_.handle, state_.data_ptr(), CUDA_C_32F, nqubit_, &output, CUDA_C_64F, &residual, + observable_matrix_.data_ptr(), CUDA_C_32F, CUSTATEVEC_MATRIX_LAYOUT_ROW, + observable_matrix_bits_.data(), observable_matrix_bits_.size(), CUSTATEVEC_COMPUTE_32F, + workspace_bytes_ ? workspace_.data_ptr() : nullptr, workspace_bytes_), + "custatevecComputeExpectation"); + custatevec_to_torch(); + check_cuda(cudaDeviceSynchronize(), "synchronize matrix expectation"); + if (std::abs(output.y) > 1e-5) + throw std::runtime_error("Hermitian expectation has non-negligible imaginary part"); + return torch::full({1}, static_cast(output.x), + torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA, device_)); + } + if (obs_p_.empty()) throw std::runtime_error("there is no compiled observable"); + return compute_pauli_expectations(state_, obs_p_, obs_b_); + } + + torch::Tensor expectation_from_state(const torch::Tensor& state, const std::vector>& paulis, + const std::vector>& bits) { + if (closed_) throw std::runtime_error("executor is closed"); + const c10::cuda::CUDAGuard guard(device_); + validate_external_state(state); + + return compute_pauli_expectations(state, paulis, bits); + } + + torch::Tensor sample(int shots, const std::vector& bit_ordering, const torch::Tensor& randnums) { + const c10::cuda::CUDAGuard guard(device_); + ready(); + if (!state_ready_) throw std::runtime_error("sample requires a completed forward pass"); + if (shots <= 0 || bit_ordering.empty() || bit_ordering.size() > static_cast(nqubit_)) + throw std::invalid_argument("invalid sampling arguments"); + if (!randnums.device().is_cpu() || randnums.scalar_type() != torch::kFloat64 || !randnums.is_contiguous() || + randnums.numel() != shots) + throw std::invalid_argument("randnums must be contiguous CPU float64 with one value per shot"); + std::vector bits; + for (int bit : bit_ordering) { + if (bit < 0 || bit >= nqubit_) throw std::invalid_argument("sampling bit is out of range"); + bits.push_back(bit); + } + bind_current_stream(); + torch_to_custatevec(); + ensure_sampler(static_cast(shots)); + check_custatevec(custatevecSamplerPreprocess(resources_.handle, resources_.sampler, + sampler_workspace_.defined() ? sampler_workspace_.data_ptr() : nullptr, + sampler_workspace_bytes_), + "custatevecSamplerPreprocess"); + // ixquantum 1.8.0 sampling reads preprocessing results on the host. + // Non-default streams need an explicit completion before that API call. + check_cuda(cudaStreamSynchronize(custatevec_uses_current_stream_ ? current_stream_ : nullptr), + "synchronize sampler preprocessing"); + auto output = torch::empty({shots}, torch::TensorOptions().dtype(torch::kInt64).device(torch::kCPU)); + check_custatevec(custatevecSamplerSample(resources_.handle, resources_.sampler, + reinterpret_cast(output.data_ptr()), + bits.data(), bits.size(), randnums.data_ptr(), shots, + CUSTATEVEC_SAMPLER_OUTPUT_RANDNUM_ORDER), + "custatevecSamplerSample"); + custatevec_to_torch(); + check_cuda(cudaDeviceSynchronize(), "synchronize sampler"); + return output; + } + + torch::Tensor adjoint_vjp(const torch::Tensor& parameters, const torch::Tensor& grad_output) { + WorkspaceLease lease(*this); + validate_weights(grad_output); + + run_forward(parameters); + return reverse_prepared(grad_output, generation_); + } + + torch::Tensor adjoint_vjp_prepared(const torch::Tensor& parameters, const torch::Tensor& grad_output, + int64_t expected_generation) { + WorkspaceLease lease(*this); + validate_parameters(parameters); + validate_weights(grad_output); + + return reverse_prepared(grad_output, expected_generation); + } + + py::tuple value_and_grad(const torch::Tensor& parameters, const torch::Tensor& weights, double constant) { + WorkspaceLease lease(*this); + validate_weights(weights); + + run_forward(parameters); + build_weighted_adjoint_state(weights); + auto energy = torch::real(torch::vdot(state_, adjoint_state_)) + constant; + auto gradient = reverse_from_current_adjoint(generation_); + return py::make_tuple(energy, gradient); + } + + py::dict memory_report() const { + py::dict out; + out["live_workspace_bytes"] = workspace_.defined() ? workspace_.nbytes() : 0; + out["state_bytes"] = state_.defined() ? state_.nbytes() : 0; + out["adjoint_bytes"] = adjoint_state_.defined() ? adjoint_state_.nbytes() : 0; + out["initial_snapshot_bytes"] = initial_state_.defined() ? initial_state_.nbytes() : 0; + out["workspace_bytes"] = workspace_bytes_; + out["sampler_workspace_bytes"] = sampler_workspace_bytes_; + return out; + } + + int64_t generation() const { return generation_; } + int64_t plan_version() const { return plan_version_; } + + void close() { + if (closed_) return; + ++generation_; + const c10::cuda::CUDAGuard guard(device_); + const auto sync_status = cudaDeviceSynchronize(); + std::exception_ptr release_error; + try { + resources_.close(); + } catch (...) { + release_error = std::current_exception(); + } + sampler_max_shots_ = 0; + sampler_workspace_bytes_ = 0; + workspace_ = torch::Tensor(); + state_ = torch::Tensor(); + initial_state_ = torch::Tensor(); + adjoint_state_ = torch::Tensor(); + sampler_workspace_ = torch::Tensor(); + observable_matrix_ = torch::Tensor(); + observable_matrix_bits_.clear(); + ops_.clear(); + state_ready_ = false; + closed_ = true; + if (release_error) std::rethrow_exception(release_error); + check_cuda(sync_status, "synchronize executor close"); + } + + private: + void ready() const { + if (closed_) throw std::runtime_error("executor is closed"); + if (!compiled_) throw std::runtime_error("executor has not been compiled"); + } + void bind_current_stream() { + current_stream_ = c10::cuda::getCurrentCUDAStream(device_).stream(); + if (!set_stream_known_unsupported_) { + const auto status = custatevecSetStream(resources_.handle, current_stream_); + if (status == CUSTATEVEC_STATUS_SUCCESS) { + custatevec_uses_current_stream_ = true; + return; + } + if (status != CUSTATEVEC_STATUS_NOT_SUPPORTED) check_custatevec(status, "set stream"); + set_stream_known_unsupported_ = true; + } + custatevec_uses_current_stream_ = false; + } + void torch_to_custatevec() { + if (custatevec_uses_current_stream_ || current_stream_ == nullptr) return; + check_cuda(cudaEventRecord(resources_.torch_to_custatevec, current_stream_), "record torch-to-cuStateVec event"); + check_cuda(cudaStreamWaitEvent(nullptr, resources_.torch_to_custatevec, 0), "wait torch-to-cuStateVec event"); + } + void custatevec_to_torch() { + if (custatevec_uses_current_stream_ || current_stream_ == nullptr) return; + check_cuda(cudaEventRecord(resources_.custatevec_to_torch, nullptr), "record cuStateVec-to-torch event"); + check_cuda(cudaStreamWaitEvent(current_stream_, resources_.custatevec_to_torch, 0), + "wait cuStateVec-to-torch event"); + } + void validate_parameters(const torch::Tensor& parameters) const { + if (!parameters.is_cuda() || parameters.get_device() != device_ || parameters.scalar_type() != torch::kFloat || + !parameters.is_contiguous() || parameters.dim() != 1 || parameters.numel() != parameter_count_) + throw std::invalid_argument( + "parameters must be a contiguous CUDA float32 vector with logical_parameter_count elements"); + } + void validate_weights(const torch::Tensor& weights) const { + ready(); + if (!weights.is_cuda() || weights.get_device() != device_ || weights.scalar_type() != torch::kFloat || + !weights.is_contiguous() || weights.dim() != 1 || weights.numel() != static_cast(obs_p_.size())) + throw std::invalid_argument( + "coefficients must be a contiguous CUDA float32 vector matching the Pauli observable count"); + } + void validate_external_state(const torch::Tensor& state) const { + if (!state.is_cuda() || state.get_device() != device_ || state.scalar_type() != torch::kComplexFloat || + state.dim() != 1 || !state.is_contiguous() || state.requires_grad() || state.numel() != (int64_t{1} << nqubit_)) + throw std::invalid_argument( + "state must be a contiguous non-differentiable CUDA complex64 vector on the executor device with 2**n " + "amplitudes"); + } + torch::Tensor compute_pauli_expectations(const torch::Tensor& state, + const std::vector>& observable_paulis, + const std::vector>& observable_bits) { + if (observable_paulis.empty() || observable_paulis.size() != observable_bits.size()) + throw std::invalid_argument("Pauli observables must be non-empty and have consistent plan lengths"); + std::vector> paulis(observable_paulis.size()); + std::vector> bits(observable_bits.size()); + std::vector pauli_ptrs; + std::vector bit_ptrs; + std::vector lengths; + std::vector output(observable_paulis.size()); + for (size_t i = 0; i < observable_paulis.size(); ++i) { + if (observable_paulis[i].empty() || observable_paulis[i].size() != observable_bits[i].size()) + throw std::invalid_argument("each Pauli observable must have matching non-empty Pauli and bit lists"); + for (int value : observable_paulis[i]) { + if (value < 1 || value > 3) throw std::invalid_argument("invalid Pauli observable value"); + paulis[i].push_back(static_cast(value)); + } + for (int value : observable_bits[i]) { + if (value < 0 || value >= nqubit_) throw std::invalid_argument("Pauli observable bit is out of range"); + bits[i].push_back(value); + } + pauli_ptrs.push_back(paulis[i].data()); + bit_ptrs.push_back(bits[i].data()); + lengths.push_back(bits[i].size()); + } + bind_current_stream(); + torch_to_custatevec(); + check_custatevec(custatevecComputeExpectationsOnPauliBasis(resources_.handle, state.data_ptr(), CUDA_C_32F, nqubit_, + output.data(), pauli_ptrs.data(), output.size(), + bit_ptrs.data(), lengths.data()), + "custatevecComputeExpectationsOnPauliBasis"); + custatevec_to_torch(); + check_cuda(cudaDeviceSynchronize(), "synchronize Pauli expectation"); + return torch::from_blob(output.data(), {static_cast(output.size())}, + torch::TensorOptions().dtype(torch::kFloat64)) + .clone() + .to(torch::kFloat32) + .to(torch::Device(torch::kCUDA, device_)); + } + std::vector parameter_values(const torch::Tensor& parameters) { + validate_parameters(parameters); + + auto host = parameters.to(torch::kCPU).contiguous(); + const float* ptr = host.data_ptr(); + return std::vector(ptr, ptr + host.numel()); + } + void prepare_initial() { + if (!state_.defined()) + state_ = torch::empty({int64_t{1} << nqubit_}, + torch::TensorOptions().dtype(torch::kComplexFloat).device(torch::kCUDA, device_)); + if (initial_state_.defined()) { + state_.copy_(initial_state_); + return; + } + state_.zero_(); + state_.index({0}).fill_(c10::complex(1, 0)); + } + void run_forward(const torch::Tensor& parameters) { + ready(); + bind_current_stream(); + ++generation_; + state_ready_ = false; + last_parameter_values_ = parameter_values(parameters); + prepare_initial(); + for (const auto& op : ops_) { + if (op.opcode == OpCode::Matrix || op.opcode == OpCode::Permutation) + apply_matrix(state_, op, false); + else if (op.opcode == OpCode::PauliRotation) + apply_rotation(state_, op, + op.parameter_index >= 0 ? -0.5 * op.parameter_scale * last_parameter_values_[op.parameter_index] + : op.angle); + else if (op.opcode == OpCode::Phase) + apply_phase( + state_, op, + op.parameter_index >= 0 ? op.parameter_scale * last_parameter_values_[op.parameter_index] : op.angle); + } + state_ready_ = true; + prepared_generation_ = generation_; + } + void ensure_sampler(uint32_t shots) { + if (resources_.sampler != nullptr) { + if (sampler_max_shots_ >= shots) return; + sampler_max_shots_ = 0; + check_custatevec(custatevecSamplerDestroy(std::exchange(resources_.sampler, nullptr)), + "custatevecSamplerDestroy"); + } + size_t size = 0; + check_custatevec(custatevecSamplerCreate(resources_.handle, state_.data_ptr(), CUDA_C_32F, nqubit_, + &resources_.sampler, shots, &size), + "custatevecSamplerCreate"); + sampler_workspace_ = size ? torch::empty({static_cast(size)}, + torch::TensorOptions().dtype(torch::kUInt8).device(torch::kCUDA, device_)) + : torch::Tensor(); + sampler_workspace_bytes_ = size; + sampler_max_shots_ = shots; + } + void apply_matrix(torch::Tensor& state, const Op& op, bool adjoint) { + if (op.opcode == OpCode::Permutation) { + torch_to_custatevec(); + auto& permutation = op.permutations[adjoint ? 1 : 0]; + check_custatevec(custatevecApplyGeneralizedPermutationMatrix( + resources_.handle, state.data_ptr(), CUDA_C_32F, nqubit_, + op.diagonal_only ? nullptr : const_cast(permutation.data()), + op.permutation_only ? nullptr : op.diagonals[adjoint ? 1 : 0].data(), CUDA_C_32F, 0, + op.targets.data(), op.targets.size(), op.controls.empty() ? nullptr : op.controls.data(), + op.values.empty() ? nullptr : op.values.data(), op.controls.size(), + workspace_bytes_ ? workspace_.data_ptr() : nullptr, workspace_bytes_), + "structured matrix"); + custatevec_to_torch(); + return; + } + + torch_to_custatevec(); + + const auto& matrix = adjoint ? op.inverse_matrix : op.matrix; + check_custatevec(custatevecApplyMatrix(resources_.handle, state.data_ptr(), CUDA_C_32F, nqubit_, matrix.data_ptr(), + CUDA_C_32F, CUSTATEVEC_MATRIX_LAYOUT_ROW, 0, op.targets.data(), + op.targets.size(), op.controls.empty() ? nullptr : op.controls.data(), + op.values.empty() ? nullptr : op.values.data(), op.controls.size(), + CUSTATEVEC_COMPUTE_32F, workspace_bytes_ ? workspace_.data_ptr() : nullptr, + workspace_bytes_), + "custatevecApplyMatrix"); + custatevec_to_torch(); + } + void apply_phase(torch::Tensor& state, const Op& op, double angle) { + c10::complex diagonal[2] = {{1, 0}, {float(std::cos(angle)), float(std::sin(angle))}}; + + torch_to_custatevec(); + check_custatevec(custatevecApplyGeneralizedPermutationMatrix( + resources_.handle, state.data_ptr(), CUDA_C_32F, nqubit_, nullptr, diagonal, CUDA_C_32F, 0, + op.targets.data(), 1, op.controls.empty() ? nullptr : op.controls.data(), + op.values.empty() ? nullptr : op.values.data(), op.controls.size(), + workspace_bytes_ ? workspace_.data_ptr() : nullptr, workspace_bytes_), + "phase diagonal"); + custatevec_to_torch(); + } + void apply_rotation(torch::Tensor& state, const Op& op, double angle) { + torch_to_custatevec(); + std::vector paulis; + for (int pauli : op.paulis) paulis.push_back(static_cast(pauli)); + check_custatevec(custatevecApplyPauliRotation(resources_.handle, state.data_ptr(), CUDA_C_32F, nqubit_, angle, + paulis.data(), op.targets.data(), op.targets.size(), + op.controls.empty() ? nullptr : op.controls.data(), + op.values.empty() ? nullptr : op.values.data(), op.controls.size()), + "custatevecApplyPauliRotation"); + custatevec_to_torch(); + } + void apply_inverse(torch::Tensor& state, const Op& op, double theta) { + if (op.opcode == OpCode::Matrix || op.opcode == OpCode::Permutation) + apply_matrix(state, op, true); + else if (op.opcode == OpCode::PauliRotation) + apply_rotation(state, op, op.parameter_index >= 0 ? 0.5 * op.parameter_scale * theta : -op.angle); + else if (op.opcode == OpCode::Phase) + apply_phase(state, op, -(op.parameter_index >= 0 ? op.parameter_scale * theta : op.angle)); + } + void build_weighted_adjoint_state(const torch::Tensor& weights) { + bind_current_stream(); + if (!adjoint_state_.defined()) adjoint_state_ = torch::empty_like(state_); + adjoint_state_.zero_(); + for (int64_t index = 0; index < weights.numel(); ++index) { + uint64_t x = 0, z = 0; + int num_y = 0; + for (size_t j = 0; j < obs_p_[index].size(); ++j) { + int pauli = obs_p_[index][j], bit = obs_b_[index][j]; + if (pauli == 1 || pauli == 2) x |= uint64_t{1} << bit; + if (pauli == 2 || pauli == 3) z |= uint64_t{1} << bit; + if (pauli == 2) ++num_y; + } + dq_pauli_action(state_.data_ptr(), adjoint_state_.data_ptr(), state_.numel(), x, z, num_y, + weights.data_ptr() + index, current_stream_); + check_cuda(cudaGetLastError(), "adjoint Pauli accumulation"); + } + } + torch::Tensor reverse_prepared(const torch::Tensor& weights, int64_t expected_generation) { + if (!state_ready_ || prepared_generation_ != expected_generation || generation_ != expected_generation) + throw std::runtime_error("prepared adjoint state is stale; execute forward again"); + build_weighted_adjoint_state(weights); + return reverse_from_current_adjoint(expected_generation); + } + torch::Tensor reverse_from_current_adjoint(int64_t expected_generation) { + if (!state_ready_ || prepared_generation_ != expected_generation || generation_ != expected_generation) + throw std::runtime_error("prepared adjoint state is stale; execute forward again"); + bind_current_stream(); + auto gradients = + torch::zeros({parameter_count_}, torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA, device_)); + + // A block-reduction buffer is reused in stream order for all parameter contributions. + auto partial = torch::empty({1024}, gradients.options()); + for (auto iterator = ops_.rbegin(); iterator != ops_.rend(); ++iterator) { + const Op& op = *iterator; + const double theta = op.parameter_index >= 0 ? last_parameter_values_[op.parameter_index] : 0.0; + uint64_t controls = 0; + for (int bit : op.controls) controls |= uint64_t{1} << bit; + if (op.parameter_index >= 0 && op.gradient_kind == GradientKind::Phase) { + // Phase generator: project onto target=1 and the active control sector. + uint64_t projector = controls | (uint64_t{1} << op.targets[0]); + dq_pauli_contract(state_.data_ptr(), adjoint_state_.data_ptr(), partial.data_ptr(), state_.numel(), 0, 0, + 0, projector, current_stream_); + check_cuda(cudaGetLastError(), "phase gradient contraction"); + gradients.index({op.parameter_index}).add_(partial.sum() * (-2.0 * op.parameter_scale)); + } + if (op.parameter_index >= 0 && op.gradient_kind == GradientKind::PauliGenerator) { + uint64_t x = 0, z = 0; + int num_y = 0; + for (size_t j = 0; j < op.paulis.size(); ++j) { + int pauli = op.paulis[j], bit = op.targets[j]; + if (pauli == 1 || pauli == 2) x |= uint64_t{1} << bit; + if (pauli == 2 || pauli == 3) z |= uint64_t{1} << bit; + if (pauli == 2) ++num_y; + } + dq_pauli_contract(state_.data_ptr(), adjoint_state_.data_ptr(), partial.data_ptr(), state_.numel(), x, z, + num_y, controls, current_stream_); + check_cuda(cudaGetLastError(), "Pauli gradient contraction"); + gradients.index({op.parameter_index}).add_(partial.sum() * (-2.0 * op.generator_coeff)); + } + apply_inverse(state_, op, theta); + apply_inverse(adjoint_state_, op, theta); + } + state_ready_ = false; + prepared_generation_ = -1; + ++generation_; + return gradients; + } + + int nqubit_, device_; + NativeResources resources_; + cudaStream_t current_stream_{nullptr}; + bool set_stream_known_unsupported_{false}, custatevec_uses_current_stream_{false}; + torch::Tensor state_, initial_state_, adjoint_state_, workspace_, sampler_workspace_, observable_matrix_; + size_t workspace_bytes_{0}, sampler_workspace_bytes_{0}; + uint32_t sampler_max_shots_{0}; + int parameter_count_{0}; + int64_t generation_{0}, plan_version_{0}, prepared_generation_{-1}; + std::vector last_parameter_values_; + std::vector ops_; + std::vector> obs_p_, obs_b_; + std::vector observable_matrix_bits_; + bool compiled_{false}, closed_{false}, state_ready_{false}; +}; +} // namespace + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, module) { + py::class_(module, "GPUCircuitExecutor") + .def(py::init()) + .def("compile", &GPUCircuitExecutor::compile) + .def("execute", &GPUCircuitExecutor::execute) + .def("forward_expectation", &GPUCircuitExecutor::forward_expectation) + .def("expectation", &GPUCircuitExecutor::expectation) + .def("expectation_from_state", &GPUCircuitExecutor::expectation_from_state) + .def("adjoint_vjp", &GPUCircuitExecutor::adjoint_vjp) + .def("adjoint_vjp_prepared", &GPUCircuitExecutor::adjoint_vjp_prepared) + .def("value_and_grad", &GPUCircuitExecutor::value_and_grad) + + .def("memory_report", &GPUCircuitExecutor::memory_report) + + .def("sample", &GPUCircuitExecutor::sample) + .def("generation", &GPUCircuitExecutor::generation) + .def("plan_version", &GPUCircuitExecutor::plan_version) + .def("close", &GPUCircuitExecutor::close); +} diff --git a/src/deepquantum/custatevec/adjoint_kernels.cu b/src/deepquantum/custatevec/adjoint_kernels.cu new file mode 100644 index 00000000..fec828ae --- /dev/null +++ b/src/deepquantum/custatevec/adjoint_kernels.cu @@ -0,0 +1,57 @@ +// Adjoint-state accumulation and gradient contractions. +// Fuse generator action with reduction to avoid a full temporary statevector. +// Masks use physical LSB indexing. +#include +#include +#include +using Complex = cuFloatComplex; +__device__ Complex pauli_value(const Complex* psi, uint64_t i, uint64_t x, uint64_t z, int ny) { + uint64_t j = i ^ x; + Complex a = psi[j]; + float sign = (__popcll(j & z) & 1) ? -1.f : 1.f; + switch (ny & 3) { + case 1: + return make_cuFloatComplex(-sign * a.y, sign * a.x); + case 2: + return make_cuFloatComplex(-sign * a.x, -sign * a.y); + case 3: + return make_cuFloatComplex(sign * a.y, -sign * a.x); + default: + return make_cuFloatComplex(sign * a.x, sign * a.y); + } +} +__global__ void pauli_action_kernel(const Complex* psi, Complex* out, uint64_t n, uint64_t x, uint64_t z, int ny, + const float* weight) { + for (uint64_t i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += uint64_t(gridDim.x) * blockDim.x) { + Complex a = pauli_value(psi, i, x, z, ny); + float w = *weight; + out[i].x += w * a.x; + out[i].y += w * a.y; + } +} +__global__ void pauli_contraction_kernel(const Complex* psi, const Complex* lambda, float* partial, uint64_t n, + uint64_t x, uint64_t z, int ny, uint64_t control) { + float sum = 0; + for (uint64_t i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += uint64_t(gridDim.x) * blockDim.x) { + if ((i & control) != control) continue; + Complex a = pauli_value(psi, i, x, z, ny), b = lambda[i]; + sum += b.x * a.y - b.y * a.x; // Im ; controls are projectors. + } + __shared__ float sums[256]; + sums[threadIdx.x] = sum; + __syncthreads(); + for (int stride = 128; stride; stride /= 2) { + if (threadIdx.x < stride) sums[threadIdx.x] += sums[threadIdx.x + stride]; + __syncthreads(); + } + if (threadIdx.x == 0) partial[blockIdx.x] = sums[0]; +} +extern "C" void dq_pauli_action(const void* psi, void* out, uint64_t n, uint64_t x, uint64_t z, int ny, const float* w, + cudaStream_t stream) { + pauli_action_kernel<<<1024, 256, 0, stream>>>((const Complex*)psi, (Complex*)out, n, x, z, ny, w); +} +extern "C" void dq_pauli_contract(const void* psi, const void* lambda, float* partial, uint64_t n, uint64_t x, + uint64_t z, int ny, uint64_t control, cudaStream_t stream) { + pauli_contraction_kernel<<<1024, 256, 0, stream>>>((const Complex*)psi, (const Complex*)lambda, partial, n, x, z, ny, + control); +} diff --git a/src/deepquantum/custatevec/circuit.py b/src/deepquantum/custatevec/circuit.py new file mode 100644 index 00000000..cf03fa31 --- /dev/null +++ b/src/deepquantum/custatevec/circuit.py @@ -0,0 +1,430 @@ +"""Compiled single-GPU statevector circuits and adjoint differentiation.""" + +from __future__ import annotations + +from collections import Counter +from contextlib import suppress +from typing import Any + +import torch +from torch import nn + +from ..circuit import QubitCircuit +from ..operation import Gate +from .compiler import CompiledCircuitPlan, compile_circuit, compile_pauli_observables +from .loader import load_gpu_executor, resolve_backend + + +class QubitCircuitGPU(QubitCircuit): + """Compile a pure statevector circuit for one NVIDIA or Iluvatar GPU. + + Gate construction follows :class:`QubitCircuit`. The native executor owns the + returned state storage; call ``clone()`` to retain a state across executions. + Qubit 0 is the most significant statevector bit, as in :class:`QubitCircuit`. + Only expectation values support differentiation, using a first-order adjoint. + + Args: + nqubit: Number of qubits, from 1 to 30, subject to device memory. + init_state: Fixed initial state or ``'zeros'``. It cannot require gradients. + name: Circuit name. + shots: Default number of terminal measurement samples. + device: Fixed CUDA-compatible execution device. Defaults to the current device. + dtype: Statevector precision. Only ``torch.complex64`` is supported. + backend: ``'auto'``, ``'cuquantum'``, or ``'ixquantum'``; selected from the PyTorch build in auto mode. + """ + + def __init__( + self, + nqubit: int, + init_state: Any = 'zeros', + name: str | None = None, + shots: int = 1024, + *, + device: str | torch.device | None = None, + dtype: torch.dtype = torch.complex64, + backend: str = 'auto', + ) -> None: + if not isinstance(nqubit, int) or isinstance(nqubit, bool) or (not 1 <= nqubit <= 30): + raise ValueError('nqubit must be an integer in [1, 30]') + if dtype != torch.complex64: + raise ValueError('QubitCircuitGPU supports torch.complex64 only') + selected = torch.device('cuda' if device is None else device) + if selected.type != 'cuda': + raise ValueError('QubitCircuitGPU requires a CUDA-compatible device') + gpu_backend = resolve_backend(backend) + if not torch.cuda.is_available(): + raise RuntimeError(f'QubitCircuitGPU requires an available GPU for {gpu_backend}') + index = torch.cuda.current_device() if selected.index is None else selected.index + if index >= torch.cuda.device_count(): + raise ValueError(f'CUDA device {index} is not visible') + super().__init__(nqubit=nqubit, init_state=init_state, name=name, shots=shots) + self.gpu_device = torch.device('cuda', index) + self.gpu_backend = gpu_backend + self._compiled_plan: CompiledCircuitPlan | None = None + self._compiled_trainability: tuple[tuple[nn.Parameter, bool], ...] = () + self._executor: Any = None + self._matrix_observable: tuple[torch.Tensor, tuple[int, ...]] | None = None + self._plan_dirty = True + + def set_init_state(self, init_state: Any) -> None: + """Set a fixed initial state, allocating the zero state only on execution.""" + self._compiled_zero_initial = isinstance(init_state, str) and init_state == 'zeros' + if self._compiled_zero_initial: + self.init_state = _ZeroState(self.nqubit) + else: + super().set_init_state(init_state) + if self.init_state.state.requires_grad: + raise ValueError('QubitCircuitGPU does not support differentiable initial states') + self._plan_dirty = True + self.state = None + + def add(self, *args: Any, **kwargs: Any) -> Any: + result = super().add(*args, **kwargs) + self.invalidate() + return result + + def multirz(self, wires: list[int], inputs: Any = None, controls: int | list[int] | None = None) -> None: + """Add a multi-qubit Z Pauli rotation.""" + wire_list = list(wires) + if not wire_list: + raise ValueError('MultiRZ requires at least one target wire') + self.add( + MultiRZ(inputs=inputs, nqubit=self.nqubit, wires=wire_list, controls=controls, requires_grad=inputs is None) + ) + + def reset_circuit(self, init_state: Any = 'zeros') -> None: + """Reset gates, observables, and the compiled state.""" + super().reset_circuit(init_state) + self._matrix_observable = None + self.invalidate() + + def __add__(self, rhs: Any) -> QubitCircuitGPU: + raise NotImplementedError('QubitCircuitGPU does not support circuit addition; add gates to one circuit') + + def inverse(self, encode: bool = False) -> QubitCircuitGPU: + """Reject whole-circuit inversion; individual inverse gates are supported.""" + raise NotImplementedError('QubitCircuitGPU does not support circuit inverse(); add individual inverse gates') + + def compile(self) -> QubitCircuitGPU: + """Compile the circuit structure; parameter values remain dynamic.""" + plan = compile_circuit(self) + self.invalidate() + self._ensure_executor_resources() + self._executor.compile( + plan.opcodes.tolist(), + [list(x) for x in plan.targets], + [list(x) for x in plan.controls], + [None if x is None else x.to(self.gpu_device) for x in plan.matrices], + [list(x) for x in plan.permutations], + [list(x) for x in plan.diagonals], + plan.angles.tolist(), + [list(x) for x in plan.paulis], + plan.parameter_indices.tolist(), + plan.parameter_scales.tolist(), + plan.gradient_kinds.tolist(), + plan.generator_coeffs.tolist(), + [list(x) for x in plan.observable_paulis], + [list(x) for x in plan.observable_bits], + None if plan.observable_matrix is None else plan.observable_matrix.to(self.gpu_device), + list(plan.observable_matrix_bits), + None + if self._compiled_zero_initial + else self.init_state.state.reshape(-1) + .detach() + .to(device=self.gpu_device, dtype=torch.complex64) + .contiguous(), + ) + self._compiled_plan = plan + self._compiled_trainability = tuple((parameter, parameter.requires_grad) for parameter in self.parameters()) + self._plan_dirty = False + self.state = None + return self + + def invalidate(self) -> None: + """Mark compiled Python gate structure or fixed data changed; the next call recompiles.""" + self._plan_dirty = True + self.state = None + + def close(self) -> None: + """Release native resources and invalidate the state, including on cleanup errors.""" + if getattr(self, '_executor', None) is not None: + try: + self._executor.close() + finally: + self._executor = None + self.invalidate() + + def memory_report(self) -> dict[str, Any]: + """Report statevector requirements and current native allocations.""" + result = {'one_state_bytes': 8 * (1 << self.nqubit)} + if self._executor is not None: + result.update(dict(self._executor.memory_report())) + return result + + def observable(self, *args: Any, **kwargs: Any) -> None: + super().observable(*args, **kwargs) + self.invalidate() + + def observable_matrix(self, matrix: torch.Tensor, wires: int | list[int]) -> None: + """Register one fixed Hermitian matrix observable for exact expectation. + + Matrix expectations are non-differentiable and cannot be combined with + Pauli ``observable()`` entries. + """ + if self.observables: + raise ValueError('observable_matrix() cannot be mixed with Pauli observable()') + if self._matrix_observable is not None: + raise ValueError('QubitCircuitGPU supports exactly one observable_matrix()') + wire_list = [wires] if isinstance(wires, int) else list(wires) + self._matrix_observable = (matrix, tuple(int(wire) for wire in wire_list)) + self.invalidate() + + def reset_observable(self) -> None: + super().reset_observable() + self._matrix_observable = None + self.invalidate() + + def forward(self, data: torch.Tensor | None = None, state: Any = None) -> torch.Tensor: + """Execute the circuit and return a borrowed ``(2**nqubit, 1)`` state tensor. + + Runtime data encoding and external forward states are unsupported. Use + ``expectation()`` for differentiable results using adjoint gradients. + """ + if data is not None or state is not None: + raise ValueError('QubitCircuitGPU accepts neither runtime data nor an external forward state') + self._ensure_compiled() + self.state = self._executor.execute(self._parameter_tensor()).reshape(-1, 1) + return self.state + + def measure( + self, + shots: int | None = None, + with_prob: bool = False, + wires: int | list[int] | None = None, + block_size: int = 2**24, + ) -> dict[str, int] | None: + """Sample the terminal state without state collapse.""" + del block_size + if with_prob: + raise ValueError('QubitCircuitGPU sampling supports with_prob=False only') + if self.state is None: + return None + shots = self.shots if shots is None else int(shots) + if shots <= 0: + raise ValueError('shots must be positive') + selected_wires = list(range(self.nqubit)) if wires is None else wires + self.wires_measure = self._convert_indices(selected_wires) + bit_ordering = [self.nqubit - wire - 1 for wire in reversed(sorted(self.wires_measure))] + randnums = torch.rand(shots, dtype=torch.float64, device='cpu') + sampled = self._executor.sample(shots, bit_ordering, randnums) + self.shots = shots + return { + format(int(value), f'0{len(self.wires_measure)}b'): int(count) + for value, count in Counter(sampled.tolist()).items() + } + + def expectation(self, shots: int | None = None, *, parameters: torch.Tensor | None = None) -> torch.Tensor: + """Evaluate terminal observables, automatically using adjoint gradients. + + When gradients are enabled and parameters require gradients, run a forward + pass and attach the adjoint backward. Otherwise read the existing state. + Explicit parameters are a packed CUDA float32 vector in first-use order, + with one entry per distinct trainable scalar. Explicit parameters always + trigger a new forward pass, including inside ``torch.no_grad()``. + """ + if shots is not None: + raise ValueError('QubitCircuitGPU supports exact expectation only (shots=None)') + self._ensure_compiled() + if not self._compiled_plan.observable_paulis and self._compiled_plan.observable_matrix is None: + raise ValueError('There is no compiled observable') + values = self._resolve_parameters(parameters) + if torch.is_grad_enabled() and values.requires_grad: + if not self._compiled_plan.observable_paulis or self._compiled_plan.observable_matrix is not None: + raise ValueError('adjoint requires one or more terminal Pauli observables') + self.state = None + return _GPUAdjointExpectation.apply(values, self) + if parameters is not None: + self.state = self._executor.execute(values.detach()).reshape(-1, 1) + return self._executor.expectation() + + def expectation_from_state(self, state: torch.Tensor, observables: list[Any]) -> torch.Tensor: + """Evaluate Pauli observables on an existing CUDA state. + + This non-differentiable readout borrows the state for the duration of the + call. Gate compilation and execution are skipped. + """ + if not isinstance(state, torch.Tensor): + raise TypeError('state must be a torch.Tensor') + if state.device.type != 'cuda': + raise ValueError('state must be a CUDA tensor') + if state.device != self.gpu_device: + raise ValueError(f'state must be on the circuit device {self.gpu_device}') + if state.dtype != torch.complex64: + raise TypeError('state must use torch.complex64') + if state.requires_grad: + raise ValueError('expectation_from_state is non-differentiable; state.requires_grad must be False') + dimension = 1 << self.nqubit + if tuple(state.shape) not in {(dimension,), (dimension, 1)}: + raise ValueError(f'state must have shape ({dimension},) or ({dimension}, 1)') + if not state.is_contiguous(): + raise ValueError('state must be contiguous') + try: + observable_list = list(observables) + except TypeError as exc: + raise TypeError('observables must be an iterable of DeepQuantum Pauli observables') from exc + paulis, bits = compile_pauli_observables(self.nqubit, observable_list) + self._ensure_executor_resources() + with torch.no_grad(): + return self._executor.expectation_from_state( + state.reshape(-1), [list(value) for value in paulis], [list(value) for value in bits] + ) + + def adjoint_vjp(self, parameters: torch.Tensor | None, coefficients: torch.Tensor) -> torch.Tensor: + """Compute the adjoint gradient of a weighted Pauli expectation.""" + self._ensure_compiled() + if not self._compiled_plan.observable_paulis: + raise ValueError('adjoint requires one or more terminal Pauli observables') + values = self._resolve_parameters(parameters) + weights = coefficients.to(self.gpu_device, torch.float32).reshape(-1).contiguous() + self.state = None + return self._executor.adjoint_vjp(values.detach(), weights) + + def value_and_grad( + self, parameters: torch.Tensor | None, coefficients: torch.Tensor, constant: float = 0.0 + ) -> tuple[torch.Tensor, torch.Tensor]: + """Compute weighted expectation value and adjoint gradient with one forward.""" + self._ensure_compiled() + if not self._compiled_plan.observable_paulis: + raise ValueError('adjoint requires one or more terminal Pauli observables') + values = self._resolve_parameters(parameters) + weights = coefficients.to(self.gpu_device, torch.float32).reshape(-1).contiguous() + self.state = None + return self._executor.value_and_grad(values.detach(), weights, float(constant)) + + def _ensure_executor_resources(self) -> None: + """Create the native executor on first use.""" + if self._executor is None: + module = load_gpu_executor(self.gpu_backend) + self._executor = module.GPUCircuitExecutor(self.nqubit, self.gpu_device.index or 0) + + def _ensure_compiled(self) -> None: + if self._plan_dirty or self._compiled_plan is None or self._executor is None or self._trainability_changed(): + self.compile() + + def _trainability_changed(self) -> bool: + return any(parameter.requires_grad != flag for parameter, flag in self._compiled_trainability) + + def _parameter_tensor(self) -> torch.Tensor: + """Pack dynamic values once per execution while preserving autograd edges.""" + if not self._compiled_plan or not self._compiled_plan.parameter_sources: + return torch.empty(0, dtype=torch.float32, device=self.gpu_device) + values = [ + value.reshape(()).to(dtype=torch.float32, device=self.gpu_device) + for value in self._compiled_plan.parameter_sources + ] + return torch.stack(values).contiguous() + + def _resolve_parameters(self, parameters: torch.Tensor | None) -> torch.Tensor: + """Return the packed logical parameter vector used by the native plan.""" + if parameters is None: + return self._parameter_tensor() + if not isinstance(parameters, torch.Tensor): + raise TypeError('parameters must be a torch.Tensor') + if parameters.device != self.gpu_device: + raise ValueError(f'parameters must be on {self.gpu_device}') + if parameters.dtype != torch.float32: + raise TypeError('parameters must use torch.float32') + if parameters.ndim != 1 or not parameters.is_contiguous(): + raise ValueError('parameters must be a contiguous one-dimensional tensor') + expected = len(self._compiled_plan.parameter_sources) if self._compiled_plan else 0 + if parameters.numel() != expected: + raise ValueError(f'expected {expected} logical parameters, got {parameters.numel()}') + return parameters + + def _apply(self, fn: Any) -> QubitCircuitGPU: + probe = fn(torch.empty(0, device=self.gpu_device)) + if probe.device != self.gpu_device: + raise ValueError('QubitCircuitGPU execution device is fixed; construct a new circuit on the desired device') + self.invalidate() + return super()._apply(fn) + + def _load_from_state_dict(self, *args: Any, **kwargs: Any) -> None: + # This hook also runs when a parent module loads the circuit's checkpoint. + self.invalidate() + super()._load_from_state_dict(*args, **kwargs) + + def __del__(self) -> None: + with suppress(Exception): + self.close() + + +class _GPUAdjointExpectation(torch.autograd.Function): + """Bridge native adjoint gradients to PyTorch autograd.""" + + @staticmethod + def forward(ctx: Any, parameters: torch.Tensor, circuit: QubitCircuitGPU) -> torch.Tensor: + ctx.circuit = circuit + ctx.executor = circuit._executor + ctx.plan_version = ctx.executor.plan_version() + ctx.save_for_backward(parameters) + result = ctx.executor.forward_expectation(parameters.detach()) + ctx.generation = ctx.executor.generation() + return result + + @staticmethod + @torch.autograd.function.once_differentiable + def backward(ctx: Any, grad_output: torch.Tensor) -> tuple[torch.Tensor, None]: + circuit = ctx.circuit + if ( + circuit._executor is not ctx.executor + or circuit._plan_dirty + or circuit._trainability_changed() + or ctx.executor.plan_version() != ctx.plan_version + ): + raise RuntimeError('single-GPU circuit changed or closed before backward') + (parameters,) = ctx.saved_tensors + weights = grad_output.to(device=parameters.device, dtype=torch.float32).reshape(-1).contiguous() + try: + gradient = ctx.executor.adjoint_vjp_prepared(parameters.detach(), weights, ctx.generation) + return (gradient, None) + finally: + circuit.state = None + + +class _ZeroState(nn.Module): + """Store zero-state metadata until GPU allocation.""" + + _compiled_zero_state = True + + def __init__(self, nqubit: int) -> None: + super().__init__() + self.nqubit = nqubit + self.den_mat = False + + +class MultiRZ(Gate): + """Describe exp(-i theta Z...Z / 2) by its angle and wires.""" + + def __init__( + self, *, inputs: Any, nqubit: int, wires: list[int], controls: int | list[int] | None, requires_grad: bool + ) -> None: + super().__init__(name='MultiRZ', nqubit=nqubit, wires=wires, controls=controls) + if inputs is None: + inputs = torch.rand((), dtype=torch.float32) * (4 * torch.pi) + elif not isinstance(inputs, torch.Tensor): + inputs = torch.tensor(inputs, dtype=torch.float32) + if inputs.numel() != 1: + raise ValueError('MultiRZ inputs must be one scalar') + self.npara = 1 + self.inv_mode = False + if requires_grad: + self.theta = nn.Parameter(inputs.reshape(())) + else: + self.register_buffer('theta', inputs.reshape(())) + + def inverse(self) -> MultiRZ: + from copy import copy + + gate = copy(self) + gate.inv_mode = not self.inv_mode + return gate diff --git a/src/deepquantum/custatevec/compiler.py b/src/deepquantum/custatevec/compiler.py new file mode 100644 index 00000000..e70b0083 --- /dev/null +++ b/src/deepquantum/custatevec/compiler.py @@ -0,0 +1,314 @@ +"""Compile DeepQuantum gates into shared cuStateVec execution plans.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +import numpy as np +import torch + +from ..gate import Barrier + +OP_MATRIX = 0 +OP_PAULI_ROTATION = 1 +OP_PHASE = 2 +OP_PERMUTATION = 3 +GRAD_NONE = 0 +GRAD_PAULI_GENERATOR = 1 +GRAD_PHASE = 2 +# Pauli labels match custatevecPauli_t: X=1, Y=2, Z=3. +_PAULI = { + 'Rx': (1,), + 'Ry': (2,), + 'Rz': (3,), + 'Rxx': (1, 1), + 'Ryy': (2, 2), + 'Rzz': (3, 3), + 'MultiRZ': None, +} + + +@dataclass(frozen=True) +class CompiledCircuitPlan: + """Host-side circuit plan consumed in one call by the native executor.""" + + nqubit: int + opcodes: np.ndarray + targets: tuple[tuple[int, ...], ...] + controls: tuple[tuple[int, ...], ...] + matrices: tuple[torch.Tensor | None, ...] + permutations: tuple[tuple[int, ...], ...] + diagonals: tuple[tuple[complex, ...], ...] + angles: np.ndarray + paulis: tuple[tuple[int, ...], ...] + parameter_indices: np.ndarray + parameter_scales: np.ndarray + gradient_kinds: np.ndarray + generator_coeffs: np.ndarray + parameter_sources: tuple[torch.Tensor, ...] + observable_paulis: tuple[tuple[int, ...], ...] + observable_bits: tuple[tuple[int, ...], ...] + observable_matrix: torch.Tensor | None + observable_matrix_bits: tuple[int, ...] + + +def _error(index: int, gate: Any, message: str) -> ValueError: + return ValueError(f'QubitCircuitGPU compile rejected gate #{index} ({type(gate).__name__}): {message}') + + +def _static_matrix(gate: Any, index: int) -> torch.Tensor: + if any(parameter.requires_grad for parameter in gate.parameters()): + raise _error(index, gate, 'trainable parameters are unsupported for generic matrix gates') + try: + matrix = gate.update_matrix() + except Exception as exc: # pragma: no cover - third-party gate subclasses. + raise _error(index, gate, f'cannot materialize a fixed matrix: {exc}') from exc + if not isinstance(matrix, torch.Tensor): + raise _error(index, gate, 'matrix is not a torch.Tensor') + if matrix.requires_grad: + raise _error(index, gate, 'matrix requires grad') + return matrix.detach().to(dtype=torch.complex64, device='cpu').contiguous() + + +def _custatevec_bits(nqubit: int, wires: tuple[int, ...]) -> tuple[int, ...]: + # DQ wire 0 is tensor/MSB; custatevec bit 0 is LSB. For a multi-target + # matrix DQ's first wire is the matrix MSB axis, so reverse target axes too. + return tuple(reversed([nqubit - wire - 1 for wire in wires])) + + +def compile_pauli_observables( + nqubit: int, observables: list[Any] | tuple[Any, ...] +) -> tuple[tuple[tuple[int, ...], ...], tuple[tuple[int, ...], ...]]: + """Validate DQ Pauli observables and map wire-0-as-MSB to cuStateVec bits.""" + mapping = {'x': 1, 'y': 2, 'z': 3} + paulis: list[tuple[int, ...]] = [] + bits: list[tuple[int, ...]] = [] + for index, observable in enumerate(observables): + try: + wires = tuple(wire[0] if isinstance(wire, list) else wire for wire in observable.wires) + basis = tuple(observable.basis) + if len(wires) != len(basis) or not wires: + raise ValueError('observable must contain one non-empty Pauli basis string') + normalized_wires = tuple(int(wire) for wire in wires) + if len(set(normalized_wires)) != len(normalized_wires) or any( + wire < 0 or wire >= nqubit for wire in normalized_wires + ): + raise ValueError('observable wires must be unique circuit wires') + paulis.append(tuple(mapping[item.lower()] for item in basis)) + bits.append(tuple(nqubit - wire - 1 for wire in normalized_wires)) + except (AttributeError, KeyError, TypeError, ValueError) as exc: + raise ValueError(f'QubitCircuitGPU rejected observable #{index}: Pauli strings only ({exc})') from exc + if not paulis: + raise ValueError('at least one Pauli observable is required') + return tuple(paulis), tuple(bits) + + +def _compile_observables( + circuit: Any, +) -> tuple[tuple[tuple[int, ...], ...], tuple[tuple[int, ...], ...], torch.Tensor | None, tuple[int, ...]]: + matrix_observable = getattr(circuit, '_matrix_observable', None) + if matrix_observable is not None: + if circuit.observables: + raise ValueError('QubitCircuitGPU cannot mix Pauli observables with observable_matrix()') + matrix, wires = matrix_observable + wires = tuple(int(wire) for wire in wires) + if not wires or len(set(wires)) != len(wires) or any(wire < 0 or wire >= circuit.nqubit for wire in wires): + raise ValueError('observable_matrix wires must be non-empty, unique circuit wires') + if not isinstance(matrix, torch.Tensor) or matrix.requires_grad: + raise ValueError('observable_matrix requires a fixed torch.Tensor') + dim = 1 << len(wires) + matrix = matrix.detach().to(dtype=torch.complex64, device='cpu').contiguous() + if matrix.shape != (dim, dim): + raise ValueError(f'observable_matrix expected a {dim}x{dim} matrix, got {tuple(matrix.shape)}') + if not torch.allclose(matrix, matrix.mH, atol=1e-5, rtol=1e-5): + raise ValueError('observable_matrix must be Hermitian') + # ixquantum 1.8.0 interprets basis bits in ascending order. Reorder both + # matrix axes at compile time to preserve the caller's wire order. + ordered_wires = tuple(sorted(wires)) + if wires != ordered_wires: + count = len(wires) + axes = tuple(wires.index(wire) for wire in ordered_wires) + matrix = matrix.reshape((2,) * (2 * count)).permute(axes + tuple(axis + count for axis in axes)) + matrix = matrix.reshape(dim, dim).contiguous() + return (), (), matrix, _custatevec_bits(circuit.nqubit, ordered_wires) + + if not circuit.observables: + return (), (), None, () + paulis, bits = compile_pauli_observables(circuit.nqubit, tuple(circuit.observables)) + return paulis, bits, None, () + + +def compile_circuit(circuit: Any) -> CompiledCircuitPlan: + """Compile a single-statevector circuit; scalar Pauli angles remain dynamic plan inputs.""" + if circuit.den_mat or circuit.mps: + raise ValueError('QubitCircuitGPU supports pure statevectors only (den_mat=False, mps=False)') + if circuit.reupload or circuit.ndata or circuit.encoders: + raise ValueError('QubitCircuitGPU does not yet support data encoding/reupload') + zero_initial = getattr(circuit.init_state, '_compiled_zero_state', False) + if not zero_initial and getattr(circuit.init_state, 'state', None) is None: + raise ValueError('QubitCircuitGPU requires init_state="zeros"') + if not zero_initial: + initial = circuit.init_state.state.reshape(-1) + if initial.numel() != 1 << circuit.nqubit or initial.dtype not in (torch.complex64, torch.complex128): + raise ValueError('QubitCircuitGPU initial state must be one pure complex statevector') + if initial.requires_grad or not torch.isfinite(initial).all() or initial.norm() == 0: + raise ValueError('QubitCircuitGPU initial state must be finite, nonzero, and non-differentiable') + + opcodes: list[int] = [] + targets: list[tuple[int, ...]] = [] + controls: list[tuple[int, ...]] = [] + matrices: list[torch.Tensor | None] = [] + angles: list[float] = [] + paulis: list[tuple[int, ...]] = [] + parameter_indices: list[int] = [] + parameter_scales: list[float] = [] + parameter_sources: list[torch.Tensor] = [] + # Distinct autograd leaves can share storage. Only merge the same object. + parameter_slots: dict[int, int] = {} + gradient_kinds: list[int] = [] + generator_coeffs: list[float] = [] + + for index, gate in enumerate(circuit.operators): + if type(gate) is Barrier: + continue + if getattr(gate, 'den_mat', False) or getattr(gate, 'condition', False): + raise _error(index, gate, 'density-matrix and conditional operations are unsupported') + wires = tuple(int(wire) for wire in getattr(gate, 'wires', [])) + gate_controls = tuple(int(wire) for wire in getattr(gate, 'controls', [])) + if not wires or len(set(wires)) != len(wires) or any(wire < 0 or wire >= circuit.nqubit for wire in wires): + raise _error(index, gate, 'targets must be non-empty, unique circuit wires') + if len(set(gate_controls)) != len(gate_controls) or any( + wire < 0 or wire >= circuit.nqubit for wire in gate_controls + ): + raise _error(index, gate, 'controls must be unique circuit wires') + if set(wires) & set(gate_controls): + raise _error(index, gate, 'targets and controls must be disjoint') + target_bits = _custatevec_bits(circuit.nqubit, wires) + control_bits = tuple(circuit.nqubit - wire - 1 for wire in gate_controls) + name = type(gate).__name__ + + if name == 'PhaseShift': + theta = gate.theta + scale = -1.0 if gate.inv_mode else 1.0 + opcodes.append(OP_PHASE) + targets.append(target_bits) + controls.append(control_bits) + matrices.append(None) + paulis.append(()) + parameter_scales.append(scale) + generator_coeffs.append(scale) + if theta.requires_grad: + key = id(theta) + if key not in parameter_slots: + parameter_slots[key] = len(parameter_sources) + parameter_sources.append(theta) + parameter_indices.append(parameter_slots[key]) + angles.append(0.0) + gradient_kinds.append(GRAD_PHASE) + else: + parameter_indices.append(-1) + angles.append(float(theta.detach().cpu()) * scale) + gradient_kinds.append(GRAD_NONE) + continue + + if name in _PAULI or name == 'Rxy': + theta = getattr(gate, 'theta', None) + if not isinstance(theta, torch.Tensor) or theta.numel() != 1: + raise _error(index, gate, 'rotation angle must be one scalar tensor') + labels = (3,) * len(wires) if name == 'MultiRZ' else _PAULI.get(name, (1, 1)) + if len(wires) != len(labels): + raise _error(index, gate, f'{name} has an invalid target count') + scale = -1.0 if getattr(gate, 'inv_mode', False) else 1.0 + # DQ Rxy is an exchange rotation: Rxx(theta/2) Ryy(theta/2). + # Both commuting rotations share the original scalar parameter. + groups = ((1, 1), (2, 2)) if name == 'Rxy' else (labels,) + if name == 'Rxy': + scale *= 0.5 + for labels in groups: + opcodes.append(OP_PAULI_ROTATION) + targets.append(target_bits) + controls.append(control_bits) + matrices.append(None) + if theta.requires_grad: + key = id(theta) + if key not in parameter_slots: + parameter_slots[key] = len(parameter_sources) + parameter_sources.append(theta) + parameter_indices.append(parameter_slots[key]) + angles.append(0.0) + gradient_kinds.append(GRAD_PAULI_GENERATOR) + generator_coeffs.append(-0.5 * scale) + else: + parameter_indices.append(-1) + angles.append(float(-0.5 * scale * theta.detach().cpu())) + gradient_kinds.append(GRAD_NONE) + generator_coeffs.append(0.0) + paulis.append(tuple(reversed(labels))) + parameter_scales.append(scale) + continue + + if name == 'Identity': + continue + if name in ('CNOT', 'Toffoli', 'Fredkin'): + control_count = 2 if name == 'Toffoli' else 1 + control_bits = (*control_bits, *(circuit.nqubit - w - 1 for w in wires[:control_count])) + wires = wires[control_count:] + target_bits = _custatevec_bits(circuit.nqubit, wires) + if name == 'Fredkin': + matrix = torch.eye(4, dtype=torch.complex64)[[0, 2, 1, 3]] + else: + matrix = torch.tensor([[0, 1], [1, 0]], dtype=torch.complex64) + else: + matrix = _static_matrix(gate, index) + dim = 1 << len(wires) + if matrix.shape != (dim, dim): + raise _error(index, gate, f'expected a {dim}x{dim} matrix, got {tuple(matrix.shape)}') + opcodes.append(OP_MATRIX) + targets.append(target_bits) + controls.append(control_bits) + matrices.append(matrix) + angles.append(0.0) + paulis.append(()) + parameter_indices.append(-1) + parameter_scales.append(1.0) + gradient_kinds.append(GRAD_NONE) + generator_coeffs.append(0.0) + + permutations = [] + diagonals = [] + for i, matrix in enumerate(matrices): + permutation = () + diagonal = () + if matrix is not None: + nonzero = matrix != 0 + if (nonzero.sum(0) == 1).all() and (nonzero.sum(1) == 1).all(): + columns = nonzero.to(torch.int64).argmax(1) + permutation = tuple(columns.tolist()) + diagonal = tuple(matrix[torch.arange(len(columns)), columns].tolist()) + opcodes[i] = OP_PERMUTATION + matrices[i] = None + permutations.append(permutation) + diagonals.append(diagonal) + + observable_paulis, observable_bits, observable_matrix, observable_matrix_bits = _compile_observables(circuit) + return CompiledCircuitPlan( + nqubit=circuit.nqubit, + opcodes=np.asarray(opcodes, dtype=np.int32), + targets=tuple(targets), + controls=tuple(controls), + matrices=tuple(matrices), + permutations=tuple(permutations), + diagonals=tuple(diagonals), + angles=np.asarray(angles, dtype=np.float64), + paulis=tuple(paulis), + parameter_indices=np.asarray(parameter_indices, dtype=np.int32), + parameter_scales=np.asarray(parameter_scales, dtype=np.float64), + gradient_kinds=np.asarray(gradient_kinds, dtype=np.int32), + generator_coeffs=np.asarray(generator_coeffs, dtype=np.float64), + parameter_sources=tuple(parameter_sources), + observable_paulis=observable_paulis, + observable_bits=observable_bits, + observable_matrix=observable_matrix, + observable_matrix_bits=observable_matrix_bits, + ) diff --git a/src/deepquantum/custatevec/loader.py b/src/deepquantum/custatevec/loader.py new file mode 100644 index 00000000..e80b9f92 --- /dev/null +++ b/src/deepquantum/custatevec/loader.py @@ -0,0 +1,106 @@ +"""Build the shared cuStateVec executor for NVIDIA CUDA or Iluvatar CoreX.""" + +import os +import sys +from pathlib import Path +from types import ModuleType + + +def resolve_backend(backend: str = 'auto') -> str: + """Select a backend once from the installed PyTorch build, without SDK fallback.""" + import torch + + if backend not in ('auto', 'cuquantum', 'ixquantum'): + raise ValueError('backend must be auto, cuquantum, or ixquantum') + corex = bool(getattr(torch, 'corex', False)) + selected = ('ixquantum' if corex else 'cuquantum') if backend == 'auto' else backend + if selected == 'ixquantum' and not corex: + raise RuntimeError('Install CoreX-enabled PyTorch to use the ixquantum backend') + if selected == 'cuquantum' and (corex or not torch.version.cuda): + raise RuntimeError('Install NVIDIA CUDA-enabled PyTorch to use the cuquantum backend') + return selected + + +def resolve_sdk(backend: str) -> tuple[Path, Path]: + """Find the cuStateVec header and shared library for the selected backend. + + cuQuantum uses ``CUQUANTUM_ROOT`` or the installed cuStateVec wheel. + ixquantum uses ``IXQUANTUM_ROOT`` (default ``/usr/local/corex``), accepting + either a flat SDK or conventional ``include`` and ``lib``/``lib64`` directories. + """ + if backend == 'cuquantum': + roots = ( + [Path(os.environ['CUQUANTUM_ROOT']).expanduser()] + if 'CUQUANTUM_ROOT' in os.environ + else [Path(p) / sub for p in sys.path for sub in ('cuquantum', 'nvidia/custatevec')] + ) + for root in roots: + include = root / 'include' + if not (include / 'custatevec.h').is_file(): + continue + for directory in (root / 'lib', root / 'lib64'): + for name in ('libcustatevec.so', 'libcustatevec.so.1'): + library = directory / name + if library.is_file(): + return include.resolve(), library.resolve() + libraries = sorted(directory.glob('libcustatevec.so.*')) + if libraries: + return include.resolve(), libraries[0].resolve() + raise RuntimeError( + 'cuQuantum SDK not found. Install custatevec-cu12 or set CUQUANTUM_ROOT (include/ and lib/).' + ) + if backend != 'ixquantum': + raise ValueError('SDK backend must be cuquantum or ixquantum') + root = Path(os.environ.get('IXQUANTUM_ROOT', '/usr/local/corex')).expanduser() + header = next((p for p in (root / 'include/custatevec.h', root / 'custatevec.h') if p.is_file()), None) + library = next( + ( + directory / 'libcustatevec.so.1.8.0' + for directory in (root / 'lib64', root / 'lib', root) + if (directory / 'libcustatevec.so.1.8.0').is_file() + ), + None, + ) + if header is None or library is None: + raise RuntimeError( + f'ixquantum 1.8.0 SDK not found under {root}. Set IXQUANTUM_ROOT to a directory containing ' + 'custatevec.h and libcustatevec.so.1.8.0, available from Iluvatar (天数).' + ) + return header.resolve().parent, library.resolve() + + +def load_gpu_executor(backend: str = 'auto') -> ModuleType: + """Build on first use and reuse PyTorch's extension cache thereafter. + + PyTorch's extension builder configures the compilers, architecture, and ABI. + CoreX-specific device compiler flags are applied only for ixquantum. + """ + backend = resolve_backend(backend) + include, library = resolve_sdk(backend) + try: + from torch.utils.cpp_extension import load + except ImportError as exc: + raise RuntimeError(f'Install the DeepQuantum build extra: pip install "deepquantum[{backend}]"') from exc + source = Path(__file__).parent + try: + return load( + name=f'deepquantum_gpu_executor_{backend}', + sources=[str(source / '_gpu_executor.cpp'), str(source / 'adjoint_kernels.cu')], + extra_include_paths=[str(include)], + extra_cflags=['-O3', '-std=c++17'], + extra_cuda_cflags=['-O3', '-std=c++17'] + (['-x', 'ivcore'] if backend == 'ixquantum' else []), + extra_ldflags=[str(library), f'-Wl,-rpath,{library.parent}'], + with_cuda=True, + verbose=False, + ) + except (OSError, RuntimeError) as exc: + raise RuntimeError( + f'Could not build/load the {backend} executor. Install deepquantum[{backend}], a compatible ' + 'development toolkit (compiler, headers and runtime libraries), and matching PyTorch. ' + 'See the original build error below.' + ) from exc + + +def load_ixquantum_executor() -> ModuleType: + """Preserve the original explicit ixquantum loader entry point.""" + return load_gpu_executor('ixquantum') diff --git a/tests/test_circuit_gpu.py b/tests/test_circuit_gpu.py new file mode 100644 index 00000000..7b5e6a3d --- /dev/null +++ b/tests/test_circuit_gpu.py @@ -0,0 +1,541 @@ +"""Numerical comparisons for the optional single-GPU cuStateVec executor.""" + +import math +import os +from pathlib import Path + +import pytest +import torch + +import deepquantum as dq +from deepquantum.custatevec.loader import resolve_backend, resolve_sdk + + +@pytest.fixture(scope='module', autouse=True) +def gpu_backend(): + requested = os.environ.get('DQ_GPU_BACKEND', 'auto') + try: + if not torch.cuda.is_available(): + raise RuntimeError('requires CUDA/CoreX PyTorch and an available GPU') + backend = resolve_backend(requested) + resolve_sdk(backend) + from torch.utils.cpp_extension import verify_ninja_availability + + verify_ninja_availability() + if backend == 'cuquantum': + from torch.utils.cpp_extension import CUDA_HOME + + if CUDA_HOME is None or not (Path(CUDA_HOME) / 'bin' / 'nvcc').is_file(): + raise RuntimeError('requires a CUDA toolkit with nvcc; set CUDA_HOME') + except (ImportError, RuntimeError) as exc: + if requested != 'auto': + pytest.fail(f'{requested} test prerequisites: {exc}', pytrace=False) + pytest.skip(str(exc)) + return backend + + +@pytest.fixture +def gpu(gpu_backend): + torch.cuda.set_device(os.environ.get('DQ_GPU_DEVICE', 'cuda:0')) + circuits = [] + + def create(nqubit, **kwargs): + circuit = dq.QubitCircuitGPU(nqubit, backend=gpu_backend, **kwargs) + circuits.append(circuit) + return circuit + + yield create + for circuit in circuits: + circuit.close() + + +def add_gates(circuit): + circuit.h(0) + circuit.rx(1, inputs=0.23) + circuit.ry(2, inputs=-0.41) + circuit.rz(0, inputs=0.61) + circuit.cnot(0, 3) + circuit.cy(3, 1) + circuit.cz(1, 2) + circuit.cp(0, 2, inputs=0.37) + circuit.swap([0, 3]) + circuit.iswap([1, 2]) + circuit.rzz([1, 3], inputs=0.21) + circuit.observable([0, 2], 'xy') + circuit.observable(3, 'z') + + +@pytest.mark.parametrize('random_initial', [False, True]) +def test_forward_expectations(gpu, random_initial): + generator = torch.Generator().manual_seed(123) + initial = torch.randn(16, dtype=torch.complex64, generator=generator) + initial /= initial.norm() + initial = initial if random_initial else 'zeros' + actual = gpu(4, init_state=initial) + expected = dq.QubitCircuit(4, init_state=initial) + add_gates(actual) + add_gates(expected) + expected.double() + torch.testing.assert_close(actual().cpu().to(torch.complex128), expected(), atol=2e-5, rtol=2e-4) + torch.testing.assert_close(actual.expectation().cpu().double(), expected.expectation(), atol=3e-5, rtol=3e-4) + external = actual.expectation_from_state(actual.state, list(actual.observables)) + torch.testing.assert_close(external, actual.expectation()) + + +def add_trainable_gates(circuit): + circuit.h(0) + circuit.rx(1) + circuit.ry(2, controls=0) + circuit.rzz([0, 3]) + circuit.cp(3, 2) + circuit.cnot(1, 3) + circuit.swap([0, 2]) + circuit.observable([0, 1], 'yz') + circuit.observable(2, 'x') + + +def test_gradients(gpu): + actual = gpu(4) + expected = dq.QubitCircuit(4) + add_trainable_gates(actual) + add_trainable_gates(expected) + expected.double() + values = torch.tensor([0.23, -0.41, 0.61, 0.37], device='cuda', requires_grad=True) + weights = torch.tensor([0.3, 0.7], device='cuda') + with torch.no_grad(): + for parameter, value in zip(expected.parameters(), values.cpu(), strict=True): + parameter.fill_(value) + for parameter, value in zip(actual.parameters(), values.detach(), strict=True): + parameter.fill_(value) + expected() + reference = (expected.expectation() * weights.cpu()).sum() + reference.backward() + gradient = torch.cat([parameter.grad.reshape(-1) for parameter in expected.parameters()]) + value, derivative = actual.value_and_grad(values, weights) + torch.testing.assert_close(value.cpu().double(), reference.detach(), atol=3e-5, rtol=3e-4) + torch.testing.assert_close(derivative.cpu().double(), gradient, atol=1e-4, rtol=1e-3) + torch.testing.assert_close(actual.adjoint_vjp(values, weights), derivative, atol=1e-4, rtol=1e-3) + (actual.expectation(parameters=values) * weights).sum().backward() + torch.testing.assert_close(values.grad, derivative, atol=1e-4, rtol=1e-3) + (actual.expectation() * weights).sum().backward() + module_gradient = torch.cat([parameter.grad.reshape(-1) for parameter in actual.parameters()]) + torch.testing.assert_close(module_gradient.cpu().double(), gradient, atol=1e-4, rtol=1e-3) + + +def test_shared_inverse_parameters(gpu): + actual = gpu(3) + expected = dq.QubitCircuit(3) + for circuit in (actual, expected): + gate = dq.Ry(nqubit=3, wires=0, requires_grad=True) + with torch.no_grad(): + gate.theta.fill_(0.37) + circuit.add(gate) + circuit.cnot(0, 1) + circuit.add(gate, wires=2) + circuit.add(gate.inverse(), wires=1) + circuit.observable(2, 'z') + circuit.observable([0, 1], 'xx') + expected.double() + expected() + expected.expectation().sum().backward() + actual.expectation().sum().backward() + torch.testing.assert_close( + next(actual.parameters()).grad.double(), next(expected.parameters()).grad, atol=1e-4, rtol=1e-3 + ) + assert len(actual._compiled_plan.parameter_sources) == 1 + + +def test_multirz(gpu): + circuit = gpu(5) + circuit.h(0) + circuit.multirz([0, 1, 3, 4]) + circuit.observable(0, 'x') + value, gradient = circuit.value_and_grad(torch.tensor([0.37], device='cuda'), torch.ones(1, device='cuda')) + assert abs(value.item() - math.cos(0.37)) < 3e-5 + assert abs(gradient.item() + math.sin(0.37)) < 1e-4 + + +def test_five_target_permutation(gpu): + generator = torch.Generator().manual_seed(91) + initial = torch.randn(128, dtype=torch.complex64, generator=generator) + initial /= initial.norm() + permutation = torch.randperm(32, generator=generator) + diagonal = torch.exp(1j * torch.randn(32, generator=generator)) + matrix = torch.diag(diagonal)[:, permutation] + expected = dq.QubitCircuit(7, init_state=initial) + expected.any(matrix, wires=[4, 0, 6, 1, 3], controls=[2]) + reference = expected() + circuit = gpu(7, init_state=initial) + circuit.any(matrix, wires=[4, 0, 6, 1, 3], controls=[2]) + torch.testing.assert_close(circuit().cpu(), reference, atol=2e-5, rtol=2e-4) + + +def test_sampling_order_and_reuse(gpu): + circuit = gpu(4) + circuit.x(0) + circuit.x(2) + circuit() + assert circuit.measure(shots=7) == {'1010': 7} + assert circuit.measure(shots=128) == {'1010': 128} + assert circuit.measure(shots=17, wires=[3, 0]) == {'10': 17} + circuit.close() + circuit() + assert circuit.measure(shots=9) == {'1010': 9} + + +def test_matrix_observable(gpu): + circuit = gpu(2) + circuit.h(0) + circuit.observable_matrix(torch.tensor([[0, 1], [1, 0]], dtype=torch.complex64), wires=0) + circuit() + assert abs(circuit.expectation().item() - 1) < 3e-5 + + +@pytest.mark.parametrize('wires', [[1], [0, 2], [2, 0], [3, 0, 2]]) +def test_matrix_observable_wire_order(gpu, wires): + generator = torch.Generator().manual_seed(42) + initial = torch.randn(16, dtype=torch.complex64, generator=generator) + initial /= initial.norm() + dimension = 2 ** len(wires) + matrix = torch.randn(dimension, dimension, dtype=torch.complex64, generator=generator) + matrix = (matrix + matrix.mH) / 2 + circuit = gpu(4, init_state=initial) + circuit.observable_matrix(matrix, wires=wires) + circuit() + axes = wires + [wire for wire in range(4) if wire not in wires] + state = initial.reshape((2,) * 4).permute(axes).reshape(dimension, -1) + expected = (state.conj() * (matrix @ state)).sum().real + torch.testing.assert_close(circuit.expectation().cpu().reshape(()), expected, atol=2e-5, rtol=2e-4) + + +def test_non_default_stream(gpu): + with torch.cuda.stream(torch.cuda.Stream()): + circuit = gpu(3) + circuit.h(0) + circuit.ry(1, controls=0) + circuit.observable(1) + value, gradient = circuit.value_and_grad(torch.tensor([0.37], device='cuda'), torch.ones(1, device='cuda')) + assert abs(value.item() - (1 + math.cos(0.37)) / 2) < 3e-5 + assert abs(gradient.item() + math.sin(0.37) / 2) < 1e-4 + + +@pytest.mark.parametrize('mutation', ['forward', 'add', 'compile', 'close', 'parameter']) +def test_stale_backward(gpu, mutation): + circuit = gpu(2) + circuit.rx(0) + circuit.observable(0) + parameter = torch.tensor([0.37], device='cuda', requires_grad=True) + value = circuit.expectation(parameters=parameter) + if mutation == 'forward': + circuit() + elif mutation == 'add': + circuit.x(1) + elif mutation == 'parameter': + with torch.no_grad(): + parameter.add_(0.1) + else: + getattr(circuit, mutation)() + with pytest.raises(RuntimeError): + value.sum().backward() + + +def test_independent_parameter_gradients_with_shared_storage(gpu): + actual = gpu(1) + expected = dq.QubitCircuit(1) + for circuit in (actual, expected): + initial = torch.tensor(0.37) + circuit.add(dq.Rx(inputs=initial, requires_grad=True)) + circuit.add(dq.Ry(inputs=initial, requires_grad=True)) + circuit.observable(0, 'z') + expected() + expected.expectation().sum().backward() + actual.expectation().sum().backward() + for parameter, reference in zip(actual.parameters(), expected.parameters(), strict=True): + assert parameter.grad is not None + torch.testing.assert_close(parameter.grad.cpu(), reference.grad, atol=1e-4, rtol=1e-3) + + +def test_parameter_freeze_and_unfreeze_recompile(gpu): + circuit = gpu(1) + circuit.ry(0) + circuit.observable(0, 'z') + theta = next(circuit.parameters()) + circuit.requires_grad_(False) + theta.fill_(0.37) + circuit() + assert not circuit.expectation().requires_grad + theta.requires_grad_(True) + with torch.no_grad(): + theta.fill_(0.9) + value = circuit.expectation().sum() + assert abs(value.item() - math.cos(0.9)) < 3e-5 + value.backward() + assert abs(theta.grad.item() + math.sin(0.9)) < 1e-4 + theta.requires_grad_(False) + circuit() + assert not circuit.expectation().requires_grad + + +def test_automatic_gradient_and_inference(gpu): + circuit = gpu(1) + circuit.ry(0) + circuit.observable(0, 'z') + with torch.no_grad(): + circuit.operators[0].theta.fill_(0.4) + circuit.expectation().sum().backward() + assert abs(circuit.operators[0].theta.grad.item() + math.sin(0.4)) < 1e-4 + with torch.no_grad(): + circuit() + generation = circuit._executor.generation() + value = circuit.expectation() + assert not value.requires_grad + assert circuit._executor.generation() == generation + assert abs(value.item() - math.cos(0.4)) < 3e-5 + value = circuit.expectation(parameters=torch.tensor([0.9], device='cuda')) + assert abs(value.item() - math.cos(0.9)) < 3e-5 + assert circuit._executor.generation() != generation + parameters = torch.tensor([0.2], device='cuda', requires_grad=True) + circuit.expectation(parameters=parameters).sum().backward() + assert abs(parameters.grad.item() + math.sin(0.2)) < 1e-4 + circuit.requires_grad_(False) + circuit() + assert not circuit.expectation().requires_grad + + +def test_matrix_observable_rejects_gradients(gpu): + circuit = gpu(1) + circuit.ry(0) + circuit.observable_matrix(torch.eye(2, dtype=torch.complex64), wires=0) + with pytest.raises(ValueError, match='Pauli observables'): + circuit.expectation() + with torch.no_grad(): + circuit() + assert abs(circuit.expectation().item() - 1) < 3e-5 + for method in (circuit.value_and_grad, circuit.adjoint_vjp): + with pytest.raises(ValueError, match='Pauli observables'): + method(None, torch.ones(1, device='cuda')) + + +def test_invalid_modes(gpu): + with pytest.raises(ValueError, match='complex64'): + gpu(2, dtype=torch.complex128) + circuit = gpu(2) + with pytest.raises(ValueError, match='runtime data'): + circuit(torch.ones(1)) + circuit.rx(0, encode=True) + with pytest.raises(ValueError, match='encoding'): + circuit.compile() + + +def test_state_lifecycle(gpu): + circuit = gpu(2) + circuit.observable(0) + with pytest.raises(RuntimeError, match='completed forward'): + circuit.expectation() + circuit() + circuit.x(0) + assert circuit.measure(10) is None + with pytest.raises(RuntimeError, match='completed forward'): + circuit.expectation() + circuit() + assert abs(circuit.expectation().item() + 1) < 3e-5 + + +def test_non_default_stream_matrix_and_sampling(gpu): + with torch.cuda.stream(torch.cuda.Stream()): + circuit = gpu(3) + circuit.x(0) + circuit.swap([0, 2]) + circuit.observable_matrix(torch.diag(torch.tensor([1, -1], dtype=torch.complex64)), wires=2) + circuit() + assert abs(circuit.expectation().item() + 1) < 3e-5 + assert circuit.measure(31) == {'001': 31} + + +@pytest.mark.parametrize('gate_type', ['Rx', 'Ry', 'Rz', 'Rxx', 'Ryy', 'Rzz', 'Rxy']) +@pytest.mark.parametrize('inverse', [False, True]) +def test_controlled_rotation_derivatives(gpu, gate_type, inverse): + generator = torch.Generator().manual_seed(712) + initial = torch.randn(16, dtype=torch.complex64, generator=generator) + initial /= initial.norm() + actual = gpu(4, init_state=initial) + expected = dq.QubitCircuit(4, init_state=initial) + wires = [2, 0] if len(gate_type) == 3 else [2] + for circuit in (actual, expected): + gate = getattr(dq, gate_type)(nqubit=4, wires=wires, controls=3, requires_grad=True) + with torch.no_grad(): + gate.theta.fill_(0.37) + circuit.add(gate.inverse() if inverse else gate) + circuit.observable([0, 1], 'xy') + circuit.observable([2, 3], 'zx') + expected.double() + expected() + loss = expected.expectation().sum() + loss.backward() + value = actual.expectation().sum() + value.backward() + torch.testing.assert_close(value.cpu().double(), loss.detach(), atol=3e-5, rtol=3e-4) + torch.testing.assert_close( + next(actual.parameters()).grad.double(), next(expected.parameters()).grad, atol=1e-4, rtol=1e-3 + ) + + +def test_ghz_sampling_distribution(gpu): + circuit = gpu(3) + circuit.h(0) + circuit.cnot(0, 1) + circuit.cnot(1, 2) + circuit() + counts = circuit.measure(4096) + assert set(counts) == {'000', '111'} + assert sum(counts.values()) == 4096 + assert abs(counts['000'] / 4096 - 0.5) < 0.05 + + +def test_cnot_with_additional_controls(gpu): + initial = torch.randn(32, dtype=torch.complex64, generator=torch.Generator().manual_seed(91)) + initial /= initial.norm() + actual = gpu(5, init_state=initial) + expected = dq.QubitCircuit(5, init_state=initial) + for circuit in (actual, expected): + circuit.add(dq.CNOT(nqubit=5, wires=[1, 4]), wires=[1, 4], controls=[0, 3]) + torch.testing.assert_close(actual().cpu(), expected(), atol=2e-5, rtol=2e-4) + + +@pytest.mark.parametrize('controls', [[], [1], [1, 3]]) +@pytest.mark.parametrize('inverse', [False, True]) +def test_phase_generator_gradients(gpu, controls, inverse): + initial = torch.randn(16, dtype=torch.complex64, generator=torch.Generator().manual_seed(482)) + initial /= initial.norm() + actual = gpu(4, init_state=initial) + expected = dq.QubitCircuit(4, init_state=initial) + for circuit in (actual, expected): + gate = dq.PhaseShift(nqubit=4, wires=2, controls=controls, requires_grad=True) + with torch.no_grad(): + gate.theta.fill_(0.37) + circuit.add(gate.inverse() if inverse else gate) + circuit.observable([0, 2], 'xy') + circuit.observable([2, 3], 'yz') + expected.double() + expected() + weights = torch.tensor([0.3, -0.7]) + reference = (expected.expectation() * weights).sum() + reference.backward() + value = (actual.expectation() * weights.cuda()).sum() + value.backward() + torch.testing.assert_close(value.cpu().double(), reference, atol=3e-5, rtol=3e-4) + torch.testing.assert_close( + next(actual.parameters()).grad.double(), next(expected.parameters()).grad, atol=1e-4, rtol=1e-3 + ) + + +@pytest.mark.parametrize('inverse', [False, True]) +def test_fixed_gate_matrix_refresh(gpu, inverse): + initial = torch.tensor([0.6, 0.8j], dtype=torch.complex64) + actual = gpu(1, init_state=initial) + expected = dq.QubitCircuit(1, init_state=initial) + for circuit in (actual, expected): + gate = dq.U3Gate(inputs=[0.3, 0.4, 0.5], nqubit=1, wires=0) + circuit.add(gate.inverse() if inverse else gate) + torch.testing.assert_close(actual().cpu(), expected(), atol=2e-5, rtol=2e-4) + for circuit in (actual, expected): + circuit.operators[0].theta.fill_(0.9) + actual.invalidate() + torch.testing.assert_close(actual().cpu(), expected(), atol=2e-5, rtol=2e-4) + + +@pytest.mark.parametrize('assign', [False, True]) +@pytest.mark.parametrize('trainable', [False, True]) +def test_checkpoint_recompiles_nested_circuit(gpu, assign, trainable): + circuit = gpu(1) + circuit.rx(0, inputs=None if trainable else 0.2) + circuit.observable(0) + circuit() + parent = torch.nn.ModuleDict({'circuit': circuit}) + checkpoint = {key: value.clone() for key, value in parent.state_dict().items()} + checkpoint['circuit.operators.0.theta'].fill_(1.0) + parent.load_state_dict(checkpoint, assign=assign) + circuit() + value = circuit.expectation().sum() + assert abs(value.item() - math.cos(1.0)) < 3e-5 + if trainable: + value.backward() + assert abs(circuit.operators[0].theta.grad.item() + math.sin(1.0)) < 1e-4 + + +def test_checkpoint_invalidates_pending_backward(gpu): + circuit = gpu(1) + circuit.rx(0) + circuit.observable(0) + value = circuit.expectation().sum() + circuit.load_state_dict(circuit.state_dict()) + with pytest.raises(RuntimeError, match='changed or closed'): + value.backward() + + +def test_barrier_and_circuit_reset(gpu): + circuit = gpu(2) + circuit.h(0) + circuit.barrier() + circuit.cnot(0, 1) + circuit.observable_matrix(torch.diag(torch.tensor([1.0, -1.0])), wires=0) + state = circuit().cpu() + torch.testing.assert_close(state.flatten(), torch.tensor([1, 0, 0, 1], dtype=torch.complex64) / math.sqrt(2)) + assert abs(circuit.expectation().item()) < 3e-5 + circuit.reset_circuit() + circuit.x(1) + circuit.observable(1) + circuit() + assert abs(circuit.expectation().item() + 1) < 3e-5 + + +def test_unsupported_circuit_composition(gpu): + circuit = gpu(2) + circuit.multirz([0, 1]) + with pytest.raises(NotImplementedError, match='circuit addition'): + circuit + gpu(2) + with pytest.raises(NotImplementedError, match='circuit inverse'): + circuit.inverse() + + +def test_fixed_execution_device(gpu): + circuit = gpu(1) + circuit.rx(0) + parameter = circuit.operators[0].theta + with pytest.raises(ValueError, match='execution device is fixed'): + circuit.cpu() + assert circuit.operators[0].theta is parameter + circuit.to(circuit.gpu_device).double() + assert circuit.operators[0].theta.dtype == torch.float64 + assert circuit().device == circuit.gpu_device + if torch.cuda.device_count() > 1: + other = (circuit.gpu_device.index + 1) % torch.cuda.device_count() + with pytest.raises(ValueError, match='execution device is fixed'): + circuit.cuda(other) + assert circuit.operators[0].theta.device == circuit.gpu_device + + +@pytest.mark.skipif(torch.cuda.device_count() < 2, reason='requires two visible GPUs') +def test_native_calls_restore_device(gpu): + original = torch.cuda.current_device() + device = (original + 1) % torch.cuda.device_count() + circuit = gpu(2, device=f'cuda:{device}') + circuit.x(0) + circuit.observable(0) + circuit.compile() + assert torch.cuda.current_device() == original + circuit() + assert torch.cuda.current_device() == original + assert abs(circuit.expectation().item() + 1) < 3e-5 + assert torch.cuda.current_device() == original + assert circuit.measure(8) == {'10': 8} + assert torch.cuda.current_device() == original + value = circuit.expectation_from_state(circuit.state, list(circuit.observables)) + assert abs(value.item() + 1) < 3e-5 + assert torch.cuda.current_device() == original + with pytest.raises(ValueError, match='parameters must be'): + circuit._executor.execute(torch.empty(0)) + assert torch.cuda.current_device() == original + circuit.close() + circuit.close() + assert torch.cuda.current_device() == original diff --git a/tests/test_gpu_loader.py b/tests/test_gpu_loader.py new file mode 100644 index 00000000..c05dbe27 --- /dev/null +++ b/tests/test_gpu_loader.py @@ -0,0 +1,186 @@ +"""SDK discovery and CPU-only compiler/import contracts.""" + +import importlib +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch + +import deepquantum as dq +from deepquantum.custatevec.compiler import compile_circuit +from deepquantum.custatevec.loader import load_gpu_executor, load_ixquantum_executor, resolve_backend, resolve_sdk + + +@pytest.mark.parametrize('layout', ['flat', 'lib', 'lib64']) +def test_resolve_sdk(tmp_path, monkeypatch, layout): + include = tmp_path if layout == 'flat' else tmp_path / 'include' + library = tmp_path if layout == 'flat' else tmp_path / layout + include.mkdir(exist_ok=True) + library.mkdir(exist_ok=True) + (include / 'custatevec.h').touch() + (library / 'libcustatevec.so.1.8.0').touch() + monkeypatch.setenv('IXQUANTUM_ROOT', str(tmp_path)) + assert resolve_sdk('ixquantum') == (include, library / 'libcustatevec.so.1.8.0') + + +def test_missing_sdk(tmp_path, monkeypatch): + monkeypatch.setenv('IXQUANTUM_ROOT', str(tmp_path)) + with pytest.raises(RuntimeError, match='IXQUANTUM_ROOT'): + resolve_sdk('ixquantum') + + +@pytest.mark.parametrize('layout', ['lib', 'lib64']) +def test_nvidia_sdk_versioned_library(tmp_path, monkeypatch, layout): + include = tmp_path / 'include' + include.mkdir() + library = tmp_path / layout + library.mkdir() + (include / 'custatevec.h').touch() + target = library / 'libcustatevec.so.1' + target.touch() + monkeypatch.setenv('CUQUANTUM_ROOT', str(tmp_path)) + assert resolve_sdk('cuquantum') == (include, target) + + +def test_backend_selection(monkeypatch): + monkeypatch.setattr(torch, 'corex', True, raising=False) + assert resolve_backend() == 'ixquantum' + with pytest.raises(RuntimeError, match='NVIDIA CUDA'): + resolve_backend('cuquantum') + monkeypatch.setattr(torch, 'corex', False) + monkeypatch.setattr(torch.version, 'cuda', '12.6') + assert resolve_backend() == 'cuquantum' + with pytest.raises(RuntimeError, match='CoreX'): + resolve_backend('ixquantum') + monkeypatch.setattr(torch.version, 'cuda', None) + with pytest.raises(RuntimeError, match='NVIDIA CUDA'): + resolve_backend() + with pytest.raises(ValueError, match='backend'): + resolve_backend('unknown') + + +@pytest.mark.parametrize('backend', ['ixquantum', 'cuquantum']) +def test_backend_build_configuration(tmp_path, monkeypatch, backend): + import torch.utils.cpp_extension as extension + + import deepquantum.custatevec.loader as loader + + monkeypatch.setattr(torch, 'corex', backend == 'ixquantum', raising=False) + monkeypatch.setattr(torch.version, 'cuda', '12.6') + monkeypatch.setattr(loader, 'resolve_sdk', lambda selected: (tmp_path, tmp_path / 'libcustatevec.so.1')) + calls = [] + monkeypatch.setattr(extension, 'load', lambda **kwargs: calls.append(kwargs) or SimpleNamespace()) + load_gpu_executor(backend) + assert calls[0]['name'] == f'deepquantum_gpu_executor_{backend}' + assert [Path(p).name for p in calls[0]['sources']] == ['_gpu_executor.cpp', 'adjoint_kernels.cu'] + assert ('ivcore' in calls[0]['extra_cuda_cflags']) == (backend == 'ixquantum') + assert calls[0]['extra_ldflags'][0] == str(tmp_path / 'libcustatevec.so.1') + + +def test_missing_nvidia_sdk_is_explicit(tmp_path, monkeypatch): + monkeypatch.setenv('CUQUANTUM_ROOT', str(tmp_path)) + with pytest.raises(RuntimeError, match='CUQUANTUM_ROOT'): + resolve_sdk('cuquantum') + + +def test_corex_optional(monkeypatch): + monkeypatch.setattr(torch, 'corex', False, raising=False) + monkeypatch.setattr(torch.cuda, 'is_available', lambda: False) + importlib.reload(importlib.import_module('deepquantum.custatevec.loader')) + circuit = dq.QubitCircuit(2) + circuit.h(0) + circuit.cnot(0, 1) + state = circuit().reshape(-1) + torch.testing.assert_close(state.abs().square(), torch.tensor([0.5, 0.0, 0.0, 0.5])) + with pytest.raises(RuntimeError, match='available GPU|NVIDIA CUDA'): + dq.QubitCircuitGPU(2) + with pytest.raises(RuntimeError, match='CoreX'): + load_ixquantum_executor() + + +def test_independent_parameters_with_shared_storage(): + initial = torch.tensor(0.37) + circuit = dq.QubitCircuit(1) + rx = dq.Rx(inputs=initial, requires_grad=True) + ry = dq.Ry(inputs=initial, requires_grad=True) + circuit.add(rx) + circuit.add(ry) + assert rx.theta is not ry.theta and rx.theta.data_ptr() == ry.theta.data_ptr() + plan = compile_circuit(circuit) + assert plan.parameter_indices.tolist() == [0, 1] + assert plan.parameter_sources[0] is rx.theta + assert plan.parameter_sources[1] is ry.theta + + +def test_compiler_order_and_shared_parameters(): + circuit = dq.QubitCircuit(4) + circuit.h(0) + circuit.cnot(0, 3) + gate = dq.Rx(nqubit=4, wires=1, requires_grad=True) + circuit.add(gate) + circuit.add(gate, wires=2) + circuit.add(gate.inverse()) + circuit.observable([0, 3], 'xy') + plan = compile_circuit(circuit) + assert plan.targets[:2] == ((3,), (0,)) + assert plan.controls[1] == (3,) + assert plan.observable_bits == ((3, 0),) + assert plan.parameter_indices.tolist() == [-1, -1, 0, 0, 0] + assert plan.parameter_scales[-3:].tolist() == [1, 1, -1] + + +def test_compiler_rejects_data_encoding(): + circuit = dq.QubitCircuit(2) + circuit.rx(0, encode=True) + with pytest.raises(ValueError, match='encoding'): + compile_circuit(circuit) + + +def test_compiler_rejects_invalid_observable(): + from deepquantum.custatevec.compiler import compile_pauli_observables + + with pytest.raises(ValueError, match='unique circuit wires'): + compile_pauli_observables(2, [SimpleNamespace(wires=[0, 0], basis='zz')]) + + +def test_specialized_api_dispatch(): + from deepquantum.custatevec.compiler import ( + GRAD_PAULI_GENERATOR, + GRAD_PHASE, + OP_MATRIX, + OP_PAULI_ROTATION, + OP_PERMUTATION, + OP_PHASE, + ) + + circuit = dq.QubitCircuit(5) + circuit.h(0) + circuit.cx(0, 4) + circuit.cz(3, 1) + circuit.swap([4, 2]) + circuit.toffoli(0, 1, 2) + circuit.fredkin(0, 3, 4) + circuit.cp(0, 1) + circuit.rzz([1, 4]) + circuit.rxy([2, 3]) + plan = compile_circuit(circuit) + assert plan.opcodes.tolist() == [OP_MATRIX] + [OP_PERMUTATION] * 5 + [OP_PHASE] + [OP_PAULI_ROTATION] * 3 + assert plan.controls[4] == (4, 3) + assert plan.targets[4] == (2,) + assert plan.controls[5] == (4,) + assert plan.targets[5] == (0, 1) + assert all(matrix is None for matrix in plan.matrices[1:]) + assert plan.gradient_kinds[6:].tolist() == [GRAD_PHASE] + [GRAD_PAULI_GENERATOR] * 3 + assert plan.parameter_indices[-1] == plan.parameter_indices[-2] + + +def test_compiler_refreshes_fixed_inverse_and_skips_barrier(): + circuit = dq.QubitCircuit(1) + gate = dq.U3Gate(inputs=[0.3, 0.4, 0.5], nqubit=1, wires=0) + original = gate.matrix.clone() + circuit.add(gate.inverse()) + circuit.barrier() + plan = compile_circuit(circuit) + assert len(plan.opcodes) == 1 + torch.testing.assert_close(plan.matrices[0], original.mH)