quantum_gpu

Compare identical circuit recordings on CPU and a hardware Vulkan GPU.

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

const PI: f64 = 3.141592653589793
const MIB: u64 = 1024 * 1024
const F32_EPSILON: f64 = 1.1920928955078125e-7

fn bell() -> q.Circuit {
    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)
    c
}

fn ghz() -> q.Circuit {
    var c = q.Circuit.new()
    var a = q.alloc_zero(&c)
    var b = q.alloc_zero(&c)
    var d = q.alloc_zero(&c)
    q.h(&c, &a)
    q.cnot(&c, a, &b)
    q.cnot(&c, b, &d)
    q.s(&c, &d)
    q.finish(&c, move a)
    q.finish(&c, move b)
    q.finish(&c, move d)
    c
}

fn qft(round_trip: bool) -> q.Circuit {
    var c = q.Circuit.new()
    var a = q.alloc_zero(&c)
    var b = q.alloc_zero(&c)
    var d = q.alloc_zero(&c)
    q.x(&c, &a)
    q.x(&c, &d)

    q.h(&c, &d)
    q.cp(&c, b, PI / 2.0, &d)
    q.cp(&c, a, PI / 4.0, &d)
    q.h(&c, &b)
    q.cp(&c, a, PI / 2.0, &b)
    q.h(&c, &a)
    q.swap(&c, &a, &d)
    if round_trip {
        q.swap(&c, &a, &d)
        q.h(&c, &a)
        q.cp(&c, a, -PI / 2.0, &b)
        q.h(&c, &b)
        q.cp(&c, a, -PI / 4.0, &d)
        q.cp(&c, b, -PI / 2.0, &d)
        q.h(&c, &d)
    }
    q.finish(&c, move a)
    q.finish(&c, move b)
    q.finish(&c, move d)
    c
}

fn phase_query(mask: u64, bias: bool) -> q.Circuit {
    var c = q.Circuit.new()
    var input = Vec(q.Qubit).new()
    for _ in 0..4 { input.push(q.alloc_zero(&c)) }
    var output = q.alloc_zero(&c)
    q.x(&c, &output)
    q.h(&c, &output)
    for i in 0..input.len() { q.h(&c, &input[i]) }
    if bias { q.x(&c, &output) }
    for i in 0..input.len() {
        if (mask & (1 << i)) != 0 { q.cnot(&c, input[i], &output) }
    }
    for i in 0..input.len() { q.h(&c, &input[i]) }
    while input.len() > 0 { q.finish(&c, input.pop().unwrap()) }
    input.into_empty()
    q.finish(&c, move output)
    c
}

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

fn cccx() -> q.Circuit {
    var c = q.Circuit.new()
    var a = q.alloc_zero(&c)
    var b = q.alloc_zero(&c)
    var d = q.alloc_zero(&c)
    var target = q.alloc_zero(&c)
    q.h(&c, &a)
    q.s(&c, &a)
    q.x(&c, &b)
    q.x(&c, &d)
    q.with_ancilla2(&c, a, b, compute_pair, fn(guard) {
        let q.AncillaParts { circuit, scratch } = guard.parts()
        q.toffoli(&circuit, scratch, d, &target)
    })
    q.finish(&c, move a)
    q.finish(&c, move b)
    q.finish(&c, move d)
    q.finish(&c, move target)
    assert(c.wire_count() == 5 && c.zero_checks().len == 1, "CCCX uses one clean scratch wire")
    c
}

fn compare(inout accelerator: gpu.Gpu, name: str, sink c: q.Circuit) -> Result((), gpu.GpuError) {
    let result = accelerator.run(c)?
    let cpu = q.CpuSim.run(move c, 0)
    let expected = cpu.amplitudes()
    assert(expected.len == result.amplitudes.len(), "state lengths agree")
    var amplitude_error = 0.0
    var probability_error = 0.0
    for i in 0..expected.len {
        let a = expected[i]
        let b = result.amplitudes[i]
        let re = a.re - b.re
        let im = a.im - b.im
        amplitude_error += re * re + im * im
        probability_error += abs(cpu.probability(i as u64) - result.probability(i))
    }
    let tolerance = 8.0 * F32_EPSILON * max(1, result.gate_count) as f64
    let l2 = sqrt(amplitude_error)
    assert(l2 <= tolerance, "phase-aware complex amplitude L2 error")
    assert(probability_error <= 2.0 * tolerance, "total probability error")
    assert(abs(cpu.norm() - 1.0) < 1e-12 && abs(result.norm - 1.0) <= 2.0 * tolerance, "unit norm")
    assert(cpu.zero_leakages().len == result.zero_leakages.len(), "all recorded zero checks ran")
    for i in 0..result.zero_leakages.len() {
        assert(cpu.zero_leakages()[i] < 1e-12 && result.zero_leakages[i] < 1e-10, "clean ancilla")
    }
    fmt.println("{} passed  {} gates, amplitude L2 {}, probability L1 {}, norm {}",
        (name, result.gate_count, l2, probability_error, result.norm))
    Ok(())
}

