View a markdown version of this page

在训练作业中使用 SageMaker 训练计划 - 亚马逊 SageMaker AI
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

在训练作业中使用 SageMaker 训练计划

通过在创建 SageMaker 训练作业时指定自己选择的计划,可以将训练计划用于训练作业。

注意

训练计划必须处于 ScheduledActive 状态才能供训练作业使用。

如果所需容量无法立即用于训练作业,则作业将等待直至该容量可用,直到满足 StoppingCondition 或作业为获得容量而处于 Pending 达 2 天(以先满足的条件为准)。如果满足停止条件,则将停止作业。如果作业已处于待处理状态达 2 天,则作业将被终止,并显示 InsufficientCapacityError

重要

预留容量终止流程:在预留容量结束时间前 30 分钟,您都可完全使用所有预留实例。当您的预留容量还剩 30 分钟时, SageMaker 培训计划将开始终止该预留容量内任何正在运行的实例。

为确保您不会因这些终止操作而丢失进度,我们建议您为训练作业设置检查点。

为训练作业设置检查点

在 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.")
注意
  • 训练作业配置遵循 First-In-First-Out (FIFO)顺序,但是如果无法完成较大的任务,则稍后创建的较小集群作业可能会先分配容量,然后再分配先前创建的较大集群作业。

  • SageMaker 训练管理的温水池与 SageMaker 训练计划兼容。要重复使用集群,您必须在后续 CreateTrainingJob 请求中提供相同的 TrainingPlanArn 值才能重复使用同一集群。