등록된 R 모델을 온라인(실시간) 엔드포인트에 배포하는 방법

적용 대상:Azure CLI ml 확장 v2(현재)

이 문서에서는 애플리케이션이 거의 실시간으로 모델에 대해 새 데이터의 점수를 매기도록 관리형 엔드포인트(Web API)에 R 모델을 배포하는 방법을 알아봅니다.

필수 조건

이 구조를 사용하여 폴더 만들기

프로젝트에 대해 다음 폴더 구조 만들기:

📂 r-deploy-azureml
 ├─📂 docker-context
 │  ├─ Dockerfile
 │  └─ start_plumber.R
 ├─📂 src
 │  └─ plumber.R
 ├─ deployment.yml
 ├─ endpoint.yml

이러한 파일의 각 내용은 이 문서에 표시되고 설명되어 있습니다.

Dockerfile

컨테이너 환경을 정의하는 파일입니다. 또한 여기에서 추가 R 패키지의 설치를 정의하기도 합니다.

샘플 Dockerfile은 다음과 같습니다.

# REQUIRED: Begin with the latest R container with plumber
FROM rstudio/plumber:latest

# REQUIRED: Install carrier package to be able to use the crated model (whether from a training job
# or uploaded)
RUN R -e "install.packages('carrier', dependencies = TRUE, repos = 'https://cloud.r-project.org/')"

# OPTIONAL: Install any additional R packages you may need for your model crate to run
RUN R -e "install.packages('<PACKAGE-NAME>', dependencies = TRUE, repos = 'https://cloud.r-project.org/')"
RUN R -e "install.packages('<PACKAGE-NAME>', dependencies = TRUE, repos = 'https://cloud.r-project.org/')"

# REQUIRED
ENTRYPOINT []

COPY ./start_plumber.R /tmp/start_plumber.R 

CMD ["Rscript", "/tmp/start_plumber.R"]

채점 스크립트에 필요한 패키지를 추가하도록 파일을 수정합니다.

plumber.R

Important

이 섹션에서는 plumber.R 스크립트를 구성하는 방법을 보여 줍니다. plumber 패키지에 대한 자세한 내용은 plumber설명서를 참조하세요.

파일 plumber.R은 채점 함수를 정의하는 R 스크립트입니다. 이 스크립트는 엔드포인트 작업을 수행하는 데 필요한 작업도 수행합니다. 이 스크립트는

  • 컨테이너의 AZUREML_MODEL_DIR 환경 변수에서 모델이 탑재되는 경로를 가져옵니다.
  • carrier 패키지에서 crate 함수를 사용하여 만든 모델 개체를 로드합니다. 이 개체는 패키지를 만들 때 crate.bin으로 저장됩니다.
  • 모델 개체의 초기화 해제
  • 채점 함수 정의

채점 함수가 생성하는 모든 것을 JSON으로 다시 변환할 수 있는지 확인합니다. 일부 R 개체는 쉽게 변환되지 않습니다.

# plumber.R
# This script will be deployed to a managed endpoint to do the model scoring

# REQUIRED
# When you deploy a model as an online endpoint, Azure Machine Learning mounts your model
# to your endpoint. Model mounting enables you to deploy new versions of the model without
# having to create a new Docker image.

model_dir <- Sys.getenv("AZUREML_MODEL_DIR")

# REQUIRED
# This reads the serialized model with its respecive predict/score method you 
# registered. The loaded load_model object is a raw binary object.
load_model <- readRDS(paste0(model_dir, "/models/crate.bin"))

# REQUIRED
# You have to unserialize the load_model object to make it its function
scoring_function <- unserialize(load_model)

# REQUIRED
# << Readiness route vs. liveness route >>
# An HTTP server defines paths for both liveness and readiness. A liveness route is used to
# check whether the server is running. A readiness route is used to check whether the 
# server's ready to do work. In machine learning inference, a server could respond 200 OK 
# to a liveness request before loading a model. The server could respond 200 OK to a
# readiness request only after the model has been loaded into memory.

#* Liveness check
#* @get /live
function() {
  "alive"
}

#* Readiness check
#* @get /ready
function() {
  "ready"
}

# << The scoring function >>
# This is the function that is deployed as a web API that will score the model
# Make sure that whatever you are producing as a score can be converted 
# to JSON to be sent back as the API response
# in the example here, forecast_horizon (the number of time units to forecast) is the input to scoring_function.  
# the output is a tibble
# we are converting some of the output types so they work in JSON


#* @param forecast_horizon 
#* @post /score
function(forecast_horizon) {
  scoring_function(as.numeric(forecast_horizon)) |> 
    tibble::as_tibble() |> 
    dplyr::transmute(period = as.character(yr_wk),
                     dist = as.character(logmove),
                     forecast = .mean) |> 
    jsonlite::toJSON()
}

