

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

# SageMaker AI AWS Batch 入門
<a name="getting-started-sagemaker"></a>

AWS Batch 服務任務可讓您透過具有排程、優先順序和佇列功能 AWS Batch 的任務佇列提交 SageMaker 訓練任務。本教學課程示範如何使用 AWS Batch 服務任務來設定和執行簡單的 SageMaker Training 任務。

**Contents**
+ [概觀](#getting-started-sagemaker-context)
+ [先決條件](#getting-started-sagemaker-prerequisites)
+ [步驟 1：建立 SageMaker AI 執行角色](#getting-started-sagemaker-step-1)
+ [步驟 2：建立您的服務環境](#getting-started-sagemaker-step-2)
+ [步驟 3：建立 SageMaker 任務佇列](#getting-started-sagemaker-step-3)
+ [步驟 4：建立並提交訓練任務](#getting-started-sagemaker-step-4)
+ [步驟 5：監控任務狀態](#getting-started-sagemaker-step-5)
+ [步驟 6：檢視任務輸出](#getting-started-sagemaker-step-6)
+ [步驟 7：清除您的教學課程資源](#getting-started-sagemaker-step-7)
+ [其他資源](#getting-started-sagemaker-additional-resources)

## 概觀
<a name="getting-started-sagemaker-context"></a>

本教學課程示範如何使用 設定 SageMaker Training 任務 AWS Batch 的服務任務 AWS CLI。

**目標對象**  
本教學課程專為負責大規模設定和執行機器學習訓練任務的資料科學家和開發人員而設計。

**使用的功能**  
本教學課程說明如何使用 AWS CLI 來：  
+ 為 SageMaker Training 任務建立服務環境
+ 建立 SageMaker 訓練任務佇列
+ 使用 `SubmitServiceJob` API 提交服務任務
+ 監控任務狀態並檢視輸出
+ 存取訓練任務的 CloudWatch 日誌

**所需時間**  
此教學課程需約 15 分鐘完成。

**區域限制**  
本教學課程可在可使用 AWS Batch 和 SageMaker AI 的任何 AWS 區域中完成。

**資源用量成本**  
建立 AWS 帳戶無需付費。不過，透過實作此解決方案，您可能會產生下列資源的成本：      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/batch/latest/userguide/getting-started-sagemaker.html)

## 先決條件
<a name="getting-started-sagemaker-prerequisites"></a>

開始本教學課程之前，您必須安裝並設定下列工具和資源，以建立和管理 AWS Batch 和 SageMaker AI 資源。
+ **AWS CLI** – 用於使用 AWS 服務的命令列工具，包括 AWS Batch 和 SageMaker AI。本指南要求您使用 2.8.6 版或更新版本。如需詳細資訊，請參閱*AWS Command Line Interface 《 使用者指南*》中的[安裝、更新和解除安裝 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) 。安裝 之後 AWS CLI，建議您也進行設定。如需詳細資訊，請參閱*AWS Command Line Interface 《 使用者指南*》中的使用 進行[快速組態`aws configure`](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-config)。

## 步驟 1：建立 SageMaker AI 執行角色
<a name="getting-started-sagemaker-step-1"></a>

SageMaker AI 使用執行角色來代表您使用其他服務 AWS 來執行操作。您必須建立執行角色，並授予 SageMaker AI 許可，以使用訓練任務所需的服務和資源。使用 `AmazonSageMakerFullAccess`受管政策，因為它包含 Amazon S3 的許可。

**注意**  
請使用下列指示來建立本教學課程的 SageMaker AI 執行角色。  
在您為生產環境建立執行角色之前，我們建議您檢閱 [ SageMaker AI 開發人員指南中的如何使用 SageMaker AI 執行角色](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html)。 *[SageMaker ](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html)*

1. 

**建立 IAM 角色**

   使用下列信任政策建立名為 `sagemaker-trust-policy.json`的 JSON 檔案：

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Principal": {
                   "Service": "sagemaker.amazonaws.com"
               },
               "Action": "sts:AssumeRole"
           }
       ]
   }
   ```

------

   使用信任政策建立 IAM 角色：

   ```
   aws iam create-role \
       --role-name SageMakerExecutionRole \
       --assume-role-policy-document file://sagemaker-trust-policy.json \
       --description "Execution role for SageMaker training jobs"
   ```

1. 

**連接 受管政策**

   將所需的 受管政策連接至角色：

   ```
   aws iam attach-role-policy \
       --role-name SageMakerExecutionRole \
       --policy-arn arn:aws:iam::aws:policy/AmazonSageMakerFullAccess
   ```

   ```
   aws iam attach-role-policy \
       --role-name SageMakerExecutionRole \
       --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess
   ```

1. 

**請注意角色 ARN**

   取得角色 ARN，您會在後續步驟中需要此角色：

   ```
   aws iam get-role --role-name SageMakerExecutionRole --query 'Role.Arn' --output text
   ```

   儲存此 ARN，因為您將在建立訓練任務承載時使用它。

## 步驟 2：建立您的服務環境
<a name="getting-started-sagemaker-step-2"></a>

服務環境定義 SageMaker Training 任務的容量限制。服務環境會封裝可同時執行的訓練執行個體數量上限。

**重要**  
當您為 SageMaker Training 建立第一個服務環境時， AWS Batch 會自動在您的`AWSServiceRoleForAWSBatchWithSagemaker`帳戶中建立名為 的服務連結角色。此角色允許 代表您 AWS Batch 佇列和管理 SageMaker Training 任務。如需此服務連結角色及其許可的詳細資訊，請參閱 [將 的角色 AWS Batch 與 SageMaker AI 搭配使用](using-service-linked-roles-batch-sagemaker.md)。

建立可處理最多 5 個執行個體的服務環境：

```
aws batch create-service-environment \
    --service-environment-name TutorialServiceEnvironment \
    --service-environment-type SAGEMAKER_TRAINING \
    --capacity-limits capacityUnit=NUM_INSTANCES,maxCapacity=5
```

輸出：

```
{
    "serviceEnvironmentName": "TutorialServiceEnvironment",
    "serviceEnvironmentArn": "arn:aws:batch:your-region:your-account-id:service-environment/TutorialServiceEnvironment"
}
```

確認您的服務環境已成功建立：

```
aws batch describe-service-environments --service-environments TutorialServiceEnvironment
```

輸出：

```
{
    "serviceEnvironments": [
        {
            "serviceEnvironmentName": "TutorialServiceEnvironment",
            "serviceEnvironmentArn": "arn:aws:batch:your-region:your-account-id:service-environment/TutorialServiceEnvironment",
            "serviceEnvironmentType": "SAGEMAKER_TRAINING",
            "state": "ENABLED",
            "status": "VALID",
            "capacityLimits": [
                {
                    "maxCapacity": 5,
                    "capacityUnit": "NUM_INSTANCES"
                }
            ],
            "tags": {}
        }
    ]
}
```

如需服務環境的詳細資訊，請參閱 [的服務環境 AWS Batch](service-environments.md)。

## 步驟 3：建立 SageMaker 任務佇列
<a name="getting-started-sagemaker-step-3"></a>

SageMaker 任務佇列會管理服務任務的排程和執行。提交至此佇列的任務將根據可用容量分派至您的服務環境。

建立 SageMaker 訓練任務佇列：

```
aws batch create-job-queue \
    --job-queue-name my-sm-training-fifo-jq \
    --job-queue-type SAGEMAKER_TRAINING \
    --priority 1 \
    --service-environment-order order=1,serviceEnvironment=TutorialServiceEnvironment
```

輸出：

```
{
    "jobQueueName": "my-sm-training-fifo-jq",
    "jobQueueArn": "arn:aws:batch:your-region:your-account-id:job-queue/my-sm-training-fifo-jq"
}
```

確認您的任務佇列已成功建立：

```
aws batch describe-job-queues --job-queues my-sm-training-fifo-jq
```

輸出：

```
{
    "jobQueues": [
        {
            "jobQueueName": "my-sm-training-fifo-jq",
            "jobQueueArn": "arn:aws:batch:your-region:your-account-id:job-queue/my-sm-training-fifo-jq",
            "state": "ENABLED",
            "status": "VALID",
            "statusReason": "JobQueue Healthy",
            "priority": 1,
            "computeEnvironmentOrder": [],
            "serviceEnvironmentOrder": [
                {
                    "order": 1,
                    "serviceEnvironment": "arn:aws:batch:your-region:your-account-id:service-environment/TutorialServiceEnvironment"
                }
            ],
            "jobQueueType": "SAGEMAKER_TRAINING",
            "tags": {}
        }
    ]
}
```

如需 SageMaker 任務佇列的詳細資訊，請參閱 [在 中建立 SageMaker 訓練任務佇列 AWS Batch](create-sagemaker-job-queue.md)。

## 步驟 4：建立並提交訓練任務
<a name="getting-started-sagemaker-step-4"></a>

現在，您將建立簡單的訓練任務，並將其提交到您的任務佇列。此範例使用基本的「hello world」訓練任務，示範服務任務功能。

建立名為 `my_training_job.json` 且具有下列內容的檔案。將 *your-account-id* 取代為您的帳戶 AWS ID：

**注意**  
`S3OutputPath` 建立 SageMaker 訓練任務時需要 ，但本教學課程的結果不會存放在 Amazon S3 儲存貯體中，您可以在下列 JSON 中使用 路徑。在您的生產環境中，如果您選擇，將需要有效的 Amazon S3 儲存貯體來將輸出存放在該處。

```
{
    "TrainingJobName": "my-simple-training-job",
    "RoleArn": "arn:aws:iam::your-account-id:role/SageMakerExecutionRole",
    "AlgorithmSpecification": {
        "TrainingInputMode": "File",
        "TrainingImage": "763104351884.dkr.ecr.us-west-2.amazonaws.com/pytorch-training:2.0.0-cpu-py310",
        "ContainerEntrypoint": [
            "echo",
            "hello world"
        ]
    },
    "ResourceConfig": {
        "InstanceType": "ml.c5.xlarge",
        "InstanceCount": 1,
        "VolumeSizeInGB": 1
    },
    "OutputDataConfig": {
        "S3OutputPath": "s3://your-s3-bucket/output"
    },
    "StoppingCondition": {
        "MaxRuntimeInSeconds": 30
    }
}
```

使用 [SubmitServiceJob](https://docs.aws.amazon.com/batch/latest/APIReference/API_SubmitServiceJob.html) API 提交訓練任務：

```
aws batch submit-service-job \
    --job-queue my-sm-training-fifo-jq \
    --job-name my-batch-sm-job \
    --service-job-type SAGEMAKER_TRAINING \
    --retry-strategy attempts=1 \
    --timeout-config attemptDurationSeconds=60 \
    --service-request-payload file://my_training_job.json
```

輸出：

```
{
    "jobArn": "arn:aws:batch:your-region:your-account-id:service-job/your-job-id",
    "jobName": "my-batch-sm-job",
    "jobId": "your-job-id"
}
```

如需服務任務承載的詳細資訊，請參閱 [中的服務任務承載 AWS Batch](service-job-payload.md)。如需提交服務任務的詳細資訊，請參閱 [在 中提交服務任務 AWS Batch](service-job-submit.md)。

## 步驟 5：監控任務狀態
<a name="getting-started-sagemaker-step-5"></a>

您可以使用下列 AWS Batch APIs監控訓練任務：[DescribeServiceJob](https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeServiceJob.html)、[ListServiceJobs](https://docs.aws.amazon.com/batch/latest/APIReference/API_ListServiceJobs.html) 和 [GetJobQueueSnapshot](https://docs.aws.amazon.com/batch/latest/APIReference/API_GetJobQueueSnapshot.html)。本節顯示檢查任務狀態和佇列資訊的不同方式。

檢視佇列中正在執行的任務：

```
aws batch list-service-jobs \
    --job-queue my-sm-training-fifo-jq --job-status RUNNING
```

輸出：

```
{
    "jobSummaryList": [
        {
            "latestAttempt": {
                "serviceResourceId": {
                    "name": "TrainingJobArn",
                    "value": "arn:aws:sagemaker:your-region:your-account-id:training-job/AWSBatch<my-simple-training-job><your-attempt-id>"
                }
            },
            "createdAt": 1753718760,
            "jobArn": "arn:aws:batch:your-region:your-account-id:service-job/your-job-id",
            "jobId": "your-job-id",
            "jobName": "my-batch-sm-job",
            "serviceJobType": "SAGEMAKER_TRAINING",
            "status": "RUNNING",
            "startedAt": 1753718820
        }
    ]
}
```

檢視處於 `RUNNABLE` 狀態的任務：

```
aws batch list-service-jobs \
    --job-queue my-sm-training-fifo-jq --job-status RUNNABLE
```

取得佇列中即將執行任務的快照：

```
aws batch get-job-queue-snapshot --job-queue my-sm-training-fifo-jq
```

輸出：

```
{
    "frontOfQueue": {
        "jobs": [
            {
                "jobArn": "arn:aws:batch:your-region:your-account-id:service-job/your-job-id",
                "earliestTimeAtPosition": 1753718880
            },
            {
                "jobArn": "arn:aws:batch:your-region:your-account-id:service-job/your-job-id-2",
                "earliestTimeAtPosition": 1753718940
            }
        ],
        "lastUpdatedAt": 1753718970
    }
}
```

依名稱搜尋任務：

```
aws batch list-service-jobs \
    --job-queue my-sm-training-fifo-jq \
    --filters name=JOB_NAME,values="my-batch-sm-job"
```

輸出：

```
{
    "jobSummaryList": [
        {
            "latestAttempt": {
                "serviceResourceId": {
                    "name": "TrainingJobArn",
                    "value": "arn:aws:sagemaker:your-region:your-account-id:training-job/AWSBatch<my-simple-training-job><your-attempt-id>"
                }
            },
            "createdAt": 1753718760,
            "jobArn": "arn:aws:batch:your-region:your-account-id:service-job/your-job-id",
            "jobId": "your-job-id",
            "jobName": "my-batch-sm-job",
            "serviceJobType": "SAGEMAKER_TRAINING",
            "status": "RUNNING"
        }
    ]
}
```

如需任務狀態映射的詳細資訊，請參閱 [將 AWS Batch 服務任務狀態映射至 SageMaker AI 狀態](service-job-status.md)。

## 步驟 6：檢視任務輸出
<a name="getting-started-sagemaker-step-6"></a>

任務完成後，您可以透過 和 SageMaker AI APIs來檢視其輸出 AWS Batch 和日誌。

從 取得任務的詳細資訊 AWS Batch：

```
aws batch describe-service-job \
    --job-id your-job-id
```

輸出：

```
{
    "attempts": [
        {
            "serviceResourceId": {
                "name": "TrainingJobArn",
                "value": "arn:aws:sagemaker:your-region:your-account-id:training-job/AWSBatch<my-simple-training-job><your-attempt-id>"
            },
            "startedAt": 1753718820,
            "stoppedAt": 1753718880,
            "statusReason": "Received status from SageMaker: Training job completed"
        }
    ],
    "createdAt": 1753718760,
    "jobArn": "arn:aws:batch:your-region:your-account-id:service-job/your-job-id",
    "jobId": "your-job-id",
    "jobName": "my-batch-sm-job",
    "jobQueue": "arn:aws:batch:your-region:your-account-id:job-queue/my-sm-training-fifo-jq",
    "latestAttempt": {
        "serviceResourceId": {
            "name": "TrainingJobArn",
            "value": "arn:aws:sagemaker:your-region:your-account-id:training-job/AWSBatch<my-simple-training-job><your-attempt-id>"
        }
    },
    "retryStrategy": {
        "attempts": 1,
        "evaluateOnExit": []
    },
    "serviceRequestPayload": "your-training-job-request-json",
    "serviceJobType": "SAGEMAKER_TRAINING",
    "startedAt": 1753718820,
    "status": "SUCCEEDED",
    "statusReason": "Received status from SageMaker: Training job completed",
    "stoppedAt": 1753718880,
    "tags": {},
    "timeoutConfig": {
        "attemptDurationSeconds": 60
    }
}
```

此命令會傳回完整的任務資訊，包括 SageMaker Training 任務 ARN，您可以用來直接透過 SageMaker AI 存取任務：

```
aws sagemaker describe-training-job \
    --training-job-name AWSBatch<my-simple-training-job><your-attempt-id>
```

若要檢視訓練任務的 CloudWatch 日誌，請先取得日誌串流名稱：

```
aws logs describe-log-streams \
    --log-group-name /aws/sagemaker/TrainingJobs \
    --log-stream-name-prefix AWSBatchmy-simple-training-job
```

輸出：

```
{
    "logStreams": [
        {
            "logStreamName": "your-log-stream-name",
            "creationTime": 1753718830,
            "firstEventTimestamp": 1753718840,
            "lastEventTimestamp": 1753718850,
            "lastIngestionTime": 1753718860,
            "uploadSequenceToken": upload-sequence-token,
            "arn": "arn:aws:logs:your-region:your-account-id:log-group:/aws/sagemaker/TrainingJobs:log-stream:AWSBatch<my-simple-training-job><your-attempt-id>/algo-1-algo-id",
            "storedBytes": 0
        }
    ]
}
```

然後使用先前回應中的日誌串流名稱擷取日誌：

```
aws logs get-log-events \
    --log-group-name /aws/sagemaker/TrainingJobs \
    --log-stream-name your-log-stream-name
```

輸出：

```
{
    "events": [
        {
            "timestamp": 1753718845,
            "message": "hello world",
            "ingestionTime": 1753718865
        }
    ],
    "nextForwardToken": "next-forward-token",
    "nextBackwardToken": "next-backward-token"
}
```

日誌輸出會顯示來自訓練任務的「hello world」訊息，確認任務已成功執行。

## 步驟 7：清除您的教學課程資源
<a name="getting-started-sagemaker-step-7"></a>

完成教學課程後，請清除您建立的資源，以避免持續收費。

首先，停用和刪除任務佇列：

```
aws batch update-job-queue \
    --job-queue my-sm-training-fifo-jq \
    --state DISABLED
```

等待任務佇列停用，然後刪除它：

```
aws batch delete-job-queue \
    --job-queue my-sm-training-fifo-jq
```

接著，停用和刪除服務環境：

```
aws batch update-service-environment \
    --service-environment TutorialServiceEnvironment \
    --state DISABLED
```

等待服務環境停用，然後刪除它：

```
aws batch delete-service-environment \
    --service-environment TutorialServiceEnvironment
```

## 其他資源
<a name="getting-started-sagemaker-additional-resources"></a>

完成教學課程後，您可能想要探索下列主題：
+ 我們建議您使用 PySDK 建立服務任務並提交到您的任務佇列，因為 PySDK 具有協助程式類別和公用程式。如需使用 PySDK 的範例，請參閱 GitHub 上的 [SageMaker AI 範例](https://github.com/aws/amazon-sagemaker-examples)。
+ 進一步了解 [中的服務任務 AWS Batch](service-jobs.md)。
+ 探索[中的服務任務承載 AWS Batch](service-job-payload.md)更複雜的訓練任務組態。
+ 了解 [在 中提交服務任務 AWS Batch](service-job-submit.md)和 `SubmitServiceJob` API。
+ 檢閱[將 AWS Batch 服務任務狀態映射至 SageMaker AI 狀態](service-job-status.md)以了解任務狀態轉換。
+ 如需使用 [Python 建立和提交 SageMaker 訓練任務的更豐富功能，請造訪 SageMaker AI Python SDK 文件](https://sagemaker.readthedocs.io/en/stable/)。 SageMaker 
+ 探索 [SageMaker 範例筆記本](https://github.com/aws/amazon-sagemaker-examples)，以取得更複雜的機器學習工作流程。