serving icon indicating copy to clipboard operation
serving copied to clipboard

Tensorflow serving retrained inception

Open Mdrbhatti opened this issue 9 years ago • 20 comments

I am trying to serve a retrained inception model, but haven't had luck for the past few days. Every question that relates to my situation has not been answered on stackoverflow or anywhere else. If anyone can help regarding this, I would be very grateful! This question pretty much describes what I am trying to do. http://stackoverflow.com/questions/38892976/tensorflow-serving-retrained-inception?rq=1

How are you actually supposed to export a retrained inception model so that it can be served? I have trouble understanding the whole exporting process in the retrain.py file. Similar to this: http://stackoverflow.com/questions/37237940/how-to-serve-the-tensorflow-graph-file-output-graph-pb-via-tensorflow-serving

Please help!

Mdrbhatti avatar May 21 '17 12:05 Mdrbhatti

Based on the error message "FetchOutputs node : not found", it looks like the core issue is that the output node it's requesting from tensorflow is not found in the graph. So likely the signature and/or the inference request has the wrong output node name.

chrisolston avatar Jun 12 '17 19:06 chrisolston

I have written a small utility which helps in exporting a retrained inception model so that it can be served. If it adds value to the community, I would be happy to contribute.

nsahaytech avatar Nov 23 '17 23:11 nsahaytech

Sounds good

vitalyli avatar Nov 24 '17 00:11 vitalyli

@nsahaytech Where can I find that utility you mention in your comment? It would be really useful for a project I'm working on.

hecforga avatar Dec 01 '17 13:12 hecforga

I would be sending the pull request soon.

Get Outlook for Androidhttps://aka.ms/ghei36


From: Héctor Fornes [email protected] Sent: Friday, December 1, 2017 6:41:57 PM To: tensorflow/serving Cc: Nishant Sahay (Service Transformation); Mention Subject: Re: [tensorflow/serving] Tensorflow serving retrained inception (#449)

** This mail has been sent from an external source. Treat hyperlinks and attachments in this email with caution**

@nsahaytechhttps://clicktime.symantec.com/a/1/jaX6N4Qn3Yi5Gjmp3E-NJP5jsusnY4XAP6Ifj3k6wY0=?d=p89ve4FRlPCaGUNAdO5WqfLU8ykyVDCrxEm3YWeWiIQDjqAqQwaBtDXX8PggIpSmJvhBHRy-PSL5CBatcgYdqLqFLlC5ONje-G-2GemPFkTuHMc_579ZmgFU_UFgo7QNlh3SkbF4UMVYiZZwOOMlERkqRCpnT2kH0kyhSDsc-6oKAWkTp5iiWKd3dpHSipa84YUh3ZKNNe8-oVD6TFN-l7Zkxvh-TlHVQpcrOuQTvU6H7ZdkLlX-EZo1b5s30DeZmU6hctG3e6Xf4epUVqYdiSwIFD78G7iMZv3cK_OImDDXkK2Xv9dGtVKdiFJRBHyDLn-EHsh44C6pj6THzGrRGpYanHAXRals5ih3XSQKYYlZxG92HKtyZTXrFlQTSb-m3Usu62aUh4i6GtCwr0_LzU9u283TO_YCgBt0bPNX8Mp6y0YzwCKNi6mV8W1HT2vpPJu0u5bdVeuzbPC_tKlF8SgwoHWEguo_11e2qC-j0Uqv-Q%3D%3D&u=https%3A%2F%2Fgithub.com%2Fnsahaytech Where can I find that utility you mention in your comment? It would be really useful for a project I'm working on.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHubhttps://clicktime.symantec.com/a/1/EXfJN8dc0SYVhcuqffcD6dOYHl7ZQ012btGSXydK4_I=?d=p89ve4FRlPCaGUNAdO5WqfLU8ykyVDCrxEm3YWeWiIQDjqAqQwaBtDXX8PggIpSmJvhBHRy-PSL5CBatcgYdqLqFLlC5ONje-G-2GemPFkTuHMc_579ZmgFU_UFgo7QNlh3SkbF4UMVYiZZwOOMlERkqRCpnT2kH0kyhSDsc-6oKAWkTp5iiWKd3dpHSipa84YUh3ZKNNe8-oVD6TFN-l7Zkxvh-TlHVQpcrOuQTvU6H7ZdkLlX-EZo1b5s30DeZmU6hctG3e6Xf4epUVqYdiSwIFD78G7iMZv3cK_OImDDXkK2Xv9dGtVKdiFJRBHyDLn-EHsh44C6pj6THzGrRGpYanHAXRals5ih3XSQKYYlZxG92HKtyZTXrFlQTSb-m3Usu62aUh4i6GtCwr0_LzU9u283TO_YCgBt0bPNX8Mp6y0YzwCKNi6mV8W1HT2vpPJu0u5bdVeuzbPC_tKlF8SgwoHWEguo_11e2qC-j0Uqv-Q%3D%3D&u=https%3A%2F%2Fgithub.com%2Ftensorflow%2Fserving%2Fissues%2F449%23issuecomment-348491121, or mute the threadhttps://clicktime.symantec.com/a/1/5QfYobMqgyoztHTrQSWiSFmXVEVBJNpl4sJ97OMIbNE=?d=p89ve4FRlPCaGUNAdO5WqfLU8ykyVDCrxEm3YWeWiIQDjqAqQwaBtDXX8PggIpSmJvhBHRy-PSL5CBatcgYdqLqFLlC5ONje-G-2GemPFkTuHMc_579ZmgFU_UFgo7QNlh3SkbF4UMVYiZZwOOMlERkqRCpnT2kH0kyhSDsc-6oKAWkTp5iiWKd3dpHSipa84YUh3ZKNNe8-oVD6TFN-l7Zkxvh-TlHVQpcrOuQTvU6H7ZdkLlX-EZo1b5s30DeZmU6hctG3e6Xf4epUVqYdiSwIFD78G7iMZv3cK_OImDDXkK2Xv9dGtVKdiFJRBHyDLn-EHsh44C6pj6THzGrRGpYanHAXRals5ih3XSQKYYlZxG92HKtyZTXrFlQTSb-m3Usu62aUh4i6GtCwr0_LzU9u283TO_YCgBt0bPNX8Mp6y0YzwCKNi6mV8W1HT2vpPJu0u5bdVeuzbPC_tKlF8SgwoHWEguo_11e2qC-j0Uqv-Q%3D%3D&u=https%3A%2F%2Fgithub.com%2Fnotifications%2Funsubscribe-auth%2FABIWz6RyAIyWyMfjvulTFJt0FRdb730uks5s7_sdgaJpZM4NhlJ1.


This email has been scanned by the Symantec Email Security.cloud service. For more information please visit http://www.symanteccloud.com


The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain proprietary, confidential or privileged information. If you are not the intended recipient, you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately and destroy all copies of this message and any attachments. WARNING: Computer viruses can be transmitted via email. The recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. www.wipro.com


This email has been scanned by the Symantec Email Security.cloud service. For more information please visit http://www.symanteccloud.com


nsahaytech avatar Dec 01 '17 17:12 nsahaytech

@nsahaytech Hey any hope of you posting that pull soon? Or could you show us how you did it :)? I have been stuck on this for a while and I'm really hoping to get my model up and running soon

