커스텀 예측 루틴을 Vertex AI로 마이그레이션

이 페이지에서는 AI Platform에서 Vertex AI로 커스텀 예측 루틴(CPR) 배포를 마이그레이션하는 방법을 설명합니다.

특히 이 페이지에서는 AI Platform의 CPR 배포 시 다음 방법을 보여줍니다.

  • Vertex AI에 배포할 해당 커스텀 컨테이너를 만듭니다. 이 커스텀 컨테이너는 Vertex AI의 CPR로 만든 모든 커스텀 컨테이너와 같이 작동합니다.
  • 커스텀 컨테이너를 로컬에서 실행하고 테스트합니다.
  • Vertex AI Model Registry에 업로드합니다.
  • 모델을 Vertex AI 엔드포인트에 배포하여 온라인 예측을 제공합니다.

시작하기 전에

  • 다음 소프트웨어가 설치되어 있는지 확인합니다.

  • Vertex AI로 마이그레이션하려는 AI Platform 배포에 CPR의 모델 아티팩트와 커스텀 코드가 있어야 합니다.

  • 모델 아티팩트를 저장할 Cloud Storage 버킷이 있어야 합니다.

  • 프로젝트에서 Vertex AI API가 사용 설정되어 있는지 확인합니다.

    Vertex AI API 사용 설정

Vertex AI 배포를 위한 소스 폴더 준비

  1. model_artifacts라는 로컬 폴더를 만들고 AI Platform 배포의 CPR에서 모델 아티팩트를 복사합니다. AI Platform 모델에 CPR을 배포할 때 deployment_uri(또는 gcloud를 사용한 경우 --origin)에서 지정한 것과 동일한 모델 아티팩트여야 합니다.

  2. cpr_src_dir이라는 로컬 폴더를 만듭니다. 이 폴더에는 Vertex AI에서 배포할 커스텀 컨테이너를 빌드하는 데 사용되는 소스 배포 패키지, adapter.pyrequirements.txt(아래에 설명)가 저장됩니다.

  3. AI Platform에 CPR을 배포할 때 Predictor 클래스가 포함된 패키지를 포함하여 package_uris에서 제공한 모든 패키지를 복사합니다.

  4. AdapterPredictor(아래 참조)가 포함된 adapter.py 파일을 만들고 PREDICTION_CLASSPredictor의 정규화된 이름으로 설정합니다. 이 값은 AI Platform에 CPR을 배포할 때 prediction_class와 동일합니다.

    어댑터가 Vertex AI 인터페이스의 CPR과 호환되도록 AI Platform Predictor 인터페이스에서 CPR을 래핑합니다.

    import pydoc
    ​
    from google.cloud.aiplatform.utils import prediction_utils
    from google.cloud.aiplatform.prediction.predictor import Predictor
    ​
    # Fully qualified name of your CPR on CAIP Predictor class.
    PREDICTION_CLASS = "predictor.MyPredictor"
    ​
    class AdapterPredictor(Predictor):
      """Predictor implementation for adapting CPR on CAIP predictors."""
    ​
      def __init__(self):
          return
    ​
      def load(self, artifacts_uri: str):
          """Loads the model artifact.
    ​
          Args:
              artifacts_uri (str):
                  Required. The model artifacts path (may be local or on Cloud Storage).
          """
          prediction_utils.download_model_artifacts(artifacts_uri)
          custom_class = pydoc.locate(PREDICTION_CLASS)
          self._predictor = custom_class.from_path(".")
    ​
    ​
      def predict(self, instances):
          """Performs prediction.
    ​
          Args:
              instances (Any):
                  Required. The instance(s) used for performing prediction.
    ​
          Returns:
              Prediction results.
          """
          return self._predictor.predict(**instances)
    
  5. 모델의 종속 항목이 포함된 requirements.txt 파일을 만듭니다. 예를 들면 다음과 같습니다.

    # Required for model serving
    google-cloud-storage>=1.26.0,<2.0.0dev
    google-cloud-aiplatform[prediction]>=1.16.0
    
    # ML dependencies
    numpy>=1.16.0
    scikit-learn==0.20.2
    

    첫 번째 섹션에는 모델 제공에 필요한 종속 항목이 나열되어 있습니다.

    두 번째 섹션에는 모델 제공에 필요한 머신러닝 패키지(예: scikit-learn, xgboost, tensorflow 등)가 나와 있습니다. 이전에 모델 버전을 배포할 때 선택한 런타임 버전에 나열된 것과 동일한 버전의 라이브러리를 설치해야 합니다.

  6. 로컬 환경에 종속 항목 설치

    pip install -U --user -r cpr_src_dir/requirements.txt 
    

