|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). You |
| 4 | +# may not use this file except in compliance with the License. A copy of |
| 5 | +# the License is located at |
| 6 | +# |
| 7 | +# http://aws.amazon.com/apache2.0/ |
| 8 | +# |
| 9 | +# or in the "license" file accompanying this file. This file is |
| 10 | +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF |
| 11 | +# ANY KIND, either express or implied. See the License for the specific |
| 12 | +# language governing permissions and limitations under the License. |
| 13 | +"""The `AutoMLStep` definition for SageMaker Pipelines Workflows""" |
| 14 | +from __future__ import absolute_import |
| 15 | + |
| 16 | +from typing import Union, Optional, List |
| 17 | + |
| 18 | +from sagemaker import Session, Model |
| 19 | +from sagemaker.exceptions import AutoMLStepInvalidModeError |
| 20 | +from sagemaker.workflow.entities import RequestType |
| 21 | + |
| 22 | +from sagemaker.workflow.pipeline_context import _JobStepArguments |
| 23 | +from sagemaker.workflow.properties import Properties |
| 24 | +from sagemaker.workflow.retry import RetryPolicy |
| 25 | +from sagemaker.workflow.steps import ConfigurableRetryStep, CacheConfig, Step, StepTypeEnum |
| 26 | +from sagemaker.workflow.utilities import validate_step_args_input |
| 27 | +from sagemaker.workflow.step_collections import StepCollection |
| 28 | + |
| 29 | + |
| 30 | +class AutoMLStep(ConfigurableRetryStep): |
| 31 | + """`AutoMLStep` for SageMaker Pipelines Workflows.""" |
| 32 | + |
| 33 | + def __init__( |
| 34 | + self, |
| 35 | + name: str, |
| 36 | + step_args: _JobStepArguments, |
| 37 | + display_name: str = None, |
| 38 | + description: str = None, |
| 39 | + cache_config: CacheConfig = None, |
| 40 | + depends_on: Optional[List[Union[str, Step, StepCollection]]] = None, |
| 41 | + retry_policies: List[RetryPolicy] = None, |
| 42 | + ): |
| 43 | + """Construct a `AutoMLStep`, given a `AutoML` instance. |
| 44 | +
|
| 45 | + In addition to the `AutoML` instance, the other arguments are those |
| 46 | + that are supplied to the `fit` method of the `sagemaker.automl.automl.AutoML`. |
| 47 | +
|
| 48 | + Args: |
| 49 | + name (str): The name of the `AutoMLStep`. |
| 50 | + step_args (_JobStepArguments): The arguments for the `AutoMLStep` definition. |
| 51 | + display_name (str): The display name of the `AutoMLStep`. |
| 52 | + description (str): The description of the `AutoMLStep`. |
| 53 | + cache_config (CacheConfig): A `sagemaker.workflow.steps.CacheConfig` instance. |
| 54 | + depends_on (List[Union[str, Step, StepCollection]]): A list of `Step`/`StepCollection` |
| 55 | + names or `Step` instances or `StepCollection` instances that this `AutoMLStep` |
| 56 | + depends on. |
| 57 | + retry_policies (List[RetryPolicy]): A list of retry policies. |
| 58 | + """ |
| 59 | + super(AutoMLStep, self).__init__( |
| 60 | + name, StepTypeEnum.AUTOML, display_name, description, depends_on, retry_policies |
| 61 | + ) |
| 62 | + |
| 63 | + validate_step_args_input( |
| 64 | + step_args=step_args, |
| 65 | + expected_caller={Session.auto_ml.__name__}, |
| 66 | + error_message="The step_args of AutoMLStep must be obtained " "from automl.fit().", |
| 67 | + ) |
| 68 | + |
| 69 | + self.step_args = step_args.args |
| 70 | + self.cache_config = cache_config |
| 71 | + |
| 72 | + root_property = Properties(step_name=name, shape_name="DescribeAutoMLJobResponse") |
| 73 | + |
| 74 | + best_candidate_properties = Properties(step_name=name, path="bestCandidateProperties") |
| 75 | + best_candidate_properties.__dict__["modelInsightsJsonReportPath"] = Properties( |
| 76 | + step_name=name, path="bestCandidateProperties.modelInsightsJsonReportPath" |
| 77 | + ) |
| 78 | + best_candidate_properties.__dict__["explainabilityJsonReportPath"] = Properties( |
| 79 | + step_name=name, path="bestCandidateProperties.explainabilityJsonReportPath" |
| 80 | + ) |
| 81 | + |
| 82 | + root_property.__dict__["bestCandidateProperties"] = best_candidate_properties |
| 83 | + self._properties = root_property |
| 84 | + |
| 85 | + @property |
| 86 | + def arguments(self) -> RequestType: |
| 87 | + """The arguments dictionary that is used to call `create_auto_ml_job`. |
| 88 | +
|
| 89 | + NOTE: The `CreateAutoMLJob` request is not quite the |
| 90 | + args list that workflow needs. |
| 91 | +
|
| 92 | + The `AutoMLJobName`, `ModelDeployConfig` and `GenerateCandidateDefinitionsOnly` |
| 93 | + attribute cannot be included. |
| 94 | + """ |
| 95 | + request_dict = self.step_args |
| 96 | + if "AutoMLJobConfig" not in request_dict: |
| 97 | + raise AutoMLStepInvalidModeError() |
| 98 | + if ( |
| 99 | + "Mode" not in request_dict["AutoMLJobConfig"] |
| 100 | + or request_dict["AutoMLJobConfig"]["Mode"] != "ENSEMBLING" |
| 101 | + ): |
| 102 | + raise AutoMLStepInvalidModeError() |
| 103 | + |
| 104 | + if "ModelDeployConfig" in request_dict: |
| 105 | + request_dict.pop("ModelDeployConfig", None) |
| 106 | + if "GenerateCandidateDefinitionsOnly" in request_dict: |
| 107 | + request_dict.pop("GenerateCandidateDefinitionsOnly", None) |
| 108 | + request_dict.pop("AutoMLJobName", None) |
| 109 | + return request_dict |
| 110 | + |
| 111 | + @property |
| 112 | + def properties(self): |
| 113 | + """A `Properties` object representing the `DescribeAutoMLJobResponse` data model.""" |
| 114 | + return self._properties |
| 115 | + |
| 116 | + def to_request(self) -> RequestType: |
| 117 | + """Updates the dictionary with cache configuration.""" |
| 118 | + request_dict = super().to_request() |
| 119 | + if self.cache_config: |
| 120 | + request_dict.update(self.cache_config.config) |
| 121 | + |
| 122 | + return request_dict |
| 123 | + |
| 124 | + def get_best_auto_ml_model(self, role, sagemaker_session=None): |
| 125 | + """Get the best candidate model artifacts, image uri and env variables for the best model. |
| 126 | +
|
| 127 | + Args: |
| 128 | + role (str): An AWS IAM role (either name or full ARN). The Amazon |
| 129 | + SageMaker AutoML jobs and APIs that create Amazon SageMaker |
| 130 | + endpoints use this role to access training data and model |
| 131 | + artifacts. |
| 132 | + sagemaker_session (sagemaker.session.Session): A SageMaker Session |
| 133 | + object, used for SageMaker interactions. |
| 134 | + If the best model will be used as part of ModelStep, then sagemaker_session |
| 135 | + should be class:`~sagemaker.workflow.pipeline_context.PipelineSession`. Example:: |
| 136 | + model = Model(sagemaker_session=PipelineSession()) |
| 137 | + model_step = ModelStep(step_args=model.register()) |
| 138 | + """ |
| 139 | + inference_container = self.properties.BestCandidate.InferenceContainers[0] |
| 140 | + inference_container_environment = inference_container.Environment |
| 141 | + image = inference_container.Image |
| 142 | + model_data = inference_container.ModelDataUrl |
| 143 | + model = Model( |
| 144 | + image_uri=image, |
| 145 | + model_data=model_data, |
| 146 | + env={ |
| 147 | + "MODEL_NAME": inference_container_environment["MODEL_NAME"], |
| 148 | + "SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": inference_container_environment[ |
| 149 | + "SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT" |
| 150 | + ], |
| 151 | + "SAGEMAKER_SUBMIT_DIRECTORY": inference_container_environment[ |
| 152 | + "SAGEMAKER_SUBMIT_DIRECTORY" |
| 153 | + ], |
| 154 | + "SAGEMAKER_INFERENCE_SUPPORTED": inference_container_environment[ |
| 155 | + "SAGEMAKER_INFERENCE_SUPPORTED" |
| 156 | + ], |
| 157 | + "SAGEMAKER_INFERENCE_OUTPUT": inference_container_environment[ |
| 158 | + "SAGEMAKER_INFERENCE_OUTPUT" |
| 159 | + ], |
| 160 | + "SAGEMAKER_PROGRAM": inference_container_environment["SAGEMAKER_PROGRAM"], |
| 161 | + }, |
| 162 | + sagemaker_session=sagemaker_session, |
| 163 | + role=role, |
| 164 | + ) |
| 165 | + |
| 166 | + return model |
0 commit comments