-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathtuner.py
2418 lines (2078 loc) · 106 KB
/
tuner.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 importlib
import inspect
import json
import logging
from enum import Enum
from typing import Dict, List, Optional, Set, Union
import sagemaker
from sagemaker.amazon.amazon_estimator import (
AmazonAlgorithmEstimatorBase,
FileSystemRecordSet,
RecordSet,
)
from sagemaker.amazon.hyperparameter import Hyperparameter as hp # noqa
from sagemaker.analytics import HyperparameterTuningJobAnalytics
from sagemaker.deprecations import removed_function
from sagemaker.estimator import EstimatorBase, Framework
from sagemaker.inputs import FileSystemInput, TrainingInput
from sagemaker.job import _Job
from sagemaker.jumpstart.utils import (
add_jumpstart_uri_tags,
get_jumpstart_base_name_if_jumpstart_model,
)
from sagemaker.parameter import (
CategoricalParameter,
ContinuousParameter,
IntegerParameter,
ParameterRange,
)
from sagemaker.session import Session
from sagemaker.utils import (
Tags,
base_from_name,
base_name_from_image,
format_tags,
name_from_base,
to_string,
)
from sagemaker.workflow.entities import PipelineVariable
from sagemaker.workflow.pipeline_context import runnable_by_pipeline
AMAZON_ESTIMATOR_MODULE = "sagemaker"
AMAZON_ESTIMATOR_CLS_NAMES = {
"factorization-machines": "FactorizationMachines",
"kmeans": "KMeans",
"lda": "LDA",
"linear-learner": "LinearLearner",
"ntm": "NTM",
"randomcutforest": "RandomCutForest",
"knn": "KNN",
"object2vec": "Object2Vec",
}
HYPERPARAMETER_TUNING_JOB_NAME = "HyperParameterTuningJobName"
PARENT_HYPERPARAMETER_TUNING_JOBS = "ParentHyperParameterTuningJobs"
WARM_START_TYPE = "WarmStartType"
HYPERBAND_STRATEGY_CONFIG = "HyperbandStrategyConfig"
HYPERBAND_MIN_RESOURCE = "MinResource"
HYPERBAND_MAX_RESOURCE = "MaxResource"
GRID_SEARCH = "Grid"
MAX_NUMBER_OF_TRAINING_JOBS_NOT_IMPROVING = "MaxNumberOfTrainingJobsNotImproving"
BEST_OBJECTIVE_NOT_IMPROVING = "BestObjectiveNotImproving"
CONVERGENCE_DETECTED = "ConvergenceDetected"
COMPLETE_ON_CONVERGENCE_DETECTED = "CompleteOnConvergence"
TARGET_OBJECTIVE_METRIC_VALUE = "TargetObjectiveMetricValue"
MAX_RUNTIME_IN_SECONDS = "MaxRuntimeInSeconds"
logger = logging.getLogger(__name__)
class WarmStartTypes(Enum):
"""Warm Start Configuration type.
There can be two types of warm start jobs:
* IdenticalDataAndAlgorithm: Type of warm start that allows users to reuse
training results from existing tuning jobs that have the same algorithm code
and datasets.
* TransferLearning: Type of warm start that allows users to reuse training
results from existing tuning jobs that have similar algorithm code and
datasets.
"""
IDENTICAL_DATA_AND_ALGORITHM = "IdenticalDataAndAlgorithm"
TRANSFER_LEARNING = "TransferLearning"
class WarmStartConfig(object):
"""Warm Start Configuration which defines the nature of the warm start.
This warm start configuration is provided to the ``HyperparameterTuner``,
with type and parents for warm start.
Examples:
>>> warm_start_config = WarmStartConfig(
>>> type=WarmStartTypes.TransferLearning, parents={"p1","p2"})
>>> warm_start_config.type
"TransferLearning"
>>> warm_start_config.parents
{"p1","p2"}
"""
def __init__(
self,
warm_start_type: WarmStartTypes,
parents: Set[Union[str, PipelineVariable]],
):
"""Creates a ``WarmStartConfig`` with provided ``WarmStartTypes`` and parents.
Args:
warm_start_type (sagemaker.tuner.WarmStartTypes): This should be one
of the supported warm start types in WarmStartType
parents (set[str] or set[PipelineVariable]): Set of parent tuning jobs which
will be used to warm start the new tuning job.
"""
if warm_start_type not in list(WarmStartTypes):
raise ValueError(
f"Invalid type: {warm_start_type}, "
f"valid warm start types are: {list(WarmStartTypes)}"
)
if not parents:
raise ValueError(f"Invalid parents: {parents}, parents should not be None/empty")
self.type = warm_start_type
self.parents = set(parents)
@classmethod
def from_job_desc(cls, warm_start_config):
"""Creates a ``WarmStartConfig`` from a warm start configuration response.
This is the warm start configuration from the DescribeTrainingJob response.
Examples:
>>> warm_start_config = WarmStartConfig.from_job_desc(warm_start_config={
>>> "WarmStartType":"TransferLearning",
>>> "ParentHyperParameterTuningJobs": [
>>> {'HyperParameterTuningJobName': "p1"},
>>> {'HyperParameterTuningJobName': "p2"},
>>> ]
>>>})
>>> warm_start_config.type
"TransferLearning"
>>> warm_start_config.parents
["p1","p2"]
Args:
warm_start_config (dict): The expected format of the
``warm_start_config`` contains two first-class
Returns:
sagemaker.tuner.WarmStartConfig: De-serialized instance of
WarmStartConfig containing the type and parents provided as part of
``warm_start_config``.
"""
if (
not warm_start_config
or WARM_START_TYPE not in warm_start_config
or PARENT_HYPERPARAMETER_TUNING_JOBS not in warm_start_config
):
return None
parents = []
for parent in warm_start_config[PARENT_HYPERPARAMETER_TUNING_JOBS]:
parents.append(parent[HYPERPARAMETER_TUNING_JOB_NAME])
return cls(
warm_start_type=WarmStartTypes(warm_start_config[WARM_START_TYPE]),
parents=parents,
)
def to_input_req(self):
"""Converts the ``self`` instance to the desired input request format.
Examples:
>>> warm_start_config = WarmStartConfig
(
warm_start_type=WarmStartTypes.TransferLearning,parents=["p1,p2"]
)
>>> warm_start_config.to_input_req()
{
"WarmStartType":"TransferLearning",
"ParentHyperParameterTuningJobs": [
{'HyperParameterTuningJobName': "p1"},
{'HyperParameterTuningJobName': "p2"},
]
}
Returns:
dict: Containing the "WarmStartType" and
"ParentHyperParameterTuningJobs" as the first class fields.
"""
return {
WARM_START_TYPE: self.type.value,
PARENT_HYPERPARAMETER_TUNING_JOBS: [
{HYPERPARAMETER_TUNING_JOB_NAME: parent} for parent in self.parents
],
}
class HyperbandStrategyConfig(object):
"""The configuration for Hyperband, a multi-fidelity based hyperparameter tuning strategy.
Hyperband uses the final and intermediate results of a training job to dynamically allocate
resources to hyperparameter configurations being evaluated while automatically stopping
under-performing configurations. This parameter should be provided only if Hyperband is
selected as the Strategy under the HyperParameterTuningJobConfig.
Examples:
>>> hyperband_strategy_config = HyperbandStrategyConfig(
>>> max_resource=10, min_resource = 1)
>>> hyperband_strategy_config.max_resource
10
>>> hyperband_strategy_config.min_resource
1
"""
def __init__(self, max_resource: int, min_resource: int):
"""Creates a ``HyperbandStrategyConfig`` with provided `min_resource`` and ``max_resource``.
Args:
max_resource (int): The maximum number of resources (such as epochs) that can be used
by a training job launched by a hyperparameter tuning job.
Once a job reaches the MaxResource value, it is stopped.
If a value for MaxResource is not provided, and Hyperband is selected as the
hyperparameter tuning strategy, HyperbandTrainingJ attempts to infer MaxResource
from the following keys (if present) in StaticsHyperParameters:
epochs
numepochs
n-epochs
n_epochs
num_epochs
If HyperbandStrategyConfig is unable to infer a value for MaxResource, it generates
a validation error.
The maximum value is 20,000 epochs. All metrics that correspond to an objective
metric are used to derive early stopping decisions.
For distributed training jobs, ensure that duplicate metrics are not printed in the
logs across the individual nodes in a training job.
If multiple nodes are publishing duplicate or incorrect metrics, hyperband
optimisation algorithm may make an incorrect stopping decision and stop the job
prematurely.
min_resource (int): The minimum number of resources (such as epochs)
that can be used by a training job launched by a hyperparameter tuning job.
If the value for MinResource has not been reached, the training job will not be
stopped by Hyperband.
"""
self.min_resource = min_resource
self.max_resource = max_resource
@classmethod
def from_job_desc(cls, hyperband_strategy_config):
"""Creates a ``HyperbandStrategyConfig`` from a hyperband strategy configuration response.
This is the Hyperband strategy configuration from the DescribeTuningJob response.
Examples:
>>> hyperband_strategy_config =
>>> HyperbandStrategyConfig.from_job_desc(hyperband_strategy_config={
>>> "MaxResource": 10,
>>> "MinResource": 1
>>> })
>>> hyperband_strategy_config.max_resource
10
>>> hyperband_strategy_config.min_resource
1
Args:
hyperband_strategy_config (dict): The expected format of the
``hyperband_strategy_config`` contains two first-class fields
Returns:
sagemaker.tuner.HyperbandStrategyConfig: De-serialized instance of
``HyperbandStrategyConfig`` containing the max_resource
and min_resource provided as part of ``hyperband_strategy_config``.
"""
return cls(
min_resource=hyperband_strategy_config[HYPERBAND_MIN_RESOURCE],
max_resource=hyperband_strategy_config[HYPERBAND_MAX_RESOURCE],
)
def to_input_req(self):
"""Converts the ``self`` instance to the desired input request format.
Examples:
>>> hyperband_strategy_config = HyperbandStrategyConfig (
max_resource=10,
min_resource=1
)
>>> hyperband_strategy_config.to_input_req()
{
"MaxResource":10,
"MinResource": 1
}
Returns:
dict: Containing the "MaxResource" and
"MinResource" as the first class fields.
"""
return {
HYPERBAND_MIN_RESOURCE: self.min_resource,
HYPERBAND_MAX_RESOURCE: self.max_resource,
}
class StrategyConfig(object):
"""The configuration for a training job launched by a hyperparameter tuning job.
Choose Bayesian for Bayesian optimization, and Random for random search optimization.
For more advanced use cases, use Hyperband, which evaluates objective metrics for training jobs
after every epoch.
"""
def __init__(
self,
hyperband_strategy_config: HyperbandStrategyConfig,
):
"""Creates a ``StrategyConfig`` with provided ``HyperbandStrategyConfig``.
Args:
hyperband_strategy_config (sagemaker.tuner.HyperbandStrategyConfig): The configuration
for the object that specifies the Hyperband strategy.
This parameter is only supported for the Hyperband selection for Strategy within
the HyperParameterTuningJobConfig.
"""
self.hyperband_strategy_config = hyperband_strategy_config
@classmethod
def from_job_desc(cls, strategy_config):
"""Creates a ``HyperbandStrategyConfig`` from a hyperband strategy configuration response.
This is the hyper band strategy configuration from the DescribeTuningJob response.
Args:
strategy_config (dict): The expected format of the
``strategy_config`` contains one first-class field
Returns:
sagemaker.tuner.StrategyConfig: De-serialized instance of
StrategyConfig containing the strategy configuration.
"""
return cls(
hyperband_strategy_config=HyperbandStrategyConfig.from_job_desc(
strategy_config[HYPERBAND_STRATEGY_CONFIG]
)
)
def to_input_req(self):
"""Converts the ``self`` instance to the desired input request format.
Examples:
>>> strategy_config = StrategyConfig(
HyperbandStrategyConfig(
max_resource=10,
min_resource=1
)
)
>>> strategy_config.to_input_req()
{
"HyperbandStrategyConfig": {
"MaxResource":10,
"MinResource": 1
}
}
Returns:
dict: Containing the strategy configurations.
"""
return {
HYPERBAND_STRATEGY_CONFIG: self.hyperband_strategy_config.to_input_req(),
}
class InstanceConfig:
"""Instance configuration for training jobs started by hyperparameter tuning.
Contains the configuration(s) for one or more resources for processing hyperparameter jobs.
These resources include compute instances and storage volumes to use in model training jobs
launched by hyperparameter tuning jobs.
"""
def __init__(
self,
instance_count: Union[int, PipelineVariable] = None,
instance_type: Union[str, PipelineVariable] = None,
volume_size: Union[int, PipelineVariable] = 30,
):
"""Creates a ``InstanceConfig`` instance.
It takes instance configuration information for training
jobs that are created as the result of a hyperparameter tuning job.
Args:
* instance_count (str or PipelineVariable): The number of compute instances of type
InstanceType to use. For distributed training, select a value greater than 1.
* instance_type (str or PipelineVariable):
The instance type used to run hyperparameter optimization tuning jobs.
* volume_size (int or PipelineVariable): The volume size in GB of the data to be
processed for hyperparameter optimization
"""
self.instance_count = instance_count
self.instance_type = instance_type
self.volume_size = volume_size
@classmethod
def from_job_desc(cls, instance_config):
"""Creates a ``InstanceConfig`` from an instance configuration response.
This is the instance configuration from the DescribeTuningJob response.
Args:
instance_config (dict): The expected format of the
``instance_config`` contains one first-class field
Returns:
sagemaker.tuner.InstanceConfig: De-serialized instance of
InstanceConfig containing the strategy configuration.
"""
return cls(
instance_count=instance_config["InstanceCount"],
instance_type=instance_config[" InstanceType "],
volume_size=instance_config["VolumeSizeInGB"],
)
def to_input_req(self):
"""Converts the ``self`` instance to the desired input request format.
Examples:
>>> strategy_config = InstanceConfig(
instance_count=1,
instance_type='ml.m4.xlarge',
volume_size=30
)
>>> strategy_config.to_input_req()
{
"InstanceCount":1,
"InstanceType":"ml.m4.xlarge",
"VolumeSizeInGB":30
}
Returns:
dict: Containing the instance configurations.
"""
return {
"InstanceCount": self.instance_count,
"InstanceType": self.instance_type,
"VolumeSizeInGB": self.volume_size,
}
class TuningJobCompletionCriteriaConfig(object):
"""The configuration for a job completion criteria."""
def __init__(
self,
max_number_of_training_jobs_not_improving: int = None,
complete_on_convergence: bool = None,
target_objective_metric_value: float = None,
):
"""Creates a ``TuningJobCompletionCriteriaConfig`` with provided criteria.
Args:
max_number_of_training_jobs_not_improving (int): The number of training jobs that do not
improve the best objective after which tuning job will stop.
complete_on_convergence (bool): A flag to stop your hyperparameter tuning job if
automatic model tuning (AMT) has detected that your model has converged as evaluated
against your objective function.
target_objective_metric_value (float): The value of the objective metric.
"""
self.max_number_of_training_jobs_not_improving = max_number_of_training_jobs_not_improving
self.complete_on_convergence = complete_on_convergence
self.target_objective_metric_value = target_objective_metric_value
@classmethod
def from_job_desc(cls, completion_criteria_config):
"""Creates a ``TuningJobCompletionCriteriaConfig`` from a configuration response.
This is the completion criteria configuration from the DescribeTuningJob response.
Args:
completion_criteria_config (dict): The expected format of the
``completion_criteria_config`` contains three first-class fields
Returns:
sagemaker.tuner.TuningJobCompletionCriteriaConfig: De-serialized instance of
TuningJobCompletionCriteriaConfig containing the completion criteria.
"""
complete_on_convergence = None
if CONVERGENCE_DETECTED in completion_criteria_config:
if completion_criteria_config[CONVERGENCE_DETECTED][COMPLETE_ON_CONVERGENCE_DETECTED]:
complete_on_convergence = bool(
completion_criteria_config[CONVERGENCE_DETECTED][
COMPLETE_ON_CONVERGENCE_DETECTED
]
== "Enabled"
)
max_number_of_training_jobs_not_improving = None
if BEST_OBJECTIVE_NOT_IMPROVING in completion_criteria_config:
if completion_criteria_config[BEST_OBJECTIVE_NOT_IMPROVING][
MAX_NUMBER_OF_TRAINING_JOBS_NOT_IMPROVING
]:
max_number_of_training_jobs_not_improving = completion_criteria_config[
BEST_OBJECTIVE_NOT_IMPROVING
][MAX_NUMBER_OF_TRAINING_JOBS_NOT_IMPROVING]
target_objective_metric_value = None
if TARGET_OBJECTIVE_METRIC_VALUE in completion_criteria_config:
target_objective_metric_value = completion_criteria_config[
TARGET_OBJECTIVE_METRIC_VALUE
]
return cls(
max_number_of_training_jobs_not_improving=max_number_of_training_jobs_not_improving,
complete_on_convergence=complete_on_convergence,
target_objective_metric_value=target_objective_metric_value,
)
def to_input_req(self):
"""Converts the ``self`` instance to the desired input request format.
Examples:
>>> completion_criteria_config = TuningJobCompletionCriteriaConfig(
max_number_of_training_jobs_not_improving=5
complete_on_convergence = True,
target_objective_metric_value = 0.42
)
>>> completion_criteria_config.to_input_req()
{
"BestObjectiveNotImproving": {
"MaxNumberOfTrainingJobsNotImproving":5
},
"ConvergenceDetected": {
"CompleteOnConvergence": "Enabled",
},
"TargetObjectiveMetricValue": 0.42
}
Returns:
dict: Containing the completion criteria configurations.
"""
completion_criteria_config = {}
if self.max_number_of_training_jobs_not_improving is not None:
completion_criteria_config[BEST_OBJECTIVE_NOT_IMPROVING] = {}
completion_criteria_config[BEST_OBJECTIVE_NOT_IMPROVING][
MAX_NUMBER_OF_TRAINING_JOBS_NOT_IMPROVING
] = self.max_number_of_training_jobs_not_improving
if self.target_objective_metric_value is not None:
completion_criteria_config[TARGET_OBJECTIVE_METRIC_VALUE] = (
self.target_objective_metric_value
)
if self.complete_on_convergence is not None:
completion_criteria_config[CONVERGENCE_DETECTED] = {}
completion_criteria_config[CONVERGENCE_DETECTED][COMPLETE_ON_CONVERGENCE_DETECTED] = (
"Enabled" if self.complete_on_convergence else "Disabled"
)
return completion_criteria_config
class HyperparameterTuner(object):
"""Defines interaction with Amazon SageMaker hyperparameter tuning jobs.
It also supports deploying the resulting models.
"""
TUNING_JOB_NAME_MAX_LENGTH = 32
SAGEMAKER_ESTIMATOR_MODULE = "sagemaker_estimator_module"
SAGEMAKER_ESTIMATOR_CLASS_NAME = "sagemaker_estimator_class_name"
DEFAULT_ESTIMATOR_MODULE = "sagemaker.estimator"
DEFAULT_ESTIMATOR_CLS_NAME = "Estimator"
def __init__(
self,
estimator: EstimatorBase,
objective_metric_name: Union[str, PipelineVariable],
hyperparameter_ranges: Dict[str, ParameterRange],
metric_definitions: Optional[List[Dict[str, Union[str, PipelineVariable]]]] = None,
strategy: Union[str, PipelineVariable] = "Bayesian",
objective_type: Union[str, PipelineVariable] = "Maximize",
max_jobs: Union[int, PipelineVariable] = None,
max_parallel_jobs: Union[int, PipelineVariable] = 1,
max_runtime_in_seconds: Optional[Union[int, PipelineVariable]] = None,
tags: Optional[Tags] = None,
base_tuning_job_name: Optional[str] = None,
warm_start_config: Optional[WarmStartConfig] = None,
strategy_config: Optional[StrategyConfig] = None,
completion_criteria_config: Optional[TuningJobCompletionCriteriaConfig] = None,
early_stopping_type: Union[str, PipelineVariable] = "Off",
estimator_name: Optional[str] = None,
random_seed: Optional[int] = None,
autotune: bool = False,
hyperparameters_to_keep_static: Optional[List[str]] = None,
):
"""Creates a ``HyperparameterTuner`` instance.
It takes an estimator to obtain configuration information for training
jobs that are created as the result of a hyperparameter tuning job.
Args:
estimator (sagemaker.estimator.EstimatorBase): An estimator object
that has been initialized with the desired configuration. There
does not need to be a training job associated with this
instance.
objective_metric_name (str or PipelineVariable): Name of the metric for evaluating
training jobs.
hyperparameter_ranges (dict[str, sagemaker.parameter.ParameterRange]): Dictionary of
parameter ranges. These parameter ranges can be one
of three types: Continuous, Integer, or Categorical. The keys of
the dictionary are the names of the hyperparameter, and the
values are the appropriate parameter range class to represent
the range.
metric_definitions (list[dict[str, str] or list[dict[str, PipelineVariable]]): A list of
dictionaries that defines the metric(s) used to evaluate the training jobs (default:
None). Each dictionary contains two keys: 'Name' for the name of
the metric, and 'Regex' for the regular expression used to
extract the metric from the logs. This should be defined only
for hyperparameter tuning jobs that don't use an Amazon
algorithm.
strategy (str or PipelineVariable): Strategy to be used for hyperparameter estimations.
More information about different strategies:
https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-how-it-works.html.
Available options are: 'Bayesian', 'Random', 'Hyperband',
'Grid' (default: 'Bayesian')
objective_type (str or PipelineVariable): The type of the objective metric for
evaluating training jobs. This value can be either 'Minimize' or
'Maximize' (default: 'Maximize').
max_jobs (int or PipelineVariable): Maximum total number of training jobs to start for
the hyperparameter tuning job. The default value is unspecified fot the 'Grid'
strategy and the default value is 1 for all others strategies (default: None).
max_parallel_jobs (int or PipelineVariable): Maximum number of parallel training jobs to
start (default: 1).
max_runtime_in_seconds (int or PipelineVariable): The maximum time in seconds
that a hyperparameter tuning job can run.
tags (Optional[Tags]): Tags for labeling the tuning job (default: None).
For more, see https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.
base_tuning_job_name (str): Prefix for the hyperparameter tuning job
name when the :meth:`~sagemaker.tuner.HyperparameterTuner.fit`
method launches. If not specified, a default job name is
generated, based on the training image name and current
timestamp.
warm_start_config (sagemaker.tuner.WarmStartConfig): A
``WarmStartConfig`` object that has been initialized with the
configuration defining the nature of warm start tuning job.
strategy_config (sagemaker.tuner.StrategyConfig): A configuration for "Hyperparameter"
tuning job optimisation strategy.
completion_criteria_config (sagemaker.tuner.TuningJobCompletionCriteriaConfig): A
configuration for the completion criteria.
early_stopping_type (str or PipelineVariable): Specifies whether early stopping is
enabled for the job. Can be either 'Auto' or 'Off' (default:
'Off'). If set to 'Off', early stopping will not be attempted.
If set to 'Auto', early stopping of some training jobs may
happen, but is not guaranteed to.
estimator_name (str): A unique name to identify an estimator within the
hyperparameter tuning job, when more than one estimator is used with
the same tuning job (default: None).
random_seed (int): An initial value used to initialize a pseudo-random number generator.
Setting a random seed will make the hyperparameter tuning search strategies to
produce more consistent configurations for the same tuning job.
autotune (bool): Whether the parameter ranges or other unset settings of a tuning job
should be chosen automatically (default: False).
hyperparameters_to_keep_static: list[str]: Names of hyperparameters that will be kept
static and will not be assigned a tunable range with Autotune functionality.
(default: None).
"""
if hyperparameter_ranges is None or len(hyperparameter_ranges) == 0:
if not autotune:
raise ValueError("Need to specify hyperparameter ranges or set autotune=True.")
if not autotune and hyperparameters_to_keep_static is not None:
raise ValueError(
"hyperparameters_to_keep_static parameter is set, however Autotune mode is not "
"enabled. Either do not set value for hyperparameters_to_keep_static parameter, "
"or enable Autotune mode by setting autotune=True."
)
if hyperparameters_to_keep_static is not None:
if len(hyperparameters_to_keep_static) != len(set(hyperparameters_to_keep_static)):
raise ValueError("Please remove duplicate names in hyperparameters_to_keep_static.")
if estimator_name is not None:
self.estimator = None
self.objective_metric_name = None
self._hyperparameter_ranges = None
self.metric_definitions = None
self.estimator_dict = {estimator_name: estimator}
self.objective_metric_name_dict = {estimator_name: objective_metric_name}
self._hyperparameter_ranges_dict = {estimator_name: hyperparameter_ranges}
self.metric_definitions_dict = (
{estimator_name: metric_definitions} if metric_definitions is not None else {}
)
self.static_hyperparameters = None
self.auto_parameters = None
self.auto_parameters_dict = None
self.hyperparameters_to_keep_static = None
self.hyperparameters_to_keep_static_dict = {
estimator_name: hyperparameters_to_keep_static
}
else:
self.estimator = estimator
self.objective_metric_name = objective_metric_name
self._hyperparameter_ranges = hyperparameter_ranges
self.metric_definitions = metric_definitions
self.estimator_dict = None
self.objective_metric_name_dict = None
self._hyperparameter_ranges_dict = None
self.metric_definitions_dict = None
self.static_hyperparameters_dict = None
self.auto_parameters = None
self.auto_parameters_dict = None
self.hyperparameters_to_keep_static = hyperparameters_to_keep_static
self.hyperparameters_to_keep_static_dict = None
self._validate_parameter_ranges(estimator, hyperparameter_ranges)
self.strategy = strategy
self.strategy_config = strategy_config
self.completion_criteria_config = completion_criteria_config
self.objective_type = objective_type
# For the GridSearch strategy we expect the max_jobs equals None and recalculate it later.
# For all other strategies for the backward compatibility we keep
# the default value as 1 (previous default value).
self.max_jobs = max_jobs
if max_jobs is None and strategy != GRID_SEARCH:
self.max_jobs = 1
self.max_parallel_jobs = max_parallel_jobs
self.max_runtime_in_seconds = max_runtime_in_seconds
self.tags = format_tags(tags)
self.base_tuning_job_name = base_tuning_job_name
self._current_job_name = None
self.latest_tuning_job = None
self.warm_start_config = warm_start_config
self.early_stopping_type = early_stopping_type
self.random_seed = random_seed
self.instance_configs_dict = None
self.instance_configs = None
self.autotune = autotune
def override_resource_config(
self,
instance_configs: Union[List[InstanceConfig], Dict[str, List[InstanceConfig]]],
):
"""Override the instance configuration of the estimators used by the tuner.
Args:
instance_configs (List[InstanceConfig] or Dict[str, List[InstanceConfig]):
The InstanceConfigs to use as an override for the instance configuration
of the estimator. ``None`` will remove the override.
"""
if isinstance(instance_configs, dict):
self._validate_dict_argument(
name="instance_configs",
value=instance_configs,
allowed_keys=list(self.estimator_dict.keys()),
)
self.instance_configs_dict = instance_configs
else:
self.instance_configs = instance_configs
if self.estimator_dict is not None and self.estimator_dict.keys():
estimator_names = list(self.estimator_dict.keys())
self.instance_configs_dict = {estimator_names[0]: instance_configs}
def _prepare_for_tuning(self, job_name=None, include_cls_metadata=False):
"""Prepare the tuner instance for tuning (fit)."""
self._prepare_job_name_for_tuning(job_name=job_name)
self._prepare_static_hyperparameters_for_tuning(include_cls_metadata=include_cls_metadata)
self._prepare_auto_parameters_for_tuning()
self._prepare_tags_for_tuning()
def _get_model_uri(
self,
estimator,
):
"""Return the model artifact URI used by the Estimator instance.
This attribute can live in multiple places, and accessing the attribute can
raise a TypeError, which needs to be handled.
"""
try:
return getattr(estimator, "model_data", None)
except TypeError:
return getattr(estimator, "model_uri", None)
def _prepare_tags_for_tuning(self):
"""Add tags to tuning job (from Estimator and JumpStart tags)."""
# Add tags from Estimator class
estimator = self.estimator or self.estimator_dict[sorted(self.estimator_dict.keys())[0]]
estimator_tags = getattr(estimator, "tags", []) or []
if self.tags is None and len(estimator_tags) > 0:
self.tags = []
for tag in estimator_tags:
if tag not in self.tags:
self.tags.append(tag)
if self.sagemaker_session.settings.include_jumpstart_tags:
self.tags = add_jumpstart_uri_tags(
tags=self.tags,
training_script_uri=getattr(estimator, "source_dir", None),
training_model_uri=self._get_model_uri(estimator),
)
def _prepare_job_name_for_tuning(self, job_name=None):
"""Set current job name before starting tuning."""
if job_name is not None:
self._current_job_name = job_name
else:
base_name = self.base_tuning_job_name
if base_name is None:
estimator = (
self.estimator or self.estimator_dict[sorted(self.estimator_dict.keys())[0]]
)
base_name = base_name_from_image(
estimator.training_image_uri(),
default_base_name=EstimatorBase.JOB_CLASS_NAME,
)
jumpstart_base_name = get_jumpstart_base_name_if_jumpstart_model(
getattr(estimator, "source_dir", None),
self._get_model_uri(estimator),
)
base_name = jumpstart_base_name or base_name
self._current_job_name = name_from_base(
base_name, max_length=self.TUNING_JOB_NAME_MAX_LENGTH, short=True
)
def _prepare_static_hyperparameters_for_tuning(self, include_cls_metadata=False):
"""Prepare static hyperparameters for all estimators before tuning."""
self.static_hyperparameters = None
if self.estimator is not None:
self.static_hyperparameters = self._prepare_static_hyperparameters(
self.estimator, self._hyperparameter_ranges, include_cls_metadata
)
self.static_hyperparameters_dict = None
if self.estimator_dict is not None:
self.static_hyperparameters_dict = {
estimator_name: self._prepare_static_hyperparameters(
estimator,
self._hyperparameter_ranges_dict[estimator_name],
(
include_cls_metadata.get(estimator_name, False)
if isinstance(include_cls_metadata, dict)
else include_cls_metadata
),
)
for (estimator_name, estimator) in self.estimator_dict.items()
}
def _prepare_auto_parameters_for_tuning(self):
"""Prepare auto parameters for all estimators before tuning."""
self.auto_parameters = None
if self.estimator is not None:
self.static_hyperparameters, self.auto_parameters = self._prepare_auto_parameters(
self.static_hyperparameters, self.hyperparameters_to_keep_static
)
self.auto_parameters_dict = None
if self.estimator_dict is not None:
static_auto_parameters_dict = {
estimator_name: self._prepare_auto_parameters(
self.static_hyperparameters_dict[estimator_name],
(
self.hyperparameters_to_keep_static_dict.get(estimator_name, None)
if self.hyperparameters_to_keep_static_dict
else None
),
)
for estimator_name in sorted(self.estimator_dict.keys())
}
self.static_hyperparameters_dict = {}
self.auto_parameters_dict = {}
for estimator_name, (
static_hyperparameters,
auto_parameters,
) in static_auto_parameters_dict.items():
self.static_hyperparameters_dict[estimator_name] = static_hyperparameters
self.auto_parameters_dict[estimator_name] = auto_parameters
@classmethod
def _prepare_static_hyperparameters(
cls, estimator, hyperparameter_ranges, include_cls_metadata
):
"""Prepare static hyperparameters for one estimator before tuning."""
# Remove any hyperparameter that will be tuned
static_hyperparameters = {
str(k): to_string(v) for (k, v) in estimator.hyperparameters().items()
}
if hyperparameter_ranges is not None:
for hyperparameter_name in hyperparameter_ranges.keys():
static_hyperparameters.pop(hyperparameter_name, None)
# For attach() to know what estimator to use for frameworks
# (other algorithms may not accept extra hyperparameters)
if include_cls_metadata or isinstance(estimator, Framework):
static_hyperparameters[cls.SAGEMAKER_ESTIMATOR_CLASS_NAME] = json.dumps(
estimator.__class__.__name__
)
static_hyperparameters[cls.SAGEMAKER_ESTIMATOR_MODULE] = json.dumps(
estimator.__module__
)
return static_hyperparameters
def _prepare_auto_parameters(self, static_hyperparameters, hyperparameters_to_keep_static):
"""Prepare auto parameters for one estimator before tuning."""
if not self.autotune:
return static_hyperparameters, None
if hyperparameters_to_keep_static is None:
hyperparameters_to_keep_static = {}
if not set(hyperparameters_to_keep_static).issubset(set(static_hyperparameters.keys())):
raise ValueError(
"Names in hyperparameters_to_keep_static must be members of estimator's "
"hyperparameters."
)
new_static_hyperparameters = {
k: v for k, v in static_hyperparameters.items() if k in hyperparameters_to_keep_static
}
auto_parameters = {
k: v
for k, v in static_hyperparameters.items()
if k not in hyperparameters_to_keep_static
}
return new_static_hyperparameters, auto_parameters
@runnable_by_pipeline
def fit(
self,
inputs: Optional[
Union[
str,
Dict,
List,
TrainingInput,
FileSystemInput,
RecordSet,
FileSystemRecordSet,
]
] = None,
job_name: Optional[str] = None,
include_cls_metadata: Union[bool, Dict[str, bool]] = False,
estimator_kwargs: Optional[Dict[str, dict]] = None,
wait: bool = True,
**kwargs,
):
"""Start a hyperparameter tuning job.
Args:
inputs: Information about the training data. Please refer to the
``fit()`` method of the associated estimator, as this can take
any of the following forms:
* (str) - The S3 location where training data is saved.
* (dict[str, str] or dict[str, sagemaker.inputs.TrainingInput]) -
If using multiple channels for training data, you can specify
a dict mapping channel names to strings or
:func:`~sagemaker.inputs.TrainingInput` objects.
* (sagemaker.inputs.TrainingInput) - Channel configuration for S3 data sources
that can provide additional information about the training dataset.
See :func:`sagemaker.inputs.TrainingInput` for full details.
* (sagemaker.session.FileSystemInput) - channel configuration for
a file system data source that can provide additional information as well as
the path to the training dataset.
* (sagemaker.amazon.amazon_estimator.RecordSet) - A collection of
Amazon :class:~`Record` objects serialized and stored in S3.
For use with an estimator for an Amazon algorithm.
* (sagemaker.amazon.amazon_estimator.FileSystemRecordSet) -
Amazon SageMaker channel configuration for a file system data source for
Amazon algorithms.
* (list[sagemaker.amazon.amazon_estimator.RecordSet]) - A list of
:class:~`sagemaker.amazon.amazon_estimator.RecordSet` objects,