serving icon indicating copy to clipboard operation
serving copied to clipboard

Elmo embeddings crash TF-Serving

Open m4nd31br0t opened this issue 8 years ago • 2 comments

Problem

A trained network that uses elmo embeddings crashes tensorflow serving.

Requirements

Dockerfile

FROM ubuntu:16.04

RUN apt-get update && apt-get install -y \
        curl \
        libcurl3-dev \
        unzip \
        wget \
        && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

RUN TEMP_DEB="$(mktemp)" \
    && wget -O "$TEMP_DEB" 'http://storage.googleapis.com/tensorflow-serving-apt/pool/tensorflow-model-server-1.9.0/t/tensorflow-model-server/tensorflow-model-server_1.9.0_all.deb' \
    && dpkg -i "$TEMP_DEB" \
    && rm -f "$TEMP_DEB"

# gRPC port
EXPOSE 8500
# REST API port
EXPOSE 8501

# Serve the model when the container starts
CMD tensorflow_model_server \
  --port=8500 \
  --rest_api_port=8501 \
  --model_name="$MODEL_NAME" \
  --model_base_path="$MODEL_PATH"

fake_network.py

import tensorflow as tf
import tensorflow_hub as hub
import numpy as np

class FakeNetwork:
    def __init__(self, batch_size=32, num_epochs=100):
        self.hparams = tf.contrib.training.HParams(
            batch_size=batch_size,
            num_epochs=num_epochs
        )
    
    def _fake_data(self):
        text_input = np.array(
            [
                'hi there how are you',
                'what up',
                'what does the whether look like today'
            ]
        )

        idx_input = np.array(
            [
                5, 2, 7
            ]
        )

        emb_input = np.array([
          [
            [15, 13, 0, 0, 0, 0, 0],
            [3, 15, 10, 14, 10, 0, 0],
            [15, 8, 5, 0, 0, 0, 0],
            [6, 14, 10, 0, 0, 0, 0],
            [16, 8, 11, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0]
          ],
          [
            [5, 15, 6, 3, 0, 0, 0],
            [11, 2, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0]
          ],
          [
            [5, 15, 6, 3, 0, 0, 0],
            [9, 8, 10, 4, 0, 0, 0],
            [3, 15, 10, 0, 0, 0, 0],
            [5, 15, 10, 3, 15, 10, 14],
            [7, 8, 8, 12, 0, 0, 0],
            [7, 13, 12, 10, 0, 0, 0],
            [3, 8, 9, 6, 16, 0, 0]
          ]
        ])
        labels = np.random.randn(3).reshape((3, 1)).astype(np.float32)
        return {"text": text_input, "idx": idx_input, "emb": emb_input}, labels

    def _input_fn(self, features, labels, mode):
        dataset = tf.data.Dataset.from_tensor_slices((features, labels))
        dataset = dataset.repeat(self.hparams.num_epochs)
        dataset = dataset.prefetch(1024)
        dataset = dataset.batch(self.hparams.batch_size)
        iterator = dataset.make_one_shot_iterator()
        features, labels = iterator.get_next()
        return features, labels

    def _model_fn(self, features, labels, mode):
        with tf.variable_scope("chars"):
            with tf.device("/cpu:0"):
                c_embs = tf.get_variable(
                    name="c_embs",
                    dtype=tf.float32, 
                    shape=[17, 10],
                    trainable=True)

            char = tf.nn.embedding_lookup(c_embs, features['emb'])
            char_out = tf.reshape(char, [-1, 7*7*10])

        with tf.variable_scope("elmo"):
            words = tf.string_split(features['text'])
            dense_words = tf.sparse_to_dense(
                sparse_indices=words.indices,
                sparse_values=words.values,
                default_value="",
                output_shape=[self.hparams.batch_size, 7])

            elmo = hub.Module("https://tfhub.dev/google/elmo/2", trainable=False)
            elmo_emb = elmo(
                inputs={"tokens": dense_words,
                        "sequence_len": tf.cast(features['idx'], tf.int32)},
                signature="tokens",
                as_dict=True)['elmo'] 

            weights = tf.get_variable(
                name='w', dtype=tf.float32,
                shape=[7*1024, 1],
                initializer=tf.random_normal_initializer())

        elmo_rs = tf.reshape(elmo_emb, [-1, 7*1024])
        logits = tf.matmul(elmo_rs, weights)
        print(logits.get_shape().as_list())

        if mode == tf.estimator.ModeKeys.PREDICT:
            predictions = {
                "logits": logits,
            }
            export_outputs = {"prediction": tf.estimator.export.PredictOutput(predictions)}

            return tf.estimator.EstimatorSpec(
                mode=mode,
                predictions=predictions,
                export_outputs=export_outputs)

        loss = tf.square(tf.subtract(labels, logits))
        loss = tf.reduce_mean(loss)

        if mode == tf.estimator.ModeKeys.TRAIN:
            opt = tf.train.AdamOptimizer(learning_rate=1e-3)
            train_op = opt.minimize(loss=loss, global_step=tf.train.get_global_step())
            return tf.estimator.EstimatorSpec(
                mode=mode,
                loss=loss,
                train_op=train_op)


def main(argv=None):
    tf.logging.set_verbosity(tf.logging.INFO)
    fn = FakeNetwork(batch_size=3)
    features_train, labels_train = fn._fake_data()
    config = tf.estimator.RunConfig(
        model_dir="/tmp/fake",
        log_step_count_steps=100,
        save_checkpoints_steps=100,
        save_summary_steps=100)
    estimator = tf.estimator.Estimator(model_fn=fn._model_fn, config=config)
    estimator.train(input_fn=lambda: fn._input_fn(features_train, labels_train, mode=tf.estimator.ModeKeys.TRAIN))


