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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
# 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

import copy
import datetime

import pytest
from mock import Mock, patch

from sagemaker.algorithm import AlgorithmEstimator
from sagemaker.estimator import _TrainingJob
from sagemaker.transformer import Transformer

DESCRIBE_ALGORITHM_RESPONSE = {
    "AlgorithmName": "scikit-decision-trees",
    "AlgorithmArn": "arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
    "AlgorithmDescription": "Decision trees using Scikit",
    "CreationTime": datetime.datetime(2018, 8, 3, 22, 44, 54, 437000),
    "TrainingSpecification": {
        "TrainingImage": "123.dkr.ecr.us-east-2.amazonaws.com/decision-trees-sample@sha256:12345",
        "TrainingImageDigest": "sha256:206854b6ea2f0020d216311da732010515169820b898ec29720bcf1d2b46806a",
        "SupportedHyperParameters": [
            {
                "Name": "max_leaf_nodes",
                "Description": "Grow a tree with max_leaf_nodes in best-first fashion.",
                "Type": "Integer",
                "Range": {
                    "IntegerParameterRangeSpecification": {"MinValue": "1", "MaxValue": "100000"}
                },
                "IsTunable": True,
                "IsRequired": False,
                "DefaultValue": "100",
            },
            {
                "Name": "free_text_hp1",
                "Description": "You can write anything here",
                "Type": "FreeText",
                "IsTunable": False,
                "IsRequired": True,
            },
        ],
        "SupportedTrainingInstanceTypes": ["ml.m4.xlarge", "ml.m4.2xlarge", "ml.m4.4xlarge"],
        "SupportsDistributedTraining": False,
        "MetricDefinitions": [
            {"Name": "validation:accuracy", "Regex": "validation-accuracy: (\\S+)"}
        ],
        "TrainingChannels": [
            {
                "Name": "training",
                "Description": "Input channel that provides training data",
                "IsRequired": True,
                "SupportedContentTypes": ["text/csv"],
                "SupportedCompressionTypes": ["None"],
                "SupportedInputModes": ["File"],
            }
        ],
        "SupportedTuningJobObjectiveMetrics": [
            {"Type": "Maximize", "MetricName": "validation:accuracy"}
        ],
    },
    "InferenceSpecification": {
        "InferenceImage": "123.dkr.ecr.us-east-2.amazonaws.com/decision-trees-sample@sha256:123",
        "SupportedTransformInstanceTypes": ["ml.m4.xlarge", "ml.m4.2xlarge"],
        "SupportedContentTypes": ["text/csv"],
        "SupportedResponseMIMETypes": ["text"],
    },
    "ValidationSpecification": {
        "ValidationRole": "arn:aws:iam::764419575721:role/SageMakerRole",
        "ValidationProfiles": [
            {
                "ProfileName": "ValidationProfile1",
                "TrainingJobDefinition": {
                    "TrainingInputMode": "File",
                    "HyperParameters": {},
                    "InputDataConfig": [
                        {
                            "ChannelName": "training",
                            "DataSource": {
                                "S3DataSource": {
                                    "S3DataType": "S3Prefix",
                                    "S3Uri": "s3://sagemaker-us-east-2-7123/-scikit-byo-iris/training-input-data",
                                    "S3DataDistributionType": "FullyReplicated",
                                }
                            },
                            "ContentType": "text/csv",
                            "CompressionType": "None",
                            "RecordWrapperType": "None",
                        }
                    ],
                    "OutputDataConfig": {
                        "KmsKeyId": "",
                        "S3OutputPath": "s3://sagemaker-us-east-2-764419575721/DEMO-scikit-byo-iris/training-output",
                    },
                    "ResourceConfig": {
                        "InstanceType": "ml.c4.xlarge",
                        "InstanceCount": 1,
                        "VolumeSizeInGB": 10,
                    },
                    "StoppingCondition": {"MaxRuntimeInSeconds": 3600},
                },
                "TransformJobDefinition": {
                    "MaxConcurrentTransforms": 0,
                    "MaxPayloadInMB": 0,
                    "TransformInput": {
                        "DataSource": {
                            "S3DataSource": {
                                "S3DataType": "S3Prefix",
                                "S3Uri": "s3://sagemaker-us-east-2/scikit-byo-iris/batch-inference/transform_test.csv",
                            }
                        },
                        "ContentType": "text/csv",
                        "CompressionType": "None",
                        "SplitType": "Line",
                    },
                    "TransformOutput": {
                        "S3OutputPath": "s3://sagemaker-us-east-2-764419575721/scikit-byo-iris/batch-transform-output",
                        "Accept": "text/csv",
                        "AssembleWith": "Line",
                        "KmsKeyId": "",
                    },
                    "TransformResources": {"InstanceType": "ml.c4.xlarge", "InstanceCount": 1},
                },
            }
        ],
        "ValidationOutputS3Prefix": "s3://sagemaker-us-east-2-764419575721/DEMO-scikit-byo-iris/validation-output",
        "ValidateForMarketplace": True,
    },
    "AlgorithmStatus": "Completed",
    "AlgorithmStatusDetails": {
        "ValidationStatuses": [{"ProfileName": "ValidationProfile1", "Status": "Completed"}]
    },
    "ResponseMetadata": {
        "RequestId": "e04bc28b-61b6-4486-9106-0edf07f5649c",
        "HTTPStatusCode": 200,
        "HTTPHeaders": {
            "x-amzn-requestid": "e04bc28b-61b6-4486-9106-0edf07f5649c",
            "content-type": "application/x-amz-json-1.1",
            "content-length": "3949",
            "date": "Fri, 03 Aug 2018 23:08:43 GMT",
        },
        "RetryAttempts": 0,
    },
}


