Skip to content

Commit 1f600a1

Browse files
Daniel Castronayan3107
authored andcommitted
feat(workflow): Support multi-step ForEach bodies
Remove the "exactly one body step" restriction so ForEach bodies can contain any number of steps. Each iteration spawns one child instance of every body step. Rename ChildOutput / ChildOutputs to IterationOutput / IterationOutputs across the public API. Property reference changes: - properties.IterationOutputs[i].<bodyStepName>.<member> now requires a body step name qualifier, since an iteration may span multiple body steps. - properties.Selected.<member> resolves directly to the selector- picked iteration's output — no body step name qualifier, because the selector's field already identifies the target body step.
1 parent 93a82e1 commit 1f600a1

3 files changed

Lines changed: 118 additions & 92 deletions

File tree

‎sagemaker-mlops/src/sagemaker/mlops/workflow/__init__.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
ForEachSelector,
5858
ForEachSelectorPickType,
5959
CurrentItem,
60-
ChildOutput,
60+
IterationOutput,
6161
)
6262
from sagemaker.mlops.workflow.lambda_step import LambdaStep, LambdaOutput
6363
from sagemaker.mlops.workflow.lineage_step import (
@@ -129,7 +129,7 @@
129129
"ForEachSelector",
130130
"ForEachSelectorPickType",
131131
"CurrentItem",
132-
"ChildOutput",
132+
"IterationOutput",
133133
"LambdaStep",
134134
"LambdaOutput",
135135
"LineageAssociation",

‎sagemaker-mlops/src/sagemaker/mlops/workflow/for_each_step.py‎

Lines changed: 60 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
MAX_CONCURRENCY_MIN = 1
2727
MAX_CONCURRENCY_MAX = 50
2828

29-
_CHILD_OUTPUT_NAMESPACE = "ChildOutput"
29+
_ITERATION_OUTPUT_NAMESPACE = "IterationOutput"
3030
_CURRENT_ITEM_PATH = "ForEach.CurrentItem"
3131

3232
# Step types that may not appear in a ForEachBody.
@@ -96,47 +96,49 @@ def __init__(self):
9696
super().__init__(_CURRENT_ITEM_PATH)
9797

9898

99-
class ChildOutput(_ForEachPropertyReference):
99+
class IterationOutput(_ForEachPropertyReference):
100100
"""Reference to a ForEach body step's output, for use in ``ForEachSelector.field``.
101101
102102
Valid ONLY as the ``field`` of a :class:`ForEachSelector`, and must target a
103103
body step of the same ForEach step, drilling at least one member deep::
104104
105-
ChildOutput(process_step).OutputParameters["InstanceCount"].expr
106-
# {"Get": "ChildOutput.ProcessItem.OutputParameters['InstanceCount']"}
105+
IterationOutput(process_step).OutputParameters["InstanceCount"].expr
106+
# {"Get": "IterationOutput.ProcessItem.OutputParameters['InstanceCount']"}
107107
108108
Args:
109109
body_step (Union[str, Step]): The body step (or its name) whose output
110-
the selector compares across children.
110+
the selector compares across iterations.
111111
"""
112112

113113
def __init__(self, body_step: Union[str, Step]):
114-
"""Initialize a ChildOutput reference rooted at the given body step."""
114+
"""Initialize an IterationOutput reference rooted at the given body step."""
115115
step_name = body_step.name if isinstance(body_step, Step) else body_step
116-
super().__init__(f"{_CHILD_OUTPUT_NAMESPACE}.{step_name}")
116+
super().__init__(f"{_ITERATION_OUTPUT_NAMESPACE}.{step_name}")
117117

118118

119-
class _ChildOutputsAccessor:
120-
"""Indexed accessor for a ForEach step's per-child outputs.
119+
class _IterationOutputsAccessor:
120+
"""Indexed accessor for a ForEach step's per-iteration outputs.
121121
122-
``ChildOutputs`` MUST be indexed (``properties.ChildOutputs[0].<member>``);
123-
a bare ``ChildOutputs.<member>`` reference is invalid, so this accessor is
124-
intentionally not a ``PipelineVariable`` itself.
122+
``IterationOutputs`` MUST be indexed (``properties.IterationOutputs[0].<bodyStepName>.<member>``);
123+
a bare ``IterationOutputs.<member>`` reference is invalid, so this accessor
124+
is intentionally not a ``PipelineVariable`` itself. The indexed reference
125+
must then be drilled by body step name, since a ForEach body may contain
126+
multiple steps.
125127
"""
126128

127129
def __init__(self, step: Step):
128-
"""Initialize a _ChildOutputsAccessor for the given ForEach step."""
130+
"""Initialize an _IterationOutputsAccessor for the given ForEach step."""
129131
self._step = step
130132

131133
def __getitem__(self, index: int) -> _ForEachPropertyReference:
132-
"""Get a drillable reference to the output of the child at ``index``."""
134+
"""Get a drillable reference to the outputs of the iteration at ``index``."""
133135
if not isinstance(index, int):
134136
raise TypeError(
135-
f"ChildOutputs of ForEach step '{self._step.name}' must be indexed "
136-
f"with an integer, e.g. properties.ChildOutputs[0]."
137+
f"IterationOutputs of ForEach step '{self._step.name}' must be indexed "
138+
f"with an integer, e.g. properties.IterationOutputs[0].<bodyStepName>."
137139
)
138140
return _ForEachPropertyReference(
139-
f"Steps.{self._step.name}.ChildOutputs[{index}]", [self._step]
141+
f"Steps.{self._step.name}.IterationOutputs[{index}]", [self._step]
140142
)
141143

142144

@@ -150,14 +152,17 @@ class ForEachSelectorPickType(Enum):
150152
class ForEachSelector:
151153
"""Selects a single child of a ForEach step by comparing a field across children.
152154
153-
The selected child's output is exposed to downstream steps via
154-
``Steps.<forEachName>.Selected.<member>``.
155+
The selected iteration's output is exposed to downstream steps via
156+
``Steps.<forEachName>.Selected.<member>`` — no body step name qualifier
157+
is required, because the selector's ``field`` already identifies which
158+
body step's output was compared.
155159
156160
Args:
157161
pick (Union[str, ForEachSelectorPickType]): The pick strategy,
158162
``"MaxBy"`` or ``"MinBy"``.
159-
field (ChildOutput): A ``ChildOutput`` reference targeting a body step
160-
of the same ForEach step, drilled at least one member deep.
163+
field (IterationOutput): An ``IterationOutput`` reference targeting a
164+
body step of the same ForEach step, drilled at least one member
165+
deep.
161166
"""
162167

163168
def __init__(
@@ -183,11 +188,11 @@ def __init__(
183188
f"got: {type(pick)}."
184189
)
185190
if field is None:
186-
raise ValueError("ForEachSelector requires 'field' (a ChildOutput reference).")
191+
raise ValueError("ForEachSelector requires 'field' (an IterationOutput reference).")
187192
if not isinstance(field, PipelineVariable):
188193
raise ValueError(
189-
"ForEachSelector 'field' must be a ChildOutput reference, e.g. "
190-
'ChildOutput(body_step).OutputParameters["MyOutput"], '
194+
"ForEachSelector 'field' must be an IterationOutput reference, e.g. "
195+
'IterationOutput(body_step).OutputParameters["MyOutput"], '
191196
f"got: {type(field)}."
192197
)
193198
self.pick = pick
@@ -205,19 +210,25 @@ class ForEachStep(Step):
205210
"""ForEach step for dynamic fan-out in SageMaker Pipelines Workflows.
206211
207212
A ForEach step takes a list of items (resolved at runtime), runs its body
208-
step once per item as child steps, enforces a concurrency cap, and exposes
209-
per-child outputs plus aggregate results to downstream steps.
210-
211-
Child steps get IDs of the form ``<bodyStepName>-<index>`` (e.g.
212-
``ProcessItem-0``). Because of this, body step names must be unique across
213-
all ForEach bodies in the pipeline, and no top-level step name may look
214-
like ``<bodyStepName>-<digits>`` — the service rejects such collisions.
215-
216-
Downstream steps can reference the parent step's properties:
217-
218-
- ``properties.ChildOutputs[i].<member>`` — per-child output (delegates to
219-
the body step's property schema; must be indexed)
220-
- ``properties.Selected.<member>`` — output of the selector-picked child
213+
step(s) once per item as child steps, enforces a concurrency cap, and
214+
exposes per-iteration outputs plus aggregate results to downstream steps.
215+
216+
A body may contain multiple steps; each item spawns one child instance of
217+
every body step. Child steps get IDs of the form ``<bodyStepName>-<index>``
218+
(e.g. ``ProcessItem-0``). Because of this, body step names must be unique
219+
across all ForEach bodies in the pipeline, and no top-level step name may
220+
look like ``<bodyStepName>-<digits>`` — the service rejects such
221+
collisions.
222+
223+
Downstream steps can reference the parent step's properties, drilling by
224+
body step name to reach a specific output:
225+
226+
- ``properties.IterationOutputs[i].<bodyStepName>.<member>`` — per-iteration
227+
output for a specific body step (must be indexed; body step name is
228+
required since the body may contain multiple steps)
229+
- ``properties.Selected.<member>`` — output of the selector-picked
230+
iteration (no body step name qualifier: the selector's ``field`` already
231+
identifies which body step's output was compared)
221232
"""
222233

223234
def __init__(
@@ -247,12 +258,13 @@ def __init__(
247258
max_concurrency (int): REQUIRED. The maximum number of child steps
248259
that run concurrently. Range: [1, 50].
249260
for_each_body (List[Step]): REQUIRED. The step(s) to run once per
250-
item. v1 supports exactly ONE body step; the list signature is
251-
future-proofing for multi-step bodies. Disallowed body step
252-
types: Condition, Fail, ForEach (no nesting). Body steps may
253-
reference the current item via :class:`CurrentItem`.
261+
item. May contain one or more body steps; each item spawns one
262+
child instance of every body step. Disallowed body step types:
263+
Condition, Fail, ForEach (no nesting). Body steps may reference
264+
the current item via :class:`CurrentItem`.
254265
selector (ForEachSelector): Optional selector that picks a single
255-
child by comparing a ``ChildOutput`` field across children.
266+
iteration by comparing an ``IterationOutput`` field across
267+
iterations.
256268
display_name (str): The display name of the `ForEachStep`.
257269
description (str): The description of the `ForEachStep`.
258270
depends_on (List[Union[str, Step]]): The list of `Step` names or
@@ -273,7 +285,7 @@ def __init__(
273285
self.selector = selector
274286

275287
root_prop = Properties(step_name=name)
276-
root_prop.__dict__["ChildOutputs"] = _ChildOutputsAccessor(self)
288+
root_prop.__dict__["IterationOutputs"] = _IterationOutputsAccessor(self)
277289
root_prop.__dict__["Selected"] = _ForEachPropertyReference(f"Steps.{name}.Selected", [self])
278290
self._properties = root_prop
279291

@@ -316,12 +328,6 @@ def _validate_for_each_body(name: str, for_each_body: Any):
316328
raise ValueError(
317329
f"ForEach step '{name}': for_each_body must be a non-empty list " f"of steps."
318330
)
319-
if len(for_each_body) != 1:
320-
raise ValueError(
321-
f"ForEach step '{name}': for_each_body currently supports exactly "
322-
f"one step; got {len(for_each_body)}. Multi-step bodies are not "
323-
f"yet supported by the service."
324-
)
325331
for body_step in for_each_body:
326332
if not isinstance(body_step, Step):
327333
raise ValueError(
@@ -348,12 +354,12 @@ def _validate_selector(
348354
f"instance. Got: {type(selector)}."
349355
)
350356
field_path = selector.field.expr.get("Get")
351-
prefix = f"{_CHILD_OUTPUT_NAMESPACE}."
357+
prefix = f"{_ITERATION_OUTPUT_NAMESPACE}."
352358
if not isinstance(field_path, str) or not field_path.startswith(prefix):
353359
raise ValueError(
354-
f"ForEach step '{name}': Selector.Field must be a ChildOutput "
355-
f"reference (e.g. ChildOutput(body_step).<member>); other "
356-
f"namespaces are constant across children. Got: {field_path}."
360+
f"ForEach step '{name}': Selector.Field must be an IterationOutput "
361+
f"reference (e.g. IterationOutput(body_step).<member>); other "
362+
f"namespaces are constant across iterations. Got: {field_path}."
357363
)
358364
remainder = field_path[len(prefix) :]
359365
match = re.match(r"^([^.\[\]]+)(.+)$", remainder)
@@ -392,6 +398,6 @@ def step_only_arguments(self) -> RequestType:
392398
def properties(self):
393399
"""A Properties object exposing the ForEach step's results.
394400
395-
Members: ``ChildOutputs[i]`` and ``Selected``.
401+
Members: ``IterationOutputs[i].<bodyStepName>`` and ``Selected``.
396402
"""
397403
return self._properties

0 commit comments

Comments
 (0)