Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-cubecl/src/kernels.rs

//! The GPU kernels.
//!
//! A vector on the GPU is dense: a word per place (32 or 64 bits) and a bit per place
//! saying whether it holds an entry, in 32-bit words. A mask is such bits plus a
//! complement flag (`comp`: a place is allowed when its bit differs from it). A list is an
//! unordered array of places, made from bits when a kernel needs one unit per entry.
//!
//! Kernels that walk a row from a list give each list entry [`LANES`] units, which take the
//! row's edges in turn, so a vertex with many edges is shared out instead of holding up
//! one unit. Sums (edges examined, entries counted) go into [`SLOTS`] counters spread by
//! unit, which the host adds up, rather than one contended counter.
//!
//! The launch functions take raw buffer lengths, so this module holds the crate's only
//! `unsafe`: every launch passes each buffer with the length it was created with.
#![allow(unsafe_code)]
#![allow(clippy::too_many_arguments)]
// CubeCL evaluates both sides of `&&` (a guard does not stop the read or the atomic after
// it), so guards are nested `if`s; it expands `a = a | b` on buffer elements, kept so.
#![allow(clippy::collapsible_if, clippy::assign_op_pattern)]

use cubecl::prelude::*;

/// Units per list entry in the kernels that walk rows.
pub const LANES: usize = 32;
/// Counters a sum is spread over.
pub const SLOTS: usize = 256;

/// `a ⊕ b`: min (`op` 0) or or (`op` 1).
#[cube]
fn add<W: Int>(a: W, b: W, #[comptime] op: u32) -> W {
    let mut r = a | b;
    if comptime![op == 0] {
        r = a;
        if b < a {
            r = b;
        }
    }
    r
}

/// `a ⊗ b`: saturating `+` with `top` absorbing (min-plus), or `&` (or-and).
#[cube]
fn mul<W: Int>(a: W, b: W, top: W, #[comptime] op: u32) -> W {
    let mut r = a & b;
    if comptime![op == 0] {
        r = top;
        if a != top && b != top {
            let s = a + b;
            if s >= a {
                r = s;
            }
        }
    }
    r
}

/// Entry `k`'s value: a word, or (`narrow`) a 32-bit number times `consts[2]`.
#[cube]
#[allow(unused_assignments)]
fn value<W: Int>(
    values: &[W],
    values32: &[u32],
    consts: &[W],
    k: usize,
    #[comptime] narrow: bool,
) -> W {
    let mut v = values[0];
    if comptime![narrow] {
        v = W::cast_from(values32[k]) * consts[2];
    } else {
        v = values[k];
    }
    v
}

/// Bit `i` of plain words.
#[cube]
fn bit(words: &[u32], i: usize) -> u32 {
    (words[i / 32] >> (i % 32) as u32) & 1u32
}

/// Word `k` of a bit array with the bits past `n` cleared.
#[cube]
fn tail(w: u32, k: usize, n: u32) -> u32 {
    let mut out = w;
    let base = k * 32;
    let n = n as usize;
    if base + 32 > n {
        let valid = n - base;
        out = w & ((1u32 << valid as u32) - 1u32);
    }
    out
}

/// `out[i] = value`.
#[cube(launch)]
pub fn fill_u32(out: &mut [u32], value: u32) {
    let i = ABSOLUTE_POS;
    if i < out.len() {
        out[i] = value;
    }
}

/// `out[i] = value[0]`.
#[cube(launch)]
pub fn fill_word<W: Int>(out: &mut [W], value: &[W]) {
    let i = ABSOLUTE_POS;
    if i < out.len() {
        out[i] = value[0];
    }
}

/// `out[i] = i`.
#[cube(launch)]
pub fn iota(out: &mut [u32]) {
    let i = ABSOLUTE_POS;
    if i < out.len() {
        out[i] = i as u32;
    }
}

/// `dst[i] = src[i]`.
#[cube(launch)]
pub fn copy_u32(src: &[u32], dst: &mut [u32]) {
    let i = ABSOLUTE_POS;
    if i < dst.len() {
        dst[i] = src[i];
    }
}

/// `dst[k] |= src[k]`.
#[cube(launch)]
pub fn or_words(src: &[u32], dst: &mut [u32]) {
    let k = ABSOLUTE_POS;
    if k < dst.len() {
        dst[k] = dst[k] | src[k];
    }
}

/// The places of `n` the bits allow (`comp` flips them), into the slots.
#[cube(launch)]
pub fn count_bits(bits: &[u32], comp: u32, n: u32, slots: &[Atomic<u32>]) {
    let k = ABSOLUTE_POS;
    if k < bits.len() {
        let mut w = bits[k];
        if comp == 1u32 {
            w = !w;
        }
        w = tail(w, k, n);
        if w != 0u32 {
            slots[k % 256].fetch_add(w.count_ones());
        }
    }
}

