將模型部署為在線端點

適用於Python SDK azure-ai-ml v2 (目前)

瞭解如何使用 Azure 機器學習 Python SDK v2 將模型部署至在線端點。

在本教學課程中,您會部署和使用模型,以預測客戶在信用卡付款上預設的可能性。

您採取的步驟如下:

  • 註冊您的模型
  • 建立端點和第一個部署
  • 部署試用版執行
  • 手動將測試數據傳送至部署
  • 取得部署的詳細數據
  • 建立第二個部署
  • 手動調整第二個部署
  • 更新這兩個部署之間的生產流量配置
  • 取得第二個部署的詳細數據
  • 推出新的部署並刪除第一個部署

這段影片示範如何開始 Azure Machine Learning 工作室,讓您可以遵循教學課程中的步驟。 影片示範如何建立筆記本、建立計算實例,以及複製筆記本。 下列各節也會說明這些步驟。

必要條件

  1. 若要使用 Azure 機器學習,您必須先有工作區。 如果您沒有資源,請完成 建立資源,才能開始 建立工作區,並深入瞭解如何使用它。

  2. 登入 Studio如果工作區尚未開啟,請選取您的工作區。

  3. 在您的工作區開啟或建立筆記本:

  4. 檢視您的 VM 配額,並確定您有足夠的配額可供建立在線部署。 在本教學課程中,您至少需要 8 個核心STANDARD_DS3_v2和 12 個核心。STANDARD_F4s_v2 若要檢視 VM 配額使用量和要求增加配額,請參閱 管理資源配額

設定核心

  1. 在開啟筆記本上方的頂端列上,如果您還沒有計算實例,請建立計算實例。

    Screenshot shows how to create a compute instance.

  2. 如果計算實例已停止,請選取 [ 啟動計算 ],並等候其執行。

    Screenshot shows how to start compute if it is stopped.

  3. 請確定位於右上方的核心是 Python 3.10 - SDK v2。 如果沒有,請使用下拉式清單來選取此核心。

    Screenshot shows how to set the kernel.

  4. 如果您看到橫幅指出您需要進行驗證,請選取 [ 驗證]。

重要

本教學課程的其餘部分包含教學課程筆記本的單元格。 將其複製/貼到新的筆記本中,或如果您複製筆記本,請立即切換至筆記本。

注意

  • 無伺服器 Spark 計算預設未 Python 3.10 - SDK v2 安裝。 建議您先建立計算實例並加以選取,再繼續進行教學課程。

建立工作區的句柄

在深入探討程序代碼之前,您需要參考工作區的方法。 建立 ml_client 工作區的句柄,並使用 ml_client 來管理資源和作業。

在下一個數據格中,輸入您的訂用帳戶標識碼、資源組名和工作區名稱。 若要尋找這些值:

  1. 在右上方的 Azure Machine Learning 工作室工具列中,選取您的工作區名稱。
  2. 將工作區、資源群組和訂用帳戶標識碼的值複製到程式代碼中。
  3. 您需要複製一個值、關閉區域並貼上,然後返回下一個值。
from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential

# authenticate
credential = DefaultAzureCredential()

# Get a handle to the workspace
ml_client = MLClient(
    credential=credential,
    subscription_id="<SUBSCRIPTION_ID>",
    resource_group_name="<RESOURCE_GROUP>",
    workspace_name="<AML_WORKSPACE_NAME>",
)

注意

建立 MLClient 不會連線到工作區。 用戶端初始化是延遲的,並等候它第一次進行呼叫(這發生在下一個程式代碼儲存格中)。

註冊模型

如果您已完成先前的定型教學課程「 定型模型」,您已註冊 MLflow 模型作為定型腳本的一部分,並可跳至下一節。

如果您未完成定型教學課程,則需要註冊模型。 在部署之前註冊模型是建議的最佳做法。

下列程式代碼會 path 指定要內嵌上傳檔案的位置。 如果您 複製 tutorials 資料夾,請依目前方式執行下列程式代碼。 否則, 請下載模型的檔案和元數據,以部署 和解壓縮檔案。 更新本機計算機上解壓縮檔案位置的路徑。

SDK 會自動上傳檔案並註冊模型。

如需將模型註冊為資產的詳細資訊,請參閱使用 SDK 在 Machine Learning 中將模型註冊為資產

# Import the necessary libraries
from azure.ai.ml.entities import Model
from azure.ai.ml.constants import AssetTypes

