Neuron TensorFlow Serving

TensorFlow Serving は、運用環境において構築したモデルをAPIとして提供できるサーバ機能です。 Neuron TensorFlow Serving では、通常の TensorFlow Serving と同じ API を使用します。ただしSaved Model は Inferentia 用にコンパイルする必要があり、 また通常の TensorFlow Serving とは異なる実行バイナリ (/usr/local/bin/tensorflow_model_server_neuron) を使用します。

tensorflow-model-server-neuron パッケージは、章3で既にインストール済みです。

次の例は、サーバ機能のために Saved Model を準備する方法と、Saved Modelを利用した推論の実行例です。

Step 1. コンパイル済み SavedModel の準備

TensorFlow Serving 用のディレクトリ構造を準備します。章4.2でコンパイルされた ResNet50 モデルを、ディレクトリ/1に保存します。

mkdir -p resnet50_inf1_serve
cp -rf resnet50_neuron resnet50_inf1_serve/1

Step 2. Saved Model をサービス提供

以下のように、tensorflow_model_server_neuron バイナリを使用して、SavedModel をサービス提供します。

tensorflow_model_server_neuron --model_name=resnet50_inf1_serve --model_base_path=$(pwd)/resnet50_inf1_serve/ --port=8500

コンパイル済みのモデルは、サーバによって推論の準備のために Inferentia DRAM 内にステージングされます。 以下のように表示されるとサーバの準備は完了です。

Running gRPC ModelServer at 0.0.0.0:8500 ...

Step 3. 新規ターミナルの起動

モデルサーバへの推論リクエストを生成するために、別のターミナルを起動し、作成済みの仮想環境を立ち上げます。

source activate aws_neuron_tensorflow_p36

Step 4. モデルサーバへの推論リクエストを生成

GRPC 経由での推論を実行します。以下のサンプルクライアントスクリプトをtfs_client.py というファイル名で保存します。

import numpy as np
import grpc
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.keras.applications.resnet50 import decode_predictions
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc

tf.keras.backend.set_image_data_format('channels_last')

if __name__ == '__main__':
    channel = grpc.insecure_channel('localhost:8500')
    stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)
    img_file = tf.keras.utils.get_file(
        "./kitten_small.jpg",
        "https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg")
    img = image.load_img(img_file, target_size=(224, 224))
    img_array = preprocess_input(image.img_to_array(img)[None, ...])
    request = predict_pb2.PredictRequest()
    request.model_spec.name = 'resnet50_inf1_serve'
    request.inputs['input'].CopyFrom(
        tf.contrib.util.make_tensor_proto(img_array, shape=img_array.shape))
    result = stub.Predict(request)
    prediction = tf.make_ndarray(result.outputs['output'])
    print(decode_predictions(prediction))

クライアントスクリプトを実行します。

python tfs_client.py

想定される出力は以下の通りです。

[[('n02123045', 'tabby', 0.684492), ('n02127052', 'lynx', 0.1263369), ('n02123159', 'tiger_cat', 0.086898394), ('n02124075', 'Egyptian_cat', 0.067847595), ('n02128757', 'snow_leopard', 0.00977607)]]

Step 5. クリーンアップ

最初のターミナルで、Ctrl-C を押して TensorFlow Serving プロセスを終了してください。