https://github.com/crowdstrike/tf2rust

Tensorflow to Rust is a tool to convert trained Tensorflow models to pure Rust code.

https://github.com/crowdstrike/tf2rust

Science Score: 26.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (7.4%) to scientific vocabulary
Last synced: 11 months ago · JSON representation

Repository

Tensorflow to Rust is a tool to convert trained Tensorflow models to pure Rust code.

Basic Info
  • Host: GitHub
  • Owner: CrowdStrike
  • License: mit
  • Language: Python
  • Default Branch: main
  • Size: 493 KB
Statistics
  • Stars: 87
  • Watchers: 6
  • Forks: 6
  • Open Issues: 0
  • Releases: 1
Created over 3 years ago · Last pushed almost 3 years ago
Metadata Files
Readme Changelog Contributing License Code of conduct Security

README.md

TensorFlow to Rust package

Special thanks to Marian Radu for his support during the development of the package

Training Workflow

training overview

General Information

conversion mechanism

A Python package that converts a TensorFlow model (.pb or .h5 format) into pure Rust code. This package is dependent on tf-layers (Rust):

Currently, this package supports models that contain the following layers (the layers number is expected to grow in the future with the addition of further architectures):

Requirements

This project targets the Python 3.8 interpreter. You will need to install graphviz using your system dependency manager of choice. On macOS, this can be done with the command:

bash brew install graphviz

To set up a virtualenv with poetry, execute the following commands in the project root:

bash poetry install poetry shell

Configuration arguments

--pathtotf_model

The path (relative or absolute) to the TensorFlow model to be converted into pure Rust code. It is mandatory.

--pathtosave

The path (relative or absolute) where to save the generated Rust code. It is mandatory.

--model_name

The model name. A struct named Model will be created in Rust. E.g model_name = Mnist => Mnist. It is mandatory.

--binary_classification

Set this flag to true/false whether the model is a binary classifier or not (false for regression or multiclass classifiers). Default is true.

--enable_inplace

Set this flag to true/false whether you want the model written in Rust to use in-place operations whenever possible (in predict_from_array function). Default is true.

--enable_memdrop

Set this flag to true/false whether you want the model written in Rust to free the memory of intermediate layers results as soon as possible (instead of the actual ending of predict_from_array function). Default is true.

--pathtofv

