Skip to content

CUDA ​

Which backend did the planner choose? This program works on a CPU-only build and a CUDA-enabled build alike.

py
"""Which backend did the planner pick? Works on CPU-only and CUDA builds alike."""

import math
import random

from menos import Circuit, Opcode, RunOptions, run

n = 20
rng = random.Random(3)
circuit = Circuit(n, 0)
for _ in range(3):
    for q in range(n):
        circuit.append(Opcode.RY, [q], [rng.uniform(0, math.pi)])
    for q in range(0, n - 1, 2):
        circuit.append(Opcode.CX, [q, q + 1])
    for q in range(1, n - 1, 2):
        circuit.append(Opcode.CX, [q, q + 1])

options = RunOptions()
options.want_statevector = True
result = run(circuit, options)

report = result.explain()
region = next(line for line in report.splitlines() if line.startswith("region 0"))
print(region)
print(f"execute: {result.execute_seconds:.3f} s")

# The Python API never names a backend; the plan records which one ran.
assert "engine=dense" in region
assert "backend=cpu" in region or "backend=cuda" in region
assert abs(sum(abs(a) ** 2 for a in result.statevector) - 1.0) < 1e-12

Output ​

On a CPU-only build:

text
region 0   qubits=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] engine=dense backend=cpu
execute: 1.084 s

On a CUDA-enabled build on a supported GPU, the same program reports backend=cuda and finishes in a fraction of the time (0.09 s on the development GPU). The two runs produce bit-identical statevectors. See CPU vs CUDA for the comparison and CUDA Installation to build with CUDA.

The script asserts the region ran on the dense engine and that the state is normalized, and accepts either backend.

Released under the Apache-2.0 license. GitHub · PyPI