/// The set places of the bits, appended to `list` (unordered; `counter[0]` its length).
#[cube(launch)]
pub fn compact(bits: &[u32], n: u32, counter: &[Atomic<u32>], list: &mut [u32]) {
    let k = ABSOLUTE_POS;
    if k < bits.len() {
        let w = tail(bits[k], k, n);
        if w != 0u32 {
            let mut at = counter[0].fetch_add(w.count_ones()) as usize;
            for b in 0..32u32 {
                if ((w >> b) & 1u32) == 1u32 {
                    list[at] = (k as u32) * 32u32 + b;
                    at += 1;
                }
            }
        }
    }
}

/// `vals[i] = value[0]` and the bit set at each listed place.
#[cube(launch)]
pub fn scatter_value<W: Int>(idx: &[u32], vals: &mut [W], bits: &[Atomic<u32>], value: &[W]) {
    let e = ABSOLUTE_POS;
    if e < idx.len() {
        let i = idx[e] as usize;
        vals[i] = value[0];
        bits[i / 32].fetch_or(1u32 << (i % 32) as u32);
    }
}

/// `w(i) = value[0]` wherever `at` has an entry.
#[cube(launch)]
pub fn assign_words<W: Int>(at_bits: &[u32], w_bits: &mut [u32], w_vals: &mut [W], value: &[W]) {
    let k = ABSOLUTE_POS;
    if k < w_bits.len() {
        let a = at_bits[k];
        if a != 0u32 {
            w_bits[k] = w_bits[k] | a;
            for b in 0..32u32 {
                if ((a >> b) & 1u32) == 1u32 {
                    w_vals[k * 32 + b as usize] = value[0];
                }
            }
        }
    }
}

/// `w ⊕= u`; `c` gets the entries of `w` that are new or changed (its bits written whole).
#[cube(launch)]
pub fn accumulate<W: Int>(
    w_vals: &mut [W],
    w_bits: &mut [u32],
    u_vals: &[W],
    u_bits: &[u32],
    c_vals: &mut [W],
    c_bits: &mut [u32],
    #[comptime] op: u32,
) {
    let k = ABSOLUTE_POS;
    if k < w_bits.len() {
        let ub = u_bits[k];
        let wb = w_bits[k];
        let mut cb = 0u32;
        if ub != 0u32 {
            for b in 0..32u32 {
                if ((ub >> b) & 1u32) == 1u32 {
                    let i = k * 32 + b as usize;
                    let x = u_vals[i];
                    if ((wb >> b) & 1u32) == 0u32 {
                        w_vals[i] = x;
                        c_vals[i] = x;
                        cb = cb | (1u32 << b);
                    } else {
                        let old = w_vals[i];
                        let y = add::<W>(old, x, op);
                        if y != old {
                            w_vals[i] = y;
                            c_vals[i] = y;
                            cb = cb | (1u32 << b);
                        }
                    }
                }
            }
            w_bits[k] = wb | ub;
        }
        c_bits[k] = cb;
    }
}

/// `Σ` row lengths at the set places, into the slots.
#[cube(launch)]
pub fn row_lengths(offsets: &[u32], bits: &[u32], n: u32, slots: &[Atomic<u32>]) {
    let k = ABSOLUTE_POS;
    if k < bits.len() {
        let w = tail(bits[k], k, n);
        if w != 0u32 {
            let mut sum = 0u32;
            for b in 0..32u32 {
                if ((w >> b) & 1u32) == 1u32 {
                    let i = k * 32 + b as usize;
                    sum += offsets[i + 1] - offsets[i];
                }
            }
            slots[k % 256].fetch_add(sum);
        }
    }
}

/// `out(r) = ⊕_k A[r, k] ⊗ x(k)` over the rows the mask allows; out's bits must start
/// clear. `consts`: the semiring's zero, the min-plus top, the narrow values' scale.
#[cube(launch)]
pub fn pull<W: Int>(
    offsets: &[u32],
    indices: &[u32],
    values: &[W],
    values32: &[u32],
    x_vals: &[W],
    x_bits: &[u32],
    mask: &[u32],
    comp: u32,
    out_vals: &mut [W],
    out_bits: &[Atomic<u32>],
    consts: &[W],
    n: u32,
    #[comptime] op: u32,
    #[comptime] valued: bool,
    #[comptime] narrow: bool,
    #[comptime] masked: bool,
) {
    let r = ABSOLUTE_POS;
    if r < n as usize {
        let mut keep = true;
        if comptime![masked] {
            keep = (bit(mask, r) ^ comp) == 1u32;
        }
        if keep {
            let top = consts[1];
            let mut acc = consts[0];
            let mut found = false;
            let end = offsets[r + 1] as usize;
            let mut k = offsets[r] as usize;
            while k < end {
                let j = indices[k] as usize;
                if bit(x_bits, j) == 1u32 {
                    let mut p = x_vals[j];
                    if comptime![valued] {
                        p = mul::<W>(p, value::<W>(values, values32, consts, k, narrow), top, op);
                    }
                    if found {
                        acc = add::<W>(acc, p, op);
                    } else {
                        acc = p;
                    }
                    found = true;
                }
                k += 1;
            }
            if found {
                out_vals[r] = acc;
                out_bits[r / 32].fetch_or(1u32 << (r % 32) as u32);
            }
        }
    }
}

