~/bend-docscommunity

st.bend source

st.bend on the hub · documented module

# bend-safetensors-reader: read .safetensors files into Bend arrays: open a file (its header parsed and checked), find# tensors by name, and load a tensor's bytes, or its values widened to F32, into an Array<U32>.#   import bend-safetensors-reader@<version>/st.bend as ST# The header is read with Base's file IO; tensor bytes with bend-raw-cells (foreign C, native builds only), which# takes 64-bit offsets, so files past 4 GiB work.import Baseimport ./w64.bend as Wimport ./header.bend as Himport ./widen.bend as Vimport bend-raw-cells@0.1.0.0/raw.bend as R# an open file: its path, where its data section starts (8 + the header's length), and its checked headertype St is Data:  St{path: String, start: W.W64, h: H.Header}def St.tensors(s: St) -> List<&2, H.Ent>:  match s:    case St{p, b, H.Header{es, m, n}}:      esdef St.meta(s: St) -> List<&2, H.KV>:  match s:    case St{p, b, H.Header{es, m, n}}:      mdef find_go(+name: String, es: List<&2, H.Ent>) -> Maybe<&2, H.Ent>:  match es:    case []:      None{}    case +e <> t:      Bool.pick(Maybe<&2, H.Ent>, String.eq(H.Ent.name(e), name), Some{e}, find_go(name, t))# the tensor named namedef St.find(s: St, +name: String) -> Maybe<&2, H.Ent>:  find_go(name, St.tensors(s))# the tensor's byte count (end - begin)def Ent.bytes(e: H.Ent) -> W.W64:  match e:    case H.Ent{n, d, s, b, f}:      W.W64.sub(f, b)# the cells read() fills: ceil(bytes / 4), 4 bytes a cell, little-endiandef Ent.cells(e: H.Ent) -> U32:  W.W64.lo(W.W64.cells(Ent.bytes(e)))# the element count (bytes / dtype size)def Ent.count(e: H.Ent) -> U32:  match e:    case H.Ent{n, d, s, b, f}:      (W.W64.lo(W.W64.sub(f, b)) / H.DType.size(d) : U32)# ---- opening ----def fail(f: File, why: String) -> IO(Result<&2, &2, String, St>):  do IO<Result<&2, &2, String, St>>:    File.close(f)    return Fail{why}# 8 bytes, little-endian, as W64def le8(bs: List<&2, U32>) -> Maybe<&2, W.W64>:  match bs:    case [+b0, +b1, +b2, +b3, +b4, +b5, +b6, +b7]:      Some{W.W64{U32.or(U32.or(b4, (b5 * 256 : U32)), U32.or((b6 * 65536 : U32), (b7 * 16777216 : U32))), U32.or(U32.or(b0, (b1 * 256 : U32)), U32.or((b2 * 65536 : U32), (b3 * 16777216 : U32)))}}    case _:      None{}def len_go(bs: List<&2, U32>, +n: U32) -> U32:  match bs:    case []:      n    case h <> t:      len_go(t, (n + 1 : U32))def size_ok(r: Maybe<&2, W.W64>, +bytes: U32) -> Bool:  match r:    case None{}:      False{}    case Some{x}:      W.W64.is_eq(x, W.W64.of(bytes))def sized_ok(ok: Bool, +path: String, +start: W.W64, h: H.Header, +bytes: U32, +n: W.W64) -> Result<&2, &2, String, St>:  match ok:    case True{}:      Done{St{path, start, h}}    case False{}:      Fail{path ++ " holds " ++ U32.show(bytes) ++ " bytes, but its header says " ++ W.W64.show(start) ++ " + " ++ W.W64.show(n)}# the file's size, when the host can tell it (Base's File.size stops at 4 GiB), must be the data section's enddef sized(+path: String, +start: W.W64, h: H.Header, sz: Result<&1, &1, U32 & String, U32>) -> Result<&2, &2, String, St>:  match h sz:    case H.Header{es, m, +n} Done{+bytes}:      sized_ok(size_ok(W.W64.add(start, n), bytes), path, start, H.Header{es, m, n}, bytes, n)    case hh Fail{e}:      Done{St{path, start, hh}}def closed(+path: String, +start: W.W64, h: H.Header, fs: File & Result<&1, &1, U32 & String, U32>) -> IO(Result<&2, &2, String, St>):  match fs:    case (f, sz):      do IO<Result<&2, &2, String, St>>:        File.close(f)        return sized(path, start, h, sz)def checked(f: File, +path: String, +start: W.W64, r: Result<&2, &2, String, H.Header>) -> IO(Result<&2, &2, String, St>):  match r:    case Fail{why}:      fail(f, path ++ ": " ++ why)    case Done{h}:      do IO<Result<&2, &2, String, St>>:        fs : File & Result<&1, &1, U32 & String, U32> <- File.size(f)        closed(path, start, h, fs)def got_bytes(ok: Bool, f: File, +path: String, +n: U32, bs: List<&2, U32>) -> IO(Result<&2, &2, String, St>):  match ok:    case True{}:      checked(f, path, W.W64.of((n + 8 : U32)), H.parse(bs))    case False{}:      fail(f, path ++ ": the file ends inside the header")def got_header(+path: String, +n: U32, r: File & Result<&1, &1, U32 & String, List<&2, U32>>) -> IO(Result<&2, &2, String, St>):  match r:    case (f, Done{+bs}):      got_bytes(U32.is_eq(len_go(bs, 0), n), f, path, n, bs)    case (f, Fail{e}):      fail(f, path ++ ": cannot read the header")# the reference implementation's limit: a header of at most 100,000,000 bytesdef got_len3(ok: Bool, f: File, +path: String, +n: U32) -> IO(Result<&2, &2, String, St>):  match ok:    case True{}:      do IO<Result<&2, &2, String, St>>:        r : File & Result<&1, &1, U32 & String, List<&2, U32>> <- File.read_at(f, 8, n)        got_header(path, n, r)    case False{}:      fail(f, path ++ ": a header of " ++ U32.show(n) ++ " bytes (more than 100,000,000)")def got_len2(m: Maybe<&2, W.W64>, f: File, +path: String) -> IO(Result<&2, &2, String, St>):  match m:    case Some{W.W64{+hi, +n}}:      got_len3(Bool.and(U32.is_eq(hi, 0), U32.is_le(n, 100000000)), f, path, n)    case None{}:      fail(f, path ++ ": not a safetensors file (shorter than 8 bytes)")def got_len(+path: String, r: File & Result<&1, &1, U32 & String, List<&2, U32>>) -> IO(Result<&2, &2, String, St>):  match r:    case (f, Done{bs}):      got_len2(le8(bs), f, path)    case (f, Fail{e}):      fail(f, path ++ ": cannot read")def opened(+path: String, r: Result<&1, &1, U32 & String, File>) -> IO(Result<&2, &2, String, St>):  match r:    case Done{f}:      do IO<Result<&2, &2, String, St>>:        b : File & Result<&1, &1, U32 & String, List<&2, U32>> <- File.read_at(f, 0, 8)        got_len(path, b)    case Fail{e}:      IO.pure(Result<&2, &2, String, St>, Fail{"cannot open " ++ path})# open a .safetensors file: its header parsed and checked, or what is wrong with itdef St.open(+path: String) -> IO(Result<&2, &2, String, St>):  do IO<Result<&2, &2, String, St>>:    r : Result<&1, &1, U32 & String, File> <- File.open(path, "r")    opened(path, r)# ---- reading ----def wrap(m: Maybe<&2, W.W64>) -> W.W64:  match m:    case None{}:      W.W64{4294967295, 4294967295}    case Some{x}:      xdef tail_set(+dst: U32, +shift: U32, a: Array<U32>, r: Array<U32> & U32) -> Array<U32>:  match r:    case (t, +v):      Array.set(U32, a, dst, (v / U32.pow(2, U32.to_nat(shift)) : U32))# the last 1 to 3 bytes: the 4 bytes ending at the tensor's end, shifted downdef tail(+path: String, +endf: W.W64, +rem: U32, +dst: U32, a: Array<U32>) -> IO(Array<U32>):  +at = W.W64.sub(endf, W.W64.of(4))  do IO<Array<U32>>:    t : Array<U32> <- R.Raw.read_at(path, W.W64.hi(at), W.W64.lo(at), Array.new(U32, 0n, 0), 0, 1)    return tail_set(dst, ((4 - rem : U32) * 8 : U32), a, Array.get(U32, t, 0))def read_tail(none: Bool, +path: String, +endf: W.W64, +rem: U32, +dst: U32, a: Array<U32>) -> IO(Array<U32>):  match none:    case True{}:      IO.pure(Array<U32>, a)    case False{}:      tail(path, endf, rem, dst, a)def read_go(+path: String, +off: W.W64, +endf: W.W64, +full: U32, +rem: U32, +dst: U32, a: Array<U32>) -> IO(Array<U32>):  do IO<Array<U32>>:    b : Array<U32> <- R.Raw.read_at(path, W.W64.hi(off), W.W64.lo(off), a, dst, full)    read_tail(U32.is_eq(rem, 0), path, endf, rem, (dst + full : U32), b)# tensor e's bytes into a, from cell dst on: 4 bytes a cell, little-endian, Ent.cells(e) cells, the last cell's# unused high bytes 0. a must hold dst + Ent.cells(e) cells. Stops the program if the file is shorter than its header# says (bend-raw-cells).def St.read(s: St, e: H.Ent, +dst: U32, a: Array<U32>) -> IO(Array<U32>):  match s e:    case St{+path, +start, h} H.Ent{nm, d, sh, +b, +f}:      +nb = W.W64.sub(f, b)      +q = W.W64.sub(W.W64.cells(nb), Bool.pick(W.W64, U32.is_eq(U32.and(W.W64.lo(nb), 3), 0), W.W64.of(0), W.W64.of(1)))      read_go(path, wrap(W.W64.add(start, b)), wrap(W.W64.add(start, f)), W.W64.lo(q), U32.and(W.W64.lo(nb), 3), dst, a)# ---- reading as F32 ----# whether read_f32 takes this dtype (F32, BF16, F16)def St.can_f32(e: H.Ent) -> Bool:  match e:    case H.Ent{n, H.DF32{}, s, b, f}:      True{}    case H.Ent{n, H.DBF16{}, s, b, f}:      True{}    case H.Ent{n, H.DF16{}, s, b, f}:      True{}    case _:      False{}# the smallest d with 2^d >= ndef depth(+n: U32) -> Nat:  Bool.pick(Nat, U32.is_le(n, 1), 0n, 1n+U32.log2((n - 1 : U32)))def half(+k: U32, +c: U32) -> U32:  Bool.pick(U32, U32.is_eq(U32.and(k, 1), 0), U32.and(c, 65535), (c / 65536 : U32))@unsafedef wid(done: Bool, +isbf: Bool, +k: U32, +n: U32, +dst: U32, src: Array<U32>, out: Array<U32>) -> Array<U32>:  match done:    case True{}:      out    case False{}:      wid_get(isbf, k, n, dst, out, Array.get(U32, src, (k / 2 : U32)))@unsafedef wid_get(+isbf: Bool, +k: U32, +n: U32, +dst: U32, out: Array<U32>, r: Array<U32> & U32) -> Array<U32>:  match r:    case (src, +c):      +h = half(k, c)      wid(U32.is_eq((k + 1 : U32), n), isbf, (k + 1 : U32), n, dst, src, Array.set(U32, out, (dst + k : U32), Bool.pick(U32, isbf, V.bf16(h), V.f16(h))))# n 16-bit values, two a cell (low half first), widened to F32 bits into out from cell dst on; one element at a time@unsafedef St.widen(+isbf: Bool, +n: U32, src: Array<U32>, +dst: U32, out: Array<U32>) -> Array<U32>:  wid(U32.is_eq(n, 0), isbf, 0, n, dst, src, out)@unsafedef read16(+s: St, +e: H.Ent, +isbf: Bool, +dst: U32, a: Array<U32>) -> IO(Array<U32>):  do IO<Array<U32>>:    t : Array<U32> <- St.read(s, e, 0, Array.new(U32, depth(Ent.cells(e)), 0))    return St.widen(isbf, Ent.count(e), t, dst, a)# tensor e's values as F32 bits into a, from cell dst on, Ent.count(e) cells: F32 as read, BF16 and F16 widened# (exactly). Other dtypes stop the program: check St.can_f32 first. a must hold dst + Ent.count(e) cells.@unsafedef St.read_f32(+s: St, +e: H.Ent, +dst: U32, a: Array<U32>) -> IO(Array<U32>):  match e:    case H.Ent{n, H.DF32{}, sh, b, f}:      St.read(s, H.Ent{n, H.DF32{}, sh, b, f}, dst, a)    case H.Ent{n, H.DBF16{}, sh, b, f}:      read16(s, H.Ent{n, H.DBF16{}, sh, b, f}, True{}, dst, a)    case H.Ent{n, H.DF16{}, sh, b, f}:      read16(s, H.Ent{n, H.DF16{}, sh, b, f}, False{}, dst, a)    case H.Ent{n, d, sh, b, f}:      IO.die(Array<U32>, 1, "St.read_f32: tensor \"" ++ n ++ "\" is " ++ H.DType.name(d) ++ ", not F32, BF16 or F16")