

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

# SageMaker 訓練任務的訓練計畫使用率
<a name="training-plan-utilization-for-training-jobs"></a>

您可以針對訓練任務使用 SageMaker 訓練計畫，方法是在建立訓練任務時指定您選擇的計畫。

**注意**  
訓練計畫必須處於 `Scheduled` 或 `Active` 狀態，才能供訓練任務使用。

如果訓練任務無法立即使用所需的容量，任務會等到該容量可用或等到符合 `StoppingCondition`，或任務已為容量 `Pending` 2 天，以先到者為準。如果符合停止條件，則會停止任務。如果任務已待定 2 天，則會以 `InsufficientCapacityError` 將其終止。

**重要**  
**預留容量終止程序：**您可以在預留容量結束時間前 30 分鐘完整存取所有預留執行個體。當預留容量剩餘 30 分鐘時，SageMaker 訓練計畫會開始終止該預留容量內任何執行中的執行個體。  
為了確保您不會由於這些終止而失去進度，建議您為訓練任務設定檢查點。

## 為您的訓練任務設定檢查點
<a name="training-jobs-checkpointing"></a>

針對 SageMaker 訓練任務使用 SageMaker 訓練計畫時，請務必在訓練指令碼中實作檢查點。這可讓您在預留容量過期之前儲存訓練進度。使用預留容量時，檢查點特別重要，因為如果您的任務在兩個預留容量之間中斷，或您的訓練計畫來到結束日期時，它可讓您從最後一個儲存點繼續訓練。

若要完成此操作，您可以使用 `SAGEMAKER_CURRENT_CAPACITY_BLOCK_EXPIRATION_TIMESTAMP` 環境變數。此變數有助於判斷何時啟動檢查點程序。透過將此邏輯納入您的訓練指令碼中，您可以確保以適當的間隔儲存模型的進度。

以下是如何在 Python 訓練指令碼中實作此檢查點邏輯的範例：

```
import os
import time
from datetime import datetime, timedelta

def is_close_to_expiration(threshold_minutes=30):
    # Retrieve the expiration timestamp from the environment variable
    expiration_time_str = os.environ.get('SAGEMAKER_CURRENT_CAPACITY_BLOCK_EXPIRATION_TIMESTAMP', '0')
    
    # If the timestamp is not set (default '0'), return False
    if expiration_time_str == '0':
        return False
    
    # Convert the timestamp string (in milliseconds) to a datetime object
    expiration_time = datetime(1970, 1, 1) + timedelta(milliseconds=int(expiration_time_str))
    
    # Calculate the time difference between now and the expiration time
    time_difference = expiration_time - datetime.now()
    
    # Return True if we're within the threshold time of expiration
    return time_difference < timedelta(minutes=threshold_minutes)

def start_checkpointing():
    # Placeholder function for checkpointing logic
    print("Starting checkpointing process...")
    # TODO: Implement actual checkpointing logic here
    # For example:
    # - Save model state
    # - Save optimizer state
    # - Save current epoch and iteration numbers
    # - Save any other relevant training state

# Main training loop
num_epochs = 100
final_checkpointing_done = False
for epoch in range(num_epochs):
    # TODO: Replace this with your actual training code
    # For example:
    # - Load a batch of data
    # - Forward pass
    # - Calculate loss
    # - Backward pass
    # - Update model parameters
    
    # Check if we're close to capacity expiration and haven't done final checkpointing
    if not final_checkpointing_done and is_close_to_expiration():
        start_checkpointing()
        final_checkpointing_done = True
    
    # Simulate some training time (remove this in actual implementation)
    time.sleep(1)
print("Training completed.")
```

**注意**  
訓練任務佈建遵循先進先出 (FIFO) 順序，但如果無法完成較大的任務，稍後建立的較小叢集任務可能會在先前建立的較大叢集任務之前獲指派容量。
SageMaker 訓練受管暖集區與 SageMaker 訓練計畫相容。如需重複使用叢集，您必須在後續 `CreateTrainingJob` 請求中提供相同的 `TrainingPlanArn` 值，才能重複使用相同的叢集。

**Topics**
+ [為您的訓練任務設定檢查點](#training-jobs-checkpointing)
+ [使用 SageMaker AI 主控台建立訓練任務](use-training-plan-for-training-jobs-using-console.md)
+ [使用 API、 AWS CLI SageMaker SDK 建立訓練任務](use-training-plan-for-training-jobs-using-api-cli-sdk.md)

# 使用 SageMaker AI 主控台建立訓練任務
<a name="use-training-plan-for-training-jobs-using-console"></a>

您可以使用 SageMaker AI UI，針對訓練任務使用 SageMaker 訓練計畫。建立訓練任務時，如果您的執行個體選擇和區域符合可用的計畫，建議您使用可用的計畫。

若要在 SageMaker 主控台中使用訓練計畫的預留容量建立訓練任務：

1. 導覽至 SageMaker AI 主控台，網址為 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/)。

1. 在左側導覽窗格中，選擇**訓練**，然後選擇**訓練任務**。

1. 選擇**建立訓練任務**按鈕。

1. 為您的訓練任務設定資源時，請尋找**執行個體容量**區段。如果有符合您所選執行個體類型和區域的可用計畫，則這裡會顯示這些計畫。選取符合您運算容量需求的訓練計畫。

   如果沒有適合的計畫可用，您可以調整執行個體類型或區域，或繼續進行而不使用訓練計畫。

1. 選取訓練計畫 (或選擇在沒有訓練計畫的情況下繼續進行) 後，請完成其餘的訓練任務組態，然後選擇**建立訓練任務**以開始程序。

