crates/kleene-cubecl/src/dev.rs
//! The device, its cache of uploaded matrices, and the GPU-resident vector and mask.
use std::any::Any;
use std::fmt;
use std::marker::PhantomData;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::atomic::{AtomicU64, AtomicUsize};
use std::sync::{Arc, Mutex, OnceLock};
use cubecl::client::Client;
use cubecl::prelude::*;
use cubecl::server::Handle;
use kleene_sparse::{CpuDevice, Csr, Mask, Value, Vector};
use crate::kernels::{self, LANES, SLOTS};
/// A GPU reached through CubeCL (the wgpu runtime: Vulkan through SPIR-V), and the CPU
/// device the operations without a GPU kernel run on.
///
/// The GPU is opened the first time a kernel runs, not when the device is made: making
/// one (or the backend's `Default`) touches no GPU. Matrices uploaded are cached on the
/// device (keyed by their host buffers, which the cache keeps alive) and uploaded once for
/// every algorithm run on them. Parts no matrix or algorithm holds any more stay up to a
/// budget of `KLEENE_GPU_CACHE_MB` (4096 when unset; [`GpuDevice::set_cache_budget`]),
/// least recently used out first; parts still held never count against it.
#[derive(Clone)]
pub struct GpuDevice {
inner: Arc<Inner>,
}
struct Inner {
client: OnceLock<Client>,
/// The kind asked for (`None`: the best the machine has), and the adapter picked with
/// its kind (looked up before the client is opened).
want: Option<GpuKind>,
picked: OnceLock<(cubecl::Device, GpuKind)>,
cpu: CpuDevice,
launches: AtomicU64,
cache: Mutex<Cache>,
budget: AtomicUsize,
uploaded: AtomicU64,
/// `None`: the defaults of the adapter's kind ([`CpuBelow::for_kind`]).
below: Mutex<Option<CpuBelow>>,
/// `KLEENE_GPU_BFS_FRONTIER` and `KLEENE_GPU_BFS_DEPTH`, read when the device is made.
bfs_env: (Option<usize>, Option<u32>),
}
/// The kind of device a [`GpuDevice`] runs on, as wgpu reports its adapter.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum GpuKind {
/// A GPU of its own (a card).
Discrete,
/// A GPU sharing the CPU's package and memory.
Integrated,
/// A GPU of a virtual machine.
Virtual,
/// An adapter wgpu cannot place.
Other,
/// No GPU at all: a Vulkan driver that runs the kernels on the CPU (llvmpipe, lavapipe,
/// SwiftShader). Its times are not a GPU's.
Software,
}
impl GpuKind {
/// Every kind, most capable first: the order a device without one asked for tries them.
pub const ALL: [GpuKind; 5] = [
GpuKind::Discrete,
GpuKind::Integrated,
GpuKind::Virtual,
GpuKind::Other,
GpuKind::Software,
];
/// Whether this is a software device rather than a GPU.
pub fn is_software(self) -> bool {
self == GpuKind::Software
}
}
/// The first adapter of `kind` this machine has (looked up, not opened). CubeCL's
/// properties of an opened device say only whether it is a card (a software device has
/// none), not which kind, so the device is asked for by kind and the kind kept.
#[cfg(not(target_os = "macos"))]
fn adapter(kind: GpuKind) -> Option<cubecl::Device> {
use cubecl::device::WgpuDeviceKind as K;
cubecl::Device::wgpu(match kind {
GpuKind::Discrete => K::DiscreteGpu(0),
GpuKind::Integrated => K::IntegratedGpu(0),
GpuKind::Virtual => K::VirtualGpu(0),
GpuKind::Other => K::Other(0),
GpuKind::Software => K::Cpu,
})
.ok()
}
/// The device to open and its kind: the kind asked for; else `CUBECL_WGPU_DEFAULT_DEVICE`
/// (`DiscreteGpu(n)`, `IntegratedGpu(n)`, `VirtualGpu(n)`, `Other(n)`, `Cpu`); else the first
/// kind of [`GpuKind::ALL`] the machine has (as CubeCL's default picks: a discrete GPU first).
#[cfg(not(target_os = "macos"))]
fn open(want: Option<GpuKind>) -> (cubecl::Device, GpuKind) {
use cubecl::device::WgpuDeviceKind as K;
if let Some(d) = want.and_then(|k| adapter(k).map(|d| (d, k))) {
return d;
}
if let Ok(v) = std::env::var("CUBECL_WGPU_DEFAULT_DEVICE") {
let named = |prefix: &str| {
v.strip_prefix(prefix)?
.strip_suffix(')')?
.parse::<usize>()
.ok()
};
let asked = if v == "Cpu" {
Some((K::Cpu, GpuKind::Software))
} else if let Some(n) = named("DiscreteGpu(") {
Some((K::DiscreteGpu(n), GpuKind::Discrete))
} else if let Some(n) = named("IntegratedGpu(") {
Some((K::IntegratedGpu(n), GpuKind::Integrated))
} else if let Some(n) = named("VirtualGpu(") {
Some((K::VirtualGpu(n), GpuKind::Virtual))
} else {
named("Other(").map(|n| (K::Other(n), GpuKind::Other))
};
if let Some((k, kind)) = asked
&& let Ok(d) = cubecl::Device::wgpu(k)
{
return (d, kind);
}
}
for kind in GpuKind::ALL {
if let Some(d) = adapter(kind) {
return (d, kind);
}
}
let d = cubecl::Device::default();
let kind = software_or_other(&d);
(d, kind)
}
/// On macOS (Metal) the device is CubeCL's default; its kind is only what its properties
/// say: no card is a software device, a card is [`GpuKind::Other`].
#[cfg(target_os = "macos")]
fn adapter(kind: GpuKind) -> Option<cubecl::Device> {
(kind == GpuKind::Other).then(cubecl::Device::default)
}
#[cfg(target_os = "macos")]
fn open(_want: Option<GpuKind>) -> (cubecl::Device, GpuKind) {
let d = cubecl::Device::default();
let kind = software_or_other(&d);
(d, kind)
}
fn software_or_other(d: &cubecl::Device) -> GpuKind {
match d.client().properties().identity.physical {
None => GpuKind::Software,
Some(_) => GpuKind::Other,
}
}
impl fmt::Display for GpuKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
GpuKind::Discrete => "discrete GPU",
GpuKind::Integrated => "integrated GPU",
GpuKind::Virtual => "virtual GPU",
GpuKind::Other => "other adapter",
GpuKind::Software => "SOFTWARE DEVICE (Vulkan on the CPU, not a GPU)",
})
}
}
/// Below how many edges each whole algorithm of [`kleene_graph::GraphBackend`] runs on the
/// device's CPU instead of the GPU: under these sizes the GPU's launches and reads cost more
/// than the CPU's whole answer. The defaults follow the adapter's kind
/// ([`CpuBelow::for_kind`]): an integrated GPU's are [`CpuBelow::INTEGRATED`], every other
/// kind's the crossovers measured on one discrete GPU ([`CpuBelow::default`]; BENCH.md,
/// "GPU on small graphs");
/// `KLEENE_GPU_CPU_BELOW_EDGES` sets every one of them to one number when the device is made
/// (0: [`CpuBelow::NEVER`]). A breadth-first search also moves its levels to the CPU when it
/// is deep and narrow (one launch a level loses to the CPU on a small frontier):
/// [`CpuBelow::bfs_frontier`] and [`CpuBelow::bfs_depth`], which `KLEENE_GPU_BFS_FRONTIER`
/// and `KLEENE_GPU_BFS_DEPTH` set when the device is made.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CpuBelow {
/// Weak components ([`kleene_graph::components_of`]).
pub components: usize,
/// Strong components ([`kleene_graph::scc_of`]).
pub strong: usize,
/// Shortest paths ([`kleene_graph::sssp_of`]), hop counts and weighted.
pub paths: usize,
/// Source sets ([`kleene_graph::reach_sets`]).
pub sets: usize,
/// PageRank ([`kleene_graph::pagerank_of`]).
pub pagerank: usize,
/// Breadth-first search ([`kleene_graph::bfs`], and Datalog reach planned as one): on
/// a graph of fewer edges every level runs on the CPU.
pub bfs: usize,
/// A search past [`CpuBelow::bfs_depth`] levels moves to the CPU while its frontier has
/// fewer vertices than this, and back to the GPU when the frontier reaches four times
/// as many (0: never moves).
pub bfs_frontier: usize,
/// The levels a search runs on the GPU before a small frontier moves it to the CPU.
pub bfs_depth: u32,
/// A round of the computed split (kleene-graph's `split_votes`, under
/// `computed_split`): on a graph of fewer out-edges it runs on the CPU. Measured with
/// the GPU forced, K = 4 (2026-11-29): on loki's RTX 5080 against 12 cores the GPU's
/// round was level on rmat14 (119806 edges, 0.2 ms each) and won from rmat16 (494438
/// edges, 0.3 against 0.6 ms); on dwarf's Radeon 660M against 12 cores it was level
/// from rmat16 to rmat22 (0.77x to 1.33x) and the whole split lost or drew (0.75x to
/// 1.04x), so an integrated GPU leaves it to the CPU.
pub split: usize,
}
impl CpuBelow {
/// Every algorithm on the GPU, whatever its size, and no search moves.
pub const NEVER: CpuBelow = CpuBelow {
bfs_frontier: 0,
..CpuBelow::all(0)
};
/// Every algorithm at `edges`; a search moves at the measured frontier and depth.
pub const fn all(edges: usize) -> CpuBelow {
CpuBelow {
components: edges,
strong: edges,
paths: edges,
sets: edges,
pagerank: edges,
bfs: edges,
bfs_frontier: BFS_FRONTIER,
bfs_depth: BFS_DEPTH,
split: edges,
}
}
}
impl CpuBelow {
/// The defaults for an integrated GPU: every algorithm (and the computed split's round)
/// on the CPU but the source sets,
/// those from 2000000 edges. Measured with the GPU forced against the CPU's threads on
/// two integrated GPUs (2026-11-29): a Radeon 660M against 12 threads won only the
/// sets (from rmat16, 494438 edges), PageRank on road grids and a few percent on rmat22
/// BFS; an Intel UHD (Tiger Lake) against 8 threads won only the sets (from rmat18,
/// 2017227 edges). The two are not told apart (both report an integrated GPU), so the
/// sets take the UHD's higher crossover, which costs the 660M a 2x on graphs between
/// the two. Every breadth-first search (and Datalog reach) also runs on the CPU: the
/// CPU won BFS on both but for a few percent on rmat22 on the 660M.
pub const INTEGRATED: CpuBelow = CpuBelow {
components: usize::MAX,
strong: usize::MAX,
paths: usize::MAX,
sets: 2_000_000,
pagerank: usize::MAX,
bfs: usize::MAX,
bfs_frontier: BFS_FRONTIER,
bfs_depth: BFS_DEPTH,
split: SPLIT_INTEGRATED,
};
/// The defaults for a GPU of this kind: [`CpuBelow::INTEGRATED`] for an integrated
/// GPU, [`CpuBelow::default`] (measured on one RTX 5080) for every other kind.
pub fn for_kind(kind: GpuKind) -> CpuBelow {
match kind {
GpuKind::Integrated => CpuBelow::INTEGRATED,
_ => CpuBelow::default(),
}
}
}
impl Default for CpuBelow {
/// The crossovers measured on loki's RTX 5080 against 5 CPU threads (R-MAT 12 to 22 and
/// road grids 256 to 1024, 2026-11-28): weak components from 131072 edges (the GPU won
/// on rmat16, 494438 edges, and lost on rmat14, 119806), strong components from 1048576
/// (won on rmat18, lost on rmat16), shortest paths from 2000000 (even on rmat18, won
/// on rmat20) and source sets from 262144 (won on rmat16, lost on rmat14). They were
/// measured on one RTX 5080, at a load average of 22. A small discrete card needs
/// higher ones ([`GpuDevice::set_cpu_below`]): on a laptop's RTX A2000 against 8
/// threads (GPU forced, R-MAT 12 to 22) weak components won only on rmat22 (32988662
/// edges; level on rmat14 and rmat16, lost on rmat18 and rmat20), strong components
/// and hop counts on none, weighted paths only on rmat22, the sets only on rmat16;
/// PageRank from rmat14 (119806 edges) as here. Integrated GPUs take
/// [`CpuBelow::INTEGRATED`] instead. PageRank from
/// 131072 edges (loki, 5 threads: the GPU lost on rmat14, 119806 edges, 8.2 against
/// 2.4 ms, and won on road256, 156666, and rmat16, 494438). Searches (and Datalog
/// reach) from 4194304 edges (lost on rmat18, 2017227 edges, won on rmat20, 8175389);
/// a search moves to the CPU past 16 levels on a frontier under 16384 vertices.
fn default() -> Self {
CpuBelow {
components: 1 << 17,
strong: 1 << 20,
paths: 2_000_000,
sets: 1 << 18,
pagerank: 1 << 17,
bfs: 1 << 22,
bfs_frontier: BFS_FRONTIER,
bfs_depth: BFS_DEPTH,
split: SPLIT_DISCRETE,
}
}
}
/// The computed split's round on a discrete GPU from this many out-edges ([`CpuBelow::split`]).
const SPLIT_DISCRETE: usize = 1 << 17;
/// The computed split's round on an integrated GPU: never ([`CpuBelow::split`]).
const SPLIT_INTEGRATED: usize = usize::MAX;
/// The frontier below which a deep search moves to the CPU: on loki's RTX 5080 (5 threads,
/// load 13-35, 2026-11-28) road2048's search (3843 levels) took 1002-2142 ms with no move,
/// 209-247 ms moving below 1024 or 4096 vertices and 200-204 ms below 16384 or 65536 (the
/// CPU's 119-133 ms); R-MAT 22 and 24 unchanged.
const BFS_FRONTIER: usize = 1 << 14;
/// The levels a search stays on the GPU first: past an R-MAT search's depth (8 on rmat26),
/// so a shallow search never moves for its small last levels (64 measured the same as 16).
const BFS_DEPTH: u32 = 16;
impl Default for GpuDevice {
fn default() -> Self {
GpuDevice::with_cpu(CpuDevice::default())
}
}
impl fmt::Debug for GpuDevice {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GpuDevice")
.field("open", &self.inner.client.get().is_some())
.field("cpu", &self.inner.cpu)
.finish()
}
}
/// Uploaded matrix parts by host buffer.
#[derive(Default)]
struct Cache {
entries: Vec<Entry>,
tick: u64,
}
struct Entry {
key: (usize, usize, u8),
/// The host buffers the key points into, kept alive so the address cannot be reused.
_host: Box<dyn Any + Send + Sync>,
part: Arc<dyn Any + Send + Sync>,
bytes: usize,
used: u64,
}
/// A pattern on the GPU: compressed rows with 32-bit offsets.
pub(crate) struct DevPattern {
pub offsets: Handle,
pub indices: Handle,
pub rows: usize,
pub nnz: usize,
}
/// What PageRank keeps of a graph on the GPU besides its in-pattern: each vertex's
/// out-degree, and the rows too long for one unit (more than [`RANK_SHORT`] entries) in
/// two lists: up to [`RANK_LONG`] entries (32 units a row) and past it (a cube a row). On
/// skewed degrees it keeps its own in-pattern instead, its in-neighbours renumbered by
/// falling out-degree (`placed`): the shares read most then share cache lines, as on the
/// CPU.
pub(crate) struct DevRank {
pub degree: Handle,
pub mid: Handle,
pub nmid: usize,
pub far: Handle,
pub nfar: usize,
pub placed: Option<Placed>,
}
/// An in-pattern whose indices are renumbered by `place` (old vertex to new).
pub(crate) struct Placed {
pub offsets: Handle,
pub indices: Handle,
pub place: Handle,
}
/// Whether a few vertices hold most of the edges: kleene-graph's test for renumbering by
/// degree (GAP's `WorthRelabelling`): over 1000 sampled vertices with edges, the mean
/// degree above 1.3 times the median.
pub(crate) fn skewed(n: usize, degree: impl Fn(usize) -> usize) -> bool {
if !(0..n).any(|v| degree(v) > 0) {
return false;
}
let samples = 1000.min(n);
let mut x = 0x5EED_u64;
let mut next = || {
// splitmix64
x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = x;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
};
let mut deg = Vec::with_capacity(samples);
while deg.len() < samples {
let v = (next() % n as u64) as usize;
let d = degree(v);
if d > 0 {
deg.push(d as u64);
}
}
deg.sort_unstable();
let mean = deg.iter().sum::<u64>() as f64 / samples as f64;
mean / 1.3 > deg[samples / 2] as f64
}
/// Each vertex's place when sorted by falling degree (ties in vertex order).
fn falling_place(deg: &[u32]) -> Vec<u32> {
let top = deg.iter().copied().max().unwrap_or(0) as usize;
let mut start = vec![0u32; top + 2];
for &d in deg {
start[top - d as usize + 1] += 1;
}
for i in 1..start.len() {
start[i] += start[i - 1];
}
deg.iter()
.map(|&d| {
let slot = &mut start[top - d as usize];
*slot += 1;
*slot - 1
})
.collect()
}
/// Rows of up to this many in-edges are summed by one unit each, in the row's order.
pub(crate) const RANK_SHORT: u32 = 32;
/// Rows of up to this many in-edges are summed by 32 units each; longer ones by 256.
pub(crate) const RANK_LONG: u32 = 4096;
/// What the computed split keeps of a graph on the GPU besides its out- and in-patterns:
/// the nodes of more than [`SPLIT_SHORT`] out- and in-edges together, listed for the
/// kernel that gives each a cube.
pub(crate) struct DevSplit {
pub long: Handle,
pub nlong: usize,
}
/// A node of at most this many out- and in-edges together counts its votes in one unit;
/// a longer one takes a cube of 256.
pub(crate) const SPLIT_SHORT: u32 = 512;
/// Values on the GPU as 32-bit numbers, each standing for itself times `scale`.
pub(crate) struct DevNarrow {
pub values: Handle,
pub scale: u64,
}
impl GpuDevice {
/// A device whose CPU side runs on `cpu`, on the first adapter of `kind`, or `None`
/// when the machine has none of that kind (it looks at the adapters without opening one).
pub fn with_cpu_on(cpu: CpuDevice, kind: GpuKind) -> Option<Self> {
adapter(kind).map(|_| GpuDevice::make(cpu, Some(kind)))
}
/// A device whose CPU side runs on `cpu`.
pub fn with_cpu(cpu: CpuDevice) -> Self {
GpuDevice::make(cpu, None)
}
fn make(cpu: CpuDevice, want: Option<GpuKind>) -> Self {
let budget = std::env::var("KLEENE_GPU_CACHE_MB")
.ok()
.and_then(|s| s.parse::<usize>().ok())
.unwrap_or(4096)
<< 20;
GpuDevice {
inner: Arc::new(Inner {
client: OnceLock::new(),
want,
picked: OnceLock::new(),
cpu,
launches: AtomicU64::new(0),
cache: Mutex::new(Cache::default()),
budget: AtomicUsize::new(budget),
uploaded: AtomicU64::new(0),
below: Mutex::new(env_usize("KLEENE_GPU_CPU_BELOW_EDGES").map(|e| match e {
0 => CpuBelow::NEVER,
e => CpuBelow::all(e),
})),
bfs_env: (
env_usize("KLEENE_GPU_BFS_FRONTIER"),
env_usize("KLEENE_GPU_BFS_DEPTH").map(|d| d.min(u32::MAX as usize) as u32),
),
}),
}
}
/// The CPU device.
pub fn cpu(&self) -> &CpuDevice {
&self.inner.cpu
}
/// Below how many edges each whole algorithm runs on the CPU: as set by
/// [`GpuDevice::set_cpu_below`] or `KLEENE_GPU_CPU_BELOW_EDGES`, else the defaults of
/// the adapter's kind ([`CpuBelow::for_kind`]; finding the adapter does not open it).
pub fn cpu_below(&self) -> CpuBelow {
let set = *self.inner.below.lock().expect("below");
set.unwrap_or_else(|| {
let mut b = CpuBelow::for_kind(self.kind());
let (f, d) = self.inner.bfs_env;
b.bfs_frontier = f.unwrap_or(b.bfs_frontier);
b.bfs_depth = d.unwrap_or(b.bfs_depth);
b
})
}
/// Set below how many edges each whole algorithm runs on the CPU, for this device and
/// every clone of it.
pub fn set_cpu_below(&self, below: CpuBelow) {
*self.inner.below.lock().expect("below") = Some(below);
}
/// The GPU client, opened on first use (the most capable wgpu adapter: a discrete GPU
/// first; `CUBECL_WGPU_DEFAULT_DEVICE` overrides).
pub(crate) fn client(&self) -> &Client {
self.inner
.client
.get_or_init(|| self.picked().0.clone().client())
}
fn picked(&self) -> &(cubecl::Device, GpuKind) {
self.inner.picked.get_or_init(|| open(self.inner.want))
}
/// The kind of device it runs on (looks the adapter up; does not open it).
pub fn kind(&self) -> GpuKind {
self.picked().1
}
/// The GPU's name and the runtime's, as `NVIDIA GeForce RTX 5080 (wgpu<spirv>)` (opens
/// it).
pub fn name(&self) -> String {
let c = self.client();
format!("{} ({})", c.properties().identity.name, c.name())
}
/// The GPU kernels launched on this device so far.
pub fn launches(&self) -> u64 {
self.inner.launches.load(Relaxed)
}
pub(crate) fn launched(&self) {
self.inner.launches.fetch_add(1, Relaxed);
}
/// The bytes of matrix parts uploaded to the GPU so far (each upload of a pattern or of
/// narrowed values the cache made).
pub fn uploaded_bytes(&self) -> u64 {
self.inner.uploaded.load(Relaxed)
}
/// The cache's budget in bytes.
pub fn cache_budget(&self) -> usize {
self.inner.budget.load(Relaxed)
}
/// Set the cache's budget in bytes, for this device and every clone of it (at the next
/// upload, least recently used parts go until the cache is within it).
pub fn set_cache_budget(&self, bytes: usize) {
self.inner.budget.store(bytes, Relaxed);
}
/// Drop every cached matrix and give unused memory back to the GPU.
pub fn cleanup(&self) {
self.inner.cache.lock().expect("cache").entries.clear();
if let Some(c) = self.inner.client.get() {
let _ = c.memory_cleanup();
}
}
/// The cached part under `key`, marked as just used.
fn hit<P: Any + Send + Sync>(&self, key: (usize, usize, u8)) -> Option<Arc<P>> {
let mut cache = self.inner.cache.lock().expect("cache");
cache.tick += 1;
let tick = cache.tick;
let e = cache.entries.iter_mut().find(|e| e.key == key)?;
e.used = tick;
Some(
Arc::clone(&e.part)
.downcast::<P>()
.expect("one type per key"),
)
}
/// The part under `key`, made and uploaded by `make` when missing. The budget counts
/// only the parts nothing outside the cache holds: putting out a part a matrix or a
/// running algorithm still holds frees no GPU memory, and its next use would upload it
/// again beside the first copy. So the least recently used of the parts held by the
/// cache alone go until those fit the budget.
fn cached<P: Any + Send + Sync, H: Any + Send + Sync>(
&self,
key: (usize, usize, u8),
host: impl FnOnce() -> H,
make: impl FnOnce() -> (P, usize),
) -> Arc<P> {
if let Some(p) = self.hit(key) {
return p;
}
let mut cache = self.inner.cache.lock().expect("cache");
// Another thread may have made it meanwhile.
if let Some(e) = cache.entries.iter().find(|e| e.key == key) {
return Arc::clone(&e.part)
.downcast::<P>()
.expect("one type per key");
}
cache.tick += 1;
let tick = cache.tick;
let (part, bytes) = make();
self.inner.uploaded.fetch_add(bytes as u64, Relaxed);
let part = Arc::new(part);
cache.entries.push(Entry {
key,
_host: Box::new(host()),
part: part.clone(),
bytes,
used: tick,
});
let unheld = |e: &Entry| Arc::strong_count(&e.part) == 1;
let mut total: usize = cache
.entries
.iter()
.filter(|e| unheld(e))
.map(|e| e.bytes)
.sum();
let budget = self.inner.budget.load(Relaxed);
while total > budget {
let Some((at, _)) = cache
.entries
.iter()
.enumerate()
.filter(|(_, e)| unheld(e))
.min_by_key(|(_, e)| e.used)
else {
break;
};
total -= cache.entries.swap_remove(at).bytes;
}
part
}
/// `a`'s pattern on the GPU (`None` when it does not fit 32-bit offsets).
pub(crate) fn pattern<T: Value>(&self, a: &Csr<T>) -> Option<Arc<DevPattern>> {
if a.nnz() >= u32::MAX as usize || a.ncols() >= u32::MAX as usize {
return None;
}
let p = a.pattern();
let key = (
p.indices().as_ptr() as usize,
p.offsets().as_ptr() as usize,
0,
);
Some(self.cached(
key,
|| p.clone(),
|| {
let c = self.client();
let offsets: Vec<u32> = p.offsets().iter().map(|&o| o as u32).collect();
let d = DevPattern {
offsets: c.create_from_slice(u32::as_bytes(&offsets)),
indices: c.create_from_slice(u32::as_bytes(&p.indices()[..])),
rows: a.nrows(),
nnz: a.nnz(),
};
(d, 4 * (offsets.len() + a.nnz()))
},
))
}
/// `a`'s values as 32-bit numbers times a scale (1, or 2^32 for words that keep a
/// number in their high half), or `None` when they do not narrow.
pub(crate) fn narrow<T: Value>(&self, a: &Csr<T>) -> Option<Arc<DevNarrow>> {
let v = a.values()?;
let key = (v.as_ptr() as usize, v.len(), 1);
if let Some(n) = self.hit::<DevNarrow>(key) {
return Some(n);
}
// One pass: the largest value, and the low halves of all of them.
let (mut max, mut low) = (0u64, 0u64);
for &x in v.iter() {
let x = x.as_usize() as u64;
max = max.max(x);
low |= x & 0xFFFF_FFFF;
}
let scale = if max <= u32::MAX as u64 {
1u64
} else if low == 0 {
1u64 << 32
} else {
return None;
};
Some(self.cached(
key,
|| v.clone(),
|| {
let n: Vec<u32> = v
.iter()
.map(|&x| (x.as_usize() as u64 / scale) as u32)
.collect();
let d = DevNarrow {
values: self.client().create_from_slice(u32::as_bytes(&n)),
scale,
};
(d, 4 * n.len())
},
))
}
/// PageRank's parts of the graph `out` ([`DevRank`]): the out-degrees from `out`'s
/// host offsets and the long rows of `inn`, with `inn`'s pattern renumbered when `p`
/// (`inn`'s cached pattern, given unless the degrees are skewed) is `None`; cached as
/// the patterns are. `None` when `inn` does not fit 32-bit offsets.
pub(crate) fn rank_parts(
&self,
out: &Csr<u8>,
inn: &Csr<u8>,
p: Option<&DevPattern>,
) -> Option<Arc<DevRank>> {
if inn.nnz() >= u32::MAX as usize || inn.ncols() >= u32::MAX as usize {
return None;
}
let (po, pi) = (out.pattern(), inn.pattern());
let key = (
po.offsets().as_ptr() as usize,
pi.offsets().as_ptr() as usize,
2 + p.is_none() as u8,
);
Some(self.cached(
key,
|| (po.clone(), pi.clone()),
|| {
let n = inn.nrows();
let off = po.offsets();
let deg: Vec<u32> = off.windows(2).map(|w| (w[1] - w[0]) as u32).collect();
let degree = self.upload_u32(°);
let mut bytes = 4 * n;
let placed = p.is_none().then(|| {
let c = self.client();
let place = self.upload_u32(&falling_place(°));
let offsets: Vec<u32> = pi.offsets().iter().map(|&o| o as u32).collect();
let offsets = self.upload_u32(&offsets);
let nnz = inn.nnz();
let plain = c.create_from_slice(u32::as_bytes(&pi.indices()[..]));
let indices = self.alloc(nnz, 4);
let (cc, dim) = grid(nnz);
kernels::renumber::launch(
c,
cc,
dim,
buf(&plain, nnz),
buf(&place, n),
buf(&indices, nnz),
);
self.launched();
bytes += 4 * (2 * n + 1 + nnz);
Placed {
offsets,
indices,
place,
}
});
let offsets = match (&placed, p) {
(Some(pl), _) => &pl.offsets,
(None, Some(p)) => &p.offsets,
(None, None) => unreachable!("a pattern or its renumbered copy"),
};
// Counted, then listed into lists of the counted lengths.
let bins = |lists: (&Handle, usize, &Handle, usize), fill: bool| {
let counters = self.filled_u32(2, 0);
let (c, dim) = grid(n);
kernels::rank_bins::launch(
self.client(),
c,
dim,
buf(offsets, n + 1),
n as u32,
RANK_SHORT,
RANK_LONG,
buf(&counters, 2),
buf(lists.0, lists.1),
buf(lists.2, lists.3),
fill,
);
self.launched();
counters
};
let none = self.alloc(1, 4);
let k = self.read_u32(&bins((&none, 1, &none, 1), false));
let (nmid, nfar) = (k[0] as usize, k[1] as usize);
let (mid, far) = (self.alloc(nmid, 4), self.alloc(nfar, 4));
if nmid + nfar > 0 {
bins((&mid, nmid, &far, nfar), true);
}
bytes += 4 * (nmid + nfar);
(
DevRank {
degree,
mid,
nmid,
far,
nfar,
placed,
},
bytes,
)
},
))
}
/// The computed split's long rows of the graph `out` (with its transpose `inn`), from
/// the host offsets, cached as the patterns are; `None` when a node's out- and in-edges
/// together do not fit 32 bits.
pub(crate) fn split_parts(&self, out: &Csr<u8>, inn: &Csr<u8>) -> Option<Arc<DevSplit>> {
let (po, pi) = (out.pattern(), inn.pattern());
let key = (
po.offsets().as_ptr() as usize,
pi.offsets().as_ptr() as usize,
4,
);
if let Some(p) = self.hit::<DevSplit>(key) {
return Some(p);
}
let (oo, io) = (po.offsets(), pi.offsets());
let mut long = Vec::new();
for v in 0..out.nrows() {
let d = (oo[v + 1] - oo[v]) + (io[v + 1] - io[v]);
if d >= u32::MAX as u64 {
return None;
}
if d > SPLIT_SHORT as u64 {
long.push(v as u32);
}
}
Some(self.cached(
key,
|| (po.clone(), pi.clone()),
|| {
let d = DevSplit {
long: self.upload_u32(&long),
nlong: long.len(),
};
(d, 4 * long.len().max(1))
},
))
}
/// The bytes a round of the computed split holds on the GPU for a graph of `nodes`
/// nodes and `edges` out- and in-edges together: both patterns (32-bit offsets and
/// indices), the part per node going up and the wanted part coming back (the list of
/// long rows is small beside them and not counted).
pub fn split_bytes(nodes: usize, edges: usize) -> u64 {
4 * (2 * (nodes as u64 + 1) + edges as u64) + 8 * nodes as u64
}
/// Whether a round of the computed split on the graph `out` (with its transpose `inn`)
/// into `parts` parts runs on this GPU, as [`kleene_graph::GraphBackend::split_votes`]
/// decides it: 1 to 64 parts, a square graph of at least [`CpuBelow::split`]
/// out-edges whose patterns fit 32-bit offsets, and [`GpuDevice::split_bytes`] within
/// three quarters of the largest memory heap the driver reports (other programs may
/// hold some of the card). Otherwise the CPU kernel answers (the same list). Opens the
/// GPU when the graph passes the size threshold.
pub fn split_on_gpu(&self, out: &Csr<u8>, inn: &Csr<u8>, parts: usize) -> bool {
let n = out.nrows();
if !(1..=64).contains(&parts)
|| n == 0
|| out.ncols() != n
|| inn.nrows() != n
|| inn.ncols() != n
|| out.nnz() < self.cpu_below().split
|| out.nnz() >= u32::MAX as usize
|| inn.nnz() >= u32::MAX as usize
{
return false;
}
let need = Self::split_bytes(n, out.nnz() + inn.nnz());
self.client()
.properties()
.memory
.max_memory()
.is_none_or(|m| need <= m / 4 * 3)
}
/// Whether the GPU computes with 64-bit floats.
pub(crate) fn has_f64(&self) -> bool {
self.client()
.properties()
.supports_type(cubecl::ir::ElemType::Float(cubecl::ir::FloatKind::F64))
}
// Buffers and reads.
pub(crate) fn upload_u32(&self, v: &[u32]) -> Handle {
self.client()
.create_from_slice(u32::as_bytes(if v.is_empty() { &[0] } else { v }))
}
pub(crate) fn upload_u64(&self, v: &[u64]) -> Handle {
self.client()
.create_from_slice(u64::as_bytes(if v.is_empty() { &[0] } else { v }))
}
/// Room for `n` words of `bytes` each (contents undefined).
pub(crate) fn alloc(&self, n: usize, bytes: usize) -> Handle {
self.client().empty(n.max(1) * bytes)
}
/// `n` 32-bit words set to `value`.
pub(crate) fn filled_u32(&self, n: usize, value: u32) -> Handle {
let h = self.alloc(n, 4);
self.fill_u32(&h, n, value);
h
}
pub(crate) fn fill_u32(&self, h: &Handle, n: usize, value: u32) {
let (count, dim) = grid(n);
kernels::fill_u32::launch(self.client(), count, dim, buf(h, n), value);
self.launched();
}
pub(crate) fn fill_word<W: Word>(&self, h: &Handle, n: usize, value: W) {
let v = self.client().create_from_slice(W::as_bytes(&[value]));
let (count, dim) = grid(n);
kernels::fill_word::launch::<W>(self.client(), count, dim, buf(h, n), buf(&v, 1));
self.launched();
}
pub(crate) fn read_u32(&self, h: &Handle) -> Vec<u32> {
u32::from_bytes(&self.client().read_one_unchecked(h.clone())).to_vec()
}
pub(crate) fn read_f32(&self, h: &Handle) -> Vec<f32> {
f32::from_bytes(&self.client().read_one_unchecked(h.clone())).to_vec()
}
pub(crate) fn read_u64(&self, h: &Handle) -> Vec<u64> {
u64::from_bytes(&self.client().read_one_unchecked(h.clone())).to_vec()
}
/// [`SLOTS`] counters at `value`.
pub(crate) fn slots(&self, value: u32) -> Handle {
self.filled_u32(SLOTS, value)
}
pub(crate) fn sum_slots(&self, h: &Handle) -> u64 {
self.read_u32(h).iter().map(|&x| x as u64).sum()
}
/// One counter at 0.
pub(crate) fn counter(&self) -> Handle {
self.filled_u32(1, 0)
}
pub(crate) fn read_counter(&self, h: &Handle) -> usize {
self.read_u32(h)[0] as usize
}
}
/// Cubes for `units` units of 256, as a grid no side of which passes 65535.
pub(crate) fn grid(units: usize) -> (CubeCount, CubeDim) {
let dim = 256usize;
let cubes = units.div_ceil(dim).max(1);
let x = cubes.min(65_535);
let y = cubes.div_ceil(x);
(
CubeCount::Static(x as u32, y as u32, 1),
CubeDim::new_1d(dim as u32),
)
}
/// Cubes for [`LANES`] units per list entry.
pub(crate) fn lanes(entries: usize) -> (CubeCount, CubeDim) {
grid(entries * LANES)
}
pub(crate) fn buf(h: &Handle, len: usize) -> BufferArg {
// SAFETY (see kernels.rs): `len` is at most the element count `h` was created with.
#[allow(unsafe_code)]
unsafe {
BufferArg::from_raw_parts(h.clone(), len.max(1))
}
}
/// The 32- and 64-bit words values live in on the GPU.
pub(crate) trait Word:
Int + CubeElement + Copy + PartialOrd + Send + Sync + 'static
{
const MAX: Self;
fn of<T: Value>(t: T) -> Self;
fn back<T: Value>(self) -> T;
}
impl Word for u32 {
const MAX: Self = u32::MAX;
fn of<T: Value>(t: T) -> Self {
t.as_usize() as u32
}
fn back<T: Value>(self) -> T {
T::from_usize(self as usize).expect("a value that came from T")
}
}
impl Word for u64 {
const MAX: Self = u64::MAX;
fn of<T: Value>(t: T) -> Self {
t.as_usize() as u64
}
fn back<T: Value>(self) -> T {
T::from_usize(self as usize).expect("a value that came from T")
}
}
/// Whether values of `T` take 64-bit words.
pub(crate) fn wide<T: Value>() -> bool {
size_of::<T>() > 4
}
pub(crate) fn words(n: usize) -> usize {
n.div_ceil(32).max(1)
}
const UNKNOWN: usize = usize::MAX;
/// A vector on the GPU: a word per place and a bit per place for its entries. The count
/// of entries is read back (and kept) when asked; a list of the entries is made when a
/// kernel needs one and kept until the vector changes.
pub struct GpuVector<T: Value> {
pub(crate) n: usize,
pub(crate) vals: Handle,
pub(crate) bits: Handle,
known: AtomicUsize,
list: OnceLock<Handle>,
pub(crate) device: GpuDevice,
_t: PhantomData<fn() -> T>,
}
impl<T: Value> fmt::Debug for GpuVector<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let known = self.known.load(Relaxed);
f.debug_struct("GpuVector")
.field("len", &self.n)
.field("nvals", &(known != UNKNOWN).then_some(known))
.finish()
}
}
impl<T: Value> Clone for GpuVector<T> {
fn clone(&self) -> Self {
let d = &self.device;
let word = if wide::<T>() { 2 } else { 1 };
let out = GpuVector::<T>::alloc(self.n, d);
copy(d, &self.vals, &out.vals, self.n.max(1) * word);
copy(d, &self.bits, &out.bits, words(self.n));
out.known.store(self.known.load(Relaxed), Relaxed);
out
}
}
fn copy(d: &GpuDevice, from: &Handle, to: &Handle, n: usize) {
let (count, dim) = grid(n);
kernels::copy_u32::launch(d.client(), count, dim, buf(from, n), buf(to, n));
d.launched();
}
impl<T: Value> GpuVector<T> {
/// Room for a vector (bits undefined).
fn alloc(n: usize, d: &GpuDevice) -> Self {
GpuVector {
n,
vals: d.alloc(n, if wide::<T>() { 8 } else { 4 }),
bits: d.alloc(words(n), 4),
known: AtomicUsize::new(UNKNOWN),
list: OnceLock::new(),
device: d.clone(),
_t: PhantomData,
}
}
/// An empty vector of `n` places.
pub(crate) fn empty(n: usize, d: &GpuDevice) -> Self {
let v = Self::alloc(n, d);
d.fill_u32(&v.bits, words(n), 0);
v.known.store(0, Relaxed);
v
}
/// An empty vector whose words start at `zero`.
pub(crate) fn empty_at(n: usize, zero: T, d: &GpuDevice) -> Self {
let v = Self::empty(n, d);
if wide::<T>() {
d.fill_word::<u64>(&v.vals, n, u64::of(zero));
} else {
d.fill_word::<u32>(&v.vals, n, u32::of(zero));
}
v
}
pub(crate) fn upload(v: &Vector<T>, d: &GpuDevice) -> Self {
let n = v.len();
if v.nvals() == 0 {
return Self::empty(n, d);
}
let mut bits = vec![0u32; words(n)];
let out = if wide::<T>() {
let mut w = vec![0u64; n.max(1)];
for (i, x) in v.iter() {
w[i as usize] = u64::of(x);
bits[i as usize / 32] |= 1 << (i % 32);
}
d.upload_u64(&w)
} else {
let mut w = vec![0u32; n.max(1)];
for (i, x) in v.iter() {
w[i as usize] = u32::of(x);
bits[i as usize / 32] |= 1 << (i % 32);
}
d.upload_u32(&w)
};
GpuVector {
n,
vals: out,
bits: d.upload_u32(&bits),
known: AtomicUsize::new(v.nvals()),
list: OnceLock::new(),
device: d.clone(),
_t: PhantomData,
}
}
/// The set places, rising (from the bits).
pub(crate) fn host_indices(&self) -> Vec<u32> {
let bits = self.device.read_u32(&self.bits);
let mut out = Vec::new();
for (k, &w) in bits.iter().enumerate() {
let mut w = w;
while w != 0 {
let b = w.trailing_zeros();
w &= w - 1;
let i = k as u32 * 32 + b;
if (i as usize) < self.n {
out.push(i);
}
}
}
out
}
pub(crate) fn download(&self) -> Vector<T> {
let idx = self.host_indices();
let val: Vec<T> = if wide::<T>() {
let w = self.device.read_u64(&self.vals);
idx.iter().map(|&i| w[i as usize].back::<T>()).collect()
} else {
let w = self.device.read_u32(&self.vals);
idx.iter().map(|&i| w[i as usize].back::<T>()).collect()
};
Vector::sparse(self.n, idx, val).expect("rising places")
}
/// The number of entries (read back once per change).
pub(crate) fn nvals(&self) -> usize {
let k = self.known.load(Relaxed);
if k != UNKNOWN {
return k;
}
let d = &self.device;
let slots = d.slots(0);
let nw = words(self.n);
let (count, dim) = grid(nw);
kernels::count_bits::launch(
d.client(),
count,
dim,
buf(&self.bits, nw),
0,
self.n as u32,
buf(&slots, SLOTS),
);
d.launched();
let k = d.sum_slots(&slots) as usize;
self.known.store(k, Relaxed);
k
}
/// The entries as an unordered list of places, with its length.
pub(crate) fn list(&self) -> (&Handle, usize) {
let nf = self.nvals();
let h = self.list.get_or_init(|| {
let d = &self.device;
let list = d.alloc(nf, 4);
let counter = d.counter();
let nw = words(self.n);
let (count, dim) = grid(nw);
kernels::compact::launch(
d.client(),
count,
dim,
buf(&self.bits, nw),
self.n as u32,
buf(&counter, 1),
buf(&list, nf),
);
d.launched();
list
});
(h, nf)
}
/// The vector changed on the GPU: its count and list are stale.
pub(crate) fn changed(&mut self) {
self.known.store(UNKNOWN, Relaxed);
self.list = OnceLock::new();
}
/// Every entry removed.
pub(crate) fn clear(&mut self) {
self.device.fill_u32(&self.bits, words(self.n), 0);
self.list = OnceLock::new();
self.known.store(0, Relaxed);
}
}
/// A mask on the GPU: a bit per place and the complement flag (a place is allowed when its
/// bit differs from the flag), as the host [`Mask`] keeps it.
pub struct GpuMask {
pub(crate) n: usize,
pub(crate) bits: Handle,
pub(crate) complement: bool,
pub(crate) device: GpuDevice,
}
impl fmt::Debug for GpuMask {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GpuMask")
.field("len", &self.n)
.field("complement", &self.complement)
.finish()
}
}
impl Clone for GpuMask {
fn clone(&self) -> Self {
let bits = self.device.alloc(words(self.n), 4);
copy(&self.device, &self.bits, &bits, words(self.n));
GpuMask {
n: self.n,
bits,
complement: self.complement,
device: self.device.clone(),
}
}
}
impl GpuMask {
pub(crate) fn upload(m: &Mask, d: &GpuDevice) -> Self {
let n = m.len();
let mut bits = Vec::with_capacity(words(n));
for &w in m.bits().words() {
bits.push(w as u32);
bits.push((w >> 32) as u32);
}
bits.resize(words(n), 0);
// Bits past the end stay clear, whatever the host words hold.
if !n.is_multiple_of(32) {
let last = words(n) - 1;
bits[last] &= (1u32 << (n % 32)) - 1;
}
GpuMask {
n,
bits: d.upload_u32(&bits),
complement: m.is_complement(),
device: d.clone(),
}
}
pub(crate) fn download(&self) -> Mask {
let bits = self.device.read_u32(&self.bits);
let mut idx = Vec::new();
for (k, &w) in bits.iter().enumerate() {
let mut w = w;
while w != 0 {
let b = w.trailing_zeros();
w &= w - 1;
let i = k * 32 + b as usize;
if i < self.n {
idx.push(i as u32);
}
}
}
let m = Mask::from_indices(self.n, &idx);
if self.complement { m.complement() } else { m }
}
pub(crate) fn comp(&self) -> u32 {
self.complement as u32
}
}
/// A matrix of the GPU backend: the host copy, and its GPU form made on first use (shared
/// through the device's cache with every matrix over the same host buffers).
#[derive(Clone)]
pub struct GpuMatrix<T: Value> {
pub(crate) host: Csr<T>,
pub(crate) dev: Arc<OnceLock<Option<DevCsr>>>,
pub(crate) device: GpuDevice,
}
impl<T: Value> fmt::Debug for GpuMatrix<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GpuMatrix")
.field("shape", &(self.host.nrows(), self.host.ncols()))
.field("nnz", &self.host.nnz())
.finish()
}
}
/// A matrix's values on the GPU.
pub(crate) enum DevValues {
Narrow(Arc<DevNarrow>),
Words(Handle),
}
pub(crate) struct DevCsr {
pub pattern: Arc<DevPattern>,
pub values: Option<DevValues>,
}
impl<T: Value> GpuMatrix<T> {
pub(crate) fn new(host: Csr<T>, device: &GpuDevice) -> Self {
GpuMatrix {
host,
dev: Arc::new(OnceLock::new()),
device: device.clone(),
}
}
/// The GPU form (`None` when it does not fit 32-bit offsets).
pub(crate) fn dev(&self) -> Option<&DevCsr> {
self.dev
.get_or_init(|| {
let a = &self.host;
let pattern = self.device.pattern(a)?;
let values = a.values().map(|v| match self.device.narrow(a) {
Some(n) => DevValues::Narrow(n),
None if wide::<T>() => {
let w: Vec<u64> = v.iter().map(|&x| u64::of(x)).collect();
DevValues::Words(self.device.upload_u64(&w))
}
None => {
let w: Vec<u32> = v.iter().map(|&x| u32::of(x)).collect();
DevValues::Words(self.device.upload_u32(&w))
}
});
Some(DevCsr { pattern, values })
})
.as_ref()
}
}
/// A whole number from the environment variable `name`, if it holds one.
fn env_usize(name: &str) -> Option<usize> {
std::env::var(name)
.ok()
.and_then(|s| s.parse::<usize>().ok())
}