jda91 avatar Dec 08 '17 21:12 jda91

Hi @nsahaytech, I'm also interested by your utility. I not a PR, can you share it as a gist? Thank you

gmercey avatar Dec 22 '17 16:12 gmercey

Have a PR that shows how to do it: https://github.com/tensorflow/tensorflow/pull/15855

The client would look like:

from grpc.beta import implementations
import tensorflow as tf

from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2


tf.app.flags.DEFINE_string('server', 'localhost:9000', 'PredictionService host:port')
tf.app.flags.DEFINE_string('image', '', 'path to image in JPEG format')
FLAGS = tf.app.flags.FLAGS


def main(_):
    host, port = FLAGS.server.split(':')
    channel = implementations.insecure_channel(host, int(port))
    stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
    # Send request
    image = tf.gfile.FastGFile(FLAGS.image, 'rb').read()
    request = predict_pb2.PredictRequest()
    request.model_spec.name = 'inception'
    request.model_spec.signature_name = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
    request.inputs['image'].CopyFrom(tf.contrib.util.make_tensor_proto(data))
    result = stub.Predict(request, 10.0)  # 10 secs timeout
    print(result)


if __name__ == '__main__':
  tf.app.run()

ksindi avatar Jan 04 '18 19:01 ksindi

thanks @ksindi

