rustsy_compute 0.1.0

CSR propagation and specialized integer relation kernels
Documentation
// Adapted from RustSy V2 to expose a resident graph library API.
use crate::graph::Graph;
use std::{
    ffi::{CStr, CString, c_char, c_void},
    ptr::null_mut,
    time::Instant,
};
fn ms(start: Instant) -> f64 {
    crate::ns(start) as f64 / 1e6
}

type Ptr = *mut c_void;
type DevicePtr = u64;
type Result<T> = std::result::Result<T, String>;

#[link(name = "kernel32")]
unsafe extern "system" {
    fn LoadLibraryExA(name: *const c_char, file: Ptr, flags: u32) -> Ptr;
    fn GetProcAddress(module: Ptr, name: *const c_char) -> Ptr;
}

macro_rules! driver {
    ($($name:ident($($arg:ty),*);)*) => {
        #[allow(non_snake_case)]
        struct Driver { $($name: unsafe extern "system" fn($($arg),*) -> i32,)* }
        impl Driver {
            fn load() -> Result<Self> {
                let module = unsafe { LoadLibraryExA(c"nvcuda.dll".as_ptr(), null_mut(), 0x800) };
                if module.is_null() { return Err("System32/nvcuda.dll unavailable".into()); }
                Ok(Self { $($name: {
                    let ptr = unsafe { GetProcAddress(module, concat!(stringify!($name), "\0").as_ptr().cast()) };
                    if ptr.is_null() { return Err(concat!("Missing ", stringify!($name)).into()); }
                    unsafe { std::mem::transmute::<Ptr, unsafe extern "system" fn($($arg),*) -> i32>(ptr) }
                },)* })
            }
        }
    }
}

driver! {
    cuInit(u32);
    cuDeviceGet(*mut i32, i32);
    cuDeviceGetName(*mut c_char, i32, i32);
    cuCtxCreate_v2(*mut Ptr, u32, i32);
    cuCtxDestroy_v2(Ptr);
    cuCtxSetCurrent(Ptr);
    cuModuleLoadData(*mut Ptr, *const c_void);
    cuModuleGetFunction(*mut Ptr, Ptr, *const c_char);
    cuMemAlloc_v2(*mut DevicePtr, usize);
    cuMemcpyHtoD_v2(DevicePtr, *const c_void, usize);
    cuMemcpyDtoH_v2(*mut c_void, DevicePtr, usize);
    cuMemsetD32Async(DevicePtr, u32, usize, Ptr);
    cuLaunchKernel(Ptr, u32, u32, u32, u32, u32, u32, u32, Ptr, *mut Ptr, *mut Ptr);
    cuEventCreate(*mut Ptr, u32);
    cuEventRecord(Ptr, Ptr);
    cuEventElapsedTime(*mut f32, Ptr, Ptr);
    cuEventDestroy_v2(Ptr);
    cuStreamCreate(*mut Ptr, u32);
    cuStreamDestroy_v2(Ptr);
    cuStreamSynchronize(Ptr);
    cuStreamBeginCapture_v2(Ptr, u32);
    cuStreamEndCapture(Ptr, *mut Ptr);
    cuGraphInstantiateWithFlags(*mut Ptr, Ptr, u64);
    cuGraphDestroy(Ptr);
    cuGraphLaunch(Ptr, Ptr);
    cuGraphExecDestroy(Ptr);
}

macro_rules! call {
    ($driver:expr, $name:ident($($args:expr),*)) => {{
        let code = unsafe { ($driver.$name)($($args),*) };
        if code == 0 { Ok(()) } else { Err(format!("{}: CUDA status {code}", stringify!($name))) }
    }}
}

pub struct Resident {
    driver: Driver,
    context: Ptr,
    kernel: Ptr,
    offsets: DevicePtr,
    sources: DevicePtr,
    values: [DevicePtr; 2],
    changed: DevicePtr,
    events: [Ptr; 2],
    stream: Ptr,
    schedule: Ptr,
    count: u32,
    latest: Option<usize>,
    pub name: String,
    pub init_ms: f64,
    pub graph_upload_ms: f64,
    pub vram_bytes: usize,
}

