Repository navigation
Description
System information
- OS Platform and Distribution (e.g., Linux Ubuntu 16.04):Windows 10 pro
- TensorFlow installed from (source or binary):binary
- TensorFlow version (or github SHA if from source):2.4.0
Command used to run the converter or code if you’re using the Python API
python convert_tflite.py --weights ./checkpoints/yolov4-416 --output ./checkpoints/yolov4-416.tflite
convert_tflite.py is as below
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 cfgflags.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:
continuedef 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_gentflite_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
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 "C:\Users\theum\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\lite\python\convert.py", line 213, in toco_convert_protos
enable_mlir_converter)
File "C:\Users\theum\AppData\Local\Programs\Python\Python37\lib\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 "C:\Users\theum\AppData\Local\Programs\Python\Python37\lib\site-packages\absl\app.py", line 300, in run
> _run_main(main, args)
> File "C:\Users\theum\AppData\Local\Programs\Python\Python37\lib\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 "C:\Users\theum\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\lite\python\lite.py", line 739, in convert
> result = _convert_saved_model(**converter_kwargs)
> File "C:\Users\theum\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\lite\python\convert.py", line 637, in convert_saved_model
> enable_mlir_converter=True)
> File "C:\Users\theum\AppData\Local\Programs\Python\Python37\lib\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
Activity
abattery commentedon Jan 11, 2021
Sorry for encountering this issue. The mutable variable cases are currently not supported by TFLite. We are working on this. I will update this thread once it is ready to use.
SunnyGrocery commentedon Jan 23, 2021
I attempt to use tf-nighty(
2.5.0.dev2021012301) to convert model to TFLite ,but it still throw this error:tensorflow.lite.python.convert.ConverterError: <unknown>:0: error: loc("batch_normalization/moving_mean")Could you provide some alternative ways or suggestions for convert Saved Model (converted from YOLOv4) to TFLite ?
terryheo commentedon Mar 17, 2021
According to #44790, you might need to use TF 2.3.0.
5 remaining items
abattery commentedon May 13, 2021
@karimnosseir could you take a look?
BazanRodrigo commentedon Jun 24, 2021
Hi, I resolved this problem in this form:
pip install tensorflow===2.3.0 python save_model.py --weights yolov4_best.weights --output ./checkpoints/yolov4_v1_darknet-416 --input_size 416 --model yolov4 --framework tflite python convert_tflite.py --weights ./checkpoints/yolov4_v1_darknet-416 --quantize_mode fp16 --output ./checkpoints/yolov4_v1_darknet-416_fp16.tfliteI hope this solve your problem
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.
rossGardiner commentedon Aug 10, 2021
For me, the tf-nightly build does not fix this issue. I don't think this should be closed. Anyone else?
abattery commentedon Aug 10, 2021
@rossGardiner please upload a new post with reproducible steps.
theumang100 commentedon Aug 10, 2021
try tf 2.3.0
PR #46314: [XLA] Fix asymmetric copy elision in conditional branches
PR #46314: [XLA] Fix asymmetric copy elision in conditional branches
PR #46314: [XLA] Fix asymmetric copy elision in conditional branches
PR #46314: [XLA] Fix asymmetric copy elision in conditional branches
PR #46314: [XLA] Fix asymmetric copy elision in conditional branches
PR #46314: [XLA] Fix asymmetric copy elision in conditional branches
PR #46314: [XLA] Fix asymmetric copy elision in conditional branches