Coder Social home page Coder Social logo

sshane / konverter Goto Github PK

View Code? Open in Web Editor NEW
38.0 2.0 9.0 7.7 MB

Convert simple Keras models to pure Python 🐍+ NumPy

Home Page: https://sshane.github.io/Konverter/

License: MIT License

Python 99.86% Makefile 0.14%
keras-tensorflow neural-networks model-converter keras python tensorflow

konverter's Introduction

Konverter Konverter Tests

Convert your Keras models into pure Python 🐍+ NumPy.

The goal of this tool is to provide a quick and easy way to execute Keras models on machines or setups where utilizing TensorFlow/Keras is impossible. Specifically, in my case, to replace SNPE (Snapdragon Neural Processing Engine) for inference on phones with Python.

Supported Keras Model Attributes

  • Models:
    • Sequential
  • Layers:
    • Dense
    • Dropout
      • Will be ignored during inference (SNPE 1.19 does NOT support dropout with Keras!)
    • SimpleRNN
      • Batch predictions do not currently work correctly.
    • GRU
      • Important: The current GRU support is based on GRU v3 in tf.keras 2.1.0. It will not work correctly with older versions of TensorFlow if not using implementation=2 (example).
      • Batch prediction untested
    • BatchNormalization
      • Works with all supported layers
  • Activations:
    • ReLU
    • LeakyReLU (supports custom alphas)
    • Sigmoid
    • Softmax
    • Tanh
    • Linear/None

Roadmap πŸ›£

The project to do list can be found here.

Features πŸ€–

  • Super quick conversion of your models. Takes less than a second. πŸ±β€πŸ‘€
  • Usually reduces the size of Keras models by about 69.37%. πŸ‘Œ
  • In some cases, prediction is quicker than Keras or SNPE (dense models). 🏎
    • RNNs: Since we lose the GPU using NumPy, predictions may be slower
  • Stores the weights and biases of your model in a separate compressed NumPy file. πŸ‘‡

Benchmarks πŸ“ˆ

Benchmarks can be found in BENCHMARKS.md.

Installation & Usage 🌍

Install Konverter using pip:

pip install keras-konverter

Konverting using the CLI: πŸ–₯

konverter examples/test_model.h5 examples/test_model.py (py suffix is optional)

Type konverter to get all possible arguments and flags!

  • Arguments πŸ’’:
    • input_model: Either the the location of your tf.keras .h5 model, or a preloaded Sequential model if using with Python. This is required
    • output_file: Optional file path for your output model, along with the weights file. Default is same name, same directory
  • Flags 🎌:
    • --indent, -i: How many spaces to use for indentation, default is 2
    • --silent, -i: Whether you want Konverter to silently Konvert
    • --no-watermark, -nw: Removes the watermark prepended to the output model file

Konverting programmatically: πŸ€–

All parameters with defaults: konverter.konvert(input_model, output_file=None, indent=2, silent=False, no_watermark=False, tf_verbose=False)

>>> import konverter
>>> konverter.konvert('examples/test_model.h5', output_file='examples/test_model')

Note: The model file will be saved as f'{output_file}.py' and the weights will be saved as f'{output_file}_weights.npz' in the same directory. Make sure to change the path inside the model wrapper if you move the files after Konversion.


That's it! If your model is supported (check Supported Keras Model Attributes), then your newly converted Konverter model should be ready to go.

To predict: Import your model wrapper and run the predict() function. ❗Always double check that the outputs closely match your Keras model's❗ Automatic verification will come soon. For the integrity of the predictions, always make sure your input is a np.float32 array.

import numpy as np
from examples.test_model import predict
predict([np.random.rand(3).astype(np.float32)])

See limitations and issues.

Demo

Dependencies

Thanks to @apiad you can now use Poetry to install all the needed dependencies for this tool! However the requirements are a pretty short list:

  • It seems most versions of TensorFlow that include Keras work perfectly fine. Tested from 1.14 to 2.2 using Actions and no issues have occurred. (Make sure you use implementation 2/v3 with GRU layers if not on TF 2.x)
    • Important: You must create your models with tf.keras currently (not keras)
  • Python >= 3.6 (for the glorious f-strings!)

