-
Notifications
You must be signed in to change notification settings - Fork 14.4k
/
sagemaker.py
1331 lines (1147 loc) · 56.7 KB
/
sagemaker.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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations
import datetime
import json
import time
import warnings
from functools import cached_property
from typing import TYPE_CHECKING, Any, Callable, Sequence
from botocore.exceptions import ClientError
from airflow.configuration import conf
from airflow.exceptions import AirflowException, AirflowProviderDeprecationWarning
from airflow.models import BaseOperator
from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook
from airflow.providers.amazon.aws.hooks.sagemaker import SageMakerHook
from airflow.providers.amazon.aws.triggers.sagemaker import SageMakerTrigger
from airflow.providers.amazon.aws.utils import trim_none_values
from airflow.providers.amazon.aws.utils.sagemaker import ApprovalStatus
from airflow.providers.amazon.aws.utils.tags import format_tags
from airflow.utils.json import AirflowJsonEncoder
if TYPE_CHECKING:
from airflow.utils.context import Context
DEFAULT_CONN_ID: str = "aws_default"
CHECK_INTERVAL_SECOND: int = 30
def serialize(result: dict) -> str:
return json.loads(json.dumps(result, cls=AirflowJsonEncoder))
class SageMakerBaseOperator(BaseOperator):
"""This is the base operator for all SageMaker operators.
:param config: The configuration necessary to start a training job (templated)
"""
template_fields: Sequence[str] = ("config",)
template_ext: Sequence[str] = ()
template_fields_renderers: dict = {"config": "json"}
ui_color: str = "#ededed"
integer_fields: list[list[Any]] = []
def __init__(self, *, config: dict, aws_conn_id: str = DEFAULT_CONN_ID, **kwargs):
super().__init__(**kwargs)
self.config = config
self.aws_conn_id = aws_conn_id
def parse_integer(self, config: dict, field: list[str] | str) -> None:
"""Recursive method for parsing string fields holding integer values to integers."""
if len(field) == 1:
if isinstance(config, list):
for sub_config in config:
self.parse_integer(sub_config, field)
return
head = field[0]
if head in config:
config[head] = int(config[head])
return
if isinstance(config, list):
for sub_config in config:
self.parse_integer(sub_config, field)
return
(head, tail) = (field[0], field[1:])
if head in config:
self.parse_integer(config[head], tail)
return
def parse_config_integers(self) -> None:
"""Parse the integer fields to ints in case the config is rendered by Jinja and all fields are str."""
for field in self.integer_fields:
self.parse_integer(self.config, field)
def expand_role(self) -> None:
"""Placeholder for calling boto3's `expand_role`, which expands an IAM role name into an ARN."""
def preprocess_config(self) -> None:
"""Process the config into a usable form."""
self._create_integer_fields()
self.log.info("Preprocessing the config and doing required s3_operations")
self.hook.configure_s3_resources(self.config)
self.parse_config_integers()
self.expand_role()
self.log.info(
"After preprocessing the config is:\n %s",
json.dumps(self.config, sort_keys=True, indent=4, separators=(",", ": ")),
)
def _create_integer_fields(self) -> None:
"""
Set fields which should be cast to integers.
Child classes should override this method if they need integer fields parsed.
"""
self.integer_fields = []
def _get_unique_job_name(
self, proposed_name: str, fail_if_exists: bool, describe_func: Callable[[str], Any]
) -> str:
"""
Returns the proposed name if it doesn't already exist, otherwise returns it with a timestamp suffix.
:param proposed_name: Base name.
:param fail_if_exists: Will throw an error if a job with that name already exists
instead of finding a new name.
:param describe_func: The `describe_` function for that kind of job.
We use it as an O(1) way to check if a job exists.
"""
job_name = proposed_name
while self._check_if_job_exists(job_name, describe_func):
# this while should loop only once in most cases, just setting it this way to regenerate a name
# in case there is collision.
if fail_if_exists:
raise AirflowException(f"A SageMaker job with name {job_name} already exists.")
else:
job_name = f"{proposed_name}-{time.time_ns()//1000000}"
self.log.info("Changed job name to '%s' to avoid collision.", job_name)
return job_name
def _check_if_job_exists(self, job_name, describe_func: Callable[[str], Any]) -> bool:
"""Returns True if job exists, False otherwise."""
try:
describe_func(job_name)
self.log.info("Found existing job with name '%s'.", job_name)
return True
except ClientError as e:
if e.response["Error"]["Code"] == "ValidationException":
return False # ValidationException is thrown when the job could not be found
else:
raise e
def execute(self, context: Context):
raise NotImplementedError("Please implement execute() in sub class!")
@cached_property
def hook(self):
"""Return SageMakerHook."""
return SageMakerHook(aws_conn_id=self.aws_conn_id)
class SageMakerProcessingOperator(SageMakerBaseOperator):
"""
Use Amazon SageMaker Processing to analyze data and evaluate machine learning models on Amazon SageMaker.
With Processing, you can use a simplified, managed experience on SageMaker
to run your data processing workloads, such as feature engineering, data
validation, model evaluation, and model interpretation.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerProcessingOperator`
:param config: The configuration necessary to start a processing job (templated).
For details of the configuration parameter see :py:meth:`SageMaker.Client.create_processing_job`
:param aws_conn_id: The AWS connection ID to use.
:param wait_for_completion: If wait is set to True, the time interval, in seconds,
that the operation waits to check the status of the processing job.
:param print_log: if the operator should print the cloudwatch log during processing
:param check_interval: if wait is set to be true, this is the time interval
in seconds which the operator will check the status of the processing job
:param max_attempts: Number of times to poll for query state before returning the current state,
defaults to None.
:param max_ingestion_time: If wait is set to True, the operation fails if the processing job
doesn't finish within max_ingestion_time seconds. If you set this parameter to None,
the operation does not timeout.
:param action_if_job_exists: Behaviour if the job name already exists. Possible options are "timestamp"
(default), "increment" (deprecated) and "fail".
:param deferrable: Run operator in the deferrable mode. This is only effective if wait_for_completion is
set to True.
:return Dict: Returns The ARN of the processing job created in Amazon SageMaker.
"""
def __init__(
self,
*,
config: dict,
aws_conn_id: str = DEFAULT_CONN_ID,
wait_for_completion: bool = True,
print_log: bool = True,
check_interval: int = CHECK_INTERVAL_SECOND,
max_attempts: int | None = None,
max_ingestion_time: int | None = None,
action_if_job_exists: str = "timestamp",
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
**kwargs,
):
super().__init__(config=config, aws_conn_id=aws_conn_id, **kwargs)
if action_if_job_exists not in ("increment", "fail", "timestamp"):
raise AirflowException(
f"Argument action_if_job_exists accepts only 'timestamp', 'increment' and 'fail'. \
Provided value: '{action_if_job_exists}'."
)
if action_if_job_exists == "increment":
warnings.warn(
"Action 'increment' on job name conflict has been deprecated for performance reasons."
"The alternative to 'fail' is now 'timestamp'.",
AirflowProviderDeprecationWarning,
stacklevel=2,
)
self.action_if_job_exists = action_if_job_exists
self.wait_for_completion = wait_for_completion
self.print_log = print_log
self.check_interval = check_interval
self.max_attempts = max_attempts or 60
self.max_ingestion_time = max_ingestion_time
self.deferrable = deferrable
def _create_integer_fields(self) -> None:
"""Set fields which should be cast to integers."""
self.integer_fields: list[list[str] | list[list[str]]] = [
["ProcessingResources", "ClusterConfig", "InstanceCount"],
["ProcessingResources", "ClusterConfig", "VolumeSizeInGB"],
]
if "StoppingCondition" in self.config:
self.integer_fields.append(["StoppingCondition", "MaxRuntimeInSeconds"])
def expand_role(self) -> None:
"""Expands an IAM role name into an ARN."""
if "RoleArn" in self.config:
hook = AwsBaseHook(self.aws_conn_id, client_type="iam")
self.config["RoleArn"] = hook.expand_role(self.config["RoleArn"])
def execute(self, context: Context) -> dict:
self.preprocess_config()
self.config["ProcessingJobName"] = self._get_unique_job_name(
self.config["ProcessingJobName"],
self.action_if_job_exists == "fail",
self.hook.describe_processing_job,
)
if self.deferrable and not self.wait_for_completion:
self.log.warning(
"Setting deferrable to True does not have effect when wait_for_completion is set to False."
)
wait_for_completion = self.wait_for_completion
if self.deferrable and self.wait_for_completion:
# Set wait_for_completion to False so that it waits for the status in the deferred task.
wait_for_completion = False
response = self.hook.create_processing_job(
self.config,
wait_for_completion=wait_for_completion,
check_interval=self.check_interval,
max_ingestion_time=self.max_ingestion_time,
)
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
raise AirflowException(f"Sagemaker Processing Job creation failed: {response}")
if self.deferrable and self.wait_for_completion:
self.defer(
timeout=self.execution_timeout,
trigger=SageMakerTrigger(
job_name=self.config["ProcessingJobName"],
job_type="Processing",
poke_interval=self.check_interval,
max_attempts=self.max_attempts,
aws_conn_id=self.aws_conn_id,
),
method_name="execute_complete",
)
return {"Processing": serialize(self.hook.describe_processing_job(self.config["ProcessingJobName"]))}
def execute_complete(self, context, event=None):
if event["status"] != "success":
raise AirflowException(f"Error while running job: {event}")
else:
self.log.info(event["message"])
return {"Processing": serialize(self.hook.describe_processing_job(self.config["ProcessingJobName"]))}
class SageMakerEndpointConfigOperator(SageMakerBaseOperator):
"""
Creates an endpoint configuration that Amazon SageMaker hosting services uses to deploy models.
In the configuration, you identify one or more models, created using the CreateModel API, to deploy and
the resources that you want Amazon SageMaker to provision.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerEndpointConfigOperator`
:param config: The configuration necessary to create an endpoint config.
For details of the configuration parameter see :py:meth:`SageMaker.Client.create_endpoint_config`
:param aws_conn_id: The AWS connection ID to use.
:return Dict: Returns The ARN of the endpoint config created in Amazon SageMaker.
"""
def __init__(
self,
*,
config: dict,
aws_conn_id: str = DEFAULT_CONN_ID,
**kwargs,
):
super().__init__(config=config, aws_conn_id=aws_conn_id, **kwargs)
def _create_integer_fields(self) -> None:
"""Set fields which should be cast to integers."""
self.integer_fields: list[list[str]] = [["ProductionVariants", "InitialInstanceCount"]]
def execute(self, context: Context) -> dict:
self.preprocess_config()
self.log.info("Creating SageMaker Endpoint Config %s.", self.config["EndpointConfigName"])
response = self.hook.create_endpoint_config(self.config)
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
raise AirflowException(f"Sagemaker endpoint config creation failed: {response}")
else:
return {
"EndpointConfig": serialize(
self.hook.describe_endpoint_config(self.config["EndpointConfigName"])
)
}
class SageMakerEndpointOperator(SageMakerBaseOperator):
"""
When you create a serverless endpoint, SageMaker provisions and manages the compute resources for you.
Then, you can make inference requests to the endpoint and receive model predictions
in response. SageMaker scales the compute resources up and down as needed to handle
your request traffic.
Requires an Endpoint Config.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerEndpointOperator`
:param config:
The configuration necessary to create an endpoint.
If you need to create a SageMaker endpoint based on an existed
SageMaker model and an existed SageMaker endpoint config::
config = endpoint_configuration;
If you need to create all of SageMaker model, SageMaker endpoint-config and SageMaker endpoint::
config = {
'Model': model_configuration,
'EndpointConfig': endpoint_config_configuration,
'Endpoint': endpoint_configuration
}
For details of the configuration parameter of model_configuration see
:py:meth:`SageMaker.Client.create_model`
For details of the configuration parameter of endpoint_config_configuration see
:py:meth:`SageMaker.Client.create_endpoint_config`
For details of the configuration parameter of endpoint_configuration see
:py:meth:`SageMaker.Client.create_endpoint`
:param wait_for_completion: Whether the operator should wait until the endpoint creation finishes.
:param check_interval: If wait is set to True, this is the time interval, in seconds, that this operation
waits before polling the status of the endpoint creation.
:param max_ingestion_time: If wait is set to True, this operation fails if the endpoint creation doesn't
finish within max_ingestion_time seconds. If you set this parameter to None it never times out.
:param operation: Whether to create an endpoint or update an endpoint. Must be either 'create or 'update'.
:param aws_conn_id: The AWS connection ID to use.
:param deferrable: Will wait asynchronously for completion.
:return Dict: Returns The ARN of the endpoint created in Amazon SageMaker.
"""
def __init__(
self,
*,
config: dict,
aws_conn_id: str = DEFAULT_CONN_ID,
wait_for_completion: bool = True,
check_interval: int = CHECK_INTERVAL_SECOND,
max_ingestion_time: int | None = None,
operation: str = "create",
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
**kwargs,
):
super().__init__(config=config, aws_conn_id=aws_conn_id, **kwargs)
self.wait_for_completion = wait_for_completion
self.check_interval = check_interval
self.max_ingestion_time = max_ingestion_time or 3600 * 10
self.operation = operation.lower()
if self.operation not in ["create", "update"]:
raise ValueError('Invalid value! Argument operation has to be one of "create" and "update"')
self.deferrable = deferrable
def _create_integer_fields(self) -> None:
"""Set fields which should be cast to integers."""
if "EndpointConfig" in self.config:
self.integer_fields: list[list[str]] = [
["EndpointConfig", "ProductionVariants", "InitialInstanceCount"]
]
def expand_role(self) -> None:
"""Expands an IAM role name into an ARN."""
if "Model" not in self.config:
return
hook = AwsBaseHook(self.aws_conn_id, client_type="iam")
config = self.config["Model"]
if "ExecutionRoleArn" in config:
config["ExecutionRoleArn"] = hook.expand_role(config["ExecutionRoleArn"])
def execute(self, context: Context) -> dict:
self.preprocess_config()
model_info = self.config.get("Model")
endpoint_config_info = self.config.get("EndpointConfig")
endpoint_info = self.config.get("Endpoint", self.config)
if model_info:
self.log.info("Creating SageMaker model %s.", model_info["ModelName"])
self.hook.create_model(model_info)
if endpoint_config_info:
self.log.info("Creating endpoint config %s.", endpoint_config_info["EndpointConfigName"])
self.hook.create_endpoint_config(endpoint_config_info)
if self.operation == "create":
sagemaker_operation = self.hook.create_endpoint
log_str = "Creating"
elif self.operation == "update":
sagemaker_operation = self.hook.update_endpoint
log_str = "Updating"
else:
raise ValueError('Invalid value! Argument operation has to be one of "create" and "update"')
self.log.info("%s SageMaker endpoint %s.", log_str, endpoint_info["EndpointName"])
try:
response = sagemaker_operation(
endpoint_info,
wait_for_completion=False,
)
# waiting for completion is handled here in the operator
except ClientError:
self.operation = "update"
sagemaker_operation = self.hook.update_endpoint
response = sagemaker_operation(
endpoint_info,
wait_for_completion=False,
)
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
raise AirflowException(f"Sagemaker endpoint creation failed: {response}")
if self.deferrable:
self.defer(
trigger=SageMakerTrigger(
job_name=endpoint_info["EndpointName"],
job_type="endpoint",
poke_interval=self.check_interval,
aws_conn_id=self.aws_conn_id,
),
method_name="execute_complete",
timeout=datetime.timedelta(seconds=self.max_ingestion_time),
)
elif self.wait_for_completion:
self.hook.get_waiter("endpoint_in_service").wait(
EndpointName=endpoint_info["EndpointName"],
WaiterConfig={"Delay": self.check_interval, "MaxAttempts": self.max_ingestion_time},
)
return {
"EndpointConfig": serialize(
self.hook.describe_endpoint_config(endpoint_info["EndpointConfigName"])
),
"Endpoint": serialize(self.hook.describe_endpoint(endpoint_info["EndpointName"])),
}
def execute_complete(self, context, event=None):
if event["status"] != "success":
raise AirflowException(f"Error while running job: {event}")
endpoint_info = self.config.get("Endpoint", self.config)
return {
"EndpointConfig": serialize(
self.hook.describe_endpoint_config(endpoint_info["EndpointConfigName"])
),
"Endpoint": serialize(self.hook.describe_endpoint(endpoint_info["EndpointName"])),
}
class SageMakerTransformOperator(SageMakerBaseOperator):
"""
Starts a transform job.
A transform job uses a trained model to get inferences on a dataset
and saves these results to an Amazon S3 location that you specify.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerTransformOperator`
:param config: The configuration necessary to start a transform job (templated).
If you need to create a SageMaker transform job based on an existed SageMaker model::
config = transform_config
If you need to create both SageMaker model and SageMaker Transform job::
config = {
'Model': model_config,
'Transform': transform_config
}
For details of the configuration parameter of transform_config see
:py:meth:`SageMaker.Client.create_transform_job`
For details of the configuration parameter of model_config, See:
:py:meth:`SageMaker.Client.create_model`
:param aws_conn_id: The AWS connection ID to use.
:param wait_for_completion: Set to True to wait until the transform job finishes.
:param check_interval: If wait is set to True, the time interval, in seconds,
that this operation waits to check the status of the transform job.
:param max_attempts: Number of times to poll for query state before returning the current state,
defaults to None.
:param max_ingestion_time: If wait is set to True, the operation fails
if the transform job doesn't finish within max_ingestion_time seconds. If you
set this parameter to None, the operation does not timeout.
:param check_if_job_exists: If set to true, then the operator will check whether a transform job
already exists for the name in the config.
:param action_if_job_exists: Behaviour if the job name already exists. Possible options are "timestamp"
(default), "increment" (deprecated) and "fail".
This is only relevant if check_if_job_exists is True.
:return Dict: Returns The ARN of the model created in Amazon SageMaker.
"""
def __init__(
self,
*,
config: dict,
aws_conn_id: str = DEFAULT_CONN_ID,
wait_for_completion: bool = True,
check_interval: int = CHECK_INTERVAL_SECOND,
max_attempts: int | None = None,
max_ingestion_time: int | None = None,
check_if_job_exists: bool = True,
action_if_job_exists: str = "timestamp",
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
**kwargs,
):
super().__init__(config=config, aws_conn_id=aws_conn_id, **kwargs)
self.wait_for_completion = wait_for_completion
self.check_interval = check_interval
self.max_attempts = max_attempts or 60
self.max_ingestion_time = max_ingestion_time
self.check_if_job_exists = check_if_job_exists
if action_if_job_exists in ("increment", "fail", "timestamp"):
if action_if_job_exists == "increment":
warnings.warn(
"Action 'increment' on job name conflict has been deprecated for performance reasons."
"The alternative to 'fail' is now 'timestamp'.",
AirflowProviderDeprecationWarning,
stacklevel=2,
)
self.action_if_job_exists = action_if_job_exists
else:
raise AirflowException(
f"Argument action_if_job_exists accepts only 'timestamp', 'increment' and 'fail'. \
Provided value: '{action_if_job_exists}'."
)
self.deferrable = deferrable
def _create_integer_fields(self) -> None:
"""Set fields which should be cast to integers."""
self.integer_fields: list[list[str]] = [
["Transform", "TransformResources", "InstanceCount"],
["Transform", "MaxConcurrentTransforms"],
["Transform", "MaxPayloadInMB"],
]
if "Transform" not in self.config:
for field in self.integer_fields:
field.pop(0)
def expand_role(self) -> None:
"""Expands an IAM role name into an ARN."""
if "Model" not in self.config:
return
config = self.config["Model"]
if "ExecutionRoleArn" in config:
hook = AwsBaseHook(self.aws_conn_id, client_type="iam")
config["ExecutionRoleArn"] = hook.expand_role(config["ExecutionRoleArn"])
def execute(self, context: Context) -> dict:
self.preprocess_config()
transform_config = self.config.get("Transform", self.config)
if self.check_if_job_exists:
transform_config["TransformJobName"] = self._get_unique_job_name(
transform_config["TransformJobName"],
self.action_if_job_exists == "fail",
self.hook.describe_transform_job,
)
model_config = self.config.get("Model")
if model_config:
self.log.info("Creating SageMaker Model %s for transform job", model_config["ModelName"])
self.hook.create_model(model_config)
self.log.info("Creating SageMaker transform Job %s.", transform_config["TransformJobName"])
if self.deferrable and not self.wait_for_completion:
self.log.warning(
"Setting deferrable to True does not have effect when wait_for_completion is set to False."
)
wait_for_completion = self.wait_for_completion
if self.deferrable and self.wait_for_completion:
# Set wait_for_completion to False so that it waits for the status in the deferred task.
wait_for_completion = False
response = self.hook.create_transform_job(
transform_config,
wait_for_completion=wait_for_completion,
check_interval=self.check_interval,
max_ingestion_time=self.max_ingestion_time,
)
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
raise AirflowException(f"Sagemaker transform Job creation failed: {response}")
if self.deferrable and self.wait_for_completion:
self.defer(
timeout=self.execution_timeout,
trigger=SageMakerTrigger(
job_name=transform_config["TransformJobName"],
job_type="Transform",
poke_interval=self.check_interval,
max_attempts=self.max_attempts,
aws_conn_id=self.aws_conn_id,
),
method_name="execute_complete",
)
return {
"Model": serialize(self.hook.describe_model(transform_config["ModelName"])),
"Transform": serialize(self.hook.describe_transform_job(transform_config["TransformJobName"])),
}
def execute_complete(self, context, event=None):
if event["status"] != "success":
raise AirflowException(f"Error while running job: {event}")
else:
self.log.info(event["message"])
transform_config = self.config.get("Transform", self.config)
return {
"Model": serialize(self.hook.describe_model(transform_config["ModelName"])),
"Transform": serialize(self.hook.describe_transform_job(transform_config["TransformJobName"])),
}
class SageMakerTuningOperator(SageMakerBaseOperator):
"""
Starts a hyperparameter tuning job.
A hyperparameter tuning job finds the best version of a model by running
many training jobs on your dataset using the algorithm you choose and
values for hyperparameters within ranges that you specify. It then chooses
the hyperparameter values that result in a model that performs the best,
as measured by an objective metric that you choose.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerTuningOperator`
:param config: The configuration necessary to start a tuning job (templated).
For details of the configuration parameter see
:py:meth:`SageMaker.Client.create_hyper_parameter_tuning_job`
:param aws_conn_id: The AWS connection ID to use.
:param wait_for_completion: Set to True to wait until the tuning job finishes.
:param check_interval: If wait is set to True, the time interval, in seconds,
that this operation waits to check the status of the tuning job.
:param max_ingestion_time: If wait is set to True, the operation fails
if the tuning job doesn't finish within max_ingestion_time seconds. If you
set this parameter to None, the operation does not timeout.
:param deferrable: Will wait asynchronously for completion.
:return Dict: Returns The ARN of the tuning job created in Amazon SageMaker.
"""
def __init__(
self,
*,
config: dict,
aws_conn_id: str = DEFAULT_CONN_ID,
wait_for_completion: bool = True,
check_interval: int = CHECK_INTERVAL_SECOND,
max_ingestion_time: int | None = None,
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
**kwargs,
):
super().__init__(config=config, aws_conn_id=aws_conn_id, **kwargs)
self.wait_for_completion = wait_for_completion
self.check_interval = check_interval
self.max_ingestion_time = max_ingestion_time
self.deferrable = deferrable
def expand_role(self) -> None:
"""Expands an IAM role name into an ARN."""
if "TrainingJobDefinition" in self.config:
config = self.config["TrainingJobDefinition"]
if "RoleArn" in config:
hook = AwsBaseHook(self.aws_conn_id, client_type="iam")
config["RoleArn"] = hook.expand_role(config["RoleArn"])
def _create_integer_fields(self) -> None:
"""Set fields which should be cast to integers."""
self.integer_fields: list[list[str]] = [
["HyperParameterTuningJobConfig", "ResourceLimits", "MaxNumberOfTrainingJobs"],
["HyperParameterTuningJobConfig", "ResourceLimits", "MaxParallelTrainingJobs"],
["TrainingJobDefinition", "ResourceConfig", "InstanceCount"],
["TrainingJobDefinition", "ResourceConfig", "VolumeSizeInGB"],
["TrainingJobDefinition", "StoppingCondition", "MaxRuntimeInSeconds"],
]
def execute(self, context: Context) -> dict:
self.preprocess_config()
self.log.info(
"Creating SageMaker Hyper-Parameter Tuning Job %s", self.config["HyperParameterTuningJobName"]
)
response = self.hook.create_tuning_job(
self.config,
wait_for_completion=False, # we handle this here
check_interval=self.check_interval,
max_ingestion_time=self.max_ingestion_time,
)
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
raise AirflowException(f"Sagemaker Tuning Job creation failed: {response}")
if self.deferrable:
self.defer(
trigger=SageMakerTrigger(
job_name=self.config["HyperParameterTuningJobName"],
job_type="tuning",
poke_interval=self.check_interval,
aws_conn_id=self.aws_conn_id,
),
method_name="execute_complete",
timeout=datetime.timedelta(seconds=self.max_ingestion_time)
if self.max_ingestion_time is not None
else None,
)
description = {} # never executed but makes static checkers happy
elif self.wait_for_completion:
description = self.hook.check_status(
self.config["HyperParameterTuningJobName"],
"HyperParameterTuningJobStatus",
self.hook.describe_tuning_job,
self.check_interval,
self.max_ingestion_time,
)
else:
description = self.hook.describe_tuning_job(self.config["HyperParameterTuningJobName"])
return {"Tuning": serialize(description)}
def execute_complete(self, context, event=None):
if event["status"] != "success":
raise AirflowException(f"Error while running job: {event}")
return {
"Tuning": serialize(self.hook.describe_tuning_job(self.config["HyperParameterTuningJobName"]))
}
class SageMakerModelOperator(SageMakerBaseOperator):
"""
Creates a model in Amazon SageMaker.
In the request, you name the model and describe a primary container. For the
primary container, you specify the Docker image that contains inference code,
artifacts (from prior training), and a custom environment map that the inference
code uses when you deploy the model for predictions.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerModelOperator`
:param config: The configuration necessary to create a model.
For details of the configuration parameter see :py:meth:`SageMaker.Client.create_model`
:param aws_conn_id: The AWS connection ID to use.
:return Dict: Returns The ARN of the model created in Amazon SageMaker.
"""
def __init__(self, *, config: dict, aws_conn_id: str = DEFAULT_CONN_ID, **kwargs):
super().__init__(config=config, aws_conn_id=aws_conn_id, **kwargs)
def expand_role(self) -> None:
"""Expands an IAM role name into an ARN."""
if "ExecutionRoleArn" in self.config:
hook = AwsBaseHook(self.aws_conn_id, client_type="iam")
self.config["ExecutionRoleArn"] = hook.expand_role(self.config["ExecutionRoleArn"])
def execute(self, context: Context) -> dict:
self.preprocess_config()
self.log.info("Creating SageMaker Model %s.", self.config["ModelName"])
response = self.hook.create_model(self.config)
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
raise AirflowException(f"Sagemaker model creation failed: {response}")
else:
return {"Model": serialize(self.hook.describe_model(self.config["ModelName"]))}
class SageMakerTrainingOperator(SageMakerBaseOperator):
"""
Starts a model training job.
After training completes, Amazon SageMaker saves the resulting
model artifacts to an Amazon S3 location that you specify.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerTrainingOperator`
:param config: The configuration necessary to start a training job (templated).
For details of the configuration parameter see :py:meth:`SageMaker.Client.create_training_job`
:param aws_conn_id: The AWS connection ID to use.
:param wait_for_completion: If wait is set to True, the time interval, in seconds,
that the operation waits to check the status of the training job.
:param print_log: if the operator should print the cloudwatch log during training
:param check_interval: if wait is set to be true, this is the time interval
in seconds which the operator will check the status of the training job
:param max_attempts: Number of times to poll for query state before returning the current state,
defaults to None.
:param max_ingestion_time: If wait is set to True, the operation fails if the training job
doesn't finish within max_ingestion_time seconds. If you set this parameter to None,
the operation does not timeout.
:param check_if_job_exists: If set to true, then the operator will check whether a training job
already exists for the name in the config.
:param action_if_job_exists: Behaviour if the job name already exists. Possible options are "timestamp"
(default), "increment" (deprecated) and "fail".
This is only relevant if check_if_job_exists is True.
:param deferrable: Run operator in the deferrable mode. This is only effective if wait_for_completion is
set to True.
:return Dict: Returns The ARN of the training job created in Amazon SageMaker.
"""
def __init__(
self,
*,
config: dict,
aws_conn_id: str = DEFAULT_CONN_ID,
wait_for_completion: bool = True,
print_log: bool = True,
check_interval: int = CHECK_INTERVAL_SECOND,
max_attempts: int | None = None,
max_ingestion_time: int | None = None,
check_if_job_exists: bool = True,
action_if_job_exists: str = "timestamp",
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
**kwargs,
):
super().__init__(config=config, aws_conn_id=aws_conn_id, **kwargs)
self.wait_for_completion = wait_for_completion
self.print_log = print_log
self.check_interval = check_interval
self.max_attempts = max_attempts or 60
self.max_ingestion_time = max_ingestion_time
self.check_if_job_exists = check_if_job_exists
if action_if_job_exists in {"timestamp", "increment", "fail"}:
if action_if_job_exists == "increment":
warnings.warn(
"Action 'increment' on job name conflict has been deprecated for performance reasons."
"The alternative to 'fail' is now 'timestamp'.",
AirflowProviderDeprecationWarning,
stacklevel=2,
)
self.action_if_job_exists = action_if_job_exists
else:
raise AirflowException(
f"Argument action_if_job_exists accepts only 'timestamp', 'increment' and 'fail'. \
Provided value: '{action_if_job_exists}'."
)
self.deferrable = deferrable
def expand_role(self) -> None:
"""Expands an IAM role name into an ARN."""
if "RoleArn" in self.config:
hook = AwsBaseHook(self.aws_conn_id, client_type="iam")
self.config["RoleArn"] = hook.expand_role(self.config["RoleArn"])
def _create_integer_fields(self) -> None:
"""Set fields which should be cast to integers."""
self.integer_fields: list[list[str]] = [
["ResourceConfig", "InstanceCount"],
["ResourceConfig", "VolumeSizeInGB"],
["StoppingCondition", "MaxRuntimeInSeconds"],
]
def execute(self, context: Context) -> dict:
self.preprocess_config()
if self.check_if_job_exists:
self.config["TrainingJobName"] = self._get_unique_job_name(
self.config["TrainingJobName"],
self.action_if_job_exists == "fail",
self.hook.describe_training_job,
)
self.log.info("Creating SageMaker training job %s.", self.config["TrainingJobName"])
if self.deferrable and not self.wait_for_completion:
self.log.warning(
"Setting deferrable to True does not have effect when wait_for_completion is set to False."
)
wait_for_completion = self.wait_for_completion
if self.deferrable and self.wait_for_completion:
# Set wait_for_completion to False so that it waits for the status in the deferred task.
wait_for_completion = False
response = self.hook.create_training_job(
self.config,
wait_for_completion=wait_for_completion,
print_log=self.print_log,
check_interval=self.check_interval,
max_ingestion_time=self.max_ingestion_time,
)
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
raise AirflowException(f"Sagemaker Training Job creation failed: {response}")
if self.deferrable and self.wait_for_completion:
self.defer(
timeout=self.execution_timeout,
trigger=SageMakerTrigger(
job_name=self.config["TrainingJobName"],
job_type="Training",
poke_interval=self.check_interval,
max_attempts=self.max_attempts,
aws_conn_id=self.aws_conn_id,
),
method_name="execute_complete",
)
result = {"Training": serialize(self.hook.describe_training_job(self.config["TrainingJobName"]))}
return result
def execute_complete(self, context, event=None):
if event["status"] != "success":
raise AirflowException(f"Error while running job: {event}")
else:
self.log.info(event["message"])
result = {"Training": serialize(self.hook.describe_training_job(self.config["TrainingJobName"]))}
return result
class SageMakerDeleteModelOperator(SageMakerBaseOperator):
"""
Deletes a SageMaker model.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerDeleteModelOperator`
:param config: The configuration necessary to delete the model.
For details of the configuration parameter see :py:meth:`SageMaker.Client.delete_model`
:param aws_conn_id: The AWS connection ID to use.
"""
def __init__(self, *, config: dict, aws_conn_id: str = DEFAULT_CONN_ID, **kwargs):
super().__init__(config=config, aws_conn_id=aws_conn_id, **kwargs)
def execute(self, context: Context) -> Any:
sagemaker_hook = SageMakerHook(aws_conn_id=self.aws_conn_id)
sagemaker_hook.delete_model(model_name=self.config["ModelName"])
self.log.info("Model %s deleted successfully.", self.config["ModelName"])
class SageMakerStartPipelineOperator(SageMakerBaseOperator):
"""
Starts a SageMaker pipeline execution.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerStartPipelineOperator`
:param config: The configuration to start the pipeline execution.
:param aws_conn_id: The AWS connection ID to use.
:param pipeline_name: Name of the pipeline to start.
:param display_name: The name this pipeline execution will have in the UI. Doesn't need to be unique.
:param pipeline_params: Optional parameters for the pipeline.
All parameters supplied need to already be present in the pipeline definition.
:param wait_for_completion: If true, this operator will only complete once the pipeline is complete.
:param check_interval: How long to wait between checks for pipeline status when waiting for completion.