serving icon indicating copy to clipboard operation
serving copied to clipboard

Export nmt trained model to tensorflow serving

Open luozhouyang opened this issue 8 years ago • 49 comments

I have trained nmt models, but I can not understand how to export the models to tensorflow serving. I read the documentations of MNIST and Inception, but I think these models are different with nmt models. Can you add a demo to show how to export the nmt models? This would be a great help to beginners like me, thanks!

luozhouyang avatar Jan 03 '18 07:01 luozhouyang

@ptamas88 I think I found the reason. It's all due to the --infer_file argument. Serving will take this file as input of the inference and return results of that input. I am working on it.

luozhouyang avatar Jun 08 '18 06:06 luozhouyang

@luozhouyang I'm using your code(https://github.com/luozhouyang/nmt/commit/dfab5a285165e5e297b96605f04a41512e0daf3b) to export model, the model can be served but it always returns the same result.

I guess it related to the --infer_file argument. Any update on it?

Thanks.

msk86 avatar Jun 28 '18 13:06 msk86

@msk86 I have same problem too! Any update @luozhouyang ?

nguyenvulebinh avatar Jul 20 '18 07:07 nguyenvulebinh

Closing as we are moving help and support to Stack Overflow:

https://stackoverflow.com/questions/tagged/tensorflow-serving

If you open a GitHub issue, it must be a bug, a feature request, or a significant problem with documentation (for small docs fixes please send a PR instead).

Thanks!

gautamvasudevan avatar Aug 10 '18 22:08 gautamvasudevan

Holp this can help you. @luozhouyang @nguyenvulebinh @msk86 First: change exporter.py

def export(self):
    infer_model = self._create_infer_model()
    with tf.Session(graph=infer_model.graph,
                    config=tf.ConfigProto(allow_soft_placement=True)) as sess:
      feature_config = {
        'input': tf.FixedLenSequenceFeature(dtype=tf.string,
                                            shape=[], allow_missing=True),
      }
      serialized_example = tf.placeholder(dtype=tf.string, name="serialized_example")
      tf_example = tf.parse_example(serialized_example, feature_config)
      inference_input = tf.identity(tf_example['input'], name="infer_input")

      saver = infer_model.model.saver
      saver.restore(sess, self._ckpt_path)
      sess.run(tf.tables_initializer())
      # note here. Do not use decode func of model.
      inference_outputs = infer_model.model.sample_words
     
      inference_signature = tf.saved_model.signature_def_utils.predict_signature_def(
        inputs={
          'seq_input': inference_input
        },
        outputs={
          'seq_output': tf.convert_to_tensor(inference_outputs)
        }
      )
      legacy_ini_op = tf.group(tf.tables_initializer(), name='legacy_init_op')

      builder = tf.saved_model.builder.SavedModelBuilder(self._export_dir)

change model_helper.py Do not use dataset API

def pre_process(src_string, src_vocab_table, eos, src_max_len=35):
  src_eos_id = tf.cast(src_vocab_table.lookup(tf.constant(eos)), tf.int32)
  src_string = tf.string_split([src_string]).values

  if src_max_len:
    src_string = src_string[:, src_max_len]
  # Convert the word strings to ids
  src = tf.cast(src_vocab_table.lookup(src_string), tf.int32)
  # Add in the word counts.
  src = tf.expand_dims(src, axis=0)
  src_len = tf.size(src)
  src_len = tf.expand_dims(src_len, axis=0)
  return BatchedInput(
    initializer=None,
    source=src,
    target_input=None,
    target_output=None,
    source_sequence_length=src_len,
    target_sequence_length=None)



def create_infer_model(model_creator, hparams, scope=None, extra_args=None):
  """Create inference model."""
  graph = tf.Graph()
  src_vocab_file = hparams.src_vocab_file
  tgt_vocab_file = hparams.tgt_vocab_file

  with graph.as_default(), tf.container(scope or "infer"):
    src_vocab_table, tgt_vocab_table = vocab_utils.create_vocab_tables(
        src_vocab_file, tgt_vocab_file, hparams.share_vocab)
    reverse_tgt_vocab_table = lookup_ops.index_to_string_table_from_file(
        tgt_vocab_file, default_value=vocab_utils.UNK)

    src_placeholder = tf.placeholder(shape=[None], dtype=tf.string)
    batch_size_placeholder = tf.constant(1, tf.int64)

    iterator = pre_process(
      src_placeholder,
        src_vocab_table,
        eos=hparams.eos,
        src_max_len=hparams.src_max_len_infer)
    model = model_creator(
        hparams,
        iterator=iterator,
        mode=tf.contrib.learn.ModeKeys.INFER,
        source_vocab_table=src_vocab_table,
        target_vocab_table=tgt_vocab_table,
        reverse_target_vocab_table=reverse_tgt_vocab_table,
        scope=scope,
        extra_args=extra_args)
  return InferModel(
      graph=graph,
      model=model,
      src_placeholder=src_placeholder,
      batch_size_placeholder=batch_size_placeholder,
      iterator=iterator)

