Tensorflow serving Keras model
I am trying to convert my Keras graph to a TF graph.
I managed to run the provided tensorflow_serving examples, but I'm having issues to run my custom model.
Here is my code:
` import tensorflow as tf from keras import backend as K from tensorflow.contrib.session_bundle import exporter def export_model_to_tf(model): K.set_learning_phase(0) # all new operations will be in test mode from now on # serialize the model and get its weights, for quick re-building
export_path = "./tmp" # where to save the exported graph
export_version = "1" # version number (integer)
print('Exporting trained model to %s' % export_path)
saver = tf.train.Saver(sharded=True)
with tf.Session() as sess:
model_exporter = exporter.Exporter(saver)
signature = exporter.classification_signature(input_tensor=model.input, scores_tensor=model.output)
model_exporter.init(sess.graph.as_graph_def(),
default_graph_signature=signature)
model_exporter.export(export_path, tf.constant(export_version), sess)
`
This is the error I am getting:
root@566d926360d6:/serving# bazel-bin/tensorflow_serving/example/main ./tmp/main_model Using TensorFlow backend. Exporting trained model to ./tmp 2017-02-03 22:32:37.001202: W external/org_tensorflow/tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations. 2017-02-03 22:32:37.001260: W external/org_tensorflow/tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations. <tensorflow.contrib.session_bundle.exporter.Exporter object at 0x7f617023db50> Traceback (most recent call last): File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/tf_serving/tensorflow_serving/example/main.py", line 100, in
main() File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/tf_serving/tensorflow_serving/example/main.py", line 98, in main save_model.export_model_to_tf(model) File "/serving/tensorflow_serving/example/save_model.py", line 25, in export_model_to_tf model_exporter.export(export_path, tf.constant(export_version), sess) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/contrib/session_bundle/exporter.py", line 275, in export meta_graph_suffix=constants.EXPORT_SUFFIX_NAME) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/training/saver.py", line 1390, in save {self.saver_def.filename_tensor_name: checkpoint_file}) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/client/session.py", line 767, in run run_metadata_ptr) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/client/session.py", line 965, in _run feed_dict_string, options, run_metadata) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/client/session.py", line 1015, in _do_run target_list, options, run_metadata) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/client/session.py", line 1035, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value dense_1_W [[Node: save/SaveV2 = SaveV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](save/ShardedFilename, save/SaveV2/tensor_names, save/SaveV2/shape_and_slices, dense_1_W, dense_1_b, dense_2_W, dense_2_b)]]
Caused by op u'save/SaveV2', defined at: File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/tf_serving/tensorflow_serving/example/main.py", line 100, in
main() File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/tf_serving/tensorflow_serving/example/main.py", line 98, in main save_model.export_model_to_tf(model) File "/serving/tensorflow_serving/example/save_model.py", line 13, in export_model_to_tf saver = tf.train.Saver(sharded=True) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/training/saver.py", line 1067, in init self.build() File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/training/saver.py", line 1097, in build restore_sequentially=self._restore_sequentially) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/training/saver.py", line 685, in build save_tensor = self._AddShardedSaveOps(filename_tensor, per_device) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/training/saver.py", line 361, in _AddShardedSaveOps return self._AddShardedSaveOpsForV2(filename_tensor, per_device) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/training/saver.py", line 335, in _AddShardedSaveOpsForV2 sharded_saves.append(self._AddSaveOps(sharded_filename, saveables)) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/training/saver.py", line 276, in _AddSaveOps save = self.save_op(filename_tensor, saveables) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/training/saver.py", line 219, in save_op tensors) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/ops/gen_io_ops.py", line 780, in save_v2 tensors=tensors, name=name) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/framework/op_def_library.py", line 768, in apply_op op_def=op_def) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/framework/ops.py", line 2402, in create_op original_op=self._default_original_op, op_def=op_def) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/framework/ops.py", line 1264, in init self._traceback = _extract_stack()
FailedPreconditionError (see above for traceback): Attempting to use uninitialized value dense_1_W [[Node: save/SaveV2 = SaveV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](save/ShardedFilename, save/SaveV2/tensor_names, save/SaveV2/shape_and_slices, dense_1_W, dense_1_b, dense_2_W, dense_2_b)]]
Do you know what could cause the Saver to fail?
Thanks!
Have you tried deleting:
with tf.Session() as sess:
and adding:
sess = tf.Session()
K.set_session(sess)
at the begin of your script?
Yes, I have tried and I'm getting a similar error. The code is still failing when calling model_exporter.export(...).
I've also tried to adapt the mnist_saved_model.py, but I'm also getting erorrs. Could it be because if the way I'm creating the signature from my keras model? My ultimate goal is to create the protobuf graph, in order to use it in my Android app.
Code: `def export_model_to_tf(model, sess):
classification_inputs = utils.build_tensor_info(model.input)
classification_outputs_scores = utils.build_tensor_info(model.output)
classification_signature = signature_def_utils.classification_signature_def(
model.input,
model.output,
None)
builder = saved_model_builder.SavedModelBuilder("./tmp/2")
builder.add_meta_graph_and_variables(
sess, [tag_constants.SERVING],
signature_def_map={
signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:classification_signature
})
builder.save()`
Error:
root@566d926360d6:/serving# bazel-bin/tensorflow_serving/example/main ./tmp/2 Using TensorFlow backend. 2017-02-04 02:48:56.048045: W external/org_tensorflow/tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations. 2017-02-04 02:48:56.048099: W external/org_tensorflow/tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations. Traceback (most recent call last): File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/tf_serving/tensorflow_serving/example/main.py", line 106, in
main() File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/tf_serving/tensorflow_serving/example/main.py", line 104, in main save_model2.export_model_to_tf(model, sess) File "/serving/tensorflow_serving/example/save_model2.py", line 28, in export_model_to_tf signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:classification_signature File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/saved_model/builder_impl.py", line 438, in add_meta_graph_and_variables saver.save(sess, variables_path, write_meta_graph=False, write_state=False) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/training/saver.py", line 1390, in save {self.saver_def.filename_tensor_name: checkpoint_file}) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/client/session.py", line 767, in run run_metadata_ptr) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/client/session.py", line 965, in _run feed_dict_string, options, run_metadata) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/client/session.py", line 1015, in _do_run target_list, options, run_metadata) File "/serving/bazel-bin/tensorflow_serving/example/main.runfiles/org_tensorflow/tensorflow/python/client/session.py", line 1035, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value dense_1_W [[Node: save/SaveV2 = SaveV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](save/ShardedFilename, save/SaveV2/tensor_names, save/SaveV2/shape_and_slices, dense_1_W, dense_1_b, dense_2_W, dense_2_b)]]
I don't think so, I'm guessing you have an issue with the sessions. Here is an example I adapt to export a Keras Model, maybe it can help you.
@GeorgianaPetria see section 4 of https://blog.keras.io/keras-as-a-simplified-interface-to-tensorflow-tutorial.html
@viksit the section 4 of tutorial is broken btw
I managed to export a Keras model for Tensorflow Serving (not sure whether it is the official way to do this). My first trial prior to creating my custom model was to use a trained model available on Keras such as VGG19.
Here is how I did (I put in separate boxes to help understanding and because I use Jupyter :)):
Creating the model
import keras.backend as K
from keras.applications import VGG19
from keras.models import Model
# very important to do this as a first thing
K.set_learning_phase(0)
model = VGG19(include_top=True, weights='imagenet')
# The creation of a new model might be optional depending on the goal
config = model.get_config()
weights = model.get_weights()
new_model = Model.from_config(config)
new_model.set_weights(weights)
Exporting the model
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model import utils
from tensorflow.python.saved_model import tag_constants, signature_constants
from tensorflow.python.saved_model.signature_def_utils_impl import build_signature_def, predict_signature_def
from tensorflow.contrib.session_bundle import exporter
export_path = 'folder_to_export'
builder = saved_model_builder.SavedModelBuilder(export_path)
signature = predict_signature_def(inputs={'images': new_model.input},
outputs={'scores': new_model.output})
with K.get_session() as sess:
builder.add_meta_graph_and_variables(sess=sess,
tags=[tag_constants.SERVING],
signature_def_map={'predict': signature})
builder.save()
Some side notes:
- It can vary depending on Keras, TensorFlow, and TensorFlow Serving version. I used the latest ones.
- Beware of the names of the signatures, since they should be used in the client as well.
- When creating the client, all preprocessing steps that are needed for the model (
preprocess_input()for example) must be executed. I didn't try to add such step in the graph itself as Inception client example.
In case you're curious about the client side, it should be similar to the below one. I added some extra things to use Keras methods for decoding predictions, but it could also be done in the serving side:
request = predict_pb2.PredictRequest()
request.model_spec.name = 'vgg19'
request.model_spec.signature_name = 'predict'
request.inputs['images'].CopyFrom(tf.contrib.util.make_tensor_proto(img))
result = stub.Predict(request, 10.0) # 10 secs timeout
to_decode = np.expand_dims(result.outputs['outputs'].float_val, axis=0)
decoded = decode_predictions(to_decode, 5)
print(decoded)
Hopefully it will help someone :)
@tspthomas I have tried to use your guide, but I'm getting the client side error:
grpc.framework.interfaces.face.face.AbortionError: AbortionError(code=StatusCode.INVALID_ARGUMENT, details="input tensor alias not found in signature: images")
Do you have any idea how I can solve this issue? Thanks!
Hi @azagovora ! Well, it seems that I made a mistake in the code.
Could you try to change from "images" to "inputs" in the client code?
request.inputs['images'].CopyFrom(tf.contrib.util.make_tensor_proto(img))
to
request.inputs['inputs'].CopyFrom(tf.contrib.util.make_tensor_proto(img))
I think the only problem is that you need to make the input signature match. Let me know if that solves your problem.
Hi @tspthomas!
Thank you for your quick reply to my question. I have corrected my code but I'm getting the same error message:
grpc.framework.interfaces.face.face.AbortionError: AbortionError(code=StatusCode.INVALID_ARGUMENT, details="input tensor alias not found in signature: input")
Hi @azagovora! Sorry for the dumb question, but you put 'inputs' or 'input' in the client code? It looks like you put 'input' per the error message, so you'd need to change accordingly.
If it is correct, could you please paste your export code and your client code?
Sorry, it was my mistake, I put 'input' instead of 'inputs'. Unfortunately, I'm getting another error:
grpc.framework.interfaces.face.face.AbortionError: AbortionError(code=StatusCode.INTERNAL, details="Output 0 of type string does not match declared output type float for node _recv_input_1_1_0 = _Recvclient_terminated=true, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=92768290196530094, tensor_name="input_1_1:0", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"")
It looks like the export problem.
Here is my export code:
import os import tensorflow as tf import keras.backend as K
from keras.applications.inception_v3 import InceptionV3 #from keras.applications import VGG19 from keras.models import Model
from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import signature_def_utils from tensorflow.python.saved_model import tag_constants from tensorflow.python.saved_model import utils from tensorflow.python.saved_model.signature_def_utils_impl import build_signature_def, predict_signature_def
#from inception_v3_finetuning_v2 import load_trained
from os.path import join as join_path
tf.app.flags.DEFINE_string('output_dir', '/tmp/inception_output', """Directory where to export inference model.""") tf.app.flags.DEFINE_integer('model_version', 4, """Version number of the model.""") FLAGS = tf.app.flags.FLAGS
def export():
K.set_learning_phase(0)
# model, _ = load_trained()
model = InceptionV3(include_top=True, weights='imagenet')
#model = VGG19(include_top=True, weights='imagenet')
# The creation of a new model might be optional depending on the goal
config = model.get_config()
weights = model.get_weights()
new_model = Model.from_config(config)
new_model.set_weights(weights)
output_path = os.path.join(FLAGS.output_dir, str(FLAGS.model_version))
print ('Exporting trained model to', output_path)
builder = saved_model_builder.SavedModelBuilder(output_path)
signature = predict_signature_def(inputs={'images': new_model.input},
outputs={'scores': new_model.output})
with K.get_session() as sess:
builder.add_meta_graph_and_variables(sess=sess,
tags=[tag_constants.SERVING],
signature_def_map={'predict': signature})
builder.save()
print ('Successfully exported model to %s' % FLAGS.output_dir)
def main(unused_argv=None): export()
if name == 'main': tf.app.run()
Hello @azagovora. It seems to me that is something in your client code not on the export. I think that you should review the way that you're reading the image. In the code I put here, I'm reading the image with Keras methods and passing as a float array to the input. It might be the case that you're reading it as a binary string and this is why you're facing the error.
If you're following the Inception v3 sample code, you need to change the way you read the image and you can use Keras default methods for that. In my case, I created a method to read and pre-process the image:
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.imagenet_utils import preprocess_input
import numpy as np
def load_preprocess_img(img_path, target_size=(224, 224)):
img = load_img(img_path, target_size=target_size)
x = img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
return x
# Before making the request, I read the image like this:
img = load_preprocess_img(FLAGS.image)
Please review the target size and other information and change it according to the model you're using. In case you still didn't find any issue, please paste your complete client code.
Hi @tspthomas!
It works now.
Thank you very much for your help!
@tspthomas awesome ! Yours was the only help I found for converting the keras model to tensorflow using the saved_model_builder. Thanks !
@azagovora @ashavish You're welcome. I'm glad that it helped :)
@GeorgianaPetria how to add new model (like you add keras model) to serving? I want to do this, but I don't know what should I do. #452
@tspthomas Thank you so much good sir! This is the only good explanation of how to do this with Keras models. Thank you again!
Cheers, Dylan
Hi @tspthomas,
Where do you put your preprocessing method? (is it in the client, or where?)
Thank you!
Dylan
@dylanrandle what kind of pre-processing are you doing? tf ops, or normal python?