pub struct Timings {
    pub upload_ms: f64,
    pub iteration_ms: f64,
    pub device_ms: f64,
    pub read_ms: f64,
    pub launches: u32,
    pub checks: u32,
}

impl Resident {
    pub fn new(graph: &Graph) -> Result<Self> {
        let start = Instant::now();
        let driver = Driver::load()?;
        call!(driver, cuInit(0))?;
        let mut device = 0;
        call!(driver, cuDeviceGet(&mut device, 0))?;
        let mut name = [0u8; 128];
        call!(
            driver,
            cuDeviceGetName(name.as_mut_ptr().cast(), name.len() as i32, device)
        )?;
        let mut resident = Self {
            driver,
            context: null_mut(),
            kernel: null_mut(),
            offsets: 0,
            sources: 0,
            values: [0; 2],
            changed: 0,
            events: [null_mut(); 2],
            stream: null_mut(),
            schedule: null_mut(),
            count: graph.count(),
            latest: None,
            name: CStr::from_bytes_until_nul(&name)
                .map_err(|e| e.to_string())?
                .to_string_lossy()
                .into_owned(),
            init_ms: 0.0,
            graph_upload_ms: 0.0,
            vram_bytes: 0,
        };
        let api = &resident.driver;
        call!(api, cuCtxCreate_v2(&mut resident.context, 0, device))?;
        let mut module = null_mut();
        let text = CString::new(include_str!("graph_fixpoint.ptx")).map_err(|e| e.to_string())?;
        call!(api, cuModuleLoadData(&mut module, text.as_ptr().cast()))?;
        call!(
            api,
            cuModuleGetFunction(&mut resident.kernel, module, c"propagate".as_ptr())
        )?;
        let sizes = [
            size_of_val(graph.offsets.as_slice()),
            size_of_val(graph.sources.as_slice()).max(4),
            graph.count() as usize * 4,
        ];
        call!(api, cuMemAlloc_v2(&mut resident.offsets, sizes[0]))?;
        call!(api, cuMemAlloc_v2(&mut resident.sources, sizes[1]))?;
        for ptr in &mut resident.values {
            call!(api, cuMemAlloc_v2(ptr, sizes[2]))?;
        }
        call!(api, cuMemAlloc_v2(&mut resident.changed, 4))?;
        for event in &mut resident.events {
            call!(api, cuEventCreate(event, 0))?;
        }
        resident.vram_bytes = sizes[0] + sizes[1] + sizes[2] * 2 + 4;
        resident.init_ms = ms(start);
        let start = Instant::now();
        resident.upload(resident.offsets, &graph.offsets)?;
        if !graph.sources.is_empty() {
            resident.upload(resident.sources, &graph.sources)?;
        }
        resident.graph_upload_ms = ms(start);
        Ok(resident)
    }

    fn upload(&self, address: DevicePtr, values: &[u32]) -> Result<()> {
        call!(
            self.driver,
            cuMemcpyHtoD_v2(address, values.as_ptr().cast(), size_of_val(values))
        )
    }

    pub fn solve(
        &mut self,
        seeds: &[u32],
        batch: u32,
        additions: &[(u32, u32)],
    ) -> Result<(Vec<u32>, Timings)> {
        self.run(seeds, batch, additions, false)
    }

    pub fn capture_schedule(&mut self) -> Result<()> {
        let api = &self.driver;
        call!(api, cuCtxSetCurrent(self.context))?;
        call!(api, cuStreamCreate(&mut self.stream, 1))?;
        call!(api, cuStreamBeginCapture_v2(self.stream, 0))?;
        let recorded = self.launch_batch(0, 4, self.stream);
        let mut graph = null_mut();
        let ended = call!(api, cuStreamEndCapture(self.stream, &mut graph));
        recorded?;
        ended?;
        let result = call!(
            api,
            cuGraphInstantiateWithFlags(&mut self.schedule, graph, 0)
        );
        let cleanup = call!(api, cuGraphDestroy(graph));
        result?;
        cleanup
    }

    pub fn replay(&mut self, seeds: &[u32]) -> Result<(Vec<u32>, Timings)> {
        self.run(seeds, 4, &[], true)
    }

