use std::{collections::VecDeque, time::Instant};
pub struct Graph {
pub(crate) offsets: Vec<u32>,
#[cfg(all(windows, target_arch = "x86_64"))]
pub(crate) sources: Vec<u32>,
outgoing: Vec<u32>,
targets: Vec<u32>,
}
impl Graph {
pub fn new(offsets: Vec<u32>, sources: Vec<u32>) -> Result<Self, &'static str> {
if offsets.len() < 2
|| offsets.len() > u32::MAX as usize
|| offsets[0] != 0
|| offsets.last().copied().unwrap() as usize != sources.len()
|| !offsets.windows(2).all(|a| a[0] <= a[1])
|| sources.iter().any(|&a| a as usize >= offsets.len() - 1)
{
return Err("Invalid CSR");
}
let mut outgoing = vec![0; offsets.len()];
for &source in &sources {
outgoing[source as usize + 1] += 1;
}
for i in 1..outgoing.len() {
outgoing[i] += outgoing[i - 1];
}
let mut cursor = outgoing.clone();
let mut targets = vec![0u32; sources.len()];
for (vertex, edge) in offsets.windows(2).enumerate() {
for &source in &sources[edge[0] as usize..edge[1] as usize] {
let position = &mut cursor[source as usize];
targets[*position as usize] = vertex as u32;
*position += 1;
}
}
Ok(Self {
offsets,
#[cfg(all(windows, target_arch = "x86_64"))]
sources,
outgoing,
targets,
})
}
pub(crate) fn count(&self) -> u32 {
(self.offsets.len() - 1) as u32
}
fn solve_lanes(&self, mut facts: Vec<u32>) -> Vec<u32> {
let mut queued: Vec<_> = facts.iter().map(|&value| value != 0).collect();
let mut work: VecDeque<_> = (0..facts.len()).filter(|&i| queued[i]).collect();
while let Some(source) = work.pop_front() {
queued[source] = false;
let value = facts[source];
for &target in
&self.targets[self.outgoing[source] as usize..self.outgoing[source + 1] as usize]
{
let target = target as usize;
let merged = facts[target] | value;
if merged != facts[target] {
facts[target] = merged;
if !queued[target] {
queued[target] = true;
work.push_back(target);
}
}
}
}
facts
}
pub fn cpu(&self, seeds: &[u32], parallel: bool) -> Result<Vec<u32>, &'static str> {
if seeds.len() != self.count() as usize {
return Err("Wrong seed count");
}
if !parallel {
return Ok(self.solve_lanes(seeds.to_vec()));
}
Ok(std::thread::scope(|scope| {
let parts: Vec<_> = (0..4)
.map(|lane| {
scope.spawn(move || {
let mask = 0xff << (lane * 8);
self.solve_lanes(seeds.iter().map(|value| value & mask).collect())
})
})
.collect();
let mut output = vec![0; seeds.len()];
for part in parts {
for (value, bits) in output.iter_mut().zip(part.join().unwrap()) {
*value |= bits;
}
}
output
}))
}
}
#[derive(Debug, Clone, Copy)]
pub enum Backend {
Cpu,
Cuda,
}
pub struct Solve {
pub facts: Vec<u32>,
pub backend: Backend,
pub wall_ns: u64,
pub fallback: Option<String>,
pub device: Option<DeviceTiming>,
}
#[derive(Debug)]
pub struct DeviceTiming {
pub upload_ms: f64,
pub iteration_ms: f64,
pub device_ms: f64,
pub read_ms: f64,
pub launches: u32,
pub checks: u32,
}
pub struct ResidentGraph {
graph: Graph,
#[cfg(all(windows, target_arch = "x86_64"))]
cuda: Option<crate::graph_cuda::Resident>,
#[cfg(all(windows, target_arch = "x86_64"))]
captured: bool,
fallback: Option<String>,
}
impl ResidentGraph {
pub fn new(graph: Graph, backend: Backend) -> Self {
#[cfg(all(windows, target_arch = "x86_64"))]
{
let device = match backend {
Backend::Cpu => Ok(None),
Backend::Cuda => crate::graph_cuda::Resident::new(&graph).map(Some),
};
match device {
Ok(cuda) => Self {
graph,
cuda,
captured: false,
fallback: None,
},
Err(error) => Self {
graph,
cuda: None,
captured: false,
fallback: Some(error),
},
}
}
#[cfg(not(all(windows, target_arch = "x86_64")))]
Self {
graph,
fallback: matches!(backend, Backend::Cuda).then(|| "CUDA requires Windows x64".into()),
}
}
#[cfg(all(windows, target_arch = "x86_64"))]
pub fn capture(&mut self) -> Result<(), String> {
if !self.captured {
self.cuda
.as_mut()
.ok_or("No CUDA context")?
.capture_schedule()?;
self.captured = true;
}
Ok(())
}
#[cfg(all(windows, target_arch = "x86_64"))]
pub fn device_info(&self) -> Option<(&str, usize, f64, f64)> {
self.cuda.as_ref().map(|cuda| {
(
cuda.name.as_str(),
cuda.vram_bytes,
cuda.init_ms,
cuda.graph_upload_ms,
)
})
}
pub fn solve(&mut self, seeds: &[u32]) -> Result<Solve, &'static str> {
if seeds.len() != self.graph.count() as usize {
return Err("Wrong seed count");
}
let start = Instant::now();
#[cfg(all(windows, target_arch = "x86_64"))]
if let Some(device) = &mut self.cuda {
let result = if self.captured {
device.replay(seeds)
} else {
device.solve(seeds, 4, &[])
};
match result {
Ok((facts, timings)) => {
return Ok(Solve {
facts,
backend: Backend::Cuda,
wall_ns: crate::ns(start),
fallback: None,
device: Some(DeviceTiming {
upload_ms: timings.upload_ms,
iteration_ms: timings.iteration_ms,
device_ms: timings.device_ms,
read_ms: timings.read_ms,
launches: timings.launches,
checks: timings.checks,
}),
});
}
Err(error) => {
self.fallback = Some(error);
self.cuda = None;
}
}
}
let facts = self.graph.cpu(seeds, false)?;
Ok(Solve {
facts,
backend: Backend::Cpu,
wall_ns: crate::ns(start),
fallback: self.fallback.clone(),
device: None,
})
}
}