# Provide the model details, including the
# path to the model files, if you've stored them locally.
mlflow_model = Model(
    path="./deploy/credit_defaults_model/",
    type=AssetTypes.MLFLOW_MODEL,
    name="credit_defaults_model",
    description="MLflow Model created from local files.",
)

# Register the model
ml_client.models.create_or_update(mlflow_model)

確認模型已註冊

您可以檢查 Azure Machine Learning 工作室 中的 [模型] 頁面,以識別已註冊的模型最新版本。

Screenshot shows the registered model in studio.

或者,下列程式代碼會擷取您要使用的最新版本號碼。

registered_model_name = "credit_defaults_model"

# Let's pick the latest version of the model
latest_model_version = max(
    [int(m.version) for m in ml_client.models.list(name=registered_model_name)]
)

print(latest_model_version)

現在您已有已註冊的模型,您可以建立端點和部署。 下一節簡要說明這些主題的一些重要詳細數據。

端點和部署

定型機器學習模型之後,您必須部署它,讓其他人可以使用它進行推斷。 為此,Azure 機器學習 可讓您建立端點,並將部署新增至這些端點

在此內容中,端點是一個 HTTPS 路徑,提供介面供用戶端將要求(輸入數據)傳送至定型模型,並從模型接收推斷(評分)結果。 端點可提供:

  • 使用「金鑰或令牌」型驗證進行驗證
  • TLS(SSL) 終止
  • 穩定評分 URI (endpoint-name.region.inference.ml.azure.com)

部署是裝載執行實際推斷之模型所需的一組資源。

單一端點可包含多個部署。 端點和部署是顯示在 Azure 入口網站中的獨立 Azure Resource Manager 資源。

Azure 機器學習 可讓您實作在線端點,以即時推斷客戶端數據,以及批次端點,以在一段時間內推斷大量數據。

在本教學課程中,您將逐步執行實 作受控在線端點的步驟。 受控在線端點可在 Azure 中使用功能強大的 CPU 和 GPU 機器,以可調整且完全受控的方式,讓您免於設定和管理基礎部署基礎結構的額外負荷。

建立在線端點

現在您已有已註冊的模型,現在可以建立您的在線端點。 端點名稱在整個 Azure 區域中必須是唯一的。 在本教學課程中,您會使用通用唯一標識碼 UUID建立唯一名稱。 如需端點命名規則的詳細資訊,請參閱 端點限制

import uuid

# Create a unique name for the endpoint
online_endpoint_name = "credit-endpoint-" + str(uuid.uuid4())[:8]

首先,使用 ManagedOnlineEndpoint 類別定義端點。

提示

  • auth_mode:使用 key 進行金鑰式驗證。 使用 aml_token 進行 Azure Machine Learning 權杖型驗證。 key 不會過期,但 aml_token 會過期。 如需驗證的詳細資訊,請參閱 驗證在線端點的用戶端。

  • (選擇性) 您可以在端點中新增描述和標籤。

from azure.ai.ml.entities import ManagedOnlineEndpoint

# define an online endpoint
endpoint = ManagedOnlineEndpoint(
    name=online_endpoint_name,
    description="this is an online endpoint",
    auth_mode="key",
    tags={
        "training_dataset": "credit_defaults",
    },
)

使用稍早建立的 MLClient ,在工作區中建立端點。 此命令會啟動端點建立,並在端點建立繼續時傳回確認回應。

注意

預期建立端點需要大約 2 分鐘的時間。

# create the online endpoint
# expect the endpoint to take approximately 2 minutes.

endpoint = ml_client.online_endpoints.begin_create_or_update(endpoint).result()

建立端點之後,您可以擷取它,如下所示:

endpoint = ml_client.online_endpoints.get(name=online_endpoint_name)

print(
    f'Endpoint "{endpoint.name}" with provisioning state "{endpoint.provisioning_state}" is retrieved'
)

了解在線部署

部署的主要層面包括:

  • name - 部署的名稱。
  • endpoint_name - 將包含部署的端點名稱。
  • model - 要用於部署的模型。 此值可以是工作區中現有已建立版本模型的參考,也可以是內嵌模型規格。
  • environment - 用於部署的環境(或執行模型)。 此值可以是工作區中現有已建立版本環境的參考,也可以是內嵌環境規格。 環境可以是具有 Conda 相依性的 Docker 映像,或 Dockerfile。
  • code_configuration - 原始碼和評分文本的組態。
  • instance_type - 要用於部署的 VM 大小。 如需支援的大小清單,請參閱受控線上端點 SKU 清單
  • instance_count - 要用於部署的實例數目。