start_plumber.R

파일 start_plumber. R은 컨테이너가 시작될 때 실행하는 R 스크립트이며 plumber.R 스크립트를 호출합니다. 다음 스크립트를 그대로 사용합니다.

entry_script_path <- paste0(Sys.getenv('AML_APP_ROOT'),'/', Sys.getenv('AZUREML_ENTRY_SCRIPT'))

pr <- plumber::plumb(entry_script_path)

args <- list(host = '0.0.0.0', port = 8000); 

if (packageVersion('plumber') >= '1.0.0') {
  pr$setDocs(TRUE)
} else { 
  args$swagger <- TRUE 
} 

do.call(pr$run, args)

컨테이너 빌드

이러한 단계에서는 첫 번째 사용자 지정 환경을 만들 때 만들어지는 작업 영역과 연결된 Azure Container Registry가 있다고 가정합니다. 사용자 지정 환경이 있는지 확인하려면 다음을 수행합니다.

  1. Azure Machine Learning Studio에 로그인합니다.
  2. 필요한 경우 작업 영역을 선택합니다.
  3. 왼쪽 탐색 메뉴에서 환경을 선택합니다.
  4. 맨 위에서 사용자 지정 환경을 선택합니다.
  5. 사용자 지정 환경이 표시되면 더 이상 필요한 것이 없습니다.
  6. 사용자 지정 환경이 표시되지 않으면 R 환경 또는 다른 사용자 지정 환경을 만듭니다. (배포를 위해 이 환경을 사용하지는 않지만 사용자를 위해 만들어진 컨테이너 레지스트리는 사용합니다.)

사용자 지정 환경이 하나 이상 있는지 확인한 후에는 다음 단계를 사용하여 컨테이너를 빌드합니다.

  1. 터미널 창을 열고 Azure에 로그인합니다. Azure Machine Learning 컴퓨팅 인스턴스에서 이 작업을 수행하는 경우 다음을 사용합니다.

    az login --identity
    

    컴퓨팅 인스턴스에 없는 경우에는 --identity를 생략하고 프롬프트에 따라 인증할 브라우저 창을 엽니다.

  2. 최신 버전의 CLI 및 ml 확장이 있는지 확인합니다.

    az upgrade
    
  3. Azure 구독이 여러 개 있는 경우 활성 구독을 작업 영역에 사용 중인 구독으로 설정합니다. (단일 구독에만 액세스할 수 있는 경우 이 단계를 건너뛸 수 있습니다.) <SUBSCRIPTION-NAME>을 구독 이름으로 바꿉니다. 또한 대괄호 <>를 제거합니다.

    az account set --subscription "<SUBSCRIPTION-NAME>"
    
  4. 기본 작업 영역을 설정합니다. 컴퓨팅 인스턴스에서 이 작업을 수행하는 경우 다음 명령을 있는 그대로 사용할 수 있습니다. 다른 컴퓨터에 있는 경우 리소스 그룹 및 작업 영역 이름을 대신 사용합니다. (이러한 값은 Azure Machine Learning 스튜디오에서 찾을 수 있습니다.)

    az configure --defaults group=$CI_RESOURCE_GROUP workspace=$CI_WORKSPACE
    
  5. 프로젝트 디렉터리에 있는지 확인합니다.

    cd r-deploy-azureml
    
  6. 클라우드에서 이미지를 빌드하려면 터미널에서 다음 bash 명령을 실행합니다. <IMAGE-NAME>을 이미지에 지정할 이름으로 바꿉니다.

    작업 영역이 가상 네트워크에 있는 경우 이 코드의 마지막 줄에 있는 az acr build 명령에 --image-build-compute를 추가하는 추가 단계는 ACR(Azure Container Registry)를 참조하세요.

    WORKSPACE=$(az config get --query "defaults[?name == 'workspace'].value" -o tsv)
    ACR_NAME=$(az ml workspace show -n $WORKSPACE --query container_registry -o tsv | cut -d'/' -f9-)
    IMAGE_TAG=${ACR_NAME}.azurecr.io/<IMAGE-NAME>
    
    az acr build ./docker-context -t $IMAGE_TAG -r $ACR_NAME
    

Important

이미지를 빌드하는 데 몇 분 정도 걸릴 수 있습니다. 빌드 프로세스가 완료될 때까지 기다렸다가 다음 섹션으로 진행합니다. 이 터미널을 닫지 말고 배포를 만드는 데 사용합니다.