@patch("sagemaker.Session")
def test_algorithm_supported_input_mode_with_valid_input_types(session):
    # verify that the Estimator verifies the
    # input mode that an Algorithm supports.

    file_mode_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    file_mode_algo["TrainingSpecification"]["TrainingChannels"] = [
        {
            "Name": "training",
            "Description": "Input channel that provides training data",
            "IsRequired": True,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["File"],
        },
        {
            "Name": "validation",
            "Description": "Input channel that provides validation data",
            "IsRequired": False,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["File", "Pipe"],
        },
    ]

    session.sagemaker_client.describe_algorithm = Mock(return_value=file_mode_algo)

    # Creating a File mode Estimator with a File mode algorithm should work
    AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    pipe_mode_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    pipe_mode_algo["TrainingSpecification"]["TrainingChannels"] = [
        {
            "Name": "training",
            "Description": "Input channel that provides training data",
            "IsRequired": True,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["Pipe"],
        },
        {
            "Name": "validation",
            "Description": "Input channel that provides validation data",
            "IsRequired": False,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["File", "Pipe"],
        },
    ]

    session.sagemaker_client.describe_algorithm = Mock(return_value=pipe_mode_algo)

    # Creating a Pipe mode Estimator with a Pipe mode algorithm should work.
    AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        input_mode="Pipe",
        sagemaker_session=session,
    )

    any_input_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    any_input_algo["TrainingSpecification"]["TrainingChannels"] = [
        {
            "Name": "training",
            "Description": "Input channel that provides training data",
            "IsRequired": True,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["File", "Pipe"],
        },
        {
            "Name": "validation",
            "Description": "Input channel that provides validation data",
            "IsRequired": False,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["File", "Pipe"],
        },
    ]

    session.sagemaker_client.describe_algorithm = Mock(return_value=any_input_algo)

    # Creating a File mode Estimator with an algorithm that supports both input modes
    # should work.
    AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        sagemaker_session=session,
    )


