~/bend-docscommunity

tree.bend source

tree.bend on the hub · documented module

# bend-ndarray's storage: one binary tree (a Bend Array<U32>) whose levels follow the dimensions. A dimension of n# elements takes dep(n) levels (the least d with 2^d >= n; a dimension of 1 or 0 takes none), the first dimension's# levels at the top. So element (i0, i1, ...) is the cell whose index is i0, i1, ... written in dep(n0), dep(n1), ...# bits, and every operation is a recursion over the tree: a subtree at a dimension's boundary is a sub-array. Cells# past a dimension's length are padding: any value, never read as data.import Baseimport ./shape.bend as Simport ./cells.bend as C# ---- sizes ----def pow2(n: Nat) -> Nat:  match n:    case 0n:      1n    case 1n+p:      Nat.mul(2n, pow2(p))def dep_if(done: Bool, +d: Nat, more: Unit -> Nat) -> Nat:  match done:    case True{}:      d    case False{}:      more(Unit{})def dep_go(fuel: Nat, +n: Nat, +d: Nat, +p: Nat) -> Nat:  match fuel:    case 0n:      d    case 1n+f:      dep_if(Nat.is_le(n, p), d, u => dep_go(f, n, 1n+d, Nat.mul(2n, p)))# the levels a dimension of n elements takes (the least d with 2^d >= n)def dep(+n: Nat) -> Nat:  dep_go(48n, n, 0n, 1n)# the levels of a whole shapedef depth(s: List<&2, Nat>) -> Nat:  match s:    case []:      0n    case +n <> t:      Nat.add(dep(n), depth(t))# the levels of the dimensions before axis idef depth_before(s: List<&2, Nat>, i: Nat) -> Nat:  match s i:    case Nil{} _:      0n    case x <> t 0n:      0n    case +x <> t 1n+j:      Nat.add(dep(x), depth_before(t, j))# the levels of the dimensions after axis idef depth_after(s: List<&2, Nat>, i: Nat) -> Nat:  match s i:    case Nil{} _:      0n    case x <> t 0n:      depth(t)    case x <> t 1n+j:      depth_after(t, j)def fill(+d: Nat, +v: U32) -> Array<U32>:  Array.new(U32, d, v)# ---- element-wise ----def amap(+op: C.U1, +dt: S.DType, a: Array<U32>) -> Array<U32>:  match a:    case ALeaf{x}:      ALeaf{C.cell1(op, dt, x)}    case ANode{l, r}:      x y = amap(op, dt, l) amap(op, dt, r)      ANode{x, y}# two trees of the same shape, cell by celldef zip(+op: C.B2, +dt: S.DType, a: Array<U32>, b: Array<U32>) -> Array<U32>:  match a b:    case ALeaf{x} ALeaf{y}:      ALeaf{C.cell2(op, dt, x, y)}    case ANode{l, r} ANode{l2, r2}:      x y = zip(op, dt, l, l2) zip(op, dt, r, r2)      ANode{x, y}    case x _:      x# ---- broadcasting: Keep one level, or Rep a sub-array 2^d times where the operand has a 1 (no levels) ----type Step is Data:  Keep{}  Rep{d: Nat}def node_of(p: Array<U32> & Array<U32>) -> Array<U32>:  match p:    case Tuple{a, b}:      ANode{a, b}def rep(d: Nat, t: Array<U32>) -> Array<U32>:  match d:    case 0n:      t    case 1n+p:      node_of(Array.clone(U32, rep(p, t)))def keeps(n: Nat, rest: List<&2, Step>) -> List<&2, Step>:  match n:    case 0n:      rest    case 1n+p:      Keep{} <> keeps(p, rest)# the steps that stretch an operand of shape a (as many dimensions as s, missing ones as 1) to sdef step_pick(e: Bool, +y: Nat, rest: List<&2, Step>) -> List<&2, Step>:  match e:    case True{}:      keeps(dep(y), rest)    case False{}:      Rep{dep(y)} <> restdef steps(a: List<&2, Nat>, s: List<&2, Nat>) -> List<&2, Step>:  match a s:    case +x <> xs +y <> ys:      step_pick(Nat.is_eq(x, y), y, steps(xs, ys))    case _ _:      []def bto(st: List<&2, Step>, t: Array<U32>) -> Array<U32>:  match st t:    case Nil{} t0:      t0    case Keep{} <> +r ANode{l, rr}:      x y = bto(r, l) bto(r, rr)      ANode{x, y}    case Keep{} <> r ALeaf{v}:      ALeaf{v}    case Rep{d} <> r t0:      rep(d, bto(r, t0))def ones(n: Nat, rest: List<&2, Nat>) -> List<&2, Nat>:  match n:    case 0n:      rest    case 1n+p:      1n <> ones(p, rest)# a (fewer or as many dimensions as s) with leading 1s up to s's countdef pad_to(+a: List<&2, Nat>, +s: List<&2, Nat>) -> List<&2, Nat>:  ones(Nat.sub(List.length(&2, Nat, s), List.length(&2, Nat, a)), a)# t, of shape a, stretched to shape s (a broadcasts to s)def stretch(+a: List<&2, Nat>, +s: List<&2, Nat>, t: Array<U32>) -> Array<U32>:  bto(steps(pad_to(a, s), s), t)# ---- reductions along an axis: the axis's 2^h sub-arrays combined pairwise, the first n of them ----def comb(+op: C.B2, +dt: S.DType, a: Maybe<&1, Array<U32>>, b: Maybe<&1, Array<U32>>) -> Maybe<&1, Array<U32>>:  match a b:    case Some{x} Some{y}:      Some{zip(op, dt, x, y)}    case Some{x} None{}:      Some{x}    case None{} y:      ydef keep_if(ok: Bool, t: Array<U32>) -> Maybe<&1, Array<U32>>:  match ok:    case True{}:      Some{t}    case False{}:      None{}# the sub-arrays below h levels whose positions (from lo) are below n, combined in pairs, left before rightdef red_axis(+op: C.B2, +dt: S.DType, h: Nat, t: Array<U32>, +lo: Nat, +n: Nat) -> Maybe<&1, Array<U32>>:  match h t:    case 0n t0:      keep_if(Nat.is_lt(lo, n), t0)    case 1n+ +g ANode{l, r}:      x y = red_axis(op, dt, g, l, lo, n) red_axis(op, dt, g, r, Nat.add(lo, pow2(g)), n)      comb(op, dt, x, y)    case 1n+g ALeaf{v}:      keep_if(Nat.is_lt(lo, n), ALeaf{v})def or_fill(+d: Nat, m: Maybe<&1, Array<U32>>) -> Array<U32>:  match m:    case Some{t}:      t    case None{}:      fill(d, 0)# reduce the axis whose levels start pre levels down (h levels, n elements; rd levels below it); n >= 1def red_at(+op: C.B2, +dt: S.DType, pre: Nat, t: Array<U32>, +h: Nat, +n: Nat, +rd: Nat) -> Array<U32>:  match pre t:    case 0n t0:      or_fill(rd, red_axis(op, dt, h, t0, 0n, n))    case 1n+ +p ANode{l, r}:      x y = red_at(op, dt, p, l, h, n, rd) red_at(op, dt, p, r, h, n, rd)      ANode{x, y}    case 1n+p ALeaf{v}:      ALeaf{v}# ---- transpose: move a group of a levels below the next b levels ----# the top level moves below the next b levelsdef sink(b: Nat, t: Array<U32>) -> Array<U32>:  match b t:    case 1n+ +c ANode{ANode{x0, x1}, ANode{y0, y1}}:      p q = sink(c, ANode{x0, y0}) sink(c, ANode{x1, y1})      ANode{p, q}    case _ t0:      t0# sink(b) applied at depth kdef sink_at(k: Nat, +b: Nat, t: Array<U32>) -> Array<U32>:  match k t:    case 0n t0:      sink(b, t0)    case 1n+ +j ANode{l, r}:      x y = sink_at(j, b, l) sink_at(j, b, r)      ANode{x, y}    case _ t0:      t0# the top a levels moved below the next b levels, the deepest of them firstdef swap_groups(a: Nat, +b: Nat, t: Array<U32>) -> Array<U32>:  match a:    case 0n:      t    case 1n+ +k:      swap_groups(k, b, sink_at(k, b, t))# swap_groups at depth offdef swap_at(off: Nat, +a: Nat, +b: Nat, t: Array<U32>) -> Array<U32>:  match off t:    case 0n t0:      swap_groups(a, b, t0)    case 1n+ +o ANode{l, r}:      x y = swap_at(o, a, b, l) swap_at(o, a, b, r)      ANode{x, y}    case _ t0:      t0# ---- sub-arrays at one level, as a list, and back ----# the 2^h sub-arrays h levels down, in orderdef kids(h: Nat, t: Array<U32>) -> List<&1, Array<U32>>:  match h t:    case 0n t0:      [t0]    case 1n+ +g ANode{l, r}:      List.append(&1, Array<U32>, kids(g, l), kids(g, r))    case 1n+g ALeaf{v}:      [ALeaf{v}]def take(n: Nat, xs: List<&1, Array<U32>>) -> List<&1, Array<U32>>:  match n xs:    case 1n+m x <> t:      x <> take(m, t)    case _ _:      []def drop(n: Nat, xs: List<&1, Array<U32>>) -> List<&1, Array<U32>>:  match n xs:    case 1n+m x <> t:      drop(m, t)    case _ ys:      ys# pairs of neighbours joined into one level, the last padded with a tree of d levelsdef pair_up(xs: List<&1, Array<U32>>, +d: Nat) -> List<&1, Array<U32>>:  match xs:    case []:      []    case x <> Nil{}:      [ANode{x, fill(d, 0)}]    case x <> y <> t:      ANode{x, y} <> pair_up(t, d)# a tree of h levels over xs (at most 2^h of them, each of d levels), padded at the enddef build(h: Nat, xs: List<&1, Array<U32>>, +d: Nat) -> Array<U32>:  match h xs:    case 0n Nil{}:      fill(d, 0)    case 0n x <> t:      x    case 1n+g ys:      build(g, pair_up(ys, d), 1n+d)# every n-th of xs from the first, m of themdef every(m: Nat, xs: List<&1, Array<U32>>, +skip: Nat) -> List<&1, Array<U32>>:  match m xs:    case 1n+k x <> t:      x <> every(k, drop(skip, t), skip)    case _ _:      []# ---- slices and concatenation, at the axis pre levels down ----# the axis (h levels, n elements; rd levels below) cut to m elements: start, start + step, ...def slice_at(pre: Nat, t: Array<U32>, +h: Nat, +start: Nat, +step: Nat, +m: Nat, +h2: Nat, +rd: Nat) -> Array<U32>:  match pre t:    case 0n t0:      build(h2, every(m, drop(start, kids(h, t0)), Nat.sub(step, 1n)), rd)    case 1n+ +p ANode{l, r}:      x y = slice_at(p, l, h, start, step, m, h2, rd) slice_at(p, r, h, start, step, m, h2, rd)      ANode{x, y}    case _ t0:      t0# the axis of a (ha levels, na elements) followed by b's (hb, nb), into h levelsdef concat_at(pre: Nat, a: Array<U32>, b: Array<U32>, +ha: Nat, +na: Nat, +hb: Nat, +nb: Nat, +h: Nat, +rd: Nat) -> Array<U32>:  match pre a b:    case 0n a0 b0:      build(h, List.append(&1, Array<U32>, take(na, kids(ha, a0)), take(nb, kids(hb, b0))), rd)    case 1n+ +p ANode{l, r} ANode{l2, r2}:      x y = concat_at(p, l, l2, ha, na, hb, nb, h, rd) concat_at(p, r, r2, ha, na, hb, nb, h, rd)      ANode{x, y}    case _ a0 b0:      a0# ---- row-major order: the elements as a list, and a tree from one ----def expand(+n: Nat, +h: Nat, ts: List<&1, Array<U32>>) -> List<&1, Array<U32>>:  match ts:    case []:      []    case t <> r:      List.append(&1, Array<U32>, take(n, kids(h, t)), expand(n, h, r))def flat(s: List<&2, Nat>, ts: List<&1, Array<U32>>) -> List<&1, Array<U32>>:  match s:    case []:      ts    case +n <> rest:      flat(rest, expand(n, dep(n), ts))def leaf_vals(ts: List<&1, Array<U32>>) -> List<&2, U32>:  match ts:    case []:      []    case ALeaf{v} <> r:      v <> leaf_vals(r)    case ANode{l, r0} <> r:      leaf_vals(r)# the elements of t (shape s) in row-major orderdef elems(+s: List<&2, Nat>, t: Array<U32>) -> List<&2, U32>:  leaf_vals(flat(s, [t]))def leaves(xs: List<&2, U32>) -> List<&1, Array<U32>>:  match xs:    case []:      []    case x <> t:      ALeaf{x} <> leaves(t)def vtake(n: Nat, xs: List<&2, U32>) -> List<&2, U32>:  match n xs:    case 1n+m x <> t:      x <> vtake(m, t)    case _ _:      []def vdrop(n: Nat, xs: List<&2, U32>) -> List<&2, U32>:  match n xs:    case 1n+m x <> t:      vdrop(m, t)    case _ ys:      ysdef zeros_list(n: Nat) -> List<&2, U32>:  match n:    case 0n:      []    case 1n+m:      0 <> zeros_list(m)def zero_chunks(k: Nat, +m: Nat) -> List<&2, List<&2, U32>>:  match k:    case 0n:      []    case 1n+j:      zeros_list(m) <> zero_chunks(j, m)# xs cut into k pieces of mdef split_n(k: Nat, +m: Nat, +xs: List<&2, U32>) -> List<&2, List<&2, U32>>:  match k:    case 0n:      []    case 1n+j:      vtake(m, xs) <> split_n(j, m, vdrop(m, xs))# each piece cut into its n sub-blocks of m, then padded with zero blocks to 2^hdef split_all(cs: List<&2, List<&2, U32>>, +n: Nat, +h: Nat, +m: Nat) -> List<&2, List<&2, U32>>:  match cs:    case []:      []    case c <> r:      List.append(&2, List<&2, U32>, List.append(&2, List<&2, U32>, split_n(n, m, c), zero_chunks(Nat.sub(pow2(h), n), m)), split_all(r, n, h, m))def heads(cs: List<&2, List<&2, U32>>) -> List<&2, U32>:  match cs:    case []:      []    case Nil{} <> r:      0 <> heads(r)    case (x <> t) <> r:      x <> heads(r)def size(s: List<&2, Nat>) -> Nat:  match s:    case []:      1n    case n <> t:      Nat.mul(n, size(t))# row-major blocks laid out in tree order, padding includeddef tree_order(s: List<&2, Nat>, cs: List<&2, List<&2, U32>>) -> List<&2, U32>:  match s:    case []:      heads(cs)    case +n <> +rest:      tree_order(rest, split_all(cs, n, dep(n), size(rest)))# the tree of shape s holding xs (row-major, size(s) of them)def from_rows(+s: List<&2, Nat>, xs: List<&2, U32>) -> Array<U32>:  build(depth(s), leaves(tree_order(s, [xs])), 0n)# ---- dense shapes: no padding anywhere (every dimension a power of two), so the tree is the row-major order ----def dense(s: List<&2, Nat>) -> Bool:  match s:    case []:      True{}    case +n <> r:      Bool.and(Nat.is_eq(pow2(dep(n)), n), dense(r))# the tree of h levels whose cell at position i (from lo) holds conv(i) for i < n (0 past n)def tab(+dt: S.DType, h: Nat, +lo: Nat, +n: Nat) -> Array<U32>:  match h:    case 0n:      ALeaf{Bool.pick(U32, Nat.is_lt(lo, n), C.cell1(C.UConv{dt}, S.DU32{}, U32.from_nat(lo)), 0)}    case 1n+ +g:      x y = tab(dt, g, lo, n) tab(dt, g, Nat.add(lo, pow2(g)), n)      ANode{x, y}