

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

# 為 SageMaker 建立自訂 Docker 容器映像，並將其用於 AWS Step Functions 中的模型訓練
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions"></a>

*Julia Bluszcz、Aubrey Oosthuizen、Mohan Gowda Purushothama、Neha Sharma 和 Mateusz Zaremba，Amazon Web Services*

## 總結
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions-summary"></a>

此模式說明如何為 [Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html) 建立 Docker 容器映像，並將其用於 [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 中的訓練模型。透過在容器中封裝自訂演算法，您可以在 SageMaker 環境中執行幾乎任何程式碼，無論程式設計語言、架構或相依性為何。

在提供的 [SageMaker 筆記本](https://docs.aws.amazon.com/sagemaker/latest/dg/nbi.html)範例中，自訂 Docker 容器映像存放在 [Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) 中。Step Functions 接著會使用存放在 Amazon ECR 中的容器來執行 SageMaker 的 Python 處理指令碼。然後，容器會將模型匯出至 [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)。

## 先決條件和限制
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 具有 Amazon S3 [ S3 許可的 SageMaker AWS Identity and Access Management (IAM) 角色](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html) 
+ [Step Functions 的 IAM 角色](https://sagemaker-examples.readthedocs.io/en/latest/step-functions-data-science-sdk/step_functions_mlworkflow_processing/step_functions_mlworkflow_scikit_learn_data_processing_and_model_evaluation.html#Create-an-Execution-Role-for-Step-Functions)
+ 熟悉 Python
+ 熟悉 Amazon SageMaker Python SDK
+ 熟悉 AWS Command Line Interface (AWS CLI)
+ 熟悉適用於 Python 的 AWS 開發套件 (Boto3)
+ 熟悉 Amazon ECR
+ 熟悉 Docker

**產品版本**
+ AWS Step Functions 資料科學 SDK 2.3.0 版
+ Amazon SageMaker Python SDK 2.78.0 版

## Architecture
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions-architecture"></a>

下圖顯示為 SageMaker 建立 Docker 容器映像的範例工作流程，然後將其用於 Step Functions 中的訓練模型：

![\[為 SageMaker 建立 Docker 容器映像以用作 Step Functions 訓練模型的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/7857d57f-3077-4b06-8971-fb5846387693/images/37755e38-0bc4-4dd0-90c7-135d95b00053.png)


該圖顯示以下工作流程：

1. 資料科學家或 DevOps 工程師使用 Amazon SageMaker 筆記本來建立自訂 Docker 容器映像。

1. 資料科學家或 DevOps 工程師會將 Docker 容器映像存放在私有登錄檔中的 Amazon ECR 私有儲存庫中。

1. 資料科學家或 DevOps 工程師使用 Docker 容器在 Step Functions 工作流程中執行 Python SageMaker 處理任務。

**自動化和擴展**

此模式中的範例 SageMaker 筆記本使用`ml.m5.xlarge`筆記本執行個體類型。您可以變更執行個體類型以符合您的使用案例。如需 SageMaker 筆記本執行個體類型的詳細資訊，請參閱 [Amazon SageMaker 定價](https://aws.amazon.com/sagemaker/pricing/)。

## 工具
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions-tools"></a>
+ [Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) 是一種受管容器映像登錄服務，安全、可擴展且可靠。
+ [Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html) 是一種受管機器學習 (ML) 服務，可協助您建置和訓練 ML 模型，然後將模型部署到生產就緒的託管環境中。
+ [Amazon SageMaker Python SDK](https://github.com/aws/sagemaker-python-sdk) 是一個開放原始碼程式庫，用於在 SageMaker 上訓練和部署機器學習模型。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一種無伺服器協同運作服務，可協助您結合 AWS Lambda 函數和其他 AWS 服務來建置業務關鍵應用程式。
+ [AWS Step Functions 資料科學 Python SDK](https://aws-step-functions-data-science-sdk.readthedocs.io/en/stable/index.html) 是一個開放原始碼程式庫，可協助您建立 Step Functions 工作流程來處理和發佈機器學習模型。

## 史詩
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions-epics"></a>

### 建立自訂 Docker 容器映像並將其存放在 Amazon ECR 中
<a name="create-a-custom-docker-container-image-and-store-it-in-amazon-ecr"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 Amazon ECR 並建立新的私有登錄檔。 | 如果您尚未設定 Amazon ECR，請遵循《Amazon ECR 使用者指南》中的[使用 Amazon ECR 設定中的指示來設定](https://docs.aws.amazon.com/AmazonECR/latest/userguide/get-set-up-for-amazon-ecr.html) Amazon ECR。 **每個 AWS 帳戶都會提供預設的私有 Amazon ECR 登錄檔。 | DevOps 工程師 | 
| 建立 Amazon ECR 私有儲存庫。 | 遵循《*Amazon ECR 使用者指南*》中[建立私有儲存庫](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)的指示。您建立的儲存庫是您存放自訂 Docker 容器映像的位置。 | DevOps 工程師 | 
| 建立 Dockerfile，其中包含執行 SageMaker 處理任務所需的規格。 | 建立 Dockerfile，其中包含透過設定 Dockerfile 執行 SageMaker 處理任務所需的規格。如需說明，請參閱《*Amazon SageMaker 開發人員指南*》中的[調整您自己的訓練容器](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html)。如需 Dockerfiles 的詳細資訊，請參閱 [Docker 文件中的 Dockerfile 參考](https://docs.docker.com/engine/reference/builder/)。**建立 Dockerfile 的 Jupyter 筆記本程式碼儲存格範例***儲存格 1*<pre># Make docker folder<br />!mkdir -p docker</pre>*儲存格 2*<pre>%%writefile docker/Dockerfile<br /><br />FROM python:3.7-slim-buster<br /><br />RUN pip3 install pandas==0.25.3 scikit-learn==0.21.3<br />ENV PYTHONUNBUFFERED=TRUE<br /><br />ENTRYPOINT ["python3"]</pre> | DevOps 工程師 | 
| 建置 Docker 容器映像並將其推送至 Amazon ECR。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions.html)如需詳細資訊，請參閱[在 GitHub 上建置您自己的演算法容器中的建置和註冊](https://sagemaker-examples.readthedocs.io/en/latest/advanced_functionality/scikit_bring_your_own/scikit_bring_your_own.html#Building-and-registering-the-container)*容器*。 GitHub**建置和註冊 Docker 映像的 Jupyter 筆記本程式碼儲存格範例**在執行下列儲存格之前，請確定您已建立 Dockerfile，並將其存放在名為 的目錄中`docker`。此外，請確定您已建立 Amazon ECR 儲存庫，並將第一個儲存格中的`ecr_repository`值取代為儲存庫的名稱。*儲存格 1*<pre>import boto3<br />tag = ':latest'<br />account_id = boto3.client('sts').get_caller_identity().get('Account')<br />region = boto3.Session().region_name<br />ecr_repository = 'byoc'<br /><br />image_uri = '{}.dkr.ecr.{}.amazonaws.com/{}'.format(account_id, region, ecr_repository + tag)</pre>*儲存格 2*<pre># Build docker image<br />!docker build -t $image_uri docker</pre>*儲存格 3*<pre># Authenticate to ECR<br />!aws ecr get-login-password --region {region} | docker login --username AWS --password-stdin {account_id}.dkr.ecr.{region}.amazonaws.com</pre>*儲存格 4*<pre># Push docker image<br />!docker push $image_uri</pre>您必須[向私有登錄檔驗證 Docker 用戶端](https://docs.aws.amazon.com/AmazonECR/latest/userguide/registry_auth.html)，才能使用 `docker push`和 `docker pull`命令。這些命令會在登錄檔中的儲存庫中推送和提取映像。 | DevOps 工程師 | 

### 建立使用自訂 Docker 容器映像的 Step Functions 工作流程
<a name="create-a-step-functions-workflow-that-uses-your-custom-docker-container-image"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Python 指令碼，其中包含您的自訂處理和模型訓練邏輯。 | 撰寫要在資料處理指令碼中執行的自訂處理邏輯。然後，將其儲存為名為 的 Python 指令碼`training.py`。如需詳細資訊，請參閱[使用 GitHub 上的 SageMaker 指令碼模式使用您自己的模型](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-script-mode/sagemaker-script-mode.html)。 GitHub**包含自訂處理和模型訓練邏輯的範例 Python 指令碼**<pre>%%writefile training.py<br />from numpy import empty<br />import pandas as pd<br />import os<br />from sklearn import datasets, svm<br />from joblib import dump, load<br /><br /><br />if __name__ == '__main__':<br />    digits = datasets.load_digits()<br />    #create classifier object<br />    clf = svm.SVC(gamma=0.001, C=100.)<br />    <br />    #fit the model<br />    clf.fit(digits.data[:-1], digits.target[:-1])<br />    <br />    #model output in binary format<br />    output_path = os.path.join('/opt/ml/processing/model', "model.joblib")<br />    dump(clf, output_path)</pre> | 資料科學家 | 
| 建立 Step Functions 工作流程，其中包含您的 SageMaker Processing 任務作為其中一個步驟。 | 安裝並匯入 [AWS Step Functions 資料科學 SDK](https://aws-step-functions-data-science-sdk.readthedocs.io/en/stable/readmelink.html)，並將 **training.py** 檔案上傳至 Amazon S3。然後，使用 [Amazon SageMaker Python SDK](https://github.com/aws/sagemaker-python-sdk) 在 Step Functions 中定義處理步驟。請確定您已在 AWS [帳戶中為 Step Functions 建立 IAM 執行角色](https://sagemaker-examples.readthedocs.io/en/latest/step-functions-data-science-sdk/step_functions_mlworkflow_processing/step_functions_mlworkflow_scikit_learn_data_processing_and_model_evaluation.html#Create-an-Execution-Role-for-Step-Functions)。**要上傳至 Amazon S3 的環境設定範例和自訂訓練指令碼**<pre>!pip install stepfunctions<br /><br />import boto3<br />import stepfunctions<br />import sagemaker<br />import datetime<br /><br />from stepfunctions import steps<br />from stepfunctions.inputs import ExecutionInput<br />from stepfunctions.steps import (<br />    Chain<br />)<br />from stepfunctions.workflow import Workflow<br />from sagemaker.processing import ScriptProcessor, ProcessingInput, ProcessingOutput<br /><br />sagemaker_session = sagemaker.Session()<br />bucket = sagemaker_session.default_bucket() <br />role = sagemaker.get_execution_role()<br />prefix = 'byoc-training-model'<br /><br /># See prerequisites section to create this role<br />workflow_execution_role = f"arn:aws:iam::{account_id}:role/AmazonSageMaker-StepFunctionsWorkflowExecutionRole"<br /><br />execution_input = ExecutionInput(<br />    schema={<br />        "PreprocessingJobName": str})<br /><br /><br />input_code = sagemaker_session.upload_data(<br />    "training.py",<br />    bucket=bucket,<br />    key_prefix="preprocessing.py",<br />)</pre>**使用自訂 Amazon ECR 映像和 Python 指令碼的 SageMaker 處理步驟定義範例**請務必使用 `execution_input` 參數來指定任務名稱。每次任務執行時， 參數的值必須是唯一的。此外，**training.py** 檔案的程式碼會做為 `input` 參數傳遞至 `ProcessingStep`，這表示它將在容器內複製。`ProcessingInput` 程式碼的目的地與 中的第二個引數相同`container_entrypoint`。<pre>script_processor = ScriptProcessor(command=['python3'],<br />                image_uri=image_uri,<br />                role=role,<br />                instance_count=1,<br />                instance_type='ml.m5.xlarge')<br /><br /><br />processing_step = steps.ProcessingStep(<br />    "training-step",<br />    processor=script_processor,<br />    job_name=execution_input["PreprocessingJobName"],<br />    inputs=[<br />        ProcessingInput(<br />            source=input_code,<br />            destination="/opt/ml/processing/input/code",<br />            input_name="code",<br />        ),<br />    ],<br />    outputs=[<br />        ProcessingOutput(<br />            source='/opt/ml/processing/model', <br />            destination="s3://{}/{}".format(bucket, prefix), <br />            output_name='byoc-example')<br />    ],<br />    container_entrypoint=["python3", "/opt/ml/processing/input/code/training.py"],<br />)</pre>**執行 SageMaker 處理任務的 Step Functions 工作流程範例**此範例工作流程僅包含 SageMaker 處理任務步驟，而非完整的 Step Functions 工作流程。如需完整的工作流程範例，請參閱 AWS Step Functions 資料科學 SDK 文件[中的 SageMaker 中的範例筆記本](https://aws-step-functions-data-science-sdk.readthedocs.io/en/stable/readmelink.html#example-notebooks-in-sagemaker)。<pre>workflow_graph = Chain([processing_step])<br /><br />workflow = Workflow(<br />    name="ProcessingWorkflow",<br />    definition=workflow_graph,<br />    role=workflow_execution_role<br />)<br /><br />workflow.create()<br /># Execute workflow<br />execution = workflow.execute(<br />    inputs={<br />        "PreprocessingJobName": str(datetime.datetime.now().strftime("%Y%m%d%H%M-%SS")),  # Each pre processing job (SageMaker processing job) requires a unique name,<br />    }<br />)<br />execution_output = execution.get_output(wait=True)</pre> | 資料科學家 | 

## 相關資源
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions-resources"></a>
+ [程序資料](https://docs.aws.amazon.com/sagemaker/latest/dg/processing-job.html) (*Amazon SageMaker 開發人員指南*)
+ [調整您自己的訓練容器](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html) (*Amazon SageMaker 開發人員指南*)