@patch("sagemaker.Session")
def test_algorithm_supported_input_mode_with_bad_input_types(session):
    # verify that the Estimator verifies raises exceptions when
    # attempting to train with an incorrect input type

    file_mode_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    file_mode_algo["TrainingSpecification"]["TrainingChannels"] = [
        {
            "Name": "training",
            "Description": "Input channel that provides training data",
            "IsRequired": True,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["File"],
        },
        {
            "Name": "validation",
            "Description": "Input channel that provides validation data",
            "IsRequired": False,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["File", "Pipe"],
        },
    ]

    session.sagemaker_client.describe_algorithm = Mock(return_value=file_mode_algo)

    # Creating a Pipe mode Estimator with a File mode algorithm should fail.
    with pytest.raises(ValueError):
        AlgorithmEstimator(
            algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
            role="SageMakerRole",
            instance_type="ml.m4.xlarge",
            instance_count=1,
            input_mode="Pipe",
            sagemaker_session=session,
        )

    pipe_mode_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    pipe_mode_algo["TrainingSpecification"]["TrainingChannels"] = [
        {
            "Name": "training",
            "Description": "Input channel that provides training data",
            "IsRequired": True,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["Pipe"],
        },
        {
            "Name": "validation",
            "Description": "Input channel that provides validation data",
            "IsRequired": False,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["File", "Pipe"],
        },
    ]

    session.sagemaker_client.describe_algorithm = Mock(return_value=pipe_mode_algo)

    # Creating a File mode Estimator with a Pipe mode algorithm should fail.
    with pytest.raises(ValueError):
        AlgorithmEstimator(
            algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
            role="SageMakerRole",
            instance_type="ml.m4.xlarge",
            instance_count=1,
            sagemaker_session=session,
        )


@patch("sagemaker.estimator.EstimatorBase.fit", Mock())
@patch("sagemaker.Session")
def test_algorithm_trainining_channels_with_expected_channels(session):
    training_channels = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)

    training_channels["TrainingSpecification"]["TrainingChannels"] = [
        {
            "Name": "training",
            "Description": "Input channel that provides training data",
            "IsRequired": True,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["File"],
        },
        {
            "Name": "validation",
            "Description": "Input channel that provides validation data",
            "IsRequired": False,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["File"],
        },
    ]

    session.sagemaker_client.describe_algorithm = Mock(return_value=training_channels)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    # Pass training and validation channels. This should work
    estimator.fit({"training": "s3://some/place", "validation": "s3://some/other"})

    # Passing only the training channel. Validation is optional so this should also work.
    estimator.fit({"training": "s3://some/place"})


@patch("sagemaker.estimator.EstimatorBase.fit", Mock())
@patch("sagemaker.Session")
def test_algorithm_trainining_channels_with_invalid_channels(session):
    training_channels = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)

    training_channels["TrainingSpecification"]["TrainingChannels"] = [
        {
            "Name": "training",
            "Description": "Input channel that provides training data",
            "IsRequired": True,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["File"],
        },
        {
            "Name": "validation",
            "Description": "Input channel that provides validation data",
            "IsRequired": False,
            "SupportedContentTypes": ["text/csv"],
            "SupportedCompressionTypes": ["None"],
            "SupportedInputModes": ["File"],
        },
    ]

    session.sagemaker_client.describe_algorithm = Mock(return_value=training_channels)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    # Passing only validation should fail as training is required.
    with pytest.raises(ValueError):
        estimator.fit({"validation": "s3://some/thing"})

    # Passing an unknown channel should fail???
    with pytest.raises(ValueError):
        estimator.fit({"training": "s3://some/data", "training2": "s3://some/other/data"})


@patch("sagemaker.Session")
def test_algorithm_train_instance_types_valid_instance_types(session):
    describe_algo_response = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    instance_types = ["ml.m4.xlarge", "ml.m5.2xlarge"]

    describe_algo_response["TrainingSpecification"][
        "SupportedTrainingInstanceTypes"
    ] = instance_types

    session.sagemaker_client.describe_algorithm = Mock(return_value=describe_algo_response)

    AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m5.2xlarge",
        instance_count=1,
        sagemaker_session=session,
    )


@patch("sagemaker.Session")
def test_algorithm_train_instance_types_invalid_instance_types(session):
    describe_algo_response = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    instance_types = ["ml.m4.xlarge", "ml.m5.2xlarge"]

    describe_algo_response["TrainingSpecification"][
        "SupportedTrainingInstanceTypes"
    ] = instance_types

    session.sagemaker_client.describe_algorithm = Mock(return_value=describe_algo_response)

    # invalid instance type, should fail
    with pytest.raises(ValueError):
        AlgorithmEstimator(
            algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
            role="SageMakerRole",
            instance_type="ml.m4.8xlarge",
            instance_count=1,
            sagemaker_session=session,
        )


