rustsy_compute 0.1.0

CSR propagation and specialized integer relation kernels
Documentation
//! Ordered identity membership for compiler-owned type lists.
//! Device results are consulted only for the exact subsequence predicate.

#[cfg(all(windows, target_arch = "x86_64"))]
mod cuda;

#[cfg(feature = "fixpoint")]
pub mod graph;
#[cfg(all(feature = "fixpoint", windows, target_arch = "x86_64"))]
mod graph_cuda;

use std::{
    cell::RefCell,
    sync::{
        OnceLock,
        atomic::{AtomicU64, Ordering::Relaxed},
    },
    time::Instant,
};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
    Off,
    Cpu,
    Cuda,
    Verify,
    Auto,
}

struct Settings {
    mode: Mode,
    minimum: usize,
}

fn settings() -> &'static Settings {
    static SETTINGS: OnceLock<Settings> = OnceLock::new();
    SETTINGS.get_or_init(|| {
        let mode = match std::env::var("RUSTSY_COMPUTE").as_deref() {
            Ok("cpu") => Mode::Cpu,
            Ok("cuda") => Mode::Cuda,
            Ok("verify") => Mode::Verify,
            Ok("auto") => Mode::Auto,
            _ => Mode::Off,
        };
        let minimum = std::env::var("RUSTSY_COMPUTE_MIN")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(if mode == Mode::Auto { 4096 } else { 1 });
        Settings { mode, minimum }
    })
}

#[derive(Default)]
struct Counters {
    calls: AtomicU64,
    max_source: AtomicU64,
    max_target: AtomicU64,
    cpu_calls: AtomicU64,
    gpu_calls: AtomicU64,
    fallback: AtomicU64,
    cpu_ns: AtomicU64,
    gpu_ns: AtomicU64,
    init_ns: AtomicU64,
    contexts: AtomicU64,
    prep_ns: AtomicU64,
    upload_ns: AtomicU64,
    dispatch_ns: AtomicU64,
    read_ns: AtomicU64,
    device_ns: AtomicU64,
}

fn counters() -> &'static Counters {
    static COUNTERS: OnceLock<Counters> = OnceLock::new();
    COUNTERS.get_or_init(Counters::default)
}

pub(crate) fn ns(start: Instant) -> u64 {
    start.elapsed().as_nanos() as u64
}

#[derive(Default)]
struct Worker {
    #[cfg(all(windows, target_arch = "x86_64"))]
    device: Option<cuda::Device>,
    failed: bool,
    // One calibration per log2 target cardinality, per checker thread.
    cuda_wins: [Option<bool>; 17],
    source: Vec<u64>,
    target: Vec<u64>,
}

thread_local! { static WORKER: RefCell<Worker> = RefCell::new(Worker::default()); }

fn cpu(baseline: impl FnOnce() -> bool, count: &Counters) -> bool {
    let start = Instant::now();
    let answer = baseline();
    count.cpu_ns.fetch_add(ns(start), Relaxed);
    count.cpu_calls.fetch_add(1, Relaxed);
    answer
}

#[cfg(all(windows, target_arch = "x86_64"))]
fn run_cuda(worker: &mut Worker, count: &Counters) -> Result<Option<bool>, String> {
    if worker.device.is_none() {
        let start = Instant::now();
        let device = cuda::Device::new();
        count.init_ns.fetch_add(ns(start), Relaxed);
        worker.device = Some(device?);
        count.contexts.fetch_add(1, Relaxed);
    }
    let (answer, times) = worker
        .device
        .as_mut()
        .expect("initialized device")
        .subset(&worker.source, &worker.target)?;
    count.upload_ns.fetch_add(times.upload_ns, Relaxed);
    count.dispatch_ns.fetch_add(times.dispatch_ns, Relaxed);
    count.read_ns.fetch_add(times.read_ns, Relaxed);
    count.device_ns.fetch_add(times.device_ns, Relaxed);
    Ok(answer)
}

#[cfg(not(all(windows, target_arch = "x86_64")))]
fn run_cuda(_: &mut Worker, _: &Counters) -> Result<Option<bool>, String> {
    Err("CUDA backend requires Windows x64 in this prototype".into())
}

/// The CPU callback preserves the compiler's original ordered scan.
/// Keys must be nonzero identities of at most 48 bits. The device never dereferences them.
pub fn ordered_subset<T: Copy>(
    source: &[T],
    target: &[T],
    identity: impl Fn(T) -> u64,
    baseline: impl FnOnce() -> bool,
) -> bool {
    let settings = settings();
    if settings.mode == Mode::Off {
        return baseline();
    }
    let count = counters();
    count.calls.fetch_add(1, Relaxed);
    count.max_source.fetch_max(source.len() as u64, Relaxed);
    count.max_target.fetch_max(target.len() as u64, Relaxed);
    if settings.mode == Mode::Cpu
        || source.is_empty()
        || target.len() < settings.minimum
        || source.len() > target.len()
        || target.len() > usize::from(u16::MAX)
    {
        return cpu(baseline, count);
    }

    WORKER.with_borrow_mut(|worker| {
        let bucket = target.len().ilog2() as usize;
        if worker.failed || (settings.mode == Mode::Auto && worker.cuda_wins[bucket] == Some(false))
        {
            return cpu(baseline, count);
        }
        let start = Instant::now();
        worker.source.clear();
        worker.target.clear();
        worker.source.extend(source.iter().copied().map(&identity));
        worker.target.extend(target.iter().copied().map(identity));
        count.prep_ns.fetch_add(ns(start), Relaxed);
        if worker
            .source
            .iter()
            .chain(&worker.target)
            .any(|key| *key == 0 || *key >= 1 << 48)
        {
            count.fallback.fetch_add(1, Relaxed);
            return cpu(baseline, count);
        }
        let attempt = run_cuda(worker, count);
        let gpu_ns = ns(start);
        count.gpu_ns.fetch_add(gpu_ns, Relaxed);
        match attempt {
            Ok(Some(answer)) => {
                count.gpu_calls.fetch_add(1, Relaxed);
                if settings.mode == Mode::Verify
                    || (settings.mode == Mode::Auto && worker.cuda_wins[bucket].is_none())
                {
                    let start = Instant::now();
                    let expected = cpu(baseline, count);
                    if settings.mode == Mode::Verify {
                        assert_eq!(answer, expected, "RustSy ordered membership mismatch");
                    } else {
                        worker.cuda_wins[bucket] = Some(answer == expected && gpu_ns < ns(start));
                        return expected;
                    }
                }
                answer
            }
            result => {
                if let Err(error) = result {
                    eprintln!("rustsy_compute_fallback: {error}");
                    worker.failed = true;
                }
                count.fallback.fetch_add(1, Relaxed);
                cpu(baseline, count)
            }
        }
    })
}

pub struct ReportOnExit;

impl Drop for ReportOnExit {
    fn drop(&mut self) {
        let settings = settings();
        if settings.mode == Mode::Off {
            return;
        }
        let c = counters();
        macro_rules! report {
            ($($field:ident),* $(,)?) => {
                eprintln!(concat!("rustsy_compute mode={:?} minimum={}", $(" ", stringify!($field), "={}"),*),
                    settings.mode, settings.minimum, $(c.$field.load(Relaxed)),*);
            }
        }
        report!(
            calls,
            max_source,
            max_target,
            cpu_calls,
            gpu_calls,
            fallback,
            cpu_ns,
            gpu_ns,
            init_ns,
            contexts,
            prep_ns,
            upload_ns,
            dispatch_ns,
            read_ns,
            device_ns
        );
    }
}