I am trying to convert a saved model tf to a tflite mode. I am getting following error in tensorflow c++ while conversion:-
tensorflow/contrib/lite/toco/tooling_util.cc:981] Check failed: name.substr(colon_pos + 1).find_first_not_of("0123456789") == string::npos (1 vs. 18446744073709551615)Array name must only have digits after colon\n'
Here is the source code :-
def convert_to_tflite_util(model_dir, output_dir):
tag_constants = set(["train"])
converter = tf.contrib.lite.TocoConverter.from_saved_model(model_dir, tag_set=tag_constants)
#converter = tf.contrib.lite.TocoConverter.from_saved_model(model_dir)
tflite_model = converter.convert()
Logs :-
2018-11-09 11:44:11.410085: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
INFO:tensorflow:Restoring parameters from /Users/deosingh/code/mldev/sensei-on-device/converters/deeplasso_converter/model/variables/variables
INFO:tensorflow:The given SavedModel MetaGraphDef contains SignatureDefs with the following keys: {'serving_default'}
INFO:tensorflow:input tensors info:
INFO:tensorflow:Tensor's key in saved_model's tensor_map: input
INFO:tensorflow: tensor name: data:0, shape: (-1, 320, 320, 4), type: DT_FLOAT
INFO:tensorflow:output tensors info:
INFO:tensorflow:Tensor's key in saved_model's tensor_map: output
INFO:tensorflow: tensor name: prob:0, shape: (1, 320, 320, 2), type: DT_FLOAT
INFO:tensorflow:Restoring parameters from /Users/deosingh/code/mldev/model/variables/variables
INFO:tensorflow:Froze 387 variables.
INFO:tensorflow:Converted 387 variables to const ops.
Traceback (most recent call last):
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1664, in <module>
main()
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1658, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1068, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/Users/deosingh/code/mldev/src/tf_to_tflite.py", line 112, in <module>
main()
File "/Users/deosingh/code/mldev/src/tf_to_tflite.py", line 108, in main
convert_to_tflite_util(args.src_dir, args.dest_dir)
File "/Users/deosingh/code/mldev/src/tf_to_tflite.py", line 91, in convert_to_tflite_util
tflite_model = converter.convert()
File "/Users/deosingh/code/mldev/venv/lib/python3.6/site-packages/tensorflow/contrib/lite/python/lite.py", line 439, in convert
**converter_kwargs)
File "/Users/deosingh/code/mldev/venv/lib/python3.6/site-packages/tensorflow/contrib/lite/python/convert.py", line 309, in toco_convert_impl
input_data.SerializeToString())
File "/Users/deosingh/code/mldev/venv/lib/python3.6/site-packages/tensorflow/contrib/lite/python/convert.py", line 109, in toco_convert_protos
(stdout, stderr))
RuntimeError: TOCO failed see console for info.
b'2018-11-09 11:44:18.328373: F tensorflow/contrib/lite/toco/tooling_util.cc:981] Check failed: name.substr(colon_pos + 1).find_first_not_of("0123456789") == string::npos (1 vs. 18446744073709551615)Array name must only have digits after colon\n'
None
Link to tensorflow source which is throwing this error.
The original model was in caffe , then was converted to tensorflow using mmdnn . Converter is complaining about name not being in the correct format i.e doesn't expect _ after : as per the tf source. Please let me know how to resolve/debug this error. Since the tf source which isthrowing this error is in c++ and I am invoking it through python I am not able to debug it through pycharm on macosx.
Related
python : 3.9.13
tensorflow : 2.9.1
I am making a custom dataset with 'tensorflow object detection'
The saved_model.pb file was generated by trainning with the FastRCNN dataset.
I took this file and applied it to Nuclio (Serverless function framework) but failed
It seems to have apply inference graph file type
I find export util pythonf file in models/research/object_detection directory "export_inference_graph.py"
But this file not working .
This is error message
Traceback (most recent call last):
File "export_inference_graph.py", line 211, in <module>
tf.app.run()
File "/home/namu/.local/lib/python3.8/site-packages/tensorflow/python/platform/app.py", line 36, in run
_run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef)
File "/home/namu/.local/lib/python3.8/site-packages/absl/app.py", line 308, in run
_run_main(main, args)
File "/home/namu/.local/lib/python3.8/site-packages/absl/app.py", line 254, in _run_main
sys.exit(main(argv))
File "export_inference_graph.py", line 199, in main
exporter.export_inference_graph(
File "/home/namu/myspace/data/models/research/object_detection/exporter.py", line 618, in export_inference_graph
_export_inference_graph(
File "/home/namu/myspace/data/models/research/object_detection/exporter.py", line 521, in _export_inference_graph
profile_inference_graph(tf.get_default_graph())
File "/home/namu/myspace/data/models/research/object_detection/exporter.py", line 649, in profile_inference_graph
contrib_tfprof.model_analyzer.TRAINABLE_VARS_PARAMS_STAT_OPTIONS)
NameError: name 'contrib_tfprof' is not defined
I knew from Google that this did not work on tensorflow 2.x
https://medium.com/#sebastingarcaacosta/how-to-export-a-tensorflow-2-x-keras-model-to-a-frozen-and-optimized-graph-39740846d9eb
I am working on it by referring to the above site
But
import tensorflow as tf
from tensorflow import keras
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
import numpy as np
#path of the directory where you want to save your model
frozen_out_path = "/home/namu/myspace/data/models/export_graph"
# name of the .pb file
frozen_model = "frozen_graph"
model = tf.keras.models.load_model('/home/namu/myspace/data/models/train_pb/saved_model') # tf_saved_model load
# model = tf.saved_model.load('/home/namu/myspace/data/models/train_pb/saved_model')
full_model = tf.function(lambda x: model(x))
full_model = full_model.get_concrete_function(tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype))
When i execute this code , error occurs
ValueError: Unable to create a Keras model from SavedModel at /home/namu/myspace/data/models/train_pb/saved_model. This SavedModel was exported with `tf.saved_model.save`, and lacks the Keras metadata file. Please save your Keras model by calling `model.save`or `tf.keras.models.save_model`. Note that you can still load this SavedModel with `tf.saved_model.load`.
How can i create inference graph pb file.
I am trying to convert a Keras model found here to TFlite using following snippet
import tensorflow as tf
import os.path as path
pwd = path.dirname(__file__)
model_path = pwd+"/models/old-models/"
print("PWD: ", model_path)
converter = tf.lite.TFLiteConverter.from_saved_model(model_path)
tflite_model = converter.convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
But I am getting following error
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/<PyCharm installed directory>/ch-0/211.6693.23/plugins/python/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "/<PyCharm installed directory>/ch-0/211.6693.23/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/<Path to project>/myproject/convert_to_tflite.py", line 7, in <module>
converter = tf.lite.TFLiteConverter.from_saved_model(model_path)
File "/<path to miniconda>/miniconda3/envs/myproject/lib/python3.8/site-packages/tensorflow/lite/python/lite.py", line 1069, in from_saved_model
saved_model = _load(saved_model_dir, tags)
File "/<path to miniconda>/miniconda3/envs/myproject/lib/python3.8/site-packages/tensorflow/python/saved_model/load.py", line 859, in load
return load_internal(export_dir, tags, options)["root"]
File "/<path to miniconda>/miniconda3/envs/myproject/lib/python3.8/site-packages/tensorflow/python/saved_model/load.py", line 871, in load_internal
loader_impl.parse_saved_model_with_debug_info(export_dir))
File "/<path to miniconda>/miniconda3/envs/myproject/lib/python3.8/site-packages/tensorflow/python/saved_model/loader_impl.py", line 56, in parse_saved_model_with_debug_info
saved_model = _parse_saved_model(export_dir)
File "/<path to miniconda>/miniconda3/envs/myproject/lib/python3.8/site-packages/tensorflow/python/saved_model/loader_impl.py", line 111, in parse_saved_model
raise IOError("SavedModel file does not exist at: %s/{%s|%s}" %
OSError: SavedModel file does not exist at: /<path to my project>/models/old-models/{saved_model.pbtxt|saved_model.pb}
I renamed the model file extension from .mlmodel to .pb, since it seems file extension need to be .pb or .pbtxt. I am sure that path to the model directory is correct.
I am using tensorflow~=2.4.1
According to https://apple.github.io/coremltools/coremlspecification, .mlmodel file extension represents a format of CoreML model. Renaming the file extension does not change the given model format to the other model format.
If you would like to generate TensorFlow Lite models, please take a look at the pre-trained model section at the guide page, https://www.tensorflow.org/lite/guide/get_started#1_choose_a_model.
I have trained a network(git link below) and saved in the saved model format. And would like to convert it to tflite. I am using python API for tflite coverter(tflite.py in git link below). But I'am not able to do so.
System information:
OS Platform and Distribution: Ubuntu 18.04.3 LTS
TensorFlow version: tensorflow/tensorflow:2.2.0-gpu (docker)
The link to network and save model code.
The output from the converter invocation:
File "tflite.py", line 22, in convert_model
tflite_model = converter.convert()
File "/usr/local/lib/python3.6/dist-packages/tensorflow/lite/python/lite.py", line 459, in convert
self._funcs[0], lower_control_flow=False))
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/convert_to_constants.py", line 706, in convert_variables_to_constants_v2_as_graph
func, lower_control_flow, aggressive_inlining)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/convert_to_constants.py", line 457, in _convert_variables_to_constants_v2_impl
tensor_data = _get_tensor_data(func)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/convert_to_constants.py", line 217, in _get_tensor_data
data = val_tensor.numpy()
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 961, in numpy
maybe_arr = self._numpy() # pylint: disable=protected-access
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 929, in _numpy
six.raise_from(core._status_to_exception(e.code, e.message), None)
File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.InvalidArgumentError: Cannot convert a Tensor of dtype resource to a NumPy array.
The link to the saved model
I'm using TF version 1.12 with conda and python 3.
My question concerns the model_dir value of tf.contrib.factorization.KMeansClustering : how to use a string placeholder for the model_dir value?
Here is the context: I have pretrained KMeans in different situation, checkpoints are in different model_dir.
I want to use predictions of these pretrained models inside a graph, depending on each situation, so I need to put in this graph the KMeansClustering which can accept different model_dirs.
In the graph I defined :
ckpt_ph = tf.placeholder(tf.string)
...
kmeans = KMeansClustering(5, model_dir=ckpt_ph,distance_metric='cosine')
def input_fn():
return tf.train.limit_epochs(tf.convert_to_tensor(x, dtype=tf.float32), num_epochs=1)
centers_idx = list(kmeans.predict(input_fn,predict_keys='cluster_index',checkpoint_path=ckpt_ph,yield_single_examples=False))[0]['cluster_index']
centers_val = kmeans.cluster_centers()
...
And I run it with:
...
for ind in range(nb_cases):
...
sess.run([...], feed_dict={..., ckpt_ph: km_ckpt[ind]})
...
Where km_ckpt is the list of pretrained KMeansClustering checkpoints pathes that I want to use for each situations.
The error that I get is:
Traceback (most recent call last):
File "main.py", line 28, in <module>
tf.app.run()
File "C:\Users\Denis\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py", line 125, in run
_sys.exit(main(argv))
File "main.py", line 23, in main
launch_training()
File "main.py", line 14, in launch_training
train_mnist.train_model()
File "C:\Users\Denis\ML\ScatteringReconstruction\src\model\train_mnist.py", line 355, in train_model
X_r = SR(X_tensor)
File "C:\Users\Denis\ML\ScatteringReconstruction\src\model\train_mnist.py", line 316, in __call__
kmeans = KMeansClustering(FLAGS.km_k, model_dir=ckpt_ph, distance_metric='cosine')
File "C:\Users\Denis\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\contrib\factorization\python\ops\kmeans.py", line 423, in __init__
config=config)
File "C:\Users\Denis\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\estimator.py", line 189, in __init__
model_dir)
File "C:\Users\Denis\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\estimator.py", line 1665, in maybe_overwrite_model_dir_and_session_config
if model_dir:
File "C:\Users\Denis\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 671, in __bool__
raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.
I think that the problem is that in KMeansClustering and KMeansClustering.predict, model_dir is expecting a Python bool or string, and I'm giving him a Tensor, but then I don't see hos to use pretrained KMeansClustering inside a graph.
Thanks in advance for the help!
I am running the tutorial code A Guide to TF Layers: Building a Convolutional Neural Network on API r.1.3
https://www.tensorflow.org/tutorials/layers
My code is here.
https://gist.github.com/Po-Hsuan-Huang/91e31d59fd3aa07f40272b75fe2a924d
The error shows:
runfile('/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST/cnn_mnist.py', wdir='/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST')
Extracting MNIST-data/train-images-idx3-ubyte.gz
Extracting MNIST-data/train-labels-idx1-ubyte.gz
Extracting MNIST-data/t10k-images-idx3-ubyte.gz
Extracting MNIST-data/t10k-labels-idx1-ubyte.gz
INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_save_checkpoints_secs': 600, '_session_config': None, '_keep_checkpoint_max': 5, '_tf_random_seed': 1, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_save_checkpoints_steps': None, '_model_dir': '/tmp/mnist_convnet_model', '_save_summary_steps': 100}
Traceback (most recent call last):
File "<ipython-input-1-c9b70e26f791>", line 1, in <module>
runfile('/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST/cnn_mnist.py', wdir='/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST')
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
builtins.execfile(filename, *where)
File "/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST/cnn_mnist.py", line 129, in <module>
main(None)
File "/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST/cnn_mnist.py", line 117, in main
hooks=[logging_hook])
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 241, in train
loss = self._train_model(input_fn=input_fn, hooks=hooks)
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 630, in _train_model
model_fn_lib.ModeKeys.TRAIN)
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 615, in _call_model_fn
model_fn_results = self._model_fn(features=features, **kwargs)
File "/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST/cnn_mnist.py", line 24, in cnn_model_fn
input_layer = tf.reshape(features, [-1, 28, 28, 1])
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 2619, in reshape
name=name)
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 493, in apply_op
raise err
TypeError: Failed to convert object of type <type 'dict'> to Tensor. Contents: {'x': <tf.Tensor 'random_shuffle_queue_DequeueMany:1' shape=(100, 784) dtype=float32>}. Consider casting elements to a supported type.
I traced down a little bit, and found the function estimator._call_input_fn() does not use parameter 'mode' at all, thus not able to create a tuple comprises features and labels. Is it the tutorial that needs to be modified, or there is some problem with this function. I don't understand why mode is unused here.
Thanks !
def _call_input_fn(self, input_fn, mode):
"""Calls the input function.
Args:
input_fn: The input function.
mode: ModeKeys
Returns:
Either features or (features, labels) where features and labels are:
features - `Tensor` or dictionary of string feature name to `Tensor`.
labels - `Tensor` or dictionary of `Tensor` with labels.
Raises:
ValueError: if input_fn takes invalid arguments.
"""
del mode # unused
input_fn_args = util.fn_args(input_fn)
kwargs = {}
if 'params' in input_fn_args:
kwargs['params'] = self.params
if 'config' in input_fn_args:
kwargs['config'] = self.config
with ops.device('/cpu:0'):
return input_fn(**kwargs)
Your gist doesn't actually contain any of your code... Either way, from your error message I think you have just mistranscribed a bit of code from the tutorial.
Your error log indicates you have
"/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST/cnn_mnist.py", line 24, in cnn_model_fn
input_layer = tf.reshape(features, [-1, 28, 28, 1])
Whereas the tutorial has:
input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])