forked from aws/sagemaker-python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.py
More file actions
3033 lines (2609 loc) · 112 KB
/
types.py
File metadata and controls
3033 lines (2609 loc) · 112 KB
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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
# pylint: skip-file
"""This module stores types related to SageMaker JumpStart."""
from __future__ import absolute_import
import re
from copy import deepcopy
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Set, Union
from sagemaker_core.shapes import ModelAccessConfig as CoreModelAccessConfig
from sagemaker.model_card.model_card import ModelCard, ModelPackageModelCard
from sagemaker.utils import (
S3_PREFIX,
get_instance_type_family,
format_tags,
Tags,
deep_override_dict,
)
from sagemaker.model_metrics import ModelMetrics
from sagemaker.metadata_properties import MetadataProperties
from sagemaker.drift_check_baselines import DriftCheckBaselines
from sagemaker.jumpstart.enums import (
JumpStartModelType,
JumpStartScriptScope,
JumpStartConfigRankingName,
)
from sagemaker.session import Session
from sagemaker.workflow.entities import PipelineVariable
from sagemaker.compute_resource_requirements.resource_requirements import ResourceRequirements
from sagemaker.enums import EndpointType
from sagemaker.jumpstart.hub.parser_utils import (
camel_to_snake,
walk_and_apply_json,
)
from sagemaker.model_life_cycle import ModelLifeCycle
class JumpStartDataHolderType:
"""Base class for many JumpStart types.
Allows objects to be added to dicts and sets,
and improves string representation. This class overrides the ``__eq__``
and ``__hash__`` methods so that different objects with the same attributes/types
can be compared.
"""
__slots__: List[str] = []
_non_serializable_slots: List[str] = []
def __eq__(self, other: Any) -> bool:
"""Returns True if ``other`` is of the same type and has all attributes equal.
Args:
other (Any): Other object to which to compare this object.
"""
if not isinstance(other, type(self)):
return False
if getattr(other, "__slots__", None) is None:
return False
if self.__slots__ != other.__slots__:
return False
for attribute in self.__slots__:
if (hasattr(self, attribute) and not hasattr(other, attribute)) or (
hasattr(other, attribute) and not hasattr(self, attribute)
):
return False
if hasattr(self, attribute) and hasattr(other, attribute):
if getattr(self, attribute) != getattr(other, attribute):
return False
return True
def __hash__(self) -> int:
"""Makes hash of object.
Maps object to unique tuple, which then gets hashed.
"""
return hash((type(self),) + tuple([getattr(self, att) for att in self.__slots__]))
def __str__(self) -> str:
"""Returns string representation of object. Example:
"JumpStartLaunchedRegionInfo:
{'content_bucket': 'bucket', 'region_name': 'us-west-2'}"
"""
att_dict = {
att: getattr(self, att)
for att in self.__slots__
if hasattr(self, att) and att not in self._non_serializable_slots
}
return f"{type(self).__name__}: {str(att_dict)}"
def __repr__(self) -> str:
"""Returns ``__repr__`` string of object. Example:
"JumpStartLaunchedRegionInfo at 0x7f664529efa0:
{'content_bucket': 'bucket', 'region_name': 'us-west-2'}"
"""
att_dict = {
att: getattr(self, att)
for att in self.__slots__
if hasattr(self, att) and att not in self._non_serializable_slots
}
return f"{type(self).__name__} at {hex(id(self))}: {str(att_dict)}"
class JumpStartS3FileType(str, Enum):
"""Type of files published in JumpStart S3 distribution buckets."""
OPEN_WEIGHT_MANIFEST = "manifest"
OPEN_WEIGHT_SPECS = "specs"
PROPRIETARY_MANIFEST = "proprietary_manifest"
PROPRIETARY_SPECS = "proprietary_specs"
class HubType(str, Enum):
"""Enum for Hub objects."""
HUB = "Hub"
class HubContentType(str, Enum):
"""Enum for Hub content objects."""
MODEL = "Model"
NOTEBOOK = "Notebook"
MODEL_REFERENCE = "ModelReference"
JumpStartContentDataType = Union[JumpStartS3FileType, HubType, HubContentType]
class JumpStartLaunchedRegionInfo(JumpStartDataHolderType):
"""Data class for launched region info."""
__slots__ = ["content_bucket", "region_name", "gated_content_bucket", "neo_content_bucket"]
def __init__(
self,
content_bucket: str,
region_name: str,
gated_content_bucket: Optional[str] = None,
neo_content_bucket: Optional[str] = None,
):
"""Instantiates JumpStartLaunchedRegionInfo object.
Args:
content_bucket (str): Name of JumpStart s3 content bucket associated with region.
region_name (str): Name of JumpStart launched region.
gated_content_bucket (Optional[str[]): Name of JumpStart gated s3 content bucket
optionally associated with region.
neo_content_bucket (Optional[str]): Name of Neo service s3 content bucket
optionally associated with region.
"""
self.content_bucket = content_bucket
self.gated_content_bucket = gated_content_bucket
self.region_name = region_name
self.neo_content_bucket = neo_content_bucket
class JumpStartModelHeader(JumpStartDataHolderType):
"""Data class JumpStart model header."""
__slots__ = ["model_id", "version", "min_version", "spec_key", "search_keywords"]
def __init__(self, header: Dict[str, str]):
"""Initializes a JumpStartModelHeader object from its json representation.
Args:
header (Dict[str, str]): Dictionary representation of header.
"""
self.from_json(header)
def to_json(self) -> Dict[str, str]:
"""Returns json representation of JumpStartModelHeader object."""
json_obj = {
att: getattr(self, att)
for att in self.__slots__
if getattr(self, att, None) is not None
}
return json_obj
def from_json(self, json_obj: Dict[str, str]) -> None:
"""Sets fields in object based on json of header.
Args:
json_obj (Dict[str, str]): Dictionary representation of header.
"""
self.model_id: str = json_obj["model_id"]
self.version: str = json_obj["version"]
self.min_version: str = json_obj["min_version"]
self.spec_key: str = json_obj["spec_key"]
self.search_keywords: Optional[List[str]] = json_obj.get("search_keywords")
class JumpStartECRSpecs(JumpStartDataHolderType):
"""Data class for JumpStart ECR specs."""
__slots__ = [
"framework",
"framework_version",
"py_version",
"huggingface_transformers_version",
"_is_hub_content",
]
_non_serializable_slots = ["_is_hub_content"]
def __init__(self, spec: Dict[str, Any], is_hub_content: Optional[bool] = False):
"""Initializes a JumpStartECRSpecs object from its json representation.
Args:
spec (Dict[str, Any]): Dictionary representation of spec.
"""
self._is_hub_content = is_hub_content
self.from_json(spec)
def from_json(self, json_obj: Dict[str, Any]) -> None:
"""Sets fields in object based on json.
Args:
json_obj (Dict[str, Any]): Dictionary representation of spec.
"""
if not json_obj:
return
if self._is_hub_content:
json_obj = walk_and_apply_json(json_obj, camel_to_snake)
self.framework = json_obj.get("framework")
self.framework_version = json_obj.get("framework_version")
self.py_version = json_obj.get("py_version")
huggingface_transformers_version = json_obj.get("huggingface_transformers_version")
if huggingface_transformers_version is not None:
self.huggingface_transformers_version = huggingface_transformers_version
def to_json(self) -> Dict[str, Any]:
"""Returns json representation of JumpStartECRSpecs object."""
json_obj = {
att: getattr(self, att)
for att in self.__slots__
if hasattr(self, att) and att not in getattr(self, "_non_serializable_slots", [])
}
return json_obj
class JumpStartHyperparameter(JumpStartDataHolderType):
"""Data class for JumpStart hyperparameter definition in the training container."""
__slots__ = [
"name",
"type",
"options",
"default",
"scope",
"min",
"max",
"exclusive_min",
"exclusive_max",
"_is_hub_content",
]
_non_serializable_slots = ["_is_hub_content"]
def __init__(self, spec: Dict[str, Any], is_hub_content: Optional[bool] = False):
"""Initializes a JumpStartHyperparameter object from its json representation.
Args:
spec (Dict[str, Any]): Dictionary representation of hyperparameter.
"""
self._is_hub_content = is_hub_content
self.from_json(spec)
def from_json(self, json_obj: Dict[str, Any]) -> None:
"""Sets fields in object based on json.
Args:
json_obj (Dict[str, Any]): Dictionary representation of hyperparameter.
"""
if self._is_hub_content:
json_obj = walk_and_apply_json(json_obj, camel_to_snake)
self.name = json_obj["name"]
self.type = json_obj["type"]
self.default = json_obj["default"]
self.scope = json_obj["scope"]
options = json_obj.get("options")
if options is not None:
self.options = options
min_val = json_obj.get("min")
if min_val is not None:
self.min = min_val
max_val = json_obj.get("max")
if max_val is not None:
self.max = max_val
# HubContentDocument model schema does not allow exclusive min/max.
if self._is_hub_content:
return
exclusive_min_val = json_obj.get("exclusive_min")
exclusive_max_val = json_obj.get("exclusive_max")
if exclusive_min_val is not None:
self.exclusive_min = exclusive_min_val
if exclusive_max_val is not None:
self.exclusive_max = exclusive_max_val
def to_json(self) -> Dict[str, Any]:
"""Returns json representation of JumpStartHyperparameter object."""
json_obj = {
att: getattr(self, att)
for att in self.__slots__
if hasattr(self, att) and att not in getattr(self, "_non_serializable_slots", [])
}
return json_obj
class JumpStartEnvironmentVariable(JumpStartDataHolderType):
"""Data class for JumpStart environment variable definitions in the hosting container."""
__slots__ = [
"name",
"type",
"default",
"scope",
"required_for_model_class",
"_is_hub_content",
]
_non_serializable_slots = ["_is_hub_content"]
def __init__(self, spec: Dict[str, Any], is_hub_content: Optional[bool] = False):
"""Initializes a JumpStartEnvironmentVariable object from its json representation.
Args:
spec (Dict[str, Any]): Dictionary representation of environment variable.
"""
self._is_hub_content = is_hub_content
self.from_json(spec)
def from_json(self, json_obj: Dict[str, Any]) -> None:
"""Sets fields in object based on json.
Args:
json_obj (Dict[str, Any]): Dictionary representation of environment variable.
"""
json_obj = walk_and_apply_json(json_obj, camel_to_snake)
self.name = json_obj["name"]
self.type = json_obj["type"]
self.default = json_obj["default"]
self.scope = json_obj["scope"]
self.required_for_model_class: bool = json_obj.get("required_for_model_class", False)
def to_json(self) -> Dict[str, Any]:
"""Returns json representation of JumpStartEnvironmentVariable object."""
json_obj = {
att: getattr(self, att)
for att in self.__slots__
if hasattr(self, att) and att not in getattr(self, "_non_serializable_slots", [])
}
return json_obj
class JumpStartPredictorSpecs(JumpStartDataHolderType):
"""Data class for JumpStart Predictor specs."""
__slots__ = [
"default_content_type",
"supported_content_types",
"default_accept_type",
"supported_accept_types",
"_is_hub_content",
]
_non_serializable_slots = ["_is_hub_content"]
def __init__(self, spec: Optional[Dict[str, Any]], is_hub_content: Optional[bool] = False):
"""Initializes a JumpStartPredictorSpecs object from its json representation.
Args:
spec (Dict[str, Any]): Dictionary representation of predictor specs.
"""
self._is_hub_content = is_hub_content
self.from_json(spec)
def from_json(self, json_obj: Optional[Dict[str, Any]]) -> None:
"""Sets fields in object based on json.
Args:
json_obj (Dict[str, Any]): Dictionary representation of predictor specs.
"""
if json_obj is None:
return
if self._is_hub_content:
json_obj = walk_and_apply_json(json_obj, camel_to_snake)
self.default_content_type = json_obj["default_content_type"]
self.supported_content_types = json_obj["supported_content_types"]
self.default_accept_type = json_obj["default_accept_type"]
self.supported_accept_types = json_obj["supported_accept_types"]
def to_json(self) -> Dict[str, Any]:
"""Returns json representation of JumpStartPredictorSpecs object."""
json_obj = {
att: getattr(self, att)
for att in self.__slots__
if hasattr(self, att) and att not in getattr(self, "_non_serializable_slots", [])
}
return json_obj
class JumpStartSerializablePayload(JumpStartDataHolderType):
"""Data class for JumpStart serialized payload specs."""
__slots__ = [
"raw_payload",
"content_type",
"accept",
"body",
"prompt_key",
"_is_hub_content",
]
_non_serializable_slots = ["raw_payload", "prompt_key", "_is_hub_content"]
def __init__(self, spec: Optional[Dict[str, Any]], is_hub_content: Optional[bool] = False):
"""Initializes a JumpStartSerializablePayload object from its json representation.
Args:
spec (Dict[str, Any]): Dictionary representation of payload specs.
"""
self._is_hub_content = is_hub_content
self.from_json(spec)
def from_json(self, json_obj: Optional[Dict[str, Any]]) -> None:
"""Sets fields in object based on json.
Args:
json_obj (Dict[str, Any]): Dictionary representation of serializable
payload specs.
Raises:
KeyError: If the dictionary is missing keys.
"""
if json_obj is None:
return
if self._is_hub_content:
json_obj = walk_and_apply_json(json_obj, camel_to_snake)
self.raw_payload = json_obj
self.content_type = json_obj["content_type"]
self.body = json_obj.get("body")
accept = json_obj.get("accept")
self.prompt_key = json_obj.get("prompt_key")
if accept:
self.accept = accept
def to_json(self) -> Dict[str, Any]:
"""Returns json representation of JumpStartSerializablePayload object."""
return deepcopy(self.raw_payload)
class JumpStartInstanceTypeVariants(JumpStartDataHolderType):
"""Data class for JumpStart instance type variants."""
__slots__ = [
"regional_aliases",
"aliases",
"variants",
"_is_hub_content",
]
_non_serializable_slots = ["_is_hub_content"]
def __init__(self, spec: Optional[Dict[str, Any]], is_hub_content: Optional[bool] = False):
"""Initializes a JumpStartInstanceTypeVariants object from its json representation.
Args:
spec (Dict[str, Any]): Dictionary representation of instance type variants.
"""
self._is_hub_content = is_hub_content
if self._is_hub_content:
self.from_describe_hub_content_response(spec)
else:
self.from_json(spec)
def from_json(self, json_obj: Optional[Dict[str, Any]]) -> None:
"""Sets fields in object based on json.
Args:
json_obj (Dict[str, Any]): Dictionary representation of instance type variants.
"""
if json_obj is None:
return
self.aliases = None
self.regional_aliases: Optional[dict] = json_obj.get("regional_aliases")
self.variants: Optional[dict] = json_obj.get("variants")
def to_json(self) -> Dict[str, Any]:
"""Returns json representation of JumpStartInstance object."""
json_obj = {
att: getattr(self, att)
for att in self.__slots__
if hasattr(self, att) and att not in getattr(self, "_non_serializable_slots", [])
}
return json_obj
def from_describe_hub_content_response(self, response: Optional[Dict[str, Any]]) -> None:
"""Sets fields in object based on DescribeHubContent response.
Args:
response (Dict[str, Any]): Dictionary representation of instance type variants.
"""
if response is None:
return
response = walk_and_apply_json(response, camel_to_snake)
self.aliases: Optional[dict] = response.get("aliases")
self.regional_aliases = None
self.variants: Optional[dict] = response.get("variants")
def regionalize( # pylint: disable=inconsistent-return-statements
self, region: str
) -> Optional[Dict[str, Any]]:
"""Returns regionalized instance type variants."""
if self.regional_aliases is None or self.aliases is not None:
return
aliases = self.regional_aliases.get(region, {})
variants = {}
for instance_name, properties in self.variants.items():
if properties.get("regional_properties") is not None:
variants.update({instance_name: properties.get("regional_properties")})
if properties.get("properties") is not None:
variants.update({instance_name: properties.get("properties")})
return {"Aliases": aliases, "Variants": variants}
def get_instance_specific_metric_definitions(
self, instance_type: str
) -> List[JumpStartHyperparameter]:
"""Returns instance specific metric definitions.
Returns empty list if a model, instance type tuple does not have specific
metric definitions.
"""
if self.variants is None:
return []
instance_specific_metric_definitions: List[Dict[str, Union[str, Any]]] = (
self.variants.get(instance_type, {}).get("properties", {}).get("metrics", [])
)
instance_type_family = get_instance_type_family(instance_type)
instance_family_metric_definitions: List[Dict[str, Union[str, Any]]] = (
self.variants.get(instance_type_family, {}).get("properties", {}).get("metrics", [])
if instance_type_family not in {"", None}
else []
)
instance_specific_metric_names = {
metric_definition["Name"] for metric_definition in instance_specific_metric_definitions
}
metric_definitions_to_return = deepcopy(instance_specific_metric_definitions)
for instance_family_metric_definition in instance_family_metric_definitions:
if instance_family_metric_definition["Name"] not in instance_specific_metric_names:
metric_definitions_to_return.append(instance_family_metric_definition)
return metric_definitions_to_return
def get_instance_specific_prepacked_artifact_key(self, instance_type: str) -> Optional[str]:
"""Returns instance specific model artifact key.
Returns None if a model, instance type tuple does not have specific
artifact key.
"""
return self._get_instance_specific_property(
instance_type=instance_type, property_name="prepacked_artifact_key"
)
def get_instance_specific_artifact_key(self, instance_type: str) -> Optional[str]:
"""Returns instance specific model artifact key.
Returns None if a model, instance type tuple does not have specific
artifact key.
"""
return self._get_instance_specific_property(
instance_type=instance_type, property_name="artifact_key"
)
def get_instance_specific_training_artifact_key(self, instance_type: str) -> Optional[str]:
"""Returns instance specific training artifact key.
Returns None if a model, instance type tuple does not have specific
training artifact key.
"""
return self._get_instance_specific_property(
instance_type=instance_type, property_name="training_artifact_uri"
) or self._get_instance_specific_property(
instance_type=instance_type, property_name="training_artifact_key"
)
def get_instance_specific_resource_requirements(self, instance_type: str) -> Optional[str]:
"""Returns instance specific resource requirements.
If a value exists for both the instance family and instance type, the instance type value
is chosen.
"""
instance_specific_resource_requirements: dict = (
self.variants.get(instance_type, {})
.get("properties", {})
.get("resource_requirements", {})
)
instance_type_family = get_instance_type_family(instance_type)
instance_family_resource_requirements: dict = (
self.variants.get(instance_type_family, {})
.get("properties", {})
.get("resource_requirements", {})
)
return {**instance_family_resource_requirements, **instance_specific_resource_requirements}
def _get_instance_specific_property(
self, instance_type: str, property_name: str
) -> Optional[str]:
"""Returns instance specific property.
If a value exists for both the instance family and instance type,
the instance type value is chosen.
Returns None if a (model, instance type, property name) tuple does not have
specific prepacked artifact key.
"""
if self.variants is None:
return None
instance_specific_property: Optional[str] = (
self.variants.get(instance_type, {}).get("properties", {}).get(property_name, None)
)
if instance_specific_property:
return instance_specific_property
instance_type_family = get_instance_type_family(instance_type)
instance_family_property: Optional[str] = (
self.variants.get(instance_type_family, {})
.get("properties", {})
.get(property_name, None)
if instance_type_family not in {"", None}
else None
)
return instance_family_property
def get_instance_specific_hyperparameters(
self, instance_type: str
) -> List[JumpStartHyperparameter]:
"""Returns instance specific hyperparameters.
Returns empty list if a model, instance type tuple does not have specific
hyperparameters.
"""
if self.variants is None:
return []
instance_specific_hyperparameters: List[JumpStartHyperparameter] = [
JumpStartHyperparameter(json)
for json in self.variants.get(instance_type, {})
.get("properties", {})
.get("hyperparameters", [])
]
instance_type_family = get_instance_type_family(instance_type)
instance_family_hyperparameters: List[JumpStartHyperparameter] = [
JumpStartHyperparameter(json)
for json in (
self.variants.get(instance_type_family, {})
.get("properties", {})
.get("hyperparameters", [])
if instance_type_family not in {"", None}
else []
)
]
instance_specific_hyperparameter_names = {
hyperparameter.name for hyperparameter in instance_specific_hyperparameters
}
hyperparams_to_return = deepcopy(instance_specific_hyperparameters)
for hyperparameter in instance_family_hyperparameters:
if hyperparameter.name not in instance_specific_hyperparameter_names:
hyperparams_to_return.append(hyperparameter)
return hyperparams_to_return
def get_instance_specific_environment_variables(self, instance_type: str) -> Dict[str, str]:
"""Returns instance specific environment variables.
Returns empty dict if a model, instance type tuple does not have specific
environment variables.
"""
if self.variants is None:
return {}
instance_specific_environment_variables: Dict[str, str] = (
self.variants.get(instance_type, {})
.get("properties", {})
.get("environment_variables", {})
)
instance_type_family = get_instance_type_family(instance_type)
instance_family_environment_variables: dict = (
self.variants.get(instance_type_family, {})
.get("properties", {})
.get("environment_variables", {})
if instance_type_family not in {"", None}
else {}
)
instance_family_environment_variables.update(instance_specific_environment_variables)
return instance_family_environment_variables
def get_instance_specific_gated_model_key_env_var_value(
self, instance_type: str
) -> Optional[str]:
"""Returns instance specific gated model env var s3 key.
Returns None if a model, instance type tuple does not have instance
specific property.
"""
gated_model_key_env_var_value = (
"gated_model_env_var_uri" if self._is_hub_content else "gated_model_key_env_var_value"
)
return self._get_instance_specific_property(instance_type, gated_model_key_env_var_value)
def get_instance_specific_default_inference_instance_type(
self, instance_type: str
) -> Optional[str]:
"""Returns instance specific default inference instance type.
Returns None if a model, instance type tuple does not have instance
specific inference instance types.
"""
return self._get_instance_specific_property(
instance_type, "default_inference_instance_type"
)
def get_instance_specific_supported_inference_instance_types(
self, instance_type: str
) -> List[str]:
"""Returns instance specific supported inference instance types.
Returns empty list if a model, instance type tuple does not have instance
specific inference instance types.
"""
if self.variants is None:
return []
instance_specific_inference_instance_types: List[str] = (
self.variants.get(instance_type, {})
.get("properties", {})
.get("supported_inference_instance_types", [])
)
instance_type_family = get_instance_type_family(instance_type)
instance_family_inference_instance_types: List[str] = (
self.variants.get(instance_type_family, {})
.get("properties", {})
.get("supported_inference_instance_types", [])
if instance_type_family not in {"", None}
else []
)
return sorted(
list(
set(
instance_specific_inference_instance_types
+ instance_family_inference_instance_types
)
)
)
def get_image_uri(self, instance_type: str, region: Optional[str] = None) -> Optional[str]:
"""Returns image uri from instance type and region.
Returns None if no instance type is available or found.
None is also returned if the metadata is improperly formatted.
"""
return self._get_regional_property(
instance_type=instance_type, region=region, property_name="image_uri"
)
def get_model_package_arn(self, instance_type: str, region: str) -> Optional[str]:
"""Returns model package arn from instance type and region.
Returns None if no instance type is available or found.
None is also returned if the metadata is improperly formatted.
"""
return self._get_regional_property(
instance_type=instance_type, region=region, property_name="model_package_arn"
)
def _get_regional_property(
self, instance_type: str, region: Optional[str], property_name: str
) -> Optional[str]:
"""Returns regional property from instance type and region.
Returns None if no instance type is available or found.
None is also returned if the metadata is improperly formatted.
"""
# pylint: disable=too-many-return-statements
# if self.variants is None or (self.aliases is None and self.regional_aliases is None):
# return None
if self.variants is None:
return None
if region is None and self.regional_aliases is not None:
return None
regional_property_alias: Optional[str] = None
regional_property_value: Optional[str] = None
if self.regional_aliases:
regional_property_alias = (
self.variants.get(instance_type, {})
.get("regional_properties", {})
.get(property_name)
)
else:
regional_property_value = (
self.variants.get(instance_type, {}).get("properties", {}).get(property_name)
)
if regional_property_alias is None and regional_property_value is None:
instance_type_family = get_instance_type_family(instance_type)
if instance_type_family in {"", None}:
return None
if self.regional_aliases:
regional_property_alias = (
self.variants.get(instance_type_family, {})
.get("regional_properties", {})
.get(property_name)
)
else:
# if reading from HubContent, aliases are already regionalized
regional_property_value = (
self.variants.get(instance_type_family, {})
.get("properties", {})
.get(property_name)
)
if (regional_property_alias is None or len(regional_property_alias) == 0) and (
regional_property_value is None or len(regional_property_value) == 0
):
return None
if regional_property_alias and not regional_property_alias.startswith("$"):
# No leading '$' indicates bad metadata.
# There are tests to ensure this never happens.
# However, to allow for fallback options in the unlikely event
# of a regression, we do not raise an exception here.
# We return None, indicating the field does not exist.
return None
if self.regional_aliases and region not in self.regional_aliases:
return None
if self.regional_aliases:
alias_value = self.regional_aliases[region].get(regional_property_alias[1:], None)
return alias_value
return regional_property_value
class JumpStartAdditionalDataSources(JumpStartDataHolderType):
"""Data class of additional data sources."""
__slots__ = ["speculative_decoding", "scripts"]
def __init__(self, spec: Dict[str, Any]):
"""Initializes a AdditionalDataSources object.
Args:
spec (Dict[str, Any]): Dictionary representation of data source.
"""
self.from_json(spec)
def from_json(self, json_obj: Dict[str, Any]) -> None:
"""Sets fields in object based on json.
Args:
json_obj (Dict[str, Any]): Dictionary representation of data source.
"""
self.speculative_decoding: Optional[List[JumpStartModelDataSource]] = (
[
JumpStartModelDataSource(data_source)
for data_source in json_obj["speculative_decoding"]
]
if json_obj.get("speculative_decoding")
else None
)
self.scripts: Optional[List[JumpStartModelDataSource]] = (
[JumpStartModelDataSource(data_source) for data_source in json_obj["scripts"]]
if json_obj.get("scripts")
else None
)
def to_json(self) -> Dict[str, Any]:
"""Returns json representation of AdditionalDataSources object."""
json_obj = {}
for att in self.__slots__:
if hasattr(self, att):
cur_val = getattr(self, att)
if isinstance(cur_val, list):
json_obj[att] = []
for obj in cur_val:
if issubclass(type(obj), JumpStartDataHolderType):
json_obj[att].append(obj.to_json())
else:
json_obj[att].append(obj)
else:
json_obj[att] = cur_val
return json_obj
class ModelAccessConfig(JumpStartDataHolderType):
"""Data class of model access config that mirrors CreateModel API."""
__slots__ = ["accept_eula"]
def __init__(self, spec: Dict[str, Any]):
"""Initializes a ModelAccessConfig object.
Args:
spec (Dict[str, Any]): Dictionary representation of data source.
"""
self.from_json(spec)
def from_json(self, json_obj: Dict[str, Any]) -> None:
"""Sets fields in object based on json.
Args:
json_obj (Dict[str, Any]): Dictionary representation of data source.
"""
self.accept_eula: bool = json_obj["accept_eula"]
def to_json(self) -> Dict[str, Any]:
"""Returns json representation of ModelAccessConfig object."""
json_obj = {att: getattr(self, att) for att in self.__slots__ if hasattr(self, att)}
return json_obj