Quantization not supported for tensorflow.python.keras.layers.wrappers.Bidirectional
Describe the bug When doing quantization of the model in order to run on Edge_TPU an error message is presented.
System information
TensorFlow installed from (source or binary): binary
TensorFlow version: 2.1
TensorFlow Model Optimization version: 0.3.0 (according to pip, I could not run tfmot.__version__)
Python version: 3.7.7
Describe the expected behavior The full quantization should proceed in order to allow executing the model on the edge_tpu.
Describe the current behavior the quantization gives a runtime error (see below).
Code to reproduce the issue Provide a reproducible code that is the bare minimum necessary to generate the problem.
import sys
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras import metrics
from tensorflow.keras.layers import (GRU, LSTM, Activation, Dense, Input,
SimpleRNN)
from tensorflow.keras.models import Model
import tensorflow_model_optimization as tfmot
print(sys.version)
print("Tensor Flow:", tf.__version__)
print("Keras: ", keras.__version__)
print("Numpy: ", np.__version__)
tf.random.set_seed(12345)
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.layers import SimpleRNN
from tensorflow.keras.layers import GRU
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Reshape
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import TimeDistributed
from tensorflow.keras.layers import Bidirectional
from tensorflow.keras.layers import Conv1D
from tensorflow.keras import regularizers
from tensorflow.keras import metrics
def define_model(length_of_sequences, batch_size=None, neurons=5, modelName="nonamegiven"):
inp = Input(batch_shape=(
batch_size, length_of_sequences, 1), name="inputs")
lstmM = Bidirectional(LSTM(50, name="lstm_m", return_sequences=True))(inp)
flat = Flatten()(lstmM)
convM = Conv1D(25, 5, activation="relu") (inp)
flatc = Flatten()(convM)
firstflat = tf.keras.layers.concatenate([flat, flatc])
denseM = Dense(2048, kernel_regularizer=regularizers.l2(0.0001))(firstflat)
denseM = Dense(1024, kernel_regularizer=regularizers.l2(0.0001))(denseM)
denseM = Dense(512, kernel_regularizer=regularizers.l2(0.0001))(denseM)
denseM = Dense(256, kernel_regularizer=regularizers.l2(0.0001))(denseM)
denseM = Dense(128, kernel_regularizer=regularizers.l2(0.0001))(denseM)
denseM = Dense(50, kernel_regularizer=regularizers.l2(0.0001))(denseM)
reshapeM = Reshape((50, 1))(denseM)
denseM = TimeDistributed(
Dense(1, kernel_regularizer=regularizers.l2(
0.0001), bias_initializer='zeros'),
input_shape=(50, 1))(reshapeM)
out_M = Reshape((50, 1), name="om")(denseM)
denseF = Dense(2048, kernel_regularizer=regularizers.l2(0.0001))(firstflat)
denseF = Dense(1024, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Dense(512, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Dense(256, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Dense(128, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Dense(50, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Reshape((50, 1))(denseF)
merger = tf.keras.layers.concatenate([out_M, denseF])
flatfi = Flatten()(merger)
denseF = Dense(100, kernel_regularizer=regularizers.l2(0.0001))(flatfi)
denseF = Dense(100, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Dense(50, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Dense(50, kernel_regularizer=regularizers.l2(
0.0001), bias_initializer='zeros')(denseF)
reshapeF = Reshape((50, 1))(denseF)
denseF = TimeDistributed(
Dense(1, kernel_regularizer=regularizers.l2(
0.0001), bias_initializer='zeros'),
input_shape=(50, 1))(reshapeF)
out_F = Reshape((50, 1), name="of")(denseF)
model = Model(inputs=[inp], outputs=[out_M, out_F], name=modelName)
model.compile(
loss={"om": "mean_squared_error", "of": "mean_squared_error"},
optimizer=keras.optimizers.RMSprop(learning_rate=0.001),
metrics=['mae'])
return model
k_model = define_model(
length_of_sequences=250, neurons=5, modelName="TFSupport02")
k_model.summary()
q_model= tfmot.quantization.keras.quantize_model(k_model)
q_model.summary()
I obtain the following error:
RuntimeError: Layer bidirectional_1:<class 'tensorflow.python.keras.layers.wrappers.Bidirectional'> is not supported. You can quantize this layer by passing a tfmot.quantization.keras.QuantizeConfig instance to the quantize_annotate_layer API.
Additional context please let me know if any further information is needed.
while reading the comprehensive guide it was not clear to me how to proceed to pass an adequate QuantizeConfig for the quantization, if possible please give some more indication.
It seems similar to issue #372 .
I wanted to check if Bidirectional is the only piece missing, and removed it from the model, and I obtained the following error:
RuntimeError: Layer lstm_m:<class 'tensorflow.python.keras.layers.recurrent.LSTM'> is not supported. You can quantize this layer by passing a tfmot.quantization.keras.QuantizeConfig instance to the quantize_annotate_layer API.
using the below code:
import sys
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras import metrics
from tensorflow.keras.layers import (GRU, LSTM, Activation, Dense, Input,
SimpleRNN)
from tensorflow.keras.models import Model
import tensorflow_model_optimization as tfmot
print(sys.version)
print("Tensor Flow:", tf.__version__)
print("Keras: ", keras.__version__)
print("Numpy: ", np.__version__)
tf.random.set_seed(12345)
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.layers import SimpleRNN
from tensorflow.keras.layers import GRU
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Reshape
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import TimeDistributed
from tensorflow.keras.layers import Bidirectional
from tensorflow.keras.layers import Conv1D
from tensorflow.keras import regularizers
from tensorflow.keras import metrics
def define_model(length_of_sequences, batch_size=None, neurons=5, modelName="nonamegiven"):
inp = Input(batch_shape=(
batch_size, length_of_sequences, 1), name="inputs")
lstmM = LSTM(50, name="lstm_m", return_sequences=True)(inp)
flat = Flatten()(lstmM)
convM = Conv1D(25, 5, activation="relu") (inp)
flatc = Flatten()(convM)
firstflat = tf.keras.layers.concatenate([flat, flatc])
denseM = Dense(2048, kernel_regularizer=regularizers.l2(0.0001))(firstflat)
denseM = Dense(1024, kernel_regularizer=regularizers.l2(0.0001))(denseM)
denseM = Dense(512, kernel_regularizer=regularizers.l2(0.0001))(denseM)
denseM = Dense(256, kernel_regularizer=regularizers.l2(0.0001))(denseM)
denseM = Dense(128, kernel_regularizer=regularizers.l2(0.0001))(denseM)
denseM = Dense(50, kernel_regularizer=regularizers.l2(0.0001))(denseM)
reshapeM = Reshape((50, 1))(denseM)
denseM = TimeDistributed(
Dense(1, kernel_regularizer=regularizers.l2(
0.0001), bias_initializer='zeros'),
input_shape=(50, 1))(reshapeM)
out_M = Reshape((50, 1), name="om")(denseM)
denseF = Dense(2048, kernel_regularizer=regularizers.l2(0.0001))(firstflat)
denseF = Dense(1024, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Dense(512, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Dense(256, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Dense(128, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Dense(50, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Reshape((50, 1))(denseF)
merger = tf.keras.layers.concatenate([out_M, denseF])
flatfi = Flatten()(merger)
denseF = Dense(100, kernel_regularizer=regularizers.l2(0.0001))(flatfi)
denseF = Dense(100, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Dense(50, kernel_regularizer=regularizers.l2(0.0001))(denseF)
denseF = Dense(50, kernel_regularizer=regularizers.l2(
0.0001), bias_initializer='zeros')(denseF)
reshapeF = Reshape((50, 1))(denseF)
denseF = TimeDistributed(
Dense(1, kernel_regularizer=regularizers.l2(
0.0001), bias_initializer='zeros'),
input_shape=(50, 1))(reshapeF)
out_F = Reshape((50, 1), name="of")(denseF)
model = Model(inputs=[inp], outputs=[out_M, out_F], name=modelName)
model.compile(
loss={"om": "mean_squared_error", "of": "mean_squared_error"},
optimizer=keras.optimizers.RMSprop(learning_rate=0.001),
metrics=['mae'])
return model
k_model = define_model(
length_of_sequences=250, neurons=5, modelName="TFSupport02")
k_model.summary()
keras.utils.plot_model(k_model, "TFSupport02_overview.png", show_shapes=True)
q_model= tfmot.quantization.keras.quantize_model(k_model)
q_model.summary()
@alanchiao Can you investigate this issue?
even I have the same issue with time disturbed
RuntimeError: Layer time_distributed:<class 'tensorflow.python.keras.layers.wrappers.TimeDistributed'> is not supported. You can quantize this layer by passing a tfmot.quantization.keras.QuantizeConfig instance to the quantize_annotate_layer API.
Dear @gargn and @alanchiao ,
I assume that it is not a high priority to have the quantization for these layer working. I am wondering if as an alternative I could do the network and specifying the dtypes as uint8, would that be equivalent as the quantization (or for instance are there some extra flags to indicate that the quantization was executed that need to be set) ?
@ericqu: as you say, there are a lot of other issues we have to address first.
If your goal is to deploy this model in TFLite, there are special considerations for LSTM (it may or may not require a clipping schedule, which some people have used in the past) as well as potential work to integrate with https://www.tensorflow.org/lite/convert/rnn. Everything other layer should be doable (though some of the layers in your model need work to add also (e.g. Conv1D).
If your goal is to just run experiments and not deploy, your best bet is to try use the recommended QuantizeConfig with examples at https://www.tensorflow.org/model_optimization/guide/quantization/training_comprehensive_guide. Bidirectional and TimeDistributed are a bit unique in that they are wrappers and I haven't considered all the implications of what it'd take to get that working. For your case, you may be able to set get_weights_and_quantizers from QuantizeConfig with 'layer.layer.kernel' and 'layer.layer.recurrent_kernel', but I haven't thought that through.
Specifying the dtypes as uint8 is not sufficient - otherwise the tooling would be much simpler. In the current form of quantization aware training, there is the usage of a FakeQuant operator that we place for you in the correct areas. QuantizeConfig is a way to configure that.
If you're interested in diving into the code a bit, extending testQuantizeSingleLayer_ProducesFullIntegerModel_TF2 unit test in this file is a good way to check if what you're doing is correct at the most basic level.
@alanchiao: Thank you for the information much appreciated.
My objective is to deploy on the EdgeTPU hence I understand that I need a TFLite model with full quantization to pass the compiler. If there is another way, let me know I would go for it if possible.
Is there an high level guide of what there is a to implement in order to achieve the quantization. I look for papers on the topic but it feels there are hundreds of them and ideally I would like to use the same idea that is currently used in the framework, if you could point me to the rights one(s) it would be great. I still have to read in more depth the test file you pointed out; but it seem that the test file will most useful to check if the quantization worked)?
As it feels that this is a substantial amount of work, I am considering taking a different approach an develop one or two custom layers to replace most of the layers except the Dense/Reshape/Input layer. Would you think this is a reasonable approach?
@alanchiao thanks for the clarification, but I cannot find a usage of Quantize Config which allows an LSTM layer to be used in a keras model. Could you confirm or deny if this is even possible (ie use an LSTM layer given a certain Quantize Config)?
Here is my Quantize Config
`LastValueQuantizer = tfmot.quantization.keras.quantizers.LastValueQuantizer MovingAverageQuantizer = tfmot.quantization.keras.quantizers.MovingAverageQuantizer
class DefaultLSTMQuantizeConfig(tfmot.quantization.keras.QuantizeConfig): # Configure how to quantize weights. def get_weights_and_quantizers(self, layer): return [(layer.layer.recurrent_kernel, LastValueQuantizer(num_bits=8, symmetric=True, narrow_range=False, per_axis=False))]
# Configure how to quantize activations.
def get_activations_and_quantizers(self, layer):
return [(layer.activation, MovingAverageQuantizer(num_bits=8, symmetric=False, narrow_range=False, per_axis=False))]
def set_quantize_weights(self, layer, quantize_weights):
# Add this line for each item returned in `get_weights_and_quantizers`
# , in the same order
layer.kernel = quantize_weights[0]
def set_quantize_activations(self, layer, quantize_activations):
# Add this line for each item returned in `get_activations_and_quantizers`
# , in the same order.
layer.activation = quantize_activations[0]
# Configure how to quantize outputs (may be equivalent to activations).
def get_output_quantizers(self, layer):
return []
def get_config(self):
return {}`
And here is how it is being used in the keras model
quant_layer = tfmot.quantization.keras.quantize_annotate_layer
quant_apply = tfmot.quantization.keras.quantize_apply
quantize_scope = tfmot.quantization.keras.quantize_scope`
i = tf.keras.Input(shape=(32,32,1))
x = (L.Conv2D(1, (5, 1), activation='relu', padding='same'))(i)
x = L.BatchNormalization()(x)
x = L.Lambda(lambda q: K.squeeze(q, -1), name='squeeze_last_dim')(x)
x = quant_layer(L.LSTM(64, return_sequences=True),DefaultLSTMQuantizeConfig())(x)
x = tf.keras.layers.Flatten()(x)
x = L.Dense(64, activation='relu')(x)
o = L.Dense(12, activation='softmax')(x)
simple_model = Model(inputs=[i], outputs=[o])
simple_model.compile(optimizer='adam', loss=['sparse_categorical_crossentropy'], metrics=['sparse_categorical_accuracy'])
with quantize_scope(
{'DefaultLSTMQuantizeConfig': DefaultLSTMQuantizeConfig}):
simple_model_quant = quant_apply(simple_model)
simple_model_quant.summary()
But this returns the error
AttributeError: 'LSTM' object has no attribute 'layer'
Any feedback about how to properly use the Quantize Config is greatly appreciated.
Try layer.cell.recurrent_kernel?
Hi @Xhark, can you take a look?
Is the issue solved ?
it's not solved, no. I am no longer working on this project though! Thanks.
Why/how the initial bug would be solved?
hey @ericqu, did you get any further with your issue?
@marbortoli, no, I did not get any further with the issue. The last relevant message is the one from @alanchiao in June 2020, indicating that this is a feature request and not a bug. Hence I am only going to work on this once the feature is there. Unless you have information indicating that the feature has been developed.
@ericqu no. I am having the same issue.