-
Notifications
You must be signed in to change notification settings - Fork 233
/
_client.py
executable file
·1936 lines (1765 loc) · 76.2 KB
/
_client.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright 2023, NVIDIA CORPORATION & AFFILIATES. 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.
import base64
import struct
import grpc
import rapidjson as json
from google.protobuf.json_format import MessageToJson
from tritonclient.grpc import service_pb2, service_pb2_grpc
from .._client import InferenceServerClientBase
from .._request import Request
from ._infer_result import InferResult
from ._infer_stream import _InferStream, _RequestIterator
from ._utils import (
_get_inference_request,
_grpc_compression_type,
get_cancelled_error,
get_error_grpc,
raise_error,
raise_error_grpc,
)
# Should be kept consistent with the value specified in
# src/core/constants.h, which specifies MAX_GRPC_MESSAGE_SIZE
# as INT32_MAX.
INT32_MAX = 2 ** (struct.Struct("i").size * 8 - 1) - 1
MAX_GRPC_MESSAGE_SIZE = INT32_MAX
class KeepAliveOptions:
"""A KeepAliveOptions object is used to encapsulate GRPC KeepAlive
related parameters for initiating an InferenceServerclient object.
See the https://github.com/grpc/grpc/blob/master/doc/keepalive.md
documentation for more information.
Parameters
----------
keepalive_time_ms: int
The period (in milliseconds) after which a keepalive ping is sent on
the transport. Default is INT32_MAX.
keepalive_timeout_ms: int
The period (in milliseconds) the sender of the keepalive ping waits
for an acknowledgement. If it does not receive an acknowledgment
within this time, it will close the connection. Default is 20000
(20 seconds).
keepalive_permit_without_calls: bool
Allows keepalive pings to be sent even if there are no calls in flight.
Default is False.
http2_max_pings_without_data: int
The maximum number of pings that can be sent when there is no
data/header frame to be sent. gRPC Core will not continue sending
pings if we run over the limit. Setting it to 0 allows sending pings
without such a restriction. Default is 2.
"""
def __init__(
self,
keepalive_time_ms=INT32_MAX,
keepalive_timeout_ms=20000,
keepalive_permit_without_calls=False,
http2_max_pings_without_data=2,
):
self.keepalive_time_ms = keepalive_time_ms
self.keepalive_timeout_ms = keepalive_timeout_ms
self.keepalive_permit_without_calls = keepalive_permit_without_calls
self.http2_max_pings_without_data = http2_max_pings_without_data
class CallContext:
"""This is a wrapper over grpc future call which can be used to
issue cancellation on an ongoing RPC call.
Parameters
----------
grpc_future : gRPC.Future
The future tracking gRPC call.
"""
def __init__(self, grpc_future):
self.__grpc_future = grpc_future
def cancel(self):
"""Issues cancellation on the underlying request."""
self.__grpc_future.cancel()
class InferenceServerClient(InferenceServerClientBase):
"""An InferenceServerClient object is used to perform any kind of
communication with the InferenceServer using gRPC protocol. Most
of the methods are thread-safe except start_stream, stop_stream
and async_stream_infer. Accessing a client stream with different
threads will cause undefined behavior.
Parameters
----------
url : str
The inference server URL, e.g. 'localhost:8001'.
verbose : bool
If True generate verbose output. Default value is False.
ssl : bool
If True use SSL encrypted secure channel. Default is False.
root_certificates : str
File holding the PEM-encoded root certificates as a byte
string, or None to retrieve them from a default location
chosen by gRPC runtime. The option is ignored if `ssl`
is False. Default is None.
private_key : str
File holding the PEM-encoded private key as a byte string,
or None if no private key should be used. The option is
ignored if `ssl` is False. Default is None.
certificate_chain : str
File holding PEM-encoded certificate chain as a byte string
to use or None if no certificate chain should be used. The
option is ignored if `ssl` is False. Default is None.
creds: grpc.ChannelCredentials
A grpc.ChannelCredentials object to use for the connection.
The ssl, root_certificates, private_key and certificate_chain
options will be ignored when using this option. Default is None.
keepalive_options: KeepAliveOptions
Object encapsulating various GRPC KeepAlive options. See
the class definition for more information. Default is None.
channel_args: List[Tuple]
List of Tuple pairs ("key", value) to be passed directly to the GRPC
channel as the channel_arguments. If this argument is provided, it is
expected the channel arguments are correct and complete, and the
keepalive_options parameter will be ignored since the corresponding
keepalive channel arguments can be set directly in this parameter. See
https://grpc.github.io/grpc/python/glossary.html#term-channel_arguments
for more details. Default is None.
Raises
------
Exception
If unable to create a client.
"""
def __init__(
self,
url,
verbose=False,
ssl=False,
root_certificates=None,
private_key=None,
certificate_chain=None,
creds=None,
keepalive_options=None,
channel_args=None,
):
super().__init__()
# Explicitly check "is not None" here to support passing an empty
# list to specify setting no channel arguments.
if channel_args is not None:
channel_opt = channel_args
else:
# Use GRPC KeepAlive client defaults if unspecified
if not keepalive_options:
keepalive_options = KeepAliveOptions()
# To specify custom channel_opt, see the channel_args parameter.
channel_opt = [
("grpc.max_send_message_length", MAX_GRPC_MESSAGE_SIZE),
("grpc.max_receive_message_length", MAX_GRPC_MESSAGE_SIZE),
("grpc.keepalive_time_ms", keepalive_options.keepalive_time_ms),
("grpc.keepalive_timeout_ms", keepalive_options.keepalive_timeout_ms),
(
"grpc.keepalive_permit_without_calls",
keepalive_options.keepalive_permit_without_calls,
),
(
"grpc.http2.max_pings_without_data",
keepalive_options.http2_max_pings_without_data,
),
]
if creds:
self._channel = grpc.secure_channel(url, creds, options=channel_opt)
elif ssl:
rc_bytes = pk_bytes = cc_bytes = None
if root_certificates is not None:
with open(root_certificates, "rb") as rc_fs:
rc_bytes = rc_fs.read()
if private_key is not None:
with open(private_key, "rb") as pk_fs:
pk_bytes = pk_fs.read()
if certificate_chain is not None:
with open(certificate_chain, "rb") as cc_fs:
cc_bytes = cc_fs.read()
creds = grpc.ssl_channel_credentials(
root_certificates=rc_bytes,
private_key=pk_bytes,
certificate_chain=cc_bytes,
)
self._channel = grpc.secure_channel(url, creds, options=channel_opt)
else:
self._channel = grpc.insecure_channel(url, options=channel_opt)
self._client_stub = service_pb2_grpc.GRPCInferenceServiceStub(self._channel)
self._verbose = verbose
self._stream = None
def _get_metadata(self, headers):
request = Request(headers)
self._call_plugin(request)
request_metadata = (
request.headers.items() if request.headers is not None else ()
)
return request_metadata
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def __del__(self):
self.close()
def close(self):
"""Close the client. Any future calls to server
will result in an Error.
"""
self.stop_stream()
self._channel.close()
def is_server_live(self, headers=None, client_timeout=None):
"""Contact the inference server and get liveness.
Parameters
----------
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
client_timeout: float
The maximum end-to-end time, in seconds, the request is allowed
to take. The client will abort request and raise
InferenceServerExeption with message "Deadline Exceeded" when the
specified time elapses. The default value is None which means
client will wait for the response from the server.
Returns
-------
bool
True if server is live, False if server is not live.
Raises
------
InferenceServerException
If unable to get liveness or has timed out.
"""
metadata = self._get_metadata(headers)
try:
request = service_pb2.ServerLiveRequest()
if self._verbose:
print("is_server_live, metadata {}\n{}".format(metadata, request))
response = self._client_stub.ServerLive(
request=request, metadata=metadata, timeout=client_timeout
)
if self._verbose:
print(response)
return response.live
except grpc.RpcError as rpc_error:
raise_error_grpc(rpc_error)
def is_server_ready(self, headers=None, client_timeout=None):
"""Contact the inference server and get readiness.
Parameters
----------
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
client_timeout: float
The maximum end-to-end time, in seconds, the request is allowed
to take. The client will abort request and raise
InferenceServerExeption with message "Deadline Exceeded" when the
specified time elapses. The default value is None which means
client will wait for the response from the server.
Returns
-------
bool
True if server is ready, False if server is not ready.
Raises
------
InferenceServerException
If unable to get readiness or has timed out.
"""
metadata = self._get_metadata(headers)
try:
request = service_pb2.ServerReadyRequest()
if self._verbose:
print("is_server_ready, metadata {}\n{}".format(metadata, request))
response = self._client_stub.ServerReady(
request=request, metadata=metadata, timeout=client_timeout
)
if self._verbose:
print(response)
return response.ready
except grpc.RpcError as rpc_error:
raise_error_grpc(rpc_error)
def is_model_ready(
self, model_name, model_version="", headers=None, client_timeout=None
):
"""Contact the inference server and get the readiness of specified model.
Parameters
----------
model_name: str
The name of the model to check for readiness.
model_version: str
The version of the model to check for readiness. The default value
is an empty string which means then the server will choose a version
based on the model and internal policy.
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
client_timeout: float
The maximum end-to-end time, in seconds, the request is allowed
to take. The client will abort request and raise
InferenceServerExeption with message "Deadline Exceeded" when the
specified time elapses. The default value is None which means
client will wait for the response from the server.
Returns
-------
bool
True if the model is ready, False if not ready.
Raises
------
InferenceServerException
If unable to get model readiness or has timed out.
"""
metadata = self._get_metadata(headers)
try:
if type(model_version) != str:
raise_error("model version must be a string")
request = service_pb2.ModelReadyRequest(
name=model_name, version=model_version
)
if self._verbose:
print("is_model_ready, metadata {}\n{}".format(metadata, request))
response = self._client_stub.ModelReady(
request=request, metadata=metadata, timeout=client_timeout
)
if self._verbose:
print(response)
return response.ready
except grpc.RpcError as rpc_error:
raise_error_grpc(rpc_error)
def get_server_metadata(self, headers=None, as_json=False, client_timeout=None):
"""Contact the inference server and get its metadata.
Parameters
----------
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
as_json : bool
If True then returns server metadata as a json dict,
otherwise as a protobuf message. Default value is
False. The returned json is generated from the protobuf
message using MessageToJson and as a result int64 values
are represented as string. It is the caller's
responsibility to convert these strings back to int64
values as necessary.
client_timeout: float
The maximum end-to-end time, in seconds, the request is allowed
to take. The client will abort request and raise
InferenceServerExeption with message "Deadline Exceeded" when the
specified time elapses. The default value is None which means
client will wait for the response from the server.
Returns
-------
dict or protobuf message
The JSON dict or ServerMetadataResponse message
holding the metadata.
Raises
------
InferenceServerException
If unable to get server metadata or has timed out.
"""
metadata = self._get_metadata(headers)
try:
request = service_pb2.ServerMetadataRequest()
if self._verbose:
print("get_server_metadata, metadata {}\n{}".format(metadata, request))
response = self._client_stub.ServerMetadata(
request=request, metadata=metadata, timeout=client_timeout
)
if self._verbose:
print(response)
if as_json:
return json.loads(
MessageToJson(response, preserving_proto_field_name=True)
)
else:
return response
except grpc.RpcError as rpc_error:
raise_error_grpc(rpc_error)
def get_model_metadata(
self,
model_name,
model_version="",
headers=None,
as_json=False,
client_timeout=None,
):
"""Contact the inference server and get the metadata for specified model.
Parameters
----------
model_name: str
The name of the model
model_version: str
The version of the model to get metadata. The default value
is an empty string which means then the server will choose
a version based on the model and internal policy.
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
as_json : bool
If True then returns model metadata as a json dict,
otherwise as a protobuf message. Default value is False.
The returned json is generated from the protobuf message
using MessageToJson and as a result int64 values are
represented as string. It is the caller's responsibility
to convert these strings back to int64 values as
necessary.
client_timeout: float
The maximum end-to-end time, in seconds, the request is allowed
to take. The client will abort request and raise
InferenceServerExeption with message "Deadline Exceeded" when the
specified time elapses. The default value is None which means
client will wait for the response from the server.
Returns
-------
dict or protobuf message
The JSON dict or ModelMetadataResponse message holding
the metadata.
Raises
------
InferenceServerException
If unable to get model metadata or has timed out.
"""
metadata = self._get_metadata(headers)
try:
if type(model_version) != str:
raise_error("model version must be a string")
request = service_pb2.ModelMetadataRequest(
name=model_name, version=model_version
)
if self._verbose:
print("get_model_metadata, metadata {}\n{}".format(metadata, request))
response = self._client_stub.ModelMetadata(
request=request, metadata=metadata, timeout=client_timeout
)
if self._verbose:
print(response)
if as_json:
return json.loads(
MessageToJson(response, preserving_proto_field_name=True)
)
else:
return response
except grpc.RpcError as rpc_error:
raise_error_grpc(rpc_error)
def get_model_config(
self,
model_name,
model_version="",
headers=None,
as_json=False,
client_timeout=None,
):
"""Contact the inference server and get the configuration for specified model.
Parameters
----------
model_name: str
The name of the model
model_version: str
The version of the model to get configuration. The default value
is an empty string which means then the server will choose
a version based on the model and internal policy.
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
as_json : bool
If True then returns configuration as a json dict, otherwise
as a protobuf message. Default value is False.
The returned json is generated from the protobuf message
using MessageToJson and as a result int64 values are
represented as string. It is the caller's responsibility
to convert these strings back to int64 values as
necessary.
client_timeout: float
The maximum end-to-end time, in seconds, the request is allowed
to take. The client will abort request and raise
InferenceServerExeption with message "Deadline Exceeded" when the
specified time elapses. The default value is None which means
client will wait for the response from the server.
Returns
-------
dict or protobuf message
The JSON dict or ModelConfigResponse message holding
the metadata.
Raises
------
InferenceServerException
If unable to get model configuration or has timed out.
"""
metadata = self._get_metadata(headers)
try:
if type(model_version) != str:
raise_error("model version must be a string")
request = service_pb2.ModelConfigRequest(
name=model_name, version=model_version
)
if self._verbose:
print("get_model_config, metadata {}\n{}".format(metadata, request))
response = self._client_stub.ModelConfig(
request=request, metadata=metadata, timeout=client_timeout
)
if self._verbose:
print(response)
if as_json:
return json.loads(
MessageToJson(response, preserving_proto_field_name=True)
)
else:
return response
except grpc.RpcError as rpc_error:
raise_error_grpc(rpc_error)
def get_model_repository_index(
self, headers=None, as_json=False, client_timeout=None
):
"""Get the index of model repository contents
Parameters
----------
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
as_json : bool
If True then returns model repository index
as a json dict, otherwise as a protobuf message.
Default value is False.
The returned json is generated from the protobuf message
using MessageToJson and as a result int64 values are
represented as string. It is the caller's responsibility
to convert these strings back to int64 values as
necessary.
client_timeout: float
The maximum end-to-end time, in seconds, the request is allowed
to take. The client will abort request and raise
InferenceServerExeption with message "Deadline Exceeded" when the
specified time elapses. The default value is None which means
client will wait for the response from the server.
Returns
-------
dict or protobuf message
The JSON dict or RepositoryIndexResponse message holding
the model repository index.
"""
metadata = self._get_metadata(headers)
try:
request = service_pb2.RepositoryIndexRequest()
if self._verbose:
print(
"get_model_repository_index, metadata {}\n{}".format(
metadata, request
)
)
response = self._client_stub.RepositoryIndex(
request=request, metadata=metadata, timeout=client_timeout
)
if self._verbose:
print(response)
if as_json:
return json.loads(
MessageToJson(response, preserving_proto_field_name=True)
)
else:
return response
except grpc.RpcError as rpc_error:
raise_error_grpc(rpc_error)
def load_model(
self,
model_name,
headers=None,
config=None,
files=None,
client_timeout=None,
):
"""Request the inference server to load or reload specified model.
Parameters
----------
model_name : str
The name of the model to be loaded.
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
config: str
Optional JSON representation of a model config provided for
the load request, if provided, this config will be used for
loading the model.
files: dict
Optional dictionary specifying file path (with "file:" prefix) in
the override model directory to the file content as bytes.
The files will form the model directory that the model will be
loaded from. If specified, 'config' must be provided to be
the model configuration of the override model directory.
client_timeout: float
The maximum end-to-end time, in seconds, the request is allowed
to take. The client will abort request and raise
InferenceServerExeption with message "Deadline Exceeded" when the
specified time elapses. The default value is None which means
client will wait for the response from the server.
Raises
------
InferenceServerException
If unable to load the model or has timed out.
"""
metadata = self._get_metadata(headers)
try:
request = service_pb2.RepositoryModelLoadRequest(model_name=model_name)
if config is not None:
request.parameters["config"].string_param = config
if self._verbose:
# Don't print file content which can be large
print(
"load_model, metadata {}\noverride files omitted:\n{}".format(
metadata, request
)
)
if files is not None:
for path, content in files.items():
request.parameters[path].bytes_param = content
self._client_stub.RepositoryModelLoad(
request=request, metadata=metadata, timeout=client_timeout
)
if self._verbose:
print("Loaded model '{}'".format(model_name))
except grpc.RpcError as rpc_error:
raise_error_grpc(rpc_error)
def unload_model(
self,
model_name,
headers=None,
unload_dependents=False,
client_timeout=None,
):
"""Request the inference server to unload specified model.
Parameters
----------
model_name : str
The name of the model to be unloaded.
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
unload_dependents : bool
Whether the dependents of the model should also be unloaded.
client_timeout: float
The maximum end-to-end time, in seconds, the request is allowed
to take. The client will abort request and raise
InferenceServerExeption with message "Deadline Exceeded" when the
specified time elapses. The default value is None which means
client will wait for the response from the server.
Raises
------
InferenceServerException
If unable to unload the model or has timed out.
"""
metadata = self._get_metadata(headers)
try:
request = service_pb2.RepositoryModelUnloadRequest(model_name=model_name)
request.parameters["unload_dependents"].bool_param = unload_dependents
if self._verbose:
print("unload_model, metadata {}\n{}".format(metadata, request))
self._client_stub.RepositoryModelUnload(
request=request, metadata=metadata, timeout=client_timeout
)
if self._verbose:
print("Unloaded model '{}'".format(model_name))
except grpc.RpcError as rpc_error:
raise_error_grpc(rpc_error)
def get_inference_statistics(
self,
model_name="",
model_version="",
headers=None,
as_json=False,
client_timeout=None,
):
"""Get the inference statistics for the specified model name and
version.
Parameters
----------
model_name : str
The name of the model to get statistics. The default value is
an empty string, which means statistics of all models will
be returned.
model_version: str
The version of the model to get inference statistics. The
default value is an empty string which means then the server
will return the statistics of all available model versions.
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
as_json : bool
If True then returns inference statistics
as a json dict, otherwise as a protobuf message.
Default value is False.
The returned json is generated from the protobuf message
using MessageToJson and as a result int64 values are
represented as string. It is the caller's responsibility
to convert these strings back to int64 values as
necessary.
client_timeout: float
The maximum end-to-end time, in seconds, the request is allowed
to take. The client will abort request and raise
InferenceServerExeption with message "Deadline Exceeded" when the
specified time elapses. The default value is None which means
client will wait for the response from the server.
Raises
------
InferenceServerException
If unable to get the model inference statistics or has timed out.
"""
metadata = self._get_metadata(headers)
try:
if type(model_version) != str:
raise_error("model version must be a string")
request = service_pb2.ModelStatisticsRequest(
name=model_name, version=model_version
)
if self._verbose:
print(
"get_inference_statistics, metadata {}\n{}".format(
metadata, request
)
)
response = self._client_stub.ModelStatistics(
request=request, metadata=metadata, timeout=client_timeout
)
if self._verbose:
print(response)
if as_json:
return json.loads(
MessageToJson(response, preserving_proto_field_name=True)
)
else:
return response
except grpc.RpcError as rpc_error:
raise_error_grpc(rpc_error)
def update_trace_settings(
self,
model_name=None,
settings={},
headers=None,
as_json=False,
client_timeout=None,
):
"""Update the trace settings for the specified model name, or
global trace settings if model name is not given.
Returns the trace settings after the update.
Parameters
----------
model_name : str
The name of the model to update trace settings. Specifying None or
empty string will update the global trace settings.
The default value is None.
settings: dict
The new trace setting values. Only the settings listed will be
updated. If a trace setting is listed in the dictionary with
a value of 'None', that setting will be cleared.
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
as_json : bool
If True then returns trace settings
as a json dict, otherwise as a protobuf message.
Default value is False.
The returned json is generated from the protobuf message
using MessageToJson and as a result int64 values are
represented as string. It is the caller's responsibility
to convert these strings back to int64 values as
necessary.
client_timeout: float
The maximum end-to-end time, in seconds, the request is allowed
to take. The client will abort request and raise
InferenceServerExeption with message "Deadline Exceeded" when the
specified time elapses. The default value is None which means
client will wait for the response from the server.
Returns
-------
dict or protobuf message
The JSON dict or TraceSettingResponse message holding
the updated trace settings.
Raises
------
InferenceServerException
If unable to update the trace settings or has timed out.
"""
metadata = self._get_metadata(headers)
try:
request = service_pb2.TraceSettingRequest()
if (model_name is not None) and (model_name != ""):
request.model_name = model_name
for key, value in settings.items():
if value is None:
request.settings[key]
else:
request.settings[key].value.extend(
value if isinstance(value, list) else [value]
)
if self._verbose:
print(
"update_trace_settings, metadata {}\n{}".format(metadata, request)
)
response = self._client_stub.TraceSetting(
request=request, metadata=metadata, timeout=client_timeout
)
if self._verbose:
print(response)
if as_json:
return json.loads(
MessageToJson(response, preserving_proto_field_name=True)
)
else:
return response
except grpc.RpcError as rpc_error:
raise_error_grpc(rpc_error)
def get_trace_settings(
self, model_name=None, headers=None, as_json=False, client_timeout=None
):
"""Get the trace settings for the specified model name, or global trace
settings if model name is not given
Parameters
----------
model_name : str
The name of the model to get trace settings. Specifying None or
empty string will return the global trace settings.
The default value is None.
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
as_json : bool
If True then returns trace settings
as a json dict, otherwise as a protobuf message.
Default value is False.
The returned json is generated from the protobuf message
using MessageToJson and as a result int64 values are
represented as string. It is the caller's responsibility
to convert these strings back to int64 values as
necessary.
client_timeout: float
The maximum end-to-end time, in seconds, the request is allowed
to take. The client will abort request and raise
InferenceServerExeption with message "Deadline Exceeded" when the
specified time elapses. The default value is None which means
client will wait for the response from the server.
Returns
-------
dict or protobuf message
The JSON dict or TraceSettingResponse message holding
the trace settings.
Raises
------
InferenceServerException
If unable to get the trace settings or has timed out.
"""
metadata = self._get_metadata(headers)
try:
request = service_pb2.TraceSettingRequest()
if (model_name is not None) and (model_name != ""):
request.model_name = model_name
if self._verbose:
print("get_trace_settings, metadata {}\n{}".format(metadata, request))
response = self._client_stub.TraceSetting(
request=request, metadata=metadata, timeout=client_timeout
)
if self._verbose:
print(response)
if as_json:
return json.loads(
MessageToJson(response, preserving_proto_field_name=True)
)
else:
return response
except grpc.RpcError as rpc_error:
raise_error_grpc(rpc_error)
def update_log_settings(
self, settings, headers=None, as_json=False, client_timeout=None
):
"""Update the global log settings.
Returns the log settings after the update.
Parameters
----------
settings: dict
The new log setting values. Only the settings listed will be
updated.
headers: dict
Optional dictionary specifying additional HTTP
headers to include in the request.
as_json : bool
If True then returns trace settings
as a json dict, otherwise as a protobuf message.
Default value is False.
The returned json is generated from the protobuf message
using MessageToJson and as a result int64 values are
represented as string. It is the caller's responsibility