

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

# 部署用於即時推論的模型
<a name="realtime-endpoints-deploy-models"></a>

**重要**  
允許 Amazon SageMaker Studio 或 Amazon SageMaker Studio Classic 建立 Amazon SageMaker 資源的自訂 IAM 政策也必須授予許可，才能將標籤新增至這些資源。需要將標籤新增至資源的許可，因為 Studio 和 Studio Classic 會自動標記它們建立的任何資源。如果 IAM 政策允許 Studio 和 Studio Classic 建立資源，但不允許標記，則在嘗試建立資源時可能會發生 "AccessDenied" 錯誤。如需詳細資訊，請參閱[提供標記 SageMaker AI 資源的許可](security_iam_id-based-policy-examples.md#grant-tagging-permissions)。  
提供許可來建立 SageMaker 資源的 [AWS Amazon SageMaker AI 的 受管政策](security-iam-awsmanpol.md) 已包含建立這些資源時新增標籤的許可。

有數個選項可以使用 SageMaker AI 託管服務部署模型。您可以使用 SageMaker Studio 以互動方式部署模型。或者，您可以使用 AWS SDK 以程式設計方式部署模型，例如 SageMaker Python SDK 或 SDK for Python (Boto3)。您也可以使用 部署 AWS CLI。

## 開始之前
<a name="deploy-prereqs"></a>

在您部署 SageMaker AI 模型之前，請先找出並記下以下內容：
+ Amazon S3 AWS 區域 儲存貯體所在的
+ 儲存模型成品的 Amazon S3 URI 路徑
+ 適用於 SageMaker AI 的 IAM 角色
+ 自訂映像的 Docker Amazon ECR URI 登錄檔路徑，其中包含推論程式碼，或 支援和 的內建 Docker 映像架構和版本 AWS

 如需每個 中 AWS 服務 可用的清單 AWS 區域，請參閱[區域地圖和邊緣網路](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需如何建立 IAM 角色的相關資訊，請參閱[建立 IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)。

**重要**  
儲存模型成品的 Amazon S3 儲存貯體，必須位在您建立模型的相同 AWS 區域 。

## 與多個模型共享資源使用率
<a name="deployed-shared-utilization"></a>

您可以使用 Amazon SageMaker AI 將一個或多個模型部署至端點。多個模型共用端點時，也會共用在該處託管的資源，例如 ML 運算執行個體、CPU 和加速器。部署多個模型到端點的最靈活方是將每個模型定義為*推論元件*。

### 推論元件
<a name="inference-components"></a>

推論元件是 SageMaker AI 託管物件，可以用來將模型部署到端點。在推論元件設定中，您可以指定模型、端點，以及模型如何利用端點託管的資源。若要指定模型，您可以指定 SageMaker AI 模型物件，也可以直接指定模型成品和影像。

在設定中，您可以自訂所需 CPU 核心、加速器和記憶體配置給模型的方式，以最佳化資源使用率。您可以將多個推論元件部署到端點，其中每個推論元件包含一個模型，以及該模型的資源使用率需求。

部署推論元件之後，您可以在 SageMaker API 中使用 InvokeEndpoint 動作時直接調用相關聯的模型。

推論元件具有以下優點：

**彈性**  
推論元件會從端點本身分離託管模型的詳細資訊。這麼一來，您可以更靈活地控制模型的託管方式和端點提供該模型的方式。您可以在相同的基礎架構上託管多個模型，也可以根據需求從端點新增或移除模型。您可以獨立更新每個模型。

**可擴展性**  
您可以指定每個模型要託管的複本數量，也可以設定複本數量下限，以確保模型能夠載入您處理請求時所需的數量。您可以將任何推論元件複本縮減為零，讓其他複本有向上擴展的空間。

當您透過以下方式部署模型時，SageMaker AI 會將模型封裝為推論元件：
+ SageMaker Studio Classic。
+ 部署模型物件的 SageMaker Python SDK (您在其中將端點類型設為 `EndpointType.INFERENCE_COMPONENT_BASED`)。
+  適用於 Python (Boto3) 的 AWS SDK 定義您部署到端點的`InferenceComponent`物件。

## 透過 SageMaker Studio 部署模型
<a name="deploy-models-studio"></a>

請完成以下步驟，透過 SageMaker Studio 以互動方式建立和部署模型。如需進一步瞭解 Studio，請參閱 [Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio.html) 文件。如需更多多種部署案例演練，請參閱部落格[使用 Amazon SageMaker AI 輕鬆套件和部署傳統 ML 模型和 LLM – 第 2 部分](https://aws.amazon.com/blogs/machine-learning/package-and-deploy-classical-ml-and-llms-easily-with-amazon-sagemaker-part-2-interactive-user-experiences-in-sagemaker-studio/)。

### 準備您的成品和許可
<a name="studio-prereqs"></a>

在 SageMaker Studio 中建立模型之前，請先完成本區段。

您可以透過兩種方式，在 Studio 中納入成品和建立模型：

1. 您可以先準備好預先封裝的 `tar.gz` 封存，其中應包含模型成品、任何自訂推論程式碼，以及 `requirements.txt` 檔案中列出的任何相依項目。

1. SageMaker AI 可以幫您封裝成品。您只需要在 `requirements.txt` 檔案中納入原始模型成品和任何相依項目，SageMaker AI 可以為您提供預設推論程式碼；或者您可以使用自己的自訂推論程式碼覆寫預設程式碼。針對這種方式，SageMaker AI 支援下列架構：PyTorch、XGBoost。

除了攜帶您的模型、您的 AWS Identity and Access Management (IAM) 角色和 Docker 容器 （或 SageMaker AI 具有預先建置容器的所需架構和版本），您還必須授予透過 SageMaker AI Studio 建立和部署模型的許可。

您應該將 [AmazonSageMakerFullAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonSageMakerFullAccess.html) 政策連接到您的 IAM 角色，以便您存取 SageMaker AI 和其他相關服務。若要查看 Studio 中執行個體類型的價格，您還必須連接 [AWS PriceListServiceFullAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AWSPriceListServiceFullAccess.html) 政策；或者如果您不想連接整個政策 (具體來說是 `pricing:GetProducts` 動作)。

如果您在建立模型時選擇上傳模型成品或上傳範例承載檔案以取得推論建議，則您必須建立 Amazon S3 儲存貯體。儲存貯體名稱的字首必須是 `SageMaker AI`。或者也可以是 SageMaker AI 的替代大寫：`Sagemaker` 或 `sagemaker`。

建議您使用儲存貯體命名慣例 `sagemaker-{Region}-{accountID}`。此儲存貯體會用來存放您上傳的成品。

建立儲存貯體之後，請將下列 CORS (跨來源資源共用) 政策連接至儲存貯體：

```
[
    {
        "AllowedHeaders": ["*"],
        "ExposeHeaders": ["Etag"],
        "AllowedMethods": ["PUT", "POST"],
        "AllowedOrigins": ['https://*.sagemaker.aws'],
    }
]
```

您可以透過以下任一方式，將 CORS 政策連接至 Amazon S3 儲存貯體：
+ 透過 Amazon S3 主控台的[編輯跨來源資源共用 (CORS)](https://s3.console.aws.amazon.com/s3/bucket/bucket-name/property/cors/edit) 頁面
+ 使用 Amazon S3 API [PutBucketCors](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketCors.html)
+ 使用 put-bucket-cors AWS CLI 命令：

  ```
  aws s3api put-bucket-cors --bucket="..." --cors-configuration="..."
  ```

### 建立可部署模型
<a name="studio-create-model"></a>

在此步驟中，您可以提供成品和其他規格，例如所需的容器和架構、任何自訂推論程式碼和網路設定，在 SageMaker AI 中建立可部署的模型版本。

請執行以下動作，在 SageMaker Studio 中建立可部署模型：

1. 開啟您的 SageMaker Studio 應用程式。

1. 在左側導覽窗格中選擇 **Models (模型)**。

1. 選擇**可部署模型**索引標籤。

1. 在**可部署模型**頁面上，選擇**建立**。

1. 在**建立可部署模型**頁面上的**模型名稱**欄位中，輸入模型的名稱。

在**建立可部署模型**頁面上還有一些需要填寫的區段。

**容器定義**區段如下螢幕擷取畫面：

![\[在 Studio 中建立模型的容器定義區段螢幕擷取畫面。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/inference/studio-container-definition.png)


**請在**容器定義**區段中，執行下列動作：**

1. 在**容器類型**中，如果您要使用 SageMaker AI 受管容器，請選取**預先建置的容器**，如果您有自己的容器，請選取**使用自有容器**。

1. 如果您選取**預先建置的容器**，請選取您要使用的**容器架構**、**架構版本**和**硬體類型**。

1. 如果您選取**使用自有容器**，請輸入**容器影像的 ECR 路徑**的 Amazon ECR 路徑。

接著填寫**成品**區段，請參考如下螢幕擷取畫面：

![\[在 Studio 中建立模型的成品區段螢幕擷取畫面。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/inference/studio-artifacts-section.png)


**請在**成品**區段中，執行下列動作：**

1. 如果您使用 SageMaker AI 所支援的架構 (PyTorch 或 XGBoost) 來封裝模型成品，則您可以在**成品**選擇**上傳成品**選項。您可以透過這個選項直接指定原始模型成品、您擁有的任何自訂推論程式碼，以及您的 requirements.txt 檔案，而 SageMaker AI 會幫您封裝封存。請執行下列操作：

   1. 在**成品**選取**上傳成品**以繼續提供您的檔案。如果您已經有包含模型檔案、推論程式碼和 `requirements.txt` 檔案的 `tar.gz` 封存，請選取**預先封裝成品的輸入 S3 URI**。

   1. 如果您選擇上傳成品，則請在 **S3 儲存貯體**輸入您希望 SageMaker AI 在封裝成品之後存放成品的儲存貯體 Amazon S3 路徑。然後，請完成下列步驟。

   1. 在**上傳模型成品**上傳您的模型檔案。

   1. 針對**推論程式碼**，如果您要使用 SageMaker AI 提供的預設程式碼來提供推論，請選取**使用預設推論程式碼**。否則請選取**上傳自訂推論程式碼**，使用您自有的推論程式碼。

   1. 針對**上傳 requirements.txt**，請上傳文字檔案，其中列出您想在執行時期安裝的任何相依項目。

1. 如果您未使用 SageMaker AI 支援的架構來封裝模型成品，Studio 會顯示**預先封裝成品**選項，您必須提供已封裝為 `tar.gz` 封存的所有成品。請執行下列操作：

   1. 針對**預先封裝的成品**，如果您的 `tar.gz` 封存已上傳至 Amazon S3，請選取**預先封裝模型成品的輸入 S3 URI**。如果您想將封存直接上傳至 SageMaker AI，請選取**上傳預先封裝的模型成品**。

   1. 如果您選取**預先封裝模型成品的輸入 S3 URI**，請輸入 **S3 URI** 的封存 Amazon S3 路徑。否則請從本機電腦選取並上傳封存。

下一部分是**安全性**，其螢幕擷取畫面如下：

![\[在 Studio 中建立模型的安全性區段螢幕擷取畫面。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/inference/studio-security-section.png)


**請針對**安全性**區段執行以下動作：**

1. 針對 **IAM 角色**輸入 IAM 角色的 ARN。

1. (選用) 針對**虛擬私有雲端 (VPC)**，您可以選取一個 Amazon VPC 來存放模型組態和成品。

1. (選用) 如果您想限制容器的網際網路存取，請開啟**網路隔離**。

最後，您可以填寫**進階選項**區段，其螢幕擷取畫面如下：

![\[在 Studio 中建立模型的進階選項區段螢幕擷取畫面。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/inference/studio-advanced-options.png)


**(選用) 請在**進階選項**區段中，執行下列動作：**

1. 如果您想在建立模型之後在模型上執行 Amazon SageMaker Inference Recommender 任務，請開啟**自訂執行個體建議**。推論建議程式是一項功能，可以為您提供最佳化推論效能和成本的建議執行個體類型。您可以在準備部署模型時檢視這些執行個體建議。

1. 在**新增環境變數**中，輸入容器的環境變數做為鍵值組。

1. 在**標籤**中，輸入任何標籤做為鍵值組。

1. 完成模型和容器組態後，選擇**建立可部署模型**。

現在，您在 SageMaker Studio 中應該已經擁有準備好進行部署的模型。

### 部署模型
<a name="studio-deploy"></a>

最後，請將您在上一個步驟中設定的模型部署到 HTTPS 端點。您可以將一個或多個模型部署到端點。

**模型和端點相容性**  
模型和端點必須具有以下相同設定值，才能將模型部署至端點：  
IAM 角色
Amazon VPC，包括其子網路和安全群組
網路隔離 (啟用或停用)
Studio 會透過以下方式，防止您將模型部署至不相容的端點：  
如果您嘗試將模型部署到新端點，SageMaker AI 會使用相容的初始設定來設定端點。如果您因變更這些設定而導致不相容，Studio 會顯示警示並防止部署。
如果您嘗試部署到現有端點且該端點不相容，Studio 會顯示警示並防止部署。
如果您嘗試將多個模型新增至部署，Studio 會防止您部署彼此不相容的模型。
當 Studio 顯示模型和端點不相容的警示時，您可以選擇在警示中**檢視詳細資訊**，查看哪些設定不相容。

其中一種部署模型的方法是在 Studio 中執行下列動作：

1. 開啟您的 SageMaker Studio 應用程式。

1. 在左側導覽窗格中選擇 **Models (模型)**。

1. 在**模型**頁面上，從 SageMaker AI 模型清單中選取一個或多個模型。

1. 選擇**部署**。

1. 針對**端點名稱**，開啟下拉式功能表。您可以選取現有端點，也可以建立要部署模型的新端點。

1. 針對**執行個體類型**，選取您要用於端點的執行個體類型。如果您先前已經為模型執行推論建議程式任務，您的建議執行個體類型會顯示在**建議**標題下的清單中。否則您會看到可能適合您模型的**潛在執行個體**。
**JumpStart 的執行個體類型相容性**  
如果您要部署 JumpStart 模型，Studio 只會顯示模型所支援的執行個體類型。

1. 針對**初始執行個體數量**，輸入您要為端點佈建的執行個體初始數量。

1. 針對**執行個體數量上限**，指定端點擴展時可佈建的執行個體數量上限，以因應流量提升。

1. 如果您要部署的模型是從模型中樞最常使用的 JumpStart LLM 之一，則執行個體類型和執行個體數量欄位後會顯示**替代組態**選項。

   對於最熱門的 JumpStart LLM， AWS 具有預先標記的執行個體類型，可最佳化成本或效能。 LLMs 這份資料可以協助您決定要用於部署 LLM 的執行個體類型。選擇**替代組態**以開啟包含預先標記資料的對話方塊。該面板外觀如下螢幕擷取畫面：  
![\[替代組態方塊的螢幕擷取畫面\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/inference/studio-jumpstart-alternate-configurations.png)

   請在**替代組態**方塊中，執行下列動作：

   1. 選取執行個體類型。您可以選擇**每小時成本**或**最佳效能**，查看最佳化指定模型的成本或效能的執行個體類型。您也可以選擇**其他支援的執行個體**，查看與 JumpStart 模型相容的其他執行個體類型。請注意，在此處選取的執行個體類型會覆寫步驟 6 中指定的任何先前執行個體。

   1. (選用) 開啟**自訂所選組態**，以指定**總記號數量上限** (記號數量上限，即輸入記號和模型產生的輸出總和)、**輸入記號長度上限** (每個請求輸入的記號數量上限) 和**並行請求上限** (模型一次可處理的請求數量上限)。

   1. 選擇**選取**，確認您的執行個體類型和組態設定。

1. **模型**欄位應該已填入您要部署的模型名稱。您可以選擇**新增模型**，將更多模型新增至部署。請針對您新增的每個模型，填寫下列欄位：

   1. 針對 **CPU 核心數量**，輸入您要專用於模型使用的 CPU 核心。

   1. 針對**複本數量下限**，輸入您在任何時間要在端點上託管的最少模型複本數量。

   1. 針對 **CPU 記憶體下限 (MB)**，輸入模型所需的記憶體數量下限 (以 MB 為單位)。

   1. 針對 **CPU 記憶體上限 (MB)**，輸入您允許模型使用的記憶體數量上限 (以 MB 為單位)。

1. (選用) 請在**進階選項**中，執行下列動作：

   1. 針對 **IAM 角色**，使用預設 SageMaker AI IAM 執行角色，或指定具所需許可的自有角色。請注意，此 IAM 角色必須與您在建立可部署模型時指定的角色相同。

   1. 針對**虛擬私有雲端 (VPC)**，您可以指定要負責託管端點的 VPC。

   1. 針對**加密 KMS 金鑰**，選取 AWS KMS 金鑰來加密連接至託管端點之 ML 運算執行個體的儲存磁碟區上的資料。

   1. 開啟**網路隔離**，限制容器的網際網路存取。

   1. 針對**逾時組態**，輸入**模型資料下載逾時 (秒)** 和**容器啟動運作狀態檢查逾時 (秒)** 欄位的值。這些值會決定 SageMaker AI 分別可以將模型下載至容器和啟動容器的時間上限。

   1. 在**標籤**中，輸入任何標籤做為鍵值組。
**注意**  
SageMaker AI 會使用與您部署的模型相容的初始值來設定 IAM 角色、VPC 和網路隔離設定。如果您因變更這些設定而導致不相容，Studio 會顯示警示並防止部署。

設定選項後，頁面應該如下螢幕擷取畫面。

![\[Studio 中部署模型頁面的螢幕擷取畫面。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/inference/studio-deploy-realtime-model-2.png)


設定部署後，選擇**部署**以建立端點並部署模型。

## 使用 Python SDK 部署模型
<a name="deploy-models-python"></a>

您可以透過 SageMaker Python SDK，以兩種方式建置模型。第一個方式是從 `Model` 或 `ModelBuilder` 類別建立模型物件。如果您使用 `Model` 類別建立 `Model` 物件，您需要指定模型套件或推論程式碼 (取決於您的模型伺服器)、處理用戶端和伺服器之間資料序列化和還原序列化的指令碼，以及要上傳到 Amazon S3 供使用的任何相依項目。第二個方式是使用提供模型成品或推論程式碼的 `ModelBuilder`。`ModelBuilder` 會自動擷取您的相依項目、推論所需序列化和還原序列化函數，並封裝您的相依項目以建立 `Model` 物件。如需 `ModelBuilder` 的相關資訊，請參閱 [使用 ModelBuilder 在 Amazon SageMaker AI 建立模型](how-it-works-modelbuilder-creation.md)。

下一個部分將說明兩種建立模型和部署模型物件的方法。

### 設定
<a name="python-setup"></a>

以下是準備模型部署程序的範例。過程中會匯入必要的程式庫，並定義尋找模型成品的 S3 URL。

------
#### [ SageMaker Python SDK ]

**Example 匯入陳述式**  
以下範例會從 SageMaker Python SDK、SDK for Python (Boto3) 和 Python 標準程式庫匯入模組。這些模組能有效協助您部署模型，而這些模型也會用於後續的其他範例。  

```
import boto3
from datetime import datetime
from sagemaker.compute_resource_requirements.resource_requirements import ResourceRequirements
from sagemaker.predictor import Predictor
from sagemaker.enums import EndpointType
from sagemaker.model import Model
from sagemaker.session import Session
```

------
#### [ boto3 inference components ]

**Example 匯入陳述式**  
以下範例會從 SDK for Python (Boto3) 和 Python 標準程式庫匯入模組。這些模組能有效協助您部署模型，而這些模型也會用於後續的其他範例。  

```
import boto3
import botocore
import sys
import time
```

------
#### [ boto3 models (without inference components) ]

**Example 匯入陳述式**  
以下範例會從 SDK for Python (Boto3) 和 Python 標準程式庫匯入模組。這些模組能有效協助您部署模型，而這些模型也會用於後續的其他範例。  

```
import boto3
import botocore
import datetime
from time import gmtime, strftime
```

------

**Example 模型成品 URL**  
下列程式碼會建置範例 Amazon S3 URL。URL 會在 Amazon S3 儲存貯體中找到預先訓練模型的模型成品。  

```
# Create a variable w/ the model S3 URL

# The name of your S3 bucket:
s3_bucket = "amzn-s3-demo-bucket"
# The directory within your S3 bucket your model is stored in:
bucket_prefix = "sagemaker/model/path"
# The file name of your model artifact:
model_filename = "my-model-artifact.tar.gz"
# Relative S3 path:
model_s3_key = f"{bucket_prefix}/"+model_filename
# Combine bucket name, model file name, and relate S3 path to create S3 model URL:
model_url = f"s3://{s3_bucket}/{model_s3_key}"
```
完整的 Amazon S3 URL 會存放在變數 `model_url` 中，該變數會用於以下範例。

### 概觀
<a name="python-overview"></a>

您可以透過 SageMaker Python SDK 或 SDK for Python (Boto3)，以多種方式部署模型。以下各部分將摘要說明各種方式的步驟。以下範例將示範這些步驟。

------
#### [ SageMaker Python SDK ]

您可以透過 SageMaker Python SDK，以下列任一方式建置模型：
+ **從 `Model` 類別建立模型物件** – 您必須指定模型套件或推論程式碼 (取決於您的模型伺服器)、處理用戶端和伺服器之間資料序列化和還原序列化的指令碼，以及要上傳到 Amazon S3 供使用的任何相依項目。
+ **從 `ModelBuilder` 類別建立模型物件** – 請提供模型成品或推論程式碼，`ModelBuilder` 會自動擷取相依項目、推論所需序列化和還原序列化函數，並封裝您的相依項目以建立 `Model` 物件。

  如需 `ModelBuilder` 的相關資訊，請參閱 [使用 ModelBuilder 在 Amazon SageMaker AI 建立模型](how-it-works-modelbuilder-creation.md)。您也可以參閱部落格[使用 SageMaker AI 輕鬆套件和部署傳統 ML 模型和 LLM – 第 1 部分](https://aws.amazon.com/blogs/machine-learning/package-and-deploy-classical-ml-and-llms-easily-with-amazon-sagemaker-part-1-pysdk-improvements/)，瞭解更多資訊。

以下範例將說明兩種建立模型和部署模型物件的方法。若要使用這些方式部署模型，請完成下列步驟：

1. 使用 `ResourceRequirements` 物件定義要配置給模型的端點資源。

1. 從 `Model` 或 `ModelBuilder` 類別建立模型物件。`ResourceRequirements` 物件是在模型設定中指定的。

1. 使用 `Model` 物件的 `deploy` 方法，將模型部署至端點。

------
#### [ boto3 inference components ]

以下範例說明如何將模型指派給推論元件，然後將推論元件部署至端點。若要使用這個方式部署模型，請完成下列步驟：

1. (選用) 使用 [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_model.html](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_model.html) 方式建立 SageMaker AI 模型物件。

1. 建立端點組態物件來設定端點。若要建立一個端點，請使用 [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_endpoint_config.html#create-endpoint-config](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_endpoint_config.html#create-endpoint-config) 方式。

1. 使用 [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_endpoint.html](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_endpoint.html) 方式建立端點，並在請求中提供您建立的端點組態。

1. 使用 `create_inference_component` 方式建立推論元件。請在設定中執行下列任一動作來指定模型：
   + 指定 SageMaker AI 模型物件
   + 指定模型影像 URI 和 S3 URL

   您也可以將端點資源配置給模型。您可以建立推論元件，以將模型部署到端點。您可以建立多個推論元件，將多個模型部署到端點 (每個模型一個推論元件)。

------
#### [ boto3 models (without inference components) ]

以下範例說明如何建立模型物件，然後將模型部署到端點。若要使用這個方式部署模型，請完成下列步驟：

1. 使用 [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_model.html](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_model.html) 方式建立 SageMaker AI 模型。

1. 建立端點組態物件來設定端點。若要建立一個端點，請使用 [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_endpoint_config.html#create-endpoint-config](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_endpoint_config.html#create-endpoint-config) 方式。請在端點組態中，將模型物件指派給生產變體。

1. 使用 [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_endpoint.html](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_endpoint.html) 方式建立端點。在請求中提供您建立的端點組態。

   建立端點時，SageMaker AI 會佈建端點資源，並將模型部署到端點。

------

### 設定
<a name="python-configure"></a>

以下範例會設定將模型部署至端點所需的資源。

------
#### [ SageMaker Python SDK ]

以下範例會指派端點資源給具有 `ResourceRequirements` 物件的模型。這些資源包括 CPU 核心、加速器和記憶體。然後，範例會從 `Model` 類別建立模型物件。或者，您可以執行個體化 [ModelBuilder](https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-modelbuilder-creation.html) 類別並執行 `build`，以建立模型物件；範例也會說明此方式。`ModelBuilder` 會提供模型封裝的統一界面，且會在此執行個體中準備大型模型部署的模型。此範例會利用 `ModelBuilder` 來建構 Hugging Face 模型。(您也可以傳遞 JumpStart 模型)。建置模型後，您可以在模型物件中指定資源需求。請在下一個步驟中使用此物件將模型部署至端點。

```
resources = ResourceRequirements(
    requests = {
        "num_cpus": 2,  # Number of CPU cores required:
        "num_accelerators": 1, # Number of accelerators required
        "memory": 8192,  # Minimum memory required in Mb (required)
        "copies": 1,
    },
    limits = {},
)

now = datetime.now()
dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
model_name = "my-sm-model"+dt_string

# build your model with Model class
model = Model(
    name = "model-name",
    image_uri = "image-uri",
    model_data = model_url,
    role = "arn:aws:iam::111122223333:role/service-role/role-name",
    resources = resources,
    predictor_cls = Predictor,
)
                        
# Alternate mechanism using ModelBuilder
# uncomment the following section to use ModelBuilder
/*
model_builder = ModelBuilder(
    model="<HuggingFace-ID>", # like "meta-llama/Llama-2-7b-hf"
    schema_builder=SchemaBuilder(sample_input,sample_output),
    env_vars={ "HUGGING_FACE_HUB_TOKEN": "<HuggingFace_token>}" }
)

# build your Model object
model = model_builder.build()

# create a unique name from string 'mb-inference-component'
model.model_name = unique_name_from_base("mb-inference-component")

# assign resources to your model
model.resources = resources
*/
```

------
#### [ boto3 inference components ]

以下範例會以 `create_endpoint_config` 方式設定端點。您可以在建立端點時將此組態指派給端點。請在組態中定義一個或多個生產變體。您可以針對每個變體選擇您希望 Amazon SageMaker AI 佈建的執行個體類型，並啟用受管執行個體擴展。

```
endpoint_config_name = "endpoint-config-name"
endpoint_name = "endpoint-name"
inference_component_name = "inference-component-name"
variant_name = "variant-name"

sagemaker_client.create_endpoint_config(
    EndpointConfigName = endpoint_config_name,
    ExecutionRoleArn = "arn:aws:iam::111122223333:role/service-role/role-name",
    ProductionVariants = [
        {
            "VariantName": variant_name,
            "InstanceType": "ml.p4d.24xlarge",
            "InitialInstanceCount": 1,
            "ManagedInstanceScaling": {
                "Status": "ENABLED",
                "MinInstanceCount": 1,
                "MaxInstanceCount": 2,
            },
        }
    ],
)
```

------
#### [ boto3 models (without inference components) ]

**Example 模型定義**  
以下範例使用 適用於 Python (Boto3) 的 AWS SDK中的 `create_model` 方式來定義 SageMaker AI 模型。  

```
model_name = "model-name"

create_model_response = sagemaker_client.create_model(
    ModelName = model_name,
    ExecutionRoleArn = "arn:aws:iam::111122223333:role/service-role/role-name",
    PrimaryContainer = {
        "Image": "image-uri",
        "ModelDataUrl": model_url,
    }
)
```
此範例會指定下列項目：  
+ `ModelName`：模型的名稱 (在這個範例中，它的儲存名稱是名為 `model_name` 的字串變數)。
+ `ExecutionRoleArn`：Amazon SageMaker AI 可扮演之 IAM 角色的 Amazon Resource Name (ARN)；該角色可存取模型成品和 Docker 映像檔，然後在機器學習 (ML) 運算執行個體上部署，或是用於批次轉換工作。
+ `PrimaryContainer`：主要 Docker 映像檔的位置，包含推論程式碼、關聯成品，以及推論程式碼在部署模型以進行預測時使用的自訂環境地圖。

**Example 端點組態**  
以下範例會以 `create_endpoint_config` 方式設定端點。Amazon SageMaker AI 會使用此組態部署模型。在組態中，您可以識別一個或多個使用 `create_model` 方式建立的模型，以部署您希望 Amazon SageMaker AI 佈建的資源。  

```
endpoint_config_response = sagemaker_client.create_endpoint_config(
    EndpointConfigName = "endpoint-config-name", 
    # List of ProductionVariant objects, one for each model that you want to host at this endpoint:
    ProductionVariants = [
        {
            "VariantName": "variant-name", # The name of the production variant.
            "ModelName": model_name, 
            "InstanceType": "ml.p4d.24xlarge",
            "InitialInstanceCount": 1 # Number of instances to launch initially.
        }
    ]
)
```
此範例會指定 `ProductionVariants` 欄位的下列金鑰：  
+ `VariantName`：生產變體的名稱。
+ `ModelName`：您要託管的模型名稱。這是您在建立模型時指定的名稱。
+ `InstanceType`：運算執行個體類型。如需支援的運算執行個體類型，以及每個執行個體類型的定價清單，請參閱 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProductionVariant.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProductionVariant.html) 和 [SageMaker AI 定價](https://aws.amazon.com/sagemaker/pricing/)中的 `InstanceType` 欄位。

------

### 部署
<a name="python-deploy"></a>

下列範例會將模型部署至端點。

------
#### [ SageMaker Python SDK ]

下列範例使用模型物件的 `deploy` 方式，將模型部署到即時的 HTTPS 端點。如果您指定了模型建立和部署的 `resources` 引數值，則會優先採用您為部署指定的資源。

```
predictor = model.deploy(
    initial_instance_count = 1,
    instance_type = "ml.p4d.24xlarge", 
    endpoint_type = EndpointType.INFERENCE_COMPONENT_BASED,
    resources = resources,
)
```

針對 `instance_type` 欄位，範例會指定模型的 Amazon EC2 執行個體類型名稱。針對 `initial_instance_count` 欄位，則會指定要在其中執行端點的執行個體初始數量。

下列程式碼範例說明另一個情況：您將模型部署到端點，然後將另一個模型部署到同一個端點。在這個情況下，您必須向兩個模型的 `deploy` 方式提供相同的端點名稱。

```
# Deploy the model to inference-component-based endpoint
falcon_predictor = falcon_model.deploy(
    initial_instance_count = 1,
    instance_type = "ml.p4d.24xlarge", 
    endpoint_type = EndpointType.INFERENCE_COMPONENT_BASED,
    endpoint_name = "<endpoint_name>"
    resources = resources,
)

# Deploy another model to the same inference-component-based endpoint
llama2_predictor = llama2_model.deploy( # resources already set inside llama2_model
    endpoint_type = EndpointType.INFERENCE_COMPONENT_BASED,
    endpoint_name = "<endpoint_name>"  # same endpoint name as for falcon model
)
```

------
#### [ boto3 inference components ]

有端點組態之後，請使用 [create\$1endpoint](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_endpoint.html) 方式來建立端點。端點名稱在帳戶中 AWS 區域 AWS 的 內必須是唯一的。

以下範例會使用請求中指定的端點組態建立端點。Amazon SageMaker AI 會使用端點來佈建資源。

```
sagemaker_client.create_endpoint(
    EndpointName = endpoint_name,
    EndpointConfigName = endpoint_config_name,
)
```

建立端點之後，您可以建立推論元件來部署一個或多個模型。下列範例使用 `create_inference_component` 方式建立一個模型。

```
sagemaker_client.create_inference_component(
    InferenceComponentName = inference_component_name,
    EndpointName = endpoint_name,
    VariantName = variant_name,
    Specification = {
        "Container": {
            "Image": "image-uri",
            "ArtifactUrl": model_url,
        },
        "ComputeResourceRequirements": {
            "NumberOfCpuCoresRequired": 1, 
            "MinMemoryRequiredInMb": 1024
        }
    },
    RuntimeConfig = {"CopyCount": 2}
)
```

------
#### [ boto3 models (without inference components) ]

**Example deployment**  

將端點組態提供給 SageMaker AI。此服務便會啟動組態所指定的機器學習 (ML) 運算執行個體，接著進行模型部署。

有模型和端點組態之後，請使用 [create\$1endpoint](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_endpoint.html) 方式來建立端點。端點名稱在帳戶中 AWS 區域 AWS 的 內必須是唯一的。

以下範例會使用請求中指定的端點組態建立端點。Amazon SageMaker AI 使用端點來佈建資源和部署模型。

```
create_endpoint_response = sagemaker_client.create_endpoint(
    # The endpoint name must be unique within an AWS Region in your AWS account:
    EndpointName = "endpoint-name"
    # The name of the endpoint configuration associated with this endpoint:
    EndpointConfigName = "endpoint-config-name")
```

------

## 使用 部署模型 AWS CLI
<a name="deploy-models-cli"></a>

您可以使用 將模型部署至端點 AWS CLI。

### 概觀
<a name="deploy-models-cli-overview"></a>

當您使用 部署模型時 AWS CLI，您可以使用或不使用推論元件來部署模型。以下各部分將摘要說明用來執行兩種方式的命令。以下範例將示範這些命令。

------
#### [ With inference components ]

若要使用推論元件來部署模型，請執行下列動作：

1. (選用) 使用 [https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-model.html](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-model.html) 命令建立模型。

1. 建立端點組態來設定端點。若要建立一個端點，請執行 [https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint-config.html](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint-config.html) 命令。

1. 使用 [https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint.html](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint.html) 命令建立端點。請在命令內文中指定您建立的端點組態。

1. 使用 `create-inference-component` 命令建立推論元件。請在設定中執行下列任一動作來指定模型：
   + 指定 SageMaker AI 模型物件
   + 指定模型影像 URI 和 S3 URL

   您也可以將端點資源配置給模型。您可以建立推論元件，以將模型部署到端點。您可以建立多個推論元件，將多個模型部署到端點 (每個模型一個推論元件)。

------
#### [ Without inference components ]

若要在不使用推論元件的情況下部署模型，請執行下列動作：

1. 使用 [https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-model.html](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-model.html) 命令建立 SageMaker AI 模型。

1. 建立端點組態物件來設定端點。若要建立一個端點，請使用 [https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint-config.html](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint-config.html) 命令。請在端點組態中，將模型物件指派給生產變體。

1. 使用 [https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint.html](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint.html) 命令建立端點。請在命令內文中指定您建立的端點組態。

   建立端點時，SageMaker AI 會佈建端點資源，並將模型部署到端點。

------

### 設定
<a name="cli-configure-endpoint"></a>

以下範例會設定將模型部署至端點所需的資源。

------
#### [ With inference components ]

**Example create-endpoint-config 命令**  
下列範例使用 [create-endpoint-config](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint-config.html) 命令來建立端點組態。  

```
aws sagemaker create-endpoint-config \
--endpoint-config-name endpoint-config-name \
--execution-role-arn arn:aws:iam::111122223333:role/service-role/role-name\
--production-variants file://production-variants.json
```
在此範例中，檔案 `production-variants.json` 使用以下 JSON 定義生產變體：  

```
[
    {
        "VariantName": "variant-name",
        "ModelName": "model-name",
        "InstanceType": "ml.p4d.24xlarge",
        "InitialInstanceCount": 1
    }
]
```
如果命令成功， 會以您建立之資源的 ARN AWS CLI 回應。  

```
{
    "EndpointConfigArn": "arn:aws:sagemaker:us-west-2:111122223333:endpoint-config/endpoint-config-name"
}
```

------
#### [ Without inference components ]

**Example create-model 命令**  
下列範例使用 [create-model](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-model.html) 命令建立模型。  

```
aws sagemaker create-model \
--model-name model-name \
--execution-role-arn arn:aws:iam::111122223333:role/service-role/role-name \
--primary-container "{ \"Image\": \"image-uri\", \"ModelDataUrl\": \"model-s3-url\"}"
```
如果命令成功， 會以您建立之資源的 ARN AWS CLI 回應。  

```
{
    "ModelArn": "arn:aws:sagemaker:us-west-2:111122223333:model/model-name"
}
```

**Example create-endpoint-config 命令**  
下列範例使用 [create-endpoint-config](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint-config.html) 命令來建立端點組態。  

```
aws sagemaker create-endpoint-config \
--endpoint-config-name endpoint-config-name \
--production-variants file://production-variants.json
```
在此範例中，檔案 `production-variants.json` 使用以下 JSON 定義生產變體：  

```
[
    {
        "VariantName": "variant-name",
        "ModelName": "model-name",
        "InstanceType": "ml.p4d.24xlarge",
        "InitialInstanceCount": 1
    }
]
```
如果命令成功， 會以您建立之資源的 ARN AWS CLI 回應。  

```
{
    "EndpointConfigArn": "arn:aws:sagemaker:us-west-2:111122223333:endpoint-config/endpoint-config-name"
}
```

------

### 部署
<a name="cli-deploy"></a>

下列範例會將模型部署至端點。

------
#### [ With inference components ]

**Example create-endpoint 命令**  
下列範例使用 [create-endpoint](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint.html) 命令來建立端點。  

```
aws sagemaker create-endpoint \
--endpoint-name endpoint-name \
--endpoint-config-name endpoint-config-name
```
如果命令成功， 會以您建立之資源的 ARN AWS CLI 回應。  

```
{
    "EndpointArn": "arn:aws:sagemaker:us-west-2:111122223333:endpoint/endpoint-name"
}
```

**Example create-inference-component 命令**  
下列範例使用 create-inference-component 命令建立推論元件。  

```
aws sagemaker create-inference-component \
--inference-component-name inference-component-name \
--endpoint-name endpoint-name \
--variant-name variant-name \
--specification file://specification.json \
--runtime-config "{\"CopyCount\": 2}"
```
在此範例中，`specification.json` 檔案使用以下 JSON 定義容器和運算資源：  

```
{
    "Container": {
        "Image": "image-uri",
        "ArtifactUrl": "model-s3-url"
    },
    "ComputeResourceRequirements": {
        "NumberOfCpuCoresRequired": 1,
        "MinMemoryRequiredInMb": 1024
    }
}
```
如果命令成功， 會以您建立之資源的 ARN AWS CLI 回應。  

```
{
    "InferenceComponentArn": "arn:aws:sagemaker:us-west-2:111122223333:inference-component/inference-component-name"
}
```

------
#### [ Without inference components ]

**Example create-endpoint 命令**  
下列範例使用 [create-endpoint](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint.html) 命令來建立端點。  

```
aws sagemaker create-endpoint \
--endpoint-name endpoint-name \
--endpoint-config-name endpoint-config-name
```
如果命令成功， 會以您建立之資源的 ARN AWS CLI 回應。  

```
{
    "EndpointArn": "arn:aws:sagemaker:us-west-2:111122223333:endpoint/endpoint-name"
}
```

------