aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/predictor/saved_model_predictor_test.py
blob: f40e2e73d99dde67f2104194f758113925ebe10d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""Tests for predictor.saved_model_predictor."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.contrib.predictor import saved_model_predictor
from tensorflow.core.framework import tensor_shape_pb2
from tensorflow.core.framework import types_pb2
from tensorflow.core.protobuf import meta_graph_pb2
from tensorflow.python.framework import ops
from tensorflow.python.platform import test
from tensorflow.python.saved_model import signature_def_utils


KEYS_AND_OPS = (('sum', lambda x, y: x + y),
                ('product', lambda x, y: x * y,),
                ('difference', lambda x, y: x - y))

MODEL_DIR_NAME = 'contrib/predictor/test_export_dir'


class SavedModelPredictorTest(test.TestCase):

  @classmethod
  def setUpClass(cls):
    # Load a saved model exported from the arithmetic `Estimator`.
    # See `testing_common.py`.
    cls._export_dir = test.test_src_dir_path(MODEL_DIR_NAME)

  def testDefault(self):
    """Test prediction with default signature."""
    np.random.seed(1111)
    x = np.random.rand()
    y = np.random.rand()
    predictor = saved_model_predictor.SavedModelPredictor(
        export_dir=self._export_dir)
    output = predictor({'x': x, 'y': y})['outputs']
    self.assertAlmostEqual(output, x + y, places=3)

  def testSpecifiedSignatureKey(self):
    """Test prediction with spedicified signature key."""
    np.random.seed(1234)
    for signature_def_key, op in KEYS_AND_OPS:
      x = np.random.rand()
      y = np.random.rand()
      expected_output = op(x, y)

      predictor = saved_model_predictor.SavedModelPredictor(
          export_dir=self._export_dir,
          signature_def_key=signature_def_key)

      output_tensor_name = predictor.fetch_tensors['outputs'].name
      self.assertRegexpMatches(
          output_tensor_name,
          signature_def_key,
          msg='Unexpected fetch tensor.')

      output = predictor({'x': x, 'y': y})['outputs']
      self.assertAlmostEqual(
          expected_output, output, places=3,
          msg='Failed for signature "{}." '
          'Got output {} for x = {} and y = {}'.format(
              signature_def_key, output, x, y))

  def testSpecifiedSignature(self):
    """Test prediction with spedicified signature definition."""
    np.random.seed(4444)
    for key, op in KEYS_AND_OPS:
      x = np.random.rand()
      y = np.random.rand()
      expected_output = op(x, y)

      inputs = {
          'x': meta_graph_pb2.TensorInfo(
              name='inputs/x:0',
              dtype=types_pb2.DT_FLOAT,
              tensor_shape=tensor_shape_pb2.TensorShapeProto()),
          'y': meta_graph_pb2.TensorInfo(
              name='inputs/y:0',
              dtype=types_pb2.DT_FLOAT,
              tensor_shape=tensor_shape_pb2.TensorShapeProto())}
      outputs = {
          key: meta_graph_pb2.TensorInfo(
              name='outputs/{}:0'.format(key),
              dtype=types_pb2.DT_FLOAT,
              tensor_shape=tensor_shape_pb2.TensorShapeProto())}
      signature_def = signature_def_utils.build_signature_def(
          inputs=inputs,
          outputs=outputs,
          method_name='tensorflow/serving/regress')
      predictor = saved_model_predictor.SavedModelPredictor(
          export_dir=self._export_dir,
          signature_def=signature_def)

      output_tensor_name = predictor.fetch_tensors[key].name
      self.assertRegexpMatches(
          output_tensor_name,
          key,
          msg='Unexpected fetch tensor.')

      output = predictor({'x': x, 'y': y})[key]
      self.assertAlmostEqual(
          expected_output, output, places=3,
          msg='Failed for signature "{}". '
          'Got output {} for x = {} and y = {}'.format(key, output, x, y))

  def testSpecifiedTensors(self):
    """Test prediction with spedicified `Tensor`s."""
    np.random.seed(987)
    for key, op in KEYS_AND_OPS:
      x = np.random.rand()
      y = np.random.rand()
      expected_output = op(x, y)
      input_names = {'x': 'inputs/x:0',
                     'y': 'inputs/y:0'}
      output_names = {key: 'outputs/{}:0'.format(key)}
      predictor = saved_model_predictor.SavedModelPredictor(
          export_dir=self._export_dir,
          input_names=input_names,
          output_names=output_names)

      output_tensor_name = predictor.fetch_tensors[key].name
      self.assertRegexpMatches(
          output_tensor_name,
          key,
          msg='Unexpected fetch tensor.')

      output = predictor({'x': x, 'y': y})[key]
      self.assertAlmostEqual(
          expected_output, output, places=3,
          msg='Failed for signature "{}". '
          'Got output {} for x = {} and y = {}'.format(key, output, x, y))

  def testBadTagsFail(self):
    """Test that predictor construction fails for bad tags."""
    bad_tags_regex = ('.* could not be found in SavedModel')
    with self.assertRaisesRegexp(RuntimeError, bad_tags_regex):
      _ = saved_model_predictor.SavedModelPredictor(
          export_dir=self._export_dir,
          tags=('zomg, bad, tags'))

  def testSpecifiedGraph(self):
    """Test that the predictor remembers a specified `Graph`."""
    g = ops.Graph()
    predictor = saved_model_predictor.SavedModelPredictor(
        export_dir=self._export_dir,
        graph=g)
    self.assertEqual(predictor.graph, g)


if __name__ == '__main__':
  test.main()