On-device reduction
.reduce(init, fold) on a gpu-resident array runs as a single-launch tree reduction over
workgroup shared memory — no host round-trip per element:
use system.gpu
gpu let data = [1, 2, 3, 4, 5, 6, 7, 8]
let sum = data.reduce(0, fn(a int, b int) int: a + b)
println(f'sum = {sum}')
Output: sum = 36. The result of a device reduce is a gpu-resident scalar.
Binding it to a host let (as above) is the fence — a single-element readback brings the value
over. Bind it with gpu let instead and it stays on the device:
use system.gpu
use system.io
use system.collections.array
fn main()
gpu var data = [1, 2, 3, 4]
gpu let sum = data.reduce(0, fn(a i32, b i32) i32: a + b)
let host_sum = sum
println(f'{host_sum}')
Output: 10. The fold must be an associative binary operator — + or *
over the two parameters. init is folded in exactly once. Anything else is rejected at compile
time. On a host array the same .reduce call falls through to the ordinary CPU fold, so one
spelling covers both residencies.