AutoML 테이블 형식 모델 내보내기

이 페이지에서는 Vertex AI를 사용하여 AutoML 테이블 형식 모델을 Cloud Storage로 내보내고 온프레미스 서버 또는 다른 클라우드 제공업체에서 호스팅하는 서버에 모델을 다운로드한 다음 Docker를 사용하여 모델을 예측에 사용하는 방법을 설명합니다.

이미지 및 동영상 Edge 모델 내보내기에 대한 자세한 내용은 AutoML Edge 모델 내보내기를 참조하세요.

테이블 형식 모델을 내보낸 후 Vertex AI로 다시 가져오려면 Vertex AI로 모델 가져오기를 참조하세요.

제한사항

AutoML 테이블 형식 모델을 내보낼 때 다음과 같은 제한사항이 있습니다.

  • AutoML 테이블 형식 분류 및 회귀 모델만 내보낼 수 있습니다. AutoML 테이블 형식 예측 모델 내보내기는 지원되지 않습니다.

  • Vertex Explainable AI는 내보낸 테이블 형식 모델을 사용할 수 없습니다. Vertex Explainable AI를 사용해야 하는 경우 Vertex AI가 호스팅하는 모델에서 예측을 제공해야 합니다.

  • 내보낸 테이블 형식 모델은 고급 벡터 확장(AVX) 명령 집합을 지원하는 x86 아키텍처 CPU에서만 실행할 수 있습니다.

내보내기 프로세스

모델을 내보내의 단계는 다음과 같습니다.

  1. 환경을 설정합니다.
  2. 모델 내보내기
  3. 모델 서버 가져오기 및 실행
  4. 예측 요청

시작하기 전에

이 작업을 완료하려면 먼저 다음 작업을 완료해야 합니다.

모델 내보내기

콘솔

  1. Google Cloud 콘솔의 Vertex AI 섹션에서 모델 페이지로 이동합니다.

    모델 페이지로 이동

  2. 내보낼 테이블 형식 모델을 클릭하여 세부정보 페이지를 엽니다.

  3. 버튼 모음에서 내보내기를 클릭하여 모델을 내보냅니다.

  4. 원하는 위치에서 Cloud Storage 폴더를 선택하거나 만듭니다.

    버킷은 버킷 요구사항을 충족해야 합니다.

    모델은 최상위 수준 버킷으로 내보낼 수 없습니다. 1개 이상의 폴더 수준을 사용해야 합니다.

    최상의 결과를 얻으려면 빈 폴더를 새로 만드세요. 이후 단계에서 폴더의 전체 콘텐츠를 복사합니다.

  5. 내보내기를 클릭합니다.

    다음 섹션에서는 내보낸 모델을 서버로 다운로드합니다.

REST

모델을 Cloud Storage로 내보내려면 models.export 메서드를 사용합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 리전
  • PROJECT: 프로젝트 ID
  • MODEL_ID: 내보낼 모델의 ID입니다.
  • GCS_DESTINATION : Cloud Storage의 대상 폴더입니다. 예를 들면 gs://export-bucket/exports입니다.

    모델은 최상위 수준 버킷으로 내보낼 수 없습니다. 1개 이상의 폴더 수준을 사용해야 합니다.

    폴더는 버킷 요구사항을 준수해야 합니다.

    최상의 결과를 얻으려면 새 폴더를 만드세요. 이후 단계에서 폴더의 전체 콘텐츠를 복사합니다.

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export

JSON 요청 본문:

{
  "outputConfig": {
    "exportFormatId": "tf-saved-model",
    "artifactDestination": {
      "outputUriPrefix": "GCS_DESTINATION"
    }
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/models/MODEL_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.ExportModelOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-10-12T20:53:40.130785Z",
      "updateTime": "2020-10-12T20:53:40.130785Z"
    },
    "outputInfo": {
      "artifactOutputUri": "gs://OUTPUT_BUCKET/model-MODEL_ID/EXPORT_FORMAT/YYYY-MM-DDThh:mm:ss.sssZ"
    }
  }
}