@patch("sagemaker.Session")
def test_algorithm_distributed_training_validation(session):
    distributed_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    distributed_algo["TrainingSpecification"]["SupportsDistributedTraining"] = True

    single_instance_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    single_instance_algo["TrainingSpecification"]["SupportsDistributedTraining"] = False

    session.sagemaker_client.describe_algorithm = Mock(return_value=distributed_algo)

    # Distributed training should work for Distributed and Single instance.
    AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=2,
        sagemaker_session=session,
    )

    session.sagemaker_client.describe_algorithm = Mock(return_value=single_instance_algo)

    # distributed training on a single instance algorithm should fail.
    with pytest.raises(ValueError):
        AlgorithmEstimator(
            algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
            role="SageMakerRole",
            instance_type="ml.m5.2xlarge",
            instance_count=2,
            sagemaker_session=session,
        )


@patch("sagemaker.Session")
def test_algorithm_hyperparameter_integer_range_valid_range(session):
    hyperparameters = [
        {
            "Description": "Grow a tree with max_leaf_nodes in best-first fashion.",
            "Type": "Integer",
            "Name": "max_leaf_nodes",
            "Range": {
                "IntegerParameterRangeSpecification": {"MinValue": "1", "MaxValue": "100000"}
            },
            "IsTunable": True,
            "IsRequired": False,
            "DefaultValue": "100",
        }
    ]

    some_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    some_algo["TrainingSpecification"]["SupportedHyperParameters"] = hyperparameters

    session.sagemaker_client.describe_algorithm = Mock(return_value=some_algo)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.2xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    estimator.set_hyperparameters(max_leaf_nodes=1)
    estimator.set_hyperparameters(max_leaf_nodes=100000)


@patch("sagemaker.Session")
def test_algorithm_hyperparameter_integer_range_invalid_range(session):
    hyperparameters = [
        {
            "Description": "Grow a tree with max_leaf_nodes in best-first fashion.",
            "Type": "Integer",
            "Name": "max_leaf_nodes",
            "Range": {
                "IntegerParameterRangeSpecification": {"MinValue": "1", "MaxValue": "100000"}
            },
            "IsTunable": True,
            "IsRequired": False,
            "DefaultValue": "100",
        }
    ]

    some_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    some_algo["TrainingSpecification"]["SupportedHyperParameters"] = hyperparameters

    session.sagemaker_client.describe_algorithm = Mock(return_value=some_algo)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.2xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    with pytest.raises(ValueError):
        estimator.set_hyperparameters(max_leaf_nodes=0)

    with pytest.raises(ValueError):
        estimator.set_hyperparameters(max_leaf_nodes=100001)


@patch("sagemaker.Session")
def test_algorithm_hyperparameter_continuous_range_valid_range(session):
    hyperparameters = [
        {
            "Description": "A continuous hyperparameter",
            "Type": "Continuous",
            "Name": "max_leaf_nodes",
            "Range": {
                "ContinuousParameterRangeSpecification": {"MinValue": "0.0", "MaxValue": "1.0"}
            },
            "IsTunable": True,
            "IsRequired": False,
            "DefaultValue": "100",
        }
    ]

    some_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    some_algo["TrainingSpecification"]["SupportedHyperParameters"] = hyperparameters

    session.sagemaker_client.describe_algorithm = Mock(return_value=some_algo)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.2xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    estimator.set_hyperparameters(max_leaf_nodes=0)
    estimator.set_hyperparameters(max_leaf_nodes=1.0)
    estimator.set_hyperparameters(max_leaf_nodes=0.5)
    estimator.set_hyperparameters(max_leaf_nodes=1)


