Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
keras-team
GitHub Repository: keras-team/keras-io
Path: blob/master/examples/keras_recipes/tf_serving.py
3507 views
1
"""
2
Title: Serving TensorFlow models with TFServing
3
Author: [Dimitre Oliveira](https://www.linkedin.com/in/dimitre-oliveira-7a1a0113a/)
4
Date created: 2023/01/02
5
Last modified: 2023/01/02
6
Description: How to serve TensorFlow models with TensorFlow Serving.
7
Accelerator: None
8
"""
9
10
"""
11
## Introduction
12
13
Once you build a machine learning model, the next step is to serve it.
14
You may want to do that by exposing your model as an endpoint service.
15
There are many frameworks that you can use to do that, but the TensorFlow
16
ecosystem has its own solution called
17
[TensorFlow Serving](https://www.tensorflow.org/tfx/guide/serving).
18
19
From the TensorFlow Serving
20
[GitHub page](https://github.com/tensorflow/serving):
21
22
> TensorFlow Serving is a flexible, high-performance serving system for machine
23
learning models, designed for production environments. It deals with the
24
inference aspect of machine learning, taking models after training and
25
managing their lifetimes, providing clients with versioned access via a
26
high-performance, reference-counted lookup table. TensorFlow Serving provides
27
out-of-the-box integration with TensorFlow models, but can be easily extended
28
to serve other types of models and data."
29
30
To note a few features:
31
32
- It can serve multiple models, or multiple versions of the same model
33
simultaneously
34
- It exposes both gRPC as well as HTTP inference endpoints
35
- It allows deployment of new model versions without changing any client code
36
- It supports canarying new versions and A/B testing experimental models
37
- It adds minimal latency to inference time due to efficient, low-overhead
38
implementation
39
- It features a scheduler that groups individual inference requests into batches
40
for joint execution on GPU, with configurable latency controls
41
- It supports many servables: Tensorflow models, embeddings, vocabularies,
42
feature transformations and even non-Tensorflow-based machine learning models
43
44
This guide creates a simple [MobileNet](https://arxiv.org/abs/1704.04861)
45
model using the [Keras applications API](https://keras.io/api/applications/),
46
and then serves it with [TensorFlow Serving](https://www.tensorflow.org/tfx/guide/serving).
47
The focus is on TensorFlow Serving, rather than the modeling and training in
48
TensorFlow.
49
50
> Note: you can find a Colab notebook with the full working code at
51
[this link](https://colab.research.google.com/drive/1nwuIJa4so1XzYU0ngq8tX_-SGTO295Mu?usp=sharing).
52
"""
53
"""
54
## Dependencies
55
"""
56
57
import os
58
59
os.environ["KERAS_BACKEND"] = "tensorflow"
60
61
import json
62
import shutil
63
import requests
64
import numpy as np
65
import tensorflow as tf
66
import keras
67
import matplotlib.pyplot as plt
68
69
"""
70
## Model
71
72
Here we load a pre-trained [MobileNet](https://arxiv.org/abs/1704.04861)
73
from the [Keras applications](https://keras.io/api/applications/), this is the
74
model that we are going to serve.
75
"""
76
77
model = keras.applications.MobileNet()
78
79
"""
80
## Preprocessing
81
82
Most models don't work out of the box on raw data, they usually require some
83
kind of preprocessing step to adjust the data to the model requirements,
84
in the case of this MobileNet we can see from its
85
[API page](https://keras.io/api/applications/mobilenet/) that it requires
86
three basic steps for its input images:
87
88
- Pixel values normalized to the `[0, 1]` range
89
- Pixel values scaled to the `[-1, 1]` range
90
- Images with the shape of `(224, 224, 3)` meaning `(height, width, channels)`
91
92
We can do all of that with the following function:
93
"""
94
95
96
def preprocess(image, mean=0.5, std=0.5, shape=(224, 224)):
97
"""Scale, normalize and resizes images."""
98
image = image / 255.0 # Scale
99
image = (image - mean) / std # Normalize
100
image = tf.image.resize(image, shape) # Resize
101
return image
102
103
104
"""
105
**A note regarding preprocessing and postprocessing using the "keras.applications" API**
106
107
All models that are available at the [Keras applications](https://keras.io/api/applications/)
108
API also provide `preprocess_input` and `decode_predictions` functions, those
109
functions are respectively responsible for the preprocessing and postprocessing
110
of each model, and already contains all the logic necessary for those steps.
111
That is the recommended way to process inputs and outputs when using Keras
112
applications models.
113
For this guide, we are not using them to present the advantages of custom
114
signatures in a clearer way.
115
"""
116
117
118
"""
119
## Postprocessing
120
121
In the same context most models output values that need extra processing to
122
meet the user requirements, for instance, the user does not want to know the
123
logits values for each class given an image, what the user wants is to know
124
from which class it belongs. For our model, this translates to the following
125
transformations on top of the model outputs:
126
127
- Get the index of the class with the highest prediction
128
- Get the name of the class from that index
129
"""
130
131
# Download human-readable labels for ImageNet.
132
imagenet_labels_url = (
133
"https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt"
134
)
135
response = requests.get(imagenet_labels_url)
136
# Skipping background class
137
labels = [x for x in response.text.split("\n") if x != ""][1:]
138
# Convert the labels to the TensorFlow data format
139
tf_labels = tf.constant(labels, dtype=tf.string)
140
141
142
def postprocess(prediction, labels=tf_labels):
143
"""Convert from probs to labels."""
144
indices = tf.argmax(prediction, axis=-1) # Index with highest prediction
145
label = tf.gather(params=labels, indices=indices) # Class name
146
return label
147
148
149
"""
150
Now let's download a banana picture and see how everything comes together.
151
"""
152
153
response = requests.get("https://i.imgur.com/j9xCCzn.jpeg", stream=True)
154
155
with open("banana.jpeg", "wb") as f:
156
shutil.copyfileobj(response.raw, f)
157
158
sample_img = plt.imread("./banana.jpeg")
159
print(f"Original image shape: {sample_img.shape}")
160
print(f"Original image pixel range: ({sample_img.min()}, {sample_img.max()})")
161
plt.imshow(sample_img)
162
plt.show()
163
164
preprocess_img = preprocess(sample_img)
165
print(f"Preprocessed image shape: {preprocess_img.shape}")
166
print(
167
f"Preprocessed image pixel range: ({preprocess_img.numpy().min()},",
168
f"{preprocess_img.numpy().max()})",
169
)
170
171
batched_img = tf.expand_dims(preprocess_img, axis=0)
172
batched_img = tf.cast(batched_img, tf.float32)
173
print(f"Batched image shape: {batched_img.shape}")
174
175
model_outputs = model(batched_img)
176
print(f"Model output shape: {model_outputs.shape}")
177
print(f"Predicted class: {postprocess(model_outputs)}")
178
179
"""
180
## Save the model
181
182
To load our trained model into TensorFlow Serving, we first need to save it in
183
[SavedModel](https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/saved_model)
184
format. This will create a protobuf file in a well-defined directory hierarchy,
185
and will include a version number.
186
[TensorFlow Serving](https://www.tensorflow.org/tfx/guide/serving) allows us
187
to select which version of a model, or "servable" we want to use when we make
188
inference requests. Each version will be exported to a different sub-directory
189
under the given path.
190
"""
191
192
model_dir = "./model"
193
model_version = 1
194
model_export_path = f"{model_dir}/{model_version}"
195
196
tf.saved_model.save(
197
model,
198
export_dir=model_export_path,
199
)
200
201
print(f"SavedModel files: {os.listdir(model_export_path)}")
202
203
"""
204
## Examine your saved model
205
206
We'll use the command line utility `saved_model_cli` to look at the
207
[MetaGraphDefs](https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/MetaGraphDef)
208
(the models) and [SignatureDefs](https://www.tensorflow.org/tfx/serving/signature_defs)
209
(the methods you can call) in our SavedModel. See
210
[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)
211
in the TensorFlow Guide.
212
"""
213
214
215
"""shell
216
saved_model_cli show --dir {model_export_path} --tag_set serve --signature_def serving_default
217
"""
218
219
"""
220
That tells us a lot about our model! For instance, we can see that its inputs
221
have a 4D shape `(-1, 224, 224, 3)` which means
222
`(batch_size, height, width, channels)`, also note that this model requires a
223
specific image shape `(224, 224, 3)` this means that we may need to reshape
224
our images before sending them to the model. We can also see that the model's
225
outputs have a `(-1, 1000)` shape which are the logits for the 1000 classes of
226
the [ImageNet](https://www.image-net.org) dataset.
227
228
This information doesn't tell us everything, like the fact that the pixel
229
values needs to be in the `[-1, 1]` range, but it's a great start.
230
231
## Serve your model with TensorFlow Serving
232
233
### Install TFServing
234
235
We're preparing to install TensorFlow Serving using
236
[Aptitude](https://wiki.debian.org/Aptitude) since this Colab runs in a Debian
237
environment. We'll add the `tensorflow-model-server` package to the list of
238
packages that Aptitude knows about. Note that we're running as root.
239
240
241
> Note: This example is running TensorFlow Serving natively, but [you can also
242
run it in a Docker container](https://www.tensorflow.org/tfx/serving/docker),
243
which is one of the easiest ways to get started using TensorFlow Serving.
244
245
```shell
246
wget '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'
247
dpkg -i tensorflow-model-server-universal_2.8.0_all.deb
248
```
249
"""
250
251
"""
252
### Start running TensorFlow Serving
253
254
This is where we start running TensorFlow Serving and load our model. After it
255
loads, we can start making inference requests using REST. There are some
256
important parameters:
257
258
- `port`: The port that you'll use for gRPC requests.
259
- `rest_api_port`: The port that you'll use for REST requests.
260
- `model_name`: You'll use this in the URL of REST requests. It can be
261
anything.
262
- `model_base_path`: This is the path to the directory where you've saved your
263
model.
264
265
Check the [TFServing API reference](https://github.com/tensorflow/serving/blob/master/tensorflow_serving/model_servers/main.cc)
266
to get all the parameters available.
267
"""
268
269
# Environment variable with the path to the model
270
os.environ["MODEL_DIR"] = f"{model_dir}"
271
272
"""
273
```shell
274
%%bash --bg
275
nohup tensorflow_model_server \
276
--port=8500 \
277
--rest_api_port=8501 \
278
--model_name=model \
279
--model_base_path=$MODEL_DIR >server.log 2>&1
280
```
281
282
```shell
283
# We can check the logs to the server to help troubleshooting
284
!cat server.log
285
```
286
outputs:
287
```
288
[warn] getaddrinfo: address family for nodename not supported
289
[evhttp_server.cc : 245] NET_LOG: Entering the event loop ...
290
```
291
292
```shell
293
# Now we can check if tensorflow is in the active services
294
!sudo lsof -i -P -n | grep LISTEN
295
```
296
outputs:
297
```
298
node 7 root 21u IPv6 19100 0t0 TCP *:8080 (LISTEN)
299
kernel_ma 34 root 7u IPv4 18874 0t0 TCP 172.28.0.12:6000 (LISTEN)
300
colab-fil 63 root 5u IPv4 17975 0t0 TCP *:3453 (LISTEN)
301
colab-fil 63 root 6u IPv6 17976 0t0 TCP *:3453 (LISTEN)
302
jupyter-n 81 root 6u IPv4 18092 0t0 TCP 172.28.0.12:9000 (LISTEN)
303
python3 101 root 23u IPv4 18252 0t0 TCP 127.0.0.1:44915 (LISTEN)
304
python3 132 root 3u IPv4 20548 0t0 TCP 127.0.0.1:15264 (LISTEN)
305
python3 132 root 4u IPv4 20549 0t0 TCP 127.0.0.1:37977 (LISTEN)
306
python3 132 root 9u IPv4 20662 0t0 TCP 127.0.0.1:40689 (LISTEN)
307
tensorflo 1101 root 5u IPv4 35543 0t0 TCP *:8500 (LISTEN)
308
tensorflo 1101 root 12u IPv4 35548 0t0 TCP *:8501 (LISTEN)
309
```
310
311
## Make a request to your model in TensorFlow Serving
312
313
Now let's create the JSON object for an inference request, and see how well
314
our model classifies it:
315
316
### REST API
317
318
#### Newest version of the servable
319
320
We'll send a predict request as a POST to our server's REST endpoint, and pass
321
it as an example. We'll ask our server to give us the latest version of our
322
servable by not specifying a particular version.
323
"""
324
325
data = json.dumps(
326
{
327
"signature_name": "serving_default",
328
"instances": batched_img.numpy().tolist(),
329
}
330
)
331
url = "http://localhost:8501/v1/models/model:predict"
332
333
334
def predict_rest(json_data, url):
335
json_response = requests.post(url, data=json_data)
336
response = json.loads(json_response.text)
337
rest_outputs = np.array(response["predictions"])
338
return rest_outputs
339
340
341
"""
342
```python
343
rest_outputs = predict_rest(data, url)
344
345
print(f"REST output shape: {rest_outputs.shape}")
346
print(f"Predicted class: {postprocess(rest_outputs)}")
347
```
348
349
outputs:
350
```
351
REST output shape: (1, 1000)
352
Predicted class: [b'banana']
353
```
354
355
### gRPC API
356
357
[gRPC](https://grpc.io/) is based on the Remote Procedure Call (RPC) model and
358
is a technology for implementing RPC APIs that uses HTTP 2.0 as its underlying
359
transport protocol. gRPC is usually preferred for low-latency, highly scalable,
360
and distributed systems. If you wanna know more about the REST vs gRPC
361
tradeoffs, checkout
362
[this article](https://cloud.google.com/blog/products/api-management/understanding-grpc-openapi-and-rest-and-when-to-use-them).
363
"""
364
365
import grpc
366
367
# Create a channel that will be connected to the gRPC port of the container
368
channel = grpc.insecure_channel("localhost:8500")
369
370
"""
371
```shell
372
pip install -q tensorflow_serving_api
373
```
374
375
```python
376
from tensorflow_serving.apis import predict_pb2, prediction_service_pb2_grpc
377
378
# Create a stub made for prediction
379
# This stub will be used to send the gRPCrequest to the TF Server
380
stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)
381
```
382
"""
383
384
# Get the serving_input key
385
loaded_model = tf.saved_model.load(model_export_path)
386
input_name = list(
387
loaded_model.signatures["serving_default"].structured_input_signature[1].keys()
388
)[0]
389
390
391
"""
392
```python
393
def predict_grpc(data, input_name, stub):
394
# Create a gRPC request made for prediction
395
request = predict_pb2.PredictRequest()
396
397
# Set the name of the model, for this use case it is "model"
398
request.model_spec.name = "model"
399
400
# Set which signature is used to format the gRPC query
401
# here the default one "serving_default"
402
request.model_spec.signature_name = "serving_default"
403
404
# Set the input as the data
405
# tf.make_tensor_proto turns a TensorFlow tensor into a Protobuf tensor
406
request.inputs[input_name].CopyFrom(tf.make_tensor_proto(data.numpy().tolist()))
407
408
# Send the gRPC request to the TF Server
409
result = stub.Predict(request)
410
return result
411
412
413
grpc_outputs = predict_grpc(batched_img, input_name, stub)
414
grpc_outputs = np.array([grpc_outputs.outputs['predictions'].float_val])
415
416
print(f"gRPC output shape: {grpc_outputs.shape}")
417
print(f"Predicted class: {postprocess(grpc_outputs)}")
418
```
419
420
outputs:
421
```
422
gRPC output shape: (1, 1000)
423
Predicted class: [b'banana']
424
```
425
"""
426
427
"""
428
## Custom signature
429
430
Note that for this model we always need to preprocess and postprocess all
431
samples to get the desired output, this can get quite tricky if are
432
maintaining and serving several models developed by a large team, and each one
433
of them might require different processing logic.
434
435
TensorFlow allows us to customize the model graph to embed all of that
436
processing logic, which makes model serving much easier, there are different
437
ways to achieve this, but since we are going to server the models using
438
TFServing we can customize the model graph straight into the serving signature.
439
440
We can just use the following code to export the same model that already
441
contains the preprocessing and postprocessing logic as the default signature,
442
this allows this model to make predictions on raw data.
443
"""
444
445
446
def export_model(model, labels):
447
@tf.function(input_signature=[tf.TensorSpec([None, None, None, 3], tf.float32)])
448
def serving_fn(image):
449
processed_img = preprocess(image)
450
probs = model(processed_img)
451
label = postprocess(probs)
452
return {"label": label}
453
454
return serving_fn
455
456
457
model_sig_version = 2
458
model_sig_export_path = f"{model_dir}/{model_sig_version}"
459
460
tf.saved_model.save(
461
model,
462
export_dir=model_sig_export_path,
463
signatures={"serving_default": export_model(model, labels)},
464
)
465
466
"""shell
467
saved_model_cli show --dir {model_sig_export_path} --tag_set serve --signature_def serving_default
468
"""
469
470
"""
471
Note that this model has a different signature, its input is still 4D but now
472
with a `(-1, -1, -1, 3)` shape, which means that it supports images with any
473
height and width size. Its output also has a different shape, it no longer
474
outputs the 1000-long logits.
475
476
We can test the model's prediction using a specific signature using this API
477
below:
478
"""
479
480
batched_raw_img = tf.expand_dims(sample_img, axis=0)
481
batched_raw_img = tf.cast(batched_raw_img, tf.float32)
482
483
loaded_model = tf.saved_model.load(model_sig_export_path)
484
loaded_model.signatures["serving_default"](**{"image": batched_raw_img})
485
486
"""
487
## Prediction using a particular version of the servable
488
489
Now let's specify a particular version of our servable. Note that when we
490
saved the model with a custom signature we used a different folder, the first
491
model was saved in folder `/1` (version 1), and the one with a custom
492
signature in folder `/2` (version 2). By default, TFServing will serve all
493
models that share the same base parent folder.
494
495
### REST API
496
"""
497
498
data = json.dumps(
499
{
500
"signature_name": "serving_default",
501
"instances": batched_raw_img.numpy().tolist(),
502
}
503
)
504
url_sig = "http://localhost:8501/v1/models/model/versions/2:predict"
505
506
"""
507
```python
508
print(f"REST output shape: {rest_outputs.shape}")
509
print(f"Predicted class: {rest_outputs}")
510
```
511
512
outputs:
513
```
514
REST output shape: (1,)
515
Predicted class: ['banana']
516
```
517
518
### gRPC API
519
"""
520
521
"""
522
```python
523
channel = grpc.insecure_channel("localhost:8500")
524
stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)
525
```
526
"""
527
528
input_name = list(
529
loaded_model.signatures["serving_default"].structured_input_signature[1].keys()
530
)[0]
531
532
"""
533
```python
534
grpc_outputs = predict_grpc(batched_raw_img, input_name, stub)
535
grpc_outputs = np.array([grpc_outputs.outputs['label'].string_val])
536
537
print(f"gRPC output shape: {grpc_outputs.shape}")
538
print(f"Predicted class: {grpc_outputs}")
539
```
540
541
outputs:
542
543
```
544
gRPC output shape: (1, 1)
545
Predicted class: [[b'banana']]
546
```
547
548
## Additional resources
549
550
- [Colab notebook with the full working code](https://colab.research.google.com/drive/1nwuIJa4so1XzYU0ngq8tX_-SGTO295Mu?usp=sharing)
551
- [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)
552
- [TensorFlow Serving playlist - TensorFlow YouTube channel](https://www.youtube.com/playlist?list=PLQY2H8rRoyvwHdpVQVohY7-qcYf2s1UYK)
553
"""
554
555