/// For each listed entry `u` of `x`, `out(j) ⊕= x(u) ⊗ A[u, j]` at every target the mask
/// allows. Out's words must start at the semiring's zero and its bits clear.
#[cube(launch)]
pub fn push<W: Int>(
    offsets: &[u32],
    indices: &[u32],
    values: &[W],
    values32: &[u32],
    flist: &[u32],
    nf: u32,
    x_vals: &[W],
    mask: &[u32],
    comp: u32,
    out_vals: &[Atomic<W>],
    out_bits: &[Atomic<u32>],
    consts: &[W],
    #[comptime] op: u32,
    #[comptime] valued: bool,
    #[comptime] narrow: bool,
    #[comptime] masked: bool,
) {
    let e = ABSOLUTE_POS / 32;
    let lane = ABSOLUTE_POS % 32;
    if e < nf as usize {
        let u = flist[e] as usize;
        let xu = x_vals[u];
        let top = consts[1];
        let end = offsets[u + 1] as usize;
        let mut k = offsets[u] as usize + lane;
        while k < end {
            let j = indices[k] as usize;
            let mut keep = true;
            if comptime![masked] {
                keep = (bit(mask, j) ^ comp) == 1u32;
            }
            if keep {
                let mut p = xu;
                if comptime![valued] {
                    p = mul::<W>(p, value::<W>(values, values32, consts, k, narrow), top, op);
                }
                if comptime![op == 0] {
                    out_vals[j].fetch_min(p);
                } else {
                    out_vals[j].fetch_or(p);
                }
                out_bits[j / 32].fetch_or(1u32 << (j % 32) as u32);
            }
            k += 32;
        }
    }
}

/// Claim place `j` in the open mask: true when this unit closed it.
#[cube]
fn claim(open: &[Atomic<u32>], j: usize, comp: u32) -> bool {
    let sh = (j % 32) as u32;
    let m = 1u32 << sh;
    let cur = open[j / 32].load();
    let mut won = false;
    // Allowed: the bit differs from `comp`.
    if (((cur >> sh) & 1u32) ^ comp) == 1u32 {
        if comp == 1u32 {
            won = (open[j / 32].fetch_or(m) & m) == 0u32;
        } else {
            won = (open[j / 32].fetch_and(!m) & m) != 0u32;
        }
    }
    won
}

/// A traversal step pushing: every open target of a listed frontier vertex is claimed
/// (closed in `open`) and set in `next` with the value 1. Edges examined go to the slots.
#[cube(launch)]
pub fn step_push(
    offsets: &[u32],
    indices: &[u32],
    flist: &[u32],
    nf: u32,
    open: &[Atomic<u32>],
    comp: u32,
    next_bits: &[Atomic<u32>],
    next_vals: &mut [u32],
    slots: &[Atomic<u32>],
) {
    let e = ABSOLUTE_POS / 32;
    let lane = ABSOLUTE_POS % 32;
    if e < nf as usize {
        let u = flist[e] as usize;
        let start = offsets[u] as usize;
        let end = offsets[u + 1] as usize;
        if lane == 0 && end > start {
            slots[e % 256].fetch_add((end - start) as u32);
        }
        let mut k = start + lane;
        while k < end {
            let j = indices[k] as usize;
            if claim(open, j, comp) {
                next_vals[j] = 1u32;
                next_bits[j / 32].fetch_or(1u32 << (j % 32) as u32);
            }
            k += 32;
        }
    }
}

/// A traversal step pulling: every open place looks along its in-edges for a frontier
/// vertex and stops at the first; found ones are closed and set in `next`.
#[cube(launch)]
pub fn step_pull(
    offsets: &[u32],
    indices: &[u32],
    x_bits: &[u32],
    open: &[Atomic<u32>],
    comp: u32,
    next_bits: &[Atomic<u32>],
    next_vals: &mut [u32],
    slots: &[Atomic<u32>],
    n: u32,
) {
    let r = ABSOLUTE_POS;
    if r < n as usize {
        let sh = (r % 32) as u32;
        let m = 1u32 << sh;
        let cur = open[r / 32].load();
        if (((cur >> sh) & 1u32) ^ comp) == 1u32 {
            let end = offsets[r + 1] as usize;
            let mut k = offsets[r] as usize;
            let mut seen = 0u32;
            let mut found = false;
            while k < end {
                seen += 1u32;
                if bit(x_bits, indices[k] as usize) == 1u32 {
                    found = true;
                    k = end;
                }
                k += 1;
            }
            if seen > 0u32 {
                slots[r % 256].fetch_add(seen);
            }
            if found {
                if comp == 1u32 {
                    open[r / 32].fetch_or(m);
                } else {
                    open[r / 32].fetch_and(!m);
                }
                next_vals[r] = 1u32;
                next_bits[r / 32].fetch_or(m);
            }
        }
    }
}