@patch("sagemaker.Session")
def test_algorithm_hyperparameter_continuous_range_invalid_range(session):
    hyperparameters = [
        {
            "Description": "A continuous hyperparameter",
            "Type": "Continuous",
            "Name": "max_leaf_nodes",
            "Range": {
                "ContinuousParameterRangeSpecification": {"MinValue": "0.0", "MaxValue": "1.0"}
            },
            "IsTunable": True,
            "IsRequired": False,
            "DefaultValue": "100",
        }
    ]

    some_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    some_algo["TrainingSpecification"]["SupportedHyperParameters"] = hyperparameters

    session.sagemaker_client.describe_algorithm = Mock(return_value=some_algo)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.2xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    with pytest.raises(ValueError):
        estimator.set_hyperparameters(max_leaf_nodes=1.1)

    with pytest.raises(ValueError):
        estimator.set_hyperparameters(max_leaf_nodes=-0.1)


@patch("sagemaker.Session")
def test_algorithm_hyperparameter_categorical_range(session):
    hyperparameters = [
        {
            "Description": "A continuous hyperparameter",
            "Type": "Categorical",
            "Name": "hp1",
            "Range": {"CategoricalParameterRangeSpecification": {"Values": ["TF", "MXNet"]}},
            "IsTunable": True,
            "IsRequired": False,
            "DefaultValue": "100",
        }
    ]

    some_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    some_algo["TrainingSpecification"]["SupportedHyperParameters"] = hyperparameters

    session.sagemaker_client.describe_algorithm = Mock(return_value=some_algo)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.2xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    estimator.set_hyperparameters(hp1="MXNet")
    estimator.set_hyperparameters(hp1="TF")

    with pytest.raises(ValueError):
        estimator.set_hyperparameters(hp1="Chainer")

    with pytest.raises(ValueError):
        estimator.set_hyperparameters(hp1="MxNET")


@patch("sagemaker.Session")
def test_algorithm_required_hyperparameters_not_provided(session):
    hyperparameters = [
        {
            "Description": "A continuous hyperparameter",
            "Type": "Categorical",
            "Name": "hp1",
            "Range": {"CategoricalParameterRangeSpecification": {"Values": ["TF", "MXNet"]}},
            "IsTunable": True,
            "IsRequired": True,
        },
        {
            "Name": "hp2",
            "Description": "A continuous hyperparameter",
            "Type": "Categorical",
            "IsTunable": False,
            "IsRequired": True,
        },
    ]

    some_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    some_algo["TrainingSpecification"]["SupportedHyperParameters"] = hyperparameters

    session.sagemaker_client.describe_algorithm = Mock(return_value=some_algo)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.2xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    # hp1 is required and was not provided
    with pytest.raises(ValueError):
        estimator.set_hyperparameters(hp2="TF2")

    # Calling fit with unset required hyperparameters should fail
    # this covers the use case of not calling set_hyperparameters() explicitly
    with pytest.raises(ValueError):
        estimator.fit({"training": "s3://some/place"})


@patch("sagemaker.Session")
@patch("sagemaker.estimator.EstimatorBase.fit", Mock())
def test_algorithm_required_hyperparameters_are_provided(session):
    hyperparameters = [
        {
            "Description": "A categorical hyperparameter",
            "Type": "Categorical",
            "Name": "hp1",
            "Range": {"CategoricalParameterRangeSpecification": {"Values": ["TF", "MXNet"]}},
            "IsTunable": True,
            "IsRequired": True,
        },
        {
            "Name": "hp2",
            "Description": "A categorical hyperparameter",
            "Type": "Categorical",
            "IsTunable": False,
            "IsRequired": True,
        },
        {
            "Name": "free_text_hp1",
            "Description": "You can write anything here",
            "Type": "FreeText",
            "IsTunable": False,
            "IsRequired": True,
        },
    ]

    some_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    some_algo["TrainingSpecification"]["SupportedHyperParameters"] = hyperparameters

    session.sagemaker_client.describe_algorithm = Mock(return_value=some_algo)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.2xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    # All 3 Hyperparameters are provided
    estimator.set_hyperparameters(hp1="TF", hp2="TF2", free_text_hp1="Hello!")


