-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtriton_utils.py
324 lines (276 loc) · 12.3 KB
/
triton_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
_____________________________________________________________________________
This file contains functions for Triton inference pipeline
_____________________________________________________________________________
"""
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from icecream import ic
import sys
import torch
import numpy as np
from attrdict import AttrDict
from functools import partial
import tritonclient.grpc.model_config_pb2 as mc
from tritonclient.utils import InferenceServerException
from tritonclient.utils import triton_to_np_dtype
import tritonclient.grpc as grpcclient
import tritonclient.http as httpclient
if sys.version_info >= (3, 0):
import queue
else:
import Queue as queue
# Callback function used for async_stream_infer()
def completion_callback(user_data, result, error):
# passing error raise and handling out
user_data._completed_requests.put((result, error))
def parse_model(model_metadata, model_config):
"""
Check the configuration of a model to make sure it meets the
requirements for an image classification network (as expected by
this client)
"""
if len(model_metadata.inputs) != 1:
raise Exception("expecting 1 input, got {}".format(
len(model_metadata.inputs)))
if len(model_metadata.outputs) != 2:
raise Exception("expecting 2 output, got {}".format(
len(model_metadata.outputs)))
if len(model_config.input) != 1:
raise Exception(
"expecting 1 input in model configuration, got {}".format(
len(model_config.input)))
input_metadata = model_metadata.inputs[0]
input_config = model_config.input[0]
output_metadata = model_metadata.outputs[0]
if output_metadata.datatype != "FP32":
raise Exception("expecting output datatype to be FP32, model '" +
model_metadata.name + "' output type is " +
output_metadata.datatype)
# Output is expected to be a vector. But allow any number of
# dimensions as long as all but 1 is size 1 (e.g. { 10 }, { 1, 10
# }, { 10, 1, 1 } are all ok). Ignore the batch dimension if there
# is one.
output_batch_dim = (model_config.max_batch_size > 0)
non_one_cnt = 0
for dim in output_metadata.shape:
if output_batch_dim:
output_batch_dim = False
elif dim > 1:
non_one_cnt += 1
if non_one_cnt > 1:
raise Exception("expecting model output to be a vector")
# Model input must have 3 dims, either CHW or HWC (not counting
# the batch dimension), either CHW or HWC
input_batch_dim = (model_config.max_batch_size > 0)
expected_input_dims = 3 + (1 if input_batch_dim else 0)
if len(input_metadata.shape) != expected_input_dims:
raise Exception(
"expecting input to have {} dimensions, model '{}' input has {}".
format(expected_input_dims, model_metadata.name,
len(input_metadata.shape)))
if type(input_config.format) == str:
FORMAT_ENUM_TO_INT = dict(mc.ModelInput.Format.items())
input_config.format = FORMAT_ENUM_TO_INT[input_config.format]
if input_config.format == mc.ModelInput.FORMAT_NHWC:
h = input_metadata.shape[1 if input_batch_dim else 0]
w = input_metadata.shape[2 if input_batch_dim else 1]
c = input_metadata.shape[3 if input_batch_dim else 2]
else:
c = input_metadata.shape[1 if input_batch_dim else 0]
h = input_metadata.shape[2 if input_batch_dim else 1]
w = input_metadata.shape[3 if input_batch_dim else 2]
return (model_config.max_batch_size, input_metadata.name,
output_metadata.name, c, h, w, input_config.format,
input_metadata.datatype)
def postprocess(results, output_name, batch_size, batching):
"""
Post-process results to show classifications.
"""
lst_out = list()
output_array = results.as_numpy(output_name)
return output_array
def convert_http_metadata_config(_metadata, _config):
_model_metadata = AttrDict(_metadata)
_model_config = AttrDict(_config)
return _model_metadata, _model_config
# UserData for Triton server
class UserData:
def __init__(self):
self._completed_requests = queue.Queue()
def requestGenerator(batched_image_data, input_name, output_name, dtype, FLAGS):
protocol = FLAGS.protocol.lower()
if protocol == "grpc":
client = grpcclient
else:
client = httpclient
# Set the input data
inputs = [client.InferInput(input_name, batched_image_data.shape, dtype)]
inputs[0].set_data_from_numpy(batched_image_data)
outputs = [
client.InferRequestedOutput(output_name)#, class_count=FLAGS.classes)
]
yield inputs, outputs, FLAGS.model_name, FLAGS.model_version
def triton_requester(FLAGS, img_resized):
if FLAGS.streaming and FLAGS.protocol.lower() != "grpc":
raise Exception("Streaming is only allowed with gRPC protocol")
try:
if FLAGS.protocol.lower() == "grpc":
# Create gRPC client for communicating with the server
triton_client = grpcclient.InferenceServerClient(
url=FLAGS.url, verbose=FLAGS.verbose)
else:
# Specify large enough concurrency to handle the
# the number of requests.
concurrency = 20 if FLAGS.async_set else 1
triton_client = httpclient.InferenceServerClient(
url=FLAGS.url, verbose=FLAGS.verbose, concurrency=concurrency)
except Exception as e:
print("client creation failed: " + str(e))
sys.exit(1)
# Make sure the model matches our requirements, and get some
# properties of the model that we need for preprocessing
try:
model_metadata = triton_client.get_model_metadata(
model_name=FLAGS.model_name, model_version=FLAGS.model_version)
except InferenceServerException as e:
print("failed to retrieve the metadata: " + str(e))
sys.exit(1)
# print(1,model_metadata)
try:
model_config = triton_client.get_model_config(
model_name=FLAGS.model_name, model_version=FLAGS.model_version)
except InferenceServerException as e:
print("failed to retrieve the config: " + str(e))
sys.exit(1)
if FLAGS.protocol.lower() == "grpc":
model_config = model_config.config
else:
model_metadata, model_config = convert_http_metadata_config(
model_metadata, model_config)
max_batch_size, input_name, output_name, c, h, w, format, dtype = parse_model(
model_metadata, model_config)
# Preprocess the images into input data according to model
# requirements
image_data = []
img_resized = np.array(img_resized)
image_data.append(img_resized)
# Send requests of FLAGS.batch_size images. If the number of
# images isn't an exact multiple of FLAGS.batch_size then just
# start over with the first images until the batch is filled.
requests = []
responses = []
result_filenames = []
request_ids = []
image_idx = 0
last_request = False
user_data = UserData()
# Holds the handles to the ongoing HTTP async requests.
async_requests = []
sent_count = 0
if FLAGS.streaming:
triton_client.start_stream(partial(completion_callback, user_data))
while not last_request:
repeated_image_data = []
for idx in range(FLAGS.batch_size):
repeated_image_data.append(image_data[image_idx])
image_idx = (image_idx + 1) % len(image_data)
if image_idx == 0:
last_request = True
if max_batch_size > 0:
batched_image_data = np.stack(repeated_image_data, axis=0)
else:
batched_image_data = repeated_image_data[0]
# Send request
try:
for inputs, outputs, model_name, model_version in requestGenerator(
batched_image_data, input_name, output_name, dtype, FLAGS):
sent_count += 1
if FLAGS.streaming:
triton_client.async_stream_infer(
FLAGS.model_name,
inputs,
request_id=str(sent_count),
model_version=FLAGS.model_version,
outputs=outputs)
elif FLAGS.async_set:
if FLAGS.protocol.lower() == "grpc":
triton_client.async_infer(
FLAGS.model_name,
inputs,
partial(completion_callback, user_data),
request_id=str(sent_count),
model_version=FLAGS.model_version,
outputs=outputs)
else:
async_requests.append(
triton_client.async_infer(
FLAGS.model_name,
inputs,
request_id=str(sent_count),
model_version=FLAGS.model_version,
outputs=outputs))
else:
responses.append(
triton_client.infer(FLAGS.model_name,
inputs,
request_id=str(sent_count),
model_version=FLAGS.model_version,
outputs=outputs))
except InferenceServerException as e:
print("inference failed: " + str(e))
if FLAGS.streaming:
triton_client.stop_stream()
sys.exit(1)
if FLAGS.streaming:
triton_client.stop_stream()
if FLAGS.protocol.lower() == "grpc":
if FLAGS.streaming or FLAGS.async_set:
processed_count = 0
while processed_count < sent_count:
(results, error) = user_data._completed_requests.get()
processed_count += 1
if error is not None:
print("inference failed: " + str(error))
sys.exit(1)
responses.append(results)
else:
if FLAGS.async_set:
# Collect results from the ongoing async requests
# for HTTP Async requests.
for async_request in async_requests:
responses.append(async_request.get_result())
for response in responses:
if FLAGS.protocol.lower() == "grpc":
this_id = response.get_response().id
else:
this_id = response.get_response()["id"]
print("Request {}, batch size {}".format(this_id, FLAGS.batch_size))
tmp = postprocess(response, output_name, FLAGS.batch_size, max_batch_size > 0)
y = torch.from_numpy(tmp)
return y