/// Mark `j` changed; the first marker appends it to `list`.
#[cube]
fn mark(changed: &[Atomic<u32>], j: usize, counter: &[Atomic<u32>], list: &mut [u32]) {
    let m = 1u32 << (j % 32) as u32;
    if (changed[j / 32].fetch_or(m) & m) == 0u32 {
        let at = counter[0].fetch_add(1u32) as usize;
        list[at] = j as u32;
    }
}

/// `bits` cleared at each listed place.
#[cube(launch)]
pub fn clear_listed(list: &[u32], count: u32, bits: &[Atomic<u32>]) {
    let e = ABSOLUTE_POS;
    if e < count as usize {
        let j = list[e] as usize;
        bits[j / 32].fetch_and(!(1u32 << (j % 32) as u32));
    }
}

/// Shortest paths: each listed vertex `u` offers `((d(u) + w) << 32) | u` to its targets
/// (`packed` holds `(distance << 32) | parent`); a target that takes it is marked changed.
#[cube(launch)]
pub fn relax(
    offsets: &[u32],
    indices: &[u32],
    weights: &[u32],
    flist: &[u32],
    nf: u32,
    packed: &[Atomic<u64>],
    changed: &[Atomic<u32>],
    counter: &[Atomic<u32>],
    clist: &mut [u32],
    #[comptime] valued: bool,
) {
    let e = ABSOLUTE_POS / 32;
    let lane = ABSOLUTE_POS % 32;
    if e < nf as usize {
        let u = flist[e] as usize;
        let du = packed[u].load() >> 32u64;
        let end = offsets[u + 1] as usize;
        let mut k = offsets[u] as usize + lane;
        while k < end {
            let j = indices[k] as usize;
            let mut w = 1u64;
            if comptime![valued] {
                w = u64::cast_from(weights[k]);
            }
            let cand = ((du + w) << 32u64) | u64::cast_from(u as u32);
            if cand < packed[j].load() {
                let old = packed[j].fetch_min(cand);
                if cand < old {
                    mark(changed, j, counter, clist);
                }
            }
            k += 32;
        }
    }
}

/// Shortest paths: each changed vertex is unmarked, then goes to the near list when its
/// distance is under `limit`, else into the pending bits.
#[cube(launch)]
pub fn split(
    clist: &[u32],
    nc: u32,
    changed: &[Atomic<u32>],
    packed: &[u64],
    limit: u64,
    pending: &[Atomic<u32>],
    counter: &[Atomic<u32>],
    flist: &mut [u32],
) {
    let e = ABSOLUTE_POS;
    if e < nc as usize {
        let j = clist[e] as usize;
        let m = 1u32 << (j % 32) as u32;
        changed[j / 32].fetch_and(!m);
        if (packed[j] >> 32u64) < limit {
            pending[j / 32].fetch_and(!m);
            let at = counter[0].fetch_add(1u32) as usize;
            flist[at] = j as u32;
        } else {
            pending[j / 32].fetch_or(m);
        }
    }
}

/// Shortest paths: the least distance among pending vertices, into the slots.
#[cube(launch)]
pub fn pending_min(pending: &[u32], packed: &[u64], slots: &[Atomic<u32>]) {
    let k = ABSOLUTE_POS;
    if k < pending.len() {
        let w = pending[k];
        if w != 0u32 {
            let mut least = 0xFFFF_FFFF_FFFF_FFFFu64;
            for b in 0..32u32 {
                if ((w >> b) & 1u32) == 1u32 {
                    let d = packed[k * 32 + b as usize] >> 32u64;
                    if d < least {
                        least = d;
                    }
                }
            }
            slots[k % 256].fetch_min(u32::cast_from(least));
        }
    }
}

/// Shortest paths: pending vertices under `limit` move to the list.
#[cube(launch)]
pub fn extract(
    pending: &mut [u32],
    packed: &[u64],
    limit: u64,
    counter: &[Atomic<u32>],
    flist: &mut [u32],
) {
    let k = ABSOLUTE_POS;
    if k < pending.len() {
        let w = pending[k];
        if w != 0u32 {
            let mut keep = w;
            for b in 0..32u32 {
                if ((w >> b) & 1u32) == 1u32 {
                    let i = k * 32 + b as usize;
                    if (packed[i] >> 32u64) < limit {
                        keep = keep & !(1u32 << b);
                        let at = counter[0].fetch_add(1u32) as usize;
                        flist[at] = i as u32;
                    }
                }
            }
            pending[k] = keep;
        }
    }
}

