Package: verysimpletransformers
Very Simple Transformers (VST)Table of ContentsInstallationUsageCLIChangelogLicenseInstallationUsageBundlingBundling your machine learning model with VerySimpleTransformers is straightforward. Follow these steps:Create or load your machine learning model (e.g., a ClassificationModel) using Simple Transformers.Example:fromsimpletransformers.classificationimportClassificationArgs,ClassificationModel# Create a ClassificationModelmodel_args=ClassificationArgs(num_train_epochs=1,overwrite_output_dir=True,save_model_every_epoch=False,)model=ClassificationModel("bert","bert-base-cased",# or something like ./outputsargs=model_args,use_cuda=True,)# optionally train on your data:model.train_model(...)Import theverysimpletransformerspackage, and use theto_vstfunction to package the model into a .vst file with
optional compression.Provide the model, the output file path, and an optional compression level (0-9).
By default, compression will be disabled.The output file path can be specified as:A string path (e.g.,"model.vst") for a standard file path.APathobject (e.g.,Path("model.vst")) usingpathlib.A binary I/O object (e.g.,BytesIO()) for in-memory operations, if you don't want to save to a file.Example:importverysimpletransformers# or: from verysimpletransformers import to_vstfrompathlibimportPath# can be used instead of a stringverysimpletransformers.to_vst(model,"my_model.vst",compression=5,# optional)Note: As an alias,bundle_modelcan be used instead ofto_vst.LoadingLoading a machine learning model from a .vst file is just as simple. Follow these steps:Importfrom_vstfromsimpletransformers.
Specify the path to the .vst file you want to load. Just like withto_vst, this path can be astr,Pathor binary
IO.
Use thefrom_vstfunction to load the model. Optionally, you can specify thedeviceparameter to set the device (
e.g., 'cpu' or 'cuda'). If not specified, the function will select a device based on availability.Example:fromverysimpletransformersimportfrom_vstfrompathlibimportPathfp=Path("model.vst")# can also be simply a string.new_model=from_vst(fp,device='cuda',# optional)You can now use thenew_modelfor various machine learning tasks.Note: As an alias,load_modelcan be used instead ofto_vst.Additional InformationThe.vstfiles can be transferred and used across different devices, regardless of where the model was originally
trained.Ensure that you have the required dependencies, such as SimpleTransformers and PyTorch, installed to use these
functions effectively.Full ExampleTo see a full example of saving and loading a.vstfile,
seeexamples/basic.pyCLIThe VerySimpleTransformers CLI provides a convenient and versatile way to interact with and manage your machine learning
models created with VerySimpleTransformers. It allows you to perform various actions using a command-line interface,
making it easy to run, serve, and upgrade your models with ease.UsageYou can use the CLI with eitherverysimpletransformersorvstinterchangeably. Here are some basic usage examples:Running a model interactively:verysimpletransformersmodel.vst
vstmodel.vst
./model.vstSpecifying an action when running:verysimpletransformers<action>model.vst
verysimpletransformersmodel.vst<action>
vst<action>model.vst
vstmodel.vst<action>
./model.vst<action># if the file has execution rightsAvailable ActionsThe following actions are available:'run': Run the model interactively by typing prompts.'serve': Start a simple HTTP server to serve model outputs. You can specify the following options:--port <PORT>: Specify the port number (default: 8000).--host <HOST>: Specify the host (default: 'localhost').'upgrade': Upgrade the metadata of a model to the latest version.ExampleHere's an example of starting a server for a classification model:vstserve./classification.vst
./classification.vstserveFor more examples,
seeexamples/basic.shNotesA .vst file (e.g., 'model.vst') is required for most commands.You can specify<action>, which can be one of the available options mentioned above.If you leave<action>empty, a dropdown menu will appear for you to select from.You can use 'vst' or 'verysimpletransformers' interchangeably.About the .vst file formatThe.vstfile format is used to bundle machine learning models created with SimpleTransformers. Understanding its
structure is useful for working with these files effectively. The format consists of the following components:Shebang Line: The first line of the file is a shebang (#!/usr/bin/env verysimpletransformers) that allows the
file to be executed using./. This line indicates that the file can be executed as a script.Fixed Information (16 bytes):VST Protocol Version(short, 2 bytes): Specifies the version of the VerySimpleTransformers Protocol used in the
file. This allows for backwards compatibility with older versions of the file, which may have less metadata.Metadata Length(short, 2 bytes): Indicates the length of the metadata section in bytes.Content Length(long long, 8 bytes): Specifies the length of the content (actual model data) in bytes.Explanation: The total size of the fixed information is 12 bytes according to the data types (2 bytes
forshort+ 2 bytes forshort+ 8 bytes forlong long). However, it sums up to 16 bytes due tostructpadding.
The padding aligns the data structure to meet memory alignment requirements and ensure efficient memory access.Metadata (Variable Length):The nextMetadata Lengthbytes contain the metadata, which can vary in length. The metadata is used to store
information about the model and its compatibility with different versions of VerySimpleTransformers. The structure
of the metadata can change between protocol versions.Checks are performed on this metadata to ensure compatibility and integrity. If the metadata is invalid or belongs
to a newer protocol version, a warning is issued, and the loading process continues.Model Content (Variable Length):The remaining bytes, equal toContent Length, contain the serialized model data. This is the actual (possibly
compressed) machine learning model that was bundled into the.vstfile.The model contents are stored (and loaded) usingdill(which is an extension ofpickle).┌───────────────────────────────────────┐
                              │#!/usr/bin/env verysimpletransformers\n├──────────► Shebang
                              ├───┬───┬───────────┬───────────────────┤
                              │   │   │           │                   │
                              │2b │2b │  4 bytes  │  content length   │
              .vst version  ◄─┼── │   │           │       (n2)        ├──────────► 16 bytes
                              │   │   │ (padding) │                   │
    meta header length (n1) ◄─┼───┼── │           │      8 bytes      │
                              │   │   │           │                   │
                              ├───┴───┴───────────┴───────────────────┤
                              │                                       │
                              │                                       │
                              │                                       │
                              │              Meta Header              │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                n1 bytes               │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              ├───────────────────────────────────────┤
                              │                                       │
                              │                                       │
                              │         (possible compressed)         │
                              │                                       │
                              │                                       │
                              │      Machine Learning Model Dill      │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │               n2 bytes                │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │                                       │
                              │            ..............             │
                              │                                       │
                              └───────────────────────────────────────┘Converting avstfile back into the original model filesIf you want to retrieve the original model files from a saved vst file, you can use thedump_to_disk()function:fromverysimpletransformersimportdump_to_diskvst_path='my_model.vst'# Convert vst file to original model filesdump_to_disk(vst_path,# a running model or path to a .vst file'model_files/',# optional, default is 'outputs/')This will extract the model contents from the vst file and save the individual components in themodel_files/directory:pytorch_model.bin- Model weightstokenizer.json- Tokenizer configurationvocab.txt- Vocabularyetc.This allows you to easily retrieve the original model files from a vst save file in order to upload or share the model
to e.g. huggingface.Extra'sDriveTo enable integration with Google Drive, this extra uses the
librarydrive-into enable uploading and downloading models from Drive.pipinstallverysimpletransformers[drive]fromverysimpletransformers.driveimportto_drive,from_drivemodel:ClassificationModel# or some other modeldrive_url=to_drive(model)# ...new_model:ClassificationModel=from_drive(drive_url)Limitations:Due to limitations with oauth2 (without using a private key, which is not feasible for an open source project),
you can only access files created by this app (i.e. uploaded withto_drive).By default, you're redirected tohttps://oauth.trialandsuccess.nl/callbackafter authenticating your Google account.
This page runsoauth-echoerand simply returns the access token
from the query arguments.
If you want to change this endpoint, you can pass aclient_idandredirect_urito the Drive functions.
Doing so requires an oauth app withdrive.filepermissions.Licenseverysimpletransformersis distributed under the terms of theMITlicense.ChangelogSeeCHANGELOG.mdon GitHub