-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathprocessing.py
2057 lines (1823 loc) · 94 KB
/
processing.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.
"""This module contains code related to the ``Processor`` class.
which is used for Amazon SageMaker Processing Jobs. These jobs let users perform
data pre-processing, post-processing, feature engineering, data validation, and model evaluation,
and interpretation on Amazon SageMaker.
"""
from __future__ import absolute_import
import logging
import os
import pathlib
import re
from copy import copy
from textwrap import dedent
from typing import Dict, List, Optional, Union
import attr
from six.moves.urllib.parse import urlparse
from six.moves.urllib.request import url2pathname
from sagemaker import s3
from sagemaker.apiutils._base_types import ApiObject
from sagemaker.config import (
PROCESSING_JOB_ENABLE_NETWORK_ISOLATION_PATH,
PROCESSING_JOB_ENVIRONMENT_PATH,
PROCESSING_JOB_INTER_CONTAINER_ENCRYPTION_PATH,
PROCESSING_JOB_KMS_KEY_ID_PATH,
PROCESSING_JOB_ROLE_ARN_PATH,
PROCESSING_JOB_SECURITY_GROUP_IDS_PATH,
PROCESSING_JOB_SUBNETS_PATH,
PROCESSING_JOB_VOLUME_KMS_KEY_ID_PATH,
)
from sagemaker.dataset_definition.inputs import DatasetDefinition, S3Input
from sagemaker.job import _Job
from sagemaker.local import LocalSession
from sagemaker.network import NetworkConfig
from sagemaker.s3 import S3Uploader
from sagemaker.session import Session
from sagemaker.utils import (
Tags,
base_name_from_image,
check_and_get_run_experiment_config,
format_tags,
get_config_value,
name_from_base,
resolve_class_attribute_from_config,
resolve_value_from_config,
)
from sagemaker.workflow import is_pipeline_variable
from sagemaker.workflow.entities import PipelineVariable
from sagemaker.workflow.execution_variables import ExecutionVariables
from sagemaker.workflow.functions import Join
from sagemaker.workflow.pipeline_context import runnable_by_pipeline
logger = logging.getLogger(__name__)
class Processor(object):
"""Handles Amazon SageMaker Processing tasks."""
JOB_CLASS_NAME = "processing-job"
def __init__(
self,
role: str = None,
image_uri: Union[str, PipelineVariable] = None,
instance_count: Union[int, PipelineVariable] = None,
instance_type: Union[str, PipelineVariable] = None,
entrypoint: Optional[List[Union[str, PipelineVariable]]] = None,
volume_size_in_gb: Union[int, PipelineVariable] = 30,
volume_kms_key: Optional[Union[str, PipelineVariable]] = None,
output_kms_key: Optional[Union[str, PipelineVariable]] = None,
max_runtime_in_seconds: Optional[Union[int, PipelineVariable]] = None,
base_job_name: Optional[str] = None,
sagemaker_session: Optional[Session] = None,
env: Optional[Dict[str, Union[str, PipelineVariable]]] = None,
tags: Optional[Tags] = None,
network_config: Optional[NetworkConfig] = None,
):
"""Initializes a ``Processor`` instance.
The ``Processor`` handles Amazon SageMaker Processing tasks.
Args:
role (str or PipelineVariable): An AWS IAM role name or ARN. Amazon SageMaker Processing
uses this role to access AWS resources, such as
data stored in Amazon S3.
image_uri (str or PipelineVariable): The URI of the Docker image to use for the
processing jobs.
instance_count (int or PipelineVariable): The number of instances to run
a processing job with.
instance_type (str or PipelineVariable): The type of EC2 instance to use for
processing, for example, 'ml.c4.xlarge'.
entrypoint (list[str] or list[PipelineVariable]): The entrypoint for the
processing job (default: None). This is in the form of a list of strings
that make a command.
volume_size_in_gb (int or PipelineVariable): Size in GB of the EBS volume
to use for storing data during processing (default: 30).
volume_kms_key (str or PipelineVariable): A KMS key for the processing
volume (default: None).
output_kms_key (str or PipelineVariable): The KMS key ID for processing job
outputs (default: None).
max_runtime_in_seconds (int or PipelineVariable): Timeout in seconds (default: None).
After this amount of time, Amazon SageMaker terminates the job,
regardless of its current status. If `max_runtime_in_seconds` is not
specified, the default value is 24 hours.
base_job_name (str): Prefix for processing job name. If not specified,
the processor generates a default job name, based on the
processing image name and current timestamp.
sagemaker_session (:class:`~sagemaker.session.Session`):
Session object which manages interactions with Amazon SageMaker and
any other AWS services needed. If not specified, the processor creates
one using the default AWS configuration chain.
env (dict[str, str] or dict[str, PipelineVariable]): Environment variables
to be passed to the processing jobs (default: None).
tags (Optional[Tags]): Tags to be passed to the processing job (default: None).
For more, see https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.
network_config (:class:`~sagemaker.network.NetworkConfig`):
A :class:`~sagemaker.network.NetworkConfig`
object that configures network isolation, encryption of
inter-container traffic, security group IDs, and subnets.
"""
self.image_uri = image_uri
self.instance_count = instance_count
self.instance_type = instance_type
self.entrypoint = entrypoint
self.volume_size_in_gb = volume_size_in_gb
self.max_runtime_in_seconds = max_runtime_in_seconds
self.base_job_name = base_job_name
self.tags = format_tags(tags)
self.jobs = []
self.latest_job = None
self._current_job_name = None
self.arguments = None
if self.instance_type in ("local", "local_gpu"):
if not isinstance(sagemaker_session, LocalSession):
# Until Local Mode Processing supports local code, we need to disable it:
sagemaker_session = LocalSession(disable_local_code=True)
self.sagemaker_session = sagemaker_session or Session()
self.output_kms_key = resolve_value_from_config(
output_kms_key, PROCESSING_JOB_KMS_KEY_ID_PATH, sagemaker_session=self.sagemaker_session
)
self.volume_kms_key = resolve_value_from_config(
volume_kms_key,
PROCESSING_JOB_VOLUME_KMS_KEY_ID_PATH,
sagemaker_session=self.sagemaker_session,
)
self.network_config = resolve_class_attribute_from_config(
NetworkConfig,
network_config,
"subnets",
PROCESSING_JOB_SUBNETS_PATH,
sagemaker_session=self.sagemaker_session,
)
self.network_config = resolve_class_attribute_from_config(
NetworkConfig,
self.network_config,
"security_group_ids",
PROCESSING_JOB_SECURITY_GROUP_IDS_PATH,
sagemaker_session=self.sagemaker_session,
)
self.network_config = resolve_class_attribute_from_config(
NetworkConfig,
self.network_config,
"enable_network_isolation",
PROCESSING_JOB_ENABLE_NETWORK_ISOLATION_PATH,
sagemaker_session=self.sagemaker_session,
)
self.network_config = resolve_class_attribute_from_config(
NetworkConfig,
self.network_config,
"encrypt_inter_container_traffic",
PROCESSING_JOB_INTER_CONTAINER_ENCRYPTION_PATH,
sagemaker_session=self.sagemaker_session,
)
self.role = resolve_value_from_config(
role, PROCESSING_JOB_ROLE_ARN_PATH, sagemaker_session=self.sagemaker_session
)
if not self.role:
# Originally IAM role was a required parameter.
# Now we marked that as Optional because we can fetch it from SageMakerConfig
# Because of marking that parameter as optional, we should validate if it is None, even
# after fetching the config.
raise ValueError("An AWS IAM role is required to create a Processing job.")
self.env = resolve_value_from_config(
env, PROCESSING_JOB_ENVIRONMENT_PATH, sagemaker_session=self.sagemaker_session
)
@runnable_by_pipeline
def run(
self,
inputs: Optional[List["ProcessingInput"]] = None,
outputs: Optional[List["ProcessingOutput"]] = None,
arguments: Optional[List[Union[str, PipelineVariable]]] = None,
wait: bool = True,
logs: bool = True,
job_name: Optional[str] = None,
experiment_config: Optional[Dict[str, str]] = None,
kms_key: Optional[str] = None,
):
"""Runs a processing job.
Args:
inputs (list[:class:`~sagemaker.processing.ProcessingInput`]): Input files for
the processing job. These must be provided as
:class:`~sagemaker.processing.ProcessingInput` objects (default: None).
outputs (list[:class:`~sagemaker.processing.ProcessingOutput`]): Outputs for
the processing job. These can be specified as either path strings or
:class:`~sagemaker.processing.ProcessingOutput` objects (default: None).
arguments (list[str] or list[PipelineVariable]): A list of string arguments
to be passed to a processing job (default: None).
wait (bool): Whether the call should wait until the job completes (default: True).
logs (bool): Whether to show the logs produced by the job.
Only meaningful when ``wait`` is True (default: True).
job_name (str): Processing job name. If not specified, the processor generates
a default job name, based on the base job name and current timestamp.
experiment_config (dict[str, str]): Experiment management configuration.
Optionally, the dict can contain three keys:
'ExperimentName', 'TrialName', and 'TrialComponentDisplayName'.
The behavior of setting these keys is as follows:
* If `ExperimentName` is supplied but `TrialName` is not a Trial will be
automatically created and the job's Trial Component associated with the Trial.
* If `TrialName` is supplied and the Trial already exists the job's Trial Component
will be associated with the Trial.
* If both `ExperimentName` and `TrialName` are not supplied the trial component
will be unassociated.
* `TrialComponentDisplayName` is used for display in Studio.
* Both `ExperimentName` and `TrialName` will be ignored if the Processor instance
is built with :class:`~sagemaker.workflow.pipeline_context.PipelineSession`.
However, the value of `TrialComponentDisplayName` is honored for display in Studio.
kms_key (str): The ARN of the KMS key that is used to encrypt the
user code file (default: None).
Returns:
None or pipeline step arguments in case the Processor instance is built with
:class:`~sagemaker.workflow.pipeline_context.PipelineSession`
Raises:
ValueError: if ``logs`` is True but ``wait`` is False.
"""
if logs and not wait:
raise ValueError(
"""Logs can only be shown if wait is set to True.
Please either set wait to True or set logs to False."""
)
normalized_inputs, normalized_outputs = self._normalize_args(
job_name=job_name,
arguments=arguments,
inputs=inputs,
kms_key=kms_key,
outputs=outputs,
)
experiment_config = check_and_get_run_experiment_config(experiment_config)
self.latest_job = ProcessingJob.start_new(
processor=self,
inputs=normalized_inputs,
outputs=normalized_outputs,
experiment_config=experiment_config,
)
self.jobs.append(self.latest_job)
if wait:
self.latest_job.wait(logs=logs)
def _extend_processing_args(self, inputs, outputs, **kwargs): # pylint: disable=W0613
"""Extend inputs and outputs based on extra parameters"""
return inputs, outputs
def _normalize_args(
self,
job_name=None,
arguments=None,
inputs=None,
outputs=None,
code=None,
kms_key=None,
):
"""Normalizes the arguments so that they can be passed to the job run
Args:
job_name (str): Name of the processing job to be created. If not specified, one
is generated, using the base name given to the constructor, if applicable
(default: None).
arguments (list[str]): A list of string arguments to be passed to a
processing job (default: None).
inputs (list[:class:`~sagemaker.processing.ProcessingInput`]): Input files for
the processing job. These must be provided as
:class:`~sagemaker.processing.ProcessingInput` objects (default: None).
outputs (list[:class:`~sagemaker.processing.ProcessingOutput`]): Outputs for
the processing job. These can be specified as either path strings or
:class:`~sagemaker.processing.ProcessingOutput` objects (default: None).
code (str): This can be an S3 URI or a local path to a file with the framework
script to run (default: None). A no op in the base class.
kms_key (str): The ARN of the KMS key that is used to encrypt the
user code file (default: None).
"""
if code and is_pipeline_variable(code):
raise ValueError(
"code argument has to be a valid S3 URI or local file path "
+ "rather than a pipeline variable"
)
self._current_job_name = self._generate_current_job_name(job_name=job_name)
inputs_with_code = self._include_code_in_inputs(inputs, code, kms_key)
normalized_inputs = self._normalize_inputs(inputs_with_code, kms_key)
normalized_outputs = self._normalize_outputs(outputs)
self.arguments = arguments
return normalized_inputs, normalized_outputs
def _include_code_in_inputs(self, inputs, _code, _kms_key):
"""A no op in the base class to include code in the processing job inputs.
Args:
inputs (list[:class:`~sagemaker.processing.ProcessingInput`]): Input files for
the processing job. These must be provided as
:class:`~sagemaker.processing.ProcessingInput` objects.
_code (str): This can be an S3 URI or a local path to a file with the framework
script to run (default: None). A no op in the base class.
kms_key (str): The ARN of the KMS key that is used to encrypt the
user code file (default: None).
Returns:
list[:class:`~sagemaker.processing.ProcessingInput`]: inputs
"""
return inputs
def _generate_current_job_name(self, job_name=None):
"""Generates the job name before running a processing job.
Args:
job_name (str): Name of the processing job to be created. If not
specified, one is generated, using the base name given to the
constructor if applicable.
Returns:
str: The supplied or generated job name.
"""
if job_name is not None:
return job_name
# Honor supplied base_job_name or generate it.
if self.base_job_name:
base_name = self.base_job_name
else:
base_name = base_name_from_image(
self.image_uri, default_base_name=Processor.JOB_CLASS_NAME
)
return name_from_base(base_name)
def _normalize_inputs(self, inputs=None, kms_key=None):
"""Ensures that all the ``ProcessingInput`` objects have names and S3 URIs.
Args:
inputs (list[sagemaker.processing.ProcessingInput]): A list of ``ProcessingInput``
objects to be normalized (default: None). If not specified,
an empty list is returned.
kms_key (str): The ARN of the KMS key that is used to encrypt the
user code file (default: None).
Returns:
list[sagemaker.processing.ProcessingInput]: The list of normalized
``ProcessingInput`` objects.
Raises:
TypeError: if the inputs are not ``ProcessingInput`` objects.
"""
from sagemaker.workflow.utilities import _pipeline_config
# Initialize a list of normalized ProcessingInput objects.
normalized_inputs = []
if inputs is not None:
# Iterate through the provided list of inputs.
for count, file_input in enumerate(inputs, 1):
if not isinstance(file_input, ProcessingInput):
raise TypeError("Your inputs must be provided as ProcessingInput objects.")
# Generate a name for the ProcessingInput if it doesn't have one.
if file_input.input_name is None:
file_input.input_name = "input-{}".format(count)
if is_pipeline_variable(file_input.source) or file_input.dataset_definition:
normalized_inputs.append(file_input)
continue
if is_pipeline_variable(file_input.s3_input.s3_uri):
normalized_inputs.append(file_input)
continue
# If the source is a local path, upload it to S3
# and save the S3 uri in the ProcessingInput source.
parse_result = urlparse(file_input.s3_input.s3_uri)
if parse_result.scheme != "s3":
if _pipeline_config:
desired_s3_uri = s3.s3_path_join(
"s3://",
self.sagemaker_session.default_bucket(),
self.sagemaker_session.default_bucket_prefix,
_pipeline_config.pipeline_name,
_pipeline_config.step_name,
"input",
file_input.input_name,
)
else:
desired_s3_uri = s3.s3_path_join(
"s3://",
self.sagemaker_session.default_bucket(),
self.sagemaker_session.default_bucket_prefix,
self._current_job_name,
"input",
file_input.input_name,
)
s3_uri = s3.S3Uploader.upload(
local_path=file_input.s3_input.s3_uri,
desired_s3_uri=desired_s3_uri,
sagemaker_session=self.sagemaker_session,
kms_key=kms_key,
)
file_input.s3_input.s3_uri = s3_uri
normalized_inputs.append(file_input)
return normalized_inputs
def _normalize_outputs(self, outputs=None):
"""Ensures that all the outputs are ``ProcessingOutput`` objects with names and S3 URIs.
Args:
outputs (list[sagemaker.processing.ProcessingOutput]): A list
of outputs to be normalized (default: None). Can be either strings or
``ProcessingOutput`` objects. If not specified,
an empty list is returned.
Returns:
list[sagemaker.processing.ProcessingOutput]: The list of normalized
``ProcessingOutput`` objects.
Raises:
TypeError: if the outputs are not ``ProcessingOutput`` objects.
"""
# Initialize a list of normalized ProcessingOutput objects.
from sagemaker.workflow.utilities import _pipeline_config
normalized_outputs = []
if outputs is not None:
# Iterate through the provided list of outputs.
for count, output in enumerate(outputs, 1):
if not isinstance(output, ProcessingOutput):
raise TypeError("Your outputs must be provided as ProcessingOutput objects.")
# Generate a name for the ProcessingOutput if it doesn't have one.
if output.output_name is None:
output.output_name = "output-{}".format(count)
if is_pipeline_variable(output.destination):
normalized_outputs.append(output)
continue
# If the output's destination is not an s3_uri, create one.
parse_result = urlparse(output.destination)
if parse_result.scheme != "s3":
if _pipeline_config:
s3_uri = Join(
on="/",
values=[
"s3:/",
self.sagemaker_session.default_bucket(),
*(
# don't include default_bucket_prefix if it is None or ""
[self.sagemaker_session.default_bucket_prefix]
if self.sagemaker_session.default_bucket_prefix
else []
),
_pipeline_config.pipeline_name,
ExecutionVariables.PIPELINE_EXECUTION_ID,
_pipeline_config.step_name,
"output",
output.output_name,
],
)
else:
s3_uri = s3.s3_path_join(
"s3://",
self.sagemaker_session.default_bucket(),
self.sagemaker_session.default_bucket_prefix,
self._current_job_name,
"output",
output.output_name,
)
output.destination = s3_uri
normalized_outputs.append(output)
return normalized_outputs
class ScriptProcessor(Processor):
"""Handles Amazon SageMaker processing tasks for jobs using a machine learning framework."""
def __init__(
self,
role: Optional[Union[str, PipelineVariable]] = None,
image_uri: Union[str, PipelineVariable] = None,
command: List[str] = None,
instance_count: Union[int, PipelineVariable] = None,
instance_type: Union[str, PipelineVariable] = None,
volume_size_in_gb: Union[int, PipelineVariable] = 30,
volume_kms_key: Optional[Union[str, PipelineVariable]] = None,
output_kms_key: Optional[Union[str, PipelineVariable]] = None,
max_runtime_in_seconds: Optional[Union[int, PipelineVariable]] = None,
base_job_name: Optional[str] = None,
sagemaker_session: Optional[Session] = None,
env: Optional[Dict[str, Union[str, PipelineVariable]]] = None,
tags: Optional[Tags] = None,
network_config: Optional[NetworkConfig] = None,
):
"""Initializes a ``ScriptProcessor`` instance.
The ``ScriptProcessor`` handles Amazon SageMaker Processing tasks for jobs
using a machine learning framework, which allows for providing a script to be
run as part of the Processing Job.
Args:
role (str or PipelineVariable): An AWS IAM role name or ARN. Amazon SageMaker Processing
uses this role to access AWS resources, such as
data stored in Amazon S3.
image_uri (str or PipelineVariable): The URI of the Docker image to use for the
processing jobs.
command ([str]): The command to run, along with any command-line flags.
Example: ["python3", "-v"].
instance_count (int or PipelineVariable): The number of instances to run
a processing job with.
instance_type (str or PipelineVariable): The type of EC2 instance to use for
processing, for example, 'ml.c4.xlarge'.
volume_size_in_gb (int or PipelineVariable): Size in GB of the EBS volume
to use for storing data during processing (default: 30).
volume_kms_key (str or PipelineVariable): A KMS key for the processing
volume (default: None).
output_kms_key (str or PipelineVariable): The KMS key ID for processing
job outputs (default: None).
max_runtime_in_seconds (int or PipelineVariable): Timeout in seconds (default: None).
After this amount of time, Amazon SageMaker terminates the job,
regardless of its current status. If `max_runtime_in_seconds` is not
specified, the default value is 24 hours.
base_job_name (str): Prefix for processing name. If not specified,
the processor generates a default job name, based on the
processing image name and current timestamp.
sagemaker_session (:class:`~sagemaker.session.Session`):
Session object which manages interactions with Amazon SageMaker and
any other AWS services needed. If not specified, the processor creates
one using the default AWS configuration chain.
env (dict[str, str] or dict[str, PipelineVariable])): Environment variables to
be passed to the processing jobs (default: None).
tags (Optional[Tags]): Tags to be passed to the processing job (default: None).
For more, see https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.
network_config (:class:`~sagemaker.network.NetworkConfig`):
A :class:`~sagemaker.network.NetworkConfig`
object that configures network isolation, encryption of
inter-container traffic, security group IDs, and subnets.
"""
self._CODE_CONTAINER_BASE_PATH = "/opt/ml/processing/input/"
self._CODE_CONTAINER_INPUT_NAME = "code"
self.command = command
super(ScriptProcessor, self).__init__(
role=role,
image_uri=image_uri,
instance_count=instance_count,
instance_type=instance_type,
volume_size_in_gb=volume_size_in_gb,
volume_kms_key=volume_kms_key,
output_kms_key=output_kms_key,
max_runtime_in_seconds=max_runtime_in_seconds,
base_job_name=base_job_name,
sagemaker_session=sagemaker_session,
env=env,
tags=format_tags(tags),
network_config=network_config,
)
def get_run_args(
self,
code,
inputs=None,
outputs=None,
arguments=None,
):
"""Returns a RunArgs object.
For processors (:class:`~sagemaker.spark.processing.PySparkProcessor`,
:class:`~sagemaker.spark.processing.SparkJar`) that have special
run() arguments, this object contains the normalized arguments for passing to
:class:`~sagemaker.workflow.steps.ProcessingStep`.
Args:
code (str): This can be an S3 URI or a local path to a file with the framework
script to run.
inputs (list[:class:`~sagemaker.processing.ProcessingInput`]): Input files for
the processing job. These must be provided as
:class:`~sagemaker.processing.ProcessingInput` objects (default: None).
outputs (list[:class:`~sagemaker.processing.ProcessingOutput`]): Outputs for
the processing job. These can be specified as either path strings or
:class:`~sagemaker.processing.ProcessingOutput` objects (default: None).
arguments (list[str]): A list of string arguments to be passed to a
processing job (default: None).
"""
logger.warning(
"This function has been deprecated and could break pipeline step caching. "
"We recommend using the run() function directly with pipeline sessions"
"to access step arguments."
)
return RunArgs(code=code, inputs=inputs, outputs=outputs, arguments=arguments)
@runnable_by_pipeline
def run(
self,
code: str,
inputs: Optional[List["ProcessingInput"]] = None,
outputs: Optional[List["ProcessingOutput"]] = None,
arguments: Optional[List[Union[str, PipelineVariable]]] = None,
wait: bool = True,
logs: bool = True,
job_name: Optional[str] = None,
experiment_config: Optional[Dict[str, str]] = None,
kms_key: Optional[str] = None,
):
"""Runs a processing job.
Args:
code (str): This can be an S3 URI or a local path to
a file with the framework script to run.
inputs (list[:class:`~sagemaker.processing.ProcessingInput`]): Input files for
the processing job. These must be provided as
:class:`~sagemaker.processing.ProcessingInput` objects (default: None).
outputs (list[:class:`~sagemaker.processing.ProcessingOutput`]): Outputs for
the processing job. These can be specified as either path strings or
:class:`~sagemaker.processing.ProcessingOutput` objects (default: None).
arguments (list[str]): A list of string arguments to be passed to a
processing job (default: None).
wait (bool): Whether the call should wait until the job completes (default: True).
logs (bool): Whether to show the logs produced by the job.
Only meaningful when wait is True (default: True).
job_name (str): Processing job name. If not specified, the processor generates
a default job name, based on the base job name and current timestamp.
experiment_config (dict[str, str]): Experiment management configuration.
Optionally, the dict can contain three keys:
'ExperimentName', 'TrialName', and 'TrialComponentDisplayName'.
The behavior of setting these keys is as follows:
* If `ExperimentName` is supplied but `TrialName` is not a Trial will be
automatically created and the job's Trial Component associated with the Trial.
* If `TrialName` is supplied and the Trial already exists the job's Trial Component
will be associated with the Trial.
* If both `ExperimentName` and `TrialName` are not supplied the trial component
will be unassociated.
* `TrialComponentDisplayName` is used for display in Studio.
* Both `ExperimentName` and `TrialName` will be ignored if the Processor instance
is built with :class:`~sagemaker.workflow.pipeline_context.PipelineSession`.
However, the value of `TrialComponentDisplayName` is honored for display in Studio.
kms_key (str): The ARN of the KMS key that is used to encrypt the
user code file (default: None).
Returns:
None or pipeline step arguments in case the Processor instance is built with
:class:`~sagemaker.workflow.pipeline_context.PipelineSession`
"""
normalized_inputs, normalized_outputs = self._normalize_args(
job_name=job_name,
arguments=arguments,
inputs=inputs,
outputs=outputs,
code=code,
kms_key=kms_key,
)
experiment_config = check_and_get_run_experiment_config(experiment_config)
self.latest_job = ProcessingJob.start_new(
processor=self,
inputs=normalized_inputs,
outputs=normalized_outputs,
experiment_config=experiment_config,
)
self.jobs.append(self.latest_job)
if wait:
self.latest_job.wait(logs=logs)
def _include_code_in_inputs(self, inputs, code, kms_key=None):
"""Converts code to appropriate input and includes in input list.
Side effects include:
* uploads code to S3 if the code is a local file.
* sets the entrypoint attribute based on the command and user script name from code.
Args:
inputs (list[:class:`~sagemaker.processing.ProcessingInput`]): Input files for
the processing job. These must be provided as
:class:`~sagemaker.processing.ProcessingInput` objects.
code (str): This can be an S3 URI or a local path to a file with the framework
script to run (default: None).
kms_key (str): The ARN of the KMS key that is used to encrypt the
user code file (default: None).
Returns:
list[:class:`~sagemaker.processing.ProcessingInput`]: inputs together with the
code as `ProcessingInput`.
"""
user_code_s3_uri = self._handle_user_code_url(code, kms_key)
user_script_name = self._get_user_code_name(code)
inputs_with_code = self._convert_code_and_add_to_inputs(inputs, user_code_s3_uri)
self._set_entrypoint(self.command, user_script_name)
return inputs_with_code
def _get_user_code_name(self, code):
"""Gets the basename of the user's code from the URL the customer provided.
Args:
code (str): A URL to the user's code.
Returns:
str: The basename of the user's code.
"""
code_url = urlparse(code)
return os.path.basename(code_url.path)
def _handle_user_code_url(self, code, kms_key=None):
"""Gets the S3 URL containing the user's code.
Inspects the scheme the customer passed in ("s3://" for code in S3, "file://" or nothing
for absolute or local file paths. Uploads the code to S3 if the code is a local file.
Args:
code (str): A URL to the customer's code.
kms_key (str): The ARN of the KMS key that is used to encrypt the
user code file (default: None).
Returns:
str: The S3 URL to the customer's code.
Raises:
ValueError: if the code isn't found, is a directory, or
does not have a valid URL scheme.
"""
code_url = urlparse(code)
if code_url.scheme == "s3":
user_code_s3_uri = code
elif code_url.scheme == "" or code_url.scheme == "file":
# Validate that the file exists locally and is not a directory.
code_path = url2pathname(code_url.path)
if not os.path.exists(code_path):
raise ValueError(
"""code {} wasn't found. Please make sure that the file exists.
""".format(
code
)
)
if not os.path.isfile(code_path):
raise ValueError(
"""code {} must be a file, not a directory. Please pass a path to a file.
""".format(
code
)
)
user_code_s3_uri = self._upload_code(code_path, kms_key)
else:
raise ValueError(
"code {} url scheme {} is not recognized. Please pass a file path or S3 url".format(
code, code_url.scheme
)
)
return user_code_s3_uri
def _upload_code(self, code, kms_key=None):
"""Uploads a code file or directory specified as a string and returns the S3 URI.
Args:
code (str): A file or directory to be uploaded to S3.
kms_key (str): The ARN of the KMS key that is used to encrypt the
user code file (default: None).
Returns:
str: The S3 URI of the uploaded file or directory.
"""
from sagemaker.workflow.utilities import _pipeline_config
if _pipeline_config and _pipeline_config.code_hash:
desired_s3_uri = s3.s3_path_join(
"s3://",
self.sagemaker_session.default_bucket(),
self.sagemaker_session.default_bucket_prefix,
_pipeline_config.pipeline_name,
self._CODE_CONTAINER_INPUT_NAME,
_pipeline_config.code_hash,
)
else:
desired_s3_uri = s3.s3_path_join(
"s3://",
self.sagemaker_session.default_bucket(),
self.sagemaker_session.default_bucket_prefix,
self._current_job_name,
"input",
self._CODE_CONTAINER_INPUT_NAME,
)
return s3.S3Uploader.upload(
local_path=code,
desired_s3_uri=desired_s3_uri,
kms_key=kms_key,
sagemaker_session=self.sagemaker_session,
)
def _convert_code_and_add_to_inputs(self, inputs, s3_uri):
"""Creates a ``ProcessingInput`` object from an S3 URI and adds it to the list of inputs.
Args:
inputs (list[sagemaker.processing.ProcessingInput]):
List of ``ProcessingInput`` objects.
s3_uri (str): S3 URI of the input to be added to inputs.
Returns:
list[sagemaker.processing.ProcessingInput]: A new list of ``ProcessingInput`` objects,
with the ``ProcessingInput`` object created from ``s3_uri`` appended to the list.
"""
code_file_input = ProcessingInput(
source=s3_uri,
destination=str(
pathlib.PurePosixPath(
self._CODE_CONTAINER_BASE_PATH, self._CODE_CONTAINER_INPUT_NAME
)
),
input_name=self._CODE_CONTAINER_INPUT_NAME,
)
return (inputs or []) + [code_file_input]
def _set_entrypoint(self, command, user_script_name):
"""Sets the entrypoint based on the user's script and corresponding executable.
Args:
user_script_name (str): A filename with an extension.
"""
user_script_location = str(
pathlib.PurePosixPath(
self._CODE_CONTAINER_BASE_PATH,
self._CODE_CONTAINER_INPUT_NAME,
user_script_name,
)
)
self.entrypoint = command + [user_script_location]
class ProcessingJob(_Job):
"""Provides functionality to start, describe, and stop processing jobs."""
def __init__(self, sagemaker_session, job_name, inputs, outputs, output_kms_key=None):
"""Initializes a Processing job.
Args:
sagemaker_session (:class:`~sagemaker.session.Session`):
Session object which manages interactions with Amazon SageMaker and
any other AWS services needed. If not specified, the processor creates
one using the default AWS configuration chain.
job_name (str): Name of the Processing job.
inputs (list[:class:`~sagemaker.processing.ProcessingInput`]): A list of
:class:`~sagemaker.processing.ProcessingInput` objects.
outputs (list[:class:`~sagemaker.processing.ProcessingOutput`]): A list of
:class:`~sagemaker.processing.ProcessingOutput` objects.
output_kms_key (str): The output KMS key associated with the job (default: None).
"""
self.inputs = inputs
self.outputs = outputs
self.output_kms_key = output_kms_key
super(ProcessingJob, self).__init__(sagemaker_session=sagemaker_session, job_name=job_name)
@classmethod
def start_new(cls, processor, inputs, outputs, experiment_config):
"""Starts a new processing job using the provided inputs and outputs.
Args:
processor (:class:`~sagemaker.processing.Processor`): The ``Processor`` instance
that started the job.
inputs (list[:class:`~sagemaker.processing.ProcessingInput`]): A list of
:class:`~sagemaker.processing.ProcessingInput` objects.
outputs (list[:class:`~sagemaker.processing.ProcessingOutput`]): A list of
:class:`~sagemaker.processing.ProcessingOutput` objects.
experiment_config (dict[str, str]): Experiment management configuration.
Optionally, the dict can contain three keys:
'ExperimentName', 'TrialName', and 'TrialComponentDisplayName'.
The behavior of setting these keys is as follows:
* If `ExperimentName` is supplied but `TrialName` is not a Trial will be
automatically created and the job's Trial Component associated with the Trial.
* If `TrialName` is supplied and the Trial already exists the job's Trial Component
will be associated with the Trial.
* If both `ExperimentName` and `TrialName` are not supplied the trial component
will be unassociated.
* `TrialComponentDisplayName` is used for display in Studio.
Returns:
:class:`~sagemaker.processing.ProcessingJob`: The instance of ``ProcessingJob`` created
using the ``Processor``.
"""
process_args = cls._get_process_args(processor, inputs, outputs, experiment_config)
# Log the job name and the user's inputs and outputs as lists of dictionaries.
logger.debug("Job Name: %s", process_args["job_name"])
logger.debug("Inputs: %s", process_args["inputs"])
logger.debug("Outputs: %s", process_args["output_config"]["Outputs"])
# Call sagemaker_session.process using the arguments dictionary.
processor.sagemaker_session.process(**process_args)
return cls(
processor.sagemaker_session,
processor._current_job_name,
inputs,
outputs,
processor.output_kms_key,
)
@classmethod
def _get_process_args(cls, processor, inputs, outputs, experiment_config):
"""Gets a dict of arguments for a new Amazon SageMaker processing job from the processor
Args:
processor (:class:`~sagemaker.processing.Processor`): The ``Processor`` instance
that started the job.
inputs (list[:class:`~sagemaker.processing.ProcessingInput`]): A list of
:class:`~sagemaker.processing.ProcessingInput` objects.
outputs (list[:class:`~sagemaker.processing.ProcessingOutput`]): A list of
:class:`~sagemaker.processing.ProcessingOutput` objects.
experiment_config (dict[str, str]): Experiment management configuration.
Optionally, the dict can contain three keys:
'ExperimentName', 'TrialName', and 'TrialComponentDisplayName'.
The behavior of setting these keys is as follows:
* If `ExperimentName` is supplied but `TrialName` is not a Trial will be
automatically created and the job's Trial Component associated with the Trial.
* If `TrialName` is supplied and the Trial already exists the job's Trial Component
will be associated with the Trial.
* If both `ExperimentName` and `TrialName` are not supplied the trial component
will be unassociated.
* `TrialComponentDisplayName` is used for display in Studio.
Returns:
Dict: dict for `sagemaker.session.Session.process` method
"""
# Initialize an empty dictionary for arguments to be passed to sagemaker_session.process.
process_request_args = {}
# Add arguments to the dictionary.
process_request_args["inputs"] = [inp._to_request_dict() for inp in inputs]
process_request_args["output_config"] = {
"Outputs": [output._to_request_dict() for output in outputs]
}
if processor.output_kms_key is not None:
process_request_args["output_config"]["KmsKeyId"] = processor.output_kms_key
process_request_args["experiment_config"] = experiment_config
process_request_args["job_name"] = processor._current_job_name
process_request_args["resources"] = {
"ClusterConfig": {
"InstanceType": processor.instance_type,
"InstanceCount": processor.instance_count,
"VolumeSizeInGB": processor.volume_size_in_gb,
}
}
if processor.volume_kms_key is not None:
process_request_args["resources"]["ClusterConfig"][
"VolumeKmsKeyId"
] = processor.volume_kms_key
if processor.max_runtime_in_seconds is not None:
process_request_args["stopping_condition"] = {
"MaxRuntimeInSeconds": processor.max_runtime_in_seconds
}
else:
process_request_args["stopping_condition"] = None
process_request_args["app_specification"] = {"ImageUri": processor.image_uri}
if processor.arguments is not None:
process_request_args["app_specification"]["ContainerArguments"] = processor.arguments
if processor.entrypoint is not None:
process_request_args["app_specification"]["ContainerEntrypoint"] = processor.entrypoint
process_request_args["environment"] = processor.env
if processor.network_config is not None:
process_request_args["network_config"] = processor.network_config._to_request_dict()
else:
process_request_args["network_config"] = None