Guide on Quantizing and Converting Model to Tensorflow Lite
In recent years, in deep learning, with the increase of the performance of the models, there is also a huge increase in the amount of the parameters in the model. For example — Inceptionv3 contains about 23M parameters. All this is making impossible to run them on mobile devices.
Fortunately, for doing so, there are several options — design lightweight architecture, or save the weights of the trained model in the low precision types like float16, uint8…
Further, we will concentrate on the second option of quantizing and converting models with the help of Tensorflow.
Overview
Within the Tensorflow Lite¹, there are several options for obtaining a mobile-optimized model
- Convert from Tensorflow to Tensorflow Lite without any modifications in the weights and activation types.
- Convert model and simultaneously quantize the weights(with default ranges in quantization algorithm)
- Do quantization aware training, which will learn min and max ranges of the weights per layer, and only after converting it to tflite.
Simple Convert
In this case, your model will be just converted to tflite without any optimization, and you will be able to use it on mobile, to do inference within the Tensorflow Lite framework.
Here is an example of converting from the Keras model.
converter = tf.lite.TFLiteConverter.from_keras_model_file('model_keras.h5')
tflite_model = converter.convert()
tflite_model_quant_file = "./test.tflite"
tflite_model_quant_file.write_bytes(tflite_model)Convert + Post Training Quantization
In this case, you have an option to convert weights to uint8, which will reduce size of the model, but be aware, that it can increase latency of the model, because in the inference time, before executing operation on the input, weights of the layer will be converted back to float32, and in summation, this operations can take significant amount of time — depend on your architecture. From the official documentation of the Tensorflow², formula of quantization is
out[i] = (in[i] - min_range) * range(T) / (max_range - min_range)
if T == qint8: out[i] -= (range(T) + 1) / 2.0
where
range(T) = numeric_limits<T>::max() - numeric_limits<T>::min()Also, there could be performance degradation, because max_range and min_range have default values for all the layers.
Here is a example of converting the model, with post-train-quantization.
converter = tf.lite.TFLiteConverter.from_keras_model_file('model_keras.h5')
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()
tflite_model_quant_file = "./test.tflite"
tflite_model_quant_file.write_bytes(tflite_model)Quantization Aware Training
To address problem raised bellow, about default ranges of min/max values, Teansorflow has created the flow where, in the process of constructing the graph you can insert fake nodes in each layer, to simulate the effect of quantization in the forward and backward passes and to learn ranges in the training process, for each layer separately.
Get Lusine Abrahamyan’s stories in your inbox
Join Medium for free to get updates from this writer.
All is needed for enabling this option in training, is add build-in method, of converting graph, to include fake nodes, after constructing the main model
with tf.variable_scope('quantize'):
output= model(x=image_tf, is_training=True, keep_prob=keep_prob_tf)
tf.contrib.quantize.create_training_graph(quant_delay=0)After the training, in the stage of exporting the graph, you will need to call a method to convert the graph to the corresponding inference only version, where already trained fake nodes will be treated as min/max ranges for each layer.
with tf.variable_scope('quantize'):
output = model(x=input, is_training=False, keep_prob=1.)g = tf.get_default_graph()
tf.contrib.quantize.create_eval_graph(input_graph=g)
And after, you can convert the model, with the help of the TensorflowLite converter, specifying options of inference and inference input types as uint8.
converter = lite.TFLiteConverter.from_session(session, [input], [output])
converter.inference_type = tf.uint8
converter.inference_input_type = tf.uint8
input_arrays = converter.get_input_arrays()
converter.quantized_input_stats = {input_arrays[0] : (0., 1.)}flatbuffer = converter.convert()with open('test.tflite', 'wb') as outfile:
outfile.write(flatbuffer)
Pitfalls in the Quantization Aware Training (for Tensorflow 1.14)
- There is no support for fused batch norm, which is a default option for tf.layers.batch_normalization.
- Currently, there is a discrepancy in the variable scopes in the train and eval graph, so there is a need to manually add variable scope to the graph.
# the training stage
with tf.variable_scope('quantize'):
output= model(x=image_tf, is_training=True, keep_prob=keep_prob_tf)
tf.contrib.quantize.create_training_graph(quant_delay=0)# exporting stage
with tf.variable_scope('quantize'):
output = model(x=input, is_training=False, keep_prob=1.)
g = tf.get_default_graph()
tf.contrib.quantize.create_eval_graph(input_graph=g)
3. Because the TensorflowLite converter is only taking into account nodes between input and output nodes strictly, the fake nodes of the last layer, which in the graph are coming only after actual node, are being ignored, and it’s causing tflite converter error. There can be a workaround in the form of adding some useless op, which will not harm the result of the graph, e.g.
with tf.variable_scope('quantize'):
output = model(x=input, is_training=False, keep_prob=1.)
output = tf.maximum(output, -1e27)References
[1] Official documentation of Tensorflow Lite, https://www.tensorflow.org/lite
[2] Implementation of the Tensorflow quantization, https://www.tensorflow.org/api_docs/python/tf/quantization/quantize










