Optional CUDA-Q QAOA Sampler Design
This page records the contract and package-boundary design for an optional CUDA-Q Quantum Approximate Optimization Algorithm (QAOA) sampler wrapper for the JuliaQUBO ecosystem (JuliaQUBO/QUBODrivers.jl#88). It defines package ownership, the minimum QUBODrivers.AbstractSampler surface, target and precision semantics, credential-free CPU conformance testing, and the Python/CUDA-Q environment probe required before runtime publication in a dedicated wrapper repository.
QUBODrivers.jl hosts this interface specification, the self-contained executable conformance prototype in examples/cudaq_qaoa_prototype.jl (CUDAQOptPrototype.QAOA.Optimizer, exercised in CI by test/drivers/optional_qaoa_prototypes.jl), and the conformance checklist only; it does not depend on PythonCall at runtime for CUDA-Q, import cudaq, or bundle GPU/vendor SDKs in core QUBODrivers.jl or QUBO.jl. Standalone package publication (CUDAQOpt.jl) is explicitly deferred until a dedicated wrapper repository is provisioned; when published, it will be added to the External Sampler Packages table in docs/src/manual/3-samplers.md.
Ownership and Package Placement
- Proposed package and module: A standalone optional wrapper package,
CUDAQOpt.jl(hosted underJuliaQUBOorSECQUOIA), exposingCUDAQOpt.QAOA.Optimizer{T} <: QUBODrivers.AbstractSampler{T}generated viaQUBODrivers.@setup. - Zero vendor leakage into core packages:
QUBODrivers.jl,QUBOTools.jl,ToQUBO.jl, andQUBODecomposition.jlremain free of CUDA,CUDA.jl, or Pythoncudaqdependencies. - Decomposition compatibility:
CUDAQOpt.QAOA.Optimizermust compose as a child solver ofQUBODecomposition.Optimizerthrough the standard zero-argument child factory() -> ...and publicMOI.copy_to/QUBODrivers.sampleinterface, without CUDA-specific branches in the decomposition controller (see Public composition pattern). - Relationship to instructional notebooks: Existing Python CUDA-Q QAOA material in
QUBONotebooks(tests/test_cudaq_qaoa.py, tracked underJuliaQUBO/QUBONotebooks#137) remains instructional Python code and is not the Julia MOI driver. - Upstream reference attribution: Where Hamiltonian assembly, parameter optimization, or bitstring decoding adapts patterns from
alpha-unito/QSplitandqsplit/adapters/nvidia/util.py, the wrapper repository must preserve the QSplit MIT license notice and record the adapted revision (4da64b072e702953038addd51cdf54f97f0f9516).
Minimum Sampler Surface and Attributes
The optimizer must be declared with QUBODrivers.@setup and expose explicit MOI / raw optimizer attributes for circuit depth, target selection, precision, shot budgets, classical optimization budget, and seeding:
| Attribute / Raw Key | Type & Default | Contract |
|---|---|---|
"p" | Integer = 1 | QAOA circuit depth ($p \ge 1$), parameterizing $2p$ variational angles $(\gamma_1, \dots, \gamma_p, \beta_1, \dots, \beta_p)$. |
"target" | String = "qpp-cpu" | Explicit CUDA-Q simulation or hardware target (for example "qpp-cpu", "nvidia", "tensornet"). |
"target_option" | Union{String,Nothing} = nothing | Explicit target option or floating-point precision selector (such as "fp32" or "fp64" when supported by the target). |
"allow_target_fallback" | Bool = false | Whether the driver may fall back according to an explicit target list when the requested GPU target or precision is unavailable at target-initialization time. |
"num_reads" | Integer = 1_024 | Shot count (shots_count) per circuit evaluation during variational parameter optimization. |
QUBODrivers.FinalNumberOfReads() / "final_num_reads" | Union{Integer,Nothing} = nothing | Shot count used to sample the final optimized QAOA circuit (honors_final_reads(::Type{<:Optimizer}) = true; defaults to "num_reads" when unset). |
"optimizer" | String = "COBYLA" | Classical outer-loop optimizer name (cudaq.optimizers or scipy.optimize.minimize). |
"max_iterations" | Integer = 100 | Maximum classical optimizer iterations (max_iterations >= 1). |
"initial_point" | Union{Vector{Float64},Nothing} = nothing | Optional length-$2p$ initial parameter vector; when nothing, initialized deterministically from "seed". |
QUBODrivers.RandomSeed() / "seed" | Union{Integer,Nothing} = nothing | Seed forwarded to cudaq.set_random_seed(seed) and initial-point / classical-optimizer RNG (supports_seed(::Type{<:Optimizer}) = true). |
Model Lowering, Bit Ordering, and Objective Evaluation
- Variable ordering and isolated variables: Retrieve the internal model in
QUBOTools.variables(sampler)order (1:n) usingn, h, J, α, β = QUBOTools.ising(sampler, :dict; sense = :min)(which usesQUBOTools's spin convention $s_i = 2x_i - 1 \in \{-1, +1\}$, i.e., $x_i = (1 + s_i)/2$ with $x_i = 0 \leftrightarrow s_i = -1$ and $x_i = 1 \leftrightarrow s_i = +1$). All $n$ free logical variables—including isolated variables with zero linear and quadratic coefficients—must be allocated a qubit index $q_{i-1}$ (0:(n - 1)), initialized in $|+\rangle = H|0\rangle$, acted on by the mixer unitary $U_B(\beta_l) = \prod_{i=0}^{n-1} R_X(2\beta_l, q_i)$, and measured. - Cost Hamiltonian: Under standard computational-basis bit encoding $|x_i\rangle$ ($b_i = \text{'0'} \leftrightarrow x_i = 0$, $b_i = \text{'1'} \leftrightarrow x_i = 1$), the Pauli-$Z$ operator satisfies $Z_{i-1}|x_i\rangle = (1 - 2x_i)|x_i\rangle = -s_i|x_i\rangle$. Substituting $s_i = -Z_{i-1}$ into the
QUBOTools.isingform (equivalently substituting $x_i = (I - Z_{i-1})/2$ intoQUBOTools.qubo) yields the Pauli-$Z$ spin Hamiltonian:\[H_C = -\sum_{i=1}^{n} h_i Z_{i-1} + \sum_{1 \le i < j \le n} J_{ij} Z_{i-1} Z_{j-1}\]
built usingcudaq.SpinOperatorterms (-h_i * spin.z(i - 1)andJ_{ij} * spin.z(i - 1) * spin.z(j - 1)). For $n = 0$ (all variables fixed or empty model), bypass CUDA-Q circuit execution and emit a singleSample{T,Int}with empty stateInt[], objective value $\alpha \beta$, andfinal_num_readsreads. - Bitstring decoding and independent energy scoring: CUDA-Q
cudaq.sample(kernel, ...; shots_count = final_num_reads)returns aSampleResultmapping measured bitstrings $b \in \{0, 1\}^n$ in register declaration order (q[0]throughq[n - 1]) to shot counts $c_b \ge 1$ with $\sum_b c_b = \text{final\_num\_reads}$.- Map each measured bit $b_k \in \{\text{'0'}, \text{'1'}\}$ to:
x_k = (b_k == '1' ? 1 : 0)when constructing a:boolSampleSet(domain = :bool), scored via $\lambda = \text{QUBOTools.value}(x, L, Q, \alpha_q, \beta_q)$ fromQUBOTools.qubo(sampler, :dict; sense = :min); ors_k = (b_k == '1' ? 1 : -1) = -z_kwhen constructing a:spinSampleSet(domain = :spin), scored via $\lambda = \text{QUBOTools.value}(s, h, J, \alpha, \beta)$ fromQUBOTools.ising(sampler, :dict; sense = :min), so that bothQUBOTools.valueandQUBOTools.attach!'sSpinDomain => BoolDomaincast ($x_k = (s_k + 1)/2$) agree identically.
- Construct
QUBOTools.Sample{T,Int}(ψ, λ, count)so shot multiplicities are preserved as sample read counts.
- Map each measured bit $b_k \in \{\text{'0'}, \text{'1'}\}$ to:
Target Isolation, Precision Policy, and Error Semantics
- Global target-state isolation: In Python
cudaq,cudaq.set_target(...)mutates process-global state. The Julia wrapper must guard target selection, seed assignment, parameter optimization, and final sampling with a module-levelReentrantLock(and explicitly set the configured target at the start of everyQUBODrivers.sample(sampler)call) so sequential or multi-task solves in the same Julia process cannot leak target or precision state across optimizer instances. - No silent precision or hardware downgrade: Unlike QSplit's automatic
nvidia (fp64) -> nvidia (fp32) -> qpp-cpuloop,CUDAQOpt.QAOA.Optimizerdefaults to"allow_target_fallback" = false:- If the caller requests
"target" = "nvidia"and"target_option" = "fp64", any missing-target, unsupported-precision, or GPU out-of-memory failure must not silently switch to"fp32"or"qpp-cpu". - Only when
"allow_target_fallback" = trueis explicitly set may target initialization fall back across a documented candidate sequence, recording both"requested_target","selected_target","fallback_applied" = true, and"fallback_reason"inmetadata["cudaq"]. - Mid-solve execution failures (such as GPU out-of-memory during circuit simulation or invalid kernel parameters) must never trigger a silent retry on a different target.
- If the caller requests
- Actionable GPU memory and capacity failures: Before and during execution, if
cudaqraises an out-of-memory, device-capacity, or invalid-target error, the wrapper must clear any stale solution on the optimizer, setMOI.TerminationStatus()toMOI.MEMORY_LIMIT(for memory / qubit-capacity exhaustion) orMOI.OTHER_ERROR, and rethrow an exception whose message includes the requested"target","target_option", logical variable count $n$, and underlying CUDA-Q error text.
Metadata Contract
Every normal solve must pass QUBODrivers.validate_metadata with zero violations and populate:
"origin":"CUDAQOpt.QAOA @ cudaq""algorithm":Dict("name" => "QAOA", "p" => p, "optimizer" => optimizer_name)"backend":Dict("name" => "cudaq", "version" => cudaq_version)"execution":Dict("mode" => selected_target == "qpp-cpu" ? "local_cpu_simulator" : "cudaq_target")"optimizer":Dict("iterations" => iterations_performed, "evaluations" => circuit_evaluations)"reads":Dict("number_of_reads" => num_reads, "final_number_of_reads" => final_num_reads)"seeds":Dict("sampler" => seed)when seeded"cudaq":Dict{String,Any}( "requested_target" => requested_target, "selected_target" => selected_target, "target_option" => target_option, "precision" => resolved_precision, "fallback_applied" => fallback_applied, "fallback_reason" => fallback_reason, "num_qubits" => n, )
Credential-Free CPU Test Route and Environment Probe
Supported Python / CUDA-Q Environment Probe
Before running wrapper conformance tests or GPU smoke checks, verify the local Python and cudaq installation with the following standalone probe (requiring no quantum hardware credentials):
using PythonCall
function probe_cudaq_environment()
sys = pyimport("sys")
py_version = pyconvert(String, sys.version)
cudaq = try
pyimport("cudaq")
catch err
error(
"Python package `cudaq` is not installed in the active PythonCall environment " *
"(Python $py_version). Install `cudaq >= 0.8` on a supported platform " *
"(Linux x86_64/aarch64 or macOS arm64 for CPU targets) before running CUDAQOpt.",
)
end
cudaq_version = hasproperty(cudaq, :__version__) ?
pyconvert(String, cudaq.__version__) : "unknown"
has_qpp_cpu = pyconvert(Bool, cudaq.has_target("qpp-cpu"))
has_nvidia = pyconvert(Bool, cudaq.has_target("nvidia"))
num_gpus = hasproperty(cudaq, :num_available_gpus) ?
pyconvert(Int, cudaq.num_available_gpus()) : 0
return (
python_version = py_version,
cudaq_version = cudaq_version,
has_qpp_cpu = has_qpp_cpu,
has_nvidia = has_nvidia,
num_gpus = num_gpus,
)
endConformance Test Plan for the Standalone Package
- Credential-free CPU conformance (
"qpp-cpu"):- Run
QUBODrivers.test(CUDAQOpt.QAOA.Optimizer; examples = true, benchmark_conformance = true)configured with"target" => "qpp-cpu","p" => 1,"num_reads" => 64,"max_iterations" => 5, and"seed" => 42. - Verify tiny 2- to 4-variable QUBO and Ising models with non-zero scale and offset,
MOI.MIN_SENSEandMOI.MAX_SENSE, isolated variables, fixed variables, and non-monotonicMOI.VariableIndexinsertion order againstQUBODrivers.ExactSampler.Optimizer.
- Run
- Target-isolation and fallback unit tests:
- Verify that two optimizer instances configured with different targets or options preserve their respective
"selected_target"and"precision"inmetadata["cudaq"]. - Verify that requesting a nonexistent target or unavailable GPU target with
"allow_target_fallback" = falsethrows an actionable error and setsMOI.TerminationStatus()toMOI.OTHER_ERROR(orMOI.MEMORY_LIMITon simulated capacity errors) without silently falling back to"qpp-cpu".
- Verify that two optimizer instances configured with different targets or options preserve their respective
- Decomposition child integration test:
- Verify that
CUDAQOpt.QAOA.Optimizerworks as the child factory ofQUBODecomposition.Optimizeron a small multi-component and sweep model.
- Verify that
- Opt-in GPU smoke test:
- Gate
"target" => "nvidia"tests behindprobe.has_nvidia && probe.num_gpus > 0(and an explicit CI/local environment variable such asJULIA_CUDAQ_TEST_GPU=true) so standard CPU CI remains deterministic and credential-free.
- Gate