使用 MLflow 模型進行部署

Azure 機器學習 支援使用 MLflow 建立和記錄之模型的無程式代碼部署。 這表示您不需要在模型部署期間提供評分腳本或環境,因為定型 MLflow 模型時會自動產生評分腳本和環境。 不過,如果您使用自定義模型,則必須在部署期間指定環境和評分腳本。

重要

如果您通常會使用評分腳本和自定義環境來部署模型,而且想要使用 MLflow 模型達到相同的功能,建議您閱讀 部署 MLflow 模型的指導方針。

將模型部署至端點

首先,建立處理 100% 傳入流量的單一部署。 選擇部署的任意色彩名稱(藍色)。 若要建立端點的部署,請使用 類別 ManagedOnlineDeployment

注意

不需要將環境或評分腳本指定為要部署的模型是 MLflow 模型。

from azure.ai.ml.entities import ManagedOnlineDeployment

# Choose the latest version of the registered model for deployment
model = ml_client.models.get(name=registered_model_name, version=latest_model_version)

# define an online deployment
# if you run into an out of quota error, change the instance_type to a comparable VM that is available.\
# Learn more on https://azure.microsoft.com/en-us/pricing/details/machine-learning/.
blue_deployment = ManagedOnlineDeployment(
    name="blue",
    endpoint_name=online_endpoint_name,
    model=model,
    instance_type="Standard_DS3_v2",
    instance_count=1,
)

使用稍早建立的 MLClient ,現在在工作區中建立部署。 此命令會啟動部署建立,並在部署建立繼續時傳回確認回應。

# create the online deployment
blue_deployment = ml_client.online_deployments.begin_create_or_update(
    blue_deployment
).result()

# blue deployment takes 100% traffic
# expect the deployment to take approximately 8 to 10 minutes.
endpoint.traffic = {"blue": 100}
ml_client.online_endpoints.begin_create_or_update(endpoint).result()

檢查端點的狀態

您可以檢查端點的狀態,以檢視模型是否已部署而不發生錯誤:

# return an object that contains metadata for the endpoint
endpoint = ml_client.online_endpoints.get(name=online_endpoint_name)

# print a selection of the endpoint's metadata
print(
    f"Name: {endpoint.name}\nStatus: {endpoint.provisioning_state}\nDescription: {endpoint.description}"
)
# existing traffic details
print(endpoint.traffic)

# Get the scoring URI
print(endpoint.scoring_uri)

使用範例數據測試端點

現在模型已部署至端點,您可以使用它執行推斷。 首先,建立範例要求檔案,其遵循評分腳本中找到的執行方法中預期的設計。

import os

# Create a directory to store the sample request file.
deploy_dir = "./deploy"
os.makedirs(deploy_dir, exist_ok=True)

現在,在部署目錄中建立檔案。 下列程式代碼數據格會使用 IPython magic 將檔案寫入您剛才建立的目錄中。

%%writefile {deploy_dir}/sample-request.json
{
  "input_data": {
    "columns": [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22],
    "index": [0, 1],
    "data": [
            [20000,2,2,1,24,2,2,-1,-1,-2,-2,3913,3102,689,0,0,0,0,689,0,0,0,0],
            [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 10, 9, 8]
            ]
                }
}

使用稍早建立的 MLClient ,取得端點的句柄。 您可以使用 命令搭配下列參數來叫用 invoke 端點:

  • endpoint_name - 端點的名稱
  • request_file - 具有要求資料的檔案
  • deployment_name - 在端點中測試的特定部署名稱

使用範例數據測試藍色部署。

# test the blue deployment with the sample data
ml_client.online_endpoints.invoke(
    endpoint_name=online_endpoint_name,
    deployment_name="blue",
    request_file="./deploy/sample-request.json",
)

取得部署的記錄

檢查記錄,以查看是否已成功叫用端點/部署。 如果您遇到錯誤,請參閱 針對在線端點部署進行疑難解答。

logs = ml_client.online_deployments.get_logs(
    name="blue", endpoint_name=online_endpoint_name, lines=50
)
print(logs)

建立第二個部署