    fn launch_batch(&self, mut current: usize, batch: u32, stream: Ptr) -> Result<usize> {
        let api = &self.driver;
        for j in 0..batch {
            let report = u32::from(j + 1 == batch);
            if report == 1 {
                call!(api, cuMemsetD32Async(self.changed, 0, 1, stream))?;
            }
            let mut args: [*const c_void; 7] = [
                (&self.offsets as *const u64).cast(),
                (&self.sources as *const u64).cast(),
                (&self.values[current] as *const u64).cast(),
                (&self.values[1 - current] as *const u64).cast(),
                (&self.changed as *const u64).cast(),
                (&self.count as *const u32).cast(),
                (&report as *const u32).cast(),
            ];
            call!(
                api,
                cuLaunchKernel(
                    self.kernel,
                    self.count.div_ceil(256),
                    1,
                    1,
                    256,
                    1,
                    1,
                    0,
                    stream,
                    args.as_mut_ptr().cast(),
                    null_mut()
                )
            )?;
            current = 1 - current;
        }
        Ok(current)
    }

    fn run(
        &mut self,
        seeds: &[u32],
        batch: u32,
        additions: &[(u32, u32)],
        replay: bool,
    ) -> Result<(Vec<u32>, Timings)> {
        call!(self.driver, cuCtxSetCurrent(self.context))?;
        let start = Instant::now();
        let mut current = if additions.is_empty() {
            self.upload(self.values[0], seeds)?;
            0
        } else {
            let current = self
                .latest
                .ok_or("Incremental solve requires a completed graph")?;
            // Caller supplies each touched vertex's old facts OR its new seeds.
            for &(vertex, facts) in additions {
                self.upload(self.values[current] + u64::from(vertex) * 4, &[facts])?;
            }
            current
        };
        let upload_ms = ms(start);
        self.latest = None;
        let mut launches = 0;
        let mut checks = 0;
        let mut device_ms = 0.0;
        let start = Instant::now();
        let api = &self.driver;
        let stream = if replay { self.stream } else { null_mut() };
        loop {
            let mut flag = 0u32;
            call!(api, cuEventRecord(self.events[0], stream))?;
            if replay {
                // Four generations always return to the initial buffer.
                call!(api, cuGraphLaunch(self.schedule, stream))?;
            } else {
                current = self.launch_batch(current, batch, stream)?;
            }
            launches += batch;
            call!(api, cuEventRecord(self.events[1], stream))?;
            if replay {
                call!(api, cuStreamSynchronize(stream))?;
            }
            call!(
                api,
                cuMemcpyDtoH_v2((&mut flag as *mut u32).cast(), self.changed, 4)
            )?;
            let mut elapsed = 0.0;
            call!(
                api,
                cuEventElapsedTime(&mut elapsed, self.events[0], self.events[1])
            )?;
            device_ms += f64::from(elapsed);
            checks += 1;
            if flag == 0 {
                break;
            }
            if launches >= self.count.saturating_add(batch) {
                return Err("Monotone propagation exceeded the graph convergence bound".into());
            }
        }
        let iteration_ms = ms(start);
        let start = Instant::now();
        let mut output = vec![0u32; self.count as usize];
        call!(
            api,
            cuMemcpyDtoH_v2(
                output.as_mut_ptr().cast(),
                self.values[current],
                size_of_val(output.as_slice())
            )
        )?;
        self.latest = Some(current);
        Ok((
            output,
            Timings {
                upload_ms,
                iteration_ms,
                device_ms,
                read_ms: ms(start),
                launches,
                checks,
            },
        ))
    }
}

impl Drop for Resident {
    fn drop(&mut self) {
        if self.context.is_null() {
            return;
        }
        unsafe {
            (self.driver.cuCtxSetCurrent)(self.context);
            if !self.schedule.is_null() {
                (self.driver.cuGraphExecDestroy)(self.schedule);
            }
            if !self.stream.is_null() {
                (self.driver.cuStreamDestroy_v2)(self.stream);
            }
            for event in self.events {
                if !event.is_null() {
                    (self.driver.cuEventDestroy_v2)(event);
                }
            }
            (self.driver.cuCtxDestroy_v2)(self.context);
        }
    }
}