

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

# Amazon SageMaker Inference Recommender
<a name="inference-recommender"></a>

Amazon SageMaker Inference Recommender 是 Amazon SageMaker AI 的一項功能。這項功能可透過自動化跨 SageMaker AI ML 執行個體進行負載測試和模型調校，以減少在生產環境中取得機器學習 (ML) 模型所需的時間。您可以使用 Inference Recommender 將模型部署到即時或無伺服器推論端點，以最低的成本提供最佳效能。Inference Recommender 可以協助您為 ML 模型和工作負載選取最合適的執行個體類型和組態。它會考慮執行個體數量、容器參數、模型最佳化、並行上限和記憶體大小等因素。

Amazon SageMaker Inference Recommender 只會針對您執行任務時使用的執行個體收費。

## 運作方式
<a name="inference-recommender-how-it-works"></a>

若要使用 Amazon SageMaker Inference Recommender，您可以[建立 SageMaker AI 模型](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html)，或將模型與模型成品一起註冊到 SageMaker 模型註冊表。使用 適用於 Python (Boto3) 的 AWS SDK 或 SageMaker AI 主控台，針對不同的 SageMaker AI 端點組態執行基準測試任務。Inference Recommender 任務可幫助您收集效能和資源使用率的指標並以視覺化方式呈現，以協助您決定要選擇的端點類型和組態。

## 如何開始
<a name="inference-recommender-get-started"></a>

如果您是第一次使用 Amazon SageMaker Inference Recommender，建議您完成以下事項：

1. 請仔細閱讀[使用 Amazon SageMaker Inference Recommender 的先決條件](inference-recommender-prerequisites.md)一節，確定您已符合使用 Amazon SageMaker Inference Recommender 的需求。

1. 請仔細閱讀[Amazon SageMaker Inference Recommender 的建議任務](inference-recommender-recommendation-jobs.md)一節，以啟動您的第一個 Inference Recommender 建議任務。

1. 探索入門的 Amazon SageMaker Inference Recommender [Jupyter 筆記本](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-inference-recommender/inference-recommender.ipynb)範例，或檢閱下一節中的範例筆記本。

## 範例筆記本
<a name="inference-recommender-notebooks"></a>

下列 Jupyter 筆記本範例可協助您處理 Inference Recommender 中多個使用案例的工作流程：
+ 如果您想要一款能夠對 TensorFlow 模型進行基準測試的入門筆記本，請參閱 [SageMaker Inference Recommender TensorFlow](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-inference-recommender/inference-recommender.ipynb)筆記本。
+ 如果您想要對 HuggingFace 模型進行基準測試，請參閱 [SageMaker Inference Recommender for HuggingFace](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-inference-recommender/huggingface-inference-recommender/huggingface-inference-recommender.ipynb) 筆記本。
+ 如果您想要對 XgBoost 模型進行基準測試，請參 [SageMaker Inference Recommender XGBoost](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-inference-recommender/xgboost/xgboost-inference-recommender.ipynb) 筆記本。
+ 如果您想要檢閱 Inference Recommender 任務的 CloudWatch 指標，請參閱 [SageMaker Inference Recommender CloudWatch 指標](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-inference-recommender/tensorflow-cloudwatch/tf-cloudwatch-inference-recommender.ipynb)筆記本。

# 使用 Amazon SageMaker Inference Recommender 的先決條件
<a name="inference-recommender-prerequisites"></a>

在您使用 Amazon SageMaker Inference Recommender 之前，您必須先滿足先決條件。舉例來說，我們將示範如何使用 PyTorch (v1.7.1) ResNet-18 預先訓練的模型來處理這兩種類型的 Amazon SageMaker Inference Recommender 推薦任務。此範例使用 適用於 Python (Boto3) 的 AWS SDK。

**注意**  
下列程式碼範例使用 Python。如果您在終端機或 AWS CLI中執行下列任何一個程式碼範例，請移除 `!` 字首字元。
您可以在 Amazon SageMaker Studio 筆記本中使用 Python 3 (TensorFlow 2.6 Python 3.8 CPU Optimized) 核心來執行下列範例。如需 Studio 的詳細資訊，請參閱 [Amazon SageMaker Studio](studio-updated.md)。

1. **為 Amazon SageMaker AI 建立 IAM 角色。**

   針對已連接 `AmazonSageMakerFullAccess` IAM 受管政策的 Amazon SageMaker AI 建立 IAM 角色。

1. **設定您的環境。**

   匯入相依性 AWS 區域，並為您的 SageMaker AI IAM 角色 （從步驟 1) 和 SageMaker AI 用戶端建立變數。

   ```
   !pip install --upgrade pip awscli botocore boto3  --quiet
   from sagemaker import get_execution_role, Session, image_uris
   import boto3
   
   region = boto3.Session().region_name
   role = get_execution_role()
   sagemaker_client = boto3.client("sagemaker", region_name=region)
   sagemaker_session = Session()
   ```

1. **(選用) 檢閱由 Inference Recommender 進行基準測試的現有模型。**

   Inference Recommender 從熱門的 Model Zoo 為模型進行基準測試。Inference Recommender 支援您的模型，即使模型尚未進行基準測試。

   使用 `ListModelMetaData` 來取得回應物件，物件會列出一般 Model Zoo 中發現之機器學習模型的網域、架構、任務和模型名稱。

   您可以在稍後的步驟中使用網域、架構、架構版本、任務和模型名稱來選取推論 Docker 映像，並在 SageMaker 模型註冊表中註冊您的模型。以下範例示範如何使用 SDK for Python (Boto3) 列出模型中繼資料：

   ```
   list_model_metadata_response=sagemaker_client.list_model_metadata()
   ```

   輸出包含類似下列範例的模型摘要 (`ModelMetadataSummaries`) 和回應中繼資料 (`ResponseMetadata`)：

   ```
   {
       'ModelMetadataSummaries': [{
               'Domain': 'NATURAL_LANGUAGE_PROCESSING',
               'Framework': 'PYTORCH:1.6.0',
                'Model': 'bert-base-cased',
                'Task': 'FILL_MASK'
                },
               {
                'Domain': 'NATURAL_LANGUAGE_PROCESSING',
                'Framework': 'PYTORCH:1.6.0',
                'Model': 'bert-base-uncased',
                'Task': 'FILL_MASK'
                },
               {
               'Domain': 'COMPUTER_VISION',
                'Framework': 'MXNET:1.8.0',
                'Model': 'resnet18v2-gluon',
                'Task': 'IMAGE_CLASSIFICATION'
                },
                {
                'Domain': 'COMPUTER_VISION',
                'Framework': 'PYTORCH:1.6.0',
                'Model': 'resnet152',
                'Task': 'IMAGE_CLASSIFICATION'
                }],
       'ResponseMetadata': {
                               'HTTPHeaders': {
                               'content-length': '2345',
                               'content-type': 'application/x-amz-json-1.1',
                               'date': 'Tue, 19 Oct 2021 20:52:03 GMT',
                               'x-amzn-requestid': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
                             },
       'HTTPStatusCode': 200,
       'RequestId': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
       'RetryAttempts': 0
       }
   }
   ```

   在此示範中，我們使用 PyTorch (v1.7.1) ResNet-18 模型來執行影像分類。下列 Python 程式碼範例會將架構、架構版本、網域和任務儲存到變數中，以供之後使用：

   ```
   # ML framework details
   framework = 'pytorch'
   framework_version = '1.7.1'
   
   # ML model details
   ml_domain = 'COMPUTER_VISION'
   ml_task = 'IMAGE_CLASSIFICATION'
   ```

1. **將您的機器學習模型上傳到 Amazon S3。**

   如果您沒有預先訓練的機器學習模型，請使用此 PyTorch (v1.7.1) ResNet-18 模型：

   ```
   # Optional: Download a sample PyTorch model
   import torch
   from torchvision import models, transforms, datasets
   
   # Create an example input for tracing
   image = torch.zeros([1, 3, 256, 256], dtype=torch.float32)
   
   # Load a pretrained resnet18 model from TorchHub
   model = models.resnet18(pretrained=True)
   
   # Tell the model we are using it for evaluation (not training). Note this is required for Inferentia compilation.
   model.eval()
   model_trace = torch.jit.trace(model, image)
   
   # Save your traced model
   model_trace.save('model.pth')
   ```

   下載範例推論指令碼 `inference.py`。建立 `code` 目錄並將推論指令碼移至 `code` 目錄。

   ```
   # Download the inference script
   !wget https://aws-ml-blog-artifacts.s3.us-east-2.amazonaws.com/inference.py
   
   # move it into a code/ directory
   !mkdir code
   !mv inference.py code/
   ```

   Amazon SageMaker AI 要求預先訓練的機器學習模型封裝成壓縮的 TAR 檔案 (`*.tar.gz`)。壓縮模型和推論指令碼以滿足此要求：

   ```
   !tar -czf test.tar.gz model.pth code/inference.py
   ```

   佈建端點時，封存中的檔案會解壓縮到端點上的 `/opt/ml/model/`。

   將模型和模型成品壓縮為 `.tar.gz` 檔案後，請將它們上傳到 Amazon S3 儲存貯體。以下範例示範如何使用 AWS CLI將您的模型上傳至 Amazon S3：

   ```
   !aws s3 cp test.tar.gz s3://{your-bucket}/models/
   ```

