forked from aws/sagemaker-python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_estimator.py
More file actions
6024 lines (5241 loc) · 208 KB
/
test_estimator.py
File metadata and controls
6024 lines (5241 loc) · 208 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.
from __future__ import absolute_import
from copy import deepcopy
import logging
import json
import os
import subprocess
from time import sleep
from sagemaker.fw_utils import UploadedCode
import pytest
from botocore.exceptions import ClientError
from mock import ANY, MagicMock, Mock, patch, PropertyMock
from sagemaker.huggingface.estimator import HuggingFace
from sagemaker.jumpstart.constants import (
JUMPSTART_GATED_AND_PUBLIC_BUCKET_NAME_SET,
JUMPSTART_RESOURCE_BASE_NAME,
)
from sagemaker.jumpstart.enums import JumpStartTag
import sagemaker.local
from sagemaker import TrainingInput, utils, vpc_utils
from sagemaker.algorithm import AlgorithmEstimator
from sagemaker.debugger import (
rule_configs,
CollectionConfig,
DebuggerHookConfig,
FrameworkProfile,
ProfilerConfig,
ProfilerRule,
Rule,
)
from sagemaker.async_inference import AsyncInferenceConfig
from sagemaker.estimator import Estimator, EstimatorBase, Framework, _TrainingJob
from sagemaker.fw_utils import PROFILER_UNSUPPORTED_REGIONS
from sagemaker.inputs import ShuffleConfig
from sagemaker.instance_group import InstanceGroup
from sagemaker.interactive_apps import SupportedInteractiveAppTypes
from sagemaker.model import FrameworkModel
from sagemaker.model_card.model_card import ModelCard, ModelOverview
from sagemaker.model_card.schema_constraints import ModelCardStatusEnum
from sagemaker.mxnet.estimator import MXNet
from sagemaker.predictor import Predictor
from sagemaker.pytorch.estimator import PyTorch
from sagemaker.session_settings import SessionSettings
from sagemaker.sklearn.estimator import SKLearn
from sagemaker.tensorflow.estimator import TensorFlow
from sagemaker.predictor_async import AsyncPredictor
from sagemaker.transformer import Transformer
from sagemaker.workflow.execution_variables import ExecutionVariable
from sagemaker.workflow.parameters import ParameterString, ParameterBoolean
from sagemaker.workflow.pipeline_context import PipelineSession, _PipelineConfig
from sagemaker.workflow.pipeline_definition_config import PipelineDefinitionConfig
from sagemaker.xgboost.estimator import XGBoost
from tests.unit import (
SAGEMAKER_CONFIG_TRAINING_JOB,
SAGEMAKER_CONFIG_TRAINING_JOB_WITH_DEBUG_HOOK_CONFIG_AS_FALSE,
SAGEMAKER_CONFIG_TRAINING_JOB_WITH_DEBUG_HOOK_CONFIG_AS_TRUE,
_test_default_bucket_and_prefix_combinations,
DEFAULT_S3_BUCKET_NAME,
DEFAULT_S3_OBJECT_KEY_PREFIX_NAME,
)
from sagemaker.model_life_cycle import ModelLifeCycle
from tests.unit.test_job import INSTANCE_PLACEMENT_CONFIG
MODEL_DATA = "s3://bucket/model.tar.gz"
MODEL_IMAGE = "mi"
ENTRY_POINT = "blah.py"
DATA_DIR = os.path.join(os.path.dirname(__file__), "..", "data")
SCRIPT_NAME = "dummy_script.py"
SCRIPT_PATH = os.path.join(DATA_DIR, SCRIPT_NAME)
TIMESTAMP = "2017-11-06-14:14:15.671"
TIME = 1510006209.073025
BUCKET_NAME = "mybucket"
INSTANCE_COUNT = 1
INSTANCE_TYPE = "c4.4xlarge"
KEEP_ALIVE_PERIOD_IN_SECONDS = 1800
TRAINING_PLAN = "arn:aws:sagemaker:us-west-2:336:training-plan/test_training_plan"
ACCELERATOR_TYPE = "ml.eia.medium"
ROLE = "DummyRole"
IMAGE_URI = "fakeimage"
REGION = "us-west-2"
JOB_NAME = "{}-{}".format(IMAGE_URI, TIMESTAMP)
TAGS = [{"Name": "some-tag", "Value": "value-for-tag"}]
OUTPUT_PATH = "s3://bucket/prefix"
GIT_REPO = "https://github.com/aws/sagemaker-python-sdk.git"
BRANCH = "test-branch-git-config"
COMMIT = "ae15c9d7d5b97ea95ea451e4662ee43da3401d73"
PRIVATE_GIT_REPO_SSH = "git@github.com:testAccount/private-repo.git"
PRIVATE_GIT_REPO = "https://github.com/testAccount/private-repo.git"
PRIVATE_BRANCH = "test-branch"
PRIVATE_COMMIT = "329bfcf884482002c05ff7f44f62599ebc9f445a"
CODECOMMIT_REPO = "https://git-codecommit.us-west-2.amazonaws.com/v1/repos/test-repo/"
CODECOMMIT_REPO_SSH = "ssh://git-codecommit.us-west-2.amazonaws.com/v1/repos/test-repo/"
CODECOMMIT_BRANCH = "master"
REPO_DIR = "/tmp/repo_dir"
ENV_INPUT = {"env_key1": "env_val1", "env_key2": "env_val2", "env_key3": "env_val3"}
TRAINING_REPOSITORY_ACCESS_MODE = "VPC"
ENABLE_INFRA_CHECK = True
TRAINING_REPOSITORY_CREDENTIALS_PROVIDER_ARN = "arn:aws:lambda:us-west-2:1234567890:function:test"
CONTAINER_ENTRY_POINT = ["entry_point1", "entry_point2"]
CONTAINER_ARGUMENTS = ["container_arg1", "container_arg2"]
DESCRIBE_TRAINING_JOB_RESULT = {"ModelArtifacts": {"S3ModelArtifacts": MODEL_DATA}}
DESCRIBE_TRAINING_JOB_RESULT_UNCOMPRESSED_S3_MODEL = {
"ModelArtifacts": {
"S3ModelArtifacts": "s3://bucket/model/prefix",
},
"OutputDataConfig": {
"CompressionType": "NONE",
"KmsKeyId": "outputkms",
"S3OutputPath": "s3://path/to/model",
},
}
RETURNED_JOB_DESCRIPTION = {
"AlgorithmSpecification": {
"TrainingInputMode": "File",
"TrainingImage": "1.dkr.ecr.us-west-2.amazonaws.com/sagemaker-other:1.0.4",
},
"HyperParameters": {
"sagemaker_submit_directory": '"s3://some/sourcedir.tar.gz"',
"checkpoint_path": '"s3://other/1508872349"',
"sagemaker_program": '"iris-dnn-classifier.py"',
"sagemaker_container_log_level": '"logging.INFO"',
"sagemaker_job_name": '"neo"',
"training_steps": "100",
},
"RoleArn": "arn:aws:iam::366:role/SageMakerRole",
"ResourceConfig": {"VolumeSizeInGB": 30, "InstanceCount": 1, "InstanceType": "ml.c4.xlarge"},
"EnableNetworkIsolation": False,
"StoppingCondition": {"MaxRuntimeInSeconds": 24 * 60 * 60},
"TrainingJobName": "neo",
"TrainingJobStatus": "Completed",
"TrainingJobArn": "arn:aws:sagemaker:us-west-2:336:training-job/neo",
"OutputDataConfig": {"KmsKeyId": "", "S3OutputPath": "s3://place/output/neo"},
"TrainingJobOutput": {"S3TrainingJobOutput": "s3://here/output.tar.gz"},
"EnableInterContainerTrafficEncryption": False,
}
MODEL_CONTAINER_DEF = {
"Environment": {
"SAGEMAKER_PROGRAM": ENTRY_POINT,
"SAGEMAKER_SUBMIT_DIRECTORY": "s3://mybucket/mi-2017-10-10-14-14-15/sourcedir.tar.gz",
"SAGEMAKER_CONTAINER_LOG_LEVEL": "20",
"SAGEMAKER_REGION": REGION,
},
"Image": MODEL_IMAGE,
"ModelDataUrl": MODEL_DATA,
}
ENDPOINT_DESC = {"EndpointConfigName": "test-endpoint"}
ENDPOINT_CONFIG_DESC = {"ProductionVariants": [{"ModelName": "model-1"}, {"ModelName": "model-2"}]}
LIST_TAGS_RESULT = {"Tags": [{"Key": "TagtestKey", "Value": "TagtestValue"}]}
DISTRIBUTION_PS_ENABLED = {"parameter_server": {"enabled": True}}
DISTRIBUTION_MWMS_ENABLED = {"multi_worker_mirrored_strategy": {"enabled": True}}
DISTRIBUTION_MPI_ENABLED = {
"mpi": {"enabled": True, "custom_mpi_options": "options", "processes_per_host": 2}
}
DISTRIBUTION_SM_DDP_ENABLED = {
"smdistributed": {"dataparallel": {"enabled": True, "custom_mpi_options": "options"}},
"torch_distributed": {"enabled": False},
}
DISTRIBUTION_SM_DDP_DISABLED = {
"smdistributed": {"enabled": True},
"torch_distributed": {"enabled": False},
}
DISTRIBUTION_SM_TORCH_DIST_AND_DDP_ENABLED = {
"smdistributed": {"dataparallel": {"enabled": True, "custom_mpi_options": "options"}},
"torch_distributed": {"enabled": True},
}
DISTRIBUTION_SM_TORCH_DIST_AND_DDP_DISABLED = {
"smdistributed": {"enabled": True},
"torch_distributed": {"enabled": True},
}
MOCKED_S3_URI = "s3://mocked_s3_uri_from_source_dir"
_DEFINITION_CONFIG = PipelineDefinitionConfig(use_custom_job_prefix=False)
MOCKED_PIPELINE_CONFIG = _PipelineConfig(
"test-pipeline",
"test-training-step",
None,
"code-hash-0123456789",
"config-hash-0123456789",
_DEFINITION_CONFIG,
)
HOOK_CONFIG_WITHOUT_S3_PATH = DebuggerHookConfig(
hook_parameters={"save_interval": "1"},
)
HOOK_CONFIG = DebuggerHookConfig(
hook_parameters={"save_interval": "1"},
s3_output_path="s3://mytestbucket/testpath/",
)
S3_OUTPUT_PATH_FROM_SESSION_S3_DEFAULT_CONFIG = "s3://mybucket/"
class DummyFramework(Framework):
_framework_name = "dummy"
def training_image_uri(self):
return IMAGE_URI
def create_model(
self,
role=None,
model_server_workers=None,
entry_point=None,
vpc_config_override=vpc_utils.VPC_CONFIG_DEFAULT,
enable_network_isolation=None,
model_dir=None,
**kwargs,
):
if enable_network_isolation is None:
enable_network_isolation = self.enable_network_isolation()
return DummyFrameworkModel(
self.sagemaker_session,
vpc_config=self.get_vpc_config(vpc_config_override),
entry_point=entry_point,
enable_network_isolation=enable_network_isolation,
role=role,
**kwargs,
)
@classmethod
def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None):
init_params = super(DummyFramework, cls)._prepare_init_params_from_job_description(
job_details, model_channel_name
)
init_params.pop("image_uri", None)
return init_params
class DummyFrameworkModel(FrameworkModel):
def __init__(self, sagemaker_session, entry_point=None, role=ROLE, **kwargs):
super(DummyFrameworkModel, self).__init__(
MODEL_DATA,
MODEL_IMAGE,
role,
entry_point or ENTRY_POINT,
sagemaker_session=sagemaker_session,
**kwargs,
)
def create_predictor(self, endpoint_name):
return None
def prepare_container_def(
self,
instance_type,
accelerator_type=None,
serverless_inference_config=None,
accept_eula=None,
model_reference_arn=None,
):
return MODEL_CONTAINER_DEF
@pytest.fixture(autouse=True)
def mock_create_tar_file():
with patch("sagemaker.utils.create_tar_file", MagicMock()) as create_tar_file:
yield create_tar_file
@pytest.fixture()
def sagemaker_session():
boto_mock = Mock(name="boto_session", region_name=REGION)
sms = MagicMock(
name="sagemaker_session",
boto_session=boto_mock,
boto_region_name=REGION,
config=None,
local_mode=False,
s3_client=None,
s3_resource=None,
settings=SessionSettings(),
default_bucket_prefix=None,
)
sms.default_bucket = Mock(name="default_bucket", return_value=BUCKET_NAME)
sms.sagemaker_client.describe_training_job = Mock(
name="describe_training_job", return_value=DESCRIBE_TRAINING_JOB_RESULT
)
sms.sagemaker_client.describe_endpoint = Mock(return_value=ENDPOINT_DESC)
sms.sagemaker_client.describe_endpoint_config = Mock(return_value=ENDPOINT_CONFIG_DESC)
sms.sagemaker_client.list_tags = Mock(return_value=LIST_TAGS_RESULT)
sms.upload_data = Mock(return_value=OUTPUT_PATH)
# For tests which doesn't verify config file injection, operate with empty config
sms.sagemaker_config = {}
return sms
@pytest.fixture()
def pipeline_session():
client_mock = Mock()
client_mock._client_config.user_agent = (
"Boto3/1.14.24 Python/3.8.5 Linux/5.4.0-42-generic Botocore/1.17.24 Resource"
)
role_mock = Mock()
type(role_mock).arn = PropertyMock(return_value=ROLE)
resource_mock = Mock()
resource_mock.Role.return_value = role_mock
session_mock = Mock(region_name=REGION, settings=SessionSettings())
session_mock.resource.return_value = resource_mock
session_mock.client.return_value = client_mock
return PipelineSession(
boto_session=session_mock, sagemaker_client=client_mock, default_bucket=BUCKET_NAME
)
@pytest.fixture()
def training_job_description(sagemaker_session):
returned_job_description = RETURNED_JOB_DESCRIPTION.copy()
mock_describe_training_job = Mock(
name="describe_training_job", return_value=returned_job_description
)
sagemaker_session.sagemaker_client.describe_training_job = mock_describe_training_job
sagemaker_session.describe_training_job = mock_describe_training_job
return returned_job_description
def test_validate_smdistributed_unsupported_image_raises(sagemaker_session):
# Test unsupported image raises error.
for unsupported_image in DummyFramework.UNSUPPORTED_DLC_IMAGE_FOR_SM_PARALLELISM:
# Fail due to unsupported CUDA12 DLC image.
f = DummyFramework(
"some_script.py",
role="DummyRole",
instance_type="ml.p4d.24xlarge",
sagemaker_session=sagemaker_session,
output_path="outputpath",
image_uri=unsupported_image,
)
with pytest.raises(ValueError):
f._distribution_configuration(DISTRIBUTION_SM_DDP_ENABLED)
with pytest.raises(ValueError):
f._distribution_configuration(DISTRIBUTION_SM_DDP_DISABLED)
# Test unsupported image with suffix raises error.
for unsupported_image in DummyFramework.UNSUPPORTED_DLC_IMAGE_FOR_SM_PARALLELISM:
# Fail due to unsupported CUDA12 DLC image.
f = DummyFramework(
"some_script.py",
role="DummyRole",
instance_type="ml.p4d.24xlarge",
sagemaker_session=sagemaker_session,
output_path="outputpath",
image_uri=unsupported_image + "-ubuntu20.04-sagemaker-pr-3303",
)
with pytest.raises(ValueError):
f._distribution_configuration(DISTRIBUTION_SM_DDP_ENABLED)
with pytest.raises(ValueError):
f._distribution_configuration(DISTRIBUTION_SM_DDP_DISABLED)
def test_validate_smdistributed_p5_raises(sagemaker_session):
# Supported DLC image.
f = DummyFramework(
"some_script.py",
role="DummyRole",
instance_type="ml.p5.48xlarge",
sagemaker_session=sagemaker_session,
output_path="outputpath",
image_uri="some_acceptable_image",
)
# Both fail because instance type is p5 and torch_distributed is off.
with pytest.raises(ValueError):
f._distribution_configuration(DISTRIBUTION_SM_DDP_ENABLED)
with pytest.raises(ValueError):
f._distribution_configuration(DISTRIBUTION_SM_DDP_DISABLED)
def test_validate_smdistributed_p5_not_raises(sagemaker_session):
f = DummyFramework(
"some_script.py",
role="DummyRole",
instance_type="ml.p5.48xlarge",
sagemaker_session=sagemaker_session,
output_path="outputpath",
image_uri="ecr-url/2.0.1-gpu-py310-cu121-ubuntu20.04-sagemaker-pr-3303",
)
# Testing with p5 instance and torch_distributed enabled.
f._distribution_configuration(DISTRIBUTION_SM_TORCH_DIST_AND_DDP_ENABLED)
f._distribution_configuration(DISTRIBUTION_SM_TORCH_DIST_AND_DDP_DISABLED)
def test_validate_smdistributed_backward_compat_p4_not_raises(sagemaker_session):
f = DummyFramework(
"some_script.py",
role="DummyRole",
instance_type="ml.p4d.24xlarge",
sagemaker_session=sagemaker_session,
output_path="outputpath",
image_uri="some_acceptable_image",
)
# Testing backwards compatability with p4d instances.
f._distribution_configuration(DISTRIBUTION_SM_TORCH_DIST_AND_DDP_ENABLED)
f._distribution_configuration(DISTRIBUTION_SM_TORCH_DIST_AND_DDP_DISABLED)
def test_validate_smdistributed_instance_groups_raises(sagemaker_session):
instance_group_1 = InstanceGroup("train_group", "ml.p4d.24xlarge", 2)
instance_group_2 = InstanceGroup("train_group", "ml.p5.48xlarge", 2)
f = DummyFramework(
"some_script.py",
role="DummyRole",
instance_groups=[instance_group_1, instance_group_2],
sagemaker_session=sagemaker_session,
output_path="outputpath",
image_uri="some_acceptable_image",
)
# Testing instance_group with p5 raises exception
with pytest.raises(ValueError):
f._distribution_configuration(DISTRIBUTION_SM_DDP_ENABLED)
with pytest.raises(ValueError):
f._distribution_configuration(DISTRIBUTION_SM_DDP_DISABLED)
def test_validate_smdistributed_instance_groups_not_raises(sagemaker_session):
instance_group_1 = InstanceGroup("train_group", "ml.p4d.24xlarge", 2)
f = DummyFramework(
"some_script.py",
role="DummyRole",
instance_groups=[instance_group_1],
sagemaker_session=sagemaker_session,
output_path="outputpath",
image_uri="some_acceptable_image",
)
# Testing instance_group without p5 does not raise exception
f._distribution_configuration(DISTRIBUTION_SM_TORCH_DIST_AND_DDP_ENABLED)
f._distribution_configuration(DISTRIBUTION_SM_TORCH_DIST_AND_DDP_DISABLED)
def test_framework_all_init_args(sagemaker_session):
f = DummyFramework(
"my_script.py",
role="DummyRole",
instance_count=3,
instance_type="ml.m4.xlarge",
sagemaker_session=sagemaker_session,
volume_size=123,
volume_kms_key="volumekms",
max_run=456,
input_mode="inputmode",
output_path="outputpath",
output_kms_key="outputkms",
base_job_name="basejobname",
tags=[{"foo": "bar"}],
subnets=["123", "456"],
security_group_ids=["789", "012"],
metric_definitions=[{"Name": "validation-rmse", "Regex": "validation-rmse=(\\d+)"}],
encrypt_inter_container_traffic=True,
checkpoint_s3_uri="s3://bucket/checkpoint",
checkpoint_local_path="file://local/checkpoint",
enable_sagemaker_metrics=True,
enable_network_isolation=True,
environment=ENV_INPUT,
max_retry_attempts=2,
)
_TrainingJob.start_new(f, "s3://mydata", None)
sagemaker_session.train.assert_called_once()
_, args = sagemaker_session.train.call_args
assert args == {
"input_mode": "inputmode",
"tags": [{"foo": "bar"}],
"hyperparameters": {},
"image_uri": "fakeimage",
"input_config": [
{
"ChannelName": "training",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3DataDistributionType": "FullyReplicated",
"S3Uri": "s3://mydata",
}
},
}
],
"output_config": {"KmsKeyId": "outputkms", "S3OutputPath": "outputpath"},
"vpc_config": {"Subnets": ["123", "456"], "SecurityGroupIds": ["789", "012"]},
"stop_condition": {"MaxRuntimeInSeconds": 456},
"retry_strategy": {"MaximumRetryAttempts": 2},
"role": sagemaker_session.expand_role(),
"job_name": None,
"resource_config": {
"VolumeSizeInGB": 123,
"InstanceCount": 3,
"VolumeKmsKeyId": "volumekms",
"InstanceType": "ml.m4.xlarge",
},
"metric_definitions": [{"Name": "validation-rmse", "Regex": "validation-rmse=(\\d+)"}],
"encrypt_inter_container_traffic": True,
"environment": {"env_key1": "env_val1", "env_key2": "env_val2", "env_key3": "env_val3"},
"experiment_config": None,
"checkpoint_s3_uri": "s3://bucket/checkpoint",
"checkpoint_local_path": "file://local/checkpoint",
"enable_sagemaker_metrics": True,
"enable_network_isolation": True,
}
def test_subnets_without_security_groups(sagemaker_session):
with pytest.raises(RuntimeError):
DummyFramework(
entry_point=SCRIPT_PATH,
sagemaker_session=sagemaker_session,
subnets=["123"],
)
def test_security_groups_without_subnets(sagemaker_session):
with pytest.raises(RuntimeError):
DummyFramework(
entry_point=SCRIPT_PATH,
sagemaker_session=sagemaker_session,
security_group_ids=["123"],
)
def test_framework_without_role_parameter(sagemaker_session):
with pytest.raises(ValueError):
DummyFramework(
entry_point=SCRIPT_PATH,
sagemaker_session=sagemaker_session,
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.m4.xlarge", 2),
],
)
def test_default_value_of_enable_network_isolation(sagemaker_session):
framework = DummyFramework(
entry_point=SCRIPT_PATH,
role=ROLE,
sagemaker_session=sagemaker_session,
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.m4.xlarge", 2),
],
)
assert framework.enable_network_isolation() is False
def test_framework_initialization_with_sagemaker_config_injection(sagemaker_session):
sagemaker_session.sagemaker_config = SAGEMAKER_CONFIG_TRAINING_JOB
framework = DummyFramework(
entry_point=SCRIPT_PATH,
sagemaker_session=sagemaker_session,
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.m4.xlarge", 2),
],
)
expected_volume_kms_key_id = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"ResourceConfig"
]["VolumeKmsKeyId"]
expected_role_arn = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"]["RoleArn"]
expected_kms_key_id = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"OutputDataConfig"
]["KmsKeyId"]
expected_subnets = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"]["VpcConfig"][
"Subnets"
]
expected_security_groups = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"VpcConfig"
]["SecurityGroupIds"]
expected_enable_network_isolation = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"EnableNetworkIsolation"
]
expected_enable_inter_container_traffic_encryption = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"][
"TrainingJob"
]["EnableInterContainerTrafficEncryption"]
expected_environment = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"]["Environment"]
expected_disable_profiler_attribute = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"ProfilerConfig"
]["DisableProfiler"]
expected_debugger_hook_config = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["PythonSDK"][
"Modules"
]["Estimator"]["DebugHookConfig"]
assert framework.role == expected_role_arn
assert framework.enable_network_isolation() == expected_enable_network_isolation
assert (
framework.encrypt_inter_container_traffic
== expected_enable_inter_container_traffic_encryption
)
assert framework.output_kms_key == expected_kms_key_id
assert framework.volume_kms_key == expected_volume_kms_key_id
assert framework.security_group_ids == expected_security_groups
assert framework.subnets == expected_subnets
assert framework.environment == expected_environment
assert framework.disable_profiler == expected_disable_profiler_attribute
assert framework.debugger_hook_config == expected_debugger_hook_config
def test_estimator_initialization_with_sagemaker_config_injection(sagemaker_session):
"""
Tests that the estimator initialization works when all the supported defaults config params "
are provided from the sagemaker_config
"""
sagemaker_session.sagemaker_config = SAGEMAKER_CONFIG_TRAINING_JOB
estimator = Estimator(
image_uri="some-image",
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.p3.16xlarge", 2),
],
sagemaker_session=sagemaker_session,
base_job_name="base_job_name",
)
expected_volume_kms_key_id = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"ResourceConfig"
]["VolumeKmsKeyId"]
expected_role_arn = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"]["RoleArn"]
expected_kms_key_id = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"OutputDataConfig"
]["KmsKeyId"]
expected_subnets = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"]["VpcConfig"][
"Subnets"
]
expected_security_groups = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"VpcConfig"
]["SecurityGroupIds"]
expected_enable_network_isolation = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"EnableNetworkIsolation"
]
expected_enable_inter_container_traffic_encryption = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"][
"TrainingJob"
]["EnableInterContainerTrafficEncryption"]
expected_environment = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"]["Environment"]
expected_disable_profiler_attribute = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"ProfilerConfig"
]["DisableProfiler"]
expected_debugger_hook_config = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["PythonSDK"][
"Modules"
]["Estimator"]["DebugHookConfig"]
assert estimator.role == expected_role_arn
assert estimator.enable_network_isolation() == expected_enable_network_isolation
assert (
estimator.encrypt_inter_container_traffic
== expected_enable_inter_container_traffic_encryption
)
assert estimator.output_kms_key == expected_kms_key_id
assert estimator.volume_kms_key == expected_volume_kms_key_id
assert estimator.security_group_ids == expected_security_groups
assert estimator.subnets == expected_subnets
assert estimator.environment == expected_environment
assert estimator.disable_profiler == expected_disable_profiler_attribute
assert estimator.debugger_hook_config == expected_debugger_hook_config
def test_estimator_with_debugger_hook_config_provided_as_bool_from_direct_input(
sagemaker_session,
):
"""
Tests that the estimator initialization works correctly with sagemaker_config injection
when debugger_hook_config is provided as True from direct input
"""
sagemaker_session.sagemaker_config = SAGEMAKER_CONFIG_TRAINING_JOB
estimator = Estimator(
image_uri="some-image",
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.p3.16xlarge", 2),
],
sagemaker_session=sagemaker_session,
base_job_name="base_job_name",
debugger_hook_config=True,
)
assert estimator.debugger_hook_config == {}
def test_estimator_with_debugger_hook_config_provided_as_dict_from_direct_input(
sagemaker_session,
):
"""
Tests that the estimator initialization works correctly with sagemaker_config injection
when debugger_hook_config is provided as dict from direct input
"""
sagemaker_session.sagemaker_config = SAGEMAKER_CONFIG_TRAINING_JOB
estimator = Estimator(
image_uri="some-image",
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.p3.16xlarge", 2),
],
sagemaker_session=sagemaker_session,
base_job_name="base_job_name",
debugger_hook_config=HOOK_CONFIG,
)
assert estimator.debugger_hook_config == HOOK_CONFIG
def test_estimator_initialization_with_sagemaker_config_injection_no_kms_supported(
sagemaker_session,
):
sagemaker_session.sagemaker_config = SAGEMAKER_CONFIG_TRAINING_JOB
estimator = Estimator(
image_uri="some-image",
instance_groups=[
InstanceGroup("group1", "ml.g5.2xlarge", 1),
InstanceGroup("group2", "ml.g5.2xlarge", 2),
],
sagemaker_session=sagemaker_session,
base_job_name="base_job_name",
)
expected_role_arn = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"]["RoleArn"]
expected_kms_key_id = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"OutputDataConfig"
]["KmsKeyId"]
expected_subnets = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"]["VpcConfig"][
"Subnets"
]
expected_security_groups = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"VpcConfig"
]["SecurityGroupIds"]
expected_enable_network_isolation = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"EnableNetworkIsolation"
]
expected_enable_inter_container_traffic_encryption = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"][
"TrainingJob"
]["EnableInterContainerTrafficEncryption"]
expected_disable_profiler_attribute = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"ProfilerConfig"
]["DisableProfiler"]
expected_debugger_hook_config = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["PythonSDK"][
"Modules"
]["Estimator"]["DebugHookConfig"]
assert estimator.role == expected_role_arn
assert estimator.enable_network_isolation() == expected_enable_network_isolation
assert (
estimator.encrypt_inter_container_traffic
== expected_enable_inter_container_traffic_encryption
)
assert estimator.output_kms_key == expected_kms_key_id
assert estimator.volume_kms_key is None
assert estimator.security_group_ids == expected_security_groups
assert estimator.subnets == expected_subnets
assert estimator.disable_profiler == expected_disable_profiler_attribute
assert estimator.debugger_hook_config == expected_debugger_hook_config
def test_estimator_initialization_with_sagemaker_config_injection_partial_kms_support(
sagemaker_session,
):
sagemaker_session.sagemaker_config = SAGEMAKER_CONFIG_TRAINING_JOB
estimator = Estimator(
image_uri="some-image",
instance_groups=[
InstanceGroup("group1", "ml.p2.xlarge", 1),
InstanceGroup("group2", "ml.g5.2xlarge", 2),
],
sagemaker_session=sagemaker_session,
base_job_name="base_job_name",
)
expected_volume_kms_key_id = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"ResourceConfig"
]["VolumeKmsKeyId"]
expected_role_arn = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"]["RoleArn"]
expected_kms_key_id = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"OutputDataConfig"
]["KmsKeyId"]
expected_subnets = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"]["VpcConfig"][
"Subnets"
]
expected_security_groups = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"VpcConfig"
]["SecurityGroupIds"]
expected_enable_network_isolation = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"EnableNetworkIsolation"
]
expected_enable_inter_container_traffic_encryption = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"][
"TrainingJob"
]["EnableInterContainerTrafficEncryption"]
expected_disable_profiler_attribute = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["TrainingJob"][
"ProfilerConfig"
]["DisableProfiler"]
expected_debugger_hook_config = SAGEMAKER_CONFIG_TRAINING_JOB["SageMaker"]["PythonSDK"][
"Modules"
]["Estimator"]["DebugHookConfig"]
assert estimator.role == expected_role_arn
assert estimator.enable_network_isolation() == expected_enable_network_isolation
assert (
estimator.encrypt_inter_container_traffic
== expected_enable_inter_container_traffic_encryption
)
assert estimator.output_kms_key == expected_kms_key_id
assert estimator.volume_kms_key == expected_volume_kms_key_id
assert estimator.security_group_ids == expected_security_groups
assert estimator.subnets == expected_subnets
assert estimator.disable_profiler == expected_disable_profiler_attribute
assert estimator.debugger_hook_config == expected_debugger_hook_config
def test_framework_with_heterogeneous_cluster(sagemaker_session):
f = DummyFramework(
entry_point=SCRIPT_PATH,
role=ROLE,
sagemaker_session=sagemaker_session,
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.m4.xlarge", 2),
],
)
f.fit("s3://mydata")
sagemaker_session.train.assert_called_once()
_, args = sagemaker_session.train.call_args
assert args["resource_config"]["InstanceGroups"][0] == {
"InstanceGroupName": "group1",
"InstanceCount": 1,
"InstanceType": "ml.c4.xlarge",
}
assert args["resource_config"]["InstanceGroups"][1] == {
"InstanceGroupName": "group2",
"InstanceCount": 2,
"InstanceType": "ml.m4.xlarge",
}
def test_framework_with_keep_alive_period(sagemaker_session):
f = DummyFramework(
entry_point=SCRIPT_PATH,
role=ROLE,
sagemaker_session=sagemaker_session,
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.m4.xlarge", 2),
],
keep_alive_period_in_seconds=KEEP_ALIVE_PERIOD_IN_SECONDS,
)
f.fit("s3://mydata")
sagemaker_session.train.assert_called_once()
_, args = sagemaker_session.train.call_args
assert args["resource_config"]["KeepAlivePeriodInSeconds"] == KEEP_ALIVE_PERIOD_IN_SECONDS
def test_framework_with_training_plan(sagemaker_session):
f = DummyFramework(
entry_point=SCRIPT_PATH,
role=ROLE,
sagemaker_session=sagemaker_session,
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.m4.xlarge", 2),
],
training_plan=TRAINING_PLAN,
)
f.fit("s3://mydata")
sagemaker_session.train.assert_called_once()
_, args = sagemaker_session.train.call_args
assert args["resource_config"]["TrainingPlanArn"] == TRAINING_PLAN
def test_framework_with_instance_placement(sagemaker_session):
f = DummyFramework(
entry_point=SCRIPT_PATH,
role=ROLE,
sagemaker_session=sagemaker_session,
instance_type="ml.c4.xlarge",
instance_count=2,
training_plan=TRAINING_PLAN,
instance_placement_config=INSTANCE_PLACEMENT_CONFIG,
)
f.fit("s3://mydata")
sagemaker_session.train.assert_called_once()
_, args = sagemaker_session.train.call_args
assert args["resource_config"]["InstancePlacementConfig"] == INSTANCE_PLACEMENT_CONFIG
def test_framework_with_both_training_repository_config(sagemaker_session):
f = DummyFramework(
entry_point=SCRIPT_PATH,
role=ROLE,
sagemaker_session=sagemaker_session,
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.m4.xlarge", 2),
],
training_repository_access_mode=TRAINING_REPOSITORY_ACCESS_MODE,
training_repository_credentials_provider_arn=TRAINING_REPOSITORY_CREDENTIALS_PROVIDER_ARN,
)
f.fit("s3://mydata")
sagemaker_session.train.assert_called_once()
_, args = sagemaker_session.train.call_args
assert (
args["training_image_config"]["TrainingRepositoryAccessMode"]
== TRAINING_REPOSITORY_ACCESS_MODE
)
assert (
args["training_image_config"]["TrainingRepositoryAuthConfig"][
"TrainingRepositoryCredentialsProviderArn"
]
== TRAINING_REPOSITORY_CREDENTIALS_PROVIDER_ARN
)
def test_framework_with_training_repository_access_mode(sagemaker_session):
f = DummyFramework(
entry_point=SCRIPT_PATH,
role=ROLE,
sagemaker_session=sagemaker_session,
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.m4.xlarge", 2),
],
training_repository_access_mode=TRAINING_REPOSITORY_ACCESS_MODE,
)
f.fit("s3://mydata")
sagemaker_session.train.assert_called_once()
_, args = sagemaker_session.train.call_args
assert (
args["training_image_config"]["TrainingRepositoryAccessMode"]
== TRAINING_REPOSITORY_ACCESS_MODE
)
assert "TrainingRepositoryAuthConfig" not in args["training_image_config"]
def test_framework_without_training_repository_config(sagemaker_session):
f = DummyFramework(
entry_point=SCRIPT_PATH,
role=ROLE,
sagemaker_session=sagemaker_session,
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.m4.xlarge", 2),
],
)
f.fit("s3://mydata")
sagemaker_session.train.assert_called_once()
_, args = sagemaker_session.train.call_args
assert args.get("training_image_config") is None
def test_framework_without_infra_check_config(sagemaker_session):
f = DummyFramework(
entry_point=SCRIPT_PATH,
role=ROLE,
sagemaker_session=sagemaker_session,
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.m4.xlarge", 2),
],
)
f.fit("s3://mydata")
sagemaker_session.train.assert_called_once()
_, args = sagemaker_session.train.call_args
assert args.get("health_check_config") is None
def test_framework_with_infra_check_config(sagemaker_session):
f = DummyFramework(
entry_point=SCRIPT_PATH,
role=ROLE,
sagemaker_session=sagemaker_session,
instance_groups=[
InstanceGroup("group1", "ml.c4.xlarge", 1),
InstanceGroup("group2", "ml.m4.xlarge", 2),
],
enable_infra_check=ENABLE_INFRA_CHECK,
)
f.fit("s3://mydata")
sagemaker_session.train.assert_called_once()
_, args = sagemaker_session.train.call_args
assert args["infra_check_config"]["EnableInfraCheck"] == ENABLE_INFRA_CHECK
def test_framework_with_container_entry_point(sagemaker_session):
f = DummyFramework(
entry_point=SCRIPT_PATH,
role=ROLE,