Repository navigation
Description
System information
- OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Both Linux 20.04 and Windows 10
- TensorFlow installed from (source or binary): Binary (pip install tf-nightly)
- TensorFlow version (or github SHA if from source): 2.5.0-dev20201111
Command used to run the converter or code if you’re using the Python API
If possible, please share a link to Colab/Jupyter/any notebook.
Command
(tf25) ubuntu@ubuntu-TFG257XS:~/yolo_tf/tensorflow-yolov4-tflite$ python convert_tflite.py --weights ./checkpoints/yolov4-416-tflite --output ./checkpoints/yolov4-416.tflite
Code
import tensorflow as tf
from absl import app, flags, logging
from absl.flags import FLAGS
import numpy as np
import cv2
from core.yolov4 import YOLOv4, YOLOv3, YOLOv3_tiny, decode
import core.utils as utils
import os
from core.config import cfg
flags.DEFINE_string('weights', './checkpoints/yolov4-416', 'path to weights file')
flags.DEFINE_string('output', './checkpoints/yolov4-416-fp32.tflite', 'path to output')
flags.DEFINE_integer('input_size', 416, 'path to output')
flags.DEFINE_string('quantize_mode', 'float32', 'quantize mode (int8, float16, float32)')
flags.DEFINE_string('dataset', "/Volumes/Elements/data/coco_dataset/coco/5k.txt", 'path to dataset')
def representative_data_gen():
fimage = open(FLAGS.dataset).read().split()
for input_value in range(10):
if os.path.exists(fimage[input_value]):
original_image=cv2.imread(fimage[input_value])
original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
image_data = utils.image_preprocess(np.copy(original_image), [FLAGS.input_size, FLAGS.input_size])
img_in = image_data[np.newaxis, ...].astype(np.float32)
print("calibration image {}".format(fimage[input_value]))
yield [img_in]
else:
continue
def save_tflite():
converter = tf.lite.TFLiteConverter.from_saved_model(FLAGS.weights)
if FLAGS.quantize_mode == 'float16':
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_types = [tf.compat.v1.lite.constants.FLOAT16]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
converter.allow_custom_ops = True
elif FLAGS.quantize_mode == 'int8':
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
converter.allow_custom_ops = True
converter.representative_dataset = representative_data_gen
tflite_model = converter.convert()
open(FLAGS.output, 'wb').write(tflite_model)
logging.info("model saved to: {}".format(FLAGS.output))
def demo():
interpreter = tf.lite.Interpreter(model_path=FLAGS.output)
interpreter.allocate_tensors()
logging.info('tflite model loaded')
input_details = interpreter.get_input_details()
print(input_details)
output_details = interpreter.get_output_details()
print(output_details)
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = [interpreter.get_tensor(output_details[i]['index']) for i in range(len(output_details))]
print(output_data)
def main(_argv):
save_tflite()
demo()
if __name__ == '__main__':
try:
app.run(main)
except SystemExit:
pass
The output from the converter invocation
(tf25) ubuntu@ubuntu-TFG257XS:~/yolo_tf/tensorflow-yolov4-tflite$ python convert_tflite.py --weights ./checkpoints/yolov4-416-tflite --output ./checkpoints/yolov4-416.tflite
2020-11-12 10:51:14.591438: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set
2020-11-12 10:51:14.591714: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2020-11-12 10:51:21.071335: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:319] Ignored output_format.
2020-11-12 10:51:21.071397: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:322] Ignored drop_control_dependency.
2020-11-12 10:51:21.071417: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:328] Ignored change_concat_input_ranges.
2020-11-12 10:51:21.072230: I tensorflow/cc/saved_model/reader.cc:32] Reading SavedModel from: ./checkpoints/yolov4-416-tflite
2020-11-12 10:51:21.126090: I tensorflow/cc/saved_model/reader.cc:55] Reading meta graph with tags { serve }
2020-11-12 10:51:21.126129: I tensorflow/cc/saved_model/reader.cc:93] Reading SavedModel debug info (if present) from: ./checkpoints/yolov4-416-tflite
2020-11-12 10:51:21.270211: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:251] None of the MLIR optimization passes are enabled (registered 0 passes)
2020-11-12 10:51:21.307128: I tensorflow/cc/saved_model/loader.cc:206] Restoring SavedModel bundle.
2020-11-12 10:51:21.354451: I tensorflow/core/platform/profile_utils/cpu_utils.cc:112] CPU Frequency: 2299965000 Hz
2020-11-12 10:51:21.867525: I tensorflow/cc/saved_model/loader.cc:190] Running initialization op on SavedModel bundle at path: ./checkpoints/yolov4-416-tflite
2020-11-12 10:51:22.030647: I tensorflow/cc/saved_model/loader.cc:277] SavedModel load for tags { serve }; Status: success: OK. Took 958418 microseconds.
2020-11-12 10:51:22.617404: I tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.cc:194] disabling MLIR crash reproducer, set env var `MLIR_CRASH_REPRODUCER_DIRECTORY` to enable.
loc("batch_normalization/moving_mean"): error: is not immutable, try running tf-saved-model-optimize-global-tensors to prove tensors are immutable
Traceback (most recent call last):
File "/home/ubuntu/anaconda3/envs/tf25/lib/python3.7/site-packages/tensorflow/lite/python/convert.py", line 213, in toco_convert_protos
enable_mlir_converter)
File "/home/ubuntu/anaconda3/envs/tf25/lib/python3.7/site-packages/tensorflow/lite/python/wrap_toco.py", line 38, in wrapped_toco_convert
enable_mlir_converter)
Exception: <unknown>:0: error: loc("batch_normalization/moving_mean"): is not immutable, try running tf-saved-model-optimize-global-tensors to prove tensors are immutable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "convert_tflite.py", line 76, in <module>
app.run(main)
File "/home/ubuntu/anaconda3/envs/tf25/lib/python3.7/site-packages/absl/app.py", line 303, in run
_run_main(main, args)
File "/home/ubuntu/anaconda3/envs/tf25/lib/python3.7/site-packages/absl/app.py", line 251, in _run_main
sys.exit(main(argv))
File "convert_tflite.py", line 71, in main
save_tflite()
File "convert_tflite.py", line 45, in save_tflite
tflite_model = converter.convert()
File "/home/ubuntu/anaconda3/envs/tf25/lib/python3.7/site-packages/tensorflow/lite/python/lite.py", line 745, in convert
result = _convert_saved_model(**converter_kwargs)
File "/home/ubuntu/anaconda3/envs/tf25/lib/python3.7/site-packages/tensorflow/lite/python/convert.py", line 637, in convert_saved_model
enable_mlir_converter=True)
File "/home/ubuntu/anaconda3/envs/tf25/lib/python3.7/site-packages/tensorflow/lite/python/convert.py", line 216, in toco_convert_protos
raise ConverterError(str(e))
tensorflow.lite.python.convert.ConverterError: <unknown>:0: error: loc("batch_normalization/moving_mean"): is not immutable, try running tf-saved-model-optimize-global-tensors to prove tensors are immutable
Also, please include a link to the saved model or GraphDef
Saved Model : yolov4-416-tflite.zip
https://drive.google.com/file/d/1JXAUuRRfkpp5h-6NA7SXduKMAeMQBssG/view?usp=sharing
Failure details
When I tried to get .tflite file from saved model(tflite), failed to generate .tflite file with Error message
This problem happens regardless of quantization (FP32, FP16, INT8)
Any other info / logs
When I tried to get .tflite with Tensorflow 2.3.0rc0, it worked well (could generate .tflite file and execute it with tflite interpreter)
But I failed to generate .tflite file with tf-nightly 2.5.0-dev2020111
How can I solve this problem?
Activity
Saduf2019 commentedon Nov 12, 2020
@kukbyung
I ran the code shared and face this error, could you please share complete code such that we could replicate the issue faced or if possible share a colab gist with the error reported.
kukbyung commentedon Nov 12, 2020
@Saduf2019
I uploaded the complete code including saved model for tflite and .weight files on Google Drive (File name : YOLO_tf2.5.zip)
[https://drive.google.com/file/d/1u7SqINdHkgThkd4xySTbjFToCqV9Z6OT/view?usp=sharing]
this whole code also can be obtained from [https://github.com/theAIGuysCode/tensorflow-yolov4-tflite]
But it needs to generate saved Model for tflite from .weight file
(yolov4.weight file need to be downloaded from https://drive.google.com/open?id=1cewMfusmPjYWbrnuJRuKhPMwRe_b9PaT)
python save_model.py --weights ./data/yolov4.weights --output ./checkpoints/yolov4-416-tflite --input_size 416 --model yolov4 --framework tfliteAnd then convert it to .tflite file (<- Problem)
python convert_tflite.py --weights ./checkpoints/yolov4-416 --output ./checkpoints/yolov4-416.tfliteThanks.
Adithia99 commentedon Dec 22, 2020
yeah im facing same error
loc("batch_normalization/moving_mean"): is not immutable, try running tf-saved-model-optimize-global-tensors to prove tensors are immutable
AlxndrMlk commentedon Jan 18, 2021
Experiencing the same issue, while trying to convert
SavedModelintotf.litemodel.The original model was trained with
tensorflow 2.0.0on Windows.I am trying to convert with
tensorflow 2.4.0@ Colab.ConverterError: <unknown>:0: error: loc("lstm_36/bias"): is not immutable, try running tf-saved-model-optimize-global-tensors to prove tensors are immutableaparico commentedon Jan 29, 2021
Possible solution is here:
hunglc007/tensorflow-yolov4-tflite#285 (comment)
snehitvaddi commentedon Mar 5, 2021
I resolved the problem by following the above mentioned thread.
Solution: In google colab I had this issue if I used the default TF version, which was 2.4.0.
Running
!pip install tensorflow==2.3.0and restarting the runtime, then converting corrected the issue.AlxndrMlk commentedon Mar 5, 2021
@snehitvaddi
I did the same and it also worked for me. The current version of TF on Colab also worked correctly (2.4.1 if I remeber correctly)
karimnosseir commentedon Mar 5, 2021
Thanks for the report everyone.
Working on a fix.
Thanks
dizcza commentedon Mar 25, 2021
I got the same issue with a similar model with the latest TF 2.4.1
Then I followed the official guideline on how to convert a SavedModel.
sandeep22-v commentedon Mar 31, 2021
Got the error :
tensorflow.lite.python.convert.ConverterError: :0: error: loc("batch_normalization/moving_mean"): is not immutable, try running tf-saved-model-optimize-global-tensors to prove tensors are immutable
SunAriesCN commentedon May 21, 2021
Hi, @karimnosseir
Just test the new tensorflow version, 2.5, also got that error.
karimnosseir commentedon May 21, 2021
Sorry for the delay everyone. The fix is not ready yet - was working on other feature and out of office for some time.
I am expecting to look in this in few weeks.
Thanks and apologies for the delay.
karimnosseir commentedon Jun 25, 2021
Hi Everyone,
Mutable variable support is now available in the nightly when converting using from_saved_model.
You need to set this flag to True for now.
Setting this should resolve the issue. Please give it a try and let us know if you're having any issues.
Thanks
google-ml-butler commentedon Jun 25, 2021
Are you satisfied with the resolution of your issue?
Yes
No