Convert a Python model to WASM object through the power of Python and Go.
To install, we need to install m2cgen. It is probably best to use a virtual environment such as venv
to not pollute the global python
setup, via something like python -m venv venv;venv/Scripts/activate;
pip install m2cgen
You will need to install the appropriate depedencies along with m2cgen
depending on your model choice, e.g. pip install m2cgen scikit-learn
Also make sure you have Go and TinyGo installed. Optionally you may want to install just and wasmer
The rough workflow is:
- Generate the model (in Go) via m2cgen
- Generate the Go code
- Generate the TinyGo compatible code for WASM build
- Build the WASM file
It would look something like the below (has some missing arguments, check justfile
for details:
$ m2cgen mymodel.pkl --language go > model2tinygo.go
$ go run model2tinygo.go > main.go
$ tinygo build -o output.wasm -target=wasi -wasm-abi=generic main.go
$ wasmer output.wasm -- 1 2 -2 -1
This has been abstracted away via just where you can run
just -l
just build-wasm mymodel.pkl mymodel.go mymodel.wasm
# in windows
just --shell powershell.exe --shell-arg -c build-wasm mymodel.pkl mymodel.go mymodel.wasm
Reproducible example:
python demo/generate_model_example.py --filename mymodel
just build-wasm mymodel.pkl mymodel.go mymodel.wasm
wasmer mymodel.wasm -- 1 2 -2 -1
# output - 199
Since I'm still getting around learning go
there are going to be patterns which don't make sense to a seasoned programmer. One example is I don't understand go generate
- does that help or hinder this pipeline?