1. **選取一個預先建立的 Docker 推論影像，或建立您自己的推論 Docker 映像。**

   SageMaker AI 為一些最常見的機器學習架構，例如 Apache MXNet、TensorFlow、PyTorch 和 Chainer 等，提供內建演算法和預先建置的 Docker 映像容器。有關可用 SageMaker AI 圖像的完整清單，請參閱[可用的深度學習容器映像](https://github.com/aws/deep-learning-containers/blob/master/available_images.md)。

   如果現有的 SageMaker AI 容器都不符合您的需求，而且您沒有自己的現有容器，請建立新的 Docker 映像。請參閱[具有自訂推論程式碼的容器](your-algorithms-inference-main.md)，了解如何建立 Docker 映像的資訊。

   以下內容示範如何使用 SageMaker Python SDK 擷取 PyTorch 1.7.1 版本的推論影像：

   ```
   from sagemaker import image_uris
   
   ## Uncomment and replace with your own values if you did not define  
   ## these variables a previous step.
   #framework = 'pytorch'
   #framework_version = '1.7.1'
   
   # Note: you can use any CPU-based instance here, 
   # this is just to set the arch as CPU for the Docker image
   instance_type = 'ml.m5.2xlarge' 
   
   image_uri = image_uris.retrieve(framework, 
                                   region, 
                                   version=framework_version, 
                                   py_version='py3', 
                                   instance_type=instance_type, 
                                   image_scope='inference')
   ```

   如需可用 SageMaker AI 執行個體的清單，請參閱 [Amazon SageMaker AI 定價](https://aws.amazon.com/sagemaker/pricing/)。

1. **建立範例承載封存。**

   建立包含負載測試工具可傳送至 SageMaker AI 端點的個別檔案的封存項目。您的推論程式碼必須能夠從範例承載讀取檔案格式。

   下列步驟會下載此範例在稍後的步驟中針對 ResNet-18 模型使用的 .jpg 影像。

   ```
   !wget https://cdn.pixabay.com/photo/2020/12/18/05/56/flowers-5841251_1280.jpg
   ```

   將範例承載壓縮為 tarball：

   ```
   !tar -cvzf payload.tar.gz flowers-5841251_1280.jpg
   ```

   將範例承載上傳到 Amazon S3，並留意 Amazon S3 URI：

   ```
   !aws s3 cp payload.tar.gz s3://{bucket}/models/
   ```

   您在稍後步驟中需要 Amazon S3 URI，因此請將其儲存在變數中：

   ```
   bucket_prefix='models'
   bucket = '<your-bucket-name>' # Provide the name of your S3 bucket
   payload_s3_key = f"{bucket_prefix}/payload.tar.gz"
   sample_payload_url= f"s3://{bucket}/{payload_s3_key}"
   ```

1. **準備建議任務的模型輸入**

   針對最後一個先決條件，您可選擇以兩種方式準備您的模型輸入。您可以在 SageMaker 模型註冊表中註冊您的模型，藉此使用該註冊表來為生產模型編目，也可以建立 SageMaker AI 模型，並在建立建議任務時於 `ContainerConfig` 欄位中指定模型。如果您想要善用[模型註冊表](https://docs.aws.amazon.com/sagemaker/latest/dg/model-registry.html)提供的功能，例如管理模型版本和自動化模型部署，則第一個選項會是首選。如果您想快速入門，第二個選擇則是理想的選擇。對於第一個選項，請前往步驟 7。對於第二個選項，請略過步驟 7 並前往步驟 8。

1. **選項 1：在模型註冊表檔中註冊模型**

   使用 SageMaker 模型註冊表，您可以為生產模型編目、管理模型版本、將中繼資料 (例如訓練指標) 與模型相連結、管理模型的核准狀態、將模型部署到生產環境，以及使用 CI/CD 自動化模型部署。

   當您使用 SageMaker 模型註冊表來追蹤和管理模型時，它們會在模型套件群組中顯示為已建立版本的模型套件。未版本化的模型套件不是模型群組的一部分。模型套件群組包含模型的多個版本或迭代。雖然不需要為註冊表中的每個模型建立它們，但它們可以協助組織所有具有相同目的之各種模型並提供自動版本控制。

   若要使用 Amazon SageMaker Inference Recommender，您必須擁有版本控制的模型套件。您可以使用 適用於 Python (Boto3) 的 AWS SDK 或 Amazon SageMaker Studio Classic，以程式設計方式建立版本控制的模型套件。若要以程式設計方式建立版本化的模型套件，請先使用 `CreateModelPackageGroup` API 建立模型套件群組。接下來，使用 `CreateModelPackage` API 建立模型套件。呼叫此方法會建立版本化的模型套件。

   如需如何使用 [建立模型群組](model-registry-model-group.md)和 [註冊模型版本](model-registry-version.md) Amazon SageMaker Studio Classic，以程式設計和互動方式分別建立模型套件群組以及如何建立版本化模型套件的詳細說明，請參閱 適用於 Python (Boto3) 的 AWS SDK 和 。

   下列程式碼範例示範如何使用 適用於 Python (Boto3) 的 AWS SDK建立版本化模型套件。
**注意**  
您不需要核准模型套件即可建立 Inference Recommender 任務。

   1. **建立模型套件群組**

      使用 `CreateModelPackageGroup` API 建立模型套件群組。針對 `ModelPackageGroupName` 為模型套件群組提供名稱，並選擇性地在 `ModelPackageGroupDescription` 欄位中提供模型套件的描述。

      ```
      model_package_group_name = '<INSERT>'
      model_package_group_description = '<INSERT>' 
      
      model_package_group_input_dict = {
       "ModelPackageGroupName" : model_package_group_name,
       "ModelPackageGroupDescription" : model_package_group_description,
      }
      
      model_package_group_response = sagemaker_client.create_model_package_group(**model_package_group_input_dict)
      ```

      請參閱 [Amazon SageMaker API 參考指南](https://docs.aws.amazon.com/sagemaker/latest/APIReference/Welcome.html)，以取得可傳遞給 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackageGroup.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackageGroup.html) 的選用和必要引數之完整清單。

      透過指定執行推論程式碼的 Docker 映像和模型成品的 Amazon S3 位置並提供 `InferenceSpecification` 值，以建立模型套件。`InferenceSpecification` 應包含可使用以此模型套件為基礎的模型執行的推論任務之相關資訊，包含下列內容：
      + 執行推論程式碼之影像的 Amazon ECR 路徑。
      + (選用) 模型套件支援用於轉換任務的執行個體類型，以及用於推論的即時端點。
      + 模型套件支援用於推論的輸入和輸出內容格式。

      此外，建立模型套件時，您必須指定下列參數：
      + [網域](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackage.html#sagemaker-CreateModelPackage-request-Domain)：模型套件及其元件的機器學習網域。常見的機器學習網域包括電腦視覺和自然語言處理。
      + [任務](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackage.html#sagemaker-CreateModelPackage-request-Task)：模型套件完成的機器學習任務。常見的機器學習任務包括物件偵測和映像分類。如果 [API 參考指南](https://docs.aws.amazon.com/sagemaker/latest/APIReference/Welcome.html)中列出的任何任務都不符合您的使用案例，請指定 "OTHER"。如需支援的機器學習任務清單，請參閱[任務](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackage.html#sagemaker-CreateModelPackage-request-Task) API 欄位描述。
      + [SamplePayloadUrl](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackage.html#sagemaker-CreateModelPackage-request-SamplePayloadUrl)：儲存範例承載的 Amazon Simple Storage Service (Amazon S3) 路徑。此路徑必須指向單一 GZIP 壓縮 TAR 存檔 (.tar.gz 字尾)。
      + [架構](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelPackageContainerDefinition.html#sagemaker-Type-ModelPackageContainerDefinition-Framework)：模型套件容器映像的機器學習架構。
      + [FrameworkVersion](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelPackageContainerDefinition.html#sagemaker-Type-ModelPackageContainerDefinition-FrameworkVersion)：模型套件容器映像的架構版本。

      如果您提供執行個體類型的允許清單，以便即時產生 [SupportedRealtimeInferenceInstanceTypes](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_InferenceSpecification.html#sagemaker-Type-InferenceSpecification-SupportedRealtimeInferenceInstanceTypes)，Inference Recommender 會在 `Default` 任務期間限制執行個體類型的搜尋空間。如有預算限制，或知道有一組特定的執行個體類型可支援您的模型和容器映像檔，請使用此參數。

      在上一個步驟中，我們下載了預先訓練的 ResNet18 模型，並將其儲存在 Amazon S3 儲存貯體中名為 `models` 的目錄。我們擷取了一個 PyTorch (v1.7.1) 深度學習容器推論影像，並將 URI 儲存在一個名為 `image_uri` 的變數。請在下面的範例程式碼中使用這些變數，以定義用作 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackage.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackage.html) API 輸入的字典。

      ```
      # Provide the Amazon S3 URI of your compressed tarfile
      # so that Model Registry knows where to find your model artifacts
      bucket_prefix='models'
      bucket = '<your-bucket-name>' # Provide the name of your S3 bucket
      model_s3_key = f"{bucket_prefix}/test.tar.gz"
      model_url= f"s3://{bucket}/{model_s3_key}"
      
      # Similar open source model to the packaged model
      # The name of the ML model as standardized by common model zoos
      nearest_model_name = 'resnet18'
      
      # The supported MIME types for input and output data. In this example, 
      # we are using images as input.
      input_content_type='image/jpeg'
      
      
      # Optional - provide a description of your model.
      model_package_description = '<INSERT>'
      
      ## Uncomment if you did not store the domain and task in an earlier
      ## step 
      #ml_domain = 'COMPUTER_VISION'
      #ml_task = 'IMAGE_CLASSIFICATION'
      
      ## Uncomment if you did not store the framework and framework version
      ## in a previous step.
      #framework = 'PYTORCH'
      #framework_version = '1.7.1'
      
      # Optional: Used for optimizing your model using SageMaker Neo
      # PyTorch uses NCHW format for images
      data_input_configuration = "[[1,3,256,256]]"
      
      # Create a dictionary to use as input for creating a model pacakge group
      model_package_input_dict = {
              "ModelPackageGroupName" : model_package_group_name,
              "ModelPackageDescription" : model_package_description,
              "Domain": ml_domain,
              "Task": ml_task,
              "SamplePayloadUrl": sample_payload_url,
              "InferenceSpecification": {
                      "Containers": [
                          {
                              "Image": image_uri,
                              "ModelDataUrl": model_url,
                              "Framework": framework.upper(), 
                              "FrameworkVersion": framework_version,
                              "NearestModelName": nearest_model_name,
                              "ModelInput": {"DataInputConfig": data_input_configuration}
                          }
                          ],
                      "SupportedContentTypes": [input_content_type]
              }
          }
      ```

   1. **建立模型套件**

      使用 `CreateModelPackage` API 來建立模型套件。傳遞在上一步中定義的輸入字典：

      ```
      model_package_response = sagemaker_client.create_model_package(**model_package_input_dict)
      ```

      您需要模型套件 ARN 才能使用 Amazon SageMaker Inference Recommender。請記下模型套件的 ARN 或將其儲存在變數中：

      ```
      model_package_arn = model_package_response["ModelPackageArn"]
      
      print('ModelPackage Version ARN : {}'.format(model_package_arn))
      ```

1. **選項 2：建立模型並設定 `ContainerConfig` 欄位**

   如果您想要啟動推論建議任務，而不需要在模型註冊表中註冊模型，請使用此選項。在下列步驟中，您會在 SageMaker AI 中建立模型，並將 `ContainerConfig` 欄位設為建議任務的輸入。

   1. **建立模型**

      使用 `CreateModel` API 建立模型。如需將模型部署到 SageMaker AI 主機時呼叫此方法的範例，請參閱[建立模型 (適用於 Python (Boto3) 的 AWS SDK)](https://docs.aws.amazon.com/sagemaker/latest/dg/realtime-endpoints-deployment.html#realtime-endpoints-deployment-create-model)。

      在上一個步驟中，我們下載了預先訓練的 ResNet18 模型，並將其儲存在 Amazon S3 儲存貯體中名為 `models` 的目錄。我們擷取了一個 PyTorch (v1.7.1) 深度學習容器推論影像，並將 URI 儲存在一個名為 `image_uri` 的變數。我們在下面的程式碼範例中使用這些變數，我們定義用作輸入 `[CreateModel](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html#sagemaker-CreateModel-request-ModelName)` API 的字典。

      ```
      model_name = '<name_of_the_model>'
      # Role to give SageMaker permission to access AWS services.
      sagemaker_role= "arn:aws:iam::<region>:<account>:role/*"
      
      # Provide the Amazon S3 URI of your compressed tarfile
      # so that Model Registry knows where to find your model artifacts
      bucket_prefix='models'
      bucket = '<your-bucket-name>' # Provide the name of your S3 bucket
      model_s3_key = f"{bucket_prefix}/test.tar.gz"
      model_url= f"s3://{bucket}/{model_s3_key}"
      
      #Create model
      create_model_response = sagemaker_client.create_model(
          ModelName = model_name,
          ExecutionRoleArn = sagemaker_role, 
          PrimaryContainer = {
              'Image': image_uri,
              'ModelDataUrl': model_url,
          })
      ```

   1. **設定 `ContainerConfig` 欄位**

      接下來，您必須使用剛才建立的模型來設定 [ContainerConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_RecommendationJobInputConfig.html#sagemaker-Type-RecommendationJobInputConfig-ContainerConfig) 欄位，並在其中指定下列參數：
      + `Domain`：模型的機器學習網域及其元件，例如電腦視覺或自然語言處理。
      + `Task`：模型完成的機器學習任務，例如影像分類或物件偵測。
      + `PayloadConfig`：建議任務的承載組態。如需有關子欄位的詳細資訊，請參閱`[RecommendationJobPayloadConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_RecommendationJobPayloadConfig.html#sagemaker-Type-RecommendationJobPayloadConfig-SamplePayloadUrl)`。
      + `Framework`：容器映像的機器學習架構，例如 PyTorch。
      + `FrameworkVersion`：容器映像的架構版本。
      + (選用) `SupportedInstanceTypes`：用於即時產生推論的執行個體類型清單。

      如果您使用 `SupportedInstanceTypes` 參數，Inference Recommender 會在 `Default` 任務期間限制執行個體類型的搜尋空間。如有預算限制，或知道有一組特定的執行個體類型可支援您的模型和容器映像檔，請使用此參數。

      在下面的程式碼範例中，我們使用先前定義的參數以及`NearestModelName`，以定義作為 `[CreateInferenceRecommendationsJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateInferenceRecommendationsJob.html)` API 輸入的字典。

      ```
      ## Uncomment if you did not store the domain and task in a previous step
      #ml_domain = 'COMPUTER_VISION'
      #ml_task = 'IMAGE_CLASSIFICATION'
      
      ## Uncomment if you did not store the framework and framework version in a previous step
      #framework = 'PYTORCH'
      #framework_version = '1.7.1'
      
      # The name of the ML model as standardized by common model zoos
      nearest_model_name = 'resnet18'
      
      # The supported MIME types for input and output data. In this example, 
      # we are using images as input
      input_content_type='image/jpeg'
      
      # Optional: Used for optimizing your model using SageMaker Neo
      # PyTorch uses NCHW format for images
      data_input_configuration = "[[1,3,256,256]]"
      
      # Create a dictionary to use as input for creating an inference recommendation job
      container_config = {
              "Domain": ml_domain,
              "Framework": framework.upper(), 
              "FrameworkVersion": framework_version,
              "NearestModelName": nearest_model_name,
              "PayloadConfig": { 
                  "SamplePayloadUrl": sample_payload_url,
                  "SupportedContentTypes": [ input_content_type ]
               },
              "DataInputConfig": data_input_configuration
              "Task": ml_task,
              }
      ```

# Amazon SageMaker Inference Recommender 的建議任務
<a name="inference-recommender-recommendation-jobs"></a>

Amazon SageMaker Inference Recommender 可以提出兩種類型的建議：

1. 推論建議 (`Default` 任務類型) 會針對建議的執行個體類型執行一組負載測試。您也可以為無伺服器端點載入測試。您只需要提供模型套件 Amazon Resource Name (ARN)，即可啟動此類建議任務。推論建議任務可在 45 分鐘內完成。

1. 端點建議 (`Advanced` 任務類型) 是以自訂負載測試為基礎，您可以在其中選取所需的機器學習 (ML) 執行個體或無伺服器端點、提供自訂流量模式，並根據生產需求提供延遲和輸送量需求。根據設定的任務持續時間和測試的推論組態總數，此任務平均需要 2 小時才能完成。

這兩種類型的建議都使用相同的 API 來建立、描述和停止任務。輸出為執行個體組態建議清單，其中包含相關的環境變數、成本、輸送量和延遲等指標。建議任務也會提供初始執行個體數量，讓您用來設定自動擴展政策。為了區分這兩種類型的任務，當您透過 SageMaker AI 主控台或 API 建立任務時，請指定 `Default` 以建立初步端點建議，並指定 `Advanced` 用於自訂負載測試與端點建議。

**注意**  
您不需要在自己的工作流程中執行這兩種類型的建議任務。您可以彼此獨立執行任一操作。

Inference Recommender 也可提供您預期執行個體清單，或針對模型部署的成本、輸送量和延遲進行最佳化的前五個執行個體類型，以及可信度分數。您可以在部署模型時選擇這些執行個體。Inference Recommender 會自動針對您的模型執行基準測試，方便您提供潛在的執行個體。由於這些是初步建議，因此建議您執行進一步的執行個體建議任務，以取得更準確的結果。若要檢視預期執行個體，請前往 SageMaker AI 模型詳細資訊頁面。如需詳細資訊，請參閱[獲取即時的潛在執行個體](inference-recommender-prospective.md)。

**Topics**
+ [獲取即時的潛在執行個體](inference-recommender-prospective.md)
+ [推論建議](inference-recommender-instance-recommendation.md)
+ [取得現有端點的推論建議](inference-recommender-existing-endpoint.md)
+ [停止您的推論建議](instance-recommendation-stop.md)
+ [使用 Neo 的編譯建議](inference-recommender-neo-compilation.md)
+ [建議結果](inference-recommender-interpret-results.md)
+ [取得自動擴展政策的建議](inference-recommender-autoscaling.md)
+ [執行自訂負載測試](inference-recommender-load-test.md)
+ [停止您的負載測試](load-test-stop.md)
+ [故障診斷 Inference Recommender 錯誤](inference-recommender-troubleshooting.md)

# 獲取即時的潛在執行個體
<a name="inference-recommender-prospective"></a>

Inference Recommender 也可以在 SageMaker AI 模型詳細資訊頁面上為您提供*潛在執行個體*或可能適用於您模型的執行個體類型清單。Inference Recommender 會自動針對您的模型執行初步基準測試，以提供前五大潛在執行個體。由於這些是初步建議，因此建議您執行進一步的執行個體建議任務，以取得更準確的結果。

您可以使用 [DescribeModel](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeModel.html) API、SageMaker Python SDK 或 SageMaker AI 主控台，以程式設計方式檢視模型的預期執行個體清單。

**注意**  
在此功能可用之前，您無法取得在 SageMaker AI 中建立的模型之預期執行個體。

若要透過主控台檢視您模型的預期執行個體，請執行以下操作：

1. 前往位在 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/) 的 SageMaker 主控台。

1. 在左側導覽窗格中，選擇**推論**，然後選擇**模型**。

1. 從模型清單中選擇您的模型。

在模型的詳細資料頁面上，前往**要部署模型的預期執行個體**區段。以下螢幕擷取畫面顯示了此區段。

![\[模型詳細資訊頁面上預期執行個體清單的螢幕擷取畫面。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/inf-rec-prospective.png)


在本節中，您可以檢視針對模型部署的成本、輸送量和延遲最佳化的預期執行個體，以及每個執行個體類型的其他資訊，例如記憶體大小、CPU 和 GPU 計數以及每小時成本。

如果您決定要對範例承載進行基準測試，並針對模型執行完整推論建議任務，則可以從此頁面啟動預設的推論建議任務。若要透過主控台啟動預設任務，請執行以下操作：

1. 在**要部署模型的潛在執行個體區段**的模型詳細資料頁面上，選擇**執行推論建議程式任務**。

1. 在快顯對話方塊中，對於**用於基準測試承載的 S3 儲存貯體**，輸入您為模型儲存範例承載的 Amazon S3 位置。

1. 針對**承載內容類型**，輸入承載資料的 MIME 類型。

1. (選用) 在**使用 SageMaker Neo 編譯模型**區段中，對於**資料輸入組態**，請以字典格式輸入資料形式。

1. 選擇**執行工作**。

Inference Recommender 會啟動任務，您可以從 SageMaker AI 主控台的**推論建議程式**清單頁面檢視任務及其結果。

如果要執行進階任務並執行自訂負載測試，或者想要為任務設置其他設定和參數，請參閱[執行自訂負載測試](inference-recommender-load-test.md)。

# 推論建議
<a name="inference-recommender-instance-recommendation"></a>

推論建議任務會在建議的執行個體類型或無伺服器端點上執行一組負載測試。推論建議任務會使用效能指標，這些指標是以您在模型版本註冊期間提供的範例資料為基礎的負載測試。

**注意**  
在建立 Inference Recommender 建議任務之前，請確定您已符合 [使用 Amazon SageMaker Inference Recommender 的先決條件](inference-recommender-prerequisites.md)。

以下示範如何使用 、 和 Amazon SageMaker Studio Classic 以及 SageMaker AI 主控台 適用於 Python (Boto3) 的 AWS SDK AWS CLI，使用 Amazon SageMaker Inference Recommender 根據您的模型類型建立推論建議

**Topics**
+ [建立推論建議](instance-recommendation-create.md)
+ [取得您的推論建議任務結果](instance-recommendation-results.md)

# 建立推論建議
<a name="instance-recommendation-create"></a>

使用 適用於 Python (Boto3) 的 AWS SDK 或 以程式設計方式建立推論建議 AWS CLI，或使用 Studio Classic 或 SageMaker AI 主控台以互動方式建立推論建議。指定推論建議的任務名稱、IAM AWS 角色 ARN、輸入組態，以及當您向模型登錄檔註冊模型時的模型套件 ARN，或是您在**先決條件**區段中建立模型時的模型名稱和`ContainerConfig`字典。

------
#### [ 適用於 Python (Boto3) 的 AWS SDK ]

使用 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateInferenceRecommendationsJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateInferenceRecommendationsJob.html) API 開始推論建議任務。將推論建議工作的 `JobType` 欄位設為 `'Default'`。此外，請提供下列項目：
+ IAM 角色的 Amazon Resource Name (ARN)，可讓 Inference Recommender 代表您執行任務。為 `RoleArn` 欄位定義此項目。
+ 模型套件 ARN 或模型名稱。Inference Recommender 支援一個模型套件 ARN 或模型名稱作為輸入。請指定下列其中一項：
  + 您在 SageMaker AI 模型註冊表中註冊模型時所建立的版本化模型套件之 ARN。在 `InputConfig` 欄位中為 `ModelPackageVersionArn` 定義此項目。
  + 您建立的模型名稱。在 `InputConfig` 欄位中為 `ModelName` 定義此項目。此外，請提供 `ContainerConfig` 字典，其中包含需要提供模型名稱的必要欄位。在 `InputConfig` 欄位中為 `ContainerConfig` 定義此項目。在 `ContainerConfig` 中，您也可以選擇性地將 `SupportedEndpointType` 欄位指定為 `RealTime` 或 `Serverless`。如果您指定此欄位，Inference Recommender 只會傳回該端點類型的建議。如果您未指定此欄位，Inference Recommender 會傳回兩種端點類型的建議。
+ `JobName` 欄位的 Inference Recommender 推薦任務的名稱。Inference Recommender 任務名稱在 AWS 區域和您的帳戶 AWS 內必須是唯一的。

匯入 適用於 Python (Boto3) 的 AWS SDK 套件，並使用用戶端類別建立 SageMaker AI 用戶端物件。如果您遵循**先決條件**區段中的步驟，請僅指定下列其中一項：
+ 選項 1：如果您想要使用模型套件 ARN 建立推論建議任務，請將模型套件群組 ARN 儲存在名為 `model_package_arn` 的變數。
+ 選項 2：如果您想要使用模型名稱和 `ContainerConfig` 建立推論建議任務，並將模型名稱儲存在名為 `model_name` 的變數中，且將 `ContainerConfig` 字典儲存在名為 `container_config` 變數中。

```
# Create a low-level SageMaker service client.
import boto3
aws_region = '<INSERT>'
sagemaker_client = boto3.client('sagemaker', region_name=aws_region) 

# Provide only one of model package ARN or model name, not both.
# Provide your model package ARN that was created when you registered your 
# model with Model Registry 
model_package_arn = '<INSERT>'
## Uncomment if you would like to create an inference recommendations job with a
## model name instead of a model package ARN, and comment out model_package_arn above
## Provide your model name
# model_name = '<INSERT>'
## Provide your container config 
# container_config = '<INSERT>'

# Provide a unique job name for SageMaker Inference Recommender job
job_name = '<INSERT>'

# Inference Recommender job type. Set to Default to get an initial recommendation
job_type = 'Default'

# Provide an IAM Role that gives SageMaker Inference Recommender permission to 
# access AWS services
role_arn = 'arn:aws:iam::<account>:role/*'

sagemaker_client.create_inference_recommendations_job(
    JobName = job_name,
    JobType = job_type,
    RoleArn = role_arn,
    # Provide only one of model package ARN or model name, not both. 
    # If you would like to create an inference recommendations job with a model name,
    # uncomment ModelName and ContainerConfig, and comment out ModelPackageVersionArn.
    InputConfig = {
        'ModelPackageVersionArn': model_package_arn
        # 'ModelName': model_name,
        # 'ContainerConfig': container_config
    }
)
```

請參閱 [Amazon SageMaker API 參考指南](https://docs.aws.amazon.com/sagemaker/latest/APIReference/Welcome.html)，以取得可傳遞給 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateInferenceRecommendationsJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateInferenceRecommendationsJob.html) 的選用和必要引數之完整清單。

------
#### [ AWS CLI ]

使用 `create-inference-recommendations-job` API 開始推論建議任務。將推論建議工作的 `job-type` 欄位設為 `'Default'`。此外，請提供下列項目：
+ IAM 角色的 Amazon Resource Name (ARN)，可讓 Amazon SageMaker Inference Recommender 代表您執行任務。為 `role-arn` 欄位定義此項目。
+ 模型套件 ARN 或模型名稱。Inference Recommender 支援一個模型套件 ARN 或模型名稱作為輸入。請指定下列其中一項：
  + 您在模型註冊表中註冊模型時所建立的版本化模型套件之 ARN。在 `input-config` 欄位中為 `ModelPackageVersionArn` 定義此項目。
  + 您建立的模型名稱。在 `input-config` 欄位中為 `ModelName` 定義此項目。此外，請提供 `ContainerConfig` 字典，其中包含需要提供模型名稱的必要欄位。在 `input-config` 欄位中為 `ContainerConfig` 定義此項目。在 `ContainerConfig` 中，您也可以選擇性地將 `SupportedEndpointType` 欄位指定為 `RealTime` 或 `Serverless`。如果您指定此欄位，Inference Recommender 只會傳回該端點類型的建議。如果您未指定此欄位，Inference Recommender 會傳回兩種端點類型的建議。
+ `job-name` 欄位的 Inference Recommender 推薦任務的名稱。Inference Recommender 任務名稱在 AWS 區域和您的帳戶 AWS 內必須是唯一的。

若要使用模型套件 ARN 建立推論建議任務，請使用下列範例：

```
aws sagemaker create-inference-recommendations-job 
    --region <region>\
    --job-name <job_name>\
    --job-type Default\
    --role-arn arn:aws:iam::<account:role/*>\
    --input-config "{
        \"ModelPackageVersionArn\": \"arn:aws:sagemaker:<region:account:role/*>\",
        }"
```

若要使用模型名稱和 `ContainerConfig` 建立推論建議任務，請使用下列範例。此範例使用 `SupportedEndpointType` 欄位來指定我們只想傳回即時推論建議：

```
aws sagemaker create-inference-recommendations-job 
    --region <region>\
    --job-name <job_name>\
    --job-type Default\
    --role-arn arn:aws:iam::<account:role/*>\
    --input-config "{
        \"ModelName\": \"model-name\",
        \"ContainerConfig\" : {
                \"Domain\": \"COMPUTER_VISION\",
                \"Framework\": \"PYTORCH\",
                \"FrameworkVersion\": \"1.7.1\",
                \"NearestModelName\": \"resnet18\",
                \"PayloadConfig\": 
                    {
                        \"SamplePayloadUrl\": \"s3://{bucket}/{payload_s3_key}\", 
                        \"SupportedContentTypes\": [\"image/jpeg\"]
                    },
                \"SupportedEndpointType\": \"RealTime\",
                \"DataInputConfig\": \"[[1,3,256,256]]\",
                \"Task\": \"IMAGE_CLASSIFICATION\",
            },
        }"
```

------
#### [ Amazon SageMaker Studio Classic ]

在 Studio Classic 中建立推論建議任務。

1. 在您的 Studio Classic 應用程式中，選擇首頁圖示 (![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/studio/icons/house.png))。

1. 在 Studio Classic 的左側邊欄中，選擇**模型**。

1. 從下拉式清單中選擇**模型註冊表**，以顯示您已在模型註冊表中註冊的模型。

   左側面板顯示模型群組的清單。此清單包含在您帳戶中註冊至模型註冊表的所有模型群組，包括在 Studio Classic 外部註冊的模型。

1. 選取您模型群組的名稱。當您選擇模型群組時，Studio Classic 的右側窗格顯示列標題，例如**版本**和**設定**。

   如果您的模型群組中有一或多個模型套件，您會在**版本**一欄中看到這些模型套件的清單。

1. 選擇**推論建議程式**一欄。

1. 選擇授予 Inference Recommender 存取 AWS 服務的許可的 IAM 角色。您可以建立角色並連接 `AmazonSageMakerFullAccess` IAM 受管政策來完成此作業。或者，也可以讓 Studio Classic 為您建立角色。

1. 選擇 **Get recommendations (取得建議)**。

   推論建議最多需要 45 分鐘的時間。
**警告**  
請勿關閉此索引標籤。如果您關閉此索引標籤，就會取消執行個體建議任務。

------
#### [ SageMaker AI console ]

透過執行下列動作，透過 SageMaker AI 主控台建立執行個體建議任務：

1. 前往位在 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/) 的 SageMaker AI 主控台。

1. 在左側導覽窗格中，選擇**推論**，然後選擇**推論建議程式**。

1. 在**推論建議程式任務**頁面上，選擇**建立任務**。

1. 針對**步驟 1：模型組態**，執行下列動作：

   1. 對於**任務類型**，選擇**預設建議程式任務**。

   1. 如果您使用的是在 SageMaker AI 模型註冊表中註冊的模型，請開啟**從模型註冊表中選擇模型**切換鈕並執行下列動作：

      1. 從**模型群組**下拉式清單中，在 SageMaker AI 模型註冊表中選擇模型所在的模型群組。

      1. 從**模型版本**下拉式清單中，選擇所需的模型版本。

   1. 如果您使用的是在 SageMaker AI 中建立的模型，請關閉**從模型註冊表中選擇模型切換鈕**，然後執行下列動作：

      1. 在**模型名稱**欄位中，輸入 SageMaker AI 模型的名稱。

   1. 從 **IAM 角色**下拉式清單中，您可以選取具有建立執行個體建議任務所需許可的現有 IAM 角色。 AWS 或者，如果您沒有現有角色，可以選擇**建立新角色**以開啟角色建立快顯視窗，SageMaker AI 會將必要的權限新增至您建立的新角色。

   1. 針對**用於基準測試承載的 S3 儲存貯體**，請輸入您範例承載存檔的 Amazon S3 路徑，其中應包含 Inference Recommender 用於在不同執行個體類型上對模型進行基準測試的範例承載檔案。

   1. 針對**承載內容類型**，輸入範例承載資料的 MIME 類型。

   1. (選用) 如果您關閉了**從模型註冊表中選擇模型切換鈕**並指定 SageMaker AI 模型，則針對**容器組態**，請執行下列操作：

      1. 在**網域**下拉式清單中，選取模型的機器學習領域，例如電腦視覺、自然語言處理或機器學習。

      1. 在**架構**下拉式清單中，選取容器的架構，例如 TensorFlow 或 XGBoost。

      1. 針對**架構版本**，請輸入容器映像的架構版本。

      1. 在**最近的模型名稱**下拉式清單中，選取大部分與您自己的模型相符的預先訓練模型。

      1. 針對**任務**下拉式清單，選取模型完成的機器學習任務，例如影像分類或迴歸。

   1. (選用) 對於**使用 SageMaker Neo 進行模型編譯**，您可以為已使用 SageMaker Neo 編譯的模型設定建議任務。針對**資料輸入組態**，請以類似 `{'input':[1,1024,1024,3]}` 的格式輸入模型的正確輸入資料形式。

   1. 選擇**下一步**。

1. 針對**步驟 2：執行個體和環境參數**，請執行下列操作：

   1. (選用) 針對**選取執行個體進行基準測試**，您最多可以選取 8 個要進行基準測試的執行個體類型。如未選取任何執行個體，Inference Recommender 會考量所有執行個體類型。

   1. 選擇**下一步**。

1. 針對**步驟 3：任務參數**，請執行下列動作：

   1. (選用) 針對**工作名稱**欄位，輸入執行個體建議任務的名稱。當您建立任務時，SageMaker AI 會在此名稱的結尾附加一個時間戳記。

   1. (選用) 針對**工作描述**，輸入該任務的描述。

   1. （選用） 針對**加密金鑰**下拉式清單，依名稱選擇 AWS KMS 金鑰，或輸入其 ARN 來加密您的資料。

   1. (選用) 針對**最長測試持續時間**，請輸入您希望每個測試執行的秒數上限。

   1. (選用) 針對**每分鐘調用數上限**，請輸入端點在停止建議任務之前每分鐘可達到的請求數量上限。達到此限制後，SageMaker AI 會結束任務。

   1. (選用) 針對 **P99 模型延遲閾值 (ms)**，輸入模型延遲百分位數 (以毫秒為單位)。

   1. 選擇**下一步**。

1. 針對**步驟 4：檢閱任務**，檢閱您的組態，然後選擇**提交**。

------

# 取得您的推論建議任務結果
<a name="instance-recommendation-results"></a>

使用 適用於 Python (Boto3) 的 AWS SDK、、 AWS CLI Studio Classic 或 SageMaker AI 主控台，以程式設計方式收集推論建議任務的結果。

------
#### [ 適用於 Python (Boto3) 的 AWS SDK ]

推論建議完成後，您可以使用 `DescribeInferenceRecommendationsJob` 來取得任務詳細資料和建議。提供建立推論建議任務時所使用的任務名稱。

```
job_name='<INSERT>'
response = sagemaker_client.describe_inference_recommendations_job(
                    JobName=job_name)
```

列印回應物件。先前的程式碼範例會以變數名稱 `response` 儲存回應。

```
print(response['Status'])
```

此項目會傳回類似下列範例的 JSON 回應。請注意，此範例顯示建議的即時推論執行個體類型 (如需顯示無伺服器推論建議的範例，請參閱此範例之後的範例)。

```
{
    'JobName': 'job-name', 
    'JobDescription': 'job-description', 
    'JobType': 'Default', 
    'JobArn': 'arn:aws:sagemaker:region:account-id:inference-recommendations-job/resource-id', 
    'Status': 'COMPLETED', 
    'CreationTime': datetime.datetime(2021, 10, 26, 20, 4, 57, 627000, tzinfo=tzlocal()), 
    'LastModifiedTime': datetime.datetime(2021, 10, 26, 20, 25, 1, 997000, tzinfo=tzlocal()), 
    'InputConfig': {
                'ModelPackageVersionArn': 'arn:aws:sagemaker:region:account-id:model-package/resource-id', 
                'JobDurationInSeconds': 0
                }, 
    'InferenceRecommendations': [{
            'Metrics': {
                'CostPerHour': 0.20399999618530273, 
                'CostPerInference': 5.246913588052848e-06, 
                'MaximumInvocations': 648, 
                'ModelLatency': 263596
                }, 
            'EndpointConfiguration': {
                'EndpointName': 'endpoint-name', 
                'VariantName': 'variant-name', 
                'InstanceType': 'ml.c5.xlarge', 
                'InitialInstanceCount': 1
                }, 
            'ModelConfiguration': {
                'Compiled': False, 
                'EnvironmentParameters': []
                }
         }, 
         {
            'Metrics': {
                'CostPerHour': 0.11500000208616257, 
                'CostPerInference': 2.92620870823157e-06, 
                'MaximumInvocations': 655, 
                'ModelLatency': 826019
                }, 
            'EndpointConfiguration': {
                'EndpointName': 'endpoint-name', 
                'VariantName': 'variant-name', 
                'InstanceType': 'ml.c5d.large', 
                'InitialInstanceCount': 1
                }, 
            'ModelConfiguration': {
                'Compiled': False, 
                'EnvironmentParameters': []
                }
            }, 
            {
                'Metrics': {
                    'CostPerHour': 0.11500000208616257, 
                    'CostPerInference': 3.3625731248321244e-06, 
                    'MaximumInvocations': 570, 
                    'ModelLatency': 1085446
                    }, 
                'EndpointConfiguration': {
                    'EndpointName': 'endpoint-name', 
                    'VariantName': 'variant-name', 
                    'InstanceType': 'ml.m5.large', 
                    'InitialInstanceCount': 1
                    }, 
                'ModelConfiguration': {
                    'Compiled': False, 
                    'EnvironmentParameters': []
                    }
            }], 
    'ResponseMetadata': {
        'RequestId': 'request-id', 
        'HTTPStatusCode': 200, 
        'HTTPHeaders': {
            'x-amzn-requestid': 'x-amzn-requestid', 
            'content-type': 'content-type', 
            'content-length': '1685', 
            'date': 'Tue, 26 Oct 2021 20:31:10 GMT'
            }, 
        'RetryAttempts': 0
        }
}
```

前幾行提供推論建議任務本身的相關資訊。其中包含任務名稱、角色 ARN 以及建立和刪除時間。

`InferenceRecommendations` 字典包含 Inference Recommender 推論建議的清單。

`EndpointConfiguration` 巢狀字典包含執行個體類型 (`InstanceType`) 建議，以及建議任務期間使用的端點和變體名稱 （已部署的 AWS 機器學習模型）。您可以使用端點和變體名稱在 Amazon CloudWatch Events 中進行監控。如需詳細資訊，請參閱[Amazon CloudWatch 中的 Amazon SageMaker AI 指標](monitoring-cloudwatch.md)。

`Metrics` 巢狀字典包含有關即時端點的估計每小時美元成本 (`CostPerHour`)、即時端點的預估每個推論美元成本 (`CostPerInference`)、傳送至端點的預期每分鐘 `InvokeEndpoint` 請求數量上限 (`MaxInvocations`)，以及模型延遲 (`ModelLatency`)，這是模型回應 SageMaker AI 所花費的時間間隔 (以微秒為單位) 等資訊。模型延遲包含傳送請求和從模型容器擷取回應的本機通訊時間，以及在容器中完成推論的時間。

下列範例顯示設定為傳回無伺服器推論建議之推論建議任務的 `InferenceRecommendations` 回應部分：

```
"InferenceRecommendations": [ 
      { 
         "EndpointConfiguration": { 
            "EndpointName": "value",
            "InitialInstanceCount": value,
            "InstanceType": "value",
            "VariantName": "value",
            "ServerlessConfig": {
                "MaxConcurrency": value,
                "MemorySizeInMb": value
            }
         },
         "InvocationEndTime": value,
         "InvocationStartTime": value,
         "Metrics": { 
            "CostPerHour": value,
            "CostPerInference": value,
            "CpuUtilization": value,
            "MaxInvocations": value,
            "MemoryUtilization": value,
            "ModelLatency": value,
            "ModelSetupTime": value
         },
         "ModelConfiguration": { 
            "Compiled": "False",
            "EnvironmentParameters": [],
            "InferenceSpecificationName": "value"
         },
         "RecommendationId": "value"
      }
   ]
```

您可以解讀無伺服器推論的建議，類似於即時推論的結果，但不包括 `ServerlessConfig`，它會告訴您具有指定 `MemorySizeInMB` 和於 `MaxConcurrency = 1` 的無伺服器端點傳回之指標。若要增加端點上可能的輸送量，請線性地增加 `MaxConcurrency` 的值。例如，如果推論建議將 `MaxInvocations` 顯示為 `1000`，則將 `MaxConcurrency` 增加到 `2` 會支援 2000 `MaxInvocations`。請注意，這僅在某個特定時間點才是準確的，這可能會根據您的模型和程式碼而有所差異。無伺服器建議也會測量指標 `ModelSetupTime`，以測量在無伺服器端點上啟動電腦資源所需的時間 (以微秒為單位)。如需有關設定無伺服器端點的詳細資訊，請參閱[無伺服器推論文件](https://docs.aws.amazon.com/sagemaker/latest/dg/serverless-endpoints.html)。

------
#### [ AWS CLI ]

推論建議完成後，您可以使用 `describe-inference-recommendations-job` 來取得任務詳細資料和建議的執行個體類型。提供建立推論建議任務時所使用的任務名稱。

```
aws sagemaker describe-inference-recommendations-job\
    --job-name <job-name>\
    --region <aws-region>
```

JSON 的回應看起來類似以下範例。請注意，此範例顯示建議的即時推論執行個體類型 (如需顯示無伺服器推論建議的範例，請參閱此範例之後的範例)。

```
{
    'JobName': 'job-name', 
    'JobDescription': 'job-description', 
    'JobType': 'Default', 
    'JobArn': 'arn:aws:sagemaker:region:account-id:inference-recommendations-job/resource-id', 
    'Status': 'COMPLETED', 
    'CreationTime': datetime.datetime(2021, 10, 26, 20, 4, 57, 627000, tzinfo=tzlocal()), 
    'LastModifiedTime': datetime.datetime(2021, 10, 26, 20, 25, 1, 997000, tzinfo=tzlocal()), 
    'InputConfig': {
                'ModelPackageVersionArn': 'arn:aws:sagemaker:region:account-id:model-package/resource-id', 
                'JobDurationInSeconds': 0
                }, 
    'InferenceRecommendations': [{
            'Metrics': {
                'CostPerHour': 0.20399999618530273, 
                'CostPerInference': 5.246913588052848e-06, 
                'MaximumInvocations': 648, 
                'ModelLatency': 263596
                }, 
            'EndpointConfiguration': {
                'EndpointName': 'endpoint-name', 
                'VariantName': 'variant-name', 
                'InstanceType': 'ml.c5.xlarge', 
                'InitialInstanceCount': 1
                }, 
            'ModelConfiguration': {
                'Compiled': False, 
                'EnvironmentParameters': []
                }
         }, 
         {
            'Metrics': {
                'CostPerHour': 0.11500000208616257, 
                'CostPerInference': 2.92620870823157e-06, 
                'MaximumInvocations': 655, 
                'ModelLatency': 826019
                }, 
            'EndpointConfiguration': {
                'EndpointName': 'endpoint-name', 
                'VariantName': 'variant-name', 
                'InstanceType': 'ml.c5d.large', 
                'InitialInstanceCount': 1
                }, 
            'ModelConfiguration': {
                'Compiled': False, 
                'EnvironmentParameters': []
                }
            }, 
            {
                'Metrics': {
                    'CostPerHour': 0.11500000208616257, 
                    'CostPerInference': 3.3625731248321244e-06, 
                    'MaximumInvocations': 570, 
                    'ModelLatency': 1085446
                    }, 
                'EndpointConfiguration': {
                    'EndpointName': 'endpoint-name', 
                    'VariantName': 'variant-name', 
                    'InstanceType': 'ml.m5.large', 
                    'InitialInstanceCount': 1
                    }, 
                'ModelConfiguration': {
                    'Compiled': False, 
                    'EnvironmentParameters': []
                    }
            }], 
    'ResponseMetadata': {
        'RequestId': 'request-id', 
        'HTTPStatusCode': 200, 
        'HTTPHeaders': {
            'x-amzn-requestid': 'x-amzn-requestid', 
            'content-type': 'content-type', 
            'content-length': '1685', 
            'date': 'Tue, 26 Oct 2021 20:31:10 GMT'
            }, 
        'RetryAttempts': 0
        }
}
```

前幾行提供推論建議任務本身的相關資訊。其中包含任務名稱、角色 ARN 以及建立和刪除時間。

`InferenceRecommendations` 字典包含 Inference Recommender 推論建議的清單。

`EndpointConfiguration` 巢狀字典包含執行個體類型 (`InstanceType`) 建議，以及建議任務期間使用的端點和變體名稱 （已部署的 AWS 機器學習模型）。您可以使用端點和變體名稱在 Amazon CloudWatch Events 中進行監控。如需詳細資訊，請參閱[Amazon CloudWatch 中的 Amazon SageMaker AI 指標](monitoring-cloudwatch.md)。

`Metrics` 巢狀字典包含有關即時端點的估計每小時美元成本 (`CostPerHour`)、即時端點的預估每個推論美元成本 (`CostPerInference`)、傳送至端點的預期每分鐘 `InvokeEndpoint` 請求數量上限 (`MaxInvocations`)，以及模型延遲 (`ModelLatency`)，這是模型回應 SageMaker AI 所花費的時間間隔 (以毫秒為單位) 等資訊。模型延遲包含傳送請求和從模型容器擷取回應的本機通訊時間，以及在容器中完成推論的時間。

下列範例顯示設定為傳回無伺服器推論建議之推論建議任務的 `InferenceRecommendations` 回應部分：

```
"InferenceRecommendations": [ 
      { 
         "EndpointConfiguration": { 
            "EndpointName": "value",
            "InitialInstanceCount": value,
            "InstanceType": "value",
            "VariantName": "value",
            "ServerlessConfig": {
                "MaxConcurrency": value,
                "MemorySizeInMb": value
            }
         },
         "InvocationEndTime": value,
         "InvocationStartTime": value,
         "Metrics": { 
            "CostPerHour": value,
            "CostPerInference": value,
            "CpuUtilization": value,
            "MaxInvocations": value,
            "MemoryUtilization": value,
            "ModelLatency": value,
            "ModelSetupTime": value
         },
         "ModelConfiguration": { 
            "Compiled": "False",
            "EnvironmentParameters": [],
            "InferenceSpecificationName": "value"
         },
         "RecommendationId": "value"
      }
   ]
```

您可以解讀無伺服器推論的建議，類似於即時推論的結果，但不包括 `ServerlessConfig`，它會告訴您具有指定 `MemorySizeInMB` 和於 `MaxConcurrency = 1` 的無伺服器端點傳回之指標。若要增加端點上可能的輸送量，請線性地增加 `MaxConcurrency` 的值。例如，如果推論建議將 `MaxInvocations` 顯示為 `1000`，則將 `MaxConcurrency` 增加到 `2` 會支援 2000 `MaxInvocations`。請注意，這僅在某個特定時間點才是準確的，這可能會根據您的模型和程式碼而有所差異。無伺服器建議也會測量指標 `ModelSetupTime`，以測量在無伺服器端點上啟動電腦資源所需的時間 (以微秒為單位)。如需有關設定無伺服器端點的詳細資訊，請參閱[無伺服器推論文件](https://docs.aws.amazon.com/sagemaker/latest/dg/serverless-endpoints.html)。

------
#### [ Amazon SageMaker Studio Classic ]

推論建議會填入 Studio Classic 內新的**推論建議**索引標籤中。最多可能需要 45 分鐘，結果才會顯示。此索引標籤包含**結果**和**詳細資訊**欄標題。

**詳細資訊**欄提供推論建議任務的相關資訊，例如推論建議的名稱、建立任務的時間 (**建立時間**) 等等。它也提供**設定**資訊，例如每分鐘發生的調用次數上限，以及所使用之 Amazon Resource Name 的相關資訊。

**結果**欄提供**部署目標**和 **SageMaker AI 建議**視窗，您可以在其中根據部署重要性調整結果的顯示順序。您可以使用三個下拉式清單選單，為您的使用案例提供**成本**、**延遲**和**輸送量**的重要性層級。您可以針對每個目標 (成本、延遲和輸送量) 設定重要性層級：**最低重要性**、**低重要性**、**中等重要性**、**高重要性**或**最高重要性**。

根據您對每個目標的重要性選擇，Inference Recommender 會在面板右側的 **SageMaker 建議**欄位中顯示其最佳建議，以及每小時的預估成本和推論請求。它也提供預期的模型延遲、調用次數上限以及執行個體數目等相關資訊。如需無伺服器建議，您可以看到並行上限和端點記憶體大小的理想值。

除了顯示的最佳建議之外，您也可以看到在**所有執行**段落中，Inference Recommender 測試過的所有執行個體處理所顯示的相同資訊。

------
#### [ SageMaker AI console ]

您可以執行下列動作，在 SageMaker AI 主控台中檢視執行個體建議任務：

1. 前往位在 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/) 的 SageMaker AI 主控台。

1. 在左側導覽窗格中，選擇**推論**，然後選擇**推論建議程式**。

1. 在**推論建議程式任務**頁面上，選擇推論建議任務的名稱。

在任務的詳細資料頁面上，您可以檢視**推論建議**，這是 SageMaker AI 針對您的模型建議的執行個體類型，如下列螢幕擷取畫面所示。

![\[SageMaker AI 主控台中任務詳細資料頁面上推論建議清單的螢幕擷取畫面。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/inf-rec-instant-recs.png)


在本節中，您可以依各種因素比較執行個體類型，例如**模型延遲**、**每小時成本**、**每個推論的成本**、**每分鐘調用數**。

您也可以在此頁面檢視針對您指定的組態。在**監控**區段中，您可以檢視針對每個執行個體類型記錄的 Amazon CloudWatch 指標。若要深入了解如何解讀這些指標，請參閱[解讀結果](https://docs.aws.amazon.com/sagemaker/latest/dg/inference-recommender-interpret-results.html)。

------

如需解讀建議任務結果的詳細資訊，請參閱[建議結果](inference-recommender-interpret-results.md)。

# 取得現有端點的推論建議
<a name="inference-recommender-existing-endpoint"></a>

推論建議任務會針對建議的執行個體類型和現有端點執行一組負載測試。推論建議任務會使用效能指標，這些指標是以您在模型版本註冊期間提供的範例資料為基礎的負載測試。

您可以對現有 SageMaker AI 推論端點進行基準測試並取得推論建議，以協助您改善端點的效能。取得現有 SageMaker AI 推論端點建議的程序與在沒有端點的情況下[取得推論建議](https://docs.aws.amazon.com/sagemaker/latest/dg/inference-recommender-instance-recommendation.html)的程序類似。在對現有端點進行基準測試時，需要注意幾項功能排除事項：
+ 每個 Inference Recommender 任務只能使用一個現有端點。
+ 您的端點上只能有一個變體。
+ 您無法使用啟用自動擴展的端點。
+ 只有[即時推論](https://docs.aws.amazon.com/sagemaker/latest/dg/realtime-endpoints.html)才支援此功能。
+ 此功能不支援[即時多模型端點](https://docs.aws.amazon.com/sagemaker/latest/dg/multi-model-endpoints.html)。

**警告**  
強烈建議您不要在處理即時流量的生產端點上執行 Inference Recommender 任務。基準測試期間的綜合負載可能會影響您的生產端點，並導致調節或提供不正確的基準結果。建議您使用非生產或開發人員端點進行比較。

下列各節示範如何使用 Amazon SageMaker Inference Recommender，根據使用適用於 Python 的 AWS SDK (Boto3) 和 的模型類型，為現有端點建立推論建議 AWS CLI。

**注意**  
在建立 Inference Recommender 建議任務之前，請確定您已符合 [使用 Amazon SageMaker Inference Recommender 的先決條件](inference-recommender-prerequisites.md)。

## 先決條件
<a name="inference-recommender-existing-endpoint-prerequisites"></a>

如果您還沒有 SageMaker AI 推論端點，則可以在沒有端點的情況下[取得推論建議](https://docs.aws.amazon.com/sagemaker/latest/dg/inference-recommender-instance-recommendation.html)，也可以按照[建立您的端點並部署您的模型](https://docs.aws.amazon.com/sagemaker/latest/dg/realtime-endpoints-deployment.html)中的指示建立即時推論端點。

## 為現有端點建立推論建議任務
<a name="inference-recommender-existing-endpoint-create"></a>

使用 或 適用於 Python (Boto3) 的 AWS SDK以程式設計方式建立推論建議 AWS CLI。為您的推論建議指定任務名稱、現有 SageMaker AI 推論端點的名稱、IAM AWS 角色 ARN、輸入組態，以及您在向模型登錄檔註冊模型時的模型套件 ARN。

------
#### [ 適用於 Python (Boto3) 的 AWS SDK ]

使用 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateInferenceRecommendationsJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateInferenceRecommendationsJob.html) API 取得推論建議。將推論建議任務的 `JobType` 欄位設為 `'Default'`。此外，請提供下列項目：
+ 為 `JobName` 欄位的 Inference Recommender 建議任務提供名稱。Inference Recommender 任務名稱在 AWS 區域和您的帳戶 AWS 內必須是唯一的。
+ IAM 角色的 Amazon Resource Name (ARN)，可讓 Inference Recommender 代表您執行任務。為 `RoleArn` 欄位定義此項目。
+ 您在模型註冊表中註冊模型時所建立的版本化模型套件之 ARN。在 `InputConfig` 欄位中為 `ModelPackageVersionArn` 定義此項目。
+ 在 `InputConfig` 欄位中提供您要為 `Endpoints` 在 Inference Recommender 中進行基準測試的現有 SageMaker AI 推論端點的名稱。

匯入 適用於 Python (Boto3) 的 AWS SDK 套件，並使用用戶端類別建立 SageMaker AI 用戶端物件。如果您遵循**先決條件**一節中的步驟，模型套件群組 ARN 會儲存在名為 `model_package_arn` 的變數。

```
# Create a low-level SageMaker service client.
import boto3
aws_region = '<region>'
sagemaker_client = boto3.client('sagemaker', region_name=aws_region) 

# Provide your model package ARN that was created when you registered your 
# model with Model Registry 
model_package_arn = '<model-package-arn>'

# Provide a unique job name for SageMaker Inference Recommender job
job_name = '<job-name>'

# Inference Recommender job type. Set to Default to get an initial recommendation
job_type = 'Default'

# Provide an IAM Role that gives SageMaker Inference Recommender permission to 
# access AWS services
role_arn = '<arn:aws:iam::<account>:role/*>'
                                    
# Provide endpoint name for your endpoint that want to benchmark in Inference Recommender
endpoint_name = '<existing-endpoint-name>'

sagemaker_client.create_inference_recommendations_job(
    JobName = job_name,
    JobType = job_type,
    RoleArn = role_arn,
    InputConfig = {
        'ModelPackageVersionArn': model_package_arn,
        'Endpoints': [{'EndpointName': endpoint_name}]
    }
)
```

請參閱 [Amazon SageMaker API 參考指南](https://docs.aws.amazon.com/sagemaker/latest/APIReference/Welcome.html)，以取得可傳遞給 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateInferenceRecommendationsJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateInferenceRecommendationsJob.html) 的選用和必要引數之完整清單。

------
#### [ AWS CLI ]

使用 `create-inference-recommendations-job` API 取得執行個體端點建議。將執行個體端點建議任務的 `job-type` 欄位設為 `'Default'`。此外，請提供下列項目：
+ 為 `job-name` 欄位的 Inference Recommender 建議任務提供名稱。Inference Recommender 任務名稱在 AWS 區域和您的帳戶 AWS 內必須是唯一的。
+ IAM 角色的 Amazon Resource Name (ARN)，可讓 Amazon SageMaker Inference Recommender 代表您執行任務。為 `role-arn` 欄位定義此項目。
+ 您在模型註冊表中註冊模型時所建立的版本化模型套件之 ARN。在 `input-config` 欄位中為 `ModelPackageVersionArn` 定義此項目。
+ 在 `input-config` 欄位中提供您要為 `Endpoints` 在 Inference Recommender 中進行基準測試的現有 SageMaker AI 推論端點的名稱。

```
aws sagemaker create-inference-recommendations-job 
    --region <region>\
    --job-name <job_name>\
    --job-type Default\
    --role-arn arn:aws:iam::<account:role/*>\
    --input-config "{
        \"ModelPackageVersionArn\": \"arn:aws:sagemaker:<region:account:role/*>\",
        \"Endpoints\": [{\"EndpointName\": <endpoint_name>}]
        }"
```

------

## 取得您的推論建議任務結果
<a name="inference-recommender-existing-endpoint-results"></a>

您可以使用與標準推論建議任務相同的程序，以程式設計方式收集推論建議任務的結果。如需詳細資訊，請參閱[取得您的推論建議任務結果](instance-recommendation-results.md)。

當您取得現有端點的推論建議任務結果時，您應該會收到類似下列內容的 JSON 回應：

```
{
    "JobName": "job-name",
    "JobType": "Default",
    "JobArn": "arn:aws:sagemaker:region:account-id:inference-recommendations-job/resource-id",
    "RoleArn": "iam-role-arn",
    "Status": "COMPLETED",
    "CreationTime": 1664922919.2,
    "LastModifiedTime": 1664924208.291,
    "InputConfig": {
        "ModelPackageVersionArn": "arn:aws:sagemaker:region:account-id:model-package/resource-id",
        "Endpoints": [
            {
                "EndpointName": "endpoint-name"
            }
        ]
    },
    "InferenceRecommendations": [
        {
            "Metrics": {
                "CostPerHour": 0.7360000014305115,
                "CostPerInference": 7.456940238625975e-06,
                "MaxInvocations": 1645,
                "ModelLatency": 171
            },
            "EndpointConfiguration": {
                "EndpointName": "sm-endpoint-name",
                "VariantName": "variant-name",
                "InstanceType": "ml.g4dn.xlarge",
                "InitialInstanceCount": 1
            },
            "ModelConfiguration": {
                "EnvironmentParameters": [
                    {
                        "Key": "TS_DEFAULT_WORKERS_PER_MODEL",
                        "ValueType": "string",
                        "Value": "4"
                    }
                ]
            }
        }
    ],
    "EndpointPerformances": [
        {
            "Metrics": {
                "MaxInvocations": 184,
                "ModelLatency": 1312
            },
            "EndpointConfiguration": {
                "EndpointName": "endpoint-name"
            }
        }
    ]
}
```

前幾行提供推論建議任務本身的相關資訊。其中包含任務名稱、角色 ARN 以及建立和最新修改時間。

`InferenceRecommendations` 字典包含 Inference Recommender 推論建議的清單。

`EndpointConfiguration` 巢狀字典包含執行個體類型 (`InstanceType`) 建議，以及建議任務期間使用的端點和變體名稱 （已部署的 AWS 機器學習模型）。

`Metrics` 巢狀字典包含有關即時端點的估計每小時美元成本 (`CostPerHour`)、即時端點的預估每個推論美元成本 (`CostPerInference`)、傳送至端點的預期每分鐘 `InvokeEndpoint` 請求數量上限 (`MaxInvocations`)，以及模型延遲 (`ModelLatency`)，這是模型回應 SageMaker AI 所花費的時間間隔 (以毫秒為單位) 等資訊。模型延遲包含傳送請求和從模型容器擷取回應的本機通訊時間，以及在容器中完成推論的時間。

`EndpointPerformances` 巢狀字典包含執行建議任務的現有端點名稱 (`EndpointName`) 以及端點的效能指標 (`MaxInvocations` 和 `ModelLatency`)。

# 停止您的推論建議
<a name="instance-recommendation-stop"></a>

如果您不小心啟動任務或不再需要執行任務，建議您停止目前正在執行的任務。使用 `StopInferenceRecommendationsJob` API 或 Studio Classic，以程式設計方式停止您的 Inference Recommender 推論建議任務。

------
#### [ 適用於 Python (Boto3) 的 AWS SDK ]

指定 `JobName` 欄位的推論建議任務名稱：

```
sagemaker_client.stop_inference_recommendations_job(
                                    JobName='<INSERT>'
                                    )
```

------
#### [ AWS CLI ]

為 `job-name` 標記指定推論建議任務的任務名稱：

```
aws sagemaker stop-inference-recommendations-job --job-name <job-name>
```

------
#### [ Amazon SageMaker Studio Classic ]

關閉您在其中啟動推論建議的索引標籤，以停止您的 Inference Recommender 推論建議。

------
#### [ SageMaker AI console ]

若要透過 SageMaker AI 主控台停止執行個體建議任務，請執行以下操作：



1. 前往位在 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/) 的 SageMaker AI 主控台。

1. 在左側導覽窗格中，選擇**推論**，然後選擇**推論建議程式**。

1. 在**推論建議程式任務**頁面上，選取您的執行個體建議任務。

1. 選擇**停止任務**。

1. 在快顯對話方塊中，選擇**確認**。

停止任務後，任務的**狀態**應變更為**正在停止**。

------

# 使用 Neo 的編譯建議
<a name="inference-recommender-neo-compilation"></a>

在 Inference Recommender 中，您可以使用 Neo 編譯模型，並取得已編譯模型的端點建議。[SageMaker Neo](https://docs.aws.amazon.com/sagemaker/latest/dg/neo.html) 是一項可針對目標硬體平台 (也就是特定執行個體類型或環境) 最佳化模型的服務。使用 Neo 最佳化模型可能會改善託管模型的效能。

對於 Neo 支援的架構和容器，Inference Recommender 會自動建議 Neo 最佳化的建議。若要符合 Neo 編譯的資格，您的輸入必須符合以下先決條件：
+ 您使用的是 SageMaker AI 擁有的 [DLC](https://docs.aws.amazon.com/deep-learning-containers/latest/devguide/what-is-dlc.html) 或 XGBoost 容器。
+ 您使用的是 Neo 支援的架構版本。如需 Neo 支援的架構版本，請參閱 SageMaker Neo 文件中的[雲端執行個體](neo-supported-cloud.md#neo-supported-cloud-instances)。
+ Neo 要求您為模型提供正確的輸入資料形式。您可以在建立模型套件時，將此資料形式指定為 `[InferenceSpecification](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackage.html#sagemaker-CreateModelPackage-request-InferenceSpecification)` 中的 `[DataInputConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelInput.html#sagemaker-Type-ModelInput-DataInputConfig)`。如需每個架構正確資料形式的詳細資訊，請參閱 SageMaker Neo 文件中的[準備模型以進行編譯](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-compilation-preparing-model.html)。

  下列範例示範如何在 `InferenceSpecification` 中指定 `DataInputConfig` 欄位，其中 `data_input_configuration` 是包含字典格式之資料形式的變數 (例如 `{'input':[1,1024,1024,3]}`)。

  ```
  "InferenceSpecification": {
          "Containers": [
              {
                  "Image": dlc_uri,
                  "Framework": framework.upper(),
                  "FrameworkVersion": framework_version,
                  "NearestModelName": model_name,
                  "ModelInput": {"DataInputConfig": data_input_configuration},
              }
          ],
          "SupportedContentTypes": input_mime_types,  # required, must be non-null
          "SupportedResponseMIMETypes": [],
          "SupportedRealtimeInferenceInstanceTypes": supported_realtime_inference_types,  # optional
      }
  ```

如果您的請求中符合這些條件，則 Inference Recommender 會針對模型的編譯版本和未編譯版本執行案例，提供多種建議組合供您選擇。您可以比較相同推論建議的編譯版本和未編譯版本的組態，並判斷哪一個最適合您的使用案例。這些建議是按每個推論的成本來排序。

要獲得 Neo 編譯建議，除了確保您的輸入符合上述要求之外，您不必執行任何其他配置。如果您的輸入符合需求，Inference Recommender 會自動在您的模型上執行 Neo 編譯，而且您會收到包含 Neo 建議的回應。

如果您在 Neo 編譯期間遇到錯誤，請參閱[故障診斷 Neo 編譯錯誤](neo-troubleshooting-compilation.md)。

下表是您可能從 Inference Recommender 任務中取得的回應範例，其中包含已編譯模型的建議。如果 `InferenceSpecificationName` 欄位為 `None`，則建議是未編譯的模型。最後一列，其中 **InferenceSpecificationName** 欄位的值是 `neo-00011122-2333-4445-5566-677788899900`，此為用 Neo 編譯的模型。欄位中的值是用來編譯和最佳化模型的 Neo 任務名稱。


| EndpointName | InstanceType | InitialInstanceCount | EnvironmentParameters | CostPerHour | CostPerInference | MaxInvocations | ModelLatency | InferenceSpecificationName | 
| --- | --- | --- | --- | --- | --- | --- | --- | --- | 
| sm-epc-example-000111222 | ml.c5.9xlarge | 1 | [] | 1.836 | 9.15E-07 | 33456 | 7 | 無 | 
| sm-epc-example-111222333 | ml.c5.2xlarge | 1 | [] | 0.408 | 2.11E-07 | 32211 | 21 | 無 | 
| sm-epc-example-222333444 | ml.c5.xlarge | 1 | [] | 0.204 | 1.86E-07 | 18276 | 92 | 無 | 
| sm-epc-example-333444555 | ml.c5.xlarge | 1 | [] | 0.204 | 1.60E-07 | 21286 | 42 | neo-00011122-2333-4445-5566-677788899900 | 

## 開始使用
<a name="inference-recommender-neo-compilation-get-started"></a>

建立包含 Neo 最佳化建議之 Inference Recommender 任務的一般步驟如下：
+ 準備您的機器學習 (ML) 模型進行編譯。如需詳細資訊，請參閱 Neo 文件中的[準備編譯模型](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-compilation-preparing-model.html)。
+ 將您的模型封裝在模型封存 (`.tar.gz` 檔案)。
+ 建立範例承載封存。
+ 在 SageMaker 模型註冊表中註冊模型。
+ 建立 Inference Recommender 任務。
+ 檢視 Inference Recommender 任務的結果並選擇組態。
+ 偵錯編譯失敗 (如果有的話)。如需詳細資訊，請參閱 [Neo 編譯錯誤的故障診斷](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-troubleshooting-compilation.html)。

如需示範先前工作流程以及如何使用 XGBoost 取得 Neo 最佳化建議的範例，請參閱下列[範例筆記本](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-inference-recommender/xgboost/xgboost-inference-recommender.ipynb)。如需示範如何使用 TensorFlow 取得 Neo 最佳化建議的範例，請參閱下列[範例筆記本](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-inference-recommender/inference-recommender.ipynb)。

# 建議結果
<a name="inference-recommender-interpret-results"></a>

每個推論建議任務結果都包含 `InstanceType`、`InitialInstanceCount` 和 `EnvironmentParameters`，這些參數是針對容器調整的環境變數參數，以改善其延遲和輸送量。結果還包含效能和成本指標，例如 `MaxInvocations`、`ModelLatency`、`CostPerHour`、`CostPerInference`、`CpuUtilization` 和 `MemoryUtilization`。

在下表中，我們提供了這些指標的說明。這些指標可協助您縮小搜尋範圍，找出適合您使用案例的最佳端點組態。例如，如果您的動機是強調輸送量的整體價格表現，那麼您應專注於 `CostPerInference`。


| 指標 | Description | 使用案例 | 
| --- | --- | --- | 
|  `ModelLatency`  |  從 SageMaker AI 角度檢視，模型回應的時間間隔。這個間隔包含傳送請求和從模型容器擷取回應的本機通訊時間，以及在容器中完成推論的時間。 單位：毫秒  | 延遲敏感的工作負載，例如廣告投放和醫療診斷 | 
|  `MaximumInvocations`  |  一分鐘內傳送到模型端點的 `InvokeEndpoint` 請求數上限。 單位：無  | 以輸送量為中心的工作負載，例如影片處理或批次推論 | 
|  `CostPerHour`  |  即時端點每小時的預估成本。 單位：美元  | 成本敏感的工作負載，無延遲期限 | 
|  `CostPerInference`  |  即時端點每次推論呼叫的預估成本。 單位：美元  | 專注於輸送量，將整體價格效能發揮到極致 | 
|  `CpuUtilization`  |  端點執行個體每分鐘調用上限時的預期 CPU 利用率。 單位：百分比  | 透過了解執行個體的核心 CPU 利用率，掌握基準測試期間的執行個體運作狀態 | 
|  `MemoryUtilization`  |  端點執行個體每分鐘調用上限時的預期記憶體利用率。 單位：百分比  | 透過了解執行個體的核心記憶體利用率，掌握基準測試期間的執行個體運作狀態 | 

在某些情況下，您可能需要瀏覽其他 [SageMaker AI 端點調用指標](https://docs.aws.amazon.com/sagemaker/latest/dg/monitoring-cloudwatch.html#cloudwatch-metrics-endpoint-invocation)，例如 `CPUUtilization`。每個 Inference Recommender 任務結果都包含負載測試期間啟動的端點名稱。即使這些端點已刪除，您也可以使用 CloudWatch 來檢閱這些端點的日誌。

下列影像是 CloudWatch 指標和圖表的範例，您可以從建議結果檢閱單一端點。此建議結果來自某項預設任務。解讀建議結果中的純量值的方法是，它們是根據調用圖表首次開始向外平整時的時間點。例如，報告的 `ModelLatency` 值是在 `03:00:31` 高原的開始處持平。

![\[CloudWatch 指標的圖表。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/inference-recommender-cw-metrics.png)


如需先前圖表中使用之 CloudWatch 指標的完整說明，請參閱 [SageMaker AI 端點調用指標](https://docs.aws.amazon.com/sagemaker/latest/dg/monitoring-cloudwatch.html#cloudwatch-metrics-endpoint-invocation)。

您也可以在 `/aws/sagemaker/InferenceRecommendationsJobs` 命名空間中查看 Inference Recommender 所發佈的效能指標，例如 `ClientInvocations` 和 `NumberOfUsers`。如需 Inference Recommender 所發佈的指標和說明之完整指標清單，請參閱[SageMaker 推論建議程式任務指標](monitoring-cloudwatch.md#cloudwatch-metrics-inference-recommender)。

如需如何使用適用於 Python 的 AWS SDK (Boto3) 探索端點 [ CloudWatch 指標的範例，請參閱 amazon-sagemaker-examples Github 儲存庫中的 Amazon SageMaker Inference Recommender - CloudWatch Metrics](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-inference-recommender/tensorflow-cloudwatch/tf-cloudwatch-inference-recommender.ipynb) Jupyter 筆記本。 [amazon-sagemaker-examples](https://github.com/aws/amazon-sagemaker-examples) CloudWatch 

# 取得自動擴展政策的建議
<a name="inference-recommender-autoscaling"></a>

使用 Amazon SageMaker Inference Recommender，您可以根據預期的流量模式取得 SageMaker AI 端點自動擴展政策的建議。如果您已經完成推論建議任務，則可以提供任務的詳細資料，以取得可套用至端點之自動擴展政策的建議。

Inference Recommender 會針對每個指標進行不同的基準測試，以決定適用於端點的理想自動擴展組態。自動擴展建議會針對在推論建議任務中定義的每個指標，傳回建議的自動擴展政策。您可以儲存政策，並使用 [PutScalingPolicy](https://docs.aws.amazon.com/autoscaling/application/APIReference/API_PutScalingPolicy.html) API 將其套用至您的端點。

若要開始使用，請檢閱下列先決條件。

## 先決條件
<a name="inference-recommender-autoscaling-prereqs"></a>

在開始之前，您必須已經完成成功的推論建議任務。在下一節中，您可以提供在推論建議任務期間進行基準測試的推論建議 ID 或 SageMaker AI 端點的名稱。

若要擷取建議任務 ID 或端點名稱，您可以在 SageMaker AI 主控台中檢視推論建議任務的詳細資料，也可以使用 `RecommendationId` 或 [DescribeInferenceRecommendationsJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeInferenceRecommendationsJob.html) API 傳回的 `EndpointName` 欄位。

## 建立自動擴展設定建議
<a name="inference-recommender-autoscaling-create"></a>

若要建立自動擴展建議政策，您可以使用 適用於 Python (Boto3) 的 AWS SDK。

以下範例顯示 [GetScalingConfigurationRecommendation](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_GetScalingConfigurationRecommendation.html) API 的欄位。當您呼叫 API 時，請使用下列欄位：
+ `InferenceRecommendationsJobName` — 輸入推論建議任務的名稱。
+ `RecommendationId` — 輸入建議任務中推論建議的 ID。如果您已指定 `EndpointName` 欄位，這將為選用項目。
+ `EndpointName` — 輸入在推論建議任務期間進行基準測試的端點名稱。如果您已指定 `RecommendationId` 欄位，這將為選用項目。
+ `TargetCpuUtilizationPerCore` — (選用) 輸入您希望端點上執行個體在自動擴展之前使用多少使用率的百分比值。如未指定此欄位，預設值則為 50%。
+ `ScalingPolicyObjective` — (選用) 您可以在其中指定預期流量模式的物件。
  + `MinInvocationsPerMinute` — (選用) 每分鐘對端點的預期請求數量下限。
  + `MaxInvocationsPerMinute` — (選用) 每分鐘對端點的預期請求數目上限。

```
{
    "InferenceRecommendationsJobName": "string", // Required
    "RecommendationId": "string", // Optional, provide one of RecommendationId or EndpointName
    "EndpointName": "string", // Optional, provide one of RecommendationId or EndpointName
    "TargetCpuUtilizationPerCore": number, // Optional
    "ScalingPolicyObjective": { // Optional
        "MinInvocationsPerMinute": number,
        "MaxInvocationsPerMinute": number
    }
}
```

提交請求後，您將收到回應，其中包含針對每個指標定義的自動擴展政策。如需解讀回應的相關資訊，請參閱下列一節。

## 檢閱自動擴展設定建議結果
<a name="inference-recommender-autoscaling-review"></a>

以下範例顯示 [GetScalingConfigurationRecommendation](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_GetScalingConfigurationRecommendation.html) API 的回應：

```
{
    "InferenceRecommendationsJobName": "string", 
    "RecommendationId": "string", // One of RecommendationId or EndpointName is shown
    "EndpointName": "string", 
    "TargetUtilizationPercentage": Integer,
    "ScalingPolicyObjective": { 
        "MinInvocationsPerMinute": Integer, 
        "MaxInvocationsPerMinute": Integer
    },
    "Metric": {
        "ModelLatency": Integer,
        "InvocationsPerInstance": Integer
    },
    "DynamicScalingConfiguration": {
        "MinCapacity": number,
        "MaxCapacity": number, 
        "ScaleInCooldown": number,
        "ScaleOutCooldown": number,
        "ScalingPolicies": [
            {
                "TargetTracking": {
                    "MetricSpecification": {
                        "Predefined" {
                            "PredefinedMetricType": "string"
                         },
                        "Customized": {
                            "MetricName": "string",
                            "Namespace": "string",
                            "Statistic": "string"
                         }
                    },
                    "TargetValue": Double
                } 
            }
        ]
    }
}
```

系統會從您的初始請求複製 `InferenceRecommendationsJobName`、`RecommendationID` 或 `EndpointName`、`TargetCpuUtilizationPerCore` 和 `ScalingPolicyObjective` 物件欄位。

`Metric` 物件會列出推論建議任務中基準測試的指標，以及執行個體使用率與 `TargetCpuUtilizationPerCore` 值相同時，每個指標值的計算方式。這對於在使用建議的自動擴展政策進行擴展和縮小時預測端點上的效能指標非常實用。例如，假設您的執行個體使用率在推論建議任務中為 50%，而您原本的 `InvocationsPerInstance` 值為 `4`。如果您在自動擴展建議請求中將 `TargetCpuUtilizationPerCore` 值指定為 100%，則回應中傳回的 `InvocationsPerInstance` 指標值是 `2`，因為您預期配置的執行個體使用率是您預期配置兩倍的執行個體使用率。

當您呼叫 [PutScalingPolicy](https://docs.aws.amazon.com/autoscaling/application/APIReference/API_PutScalingPolicy.html) API 時，`DynamicScalingConfiguration` 物件會傳回您應該為 [TargetTrackingScalingPolicyConfiguration](https://docs.aws.amazon.com/autoscaling/application/APIReference/API_PutScalingPolicy.html#autoscaling-PutScalingPolicy-request-TargetTrackingScalingPolicyConfiguration) 指定的值。這包括建議的最小和最大容量值、建議的擴展和縮小冷卻時間，以及 `ScalingPolicies` 物件，其中包含您應為每個指標指定的建議 `TargetValue`。

# 執行自訂負載測試
<a name="inference-recommender-load-test"></a>

Amazon SageMaker Inference Recommender 負載測試會根據延遲和輸送量、自訂流量模式以及您選取的無伺服器端點或即時執行個體 (最多 10 個) 的生產需求，進行廣泛的基準測試。

下列各節示範如何使用 和 以程式設計方式建立、描述和停止負載測試 適用於 Python (Boto3) 的 AWS SDK AWS CLI，或使用 Amazon SageMaker Studio Classic 或 SageMaker AI 主控台以互動方式進行。

## 建立負載測試任務
<a name="load-test-create"></a>

使用 適用於 Python (Boto3) 的 AWS SDK、 搭配 以程式設計方式建立負載測試 AWS CLI，或使用 Studio Classic 或 SageMaker AI 主控台以互動方式建立負載測試。如同 Inference Recommender 推論建議，當您向模型登錄檔註冊模型時，請為負載測試指定任務名稱、IAM AWS 角色 ARN、輸入組態和模型套件 ARN。負載測試還會要求您指定流量模式和停止條件。

------
#### [ 適用於 Python (Boto3) 的 AWS SDK ]

使用 `CreateInferenceRecommendationsJob` API 建立 Inference Recommender 負載測試。為 `JobType` 欄位指定 `Advanced` 並提供：
+ 負載測試的任務名稱 (`JobName`)。任務名稱在您的 AWS 區域和 AWS 帳戶中必須是唯一的。
+ IAM 角色的 Amazon Resource Name (ARN)，可讓 Inference Recommender 代表您執行任務。為 `RoleArn` 欄位定義此項目。
+ 端點組態字典 (`InputConfig`)，方便您在其中指定以下項目：
  + 針對 `TrafficPattern`，指定階段或樓梯流量模式。透過階段流量模式，新使用者每分鐘產生一次您指定的速率。在階梯流量模式下，新使用者會以您指定的速率按定時間隔 (或*步驟*) 產生。選擇下列其中一項：
    + 對於 `TrafficType`，請指定 `PHASES`。接著，針對 `Phases` 陣列，指定 `InitialNumberOfUsers` (開始使用多少個並行使用者，最少為 1 且最多為 3 )、`SpawnRate` (在特定負載測試階段中，一分鐘內產生的使用者數目，最少為 0 且最多為 3)，以及 `DurationInSeconds` (流量階段應為多長時間，最少為 120 且最多為 3600)。
    + 對於 `TrafficType`，請指定 `STAIRS`。然後，針對 `Stairs` 陣列，指定 `DurationInSeconds` (流量階段應為多長時間，最少為 120 且最多為 3600)、`NumberOfSteps` (階段期間使用的間隔數目) 和 `UsersPerStep` (每個間隔期間新增了多少使用者)。請注意，每個步驟的長度都是 `DurationInSeconds / NumberOfSteps` 的值。例如，如果您的 `DurationInSeconds` 是 `600` 並指定 `5` 步驟，則每個步驟長度為 120 秒。
**注意**  
使用者會定義為系統產生的實行者，在迴路中執行，並以 Inference Recommender 的一部分調用端點的請求。對於在 `ml.c5.large` 執行個體上執行的典型 XGBoost 容器，端點每分鐘可達到 30,000 次調用 (500 tps)，而且只有 15-20 個使用者。
  + 對於 `ResourceLimit`，請指定 `MaxNumberOfTests` (Inference Recommender 任務的基準測試負載測試數目上限，最少為 1，最多為 10) 和 `MaxParallelOfTests` (Inference Recommender 任務的平行基準測試負載測試數目上限，最少為 1，最多為 10)。
  + 針對 `EndpointConfigurations`，您可以指定下列其中一項：
    + `InstanceType` 欄位方便您在其中指定要執行負載測試的執行個體類型。
    + 您可以在 `ServerlessConfig` 中為無伺服器端點指定 `MaxConcurrency` 和 `MemorySizeInMB` 的理想值。如需詳細資訊，請參閱[無伺服器推論文件](https://docs.aws.amazon.com/sagemaker/latest/dg/serverless-endpoints.html)。
+ 停止條件字典 (`StoppingConditions`)，如果符合任何條件，Inference Recommender 任務就會停止。對於此範例，請在字典中指定下列欄位：
  + 針對 `MaxInvocations`，指定端點每分鐘預期的請求數目上限，最少為 1 且最多為 30,000。
  + 針對 `ModelLatencyThresholds`，指定 `Percentile` (模型延遲百分位數閾值) 和 `ValueInMilliseconds` (模型延遲百分位數值 (以毫秒為單位))。
  + (選用) 針對 `FlatInvocations`，您可以指定當 TPS (每分鐘調用數) 速率持平時是否繼續負載測試。持平的 TPS 率通常表示端點已達到容量。不過，您可能需要在完整容量條件下繼續監控端點。若要在發生這種情況時繼續負載測試，請將此值指定為 `Continue`。否則，預設值為 `Stop`。

```
# Create a low-level SageMaker service client.
import boto3
aws_region=<INSERT>
sagemaker_client=boto3.client('sagemaker', region=aws_region) 
                
# Provide a name to your recommendation based on load testing
load_test_job_name="<INSERT>"

# Provide the name of the sagemaker instance type
instance_type="<INSERT>"

# Provide the IAM Role that gives SageMaker permission to access AWS services 
role_arn='arn:aws:iam::<account>:role/*'

# Provide your model package ARN that was created when you registered your 
# model with Model Registry
model_package_arn='arn:aws:sagemaker:<region>:<account>:role/*'

sagemaker_client.create_inference_recommendations_job(
                        JobName=load_test_job_name,
                        JobType="Advanced",
                        RoleArn=role_arn,
                        InputConfig={
                            'ModelPackageVersionArn': model_package_arn,
                            "JobDurationInSeconds": 7200,
                            'TrafficPattern' : {
                                # Replace PHASES with STAIRS to use the stairs traffic pattern
                                'TrafficType': 'PHASES',
                                'Phases': [
                                    {
                                        'InitialNumberOfUsers': 1,
                                        'SpawnRate': 1,
                                        'DurationInSeconds': 120
                                    },
                                    {
                                        'InitialNumberOfUsers': 1,
                                        'SpawnRate': 1,
                                        'DurationInSeconds': 120
                                    }
                                ]
                                # Uncomment this section and comment out the Phases object above to use the stairs traffic pattern
                                # 'Stairs' : {
                                #   'DurationInSeconds': 240,
                                #   'NumberOfSteps': 2,
                                #   'UsersPerStep': 2
                                # }
                            },
                            'ResourceLimit': {
                                        'MaxNumberOfTests': 10,
                                        'MaxParallelOfTests': 3
                                },
                            "EndpointConfigurations" : [{
                                        'InstanceType': 'ml.c5.xlarge'
                                    },
                                    {
                                        'InstanceType': 'ml.m5.xlarge'
                                    },
                                    {
                                        'InstanceType': 'ml.r5.xlarge'
                                    }]
                                    # Uncomment the ServerlessConfig and comment out the InstanceType field if you want recommendations for a serverless endpoint
                                    # "ServerlessConfig": {
                                    #     "MaxConcurrency": value, 
                                    #     "MemorySizeInMB": value 
                                    # }
                        },
                        StoppingConditions={
                            'MaxInvocations': 1000,
                            'ModelLatencyThresholds':[{
                                'Percentile': 'P95', 
                                'ValueInMilliseconds': 100
                            }],
                            # Change 'Stop' to 'Continue' to let the load test continue if invocations flatten 
                            'FlatInvocations': 'Stop'
                        }
                )
```

請參閱 [Amazon SageMaker API 參考指南](https://docs.aws.amazon.com/sagemaker/latest/APIReference/Welcome.html)，以取得可傳遞給 `CreateInferenceRecommendationsJob` 的選用和必要引數之完整清單。

------
#### [ AWS CLI ]

使用 `create-inference-recommendations-job` API 建立 Inference Recommender 負載測試。為 `JobType` 欄位指定 `Advanced` 並提供：
+ 負載測試的任務名稱 (`job-name`)。任務名稱在您的 AWS 區域和 AWS 帳戶中必須是唯一的。
+ IAM 角色的 Amazon Resource Name (ARN)，可讓 Inference Recommender 代表您執行任務。為 `role-arn` 欄位定義此項目。
+ 端點組態字典 (`input-config`)，方便您在其中指定以下項目：
  + 針對 `TrafficPattern`，指定階段或樓梯流量模式。透過階段流量模式，新使用者每分鐘產生一次您指定的速率。在階梯流量模式下，新使用者會以您指定的速率按定時間隔 (或*步驟*) 產生。選擇下列其中一項：
    + 對於 `TrafficType`，請指定 `PHASES`。接著，針對 `Phases` 陣列，指定 `InitialNumberOfUsers` (開始使用多少個並行使用者，最少為 1 且最多為 3 )、`SpawnRate` (在特定負載測試階段中，一分鐘內產生的使用者數目，最少為 0 且最多為 3)，以及 `DurationInSeconds` (流量階段應為多長時間，最少為 120 且最多為 3600)。
    + 對於 `TrafficType`，請指定 `STAIRS`。然後，針對 `Stairs` 陣列，指定 `DurationInSeconds` (流量階段應為多長時間，最少為 120 且最多為 3600)、`NumberOfSteps` (階段期間使用的間隔數目) 和 `UsersPerStep` (每個間隔期間新增了多少使用者)。請注意，每個步驟的長度都是 `DurationInSeconds / NumberOfSteps` 的值。例如，如果您的 `DurationInSeconds` 是 `600` 並指定 `5` 步驟，則每個步驟長度為 120 秒。
**注意**  
使用者會定義為系統產生的實行者，在迴路中執行，並以 Inference Recommender 的一部分調用端點的請求。對於在 `ml.c5.large` 執行個體上執行的典型 XGBoost 容器，端點每分鐘可達到 30,000 次調用 (500 tps)，而且只有 15-20 個使用者。
  + 對於 `ResourceLimit`，請指定 `MaxNumberOfTests` (Inference Recommender 任務的基準測試負載測試數目上限，最少為 1，最多為 10) 和 `MaxParallelOfTests` (Inference Recommender 任務的平行基準測試負載測試數目上限，最少為 1，最多為 10)。
  + 針對 `EndpointConfigurations`，您可以指定下列其中一項：
    + `InstanceType` 欄位方便您在其中指定要執行負載測試的執行個體類型。
    + 您可以在 `ServerlessConfig` 中為無伺服器端點指定 `MaxConcurrency` 和 `MemorySizeInMB` 的理想值。
+ 停止條件字典 (`stopping-conditions`)，如果符合任何條件，Inference Recommender 任務就會停止。對於此範例，請在字典中指定下列欄位：
  + 針對 `MaxInvocations`，指定端點每分鐘預期的請求數目上限，最少為 1 且最多為 30,000。
  + 針對 `ModelLatencyThresholds`，指定 `Percentile` (模型延遲百分位數閾值) 和 `ValueInMilliseconds` (模型延遲百分位數值 (以毫秒為單位))。
  + (選用) 針對 `FlatInvocations`，您可以指定當 TPS (每分鐘調用數) 速率持平時是否繼續負載測試。持平的 TPS 率通常表示端點已達到容量。不過，您可能需要在完整容量條件下繼續監控端點。若要在發生這種情況時繼續負載測試，請將此值指定為 `Continue`。否則，預設值為 `Stop`。

```
aws sagemaker create-inference-recommendations-job\
    --region <region>\
    --job-name <job-name>\
    --job-type ADVANCED\
    --role-arn arn:aws:iam::<account>:role/*\
    --input-config \"{
        \"ModelPackageVersionArn\": \"arn:aws:sagemaker:<region>:<account>:role/*\",
        \"JobDurationInSeconds\": 7200,                                
        \"TrafficPattern\" : {
                # Replace PHASES with STAIRS to use the stairs traffic pattern
                \"TrafficType\": \"PHASES\",
                \"Phases\": [
                    {
                        \"InitialNumberOfUsers\": 1,
                        \"SpawnRate\": 60,
                        \"DurationInSeconds\": 300
                    }
                ]
                # Uncomment this section and comment out the Phases object above to use the stairs traffic pattern
                # 'Stairs' : {
                #   'DurationInSeconds': 240,
                #   'NumberOfSteps': 2,
                #   'UsersPerStep': 2
                # }
            },
            \"ResourceLimit\": {
                \"MaxNumberOfTests\": 10,
                \"MaxParallelOfTests\": 3
            },
            \"EndpointConfigurations\" : [
                {
                    \"InstanceType\": \"ml.c5.xlarge\"
                },
                {
                    \"InstanceType\": \"ml.m5.xlarge\"
                },
                {
                    \"InstanceType\": \"ml.r5.xlarge\"
                }
                # Use the ServerlessConfig and leave out the InstanceType fields if you want recommendations for a serverless endpoint
                # \"ServerlessConfig\": {
                #     \"MaxConcurrency\": value, 
                #     \"MemorySizeInMB\": value 
                # }
            ]
        }\"
    --stopping-conditions \"{
        \"MaxInvocations\": 1000,
        \"ModelLatencyThresholds\":[
                {
                    \"Percentile\": \"P95\", 
                    \"ValueInMilliseconds\": 100
                }
        ],
        # Change 'Stop' to 'Continue' to let the load test continue if invocations flatten 
        \"FlatInvocations\": \"Stop\"
    }\"
```

------
#### [ Amazon SageMaker Studio Classic ]

使用 Studio Classic 建立負載測試。

1. 在您的 Studio Classic 應用程式中，選擇首頁圖示 (![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/studio/icons/house.png))。

1. 在 Studio Classic 的左側邊欄中，選擇**部署**。

1. 從下拉式清單中選擇**推論建議程式**。

1. 選擇**建立推論建議程式任務**。名為**建立推論建議程式任務**的新索引標籤會隨即開啟。

1. 從下拉式清單**模型群組**欄位中選取模型群組的名稱。此清單包含在您帳戶中註冊至模型註冊表的所有模型群組，包括在 Studio Classic 外部註冊的模型。

1. 從下拉式清單**模型版本**欄位中選取模型版本。

1. 選擇**繼續**。

1. 在**名稱**欄位中提供任務的名稱。

1. (選用) 在**說明**欄位中提供任務的描述。

1. 選擇授予 Inference Recommender 存取 AWS 服務的許可的 IAM 角色。您可以建立角色並連接 `AmazonSageMakerFullAccess` IAM 受管政策來達成此目的，也可以讓 Studio Classic 為您建立角色。

1. 選擇**停止條件**以展開可用的輸入欄位。提供一組停止部署建議的條件。

   1. 在**每分鐘調用數上限**欄位中，指定端點每分鐘預期的請求數量上限。

   1. 在**模型延遲閾值**欄位中指定模型延遲閾值 (以微秒為單位)。**模型延遲閾值**描述了從 Inference Recommender 檢視的模型回應所花費的時間間隔。這個間隔包含傳送請求和從模型容器擷取回應的本機通訊時間，以及在容器中完成推論的時間。

1. 選擇**流量模式**以展開可用的輸入欄位。

   1. 在**初始使用者數目**欄位中指定一個整數，以設定虛擬使用者的初始數量。

   1. 在**產生率**欄位中提供一個整數。產生率設定每秒建立的使用者數目。

   1. 在**持續時間**欄位中指定一個整數，以秒為單位設定階段的持續時間。

   1. (選用) 新增其他流量模式。若要這麼做，請選擇**新增**。

1. 選擇**其他**設定以顯示**最長測試持續時間**欄位。指定任務期間測試所需的時間上限 (以秒為單位)。在定義的持續時間之後，不會排定新任務。這有助於確保進行中的任務不會停止，而且您只能檢視已完成的任務。

1. 選擇**繼續**。

1. 選擇**選取的執行個體**。

1. 在**基準測試執行個體**欄位中，選擇**新增要測試的執行個體**。為 Inference Recommender 選取最多 10 個執行個體，以用於負載測試。

1. 選擇**其他設定**。

   1. 提供一個整數，此整數會設定任務可在**測試數量上限欄位**中進行的測試次數上限。請注意，每個端點組態都會產生新的負載測試。

   1. 為**平行測試上限**測試欄位提供一個整數。此設定定義可以平行執行的負載測試次數上限。

1. 選擇**提交**。

   負載測試最多需要 2 小時的時間。
**警告**  
請勿關閉此索引標籤。如果您關閉此索引標籤，就會取消 Inference Recommender 負載測試任務。

------
#### [ SageMaker AI console ]

透過執行下列動作，透過 SageMaker AI 主控台建立自訂負載測試：

1. 前往位在 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/) 的 SageMaker AI 主控台。

1. 在左側導覽窗格中，選擇**推論**，然後選擇**推論建議程式**。

1. 在**推論建議程式任務**頁面上，選擇**建立任務**。

1. 針對**步驟 1：模型組態**，執行下列動作：

   1. 針對**任務類型**，選擇**進階推薦程式任務**。

   1. 如果您使用的是在 SageMaker AI 模型註冊表中註冊的模型，請開啟**從模型註冊表中選擇模型**切換鈕並執行下列動作：

      1. 對於**模型群組**下拉式清單，請在 SageMaker AI 模型註冊表中選擇模型所在的模型群組。

      1. 對於**模型版本**下拉式清單，選擇您想要的模型版本。

   1. 如果您使用的是在 SageMaker AI 中建立的模型，請關閉**從模型註冊表中選擇模型切換鈕**，然後執行下列動作：

      1. 在**模型名稱**欄位中，輸入 SageMaker AI 模型的名稱。

   1. 對於 **IAM 角色**，您可以選取具有建立執行個體建議任務所需許可的現有 IAM 角色。 AWS 或者，如果您沒有現有角色，可以選擇**建立新角色**以開啟角色建立快顯視窗，SageMaker AI 會將必要的權限新增至您建立的新角色。

   1. 針對**用於基準測試承載的 S3 儲存貯體**，請輸入您範例承載存檔的 Amazon S3 路徑，其中應包含 Inference Recommender 用於在不同執行個體類型上對模型進行基準測試的範例承載檔案。

   1. 針對**承載內容類型**，輸入範例承載資料的 MIME 類型。

   1. 對於**流量模式**，請執行下列動作來設定負載測試的階段：

      1. 對於**初始使用者數目**，請指定您要開始使用的並行使用者數目 (最少為 1，最多為 3)。

      1. 對於**產生率**，請指定該階段在一分鐘內產生的使用者數目 (最少為 0 且最多為 3)。

      1. 對於**持續時間 (秒)**，請指定流量階段應多低，以秒為單位 (最少為 120 且最多為 3600)。

   1. (選用) 如果您關閉了**從模型註冊表中選擇模型切換鈕**並指定 SageMaker AI 模型，則針對**容器組態**，請執行下列操作：

      1. 在**網域**下拉式清單中，選取模型的機器學習領域，例如電腦視覺、自然語言處理或機器學習。

      1. 在**架構**下拉式清單中，選取容器的架構，例如 TensorFlow 或 XGBoost。

      1. 針對**架構版本**，請輸入容器映像的架構版本。

      1. 在**最近的模型名稱**下拉式清單中，選取大部分與您自己的模型相符的預先訓練模型。

      1. 針對**任務**下拉式清單，選取模型完成的機器學習任務，例如影像分類或迴歸。

   1. (選用) 對於**使用 SageMaker Neo 進行模型編譯**，您可以為已使用 SageMaker Neo 編譯的模型設定建議任務。針對**資料輸入組態**，請以類似 `{'input':[1,1024,1024,3]}` 的格式輸入模型的正確輸入資料形式。

   1. 選擇**下一步**。

1. 針對**步驟 2：執行個體和環境參數**，請執行下列操作：

   1. 針對**選取要進行基準測試的執行個體**，請選取最多 8 個您要進行基準測試的執行個體類型。

   1. (選用) 對於**環境參數範圍**，您可以指定有助於最佳化模型的環境參數。將參數指定為**鍵**和**值**對。

   1. 選擇**下一步**。

1. 針對**步驟 3：任務參數**，請執行下列動作：

   1. (選用) 針對**工作名稱**欄位，輸入執行個體建議任務的名稱。當您建立任務時，SageMaker AI 會在此名稱的結尾附加一個時間戳記。

   1. (選用) 針對**工作描述**，輸入該任務的描述。

   1. （選用） 針對**加密金鑰**下拉式清單，依名稱選擇 AWS KMS 金鑰，或輸入其 ARN 來加密您的資料。

   1. (選用) 針對**測試次數上限**，輸入建議任務期間要執行的測試數量。

   1. (選用) 針對**平行測試上限**，輸入建議任務期間要執行的平行測試數量上限。

   1. 針對**最長測試持續時間**，請輸入您希望每個測試執行的秒數上限。

   1. 針對**每分鐘調用數上限**，請輸入端點在停止建議任務之前每分鐘可達到的請求數量上限。達到此限制後，SageMaker AI 會結束任務。

   1. 對於 **P99 模型延遲閾值 (ms)**，輸入模型延遲百分位數 (以毫秒為單位)。

   1. 選擇**下一步**。

1. 針對**步驟 4：檢閱任務**，檢閱您的組態，然後選擇**提交**。

------

## 取得負載測試結果
<a name="load-test-describe"></a>

完成負載測試後，您可以透過程式設計方式收集所有負載測試的指標 適用於 Python (Boto3) 的 AWS SDK、 AWS CLI、Studio Classic 或 SageMaker AI 主控台。

------
#### [ 適用於 Python (Boto3) 的 AWS SDK ]

使用 `DescribeInferenceRecommendationsJob` API 收集指標。為 `JobName` 欄位指定負載測試的任務名稱：

```
load_test_response = sagemaker_client.describe_inference_recommendations_job(
                                                        JobName=load_test_job_name
                                                        )
```

列印回應物件。

```
load_test_response['Status']
```

此項目會傳回類似下列範例的 JSON 回應。請注意，此範例顯示建議的即時推論執行個體類型 (如需顯示無伺服器推論建議的範例，請參閱此範例之後的範例)。

```
{
    'JobName': 'job-name', 
    'JobDescription': 'job-description', 
    'JobType': 'Advanced', 
    'JobArn': 'arn:aws:sagemaker:region:account-id:inference-recommendations-job/resource-id', 
    'Status': 'COMPLETED', 
    'CreationTime': datetime.datetime(2021, 10, 26, 19, 38, 30, 957000, tzinfo=tzlocal()), 
    'LastModifiedTime': datetime.datetime(2021, 10, 26, 19, 46, 31, 399000, tzinfo=tzlocal()), 
    'InputConfig': {
        'ModelPackageVersionArn': 'arn:aws:sagemaker:region:account-id:model-package/resource-id', 
        'JobDurationInSeconds': 7200, 
        'TrafficPattern': {
            'TrafficType': 'PHASES'
            }, 
        'ResourceLimit': {
            'MaxNumberOfTests': 100, 
            'MaxParallelOfTests': 100
            }, 
        'EndpointConfigurations': [{
            'InstanceType': 'ml.c5d.xlarge'
            }]
        }, 
    'StoppingConditions': {
        'MaxInvocations': 1000, 
        'ModelLatencyThresholds': [{
            'Percentile': 'P95', 
            'ValueInMilliseconds': 100}
            ]}, 
    'InferenceRecommendations': [{
        'Metrics': {
            'CostPerHour': 0.6899999976158142, 
            'CostPerInference': 1.0332434612791985e-05, 
            'MaximumInvocations': 1113, 
            'ModelLatency': 100000
            }, 
    'EndpointConfiguration': {
        'EndpointName': 'endpoint-name', 
        'VariantName': 'variant-name', 
        'InstanceType': 'ml.c5d.xlarge', 
        'InitialInstanceCount': 3
        }, 
    'ModelConfiguration': {
        'Compiled': False, 
        'EnvironmentParameters': []
        }
    }], 
    'ResponseMetadata': {
        'RequestId': 'request-id', 
        'HTTPStatusCode': 200, 
        'HTTPHeaders': {
            'x-amzn-requestid': 'x-amzn-requestid', 
            'content-type': 'content-type', 
            'content-length': '1199', 
            'date': 'Tue, 26 Oct 2021 19:57:42 GMT'
            }, 
        'RetryAttempts': 0}
    }
```

前幾行提供負載測試任務本身的相關資訊。其中包含任務名稱、角色 ARN 以及建立和刪除時間。

`InferenceRecommendations` 字典包含 Inference Recommender 推論建議的清單。

`EndpointConfiguration` 巢狀字典包含執行個體類型 (`InstanceType`) 建議，以及建議任務期間使用的端點和變體名稱 （已部署的 AWS 機器學習模型）。您可以使用端點和變體名稱在 Amazon CloudWatch Events 中進行監控。如需詳細資訊，請參閱[Amazon CloudWatch 中的 Amazon SageMaker AI 指標](monitoring-cloudwatch.md)。

`EndpointConfiguration` 巢狀字典也包含執行個體計數 (`InitialInstanceCount`) 建議。這是您應在端點中佈建以符合 `StoppingConditions` 中指定的 `MaxInvocations` 執行個體數目。例如，如果 `InstanceType` 為 `ml.m5.large` 而 `InitialInstanceCount` 是 `2`，則您應該為端點佈建 2 個 `ml.m5.large` 執行個體，以便它可以處理 `MaxInvocations` 停止條件中指定的 TPS。

`Metrics` 巢狀字典包含有關即時端點的估計每小時成本 (`CostPerHour`)、即時端點的預估每個推論美元成本 (`CostPerInference`)、傳送至端點的 `InvokeEndpoint` 請求數量上限，以及模型延遲 (`ModelLatency`)，這是模型回應 SageMaker AI 所花費的時間間隔 (以微秒為單位) 等資訊。模型延遲包含傳送請求和從模型容器擷取回應的本機通訊時間，以及在容器中完成推論的時間。

下列範例顯示設定為傳回無伺服器推論建議之負載測試任務的 `InferenceRecommendations` 回應部分：

```
"InferenceRecommendations": [ 
      { 
         "EndpointConfiguration": { 
            "EndpointName": "value",
            "InitialInstanceCount": value,
            "InstanceType": "value",
            "VariantName": "value",
            "ServerlessConfig": {
                "MaxConcurrency": value,
                "MemorySizeInMb": value
            }
         },
         "InvocationEndTime": value,
         "InvocationStartTime": value,
         "Metrics": { 
            "CostPerHour": value,
            "CostPerInference": value,
            "CpuUtilization": value,
            "MaxInvocations": value,
            "MemoryUtilization": value,
            "ModelLatency": value,
            "ModelSetupTime": value
         },
         "ModelConfiguration": { 
            "Compiled": "False",
            "EnvironmentParameters": [],
            "InferenceSpecificationName": "value"
         },
         "RecommendationId": "value"
      }
   ]
```

您可以解讀無伺服器推論的建議，類似於即時推論的結果，但不包括 `ServerlessConfig`，它會告訴您具有指定 `MaxConcurrency` 和 `MemorySizeInMB` 值的負載測試設定之指標。無伺服器建議也會測量指標 `ModelSetupTime`，以測量在無伺服器端點上啟動運算資源所需的時間 (以微秒為單位)。如需有關設定無伺服器端點的詳細資訊，請參閱[無伺服器推論文件](https://docs.aws.amazon.com/sagemaker/latest/dg/serverless-endpoints.html)。

------
#### [ AWS CLI ]

使用 `describe-inference-recommendations-job` API 收集指標。為 `job-name` 標記指定負載測試的任務名稱：

```
aws sagemaker describe-inference-recommendations-job --job-name <job-name>
```

此項目會傳回類似下列範例的回應。請注意，此範例顯示建議的即時推論執行個體類型 (如需顯示無伺服器推論建議的範例，請參閱此範例之後的範例)。

```
{
    'JobName': 'job-name', 
    'JobDescription': 'job-description', 
    'JobType': 'Advanced', 
    'JobArn': 'arn:aws:sagemaker:region:account-id:inference-recommendations-job/resource-id', 
    'Status': 'COMPLETED', 
    'CreationTime': datetime.datetime(2021, 10, 26, 19, 38, 30, 957000, tzinfo=tzlocal()), 
    'LastModifiedTime': datetime.datetime(2021, 10, 26, 19, 46, 31, 399000, tzinfo=tzlocal()), 
    'InputConfig': {
        'ModelPackageVersionArn': 'arn:aws:sagemaker:region:account-id:model-package/resource-id', 
        'JobDurationInSeconds': 7200, 
        'TrafficPattern': {
            'TrafficType': 'PHASES'
            }, 
        'ResourceLimit': {
            'MaxNumberOfTests': 100, 
            'MaxParallelOfTests': 100
            }, 
        'EndpointConfigurations': [{
            'InstanceType': 'ml.c5d.xlarge'
            }]
        }, 
    'StoppingConditions': {
        'MaxInvocations': 1000, 
        'ModelLatencyThresholds': [{
            'Percentile': 'P95', 
            'ValueInMilliseconds': 100
            }]
        }, 
    'InferenceRecommendations': [{
        'Metrics': {
        'CostPerHour': 0.6899999976158142, 
        'CostPerInference': 1.0332434612791985e-05, 
        'MaximumInvocations': 1113, 
        'ModelLatency': 100000
        }, 
        'EndpointConfiguration': {
            'EndpointName': 'endpoint-name', 
            'VariantName': 'variant-name', 
            'InstanceType': 'ml.c5d.xlarge', 
            'InitialInstanceCount': 3
            }, 
        'ModelConfiguration': {
            'Compiled': False, 
            'EnvironmentParameters': []
            }
        }], 
    'ResponseMetadata': {
        'RequestId': 'request-id', 
        'HTTPStatusCode': 200, 
        'HTTPHeaders': {
            'x-amzn-requestid': 'x-amzn-requestid', 
            'content-type': 'content-type', 
            'content-length': '1199', 
            'date': 'Tue, 26 Oct 2021 19:57:42 GMT'
            }, 
        'RetryAttempts': 0
        }
    }
```

前幾行提供負載測試任務本身的相關資訊。其中包含任務名稱、角色 ARN 以及建立和刪除時間。

`InferenceRecommendations` 字典包含 Inference Recommender 推論建議的清單。

`EndpointConfiguration` 巢狀字典包含執行個體類型 (`InstanceType`) 建議，以及建議任務期間使用的端點和變體名稱 （已部署的 AWS 機器學習模型）。您可以使用端點和變體名稱在 Amazon CloudWatch Events 中進行監控。如需詳細資訊，請參閱[Amazon CloudWatch 中的 Amazon SageMaker AI 指標](monitoring-cloudwatch.md)。

`Metrics` 巢狀字典包含有關即時端點的估計每小時成本 (`CostPerHour`)、即時端點的預估每個推論美元成本 (`CostPerInference`)、傳送至端點的 `InvokeEndpoint` 請求數量上限，以及模型延遲 (`ModelLatency`)，這是模型回應 SageMaker AI 所花費的時間間隔 (以微秒為單位) 等資訊。模型延遲包含傳送請求和從模型容器擷取回應的本機通訊時間，以及在容器中完成推論的時間。

下列範例顯示設定為傳回無伺服器推論建議之負載測試任務的 `InferenceRecommendations` 回應部分：

```
"InferenceRecommendations": [ 
      { 
         "EndpointConfiguration": { 
            "EndpointName": "value",
            "InitialInstanceCount": value,
            "InstanceType": "value",
            "VariantName": "value",
            "ServerlessConfig": {
                "MaxConcurrency": value,
                "MemorySizeInMb": value
            }
         },
         "InvocationEndTime": value,
         "InvocationStartTime": value,
         "Metrics": { 
            "CostPerHour": value,
            "CostPerInference": value,
            "CpuUtilization": value,
            "MaxInvocations": value,
            "MemoryUtilization": value,
            "ModelLatency": value,
            "ModelSetupTime": value
         },
         "ModelConfiguration": { 
            "Compiled": "False",
            "EnvironmentParameters": [],
            "InferenceSpecificationName": "value"
         },
         "RecommendationId": "value"
      }
   ]
```

您可以解讀無伺服器推論的建議，類似於即時推論的結果，但不包括 `ServerlessConfig`，它會告訴您具有指定 `MaxConcurrency` 和 `MemorySizeInMB` 值的負載測試設定之指標。無伺服器建議也會測量指標 `ModelSetupTime`，以測量在無伺服器端點上啟動電腦資源所需的時間 (以微秒為單位)。如需有關設定無伺服器端點的詳細資訊，請參閱[無伺服器推論文件](https://docs.aws.amazon.com/sagemaker/latest/dg/serverless-endpoints.html)。

------
#### [ Amazon SageMaker Studio Classic ]

建議內容會填入 Studio Classic 內名為**推論建議**的新索引標籤中。最多可能需要 2 小時，結果才會顯示。此索引標籤包含**結果**和**詳細資訊**欄。

**詳細資訊**欄提供有關負載測試任務的資訊，例如指定給負載測試任務的名稱、建立任務的時間 (**建立時間**) 等。它也包含**設定**資訊，例如每分鐘發生的調用次數上限，以及所使用之 Amazon Resource Name 的相關資訊。

**結果**欄提供**部署目標**和 **SageMaker AI 建議**視窗，您可以在其中根據部署重要性調整結果的顯示順序。您可以在三個下拉式清單選單中為使用案例提供**成本**、**延遲**和**輸送量**的重要性層級。您可以針對每個目標 (成本、延遲和輸送量) 設定重要性層級：**最低重要性**、**低重要性**、**中等重要性**、**高重要性**或**最高重要性**。

根據您對每個目標的重要性選擇，Inference Recommender 會在面板右側的 **SageMaker 建議**欄位中顯示其最佳建議，以及每小時的預估成本和推論請求。同時也提供預期模型延遲、調用次數上限以及執行個體數目的相關資訊。

除了顯示的最佳建議之外，您也可以看到在**所有執行**段落中，Inference Recommender 測試過的所有執行個體處理所顯示的相同資訊。

------
#### [ SageMaker AI console ]

您可以執行下列動作，在 SageMaker AI 主控台中檢視自訂負載測試任務結果：

1. 前往位在 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/) 的 SageMaker AI 主控台。

1. 在左側導覽窗格中，選擇**推論**，然後選擇**推論建議程式**。

1. 在**推論建議程式任務**頁面上，選擇推論建議任務的名稱。

在任務的詳細資料頁面上，您可以檢視**推論建議**，這是 SageMaker AI 針對您的模型建議的執行個體類型，如下列螢幕擷取畫面所示。

![\[SageMaker AI 主控台中任務詳細資料頁面上推論建議清單的螢幕擷取畫面。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/inf-rec-instant-recs.png)


在本節中，您可以依各種因素比較執行個體類型，例如**模型延遲**、**每小時成本**、**每個推論的成本**、**每分鐘調用數**。

您也可以在此頁面檢視針對您指定的組態。在**監控**區段中，您可以檢視針對每個執行個體類型記錄的 Amazon CloudWatch 指標。若要深入了解如何解讀這些指標，請參閱[解讀結果](https://docs.aws.amazon.com/sagemaker/latest/dg/inference-recommender-interpret-results.html)。

------

# 停止您的負載測試
<a name="load-test-stop"></a>

如果您不小心啟動任務或不再需要執行任務，建議您停止目前正在執行的任務。透過 `StopInferenceRecommendationsJob` API，或透過 Studio Classic 或 SageMaker AI 主控台，以程式設計方式停止負載測試任務。

------
#### [ 適用於 Python (Boto3) 的 AWS SDK ]

為 `JobName` 欄位指定負載測試的任務名稱：

```
sagemaker_client.stop_inference_recommendations_job(
                                    JobName='<INSERT>'
                                    )
```

------
#### [ AWS CLI ]

為 `job-name` 標記指定負載測試的任務名稱：

```
aws sagemaker stop-inference-recommendations-job --job-name <job-name>
```

------
#### [ Amazon SageMaker Studio Classic ]

關閉您啟動自訂載入任務的索引標籤，以停止 Inference Recommender 負載測試。

------
#### [ SageMaker AI console ]

若要透過 SageMaker AI 主控台停止負載測試任務，請執行以下操作：

1. 前往位在 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/) 的 SageMaker AI 主控台。

1. 在左側導覽窗格中，選擇**推論**，然後選擇**推論建議程式**。

1. 在**推論建議程式任務**頁面上，選取您的負載測試任務。

1. 選擇**停止任務**。

1. 在快顯對話方塊中，選擇**確認**。

停止任務後，任務的**狀態**應變更為**正在停止**。

------

# 故障診斷 Inference Recommender 錯誤
<a name="inference-recommender-troubleshooting"></a>

本節包含如何了解並防止常見錯誤、其所產生錯誤訊息的資訊，以及如何解決這些錯誤的指導方針。

## 如何故障診斷
<a name="inference-recommender-troubleshooting-how-to"></a>

您可以透過執行以下步驟嘗試解決錯誤：
+ 檢查您是否已涵蓋使用 Inference Recommender 的所有先決條件。請參閱 [Inference Recommender 先決條件](https://docs.aws.amazon.com/sagemaker/latest/dg/inference-recommender-prerequisites.html)。
+ 檢查您是否能夠將模型從模型註冊表部署到端點，並且可毫無錯誤地處理您的承載。請參閱[從註冊表部署模型](https://docs.aws.amazon.com/sagemaker/latest/dg/model-registry-deploy.html)。
+ 當您開始執行 Inference Recommender 任務時，您應該會看到在主控台中建立的端點，而且也可以檢閱 CloudWatch 記錄。

## 常見錯誤
<a name="inference-recommender-troubleshooting-common"></a>

請參閱下表，了解常見的 Inference Recommender 錯誤及其解決方案。


| 錯誤 | 解決方案 | 
| --- | --- | 
|  在模型套件版本 1 中指定 `Domain`。`Domain` 是任務的必要參數。  |  確保您提供機器學習 (ML) 網域或者在未知的情況下提供 `OTHER`。  | 
|  無法假設提供的角色 ARN 並發生 `AWSSecurityTokenServiceException` 錯誤。  |  請確定提供的執行角色具有先決條件中指定的必要許可。  | 
|  在模型套件版本 1 中指定 `Framework`。`Framework` 是任務的必要參數。  |  確保您提供機器學習 (ML) 架構或者在未知的情況下提供 `OTHER`。  | 
|  上一階段結束時的使用者為 0，而目前階段的初始使用者為 1。  |  此處的使用者指的是用來傳送請求的虛擬使用者或執行緒。每個階段都以 A 使用者開始，並以 B 使用者結束，以便 B > A. 在循序階段 x\$11 和 x\$12 之間，我們會要求 abs(x\$12.A - x\$11.B) <= 3 且 >= 0。  | 
|  總流量持續時間 (跨階段) 不應超過任務持續時間。  |  所有階段的總持續時間不能超過任務持續時間。  | 
|  不允許高載執行個體類型 ml.t2.medium。  |  Inference Recommender 不支援 t2 執行個體系列上的負載測試，因為高載執行個體無法提供一致的效能。  | 
|  呼叫 CreateEndpoint 操作時使用 ResourceLimitExceeded  |  您已超過 SageMaker AI 資源限制。例如，如果帳戶已達到端點配額，Inference Recommender 可能無法佈建端點以進行基準測試。如需 SageMaker AI 限制和配額的參考資訊，請參閱 [Amazon SageMaker AI 端點與配額](https://docs.aws.amazon.com/general/latest/gr/sagemaker.html)。  | 
|  呼叫 InvokeEndpoint 操作時出現 ModelError  |  模型錯誤可能是由於下列原因所發生： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/inference-recommender-troubleshooting.html)  | 
|  呼叫 InvokeEndpoint 操作時出現 PayloadError  |  承載錯誤可能是由於下列原因所發生： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/inference-recommender-troubleshooting.html)  | 

## 檢查 CloudWatch
<a name="inference-recommender-troubleshooting-check-cw"></a>

當您開始執行 Inference Recommender 任務時，您應該會看到主控台正在建立端點。選取其中一個端點並檢視 CloudWatch 日誌，以監控是否有任何 4xx/5xx 錯誤。如果您有成功的 Inference Recommender 任務，您將能夠看到端點名稱作為結果的一部分。即使您的 Inference Recommender 任務失敗，您仍然可以按照以下步驟檢查已刪除端點的 CloudWatch 日誌：

1. 在 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 開啟 Amazon CloudWatch 主控台。

1. 從右上角的**區域**下拉式清單中，選取您在其中建立 Inference Recommender 任務的區域。

1. 在 CloudWatch 導覽窗格中，選擇**日誌**，然後選擇**日誌群組**。

1. 搜尋名為 `/aws/sagemaker/Endpoints/sm-epc-*` 的日誌群組。根據您最近的 Inference Recommender 任務選取日誌群組。

您也可以檢查 Inference Recommender CloudWatch 日誌，對任務進行故障診斷。在 `/aws/sagemaker/InferenceRecommendationsJobs` CloudWatch 日誌群組中發佈的 Inference Recommender 日誌，可提供 `<jobName>/execution` 日誌串流中任務進度的高階檢視。您可以在 `<jobName>/Endpoint/<endpointName>` 日誌串流中找到有關正在測試的每個端點組態之詳情。

**Inference Recommender 日誌串流概觀**
+ `<jobName>/execution` 包含整體任務資訊，例如針對基準測試排程的端點組態、編譯任務略過原因，以及驗證失敗原因。
+ `<jobName>/Endpoint/<endpointName>` 包含資源建立進度、測試組態、載入測試停止原因和資源清理狀態等資訊。
+ `<jobName>/CompilationJob/<compilationJobName>` 包含 Inference Recommender 所建立之編譯任務的相關資訊，例如編譯任務組態和編譯任務狀態。

**建立 Inference Recommender 錯誤訊息的警示**

Inference Recommender 會針對故障診斷時可能有幫助的錯誤輸出日誌陳述式。借助CloudWatch 日誌群組，您可在要傳送至 CloudWatch 的此份日誌資料中尋找詞彙和模式。然後，您可以根據日誌群組指標篩選條件建立 CloudWatch 警示。如需詳情，請參閱[根據日誌群組指標篩選條件建立 CloudWatch 警示](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Create_alarm_log_group_metric_filter.html)。

## 檢查基準
<a name="inference-recommender-troubleshooting-check-benchmarks"></a>

當您開始執行 Inference Recommender 任務時，Inference Recommender 會建立數個基準測試，以評估模型在不同執行個體類型上的效能。您可以使用 [ListInferenceRecommendationsJobSteps](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ListInferenceRecommendationsJobSteps.html) API 來檢視所有基準測試的詳細資料。如果您有一個失敗的基準測試，您可以看到失敗原因作為結果的一部分。

若要使用 [ListInferenceRecommendationsJobSteps](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ListInferenceRecommendationsJobSteps.html) API，請提供下列值：
+ 對於 `JobName`，提供 Inference Recommender 任務的名稱。
+ 對於 `StepType`，使用 `BENCHMARK` 傳回有關任務基準測試的詳細資訊。
+ 對於 `Status`，使用 `FAILED` 僅傳回失敗基準測試的詳細資訊。如需其他狀態類型的清單，請參閱 [ListInferenceRecommendationsJobSteps](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ListInferenceRecommendationsJobSteps.html) API 中的 `Status` 欄位。

```
# Create a low-level SageMaker service client.
import boto3
aws_region = '<region>'
sagemaker_client = boto3.client('sagemaker', region_name=aws_region) 

# Provide the job name for the SageMaker Inference Recommender job
job_name = '<job-name>'

# Filter for benchmarks
step_type = 'BENCHMARK' 

# Filter for benchmarks that have a FAILED status
status = 'FAILED'

response = sagemaker_client.list_inference_recommendations_job_steps(
    JobName = job_name,
    StepType = step_type,
    Status = status
)
```

您可以列印回應物件以檢視結果。前面的程式碼範例將回應儲存在一個名為 `response` 的變數：

```
print(response)
```