Vertex AI にモデルをインポートする

このガイドでは、モデル レジストリにモデルをインポートする方法について説明します。モデルをインポートすると、モデル レジストリに表示されます。モデル レジストリから、インポートしたモデルをエンドポイントにデプロイし、予測を実行できます。

必要なロール

モデルをインポートするために必要な権限を取得するには、プロジェクトに対する Vertex AI ユーザー roles/aiplatform.user)IAM ロールの付与を管理者に依頼してください。 ロールの付与の詳細については、アクセス権の管理をご覧ください。

必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

ビルド済みコンテナまたはカスタム コンテナ

モデルをインポートするときに、Vertex AI が予測リクエストを実行するためにモデルをコンテナに関連付けます。Vertex AI が提供するビルド済みコンテナを使用することも、独自のカスタム コンテナをビルドして Artifact Registry に push することもできます。

モデルが次の要件を満たしている場合、ビルド済みコンテナを使用できます。

以前にエクスポートした表形式の AutoML モデルをインポートする場合は、Vertex AI が提供する特定のカスタム コンテナを使用する必要があります。

それ以外の場合は、新しいカスタム コンテナを作成するか、Artifact Registry 内の既存のカスタム コンテナを使用します。

モデル アーティファクトを Cloud Storage にアップロードする

モデルのアーティファクトは、使用しているリージョン エンドポイントと一致するリージョンの Cloud Storage バケットに保存する必要があります。

Cloud Storage バケットが別の Google Cloud プロジェクトにある場合、モデル アーティファクトを読み取るには、Vertex AI にアクセス権を付与する必要があります。

ビルド済みコンテナを使用する場合は、モデル アーティファクトのファイル名が次の例と完全に一致していることを確認します。

  • TensorFlow SavedModel: saved_model.pb
  • PyTorch: model.mar
  • scikit-learn: model.joblib または model.pkl
  • XGBoost: model.bstmodel.joblibmodel.pkl

詳しくは、予測に使用するモデル アーティファクトのエクスポートをご覧ください。

Google Cloud コンソールを使用してモデルをインポートする

Google Cloud コンソールを使用してモデルをインポートするには:

  1. Google Cloud コンソールで、Vertex AI の [モデル] ページに移動します。

    [モデル] ページに移動

  2. [インポート] をクリックします。

  3. 新しいモデルをインポートするには、[新しいモデルとしてインポート] を選択します。

  4. モデルを既存のモデルのバージョンとしてインポートするには、[新しいバージョンとしてインポート] を選択します。モデルのバージョニングの詳細については、モデルのバージョニングをご覧ください。

  5. 名前とリージョン: モデルの名前を入力します。バケットのリージョンと、使用している Vertex AI リージョン エンドポイントの両方に一致するリージョンを選択します。[続行] をクリックします。

  6. [詳細オプション] を開くと、必要に応じて顧客管理の暗号鍵を追加できます。

使用しているコンテナの種類に応じて、該当するタブを選択してください。

ビルド済みコンテナ

  1. [新しいビルド済みコンテナにモデル アーティファクトをインポートする] を選択します。

  2. モデルのトレーニングに使用したモデル フレームワークモデル フレームワークのバージョンを選択します。

  3. GPU を使用して予測を行う場合は、[アクセラレータ タイプ] を [GPU] に設定します。

    GPU のタイプは、後でモデルをエンドポイントにデプロイするときに選択します。

  4. モデル アーティファクトを含むディレクトリの Cloud Storage パスを指定します。

    例: gs://BUCKET_NAME/models/

  5. [予測スキマータ] は空白のままにします。

  6. Vertex Explainable AI の設定を使用せずにモデルをインポートするには、[インポート] をクリックします。

    インポートが完了すると、[モデル] ページにモデルが表示されます。

    それ以外の場合は、[説明可能性] タブに説明可能性の設定を入力して、モデルの構成を続けます。詳細については、説明可能性の設定をご覧ください。

カスタム コンテナ

  1. [既存のカスタム コンテナをインポート] を選択します。

  2. コンテナ イメージの URI を設定します。

  3. コンテナ イメージに加えてモデル アーティファクトも含める場合は、モデル アーティファクトが格納されたディレクトリの Cloud Storage パスを指定します。

    例: gs://BUCKET_NAME/models/

  4. その他のフィールドに値を指定します。

    詳細については、省略可能なフィールドをご覧ください。

  5. Vertex Explainable AI の設定を使用せずにモデルをインポートするには、[インポート] をクリックします。

    インポートが完了すると、[モデル] ページにモデルが表示されます。

    それ以外の場合は、[説明可能性] タブに説明可能性の設定を入力して、モデルの構成を続けます。詳細については、説明可能性の設定をご覧ください。