/// `packed[i] = value` for the one listed place.
#[cube(launch)]
pub fn set_u64(packed: &mut [u64], at: u32, value: u64) {
    if ABSOLUTE_POS == 0 {
        packed[at as usize] = value;
    }
}

/// Union-find: hook the trees of `a` and `b` (parents in `f`, roots their own parents),
/// the higher root under the lower (Afforest's link).
#[cube]
fn link(f: &[Atomic<u32>], a: u32, b: u32) {
    let mut p1 = f[a as usize].load();
    let mut p2 = f[b as usize].load();
    while p1 != p2 {
        let mut high = p1;
        let mut low = p2;
        if p2 > p1 {
            high = p2;
            low = p1;
        }
        let ph = f[high as usize].load();
        let mut done = ph == low;
        if !done && ph == high {
            done = f[high as usize].compare_exchange_weak(high, low) == high;
        }
        if done {
            p2 = p1;
        } else {
            p1 = f[f[high as usize].load() as usize].load();
            p2 = f[low as usize].load();
        }
    }
}

/// The root of `v` (the tree is only read).
#[cube]
fn root(f: &[Atomic<u32>], v: u32) -> u32 {
    let mut r = v;
    let mut p = f[r as usize].load();
    while p != r {
        r = p;
        p = f[r as usize].load();
    }
    r
}

/// Union-find: link each vertex with its row's entries `from .. from + count` (clipped to
/// the row), skipping (when `skip` is not `u32::MAX`) vertices whose root is `skip`.
#[cube(launch)]
pub fn link_rows(
    offsets: &[u32],
    indices: &[u32],
    f: &[Atomic<u32>],
    from: u32,
    count: u32,
    skip: u32,
    n: u32,
) {
    let v = ABSOLUTE_POS;
    if v < n as usize {
        let mut go = true;
        if skip != u32::MAX {
            go = root(f, v as u32) != skip;
        }
        if go {
            let start = offsets[v] + from;
            let end = offsets[v + 1];
            let mut stop = end;
            if count != u32::MAX && start + count < end {
                stop = start + count;
            }
            let mut k = start;
            while k < stop {
                link(f, v as u32, indices[k as usize]);
                k += 1u32;
            }
        }
    }
}

/// Union-find: every vertex points at its root.
#[cube(launch)]
pub fn compress(f: &[Atomic<u32>], n: u32) {
    let v = ABSOLUTE_POS;
    if v < n as usize {
        let r = root(f, v as u32);
        f[v].store(r);
    }
}

/// `out[e] = f[at[e]]`.
#[cube(launch)]
pub fn gather(f: &[u32], at: &[u32], out: &mut [u32]) {
    let e = ABSOLUTE_POS;
    if e < out.len() {
        out[e] = f[at[e] as usize];
    }
}

/// Strong components: a live vertex (`of == MAX`) with no live in- or out-neighbour other
/// than itself is alone; it is named and counted into the slots.
#[cube(launch)]
pub fn trim(
    out_off: &[u32],
    out_idx: &[u32],
    in_off: &[u32],
    in_idx: &[u32],
    of: &[Atomic<u32>],
    slots: &[Atomic<u32>],
    n: u32,
) {
    let v = ABSOLUTE_POS;
    let mut live = false;
    if v < n as usize {
        live = of[v].load() == u32::MAX;
    }
    if live {
        let mut has_out = false;
        let mut k = out_off[v] as usize;
        let end = out_off[v + 1] as usize;
        while k < end {
            let j = out_idx[k] as usize;
            if j != v {
                if of[j].load() == u32::MAX {
                    has_out = true;
                    k = end;
                }
            }
            k += 1;
        }
        let mut has_in = false;
        if has_out {
            let mut k = in_off[v] as usize;
            let end = in_off[v + 1] as usize;
            while k < end {
                let j = in_idx[k] as usize;
                if j != v {
                    if of[j].load() == u32::MAX {
                        has_in = true;
                        k = end;
                    }
                }
                k += 1;
            }
        }
        if !has_in {
            of[v].store(v as u32);
            slots[v % 256].fetch_add(1u32);
        }
    }
}

/// Strong components: each live vertex takes its own number as colour and is listed; the
/// rest take `u32::MAX`.
#[cube(launch)]
pub fn colour_init(
    of: &[u32],
    colour: &mut [u32],
    counter: &[Atomic<u32>],
    list: &mut [u32],
    n: u32,
) {
    let v = ABSOLUTE_POS;
    if v < n as usize {
        if of[v] == u32::MAX {
            colour[v] = v as u32;
            let at = counter[0].fetch_add(1u32) as usize;
            list[at] = v as u32;
        } else {
            colour[v] = u32::MAX;
        }
    }
}

