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
Open
nayan3107
wants to merge
1
commit into
aws:master
Choose a base branch
from
nayan3107:feat/run-conditions
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+407
−3
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
88 changes: 88 additions & 0 deletions
88
sagemaker-mlops/src/sagemaker/mlops/workflow/step_dependency.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| 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} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
93 changes: 93 additions & 0 deletions
93
sagemaker-mlops/tests/integ/workflow/test_run_conditions.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Can we make sure we have unit tests for all possible combinations here of mixed StepDependency + str and pure types? I think some cases are not raising "conflicting triggers" when they should
depends_on=DependsOn["A"]['A'][a]['A'][a, "A"]['A'][SD(a)]['A'][SD(a, COMPLETED)]['A'][SD(a, FAILED)][{'Step':'A','Trigger':'Failed'}][SD(a, ANY)][{'Step':'A','Trigger':'Any'}][SD(a,COMPLETED), SD(a,FAILED)][SD(a,FAILED), SD("A",FAILED)][{'Step':'A','Trigger':'Failed'}]["A", SD(a,FAILED)][{'Step':'A','Trigger':'Failed'}][a, SD(a,FAILED)][{'Step':'A','Trigger':'Failed'}][SD(a,FAILED), "A"][{'Step':'A','Trigger':'Failed'}]