使用 REST 部署模型

了解如何使用 Azure 机器学习 REST API 部署模型。

REST API 使用标准 HTTP 谓词创建、检索、更新和删除资源。 REST API 适用于可发出 HTTP 请求的任何语言或工具。 REST 具有简单的结构,因此它是适合脚本编写环境和 MLOps 自动化的良好选择。

本文介绍如何使用新的 REST API 执行以下操作:

  • 创建机器学习资产
  • 创建基本训练作业
  • 创建超参数优化扫描作业

先决条件

设置终结点名称

注意

终结点名称在 Azure 区域级别需是唯一的。 例如,chinaeast2 中只能有一个名为 my-endpoint 的终结点。

export ENDPOINT_NAME=endpt-rest-`echo $RANDOM`

Azure 机器学习联机终结点

通过联机终结点,无需创建和管理底层基础结构以及 Kubernetes 群集即可部署模型。 在本文中,你将创建一个联机终结点和部署,并通过调用它来对其进行验证。 但首先必须注册部署所需的资产,包括模型、代码和环境。

有多种方法可以创建 Azure 机器学习联机终结点,包括使用 Azure CLI 创建,以及在工作室中以可视方式创建。 下面的示例使用 REST API 部署联机终结点。

创建机器学习资产

首先设置 Azure 机器学习资产以配置作业。

在以下 REST API 调用中,我们使用了 SUBSCRIPTION_IDRESOURCE_GROUPLOCATIONWORKSPACE 作为占位符。 将占位符替换为自己的值。

管理 REST 请求一个服务主体身份验证令牌。 请将 TOKEN 替换为你自己的值。 可使用以下命令检索此令牌:

response=$(curl -H "Content-Length: 0" --location --request POST "https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/onlineEndpoints/$ENDPOINT_NAME/token?api-version=$API_VERSION" \
--header "Authorization: Bearer $TOKEN")
accessToken=$(echo $response | jq -r '.accessToken')

服务提供商使用 api-version 参数来确保兼容性。 api-version 参数因服务而异。 将 API 版本设置为变量以适应将来的版本:

API_VERSION="2022-05-01"

获取存储帐户详细信息

若要注册模型和代码,首先需要将其上传到存储帐户。 数据存储中提供了存储帐户的详细信息。 此示例将获取工作区的默认数据存储和 Azure 存储帐户。 使用 GET 请求查询工作区,以获取包含信息的 JSON 文件。

可以使用工具 jq 分析 JSON 结果并获取所需的值。 也可以使用 Azure 门户找到相同的信息:

# Get values for storage account
response=$(curl --location --request GET "https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/datastores?api-version=$API_VERSION&isDefault=true" \
--header "Authorization: Bearer $TOKEN")
AZUREML_DEFAULT_DATASTORE=$(echo $response | jq -r '.value[0].name')
AZUREML_DEFAULT_CONTAINER=$(echo $response | jq -r '.value[0].properties.containerName')
export AZURE_STORAGE_ACCOUNT=$(echo $response | jq -r '.value[0].properties.accountName')

上传和注册代码

获取数据存储后,可以上传评分脚本。 使用 Azure 存储 CLI 将 Blob 上传到默认容器中:

az storage blob upload-batch -d $AZUREML_DEFAULT_CONTAINER/score -s endpoints/online/model-1/onlinescoring

提示

也可以使用其他方法来上传,例如 Azure 门户或 Azure 存储资源管理器

上传代码后,可以使用 PUT 请求指定代码,并使用 datastoreId 引用数据存储:

curl --location --request PUT "https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/codes/score-sklearn/versions/1?api-version=$API_VERSION" \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data-raw "{
  \"properties\": {
    \"codeUri\": \"https://$AZURE_STORAGE_ACCOUNT.blob.core.chinacloudapi.cn/$AZUREML_DEFAULT_CONTAINER/score\"
  }
}"

上传和注册模型

与代码类似,上传模型文件:

az storage blob upload-batch -d $AZUREML_DEFAULT_CONTAINER/model -s endpoints/online/model-1/model

现在注册模型:

curl --location --request PUT "https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/models/sklearn/versions/1?api-version=$API_VERSION" \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data-raw "{
    \"properties\": {
        \"modelUri\":\"azureml://subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/workspaces/$WORKSPACE/datastores/$AZUREML_DEFAULT_DATASTORE/paths/model/sklearn_regression_model.pkl\"
    }
}"

创建环境

部署需要在具有所需依赖关系的环境中运行。 使用 PUT 请求创建环境。 使用 Microsoft Container Registry 中的 Docker 映像。 可以使用 Docker 配置 Docker 映像,并使用 condaFile 添加 Conda 依赖项。

在以下代码片段中,已将 Conda 环境 (YAML 文件) 的内容读入环境变量:

ENV_VERSION=$RANDOM
curl --location --request PUT "https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/environments/sklearn-env/versions/$ENV_VERSION?api-version=$API_VERSION" \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data-raw "{
    \"properties\":{
        \"condaFile\": \"$CONDA_FILE\",
        \"image\": \"mcr.microsoft.com/azureml/openmpi3.1.2-ubuntu18.04:20210727.v1\"
    }
}"

创建终结点

创建联机终结点:

response=$(curl --location --request PUT "https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/onlineEndpoints/my-first-endpoint?api-version=$API_VERSION" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer $TOKEN" \
--data-raw "{
    \"identity\": {
       \"type\": \"systemAssigned\"
    },
    \"properties\": {
        \"authMode\": \"AMLToken\"
    },
    \"location\": \"$LOCATION\"
}")

创建部署

在该终结点下创建部署:

response=$(curl --location --request PUT "https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/onlineEndpoints/my-first-endpoint/deployments/blue?api-version=$API_VERSION" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer $TOKEN" \
--data-raw "{
    \"location\": \"$LOCATION\",
    \"sku\": {
        \"capacity\": 1,
        \"name\": \"Standard_DS2_v2\"
    },
    \"properties\": {
        \"endpointComputeType\": \"Managed\",
        \"scaleSettings\": {
            \"scaleType\": \"Default\"
        },
        \"model\": \"/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/models/sklearn/versions/1\",
        \"codeConfiguration\": {
            \"codeId\": \"/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/codes/score-sklearn/versions/1\",
            \"scoringScript\": \"score.py\"
        },
        \"environmentId\": \"/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/environments/sklearn-env/versions/$ENV_VERSION\"
    }
}")

调用终结点为模型数据评分

需要评分 uri 和访问令牌来调用终结点。 首先获取评分 uri:

response=$(curl --location --request GET "https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/onlineEndpoints/my-first-endpoint?api-version=$API_VERSION" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer $TOKEN")

scoringUri=$(echo $response | jq -r '.properties' | jq -r '.scoringUri')

获取终结点访问令牌:

response=$(curl -H "Content-Length: 0" --location --request POST "https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/onlineEndpoints/my-first-endpoint/token?api-version=$API_VERSION" \
--header "Authorization: Bearer $TOKEN")
accessToken=$(echo $response | jq -r '.accessToken')

现在,使用 curl 调用该终结点:

curl --location --request POST $scoringUri \
--header "Authorization: Bearer $accessToken" \
--header "Content-Type: application/json" \
--data-raw @endpoints/online/model-1/sample-request.json

检查日志

检查部署日志:

curl --location --request POST "https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/onlineEndpoints/my-first-endpoint/deployments/blue/getLogs?api-version=$API_VERSION" \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data-raw "{ \"tail\": 100 }"

删除终结点

如果你将来不再使用该部署,应使用以下命令将其删除(这会删除终结点和所有基础部署):

curl --location --request DELETE "https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/onlineEndpoints/my-first-endpoint?api-version=$API_VERSION" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer $TOKEN" || true

后续步骤