/// Strong components: each listed vertex sends its colour to its live targets; a target
/// whose colour falls is marked changed.
#[cube(launch)]
pub fn colour_push(
    offsets: &[u32],
    indices: &[u32],
    flist: &[u32],
    nf: u32,
    of: &[u32],
    colour: &[Atomic<u32>],
    changed: &[Atomic<u32>],
    counter: &[Atomic<u32>],
    clist: &mut [u32],
) {
    let e = ABSOLUTE_POS / 32;
    let lane = ABSOLUTE_POS % 32;
    if e < nf as usize {
        let u = flist[e] as usize;
        let cu = colour[u].load();
        let end = offsets[u + 1] as usize;
        let mut k = offsets[u] as usize + lane;
        while k < end {
            let j = indices[k] as usize;
            if of[j] == u32::MAX {
                if cu < colour[j].load() {
                    let old = colour[j].fetch_min(cu);
                    if cu < old {
                        mark(changed, j, counter, clist);
                    }
                }
            }
            k += 32;
        }
    }
}

/// Strong components: a live vertex that kept its own colour is a root: named, listed.
#[cube(launch)]
pub fn roots(of: &mut [u32], colour: &[u32], counter: &[Atomic<u32>], list: &mut [u32], n: u32) {
    let v = ABSOLUTE_POS;
    if v < n as usize {
        if of[v] == u32::MAX {
            if colour[v] == v as u32 {
                of[v] = v as u32;
                let at = counter[0].fetch_add(1u32) as usize;
                list[at] = v as u32;
            }
        }
    }
}

/// Strong components: from each listed vertex, back along its in-edges to live vertices of
/// its colour; each is named by the colour (once) and listed.
#[cube(launch)]
pub fn back_push(
    offsets: &[u32],
    indices: &[u32],
    flist: &[u32],
    nf: u32,
    colour: &[u32],
    of: &[Atomic<u32>],
    counter: &[Atomic<u32>],
    clist: &mut [u32],
) {
    let e = ABSOLUTE_POS / 32;
    let lane = ABSOLUTE_POS % 32;
    if e < nf as usize {
        let u = flist[e] as usize;
        let cu = colour[u];
        let end = offsets[u + 1] as usize;
        let mut k = offsets[u] as usize + lane;
        while k < end {
            let p = indices[k] as usize;
            if colour[p] == cu {
                if of[p].load() == u32::MAX {
                    if of[p].compare_exchange_weak(u32::MAX, cu) == u32::MAX {
                        let at = counter[0].fetch_add(1u32) as usize;
                        clist[at] = p as u32;
                    }
                }
            }
            k += 32;
        }
    }
}

/// Source sets: `vals[idx[e]] |= bits[e]`.
#[cube(launch)]
pub fn seed_sets(idx: &[u32], bits: &[u64], vals: &[Atomic<u64>]) {
    let e = ABSOLUTE_POS;
    if e < idx.len() {
        vals[idx[e] as usize].fetch_or(bits[e]);
    }
}

/// Source sets: each listed vertex ors its set into its targets; a target that gains a
/// source is marked changed.
#[cube(launch)]
pub fn sets_push(
    offsets: &[u32],
    indices: &[u32],
    flist: &[u32],
    nf: u32,
    vals: &[Atomic<u64>],
    changed: &[Atomic<u32>],
    counter: &[Atomic<u32>],
    clist: &mut [u32],
) {
    let e = ABSOLUTE_POS / 32;
    let lane = ABSOLUTE_POS % 32;
    if e < nf as usize {
        let u = flist[e] as usize;
        let xu = vals[u].load();
        let end = offsets[u + 1] as usize;
        let mut k = offsets[u] as usize + lane;
        while k < end {
            let j = indices[k] as usize;
            if (vals[j].load() | xu) != vals[j].load() {
                let old = vals[j].fetch_or(xu);
                if (old | xu) != old {
                    mark(changed, j, counter, clist);
                }
            }
            k += 32;
        }
    }
}

// PageRank (GAP's pull rounds). Scores and shares are `f32`, as on the CPU; the change of a
// round is summed in `F` (`f64` where the GPU has it).

/// The first round's scores (`init`) and shares (`init / out-degree`, 0 without out-edges),
/// a vertex's share at `place[v]` when `placed`.
#[cube(launch)]
pub fn rank_init(
    degree: &[u32],
    place: &[u32],
    scores: &mut [f32],
    shares: &mut [f32],
    init: f32,
    #[comptime] placed: bool,
) {
    let v = ABSOLUTE_POS;
    if v < scores.len() {
        scores[v] = init;
        let d = degree[v];
        let mut s = 0.0f32;
        if d != 0u32 {
            s = init / f32::cast_from(d);
        }
        let mut at = v;
        if comptime![placed] {
            at = place[v] as usize;
        }
        shares[at] = s;
    }
}

/// `out[k] = place[indices[k]]`: in-neighbours renumbered.
#[cube(launch)]
pub fn renumber(indices: &[u32], place: &[u32], out: &mut [u32]) {
    let k = ABSOLUTE_POS;
    if k < out.len() {
        out[k] = place[indices[k] as usize];
    }
}

