-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
utils.py
1925 lines (1518 loc) · 65.8 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
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.
"""Placeholder docstring"""
from __future__ import absolute_import
import contextlib
import copy
import errno
import inspect
import logging
import os
import random
import re
import shutil
import tarfile
import tempfile
import time
from functools import lru_cache
from typing import Union, Any, List, Optional, Dict
import json
import abc
import uuid
from datetime import datetime
from os.path import abspath, realpath, dirname, normpath, join as joinpath
from importlib import import_module
import boto3
import botocore
from botocore.utils import merge_dicts
from six.moves.urllib import parse
from six import viewitems
from sagemaker import deprecations
from sagemaker.config import validate_sagemaker_config
from sagemaker.config.config_utils import (
_log_sagemaker_config_single_substitution,
_log_sagemaker_config_merge,
)
from sagemaker.enums import RoutingStrategy
from sagemaker.session_settings import SessionSettings
from sagemaker.workflow import is_pipeline_variable, is_pipeline_parameter_string
from sagemaker.workflow.entities import PipelineVariable
ALTERNATE_DOMAINS = {
"cn-north-1": "amazonaws.com.cn",
"cn-northwest-1": "amazonaws.com.cn",
"us-iso-east-1": "c2s.ic.gov",
"us-isob-east-1": "sc2s.sgov.gov",
"us-isof-south-1": "csp.hci.ic.gov",
"us-isof-east-1": "csp.hci.ic.gov",
}
ECR_URI_PATTERN = r"^(\d+)(\.)dkr(\.)ecr(\.)(.+)(\.)(.*)(/)(.*:.*)$"
MODEL_PACKAGE_ARN_PATTERN = (
r"arn:aws([a-z\-]*)?:sagemaker:([a-z0-9\-]*):([0-9]{12}):model-package/(.*)"
)
MODEL_ARN_PATTERN = r"arn:aws([a-z\-]*):sagemaker:([a-z0-9\-]*):([0-9]{12}):model/(.*)"
MAX_BUCKET_PATHS_COUNT = 5
S3_PREFIX = "s3://"
HTTP_PREFIX = "http://"
HTTPS_PREFIX = "https://"
DEFAULT_SLEEP_TIME_SECONDS = 10
WAITING_DOT_NUMBER = 10
MAX_ITEMS = 100
PAGE_SIZE = 10
logger = logging.getLogger(__name__)
TagsDict = Dict[str, Union[str, PipelineVariable]]
Tags = Union[List[TagsDict], TagsDict]
# Use the base name of the image as the job name if the user doesn't give us one
def name_from_image(image, max_length=63):
"""Create a training job name based on the image name and a timestamp.
Args:
image (str): Image name.
Returns:
str: Training job name using the algorithm from the image name and a
timestamp.
max_length (int): Maximum length for the resulting string (default: 63).
"""
return name_from_base(base_name_from_image(image), max_length=max_length)
def name_from_base(base, max_length=63, short=False):
"""Append a timestamp to the provided string.
This function assures that the total length of the resulting string is
not longer than the specified max length, trimming the input parameter if
necessary.
Args:
base (str): String used as prefix to generate the unique name.
max_length (int): Maximum length for the resulting string (default: 63).
short (bool): Whether or not to use a truncated timestamp (default: False).
Returns:
str: Input parameter with appended timestamp.
"""
timestamp = sagemaker_short_timestamp() if short else sagemaker_timestamp()
trimmed_base = base[: max_length - len(timestamp) - 1]
return "{}-{}".format(trimmed_base, timestamp)
def unique_name_from_base_uuid4(base, max_length=63):
"""Append a UUID to the provided string.
This function is used to generate a name using UUID instead of timestamps
for uniqueness.
Args:
base (str): String used as prefix to generate the unique name.
max_length (int): Maximum length for the resulting string (default: 63).
Returns:
str: Input parameter with appended timestamp.
"""
random.seed(int(uuid.uuid4())) # using uuid to randomize
unique = str(uuid.uuid4())
trimmed_base = base[: max_length - len(unique) - 1]
return "{}-{}".format(trimmed_base, unique)
def unique_name_from_base(base, max_length=63):
"""Placeholder Docstring"""
random.seed(int(uuid.uuid4())) # using uuid to randomize, otherwise system timestamp is used.
unique = "%04x" % random.randrange(16**4) # 4-digit hex
ts = str(int(time.time()))
available_length = max_length - 2 - len(ts) - len(unique)
trimmed = base[:available_length]
return "{}-{}-{}".format(trimmed, ts, unique)
def base_name_from_image(image, default_base_name=None):
"""Extract the base name of the image to use as the 'algorithm name' for the job.
Args:
image (str): Image name.
default_base_name (str): The default base name
Returns:
str: Algorithm name, as extracted from the image name.
"""
if is_pipeline_variable(image):
if is_pipeline_parameter_string(image) and image.default_value:
image_str = image.default_value
else:
return default_base_name if default_base_name else "base_name"
else:
image_str = image
m = re.match("^(.+/)?([^:/]+)(:[^:]+)?$", image_str)
base_name = m.group(2) if m else image_str
return base_name
def base_from_name(name):
"""Extract the base name of the resource name (for use with future resource name generation).
This function looks for timestamps that match the ones produced by
:func:`~sagemaker.utils.name_from_base`.
Args:
name (str): The resource name.
Returns:
str: The base name, as extracted from the resource name.
"""
m = re.match(r"^(.+)-(\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}-\d{3}|\d{6}-\d{4})", name)
return m.group(1) if m else name
def sagemaker_timestamp():
"""Return a timestamp with millisecond precision."""
moment = time.time()
moment_ms = repr(moment).split(".")[1][:3]
return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_ms), time.gmtime(moment))
def sagemaker_short_timestamp():
"""Return a timestamp that is relatively short in length"""
return time.strftime("%y%m%d-%H%M")
def build_dict(key, value):
"""Return a dict of key and value pair if value is not None, otherwise return an empty dict.
Args:
key (str): input key
value (str): input value
Returns:
dict: dict of key and value or an empty dict.
"""
if value:
return {key: value}
return {}
def get_config_value(key_path, config):
"""Placeholder Docstring"""
if config is None:
return None
current_section = config
for key in key_path.split("."):
if key in current_section:
current_section = current_section[key]
else:
return None
return current_section
def get_nested_value(dictionary: dict, nested_keys: List[str]):
"""Returns a nested value from the given dictionary, and None if none present.
Raises
ValueError if the dictionary structure does not match the nested_keys
"""
if (
dictionary is not None
and isinstance(dictionary, dict)
and nested_keys is not None
and len(nested_keys) > 0
):
current_section = dictionary
for key in nested_keys[:-1]:
current_section = current_section.get(key, None)
if current_section is None:
# means the full path of nested_keys doesnt exist in the dictionary
# or the value was set to None
return None
if not isinstance(current_section, dict):
raise ValueError(
"Unexpected structure of dictionary.",
"Expected value of type dict at key '{}' but got '{}' for dict '{}'".format(
key, current_section, dictionary
),
)
return current_section.get(nested_keys[-1], None)
return None
def set_nested_value(dictionary: dict, nested_keys: List[str], value_to_set: object):
"""Sets a nested value in a dictionary.
This sets a nested value inside the given dictionary and returns the new dictionary. Note: if
provided an unintended list of nested keys, this can overwrite an unexpected part of the dict.
Recommended to use after a check with get_nested_value first
"""
if dictionary is None:
dictionary = {}
if (
dictionary is not None
and isinstance(dictionary, dict)
and nested_keys is not None
and len(nested_keys) > 0
):
current_section = dictionary
for key in nested_keys[:-1]:
if (
key not in current_section
or current_section[key] is None
or not isinstance(current_section[key], dict)
):
current_section[key] = {}
current_section = current_section[key]
current_section[nested_keys[-1]] = value_to_set
return dictionary
def get_short_version(framework_version):
"""Return short version in the format of x.x
Args:
framework_version: The version string to be shortened.
Returns:
str: The short version string
"""
return ".".join(framework_version.split(".")[:2])
def secondary_training_status_changed(current_job_description, prev_job_description):
"""Returns true if training job's secondary status message has changed.
Args:
current_job_description: Current job description, returned from DescribeTrainingJob call.
prev_job_description: Previous job description, returned from DescribeTrainingJob call.
Returns:
boolean: Whether the secondary status message of a training job changed
or not.
"""
current_secondary_status_transitions = current_job_description.get("SecondaryStatusTransitions")
if (
current_secondary_status_transitions is None
or len(current_secondary_status_transitions) == 0
):
return False
prev_job_secondary_status_transitions = (
prev_job_description.get("SecondaryStatusTransitions")
if prev_job_description is not None
else None
)
last_message = (
prev_job_secondary_status_transitions[-1]["StatusMessage"]
if prev_job_secondary_status_transitions is not None
and len(prev_job_secondary_status_transitions) > 0
else ""
)
message = current_job_description["SecondaryStatusTransitions"][-1]["StatusMessage"]
return message != last_message
def secondary_training_status_message(job_description, prev_description):
"""Returns a string contains last modified time and the secondary training job status message.
Args:
job_description: Returned response from DescribeTrainingJob call
prev_description: Previous job description from DescribeTrainingJob call
Returns:
str: Job status string to be printed.
"""
if (
job_description is None
or job_description.get("SecondaryStatusTransitions") is None
or len(job_description.get("SecondaryStatusTransitions")) == 0
):
return ""
prev_description_secondary_transitions = (
prev_description.get("SecondaryStatusTransitions") if prev_description is not None else None
)
prev_transitions_num = (
len(prev_description["SecondaryStatusTransitions"])
if prev_description_secondary_transitions is not None
else 0
)
current_transitions = job_description["SecondaryStatusTransitions"]
if len(current_transitions) == prev_transitions_num:
# Secondary status is not changed but the message changed.
transitions_to_print = current_transitions[-1:]
else:
# Secondary status is changed we need to print all the entries.
transitions_to_print = current_transitions[
prev_transitions_num - len(current_transitions) :
]
status_strs = []
for transition in transitions_to_print:
message = transition["StatusMessage"]
time_str = datetime.utcfromtimestamp(
time.mktime(job_description["LastModifiedTime"].timetuple())
).strftime("%Y-%m-%d %H:%M:%S")
status_strs.append("{} {} - {}".format(time_str, transition["Status"], message))
return "\n".join(status_strs)
def download_folder(bucket_name, prefix, target, sagemaker_session):
"""Download a folder from S3 to a local path
Args:
bucket_name (str): S3 bucket name
prefix (str): S3 prefix within the bucket that will be downloaded. Can
be a single file.
target (str): destination path where the downloaded items will be placed
sagemaker_session (sagemaker.session.Session): a sagemaker session to
interact with S3.
"""
boto_session = sagemaker_session.boto_session
s3 = boto_session.resource("s3", region_name=boto_session.region_name)
prefix = prefix.lstrip("/")
# Try to download the prefix as an object first, in case it is a file and not a 'directory'.
# Do this first, in case the object has broader permissions than the bucket.
if not prefix.endswith("/"):
try:
file_destination = os.path.join(target, os.path.basename(prefix))
s3.Object(bucket_name, prefix).download_file(file_destination)
return
except botocore.exceptions.ClientError as e:
err_info = e.response["Error"]
if err_info["Code"] == "404" and err_info["Message"] == "Not Found":
# S3 also throws this error if the object is a folder,
# so assume that is the case here, and then raise for an actual 404 later.
pass
else:
raise
_download_files_under_prefix(bucket_name, prefix, target, s3)
def _download_files_under_prefix(bucket_name, prefix, target, s3):
"""Download all S3 files which match the given prefix
Args:
bucket_name (str): S3 bucket name
prefix (str): S3 prefix within the bucket that will be downloaded
target (str): destination path where the downloaded items will be placed
s3 (boto3.resources.base.ServiceResource): S3 resource
"""
bucket = s3.Bucket(bucket_name)
for obj_sum in bucket.objects.filter(Prefix=prefix):
# if obj_sum is a folder object skip it.
if obj_sum.key.endswith("/"):
continue
obj = s3.Object(obj_sum.bucket_name, obj_sum.key)
s3_relative_path = obj_sum.key[len(prefix) :].lstrip("/")
file_path = os.path.join(target, s3_relative_path)
try:
os.makedirs(os.path.dirname(file_path))
except OSError as exc:
# EEXIST means the folder already exists, this is safe to skip
# anything else will be raised.
if exc.errno != errno.EEXIST:
raise
obj.download_file(file_path)
def create_tar_file(source_files, target=None):
"""Create a tar file containing all the source_files
Args:
source_files: (List[str]): List of file paths that will be contained in the tar file
target:
Returns:
(str): path to created tar file
"""
if target:
filename = target
else:
_, filename = tempfile.mkstemp()
with tarfile.open(filename, mode="w:gz", dereference=True) as t:
for sf in source_files:
# Add all files from the directory into the root of the directory structure of the tar
t.add(sf, arcname=os.path.basename(sf))
return filename
@contextlib.contextmanager
def _tmpdir(suffix="", prefix="tmp", directory=None):
"""Create a temporary directory with a context manager.
The file is deleted when the context exits, even when there's an exception.
The prefix, suffix, and dir arguments are the same as for mkstemp().
Args:
suffix (str): If suffix is specified, the file name will end with that
suffix, otherwise there will be no suffix.
prefix (str): If prefix is specified, the file name will begin with that
prefix; otherwise, a default prefix is used.
directory (str): If a directory is specified, the file will be downloaded
in this directory; otherwise, a default directory is used.
Returns:
str: path to the directory
"""
if directory is not None and not (os.path.exists(directory) and os.path.isdir(directory)):
raise ValueError(
"Inputted directory for storing newly generated temporary "
f"directory does not exist: '{directory}'"
)
tmp = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=directory)
try:
yield tmp
finally:
shutil.rmtree(tmp)
def repack_model(
inference_script,
source_directory,
dependencies,
model_uri,
repacked_model_uri,
sagemaker_session,
kms_key=None,
):
"""Unpack model tarball and creates a new model tarball with the provided code script.
This function does the following: - uncompresses model tarball from S3 or
local system into a temp folder - replaces the inference code from the model
with the new code provided - compresses the new model tarball and saves it
in S3 or local file system
Args:
inference_script (str): path or basename of the inference script that
will be packed into the model
source_directory (str): path including all the files that will be packed
into the model
dependencies (list[str]): A list of paths to directories (absolute or
relative) with any additional libraries that will be exported to the
container (default: []). The library folders will be copied to
SageMaker in the same folder where the entrypoint is copied.
Example
The following call >>> Estimator(entry_point='train.py',
dependencies=['my/libs/common', 'virtual-env']) results in the
following inside the container:
>>> $ ls
>>> opt/ml/code
>>> |------ train.py
>>> |------ common
>>> |------ virtual-env
model_uri (str): S3 or file system location of the original model tar
repacked_model_uri (str): path or file system location where the new
model will be saved
sagemaker_session (sagemaker.session.Session): a sagemaker session to
interact with S3.
kms_key (str): KMS key ARN for encrypting the repacked model file
Returns:
str: path to the new packed model
"""
dependencies = dependencies or []
local_download_dir = (
None
if sagemaker_session.settings is None
or sagemaker_session.settings.local_download_dir is None
else sagemaker_session.settings.local_download_dir
)
with _tmpdir(directory=local_download_dir) as tmp:
model_dir = _extract_model(model_uri, sagemaker_session, tmp)
_create_or_update_code_dir(
model_dir,
inference_script,
source_directory,
dependencies,
sagemaker_session,
tmp,
)
tmp_model_path = os.path.join(tmp, "temp-model.tar.gz")
with tarfile.open(tmp_model_path, mode="w:gz") as t:
t.add(model_dir, arcname=os.path.sep)
_save_model(repacked_model_uri, tmp_model_path, sagemaker_session, kms_key=kms_key)
def _save_model(repacked_model_uri, tmp_model_path, sagemaker_session, kms_key):
"""Placeholder docstring"""
if repacked_model_uri.lower().startswith("s3://"):
url = parse.urlparse(repacked_model_uri)
bucket, key = url.netloc, url.path.lstrip("/")
new_key = key.replace(os.path.basename(key), os.path.basename(repacked_model_uri))
settings = (
sagemaker_session.settings if sagemaker_session is not None else SessionSettings()
)
encrypt_artifact = settings.encrypt_repacked_artifacts
if kms_key:
extra_args = {"ServerSideEncryption": "aws:kms", "SSEKMSKeyId": kms_key}
elif encrypt_artifact:
extra_args = {"ServerSideEncryption": "aws:kms"}
else:
extra_args = None
sagemaker_session.boto_session.resource(
"s3", region_name=sagemaker_session.boto_region_name
).Object(bucket, new_key).upload_file(tmp_model_path, ExtraArgs=extra_args)
else:
shutil.move(tmp_model_path, repacked_model_uri.replace("file://", ""))
def _create_or_update_code_dir(
model_dir, inference_script, source_directory, dependencies, sagemaker_session, tmp
):
"""Placeholder docstring"""
code_dir = os.path.join(model_dir, "code")
if source_directory and source_directory.lower().startswith("s3://"):
local_code_path = os.path.join(tmp, "local_code.tar.gz")
download_file_from_url(source_directory, local_code_path, sagemaker_session)
with tarfile.open(name=local_code_path, mode="r:gz") as t:
custom_extractall_tarfile(t, code_dir)
elif source_directory:
if os.path.exists(code_dir):
shutil.rmtree(code_dir)
shutil.copytree(source_directory, code_dir)
else:
if not os.path.exists(code_dir):
os.mkdir(code_dir)
try:
shutil.copy2(inference_script, code_dir)
except FileNotFoundError:
if os.path.exists(os.path.join(code_dir, inference_script)):
pass
else:
raise
for dependency in dependencies:
lib_dir = os.path.join(code_dir, "lib")
if os.path.isdir(dependency):
shutil.copytree(dependency, os.path.join(lib_dir, os.path.basename(dependency)))
else:
if not os.path.exists(lib_dir):
os.mkdir(lib_dir)
shutil.copy2(dependency, lib_dir)
def _extract_model(model_uri, sagemaker_session, tmp):
"""Placeholder docstring"""
tmp_model_dir = os.path.join(tmp, "model")
os.mkdir(tmp_model_dir)
if model_uri.lower().startswith("s3://"):
local_model_path = os.path.join(tmp, "tar_file")
download_file_from_url(model_uri, local_model_path, sagemaker_session)
else:
local_model_path = model_uri.replace("file://", "")
with tarfile.open(name=local_model_path, mode="r:gz") as t:
custom_extractall_tarfile(t, tmp_model_dir)
return tmp_model_dir
def download_file_from_url(url, dst, sagemaker_session):
"""Placeholder docstring"""
url = parse.urlparse(url)
bucket, key = url.netloc, url.path.lstrip("/")
download_file(bucket, key, dst, sagemaker_session)
def download_file(bucket_name, path, target, sagemaker_session):
"""Download a Single File from S3 into a local path
Args:
bucket_name (str): S3 bucket name
path (str): file path within the bucket
target (str): destination directory for the downloaded file.
sagemaker_session (sagemaker.session.Session): a sagemaker session to
interact with S3.
"""
path = path.lstrip("/")
boto_session = sagemaker_session.boto_session
s3 = boto_session.resource("s3", region_name=sagemaker_session.boto_region_name)
bucket = s3.Bucket(bucket_name)
bucket.download_file(path, target)
def sts_regional_endpoint(region):
"""Get the AWS STS endpoint specific for the given region.
We need this function because the AWS SDK does not yet honor
the ``region_name`` parameter when creating an AWS STS client.
For the list of regional endpoints, see
https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html#id_credentials_region-endpoints.
Args:
region (str): AWS region name
Returns:
str: AWS STS regional endpoint
"""
endpoint_data = _botocore_resolver().construct_endpoint("sts", region)
if region == "il-central-1" and not endpoint_data:
endpoint_data = {"hostname": "sts.{}.amazonaws.com".format(region)}
return "https://{}".format(endpoint_data["hostname"])
def retries(
max_retry_count,
exception_message_prefix,
seconds_to_sleep=DEFAULT_SLEEP_TIME_SECONDS,
):
"""Retries until max retry count is reached.
Args:
max_retry_count (int): The retry count.
exception_message_prefix (str): The message to include in the exception on failure.
seconds_to_sleep (int): The number of seconds to sleep between executions.
"""
for i in range(max_retry_count):
yield i
time.sleep(seconds_to_sleep)
raise Exception(
"'{}' has reached the maximum retry count of {}".format(
exception_message_prefix, max_retry_count
)
)
def retry_with_backoff(callable_func, num_attempts=8, botocore_client_error_code=None):
"""Retry with backoff until maximum attempts are reached
Args:
callable_func (callable): The callable function to retry.
num_attempts (int): The maximum number of attempts to retry.(Default: 8)
botocore_client_error_code (str): The specific Botocore ClientError exception error code
on which to retry on.
If provided other exceptions will be raised directly w/o retry.
If not provided, retry on any exception.
(Default: None)
"""
if num_attempts < 1:
raise ValueError(
"The num_attempts must be >= 1, but the given value is {}.".format(num_attempts)
)
for i in range(num_attempts):
try:
return callable_func()
except Exception as ex: # pylint: disable=broad-except
if not botocore_client_error_code or (
botocore_client_error_code
and isinstance(ex, botocore.exceptions.ClientError)
and ex.response["Error"]["Code"] # pylint: disable=no-member
== botocore_client_error_code
):
if i == num_attempts - 1:
raise ex
else:
raise ex
logger.error("Retrying in attempt %s, due to %s", (i + 1), str(ex))
time.sleep(2**i)
def _botocore_resolver():
"""Get the DNS suffix for the given region.
Args:
region (str): AWS region name
Returns:
str: the DNS suffix
"""
loader = botocore.loaders.create_loader()
return botocore.regions.EndpointResolver(loader.load_data("endpoints"))
def aws_partition(region):
"""Given a region name (ex: "cn-north-1"), return the corresponding aws partition ("aws-cn").
Args:
region (str): The region name for which to return the corresponding partition.
Ex: "cn-north-1"
Returns:
str: partition corresponding to the region name passed in. Ex: "aws-cn"
"""
endpoint_data = _botocore_resolver().construct_endpoint("sts", region)
if region == "il-central-1" and not endpoint_data:
endpoint_data = {"hostname": "sts.{}.amazonaws.com".format(region)}
return endpoint_data["partition"]
class DeferredError(object):
"""Stores an exception and raises it at a later time if this object is accessed in any way.
Useful to allow soft-dependencies on imports, so that the ImportError can be raised again
later if code actually relies on the missing library.
Example::
try:
import obscurelib
except ImportError as e:
logger.warning("Failed to import obscurelib. Obscure features will not work.")
obscurelib = DeferredError(e)
"""
def __init__(self, exception):
"""Placeholder docstring"""
self.exc = exception
def __getattr__(self, name):
"""Called by Python interpreter before using any method or property on the object.
So this will short-circuit essentially any access to this object.
Args:
name:
"""
raise self.exc
def _module_import_error(py_module, feature, extras):
"""Return error message for module import errors, provide installation details.
Args:
py_module (str): Module that failed to be imported
feature (str): Affected SageMaker feature
extras (str): Name of the `extras_require` to install the relevant dependencies
Returns:
str: Error message with installation instructions.
"""
error_msg = (
"Failed to import {}. {} features will be impaired or broken. "
"Please run \"pip install 'sagemaker[{}]'\" "
"to install all required dependencies."
)
return error_msg.format(py_module, feature, extras)
class DataConfig(abc.ABC):
"""Abstract base class for accessing data config hosted in AWS resources.
Provides a skeleton for customization by overriding of method fetch_data_config.
"""
@abc.abstractmethod
def fetch_data_config(self):
"""Abstract method implementing retrieval of data config from a pre-configured data source.
Returns:
object: The data configuration object.
"""
class S3DataConfig(DataConfig):
"""This class extends the DataConfig class to fetch a data config file hosted on S3"""
def __init__(
self,
sagemaker_session,
bucket_name,
prefix,
):
"""Initialize a ``S3DataConfig`` instance.
Args:
sagemaker_session (Session): SageMaker session instance to use for boto configuration.
bucket_name (str): Required. Bucket name from which data config needs to be fetched.
prefix (str): Required. The object prefix for the hosted data config.
"""
if bucket_name is None or prefix is None:
raise ValueError(
"Bucket Name and S3 file Prefix are required arguments and must be provided."
)
super(S3DataConfig, self).__init__()
self.bucket_name = bucket_name
self.prefix = prefix
self.sagemaker_session = sagemaker_session
def fetch_data_config(self):
"""Fetches data configuration from a S3 bucket.
Returns:
object: The JSON object containing data configuration.
"""
json_string = self.sagemaker_session.read_s3_file(self.bucket_name, self.prefix)
return json.loads(json_string)
def get_data_bucket(self, region_requested=None):
"""Provides the bucket containing the data for specified region.
Args:
region_requested (str): The region for which the data is beig requested.
Returns:
str: Name of the S3 bucket containing datasets in the requested region.
"""
config = self.fetch_data_config()
region = region_requested if region_requested else self.sagemaker_session.boto_region_name
return config[region] if region in config.keys() else config["default"]
get_ecr_image_uri_prefix = deprecations.removed_function("get_ecr_image_uri_prefix")
def update_container_with_inference_params(
framework=None,
framework_version=None,
nearest_model_name=None,
data_input_configuration=None,
container_def=None,
container_list=None,
):
"""Function to check if inference recommender parameters exist and update container.
Args:
framework (str): Machine learning framework of the model package container image
(default: None).
framework_version (str): Framework version of the Model Package Container Image
(default: None).
nearest_model_name (str): Name of a pre-trained machine learning benchmarked by
Amazon SageMaker Inference Recommender (default: None).
data_input_configuration (str): Input object for the model (default: None).
container_def (dict): object to be updated.
container_list (list): list to be updated.
Returns:
dict: dict with inference recommender params
"""
if container_list is not None:
for obj in container_list:
construct_container_object(
obj, data_input_configuration, framework, framework_version, nearest_model_name
)
if container_def is not None:
construct_container_object(
container_def,
data_input_configuration,
framework,
framework_version,
nearest_model_name,
)
return container_list or container_def
def construct_container_object(
obj, data_input_configuration, framework, framework_version, nearest_model_name
):
"""Function to construct container object.
Args:
framework (str): Machine learning framework of the model package container image
(default: None).
framework_version (str): Framework version of the Model Package Container Image
(default: None).
nearest_model_name (str): Name of a pre-trained machine learning benchmarked by
Amazon SageMaker Inference Recommender (default: None).
data_input_configuration (str): Input object for the model (default: None).
obj (dict): object to be updated.
Returns:
dict: container object
"""
if framework is not None:
obj.update(
{
"Framework": framework,
}
)
if framework_version is not None:
obj.update(
{
"FrameworkVersion": framework_version,
}
)
if nearest_model_name is not None:
obj.update(
{
"NearestModelName": nearest_model_name,
}
)
if data_input_configuration is not None:
obj.update(
{
"ModelInput": {
"DataInputConfig": data_input_configuration,
},
}
)
return obj