if __name__ == "__main__":
    main()

save.py

import tensorflow as tf
from fake_network import FakeNetwork


tf.logging.set_verbosity(tf.logging.INFO)

fn = FakeNetwork()

config = tf.estimator.RunConfig(
    model_dir="/tmp/fake",
    log_step_count_steps=100,
    save_checkpoints_steps=100,
    save_summary_steps=100)
estimator = tf.estimator.Estimator(model_fn=fn._model_fn, config=config)

def serving_input_receiver_fn():
    feature_spec = {
        "text": tf.placeholder(dtype=tf.string, shape=[None]),
        "idx": tf.placeholder(dtype=tf.int64, shape=[None]),
        "emb": tf.placeholder(dtype=tf.int64, shape=[None, 7, 7]),
    }
    return tf.estimator.export.ServingInputReceiver(feature_spec, feature_spec)

estimator.export_savedmodel(
    "./data/models",
    serving_input_receiver_fn=serving_input_receiver_fn)

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 __init__(self):
        pass

    def run(self, options):
        text = "hi there how are you".encode()
        idx = np.array([5]).astype(np.int64)
        emb = np.array([[[15, 13,  0,  0,  0,  0,  0],
                         [ 3, 15, 10, 14, 10,  0,  0],
                         [15,  8,  5,  0,  0,  0,  0],
                         [ 6, 14, 10,  0,  0,  0,  0],
                         [16,  8, 11,  0,  0,  0,  0],
                         [ 0,  0,  0,  0,  0,  0,  0],
                         [ 0,  0,  0,  0,  0,  0,  0]]]).astype(np.int64)

        # 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 = "prediction"

        request.inputs['text'].CopyFrom(tf.make_tensor_proto([text]))
        request.inputs['idx'].CopyFrom(tf.make_tensor_proto(idx))
        request.inputs['emb'].CopyFrom(tf.make_tensor_proto(emb))

        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="fake")

    options = parser.parse_args()
    return options


if __name__ == "__main__":
    parser = ArgumentParser(description="")
    options = parse_args(parser)
    client = Client()
    client.run(options)

Steps to Reproduce

$ mkdir -p models_for_serving/fake/1
$ docker build --rm -f Dockerfile -t tensorflow-serving-example:0.1 .
$ python ./fake_network.py
$ python ./save.py
$ cp -r ./data/models/1534131343/* ./models_for_serving/fake/1/
$ docker run --rm  -v ${PWD}/models_for_serving:/models \
  -e MODEL_NAME="fake" \
  -e MODEL_PATH="/models/fake" \
  -p 8500:8500  \
  -p 8501:8501  \
  --name tensorflow-server \
  tensorflow-serving-example:0.1
$ (python ./client.py >> log) 2>&1 | tee -a log

Errors

03:47:17.604604: I tensorflow_serving/core/loader_harness.cc:86] Successfully loaded servable version {name: fake version: 1}
03:47:17.606375: I tensorflow_serving/model_servers/main.cc:323] Running ModelServer at 0.0.0.0:8500 ...
[warn] getaddrinfo: address family for nodename not supported
[evhttp_server.cc : 235] RAW: Entering the event loop ...
03:47:17.607241: I tensorflow_serving/model_servers/main.cc:333] Exporting HTTP/REST API at:localhost:8501 ...

Segmentation fault (core dumped)
$ cat log
 This method will be removed in near future versions of TF Serving. Please switch to GA gRPC API in prediction_service_pb2_grpc.
  'prediction_service_pb2_grpc.', DeprecationWarning)
Traceback (most recent call last):
  File "./grpc_ner_client.py", line 63, in <module>
    client.run(options)
  File "./grpc_ner_client.py", line 40, in run
    response = stub.Predict(request, 10.0)
  File "/home/vagrant/gans/.venv/lib/python3.6/site-packages/grpc/_channel.py", line 514, in __call__
    return _end_unary_response_blocking(state, call, False, None)
  File "/home/vagrant/gans/.venv/lib/python3.6/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.UNAVAILABLE
        details = "Socket closed"
        debug_error_string = "{"created":"@1534129917.219040483","description":"Error received from peer","file":"src/core/lib/surface/call.cc","file_line":1095,"grpc_message":"Socket closed","grpc_status":14}"

Environment

requirements.txt

numpy==1.14.5
scipy==1.1.0
six==1.11.0
tensorboard==1.10.0
tensorflow==1.10.0
tensorflow-hub==0.1.1
tensorflow-serving-api==1.10.0

Docker version 18.06.0-ce, build 0ffa825

python3.6.4 gcc version 7.3.0 (Ubuntu 7.3.0-16ubuntu3)

Operating System: Ubuntu 18.04.1 LTS Kernel: Linux 4.15.0-30-generic Architecture: x86-64

Also addressed here: https://github.com/tensorflow/hub/issues/135

m4nd31br0t avatar Aug 14 '18 20:08 m4nd31br0t

Hmmm. A segmentation fault without a stack trace is going to be hard to debug. (I wonder if it could be a stack overflow.)

If you can do some digging to narrow it down to which part of the system is causing the problem, that would be helpful. In particular, is it (1) inside a TF op, (2) inside the TF-core framework e.g. the thing that schedules/executes the ops, or (3) inside TF-Serving's code that calls into TF-core. That will help route the bug report.

chrisolston avatar Aug 20 '18 17:08 chrisolston

https://github.com/tensorflow/hub/issues/135.

m4nd31br0t avatar Aug 22 '18 18:08 m4nd31br0t