This solution works in my case(I'am not using tensorflow-serving). Inference_signature should also need to change while using serving module and it's not hard.

bidai541 avatar Sep 15 '18 06:09 bidai541

@bidai541 how did you deploy your model ? can you please share your code.

harshS26 avatar Oct 17 '18 06:10 harshS26

@harshS26 The main modification is "model_helper.py". I do not use tensorflow-serving, in my case, I exported the model to do inference in spark cluster.

bidai541 avatar Oct 19 '18 02:10 bidai541

@bidai541 @luozhouyang i did modify the model_helper.py and exported the model using https://github.com/tensorflow/nmt/pull/344 but while making the grpc request i am getting the following error

grpc.framework.interfaces.face.face.AbortionError: AbortionError(code=StatusCode.INVALID_ARGUMENT, details="You must feed a value for placeholder tensor 'src_placeholder' with dtype string [[{{node src_placeholder}} = Placeholder_output_shapes=[], dtype=DT_STRING, shape=, _device="/job:localhost/replica:0/task:0/device:CPU:0"]]")

harshS26 avatar Oct 20 '18 07:10 harshS26

@harshS26 I think you should move out the definition of placeholder src_placeholder = tf.placeholder(shape=[None], dtype=tf.string) to export.py then create the graph using this placeholder. Add it to the params of model_helper.create_infer_model().

bidai541 avatar Oct 20 '18 07:10 bidai541

@bidai541 I am also getting the same issue as @harshS26

joshi-bharat avatar Oct 22 '18 05:10 joshi-bharat

@bidai541 I made changes in exporter.py and the error got resolved. But now i get only one word as output for every input sequence, which i think is because of this line: inference_outputs = infer_model.model.sample_words

harshS26 avatar Oct 22 '18 05:10 harshS26

@bharat-robotics try this.. exporter.py

def export(self):
    infer_model = self._create_infer_model()

    with tf.Session(graph=infer_model.graph,
                    config=tf.ConfigProto(allow_soft_placement=True)) as sess:
      feature_config = {
        'input': tf.FixedLenSequenceFeature(dtype=tf.string,
                                            shape=[], allow_missing=True),
      }
      inference_input = infer_model.graph.get_tensor_by_name('src_placeholder:0')	  
      saver = infer_model.model.saver
      saver.restore(sess, self._ckpt_path)

      sess.run(tf.tables_initializer())
      inference_outputs = infer_model.model.sample_words
      inference_output = inference_outputs[0]
      inference_signature = tf.saved_model.signature_def_utils.predict_signature_def(
        inputs={
          'seq_input': inference_input
        },
        outputs={
          'seq_output': tf.convert_to_tensor(inference_output)
        }
      )

model_helper.py

src_placeholder = tf.placeholder(dtype=tf.string,name="src_placeholder")
batch_size_placeholder = tf.constant(1, tf.int64)

iterator = pre_process(
      src_placeholder,
        src_vocab_table,
        eos=hparams.eos,
        src_max_len=hparams.src_max_len_infer)

harshS26 avatar Oct 22 '18 06:10 harshS26

@harshS26 You are right. This is my inference function in spark cluster. The output is "decoder_output_bm".

def predict(iterator):
  """
  For each partition, load the pb model and feed in each item of the RDD to the placehold
  """
  from tensorflow.contrib.seq2seq.python.ops import beam_search_ops   # note: do not remove this line
  result = []
  sess = tf.Session()
  graph = tf.get_default_graph()
  tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], model_path)
  input_feature = graph.get_tensor_by_name("src_placeholder:0")
  output = graph.get_tensor_by_name("decoder_output_bm:0")
  for item in iterator:
    one_query_result = []
    predict_result = sess.run([output], feed_dict={input_feature: [item[1]]})
    predict_result = predict_result[0]
    predict_result = np.transpose(predict_result, [2, 1, 0])
    predict_result = np.squeeze(predict_result, axis=1)
    for idx in range(args.beam_size):
      one_query_result.append(" ".join(list(predict_result[idx, :])))
    result.append((item[0] + "\t" + item[1] + "\t" + item[2], one_query_result))
  return iter(result)

bidai541 avatar Oct 22 '18 07:10 bidai541

@harshS26 You are right. This is my inference function in spark cluster. The output is "decoder_output_bm".

def predict(iterator):
  """
  For each partition, load the pb model and feed in each item of the RDD to the placehold
  """
  from tensorflow.contrib.seq2seq.python.ops import beam_search_ops   # note: do not remove this line
  result = []
  sess = tf.Session()
  graph = tf.get_default_graph()
  tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], model_path)
  input_feature = graph.get_tensor_by_name("src_placeholder:0")
  output = graph.get_tensor_by_name("decoder_output_bm:0")
  for item in iterator:
    one_query_result = []
    predict_result = sess.run([output], feed_dict={input_feature: [item[1]]})
    predict_result = predict_result[0]
    predict_result = np.transpose(predict_result, [2, 1, 0])
    predict_result = np.squeeze(predict_result, axis=1)
    for idx in range(args.beam_size):
      one_query_result.append(" ".join(list(predict_result[idx, :])))
    result.append((item[0] + "\t" + item[1] + "\t" + item[2], one_query_result))
  return iter(result)

