Source: Deep Learning on Medium
This tutorial will demonstrate how you can reduce the size of your Keras model by 5 times with TensorFlow model optimization, which can be particularly important for deployment in resource-constraint environments.
From the official TensorFlow model optimization documentation. Weight pruning means eliminating unnecessary values in weight tensors. We set the neural network parameters’ values to zero to remove what we estimate are unnecessary connections between the layers of a neural network. This is done during the training process to allow the neural network to adapt to the changes.
Here is a breakdown of how you can adopt this technique.
- Train Keras model to reach an acceptable accuracy as always.
- Make Keras layers or model ready to be pruned.
- Create a pruning schedule and train the model for more epochs.
- Export the pruned model by striping pruning wrappers from the model.
- Convert Keras model to TensorFlow Lite with optional quantization.
Prune your pre-trained Keras model
Your pre-trained model has already achieved desirable accuracy, you want to cut down its size while maintaining the performance. The pruning API can help you make it happen.
To use the pruning API, install the
pip uninstall -yq tensorflow
pip uninstall -yq tf-nightly
pip install -Uq tf-nightly-gpu
pip install -q tensorflow-model-optimization
Then you can load your previous trained model and make it “prunable”. The Keras-based API can be applied at the level of individual layers, or the entire model. Since you have the entire model pre-trained, it is easier to apply the pruning to the entire model. The algorithm will be applied to all layers capable of weight pruning.
For the pruning schedule, we start at the sparsity level 50% and gradually train the model to reach 90% sparsity. X% sparsity means that X% of the weight tensor is going to be pruned away.
Furthermore, we give the model some time to recover after each pruning step, so pruning does not happen on every step. We set the pruning
frequency to 100. Similar to pruning a bonsai, we are trimming it gradually so that the tree can adequately heal the wound created during pruning instead of cutting 90% of its branches in one day.
Given the model already reached a satisfactory accuracy, we can start pruning immediately. As a result, we set the
begin_step to 0 here, and only train for another four epochs.
The end step is calculated given the number of train example, batch size, and the total epochs to train.
Don’t panic if you find more trainable parameters in the
new_pruned_model summary, those came from the pruning wrappers which we will remove later.
Now let’s start the training and pruning model.
The test loss and accuracy of the pruned model should look similar to your original Keras model.
Export the pruned model
Those pruning wrappers can be removed easily like this, after which the total number of parameters should be the same as your original model.
final_model = sparsity.strip_pruning(pruned_model)
Now you can check the percentage of weights were pruned by comparing them to zero.
Here is the results, as you can see, 90% of convolution, dense and batch norm layers’ weights are pruned.
Now, simply using a generic file compression algorithm (e.g. zip), the Keras model will be reduced by x5 times.
Here is what you get, x5 times smaller model.
Size of the pruned model before compression: 12.52 Mb
Size of the pruned model after compression: 2.51 Mb
Convert Keras model to TensorFlow Lite
Tensorflow Lite is an example format you can use to deploy to mobile devices. To convert to a Tensorflow Lite graph, it is necessary to use the
TFLiteConverter as below:
Then you can use a similar technique to zip the
tflite file and reduce size x5 times smaller.
Post-training quantization converts weights to 8-bit precision as part of the model conversion from keras model to TFLite’s flat buffer, resulting in another 4x reduction in the model size. Just add the following line to the previous snippet before calling the
converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
The compressed 8-bit tensorflow lite model only takes 0.60 Mb compared to the original Keras model’s 12.52 Mb while maintaining comparable test accuracy. That’s totally x16 times size reduction.
You can evaluate the accuracy of the converted TensorFlow Lite model like this where you feed the
eval_model with the test dataset.
Conclusion and Further reading
In this tutorial, we showed you how to create sparse models with the TensorFlow model optimization toolkit weight pruning API. Right now, this allows you to create models that take significantly less space on the disk. The resulting model can also be more efficiently implemented to avoid computation; in the future, TensorFlow Lite will provide such capabilities.
The source code for this post is available on my Github and runnable on Google Colab Notebook.
Originally published at https://www.dlology.com.