forked from aws/sagemaker-python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathestimator.py
2059 lines (1818 loc) · 93.9 KB
/
estimator.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 2017-2020 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 print_function, absolute_import
import json
import logging
import os
import uuid
import warnings
from abc import ABCMeta
from abc import abstractmethod
from six import with_metaclass
from six import string_types
from six.moves.urllib.parse import urlparse
import sagemaker
from sagemaker import git_utils
from sagemaker.analytics import TrainingJobAnalytics
from sagemaker.debugger import DebuggerHookConfig
from sagemaker.debugger import TensorBoardOutputConfig # noqa: F401 # pylint: disable=unused-import
from sagemaker.debugger import get_rule_container_image_uri
from sagemaker.s3 import S3Uploader
from sagemaker.fw_utils import (
create_image_uri,
tar_and_upload_dir,
parse_s3_url,
UploadedCode,
validate_source_dir,
_region_supports_debugger,
)
from sagemaker.job import _Job
from sagemaker.local import LocalSession
from sagemaker.model import Model, NEO_ALLOWED_FRAMEWORKS
from sagemaker.model import (
SCRIPT_PARAM_NAME,
DIR_PARAM_NAME,
CLOUDWATCH_METRICS_PARAM_NAME,
CONTAINER_LOG_LEVEL_PARAM_NAME,
JOB_NAME_PARAM_NAME,
SAGEMAKER_REGION_PARAM_NAME,
)
from sagemaker.predictor import Predictor
from sagemaker.session import Session
from sagemaker.session import s3_input
from sagemaker.transformer import Transformer
from sagemaker.utils import base_from_name, base_name_from_image, name_from_base, get_config_value
from sagemaker import vpc_utils
class EstimatorBase(with_metaclass(ABCMeta, object)):
"""Handle end-to-end Amazon SageMaker training and deployment tasks.
For introduction to model training and deployment, see
http://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-training.html
Subclasses must define a way to determine what image to use for training,
what hyperparameters to use, and how to create an appropriate predictor
instance.
"""
def __init__(
self,
role,
train_instance_count,
train_instance_type,
train_volume_size=30,
train_volume_kms_key=None,
train_max_run=24 * 60 * 60,
input_mode="File",
output_path=None,
output_kms_key=None,
base_job_name=None,
sagemaker_session=None,
tags=None,
subnets=None,
security_group_ids=None,
model_uri=None,
model_channel_name="model",
metric_definitions=None,
encrypt_inter_container_traffic=False,
train_use_spot_instances=False,
train_max_wait=None,
checkpoint_s3_uri=None,
checkpoint_local_path=None,
rules=None,
debugger_hook_config=None,
tensorboard_output_config=None,
enable_sagemaker_metrics=None,
enable_network_isolation=False,
):
"""Initialize an ``EstimatorBase`` instance.
Args:
role (str): An AWS IAM role (either name or full ARN). The Amazon
SageMaker training jobs and APIs that create Amazon SageMaker
endpoints use this role to access training data and model
artifacts. After the endpoint is created, the inference code
might use the IAM role, if it needs to access an AWS resource.
train_instance_count (int): Number of Amazon EC2 instances to use
for training.
train_instance_type (str): Type of EC2 instance to use for training,
for example, 'ml.c4.xlarge'.
train_volume_size (int): Size in GB of the EBS volume to use for
storing input data during training (default: 30). Must be large
enough to store training data if File Mode is used (which is the
default).
train_volume_kms_key (str): Optional. KMS key ID for encrypting EBS
volume attached to the training instance (default: None).
train_max_run (int): Timeout in seconds for training (default: 24 *
60 * 60). After this amount of time Amazon SageMaker terminates
the job regardless of its current status.
input_mode (str): The input mode that the algorithm supports
(default: 'File'). Valid modes: 'File' - Amazon SageMaker copies
the training dataset from the S3 location to a local directory.
'Pipe' - Amazon SageMaker streams data directly from S3 to the
container via a Unix-named pipe. This argument can be overriden
on a per-channel basis using
``sagemaker.session.s3_input.input_mode``.
output_path (str): S3 location for saving the training result (model
artifacts and output files). If not specified, results are
stored to a default bucket. If the bucket with the specific name
does not exist, the estimator creates the bucket during the
:meth:`~sagemaker.estimator.EstimatorBase.fit` method execution.
file:// urls are used for local mode. For example: 'file://model/'
will save to the model folder in the current directory.
output_kms_key (str): Optional. KMS key ID for encrypting the
training output (default: None).
base_job_name (str): Prefix for training job name when the
:meth:`~sagemaker.estimator.EstimatorBase.fit` method launches.
If not specified, the estimator generates a default job name
based on the training image name and current timestamp.
sagemaker_session (sagemaker.session.Session): Session object which
manages interactions with Amazon SageMaker APIs and any other
AWS services needed. If not specified, the estimator creates one
using the default AWS configuration chain.
tags (list[dict]): List of tags for labeling a training job. For
more, see
https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.
subnets (list[str]): List of subnet ids. If not specified training
job will be created without VPC config.
security_group_ids (list[str]): List of security group ids. If not
specified training job will be created without VPC config.
model_uri (str): URI where a pre-trained model is stored, either
locally or in S3 (default: None). If specified, the estimator
will create a channel pointing to the model so the training job
can download it. This model can be a 'model.tar.gz' from a
previous training job, or other artifacts coming from a
different source.
In local mode, this should point to the path in which the model
is located and not the file itself, as local Docker containers
will try to mount the URI as a volume.
More information:
https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-training.html#td-deserialization
model_channel_name (str): Name of the channel where 'model_uri' will
be downloaded (default: 'model').
metric_definitions (list[dict]): A list of dictionaries that defines
the metric(s) used to evaluate the training jobs. 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 jobs that
don't use an Amazon algorithm.
encrypt_inter_container_traffic (bool): Specifies whether traffic
between training containers is encrypted for the training job
(default: ``False``).
train_use_spot_instances (bool): Specifies whether to use SageMaker
Managed Spot instances for training. If enabled then the
`train_max_wait` arg should also be set.
More information:
https://docs.aws.amazon.com/sagemaker/latest/dg/model-managed-spot-training.html
(default: ``False``).
train_max_wait (int): Timeout in seconds waiting for spot training
instances (default: None). After this amount of time Amazon
SageMaker will stop waiting for Spot instances to become
available (default: ``None``).
checkpoint_s3_uri (str): The S3 URI in which to persist checkpoints
that the algorithm persists (if any) during training. (default:
``None``).
checkpoint_local_path (str): The local path that the algorithm
writes its checkpoints to. SageMaker will persist all files
under this path to `checkpoint_s3_uri` continually during
training. On job startup the reverse happens - data from the
s3 location is downloaded to this path before the algorithm is
started. If the path is unset then SageMaker assumes the
checkpoints will be provided under `/opt/ml/checkpoints/`.
(default: ``None``).
rules (list[:class:`~sagemaker.debugger.Rule`]): A list of
:class:`~sagemaker.debugger.Rule` objects used to define
rules for continuous analysis with SageMaker Debugger
(default: ``None``). For more, see
https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_debugger.html#continuous-analyses-through-rules
debugger_hook_config (:class:`~sagemaker.debugger.DebuggerHookConfig` or bool):
Configuration for how debugging information is emitted with
SageMaker Debugger. If not specified, a default one is created using
the estimator's ``output_path``, unless the region does not
support SageMaker Debugger. To disable SageMaker Debugger,
set this parameter to ``False``. For more, see
https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_debugger.html
tensorboard_output_config (:class:`~sagemaker.debugger.TensorBoardOutputConfig`):
Configuration for customizing debugging visualization using TensorBoard
(default: ``None``). For more, see
https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_debugger.html#capture-real-time-tensorboard-data-from-the-debugging-hook
enable_sagemaker_metrics (bool): Enables SageMaker Metrics Time
Series. For more information see:
https://docs.aws.amazon.com/sagemaker/latest/dg/API_AlgorithmSpecification.html#SageMaker-Type-AlgorithmSpecification-EnableSageMakerMetricsTimeSeries
(default: ``None``).
enable_network_isolation (bool): Specifies whether container will
run in network isolation mode (default: ``False``). Network
isolation mode restricts the container access to outside networks
(such as the Internet). The container does not make any inbound or
outbound network calls. Also known as Internet-free mode.
"""
self.role = role
self.train_instance_count = train_instance_count
self.train_instance_type = train_instance_type
self.train_volume_size = train_volume_size
self.train_volume_kms_key = train_volume_kms_key
self.train_max_run = train_max_run
self.input_mode = input_mode
self.tags = tags
self.metric_definitions = metric_definitions
self.model_uri = model_uri
self.model_channel_name = model_channel_name
self.code_uri = None
self.code_channel_name = "code"
if self.train_instance_type in ("local", "local_gpu"):
if self.train_instance_type == "local_gpu" and self.train_instance_count > 1:
raise RuntimeError("Distributed Training in Local GPU is not supported")
self.sagemaker_session = sagemaker_session or LocalSession()
if not isinstance(self.sagemaker_session, sagemaker.local.LocalSession):
raise RuntimeError(
"instance_type local or local_gpu is only supported with an"
"instance of LocalSession"
)
else:
self.sagemaker_session = sagemaker_session or Session()
self.base_job_name = base_job_name
self._current_job_name = None
if (
not self.sagemaker_session.local_mode
and output_path
and output_path.startswith("file://")
):
raise RuntimeError("file:// output paths are only supported in Local Mode")
self.output_path = output_path
self.output_kms_key = output_kms_key
self.latest_training_job = None
self.jobs = []
self.deploy_instance_type = None
self._compiled_models = {}
# VPC configurations
self.subnets = subnets
self.security_group_ids = security_group_ids
self.encrypt_inter_container_traffic = encrypt_inter_container_traffic
self.train_use_spot_instances = train_use_spot_instances
self.train_max_wait = train_max_wait
self.checkpoint_s3_uri = checkpoint_s3_uri
self.checkpoint_local_path = checkpoint_local_path
self.rules = rules
self.debugger_hook_config = debugger_hook_config
self.tensorboard_output_config = tensorboard_output_config
self.debugger_rule_configs = None
self.collection_configs = None
self.enable_sagemaker_metrics = enable_sagemaker_metrics
self._enable_network_isolation = enable_network_isolation
@abstractmethod
def train_image(self):
"""Return the Docker image to use for training.
The :meth:`~sagemaker.estimator.EstimatorBase.fit` method, which does
the model training, calls this method to find the image to use for model
training.
Returns:
str: The URI of the Docker image.
"""
@abstractmethod
def hyperparameters(self):
"""Return the hyperparameters as a dictionary to use for training.
The :meth:`~sagemaker.estimator.EstimatorBase.fit` method, which
trains the model, calls this method to find the hyperparameters.
Returns:
dict[str, str]: The hyperparameters.
"""
def enable_network_isolation(self):
"""Return True if this Estimator will need network isolation to run.
Returns:
bool: Whether this Estimator needs network isolation or not.
"""
return self._enable_network_isolation
def prepare_workflow_for_training(self, job_name=None):
"""Calls _prepare_for_training. Used when setting up a workflow.
Args:
job_name (str): Name of the training job to be created. If not
specified, one is generated, using the base name given to the
constructor if applicable.
"""
self._prepare_for_training(job_name=job_name)
def _ensure_base_job_name(self):
"""Set ``self.base_job_name`` if it is not set already."""
# honor supplied base_job_name or generate it
if self.base_job_name is None:
self.base_job_name = base_name_from_image(self.train_image())
def _get_or_create_name(self, name=None):
"""Generate a name based on the base job name or training image if needed.
Args:
name (str): User-supplied name. If not specified, a name is generated from
the base job name or training image.
Returns:
str: Either the user-supplied name or a generated name.
"""
if name:
return name
self._ensure_base_job_name()
return name_from_base(self.base_job_name)
def _prepare_for_training(self, job_name=None):
"""Set any values in the estimator that need to be set before training.
Args:
job_name (str): Name of the training job to be created. If not
specified, one is generated, using the base name given to the
constructor if applicable.
"""
self._current_job_name = self._get_or_create_name(job_name)
# if output_path was specified we use it otherwise initialize here.
# For Local Mode with local_code=True we don't need an explicit output_path
if self.output_path is None:
local_code = get_config_value("local.local_code", self.sagemaker_session.config)
if self.sagemaker_session.local_mode and local_code:
self.output_path = ""
else:
self.output_path = "s3://{}/".format(self.sagemaker_session.default_bucket())
# Prepare rules and debugger configs for training.
if self.rules and self.debugger_hook_config is None:
self.debugger_hook_config = DebuggerHookConfig(s3_output_path=self.output_path)
# If an object was provided without an S3 URI is not provided, default it for the customer.
if self.debugger_hook_config and not self.debugger_hook_config.s3_output_path:
self.debugger_hook_config.s3_output_path = self.output_path
self._prepare_rules()
self._prepare_collection_configs()
def _prepare_rules(self):
"""Set any necessary values in debugger rules, if they are provided."""
self.debugger_rule_configs = []
if self.rules is not None:
# Iterate through each of the provided rules.
for rule in self.rules:
# Set the image URI using the default rule evaluator image and the region.
if rule.image_uri == "DEFAULT_RULE_EVALUATOR_IMAGE":
rule.image_uri = get_rule_container_image_uri(
self.sagemaker_session.boto_region_name
)
rule.instance_type = None
rule.volume_size_in_gb = None
# If source was provided as a rule parameter, upload to S3 and save the S3 uri.
if "source_s3_uri" in (rule.rule_parameters or {}):
parse_result = urlparse(rule.rule_parameters["source_s3_uri"])
if parse_result.scheme != "s3":
desired_s3_uri = os.path.join(
"s3://",
self.sagemaker_session.default_bucket(),
rule.name,
str(uuid.uuid4()),
)
s3_uri = S3Uploader.upload(
local_path=rule.rule_parameters["source_s3_uri"],
desired_s3_uri=desired_s3_uri,
sagemaker_session=self.sagemaker_session,
)
rule.rule_parameters["source_s3_uri"] = s3_uri
# Save the request dictionary for the rule.
self.debugger_rule_configs.append(rule.to_debugger_rule_config_dict())
def _prepare_collection_configs(self):
"""De-duplicate any collection configurations and save them
in the debugger hook configuration.
"""
# Create a set to de-duplicate CollectionConfigs.
self.collection_configs = set()
# Iterate through the rules and add their respective CollectionConfigs to the set.
if self.rules is not None:
for rule in self.rules:
self.collection_configs.update(rule.collection_configs)
# Add the CollectionConfigs from DebuggerHookConfig to the set.
if self.debugger_hook_config:
self.collection_configs.update(self.debugger_hook_config.collection_configs or [])
def latest_job_debugger_artifacts_path(self):
"""Gets the path to the DebuggerHookConfig output artifacts.
Returns:
str: An S3 path to the output artifacts.
"""
self._ensure_latest_training_job(
error_message="""Cannot get the Debugger artifacts path.
The Estimator is not associated with a training job."""
)
if self.debugger_hook_config is not None:
return os.path.join(
self.debugger_hook_config.s3_output_path,
self.latest_training_job.name,
"debug-output",
)
return None
def latest_job_tensorboard_artifacts_path(self):
"""Gets the path to the TensorBoardOutputConfig output artifacts.
Returns:
str: An S3 path to the output artifacts.
"""
self._ensure_latest_training_job(
error_message="""Cannot get the TensorBoard artifacts path.
The Estimator is not associated with a training job."""
)
if self.debugger_hook_config is not None:
return os.path.join(
self.tensorboard_output_config.s3_output_path,
self.latest_training_job.name,
"tensorboard-output",
)
return None
def fit(self, inputs=None, wait=True, logs="All", job_name=None, experiment_config=None):
"""Train a model using the input training dataset.
The API calls the Amazon SageMaker CreateTrainingJob API to start
model training. The API uses configuration you provided to create the
estimator and the specified input training data to send the
CreatingTrainingJob request to Amazon SageMaker.
This is a synchronous operation. After the model training
successfully completes, you can call the ``deploy()`` method to host the
model using the Amazon SageMaker hosting services.
Args:
inputs (str or dict or sagemaker.session.s3_input): Information
about the training data. This can be one of three types:
* (str) the S3 location where training data is saved, or a file:// path in
local mode.
* (dict[str, str] or dict[str, sagemaker.session.s3_input]) If using multiple
channels for training data, you can specify a dict mapping channel names to
strings or :func:`~sagemaker.session.s3_input` objects.
* (sagemaker.session.s3_input) - channel configuration for S3 data sources that can
provide additional information as well as the path to the training dataset.
See :func:`sagemaker.session.s3_input` 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.
wait (bool): Whether the call should wait until the job completes (default: True).
logs ([str]): A list of strings specifying which logs to print. Acceptable
strings are "All", "None", "Training", or "Rules". To maintain backwards
compatibility, boolean values are also accepted and converted to strings.
Only meaningful when wait is True.
job_name (str): Training job name. If not specified, the estimator generates
a default job name based on the training image name and current timestamp.
experiment_config (dict[str, str]): Experiment management configuration.
Dictionary contains three optional keys,
'ExperimentName', 'TrialName', and 'TrialComponentDisplayName'.
"""
self._prepare_for_training(job_name=job_name)
self.latest_training_job = _TrainingJob.start_new(self, inputs, experiment_config)
self.jobs.append(self.latest_training_job)
if wait:
self.latest_training_job.wait(logs=logs)
def _compilation_job_name(self):
"""Placeholder docstring"""
base_name = self.base_job_name or base_name_from_image(self.train_image())
return name_from_base("compilation-" + base_name)
def compile_model(
self,
target_instance_family,
input_shape,
output_path,
framework=None,
framework_version=None,
compile_max_run=15 * 60,
tags=None,
**kwargs
):
"""Compile a Neo model using the input model.
Args:
target_instance_family (str): Identifies the device that you want to
run your model after compilation, for example: ml_c5. For allowed
strings see
https://docs.aws.amazon.com/sagemaker/latest/dg/API_OutputConfig.html.
input_shape (dict): Specifies the name and shape of the expected
inputs for your trained model in json dictionary form, for
example: {'data':[1,3,1024,1024]}, or {'var1': [1,1,28,28],
'var2':[1,1,28,28]}
output_path (str): Specifies where to store the compiled model
framework (str): The framework that is used to train the original
model. Allowed values: 'mxnet', 'tensorflow', 'keras', 'pytorch',
'onnx', 'xgboost'
framework_version (str): The version of the framework
compile_max_run (int): Timeout in seconds for compilation (default:
3 * 60). After this amount of time Amazon SageMaker Neo
terminates the compilation job regardless of its current status.
tags (list[dict]): List of tags for labeling a compilation job. For
more, see
https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.
**kwargs: Passed to invocation of ``create_model()``.
Implementations may customize ``create_model()`` to accept
``**kwargs`` to customize model creation during deploy. For
more, see the implementation docs.
Returns:
sagemaker.model.Model: A SageMaker ``Model`` object. See
:func:`~sagemaker.model.Model` for full details.
"""
if framework and framework not in NEO_ALLOWED_FRAMEWORKS:
raise ValueError(
"Please use valid framework, allowed values: {}".format(NEO_ALLOWED_FRAMEWORKS)
)
if (framework is None) != (framework_version is None):
raise ValueError("You should provide framework and framework_version at the same time.")
model = self.create_model(**kwargs)
self._compiled_models[target_instance_family] = model.compile(
target_instance_family,
input_shape,
output_path,
self.role,
tags,
self._compilation_job_name(),
compile_max_run,
framework=framework,
framework_version=framework_version,
)
return self._compiled_models[target_instance_family]
@classmethod
def attach(cls, training_job_name, sagemaker_session=None, model_channel_name="model"):
"""Attach to an existing training job.
Create an Estimator bound to an existing training job, each subclass
is responsible to implement
``_prepare_init_params_from_job_description()`` as this method delegates
the actual conversion of a training job description to the arguments
that the class constructor expects. After attaching, if the training job
has a Complete status, it can be ``deploy()`` ed to create a SageMaker
Endpoint and return a ``Predictor``.
If the training job is in progress, attach will block and display log
messages from the training job, until the training job completes.
Examples:
>>> my_estimator.fit(wait=False)
>>> training_job_name = my_estimator.latest_training_job.name
Later on:
>>> attached_estimator = Estimator.attach(training_job_name)
>>> attached_estimator.deploy()
Args:
training_job_name (str): The name of the training job to attach to.
sagemaker_session (sagemaker.session.Session): Session object which
manages interactions with Amazon SageMaker APIs and any other
AWS services needed. If not specified, the estimator creates one
using the default AWS configuration chain.
model_channel_name (str): Name of the channel where pre-trained
model data will be downloaded (default: 'model'). If no channel
with the same name exists in the training job, this option will
be ignored.
Returns:
Instance of the calling ``Estimator`` Class with the attached
training job.
"""
sagemaker_session = sagemaker_session or Session()
job_details = sagemaker_session.sagemaker_client.describe_training_job(
TrainingJobName=training_job_name
)
init_params = cls._prepare_init_params_from_job_description(job_details, model_channel_name)
tags = sagemaker_session.sagemaker_client.list_tags(
ResourceArn=job_details["TrainingJobArn"]
)["Tags"]
init_params.update(tags=tags)
estimator = cls(sagemaker_session=sagemaker_session, **init_params)
estimator.latest_training_job = _TrainingJob(
sagemaker_session=sagemaker_session, job_name=training_job_name
)
estimator._current_job_name = estimator.latest_training_job.name
estimator.latest_training_job.wait()
return estimator
def deploy(
self,
initial_instance_count,
instance_type,
accelerator_type=None,
endpoint_name=None,
use_compiled_model=False,
wait=True,
model_name=None,
kms_key=None,
data_capture_config=None,
tags=None,
**kwargs
):
"""Deploy the trained model to an Amazon SageMaker endpoint and return a
``sagemaker.Predictor`` object.
More information:
http://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-training.html
Args:
initial_instance_count (int): Minimum number of EC2 instances to
deploy to an endpoint for prediction.
instance_type (str): Type of EC2 instance to deploy to an endpoint
for prediction, for example, 'ml.c4.xlarge'.
accelerator_type (str): Type of Elastic Inference accelerator to
attach to an endpoint for model loading and inference, for
example, 'ml.eia1.medium'. If not specified, no Elastic
Inference accelerator will be attached to the endpoint. For more
information:
https://docs.aws.amazon.com/sagemaker/latest/dg/ei.html
endpoint_name (str): Name to use for creating an Amazon SageMaker
endpoint. If not specified, the name of the training job is
used.
use_compiled_model (bool): Flag to select whether to use compiled
(optimized) model. Default: False.
wait (bool): Whether the call should wait until the deployment of
model completes (default: True).
model_name (str): Name to use for creating an Amazon SageMaker
model. If not specified, the estimator generates a default job name
based on the training image name and current timestamp.
kms_key (str): The ARN of the KMS key that is used to encrypt the
data on the storage volume attached to the instance hosting the
endpoint.
data_capture_config (sagemaker.model_monitor.DataCaptureConfig): Specifies
configuration related to Endpoint data capture for use with
Amazon SageMaker Model Monitoring. Default: None.
tags(List[dict[str, str]]): Optional. The list of tags to attach to this specific
endpoint. Example:
>>> tags = [{'Key': 'tagname', 'Value': 'tagvalue'}]
For more information about tags, see
https://boto3.amazonaws.com/v1/documentation\
/api/latest/reference/services/sagemaker.html#SageMaker.Client.add_tags
**kwargs: Passed to invocation of ``create_model()``.
Implementations may customize ``create_model()`` to accept
``**kwargs`` to customize model creation during deploy.
For more, see the implementation docs.
Returns:
sagemaker.predictor.Predictor: A predictor that provides a ``predict()`` method,
which can be used to send requests to the Amazon SageMaker
endpoint and obtain inferences.
"""
self._ensure_latest_training_job()
self._ensure_base_job_name()
default_name = name_from_base(self.base_job_name)
endpoint_name = endpoint_name or default_name
model_name = model_name or default_name
self.deploy_instance_type = instance_type
if use_compiled_model:
family = "_".join(instance_type.split(".")[:-1])
if family not in self._compiled_models:
raise ValueError(
"No compiled model for {}. "
"Please compile one with compile_model before deploying.".format(family)
)
model = self._compiled_models[family]
else:
kwargs["model_kms_key"] = self.output_kms_key
model = self.create_model(**kwargs)
model.name = model_name
return model.deploy(
instance_type=instance_type,
initial_instance_count=initial_instance_count,
accelerator_type=accelerator_type,
endpoint_name=endpoint_name,
tags=tags or self.tags,
wait=wait,
kms_key=kms_key,
data_capture_config=data_capture_config,
)
@property
def model_data(self):
"""str: The model location in S3. Only set if Estimator has been
``fit()``.
"""
if self.latest_training_job is not None:
model_uri = self.sagemaker_session.sagemaker_client.describe_training_job(
TrainingJobName=self.latest_training_job.name
)["ModelArtifacts"]["S3ModelArtifacts"]
else:
logging.warning(
"No finished training job found associated with this estimator. Please make sure "
"this estimator is only used for building workflow config"
)
model_uri = os.path.join(
self.output_path, self._current_job_name, "output", "model.tar.gz"
)
return model_uri
@abstractmethod
def create_model(self, **kwargs):
"""Create a SageMaker ``Model`` object that can be deployed to an
``Endpoint``.
Args:
**kwargs: Keyword arguments used by the implemented method for
creating the ``Model``.
Returns:
sagemaker.model.Model: A SageMaker ``Model`` object. See
:func:`~sagemaker.model.Model` for full details.
"""
@classmethod
def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None):
"""Convert the job description to init params that can be handled by the
class constructor
Args:
job_details: the returned job details from a describe_training_job
API call.
model_channel_name (str): Name of the channel where pre-trained
model data will be downloaded.
Returns:
dictionary: The transformed init_params
"""
init_params = dict()
init_params["role"] = job_details["RoleArn"]
init_params["train_instance_count"] = job_details["ResourceConfig"]["InstanceCount"]
init_params["train_instance_type"] = job_details["ResourceConfig"]["InstanceType"]
init_params["train_volume_size"] = job_details["ResourceConfig"]["VolumeSizeInGB"]
init_params["train_max_run"] = job_details["StoppingCondition"]["MaxRuntimeInSeconds"]
init_params["input_mode"] = job_details["AlgorithmSpecification"]["TrainingInputMode"]
init_params["base_job_name"] = base_from_name(job_details["TrainingJobName"])
init_params["output_path"] = job_details["OutputDataConfig"]["S3OutputPath"]
init_params["output_kms_key"] = job_details["OutputDataConfig"]["KmsKeyId"]
if "EnableNetworkIsolation" in job_details:
init_params["enable_network_isolation"] = job_details["EnableNetworkIsolation"]
has_hps = "HyperParameters" in job_details
init_params["hyperparameters"] = job_details["HyperParameters"] if has_hps else {}
if "AlgorithmName" in job_details["AlgorithmSpecification"]:
init_params["algorithm_arn"] = job_details["AlgorithmSpecification"]["AlgorithmName"]
elif "TrainingImage" in job_details["AlgorithmSpecification"]:
init_params["image_uri"] = job_details["AlgorithmSpecification"]["TrainingImage"]
else:
raise RuntimeError(
"Invalid AlgorithmSpecification. Either TrainingImage or "
"AlgorithmName is expected. None was found."
)
if "MetricDefinitons" in job_details["AlgorithmSpecification"]:
init_params["metric_definitions"] = job_details["AlgorithmSpecification"][
"MetricsDefinition"
]
if "EnableInterContainerTrafficEncryption" in job_details:
init_params["encrypt_inter_container_traffic"] = job_details[
"EnableInterContainerTrafficEncryption"
]
subnets, security_group_ids = vpc_utils.from_dict(job_details.get(vpc_utils.VPC_CONFIG_KEY))
if subnets:
init_params["subnets"] = subnets
if security_group_ids:
init_params["security_group_ids"] = security_group_ids
if "InputDataConfig" in job_details and model_channel_name:
for channel in job_details["InputDataConfig"]:
if channel["ChannelName"] == model_channel_name:
init_params["model_channel_name"] = model_channel_name
init_params["model_uri"] = channel["DataSource"]["S3DataSource"]["S3Uri"]
break
return init_params
def transformer(
self,
instance_count,
instance_type,
strategy=None,
assemble_with=None,
output_path=None,
output_kms_key=None,
accept=None,
env=None,
max_concurrent_transforms=None,
max_payload=None,
tags=None,
role=None,
volume_kms_key=None,
vpc_config_override=vpc_utils.VPC_CONFIG_DEFAULT,
enable_network_isolation=None,
model_name=None,
):
"""Return a ``Transformer`` that uses a SageMaker Model based on the
training job. It reuses the SageMaker Session and base job name used by
the Estimator.
Args:
instance_count (int): Number of EC2 instances to use.
instance_type (str): Type of EC2 instance to use, for example,
'ml.c4.xlarge'.
strategy (str): The strategy used to decide how to batch records in
a single request (default: None). Valid values: 'MultiRecord'
and 'SingleRecord'.
assemble_with (str): How the output is assembled (default: None).
Valid values: 'Line' or 'None'.
output_path (str): S3 location for saving the transform result. If
not specified, results are stored to a default bucket.
output_kms_key (str): Optional. KMS key ID for encrypting the
transform output (default: None).
accept (str): The accept header passed by the client to
the inference endpoint. If it is supported by the endpoint,
it will be the format of the batch transform output.
env (dict): Environment variables to be set for use during the
transform job (default: None).
max_concurrent_transforms (int): The maximum number of HTTP requests
to be made to each individual transform container at one time.
max_payload (int): Maximum size of the payload in a single HTTP
request to the container in MB.
tags (list[dict]): List of tags for labeling a transform job. If
none specified, then the tags used for the training job are used
for the transform job.
role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``,
which is also used during transform jobs. If not specified, the
role from the Estimator will be used.
volume_kms_key (str): Optional. KMS key ID for encrypting the volume
attached to the ML compute instance (default: None).
vpc_config_override (dict[str, list[str]]): Optional override for the
VpcConfig set on the model.
Default: use subnets and security groups from this Estimator.
* 'Subnets' (list[str]): List of subnet ids.
* 'SecurityGroupIds' (list[str]): List of security group ids.
enable_network_isolation (bool): Specifies whether container will
run in network isolation mode. Network isolation mode restricts
the container access to outside networks (such as the internet).
The container does not make any inbound or outbound network
calls. If True, a channel named "code" will be created for any
user entry script for inference. Also known as Internet-free mode.
If not specified, this setting is taken from the estimator's
current configuration.
model_name (str): Name to use for creating an Amazon SageMaker
model. If not specified, the estimator generates a default job name
based on the training image name and current timestamp.
"""
tags = tags or self.tags
model_name = self._get_or_create_name(model_name)
if self.latest_training_job is None:
logging.warning(
"No finished training job found associated with this estimator. Please make sure "
"this estimator is only used for building workflow config"
)
else:
if enable_network_isolation is None:
enable_network_isolation = self.enable_network_isolation()
model = self.create_model(
vpc_config_override=vpc_config_override,
model_kms_key=self.output_kms_key,
enable_network_isolation=enable_network_isolation,
)
# not all create_model() implementations have the same kwargs
model.name = model_name
if role is not None:
model.role = role
model._create_sagemaker_model(instance_type, tags=tags)
return Transformer(
model_name,
instance_count,
instance_type,
strategy=strategy,
assemble_with=assemble_with,
output_path=output_path,
output_kms_key=output_kms_key,
accept=accept,
max_concurrent_transforms=max_concurrent_transforms,
max_payload=max_payload,
env=env,
tags=tags,
base_transform_job_name=self.base_job_name,
volume_kms_key=volume_kms_key,
sagemaker_session=self.sagemaker_session,
)
@property
def training_job_analytics(self):
"""Return a ``TrainingJobAnalytics`` object for the current training
job.
"""
if self._current_job_name is None:
raise ValueError("Estimator is not associated with a TrainingJob")
return TrainingJobAnalytics(
self._current_job_name, sagemaker_session=self.sagemaker_session
)
def get_vpc_config(self, vpc_config_override=vpc_utils.VPC_CONFIG_DEFAULT):
"""Returns VpcConfig dict either from this Estimator's subnets and
security groups, or else validate and return an optional override value.
Args:
vpc_config_override:
"""
if vpc_config_override is vpc_utils.VPC_CONFIG_DEFAULT:
return vpc_utils.to_dict(self.subnets, self.security_group_ids)
return vpc_utils.sanitize(vpc_config_override)
def _ensure_latest_training_job(
self, error_message="Estimator is not associated with a training job"
):
"""
Args:
error_message:
"""
if self.latest_training_job is None:
raise ValueError(error_message)
class _TrainingJob(_Job):
"""Placeholder docstring"""
@classmethod
def start_new(cls, estimator, inputs, experiment_config):
"""Create a new Amazon SageMaker training job from the estimator.
Args:
estimator (sagemaker.estimator.EstimatorBase): Estimator object
created by the user.
inputs (str): Parameters used when called
:meth:`~sagemaker.estimator.EstimatorBase.fit`.
experiment_config (dict[str, str]): Experiment management configuration used when called
:meth:`~sagemaker.estimator.EstimatorBase.fit`. Dictionary contains
three optional keys, 'ExperimentName', 'TrialName', and 'TrialComponentDisplayName'.
Returns:
sagemaker.estimator._TrainingJob: Constructed object that captures
all information about the started training job.
"""
local_mode = estimator.sagemaker_session.local_mode