Quantum circuits

Import std.quantum explicitly to record circuits and run them on the threaded CPU state-vector simulator. A Circuit owns the recording. Each alloc_zero(&c) yields a linear Qubit for a wire initialized in |0⟩. Pass each token to finish, release_zero, measure or discard when you are done using it.

import std.quantum as q

fn main() {
    var c = q.Circuit.new()
    var a = q.alloc_zero(&c)
    var b = q.alloc_zero(&c)
    q.h(&c, &a)
    q.cnot(&c, a, &b)
    q.finish(&c, move a)
    q.finish(&c, move b)

    var sim = q.CpuSim.run(move c, 42)
    println(sim.amplitude(3).re)
    println(sim.sample())
}

Wire zero is the low bit of a basis index. The Bell circuit above gives |00⟩ and |11⟩ equal real amplitudes. amplitudes() exposes the complex state in basis-index order, probability(i) returns the squared magnitude at index i, and norm() sums those probabilities. sample() draws a basis index without collapsing the state. measure_all() draws an index and collapses the full state to that outcome.

Gates and wire loans

Borrow a gate’s target with &. Controls such as a in cnot(&c, a, &b) are shared loans. A controlled operation preserves the control’s computational-basis value and can change its relative phase through kickback. The borrow checker rejects using the same token as a shared control and a mutable target in one call.

The module provides x, y, z, h, s, sdg, t, tdg, rx, ry, rz and p (phase). Rotation angles are in radians and go before the target, as in ry(&c, angle, &b). Controlled gates include cnot (cx), cz, cp and toffoli (ccx). swap takes two mutable targets and records three CNOTs.

Use control(q, value) to borrow a wire and specify which basis value enables a gate. mcx(&c, controls, &target) applies X if all the controls match. controlled(&c, controls, matrix, &target) accepts an arbitrary unitary Matrix and checks the matrix’s column norms and orthogonality.

Automatically uncompute scratch wires

An ancilla can hold the result of a reversible computation while it controls another operation. Define the computation with #[reversible(inverse_name)]. In the quantum subset its parameters are an inout Circuit, any shared Qubit controls, and one inout Qubit scratch target. The compiler certifies calls to std.quantum.x, cnot and toffoli, and to other certified quantum reversible routines. Each call operates on the same circuit and scratch, with distinct operands. The compiler emits the corresponding inverse calls in reverse order.

import std.quantum as q

#[reversible(uncompute_pair)]
fn compute_pair(inout c: q.Circuit, a: q.Qubit, b: q.Qubit, inout scratch: q.Qubit) {
    q.toffoli(&c, a, b, &scratch)
}

fn cccx(inout c: q.Circuit, a: q.Qubit, b: q.Qubit, d: q.Qubit, inout target: q.Qubit) {
    q.with_ancilla2(&c, a, b, compute_pair, fn(guard) {
        let q.AncillaParts { circuit, scratch } = guard.parts()
        q.toffoli(&circuit, scratch, d, &target)
    })
}

with_ancilla1 and with_ancilla2 take a named certified function and a compile-time closure. The closure receives a loan of the guard. parts() provides the mutable circuit and shared scratch view together. The original controls stay borrowed until the guard runs inverse(compute) and records a zero check. The scratch view is read-only and cannot escape the callback.

release_zero also records a zero check when retiring a token directly. A later allocation can reuse that wire. The simulator checks that the wire’s |1⟩ probability is below 1e-12 at the recorded gate boundary, before any gate can use the recycled wire. zero_leakages() reports the probability at every completed check. finish retires a token and keeps its wire in the final state for inspection.

Interactive execution

Start with q.CpuSim.new(seed) and use inout c = &sim.circuit() to record gates. sim.execute() applies new gates and zero checks. Amplitude and probability queries read the last executed state. sample, measure_all, q.measure(&sim, move bit) and q.discard(&sim, move bit) execute pending gates automatically. The single-wire measurement samples the Born probabilities, renormalizes the selected branch and consumes the token. Discard performs the same collapse without returning the result. Equal seeds and operation sequences give reproducible results.

Hardware Vulkan execution

