

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

# 自動擴展非同步端點
<a name="async-inference-autoscale"></a>

Amazon SageMaker AI 支援自動擴展您的非同步端點。自動擴展會動態調整針對模型佈建的執行個體數量，因應工作負載的變更。與其他託管模型 Amazon SageMaker AI 支援不同，使用非同步推論，您也可以將非同步端點執行個體縮減為零。擴展端點後，執行個體數量為零時，收到的請求會排入佇列進行處理。

若要自動擴展非同步端點的規模，您至少必須：
+ 註冊已部署的模型 (生產變體)。
+ 定義擴展政策。
+ 套用自動擴展政策。

您必須先將模型部署到 SageMaker AI 端點，才能使用自動擴展。部署的模型稱為[生產變體](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProductionVariant.html)。如需將模型部署到端點的詳細資訊，請參閱[將模型部署到 SageMaker 託管服務](https://docs.aws.amazon.com/sagemaker/latest/dg/ex1-model-deployment.html#ex1-deploy-model)。若要指定擴展政策的指標和目標值，您可以設定擴展政策。有關如何定義擴展策略的資訊，請參閱[定義擴展策略](https://docs.aws.amazon.com/sagemaker/latest/dg/endpoint-auto-scaling-add-code-define.html)。在登錄您的模型和制定擴展政策之後，請將此擴展政策套用到已登錄的模型。有關如何應用擴展策略的資訊，請參閱[應用擴展策略](https://docs.aws.amazon.com/sagemaker/latest/dg/endpoint-auto-scaling-add-code-apply.html)。

如需如何定義其他選用擴展政策，在端點縮減為零後收到請求時擴展端點的詳細資訊，請參閱[選用：定義新請求從零擴展的擴展政策](#async-inference-autoscale-scale-up)。如果未指定這個選用政策，則端點只會在待辦項目請求數量超出目標追蹤值後，才會從零啟動擴展。

 有關與自動縮放搭配使用的其他先決條件和元件的詳細資訊，請參閱 SageMaker AI 自動擴展文件中的[先決條件](https://docs.aws.amazon.com/sagemaker/latest/dg/endpoint-auto-scaling-prerequisites.html)區段。

**注意**  
如果您將多個擴展政策連接到相同的自動擴展群組，則可能發生擴展衝突。發生衝突時，Amazon EC2 Auto Scaling 會選擇對於擴增和縮減均可佈建容量上限的政策。如需有關此行為的詳細資訊，請參閱 *Amazon EC2 Auto Scaling 文件*中的[多個動態擴展政策](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scale-based-on-demand.html#multiple-scaling-policy-resolution)。

## 定義擴展政策
<a name="async-inference-autoscale-define-async"></a>

若要指定擴展政策的指標和目標值，您可以設定目標追蹤規模調整政策。將擴展政策定義為文字檔案中的 JSON 區塊。您可以使用該文字檔案來調用 AWS CLI 或 Application Auto Scaling API。如需政策組態語法的詳細資訊，請參閱 [Application Auto Scaling API 參考](https://docs.aws.amazon.com/autoscaling/application/APIReference/API_TargetTrackingScalingPolicyConfiguration.html)中的 `TargetTrackingScalingPolicyConfiguration`。

針對非同步端點，SageMaker AI 強烈建議您建立針對變體進行目標追蹤擴展的政策組態。在這個組態範例中，我們使用稱為 `ApproximateBacklogSizePerInstance` 的自訂指標 `CustomizedMetricSpecification`。

```
TargetTrackingScalingPolicyConfiguration={
        'TargetValue': 5.0, # The target value for the metric. Here the metric is: ApproximateBacklogSizePerInstance
        'CustomizedMetricSpecification': {
            'MetricName': 'ApproximateBacklogSizePerInstance',
            'Namespace': 'AWS/SageMaker',
            'Dimensions': [
                {'Name': 'EndpointName', 'Value': <endpoint_name> }
            ],
            'Statistic': 'Average',
        }
    }
```

## 定義可擴展至零的擴展政策
<a name="async-inference-autoscale-define-async-zero"></a>

以下示範如何使用 適用於 Python (Boto3) 的 AWS SDK，透過應用程式自動擴展搭配定義和註冊端點變體。使用 Boto3 定義代表應用程式自動擴展的低階用戶端物件後，我們使用 [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/application-autoscaling.html#ApplicationAutoScaling.Client.register_scalable_target](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/application-autoscaling.html#ApplicationAutoScaling.Client.register_scalable_target) 方法註冊生產變體。我們將 `MinCapacity` 設定為 0，因為在沒有要處理請求時，非同步推論可讓您自動擴展至 0。

```
# Common class representing application autoscaling for SageMaker 
client = boto3.client('application-autoscaling') 

# This is the format in which application autoscaling references the endpoint
resource_id='endpoint/' + <endpoint_name> + '/variant/' + <'variant1'> 

# Define and register your endpoint variant
response = client.register_scalable_target(
    ServiceNamespace='sagemaker', 
    ResourceId=resource_id,
    ScalableDimension='sagemaker:variant:DesiredInstanceCount', # The number of EC2 instances for your Amazon SageMaker model endpoint variant.
    MinCapacity=0,
    MaxCapacity=5
)
```

有關應用程式自動擴展 API 的詳細說明，請參閱[應用程式縮放肉毒桿菌 3](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/application-autoscaling.html#ApplicationAutoScaling.Client.register_scalable_target) 文件。

## 選用：定義新請求從零擴展的擴展政策
<a name="async-inference-autoscale-scale-up"></a>

您可能有一個使用案例，其中具有零星請求或請求數量較少的期間。如果您的端點在這些期間縮減為零個執行個體，則佇列中的請求數量超出擴展政策中所指定的目標後，您的端點才會再次擴展。這可能會導致佇列中的請求等待時間很長。以下一節示範如何建立其他擴展政策，在佇列中收到任何新請求後，將端點從零個執行個體進行擴展。您的端點將能夠更快地回應新請求，而不是等待佇列大小超出目標。

若要建立從零個執行個體擴展的端點擴展政策，請執行以下操作：

1. 建立定義所需行為的擴展政策，在執行個體數量為零但佇列中有請求時擴展端點。以下示範如何使用 適用於 Python (Boto3) 的 AWS SDK 定義稱為 `HasBacklogWithoutCapacity-ScalingPolicy` 的擴展政策。當佇列大於零，而且端點目前執行個體計數也為零時，該政策會擴展您的端點。在所有其他情況下，該政策不會影響端點的擴展。

   ```
   response = client.put_scaling_policy(
       PolicyName="HasBacklogWithoutCapacity-ScalingPolicy",
       ServiceNamespace="sagemaker",  # The namespace of the service that provides the resource.
       ResourceId=resource_id,  # Endpoint name
       ScalableDimension="sagemaker:variant:DesiredInstanceCount",  # SageMaker supports only Instance Count
       PolicyType="StepScaling",  # 'StepScaling' or 'TargetTrackingScaling'
       StepScalingPolicyConfiguration={
           "AdjustmentType": "ChangeInCapacity", # Specifies whether the ScalingAdjustment value in the StepAdjustment property is an absolute number or a percentage of the current capacity. 
           "MetricAggregationType": "Average", # The aggregation type for the CloudWatch metrics.
           "Cooldown": 300, # The amount of time, in seconds, to wait for a previous scaling activity to take effect. 
           "StepAdjustments": # A set of adjustments that enable you to scale based on the size of the alarm breach.
           [ 
               {
                 "MetricIntervalLowerBound": 0,
                 "ScalingAdjustment": 1
               }
             ]
       },    
   )
   ```

1. 使用自訂指標 `HasBacklogWithoutCapacity` 建立 CloudWatch 警示。警示觸發時，會啟動先前定義的擴展政策。如需關於 `HasBacklogWithoutCapacity` 指標的詳細資訊，請參閱[非同步推論端點指標](async-inference-monitor.md#async-inference-monitor-cloudwatch-async)。

   ```
   response = cw_client.put_metric_alarm(
       AlarmName=step_scaling_policy_alarm_name,
       MetricName='HasBacklogWithoutCapacity',
       Namespace='AWS/SageMaker',
       Statistic='Average',
       EvaluationPeriods= 2,
       DatapointsToAlarm= 2,
       Threshold= 1,
       ComparisonOperator='GreaterThanOrEqualToThreshold',
       TreatMissingData='missing',
       Dimensions=[
           { 'Name':'EndpointName', 'Value':endpoint_name },
       ],
       Period= 60,
       AlarmActions=[step_scaling_policy_arn]
   )
   ```

您現在應該要具備擴展政策和 CloudWatch 警示，當佇列有待處理的請求時，就可以隨時從零個執行個體擴展端點。