Package: zanj
ZANJOverviewTheZANJformat is meant to be a way of saving arbitrary objects to disk, in a way that is flexible, allows keeping configuration and data together, and is human readable. It is very loosely inspired by HDF5 and the derivedexdirformat, and the implementation is inspired bynpzfiles.You can take anySerializableDataclassfrom themuutilslibrary and save it to disk -- any large arrays or lists will be stored efficiently as external files in the zip archive, while the basic structure and metadata will be stored in readable JSON files.You can also specify a specialConfiguredModel, which inherits from atorch.nn.Modulewhich will let you save not just your model weights, but all required configuration information, plus any other metadata (like training logs) in a single file.This library was originally a module inmuutilsInstallationAvailable on PyPI aszanjpip install zanjUsageYou can find a runnable example of this indemo.ipynbSaving a basic objectAnySerializableDataclassof basic types can be saved as zanj:importnumpyasnpimportpandasaspdfrommuutils.json_serializeimportSerializableDataclass,serializable_dataclass,serializable_fieldfromzanjimportZANJ@serializable_dataclassclassBasicZanj(SerializableDataclass):a:strq:int=42c:list[int]=serializable_field(default_factory=list)# initialize a zanj reader/writerzj=ZANJ()# create an instanceinstance:BasicZanj=BasicZanj("hello",42,[1,2,3])path:str="tests/junk_data/path_to_save_instance.zanj"zj.save(instance,path)recovered:BasicZanj=zj.read(path)ZANJ will intelligently handle nested serializable dataclasses, numpy arrays, pytorch tensors, and pandas dataframes:importtorchimportpandasaspd@serializable_dataclassclassComplicated(SerializableDataclass):name:strarr1:np.ndarrayarr2:np.ndarrayiris_data:pd.DataFramebrain_data:pd.DataFramecontainer:list[BasicZanj]torch_tensor:torch.TensorFor custom classes, you can specify aserialization_fnandloading_fnto handle the logic of converting to and from a json-serializable format:@serializable_dataclassclassComplicated(SerializableDataclass):name:strdevice:torch.device=serializable_field(serialization_fn=lambdaself:str(self.device),loading_fn=lambdadata:torch.device(data["device"]),)Note thatloading_fntakes the dictionary of the whole class -- this is in case you've stored data in multiple fields of the dict which are needed to reconstruct the object.Saving ModelsFirst, define a configuration class for your model. This class will hold the parameters for your model and any associated objects (like losses and optimizers). The configuration class should be a subclass ofSerializableDataclassand use theserializable_fieldfunction to define fields that need special serialization.Here's an example that defines a GPT-like model configuration:fromzanj.torchutilimportConfiguredModel,set_config_class@serializable_dataclassclassMyNNConfig(SerializableDataclass):input_dim:inthidden_dim:intoutput_dim:int# store the activation function by name, reconstruct it by looking it up in torch.nnact_fn:torch.nn.Module=serializable_field(serialization_fn=lambdax:x.__name__,loading_fn=lambdax:getattr(torch.nn,x["act_fn"]),)# same for the loss functionloss_kwargs:dict=serializable_field(default_factory=dict)loss_factory:torch.nn.modules.loss._Loss=serializable_field(default_factory=lambda:torch.nn.CrossEntropyLoss,serialization_fn=lambdax:x.__name__,loading_fn=lambdax:getattr(torch.nn,x["loss_factory"]),)loss=property(lambdaself:self.loss_factory(**self.loss_kwargs))Then, define your model class. It should be a subclass ofConfiguredModel, and use theset_config_classdecorator to associate it with your configuration class. The__init__method should take a single argument, which is an instance of your configuration class. You must also call the superclass__init__method with the configuration instance.@set_config_class(MyNNConfig)classMyNN(ConfiguredModel[MyNNConfig]):def__init__(self,config:MyNNConfig):# call the superclass init!# this will store the model in the zanj_model_config fieldsuper().__init__(config)# whatever you want hereself.net=torch.nn.Sequential(torch.nn.Linear(config.input_dim,config.hidden_dim),config.act_fn(),torch.nn.Linear(config.hidden_dim,config.output_dim),)defforward(self,x):returnself.net(x)You can now create instances of your model, save them to disk, and load them back into memory:config=MyNNConfig(input_dim=10,hidden_dim=20,output_dim=2,act_fn=torch.nn.ReLU,loss_kwargs=dict(reduction="mean"),)# create your model from the config, and savemodel=MyNN(config)fname="tests/junk_data/path_to_save_model.zanj"ZANJ().save(model,fname)# load by calling the class method `read()`loaded_model=MyNN.read(fname)# zanj will actually infer the type of the object in the file# -- and will warn you if you don't have the correct package installedloaded_another_way=ZANJ().read(fname)ConfigurationWhen initializing aZANJobject, you can specify some configuration info about saving, such as:thresholds for how big an array/table has to be before moving to external filecompression settingserror modesadditional handlers for serialization# how big an array or list (including pandas DataFrame) can be before moving it from the core JSON fileexternal_array_threshold:int=ZANJ_GLOBAL_DEFAULTS.external_array_thresholdexternal_list_threshold:int=ZANJ_GLOBAL_DEFAULTS.external_list_threshold# compression settings passed to `zipfile` packagecompress:bool|int=ZANJ_GLOBAL_DEFAULTS.compress# for doing very cursed things in your own custom loading or serialization functionscustom_settings:dict[str,Any]|None=ZANJ_GLOBAL_DEFAULTS.custom_settings# specify additional serialization handlershandlers_pre:MonoTuple[SerializerHandler]=tuple()handlers_default:MonoTuple[SerializerHandler]=DEFAULT_SERIALIZER_HANDLERS_ZANJ,ImplementationThe on-disk format is a file<filename>.zanjis a zip file containing:__zanj_meta__.json: a file containing zanj-specific metadata including:system informationinstalled packagesinformation about external files__zanj__.json: a file containing user-specified datawhen an element is too big, it can be moved to an external file.npyfor numpy arrays or torch tensors.jsonlfor pandas dataframes or large sequenceslist of external files stored in__zanj_meta__.json"$ref" key will have value pointing to external file__format__key will detail an external format typeComparison to other formatsFormatSafeZero-copyLazy loadingNo file size limitLayout controlFlexibilityBfloat16pickle (PyTorch)❌❌❌✅❌✅✅H5 (Tensorflow)✅❌✅✅~~❌HDF5✅?✅✅~✅❌SavedModel (Tensorflow)✅❌❌✅✅❌✅MsgPack (flax)✅✅❌✅❌❌✅Protobuf (ONNX)✅❌❌❌❌❌✅Cap'n'Proto✅✅~✅✅~❌Numpy (npy,npz)✅??❌✅❌❌SafeTensors✅✅✅✅✅❌✅exdir✅????✅❌ZANJ✅❌❌*✅✅✅❌*Safe: Can I use a file randomly downloaded and expect not to run arbitrary code ?Zero-copy: Does reading the file require more memory than the original file ?Lazy loading: Can I inspect the file without loading everything ? And loading only some tensors in it without scanning the whole file (distributed setting) ?Layout control: Lazy loading, is not necessarily enough since if the information about tensors is spread out in your file, then even if the information is lazily accessible you might have to access most of your file to read the available tensors (incurring many DISK -> RAM copies). Controlling the layout to keep fast access to single tensors is important.No file size limit: Is there a limit to the file size ?Flexibility: Can I save custom code in the format and be able to use it later with zero extra code ? (~ means we can store more than pure tensors, but no custom code)Bfloat16: Does the format support native bfloat16 (meaning no weird workarounds are necessary)? This is becoming increasingly important in the ML world.*denotes this feature may be coming at a future date :)(This table was stolen fromsafetensors)