@patch("sagemaker.Session")
def test_algorithm_required_free_text_hyperparameter_not_provided(session):
    hyperparameters = [
        {
            "Name": "free_text_hp1",
            "Description": "You can write anything here",
            "Type": "FreeText",
            "IsTunable": False,
            "IsRequired": True,
        },
        {
            "Name": "free_text_hp2",
            "Description": "You can write anything here",
            "Type": "FreeText",
            "IsTunable": False,
            "IsRequired": False,
        },
    ]

    some_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    some_algo["TrainingSpecification"]["SupportedHyperParameters"] = hyperparameters

    session.sagemaker_client.describe_algorithm = Mock(return_value=some_algo)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.2xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    # Calling fit with unset required hyperparameters should fail
    # this covers the use case of not calling set_hyperparameters() explicitly
    with pytest.raises(ValueError):
        estimator.fit({"training": "s3://some/place"})

    # hp1 is required and was not provided
    with pytest.raises(ValueError):
        estimator.set_hyperparameters(free_text_hp2="some text")


@patch("sagemaker.Session")
@patch("sagemaker.algorithm.AlgorithmEstimator.create_model")
def test_algorithm_create_transformer(create_model, session):
    session.sagemaker_client.describe_algorithm = Mock(return_value=DESCRIBE_ALGORITHM_RESPONSE)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    estimator.latest_training_job = _TrainingJob(session, "some-job-name")
    model = Mock()
    model.name = "my-model"
    create_model.return_value = model

    transformer = estimator.transformer(instance_count=1, instance_type="ml.m4.xlarge")

    assert isinstance(transformer, Transformer)
    create_model.assert_called()
    assert transformer.model_name == "my-model"


@patch("sagemaker.Session")
def test_algorithm_create_transformer_without_completed_training_job(session):
    session.sagemaker_client.describe_algorithm = Mock(return_value=DESCRIBE_ALGORITHM_RESPONSE)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    with pytest.raises(RuntimeError) as error:
        estimator.transformer(instance_count=1, instance_type="ml.m4.xlarge")
        assert "No finished training job found associated with this estimator" in str(error)


@patch("sagemaker.algorithm.AlgorithmEstimator.create_model")
@patch("sagemaker.Session")
def test_algorithm_create_transformer_with_product_id(create_model, session):
    response = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    response["ProductId"] = "some-product-id"
    session.sagemaker_client.describe_algorithm = Mock(return_value=response)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    estimator.latest_training_job = _TrainingJob(session, "some-job-name")
    model = Mock()
    model.name = "my-model"
    create_model.return_value = model

    transformer = estimator.transformer(instance_count=1, instance_type="ml.m4.xlarge")
    assert transformer.env is None


@patch("sagemaker.Session")
def test_algorithm_enable_network_isolation_no_product_id(session):
    session.sagemaker_client.describe_algorithm = Mock(return_value=DESCRIBE_ALGORITHM_RESPONSE)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    network_isolation = estimator.enable_network_isolation()
    assert network_isolation is False


@patch("sagemaker.Session")
def test_algorithm_enable_network_isolation_with_product_id(session):
    response = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    response["ProductId"] = "some-product-id"
    session.sagemaker_client.describe_algorithm = Mock(return_value=response)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        sagemaker_session=session,
    )

    network_isolation = estimator.enable_network_isolation()
    assert network_isolation is True


@patch("sagemaker.Session")
def test_algorithm_encrypt_inter_container_traffic(session):
    response = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    response["encrypt_inter_container_traffic"] = True
    session.sagemaker_client.describe_algorithm = Mock(return_value=response)

    estimator = AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        sagemaker_session=session,
        encrypt_inter_container_traffic=True,
    )

    encrypt_inter_container_traffic = estimator.encrypt_inter_container_traffic
    assert encrypt_inter_container_traffic is True


@patch("sagemaker.Session")
def test_algorithm_no_required_hyperparameters(session):
    some_algo = copy.deepcopy(DESCRIBE_ALGORITHM_RESPONSE)
    del some_algo["TrainingSpecification"]["SupportedHyperParameters"]

    session.sagemaker_client.describe_algorithm = Mock(return_value=some_algo)

    # Calling AlgorithmEstimator() with unset required hyperparameters
    # should fail if they are required.
    # Pass training and hyperparameters channels. This should work
    assert AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.2xlarge",
        instance_count=1,
        sagemaker_session=session,
    )


