~/bend-docscommunity

tensor_model.bend source

tensor_model.bend on the hub · documented module

# Models: a step computes with tensors it takes by name from a store, so a# network reads as one step after another and its weights are loaded once.import Baseimport ./tensor.bend as Tensorsimport ./tensor_grid.bend as Gridimport ./tensor_file.bend as Filesimport ./tensor_tiled.bend as Tiled# The store holds the tensors in their tiled form: a file read tiles once.def Tensor() -> Type:  Tiled.Tiled# A stored tensor is laid out as parameters are read: weights [outputs,# inputs,...] with the lanes along the outputs and the groups outermost, as# convolutions and matrix products read them.def stored_along(single: Bool,tensor: Files.Tensor()) -> Tensor():  match single:    case True{}: Tiled.tiled(tensor)    case False{}: Tiled.tiled_at(tensor,0n,Grid.Outermost{})def stored(tensor: Files.Tensor()) -> Tensor():  Tensors.with_metadata(~F32,~Tensor(),tensor,tensor => shape => fill => status => workers => stored_along(U32.is_eq(Tensors.known_count(List.get(&2,U32,shape,0n)),1),tensor))# A store that could not be loaded keeps its problem, and every take reports it.type Store is Type:  Empty{}  Entry{name: String,tensor: Tensor(),rest: Store}  Unavailable{problem: Tensors.Problem}# A step: given the store, a value and the store that remains.def Model(A: Type) -> Type:  Store -> A & Storedef Model.pure(-A: Type,value: A) -> Model(A):  store => (value,store)def Model.next(-A: Type,-B: Type,pair: A & Store,next: A -> Model(B)) -> B & Store:  (value,store) = pair  next(value)(store)def Model.bind(-A: Type,-B: Type,step: Model(A),next: A -> Model(B)) -> Model(B):  store => Model.next(A,B,step(store),next)def missing(+name: String) -> Tensor():  Tiled.failed("take",Tensors.MissingName{name},[],1)def unavailable(problem: Tensors.Problem) -> Tensor():  Tensors.Problem{operation,reason} = problem  Tiled.failed(operation,reason,[],1)def passed(name: String,tensor: Tensor(),pair: Tensor() & Store) -> Tensor() & Store:  (result,store) = pair  (result,Entry{name,tensor,store})def scan(rest: Store,same: Bool,+name: String,tensor: Tensor(),+wanted: String) -> Tensor() & Store:  match rest same:    case Empty{} True{}: (tensor,Empty{})    case Entry{next,other,more} True{}: (tensor,Entry{next,other,more})    case Unavailable{problem} True{}: (tensor,Unavailable{problem})    case Empty{} False{}: (missing(wanted),Entry{name,tensor,Empty{}})    case Unavailable{+problem} False{}: (unavailable(problem),Entry{name,tensor,Unavailable{problem}})    case Entry{+next,other,more} False{}: passed(name,tensor,scan(more,String.eq(next,wanted),next,other,wanted))def taken(store: Store,+wanted: String) -> Tensor() & Store:  match store:    case Empty{}: (missing(wanted),Empty{})    case Unavailable{+problem}: (unavailable(problem),Unavailable{problem})    case Entry{+name,tensor,rest}: scan(rest,String.eq(name,wanted),name,tensor,wanted)# The tensor of that name leaves the store. A name that is not there gives a# failed tensor.def take(+name: String) -> Model(Tensor()):  store => taken(store,name)def kept(+name: String,pair: Tensor() & Tensor(),store: Store) -> Tensor() & Store:  (tensor,copy) = pair  (tensor,Entry{name,copy,store})# Puts a copy under the name, for a later take, and gives the tensor back.def named_rest(+name: String,tensor: Tensor(),pair: List<&2,String> & Store) -> List<&2,String> & Store:  (names,rest) = pair  (name <> names,Entry{name,tensor,rest})# The names in the store, in its order, and the store unchanged.def names(store: Store) -> List<&2,String> & Store:  match store:    case Empty{}: ([],Empty{})    case Unavailable{problem}: ([],Unavailable{problem})    case Entry{+name,tensor,rest}: named_rest(name,tensor,names(rest))def listed_names() -> Model(List<&2,String>):  store => names(store)def keep(+name: String,tensor: Tensor()) -> Model(Tensor()):  store => kept(name,Tiled.copy(tensor),store)def run(-A: Type,step: Model(A),store: Store) -> A & Store:  step(store)def value(-A: Type,pair: A & Store) -> A:  (result,store) = pair  result# Runs the steps on the store and gives the result; what remains in the store is dropped.def result(-A: Type,step: Model(A),store: Store) -> A:  value(A,step(store))def joined(+name: String,first: Tensor(),second: Tensor(),rest: Store & Store) -> Store & Store:  (left,right) = rest  (Entry{name,first,left},Entry{name,second,right})def copied_entry(+name: String,pair: Tensor() & Tensor(),rest: Store & Store) -> Store & Store:  (first,second) = pair  joined(name,first,second,rest)# Two stores with the same tensors, to run a model more than once.def copy(store: Store) -> Store & Store:  match store:    case Empty{}: (Empty{},Empty{})    case Unavailable{+problem}: (Unavailable{problem},Unavailable{problem})    case Entry{+name,tensor,rest}: copied_entry(name,Tiled.copy(tensor),copy(rest))# Loading: folder/names.txt lists one name per line; folder/<name>.npy holds its tensor.def entry(+name: String,tensor: Tensor(),store: Store) -> Store:  Entry{name,tensor,store}def load_each(names: List<&2,String>,+folder: String) -> IO(Store):  match names:    case Nil{}: IO.pure(Store,Empty{})    case Con{+name,rest}:      match name:        case SNil{}: load_each(rest,folder)        case SCon{head,tail}:          do IO<Store>:            tensor : Files.Tensor() <- Files.load_npy(folder ++ "/" ++ name ++ ".npy")            store : Store <- load_each(rest,folder)            IO.pure(Store,entry(name,stored(tensor),store))def unlisted(+folder: String,detail: String) -> Store:  Unavailable{Tensors.Problem{"load_weights",Tensors.FileFault{folder ++ "/names.txt",detail}}}def named(text: Result<&1,&1,U32 & String,String>,+folder: String) -> IO(Store):  match text:    case Fail{error}: IO.pure(Store,unlisted(folder,"cannot be read"))    case Done{text}: load_each(String.lines(text),folder)def listed(read: File & Result<&1,&1,U32 & String,String>,+folder: String) -> IO(Store):  (file,text) = read  do IO<Store>:    File.close(file)    named(text,folder)def opened(result: Result<&1,&1,U32 & String,File>,+folder: String) -> IO(Store):  match result:    case Fail{error}: IO.pure(Store,unlisted(folder,"cannot be opened"))    case Done{file}:      do IO<Store>:        read : File & Result<&1,&1,U32 & String,String> <- File.read(file,1048576)        listed(read,folder)# A folder whose names.txt cannot be read gives a store whose every take reports it.def load(+folder: String) -> IO(Store):  do IO<Store>:    result : Result<&1,&1,U32 & String,File> <- File.open(folder ++ "/names.txt","r")    opened(result,folder)# Saving: the tensors of a store as folder/<name>.npy, and their names in folder/names.txt.def first(written: File & Result<&1,&1,U32 & String,Unit>) -> File:  (file,result) = written  filedef lines(names: List<&2,String>) -> String:  match names:    case []: ""    case name <> rest: name ++ "" ++ lines(rest)def save_each(store: Store,+folder: String) -> IO(Store):  match store:    case Empty{}: IO.pure(Store,Empty{})    case Unavailable{problem}: IO.pure(Store,Unavailable{problem})    case Entry{+name,tensor,rest}:      do IO<Store>:        saved : Files.Tensor() <- Files.save_npy(folder ++ "/" ++ name ++ ".npy",Tiled.untiled(tensor))        others : Store <- save_each(rest,folder)        IO.pure(Store,entry(name,stored(saved),others))def listing(result: Result<&1,&1,U32 & String,File>,text: String) -> IO(Unit):  match result:    case Fail{error}: IO.pure(Unit,Unit{})    case Done{file}:      do IO<Unit>:        written : File & Result<&1,&1,U32 & String,Unit> <- File.write(file,text)        File.close(first(written))def save_listed(pair: List<&2,String> & Store,+folder: String) -> IO(Store):  (names,store) = pair  do IO<Store>:    result : Result<&1,&1,U32 & String,File> <- File.open(folder ++ "/names.txt","w")    listing(result,lines(names))    save_each(store,folder)# Gives the store back; a tensor that could not be written comes back failed.def save(+folder: String,store: Store) -> IO(Store):  save_listed(names(store),folder)