AutoML 表形式のコンテナ

  1. [既存のカスタム コンテナをインポート] を選択します。

  2. [コンテナ イメージ] フィールドに「MULTI_REGION-docker.pkg.dev/vertex-ai/automl-tabular/prediction-server-v1:latest」と入力します。

    MULTI_REGIONuseurope、または asia に置き換え、Docker イメージの取得元となる Docker リポジトリを選択します。各リポジトリは同じ Docker イメージを提供しますが、Docker を実行しているマシンに最も近い Artifact Registry マルチリージョンを選択すると、レイテンシが短縮される可能性があります。

  3. [パッケージの場所] フィールドに、モデル アーティファクトが格納されているディレクトリの Cloud Storage パスを指定します。

    パスは次の例のようになります。

    gs://BUCKET_NAME/models-MODEL_ID/tf-saved-model/TIMESTAMP/

  4. その他のフィールドは空欄のままにします。

  5. [インポート] をクリックします。

    インポートが完了すると、[モデル] ページにモデルが表示されます。このモデルは他の AutoML 表形式モデルと同じように使用できますが、インポートした AutoML 表形式モデルでは Vertex Explainable AI がサポートされません。

モデルをプログラムでインポートする

次の例は、さまざまなツールを使用してモデルをインポートする方法を示しています。

gcloud

次の例では、gcloud ai models upload コマンドを使用します。

gcloud ai models upload \
  --region=LOCATION \
  --display-name=MODEL_NAME \
  --container-image-uri=IMAGE_URI \
  --artifact-uri=PATH_TO_MODEL_ARTIFACT_DIRECTORY

次のように置き換えます。

  • LOCATION_ID: Vertex AI を使用するリージョン。
  • MODEL_NAME: Model の表示名。
  • IMAGE_URI: 予測に使用するコンテナ イメージの URI。例: us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-1:latestビルド済みコンテナまたはカスタム コンテナを使用します。
  • PATH_TO_MODEL_ARTIFACT_DIRECTORY: モデル アーティファクトを含む Cloud Storage 内のディレクトリの Cloud Storage URI(gs:// で始まります)。

上の例は、ほとんどのモデルのインポートで必要になるフラグを示しています。ビルド済みコンテナを予測に使用しない場合は、Vertex AI がコンテナ イメージを使用できるように、追加のオプション フラグの指定が必要になることがあります。これらのフラグは --container- で始まり、ModelcontainerSpec のフィールドに対応します。

REST

次のコードサンプルを使用して、model リソースの upload メソッドを使用してモデルをアップロードします。

リクエストのデータを使用する前に、次のように置き換えます。

  • LOCATION_ID: Vertex AI を使用するリージョン。
  • PROJECT_ID: 実際のプロジェクト ID。
  • MODEL_NAME: Model の表示名。
  • MODEL_DESCRIPTION: 省略可。モデルの説明。
  • IMAGE_URI: 予測に使用するコンテナ イメージの URI。例: us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-1:latestビルド済みコンテナまたはカスタム コンテナを使用します。
  • PATH_TO_MODEL_ARTIFACT_DIRECTORY: モデル アーティファクトを含む Cloud Storage 内のディレクトリの Cloud Storage URI(gs:// で始まります)。カスタム コンテナを使用している場合、この変数と artifactUri フィールドは省略可能です。
  • labels: 省略可。モデルを整理するための任意の Key-Value ペアのセット。例:
    • "env": "prod"
    • "tier": "backend"
  • このトレーニング パイプラインに適用するラベルの LABEL_NAMELABEL_VALUE を指定します。

HTTP メソッドと URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/models:upload

JSON 本文のリクエスト:

{
  "model": {
    "displayName": "MODEL_NAME",
    "predictSchemata": {},
    "containerSpec": {
      "imageUri": "IMAGE_URI"
    },
    "artifactUri": "PATH_TO_MODEL_ARTIFACT_DIRECTORY",
    "labels": {
      "LABEL_NAME_1": "LABEL_VALUE_1",
      "LABEL_NAME_2": "LABEL_VALUE_2"
    }
  }
}

リクエストを送信するには、次のいずれかのオプションを選択します。

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_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/models:upload"

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_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/models:upload" | Select-Object -Expand Content

Java

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Java の設定手順を完了してください。詳細については、Vertex AI Java API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.Model;
import com.google.cloud.aiplatform.v1.ModelContainerSpec;
import com.google.cloud.aiplatform.v1.ModelServiceClient;
import com.google.cloud.aiplatform.v1.ModelServiceSettings;
import com.google.cloud.aiplatform.v1.UploadModelOperationMetadata;
import com.google.cloud.aiplatform.v1.UploadModelResponse;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UploadModelSample {
  public static void main(String[] args)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String modelDisplayName = "YOUR_MODEL_DISPLAY_NAME";
    String metadataSchemaUri =
        "gs://google-cloud-aiplatform/schema/trainingjob/definition/custom_task_1.0.0.yaml";
    String imageUri = "YOUR_IMAGE_URI";
    String artifactUri = "gs://your-gcs-bucket/artifact_path";
    uploadModel(project, modelDisplayName, metadataSchemaUri, imageUri, artifactUri);
  }

  static void uploadModel(
      String project,
      String modelDisplayName,
      String metadataSchemaUri,
      String imageUri,
      String artifactUri)
      throws IOException, InterruptedException, ExecutionException, 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";
      LocationName locationName = LocationName.of(project, location);

      ModelContainerSpec modelContainerSpec =
          ModelContainerSpec.newBuilder().setImageUri(imageUri).build();

      Model model =
          Model.newBuilder()
              .setDisplayName(modelDisplayName)
              .setMetadataSchemaUri(metadataSchemaUri)
              .setArtifactUri(artifactUri)
              .setContainerSpec(modelContainerSpec)
              .build();

      OperationFuture<UploadModelResponse, UploadModelOperationMetadata> uploadModelResponseFuture =
          modelServiceClient.uploadModelAsync(locationName, model);
      System.out.format(
          "Operation name: %s\n", uploadModelResponseFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      UploadModelResponse uploadModelResponse = uploadModelResponseFuture.get(5, TimeUnit.MINUTES);

      System.out.println("Upload Model Response");
      System.out.format("Model: %s\n", uploadModelResponse.getModel());
    }
  }
}