def test_algorithm_attach_from_hyperparameter_tuning():
    session = Mock()
    job_name = "training-job-that-is-part-of-a-tuning-job"
    algo_arn = "arn:aws:sagemaker:us-east-2:000000000000:algorithm/scikit-decision-trees"
    role_arn = "arn:aws:iam::123412341234:role/SageMakerRole"
    instance_count = 1
    instance_type = "ml.m4.xlarge"
    volume_size = 30
    input_mode = "File"

    session.sagemaker_client.list_tags.return_value = {"Tags": []}
    session.sagemaker_client.describe_algorithm.return_value = DESCRIBE_ALGORITHM_RESPONSE
    session.sagemaker_client.describe_training_job.return_value = {
        "TrainingJobName": job_name,
        "TrainingJobArn": "arn:aws:sagemaker:us-east-2:123412341234:training-job/%s" % job_name,
        "TuningJobArn": "arn:aws:sagemaker:us-east-2:123412341234:hyper-parameter-tuning-job/%s"
        % job_name,
        "ModelArtifacts": {
            "S3ModelArtifacts": "s3://sagemaker-us-east-2-123412341234/output/model.tar.gz"
        },
        "TrainingJobOutput": {
            "S3TrainingJobOutput": "s3://sagemaker-us-east-2-123412341234/output/output.tar.gz"
        },
        "TrainingJobStatus": "Succeeded",
        "HyperParameters": {
            "_tuning_objective_metric": "validation:accuracy",
            "max_leaf_nodes": 1,
            "free_text_hp1": "foo",
        },
        "AlgorithmSpecification": {"AlgorithmName": algo_arn, "TrainingInputMode": input_mode},
        "MetricDefinitions": [
            {"Name": "validation:accuracy", "Regex": "validation-accuracy: (\\S+)"}
        ],
        "RoleArn": role_arn,
        "InputDataConfig": [
            {
                "ChannelName": "training",
                "DataSource": {
                    "S3DataSource": {
                        "S3DataType": "S3Prefix",
                        "S3Uri": "s3://sagemaker-us-east-2-123412341234/input/training.csv",
                        "S3DataDistributionType": "FullyReplicated",
                    }
                },
                "CompressionType": "None",
                "RecordWrapperType": "None",
            }
        ],
        "OutputDataConfig": {
            "KmsKeyId": "",
            "S3OutputPath": "s3://sagemaker-us-east-2-123412341234/output",
            "RemoveJobNameFromS3OutputPath": False,
        },
        "ResourceConfig": {
            "InstanceType": instance_type,
            "InstanceCount": instance_count,
            "VolumeSizeInGB": volume_size,
        },
        "StoppingCondition": {"MaxRuntimeInSeconds": 86400},
    }

    estimator = AlgorithmEstimator.attach(job_name, sagemaker_session=session)
    assert estimator.hyperparameters() == {"max_leaf_nodes": 1, "free_text_hp1": "foo"}
    assert estimator.algorithm_arn == algo_arn
    assert estimator.role == role_arn
    assert estimator.instance_count == instance_count
    assert estimator.instance_type == instance_type
    assert estimator.volume_size == volume_size
    assert estimator.input_mode == input_mode
    assert estimator.sagemaker_session == session


@patch("sagemaker.Session")
def test_algorithm_supported_with_spot_instances(session):
    session.sagemaker_client.describe_algorithm = Mock(return_value=DESCRIBE_ALGORITHM_RESPONSE)

    assert AlgorithmEstimator(
        algorithm_arn="arn:aws:sagemaker:us-east-2:1234:algorithm/scikit-decision-trees",
        role="SageMakerRole",
        instance_type="ml.m4.xlarge",
        instance_count=1,
        use_spot_instances=True,
        max_wait=500,
        sagemaker_session=session,
    )