Tensorflow Serving API

I already looked into the official Tensorflow Docker Model Server and managed to get it to work with CUDA support. The next step is to use this container to serve my own Keras-trained model.
Starting the Model Server
Export your Tensorflow model in the saved_model format and point the tensorflow-serving container to model path, e.g.:
docker run --gpus all -p 8501:8501 -p 8500:8500 --name tf-model-server \
--mount type=bind,source=$(pwd)/saved_model,target=/models \
-e MODEL_NAME=efficientv2b0_model -t tensorflow/serving:latest-gpu
The container uses the port 8500 for the GRPC api and port 8501 for the REST api.
ERROR
message: W tensorflow_serving/sources/storage_path/file_system_storage_path_source.cc:252] No versions of servable efficientv2b0_model found under base path /models/efficientv2b0_model. Did you forget to name your leaf directory as a number (eg. '/1/')?
The server expects the model path to have numbered sub directories - create a subdir inside the saved model directory named 1 and copy everything that Tensorflow saved into it. Subsequently, every time you retrain the model place the updated files in folders with incrementing numbers. The model server will automatically switch to the latest version for you.
saved_model tree -L 2
.
├── efficientv2b0_model
│ └── 1
│ ├── assets
│ ├── fingerprint.pb
│ ├── keras_metadata.pb
│ ├── saved_model.pb
│ └── variables
Verifying MetaGraph and Signature Definitions using saved_model_cli utility:
saved_model_cli show --dir ./saved_model/efficientv2b0_model/1/ --tag_set serve --signature_def serving_default
The given SavedModel SignatureDef contains the following input(s):
inputs['input_2'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 224, 224, 3)
name: serving_default_input_2:0
The given SavedModel SignatureDef contains the following output(s):
outputs['dense_2'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 48)
name: StatefulPartitionedCall:0
Method name is: tensorflow/serving/predict
Now the server starts successfully:
I tensorflow_serving/core/loader_harness.cc:95] Successfully loaded servable version {name: efficientv2b0_model version: 1}
I tensorflow_serving/model_servers/server_core.cc:486] Finished adding/updating models
I tensorflow_serving/model_servers/server.cc:118] Using InsecureServerCredentials
I tensorflow_serving/model_servers/server.cc:383] Profiler service is enabled
I tensorflow_serving/model_servers/server.cc:409] Running gRPC ModelServer at 0.0.0.0:8500 ...
[warn] getaddrinfo: address family for nodename not supported
I tensorflow_serving/model_servers/server.cc:430] Exporting HTTP/REST API at:localhost:8501 ...
[evhttp_server.cc : 245] NET_LOG: Entering the event loop ...
You can verify the REST API by retrieving your models metadata:
curl http://localhost:8501/v1/models/efficientv2b0_model/metadata
{
"model_spec":{
"name": "efficientv2b0_model",
"signature_name": "",
"version": "1"
}
...
Inference Server
REST API
For testing I will just start a simple python container and install my dependencies manually:
docker run --rm -ti --network host \
--mount type=bind,source=$(pwd)/api_request,target=/opt/app \
python:alpine /bin/ash
pip install pillow requests numpy
/opt/app/api_request/rest_request.py
import json
import numpy as np
from PIL import Image
import requests
labels = ['Gladiolus', 'Adenium', 'Alpinia_Purpurata', 'Alstroemeria', 'Amaryllis', 'Anthurium_Andraeanum', 'Antirrhinum', 'Aquilegia', 'Billbergia_Pyramidalis', 'Cattleya', 'Cirsium', 'Coccinia_Grandis', 'Crocus', 'Cyclamen', 'Dahlia', 'Datura_Metel', 'Dianthus_Barbatus', 'Digitalis', 'Echinacea_Purpurea', 'Echinops_Bannaticus', 'Fritillaria_Meleagris', 'Gaura', 'Gazania', 'Gerbera', 'Guzmania', 'Helianthus_Annuus', 'Iris_Pseudacorus', 'Leucanthemum', 'Malvaceae', 'Narcissus_Pseudonarcissus', 'Nerine', 'Nymphaea_Tetragona', 'Paphiopedilum', 'Passiflora', 'Pelargonium', 'Petunia', 'Platycodon_Grandiflorus', 'Plumeria', 'Poinsettia', 'Primula', 'Protea_Cynaroides', 'Rose', 'Rudbeckia', 'Strelitzia_Reginae', 'Tropaeolum_Majus', 'Tussilago', 'Viola', 'Zantedeschia_Aethiopica']
url1 = 'http://localhost:8501/v1/models/efficientv2b0_model:predict'
test_img1 = "/opt/app/snapshots/Viola_Tricolor.jpg"
test_img2 = "/opt/app/snapshots/Water_Lilly.jpg"
test_img3 = "/opt/app/snapshots/Strelitzia.jpg"
with Image.open (test_img2) as im:
preprocess_img = im.resize((224, 224))
batched_img = np.expand_dims(preprocess_img, axis=0)
batched_img = np.float32(batched_img)
data = json.dumps(
{"signature_name": "serving_default", "instances": batched_img.tolist()}
)
def predict_rest(json_data, url):
json_response = requests.post(url, data=json_data)
response = json.loads(json_response.text)
rest_outputs = np.array(response["predictions"])
return rest_outputs
# get prediction from efficientv2b0_model
rest_outputs = predict_rest(data, url1)
index = np.argmax(rest_outputs, axis=-1)[0] # Index with highest prediction
print("Prediction Results: EfficientV2B0")
print("Class probabilities: ", rest_outputs)
print("Predicted class: ", labels[index])
Executing the API request script /opt/app/api_request/rest_request.py inside the container will send 1 of 3 test images to the Tensorflow model API to retrieve a prediction:
python /opt/app/rest_request.py
Class probabilities: [[2.02370361e-13 5.45808624e-12 3.14568647e-17 4.50543422e-11
1.74268600e-09 2.22335952e-12 5.15965439e-12 2.28333991e-10
3.17855503e-18 3.61456546e-12 1.40493947e-17 1.46841839e-09
3.42843321e-13 2.59899831e-16 2.68869540e-12 1.53930095e-08
1.36200578e-12 6.06594810e-16 2.21194929e-14 5.79839779e-17
1.05216942e-12 6.55278443e-10 2.30210545e-13 6.22206000e-15
5.16498033e-16 1.86334712e-15 7.34451477e-09 9.92521278e-13
1.40660292e-08 5.47506651e-10 3.36575397e-16 1.56563315e-12
4.54165000e-09 4.07618221e-13 1.69515952e-05 1.08003778e-05
2.42027980e-08 1.65058089e-09 1.25125591e-13 4.95898966e-09
1.62804418e-16 5.25978046e-17 1.91704139e-14 2.93358880e-18
3.04848768e-08 1.63559369e-14 9.99972224e-01 2.25344784e-10]]
Predicted class: Viola
Serving Multiple Models
Ok, with this working I want to configure the Model Server to serve all the trained models.
tree -L 2 saved_model
saved_model
├── deit_model
│ └── 1
├── efficients_model
│ └── 1
├── efficientv2b0_model
│ └── 1
├── inception_model_model_ft
│ └── 1
├── mobilenet2_model_ft
│ └── 1
├── mobilenetv3L_model_ft