Node.js

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Node.js の設定手順を完了してください。詳細については、Vertex AI Node.js API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 */

// const modelDisplayName = 'YOUR_MODEL_DISPLAY_NAME';
// const metadataSchemaUri = 'YOUR_METADATA_SCHEMA_URI';
// const imageUri = 'YOUR_IMAGE_URI';
// const artifactUri = 'YOUR_ARTIFACT_URI';
// 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 uploadModel() {
  // Configure the parent resources
  const parent = `projects/${project}/locations/${location}`;
  // Configure the model resources
  const model = {
    displayName: modelDisplayName,
    metadataSchemaUri: '',
    artifactUri: artifactUri,
    containerSpec: {
      imageUri: imageUri,
      command: [],
      args: [],
      env: [],
      ports: [],
      predictRoute: '',
      healthRoute: '',
    },
  };
  const request = {
    parent,
    model,
  };

  console.log('PARENT AND MODEL');
  console.log(parent, model);
  // Upload Model request
  const [response] = await modelServiceClient.uploadModel(request);
  console.log(`Long running operation : ${response.name}`);

  // Wait for operation to complete
  await response.promise();
  const result = response.result;

  console.log('Upload model response ');
  console.log(`\tModel : ${result.model}`);
}
uploadModel();

Vertex AI SDK for Python

Vertex AI SDK for Python をインストールまたは更新する方法については、Vertex AI SDK for Python をインストールするをご覧ください。詳細については、Vertex AI SDK for Python API のリファレンス ドキュメントをご覧ください。

def upload_model_sample(
    project: str,
    location: str,
    display_name: str,
    serving_container_image_uri: str,
    artifact_uri: Optional[str] = None,
    serving_container_predict_route: Optional[str] = None,
    serving_container_health_route: Optional[str] = None,
    description: Optional[str] = None,
    serving_container_command: Optional[Sequence[str]] = None,
    serving_container_args: Optional[Sequence[str]] = None,
    serving_container_environment_variables: Optional[Dict[str, str]] = None,
    serving_container_ports: Optional[Sequence[int]] = None,
    instance_schema_uri: Optional[str] = None,
    parameters_schema_uri: Optional[str] = None,
    prediction_schema_uri: Optional[str] = None,
    explanation_metadata: Optional[explain.ExplanationMetadata] = None,
    explanation_parameters: Optional[explain.ExplanationParameters] = None,
    sync: bool = True,
):

    aiplatform.init(project=project, location=location)

    model = aiplatform.Model.upload(
        display_name=display_name,
        artifact_uri=artifact_uri,
        serving_container_image_uri=serving_container_image_uri,
        serving_container_predict_route=serving_container_predict_route,
        serving_container_health_route=serving_container_health_route,
        instance_schema_uri=instance_schema_uri,
        parameters_schema_uri=parameters_schema_uri,
        prediction_schema_uri=prediction_schema_uri,
        description=description,
        serving_container_command=serving_container_command,
        serving_container_args=serving_container_args,
        serving_container_environment_variables=serving_container_environment_variables,
        serving_container_ports=serving_container_ports,
        explanation_metadata=explanation_metadata,
        explanation_parameters=explanation_parameters,
        sync=sync,
    )

    model.wait()

    print(model.display_name)
    print(model.resource_name)
    return model

Vertex Explainable AI の設定を有効にしてモデルをインポートするには、Vertex Explainable AI モデルのインポート例をご覧ください。

オペレーションのステータスの取得

一部のリクエストでは、完了までに長時間かかるオペレーションが実行されます。このようなリクエストではオペレーション名が返されます。そのオペレーション名を使用して、オペレーションのステータス確認やキャンセルを行うことができます。Vertex AI には、長時間実行オペレーションに対して呼び出しを行うためのヘルパー メソッドが用意されています。詳細については、長時間実行オペレーションによる作業をご覧ください。

制限事項

  • サポートされているモデルの最大サイズは 10 GiB です。

次のステップ