~/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. A float64 element is two cells, its high word# then its low one, under one node: the tree of a float64 array of shape s is that of shape s + [2], so moving# elements (reshape, transpose, slices, joins, broadcasting) works on it unchanged, and element-wise operations stop# at those nodes.import Baseimport ./shape.bend as Simport ./cells.bend as Cimport ./cells64.bend as C64import bend-float64@0.1.8.0/float64.bend as F# ---- 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)# ---- float64 elements ----def pair(x: F.F64) -> Array<U32>:  match x:    case F.F64{h, l}:      ANode{ALeaf{h}, ALeaf{l}}def fill2(d: Nat, +h: U32, +l: U32) -> Array<U32>:  match d:    case 0n:      ANode{ALeaf{h}, ALeaf{l}}    case 1n+ +p:      x y = fill2(p, h, l) fill2(p, h, l)      ANode{x, y}def fill_k(w: Bool, +d: Nat, +v: U32) -> Array<U32>:  match w:    case True{}:      fill2(d, v, 0)    case False{}:      fill(d, v)# d levels of elements all v (a float64's v is its high word, the low one 0: enough for 0, 1 and the identities)def fill_dt(+dt: S.DType, +d: Nat, +v: U32) -> Array<U32>:  fill_k(C64.is_f64(dt), d, v)# ---- element-wise ----def amap32(+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 = amap32(op, dt, l) amap32(op, dt, r)      ANode{x, y}# float64 elements to float64 elementsdef amap64(+op: C.U1, a: Array<U32>) -> Array<U32>:  match a:    case ANode{ALeaf{h}, ALeaf{l}}:      pair(C64.cell1(op, F.F64{h, l}))    case ANode{l, r}:      x y = amap64(op, l) amap64(op, r)      ANode{x, y}    case ALeaf{v}:      ALeaf{v}# float64 elements to cells of dtype todef narrow(+to: S.DType, a: Array<U32>) -> Array<U32>:  match a:    case ANode{ALeaf{h}, ALeaf{l}}:      ALeaf{C64.to_cell(to, F.F64{h, l})}    case ANode{l, r}:      x y = narrow(to, l) narrow(to, r)      ANode{x, y}    case ALeaf{v}:      ALeaf{v}# cells of dtype from to float64 elementsdef widen(+from: S.DType, a: Array<U32>) -> Array<U32>:  match a:    case ALeaf{v}:      pair(C64.of_cell(from, v))    case ANode{l, r}:      x y = widen(from, l) widen(from, r)      ANode{x, y}# how an operation's elements change width: 32-bit cells, float64 elements, or a conversion one waytype MK is Data:  K32{}  K64{}  KNarrow{to: S.DType}  KWiden{}def conv_kind(from64: Bool, to64: Bool, +to: S.DType) -> MK:  match from64 to64:    case True{} True{}:      K64{}    case True{} False{}:      KNarrow{to}    case False{} True{}:      KWiden{}    case False{} False{}:      K32{}def map_kind(op: C.U1, +dt: S.DType) -> MK:  match op:    case C.UConv{+to}:      conv_kind(C64.is_f64(dt), C64.is_f64(to), to)    case _:      Bool.pick(MK, C64.is_f64(dt), K64{}, K32{})def amap_k(k: MK, +op: C.U1, +dt: S.DType, a: Array<U32>) -> Array<U32>:  match k:    case K32{}:      amap32(op, dt, a)    case K64{}:      amap64(op, a)    case KNarrow{to}:      narrow(to, a)    case KWiden{}:      widen(dt, a)# op on every element of a tree of dtype dtdef amap(+op: C.U1, +dt: S.DType, a: Array<U32>) -> Array<U32>:  amap_k(map_kind(op, dt), op, dt, a)# two trees of the same shape, cell by celldef zip32(+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 = zip32(op, dt, l, l2) zip32(op, dt, r, r2)      ANode{x, y}    case x _:      x# a float64 result: a comparison's bool cell, or a float64 elementdef out64(cmp: Bool, +op: C.B2, +x: F.F64, +y: F.F64) -> Array<U32>:  match cmp:    case True{}:      ALeaf{C64.cmp2(op, x, y)}    case False{}:      pair(C64.f2(op, x, y))# two float64 trees of the same shape, element by elementdef zip64(+op: C.B2, a: Array<U32>, b: Array<U32>) -> Array<U32>:  match a b:    case ANode{ALeaf{h1}, ALeaf{l1}} ANode{ALeaf{h2}, ALeaf{l2}}:      out64(C.is_cmp(op), op, F.F64{h1, l1}, F.F64{h2, l2})    case ANode{l, r} ANode{l2, r2}:      x y = zip64(op, l, l2) zip64(op, r, r2)      ANode{x, y}    case x _:      xdef zip_k(w: Bool, +op: C.B2, +dt: S.DType, a: Array<U32>, b: Array<U32>) -> Array<U32>:  match w:    case True{}:      zip64(op, a, b)    case False{}:      zip32(op, dt, a, b)# two trees of dtype dt and the same shape, element by elementdef zip(+op: C.B2, +dt: S.DType, a: Array<U32>, b: Array<U32>) -> Array<U32>:  zip_k(C64.is_f64(dt), op, dt, a, b)# ---- 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}# 2^d copies of t: split first, so each copy is cloned from t itself (not from the copies made so far) and the halves# are built in paralleldef rep_two(c: Array<U32> & Array<U32>, f: Array<U32> -> Array<U32>, g: Array<U32> -> Array<U32>) -> Array<U32>:  match c:    case Tuple{a, b}:      x y = f(a) g(b)      ANode{x, y}def rep(d: Nat, t: Array<U32>) -> Array<U32>:  match d:    case 0n:      t    case 1n+ +p:      rep_two(Array.clone(U32, t), u => rep(p, u), v => rep(p, v))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)))# ---- 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))def rows_dense(d: Bool, +s: List<&2, Nat>, xs: List<&2, U32>) -> Array<U32>:  match d:    case True{}:      build(depth(s), leaves(xs), 0n)    case False{}:      build(depth(s), leaves(tree_order(s, [xs])), 0n)# the tree of shape s holding xs (row-major, size(s) of them); without padding, row-major is already tree orderdef from_rows(+s: List<&2, Nat>, xs: List<&2, U32>) -> Array<U32>:  rows_dense(dense(s), s, xs)# the tree of h levels whose cell at position i (from lo) holds conv(i) for i < n (0 past n)def tab32(+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 = tab32(dt, g, lo, n) tab32(dt, g, Nat.add(lo, pow2(g)), n)      ANode{x, y}# the same for float64 elementsdef tab64(h: Nat, +lo: Nat, +n: Nat) -> Array<U32>:  match h:    case 0n:      pair(Bool.pick(F.F64, Nat.is_lt(lo, n), F.from_u32(U32.from_nat(lo)), F.F64{0, 0}))    case 1n+ +g:      x y = tab64(g, lo, n) tab64(g, Nat.add(lo, pow2(g)), n)      ANode{x, y}def tab_k(w: Bool, +dt: S.DType, +h: Nat, +lo: Nat, +n: Nat) -> Array<U32>:  match w:    case True{}:      tab64(h, lo, n)    case False{}:      tab32(dt, h, lo, n)def tab(+dt: S.DType, +h: Nat, +lo: Nat, +n: Nat) -> Array<U32>:  tab_k(C64.is_f64(dt), dt, h, lo, n)