az acr 명령은 이미지를 빌드할 아티팩트가 포함된 docker-context 폴더를 Azure Container Registry에서 이미지를 빌드하고 호스트하는 클라우드에 자동으로 업로드합니다.

모델 배포

문서의 이 섹션에서는 이전 단계에서 빌드된 모델 및 이미지를 관리형 온라인 엔드포인트에 배포하는 엔드포인트 및 배포를 정의하고 만듭니다.

엔드포인트는 클라이언트(예: 애플리케이션)가 학습된 모델의 채점 출력을 수신하기 위해 호출할 수 있는 HTTPS 엔드포인트입니다. 이 콘솔은 다음과 같은 기능을 제공합니다.

  • “키 및 토큰” 기반 인증을 사용하여 인증
  • SSL 종료
  • 안정적인 채점 URI(endpoint-name.region.inference.ml.Azure.com)

배포는 실제 채점을 수행하는 모델을 호스트하는 데 필요한 리소스 집합입니다. 단일 엔드포인트에는 여러 배포가 포함될 수 있습니다. Azure Machine Learning 관리형 엔드포인트의 부하 분산 기능을 사용하면 각 배포에 트래픽의 백분율을 제공할 수 있습니다. 트래픽 할당을 사용하여 여러 인스턴스로 요청을 분산하여 안전 롤아웃 파란색/녹색 배포를 수행할 수 있습니다.

관리형 온라인 엔드포인트 만들기

  1. 프로젝트 디렉터리에서 다음 코드를 사용하여 endpoint.yml 파일을 추가합니다. <ENDPOINT-NAME>을 관리형 엔드포인트로 바꿉니다.

    $schema: https://azuremlschemas.azureedge.net/latest/managedOnlineEndpoint.schema.json
    name: <ENDPOINT-NAME>
    auth_mode: aml_token
    
  2. 이미지를 빌드한 동일한 터미널을 사용하여 다음 CLI 명령을 실행하면 엔드포인트를 만들 수 있습니다.

    az ml online-endpoint create -f endpoint.yml
    
  3. 다음 섹션에서 계속 사용하려면 터미널을 그대로 열어 두세요.

배포 만들기

  1. 배포를 만들려면 deployment.yml 파일에 다음 코드를 추가합니다.

    • <ENDPOINT-NAME>endpoint.yml 파일에 정의한 엔드포인트 이름으로 바꿉니다.

    • <DEPLOYMENT-NAME>을 배포에 지정할 이름으로 바꿉니다.

    • <MODEL-URI>azureml:modelname@latest의 형식으로 등록된 모델의 URI로 바꿉니다.

    • <IMAGE-TAG>를 다음 값으로 바꿉니다.

      echo $IMAGE_TAG
      
    $schema: https://azuremlschemas.azureedge.net/latest/managedOnlineDeployment.schema.json
    name: <DEPLOYMENT-NAME>
    endpoint_name: <ENDPOINT-NAME>
    code_configuration:
      code: ./src
      scoring_script: plumber.R
    model: <MODEL-URI>
    environment:
      image: <IMAGE-TAG>
      inference_config:
        liveness_route:
          port: 8000
          path: /live
        readiness_route:
          port: 8000
          path: /ready
        scoring_route:
          port: 8000
          path: /score
    instance_type: Standard_DS2_v2
    instance_count: 1
    
  2. 다음으로 터미널에서 다음 CLI 명령을 실행하여 배포를 만듭니다(이 모델에 대한 트래픽의 100% 설정).

    az ml online-deployment create -f deployment.yml --all-traffic --skip-script-validation
    

참고 항목

서비스를 배포하는 데 몇 분 정도 걸릴 수 있습니다. 다음 섹션으로 진행하기 전에 배포가 완료될 때까지 기다립니다.

테스트

배포가 성공적으로 만들어지면 스튜디오 또는 CLI를 사용하여 엔드포인트를 테스트할 수 있습니다.

Azure Machine Learning 스튜디오로 이동하여 왼쪽 메뉴 엔드포인트에서 선택합니다. 다음으로, 이전에 만든 r-endpoint-iris를 선택합니다.

다음 json을 실시간 엔드포인트에 대한 입력 데이터에 입력합니다.

{
    "forecast_horizon" : [2]
}

테스트를 선택합니다. 다음과 같은 출력이 표시됩니다.

Screenshot shows results from testing a model.

리소스 정리

엔드포인트를 사용하여 성공적으로 점수를 매겼으므로 지속적인 비용이 발생하지 않도록 삭제할 수 있습니다.

az ml online-endpoint delete --name r-endpoint-forecast

다음 단계

Azure Machine Learning에서 R을 사용하는 방법에 대한 자세한 내용은 Azure Machine Learning의 R 기능 개요를 참조하세요.