Path: blob/master/examples/keras_recipes/tf_serving.py
3507 views
"""1Title: Serving TensorFlow models with TFServing2Author: [Dimitre Oliveira](https://www.linkedin.com/in/dimitre-oliveira-7a1a0113a/)3Date created: 2023/01/024Last modified: 2023/01/025Description: How to serve TensorFlow models with TensorFlow Serving.6Accelerator: None7"""89"""10## Introduction1112Once you build a machine learning model, the next step is to serve it.13You may want to do that by exposing your model as an endpoint service.14There are many frameworks that you can use to do that, but the TensorFlow15ecosystem has its own solution called16[TensorFlow Serving](https://www.tensorflow.org/tfx/guide/serving).1718From the TensorFlow Serving19[GitHub page](https://github.com/tensorflow/serving):2021> TensorFlow Serving is a flexible, high-performance serving system for machine22learning models, designed for production environments. It deals with the23inference aspect of machine learning, taking models after training and24managing their lifetimes, providing clients with versioned access via a25high-performance, reference-counted lookup table. TensorFlow Serving provides26out-of-the-box integration with TensorFlow models, but can be easily extended27to serve other types of models and data."2829To note a few features:3031- It can serve multiple models, or multiple versions of the same model32simultaneously33- It exposes both gRPC as well as HTTP inference endpoints34- It allows deployment of new model versions without changing any client code35- It supports canarying new versions and A/B testing experimental models36- It adds minimal latency to inference time due to efficient, low-overhead37implementation38- It features a scheduler that groups individual inference requests into batches39for joint execution on GPU, with configurable latency controls40- It supports many servables: Tensorflow models, embeddings, vocabularies,41feature transformations and even non-Tensorflow-based machine learning models4243This guide creates a simple [MobileNet](https://arxiv.org/abs/1704.04861)44model using the [Keras applications API](https://keras.io/api/applications/),45and then serves it with [TensorFlow Serving](https://www.tensorflow.org/tfx/guide/serving).46The focus is on TensorFlow Serving, rather than the modeling and training in47TensorFlow.4849> Note: you can find a Colab notebook with the full working code at50[this link](https://colab.research.google.com/drive/1nwuIJa4so1XzYU0ngq8tX_-SGTO295Mu?usp=sharing).51"""52"""53## Dependencies54"""5556import os5758os.environ["KERAS_BACKEND"] = "tensorflow"5960import json61import shutil62import requests63import numpy as np64import tensorflow as tf65import keras66import matplotlib.pyplot as plt6768"""69## Model7071Here we load a pre-trained [MobileNet](https://arxiv.org/abs/1704.04861)72from the [Keras applications](https://keras.io/api/applications/), this is the73model that we are going to serve.74"""7576model = keras.applications.MobileNet()7778"""79## Preprocessing8081Most models don't work out of the box on raw data, they usually require some82kind of preprocessing step to adjust the data to the model requirements,83in the case of this MobileNet we can see from its84[API page](https://keras.io/api/applications/mobilenet/) that it requires85three basic steps for its input images:8687- Pixel values normalized to the `[0, 1]` range88- Pixel values scaled to the `[-1, 1]` range89- Images with the shape of `(224, 224, 3)` meaning `(height, width, channels)`9091We can do all of that with the following function:92"""939495def preprocess(image, mean=0.5, std=0.5, shape=(224, 224)):96"""Scale, normalize and resizes images."""97image = image / 255.0 # Scale98image = (image - mean) / std # Normalize99image = tf.image.resize(image, shape) # Resize100return image101102103"""104**A note regarding preprocessing and postprocessing using the "keras.applications" API**105106All models that are available at the [Keras applications](https://keras.io/api/applications/)107API also provide `preprocess_input` and `decode_predictions` functions, those108functions are respectively responsible for the preprocessing and postprocessing109of each model, and already contains all the logic necessary for those steps.110That is the recommended way to process inputs and outputs when using Keras111applications models.112For this guide, we are not using them to present the advantages of custom113signatures in a clearer way.114"""115116117"""118## Postprocessing119120In the same context most models output values that need extra processing to121meet the user requirements, for instance, the user does not want to know the122logits values for each class given an image, what the user wants is to know123from which class it belongs. For our model, this translates to the following124transformations on top of the model outputs:125126- Get the index of the class with the highest prediction127- Get the name of the class from that index128"""129130# Download human-readable labels for ImageNet.131imagenet_labels_url = (132"https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt"133)134response = requests.get(imagenet_labels_url)135# Skipping background class136labels = [x for x in response.text.split("\n") if x != ""][1:]137# Convert the labels to the TensorFlow data format138tf_labels = tf.constant(labels, dtype=tf.string)139140141def postprocess(prediction, labels=tf_labels):142"""Convert from probs to labels."""143indices = tf.argmax(prediction, axis=-1) # Index with highest prediction144label = tf.gather(params=labels, indices=indices) # Class name145return label146147148"""149Now let's download a banana picture and see how everything comes together.150"""151152response = requests.get("https://i.imgur.com/j9xCCzn.jpeg", stream=True)153154with open("banana.jpeg", "wb") as f:155shutil.copyfileobj(response.raw, f)156157sample_img = plt.imread("./banana.jpeg")158print(f"Original image shape: {sample_img.shape}")159print(f"Original image pixel range: ({sample_img.min()}, {sample_img.max()})")160plt.imshow(sample_img)161plt.show()162163preprocess_img = preprocess(sample_img)164print(f"Preprocessed image shape: {preprocess_img.shape}")165print(166f"Preprocessed image pixel range: ({preprocess_img.numpy().min()},",167f"{preprocess_img.numpy().max()})",168)169170batched_img = tf.expand_dims(preprocess_img, axis=0)171batched_img = tf.cast(batched_img, tf.float32)172print(f"Batched image shape: {batched_img.shape}")173174model_outputs = model(batched_img)175print(f"Model output shape: {model_outputs.shape}")176print(f"Predicted class: {postprocess(model_outputs)}")177178"""179## Save the model180181To load our trained model into TensorFlow Serving, we first need to save it in182[SavedModel](https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/saved_model)183format. This will create a protobuf file in a well-defined directory hierarchy,184and will include a version number.185[TensorFlow Serving](https://www.tensorflow.org/tfx/guide/serving) allows us186to select which version of a model, or "servable" we want to use when we make187inference requests. Each version will be exported to a different sub-directory188under the given path.189"""190191model_dir = "./model"192model_version = 1193model_export_path = f"{model_dir}/{model_version}"194195tf.saved_model.save(196model,197export_dir=model_export_path,198)199200print(f"SavedModel files: {os.listdir(model_export_path)}")201202"""203## Examine your saved model204205We'll use the command line utility `saved_model_cli` to look at the206[MetaGraphDefs](https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/MetaGraphDef)207(the models) and [SignatureDefs](https://www.tensorflow.org/tfx/serving/signature_defs)208(the methods you can call) in our SavedModel. See209[this discussion of the SavedModel CLI](https://github.com/tensorflow/docs/blob/master/site/en/r1/guide/saved_model.md#cli-to-inspect-and-execute-savedmodel)210in the TensorFlow Guide.211"""212213214"""shell215saved_model_cli show --dir {model_export_path} --tag_set serve --signature_def serving_default216"""217218"""219That tells us a lot about our model! For instance, we can see that its inputs220have a 4D shape `(-1, 224, 224, 3)` which means221`(batch_size, height, width, channels)`, also note that this model requires a222specific image shape `(224, 224, 3)` this means that we may need to reshape223our images before sending them to the model. We can also see that the model's224outputs have a `(-1, 1000)` shape which are the logits for the 1000 classes of225the [ImageNet](https://www.image-net.org) dataset.226227This information doesn't tell us everything, like the fact that the pixel228values needs to be in the `[-1, 1]` range, but it's a great start.229230## Serve your model with TensorFlow Serving231232### Install TFServing233234We're preparing to install TensorFlow Serving using235[Aptitude](https://wiki.debian.org/Aptitude) since this Colab runs in a Debian236environment. We'll add the `tensorflow-model-server` package to the list of237packages that Aptitude knows about. Note that we're running as root.238239240> Note: This example is running TensorFlow Serving natively, but [you can also241run it in a Docker container](https://www.tensorflow.org/tfx/serving/docker),242which is one of the easiest ways to get started using TensorFlow Serving.243244```shell245wget 'http://storage.googleapis.com/tensorflow-serving-apt/pool/tensorflow-model-server-universal-2.8.0/t/tensorflow-model-server-universal/tensorflow-model-server-universal_2.8.0_all.deb'246dpkg -i tensorflow-model-server-universal_2.8.0_all.deb247```248"""249250"""251### Start running TensorFlow Serving252253This is where we start running TensorFlow Serving and load our model. After it254loads, we can start making inference requests using REST. There are some255important parameters:256257- `port`: The port that you'll use for gRPC requests.258- `rest_api_port`: The port that you'll use for REST requests.259- `model_name`: You'll use this in the URL of REST requests. It can be260anything.261- `model_base_path`: This is the path to the directory where you've saved your262model.263264Check the [TFServing API reference](https://github.com/tensorflow/serving/blob/master/tensorflow_serving/model_servers/main.cc)265to get all the parameters available.266"""267268# Environment variable with the path to the model269os.environ["MODEL_DIR"] = f"{model_dir}"270271"""272```shell273%%bash --bg274nohup tensorflow_model_server \275--port=8500 \276--rest_api_port=8501 \277--model_name=model \278--model_base_path=$MODEL_DIR >server.log 2>&1279```280281```shell282# We can check the logs to the server to help troubleshooting283!cat server.log284```285outputs:286```287[warn] getaddrinfo: address family for nodename not supported288[evhttp_server.cc : 245] NET_LOG: Entering the event loop ...289```290291```shell292# Now we can check if tensorflow is in the active services293!sudo lsof -i -P -n | grep LISTEN294```295outputs:296```297node 7 root 21u IPv6 19100 0t0 TCP *:8080 (LISTEN)298kernel_ma 34 root 7u IPv4 18874 0t0 TCP 172.28.0.12:6000 (LISTEN)299colab-fil 63 root 5u IPv4 17975 0t0 TCP *:3453 (LISTEN)300colab-fil 63 root 6u IPv6 17976 0t0 TCP *:3453 (LISTEN)301jupyter-n 81 root 6u IPv4 18092 0t0 TCP 172.28.0.12:9000 (LISTEN)302python3 101 root 23u IPv4 18252 0t0 TCP 127.0.0.1:44915 (LISTEN)303python3 132 root 3u IPv4 20548 0t0 TCP 127.0.0.1:15264 (LISTEN)304python3 132 root 4u IPv4 20549 0t0 TCP 127.0.0.1:37977 (LISTEN)305python3 132 root 9u IPv4 20662 0t0 TCP 127.0.0.1:40689 (LISTEN)306tensorflo 1101 root 5u IPv4 35543 0t0 TCP *:8500 (LISTEN)307tensorflo 1101 root 12u IPv4 35548 0t0 TCP *:8501 (LISTEN)308```309310## Make a request to your model in TensorFlow Serving311312Now let's create the JSON object for an inference request, and see how well313our model classifies it:314315### REST API316317#### Newest version of the servable318319We'll send a predict request as a POST to our server's REST endpoint, and pass320it as an example. We'll ask our server to give us the latest version of our321servable by not specifying a particular version.322"""323324data = json.dumps(325{326"signature_name": "serving_default",327"instances": batched_img.numpy().tolist(),328}329)330url = "http://localhost:8501/v1/models/model:predict"331332333def predict_rest(json_data, url):334json_response = requests.post(url, data=json_data)335response = json.loads(json_response.text)336rest_outputs = np.array(response["predictions"])337return rest_outputs338339340"""341```python342rest_outputs = predict_rest(data, url)343344print(f"REST output shape: {rest_outputs.shape}")345print(f"Predicted class: {postprocess(rest_outputs)}")346```347348outputs:349```350REST output shape: (1, 1000)351Predicted class: [b'banana']352```353354### gRPC API355356[gRPC](https://grpc.io/) is based on the Remote Procedure Call (RPC) model and357is a technology for implementing RPC APIs that uses HTTP 2.0 as its underlying358transport protocol. gRPC is usually preferred for low-latency, highly scalable,359and distributed systems. If you wanna know more about the REST vs gRPC360tradeoffs, checkout361[this article](https://cloud.google.com/blog/products/api-management/understanding-grpc-openapi-and-rest-and-when-to-use-them).362"""363364import grpc365366# Create a channel that will be connected to the gRPC port of the container367channel = grpc.insecure_channel("localhost:8500")368369"""370```shell371pip install -q tensorflow_serving_api372```373374```python375from tensorflow_serving.apis import predict_pb2, prediction_service_pb2_grpc376377# Create a stub made for prediction378# This stub will be used to send the gRPCrequest to the TF Server379stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)380```381"""382383# Get the serving_input key384loaded_model = tf.saved_model.load(model_export_path)385input_name = list(386loaded_model.signatures["serving_default"].structured_input_signature[1].keys()387)[0]388389390"""391```python392def predict_grpc(data, input_name, stub):393# Create a gRPC request made for prediction394request = predict_pb2.PredictRequest()395396# Set the name of the model, for this use case it is "model"397request.model_spec.name = "model"398399# Set which signature is used to format the gRPC query400# here the default one "serving_default"401request.model_spec.signature_name = "serving_default"402403# Set the input as the data404# tf.make_tensor_proto turns a TensorFlow tensor into a Protobuf tensor405request.inputs[input_name].CopyFrom(tf.make_tensor_proto(data.numpy().tolist()))406407# Send the gRPC request to the TF Server408result = stub.Predict(request)409return result410411412grpc_outputs = predict_grpc(batched_img, input_name, stub)413grpc_outputs = np.array([grpc_outputs.outputs['predictions'].float_val])414415print(f"gRPC output shape: {grpc_outputs.shape}")416print(f"Predicted class: {postprocess(grpc_outputs)}")417```418419outputs:420```421gRPC output shape: (1, 1000)422Predicted class: [b'banana']423```424"""425426"""427## Custom signature428429Note that for this model we always need to preprocess and postprocess all430samples to get the desired output, this can get quite tricky if are431maintaining and serving several models developed by a large team, and each one432of them might require different processing logic.433434TensorFlow allows us to customize the model graph to embed all of that435processing logic, which makes model serving much easier, there are different436ways to achieve this, but since we are going to server the models using437TFServing we can customize the model graph straight into the serving signature.438439We can just use the following code to export the same model that already440contains the preprocessing and postprocessing logic as the default signature,441this allows this model to make predictions on raw data.442"""443444445def export_model(model, labels):446@tf.function(input_signature=[tf.TensorSpec([None, None, None, 3], tf.float32)])447def serving_fn(image):448processed_img = preprocess(image)449probs = model(processed_img)450label = postprocess(probs)451return {"label": label}452453return serving_fn454455456model_sig_version = 2457model_sig_export_path = f"{model_dir}/{model_sig_version}"458459tf.saved_model.save(460model,461export_dir=model_sig_export_path,462signatures={"serving_default": export_model(model, labels)},463)464465"""shell466saved_model_cli show --dir {model_sig_export_path} --tag_set serve --signature_def serving_default467"""468469"""470Note that this model has a different signature, its input is still 4D but now471with a `(-1, -1, -1, 3)` shape, which means that it supports images with any472height and width size. Its output also has a different shape, it no longer473outputs the 1000-long logits.474475We can test the model's prediction using a specific signature using this API476below:477"""478479batched_raw_img = tf.expand_dims(sample_img, axis=0)480batched_raw_img = tf.cast(batched_raw_img, tf.float32)481482loaded_model = tf.saved_model.load(model_sig_export_path)483loaded_model.signatures["serving_default"](**{"image": batched_raw_img})484485"""486## Prediction using a particular version of the servable487488Now let's specify a particular version of our servable. Note that when we489saved the model with a custom signature we used a different folder, the first490model was saved in folder `/1` (version 1), and the one with a custom491signature in folder `/2` (version 2). By default, TFServing will serve all492models that share the same base parent folder.493494### REST API495"""496497data = json.dumps(498{499"signature_name": "serving_default",500"instances": batched_raw_img.numpy().tolist(),501}502)503url_sig = "http://localhost:8501/v1/models/model/versions/2:predict"504505"""506```python507print(f"REST output shape: {rest_outputs.shape}")508print(f"Predicted class: {rest_outputs}")509```510511outputs:512```513REST output shape: (1,)514Predicted class: ['banana']515```516517### gRPC API518"""519520"""521```python522channel = grpc.insecure_channel("localhost:8500")523stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)524```525"""526527input_name = list(528loaded_model.signatures["serving_default"].structured_input_signature[1].keys()529)[0]530531"""532```python533grpc_outputs = predict_grpc(batched_raw_img, input_name, stub)534grpc_outputs = np.array([grpc_outputs.outputs['label'].string_val])535536print(f"gRPC output shape: {grpc_outputs.shape}")537print(f"Predicted class: {grpc_outputs}")538```539540outputs:541542```543gRPC output shape: (1, 1)544Predicted class: [[b'banana']]545```546547## Additional resources548549- [Colab notebook with the full working code](https://colab.research.google.com/drive/1nwuIJa4so1XzYU0ngq8tX_-SGTO295Mu?usp=sharing)550- [Train and serve a TensorFlow model with TensorFlow Serving - TensorFlow blog](https://www.tensorflow.org/tfx/tutorials/serving/rest_simple#make_a_request_to_your_model_in_tensorflow_serving)551- [TensorFlow Serving playlist - TensorFlow YouTube channel](https://www.youtube.com/playlist?list=PLQY2H8rRoyvwHdpVQVohY7-qcYf2s1UYK)552"""553554555