bang.bend source
bang.bend on the hub · documented module
# 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<U32> 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 Baseimport bend-ml-tensor-array@0.1.20.0/main.bend as TAimport ./lanes.bend as L@unsafedef fv(u: U32) -> F32: match u: case U32{w}: F32{w}@unsafedef uv(x: F32) -> U32: match x: case F32{w}: U32{w}type AR is Type: AR{a0: Array<U32>, a1: Array<U32>, a2: Array<U32>, a3: Array<U32>, a4: Array<U32>, a5: Array<U32>}def one(u: Unit) -> Array<U32>: Array.new(U32, 0n, 0)@unsafedef 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)@unsafedef 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))@unsafedef tree(~E: Data, ~g: @+i: U32 -> @+e: E -> AR -> AR, d: Nat, +t: U32, +l: U32, +n: U32, +e: E, +x0: Array<U32>, +x1: Array<U32>, +x2: Array<U32>, +x3: Array<U32>, +x4: Array<U32>, +x5: Array<U32>) -> 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)@unsafedef 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<U32>, x: U32, y: U32}def g2b(+x: U32, r: Array<U32> & U32) -> G2: match r: case Tuple{a, y}: G2{a, x, y}def g2a(+j: U32, r: Array<U32> & U32) -> G2: match r: case Tuple{a, +x}: g2b(x, Array.get(U32, a, j))def g2(a: Array<U32>, +i: U32, +j: U32) -> G2: g2a(j, Array.get(U32, a, i))