共用方式為


從用於即時推斷的已部署模型收集生產資料

適用於:Azure CLI ml extension v2 (目前版本)Python SDK azure-ai-ml v2 (目前版本)

在本文中,您將了解如何使用 Azure Machine Learning 資料收集器,從部署至 Azure Machine Learning 受控線上端點或 Kubernetes 線上端點的模型中收集生產推斷資料。

您可以為新的或現有的線上端點部署啟用資料收集。 Azure Machine Learning 資料收集器會將推斷資料記錄至 Azure Blob 儲存體。 使用 Python SDK 收集的資料會自動在您的 Azure Machine Learning 工作區中註冊為資料資產。 此資料資產可用於模型監視。

如果您有興趣收集部署到即時端點之 MLflow 模型的生產推斷資料,請參閱 MLflow 模型的資料收集

先決條件

  • Azure CLIml Azure CLI 的擴充功能,已安裝並設定。 如需詳細資訊,請參閱 安裝和設定 CLI (v2)

  • Bash 殼層或相容的殼層,例如 Linux 系統上的殼層或 Windows 子系統 Linux 版 (部分內容可能是機器或 AI 翻譯)。 本文中的 Azure CLI 範例假設您使用這種類型的終端機。

  • Azure Machine Learning 工作區。 如需建立工作區的指示,請參閱 設定

  • Azure 角色型存取控制 (Azure RBAC) 可用來授與 Azure Machine Learning 作業的存取權。 若要執行本文中的步驟,您的使用者帳戶必須在 Azure Machine Learning 工作區中被指派擁有者參與者角色,或是允許 Microsoft.MachineLearningServices/workspaces/onlineEndpoints/* 的自訂角色。 如需詳細資訊,請參閱管理對 Azure Machine Learning 工作區的存取

執行用於模型監視的自訂記錄

使用自訂記錄進行資料收集,可讓您在評分指令碼中於任何資料轉換之前、期間及之後,直接記錄 pandas DataFrames。 透過自訂記錄,表格式資料會即時記錄到您的工作區 Blob 儲存體或自訂的 blob 儲存體容器中。 您的模型監視器可以從儲存體取用這些資料。

使用自訂記錄程式碼更新您的評分指令碼

首先,將自訂記錄程式碼新增至您的評分指令碼 (score.py)。 若要使用自訂記錄,您需要 azureml-ai-monitoring 套件。 如需此套件的詳細資訊,請參閱資料收集器 SDK 的 PyPI 頁面

  1. 在評分指令碼頂端新增下列這一行,以匯入 azureml-ai-monitoring 套件:

    from azureml.ai.monitoring import Collector
    
  2. init() 函式中宣告您的資料收集變數 (最多五個):

    附註

    如果您將 Collector 物件命名為 model_inputsmodel_outputs,模型監視系統會自動辨識自動註冊的資料資產,以提供更順暢的模型監視體驗。

    global inputs_collector, outputs_collector
    inputs_collector = Collector(name='model_inputs')          
    outputs_collector = Collector(name='model_outputs')
    

    依預設,若資料收集期間發生失敗,Azure Machine Learning 會引發例外狀況。 您也可以選擇使用 on_error 參數,指定在記錄失敗時要執行的函式。 例如,在下列程式碼中使用 on_error 參數時,Azure Machine Learning 會記錄錯誤而非擲回例外狀況:

    inputs_collector = Collector(name='model_inputs', on_error=lambda e: logging.info("ex:{}".format(e)))
    
  3. run() 函式中,使用 collect() 函式於評分前後記錄 DataFrames。 context 會在第一次呼叫 collect() 時傳回,並包含可在後續關聯模型輸入與模型輸出所需的資訊。

    context = inputs_collector.collect(data) 
    result = model.predict(data)
    outputs_collector.collect(result, context)
    

    附註

    目前,collect() API 僅會記錄 pandas DataFrames。 如果將資料以非 DataFrame 形式傳遞給 collect(),該資料將不會被記錄到儲存體中,且會回報錯誤。

下列程式碼為使用自訂記錄 Python SDK 的完整評分指令碼 (score.py) 範例。

import pandas as pd
import json
from azureml.ai.monitoring import Collector

def init():
  global inputs_collector, outputs_collector, inputs_outputs_collector

  # instantiate collectors with appropriate names, make sure align with deployment spec
  inputs_collector = Collector(name='model_inputs')                    
  outputs_collector = Collector(name='model_outputs')

def run(data): 
  # json data: { "data" : {  "col1": [1,2,3], "col2": [2,3,4] } }
  pdf_data = preprocess(json.loads(data))
  
  # tabular data: {  "col1": [1,2,3], "col2": [2,3,4] }
  input_df = pd.DataFrame(pdf_data)

  # collect inputs data, store correlation_context
  context = inputs_collector.collect(input_df)

  # perform scoring with pandas Dataframe, return value is also pandas Dataframe
  output_df = predict(input_df) 

  # collect outputs data, pass in correlation_context so inputs and outputs data can be correlated later
  outputs_collector.collect(output_df, context)
  
  return output_df.to_dict()
  
def preprocess(json_data):
  # preprocess the payload to ensure it can be converted to pandas DataFrame
  return json_data["data"]

def predict(input_df):
  # process input and return with outputs
  ...
  
  return output_df

更新您的評分指令碼以記錄自訂的唯一識別碼

除了在評分指令碼中直接記錄 pandas DataFrames 之外,您也可以使用自行選擇的唯一識別碼來記錄資料。 這些識別碼可以來自您的應用程式、外部系統,或由您自行產生。 如果您未依本節所述提供自訂 ID,資料收集器將自動產生唯一的 correlationid,以協助您在後續關聯模型輸入與模型輸出。 如果您提供自訂 ID,已記錄資料中的 correlationid 欄位將包含您所提供的自訂 ID 值。

  1. 請先完成前一節中的步驟,然後在評分指令碼中新增下列這一行,以匯入 azureml.ai.monitoring.context 套件:

    from azureml.ai.monitoring.context import BasicCorrelationContext
    
  2. 在您的評分指令碼中,建立一個 BasicCorrelationContext 物件,並傳入您希望為該資料列記錄的 id。 我們建議此 id 使用來自您系統的唯一識別碼,讓您可以從 Blob 儲存體中唯一識別每一筆已記錄的資料列。 請將此物件作為參數傳遞至 collect() API 呼叫中:

      # create a context with a custom unique id
      artificial_context = BasicCorrelationContext(id='test')
    
      # collect inputs data, store correlation_context
      context = inputs_collector.collect(input_df, artificial_context)
    
  3. 請確定您將此內容傳遞至 outputs_collector,讓模型輸入與模型輸出能以相同的唯一 ID 進行記錄,並在後續輕鬆加以關聯:

      # collect outputs data, pass in context so inputs and outputs data can be correlated later
      outputs_collector.collect(output_df, context)
    

下列程式碼為記錄自訂唯一識別碼的完整評分指令碼 (score.py) 範例。

import pandas as pd
import json
from azureml.ai.monitoring import Collector
from azureml.ai.monitoring.context import BasicCorrelationContext

def init():
  global inputs_collector, outputs_collector, inputs_outputs_collector

  # instantiate collectors with appropriate names, make sure align with deployment spec
  inputs_collector = Collector(name='model_inputs')                    
  outputs_collector = Collector(name='model_outputs')

def run(data): 
  # json data: { "data" : {  "col1": [1,2,3], "col2": [2,3,4] } }
  pdf_data = preprocess(json.loads(data))
  
  # tabular data: {  "col1": [1,2,3], "col2": [2,3,4] }
  input_df = pd.DataFrame(pdf_data)

  # create a context with a custom unique id
  artificial_context = BasicCorrelationContext(id='test')

  # collect inputs data, store correlation_context
  context = inputs_collector.collect(input_df, artificial_context)

  # perform scoring with pandas Dataframe, return value is also pandas Dataframe
  output_df = predict(input_df) 

  # collect outputs data, pass in context so inputs and outputs data can be correlated later
  outputs_collector.collect(output_df, context)
  
  return output_df.to_dict()
  
def preprocess(json_data):
  # preprocess the payload to ensure it can be converted to pandas DataFrame
  return json_data["data"]

def predict(input_df):
  # process input and return with outputs
  ...
  
  return output_df

收集用於模型效能監視的資料

如果您想將收集的資料用於模型效能監視,請務必讓每一筆已記錄的資料列都具有唯一的 correlationid,以便在取得實際標註資料時,用來與其進行關聯。 資料收集器會為每一筆已記錄的資料列自動產生唯一的 correlationid,並將此自動產生的 ID 包含在 JSON 物件中的 correlationid 欄位。 如需 JSON 結構描述的詳細資訊,請參閱將收集的資料儲存在 Blob 儲存體中

如果您想在生產資料記錄中使用您自己的唯一 ID,建議您將此 ID 記錄為 pandas DataFrame 中的獨立資料行,因為資料收集器會將彼此時間相近的要求進行批次處理。 透過將 correlationid 記錄為獨立資料行,後續即可輕鬆與實際標註資料進行整合。

更新相依性

在您能使用更新後的評分指令碼建立部署之前,必須先建立包含基底映像 mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu20.04 與適當 conda 相依性的環境。 接著,您可以使用下列 YAML 中的規格來建置環境。

channels:
  - conda-forge
dependencies:
  - python=3.8
  - pip=22.3.1
  - pip:
      - azureml-defaults==1.38.0
      - azureml-ai-monitoring~=0.1.0b1
name: model-env

更新部署 YAML

接下來,建立部署 YAML。 若要建立部署 YAML,請包含 data_collector 屬性,並為先前透過自訂記錄 Python SDK 建立的 Collector 物件 model_inputsmodel_outputs 啟用資料收集:

data_collector:
  collections:
    model_inputs:
      enabled: 'True'
    model_outputs:
      enabled: 'True'

下列程式碼為受控線上端點部署的完整部署 YAML 範例。 請依您的情境更新部署 YAML。 如需更多有關推斷資料記錄之部署 YAML 格式的範例,請參閱 Azure 模型資料收集器範例

$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineDeployment.schema.json
name: blue
endpoint_name: my_endpoint
model: azureml:iris_mlflow_model@latest
environment:
  image: mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu20.04
  conda_file: model/conda.yaml
code_configuration:
  code: scripts
  scoring_script: score.py
instance_type: Standard_F2s_v2
instance_count: 1
data_collector:
  collections:
    model_inputs:
      enabled: 'True'
    model_outputs:
      enabled: 'True'

您也可以選擇性調整 data_collector 的下列額外參數:

  • data_collector.rolling_rate:在儲存體中分割資料的速率。 請從下列值中選擇:MinuteHourDayMonthYear
  • data_collector.sampling_rate:要收集的資料百分比,以小數表示。 例如,值為 1.0 代表收集 100% 的資料。
  • data_collector.collections.<collection_name>.data.name:要以收集資料註冊的資料資產名稱。
  • data_collector.collections.<collection_name>.data.path:收集的資料應註冊為資料資產之 Azure Machine Learning 資料存放區完整路徑。
  • data_collector.collections.<collection_name>.data.version:要與 Blob 儲存體中收集的資料一起註冊之資料資產版本。

將資料收集到自訂的 Blob 儲存體容器

您可以依照下列步驟,使用資料收集器將生產推斷資料收集到自訂的 Blob 儲存體容器:

  1. 將儲存體容器連線至 Azure Machine Learning 資料存放區。 如需有關將儲存體容器連線至 Azure Machine Learning 資料存放區的詳細資訊,請參閱建立資料存放區

  2. 確認您的 Azure Machine Learning 端點具有寫入資料存放區目的地所需的權限。

    資料收集器同時支援系統指派受控識別 (SAMIs) 與使用者指派受控識別 (UAMIs)。 將識別新增至您的端點。 將 Storage Blob Data Contributor 角色指派給此識別,並將要作為資料目的地的 Blob 儲存體容器套用該角色。 若要深入了解如何在 Azure 中使用受控識別,請參閱將 Azure 角色指派給受控識別

  3. 更新您的部署 YAML,在每個集合中包含 data 屬性。

    • 必要參數 data.name,用於指定要以收集資料註冊的資料資產名稱。
    • 必要參數 data.path,用於指定完整的 Azure Machine Learning 資料存放區路徑,該路徑已連線至您的 Azure Blob 儲存體容器。
    • 選用參數 data.version,用於指定資料資產的版本 (預設為 1)。

    下列 YAML 組態示範如何在每個集合中包含 data 屬性。

    data_collector:
      collections:
        model_inputs:
          enabled: 'True'
          data: 
            name: my_model_inputs_data_asset
            path: azureml://datastores/workspaceblobstore/paths/modelDataCollector/my_endpoint/blue/model_inputs
            version: 1
        model_outputs:
          enabled: 'True'
          data: 
            name: my_model_outputs_data_asset
            path: azureml://datastores/workspaceblobstore/paths/modelDataCollector/my_endpoint/blue/model_outputs 
            version: 1
    

    附註

    您也可以使用 data.path 參數,提供符合下列格式的路徑,將其指向不同 Azure 訂用帳戶中的資料存放區:azureml://subscriptions/<sub_id>/resourcegroups/<rg_name>/workspaces/<ws_name>/datastores/<datastore_name>/paths/<path>

建立啟用資料收集的部署

部署已啟用自訂記錄的模型:

$ az ml online-deployment create -f deployment.YAML

如需有關 Kubernetes 線上端點進行資料收集之部署 YAML 格式的詳細資訊,請參閱 CLI (v2) Azure Arc 啟用 Kubernetes 線上部署 YAML 結構描述

如需有關受控線上端點進行資料收集之部署 YAML 格式的詳細資訊,請參閱 CLI (v2) 受控線上部署 YAML 結構描述

執行承載記錄

除了使用所提供的 Python SDK 進行自訂記錄之外,您也可以直接收集要求與回應的 HTTP 承載資料,而無需擴充您的評分指令碼 (score.py)。

  1. 若要啟用承載記錄,請在您的部署 YAML 中使用 requestresponse 名稱:

    $schema: http://azureml/sdk-2-0/OnlineDeployment.json
    
    endpoint_name: my_endpoint 
    name: blue 
    model: azureml:my-model-m1:1 
    environment: azureml:env-m1:1 
    data_collector:
       collections:
           request:
               enabled: 'True'
           response:
               enabled: 'True'
    
  2. 部署已啟用承載記錄的模型:

    $ az ml online-deployment create -f deployment.YAML
    

使用承載記錄時,所收集的資料不保證為表格式。 因此,若您想將收集的承載資料用於模型監視,將需要提供前處理元件,將資料轉換為表格式。 若您希望獲得更順暢的模型監視體驗,建議使用自訂記錄 Python SDK

當您的部署被使用時,所收集的資料會流向您的工作區 Blob 儲存體。 下列 JSON 程式碼為所收集之 HTTP 要求的範例:

{"specversion":"1.0",
"id":"19790b87-a63c-4295-9a67-febb2d8fbce0",
"source":"/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/mire2etesting/providers/Microsoft.MachineLearningServices/workspaces/mirmasterenvws/onlineEndpoints/localdev-endpoint/deployments/localdev",
"type":"azureml.inference.request",
"datacontenttype":"application/json",
"time":"2022-05-25T08:59:48Z",
"data":{"data": [  [1,2,3,4,5,6,7,8,9,10], [10,9,8,7,6,5,4,3,2,1]]},
"path":"/score",
"method":"POST",
"contentrange":"bytes 0-59/*",
"correlationid":"aaaa0000-bb11-2222-33cc-444444dddddd","xrequestid":"aaaa0000-bb11-2222-33cc-444444dddddd"}

下列 JSON 程式碼則為另一個所收集之 HTTP 回應範例:

{"specversion":"1.0",
"id":"bbd80e51-8855-455f-a719-970023f41e7d",
"source":"/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/mire2etesting/providers/Microsoft.MachineLearningServices/workspaces/mirmasterenvws/onlineEndpoints/localdev-endpoint/deployments/localdev",
"type":"azureml.inference.response",
"datacontenttype":"application/json",
"time":"2022-05-25T08:59:48Z",
"data":[11055.977245525679, 4503.079536107787],
"contentrange":"bytes 0-38/39",
"correlationid":"aaaa0000-bb11-2222-33cc-444444dddddd","xrequestid":"aaaa0000-bb11-2222-33cc-444444dddddd"}

將收集的資料儲存在 Blob 儲存體中

資料收集可讓您將生產推斷資料記錄到您選擇的 Blob 儲存體目的地。 資料目的地設定可在 collection_name 層級進行組態。

Blob 儲存體輸出/格式

  • 依預設,收集的資料會儲存在您工作區 Blob 儲存體中的下列路徑:azureml://datastores/workspaceblobstore/paths/modelDataCollector

  • Blob 中的最終路徑會附加 {endpoint_name}/{deployment_name}/{collection_name}/{yyyy}/{MM}/{dd}/{HH}/{instance_id}.jsonl

  • 檔案中的每一行都是一個 JSON 物件,代表一筆已記錄的推斷要求/回應。

附註

collection_name 指的是資料收集名稱 (例如 model_inputsmodel_outputs)。 instance_id 是用來識別所記錄資料分組的唯一識別碼。

收集的資料遵循下列 JSON 結構描述。 收集的資料可從 data 索引鍵取得,並會提供其他中繼資料。

{"specversion":"1.0",
"id":"725aa8af-0834-415c-aaf5-c76d0c08f694",
"source":"/subscriptions/bbbb1b1b-cc2c-dd3d-ee4e-ffffff5f5f5f/resourceGroups/mire2etesting/providers/Microsoft.MachineLearningServices/workspaces/mirmasterws/onlineEndpoints/localdev-endpoint/deployments/localdev",
"type":"azureml.inference.inputs",
"datacontenttype":"application/json",
"time":"2022-12-01T08:51:30Z",
"data":[{"label":"DRUG","pattern":"aspirin"},{"label":"DRUG","pattern":"trazodone"},{"label":"DRUG","pattern":"citalopram"}],
"correlationid":"bbbb1111-cc22-3333-44dd-555555eeeeee","xrequestid":"bbbb1111-cc22-3333-44dd-555555eeeeee",
"modelversion":"default",
"collectdatatype":"pandas.core.frame.DataFrame",
"agent":"monitoring-sdk/0.1.2",
"contentrange":"bytes 0-116/117"}

秘訣

為了便於閱讀,僅顯示換行。 在您收集的 .jsonl 檔案中,不會有任何換行。

儲存大型承載

如果資料的承載大於 4 MB,{instance_id}.jsonl 檔案中會有一個事件,該檔案位於 {endpoint_name}/{deployment_name}/request/.../{instance_id}.jsonl 路徑下,並指向原始檔案路徑,其路徑如下:blob_url/{blob_container}/{blob_path}/{endpoint_name}/{deployment_name}/{rolled_time}/{instance_id}.jsonl。 收集的資料將存在於此路徑。

儲存二進位資料

對於收集的二進位資料,會直接顯示原始檔案,並以 instance_id 作為檔案名稱。 二進位資料會依據 rolling_rate,放置在與要求來源群組路徑相同的資料夾中。 下列範例反映 data 欄位中的路徑。 格式為 json,換行僅為便於閱讀而顯示:

{
"specversion":"1.0",
"id":"ba993308-f630-4fe2-833f-481b2e4d169a",
"source":"/subscriptions//resourceGroups//providers/Microsoft.MachineLearningServices/workspaces/ws/onlineEndpoints/ep/deployments/dp",
"type":"azureml.inference.request",
"datacontenttype":"text/plain",
"time":"2022-02-28T08:41:07Z",
"data":"https://masterws0373607518.blob.core.windows.net/modeldata/mdc/%5Byear%5D%5Bmonth%5D%5Bday%5D-%5Bhour%5D_%5Bminute%5D/ba993308-f630-4fe2-833f-481b2e4d169a",
"path":"/score?size=1",
"method":"POST",
"contentrange":"bytes 0-80770/80771",
"datainblob":"true"
}

資料收集器批次處理

如果在短時間間隔內傳送多個要求,資料收集器會將它們批次處理為同一個 JSON 物件。 例如,若您執行指令碼將範例資料傳送至端點,且部署已啟用資料收集,則視要求之間的時間間隔而定,部分要求可能會被一起批次處理。 如果您搭配 Azure Machine Learning 模型監視使用資料收集,模型監視服務會獨立處理每一個要求。 不過,如果您希望每一筆已記錄的資料列都具有各自唯一的 correlationid,您可以將 correlationid 納入以資料收集器記錄的 pandas DataFrame 中,作為一個資料行。 如需如何將您的唯一 correlationid 納入 pandas DataFrame 資料行的詳細資訊,請參閱收集用於模型效能監視的資料

以下為兩筆被批次處理在一起的已記錄要求範例:

{"specversion":"1.0",
"id":"720b8867-54a2-4876-80eb-1fd6a8975770",
"source":"/subscriptions/cccc2c2c-dd3d-ee4e-ff5f-aaaaaa6a6a6a/resourceGroups/rg-bozhlinmomoignite/providers/Microsoft.MachineLearningServices/workspaces/momo-demo-ws/onlineEndpoints/credit-default-mdc-testing-4/deployments/main2",
"type":"azureml.inference.model_inputs",
"datacontenttype":"application/json",
"time":"2024-03-05T18:16:25Z",
"data":[{"LIMIT_BAL":502970,"AGE":54,"BILL_AMT1":308068,"BILL_AMT2":381402,"BILL_AMT3":442625,"BILL_AMT4":320399,"BILL_AMT5":322616,"BILL_AMT6":397534,"PAY_AMT1":17987,"PAY_AMT2":78764,"PAY_AMT3":26067,"PAY_AMT4":24102,"PAY_AMT5":-1155,"PAY_AMT6":2154,"SEX":2,"EDUCATION":2,"MARRIAGE":2,"PAY_0":0,"PAY_2":0,"PAY_3":0,"PAY_4":0,"PAY_5":0,"PAY_6":0},{"LIMIT_BAL":293458,"AGE":35,"BILL_AMT1":74131,"BILL_AMT2":-71014,"BILL_AMT3":59284,"BILL_AMT4":98926,"BILL_AMT5":110,"BILL_AMT6":1033,"PAY_AMT1":-3926,"PAY_AMT2":-12729,"PAY_AMT3":17405,"PAY_AMT4":25110,"PAY_AMT5":7051,"PAY_AMT6":1623,"SEX":1,"EDUCATION":3,"MARRIAGE":2,"PAY_0":-2,"PAY_2":-2,"PAY_3":-2,"PAY_4":-2,"PAY_5":-1,"PAY_6":-1}],
"contentrange":"bytes 0-6794/6795",
"correlationid":"test",
"xrequestid":"test",
"modelversion":"default",
"collectdatatype":"pandas.core.frame.DataFrame",
"agent":"azureml-ai-monitoring/0.1.0b4"}

在 Studio UI 中檢視資料

若要從 Studio UI 檢視儲存在 Blob 儲存體中的收集資料:

  1. 前往 Azure Machine Learning 工作區中的資料索引標籤:

    螢幕擷取畫面顯示 Azure Machine Learning 工作區中的資料頁面

  2. 瀏覽至資料存放區,並選取 workspaceblobstore (預設)

    截圖重點顯示 Azure Machine Learning Workspace 中的 Datastores 頁面

  3. 使用瀏覽功能表來檢視收集的生產資料:

    螢幕擷取畫面顯示資料存放區中的樹狀結構

收集 MLflow 模型的資料

如果您要將 MLflow 模型部署至 Azure Machine Learning 線上端點,您可以在 Studio UI 中透過單一切換來啟用生產推斷資料收集。 啟用資料收集後,Azure Machine Learning 會自動在您的評分指令碼中植入自訂記錄程式碼,以確保生產資料會記錄至您的工作區 Blob 儲存體。 接著,您的模型監視器即可使用這些資料來監視生產環境中 MLflow 模型的效能。

在設定模型部署時,您可以啟用生產資料收集。 在部署索引標籤下,將資料收集設為已啟用

啟用資料收集後,生產推斷資料會記錄至您的 Azure Machine Learning 工作區 Blob 儲存體,並建立兩個資料資產,名稱為 <endpoint_name>-<deployment_name>-model_inputs<endpoint_name>-<deployment_name>-model_outputs。 這些資料資產會在您於生產環境中使用部署時即時更新。 接著,您的模型監視器即可使用這些資料資產來監視模型在生產環境中的效能。