/// Counts (`fill` false) or lists (`fill` true) the rows of more than `short` entries: up
/// to `long` into `mid`, the rest into `far`; `counters[0]` and `[1]` count them.
#[cube(launch)]
pub fn rank_bins(
    offsets: &[u32],
    n: u32,
    short: u32,
    long: u32,
    counters: &[Atomic<u32>],
    mid: &mut [u32],
    far: &mut [u32],
    #[comptime] fill: bool,
) {
    let v = ABSOLUTE_POS;
    if v < n as usize {
        let deg = offsets[v + 1] - offsets[v];
        if deg > short {
            if deg > long {
                let k = counters[1].fetch_add(1u32);
                if comptime![fill] {
                    far[k as usize] = v as u32;
                }
            } else {
                let k = counters[0].fetch_add(1u32);
                if comptime![fill] {
                    mid[k as usize] = v as u32;
                }
            }
        }
    }
}

/// One PageRank round over rows, `group` units a row (each takes the row's entries in
/// turn; the group adds its sums as a tree): a row's sum of its in-neighbours' shares
/// gives its new score `base + damping * sum` and its next share (score / out-degree). All
/// rows of at most `most` entries (`listed` false, one unit a row, the entries in the
/// row's order), or the `count` rows of `rows`. Each cube adds its rows' `|new - old|` as
/// a tree into `partial[at + cube]`. `half` is `group / 2`. When `placed`, the shares are
/// kept renumbered (`place`, and `indices` renumbered with it).
#[cube(launch)]
pub fn rank_rows<F: Float>(
    offsets: &[u32],
    indices: &[u32],
    rows: &[u32],
    count: u32,
    degree: &[u32],
    place: &[u32],
    now: &[f32],
    next: &mut [f32],
    scores: &mut [f32],
    base: f32,
    damping: f32,
    most: u32,
    half: u32,
    partial: &mut [F],
    at: u32,
    #[comptime] group: u32,
    #[comptime] listed: bool,
    #[comptime] placed: bool,
) {
    let mut acc = Shared::<[f32]>::new_slice(256usize);
    let mut errs = Shared::<[F]>::new_slice(256usize);
    let u = UNIT_POS as usize;
    let g = comptime![group as usize];
    let per = comptime![256 / group as usize];
    let i = CUBE_POS * per + u / g;
    let lane = u % g;
    let mut sum = 0.0f32;
    let mut v = 0usize;
    let mut live = false;
    let mut old = 0.0f32;
    if i < count as usize {
        v = i;
        if comptime![listed] {
            v = rows[i] as usize;
        }
        // Read before the row is summed: read after it, next to the store below, it came
        // back as the new score on RADV (AMD) in the `placed` variant (CubeCL 0.11.4), so
        // every change was 0 and the rounds stopped after one.
        old = scores[v];
        let start = offsets[v] as usize;
        let end = offsets[v + 1] as usize;
        live = true;
        if comptime![!listed] {
            live = end - start <= most as usize;
        }
        if live {
            let mut k = start + lane;
            while k < end {
                sum += now[indices[k] as usize];
                k += g;
            }
        }
    }
    if comptime![group > 1] {
        acc[u] = sum;
        sync_cube();
        let mut s = half;
        while s > 0u32 {
            if (lane as u32) < s {
                acc[u] = acc[u] + acc[u + s as usize];
            }
            sync_cube();
            s = s / 2u32;
        }
        sum = acc[u];
    }
    let mut err = F::from_int(0);
    if live {
        if lane == 0 {
            let new = base + damping * sum;
            err = F::cast_from(f32::abs(new - old));
            scores[v] = new;
            let d = degree[v];
            let mut share = 0.0f32;
            if d != 0u32 {
                share = new / f32::cast_from(d);
            }
            let mut slot = v;
            if comptime![placed] {
                slot = place[v] as usize;
            }
            next[slot] = share;
        }
    }
    errs[u] = err;
    sync_cube();
    let mut s = 128u32;
    while s > 0u32 {
        if (u as u32) < s {
            errs[u] = errs[u] + errs[u + s as usize];
        }
        sync_cube();
        s = s / 2u32;
    }
    if u == 0 {
        partial[at as usize + CUBE_POS] = errs[0];
    }
}

/// `out[0] = Σ partial[..count]`, one cube of 256 units.
#[cube(launch)]
pub fn sum_partials<F: Float>(partial: &[F], count: u32, out: &mut [F]) {
    let mut errs = Shared::<[F]>::new_slice(256usize);
    let u = UNIT_POS as usize;
    let mut acc = F::from_int(0);
    let mut k = u;
    while k < count as usize {
        acc += partial[k];
        k += 256;
    }
    errs[u] = acc;
    sync_cube();
    let mut s = 128u32;
    while s > 0u32 {
        if (u as u32) < s {
            errs[u] = errs[u] + errs[u + s as usize];
        }
        sync_cube();
        s = s / 2u32;
    }
    if u == 0 {
        out[0] = errs[0];
    }
}

