~/bend-docscommunity

test/read.bend source

test/read.bend on the hub · documented module

# For each tensor name given after the file, reads the tensor with St.read and (for F32, BF16, F16) St.read_f32, and# prints the cell count, the wrapping sum and the xor of the cells of each. test/check_read.py computes the same from# the file with NumPy.import Baseimport ../w64.bend as Wimport ../header.bend as Himport ../st.bend as STtype Sum is Data:  Sum{s: U32, x: U32}@unsafedef fold(done: Bool, +k: U32, +n: U32, a: Array<U32>, +s: U32, +x: U32) -> Sum:  match done:    case True{}:      Sum{s, x}    case False{}:      fold_get(k, n, s, x, Array.get(U32, a, k))@unsafedef fold_get(+k: U32, +n: U32, +s: U32, +x: U32, r: Array<U32> & U32) -> Sum:  match r:    case (a, +v):      fold(U32.is_eq((k + 1 : U32), n), (k + 1 : U32), n, a, (s + v : U32), U32.xor(x, v))def sum_show(+n: U32, r: Sum) -> String:  match r:    case Sum{+s, +x}:      U32.show(n) ++ " " ++ U32.show(s) ++ " " ++ U32.show(x)@unsafedef sums(+n: U32, a: Array<U32>) -> String:  sum_show(n, fold(U32.is_eq(n, 0), 0, n, a, 0, 0))@unsafedef f32_part(ok: Bool, +s: ST.St, +e: H.Ent) -> IO(String):  match ok:    case True{}:      do IO<String>:        a : Array<U32> <- ST.St.read_f32(s, e, 0, Array.new(U32, ST.depth(ST.Ent.count(e)), 0))        return " f32 " ++ sums(ST.Ent.count(e), a)    case False{}:      IO.pure(String, "")@unsafedef one(+s: ST.St, +name: String, m: Maybe<&2, H.Ent>) -> IO(Unit):  match m:    case None{}:      IO.print(name ++ " MISSING")    case Some{+e}:      do IO<Unit>:        a : Array<U32> <- ST.St.read(s, e, 0, Array.new(U32, ST.depth(ST.Ent.cells(e)), 0))        f : String <- f32_part(ST.St.can_f32(e), s, e)        IO.print(name ++ " raw " ++ sums(ST.Ent.cells(e), a) ++ f)@unsafedef each(+s: ST.St, names: List<String>) -> IO(Unit):  match names:    case []:      IO.pure(Unit, Unit{})    case +n <> t:      do IO<Unit>:        one(s, n, ST.St.find(s, n))        each(s, t)@unsafedef opened(names: List<String>, r: Result<&2, &2, String, ST.St>) -> IO(Unit):  match r:    case Done{s}:      each(s, names)    case Fail{why}:      IO.print("REFUSED " ++ why)@unsafedef arg(xs: List<String>) -> IO(Unit):  match xs:    case prog <> p <> names:      do IO<Unit>:        r : Result<&2, &2, String, ST.St> <- ST.St.open(p)        opened(names, r)    case _:      IO.print("usage: read <file.safetensors> NAME...")@unsafedef main() -> IO(Unit):  do IO<Unit>:    a : List<String> <- IO.args()    arg(a)