# Data-parallel GPU kernels in plain Bend 2: one `!` bang over a fork tree of up to 2^14 leaves (the runtime's 16,384 # lanes), each leaf running items t, t + l, t + 2l, ... in flat loops over up to six shared arrays. F32 values live in # Array cells as their bits (fv / uv). Arrays are shared between leaves through Base's @unsafe Array.fork: each # leaf must write only its own items' cells. Call `bang` as its own IO step so it runs on the GPU. import Base import bend-ml-tensor-array@0.1.20.0/main.bend as TA import ./lanes.bend as L @unsafe def fv(u: U32) -> F32: match u: case U32{w}: F32{w} @unsafe def uv(x: F32) -> U32: match x: case F32{w}: U32{w} type AR is Type: AR{a0: Array, a1: Array, a2: Array, a3: Array, a4: Array, a5: Array} def one(u: Unit) -> Array: Array.new(U32, 0n, 0) @unsafe def join6(x: AR, y: AR) -> AR: match x y: case AR{x0, x1, x2, x3, x4, x5} AR{y0, y1, y2, y3, y4, y5}: AR{Array.join(U32, x0, y0), Array.join(U32, x1, y1), Array.join(U32, x2, y2), Array.join(U32, x3, y3), Array.join(U32, x4, y4), Array.join(U32, x5, y5)} def depth2(big: Bool, +n: Nat) -> Nat: match big: case True{}: 14n case False{}: TA.cap_depth(n) def depth(+n: Nat) -> Nat: depth2(Nat.is_le(16384n, n), n) @unsafe def items(~E: Data, ~g: @+i: U32 -> @+e: E -> AR -> AR, cnt: Nat, +i: U32, +l: U32, +e: E, r: AR) -> AR: match cnt: case 0n: r case 1n+q: items(~E, ~g, q, (i + l : U32), l, e, g(i, e, r)) @unsafe def tree(~E: Data, ~g: @+i: U32 -> @+e: E -> AR -> AR, d: Nat, +t: U32, +l: U32, +n: U32, +e: E, +x0: Array, +x1: Array, +x2: Array, +x3: Array, +x4: Array, +x5: Array) -> AR: match d: case 0n: items(~E, ~g, L.share(t, n, l), t, l, e, AR{x0, x1, x2, x3, x4, x5}) case 1n++q: x y = tree(~E, ~g, q, (t * 2 : U32), l, n, e, x0, x1, x2, x3, x4, x5) tree(~E, ~g, q, ((t * 2 : U32) + 1 : U32), l, n, e, x0, x1, x2, x3, x4, x5) join6(x, y) # n items over the six arrays, in one bang (call it as its own IO step so it runs on the GPU) @unsafe def bang(~E: Data, ~g: @+i: U32 -> @+e: E -> AR -> AR, +n: Nat, +e: E, r: AR) -> AR: match r: case AR{x0, x1, x2, x3, x4, x5}: tree!(~E, ~g, depth(n), 0, U32.pow(2, depth(n)), U32.from_nat(n), e, x0, x1, x2, x3, x4, x5) type G2 is Type: G2{a: Array, x: U32, y: U32} def g2b(+x: U32, r: Array & U32) -> G2: match r: case Tuple{a, y}: G2{a, x, y} def g2a(+j: U32, r: Array & U32) -> G2: match r: case Tuple{a, +x}: g2b(x, Array.get(U32, a, j)) def g2(a: Array, +i: U32, +j: U32) -> G2: g2a(j, Array.get(U32, a, i))