/// The computed split's vote of one row (kleene-graph's `split_votes`): the part `p` of the
/// largest `votes[p] * room[p]` (64-bit), starting from the node's own part `own`, so a tie
/// keeps `own` and otherwise goes to the lowest part (a later part must score strictly more).
#[cube]
fn split_pick(votes: &Array<u32>, room: &[u32], own: u32, k: u32) -> u32 {
    let mut best = own;
    let mut top = u64::cast_from(votes[own as usize]) * u64::cast_from(room[own as usize]);
    let mut p = 0u32;
    while p < k {
        let s = u64::cast_from(votes[p as usize]) * u64::cast_from(room[p as usize]);
        if s > top {
            top = s;
            best = p;
        }
        p += 1u32;
    }
    best
}

/// Node `v`'s neighbours `indices[start..end]` counted into `votes` by their part (a
/// self-loop not counted).
#[cube]
fn split_count(
    indices: &[u32],
    start: u32,
    end: u32,
    v: u32,
    part: &[u32],
    votes: &mut Array<u32>,
) {
    let mut e = start;
    while e < end {
        let u = indices[e as usize];
        if u != v {
            let q = part[u as usize] as usize;
            votes[q] = votes[q] + 1u32;
        }
        e += 1u32;
    }
}

/// The computed split's round, a unit a node: each node of at most `most` out- and
/// in-edges together counts its neighbours per part (a self-loop not) in `cap` counters of its own (`k` of
/// them used; a local array, `cap` a power of two up to 64) and writes the part it wants
/// (`split_pick`). Longer rows are left to `split_votes_long`.
#[cube(launch)]
pub fn split_votes_rows(
    out_offsets: &[u32],
    out_indices: &[u32],
    in_offsets: &[u32],
    in_indices: &[u32],
    part: &[u32],
    room: &[u32],
    want: &mut [u32],
    n: u32,
    k: u32,
    most: u32,
    #[comptime] cap: usize,
) {
    let v = ABSOLUTE_POS;
    if v < n as usize {
        let os = out_offsets[v];
        let oe = out_offsets[v + 1];
        let is = in_offsets[v];
        let ie = in_offsets[v + 1];
        if (oe - os) + (ie - is) <= most {
            let mut votes = Array::<u32>::new(cap);
            let mut p = 0u32;
            while p < k {
                votes[p as usize] = 0u32;
                p += 1u32;
            }
            split_count(out_indices, os, oe, v as u32, part, &mut votes);
            split_count(in_indices, is, ie, v as u32, part, &mut votes);
            want[v] = split_pick(&votes, room, part[v], k);
        }
    }
}

/// The computed split's round for the long rows, a cube of 256 units a listed node: the
/// units take the row's out- and in-edges in turn and count them per part (a self-loop not)
/// in 64 counters in
/// the cube's shared memory, then unit 0 writes the part the node wants (as
/// `split_pick`).
#[cube(launch)]
pub fn split_votes_long(
    out_offsets: &[u32],
    out_indices: &[u32],
    in_offsets: &[u32],
    in_indices: &[u32],
    part: &[u32],
    room: &[u32],
    rows: &[u32],
    count: u32,
    want: &mut [u32],
    k: u32,
) {
    let votes = Shared::<[Atomic<u32>]>::new_slice(64usize);
    let u = UNIT_POS as usize;
    let i = CUBE_POS;
    if u < 64 {
        votes[u].store(0u32);
    }
    sync_cube();
    if i < count as usize {
        let v = rows[i] as usize;
        let mut e = out_offsets[v] as usize + u;
        let oe = out_offsets[v + 1] as usize;
        while e < oe {
            let w = out_indices[e] as usize;
            if w != v {
                votes[part[w] as usize].fetch_add(1u32);
            }
            e += 256;
        }
        let mut e = in_offsets[v] as usize + u;
        let ie = in_offsets[v + 1] as usize;
        while e < ie {
            let w = in_indices[e] as usize;
            if w != v {
                votes[part[w] as usize].fetch_add(1u32);
            }
            e += 256;
        }
    }
    sync_cube();
    if u == 0 {
        if i < count as usize {
            let v = rows[i] as usize;
            let own = part[v];
            let mut best = own;
            let mut top =
                u64::cast_from(votes[own as usize].load()) * u64::cast_from(room[own as usize]);
            let mut p = 0u32;
            while p < k {
                let s = u64::cast_from(votes[p as usize].load()) * u64::cast_from(room[p as usize]);
                if s > top {
                    top = s;
                    best = p;
                }
                p += 1u32;
            }
            want[v] = best;
        }
    }
}