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 にホストされているモデルから予測を行う必要があります。

  • エクスポートした表形式モデルは、Advanced Vector Extensions(AVX)命令セットをサポートする x86 アーキテクチャ CPU でのみ実行できます。

エクスポート プロセス

モデルをエクスポートする手順は以下のとおりです。

  1. 環境を設定します
  2. モデルをエクスポートします
  3. モデルサーバーを pull して実行します。
  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

Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。詳細については、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 には、長時間実行オペレーションに対して呼び出しを行うためのヘルパー メソッドが用意されています。詳細については、長時間実行オペレーションによる作業をご覧ください。

モデルサーバーを pull して実行する

このタスクでは、エクスポートしたモデルを Cloud Storage からダウンロードし、Docker コンテナを起動して、モデルが予測リクエストを受信できるようにします。

モデルサーバーを pull して実行するには:

  1. モデルを実行するマシンで、エクスポートしたモデルを保存するディレクトリに移動します。

  2. エクスポートしたモデルをダウンロードします。

    gcloud storage cp <var>gcs-destination</var> . --recursive
    

    ここで 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 イメージを pull します。

    sudo docker pull MODEL_SERVER_IMAGE
    

    pull するモデルサーバーのイメージは、エクスポートされたモデル ディレクトリの 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_REGIONuseurope、または 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 が、前に pull した 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
    }
  ]
}

次のステップ