Java

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Vertex AI Java API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.ExportModelOperationMetadata;
import com.google.cloud.aiplatform.v1.ExportModelRequest;
import com.google.cloud.aiplatform.v1.ExportModelResponse;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.cloud.aiplatform.v1.ModelServiceClient;
import com.google.cloud.aiplatform.v1.ModelServiceSettings;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ExportModelTabularClassificationSample {
  public static void main(String[] args)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    String gcsDestinationOutputUriPrefix = "gs://your-gcs-bucket/destination_path";
    String project = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    exportModelTableClassification(gcsDestinationOutputUriPrefix, project, modelId);
  }

  static void exportModelTableClassification(
      String gcsDestinationOutputUriPrefix, String project, String modelId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    ModelServiceSettings modelServiceSettings =
        ModelServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings)) {
      String location = "us-central1";
      ModelName modelName = ModelName.of(project, location, modelId);

      GcsDestination.Builder gcsDestination = GcsDestination.newBuilder();
      gcsDestination.setOutputUriPrefix(gcsDestinationOutputUriPrefix);
      ExportModelRequest.OutputConfig outputConfig =
          ExportModelRequest.OutputConfig.newBuilder()
              .setExportFormatId("tf-saved-model")
              .setArtifactDestination(gcsDestination)
              .build();

      OperationFuture<ExportModelResponse, ExportModelOperationMetadata> exportModelResponseFuture =
          modelServiceClient.exportModelAsync(modelName, outputConfig);
      System.out.format(
          "Operation name: %s\n", exportModelResponseFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      ExportModelResponse exportModelResponse =
          exportModelResponseFuture.get(300, TimeUnit.SECONDS);
      System.out.format(
          "Export Model Tabular Classification Response: %s", exportModelResponse.toString());
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Vertex AI Node.js API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const gcsDestinationOutputUriPrefix ='YOUR_GCS_DESTINATION_\
// OUTPUT_URI_PREFIX'; eg. "gs://<your-gcs-bucket>/destination_path"
// const modelId = 'YOUR_MODEL_ID';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Model Service Client library
const {ModelServiceClient} = require('@google-cloud/aiplatform');

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

// Instantiates a client
const modelServiceClient = new ModelServiceClient(clientOptions);

async function exportModelTabularClassification() {
  // Configure the name resources
  const name = `projects/${project}/locations/${location}/models/${modelId}`;
  // Configure the outputConfig resources
  const outputConfig = {
    exportFormatId: 'tf-saved-model',
    artifactDestination: {
      outputUriPrefix: gcsDestinationOutputUriPrefix,
    },
  };
  const request = {
    name,
    outputConfig,
  };

  // Export Model request
  const [response] = await modelServiceClient.exportModel(request);
  console.log(`Long running operation : ${response.name}`);

  // Wait for operation to complete
  await response.promise();
  console.log(`Export model response : ${JSON.stringify(response.result)}`);
}
exportModelTabularClassification();

Python

Python을 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참고 문서를 참조하세요.

from google.cloud import aiplatform_v1beta1

def export_model_tabular_classification_sample(
    project: str,
    model_id: str,
    gcs_destination_output_uri_prefix: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
    timeout: int = 300,
):
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform_v1beta1.ModelServiceClient(client_options=client_options)
    gcs_destination = {"output_uri_prefix": gcs_destination_output_uri_prefix}
    output_config = {
        "artifact_destination": gcs_destination,
        "export_format_id": "tf-saved-model",
    }
    name = client.model_path(project=project, location=location, model=model_id)
    response = client.export_model(name=name, output_config=output_config)
    print("Long running operation:", response.operation.name)
    print("output_info:", response.metadata.output_info)
    export_model_response = response.result(timeout=timeout)
    print("export_model_response:", export_model_response)

내보내기 작업 상태 가져오기

일부 요청은 완료하는 데 시간이 걸리는 장기 실행 작업을 시작합니다. 이러한 요청은 작업 상태를 보거나 작업을 취소하는 데 사용할 수 있는 작업 이름을 반환합니다. Vertex AI는 장기 실행 작업을 호출하는 도우미 메서드를 제공합니다. 자세한 내용은 장기 실행 작업 다루기를 참조하세요.

모델 서버 가져오기 및 실행

이 작업에서는 Cloud Storage에서 내보낸 모델을 다운로드하고 모델이 예측 요청을 수신할 수 있도록 Docker 컨테이너를 시작합니다.

모델 서버를 가져오고 실행하려면 다음 안내를 따르세요.

  1. 모델을 실행할 머신에서 내보낸 모델을 저장할 디렉터리로 변경합니다.

  2. 내보낸 모델을 다운로드합니다.

    gsutil cp -r <var>gcs-destination</var> .
    

    여기서 gcs-destination은 Cloud Storage에서 내보낸 모델의 위치 경로입니다.

    모델이 다음 경로 아래의 현재 디렉터리에 복사됩니다.

    ./model-<model-id>/tf-saved-model/<export-timestamp>

    경로에는 tf-saved-model 또는 custom-trained가 포함될 수 있습니다.

  3. 디렉터리 이름을 변경하여 타임스탬프를 제거합니다.

    mv model-<model-id>/tf-saved-model/<export-timestamp> model-<model-id>/tf-saved-model/<new-dir-name>
    

    타임스탬프는 Docker의 디렉터리를 무효 처리합니다.

  4. 모델 서버 Docker 이미지를 가져옵니다.

    sudo docker pull MODEL_SERVER_IMAGE
    

    가져올 모델 서버 이미지는 내보낸 모델 디렉터리의 environment.json 파일에 있습니다. 다음 경로를 따라야 합니다.

    ./model-<model-id>/tf-saved-model/<new-dir-name>/environment.json

    environment.json 파일이 없으면 다음을 사용합니다.

    MULTI_REGION-docker.pkg.dev/vertex-ai/automl-tabular/prediction-server-v1

    MULTI_REGIONus, europe 또는 asia로 바꿔 Docker 이미지를 가져올 Docker 저장소를 선택합니다. 각 저장소에서 동일한 Docker 이미지를 제공하지만 Docker를 실행하는 머신에 가장 가까운 Artifact Registry 멀티 리전을 선택하면 지연 시간이 줄어들 수 있습니다.

  5. 위에서 생성한 디렉터리 이름을 사용하여 Docker 컨테이너를 시작합니다.

    docker run -v `pwd`/model-<model-id>/tf-saved-model/<new-dir-name>:/models/default -p 8080:8080 -it MODEL_SERVER_IMAGE
    

Ctrl-C을 사용하여 언제든지 모델 서버를 중지할 수 있습니다.

모델 서버 Docker 컨테이너 업데이트

모델을 내보낼 때 모델 서버 Docker 컨테이너를 다운로드하므로 모델 서버를 명시적으로 업데이트하여 업데이트 및 버그 수정을 적용해야 합니다. 다음 명령어를 사용하여 모델 서버를 주기적으로 업데이트해야 합니다.

docker pull MODEL_SERVER_IMAGE

Docker 이미지 URI가 이전에 가져온 Docker 이미지의 URI와 일치하는지 확인합니다.

내보낸 모델에서 예측 가져오기

Vertex AI 이미지 컨테이너의 모델 서버는 예측 요청을 처리하고 예측 결과를 반환합니다.

내보내기 모델에서는 일괄 예측을 사용할 수 없습니다.

예측 데이터 형식

예측 요청에 대한 데이터(payload 필드)를 다음 JSON 형식으로 제공합니다.

{ "instances": [ { "column_name_1": value, "column_name_2": value, … } , … ] }

다음 예시에서는 범주형 열, 숫자 열, 구조체의 3개 열이 포함된 요청을 보여줍니다. 요청에는 2개의 행이 포함됩니다.

{
  "instances": [
    {
      "categorical_col": "mouse",
      "num_array_col": [
        1,
        2,
        3
      ],
      "struct_col": {
        "foo": "piano",
        "bar": "2019-05-17T23:56:09.05Z"
      }
    },
    {
      "categorical_col": "dog",
      "num_array_col": [
        5,
        6,
        7
      ],
      "struct_col": {
        "foo": "guitar",
        "bar": "2019-06-17T23:56:09.05Z"
      }
    }
  ]
}

예측 요청 수행

  1. 요청 데이터를 텍스트 파일(예: tmp/request.json)에 배치합니다.

    미니 배치 크기라고도 하는 예측 요청의 데이터 행 수는 예측 지연 시간 및 처리량에 영향을 줍니다. 미니 배치 크기가 클수록 지연 시간이 길어지고 처리량이 높습니다. 지연 시간을 줄이려면 미니 배치 크기를 줄이고, 처리량을 높이려면 미니 배치 크기를 늘립니다. 가장 일반적으로 사용되는 미니 배치 크기는 1, 32, 64, 128, 256, 512, 1024입니다.

  2. 예측을 요청합니다.

    curl -X POST --data @/tmp/request.json http://localhost:8080/predict
    

예측 결과 형식

결과 형식은 모델 목표에 따라 다릅니다.

분류 모델 결과

분류 모델(이진 및 멀티클래스)의 예측 결과는 타겟 열의 각 예상 값에 대한 확률 점수를 반환합니다. 점수 사용 방식을 결정해야 합니다. 예를 들어 제공된 점수에서 이진 분류를 가져오려면 임계값을 식별해야 합니다. 'A'와 'B'라는 2개의 클래스가 있을 때 'A' 점수가 선택한 임계값보다 크다면 예시를 'A'로 분류하고, 그 외의 경우에는 'B'로 분류해야 합니다. 클래스의 균형이 맞지 않으면 임계값이 100% 또는 0%에 접근하게 됩니다.

분류 모델의 결과 페이로드는 다음 예시와 유사하게 나타납니다.

{
  "predictions": [
    {
      "scores": [
        0.539999994635582,
        0.2599999845027924,
        0.2000000208627896
      ],
      "classes": [
        "apple",
        "orange",
        "grape"
      ]
    },
    {
      "scores": [
        0.23999999463558197,
        0.35999998450279236,
        0.40000002086278963
      ],
      "classes": [
        "apple",
        "orange",
        "grape"
      ]
    }
  ]
}

회귀 모델 결과

예측 값은 예측 요청의 유효한 행별로 반환됩니다. 내보낸 모델에 대한 예측 간격은 반환되지 않습니다.

회귀 모델의 결과 페이로드는 다음 예시와 유사하게 나타납니다.

{
  "predictions": [
    {
      "value": -304.3663330078125,
      "lower_bound": -56.32196807861328,
      "upper_bound": 126.51904296875
    },
    {
      "value": -112.3663330078125,
      "lower_bound": 16.32196807861328,
      "upper_bound": 255.51904296875
    }
  ]
}

다음 단계