Frozen Network w/Universal Sentence Encoder throws `table not initialized` error in Tensorflow serving call
Problem
Tensorflow serving throws and error that tables are not initialized when freezing a trained graph and quantizing weights despite adding init_all_tables arg to freeze graph method.
Setup
example.py
import os
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from configs import config
from sklearn.utils import check_X_y
class Example:
def __init__(self,
model_name="Example",
embeddings="https://tfhub.dev/google/universal-sentence-encoder/1",
model_dir=".",
num_epochs=10,
batch_size=32,
trainable_embeddings=False,
learning_rate=0.001,
hidden_units=[256, 128, 64],
max_steps=10000,
embedding_column="text",
trainable_embedding=False,
tf_random_seed=143,
log_step_count_steps=100,
save_summary_steps=100,
save_checkpoints_steps=100,
**kwargs):
self.hparams = tf.contrib.training.HParams(
num_epochs=num_epochs,
batch_size=batch_size,
trainable_embeddings=trainable_embeddings,
learning_rate=learning_rate,
hidden_units=hidden_units,
max_steps=max_steps,
embedding_column=embedding_column,
trainable_embedding=trainable_embedding)
self.run_config = tf.estimator.RunConfig(
model_dir=os.path.join(model_dir, model_name),
tf_random_seed=tf_random_seed,
log_step_count_steps=log_step_count_steps,
save_summary_steps=save_summary_steps,
save_checkpoints_steps=save_checkpoints_steps,
**kwargs)
self.embeddings = embeddings
self.feature_columns = self._create_feature_column()
def train(self, X, y, labels):
self.labels = labels
self.hparams.num_classes = len(self.labels)
_X, _y = check_X_y(X, y, ensure_2d=False)
features = {self.hparams.embedding_column: X}
self.estimator = self._create_estimator()
self.estimator.train(input_fn=lambda: self._input_fn(
features=features,
labels=y,
mode=tf.estimator.ModeKeys.TRAIN))
def _create_estimator(self):
feature_columns = self._create_feature_column()
optimizer = tf.train.AdamOptimizer(learning_rate=self.hparams.learning_rate)
return tf.estimator.DNNClassifier(
feature_columns=feature_columns,
n_classes=self.hparams.num_classes,
hidden_units=self.hparams.hidden_units,
label_vocabulary=self.labels,
optimizer=optimizer,
config=self.run_config)
def _create_feature_column(self):
text_embeding_column = hub.text_embedding_column(
self.hparams.embedding_column,
self.embeddings,
trainable=self.hparams.trainable_embedding)
feature_columns = [text_embeding_column]
return feature_columns
def _input_fn(self, features, labels, mode=tf.estimator.ModeKeys.TRAIN):
buffer_size = 2 * self.hparams.batch_size + 1
shuffle = True if mode == tf.estimator.ModeKeys.TRAIN else False
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
if shuffle:
dataset = dataset.shuffle(buffer_size)
dataset = dataset.apply(
tf.contrib.data.batch_and_drop_remainder(
self.hparams.batch_size))
dataset = dataset.repeat(self.hparams.num_epochs)
dataset = dataset.prefetch(buffer_size)
return dataset
def serving_input_receiver_fn(self):
receiver_tensor = {
self.hparams.embedding_column: tf.placeholder(
dtype=tf.string, shape=[None])}
return tf.estimator.export.ServingInputReceiver(
receiver_tensor, receiver_tensor)
def export_saved_model(self, name="model"):
self.estimator.export_savedmodel(
name,
serving_input_receiver_fn=self.serving_input_receiver_fn)
def get_data(self):
X = np.array([
["what is the weather like today"],
["call mom please"],
["do I have any events on my calendar today"],
])
y = np.array(["weather", "contacts", "events"])
labels = list(set(y.tolist()))
return X, y, labels
def main(argv=None):
tf.logging.set_verbosity(tf.logging.INFO)
ex = Example()
x, y, l = ex.get_data()
ex.train(x, y, l)
ex.export_saved_model()
if __name__ == "__main__":
main()
freeze_and_transform_graph.py
import tensorflow as tf
from tensorflow.python.util import compat as _compat
from tensorflow.saved_model import simple_save
from tensorflow.saved_model import signature_constants
from tensorflow.saved_model import tag_constants
from tensorflow.tools.graph_transforms import TransformGraph
from tensorflow.contrib.meta_graph_transform.meta_graph_transform import (
meta_graph_transform)
with tf.Session() as sess:
meta_graph_def = tf.saved_model.loader.load(
sess,
[tag_constants.SERVING],
"./1535638911")
new_meta_def = meta_graph_transform(
base_meta_graph_def=meta_graph_def,
input_names=["Placeholder"],
output_names=["dnn/head/predictions/probabilities", "init_all_tables"],
transforms=["freeze_graph", "quantize_weights"],
tags=[tag_constants.SERVING],
checkpoint_path="/home/ubuntu/tf-serving-example/Example/model.ckpt-0")
assert new_meta_def.graph_def
with tf.Graph().as_default() as graph:
tf.import_graph_def(new_meta_def.graph_def)
in_tensor = graph.get_tensor_by_name("import/Placeholder:0")
out_tensor = graph.get_tensor_by_name("import/dnn/head/predictions/probabilities:0")
simple_save(
sess,
"./new",
inputs={"inputs": in_tensor},
outputs={"outputs": out_tensor})
client.py
import numpy as np
import tensorflow as tf
from grpc.beta import implementations
from argparse import ArgumentParser
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2
from tensorflow_serving.apis import classification_pb2
class Client:
def run(self, options):
text = "take me to the nearest grocery store".encode()
# establish a connection
channel = implementations.insecure_channel(options.host, options.port)
stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
request = predict_pb2.PredictRequest()
request.model_spec.name = options.model
request.model_spec.signature_name = options.signature_name
request.inputs['inputs'].CopyFrom(tf.make_tensor_proto([text]))
response = stub.Predict(request, 10.0)
print(response)
def parse_args(parser):
parser.add_argument("--text", type=str)
parser.add_argument("--host", type=str, default="localhost")
parser.add_argument("--port", type=int, default=8500)
parser.add_argument("--model", type=str, default="Example")
parser.add_argument(
"--signature-model", type=str,
default="serving_default", dest="signature_name")
options = parser.parse_args()
return options
if __name__ == "__main__":
parser = ArgumentParser(description="")
options = parse_args(parser)
client = Client()
client.run(options)
Execute
$ python ./client.py
Errors
client
Traceback (most recent call last):
File "./universal_grpc.py", line 50, in <module>
client.run(options)
File "./universal_grpc.py", line 27, in run
response = stub.Predict(request, 10.0)
File "/home/ubuntu/tf-serving-example/.env-py27/local/lib/python2.7/site-packages/grpc/_channel.py", line 514, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/home/ubuntu/tf-serving-example/.env-py27/local/lib/python2.7/site-packages/grpc/_channel.py", line 448, in _end_unary_response_blocking
raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
status = StatusCode.FAILED_PRECONDITION
details = "Table not initialized.
[[Node: import/dnn/input_from_feature_columns/input_layer/text_hub_module_embedding/module_apply_default/string_to_index_Lookup/hash_table_Lookup = LookupTableFindV2[Tin=DT_STRING, Tout=DT_INT64, _output_shapes=[[?]], _device="/job:localhost/replica:0/task:0/device:CPU:0"](import/dnn/input_from_feature_columns/input_layer/text_hub_module_embedding/module/string_to_index/hash_table, import/dnn/input_from_feature_columns/input_layer/text_hub_module_embedding/module_apply_default/compound_bigrams/boolean_mask/Gather, import/dnn/input_from_feature_columns/input_layer/text_hub_module_embedding/module_apply_default/string_to_index/hash_table/Const)]]"
debug_error_string = "{"created":"@1535643979.173766887","description":"Error received from peer","file":"src/core/lib/surface/call.cc","file_line":1095,"grpc_message":"Table not initialized.\n\t [[Node: import/dnn/input_from_feature_columns/input_layer/text_hub_module_embedding/module_apply_default/string_to_index_Lookup/hash_table_Lookup = LookupTableFindV2[Tin=DT_STRING, Tout=DT_INT64, _output_shapes=[[?]], _device="/job:localhost/replica:0/task:0/device:CPU:0"](import/dnn/input_from_feature_columns/input_layer/text_hub_module_embedding/module/string_to_index/hash_table, import/dnn/input_from_feature_columns/input_layer/text_hub_module_embedding/module_apply_default/compound_bigrams/boolean_mask/Gather, import/dnn/input_from_feature_columns/input_layer/text_hub_module_embedding/module_apply_default/string_to_index/hash_table/Const)]]","grpc_status":9}"
server
W external/org_tensorflow/tensorflow/core/framework/op_kernel.cc:1318] OP_REQUIRES failed at lookup_table_op.cc:675 : Failed precondition: Table not initialized.
Env
$ lscpu
...
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 4
On-line CPU(s) list: 0-3
Thread(s) per core: 2
Core(s) per socket: 2
Socket(s): 1
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 79
Model name: Intel(R) Xeon(R) CPU E5-2686 v4 @ 2.30GHz
$ lsb_release -a
...
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 16.04.5 LTS
Release: 16.04
Codename: xenial
Related
Related question on stackoverflow
You are using tf.import_graph_def(new_meta_def.graph_def) to create your final serving graph. Importing a graph def and not a meta_graph makes it lose all collections, in particular the init_tables collection, so that op never ends up being executed the serving graph init_op.
Additionally you are also dropping the ASSET_FILENAMES collection, so the exported saved model is not hermetic and will likely fail.
PS: Since there is no bug in hub or action to take from hub side, I am closing the issue.
@andresusanopinto - opened this new issue that references this. I notice that this error persists even if the meta_graph is imported.