Обновление конечных точек развертывания до пакета SDK версии 2

С помощью пакета SDK или CLI версии 1 модели можно развертывать в ACI или AKS в качестве веб-служб. Существующие развертывания моделей версии 1 и веб-службы будут работать как есть, но использование пакета SDK или CLI версии 1 для развертывания моделей в ACI или AKS в качестве веб-служб теперь считается устаревшим. Для развертываний новых моделей рекомендуется выполнить обновление до версии 2.

В версии 2 мы предлагаем управляемые конечные точки или конечные точки Kubernetes. Сравнение версий 1 и 2 см. в разделе Конечные точки и развертывание.

Существует несколько воронок развертывания, таких как управляемые сетевые конечные точки, сетевые конечные точки Kubernetes (включая Службы Azure Kubernetes и Kubernetes с поддержкой Arc) в версии 2, а также веб-службы Экземпляры контейнеров Azure (ACI) и Службы Kubernetes (AKS) в версии 1. В этой статье мы рассмотрим сравнение развертывания в веб-службах ACI (версия 1) и управляемых сетевых конечных точках (версия 2).

В примерах этой статьи показано, как:

  • Развертывание модели в Azure
  • Оценка с помощью конечной точки
  • Удаление веб-службы или конечной точки

Создание ресурсов вывода

  • Пакет SDK версии 1
    1. Настройка модели, среды и скрипта оценки:

      # configure a model. example for registering a model 
      from azureml.core.model import Model
      model = Model.register(ws, model_name="bidaf_onnx", model_path="./model.onnx")
      
      # configure an environment
      from azureml.core import Environment
      env = Environment(name='myenv')
      python_packages = ['nltk', 'numpy', 'onnxruntime']
      for package in python_packages:
          env.python.conda_dependencies.add_pip_package(package)
      
      # configure an inference configuration with a scoring script
      from azureml.core.model import InferenceConfig
      inference_config = InferenceConfig(
          environment=env,
          source_directory="./source_dir",
          entry_script="./score.py",
      )
      
    2. Настройка и развертывание веб-службы ACI:

      from azureml.core.webservice import AciWebservice
      
      # defince compute resources for ACI
      deployment_config = AciWebservice.deploy_configuration(
          cpu_cores=0.5, memory_gb=1, auth_enabled=True
      )
      
      # define an ACI webservice
      service = Model.deploy(
          ws,
          "myservice",
          [model],
          inference_config,
          deployment_config,
          overwrite=True,
      )
      
      # create the service 
      service.wait_for_deployment(show_output=True)
      

Дополнительные сведения о регистрации моделей см. в разделе Регистрация модели из локального файла.

  • Пакет SDK версии 2

    1. Настройка модели, среды и скрипта оценки:

      from azure.ai.ml.entities import Model
      # configure a model
      model = Model(path="../model-1/model/sklearn_regression_model.pkl")
      
      # configure an environment
      from azure.ai.ml.entities import Environment
      env = Environment(
          conda_file="../model-1/environment/conda.yml",
          image="mcr.microsoft.com/azureml/openmpi3.1.2-ubuntu18.04:20210727.v1",
      )
      
      # configure an inference configuration with a scoring script
      from azure.ai.ml.entities import CodeConfiguration
      code_config = CodeConfiguration(
              code="../model-1/onlinescoring", scoring_script="score.py"
          )
      
    2. Настройка и создание сетевой конечной точки:

      import datetime
      from azure.ai.ml.entities import ManagedOnlineEndpoint
      
      # create a unique endpoint name with current datetime to avoid conflicts
      online_endpoint_name = "endpoint-" + datetime.datetime.now().strftime("%m%d%H%M%f")
      
      # define an online endpoint
      endpoint = ManagedOnlineEndpoint(
          name=online_endpoint_name,
          description="this is a sample online endpoint",
          auth_mode="key",
          tags={"foo": "bar"},
      )
      
      # create the endpoint:
      ml_client.begin_create_or_update(endpoint)
      
    3. Настройте и создайте развертывание в сети:

      from azure.ai.ml.entities import ManagedOnlineDeployment
      
      # define a deployment
      blue_deployment = ManagedOnlineDeployment(
          name="blue",
          endpoint_name=online_endpoint_name,
          model=model,
          environment=env,
          code_configuration=code_config,
          instance_type="Standard_F2s_v2",
          instance_count=1,
      )
      
      # create the deployment:
      ml_client.begin_create_or_update(blue_deployment)
      
      # blue deployment takes 100 traffic
      endpoint.traffic = {"blue": 100}
      ml_client.begin_create_or_update(endpoint)
      

Дополнительные сведения о концепциях конечных точек и развертываний см. в статье Что такое сетевые конечные точки?

Отправка запроса

  • Пакет SDK версии 1

    import json
    data = {
        "query": "What color is the fox",
        "context": "The quick brown fox jumped over the lazy dog.",
    }
    data = json.dumps(data)
    predictions = service.run(input_data=data)
    print(predictions)
    
  • Пакет SDK версии 2

    # test the endpoint (the request will route to blue deployment as set above)
    ml_client.online_endpoints.invoke(
        endpoint_name=online_endpoint_name,
        request_file="../model-1/sample-request.json",
    )
    
    # test the specific (blue) deployment
    ml_client.online_endpoints.invoke(
        endpoint_name=online_endpoint_name,
        deployment_name="blue",
        request_file="../model-1/sample-request.json",
    )
    

Удаление ресурсов

  • Пакет SDK версии 1

    service.delete()
    
  • Пакет SDK версии 2

    ml_client.online_endpoints.begin_delete(name=online_endpoint_name)
    

Сопоставление основных функциональных возможностей в пакетах SDK версии 1 и SDK версии 2

Функциональные возможности пакета SDK версии 1 Грубое сопоставление в пакете SDK версии 2
Класс azureml.core.model.Model Класс azure.ai.ml.entities.Model
Класс azureml.core.Environment Класс azure.ai.ml.entities.Environment
Класс azureml.core.model.InferenceConfig Класс azure.ai.ml.entities.CodeConfiguration
Класс azureml.core.webservice.AciWebservice класс azure.ai.ml.entities.OnlineDeploymentкласс azure.ai.ml.entities.ManagedOnlineEndpoint)
Model.deploy или Webservice.deploy ml_client.begin_create_or_update(online_deployment)
Webservice.run ml_client.online_endpoints.invoke
Webservice.delete ml_client.online_endpoints.delete

Дополнительные сведения см. в разделе

Документация по версии 2:

Документация версии 1: