-
Notifications
You must be signed in to change notification settings - Fork 354
/
Copy pathmodels.py
3019 lines (2738 loc) · 144 KB
/
models.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
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pathlib
import proto
import re
import shutil
import tempfile
from typing import Dict, List, NamedTuple, Optional, Sequence, Tuple, Union
from google.api_core import operation
from google.api_core import exceptions as api_exceptions
from google.auth import credentials as auth_credentials
from google.cloud import aiplatform
from google.cloud.aiplatform import base
from google.cloud.aiplatform import explain
from google.cloud.aiplatform import initializer
from google.cloud.aiplatform import jobs
from google.cloud.aiplatform import models
from google.cloud.aiplatform import utils
from google.cloud.aiplatform.utils import gcs_utils
from google.cloud.aiplatform.compat.services import endpoint_service_client
from google.cloud.aiplatform.compat.types import (
encryption_spec as gca_encryption_spec,
endpoint as gca_endpoint_compat,
endpoint_v1 as gca_endpoint_v1,
explanation as gca_explanation_compat,
io as gca_io_compat,
machine_resources as gca_machine_resources_compat,
model as gca_model_compat,
model_service as gca_model_service_compat,
env_var as gca_env_var_compat,
)
from google.protobuf import json_format
_LOGGER = base.Logger(__name__)
_SUPPORTED_MODEL_FILE_NAMES = [
"model.pkl",
"model.joblib",
"model.bst",
"saved_model.pb",
"saved_model.pbtxt",
]
class Prediction(NamedTuple):
"""Prediction class envelopes returned Model predictions and the Model id.
Attributes:
predictions:
The predictions that are the output of the predictions
call. The schema of any single prediction may be specified via
Endpoint's DeployedModels' [Model's][google.cloud.aiplatform.v1beta1.DeployedModel.model]
[PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata]
deployed_model_id:
ID of the Endpoint's DeployedModel that served this prediction.
explanations:
The explanations of the Model's predictions. It has the same number
of elements as instances to be explained. Default is None.
"""
predictions: Dict[str, List]
deployed_model_id: str
explanations: Optional[Sequence[gca_explanation_compat.Explanation]] = None
class Endpoint(base.VertexAiResourceNounWithFutureManager):
client_class = utils.EndpointClientWithOverride
_resource_noun = "endpoints"
_getter_method = "get_endpoint"
_list_method = "list_endpoints"
_delete_method = "delete_endpoint"
_parse_resource_name_method = "parse_endpoint_path"
_format_resource_name_method = "endpoint_path"
def __init__(
self,
endpoint_name: str,
project: Optional[str] = None,
location: Optional[str] = None,
credentials: Optional[auth_credentials.Credentials] = None,
):
"""Retrieves an endpoint resource.
Args:
endpoint_name (str):
Required. A fully-qualified endpoint resource name or endpoint ID.
Example: "projects/123/locations/us-central1/endpoints/456" or
"456" when project and location are initialized or passed.
project (str):
Optional. Project to retrieve endpoint from. If not set, project
set in aiplatform.init will be used.
location (str):
Optional. Location to retrieve endpoint from. If not set, location
set in aiplatform.init will be used.
credentials (auth_credentials.Credentials):
Optional. Custom credentials to use to upload this model. Overrides
credentials set in aiplatform.init.
"""
super().__init__(
project=project,
location=location,
credentials=credentials,
resource_name=endpoint_name,
)
endpoint_name = utils.full_resource_name(
resource_name=endpoint_name,
resource_noun="endpoints",
parse_resource_name_method=self._parse_resource_name,
format_resource_name_method=self._format_resource_name,
project=project,
location=location,
)
# Lazy load the Endpoint gca_resource until needed
self._gca_resource = gca_endpoint_compat.Endpoint(name=endpoint_name)
self._prediction_client = self._instantiate_prediction_client(
location=self.location, credentials=credentials,
)
def _skipped_getter_call(self) -> bool:
"""Check if GAPIC resource was populated by call to get/list API methods
Returns False if `_gca_resource` is None or fully populated. Returns True
if `_gca_resource` is partially populated
"""
return self._gca_resource and not self._gca_resource.create_time
def _sync_gca_resource_if_skipped(self) -> None:
"""Sync GAPIC service representation of Endpoint class resource only if
get_endpoint() was never called."""
if self._skipped_getter_call():
self._gca_resource = self._get_gca_resource(
resource_name=self._gca_resource.name
)
def _assert_gca_resource_is_available(self) -> None:
"""Ensures Endpoint getter was called at least once before
asserting on gca_resource's availability."""
super()._assert_gca_resource_is_available()
self._sync_gca_resource_if_skipped()
@property
def traffic_split(self) -> Dict[str, int]:
"""A map from a DeployedModel's ID to the percentage of this Endpoint's
traffic that should be forwarded to that DeployedModel.
If a DeployedModel's ID is not listed in this map, then it receives no traffic.
The traffic percentage values must add up to 100, or map must be empty if
the Endpoint is to not accept any traffic at a moment.
"""
self._sync_gca_resource()
return dict(self._gca_resource.traffic_split)
@property
def network(self) -> Optional[str]:
"""The full name of the Google Compute Engine
[network](https://cloud.google.com/vpc/docs/vpc#networks) to which this
Endpoint should be peered.
Takes the format `projects/{project}/global/networks/{network}`. Where
{project} is a project number, as in `12345`, and {network} is a network name.
Private services access must already be configured for the network. If left
unspecified, the Endpoint is not peered with any network.
"""
self._assert_gca_resource_is_available()
return getattr(self._gca_resource, "network", None)
@classmethod
def create(
cls,
display_name: str,
description: Optional[str] = None,
labels: Optional[Dict[str, str]] = None,
metadata: Optional[Sequence[Tuple[str, str]]] = (),
project: Optional[str] = None,
location: Optional[str] = None,
credentials: Optional[auth_credentials.Credentials] = None,
encryption_spec_key_name: Optional[str] = None,
sync=True,
) -> "Endpoint":
"""Creates a new endpoint.
Args:
display_name (str):
Required. The user-defined name of the Endpoint.
The name can be up to 128 characters long and can be consist
of any UTF-8 characters.
project (str):
Required. Project to retrieve endpoint from. If not set, project
set in aiplatform.init will be used.
location (str):
Required. Location to retrieve endpoint from. If not set, location
set in aiplatform.init will be used.
description (str):
Optional. The description of the Endpoint.
labels (Dict[str, str]):
Optional. The labels with user-defined metadata to
organize your Endpoints.
Label keys and values can be no longer than 64
characters (Unicode codepoints), can only
contain lowercase letters, numeric characters,
underscores and dashes. International characters
are allowed.
See https://goo.gl/xmQnxf for more information
and examples of labels.
metadata (Sequence[Tuple[str, str]]):
Optional. Strings which should be sent along with the request as
metadata.
credentials (auth_credentials.Credentials):
Optional. Custom credentials to use to upload this model. Overrides
credentials set in aiplatform.init.
encryption_spec_key_name (Optional[str]):
Optional. The Cloud KMS resource identifier of the customer
managed encryption key used to protect the model. Has the
form:
``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``.
The key needs to be in the same region as where the compute
resource is created.
If set, this Endpoint and all sub-resources of this Endpoint will be secured by this key.
Overrides encryption_spec_key_name set in aiplatform.init.
sync (bool):
Whether to execute this method synchronously. If False, this method
will be executed in concurrent Future and any downstream object will
be immediately returned and synced when the Future has completed.
Returns:
endpoint (endpoint.Endpoint):
Created endpoint.
"""
api_client = cls._instantiate_client(location=location, credentials=credentials)
utils.validate_display_name(display_name)
if labels:
utils.validate_labels(labels)
project = project or initializer.global_config.project
location = location or initializer.global_config.location
return cls._create(
api_client=api_client,
display_name=display_name,
project=project,
location=location,
description=description,
labels=labels,
metadata=metadata,
credentials=credentials,
encryption_spec=initializer.global_config.get_encryption_spec(
encryption_spec_key_name=encryption_spec_key_name
),
sync=sync,
)
@classmethod
@base.optional_sync()
def _create(
cls,
api_client: endpoint_service_client.EndpointServiceClient,
display_name: str,
project: str,
location: str,
description: Optional[str] = None,
labels: Optional[Dict[str, str]] = None,
metadata: Optional[Sequence[Tuple[str, str]]] = (),
credentials: Optional[auth_credentials.Credentials] = None,
encryption_spec: Optional[gca_encryption_spec.EncryptionSpec] = None,
sync=True,
) -> "Endpoint":
"""Creates a new endpoint by calling the API client.
Args:
api_client (EndpointServiceClient):
Required. An instance of EndpointServiceClient with the correct
api_endpoint already set based on user's preferences.
display_name (str):
Required. The user-defined name of the Endpoint.
The name can be up to 128 characters long and can be consist
of any UTF-8 characters.
project (str):
Required. Project to retrieve endpoint from. If not set, project
set in aiplatform.init will be used.
location (str):
Required. Location to retrieve endpoint from. If not set, location
set in aiplatform.init will be used.
description (str):
Optional. The description of the Endpoint.
labels (Dict[str, str]):
Optional. The labels with user-defined metadata to
organize your Endpoints.
Label keys and values can be no longer than 64
characters (Unicode codepoints), can only
contain lowercase letters, numeric characters,
underscores and dashes. International characters
are allowed.
See https://goo.gl/xmQnxf for more information
and examples of labels.
metadata (Sequence[Tuple[str, str]]):
Optional. Strings which should be sent along with the request as
metadata.
credentials (auth_credentials.Credentials):
Optional. Custom credentials to use to upload this model. Overrides
credentials set in aiplatform.init.
encryption_spec (Optional[gca_encryption_spec.EncryptionSpec]):
Optional. The Cloud KMS customer managed encryption key used to protect the dataset.
The key needs to be in the same region as where the compute
resource is created.
If set, this Dataset and all sub-resources of this Dataset will be secured by this key.
sync (bool):
Whether to create this endpoint synchronously.
Returns:
endpoint (endpoint.Endpoint):
Created endpoint.
"""
parent = initializer.global_config.common_location_path(
project=project, location=location
)
gapic_endpoint = gca_endpoint_compat.Endpoint(
display_name=display_name,
description=description,
labels=labels,
encryption_spec=encryption_spec,
)
operation_future = api_client.create_endpoint(
parent=parent, endpoint=gapic_endpoint, metadata=metadata
)
_LOGGER.log_create_with_lro(cls, operation_future)
created_endpoint = operation_future.result()
_LOGGER.log_create_complete(cls, created_endpoint, "endpoint")
return cls._construct_sdk_resource_from_gapic(
gapic_resource=created_endpoint,
project=project,
location=location,
credentials=credentials,
)
@classmethod
def _construct_sdk_resource_from_gapic(
cls,
gapic_resource: proto.Message,
project: Optional[str] = None,
location: Optional[str] = None,
credentials: Optional[auth_credentials.Credentials] = None,
) -> "Endpoint":
"""Given a GAPIC Endpoint object, return the SDK representation.
Args:
gapic_resource (proto.Message):
A GAPIC representation of a Endpoint resource, usually
retrieved by a get_* or in a list_* API call.
project (str):
Optional. Project to construct Endpoint object from. If not set,
project set in aiplatform.init will be used.
location (str):
Optional. Location to construct Endpoint object from. If not set,
location set in aiplatform.init will be used.
credentials (auth_credentials.Credentials):
Optional. Custom credentials to use to construct Endpoint.
Overrides credentials set in aiplatform.init.
Returns:
Endpoint:
An initialized Endpoint resource.
"""
endpoint = cls._empty_constructor(
project=project, location=location, credentials=credentials
)
endpoint._gca_resource = gapic_resource
endpoint._prediction_client = cls._instantiate_prediction_client(
location=endpoint.location, credentials=credentials,
)
return endpoint
@staticmethod
def _allocate_traffic(
traffic_split: Dict[str, int], traffic_percentage: int,
) -> Dict[str, int]:
"""Allocates desired traffic to new deployed model and scales traffic
of older deployed models.
Args:
traffic_split (Dict[str, int]):
Required. Current traffic split of deployed models in endpoint.
traffic_percentage (int):
Required. Desired traffic to new deployed model.
Returns:
new_traffic_split (Dict[str, int]):
Traffic split to use.
"""
new_traffic_split = {}
old_models_traffic = 100 - traffic_percentage
if old_models_traffic:
unallocated_traffic = old_models_traffic
for deployed_model in traffic_split:
current_traffic = traffic_split[deployed_model]
new_traffic = int(current_traffic / 100 * old_models_traffic)
new_traffic_split[deployed_model] = new_traffic
unallocated_traffic -= new_traffic
# will likely under-allocate. make total 100.
for deployed_model in new_traffic_split:
if unallocated_traffic == 0:
break
new_traffic_split[deployed_model] += 1
unallocated_traffic -= 1
new_traffic_split["0"] = traffic_percentage
return new_traffic_split
@staticmethod
def _unallocate_traffic(
traffic_split: Dict[str, int], deployed_model_id: str,
) -> Dict[str, int]:
"""Sets deployed model id's traffic to 0 and scales the traffic of
other deployed models.
Args:
traffic_split (Dict[str, int]):
Required. Current traffic split of deployed models in endpoint.
deployed_model_id (str):
Required. Desired traffic to new deployed model.
Returns:
new_traffic_split (Dict[str, int]):
Traffic split to use.
"""
new_traffic_split = traffic_split.copy()
del new_traffic_split[deployed_model_id]
deployed_model_id_traffic = traffic_split[deployed_model_id]
traffic_percent_left = 100 - deployed_model_id_traffic
if traffic_percent_left:
unallocated_traffic = 100
for deployed_model in new_traffic_split:
current_traffic = traffic_split[deployed_model]
new_traffic = int(current_traffic / traffic_percent_left * 100)
new_traffic_split[deployed_model] = new_traffic
unallocated_traffic -= new_traffic
# will likely under-allocate. make total 100.
for deployed_model in new_traffic_split:
if unallocated_traffic == 0:
break
new_traffic_split[deployed_model] += 1
unallocated_traffic -= 1
new_traffic_split[deployed_model_id] = 0
return new_traffic_split
@staticmethod
def _validate_deploy_args(
min_replica_count: int,
max_replica_count: int,
accelerator_type: Optional[str],
deployed_model_display_name: Optional[str],
traffic_split: Optional[Dict[str, int]],
traffic_percentage: int,
explanation_metadata: Optional[explain.ExplanationMetadata] = None,
explanation_parameters: Optional[explain.ExplanationParameters] = None,
):
"""Helper method to validate deploy arguments.
Args:
min_replica_count (int):
Required. The minimum number of machine replicas this deployed
model will be always deployed on. If traffic against it increases,
it may dynamically be deployed onto more replicas, and as traffic
decreases, some of these extra replicas may be freed.
max_replica_count (int):
Required. The maximum number of replicas this deployed model may
be deployed on when the traffic against it increases. If requested
value is too large, the deployment will error, but if deployment
succeeds then the ability to scale the model to that many replicas
is guaranteed (barring service outages). If traffic against the
deployed model increases beyond what its replicas at maximum may
handle, a portion of the traffic will be dropped. If this value
is not provided, the larger value of min_replica_count or 1 will
be used. If value provided is smaller than min_replica_count, it
will automatically be increased to be min_replica_count.
accelerator_type (str):
Required. Hardware accelerator type. One of ACCELERATOR_TYPE_UNSPECIFIED,
NVIDIA_TESLA_K80, NVIDIA_TESLA_P100, NVIDIA_TESLA_V100, NVIDIA_TESLA_P4,
NVIDIA_TESLA_T4
deployed_model_display_name (str):
Required. The display name of the DeployedModel. If not provided
upon creation, the Model's display_name is used.
traffic_split (Dict[str, int]):
Required. A map from a DeployedModel's ID to the percentage of
this Endpoint's traffic that should be forwarded to that DeployedModel.
If a DeployedModel's ID is not listed in this map, then it receives
no traffic. The traffic percentage values must add up to 100, or
map must be empty if the Endpoint is to not accept any traffic at
the moment. Key for model being deployed is "0". Should not be
provided if traffic_percentage is provided.
traffic_percentage (int):
Required. Desired traffic to newly deployed model. Defaults to
0 if there are pre-existing deployed models. Defaults to 100 if
there are no pre-existing deployed models. Negative values should
not be provided. Traffic of previously deployed models at the endpoint
will be scaled down to accommodate new deployed model's traffic.
Should not be provided if traffic_split is provided.
explanation_metadata (explain.ExplanationMetadata):
Optional. Metadata describing the Model's input and output for explanation.
Both `explanation_metadata` and `explanation_parameters` must be
passed together when used. For more details, see
`Ref docs <http://tinyurl.com/1igh60kt>`
explanation_parameters (explain.ExplanationParameters):
Optional. Parameters to configure explaining for Model's predictions.
For more details, see `Ref docs <http://tinyurl.com/1an4zake>`
Raises:
ValueError: if Min or Max replica is negative. Traffic percentage > 100 or
< 0. Or if traffic_split does not sum to 100.
ValueError: if either explanation_metadata or explanation_parameters
but not both are specified.
"""
if min_replica_count < 0:
raise ValueError("Min replica cannot be negative.")
if max_replica_count < 0:
raise ValueError("Max replica cannot be negative.")
if deployed_model_display_name is not None:
utils.validate_display_name(deployed_model_display_name)
if traffic_split is None:
if traffic_percentage > 100:
raise ValueError("Traffic percentage cannot be greater than 100.")
if traffic_percentage < 0:
raise ValueError("Traffic percentage cannot be negative.")
elif traffic_split:
# TODO(b/172678233) verify every referenced deployed model exists
if sum(traffic_split.values()) != 100:
raise ValueError(
"Sum of all traffic within traffic split needs to be 100."
)
if bool(explanation_metadata) != bool(explanation_parameters):
raise ValueError(
"Both `explanation_metadata` and `explanation_parameters` should be specified or None."
)
# Raises ValueError if invalid accelerator
if accelerator_type:
utils.validate_accelerator_type(accelerator_type)
def deploy(
self,
model: "Model",
deployed_model_display_name: Optional[str] = None,
traffic_percentage: int = 0,
traffic_split: Optional[Dict[str, int]] = None,
machine_type: Optional[str] = None,
min_replica_count: int = 1,
max_replica_count: int = 1,
accelerator_type: Optional[str] = None,
accelerator_count: Optional[int] = None,
service_account: Optional[str] = None,
explanation_metadata: Optional[explain.ExplanationMetadata] = None,
explanation_parameters: Optional[explain.ExplanationParameters] = None,
metadata: Optional[Sequence[Tuple[str, str]]] = (),
sync=True,
) -> None:
"""Deploys a Model to the Endpoint.
Args:
model (aiplatform.Model):
Required. Model to be deployed.
deployed_model_display_name (str):
Optional. The display name of the DeployedModel. If not provided
upon creation, the Model's display_name is used.
traffic_percentage (int):
Optional. Desired traffic to newly deployed model. Defaults to
0 if there are pre-existing deployed models. Defaults to 100 if
there are no pre-existing deployed models. Negative values should
not be provided. Traffic of previously deployed models at the endpoint
will be scaled down to accommodate new deployed model's traffic.
Should not be provided if traffic_split is provided.
traffic_split (Dict[str, int]):
Optional. A map from a DeployedModel's ID to the percentage of
this Endpoint's traffic that should be forwarded to that DeployedModel.
If a DeployedModel's ID is not listed in this map, then it receives
no traffic. The traffic percentage values must add up to 100, or
map must be empty if the Endpoint is to not accept any traffic at
the moment. Key for model being deployed is "0". Should not be
provided if traffic_percentage is provided.
machine_type (str):
Optional. The type of machine. Not specifying machine type will
result in model to be deployed with automatic resources.
min_replica_count (int):
Optional. The minimum number of machine replicas this deployed
model will be always deployed on. If traffic against it increases,
it may dynamically be deployed onto more replicas, and as traffic
decreases, some of these extra replicas may be freed.
max_replica_count (int):
Optional. The maximum number of replicas this deployed model may
be deployed on when the traffic against it increases. If requested
value is too large, the deployment will error, but if deployment
succeeds then the ability to scale the model to that many replicas
is guaranteed (barring service outages). If traffic against the
deployed model increases beyond what its replicas at maximum may
handle, a portion of the traffic will be dropped. If this value
is not provided, the larger value of min_replica_count or 1 will
be used. If value provided is smaller than min_replica_count, it
will automatically be increased to be min_replica_count.
accelerator_type (str):
Optional. Hardware accelerator type. Must also set accelerator_count if used.
One of ACCELERATOR_TYPE_UNSPECIFIED, NVIDIA_TESLA_K80, NVIDIA_TESLA_P100,
NVIDIA_TESLA_V100, NVIDIA_TESLA_P4, NVIDIA_TESLA_T4
accelerator_count (int):
Optional. The number of accelerators to attach to a worker replica.
service_account (str):
The service account that the DeployedModel's container runs as. Specify the
email address of the service account. If this service account is not
specified, the container runs as a service account that doesn't have access
to the resource project.
Users deploying the Model must have the `iam.serviceAccounts.actAs`
permission on this service account.
explanation_metadata (explain.ExplanationMetadata):
Optional. Metadata describing the Model's input and output for explanation.
Both `explanation_metadata` and `explanation_parameters` must be
passed together when used. For more details, see
`Ref docs <http://tinyurl.com/1igh60kt>`
explanation_parameters (explain.ExplanationParameters):
Optional. Parameters to configure explaining for Model's predictions.
For more details, see `Ref docs <http://tinyurl.com/1an4zake>`
metadata (Sequence[Tuple[str, str]]):
Optional. Strings which should be sent along with the request as
metadata.
sync (bool):
Whether to execute this method synchronously. If False, this method
will be executed in concurrent Future and any downstream object will
be immediately returned and synced when the Future has completed.
"""
self._sync_gca_resource_if_skipped()
self._validate_deploy_args(
min_replica_count,
max_replica_count,
accelerator_type,
deployed_model_display_name,
traffic_split,
traffic_percentage,
explanation_metadata,
explanation_parameters,
)
self._deploy(
model=model,
deployed_model_display_name=deployed_model_display_name,
traffic_percentage=traffic_percentage,
traffic_split=traffic_split,
machine_type=machine_type,
min_replica_count=min_replica_count,
max_replica_count=max_replica_count,
accelerator_type=accelerator_type,
accelerator_count=accelerator_count,
service_account=service_account,
explanation_metadata=explanation_metadata,
explanation_parameters=explanation_parameters,
metadata=metadata,
sync=sync,
)
@base.optional_sync()
def _deploy(
self,
model: "Model",
deployed_model_display_name: Optional[str] = None,
traffic_percentage: Optional[int] = 0,
traffic_split: Optional[Dict[str, int]] = None,
machine_type: Optional[str] = None,
min_replica_count: int = 1,
max_replica_count: int = 1,
accelerator_type: Optional[str] = None,
accelerator_count: Optional[int] = None,
service_account: Optional[str] = None,
explanation_metadata: Optional[explain.ExplanationMetadata] = None,
explanation_parameters: Optional[explain.ExplanationParameters] = None,
metadata: Optional[Sequence[Tuple[str, str]]] = (),
sync=True,
) -> None:
"""Deploys a Model to the Endpoint.
Args:
model (aiplatform.Model):
Required. Model to be deployed.
deployed_model_display_name (str):
Optional. The display name of the DeployedModel. If not provided
upon creation, the Model's display_name is used.
traffic_percentage (int):
Optional. Desired traffic to newly deployed model. Defaults to
0 if there are pre-existing deployed models. Defaults to 100 if
there are no pre-existing deployed models. Negative values should
not be provided. Traffic of previously deployed models at the endpoint
will be scaled down to accommodate new deployed model's traffic.
Should not be provided if traffic_split is provided.
traffic_split (Dict[str, int]):
Optional. A map from a DeployedModel's ID to the percentage of
this Endpoint's traffic that should be forwarded to that DeployedModel.
If a DeployedModel's ID is not listed in this map, then it receives
no traffic. The traffic percentage values must add up to 100, or
map must be empty if the Endpoint is to not accept any traffic at
the moment. Key for model being deployed is "0". Should not be
provided if traffic_percentage is provided.
machine_type (str):
Optional. The type of machine. Not specifying machine type will
result in model to be deployed with automatic resources.
min_replica_count (int):
Optional. The minimum number of machine replicas this deployed
model will be always deployed on. If traffic against it increases,
it may dynamically be deployed onto more replicas, and as traffic
decreases, some of these extra replicas may be freed.
max_replica_count (int):
Optional. The maximum number of replicas this deployed model may
be deployed on when the traffic against it increases. If requested
value is too large, the deployment will error, but if deployment
succeeds then the ability to scale the model to that many replicas
is guaranteed (barring service outages). If traffic against the
deployed model increases beyond what its replicas at maximum may
handle, a portion of the traffic will be dropped. If this value
is not provided, the larger value of min_replica_count or 1 will
be used. If value provided is smaller than min_replica_count, it
will automatically be increased to be min_replica_count.
accelerator_type (str):
Optional. Hardware accelerator type. Must also set accelerator_count if used.
One of ACCELERATOR_TYPE_UNSPECIFIED, NVIDIA_TESLA_K80, NVIDIA_TESLA_P100,
NVIDIA_TESLA_V100, NVIDIA_TESLA_P4, NVIDIA_TESLA_T4
accelerator_count (int):
Optional. The number of accelerators to attach to a worker replica.
service_account (str):
The service account that the DeployedModel's container runs as. Specify the
email address of the service account. If this service account is not
specified, the container runs as a service account that doesn't have access
to the resource project.
Users deploying the Model must have the `iam.serviceAccounts.actAs`
permission on this service account.
explanation_metadata (explain.ExplanationMetadata):
Optional. Metadata describing the Model's input and output for explanation.
Both `explanation_metadata` and `explanation_parameters` must be
passed together when used. For more details, see
`Ref docs <http://tinyurl.com/1igh60kt>`
explanation_parameters (explain.ExplanationParameters):
Optional. Parameters to configure explaining for Model's predictions.
For more details, see `Ref docs <http://tinyurl.com/1an4zake>`
metadata (Sequence[Tuple[str, str]]):
Optional. Strings which should be sent along with the request as
metadata.
sync (bool):
Whether to execute this method synchronously. If False, this method
will be executed in concurrent Future and any downstream object will
be immediately returned and synced when the Future has completed.
Raises:
ValueError: If there is not current traffic split and traffic percentage
is not 0 or 100.
"""
_LOGGER.log_action_start_against_resource(
f"Deploying Model {model.resource_name} to", "", self
)
self._deploy_call(
self.api_client,
self.resource_name,
model.resource_name,
self._gca_resource.traffic_split,
deployed_model_display_name=deployed_model_display_name,
traffic_percentage=traffic_percentage,
traffic_split=traffic_split,
machine_type=machine_type,
min_replica_count=min_replica_count,
max_replica_count=max_replica_count,
accelerator_type=accelerator_type,
accelerator_count=accelerator_count,
service_account=service_account,
explanation_metadata=explanation_metadata,
explanation_parameters=explanation_parameters,
metadata=metadata,
)
_LOGGER.log_action_completed_against_resource("model", "deployed", self)
self._sync_gca_resource()
@classmethod
def _deploy_call(
cls,
api_client: endpoint_service_client.EndpointServiceClient,
endpoint_resource_name: str,
model_resource_name: str,
endpoint_resource_traffic_split: Optional[proto.MapField] = None,
deployed_model_display_name: Optional[str] = None,
traffic_percentage: Optional[int] = 0,
traffic_split: Optional[Dict[str, int]] = None,
machine_type: Optional[str] = None,
min_replica_count: int = 1,
max_replica_count: int = 1,
accelerator_type: Optional[str] = None,
accelerator_count: Optional[int] = None,
service_account: Optional[str] = None,
explanation_metadata: Optional[explain.ExplanationMetadata] = None,
explanation_parameters: Optional[explain.ExplanationParameters] = None,
metadata: Optional[Sequence[Tuple[str, str]]] = (),
):
"""Helper method to deploy model to endpoint.
Args:
api_client (endpoint_service_client.EndpointServiceClient):
Required. endpoint_service_client.EndpointServiceClient to make call.
endpoint_resource_name (str):
Required. Endpoint resource name to deploy model to.
model_resource_name (str):
Required. Model resource name of Model to deploy.
endpoint_resource_traffic_split (proto.MapField):
Optional. Endpoint current resource traffic split.
deployed_model_display_name (str):
Optional. The display name of the DeployedModel. If not provided
upon creation, the Model's display_name is used.
traffic_percentage (int):
Optional. Desired traffic to newly deployed model. Defaults to
0 if there are pre-existing deployed models. Defaults to 100 if
there are no pre-existing deployed models. Negative values should
not be provided. Traffic of previously deployed models at the endpoint
will be scaled down to accommodate new deployed model's traffic.
Should not be provided if traffic_split is provided.
traffic_split (Dict[str, int]):
Optional. A map from a DeployedModel's ID to the percentage of
this Endpoint's traffic that should be forwarded to that DeployedModel.
If a DeployedModel's ID is not listed in this map, then it receives
no traffic. The traffic percentage values must add up to 100, or
map must be empty if the Endpoint is to not accept any traffic at
the moment. Key for model being deployed is "0". Should not be
provided if traffic_percentage is provided.
machine_type (str):
Optional. The type of machine. Not specifying machine type will
result in model to be deployed with automatic resources.
min_replica_count (int):
Optional. The minimum number of machine replicas this deployed
model will be always deployed on. If traffic against it increases,
it may dynamically be deployed onto more replicas, and as traffic
decreases, some of these extra replicas may be freed.
max_replica_count (int):
Optional. The maximum number of replicas this deployed model may
be deployed on when the traffic against it increases. If requested
value is too large, the deployment will error, but if deployment
succeeds then the ability to scale the model to that many replicas
is guaranteed (barring service outages). If traffic against the
deployed model increases beyond what its replicas at maximum may
handle, a portion of the traffic will be dropped. If this value
is not provided, the larger value of min_replica_count or 1 will
be used. If value provided is smaller than min_replica_count, it
will automatically be increased to be min_replica_count.
service_account (str):
The service account that the DeployedModel's container runs as. Specify the
email address of the service account. If this service account is not
specified, the container runs as a service account that doesn't have access
to the resource project.
Users deploying the Model must have the `iam.serviceAccounts.actAs`
permission on this service account.
explanation_metadata (explain.ExplanationMetadata):
Optional. Metadata describing the Model's input and output for explanation.
Both `explanation_metadata` and `explanation_parameters` must be
passed together when used. For more details, see
`Ref docs <http://tinyurl.com/1igh60kt>`
explanation_parameters (explain.ExplanationParameters):
Optional. Parameters to configure explaining for Model's predictions.
For more details, see `Ref docs <http://tinyurl.com/1an4zake>`
metadata (Sequence[Tuple[str, str]]):
Optional. Strings which should be sent along with the request as
metadata.
sync (bool):
Whether to execute this method synchronously. If False, this method
will be executed in concurrent Future and any downstream object will
be immediately returned and synced when the Future has completed.
Raises:
ValueError: If there is not current traffic split and traffic percentage
is not 0 or 100.
ValueError: If only `explanation_metadata` or `explanation_parameters`
is specified.
"""
max_replica_count = max(min_replica_count, max_replica_count)
if bool(accelerator_type) != bool(accelerator_count):
raise ValueError(
"Both `accelerator_type` and `accelerator_count` should be specified or None."
)
deployed_model = gca_endpoint_compat.DeployedModel(
model=model_resource_name,
display_name=deployed_model_display_name,
service_account=service_account,
)
if machine_type:
machine_spec = gca_machine_resources_compat.MachineSpec(
machine_type=machine_type
)
if accelerator_type and accelerator_count:
utils.validate_accelerator_type(accelerator_type)
machine_spec.accelerator_type = accelerator_type
machine_spec.accelerator_count = accelerator_count
deployed_model.dedicated_resources = gca_machine_resources_compat.DedicatedResources(
machine_spec=machine_spec,
min_replica_count=min_replica_count,
max_replica_count=max_replica_count,
)
else:
deployed_model.automatic_resources = gca_machine_resources_compat.AutomaticResources(
min_replica_count=min_replica_count,
max_replica_count=max_replica_count,
)
# Service will throw error if both metadata and parameters are not provided
if explanation_metadata and explanation_parameters:
explanation_spec = gca_endpoint_compat.explanation.ExplanationSpec()
explanation_spec.metadata = explanation_metadata
explanation_spec.parameters = explanation_parameters
deployed_model.explanation_spec = explanation_spec
if traffic_split is None:
# new model traffic needs to be 100 if no pre-existing models
if not endpoint_resource_traffic_split:
# default scenario
if traffic_percentage == 0:
traffic_percentage = 100
# verify user specified 100
elif traffic_percentage < 100:
raise ValueError(
"""There are currently no deployed models so the traffic
percentage for this deployed model needs to be 100."""
)
traffic_split = cls._allocate_traffic(
traffic_split=dict(endpoint_resource_traffic_split),
traffic_percentage=traffic_percentage,
)
operation_future = api_client.deploy_model(
endpoint=endpoint_resource_name,
deployed_model=deployed_model,
traffic_split=traffic_split,
metadata=metadata,
)
_LOGGER.log_action_started_against_resource_with_lro(
"Deploy", "model", cls, operation_future
)
operation_future.result()
def undeploy(
self,
deployed_model_id: str,
traffic_split: Optional[Dict[str, int]] = None,
metadata: Optional[Sequence[Tuple[str, str]]] = (),
sync=True,
) -> None:
"""Undeploys a deployed model.
The model to be undeployed should have no traffic or user must provide