Set the path to a npz array containing the FV for a bunch of samples. The keys for the arrays should match the keys from perform_fx from NeuralBrain (which must be the same as the InputLayers' names when building the model). Also, the expected predictions should be saved as an array in features.npz by the key predictions. This flag is optional.

Output Files

generated files

  • savedmodelfrom_tensorflow:
    • computation_graph.json: The computational dependencies.
    • modelarchitecture.json: Different parameters for the actual NN layers (stride, poolsize, kernel_size, activation type, etc).
    • model_overview.png: A graph image describing the model.
    • model_weights.npz: model's weights.
  • rustgeneratedcode:
    • build.rs: A Rust build file used in serializing the model by reading from model_weights.npz
    • Cargo.toml: the place where all the imports are specified (and many more).
  • rustgeneratedcode/model:
    • model_weights.npz: model weights saved in a format that can be used by Rust.
    • thresholds.json: the thresholds for low, bottom, medium, high confidence levels.
  • rustgeneratedcode/src:
    • model.rs: A Rust structure encapsulating all the logic behind prediction.
    • lib.rs: the file containing the tests.
  • rustgeneratedcode/testdata:
    • features.npz: the features to be passed to the model (1D numpy ndarray).
  • rustgeneratedcode/benches:
    • benchmarks.rs: the file in charge of benchmarks.

In order to asses the performance of the model, run cargo bench

In order to test the predictions and see the translation went as expected, run cargo test

Note: all this commands need be executed on rust_generated_code/ directory

Usage

To convert a TensorFlow model use a command-line like the followings:

```bash python3 -m tf2rust \ --pathtotfmodel tests/data/mnist/tfmodel/ \ --pathtosave tests/data/generatedclassifiers/mnist \ --modelname MNist \ --binaryclassification True \ --enableinplace True \ --enablememdrop True \ --pathto_fv tests/data/mnist/features.npz # for testing purposes, optional

```

Converting .h5 models to .pb

```python from tensorflow.keras.models import loadmodel, savemodel

Note that models will have different metrics also saved with the models and expect the implementations for these

metrics.

We have these implemented in utils/scoring_metrics.py but these are not used, and we can also provide None.

model = loadmodel('newmodel.h5', customobjects={'tpr': None, 'tnr': None, 'auc': None}) savemodel(model=model, filepath='tfmodel/', includeoptimizer=False) ```

Running the tests

At the time we'll migrate towards Dockerising this, we'll also switch to tox (this should not pose any difficulties).

We have currently set up integration tests, which do the following:

  • Given model artifacts, generate Rust code
  • Check that the Rust code is the same code to what we expect to be generated
  • Compile the Rust code and see that all tests pass
    • Tests take in FVs and the DVs generated by the Tensorflow model
    • We check that inference with the Rust model yields the same results as the initial Tensorflow model

bash pytest

Next steps

After everything runs smoothly with your model, please add artifacts and a new test for it.

Owner

  • Name: CrowdStrike
  • Login: CrowdStrike
  • Kind: organization
  • Email: github@crowdstrike.com
  • Location: United States of America

GitHub Events

Total
  • Watch event: 4
Last Year
  • Watch event: 4

Committers

Last synced: about 1 year ago

All Time
  • Total Commits: 5
  • Total Committers: 2
  • Avg Commits per committer: 2.5
  • Development Distribution Score (DDS): 0.4
Past Year
  • Commits: 0
  • Committers: 0
  • Avg Commits per committer: 0.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
Lukasz Woznicki 7****t 3
Sebastian Nae n****0@g****m 2

Issues and Pull Requests

Last synced: about 1 year ago

All Time
  • Total issues: 2
  • Total pull requests: 3
  • Average time to close issues: 8 months
  • Average time to close pull requests: about 15 hours
  • Total issue authors: 2
  • Total pull request authors: 2
  • Average comments per issue: 1.5
  • Average comments per pull request: 0.0
  • Merged pull requests: 3
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 1
  • Pull requests: 0
  • Average time to close issues: 3 days
  • Average time to close pull requests: N/A
  • Issue authors: 1
  • Pull request authors: 0
  • Average comments per issue: 2.0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • ViaAdmin (1)
  • SkBlaz (1)
Pull Request Authors
  • makr11st (2)
  • SheepSeb (1)
Top Labels
Issue Labels
Pull Request Labels

Dependencies

poetry.lock pypi
  • absl-py 1.4.0
  • argparse 1.4.0
  • astunparse 1.6.3
  • atomicwrites 1.4.1
  • attrs 23.1.0
  • black 22.12.0
  • cachetools 5.3.1
  • certifi 2023.7.22
  • cffi 1.15.1
  • charset-normalizer 3.2.0
  • click 8.1.7
  • colorama 0.4.6
  • cryptography 41.0.3
  • distlib 0.3.7
  • docutils 0.20.1
  • filelock 3.12.4
  • flatbuffers 23.5.26
  • gast 0.4.0
  • google-auth 2.23.0
  • google-auth-oauthlib 1.0.0
  • google-pasta 0.2.0
  • grpcio 1.58.0
  • h5py 3.9.0
  • idna 3.4
  • importlib-metadata 6.8.0
  • iniconfig 2.0.0
  • isort 5.12.0
  • jaraco-classes 3.3.0
  • jeepney 0.8.0
  • joblib 1.3.2
  • keras 2.13.1
  • keyring 24.2.0
  • libclang 16.0.6
  • markdown 3.4.4
  • markdown-it-py 3.0.0
  • markupsafe 2.1.3
  • mdurl 0.1.2
  • more-itertools 10.1.0
  • mypy-extensions 1.0.0
  • nh3 0.2.14
  • numpy 1.24.3
  • oauthlib 3.2.2
  • opt-einsum 3.3.0
  • packaging 23.1
  • pathspec 0.11.2
  • pkginfo 1.9.6
  • platformdirs 3.10.0
  • pluggy 1.3.0
  • protobuf 4.24.3
  • py 1.11.0
  • pyasn1 0.5.0
  • pyasn1-modules 0.3.0
  • pycparser 2.21
  • pydot 1.4.2
  • pygments 2.16.1
  • pyparsing 3.1.1
  • pytest 6.2.5
  • pywin32-ctypes 0.2.2
  • readme-renderer 42.0
  • requests 2.31.0
  • requests-oauthlib 1.3.1
  • requests-toolbelt 1.0.0
  • rfc3986 2.0.0
  • rich 13.5.2
  • rsa 4.9
  • scikit-learn 1.3.0
  • scipy 1.11.2
  • secretstorage 3.3.3
  • setuptools 68.2.2
  • six 1.16.0
  • tensorboard 2.13.0
  • tensorboard-data-server 0.7.1
  • tensorflow 2.13.0
  • tensorflow-estimator 2.13.0
  • tensorflow-io-gcs-filesystem 0.34.0
  • termcolor 2.3.0
  • threadpoolctl 3.2.0
  • toml 0.10.2
  • tomli 2.0.1
  • tox 3.28.0
  • twine 4.0.2
  • typing-extensions 4.5.0
  • urllib3 1.26.16
  • virtualenv 20.24.5
  • werkzeug 2.3.7
  • wheel 0.41.2
  • wrapt 1.15.0
  • zipp 3.16.2
pyproject.toml pypi
  • black ^22.3.0 develop
  • isort ^5.10.1 develop
  • pytest ^6 develop
  • tox ^3.28.0 develop
  • twine ^4.0.2 develop
  • argparse ==1.4
  • numpy ==1.24.3
  • pydot ==1.4.2
  • python >=3.9,<3.12
  • scikit-learn ==1.3.0
  • scikit-learn ==1.1.3
  • tensorflow ==2.13.0