To install all needed dependencies, simply cd into the base directory of Konverter, and run:

poetry install --no-dev

If you would like to use this version of Konverter (not from pip), then you may need to also run poetry shell after to enter poetry's virtualenv environment. If you go down this path, make sure to remove --no-dev so TensorFlow installs in the venv!

Current Limitations and Issues 😬

  • Dimensionality of input data:

    When working with models using softmax, the dimensionality of the input data matters. For example, predicting on the same data with different input dimensionality sometimes results in different outputs:

    >>> model.predict([[1, 3, 5]])  # keras model, correct output
    array([[14.792273, 15.59787 , 15.543163]])
    >>> predict([[1, 3, 5]])  # Konverted model, wrong output
    array([[11.97839948, 18.09931636, 15.48014805]])
    >>> predict([1, 3, 5])  # And correct output
    array([14.79227209, 15.59786987, 15.54316282])

    If trying a batch prediction with classes and softmax, the model fails completely:

    >>> predict([[0.5], [0.5]])
    array([[0.5, 0.5, 0.5, 0.5], [0.5, 0.5, 0.5, 0.5]])

    Always double check that predictions are working correctly before deploying the model.

  • Batch prediction with SimpleRNN (and possibly all RNN) layers

    Currently, the converted model has no way of determining if you're feeding a single prediction or a batch of predictions, and it will fail to give the correct output in certain cases (more likely with recurrent layers and softmax dense outputs layers). Support will be added soon.

konverter's People

Contributors

apiad avatar sshane avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

konverter's Issues

Add support for LSTM

Will probably not be worked on for a while due to supporting GRU. GRU is also faster since it has one less gate.

Support for More Layers

Firstly, nice work on this project -- this looks really cool!

I'm working on a computer vision project, and would love to use Konverter to convert some pre-trained models. As such, these models include ZeroPadding2D layers. Because this layer type isn't supported, when I run Konverter on the model (yes I tried anyway haha) this is the resulting traceback and error:

Traceback (most recent call last):
File "test.py", line 14, in
konverter.konvert(os.path.join(os.getcwd(), 'models_eynollah', 'model_page_mixed_best.h5'), output_file=os.path.join(os.getcwd(), 'models', 'page_mixed_best.py'))
File "/venv/lib/python3.7/site-packages/konverter/init.py", line 20, in init
no_watermark=no_watermark)
File "/venv/lib/python3.7/site-packages/konverter/init.py", line 41, in _konvert
self.start()
File "/venv/lib/python3.7/site-packages/konverter/init.py", line 45, in start
self.get_layers()
File "/venv/lib/python3.7/site-packages/konverter/init.py", line 214, in get_layers
layer = support.get_layer_info(layer, next_layer)
File "/venv/lib/python3.7/site-packages/konverter/utils/konverter_support.py", line 104, in get_layer_info
layer_class.info.activation = self._get_layer_activation(layer)
File "/venv/lib/python3.7/site-packages/konverter/utils/konverter_support.py", line 80, in _get_layer_activation
if hasattr(layer.activation, '_keras_api_names'):
AttributeError: 'ZeroPadding2D' object has no attribute 'activation'

Do you have any advice for how I could add functionality for more layers and/or would you consider adding support for more layers?

Thanks!

Clean up/refactor

KonverterSupport and the model_attributes.py file should be refactored to more cleanly work together. For example, better class variables in KonverterSupport that are more clearly named and grab their contents from model_attributes so we don't have to define behavior/variables/support in more than one place.

Less restrictive NumPy version?

Installing with pip forces the version of NumPy. This didn't work in my environment, which is still a bit experimental (TensorFlow on Apple Silicon).

Would it be possible to only require a minimum version of NumPy and then react to any issue that may pop up in the future?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.