使用批处理模型部署进行图像处理

适用范围:Azure CLI ml 扩展 v2(最新版)Python SDK azure-ai-ml v2(最新版)

批处理模型部署可用于处理表格数据,也可用于处理图像等任何其他文件类型。 MLflow 和自定义模型都支持这些部署。 本教程介绍如何根据 ImageNet 分类部署图像分类模型。

关于此示例

我们将采用的模型使用 TensorFlow 和 RestNet 体系结构 (深度残差网络中的标识映射) 建成。 可从此处下载此模型的示例。 此模型具有以下约束,这些约束对于部署而言非常重要,请务必牢记:

  • 适用于大小为 244x244 的图像(张量 (224, 224, 3))。
  • 要求将输入缩放到范围 [0,1] 内。

本文中的信息基于 azureml-examples 存储库中包含的代码示例。 要在本地运行命令而不必复制/粘贴 YAML 和其他文件,请克隆存储库repo,然后将目录更改为 cli/endpoints/batch/deploy-models/imagenet-classifier(如果你使用的是 Azure CLI)或更改为 sdk/python/endpoints/batch/deploy-models/imagenet-classifier(如果你使用的是我们的 Python SDK)。

git clone https://github.com/Azure/azureml-examples --depth 1
cd azureml-examples/cli/endpoints/batch/deploy-models/imagenet-classifier

在 Jupyter Notebook 中继续操作

可以在 Jupyter Notebook 中按照此示例进行操作。 在克隆的存储库中,打开以下笔记本:imagenet-classifier-batch.ipynb

先决条件

