alexander | 3c79893 | 2021-03-26 21:42:19 +0000 | [diff] [blame] | 1 | # Copyright (c) 2021 Arm Limited. All rights reserved. |
| 2 | # SPDX-License-Identifier: Apache-2.0 |
| 3 | # |
| 4 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | # you may not use this file except in compliance with the License. |
| 6 | # You may obtain a copy of the License at |
| 7 | # |
| 8 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | # |
| 10 | # Unless required by applicable law or agreed to in writing, software |
| 11 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | # See the License for the specific language governing permissions and |
| 14 | # limitations under the License. |
| 15 | """ |
| 16 | This script will provide you with a short example of how to perform magnitude-based weight pruning in TensorFlow |
| 17 | using the TensorFlow Model Optimization Toolkit. |
| 18 | |
| 19 | The output from this example will be a TensorFlow Lite model file where ~75% percent of the weights have been 'pruned' to the |
| 20 | value 0 during training - quantization has then been applied on top of this. |
| 21 | |
| 22 | By pruning the model we can improve compression of the model file. This can be essential for deploying certain models |
| 23 | on systems with limited resources - such as embedded systems using Arm Ethos NPU. Also, if the pruned model is run |
| 24 | on an Arm Ethos NPU then this pruning can improve the execution time of the model. |
| 25 | |
| 26 | After pruning is complete we do post-training quantization to quantize the model and then generate a TensorFlow Lite file. |
| 27 | |
| 28 | If you are targetting an Arm Ethos-U55 NPU then the output TensorFlow Lite file will also need to be passed through the Vela |
| 29 | compiler for further optimizations before it can be used. |
| 30 | |
| 31 | For more information on using Vela see: https://git.mlplatform.org/ml/ethos-u/ethos-u-vela.git/about/ |
| 32 | For more information on weight pruning see: https://www.tensorflow.org/model_optimization/guide/pruning |
| 33 | """ |
| 34 | import pathlib |
| 35 | |
| 36 | import tensorflow as tf |
| 37 | import tensorflow_model_optimization as tfmot |
| 38 | |
| 39 | from training_utils import get_data, create_model |
| 40 | from post_training_quantization import post_training_quantize, evaluate_tflite_model |
| 41 | |
| 42 | |
| 43 | def prepare_for_pruning(keras_model): |
| 44 | """Prepares a Keras model for pruning.""" |
| 45 | |
| 46 | # We use a constant sparsity schedule so the amount of sparsity in the model is kept at the same percent throughout |
| 47 | # training. An alternative is PolynomialDecay where sparsity can be gradually increased during training. |
| 48 | pruning_schedule = tfmot.sparsity.keras.ConstantSparsity(target_sparsity=0.75, begin_step=0) |
| 49 | |
| 50 | # Apply the pruning wrapper to the whole model so weights in every layer will get pruned. You may find that to avoid |
| 51 | # too much accuracy loss only certain non-critical layers in your model should be pruned. |
| 52 | pruning_ready_model = tfmot.sparsity.keras.prune_low_magnitude(keras_model, pruning_schedule=pruning_schedule) |
| 53 | |
| 54 | # We must recompile the model after making it ready for pruning. |
| 55 | pruning_ready_model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), |
| 56 | loss=tf.keras.losses.sparse_categorical_crossentropy, |
| 57 | metrics=['accuracy']) |
| 58 | |
| 59 | return pruning_ready_model |
| 60 | |
| 61 | |
| 62 | def main(): |
| 63 | x_train, y_train, x_test, y_test = get_data() |
| 64 | model = create_model() |
| 65 | |
| 66 | # Compile and train the model first. |
| 67 | # In general it is easier to do pruning as a fine-tuning step after the model is fully trained. |
| 68 | model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), |
| 69 | loss=tf.keras.losses.sparse_categorical_crossentropy, |
| 70 | metrics=['accuracy']) |
| 71 | |
| 72 | model.fit(x=x_train, y=y_train, batch_size=128, epochs=5, verbose=1, shuffle=True) |
| 73 | |
| 74 | # Test the trained model accuracy. |
| 75 | test_loss, test_acc = model.evaluate(x_test, y_test) |
| 76 | print(f"Test accuracy before pruning: {test_acc:.3f}") |
| 77 | |
| 78 | # Prepare the model for pruning and add the pruning update callback needed in training. |
| 79 | pruned_model = prepare_for_pruning(model) |
| 80 | callbacks = [tfmot.sparsity.keras.UpdatePruningStep()] |
| 81 | |
| 82 | # Continue training the model but now with pruning applied - remember to pass in the callbacks! |
| 83 | pruned_model.fit(x=x_train, y=y_train, batch_size=128, epochs=1, verbose=1, shuffle=True, callbacks=callbacks) |
| 84 | test_loss, test_acc = pruned_model.evaluate(x_test, y_test) |
| 85 | print(f"Test accuracy after pruning: {test_acc:.3f}") |
| 86 | |
| 87 | # Remove all variables that pruning only needed in the training phase. |
| 88 | model_for_export = tfmot.sparsity.keras.strip_pruning(pruned_model) |
| 89 | |
| 90 | # Apply post-training quantization on top of the pruning and save the resulting TensorFlow Lite model to file. |
| 91 | tflite_model = post_training_quantize(model_for_export, x_train) |
| 92 | |
| 93 | tflite_models_dir = pathlib.Path('./conditioned_models/') |
| 94 | tflite_models_dir.mkdir(exist_ok=True, parents=True) |
| 95 | |
| 96 | pruned_quant_model_save_path = tflite_models_dir / 'pruned_post_training_quant_model.tflite' |
| 97 | with open(pruned_quant_model_save_path, 'wb') as f: |
| 98 | f.write(tflite_model) |
| 99 | |
| 100 | # Test the pruned quantized model accuracy. Save time by only testing a subset of the whole data. |
| 101 | num_test_samples = 1000 |
| 102 | evaluate_tflite_model(pruned_quant_model_save_path, x_test[0:num_test_samples], y_test[0:num_test_samples]) |
| 103 | |
| 104 | |
| 105 | if __name__ == "__main__": |
| 106 | main() |