

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

# 在 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)