Repository navigation
feat(mlops): Add run conditions to step dependencies #6475
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| # 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. | ||
| """Run conditions for step dependencies in SageMaker Pipelines.""" | ||
|
|
||
| from __future__ import absolute_import | ||
|
|
||
| from enum import Enum | ||
| from typing import Union, TYPE_CHECKING | ||
|
|
||
| from sagemaker.core.workflow.step_outputs import StepOutput, get_step | ||
|
|
||
| if TYPE_CHECKING: | ||
| from sagemaker.mlops.workflow.steps import Step | ||
|
|
||
|
|
||
| class TriggerCondition(Enum): | ||
| """Upstream step outcome that allows a dependent step to run.""" | ||
|
|
||
| COMPLETED = "Completed" | ||
| FAILED = "Failed" | ||
| STOPPED = "Stopped" | ||
| ANY = "Any" | ||
|
|
||
|
|
||
| class StepDependency: | ||
| """A `depends_on` entry that runs the dependent step on a chosen upstream outcome. | ||
|
|
||
| Plain entries in `depends_on` (a step or step name) keep their existing meaning: the | ||
| dependent step runs only after the upstream step completes. Wrap an entry in | ||
| `StepDependency` to run the dependent step when the upstream step fails, stops, or | ||
| reaches any terminal state, for example to send a notification when training fails: | ||
|
|
||
| .. code-block:: python | ||
|
|
||
| notify = LambdaStep( | ||
| name="NotifyOnFailure", | ||
| lambda_func=notify_lambda, | ||
| depends_on=[StepDependency(train, TriggerCondition.FAILED)], | ||
| ) | ||
|
|
||
| A pipeline whose steps run on a failed upstream step ends in the | ||
| `CompletedWithFailures` status instead of `Failed`. Run conditions are not supported | ||
| in local mode. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| step: Union[str, "Step", StepOutput], | ||
| trigger: TriggerCondition = TriggerCondition.COMPLETED, | ||
| ): | ||
| """Create a step dependency with a run condition. | ||
|
|
||
| Args: | ||
| step (Union[str, Step, StepOutput]): The upstream `Step`, its name, or a | ||
| `StepOutput` produced by it. | ||
| trigger (TriggerCondition): The upstream outcome that lets the dependent step | ||
| run (default: `TriggerCondition.COMPLETED`). | ||
| """ | ||
| if not isinstance(trigger, TriggerCondition): | ||
| raise TypeError(f"trigger must be a TriggerCondition, got {type(trigger).__name__}.") | ||
| self.step = get_step(step) if isinstance(step, StepOutput) else step | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Low: |
||
| self.trigger = trigger | ||
|
|
||
| @property | ||
| def step_name(self) -> str: | ||
| """The name of the upstream step.""" | ||
| return self.step if isinstance(self.step, str) else self.step.name | ||
|
|
||
| def to_request(self, step_name: str = None) -> Union[str, dict]: | ||
| """Get the `DependsOn` entry for this dependency. | ||
|
|
||
| A `COMPLETED` dependency is emitted as a plain step name, so definitions that do not | ||
| use run conditions are unchanged. | ||
| """ | ||
| name = step_name or self.step_name | ||
| if self.trigger == TriggerCondition.COMPLETED: | ||
| return name | ||
| return {"Step": name, "Trigger": self.trigger.value} | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| # 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. | ||
| """Integration test for run conditions (StepDependency triggers). | ||
|
|
||
| A Processing step fails on purpose. A step that depends on it with the Failed trigger | ||
| runs, and a step with a plain (Completed) dependency does not. | ||
| """ | ||
|
|
||
| from __future__ import absolute_import | ||
|
|
||
| import logging | ||
| import time | ||
| import uuid | ||
|
|
||
| from sagemaker.core import image_uris | ||
| from sagemaker.core.processing import Processor | ||
| from sagemaker.mlops.workflow import StepDependency, TriggerCondition | ||
| from sagemaker.mlops.workflow.pipeline import Pipeline | ||
| from sagemaker.mlops.workflow.steps import ProcessingStep | ||
|
|
||
|
|
||
| def _shell_step(name, command, image_uri, role, pipeline_session, depends_on=None): | ||
| processor = Processor( | ||
| role=role, | ||
| image_uri=image_uri, | ||
| instance_count=1, | ||
| instance_type="ml.m5.large", | ||
| entrypoint=["/bin/sh", "-c", command], | ||
| sagemaker_session=pipeline_session, | ||
| ) | ||
| return ProcessingStep(name=name, step_args=processor.run(), depends_on=depends_on) | ||
|
|
||
|
|
||
| def test_failed_trigger_runs_after_upstream_failure(pipeline_session, role, sklearn_latest_version): | ||
| stamp = uuid.uuid4().hex[:8] | ||
| image_uri = image_uris.retrieve( | ||
| framework="sklearn", | ||
| region=pipeline_session.boto_region_name, | ||
| version=sklearn_latest_version, | ||
| py_version="py3", | ||
| instance_type="ml.m5.large", | ||
| ) | ||
|
|
||
| work = _shell_step("Work", "exit 1", image_uri, role, pipeline_session) | ||
| on_failure = _shell_step( | ||
| "OnFailure", | ||
| "echo recovered", | ||
| image_uri, | ||
| role, | ||
| pipeline_session, | ||
| depends_on=[StepDependency(work, TriggerCondition.FAILED)], | ||
| ) | ||
| on_success = _shell_step( | ||
| "OnSuccess", "echo done", image_uri, role, pipeline_session, depends_on=[work] | ||
| ) | ||
| pipeline = Pipeline( | ||
| name=f"integ-run-conditions-{stamp}", | ||
| steps=[work, on_failure, on_success], | ||
| sagemaker_session=pipeline_session, | ||
| ) | ||
|
|
||
| try: | ||
| pipeline.upsert(role_arn=role) | ||
| execution = pipeline.start() | ||
|
|
||
| status = None | ||
| deadline = time.time() + 1800 | ||
| while time.time() < deadline: | ||
| status = execution.describe()["PipelineExecutionStatus"] | ||
| if status in ("Succeeded", "Failed", "Stopped", "CompletedWithFailures"): | ||
| break | ||
| time.sleep(30) | ||
|
|
||
| step_status = {s["StepName"]: s["StepStatus"] for s in execution.list_steps()} | ||
| assert status == "CompletedWithFailures", f"status={status}, steps={step_status}" | ||
| assert step_status["Work"] == "Failed" | ||
| assert step_status["OnFailure"] == "Succeeded" | ||
| assert "OnSuccess" not in step_status | ||
| finally: | ||
| try: | ||
| pipeline.delete() | ||
| except Exception as e: | ||
| logging.warning("Failed to delete pipeline %s: %s", pipeline.name, e) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Low:
_to_depends_on_requestcallsself._simplify_step_list([item])[0].nameonce per entry instep.depends_on, giving O(n^2) resolution over the dependency list. Dependency lists are small so this is not a real performance concern, but resolving names into thedependenciesmap in a single pass (and only once per unique item) would be a touch cleaner.