On x86_64 and aarch64 Linux, import gpu.quantum_gpu from lib/gpu/ to execute the same Circuit on a hardware compute queue. The module loads libvulkan.so.1 at runtime and emits SPIR-V 1.0 in jihoo. Native programs can opt in by importing it. The compiler, CPU simulator and freestanding and UEFI programs can use their existing modules independently.

import gpu.quantum_gpu as gpu
import std.quantum as q

fn bell_on_gpu(inout device: gpu.Gpu) -> Result(gpu.GpuRunResult, gpu.GpuError) {
    var c = q.Circuit.new()
    var a = q.alloc_zero(&c)
    var b = q.alloc_zero(&c)
    q.h(&c, &a)
    q.cnot(&c, a, &b)
    q.finish(&c, move a)
    q.finish(&c, move b)
    device.run(c)
}

fn main() {
    var device = gpu.Gpu.open(gpu.GpuOptions.from_env().unwrap()).unwrap()
    let result = bell_on_gpu(&device).unwrap()
    println(result.probability(3))
}

Selection prefers a discrete GPU, then an integrated GPU. The loader must report one of those two Vulkan device types and a compute queue. If no eligible device or loader is available, Gpu.open returns GpuError.DeviceUnavailable. GpuOptions.from_env() reads an optional hexadecimal vendor and device pair such as JIHOO_GPU_DEVICE=1002:7590. Set GpuOptions.device directly to select an adapter in code.

The default shader and device state use f32. Set GpuOptions.precision to gpu.Precision.F64 to request f64 on a device that advertises shaderFloat64. The state uses one interleaved storage buffer and is limited by the selected device’s storage-buffer range and available memory. Each dispatch updates a gate, and long gate streams are split across fenced submissions. A staging buffer transfers the initial and final state and reads back each zero-check boundary before a later gate can reuse its released wire. The leakage threshold is 1e-10 for f32 and 1e-12 for f64.

Gpu.run(c) borrows the circuit and returns amplitudes as q.Complex with f64 components, the norm, recorded leakage probabilities, device and precision information, the gate count, and the state size. Use probability(i) for one squared magnitude or probabilities() to materialize them all. Timings cover per-run setup, initialization and upload, gate recording and submission, and readback including host conversion. Opening the Vulkan device is separate from these timings.

Run out/jihoo run examples/quantum_gpu.jh for CPU/GPU comparisons and benchmarks. It reports a skip when no hardware GPU is available. scripts/gpu_check.sh runs the SPIR-V tests and requires hardware GPU execution to succeed. It accepts JIHOO_COMPILER and passes JIHOO_GPU_DEVICE through to the example. The benchmark compares CPU and GPU at 18 and 20 qubits and runs GPU-only at 22 and 24 qubits.

Compute jobs

gpu.quantum_gpu is built on gpu.vulkan, whose Device.with_job lends a Job (a storage buffer, its staging memory and a compute pipeline) to a closure and destroys it when the closure returns. Only with_job is unsafe, because the GPU runs the shader unchecked. The job’s methods are safe: write, begin_gates, dispatch, submit and download check the job’s state and return GpuError.InvalidUse when they are called out of order. view(T) shows the staging memory as a [T]. T must be a Scalar (f32, f64, i32 or u32), so every bit pattern is a valid value. The view borrows the job. The borrow checker therefore rejects using it after a later call that runs GPU work, and the job cannot leave the closure:

let total = unsafe {
    device.with_job(f64, size, shader, push_size, fn(job) -> Result(f64, vulkan.GpuError) {
        job.download()?
        let state = job.view(f32)?   // borrows `job`
        Ok(state[0] as f64)          // `job.submit()` before this line is an error
    })
}?

Circuit representation

wire_count() gives the number of addressable wires used by the circuit. Each entry in gates() gives a target wire, four complex f64 coefficients in row order, and two u64 masks. The matrix acts on an amplitude pair when (index & control_mask) == control_value. Each entry in zero_checks() gives a wire and the number of gates to execute before checking it. The CPU runs up to 12 wires serially and distributes larger gate applications over disjoint amplitude pairs with std.thread.each.

Runnable Deutsch–Jozsa, Bernstein–Vazirani and Toffoli parity examples

Reversible functions and inverse

Esc