I can try using your approach but I have few questions on this: 1.predict_result = sess.run([output], feed_dict={input_feature: [item[1]]}) what is item[1] in this? 2.Which variable do i assign the name decoder_output_bm ?

harshS26 avatar Oct 22 '18 12:10 harshS26

@harshS26 You are right. This is my inference function in spark cluster. The output is "decoder_output_bm".

def predict(iterator):
  """
  For each partition, load the pb model and feed in each item of the RDD to the placehold
  """
  from tensorflow.contrib.seq2seq.python.ops import beam_search_ops   # note: do not remove this line
  result = []
  sess = tf.Session()
  graph = tf.get_default_graph()
  tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], model_path)
  input_feature = graph.get_tensor_by_name("src_placeholder:0")
  output = graph.get_tensor_by_name("decoder_output_bm:0")
  for item in iterator:
    one_query_result = []
    predict_result = sess.run([output], feed_dict={input_feature: [item[1]]})
    predict_result = predict_result[0]
    predict_result = np.transpose(predict_result, [2, 1, 0])
    predict_result = np.squeeze(predict_result, axis=1)
    for idx in range(args.beam_size):
      one_query_result.append(" ".join(list(predict_result[idx, :])))
    result.append((item[0] + "\t" + item[1] + "\t" + item[2], one_query_result))
  return iter(result)

I can try using your approach but I have few questions on this: 1.predict_result = sess.run([output], feed_dict={input_feature: [item[1]]}) what is item[1] in this? 2.Which variable do i assign the name decoder_output_bm ?

Sorry, my mistake.
Anthor modification in model.py of line 121

    elif self.mode == tf.contrib.learn.ModeKeys.INFER:
      self.infer_logits, _, self.final_context_state, self.sample_id = res
      self.sample_words = reverse_target_vocab_table.lookup(
          tf.to_int64(self.sample_id), name="decoder_output_bm")

This is same node with "inference_outputs = infer_model.model.sample_words". Maybe something else went wrong, a suggestion, you can print the source string before feeding into graph.

bidai541 avatar Oct 22 '18 12:10 bidai541

@bidai541 this is the error i get while exporting

KeyError: "The name 'decoder_output_bm:0' refers to a Tensor which does not exist

harshS26 avatar Oct 22 '18 13:10 harshS26

@bidai541 Thanks...i get proper prediction using your code.

harshS26 avatar Oct 23 '18 06:10 harshS26

@harshS26 can u share your detailed code?

B1gMinnow avatar Feb 22 '19 07:02 B1gMinnow

@bharat-robotics try this.. exporter.py

def export(self):
    infer_model = self._create_infer_model()

    with tf.Session(graph=infer_model.graph,
                    config=tf.ConfigProto(allow_soft_placement=True)) as sess:
      feature_config = {
        'input': tf.FixedLenSequenceFeature(dtype=tf.string,
                                            shape=[], allow_missing=True),
      }
      inference_input = infer_model.graph.get_tensor_by_name('src_placeholder:0')	  
      saver = infer_model.model.saver
      saver.restore(sess, self._ckpt_path)

      sess.run(tf.tables_initializer())
      inference_outputs = infer_model.model.sample_words
      inference_output = inference_outputs[0]
      inference_signature = tf.saved_model.signature_def_utils.predict_signature_def(
        inputs={
          'seq_input': inference_input
        },
        outputs={
          'seq_output': tf.convert_to_tensor(inference_output)
        }
      )

model_helper.py

src_placeholder = tf.placeholder(dtype=tf.string,name="src_placeholder")
batch_size_placeholder = tf.constant(1, tf.int64)

iterator = pre_process(
      src_placeholder,
        src_vocab_table,
        eos=hparams.eos,
        src_max_len=hparams.src_max_len_infer)

use your code ,i meet error: grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with: status = StatusCode.INVALID_ARGUMENT details = "input must be a vector, got shape: [1,1] [[{{node StringSplit}}]]" debug_error_string = "{"created":"@1550828332.451979981","description":"Error received from peer","file":"src/core/lib/surface/call.cc","file_line":1095,"grpc_message":"input must be a vector, got shape: [1,1]\n\t [[{{node StringSplit}}]]","grpc_status":3}"

B1gMinnow avatar Feb 22 '19 09:02 B1gMinnow

@bidai541 I made changes in exporter.py and the error got resolved. But now i get only one word as output for every input sequence, which i think is because of this line: inference_outputs = infer_model.model.sample_words

i get the same issue, just one word for every input

B1gMinnow avatar Feb 23 '19 09:02 B1gMinnow