For anybody else who needs human readable class names in the output, change the outputs to the following, making sure to pass image_lists.keys() to def export_model() in the PR (https://github.com/tensorflow/tensorflow/pull/15855/files):

outputs = {'prediction': tf.saved_model.utils.build_tensor_info(out_classes),
             'classes': tf.saved_model.utils.build_tensor_info(tf.convert_to_tensor(list(keys))),}

Gist here: https://gist.github.com/pgpgpg/9f212cba5c77bc9b49b14f6fd0b4868b

pgpgpg avatar Jan 29 '18 15:01 pgpgpg

Hi @ksindi,

I am new to Tensorflow serving, so will need some help on the client side. For the client you show, when use directly I see the following error. Can you advise? Is it possible that I can use the default inception_client.py?

request.inputs['image'].CopyFrom(tf.contrib.util.make_tensor_proto(data))

NameError: global name 'data' is not defined

heng2j avatar Mar 15 '18 12:03 heng2j

Hi @ksindi

No worries, I figured out that the data should be replace with the variable name image

Thank you so much for putting this PR.

heng2j avatar Mar 15 '18 12:03 heng2j

Hi @ksindi and everyone, with this retrained inception, from the client end. How do we also show labels from the prediction? My goal is to get he label with the highest accuracy.

And now my outputs just look like this. And suggestions?

outputs { key: "prediction" value { dtype: DT_FLOAT tensor_shape { dim { size: 1 } dim { size: 4 } } float_val: 0.0137002402917 float_val: 0.0319225639105 float_val: 0.869793236256 float_val: 0.0845839455724 } }

heng2j avatar Mar 15 '18 13:03 heng2j

@heng2j this is what I did:

import json

from google.protobuf import json_format

...
result = stub.Predict(request, 10.0)  # 10 secs timeout
json_string = json_format.MessageToJson(result)
d = json.loads(json_string)
scores = d['outputs']['prediction']['floatVal']
print(scores)

ksindi avatar Mar 15 '18 13:03 ksindi

Hi @ksindi

Thank you for your quick response.

I see that you also used from inception.config import config

Do you know where I can get or generate this import as well?

Currently I received this error since I don't have inception.config ImportError: No module named config

heng2j avatar Mar 15 '18 14:03 heng2j

Sorry the config import was from a personal project. You don't need it.

ksindi avatar Mar 15 '18 14:03 ksindi

Hi @ksindi ,

Thank you then I guess I will also need to modify the retrain.py to include the signature_def_map to get the classes and scores

Currently with DEFAULT_SERVING_SIGNATURE_DEF_KEY I can only get scores but not the labels.

heng2j avatar Mar 15 '18 14:03 heng2j

Hi @pgpgpg

When I tried to follow the modification you mentioned to get the classeses by adding the image_lists.keys() references as in Gist, I encountered the grpc time out issue.

Maybe because I am using TF 1.4 instead of 1.4.1?

Traceback (most recent call last): File "/home/ubuntu/tensorflow_serving/serving/tensorflow_serving/example/csl_client.py", line 35, in tf.app.run() File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 48, in run _sys.exit(main(_sys.argv[:1] + flags_passthrough)) File "/home/ubuntu/tensorflow_serving/serving/tensorflow_serving/example/csl_client.py", line 30, in main result = stub.Predict(request, 10.0) # 10 secs timeout File "/usr/local/lib/python2.7/dist-packages/grpc/beta/_client_adaptations.py", line 309, in call self._request_serializer, self._response_deserializer) File "/usr/local/lib/python2.7/dist-packages/grpc/beta/_client_adaptations.py", line 195, in _blocking_unary_unary raise _abortion_error(rpc_error_call) grpc.framework.interfaces.face.face.ExpirationError: ExpirationError(code=StatusCode.DEADLINE_EXCEEDED, details="Deadline Exceeded")

heng2j avatar Mar 15 '18 18:03 heng2j

Hi @pgpgpg

No worries, I figured out that the on and off exceeded run time was due to multiple processes were running on port 9000. So it jammed

heng2j avatar Mar 15 '18 21:03 heng2j

The retrain script changed a bit where the input tensor name changed from 'DecodeJpeg/contents:0' to 'Mul:0'. So you have to decode the image and normalize the image first.

import tensorflow as tf
from grpc.beta import implementations
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2

tf.enable_eager_execution()

tf.app.flags.DEFINE_string('server', 'localhost:9000',
                           'PredictionService host:port')
tf.app.flags.DEFINE_string('image', '', 'path to image in JPEG format')
FLAGS = tf.app.flags.FLAGS


def read_tensor_from_image_file(file_name,
                                input_height=299,
                                input_width=299,
                                input_mean=0,
                                input_std=255):
    input_name = "file_reader"
    file_reader = tf.read_file(file_name, input_name)
    if file_name.endswith(".png"):
        image_reader = tf.image.decode_png(
            file_reader, channels=3, name="png_reader")
    elif file_name.endswith(".gif"):
        image_reader = tf.squeeze(
            tf.image.decode_gif(file_reader, name="gif_reader"))
    elif file_name.endswith(".bmp"):
        image_reader = tf.image.decode_bmp(file_reader, name="bmp_reader")
    else:
        image_reader = tf.image.decode_jpeg(
            file_reader, channels=3, name="jpeg_reader")
    float_caster = tf.cast(image_reader, tf.float32)
    dims_expander = tf.expand_dims(float_caster, 0)
    resized = tf.image.resize_bilinear(
        dims_expander, [input_height, input_width])
    normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])

    return normalized


def main(args):
    host, port = FLAGS.server.split(':')
    channel = implementations.insecure_channel(host, int(port))
    stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
    # Send request
    image = read_tensor_from_image_file(FLAGS.image)

    request = predict_pb2.PredictRequest()
    request.model_spec.name = 'inception'
    request.model_spec.signature_name = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
    request.inputs['image'].CopyFrom(tf.contrib.util.make_tensor_proto(image))
    result = stub.Predict(request, 10.0)  # 10 secs timeout
    print(result)


if __name__ == '__main__':
    tf.app.run()

ksindi avatar Apr 14 '18 17:04 ksindi

Closing as this issue is resolved.

wt-huang avatar Oct 12 '18 18:10 wt-huang