sagemaker-python-sdk icon indicating copy to clipboard operation
sagemaker-python-sdk copied to clipboard

Getting incorrect random string values from prediction output

Open mihi-r opened this issue 8 years ago • 5 comments

I've deployed a model which will return various things when making a prediction, including string values. Now, the int and float values are coming back fine, but my string outputs (defined as labels in my code) are returning as random strings.

For example, the string "DEV01" will return as "REVWMDQ=" instead.

Here is my prediction block:

  if mode == tf.estimator.ModeKeys.PREDICT:
    s3 = boto3.resource('s3')
    content_object = s3.Object('sagemaker-blah', 'labels.json')
    file_content = content_object.get()['Body'].read().decode('utf-8')
    labels = json.loads(file_content)
    labels = tf.convert_to_tensor(labels, dtype=tf.string)
    predictions={
      'index': predicted_class_index,
      'classes': labels,
      'predictions': tf.nn.softmax(scores)
    }
    export_outputs = {SIGNATURE_NAME: tf.estimator.export.PredictOutput(predictions)}
    return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions, export_outputs=export_outputs)

When I just run the block of code below locally, my string values are normal:

s3 = boto3.resource('s3')
content_object = s3.Object('sagemaker-tcclassification', 'labels.json')
file_content = content_object.get()['Body'].read().decode('utf-8')
labels = json.loads(file_content)
labels = tf.convert_to_tensor(labels, dtype=tf.string)

Why do the string values change when outputting through tf.estimator.EstimatorSpec and SageMaker? Are they getting serialized? If so, how can I deserialize them after getting the predictions back?

mihi-r avatar Apr 03 '18 18:04 mihi-r

Hello,

I am not too sure why the string values change when outputting through tf.estimator.EstimatorSpec.

Yes, they are getting serialized before being returned. This is defined in the output_fn, which can be found in our README, https://github.com/aws/sagemaker-python-sdk/blob/master/README.rst.

You can define your own output_fn or change the response_content_type, to see if the serialization may be causing this.

For deserializing, you can write your own deserializer or use the current existing one, https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/tensorflow/predictor.py. This is specified in the predictor, https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/tensorflow/model.py#L22.

To help me further investigate this issue, can you please provide a minimum repro case?

I believe that the serialization/deserialization shouldn't be causing this issue, so I am not too sure why this is happening.

Thank you!

ChoiByungWook avatar Apr 04 '18 01:04 ChoiByungWook

I will try a few of these suggestions out and see if I can solve the issue. Since I'm calling the endpoint through a Lambda function, I can temporarily get around this issue by just loading the JSON file there and tacking it onto the JSON response from SageMaker.

Ideally, I'd like use a JSON response_content_type.

I'll see if I can provide a minimum repro case by next week. Thanks for the suggestions!

mihi-r avatar Apr 05 '18 14:04 mihi-r

@ChoiByungWook Here's the minimum reproduction case you've requested.

mihi-r avatar Apr 19 '18 13:04 mihi-r

The problem is in the tf_json_deserializer is returned the protobuf message parsed as JSON. The json_formatter from protobuf is encoding the labels. I reproduced the bug with the following experiment:

import tensorflow as tf
import numpy as np

# Update with your own path
prediction_set = tf.contrib.learn.datasets.base.load_csv_without_header(
    filename=os.path.join('data/abalone_predict.csv'), target_dtype=np.int, features_dtype=np.float32)

JSON -> JSON

from sagemaker.predictor import RealTimePredictor

data = prediction_set.data[0]
tensor_proto = tf.make_tensor_proto(values=np.asarray(data), shape=[1, len(data)], dtype=tf.float32)

print(abalone_predictor.predict(tensor_proto))
{'outputs': {'example_strings': {'stringVal': ['YXBwbGU=', 'YmFuYW5h', 'b3Jhbmdl'], 'tensorShape': {'dim': [{'size': '3'}]}, 'dtype': 'DT_STRING'}, 'ages': {'floatVal': [4.954165935516357], 'tensorShape': {'dim': [{'size': '1'}]}, 'dtype': 'DT_FLOAT'}}, 'modelSpec': {'version': '1531758457', 'name': 'generic_model', 'signatureName': 'serving_default'}}

JSON -> PB

from sagemaker.predictor import RealTimePredictor

    
predictor = RealTimePredictor(endpoint=abalone_predictor.endpoint,
                              deserializer=tf_json_deserializer, 
                              serializer=tf_json_serializer,
                              content_type='application/json')

data = prediction_set.data[0]
tensor_proto = tf.make_tensor_proto(values=np.asarray(data), shape=[1, len(data)], dtype=tf.float32)

predictor.predict(tensor_proto)
{'modelSpec': {'name': 'generic_model',
  'signatureName': 'serving_default',
  'version': '1531758457'},
 'outputs': {'ages': {'dtype': 'DT_FLOAT',
   'floatVal': [4.954165935516357],
   'tensorShape': {'dim': [{'size': '1'}]}},
  'example_strings': {'dtype': 'DT_STRING',
   'stringVal': ['YXBwbGU=', 'YmFuYW5h', 'b3Jhbmdl'],
   'tensorShape': {'dim': [{'size': '3'}]}}}}

I have a pr with the fix https://github.com/aws/sagemaker-python-sdk/pull/294

Thanks for reporting this issue!

mvsusp avatar Jul 16 '18 18:07 mvsusp

Interesting. Thanks for taking care of the issue @mvsusp!

mihi-r avatar Jul 20 '18 14:07 mihi-r