~/bend-docscommunity

header.bend source

header.bend on the hub · documented module

# A safetensors header, from its bytes to a checked table of tensors. Pure: no IO, no @unsafe.# The header is a JSON object: each key a tensor name whose value is {"dtype": .., "shape": [..], "data_offsets":# [begin, end]}, plus an optional "__metadata__" object of strings. A header is accepted only if, sorted by offset,# the tensors tile the data section from 0 with no gap or overlap, each tensor's bytes are its element count times# its dtype's size, and no two tensors share a name (the checks of the reference Rust implementation).import Baseimport ./w64.bend as Wimport ./lex.bend as Xtype DType is Data:  DBool{}  DU8{}  DI8{}  DF8E5M2{}  DF8E4M3{}  DI16{}  DU16{}  DF16{}  DBF16{}  DI32{}  DU32{}  DF32{}  DF64{}  DI64{}  DU64{}# bytes an elementdef DType.size(d: DType) -> U32:  match d:    case DBool{}: 1    case DU8{}: 1    case DI8{}: 1    case DF8E5M2{}: 1    case DF8E4M3{}: 1    case DI16{}: 2    case DU16{}: 2    case DF16{}: 2    case DBF16{}: 2    case DI32{}: 4    case DU32{}: 4    case DF32{}: 4    case DF64{}: 8    case DI64{}: 8    case DU64{}: 8# the name a header usesdef DType.name(d: DType) -> String:  match d:    case DBool{}: "BOOL"    case DU8{}: "U8"    case DI8{}: "I8"    case DF8E5M2{}: "F8_E5M2"    case DF8E4M3{}: "F8_E4M3"    case DI16{}: "I16"    case DU16{}: "U16"    case DF16{}: "F16"    case DBF16{}: "BF16"    case DI32{}: "I32"    case DU32{}: "U32"    case DF32{}: "F32"    case DF64{}: "F64"    case DI64{}: "I64"    case DU64{}: "U64"def dtypes() -> List<&2, DType>:  [DBool{}, DU8{}, DI8{}, DF8E5M2{}, DF8E4M3{}, DI16{}, DU16{}, DF16{}, DBF16{}, DI32{}, DU32{}, DF32{}, DF64{}, DI64{}, DU64{}]def dtype_go(+s: String, ds: List<&2, DType>) -> Maybe<&2, DType>:  match ds:    case []:      None{}    case +d <> t:      Bool.pick(Maybe<&2, DType>, String.eq(DType.name(d), s), Some{d}, dtype_go(s, t))def DType.of(+s: String) -> Maybe<&2, DType>:  dtype_go(s, dtypes())# one tensor: data_offsets are bytes from the start of the data section, which follows the headertype Ent is Data:  Ent{name: String, dtype: DType, shape: List<&2, U32>, begin: W.W64, end: W.W64}def Ent.name(e: Ent) -> String:  match e:    case Ent{n, d, s, b, f}:      ndef Ent.begin(e: Ent) -> W.W64:  match e:    case Ent{n, d, s, b, f}:      bdef Ent.end(e: Ent) -> W.W64:  match e:    case Ent{n, d, s, b, f}:      f# ---- element and byte counts ----def mul_m(acc: Maybe<&2, W.W64>, +k: U32) -> Maybe<&2, W.W64>:  match acc:    case None{}:      None{}    case Some{x}:      W.W64.mul(x, k)# the product of the dimensions (1 for a scalar), or None past 2^64 - 1def count(sh: List<&2, U32>, acc: Maybe<&2, W.W64>) -> Maybe<&2, W.W64>:  match sh:    case []:      acc    case +h <> t:      count(t, mul_m(acc, h))# the bytes a tensor of this dtype and shape holds, or None past 2^64 - 1def nbytes(d: DType, sh: List<&2, U32>) -> Maybe<&2, W.W64>:  mul_m(count(sh, Some{W.W64.of(1)}), DType.size(d))# ---- the parser: one step a token, over the header's fixed shape ----# a metadata entrytype KV is Data:  KV{key: String, value: String}type Part is Data:  Part{dt: Maybe<&2, DType>, sh: Maybe<&2, List<&2, U32>>, of: Maybe<&2, List<&2, W.W64>>}type Acc is Data:  Acc{ents: List<&2, Ent>, meta: Maybe<&2, List<&2, KV>>}type Ps is Data:  PStart{}  PKey{a: Acc, first: Bool}  PColon{a: Acc, k: String}  PVal{a: Acc, k: String}  PNext{a: Acc}  PEnd{a: Acc}  MKey{a: Acc, m: List<&2, KV>, first: Bool}  MColon{a: Acc, m: List<&2, KV>, k: String}  MVal{a: Acc, m: List<&2, KV>, k: String}  MNext{a: Acc, m: List<&2, KV>}  TKey{a: Acc, k: String, p: Part, first: Bool}  TColon{a: Acc, k: String, p: Part, f: String}  TVal{a: Acc, k: String, p: Part, f: String}  TList{a: Acc, k: String, p: Part, f: String, xs: List<&2, W.W64>, first: Bool}  TLNext{a: Acc, k: String, p: Part, f: String, xs: List<&2, W.W64>}  TNext{a: Acc, k: String, p: Part}  PBad{why: String}def tok_show(t: X.Tok) -> String:  match t:    case X.TOpen{}: "'{'"    case X.TClose{}: "'}'"    case X.TLBr{}: "'['"    case X.TRBr{}: "']'"    case X.TColon{}: "':'"    case X.TComma{}: "','"    case X.TStr{s}: "the string \"" ++ s ++ "\""    case X.TNum{v}: "a number"    case X.TBad{why}: whydef meta_done(a: Acc, m: List<&2, KV>) -> Ps:  match a:    case Acc{es, None{}}:      PNext{Acc{es, Some{List.reverse(&2, KV, m)}}}    case Acc{es, Some{old}}:      PBad{"two __metadata__ objects"}def val_open(meta: Bool, a: Acc, k: String) -> Ps:  match meta:    case True{}:      MKey{a, [], True{}}    case False{}:      TKey{a, k, Part{None{}, None{}, None{}}, True{}}# the dimensions as U32 (xs arrives reversed, so collecting onto acc restores the order), or None past 2^32 - 1def dims(xs: List<&2, W.W64>, acc: List<&2, U32>) -> Maybe<&2, List<&2, U32>>:  match xs:    case []:      Some{acc}    case W.W64{+h, +l} <> t:      Bool.pick(Maybe<&2, List<&2, U32>>, U32.is_eq(h, 0), dims(t, l <> acc), None{})def set_dt(r: Maybe<&2, DType>, a: Acc, k: String, p: Part, +v: String) -> Ps:  match r p:    case None{} _:      PBad{"tensor \"" ++ k ++ "\" has an unknown dtype \"" ++ v ++ "\""}    case Some{d} Part{None{}, sh, of}:      TNext{a, k, Part{Some{d}, sh, of}}    case Some{d} Part{Some{e}, sh, of}:      PBad{"tensor \"" ++ k ++ "\" has two dtypes"}def set_sh(r: Maybe<&2, List<&2, U32>>, a: Acc, k: String, p: Part) -> Ps:  match r p:    case None{} _:      PBad{"tensor \"" ++ k ++ "\" has a dimension past 2^32 - 1"}    case Some{s} Part{dt, None{}, of}:      TNext{a, k, Part{dt, Some{s}, of}}    case Some{s} Part{dt, Some{e}, of}:      PBad{"tensor \"" ++ k ++ "\" has two shapes"}def set_of(a: Acc, k: String, p: Part, xs: List<&2, W.W64>) -> Ps:  match p:    case Part{dt, sh, None{}}:      TNext{a, k, Part{dt, sh, Some{List.reverse(&2, W.W64, xs)}}}    case Part{dt, sh, Some{e}}:      PBad{"tensor \"" ++ k ++ "\" has two data_offsets"}def field_str(isdt: Bool, a: Acc, k: String, p: Part, +f: String, +v: String) -> Ps:  match isdt:    case True{}:      set_dt(DType.of(v), a, k, p, v)    case False{}:      PBad{"tensor \"" ++ k ++ "\": field \"" ++ f ++ "\" is not a list"}def field_list(issh: Bool, isof: Bool, a: Acc, k: String, p: Part, +f: String, xs: List<&2, W.W64>) -> Ps:  match issh isof:    case True{} _:      set_sh(dims(xs, []), a, k, p)    case False{} True{}:      set_of(a, k, p, xs)    case False{} False{}:      PBad{"tensor \"" ++ k ++ "\": field \"" ++ f ++ "\" is not a string"}def field_key(known: Bool, a: Acc, k: String, p: Part, +f: String) -> Ps:  match known:    case True{}:      TColon{a, k, p, f}    case False{}:      PBad{"tensor \"" ++ k ++ "\" has an unknown field \"" ++ f ++ "\""}def tensor_done(a: Acc, k: String, p: Part) -> Ps:  match a p:    case Acc{es, m} Part{Some{d}, Some{s}, Some{b <> e <> []}}:      PNext{Acc{Ent{k, d, s, b, e} <> es, m}}    case _ Part{Some{d}, Some{s}, Some{xs}}:      PBad{"tensor \"" ++ k ++ "\": data_offsets is not two numbers"}    case _ _:      PBad{"tensor \"" ++ k ++ "\" lacks dtype, shape or data_offsets"}def is_field(+f: String) -> Bool:  Bool.or(String.eq(f, "dtype"), Bool.or(String.eq(f, "shape"), String.eq(f, "data_offsets")))def pstep(st: Ps, t: X.Tok) -> Ps:  match st t:    case PBad{why} _:      PBad{why}    case _ X.TBad{why}:      PBad{why}    case PStart{} X.TOpen{}:      PKey{Acc{[], None{}}, True{}}    case PKey{a, first} X.TStr{k}:      PColon{a, k}    case PKey{a, True{}} X.TClose{}:      PEnd{a}    case PColon{a, k} X.TColon{}:      PVal{a, k}    case PVal{a, +k} X.TOpen{}:      val_open(String.eq(k, "__metadata__"), a, k)    case PNext{a} X.TComma{}:      PKey{a, False{}}    case PNext{a} X.TClose{}:      PEnd{a}    case MKey{a, m, first} X.TStr{k}:      MColon{a, m, k}    case MKey{a, m, True{}} X.TClose{}:      meta_done(a, m)    case MColon{a, m, k} X.TColon{}:      MVal{a, m, k}    case MVal{a, m, k} X.TStr{v}:      MNext{a, KV{k, v} <> m}    case MNext{a, m} X.TComma{}:      MKey{a, m, False{}}    case MNext{a, m} X.TClose{}:      meta_done(a, m)    case TKey{a, k, p, first} X.TStr{+f}:      field_key(is_field(f), a, k, p, f)    case TKey{a, k, p, True{}} X.TClose{}:      tensor_done(a, k, p)    case TColon{a, k, p, f} X.TColon{}:      TVal{a, k, p, f}    case TVal{a, k, p, +f} X.TStr{v}:      field_str(String.eq(f, "dtype"), a, k, p, f, v)    case TVal{a, k, p, f} X.TLBr{}:      TList{a, k, p, f, [], True{}}    case TList{a, k, p, +f, xs, True{}} X.TRBr{}:      field_list(String.eq(f, "shape"), String.eq(f, "data_offsets"), a, k, p, f, xs)    case TList{a, k, p, f, xs, first} X.TNum{v}:      TLNext{a, k, p, f, v <> xs}    case TLNext{a, k, p, f, xs} X.TComma{}:      TList{a, k, p, f, xs, False{}}    case TLNext{a, k, p, +f, xs} X.TRBr{}:      field_list(String.eq(f, "shape"), String.eq(f, "data_offsets"), a, k, p, f, xs)    case TNext{a, k, p} X.TComma{}:      TKey{a, k, p, False{}}    case TNext{a, k, p} X.TClose{}:      tensor_done(a, k, p)    case PEnd{a} t2:      PBad{"did not expect " ++ tok_show(t2) ++ " after the header object"}    case s t2:      PBad{"did not expect " ++ tok_show(t2) ++ " there"}def run(ts: List<&2, X.Tok>, st: Ps) -> Ps:  match ts:    case []:      st    case t <> rest:      run(rest, pstep(st, t))# ---- validation ----type Header is Data:  Header{ents: List<&2, Ent>, meta: List<&2, KV>, size: W.W64}# by begin, then end, so an empty tensor sorts before the tensor that starts where it isdef le_be(+ab: W.W64, +ae: W.W64, +bb: W.W64, +be: W.W64) -> Bool:  Bool.or(W.W64.is_lt(ab, bb), Bool.and(W.W64.is_eq(ab, bb), W.W64.is_le(ae, be)))def le_begin(a: Ent, b: Ent) -> Bool:  match a b:    case Ent{an, ad, as, ab, ae} Ent{bn, bd, bs, bb, be}:      le_be(ab, ae, bb, be)def le_name(a: Ent, b: Ent) -> Bool:  String.is_le(Ent.name(a), Ent.name(b))# the first name that two neighbours of a name-sorted list sharedef dup(es: List<&2, Ent>) -> Maybe<&2, String>:  match es:    case []:      None{}    case e <> []:      None{}    case +a <> +b <> t:      Bool.pick(Maybe<&2, String>, String.eq(Ent.name(a), Ent.name(b)), Some{Ent.name(a)}, dup(b <> t))# ---- the spec: the tensors, sorted by begin, tile the data section (LAWS.bend: tile agrees with Ends) ----def same(r: Maybe<&2, W.W64>, +end: W.W64) -> Bool:  match r:    case None{}:      False{}    case Some{x}:      W.W64.is_eq(x, end)def end_of(r: Maybe<&2, W.W64>, +b: W.W64) -> Maybe<&2, W.W64>:  match r:    case None{}:      None{}    case Some{n}:      W.W64.add(b, n)# whether e starts at pos and its byte range holds exactly its element count times its dtype's sizedef fits(e: Ent, +pos: W.W64) -> Bool:  match e:    case Ent{nm, d, s, +b, +f}:      Bool.and(W.W64.is_eq(b, pos), same(end_of(nbytes(d, s), b), f))def ends_if(ok: Bool, r: Maybe<&2, W.W64>) -> Maybe<&2, W.W64>:  match ok:    case True{}:      r    case False{}:      None{}# the spec: where the tensors, in order, end if each starts where the one before it ends (the first at pos) and# spans its element count times its dtype size; None if they do notdef Ends(es: List<&2, Ent>, +pos: W.W64) -> Maybe<&2, W.W64>:  match es:    case []:      Some{pos}    case +e <> t:      ends_if(fits(e, pos), Ends(t, Ent.end(e)))# ---- the check, with the first problem as a message ----def why_size(ok: Bool, +nm: String) -> Maybe<&2, String>:  match ok:    case True{}:      None{}    case False{}:      Some{"tensor \"" ++ nm ++ "\": data_offsets do not span its shape times its dtype size"}def why_at(ok: Bool, +nm: String, +b: W.W64, +pos: W.W64, size_ok: Bool) -> Maybe<&2, String>:  match ok:    case True{}:      why_size(size_ok, nm)    case False{}:      Some{"tensor \"" ++ nm ++ "\" starts at byte " ++ W.W64.show(b) ++ " of the data, but the tensor before it ends at " ++ W.W64.show(pos) ++ " (a gap or an overlap)"}def check(e: Ent, +pos: W.W64) -> Maybe<&2, String>:  match e:    case Ent{+nm, d, s, +b, +f}:      why_at(W.W64.is_eq(b, pos), nm, b, pos, same(end_of(nbytes(d, s), b), f))def tile_join(c: Maybe<&2, String>, r: Result<&2, &2, String, W.W64>) -> Result<&2, &2, String, W.W64>:  match c:    case None{}:      r    case Some{why}:      Fail{why}# the end of the tiling from pos, or the first problemdef tile(es: List<&2, Ent>, +pos: W.W64) -> Result<&2, &2, String, W.W64>:  match es:    case []:      Done{pos}    case +e <> t:      tile_join(check(e, pos), tile(t, Ent.end(e)))# ---- the header ----def meta_of(m: Maybe<&2, List<&2, KV>>) -> List<&2, KV>:  match m:    case None{}:      []    case Some{xs}:      xsdef finish(es: List<&2, Ent>, m: List<&2, KV>, r: Result<&2, &2, String, W.W64>) -> Result<&2, &2, String, Header>:  match r:    case Fail{why}:      Fail{why}    case Done{n}:      Done{Header{es, m, n}}def unique(d: Maybe<&2, String>, +es: List<&2, Ent>, m: List<&2, KV>) -> Result<&2, &2, String, Header>:  match d:    case None{}:      finish(es, m, tile(es, W.W64.zero()))    case Some{nm}:      Fail{"two tensors are named \"" ++ nm ++ "\""}def accept(a: Acc) -> Result<&2, &2, String, Header>:  match a:    case Acc{es, m}:      +sorted = List.sort(~Ent, ~le_begin, es)      unique(dup(List.sort(~Ent, ~le_name, sorted)), sorted, meta_of(m))def parsed(st: Ps) -> Result<&2, &2, String, Header>:  match st:    case PEnd{a}:      accept(a)    case PBad{why}:      Fail{why}    case PStart{}:      Fail{"the header is empty"}    case _:      Fail{"the header ends early"}# the header's tensors, sorted by begin, its metadata, and the size of its data section; or what is wrong with itdef parse(bs: List<&2, U32>) -> Result<&2, &2, String, Header>:  parsed(run(X.tokens(bs), PStart{}))