Skip to main content

reduction/
reduction.rs

1//! A classic block-level tree reduction, run twice: once correct, once with
2//! the barrier inside the loop "optimised away", a bug that often passes on
3//! real hardware because warps happen to run in lockstep.
4//!
5//! cargo run --example reduction
6
7use riri::{launch, GlobalBuf, LaunchConfig, ThreadCtx};
8
9const BLOCK: u32 = 64;
10const BLOCKS: u32 = 4;
11
12fn reduce(t: &ThreadCtx<'_>, input: &GlobalBuf<u32>, partial: &GlobalBuf<u32>, buggy: bool) {
13    let tile = t.shared::<u32>("tile", BLOCK as usize);
14    let i = t.thread_linear();
15    tile.write(t, i, input.read(t, t.global_linear()));
16    t.sync_threads();
17
18    let mut stride = BLOCK as usize / 2;
19    while stride > 0 {
20        if i < stride {
21            let sum = tile.read(t, i) + tile.read(t, i + stride);
22            tile.write(t, i, sum);
23        }
24        if !buggy {
25            t.sync_threads();
26        }
27        stride /= 2;
28    }
29
30    if i == 0 {
31        partial.write(t, t.block_linear(), tile.read(t, 0));
32    }
33}
34
35fn main() {
36    let n = (BLOCK * BLOCKS) as usize;
37    let input = GlobalBuf::new("input", (1..=n as u32).collect());
38    let expected: u32 = (1..=n as u32).sum();
39
40    for buggy in [false, true] {
41        let partial = GlobalBuf::new("partial", vec![0u32; BLOCKS as usize]);
42        let report = launch(&LaunchConfig::new(BLOCKS, BLOCK).seed(2026), |t| {
43            reduce(t, &input, &partial, buggy)
44        });
45        let total: u32 = partial.to_vec().iter().sum();
46        println!(
47            "== {} reduction: total {total} (expected {expected})",
48            if buggy { "buggy" } else { "correct" }
49        );
50        print!("{report}");
51        println!();
52    }
53}