

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Pipelines 步驟
<a name="build-and-manage-steps"></a>

Pipelines 由步驟組成。這些步驟使用屬性定義管道採取的動作以及步驟之間的關係。下頁描述步驟的類型、其屬性，以及它們之間的關係。

**Topics**
+ [新增步驟](build-and-manage-steps-types.md)
+ [新增整合](build-and-manage-steps-integration.md)
+ [步驟屬性](#build-and-manage-properties)
+ [步驟平行處理](#build-and-manage-parallelism)
+ [步驟之間的資料相依性](#build-and-manage-data-dependency)
+ [步驟之間的自訂相依性](#build-and-manage-custom-dependency)
+ [步驟中的自訂映像](#build-and-manage-images)

# 新增步驟
<a name="build-and-manage-steps-types"></a>

下文描述每個步驟類型的要求，並提供步驟的範例實作，以及如何將步驟新增至 Pipelines。這些不是有效的實作，因為它們不提供所需的資源和輸入。有關實現這些步驟的教學課程，請參閱[Pipelines 動作](pipelines-build.md)。

**注意**  
您也可以從本機機器學習程式碼建立步驟，方法是使用 `@step` 裝飾項目將其轉換為 Pipelines 步驟。如需詳細資訊，請參閱[@step 裝飾項目](#step-type-custom)。

Amazon SageMaker Pipelines 支援下列步驟類型：
+ [執行程式碼](#step-type-executecode)

  [處理](#step-type-processing)
+ [培訓](#step-type-training)
+ [調校](#step-type-tuning)
+ [AutoML](#step-type-automl)
+ [`Model`](#step-type-model)
+ [`Create model`](#step-type-create-model)
+ [`Register model`](#step-type-register-model)
+ [`Deploy model (endpoint)`](#step-type-deploy-model-endpoint)
+ [轉換](#step-type-transform)
+ [條件](#step-type-condition)
+ [`Callback`](#step-type-callback)
+ [Lambda](#step-type-lambda)
+ [`ClarifyCheck`](#step-type-clarify-check)
+ [`QualityCheck`](#step-type-quality-check)
+ [EMR](#step-type-emr)
+ [筆記本任務](#step-type-notebook-job)
+ [失敗](#step-type-fail)

## @step 裝飾項目
<a name="step-type-custom"></a>

如果您想要在drag-and-drop管道 UI 中協調利用進階 SageMaker AI 功能或其他 AWS 服務的自訂 ML 任務，請使用 [執行程式碼步驟](#step-type-executecode)。

您可以使用 `@step` 裝飾項目從本機機器學習程式碼建立步驟。測試您的程式碼後，您可以透過使用 `@step` 裝飾項目註釋函數，將該函數轉換為 SageMaker AI 管道步驟。當您將 `@step` 裝飾函數的輸出作為步驟傳遞至管道時，Pipelines 會建立並執行管道。您也可以建立多步驟 DAG 管道，其中包含一或多個 `@step` 裝飾函數，以及傳統 SageMaker AI 管道步驟。如需如何使用 `@step` 裝飾項目建立步驟的詳細資訊，請參閱[使用 @step 裝飾項目直接移轉程式碼](pipelines-step-decorator.md)。

## 執行程式碼步驟
<a name="step-type-executecode"></a>

在 Pipelines 拖放 UI 中，您可以使用**執行程式碼**步驟，將您自己的程式碼作為管道步驟執行。您可以上傳 Python 函數、指令碼或筆記本，作為管道的一部分執行。如果您想要協調利用進階 SageMaker AI 功能或其他 AWS 服務的自訂 ML 任務，您應該使用此步驟。

**執行程式碼**步驟會將檔案上傳至 Amazon SageMaker AI 的預設 Amazon S3 儲存貯體。此儲存貯體可能未設定必要的跨來源資源共用 (CORS) 許可。若要進一步了解如何設定 CORS 許可，請參閱[輸入影像資料的 CORS 要求](sms-cors-update.md)。

**執行程式碼**步驟會使用 Amazon SageMaker 訓練任務來執行您的程式碼。確保您的 IAM 角色具有 `sagemaker:DescribeTrainingJob` 和 `sagemaker:CreateTrainingJob` API 許可。若要進一步了解 Amazon SageMaker AI 的所有必要許可，以及如何設定這些許可，請參閱 [Amazon SageMaker AI API 許可：動作、許可與資源參考](api-permissions-reference.md)。

若要使用管道設計工具將執行程式碼步驟新增至管道，請執行下列動作：

1. 遵循 [啟動 Amazon SageMaker Studio](studio-updated-launch.md) 中的指示開啟 Amazon SageMaker Studio 主控台。

1. 在左側導覽窗格中，選取**管道**。

1. 選擇**建立**。

1. 選擇**空白**。

1. 在左側邊欄中，選擇**執行程式碼**並將其拖曳至畫布。

1. 在畫布中，選擇您已新增的**執行程式碼**步驟。

1. 在右側邊欄中，完成**設定**和**詳細資訊**索引標籤中的表單。

1. 您可以上傳單一檔案，以執行或上傳包含多個成品的壓縮資料夾。

1. 對於單一檔案上傳，您可以為筆記本、python 函數或指令碼提供選用參數。

1. 提供 Python 函數時，必須以格式 `file.py:<function_name>` 提供處理常式

1. 對於壓縮資料夾上傳，必須提供程式碼的相對路徑，而且您可以選擇性地在壓縮資料夾內提供 `requirements.txt` 檔案或初始化指令碼的路徑。

1. 如果畫布包含緊接在您已新增之**執行程式碼**步驟之前的任何步驟，請按一下游標，然後將其從該步驟拖曳到**執行程式碼**步驟以建立邊緣。

1. 如果畫布包含緊接在您已新增之**執行程式碼**步驟之後的任何步驟，請按一下游標，然後將其從**執行程式碼**步驟拖曳到該步驟以建立邊緣。Python 函數可以參考**執行程式碼**步驟的輸出。

## 處理步驟
<a name="step-type-processing"></a>

使用處理步驟建立用於資料處理的處理任務。如需有關處理工作的詳細資訊，請參閱[處理資料和評估模型](https://docs.aws.amazon.com/sagemaker/latest/dg/processing-job.html)。

------
#### [ Pipeline Designer ]

若要使用管道設計工具將處理步驟新增至管道，請執行下列動作：

1. 遵循 [啟動 Amazon SageMaker Studio](studio-updated-launch.md) 中的指示開啟 Amazon SageMaker Studio 主控台。

1. 在左側導覽窗格中，選取**管道**。

1. 選擇**建立**。

1. 在左側邊欄中，選擇**處理資料**並將其拖曳至畫布。

1. 在畫布中，選擇您新增的**處理資料**步驟。

1. 在右側邊欄中，完成**設定**和**詳細資訊**索引標籤中的表單。如需這些標籤中欄位的相關資訊，請參閱 [sagemaker.workflow.steps.ProcessingStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.steps.ProcessingStep)。

1. 如果畫布包含緊接在您已新增之**處理資料**步驟之前的任何步驟，請按一下游標，然後將其從步驟拖曳到**處理資料**步驟以建立邊緣。

1. 如果畫布包含緊接在您已新增之**處理資料**步驟之後的任何步驟，請按一下游標，然後將其從**處理資料**步驟拖曳到該步驟以建立邊緣。

------
#### [ SageMaker Python SDK ]

處理步驟需要處理器、定義處理程式碼的 Python 指令碼、處理輸出以及任務引數。下列範例示範如何建立 `ProcessingStep` 定義。

```
from sagemaker.sklearn.processing import SKLearnProcessor

sklearn_processor = SKLearnProcessor(framework_version='1.0-1',
                                     role=<role>,
                                     instance_type='ml.m5.xlarge',
                                     instance_count=1)
```

```
from sagemaker.processing import ProcessingInput, ProcessingOutput
from sagemaker.workflow.steps import ProcessingStep

inputs = [
    ProcessingInput(source=<input_data>, destination="/opt/ml/processing/input"),
]

outputs = [
    ProcessingOutput(output_name="train", source="/opt/ml/processing/train"),
    ProcessingOutput(output_name="validation", source="/opt/ml/processing/validation"),
    ProcessingOutput(output_name="test", source="/opt/ml/processing/test")
]

step_process = ProcessingStep(
    name="AbaloneProcess",
    step_args = sklearn_processor.run(inputs=inputs, outputs=outputs,
        code="abalone/preprocessing.py")
)
```

**傳遞執行期參數**

下列範例示範如何將執行期參數從 PySpark 處理器傳遞給 `ProcessingStep`。

```
from sagemaker.workflow.pipeline_context import PipelineSession
from sagemaker.spark.processing import PySparkProcessor
from sagemaker.processing import ProcessingInput, ProcessingOutput
from sagemaker.workflow.steps import ProcessingStep

pipeline_session = PipelineSession()

pyspark_processor = PySparkProcessor(
    framework_version='2.4',
    role=<role>,
    instance_type='ml.m5.xlarge',
    instance_count=1,
    sagemaker_session=pipeline_session,
)

step_args = pyspark_processor.run(
    inputs=[ProcessingInput(source=<input_data>, destination="/opt/ml/processing/input"),],
    outputs=[
        ProcessingOutput(output_name="train", source="/opt/ml/processing/train"),
        ProcessingOutput(output_name="validation", source="/opt/ml/processing/validation"),
        ProcessingOutput(output_name="test", source="/opt/ml/processing/test")
    ],
    code="preprocess.py",
    arguments=None,
)


step_process = ProcessingStep(
    name="AbaloneProcess",
    step_args=step_args,
)
```

如需有關處理步驟要求的詳細資訊，請參閱 [sagemaker.workflow.steps.ProcessingStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.steps.ProcessingStep) 文件。如需深入範例，請參閱[協調任務以使用 Amazon SageMaker Pipelines 訓練和評估模型](https://github.com/aws/amazon-sagemaker-examples/blob/62de6a1fca74c7e70089d77e36f1356033adbe5f/sagemaker-pipelines/tabular/abalone_build_train_deploy/sagemaker-pipelines-preprocess-train-evaluate-batch-transform.ipynb)範例筆記本。*定義特徵工程的處理步驟*一節包含詳細資訊。

------

## 訓練步驟
<a name="step-type-training"></a>

您使用訓練步驟建立訓練任務來訓練模型。如需訓練任務的詳細資訊，請參閱[使用 Amazon SageMaker AI 訓練模型](https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-training.html)。

訓練步驟需要估算器以及訓練和驗證資料輸入。

------
#### [ Pipeline Designer ]

若要使用管道設計工具將訓練步驟新增至管道，請執行下列動作：

1. 遵循 [啟動 Amazon SageMaker Studio](studio-updated-launch.md) 中的指示開啟 Amazon SageMaker Studio 主控台。

1. 在左側導覽窗格中，選取**管道**。

1. 選擇**建立**。

1. 選擇**空白**。

1. 在左側邊欄中，選擇**訓練模型**並將其拖曳至畫布。

1. 在畫布中，選擇您新增的**訓練模型**步驟。

1. 在右側邊欄中，完成**設定**和**詳細資訊**索引標籤中的表單。如需這些標籤中欄位的相關資訊，請參閱 [sagemaker.workflow.steps.TrainingStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.steps.TrainingStep)。

1. 如果畫布包含緊接在您已新增之**訓練模型**步驟之前的任何步驟，請按一下游標，然後將其從該步驟拖曳到**訓練模型**步驟以建立邊緣。

1. 如果畫布包含緊接在您已新增之**訓練模型**步驟之後的任何步驟，請按一下游標，然後將其從**訓練模型**步驟拖曳到該步驟以建立邊緣。

------
#### [ SageMaker Python SDK ]

下列範例示範如何建立 `TrainingStep` 定義。如需訓練步驟要求的詳細資訊，請參閱 [sagemaker.workflow.steps.TrainingStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.steps.TrainingStep) 文件。

```
from sagemaker.workflow.pipeline_context import PipelineSession

from sagemaker.inputs import TrainingInput
from sagemaker.workflow.steps import TrainingStep

from sagemaker.xgboost.estimator import XGBoost

pipeline_session = PipelineSession()

xgb_estimator = XGBoost(..., sagemaker_session=pipeline_session)

step_args = xgb_estimator.fit(
    inputs={
        "train": TrainingInput(
            s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
                "train"
            ].S3Output.S3Uri,
            content_type="text/csv"
        ),
        "validation": TrainingInput(
            s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
                "validation"
            ].S3Output.S3Uri,
            content_type="text/csv"
        )
    }
)

step_train = TrainingStep(
    name="TrainAbaloneModel",
    step_args=step_args,
)
```

------

## 調校步驟
<a name="step-type-tuning"></a>

您可以使用調校步驟來建立超參數調校任務，也稱為超參數最佳化 (HPO)。超參數調校任務會執行多個訓練任務，每個任務都會產生一個模型版本。如需有關超參數調校的詳細資訊，請參閱[使用 SageMaker AI 執行自動模型調校](automatic-model-tuning.md)。

調校任務與管道的 SageMaker AI 實驗相關聯，並以試驗的形式建立訓練任務。如需詳細資訊，請參閱[Experiments 整合](pipelines-experiments.md)。

調校步驟需要 [HyperparameterTuner](https://sagemaker.readthedocs.io/en/stable/api/training/tuner.html) 和訓練輸入。您可以指定 `HyperparameterTuner` 之 `warm_start_config` 參數來重新訓練先前的調校任務。如需有關超參數調整和熱啟動的詳細資訊，請參閱[執行超參數調校任務的暖啟動](automatic-model-tuning-warm-start.md)。

您使用 [sagemaker.workflow.steps.TuningStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.steps.TuningStep) 類別的 [get\$1top\$1model\$1s3\$1uri](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.steps.TuningStep.get_top_model_s3_uri) 方法，從效能最佳的模型版本之一取得模型成品。如需顯示如何在 SageMaker AI 管道中使用調校步驟的筆記本，請參閱 [sagemaker-pipelines-tuning-step.ipynb](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-pipelines/tabular/tuning-step/sagemaker-pipelines-tuning-step.ipynb)。

**重要**  
Amazon SageMaker Python SDK v2.48.0 和 Amazon SageMaker Studio Classic v3.8.0 中引入了調校步驟。您必須先更新 Studio Classic，才能使用調校步驟，否則管道 DAG 不會顯示。若要更新 Studio Classic，請參閱[關閉並更新 Amazon SageMaker Studio Classic](studio-tasks-update-studio.md)。

下列範例示範如何建立 `TuningStep` 定義。

```
from sagemaker.workflow.pipeline_context import PipelineSession

from sagemaker.tuner import HyperparameterTuner
from sagemaker.inputs import TrainingInput
from sagemaker.workflow.steps import TuningStep

tuner = HyperparameterTuner(..., sagemaker_session=PipelineSession())
    
step_tuning = TuningStep(
    name = "HPTuning",
    step_args = tuner.fit(inputs=TrainingInput(s3_data="s3://amzn-s3-demo-bucket/my-data"))
)
```

**取得最佳模型版本**

下列範例示範如何使用 `get_top_model_s3_uri` 方法從調校任務取得最佳模型版本。根據 [HyperParameterTuningJobObjective](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_HyperParameterTuningJobObjective.html)，最多提供效能排名前 50 的版本。`top_k` 引數是版本的索引，其中 `top_k=0` 是效能最佳的版本，而 `top_k=49` 是效能最差的版本。

```
best_model = Model(
    image_uri=image_uri,
    model_data=step_tuning.get_top_model_s3_uri(
        top_k=0,
        s3_bucket=sagemaker_session.default_bucket()
    ),
    ...
)
```

如需有關調整步驟要求的詳細資訊，請參閱 [sagemaker.workflow.steps.TuningStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.steps.TuningStep) 文件。

## 微調步驟
<a name="step-type-fine-tuning"></a>

微調會在新資料集上，從 Amazon SageMaker JumpStart 訓練預先訓練的基礎模型。這個程序也稱為移轉學習，可以利用較小的資料集和較短的訓練時間來產生精確的模型。微調模型時，您可以使用預設資料集或選擇自己的資料。若要進一步了解如何從 JumpStart 微調基礎模型，請參閱[微調模型](jumpstart-fine-tune.md)。

微調步驟使用 Amazon SageMaker 訓練任務來自訂您的模型。確保您的 IAM 角色具有在您管道中執行微調任務的 `sagemaker:DescribeTrainingJob` 和 `sagemaker:CreateTrainingJob` API 許可。若要進一步了解 Amazon SageMaker AI 的必要許可，以及如何設定這些許可，請參閱 [Amazon SageMaker AI API 許可：動作、許可與資源參考](api-permissions-reference.md)。

若要使用拖放編輯器將**微調模型**步驟新增至您的管道，請遵循下列步驟：

1. 遵循 [啟動 Amazon SageMaker Studio](studio-updated-launch.md) 中的指示開啟 Studio 主控台。

1. 在左側導覽窗格中，選取**管道**。

1. 選擇**建立**。

1. 選擇**空白**。

1. 在左側邊欄中，選擇**微調模型**並將其拖曳至畫布。

1. 在畫布中，選擇您已新增的**微調模型**步驟。

1. 在右側邊欄中，完成**設定**和**詳細資訊**索引標籤中的表單。

1. 如果畫布包含緊接在您已新增之**微調模型**步驟之前的任何步驟，請按一下游標，然後將其從該步驟拖曳到**微調模型**步驟以建立邊緣。

1. 如果畫布包含緊接在您已新增之**微調模型**步驟之後的任何步驟，請按一下游標，然後將其從**微調模型**步驟拖曳到該步驟以建立邊緣。

## AutoML 步驟
<a name="step-type-automl"></a>

使用 [AutoML](https://sagemaker.readthedocs.io/en/stable/api/training/automl.html) API 建立 AutoML 任務以自動訓練模型。如需有關 AutoML 任務的詳細資訊，請參閱[使用 Amazon SageMaker Autopilot 將模型開發自動化](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-automate-model-development.html)。

**注意**  
目前，AutoML 步驟僅支援[集成訓練模式](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-model-support-validation.html)。

下列範例示範如何使用 `AutoMLStep` 建立定義。

```
from sagemaker.workflow.pipeline_context import PipelineSession
from sagemaker.workflow.automl_step import AutoMLStep

pipeline_session = PipelineSession()

auto_ml = AutoML(...,
    role="<role>",
    target_attribute_name="my_target_attribute_name",
    mode="ENSEMBLING",
    sagemaker_session=pipeline_session) 

input_training = AutoMLInput(
    inputs="s3://amzn-s3-demo-bucket/my-training-data",
    target_attribute_name="my_target_attribute_name",
    channel_type="training",
)
input_validation = AutoMLInput(
    inputs="s3://amzn-s3-demo-bucket/my-validation-data",
    target_attribute_name="my_target_attribute_name",
    channel_type="validation",
)

step_args = auto_ml.fit(
    inputs=[input_training, input_validation]
)

step_automl = AutoMLStep(
    name="AutoMLStep",
    step_args=step_args,
)
```

**取得最佳模型版本**

AutoML 步驟會自動訓練多個候選模型。使用 `get_best_auto_ml_model` 方法從 AutoML 任務取得具有最佳目標指標的模型，如下所示。您亦須使用 IAM `role` 來存取模型成品。

```
best_model = step_automl.get_best_auto_ml_model(role=<role>)
```

如需詳細資訊，請參閱 SageMaker Python SDK 中的 [AutoML](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.automl_step.AutoMLStep) 步驟。

## 模型步驟
<a name="step-type-model"></a>

使用 `ModelStep` 建立或註冊 SageMaker AI 模型。如需有關 `ModelStep` 要求的更多資訊，請參閱 [sagemaker.workflow.model\$1step.ModelStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.model_step.ModelStep) 文件。

### 建立模型
<a name="step-type-model-create"></a>

您可以使用 `ModelStep` 建立 SageMaker AI 模型。`ModelStep` 需要模型成品以及您用來建立模型所需之 SageMaker AI 執行個體的相關資訊。如需 SageMaker AI 模型的詳細資訊，請參閱[使用 Amazon SageMaker AI 訓練模型](https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-training.html)。

下列範例示範如何建立 `ModelStep` 定義。

```
from sagemaker.workflow.pipeline_context import PipelineSession
from sagemaker.model import Model
from sagemaker.workflow.model_step import ModelStep

step_train = TrainingStep(...)
model = Model(
    image_uri=pytorch_estimator.training_image_uri(),
    model_data=step_train.properties.ModelArtifacts.S3ModelArtifacts,
    sagemaker_session=PipelineSession(),
    role=role,
)

step_model_create = ModelStep(
   name="MyModelCreationStep",
   step_args=model.create(instance_type="ml.m5.xlarge"),
)
```

### 註冊模型
<a name="step-type-model-register"></a>

您可以使用 `ModelStep` 搭配 Amazon SageMaker 模型註冊表註冊 `sagemaker.model.Model` 或 `sagemaker.pipeline.PipelineModel`。`PipelineModel` 表示推論管道，是一種由直線順序容器構成的模型，可處理推論請求。如需有關如何註冊模型的詳細資訊，請參閱[使用模型註冊庫進行模型註冊部署](model-registry.md)。

下列範例示範如何建立註冊 `PipelineModel` 所需的 `ModelStep`。

```
import time

from sagemaker.workflow.pipeline_context import PipelineSession
from sagemaker.sklearn import SKLearnModel
from sagemaker.xgboost import XGBoostModel

pipeline_session = PipelineSession()

code_location = 's3://{0}/{1}/code'.format(bucket_name, prefix)

sklearn_model = SKLearnModel(
   model_data=processing_step.properties.ProcessingOutputConfig.Outputs['model'].S3Output.S3Uri,
   entry_point='inference.py',
   source_dir='sklearn_source_dir/',
   code_location=code_location,
   framework_version='1.0-1',
   role=role,
   sagemaker_session=pipeline_session,
   py_version='py3'
)

xgboost_model = XGBoostModel(
   model_data=training_step.properties.ModelArtifacts.S3ModelArtifacts,
   entry_point='inference.py',
   source_dir='xgboost_source_dir/',
   code_location=code_location,
   framework_version='0.90-2',
   py_version='py3',
   sagemaker_session=pipeline_session,
   role=role
)

from sagemaker.workflow.model_step import ModelStep
from sagemaker import PipelineModel

pipeline_model = PipelineModel(
   models=[sklearn_model, xgboost_model],
   role=role,sagemaker_session=pipeline_session,
)

register_model_step_args = pipeline_model.register(
    content_types=["application/json"],
   response_types=["application/json"],
   inference_instances=["ml.t2.medium", "ml.m5.xlarge"],
   transform_instances=["ml.m5.xlarge"],
   model_package_group_name='sipgroup',
)

step_model_registration = ModelStep(
   name="AbaloneRegisterModel",
   step_args=register_model_step_args,
)
```

## 建立模型步驟
<a name="step-type-create-model"></a>

您可以使用建立模型步驟建立 SageMaker AI 模型。如需 SageMaker AI 模型的詳細資訊，請參閱[使用 Amazon SageMaker 訓練模型](how-it-works-training.md)。

建立模型步驟需要模型成品以及您用來建立模型所需之 SageMaker AI 執行個體的相關資訊。下列範例展示如何建立一個建立模型步驟定義。如需建立模型步驟要求的詳細資訊，請參閱 [sagemaker.workflow.steps.CreateModelStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.steps.CreateModelStep) 文件。

------
#### [ Pipeline Designer ]

若要將建立模型步驟新增至您的管道，請執行下列動作：

1. 遵循 [啟動 Amazon SageMaker Studio](studio-updated-launch.md) 中的指示開啟 Studio 主控台。

1. 在左側導覽窗格中，選取**管道**。

1. 選擇**建立**。

1. 選擇**空白**。

1. 在左側邊欄中，選擇**建立模型**並將其拖曳至畫布。

1. 在畫布中，選擇您已新增的**建立模型**步驟。

1. 在右側邊欄中，完成**設定**和**詳細資訊**索引標籤中的表單。如需這些索引標籤中欄位的相關資訊，請參閱 [sagemaker.workflow.steps.CreateModelStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.steps.CreateModelStep)。

1. 如果畫布包含緊接在您已新增之**建立模型**步驟之前的任何步驟，請按一下游標，然後將其從該步驟拖曳到**建立模型**步驟以建立邊緣。

1. 如果畫布包含緊接在您已新增之**建立模型**步驟之後的任何步驟，請按一下游標，然後將其從**建立模型**步驟拖曳到該步驟以建立邊緣。

------
#### [ SageMaker Python SDK ]

**重要**  
我們建議從 SageMaker AI Python SDK v2.90.0 起使用 [模型步驟](#step-type-model) 建立模型。`CreateModelStep` 將會繼續在 SageMaker Python SDK 的先前版本中運作，但不再受到主動支援。

```
from sagemaker.workflow.steps import CreateModelStep

step_create_model = CreateModelStep(
    name="AbaloneCreateModel",
    model=best_model,
    inputs=inputs
)
```

------

## 註冊模型步驟
<a name="step-type-register-model"></a>

註冊模型步驟會將模型註冊至 SageMaker 模型註冊庫。

------
#### [ Pipeline Designer ]

若要使用管道設計工具從管道註冊模型，請執行下列動作：

1. 遵循 [啟動 Amazon SageMaker Studio](studio-updated-launch.md) 中的指示開啟 Amazon SageMaker Studio 主控台。

1. 在左側導覽窗格中，選取**管道**。

1. 選擇**建立**。

1. 選擇**空白**。

1. 在左側邊欄中，選擇**註冊模型**並將其拖曳至畫布。

1. 在畫布中，選擇您新增的**註冊模型**步驟。

1. 在右側邊欄中，完成**設定**和**詳細資訊**索引標籤中的表單。如需這些標籤中欄位的相關資訊，請參閱 [sagemaker.workflow.step\$1collections.RegisterModel](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.step_collections.RegisterModel)。

1. 如果畫布包含緊接在您已新增之**註冊模型**步驟之前的任何步驟，請按一下游標，然後將其從該步驟拖曳到**註冊模型**步驟以建立邊緣。

1. 如果畫布包含緊接在您已新增之**註冊模型**步驟之後的任何步驟，請按一下游標，然後將其從**註冊模型**步驟拖曳到該步驟以建立邊緣。

------
#### [ SageMaker Python SDK ]

**重要**  
我們建議從 SageMaker AI Python SDK v2.90.0 起使用 [模型步驟](#step-type-model) 註冊模型。`RegisterModel` 將會繼續在 SageMaker Python SDK 的先前版本中運作，但不再受到主動支援。

您可以使用 `RegisterModel` 步驟搭配 Amazon SageMaker 模型註冊表註冊 [sagemaker.model.Model](https://sagemaker.readthedocs.io/en/stable/api/inference/model.html) 或 [sagemaker.pipeline.PipelineModel](https://sagemaker.readthedocs.io/en/stable/api/inference/pipeline.html#pipelinemodel)。`PipelineModel` 表示推論管道，是一種由直線順序容器構成的模型，可處理推論請求。

如需有關如何註冊模型的詳細資訊，請參閱[使用模型註冊庫進行模型註冊部署](model-registry.md)。如需有關 `RegisterModel` 步驟要求的詳細資訊，請參閱 [sagemaker.workflow.step\$1collections.RegisterModel](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.step_collections.RegisterModel) 文件。

下列範例示範如何建立註冊 `PipelineModel` 所需的 `RegisterModel` 步驟。

```
import time
from sagemaker.sklearn import SKLearnModel
from sagemaker.xgboost import XGBoostModel

code_location = 's3://{0}/{1}/code'.format(bucket_name, prefix)

sklearn_model = SKLearnModel(model_data=processing_step.properties.ProcessingOutputConfig.Outputs['model'].S3Output.S3Uri,
 entry_point='inference.py',
 source_dir='sklearn_source_dir/',
 code_location=code_location,
 framework_version='1.0-1',
 role=role,
 sagemaker_session=sagemaker_session,
 py_version='py3')

xgboost_model = XGBoostModel(model_data=training_step.properties.ModelArtifacts.S3ModelArtifacts,
 entry_point='inference.py',
 source_dir='xgboost_source_dir/',
 code_location=code_location,
 framework_version='0.90-2',
 py_version='py3',
 sagemaker_session=sagemaker_session,
 role=role)

from sagemaker.workflow.step_collections import RegisterModel
from sagemaker import PipelineModel
pipeline_model = PipelineModel(models=[sklearn_model,xgboost_model],role=role,sagemaker_session=sagemaker_session)

step_register = RegisterModel(
 name="AbaloneRegisterModel",
 model=pipeline_model,
 content_types=["application/json"],
 response_types=["application/json"],
 inference_instances=["ml.t2.medium", "ml.m5.xlarge"],
 transform_instances=["ml.m5.xlarge"],
 model_package_group_name='sipgroup',
)
```

如果未提供 `model`，則註冊模型步驟需要估算器，如下列範例所示。

```
from sagemaker.workflow.step_collections import RegisterModel

step_register = RegisterModel(
    name="AbaloneRegisterModel",
    estimator=xgb_train,
    model_data=step_train.properties.ModelArtifacts.S3ModelArtifacts,
    content_types=["text/csv"],
    response_types=["text/csv"],
    inference_instances=["ml.t2.medium", "ml.m5.xlarge"],
    transform_instances=["ml.m5.xlarge"],
    model_package_group_name=model_package_group_name,
    approval_status=model_approval_status,
    model_metrics=model_metrics
)
```

------

## 部署模型 (端點) 步驟
<a name="step-type-deploy-model-endpoint"></a>

在管道設計工具中，使用部署模型 (端點) 步驟將您的模型部署到端點。您可以建立新的端點或使用現有的端點。即時推論非常適合您具有即時、互動、低延遲需求的推論工作負載。您可以將模型部署到 SageMaker AI 託管服務，並取得可用於推論的即時端點。這些端點是完全受管且支援自動擴展。若要進一步了解 SageMaker AI 中的即時推論，請參閱[即時推論](realtime-endpoints.md)。

在將部署模型步驟新增至您的管道之前，請確定您的 IAM 角色具有下列許可：
+ `sagemaker:CreateModel`
+ `sagemaker:CreateEndpointConfig`
+ `sagemaker:CreateEndpoint`
+ `sagemaker:UpdateEndpoint`
+ `sagemaker:DescribeModel`
+ `sagemaker:DescribeEndpointConfig`
+ `sagemaker:DescribeEndpoint`

若要進一步了解 SageMaker AI 的所有必要許可，以及如何設定這些許可，請參閱 [Amazon SageMaker AI API 許可：動作、許可與資源參考](api-permissions-reference.md)。

若要在拖放編輯器中將模型部署步驟新增至您的管道，請完成下列步驟：

1. 遵循 [啟動 Amazon SageMaker Studio](studio-updated-launch.md) 中的指示開啟 Studio 主控台。

1. 在左側導覽窗格中，選取**管道**。

1. 選擇**建立**。

1. 選擇**空白**。

1. 在左側邊欄中，選擇**部署模型 (端點)** 並將其拖曳至畫布。

1. 在畫布中，選擇您新增的**部署模型 (端點)** 步驟。

1. 在右側邊欄中，完成**設定**和**詳細資訊**索引標籤中的表單。

1. 如果畫布包含緊接在您已新增之**部署模型 (端點)** 步驟之前的任何步驟，請按一下游標，然後將其從該步驟拖曳到**部署模型 (端點)** 步驟以建立邊緣。

1. 如果畫布包含緊接在您已新增之**部署模型 (端點)** 步驟之後的任何步驟，請按一下游標，然後將其從**部署模型 (端點)** 步驟拖曳到該步驟以建立邊緣。

## 轉換步驟
<a name="step-type-transform"></a>

您可以使用批次轉換的轉換步驟對整個資料集執行推論。有關批次轉換的更多資訊，請參閱[使用推論管道執行批次轉換](inference-pipeline-batch.md)。

轉換步驟需要轉換器以及要對其執行批次轉換的資料。下列範例展示如何建立轉換步驟定義。如需轉換步驟要求的詳細資訊，請參閱 [sagemaker.workflow.steps.TransformStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.steps.TransformStep) 文件。

------
#### [ Pipeline Designer ]

若要使用拖放視覺化編輯器將批次轉換步驟新增至您的管道，請執行下列動作：

1. 遵循 [啟動 Amazon SageMaker Studio](studio-updated-launch.md) 中的指示開啟 Studio 主控台。

1. 在左側導覽窗格中，選取**管道**。

1. 選擇**建立**。

1. 選擇**空白**。

1. 在左側邊欄中，選擇**部署模型 (批次轉換)** 並將其拖曳至畫布。

1. 在畫布中，選擇您已新增的**部署模型 (批次轉換)** 步驟。

1. 在右側邊欄中，完成**設定**和**詳細資訊**索引標籤中的表單。如需這些索引標籤中欄位的相關資訊，請參閱 [sagemaker.workflow.steps.TransformStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.steps.TransformStep)。

1. 如果畫布包含緊接在您已新增之**部署模型 (批次轉換)** 步驟之前的任何步驟，請按一下游標，然後將其從該步驟拖曳到**部署模型 (批次轉換)** 步驟以建立邊緣。

1. 如果畫布包含緊接在您已新增之**部署模型 (批次轉換)** 步驟之後的任何步驟，請按一下游標，然後將其從**部署模型 (批次轉換)** 步驟拖曳到該步驟以建立邊緣。

------
#### [ SageMaker Python SDK ]

```
from sagemaker.workflow.pipeline_context import PipelineSession

from sagemaker.transformer import Transformer
from sagemaker.inputs import TransformInput
from sagemaker.workflow.steps import TransformStep

transformer = Transformer(..., sagemaker_session=PipelineSession())

step_transform = TransformStep(
    name="AbaloneTransform",
    step_args=transformer.transform(data="s3://amzn-s3-demo-bucket/my-data"),
)
```

------

## 條件步驟
<a name="step-type-condition"></a>

您可以使用條件步驟來評估步驟屬性的條件，以評估接下來應該在管道中採取哪些動作。

條件步驟需要：
+ 條件清單。
+ 如果條件評估為 `true`，要執行的步驟清單。
+ 如果條件評估為 `false`，要執行的步驟清單。

------
#### [ Pipeline Designer ]

若要使用管道設計工具將條件步驟新增至管道，請執行下列動作：

1. 遵循 [啟動 Amazon SageMaker Studio](studio-updated-launch.md) 中的指示開啟 Amazon SageMaker Studio 主控台。

1. 在左側導覽窗格中，選取**管道**。

1. 選擇**建立**。

1. 選擇**空白**。

1. 在左側邊欄中，選擇**條件**並將其拖曳至畫布。

1. 在畫布中，選擇您已新增的**條件**步驟。

1. 在右側邊欄中，完成**設定**和**詳細資訊**索引標籤中的表單。如需這些索引標籤中欄位的相關資訊，請參閱 [sagemaker.workflow.condition\$1step.ConditionStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.condition_step.ConditionStep)。

1. 如果畫布包含緊接在您已新增之**條件**步驟之前的任何步驟，請按一下游標，然後將其從該步驟拖曳到**條件**步驟以建立邊緣。

1. 如果畫布包含緊接在您已新增之**條件**步驟之後的任何步驟，請按一下游標，然後將其從**條件**步驟拖曳到該步驟以建立邊緣。

------
#### [ SageMaker Python SDK ]

 下列範例示範如何建立 `ConditionStep` 定義。

**限制**
+ Pipelines 不支援使用巢狀條件步驟。您無法將條件步驟作為另一個條件步驟的輸入傳遞。
+ 條件步驟不能在兩個分支中使用相同的步驟。如果您需要在兩個分支中使用相同的步驟功能，請複製該步驟並為其指定不同的名稱。

```
from sagemaker.workflow.conditions import ConditionLessThanOrEqualTo
from sagemaker.workflow.condition_step import ConditionStep
from sagemaker.workflow.functions import JsonGet

cond_lte = ConditionLessThanOrEqualTo(
    left=JsonGet(
        step_name=step_eval.name,
        property_file=evaluation_report,
        json_path="regression_metrics.mse.value"
    ),
    right=6.0
)

step_cond = ConditionStep(
    name="AbaloneMSECond",
    conditions=[cond_lte],
    if_steps=[step_register, step_create_model, step_transform],
    else_steps=[]
)
```

如需有關 `ConditionStep` 要求的詳細資訊，請參閱 [sagemaker.workflow.condition\$1step.ConditionStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#conditionstep) API 參考。如需支援的條件的詳細資訊，請參閱 SageMaker AI Python SDK 文件中的 *[Amazon SageMaker Pipelines - 條件](https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_model_building_pipeline.html#conditions)*。

------

## 回呼步驟
<a name="step-type-callback"></a>

使用`Callback`步驟將非由 Amazon SageMaker Pipelines 直接提供的其他程序和 AWS 服務新增至您的工作流程。`Callback` 步驟執行時，會發生下列程序：
+ Pipelines 會將訊息傳送至客戶指定的 Amazon Simple Queue Service (Amazon SQS) 佇列。訊息包含 Pipelines 產生的字符，以及客戶提供的輸入參數清單。傳送訊息後，Pipelines 會等待客戶回應。
+ 客戶從 Amazon SQS 佇列擷取訊息，並開始自訂程序。
+ 程序完成時，客戶會呼叫下列其中一個 API，並提交 Pipelines 產生的字符：
  +  [SendPipelineExecutionStepSuccess](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_SendPipelineExecutionStepSuccess.html) 以及輸出參數清單
  +  [SendPipelineExecutionStepFailure](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_SendPipelineExecutionStepFailure.html) 以及失敗原因
+ API 呼叫會使 Pipeline 繼續進行管道程序或使程序失敗。

如需有關 `Callback` 步驟要求的詳細資訊，請參閱[工作流程回調步驟回調步驟](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.callback_step.CallbackStep)文件。有關完整的解決方案，請參閱[擴展 SageMaker 管道以包含使用回調步驟的自訂步驟](https://aws.amazon.com/blogs/machine-learning/extend-amazon-sagemaker-pipelines-to-include-custom-steps-using-callback-steps/)。

**重要**  
Amazon SageMaker Python SDK v2.45.0 和 Amazon SageMaker Studio Classic v3.6.2 中引入了 `Callback` 步驟。您必須先更新 Studio Classic，才能使用 `Callback` 步驟，否則管道 DAG 不會顯示。若要更新 Studio Classic，請參閱[關閉並更新 Amazon SageMaker Studio Classic](studio-tasks-update-studio.md)。

下列範例展示上述程序的實作。

```
from sagemaker.workflow.callback_step import CallbackStep

step_callback = CallbackStep(
    name="MyCallbackStep",
    sqs_queue_url="https://sqs.us-east-2.amazonaws.com/012345678901/MyCallbackQueue",
    inputs={...},
    outputs=[...]
)

callback_handler_code = '
    import boto3
    import json

    def handler(event, context):
        sagemaker_client=boto3.client("sagemaker")

        for record in event["Records"]:
            payload=json.loads(record["body"])
            token=payload["token"]

            # Custom processing

            # Call SageMaker AI to complete the step
            sagemaker_client.send_pipeline_execution_step_success(
                CallbackToken=token,
                OutputParameters={...}
            )
'
```

**注意**  
`CallbackStep` 的輸出參數不應巢狀化。例如，如果您使用巢狀字典作為輸出參數，則字典會被視為單一字串 (例如 `{"output1": "{\"nested_output1\":\"my-output\"}"}`)。如果您提供巢狀值，則當您嘗試參考特定輸出參數時，SageMaker AI 會擲出不可重試的用戶端錯誤。

**停止行為**

`Callback` 步驟執行期間，管道程序不會停止。

當您使用執行中 `Callback` 步驟對管道程序呼叫 [StopPipelineExecution](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_StopPipelineExecution.html) 時，Pipelines 會將 Amazon SQS 訊息傳送到 SQS 佇列。SQS 訊息的主體包含設定為 `Stopping` 的**狀態**欄位。下列範例示範 SQS 訊息主體。

```
{
  "token": "26vcYbeWsZ",
  "pipelineExecutionArn": "arn:aws:sagemaker:us-east-2:012345678901:pipeline/callback-pipeline/execution/7pinimwddh3a",
  "arguments": {
    "number": 5,
    "stringArg": "some-arg",
    "inputData": "s3://sagemaker-us-west-2-012345678901/abalone/abalone-dataset.csv"
  },
  "status": "Stopping"
}
```

您應該將邏輯新增至 Amazon SQS 訊息取用者，以在收到訊息時採取任何必要的動作 (例如資源清理)。然後將呼叫新增至 `SendPipelineExecutionStepSuccess` 或 `SendPipelineExecutionStepFailure`。

只有當 Pipelines 接收到其中一個呼叫時，才會停止管道程序。

## Lambda 步驟
<a name="step-type-lambda"></a>

您可以使用 Lambda 步驟來執行 AWS Lambda 函數。您可以執行現有的 Lambda 函式，或 SageMaker AI 可以建立並執行新的 Lambda 函式。如果您選擇使用現有的 Lambda 函數，它必須與 SageMaker AI 管道 AWS 區域 位於相同的 中。如需顯示如何在 SageMaker AI 管道中使用 Lambda 步驟的筆記本，請參閱 [sagemaker-pipelines-lambda-step.ipynb](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-pipelines/tabular/lambda-step/sagemaker-pipelines-lambda-step.ipynb)。

**重要**  
Amazon SageMaker Python SDK v2.51.0 和 Amazon SageMaker Studio Classic v3.9.1 中引入了 Lambda 步驟。您必須先更新 Studio Classic，才能使用 Lambda 步驟，否則管道 DAG 不會顯示。若要更新 Studio Classic，請參閱[關閉並更新 Amazon SageMaker Studio Classic](studio-tasks-update-studio.md)。

SageMaker AI 提供 [sagemaker.lambda\$1helper.Lambda](https://sagemaker.readthedocs.io/en/stable/api/utility/lambda_helper.html) 類別，以建立、更新、調用和刪除 Lambda 函式。`Lambda` 具有下列簽章。

```
Lambda(
    function_arn,       # Only required argument to invoke an existing Lambda function

    # The following arguments are required to create a Lambda function:
    function_name,
    execution_role_arn,
    zipped_code_dir,    # Specify either zipped_code_dir and s3_bucket, OR script
    s3_bucket,          # S3 bucket where zipped_code_dir is uploaded
    script,             # Path of Lambda function script
    handler,            # Lambda handler specified as "lambda_script.lambda_handler"
    timeout,            # Maximum time the Lambda function can run before the lambda step fails
    ...
)
```

[sagemaker.workflow.lambda\$1step.LambdaStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.lambda_step.LambdaStep) 類別具有 `Lambda` 類型的 `lambda_func` 引數。若要調用現有的 Lambda 函式，唯一的要求是將函式的 Amazon Resource Name (ARN) 提供給 `function_arn`。如果您未提供 `function_arn` 的值，則必須指定 `handler` 和下列其中一項：
+ `zipped_code_dir` – 壓縮 Lambda 函式的路徑

  `s3_bucket` – `zipped_code_dir` 上傳至的 Amazon S3 儲存貯體
+ `script` – Lambda 函式指令碼檔案的路徑

下列範例示範如何建立調用現有 Lambda 函式的 `Lambda` 步驟定義。

```
from sagemaker.workflow.lambda_step import LambdaStep
from sagemaker.lambda_helper import Lambda

step_lambda = LambdaStep(
    name="ProcessingLambda",
    lambda_func=Lambda(
        function_arn="arn:aws:lambda:us-west-2:012345678910:function:split-dataset-lambda"
    ),
    inputs={
        s3_bucket = s3_bucket,
        data_file = data_file
    },
    outputs=[
        "train_file", "test_file"
    ]
)
```

下列範例示範如何建立使用 Lambda 函式指令碼建立並調用 Lambda 函式的 `Lambda` 步驟定義。

```
from sagemaker.workflow.lambda_step import LambdaStep
from sagemaker.lambda_helper import Lambda

step_lambda = LambdaStep(
    name="ProcessingLambda",
    lambda_func=Lambda(
      function_name="split-dataset-lambda",
      execution_role_arn=execution_role_arn,
      script="lambda_script.py",
      handler="lambda_script.lambda_handler",
      ...
    ),
    inputs={
        s3_bucket = s3_bucket,
        data_file = data_file
    },
    outputs=[
        "train_file", "test_file"
    ]
)
```

**輸入和輸出**

如果您的 `Lambda` 函式具有輸入或輸出，則輸入或輸出也必須在 `Lambda` 步驟中定義。

**注意**  
輸入和輸出參數不應巢狀化。例如，如果您使用巢狀字典作為輸出參數，則字典會被視為單一字串 (例如 `{"output1": "{\"nested_output1\":\"my-output\"}"}`)。如果您提供巢狀值並稍後嘗試參考它，則系統會拋出不可重試的用戶端錯誤。

定義 `Lambda` 步驟時，`inputs` 必須是鍵值對的字典。`inputs` 字典的每個值都必須是基本類型 (字串、整數或浮點數)。不支援巢狀物件。如果未定義，則 `inputs` 值預設為 `None`。

`outputs` 值必須是鍵清單。這些鍵指的是在 `Lambda` 函式的輸出中定義的字典。與 `inputs` 類似，這些鍵必須是基本類型，並且不支援巢狀物件。

**逾時和停止行為**

`Lambda` 類別具有一個 `timeout` 引數，可指定 Lambda 函式可以執行的最長時間。預設值是 120 秒，上限值為 10 分鐘。如果 Lambda 函式在達到逾時時間時正在執行，則 Lambda 步驟會失敗；不過，Lambda 函式會繼續執行。

Lambda 步驟執行時，無法停止管道程序，因為 Lambda 步驟調用的 Lambda 函式無法停止。如果您在 Lambda 函式執行時停止程序，管道會等待該函式完成，或直到逾時為止。這取決於哪個先發生。程序接著會停止。如果 Lambda 函式完成，則管道程序狀態為 `Stopped`。如果超時到達，則管道程序狀態為 `Failed`。

## ClarifyCheck 步驟
<a name="step-type-clarify-check"></a>

您可以使用 `ClarifyCheck` 步驟可對照先前的基準執行基準漂移檢查，以便進行偏差分析和模型可解釋性。然後，您可以使用 `model.register()` 方法產生並[註冊基準](https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-quality-clarify-baseline-lifecycle.html#pipelines-quality-clarify-baseline-calculations)，然後使用 `[step\$1args](https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_model_building_pipeline.html#model-step)` 將該方法的輸出傳遞給 [模型步驟](#step-type-model)。Amazon SageMaker Model Monitor 可以針對您的模型端點使用這些基準，進行漂移檢查。因此，您不需要個別提出[基準](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-create-baseline.html)建議。

`ClarifyCheck` 步驟也可以從模型註冊中提取漂移檢查基準。`ClarifyCheck` 步驟會使用 SageMaker Clarify 預先建置的容器。此容器提供一系列模型監控功能，包括建議限制條件和根據指定基準來驗證限制條件。如需詳細資訊，請參閱[預先建置的 SageMaker Clarify 容器](clarify-processing-job-configure-container.md)。

### 設定 ClarifyCheck 步驟
<a name="configuring-step-type-clarify"></a>

您可以設定 `ClarifyCheck` 步驟，以便每次在管道中使用該步驟時僅執行下列其中一種可用的檢查類型。
+ 資料偏差檢查
+ 模型偏差檢查
+ 模型可解釋性檢查

若要這樣做，請使用下列其中一個檢查類型值來設定 `clarify_check_config` 參數：
+ `DataBiasCheckConfig`
+ `ModelBiasCheckConfig`
+ `ModelExplainabilityCheckConfig`

`ClarifyCheck` 步驟會啟動執行 SageMaker Clarify AI 預先建置容器的處理任務，並需要專用的[檢查和處理任務組態](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-configure-processing-jobs.html)。`ClarifyCheckConfig` 和 `CheckJobConfig` 是這些組態的協助程式函式。這些協助程式函式與 SageMaker Clarify 處理任務進行運算，以檢查模型偏差、資料偏差或模型可解釋性的方式一玫。如需詳細資訊，請參閱[執行 SageMaker Clarify 處理任務以進行偏差分析和解釋性](clarify-processing-job-run.md)。

### 控制漂移檢查的步驟行為
<a name="controlling-step-type-clarify"></a>

`ClarifyCheck` 步驟需要下列兩個布林標記來控制其行為：
+ `skip_check`：此參數指示是否略過針對先前基準的漂移檢查。如果設定為 `False`，則必須有已設定檢查類型的先前基準。
+ `register_new_baseline`：此參數指示是否可透過步驟屬性 `BaselineUsedForDriftCheckConstraints` 存取新計算的基準。如果設定為 `False`，則也必須有已設定檢查類型的先前基準。這可以透過 `BaselineUsedForDriftCheckConstraints` 屬性存取。

如需更多詳細資訊，請參閱[Amazon SageMaker Pipelines 中具有 ClarifyCheck 和 QualityCheck 步驟的基準計算、漂移偵測和生命週期](pipelines-quality-clarify-baseline-lifecycle.md)。

### 處理基準
<a name="step-type-clarify-working-with-baselines"></a>

您可以選擇性地指定 `model_package_group_name` 來尋找現有的基準。然後，`ClarifyCheck` 步驟會在模型套件群組中提取最新核准的模型套件上的 `DriftCheckBaselines`。

或者，您可以透過 `supplied_baseline_constraints` 參數提供先前的基準。如果同時指定 `model_package_group_name` 和 `supplied_baseline_constraints`，則 `ClarifyCheck` 步驟會使用 `supplied_baseline_constraints` 參數指定的基準。

如需使用 `ClarifyCheck` 步驟要求的詳細資訊，請參閱 *Amazon SageMaker AI SageMaker AI SDK for Python* 中的 [sagemaker.workflow.steps.ClarifyCheckStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.clarify_check_step.ClarifyCheckStep)。如需顯示如何在 Pipelines 中使用 `ClarifyCheck` 步驟的 Amazon SageMaker Studio Classic 筆記本，請參閱 [sagemaker-pipeline-model-monitor-clarify-steps.ipynb](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-pipelines/tabular/model-monitor-clarify-pipelines/sagemaker-pipeline-model-monitor-clarify-steps.ipynb)。

**Example 為資料偏差檢查建立 `ClarifyCheck` 步驟**  

```
from sagemaker.workflow.check_job_config import CheckJobConfig
from sagemaker.workflow.clarify_check_step import DataBiasCheckConfig, ClarifyCheckStep
from sagemaker.workflow.execution_variables import ExecutionVariables

check_job_config = CheckJobConfig(
    role=role,
    instance_count=1,
    instance_type="ml.c5.xlarge",
    volume_size_in_gb=120,
    sagemaker_session=sagemaker_session,
)

data_bias_data_config = DataConfig(
    s3_data_input_path=step_process.properties.ProcessingOutputConfig.Outputs["train"].S3Output.S3Uri,
    s3_output_path=Join(on='/', values=['s3:/', your_bucket, base_job_prefix, ExecutionVariables.PIPELINE_EXECUTION_ID, 'databiascheckstep']),
    label=0,
    dataset_type="text/csv",
    s3_analysis_config_output_path=data_bias_analysis_cfg_output_path,
)

data_bias_config = BiasConfig(
    label_values_or_threshold=[15.0], facet_name=[8], facet_values_or_threshold=[[0.5]]  
)

data_bias_check_config = DataBiasCheckConfig(
    data_config=data_bias_data_config,
    data_bias_config=data_bias_config,
)h

data_bias_check_step = ClarifyCheckStep(
    name="DataBiasCheckStep",
    clarify_check_config=data_bias_check_config,
    check_job_config=check_job_config,
    skip_check=False,
    register_new_baseline=False
   supplied_baseline_constraints="s3://sagemaker-us-west-2-111122223333/baseline/analysis.json",
    model_package_group_name="MyModelPackageGroup"
)
```

## QualityCheck 步驟
<a name="step-type-quality-check"></a>

使用 `QualityCheck` 步驟，針對管道中先前的資料品質或模型品質基準執行[基準建議](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-create-baseline.html)和漂移檢查。然後，您可以使用 `model.register()` 方法產生並[註冊基準](https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-quality-clarify-baseline-lifecycle.html#pipelines-quality-clarify-baseline-calculations)，然後使用 `[step\$1args](https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_model_building_pipeline.html#model-step)` 將該方法的輸出傳遞給 [模型步驟](#step-type-model)。

Model Monitor 可針對模型端點使用這些基準進行漂移檢查，因此您不需要單獨執行基準建議。`QualityCheck` 步驟也可以從模型註冊中提取漂移檢查基準。`QualityCheck` 步驟會利用 Amazon SageMaker AI Model Monitor 預先建置的容器。此容器具有一系列模型監控功能，包括建議限制條件、產生統計資料和根據基準驗證限制條件。如需詳細資訊，請參閱[Amazon SageMaker Model Monitor 預建容器](model-monitor-pre-built-container.md)。

### 設定 QualityCheck 步驟
<a name="configuring-step-type-quality"></a>

您可以將 `QualityCheck` 步驟設定為每次在管道中使用該步驟時，僅執行下列其中一種檢查類型。
+ 資料品質檢查
+ 模型品質檢查

為了執行此動作，您可以使用下列其中一個檢查類型值來設定 `quality_check_config` 參數：
+ `DataQualityCheckConfig`
+ `ModelQualityCheckConfig`

`QualityCheck` 步驟會啟動執行 Model Monitor 預先建置容器的處理任務，並需要檢查和處理任務的專用組態。`QualityCheckConfig` 和 `CheckJobConfig` 是這些組態的協助程式函式。這些協助程式函式與 Model Monitor 為模型品質或資料品質監控建立基準的方式一致。如需有關模型監視器基線建議的詳細資訊，請參閱[建立基準](model-monitor-create-baseline.md)和[建立模型品質基準](model-monitor-model-quality-baseline.md)。

### 控制漂移檢查的步驟行為
<a name="controlling-step-type-quality"></a>

`QualityCheck` 步驟需要下列兩個布林標記來控制其行為：
+ `skip_check`：此參數指示是否略過針對先前基準的漂移檢查。如果設定為 `False`，則必須有已設定檢查類型的先前基準。
+ `register_new_baseline`：此參數指示是否可透過步驟屬性 `BaselineUsedForDriftCheckConstraints` 和 `BaselineUsedForDriftCheckStatistics` 存取新計算的基準。如果設定為 `False`，則也必須有已設定檢查類型的先前基準。這些可透過 `BaselineUsedForDriftCheckConstraints` 和 `BaselineUsedForDriftCheckStatistics` 屬性存取。

如需更多詳細資訊，請參閱[Amazon SageMaker Pipelines 中具有 ClarifyCheck 和 QualityCheck 步驟的基準計算、漂移偵測和生命週期](pipelines-quality-clarify-baseline-lifecycle.md)。

### 處理基準
<a name="step-type-quality-working-with-baselines"></a>

您可以直接透過 `supplied_baseline_statistics` 和 `supplied_baseline_constraints` 參數指定先前的基準。您也可以指定 `model_package_group_name`，然後 `QualityCheck` 步驟會在模型套件組中提取最新核准的模型套件上的 `DriftCheckBaselines`。

當您指定下列項目時，`QualityCheck` 步驟會對 `QualityCheck` 步驟的檢查類型使用 `supplied_baseline_constraints` 和 `supplied_baseline_statistics` 指定的基準。
+ `model_package_group_name`
+ `supplied_baseline_constraints`
+ `supplied_baseline_statistics`

如需使用 `QualityCheck` 步驟要求的詳細資訊，請參閱 *Amazon SageMaker AI SageMaker AI SDK for Python* 中的 [sagemaker.workflow.steps.QualityCheckStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.quality_check_step.QualityCheckStep)。如需顯示如何在 Pipelines 中使用 `QualityCheck` 步驟的 Amazon SageMaker Studio Classic 筆記本，請參閱 [sagemaker-pipeline-model-monitor-clarify-steps.ipynb](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-pipelines/tabular/model-monitor-clarify-pipelines/sagemaker-pipeline-model-monitor-clarify-steps.ipynb)。

**Example 為資料品質檢查建立 `QualityCheck` 步驟**  

```
from sagemaker.workflow.check_job_config import CheckJobConfig
from sagemaker.workflow.quality_check_step import DataQualityCheckConfig, QualityCheckStep
from sagemaker.workflow.execution_variables import ExecutionVariables

check_job_config = CheckJobConfig(
    role=role,
    instance_count=1,
    instance_type="ml.c5.xlarge",
    volume_size_in_gb=120,
    sagemaker_session=sagemaker_session,
)

data_quality_check_config = DataQualityCheckConfig(
    baseline_dataset=step_process.properties.ProcessingOutputConfig.Outputs["train"].S3Output.S3Uri,
    dataset_format=DatasetFormat.csv(header=False, output_columns_position="START"),
    output_s3_uri=Join(on='/', values=['s3:/', your_bucket, base_job_prefix, ExecutionVariables.PIPELINE_EXECUTION_ID, 'dataqualitycheckstep'])
)

data_quality_check_step = QualityCheckStep(
    name="DataQualityCheckStep",
    skip_check=False,
    register_new_baseline=False,
    quality_check_config=data_quality_check_config,
    check_job_config=check_job_config,
    supplied_baseline_statistics="s3://sagemaker-us-west-2-555555555555/baseline/statistics.json",
    supplied_baseline_constraints="s3://sagemaker-us-west-2-555555555555/baseline/constraints.json",
    model_package_group_name="MyModelPackageGroup"
)
```

## EMR 步驟
<a name="step-type-emr"></a>

使用 Amazon SageMaker Pipelines [EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-overview.html) 步驟：
+ 在執行中 Amazon EMR 叢集上處理 [Amazon EMR 步驟](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-work-with-steps.html)。
+ 讓管道為您在 Amazon EMR 叢集上建立和管理叢集。

如需有關 Amazon EMR 的詳細資訊，請參閱 [Getting started with Amazon EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-gs.html)。

EMR 步驟要求 `EMRStepConfig` 包括 Amazon EMR 叢集所使用的 JAR 檔案的位置，以及要傳遞的任何引數。如果您想要在執行中的 EMR 叢集上執行步驟，您也會提供 Amazon EMR 叢集 ID。您也可以傳遞叢集組態，在其為您建立、管理和終止的叢集上執行 EMR 步驟。以下章節包括示範這兩種方法的範例和範例筆記本連結。

**注意**  
EMR 步驟要求傳遞至管道的角色具有其他許可。將 [AWS 受管政策：`AmazonSageMakerPipelinesIntegrations`](https://docs.aws.amazon.com/sagemaker/latest/dg/security-iam-awsmanpol-pipelines.html#security-iam-awsmanpol-AmazonSageMakerPipelinesIntegrations) 連接至您的管道角色，或確保該角色包含該政策中的許可。
如果您在執行中的叢集上處理 EMR 步驟，則只能使用處於下列其中一種狀態的叢集：  
`STARTING`
`BOOTSTRAPPING`
`RUNNING`
`WAITING`
如果您在正在執行的叢集上處理 EMR 步驟，則 EMR 叢集上最多可以有 256 個處於 `PENDING` 狀態的 EMR 步驟。提交超出此限制的 EMR 步驟會導致管道執行失敗。您可以考慮使用 [管道步驟的重試政策](pipelines-retry-policy.md)。
您可以指定叢集 ID 或叢集組態，但不能同時指定兩者。
EMR 步驟憑藉 Amazon EventBridge 來監控 EMR 步驟或叢集狀態變更。如果您在正在執行的叢集上處理 Amazon EMR 任務，EMR 步驟會使用 `SageMakerPipelineExecutionEMRStepStatusUpdateRule` 規則來監控 EMR 步驟狀態。如果您在 EMR 步驟建立的叢集上處理任務，則此步驟會使用 `SageMakerPipelineExecutionEMRClusterStatusRule` 規則來監控叢集狀態中的變化。如果您在 AWS 帳戶中看到這些 EventBridge 規則之一，請不要刪除它們，否則 EMR 步驟可能無法完成。

**將 Amazon EMR 步驟新增至管道**

若要將 EMR 步驟新增至管道，請執行下列動作：
+ 依照[啟動 Amazon SageMaker Studio 中的指示開啟 Studio ](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html)主控台。
+ 在左側導覽窗格中，選取**管道**。
+ 選擇**建立**。
+ 選擇**空白**。
+ 在左側邊欄中，選擇**處理資料**並將其拖曳至畫布。
+ 在畫布中，選擇您新增的**處理資料**步驟。
+ 在右側邊欄中的 模式下，選擇 **EMR （受管）**。
+ 在右側邊欄中，完成**設定和詳細資訊**索引標籤中的表單。如需這些標籤中欄位的相關資訊，請參閱 [sagemaker.workflow.fail\$1step.EMRstep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.emr_step.EMRStep)。

**在正在執行的 Amazon EMR 叢集上啟動新任務**

若要在執行中的 Amazon EMR 叢集上啟動新任務，請將叢集 ID 作為字串傳遞至 `EMRStep` 的 `cluster_id` 引數。下列範例示範此程序。

```
from sagemaker.workflow.emr_step import EMRStep, EMRStepConfig

emr_config = EMRStepConfig(
    jar="jar-location", # required, path to jar file used
    args=["--verbose", "--force"], # optional list of arguments to pass to the jar
    main_class="com.my.Main1", # optional main class, this can be omitted if jar above has a manifest 
    properties=[ # optional list of Java properties that are set when the step runs
    {
        "key": "mapred.tasktracker.map.tasks.maximum",
        "value": "2"
    },
    {
        "key": "mapreduce.map.sort.spill.percent",
        "value": "0.90"
   },
   {
       "key": "mapreduce.tasktracker.reduce.tasks.maximum",
       "value": "5"
    }
  ]
)

step_emr = EMRStep (
    name="EMRSampleStep", # required
    cluster_id="j-1ABCDEFG2HIJK", # include cluster_id to use a running cluster
    step_config=emr_config, # required
    display_name="My EMR Step",
    description="Pipeline step to execute EMR job"
)
```

如需逐步引導您完成整個範例的範例筆記本，請參閱 [Pipelines EMR Step With Running EMR Cluster](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-pipelines/tabular/emr-step/sagemaker-pipelines-emr-step-with-running-emr-cluster.ipynb)。

**在新的 Amazon EMR 叢集上啟動新任務**

若要在 `EMRStep` 為您建立的新叢集上啟動新任務，請提供您的叢集組態作為字典。字典必須具有與 [RunJobFlow](https://docs.aws.amazon.com/emr/latest/APIReference/API_RunJobFlow.html) 請求相同的結構。但是，請勿在叢集組態中包含下列欄位：
+ [`Name`]
+ [`Steps`]
+ [`AutoTerminationPolicy`]
+ [`Instances`][`KeepJobFlowAliveWhenNoSteps`]
+ [`Instances`][`TerminationProtected`]

所有其他 `RunJobFlow` 引數都可以在叢集組態中使用。如需有關請求語法的詳細資訊，請參閱 [RunJobFlow](https://docs.aws.amazon.com/emr/latest/APIReference/API_RunJobFlow.html)。

下列範例會將叢集組態傳遞至 EMR 步驟定義。這會提示在新的 EMR 叢集上啟動新任務的步驟。此範例中的 EMR 叢集組態包含主要和核心 EMR 叢集節點的規格。如需有關 Amazon EMR 節點類型的詳細資訊，請參閱[了解節點類型：主節點、核心節點和任務節點](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-master-core-task-nodes.html)。

```
from sagemaker.workflow.emr_step import EMRStep, EMRStepConfig

emr_step_config = EMRStepConfig(
    jar="jar-location", # required, path to jar file used
    args=["--verbose", "--force"], # optional list of arguments to pass to the jar
    main_class="com.my.Main1", # optional main class, this can be omitted if jar above has a manifest 
    properties=[ # optional list of Java properties that are set when the step runs
    {
        "key": "mapred.tasktracker.map.tasks.maximum",
        "value": "2"
    },
    {
        "key": "mapreduce.map.sort.spill.percent",
        "value": "0.90"
   },
   {
       "key": "mapreduce.tasktracker.reduce.tasks.maximum",
       "value": "5"
    }
  ]
)

# include your cluster configuration as a dictionary
emr_cluster_config = {
    "Applications": [
        {
            "Name": "Spark", 
        }
    ],
    "Instances":{
        "InstanceGroups":[
            {
                "InstanceRole": "MASTER",
                "InstanceCount": 1,
                "InstanceType": "m5.2xlarge"
            },
            {
                "InstanceRole": "CORE",
                "InstanceCount": 2,
                "InstanceType": "m5.2xlarge"
            }
        ]
    },
    "BootstrapActions":[],
    "ReleaseLabel": "emr-6.6.0",
    "JobFlowRole": "job-flow-role",
    "ServiceRole": "service-role"
}

emr_step = EMRStep(
    name="emr-step",
    cluster_id=None,
    display_name="emr_step",
    description="MyEMRStepDescription",
    step_config=emr_step_config,
    cluster_config=emr_cluster_config
)
```

如需逐步引導您完成整個範例的範例筆記本，請參閱 [Pipelines EMR Step With Cluster Lifecycle Management](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-pipelines/tabular/emr-step/sagemaker-pipelines-emr-step-with-cluster-lifecycle-management.ipynb)。

## EMR 無伺服器步驟
<a name="step-type-serverless"></a>

若要將 EMR 無伺服器步驟新增至管道，請執行下列動作：
+ 依照[啟動 Amazon SageMaker Studio 中的指示開啟 Studio ](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html)主控台。
+ 在左側導覽窗格中，選取**管道**。
+ 選擇**建立**。
+ 選擇**空白**。
+ 在左側邊欄中，選擇**處理資料**並將其拖曳至畫布。
+ 在畫布中，選擇您新增的**處理資料**步驟。
+ 在右側邊欄中的 模式下，選擇 **EMR （無伺服器）**。
+ 在右側邊欄中，完成**設定和詳細資訊**索引標籤中的表單。

## 筆記本任務步驟
<a name="step-type-notebook-job"></a>

使用 `NotebookJobStep` 以非互動方式將您的 SageMaker 筆記本任務做為管道步驟執行。如果您在 Pipelines 拖放 UI 中建置管道，請使用 [執行程式碼步驟](#step-type-executecode) 來執行筆記本。如需 SageMaker 筆記本任務的詳細資訊，請參閱 [SageMaker 筆記本工作](notebook-auto-run.md)。

`NotebookJobStep` 至少需要一個輸入筆記本、映像 URI 和核心名稱。如需筆記本任務步驟要求以及您可以設定為自訂步驟的其他參數的詳細資訊，請參閱 [sagemaker.workflow.steps.NotebookJobStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.notebook_job_step.NotebookJobStep)。

下列範例使用最少引數來定義 `NotebookJobStep`。

```
from sagemaker.workflow.notebook_job_step import NotebookJobStep


notebook_job_step = NotebookJobStep(
    input_notebook=input_notebook,
    image_uri=image_uri,
    kernel_name=kernel_name
)
```

您的 `NotebookJobStep` 管道步驟會被視為 SageMaker 筆記本任務。因此，請在 Studio Classic UI 筆記本任務儀表板中追蹤執行狀態，方法是使用 `tags` 引數包含特定標籤。如需要包含的標籤詳細資訊，請參閱[在 Studio UI 儀表板中檢視您的筆記本任務](create-notebook-auto-run-sdk.md#create-notebook-auto-run-dash)。

此外，如果您使用 SageMaker Python SDK 排程筆記本任務，您只能指定特定映像來執行筆記本任務。如需詳細資訊，請參閱[SageMaker AI Python SDK 筆記本任務的映像限制條件](notebook-auto-run-constraints.md#notebook-auto-run-constraints-image-sdk)。

## 失敗步驟
<a name="step-type-fail"></a>

使用失敗步驟在未達到所需條件或狀態時停止 Amazon SageMaker Pipelines 執行。失敗步驟也可讓您輸入自訂錯誤訊息，指出管道執行失敗的原因。

**注意**  
當失敗步驟和其他管道步驟同時執行時，在所有並行步驟都完成之前，管道都不會終止。

### 使用失敗步驟的限制
<a name="step-type-fail-limitations"></a>
+ 您無法將失敗步驟新增至其他步驟的 `DependsOn` 清單。如需詳細資訊，請參閱[步驟之間的自訂相依性](build-and-manage-steps.md#build-and-manage-custom-dependency)。
+ 其他步驟無法參考失敗步驟。它*始終*是管道執行的最後一步。
+ 您無法重試以失敗步驟結束的管道執行。

您能以靜態文字字串的形式建立失敗步驟錯誤訊息。或者，您也可以使用[管道參數](https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-parameters.html)和[聯結](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html?highlight=Join#sagemaker.workflow.functions.Join)操作或其他[步驟屬性](https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html#build-and-manage-properties)，來建立資訊更豐富的錯誤訊息，如果您使用 SDK 的話。

------
#### [ Pipeline Designer ]

若要將失敗步驟新增至您的管道，請執行下列動作：

1. 遵循 [啟動 Amazon SageMaker Studio](studio-updated-launch.md) 中的指示開啟 Studio 主控台。

1. 在左側導覽窗格中，選取**管道**。

1. 選擇**建立**。

1. 選擇**空白**。

1. 在左側邊欄中，選擇**失敗**並將其拖曳至畫布。

1. 在畫布中，選擇您已新增的**失敗**步驟。

1. 在右側邊欄中，完成**設定**和**詳細資訊**索引標籤中的表單。如需這些索引標籤中欄位的相關資訊，請參閱 [sagemaker.workflow.fail\$1step.FailStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.fail_step.FailStep)。

1. 如果畫布包含緊接在您已新增之**失敗**步驟之前的任何步驟，請按一下游標，然後將其從該步驟拖曳到**失敗**步驟以建立邊緣。

1. 如果畫布包含緊接在您已新增之**失敗**步驟之後的任何步驟，請按一下游標，然後將其從**失敗**步驟拖曳到該步驟以建立邊緣。

------
#### [ SageMaker Python SDK ]

**Example**  
下列範例程式碼片段使用 `FailStep` (包含透過管道參數和 `Join` 操作設定的 `ErrorMessage`)。  

```
from sagemaker.workflow.fail_step import FailStep
from sagemaker.workflow.functions import Join
from sagemaker.workflow.parameters import ParameterInteger

mse_threshold_param = ParameterInteger(name="MseThreshold", default_value=5)
step_fail = FailStep(
    name="AbaloneMSEFail",
    error_message=Join(
        on=" ", values=["Execution failed due to MSE >", mse_threshold_param]
    ),
)
```

------

# 新增整合
<a name="build-and-manage-steps-integration"></a>

MLflow 整合可讓您將 MLflow 與管道搭配使用，以選取追蹤伺服器或無伺服器應用程式、選擇實驗和日誌指標。

## 重要概念
<a name="add-integration-key-concepts"></a>

**預設應用程式建立** - 當您輸入管道視覺化編輯器時，將會建立預設 MLflow 應用程式。

**整合面板** - 新的整合面板包含 MLflow，您可以選取和設定。

**更新應用程式和實驗** - 在管道執行期間覆寫所選應用程式和實驗的選項。

## 運作方式
<a name="add-integration-how-it-works"></a>
+ 前往**管道視覺化編輯器**
+ 選擇工具列上的**整合** 
+ 選擇 **MLflow**
+ 設定 MLflow 應用程式和實驗

## 範例螢幕擷取畫面
<a name="add-integration-example-screenshots"></a>

整合側邊面板

![\[要執行的描述。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/screenshot-pipeline-1.png)


MLflow 組態

![\[要執行的描述。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/screenshot-pipeline-2.png)


如何在管道執行期間覆寫實驗

![\[要執行的描述。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/screenshot-pipeline-3.png)


## 步驟屬性
<a name="build-and-manage-properties"></a>

使用 `properties` 屬性在管道中的步驟之間新增資料相依性。Pipelines 會使用這些資料相依性，從管道定義建構 DAG。這些屬性可以作為預留位置值參考，並在執行期解析。

Pipelines 步驟的 `properties` 屬性與 `Describe` 呼叫針對對應 SageMaker AI 任務類型傳回的物件相符。對於每個任務類型，`Describe` 呼叫都會傳回下列回應物件：
+ `ProcessingStep` – [DescribeProcessingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeProcessingJob.html)
+ `TrainingStep` – [DescribeTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrainingJob.html)
+ `TransformStep` – [DescribeTransformJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTransformJob.html)

若要在建立資料相依性期間檢查每個步驟類型可參考的屬性，請參閱 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 中的 *[資料相依性 - 屬性參考](https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_model_building_pipeline.html#data-dependency-property-reference)*。

## 步驟平行處理
<a name="build-and-manage-parallelism"></a>

當步驟不依賴任何其他步驟時，其會在管道執行時立即執行。不過，平行執行過多管道步驟可能會快速耗盡可用的資源。使用 `ParallelismConfiguration` 控制管道執行的並行步驟數量。

下列範例使用 `ParallelismConfiguration` 將並行步驟限制為 5 個。

```
pipeline.create(
    parallelism_config=ParallelismConfiguration(5),
)
```

## 步驟之間的資料相依性
<a name="build-and-manage-data-dependency"></a>

您可以透過指定步驟之間的資料關係來定義 DAG 的結構。若要在步驟之間建立資料相依性，請將一個步驟的屬性作為輸入傳遞至管道中的另一個步驟。在提供輸入的步驟執行完後，接收輸入的步驟才會啟動。

資料相依性使用以下格式的 JsonPath 表示法。此格式會周遊 JSON 屬性檔案。這表示您可以視需要附加任意數量的 *<property>* 執行個體，以達到檔案中所需的巢狀屬性。如需有關 JsonPath 符號的詳細資訊，請參閱 [JSONPath 回購](https://github.com/json-path/JsonPath)。

```
<step_name>.properties.<property>.<property>
```

下面示範如何使用處理步驟的 `ProcessingOutputConfig` 屬性來指定 Amazon S3 儲存貯體。

```
step_process.properties.ProcessingOutputConfig.Outputs["train_data"].S3Output.S3Uri
```

若要建立資料相依性，請將儲存貯體傳遞至訓練步驟，如下所示。

```
from sagemaker.workflow.pipeline_context import PipelineSession

sklearn_train = SKLearn(..., sagemaker_session=PipelineSession())

step_train = TrainingStep(
    name="CensusTrain",
    step_args=sklearn_train.fit(inputs=TrainingInput(
        s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
            "train_data"].S3Output.S3Uri
    ))
)
```

若要在建立資料相依性期間檢查每個步驟類型可參考的屬性，請參閱 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 中的[Data Dependency - Property Reference](https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_model_building_pipeline.html#data-dependency-property-reference)。**

## 步驟之間的自訂相依性
<a name="build-and-manage-custom-dependency"></a>

當您指定資料相依性時，Pipelines 會提供步驟之間的資料連線。或者，一個步驟可以存取上一個步驟中的資料，而無需直接使用 Pipelines。在此情況下，您可以建立自訂相依性，告知 Pipelines 在另一個步驟完成執行之前不要開始步驟。您可以透過指定步驟的 `DependsOn` 屬性來建立自訂相依性。

例如，下列內容定義了僅在 `A` 步驟和 `B` 步驟執行完後才開始的 `C` 步驟。

```
{
  'Steps': [
    {'Name':'A', ...},
    {'Name':'B', ...},
    {'Name':'C', 'DependsOn': ['A', 'B']}
  ]
}
```

如果相依性將建立循環相依性，Pipelines 會擲回驗證例外狀況。

下列範例會建立在處理步驟執行完後開始的訓練步驟。

```
processing_step = ProcessingStep(...)
training_step = TrainingStep(...)

training_step.add_depends_on([processing_step])
```

下列範例會建立在兩個不同的處理步驟執行完後才開始的訓練步驟。

```
processing_step_1 = ProcessingStep(...)
processing_step_2 = ProcessingStep(...)

training_step = TrainingStep(...)

training_step.add_depends_on([processing_step_1, processing_step_2])
```

下面提供了建立自訂相依性的替代方法。

```
training_step.add_depends_on([processing_step_1])
training_step.add_depends_on([processing_step_2])
```

下列範例會建立一個訓練步驟，接收來自一個處理步驟的輸入，並等待另一個處理步驟執行完成。

```
processing_step_1 = ProcessingStep(...)
processing_step_2 = ProcessingStep(...)

training_step = TrainingStep(
    ...,
    inputs=TrainingInput(
        s3_data=processing_step_1.properties.ProcessingOutputConfig.Outputs[
            "train_data"
        ].S3Output.S3Uri
    )

training_step.add_depends_on([processing_step_2])
```

下列範例示範如何擷取步驟之自訂相依性的字串清單。

```
custom_dependencies = training_step.depends_on
```

## 步驟中的自訂映像
<a name="build-and-manage-images"></a>

 在您的管道中建立步驟時，您可以使用任何可用的 SageMaker AI [深度學習容器映像](https://github.com/aws/deep-learning-containers/blob/master/available_images.md)。

您也可以在管道步驟中使用您自己的容器。因為您無法從 Studio Classic 內建立映像，所以必須先使用另一種方法建立映像，然後才能使用該映像搭配 Pipelines。

若要在為管道建立步驟時使用您自己的容器，請在估算器定義中包含映像 URI。如需使用您自己的容器搭配 SageMaker AI 的詳細資訊，請參閱[使用 Docker 容器搭配 SageMaker AI](https://docs.aws.amazon.com/sagemaker/latest/dg/docker-containers.html)。