![\[SageMaker AI 主控台頁面，用於建立新的訓練任務。此頁面會顯示各種組態選項，包括任務設定、演算法選項、資源組態、訓練計畫選擇，以及停止條件。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/training-plans/tp-create-training-job.png)


檢閱並啟動您的任務。訓練計畫一變成 `Active` (待定容量)，您的任務就會開始執行。

# 使用 API、 AWS CLI SageMaker SDK 建立訓練任務
<a name="use-training-plan-for-training-jobs-using-api-cli-sdk"></a>

若要針對 SageMaker 訓練任務使用 SageMaker 訓練計畫，請在呼叫 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html) API 操作時，在 `ResourceConfig` 中指定所需計畫的 `TrainingPlanArn` 參數。您只能每個任務使用一個計畫。

**重要**  
`CreateTrainingJob` 請求的 `ResourceConfig` 區段中設定的 `InstanceType` 欄位集必須符合訓練計畫的 `InstanceType`。

## 使用 CLI 在計畫上執行訓練任務
<a name="training-job-cli"></a>

下列範例示範如何建立 SageMaker 訓練任務，並使用 `TrainingPlanArn` `create-training-job` AWS CLI 命令中的 屬性將其與提供的訓練計畫建立關聯。

如需如何使用 AWS CLI [CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html) 命令建立訓練任務的詳細資訊，請參閱 [https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-training-job.html](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-training-job.html)。

```
# Create a training job
aws sagemaker create-training-job \
  --training-job-name training-job-name \
  ...
    
  --resource-config '{
        "InstanceType": "ml.p5.48xlarge",
        "InstanceCount": 8,
        "VolumeSizeInGB": 10,
        "TrainingPlanArn": "training-plan-arn"
        }
    }' \
    ...
```

此 AWS CLI 範例命令會在 SageMaker AI 中建立新的訓練任務，並在 `--resource-config` 引數中傳遞訓練計畫。

```
aws sagemaker create-training-job \
  --training-job-name job-name \
  --role-arn arn:aws:iam::111122223333:role/DataAndAPIAccessRole \
  --algorithm-specification '{"TrainingInputMode": "File","TrainingImage": "111122223333.dkr.ecr.us-east-1.amazonaws.com/algo-image:tag", "ContainerArguments": [" "]}' \
  --input-data-config '[{"ChannelName":"training","DataSource":{"S3DataSource":{"S3DataType":"S3Prefix","S3Uri":"s3://bucketname/input","S3DataDistributionType":"ShardedByS3Key"}}}]' \
  --output-data-config '{"S3OutputPath": "s3://bucketname/output"}' \
  --resource-config '{"VolumeSizeInGB":10,"InstanceCount":4,"InstanceType":"ml.p5.48xlarge", "TrainingPlanArn" : "arn:aws:sagemaker:us-east-1:111122223333:training-plan/plan-name"}' \
  --stopping-condition '{"MaxRuntimeInSeconds": 1800}' \
  --region us-east-1
```

在建立訓練任務之後，您可以透過呼叫 `DescribeTrainingJob` API 來驗證是否已正確指派給訓練計畫。

```
aws sagemaker describe-training-job --training-job-name training-job-name
```

## 使用 SageMaker AI Python SDK 在計畫上執行訓練任務
<a name="training-job-sdk"></a>

或者，您可以使用 [SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable/v2.html) 建立與訓練計畫相關聯的訓練任務。

如果您在 Studio 中使用來自 JupyterLab 的 SageMaker Python SDK 建立訓練任務，請確定執行 JupyterLab 應用程式之空間所使用的執行角色，具有使用 SageMaker 訓練計畫所需的許可。若要了解使用 SageMaker 訓練計畫所需的許可，請參閱 [IAM for SageMaker 訓練計畫](training-plan-iam-permissions.md)。

下列範例示範如何在使用 SageMaker Python SDK 時，使用 `Estimator` 物件中的 `training_plan` 屬性建立 SageMaker 訓練任務，並將其與提供的訓練計畫建立關聯。

如需 SageMaker 估算器的詳細資訊，請參閱[使用 SageMaker 估算器來執行訓練任務](https://docs.aws.amazon.com/sagemaker/latest/dg/docker-containers-adapt-your-own-private-registry-estimator.html)。

```
import sagemaker
import boto3
from sagemaker import get_execution_role
from sagemaker.estimator import Estimator
from sagemaker.inputs import TrainingInput

# Set up the session and SageMaker client
session = boto3.Session()
region = session.region_name
sagemaker_session = session.client('sagemaker')

# Get the execution role for the training job
role = get_execution_role()

# Define the input data configuration
trainingInput = TrainingInput(
    s3_data='s3://input-path',
    distribution='ShardedByS3Key',
    s3_data_type='S3Prefix'
)

estimator = Estimator(
    entry_point='train.py',
    image_uri="123456789123.dkr.ecr.{}.amazonaws.com/image:tag",
    role=role,
    instance_count=4,
    instance_type='ml.p5.48xlarge',
    training_plan="training-plan-arn",
    volume_size=20,
    max_run=3600,
    sagemaker_session=sagemaker_session,
    output_path="s3://output-path"
)

# Create the training job
estimator.fit(inputs=trainingInput, job_name=job_name)
```

在建立訓練任務之後，您可以透過呼叫 `DescribeTrainingJob` API 來驗證是否已正確指派給訓練計畫。

```
# Check job details
sagemaker_session.describe_training_job(TrainingJobName=job_name)
```