Cloud Storage에 모델 아티팩트 업로드

Cloud Storage에 모델 아티팩트 업로드

gsutil cp model_artifacts/* gs://BUCKET_NAME/MODEL_ARTIFACT_DIR

Artifact Registry 설정

Artifact Registry는 Docker 컨테이너 이미지를 저장하고 관리하는 데 사용됩니다.

  1. 프로젝트에서 Artifact Registry API가 사용 설정되어 있는지 확인합니다.

    Artifacts Registry API 사용 설정

  2. 저장소가 없는 경우 저장소를 만듭니다.

    gcloud artifacts repositories create {REPOSITORY} \
        --repository-format=docker \
        --location={REGION}
    
  3. 이미지를 푸시하거나 가져오려면 먼저 Docker가 Artifact Registry에 대한 요청을 인증하는 데 Google Cloud CLI를 사용하도록 구성해야 합니다.

    gcloud auth configure-docker {REGION}-docker.pkg.dev
    

커스텀 컨테이너 빌드, 테스트, 배포

다음 Python 스크립트는 Vertex AI SDK의 API를 사용하여 커스텀 컨테이너를 빌드, 테스트, 배포하는 방법을 보여줍니다. 스크립트 상단에 변수를 설정해야 합니다.

import json
import logging
import os

from google.cloud import aiplatform
from google.cloud.aiplatform.prediction import LocalModel
from cpr_src_dir.adapter import AdapterPredictor

##########################################################################
# CONFIGURE THE FOLLOWING
##########################################################################
# We recommend that you choose the region closest to you.
REGION = …
# Your project ID.
PROJECT_ID = …
# Name of the Artifact Repository to create or use.
REPOSITORY = …
# Name of the container image that will be pushed.
IMAGE = …
# Cloud Storage bucket where your model artifacts will be stored.
BUKCET_NAME = …
# Directory within the bucket where your model artifacts are stored.
MODEL_ARTIFACT_DIR = …
# Your model's input instances.
INSTANCES = …

##########################################################################
# Build the CPR custom container
##########################################################################
local_model = LocalModel.build_cpr_model(
    "cpr_src_dir",
    f"{REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}",
    predictor=AdapterPredictor,
    requirements_path="cpr_src_dir/requirements.txt",
    extra_packages=["cpr_src_dir/my_custom_code-0.1.tar.gz"],
)

##########################################################################
# Run and test the custom container locally
##########################################################################
logging.basicConfig(level=logging.INFO)

local_endpoint =
       local_model.deploy_to_local_endpoint(artifact_uri="model_artifacts")
local_endpoint.serve()

health_check_response = local_endpoint.run_health_check()

predict_response = local_endpoint.predict(
        request=json.dumps({"instances": INSTANCES}),
        headers={"Content-Type": "application/json"},
    )

local_endpoint.stop()

print(predict_response, predict_response.content)
print(health_check_response, health_check_response.content)
local_endpoint.print_container_logs(show_all=True)

##########################################################################
# Upload and deploy to Vertex
##########################################################################
local_model.push_image()

model = aiplatform.Model.upload(\
    local_model=local_model,
    display_name=MODEL_DISPLAY_NAME,
    artifact_uri=f"gs://{BUKCET_NAME}/{MODEL_ARTIFACT_DIR}",
)

endpoint = model.deploy(machine_type="n1-standard-4")

endpoint.predict(instances=INSTANCES)

Vertex AI 예측에 대해 자세히 알아봅니다.