在按照本文中的步骤操作之前,请确保满足以下先决条件:

  • Azure 订阅。 如果没有 Azure 订阅,可在开始前创建一个试用帐户。 试用 Azure 机器学习

  • 一个 Azure 机器学习工作区。 如果你没有,请按照管理 Azure 机器学习工作区一文中的步骤创建一个。

  • 确保你在工作区中具有以下权限:

    • 创建或管理批处理终结点和部署:使用允许 Microsoft.MachineLearningServices/workspaces/batchEndpoints/* 的所有者、参与者或自定义角色。

    • 在工作区资源组中创建 ARM 部署:在部署工作区的资源组中使用允许 Microsoft.Resources/deployments/write 的所有者角色、参与者角色或自定义角色。

  • 需要安装以下软件才能使用 Azure 机器学习:

    Azure CLIml适用于 Azure 机器学习的扩展

    az extension add -n ml
    

    注意

    Azure CLI 的 ml 扩展版本 2.7 中引入了 Batch 终结点的管道组件部署。 使用 az extension update --name ml 获取它的上一个版本。

连接到工作区

工作区是 Azure 机器学习的顶级资源,为使用 Azure 机器学习时创建的所有项目提供了一个集中的处理位置。 在本部分,我们将连接到要在其中执行部署任务的工作区。

在以下代码中传入订阅 ID、工作区、位置和资源组的值:

az account set --subscription <subscription>
az configure --defaults workspace=<workspace> group=<resource-group> location=<location>

利用批部署进行图像分类

在此示例中,我们将了解如何部署可根据 ImageNet 分类对给定图像进行分类的深度学习模型。

创建终结点

首先,让我们创建将托管模型的终结点:

确定终结点的名称:

ENDPOINT_NAME="imagenet-classifier-batch"

以下 YAML 文件定义批处理终结点:

endpoint.yml

$schema: https://azuremlschemas.azureedge.net/latest/batchEndpoint.schema.json
name: imagenet-classifier-batch
description: A batch endpoint for performing image classification using a TFHub model ImageNet model.
auth_mode: aad_token

运行以下代码以创建终结点。

az ml batch-endpoint create --file endpoint.yml  --name $ENDPOINT_NAME

注册模型

模型部署只能部署已注册的模型,因此我们需要先注册。 如果打算部署的模型已注册,则可以跳过此步骤。

  1. 下载模型副本:

    wget https://azuremlexampledata.blob.core.chinacloudapi.cn/data/imagenet/model.zip
    mkdir -p imagenet-classifier
    unzip model.zip -d imagenet-classifier
    
  2. 注册模型:

    MODEL_NAME='imagenet-classifier'
    az ml model create --name $MODEL_NAME --path "model"
    

创建评分脚本

我们需要创建评分脚本,该脚本应能读取批处理部署提供的映像并返回模型的分数。 以下脚本:

  • 表示init使用tensorflow中模块keras加载模型的函数。
  • 表示run为批处理部署提供的每个小型批处理执行的函数。
  • 函数run一次读取文件的一个图像
  • run方法可将图像大小调整为模型的预期大小。
  • run方法将图像重新缩放到范围[0,1]域,即模型的预期内容。
  • 它会返回与预测有关的类和概率。

code/score-by-file/batch_driver.py

import os
import numpy as np
import pandas as pd
import tensorflow as tf
from os.path import basename
from PIL import Image
from tensorflow.keras.models import load_model


def init():
    global model
    global input_width
    global input_height

    # AZUREML_MODEL_DIR is an environment variable created during deployment
    model_path = os.path.join(os.environ["AZUREML_MODEL_DIR"], "model")

    # load the model
    model = load_model(model_path)
    input_width = 244
    input_height = 244


def run(mini_batch):
    results = []

    for image in mini_batch:
        data = Image.open(image).resize(
            (input_width, input_height)
        )  # Read and resize the image
        data = np.array(data) / 255.0  # Normalize
        data_batch = tf.expand_dims(
            data, axis=0
        )  # create a batch of size (1, 244, 244, 3)

        # perform inference
        pred = model.predict(data_batch)

        # Compute probabilities, classes and labels
        pred_prob = tf.math.reduce_max(tf.math.softmax(pred, axis=-1)).numpy()
        pred_class = tf.math.argmax(pred, axis=-1).numpy()

        results.append([basename(image), pred_class[0], pred_prob])

    return pd.DataFrame(results)

提示

尽管图像由部署在小型批处理中提供,但此评分脚本一次仅处理一个图像。 这是一种常见模式,尝试加载整个批处理并将其一次性发送到模型可能会导致批处理执行程序(OOM 执行程序)的内存压力增大。 但是,在某些情况下,这样做会在评分任务中出现高吞吐量。 例如,通过 GPU 硬件进行批量部署,我们想实现高 GPU 利用率时。 有关基于它的评分脚本示例,请参阅高吞吐量部署

注意

如想部署生成模型 (生成文件的模型) ,请参阅产生多个文件的模型部署中的如何编写评分脚本。

创建部署

评分脚本创建完成后,开始创建批处理部署。 按照以下步骤进行创建:

  1. 确保创建了一个可在其中创建部署的计算群集。 本示例将使用名为 gpu-cluster 的计算群集。 尽管这不是必需的,但我们使用 GPU 来加快处理速度。

  2. 我们需要指出我们将在哪个环境中运行部署。 在本例中,模型在 TensorFlow 上运行。 Azure 机器学习已具备已安装所需软件的环境,我们可以使用此环境。 只需在conda.yml文件中添加几个依赖项即可。

    环境定义将包含在部署文件中。

compute: azureml:gpu-cluster
environment:
  name: tensorflow27-cuda11-gpu
  image: mcr.microsoft.com/azureml/curated/tensorflow-2.7-ubuntu20.04-py38-cuda11-gpu:latest

获取对环境的引用:

environment = Environment(
    name="tensorflow27-cuda11-gpu",
    conda_file="environment/conda.yml",
    image="mcr.microsoft.com/azureml/curated/tensorflow-2.7-ubuntu20.04-py38-cuda11-gpu:latest",
)
  1. 现在,创建部署。

    如需在创建的终结点下创建新部署,请创建如下所示的 YAML 配置。 可以检查额外属性中的完整批处理终结点 YAML 机构

$schema: https://azuremlschemas.azureedge.net/latest/batchDeployment.schema.json
endpoint_name: imagenet-classifier-batch
name: imagenet-classifier-resnetv2
description: A ResNetV2 model architecture for performing ImageNet classification in batch
type: model
model: azureml:imagenet-classifier@latest
compute: azureml:gpu-cluster
environment:
  name: tensorflow27-cuda11-gpu
  image: mcr.microsoft.com/azureml/curated/tensorflow-2.7-ubuntu20.04-py38-cuda11-gpu:latest
  conda_file: environment/conda.yaml
code_configuration:
  code: code/score-by-file
  scoring_script: batch_driver.py
resources:
  instance_count: 2
settings:
  max_concurrency_per_instance: 1
  mini_batch_size: 5
  output_action: append_row
  output_file_name: predictions.csv
  retry_settings:
    max_retries: 3
    timeout: 300
  error_threshold: -1
  logging_level: info

然后,用以下命令创建部署:

DEPLOYMENT_NAME="imagenet-classifier-resnetv2"
az ml batch-deployment create -f deployment.yml