fn benchmark_circuit(wires: i64) -> q.Circuit {
    var c = q.Circuit.new()
    var low = q.alloc_zero(&c)
    let middle = q.alloc_zero(&c)
    for _ in 2..wires - 1 { q.finish(&c, q.alloc_zero(&c)) }
    var high = q.alloc_zero(&c)
    q.h(&c, &low)
    q.rx(&c, 0.37, &high)
    q.cnot(&c, high, &low)
    q.ry(&c, -0.51, &high)
    q.cp(&c, low, 0.3, &high)
    q.mcx(&c, [q.control(low, true), q.control(middle, false)], &high)
    q.h(&c, &high)
    q.rz(&c, 0.62, &low)
    q.finish(&c, move low)
    q.finish(&c, move middle)
    q.finish(&c, move high)
    c
}

fn ms(ns: u64) -> f64 { ns as f64 / 1000000.0 }

fn benchmark(inout accelerator: gpu.Gpu, wires: i64, run_cpu: bool) -> Result((), gpu.GpuError) {
    let c = benchmark_circuit(wires)
    let start = gpu.monotonic_ns()
    let result = accelerator.run(c)?
    let gpu_ns = gpu.monotonic_ns() - start
    assert(
        abs(result.norm - 1.0) <= 16.0 * F32_EPSILON * result.gate_count as f64,
        "benchmark unit norm"
    )
    if run_cpu {
        let start = gpu.monotonic_ns()
        let cpu = q.CpuSim.run(move c, 0)
        let cpu_ns = gpu.monotonic_ns() - start
        assert(abs(cpu.norm() - 1.0) < 1e-12, "CPU benchmark unit norm")
        fmt.println(
            "{} qubits  {}  CPU {} ms  GPU {} ms  {}x speedup",
            (
                wires,
                result.device_name.as_str(),
                ms(cpu_ns),
                ms(gpu_ns),
                cpu_ns as f64 / gpu_ns as f64
            )
        )
    } else {
        fmt.println("{} qubits  {}  GPU {} ms  {} MiB state",
            (wires, result.device_name.as_str(), ms(gpu_ns), result.state_bytes / MIB))
    }
    let t = result.timings
    fmt.println("  setup {} ms  upload {} ms  compute/submit {} ms  readback {} ms",
        (ms(t.setup_ns), ms(t.upload_ns), ms(t.compute_ns), ms(t.readback_ns)))
    Ok(())
}

fn check_reuse_boundary(inout accelerator: gpu.Gpu) -> Result((), gpu.GpuError) {
    var c = q.Circuit.new()
    var scratch = q.alloc_zero(&c)
    q.x(&c, &scratch)
    q.release_zero(&c, move scratch)
    var reused = q.alloc_zero(&c)
    q.x(&c, &reused)
    q.finish(&c, move reused)
    match accelerator.run(c) {
        Err(gpu.GpuError.AncillaLeakage(gates, wire, p)) => {
            assert(gates == 1 && wire == 0 && p == 1.0, "leakage at the release boundary")
            Ok(())
        }
        Err(error) => Err(error)
        Ok(_) => panic("reusing a dirty ancilla must fail before the next gate")
    }
}

fn exercise(inout accelerator: gpu.Gpu) -> Result((), gpu.GpuError) {
    compare(&accelerator, "Bell", bell())?
    compare(&accelerator, "GHZ", ghz())?
    compare(&accelerator, "QFT", qft(false))?
    compare(&accelerator, "QFT + inverse QFT", qft(true))?
    compare(&accelerator, "Deutsch–Jozsa (constant)", phase_query(0, true))?
    compare(&accelerator, "Deutsch–Jozsa (balanced)", phase_query(0b0101, false))?
    compare(&accelerator, "Bernstein–Vazirani", phase_query(0b1011, false))?
    compare(&accelerator, "Five-wire clean-ancilla CCCX", cccx())?
    check_reuse_boundary(&accelerator)?
    benchmark(&accelerator, 18, true)?
    benchmark(&accelerator, 20, true)?
    benchmark(&accelerator, 22, false)?
    benchmark(&accelerator, 24, false)
}

fn main() -> i32 {
    let options = match gpu.GpuOptions.from_env() {
        Ok(value) => value
        Err(error) => {
            eprintln(error.to_string())
            return 1
        }
    }
    var accelerator = match gpu.Gpu.open(options) {
        Ok(device) => device
        Err(gpu.GpuError.DeviceUnavailable(reason)) => {
            if env.get("JIHOO_REQUIRE_GPU") == Some("1") {
                eprintln("Vulkan GPU required: " + reason.as_str())
                return 1
            }
            println("Vulkan GPU skipped: " + reason.as_str())
            return 0
        }
        Err(error) => {
            eprintln(error.to_string())
            return 1
        }
    }
    let id = accelerator.device_id()
    fmt.println(
        "Vulkan {} (vendor {:x}, device {:x}), f32",
        (accelerator.device_name(), id.vendor_id, id.device_id)
    )
    match exercise(&accelerator) {
        Ok(()) => 0
        Err(error) => {
            eprintln(error.to_string())
            1
        }
    }
}

View on GitHub

Esc