將模型部署為名為 green的第二個部署。 實際上,您可以建立數個部署並比較其效能。 這些部署可以使用相同模型的不同版本、不同的模型或更強大的計算實例。

在此範例中,您會使用更強大的計算實例來部署相同的模型版本,以可能改善效能。

# pick the model to deploy. Here you use the latest version of the registered model
model = ml_client.models.get(name=registered_model_name, version=latest_model_version)

# define an online deployment using a more powerful instance type
# if you run into an out of quota error, change the instance_type to a comparable VM that is available.\
# Learn more on https://azure.microsoft.com/en-us/pricing/details/machine-learning/.
green_deployment = ManagedOnlineDeployment(
    name="green",
    endpoint_name=online_endpoint_name,
    model=model,
    instance_type="Standard_F4s_v2",
    instance_count=1,
)

# create the online deployment
# expect the deployment to take approximately 8 to 10 minutes
green_deployment = ml_client.online_deployments.begin_create_or_update(
    green_deployment
).result()

調整部署以處理更多流量

使用稍早建立的 MLClient ,您可以取得部署的 green 句柄。 然後,您可以藉由增加或減少 instance_count來調整它。

在下列程式代碼中,您可以手動增加 VM 實例。 不過,您也可以自動調整在線端點。 自動調整會自動執行正確的資源量,以處理應用程式的負載。 受控線上端點透過與 Azure 監視器自動調整功能的整合,支援自動調整。 若要設定自動調整,請參閱 自動調整在線端點

# update definition of the deployment
green_deployment.instance_count = 2

# update the deployment
# expect the deployment to take approximately 8 to 10 minutes
ml_client.online_deployments.begin_create_or_update(green_deployment).result()

更新部署的流量配置

您可以在部署之間分割生產流量。 您可能先想要使用範例數據來測試 green 部署,就像您針對部署所做的 blue 一樣。 測試綠色部署之後,請將少量的流量配置給它。

endpoint.traffic = {"blue": 80, "green": 20}
ml_client.online_endpoints.begin_create_or_update(endpoint).result()

叫用端點數次來測試流量配置:

# You can invoke the endpoint several times
for i in range(30):
    ml_client.online_endpoints.invoke(
        endpoint_name=online_endpoint_name,
        request_file="./deploy/sample-request.json",
    )

顯示來自部署的 green 記錄,以檢查是否有連入要求,且模型已成功評分。

logs = ml_client.online_deployments.get_logs(
    name="green", endpoint_name=online_endpoint_name, lines=50
)
print(logs)

使用 Azure 監視器檢視計量

您可以檢視在線端點及其部署的各種計量(要求號碼、要求延遲、網路位元組、CPU/GPU/磁碟/記憶體使用率等等),方法是遵循 Studio 中端點詳細數據頁面的連結。 遵循上述任何連結,會帶您前往端點或部署 Azure 入口網站 中的確切計量頁面。

Screenshot showing links on the endpoint details page to view online endpoint and deployment metrics.

如果您開啟在線端點的計量,您可以設定頁面來查看計量,例如平均要求延遲,如下圖所示。

Screenshot showing online endpoint metrics in the Azure portal.

如需如何檢視在線端點計量的詳細資訊,請參閱 監視在線端點

將所有流量傳送至新的部署

一旦您完全滿意您的 green 部署,請將所有流量切換至該部署。

endpoint.traffic = {"blue": 0, "green": 100}
ml_client.begin_create_or_update(endpoint).result()

刪除舊的部署

移除舊的 (藍色) 部署:

ml_client.online_deployments.begin_delete(
    name="blue", endpoint_name=online_endpoint_name
).result()

清除資源

如果您在完成本教學課程之後不會使用端點和部署,您應該將其刪除。

注意

預期完整刪除大約需要 20 分鐘。

ml_client.online_endpoints.begin_delete(name=online_endpoint_name).result()

刪除所有內容

請使用下列步驟來刪除 Azure Machine Learning 工作區和所有計算資源。

重要

您所建立的資源可用來作為其他 Azure Machine Learning 教學課程和操作說明文章的先決條件。

如果不打算使用您建立的任何資源,請刪除以免產生任何費用:

  1. 在 Azure 入口網站中,選取最左邊的 [資源群組]

  2. 從清單中,選取您所建立的資源群組。

  3. 選取 [刪除資源群組]

    Screenshot of the selections to delete a resource group in the Azure portal.

  4. 輸入資源群組名稱。 接著選取刪除

後續步驟