Model Garden と Vertex AI GPU 対応エンドポイントを使用して Gemma をデプロイして推論する

このチュートリアルでは、Model Garden を使用して、GPU をベースとする Vertex AI エンドポイントに Gemma 1B オープンモデルをデプロイします。オンライン予測用にモデルを配信する前に、モデルをエンドポイントにデプロイする必要があります。モデルのデプロイでは、少ないレイテンシでオンライン予測を提供できるように、モデルに物理リソースを関連付けます。

Gemma 1B モデルをデプロイしたら、PredictionServiceClient を使用してトレーニング済みモデルを推論し、オンライン予測を取得します。オンライン予測は、エンドポイントにデプロイされたモデルに対して行われる同期リクエストです。

目標

このチュートリアルでは、次のタスクを行う方法について説明します。

  • Model Garden を使用して、Gemma 1B オープンモデルを GPU ベースのエンドポイントにデプロイする
  • PredictionServiceClient を使用してオンライン予測を取得する

費用

このドキュメントでは、課金対象である次の Google Cloudコンポーネントを使用します。

料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。

新規の Google Cloud ユーザーは無料トライアルをご利用いただける場合があります。

このドキュメントに記載されているタスクの完了後、作成したリソースを削除すると、それ以上の請求は発生しません。詳細については、クリーンアップをご覧ください。

始める前に

このチュートリアルでは、次の作業が必要です。

  • Google Cloud プロジェクトを設定し、Vertex AI API を有効にする
  • ローカルマシンで以下を行います。
    • Google Cloud CLI をインストール、初期化、認証する
    • 言語の SDK をインストールする

Google Cloud プロジェクトの設定

Google Cloud プロジェクトを設定し、Vertex AI API を有効にします。

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  8. Google Cloud CLI を設定する

    ローカルマシンで Google Cloud CLI を設定します。

    1. Google Cloud CLI をインストールして初期化する

    2. すでに gcloud CLI をインストールしている場合は、このコマンドを実行して gcloud コンポーネントが更新されていることを確認します。

      gcloud components update
    3. gcloud CLI で認証するには、次のコマンドを実行してローカルのアプリケーションのデフォルト認証情報(ADC)ファイルを生成します。コマンドで起動されたウェブフローを使用して、ユーザー認証情報を提供します。

      gcloud auth application-default login

      詳細については、gcloud CLI 認証構成と ADC 構成をご覧ください。

    プログラミング言語の SDK を設定する

    このチュートリアルで使用する環境を設定するには、使用する言語の Vertex AI SDK とプロトコル バッファ ライブラリをインストールします。コードサンプルでは、プロトコル バッファ ライブラリの関数を使用して、入力ディクショナリを API が想定する JSON 形式に変換します。

    ローカルマシンで、次のいずれかのタブをクリックして、プログラミング言語の SDK をインストールします。

    Python

    ローカルマシンで、次のいずれかのタブをクリックして、プログラミング言語の SDK をインストールします。

    • 次のコマンドを実行して、Vertex AI SDK for Python をインストールして更新します。

      pip3 install --upgrade "google-cloud-aiplatform>=1.64"
    • 次のコマンドを実行して、Python 用のプロトコル バッファ ライブラリをインストールします。

      pip3 install --upgrade "protobuf>=5.28"

    Node.js

    次のコマンドを実行して、Node.js 用の aiplatform SDK をインストールまたは更新します。

    npm install @google-cloud/aiplatform

    Java

    google-cloud-aiplatform を依存関係として追加するには、環境に適したコードを追加します。

    BOM ありの Maven

    pom.xml に次の HTML を追加します。

    <dependencyManagement>
    <dependencies>
      <dependency>
        <artifactId>libraries-bom</artifactId>
        <groupId>com.google.cloud</groupId>
        <scope>import</scope>
        <type>pom</type>
        <version>26.34.0</version>
      </dependency>
    </dependencies>
    </dependencyManagement>
    <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-aiplatform</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java-util</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
    </dependency>
    </dependencies>

    BOM なしの Maven

    pom.xml に次の行を追加します。

    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-aiplatform</artifactId>
      <version>1.1.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java-util</artifactId>
      <version>5.28</version>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.11.0</version>
    </dependency>

    BOM なしの Gradle

    build.gradle に次の行を追加します。

    implementation 'com.google.cloud:google-cloud-aiplatform:1.1.0'

    Go

    次のコマンドを実行して、これらの Go パッケージをインストールします。

    go get cloud.google.com/go/aiplatform
    go get google.golang.org/protobuf
    go get github.com/googleapis/gax-go/v2

    Model Garden を使用して Gemma をデプロイする

    Gemma 1B は、 Google Cloud コンソールのモデルカードを使用する、あるいはプログラム使用することでデプロイできます。

    Google Gen AI SDK または Google Cloud CLI の設定の詳細については、Google Gen AI SDK の概要または Google Cloud CLI をインストールするをご覧ください。

    Python

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

    1. デプロイ可能なモデルを一覧で確認し、デプロイするモデルのモデル ID を記録します。必要に応じて、Model Garden でサポートされている Hugging Face モデルの一覧を表示して、モデル名でフィルタすることもできます。出力には、チューニングされたモデルは含まれません。

      
      import vertexai
      from vertexai import model_garden
      
      # TODO(developer): Update and un-comment below lines
      # PROJECT_ID = "your-project-id"
      vertexai.init(project=PROJECT_ID, location="us-central1")
      
      # List deployable models, optionally list Hugging Face models only or filter by model name.
      deployable_models = model_garden.list_deployable_models(list_hf_models=False, model_filter="gemma")
      print(deployable_models)
      # Example response:
      # ['google/gemma2@gemma-2-27b','google/gemma2@gemma-2-27b-it', ...]
      
    2. 前のステップのモデル ID を使用して、モデルのデプロイ仕様を確認します。Model Garden で特定のモデルに対して検証されたマシンタイプ、アクセラレータ タイプ、コンテナ イメージ URI を確認できます。

      
      import vertexai
      from vertexai import model_garden
      
      # TODO(developer): Update and un-comment below lines
      # PROJECT_ID = "your-project-id"
      # model = "google/gemma3@gemma-3-1b-it"
      vertexai.init(project=PROJECT_ID, location="us-central1")
      
      # For Hugging Face modelsm the format is the Hugging Face model name, as in
      # "meta-llama/Llama-3.3-70B-Instruct".
      # Go to https://console.cloud.google.com/vertex-ai/model-garden to find all deployable
      # model names.
      
      model = model_garden.OpenModel(model)
      deploy_options = model.list_deploy_options()
      print(deploy_options)
      # Example response:
      # [
      #   dedicated_resources {
      #     machine_spec {
      #       machine_type: "g2-standard-12"
      #       accelerator_type: NVIDIA_L4
      #       accelerator_count: 1
      #     }
      #   }
      #   container_spec {
      #     ...
      #   }
      #   ...
      # ]
      
    3. エンドポイントにモデルをデプロイします。引数と値を追加で指定しない限り、Model Garden はデフォルトのデプロイ構成を使用します。

      
      import vertexai
      from vertexai import model_garden
      
      # TODO(developer): Update and un-comment below lines
      # PROJECT_ID = "your-project-id"
      vertexai.init(project=PROJECT_ID, location="us-central1")
      
      open_model = model_garden.OpenModel("google/gemma3@gemma-3-12b-it")
      endpoint = open_model.deploy(
          machine_type="g2-standard-48",
          accelerator_type="NVIDIA_L4",
          accelerator_count=4,
          accept_eula=True,
      )
      
      # Optional. Run predictions on the deployed endoint.
      # endpoint.predict(instances=[{"prompt": "What is Generative AI?"}])
      

    gcloud

    始める前に、次のコマンドを実行する割り当てプロジェクトを指定します。実行したコマンドは、そのプロジェクトの割り当てに対してカウントされます。詳細については、割り当てプロジェクトを設定するをご覧ください。

    1. gcloud ai model-garden models list コマンドを実行して、デプロイ可能なモデルを一覧で確認します。このコマンドは、すべてのモデル ID と、セルフデプロイできるモデル ID を一覧で表示します。

      gcloud ai model-garden models list --model-filter=gemma
      

      デプロイするモデル ID を出力で確認します。次の例で示すのは、省略された出力です。

      MODEL_ID                                      CAN_DEPLOY  CAN_PREDICT
      google/gemma2@gemma-2-27b                     Yes         No
      google/gemma2@gemma-2-27b-it                  Yes         No
      google/gemma2@gemma-2-2b                      Yes         No
      google/gemma2@gemma-2-2b-it                   Yes         No
      google/gemma2@gemma-2-9b                      Yes         No
      google/gemma2@gemma-2-9b-it                   Yes         No
      google/gemma3@gemma-3-12b-it                  Yes         No
      google/gemma3@gemma-3-12b-pt                  Yes         No
      google/gemma3@gemma-3-1b-it                   Yes         No
      google/gemma3@gemma-3-1b-pt                   Yes         No
      google/gemma3@gemma-3-27b-it                  Yes         No
      google/gemma3@gemma-3-27b-pt                  Yes         No
      google/gemma3@gemma-3-4b-it                   Yes         No
      google/gemma3@gemma-3-4b-pt                   Yes         No
      google/gemma3n@gemma-3n-e2b                   Yes         No
      google/gemma3n@gemma-3n-e2b-it                Yes         No
      google/gemma3n@gemma-3n-e4b                   Yes         No
      google/gemma3n@gemma-3n-e4b-it                Yes         No
      google/gemma@gemma-1.1-2b-it                  Yes         No
      google/gemma@gemma-1.1-2b-it-gg-hf            Yes         No
      google/gemma@gemma-1.1-7b-it                  Yes         No
      google/gemma@gemma-1.1-7b-it-gg-hf            Yes         No
      google/gemma@gemma-2b                         Yes         No
      google/gemma@gemma-2b-gg-hf                   Yes         No
      google/gemma@gemma-2b-it                      Yes         No
      google/gemma@gemma-2b-it-gg-hf                Yes         No
      google/gemma@gemma-7b                         Yes         No
      google/gemma@gemma-7b-gg-hf                   Yes         No
      google/gemma@gemma-7b-it                      Yes         No
      google/gemma@gemma-7b-it-gg-hf                Yes         No
      

      出力には、チューニングされたモデルや Hugging Face モデルは含まれません。サポートされている Hugging Face モデルを確認するには、--can-deploy-hugging-face-models フラグを追加します。

    2. モデルのデプロイ仕様を確認するには、gcloud ai model-garden models list-deployment-config コマンドを実行します。Model Garden で特定のモデルでサポートされているマシンタイプ、アクセラレータ タイプ、コンテナ イメージ URI を確認できます。

      gcloud ai model-garden models list-deployment-config \
          --model=MODEL_ID
      

      MODEL_ID は、前の list コマンドで取得したモデル ID(google/gemma@gemma-2bstabilityai/stable-diffusion-xl-base-1.0 など)に置き換えます。

    3. gcloud ai model-garden models deploy コマンドを実行して、モデルをエンドポイントにデプロイします。引数と値を追加で指定しない限り、Model Garden はエンドポイントの表示名を生成し、デフォルトのデプロイ構成を使用します。

      コマンドを非同期で実行するには、--asynchronous フラグを含めます。

      gcloud ai model-garden models deploy \
          --model=MODEL_ID \
          [--machine-type=MACHINE_TYPE] \
          [--accelerator-type=ACCELERATOR_TYPE] \
          [--endpoint-display-name=ENDPOINT_NAME] \
          [--hugging-face-access-token=HF_ACCESS_TOKEN] \
          [--reservation-affinity reservation-affinity-type=any-reservation] \
          [--reservation-affinity reservation-affinity-type=specific-reservation, key="compute.googleapis.com/reservation-name", values=RESERVATION_RESOURCE_NAME] \
          [--asynchronous]
      

      各プレースホルダを次のように置き換えます。

      • MODEL_ID: 前の list コマンドのモデル ID。Hugging Face モデルの場合は、stabilityai/stable-diffusion-xl-base-1.0 などの Hugging Face モデル URL 形式を使用します。
      • MACHINE_TYPE: モデルにデプロイするリソースのセット(g2-standard-4 など)を定義します。
      • ACCELERATOR_TYPE: NVIDIA_L4 などの負荷の高いワークロードを処理する際のパフォーマンスを向上させるため、デプロイに追加するアクセラレータを指定します。
      • ENDPOINT_NAME: デプロイされた Vertex AI エンドポイントの名前。
      • HF_ACCESS_TOKEN: Hugging Face モデルにおいてモデルがゲートされている場合は、アクセス トークンを指定します。
      • RESERVATION_RESOURCE_NAME: 特定の Compute Engine 予約を使用するには、予約の名前を指定します。特定の予約を指定した場合、any-reservation は指定できません。

      出力には、Model Garden が使用したデプロイ構成、エンドポイント ID、デプロイ オペレーション ID が含まれます。デプロイ オペレーション ID を使用して、デプロイ ステータスを確認できます。

      Using the default deployment configuration:
       Machine type: g2-standard-12
       Accelerator type: NVIDIA_L4
       Accelerator count: 1
      
      The project has enough quota. The current usage of quota for accelerator type NVIDIA_L4 in region us-central1 is 0 out of 28.
      
      Deploying the model to the endpoint. To check the deployment status, you can try one of the following methods:
      1) Look for endpoint `ENDPOINT_DISPLAY_NAME` at the [Vertex AI] -> [Online prediction] tab in Cloud Console
      2) Use `gcloud ai operations describe OPERATION_ID --region=LOCATION` to find the status of the deployment long-running operation
      
    4. デプロイの詳細を確認するには、gcloud ai endpoints list --list-model-garden-endpoints-only コマンドを実行します。

      gcloud ai endpoints list --list-model-garden-endpoints-only \
          --region=LOCATION_ID
      

      LOCATION_ID は、モデルをデプロイしたリージョンに置き換えます。

      出力には、Model Garden から作成されたすべてのエンドポイントのほか、エンドポイント ID、エンドポイント名、エンドポイントがデプロイされたモデルに関連付けられているかどうかなどの情報が含まれます。デプロイを見つけるには、前のコマンドから返されたエンドポイント名を探します。

    REST

    デプロイ可能なすべてのモデルを一覧で確認し、デプロイするモデルの ID を取得します。その後、デフォルトの構成とエンドポイントを使用してモデルをデプロイできます。または、特定のマシンタイプの設定や専用エンドポイントの使用など、デプロイをカスタマイズすることもできます。

    デプロイできるモデルを一覧で確認する

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

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
    • QUERY_PARAMETERS: Model Garden モデルを一覧で確認するには、次のクエリ パラメータ listAllVersions=True&filter=can_deploy(true) を追加します。Hugging Face モデルを一覧で確認するには、フィルタを alt=json&is_hf_wildcard(true)+AND+labels.VERIFIED_DEPLOYMENT_CONFIG%3DVERIFIED_DEPLOYMENT_SUCCEED&listAllVersions=True に設定します。

    HTTP メソッドと URL:

    GET https://us-central1-aiplatform.googleapis.com/v1/publishers/*/models?QUERY_PARAMETERS

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

    curl

    次のコマンドを実行します。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "x-goog-user-project: PROJECT_ID" \
    "https://us-central1-aiplatform.googleapis.com/v1/publishers/*/models?QUERY_PARAMETERS"

    PowerShell

    次のコマンドを実行します。

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }

    Invoke-WebRequest `
    -Method GET `
    -Headers $headers `
    -Uri "https://us-central1-aiplatform.googleapis.com/v1/publishers/*/models?QUERY_PARAMETERS" | Select-Object -Expand Content

    次のような JSON レスポンスが返されます。

    {
      "publisherModels": [
        {
          "name": "publishers/google/models/gemma3",
          "versionId": "gemma-3-1b-it",
          "openSourceCategory": "GOOGLE_OWNED_OSS_WITH_GOOGLE_CHECKPOINT",
          "supportedActions": {
            "openNotebook": {
              "references": {
                "us-central1": {
                  "uri": "https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_gradio_streaming_chat_completions.ipynb"
                }
              },
              "resourceTitle": "Notebook",
              "resourceUseCase": "Chat Completion Playground",
              "resourceDescription": "Chat with deployed Gemma 2 endpoints via Gradio UI."
            },
            "deploy": {
              "modelDisplayName": "gemma-3-1b-it",
              "containerSpec": {
                "imageUri": "us-docker.pkg.dev/vertex-ai/vertex-vision-model-garden-dockers/pytorch-vllm-serve:20250312_0916_RC01",
                "args": [
                  "python",
                  "-m",
                  "vllm.entrypoints.api_server",
                  "--host=0.0.0.0",
                  "--port=8080",
                  "--model=gs://vertex-model-garden-restricted-us/gemma3/gemma-3-1b-it",
                  "--tensor-parallel-size=1",
                  "--swap-space=16",
                  "--gpu-memory-utilization=0.95",
                  "--disable-log-stats"
                ],
                "env": [
                  {
                    "name": "MODEL_ID",
                    "value": "google/gemma-3-1b-it"
                  },
                  {
                    "name": "DEPLOY_SOURCE",
                    "value": "UI_NATIVE_MODEL"
                  }
                ],
                "ports": [
                  {
                    "containerPort": 8080
                  }
                ],
                "predictRoute": "/generate",
                "healthRoute": "/ping"
              },
              "dedicatedResources": {
                "machineSpec": {
                  "machineType": "g2-standard-12",
                  "acceleratorType": "NVIDIA_L4",
                  "acceleratorCount": 1
                }
              },
              "publicArtifactUri": "gs://vertex-model-garden-restricted-us/gemma3/gemma3.tar.gz",
              "deployTaskName": "vLLM 128K context",
              "deployMetadata": {
                "sampleRequest": "{\n    \"instances\": [\n        {\n          \"@requestFormat\": \"chatCompletions\",\n          \"messages\": [\n              {\n                  \"role\": \"user\",\n                  \"content\": \"What is machine learning?\"\n              }\n          ],\n          \"max_tokens\": 100\n        }\n    ]\n}\n"
              }
            },
            ...
    

    モデルをデプロイする

    Model Garden のモデルまたは Hugging Face のモデルをデプロイします。追加の JSON フィールドを指定して、デプロイをカスタマイズすることもできます。

    デフォルト構成でモデルをデプロイします。

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

    • LOCATION: モデルがデプロイされているリージョン。
    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
    • MODEL_ID: デプロイするモデルの ID。デプロイ可能なすべてのモデルの一覧から取得できます。ID の形式は publishers/PUBLISHER_NAME/models/MODEL_NAME@MODEL_VERSION です。

    HTTP メソッドと URL:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION:deploy

    リクエストの本文(JSON):

    {
      "publisher_model_name": "MODEL_ID",
      "model_config": {
        "accept_eula": "true"
      }
    }
    

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

    curl

    リクエスト本文を request.json という名前のファイルに保存します。ターミナルで次のコマンドを実行して、このファイルを現在のディレクトリに作成または上書きします。

    cat > request.json << 'EOF'
    {
      "publisher_model_name": "MODEL_ID",
      "model_config": {
        "accept_eula": "true"
      }
    }
    EOF

    その後、次のコマンドを実行して REST リクエストを送信します。

    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_ID/locations/LOCATION:deploy"

    PowerShell

    リクエスト本文を request.json という名前のファイルに保存します。ターミナルで次のコマンドを実行して、このファイルを現在のディレクトリに作成または上書きします。

    @'
    {
      "publisher_model_name": "MODEL_ID",
      "model_config": {
        "accept_eula": "true"
      }
    }
    '@  | Out-File -FilePath request.json -Encoding utf8

    その後、次のコマンドを実行して REST リクエストを送信します。

    $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_ID/locations/LOCATION:deploy" | Select-Object -Expand Content

    次のような JSON レスポンスが返されます。

    {
      "name": "projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.aiplatform.v1.DeployOperationMetadata",
        "genericMetadata": {
          "createTime": "2025-03-13T21:44:44.538780Z",
          "updateTime": "2025-03-13T21:44:44.538780Z"
        },
        "publisherModel": "publishers/google/models/gemma3@gemma-3-1b-it",
        "destination": "projects/PROJECT_ID/locations/LOCATION",
        "projectNumber": "PROJECT_ID"
      }
    }
    

    Hugging Face モデルをデプロイする

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

    • LOCATION: モデルがデプロイされているリージョン。
    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
    • MODEL_ID: デプロイする Hugging Face モデル ID。デプロイ可能なすべてのモデルの一覧から取得できます。ID は PUBLISHER_NAME/MODEL_NAME の形式を使用します。
    • ACCESS_TOKEN: モデルがゲートされている場合は、アクセス トークンを指定します。

    HTTP メソッドと URL:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION:deploy

    リクエストの本文(JSON):

    {
      "hugging_face_model_id": "MODEL_ID",
      "hugging_face_access_token": "ACCESS_TOKEN",
      "model_config": {
        "accept_eula": "true"
      }
    }
    

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

    curl

    リクエスト本文を request.json という名前のファイルに保存します。ターミナルで次のコマンドを実行して、このファイルを現在のディレクトリに作成または上書きします。

    cat > request.json << 'EOF'
    {
      "hugging_face_model_id": "MODEL_ID",
      "hugging_face_access_token": "ACCESS_TOKEN",
      "model_config": {
        "accept_eula": "true"
      }
    }
    EOF

    その後、次のコマンドを実行して REST リクエストを送信します。

    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_ID/locations/LOCATION:deploy"

    PowerShell

    リクエスト本文を request.json という名前のファイルに保存します。ターミナルで次のコマンドを実行して、このファイルを現在のディレクトリに作成または上書きします。

    @'
    {
      "hugging_face_model_id": "MODEL_ID",
      "hugging_face_access_token": "ACCESS_TOKEN",
      "model_config": {
        "accept_eula": "true"
      }
    }
    '@  | Out-File -FilePath request.json -Encoding utf8

    その後、次のコマンドを実行して REST リクエストを送信します。

    $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_ID/locations/LOCATION:deploy" | Select-Object -Expand Content

    次のような JSON レスポンスが返されます。

    {
      "name": "projects/PROJECT_ID/locations/us-central1LOCATION/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.aiplatform.v1.DeployOperationMetadata",
        "genericMetadata": {
          "createTime": "2025-03-13T21:44:44.538780Z",
          "updateTime": "2025-03-13T21:44:44.538780Z"
        },
        "publisherModel": "publishers/PUBLISHER_NAME/model/MODEL_NAME",
        "destination": "projects/PROJECT_ID/locations/LOCATION",
        "projectNumber": "PROJECT_ID"
      }
    }
    

    カスタマイズを加えてモデルをデプロイする

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

    • LOCATION: モデルがデプロイされているリージョン。
    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
    • MODEL_ID: デプロイするモデルの ID。デプロイ可能なすべてのモデルの一覧から取得できます。ID は publishers/PUBLISHER_NAME/models/MODEL_NAME@MODEL_VERSION の形式になります(google/gemma@gemma-2bstabilityai/stable-diffusion-xl-base-1.0 など)。
    • MACHINE_TYPE: モデルにデプロイするリソースのセット(g2-standard-4 など)を定義します。
    • ACCELERATOR_TYPE: NVIDIA_L4 などの負荷の高いワークロードを処理する際のパフォーマンスを向上させるため、デプロイに追加するアクセラレータを指定します。
    • ACCELERATOR_COUNT: デプロイで使用するアクセラレータの数。
    • reservation_affinity_type: デプロイに既存の Compute Engine 予約を使用するには、任意の予約または特定の予約を指定します。この値を指定する場合は、spot を指定しないでください。
    • spot: デプロイに Spot VM を使用するかどうかを指定します。
    • IMAGE_URI: 使用するコンテナ イメージのロケーション(us-docker.pkg.dev/vertex-ai/vertex-vision-model-garden-dockers/pytorch-vllm-serve:20241016_0916_RC00_maas など)。
    • CONTAINER_ARGS: デプロイ時にコンテナに渡す引数。
    • CONTAINER_PORT: コンテナのポート番号。
    • fast_tryout_enabled: モデルのテスト時に、高速デプロイを使用できます。このオプションは、特定のマシンタイプでよく使用されるモデルでのみ使用できます。有効にすると、モデルまたはデプロイ構成を指定できません。

    HTTP メソッドと URL:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION:deploy

    リクエストの本文(JSON):

    {
      "publisher_model_name": "MODEL_ID",
      "deploy_config": {
        "dedicated_resources": {
          "machine_spec": {
            "machine_type": "MACHINE_TYPE",
            "accelerator_type": "ACCELERATOR_TYPE",
            "accelerator_count": ACCELERATOR_COUNT,
            "reservation_affinity": {
              "reservation_affinity_type": "ANY_RESERVATION"
            }
          },
          "spot": "false"
        }
      },
      "model_config": {
        "accept_eula": "true",
        "container_spec": {
          "image_uri": "IMAGE_URI",
          "args": [CONTAINER_ARGS ],
          "ports": [
            {
              "container_port": CONTAINER_PORT
            }
          ]
        }
      },
      "deploy_config": {
        "fast_tryout_enabled": false
      },
    }
    

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

    curl

    リクエスト本文を request.json という名前のファイルに保存します。ターミナルで次のコマンドを実行して、このファイルを現在のディレクトリに作成または上書きします。

    cat > request.json << 'EOF'
    {
      "publisher_model_name": "MODEL_ID",
      "deploy_config": {
        "dedicated_resources": {
          "machine_spec": {
            "machine_type": "MACHINE_TYPE",
            "accelerator_type": "ACCELERATOR_TYPE",
            "accelerator_count": ACCELERATOR_COUNT,
            "reservation_affinity": {
              "reservation_affinity_type": "ANY_RESERVATION"
            }
          },
          "spot": "false"
        }
      },
      "model_config": {
        "accept_eula": "true",
        "container_spec": {
          "image_uri": "IMAGE_URI",
          "args": [CONTAINER_ARGS ],
          "ports": [
            {
              "container_port": CONTAINER_PORT
            }
          ]
        }
      },
      "deploy_config": {
        "fast_tryout_enabled": false
      },
    }
    EOF

    その後、次のコマンドを実行して REST リクエストを送信します。

    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_ID/locations/LOCATION:deploy"

    PowerShell

    リクエスト本文を request.json という名前のファイルに保存します。ターミナルで次のコマンドを実行して、このファイルを現在のディレクトリに作成または上書きします。

    @'
    {
      "publisher_model_name": "MODEL_ID",
      "deploy_config": {
        "dedicated_resources": {
          "machine_spec": {
            "machine_type": "MACHINE_TYPE",
            "accelerator_type": "ACCELERATOR_TYPE",
            "accelerator_count": ACCELERATOR_COUNT,
            "reservation_affinity": {
              "reservation_affinity_type": "ANY_RESERVATION"
            }
          },
          "spot": "false"
        }
      },
      "model_config": {
        "accept_eula": "true",
        "container_spec": {
          "image_uri": "IMAGE_URI",
          "args": [CONTAINER_ARGS ],
          "ports": [
            {
              "container_port": CONTAINER_PORT
            }
          ]
        }
      },
      "deploy_config": {
        "fast_tryout_enabled": false
      },
    }
    '@  | Out-File -FilePath request.json -Encoding utf8

    その後、次のコマンドを実行して REST リクエストを送信します。

    $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_ID/locations/LOCATION:deploy" | Select-Object -Expand Content

    次のような JSON レスポンスが返されます。

    {
      "name": "projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.aiplatform.v1.DeployOperationMetadata",
        "genericMetadata": {
          "createTime": "2025-03-13T21:44:44.538780Z",
          "updateTime": "2025-03-13T21:44:44.538780Z"
        },
        "publisherModel": "publishers/google/models/gemma3@gemma-3-1b-it",
        "destination": "projects/PROJECT_ID/locations/LOCATION",
        "projectNumber": "PROJECT_ID"
      }
    }
    

    コンソール

    1. Google Cloud コンソールで、[Model Garden] ページに移動します。

      Model Garden に移動

    2. デプロイするサポート対象モデルを見つけて、そのモデルカードをクリックします。

    3. [デプロイ] をクリックして、[モデルのデプロイ] ペインを開きます。

    4. [モデルのデプロイ] ペインで、デプロイの詳細を指定します。

      1. 生成されたモデル名とエンドポイント名を使用するか、変更します。
      2. モデル エンドポイントを作成するロケーションを選択します。
      3. デプロイの各ノードに使用するマシンタイプを選択します。
      4. Compute Engine の予約を使用するには、[デプロイの設定] セクションで [詳細] を選択します。

        [予約タイプ] フィールドで予約タイプを選択します。予約は、指定したマシンの仕様に一致している必要があります。

        • 作成済みの予約を自動的に使用する: Vertex AI は、一致するプロパティを持つ許可された予約を自動的に選択します。自動的に選択された予約に容量がない場合、Vertex AI は Google Cloudの一般リソースプールを使用します。
        • Select specific reservations: Vertex AI は特定の予約を使用します。選択した予約に容量がない場合は、エラーがスローされます。
        • 使用しない(デフォルト): Vertex AI は、一般的なGoogle Cloud リソースプールを使用します。この値は、予約を指定しない場合と同じ効果があります。
    5. [デプロイ] をクリックします。

    Terraform

    Terraform 構成を適用または削除する方法については、基本的な Terraform コマンドをご覧ください。詳細については、Terraform プロバイダのリファレンス ドキュメントをご覧ください。

    モデルをデプロイする

    次の例では、デフォルトの構成を使用して、gemma-3-1b-it モデルを us-central1 の新しい Vertex AI エンドポイントにデプロイします。

    terraform {
      required_providers {
        google = {
          source = "hashicorp/google"
          version = "6.45.0"
        }
      }
    }
    
    provider "google" {
      region  = "us-central1"
    }
    
    resource "google_vertex_ai_endpoint_with_model_garden_deployment" "gemma_deployment" {
      publisher_model_name = "publishers/google/models/gemma3@gemma-3-1b-it"
      location = "us-central1"
      model_config {
        accept_eula = True
      }
    }
    

    カスタマイズを使用してモデルをデプロイするには、Model Garden デプロイによる Vertex AI エンドポイントをご覧ください。

    構成を適用する

    terraform init
    terraform plan
    terraform apply
    

    構成を適用すると、Terraform は新しい Vertex AI エンドポイントをプロビジョニングし、指定されたオープンモデルをデプロイします。

    クリーンアップする

    エンドポイントとモデルのデプロイを削除するには、次のコマンドを実行します。

    terraform destroy
    

    PredictionServiceClient で Gemma 1B を推論する

    Gemma 1B をデプロイしたら、PredictionServiceClient を使用して「空はなぜ青いの?」というプロンプトのオンライン予測を取得します。

    コード パラメータ

    PredictionServiceClient コードサンプルでは、以下を更新する必要があります。

    • PROJECT_ID: プロジェクト ID を確認する手順は次のとおりです。

      1. Google Cloud コンソールの [ようこそ] ページに移動します。

        [ようこそ] に移動

      2. ページ上部のプロジェクト選択ツールで、自分のプロジェクトを選択します。

        プロジェクト名、プロジェクト番号、プロジェクト ID は [ようこそ] の見出しの後に表示されます。

    • ENDPOINT_REGION: エンドポイントをデプロイしたリージョンです。

    • ENDPOINT_ID: エンドポイント ID を確認するには、コンソールで確認するか、gcloud ai endpoints list コマンドを実行します。[モデルをデプロイ] ペインからエンドポイント名とリージョンを取得します。

      コンソール

      [オンライン予測] > [エンドポイント] をクリックしてリージョンを選択すると、エンドポイントの詳細を確認できます。ID 列に表示される番号をメモします。

      エンドポイントに移動

      gcloud

      エンドポイントの詳細を表示するには、gcloud ai endpoints list コマンドを実行します。

      gcloud ai endpoints list \
        --region=ENDPOINT_REGION \
        --filter=display_name=ENDPOINT_NAME
      

      出力は次のようになります。

      Using endpoint [https://us-central1-aiplatform.googleapis.com/]
      ENDPOINT_ID: 1234567891234567891
      DISPLAY_NAME: gemma2-2b-it-mg-one-click-deploy
      

    サンプルコード

    言語のサンプルコードで、PROJECT_IDENDPOINT_REGIONENDPOINT_ID を更新します。次に、コードを実行します。

    Python

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

    """
    Sample to run inference on a Gemma2 model deployed to a Vertex AI endpoint with GPU accellerators.
    """
    
    from google.cloud import aiplatform
    from google.protobuf import json_format
    from google.protobuf.struct_pb2 import Value
    
    # TODO(developer): Update & uncomment lines below
    # PROJECT_ID = "your-project-id"
    # ENDPOINT_REGION = "your-vertex-endpoint-region"
    # ENDPOINT_ID = "your-vertex-endpoint-id"
    
    # Default configuration
    config = {"max_tokens": 1024, "temperature": 0.9, "top_p": 1.0, "top_k": 1}
    
    # Prompt used in the prediction
    prompt = "Why is the sky blue?"
    
    # Encapsulate the prompt in a correct format for GPUs
    # Example format: [{'inputs': 'Why is the sky blue?', 'parameters': {'temperature': 0.9}}]
    input = {"inputs": prompt, "parameters": config}
    
    # Convert input message to a list of GAPIC instances for model input
    instances = [json_format.ParseDict(input, Value())]
    
    # Create a client
    api_endpoint = f"{ENDPOINT_REGION}-aiplatform.googleapis.com"
    client = aiplatform.gapic.PredictionServiceClient(
        client_options={"api_endpoint": api_endpoint}
    )
    
    # Call the Gemma2 endpoint
    gemma2_end_point = (
        f"projects/{PROJECT_ID}/locations/{ENDPOINT_REGION}/endpoints/{ENDPOINT_ID}"
    )
    response = client.predict(
        endpoint=gemma2_end_point,
        instances=instances,
    )
    text_responses = response.predictions
    print(text_responses[0])
    

    Node.js

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

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

    async function gemma2PredictGpu(predictionServiceClient) {
      // Imports the Google Cloud Prediction Service Client library
      const {
        // TODO(developer): Uncomment PredictionServiceClient before running the sample.
        // PredictionServiceClient,
        helpers,
      } = require('@google-cloud/aiplatform');
      /**
       * TODO(developer): Update these variables before running the sample.
       */
      const projectId = 'your-project-id';
      const endpointRegion = 'your-vertex-endpoint-region';
      const endpointId = 'your-vertex-endpoint-id';
    
      // Default configuration
      const config = {maxOutputTokens: 1024, temperature: 0.9, topP: 1.0, topK: 1};
      // Prompt used in the prediction
      const prompt = 'Why is the sky blue?';
    
      // Encapsulate the prompt in a correct format for GPUs
      // Example format: [{inputs: 'Why is the sky blue?', parameters: {temperature: 0.9}}]
      const input = {
        inputs: prompt,
        parameters: config,
      };
    
      // Convert input message to a list of GAPIC instances for model input
      const instances = [helpers.toValue(input)];
    
      // TODO(developer): Uncomment apiEndpoint and predictionServiceClient before running the sample.
      // const apiEndpoint = `${endpointRegion}-aiplatform.googleapis.com`;
    
      // Create a client
      // predictionServiceClient = new PredictionServiceClient({apiEndpoint});
    
      // Call the Gemma2 endpoint
      const gemma2Endpoint = `projects/${projectId}/locations/${endpointRegion}/endpoints/${endpointId}`;
    
      const [response] = await predictionServiceClient.predict({
        endpoint: gemma2Endpoint,
        instances,
      });
    
      const predictions = response.predictions;
      const text = predictions[0].stringValue;
    
      console.log('Predictions:', text);
      return text;
    }
    
    module.exports = gemma2PredictGpu;
    
    // TODO(developer): Uncomment below lines before running the sample.
    // gemma2PredictGpu(...process.argv.slice(2)).catch(err => {
    //   console.error(err.message);
    //   process.exitCode = 1;
    // });

    Java

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

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

    
    import com.google.cloud.aiplatform.v1.EndpointName;
    import com.google.cloud.aiplatform.v1.PredictResponse;
    import com.google.cloud.aiplatform.v1.PredictionServiceClient;
    import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
    import com.google.gson.Gson;
    import com.google.protobuf.InvalidProtocolBufferException;
    import com.google.protobuf.Value;
    import com.google.protobuf.util.JsonFormat;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class Gemma2PredictGpu {
    
      private final PredictionServiceClient predictionServiceClient;
    
      // Constructor to inject the PredictionServiceClient
      public Gemma2PredictGpu(PredictionServiceClient predictionServiceClient) {
        this.predictionServiceClient = predictionServiceClient;
      }
    
      public static void main(String[] args) throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "YOUR_PROJECT_ID";
        String endpointRegion = "us-east4";
        String endpointId = "YOUR_ENDPOINT_ID";
    
        PredictionServiceSettings predictionServiceSettings =
            PredictionServiceSettings.newBuilder()
                .setEndpoint(String.format("%s-aiplatform.googleapis.com:443", endpointRegion))
                .build();
        PredictionServiceClient predictionServiceClient =
            PredictionServiceClient.create(predictionServiceSettings);
        Gemma2PredictGpu creator = new Gemma2PredictGpu(predictionServiceClient);
    
        creator.gemma2PredictGpu(projectId, endpointRegion, endpointId);
      }
    
      // Demonstrates how to run inference on a Gemma2 model
      // deployed to a Vertex AI endpoint with GPU accelerators.
      public String gemma2PredictGpu(String projectId, String region,
                   String endpointId) throws IOException {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("temperature", 0.9);
        paramsMap.put("maxOutputTokens", 1024);
        paramsMap.put("topP", 1.0);
        paramsMap.put("topK", 1);
        Value parameters = mapToValue(paramsMap);
    
        // Prompt used in the prediction
        String instance = "{ \"inputs\": \"Why is the sky blue?\"}";
        Value.Builder instanceValue = Value.newBuilder();
        JsonFormat.parser().merge(instance, instanceValue);
        // Encapsulate the prompt in a correct format for GPUs
        // Example format: [{'inputs': 'Why is the sky blue?', 'parameters': {'temperature': 0.8}}]
        List<Value> instances = new ArrayList<>();
        instances.add(instanceValue.build());
    
        EndpointName endpointName = EndpointName.of(projectId, region, endpointId);
    
        PredictResponse predictResponse = this.predictionServiceClient
            .predict(endpointName, instances, parameters);
        String textResponse = predictResponse.getPredictions(0).getStringValue();
        System.out.println(textResponse);
        return textResponse;
      }
    
      private static Value mapToValue(Map<String, Object> map) throws InvalidProtocolBufferException {
        Gson gson = new Gson();
        String json = gson.toJson(map);
        Value.Builder builder = Value.newBuilder();
        JsonFormat.parser().merge(json, builder);
        return builder.build();
      }
    }

    Go

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

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

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/aiplatform/apiv1/aiplatformpb"
    
    	"google.golang.org/protobuf/types/known/structpb"
    )
    
    // predictGPU demonstrates how to run interference on a Gemma2 model deployed to a Vertex AI endpoint with GPU accelerators.
    func predictGPU(w io.Writer, client PredictionsClient, projectID, location, endpointID string) error {
    	ctx := context.Background()
    
    	// Note: client can be initialized in the following way:
    	// apiEndpoint := fmt.Sprintf("%s-aiplatform.googleapis.com:443", location)
    	// client, err := aiplatform.NewPredictionClient(ctx, option.WithEndpoint(apiEndpoint))
    	// if err != nil {
    	// 	return fmt.Errorf("unable to create prediction client: %v", err)
    	// }
    	// defer client.Close()
    
    	gemma2Endpoint := fmt.Sprintf("projects/%s/locations/%s/endpoints/%s", projectID, location, endpointID)
    	prompt := "Why is the sky blue?"
    	parameters := map[string]interface{}{
    		"temperature":     0.9,
    		"maxOutputTokens": 1024,
    		"topP":            1.0,
    		"topK":            1,
    	}
    
    	// Encapsulate the prompt in a correct format for TPUs.
    	// Pay attention that prompt should be set in "inputs" field.
    	// Example format: [{'inputs': 'Why is the sky blue?', 'parameters': {'temperature': 0.9}}]
    	promptValue, err := structpb.NewValue(map[string]interface{}{
    		"inputs":     prompt,
    		"parameters": parameters,
    	})
    	if err != nil {
    		fmt.Fprintf(w, "unable to convert prompt to Value: %v", err)
    		return err
    	}
    
    	req := &aiplatformpb.PredictRequest{
    		Endpoint:  gemma2Endpoint,
    		Instances: []*structpb.Value{promptValue},
    	}
    
    	resp, err := client.Predict(ctx, req)
    	if err != nil {
    		return err
    	}
    
    	prediction := resp.GetPredictions()
    	value := prediction[0].GetStringValue()
    	fmt.Fprintf(w, "%v", value)
    
    	return nil
    }
    

    クリーンアップ

    このチュートリアルで使用したリソースについて、Google Cloud アカウントに課金されないようにするには、リソースを含むプロジェクトを削除するか、プロジェクトを維持して個々のリソースを削除します。

    プロジェクトを削除する

    1. In the Google Cloud console, go to the Manage resources page.

      Go to Manage resources

    2. In the project list, select the project that you want to delete, and then click Delete.
    3. In the dialog, type the project ID, and then click Shut down to delete the project.

    リソースを個別に削除する

    プロジェクトを保持する場合は、このチュートリアルで使用したリソースを削除します。

    • モデルのデプロイを解除してエンドポイントを削除する
    • Model Registry からモデルを削除する

    モデルのデプロイを解除してエンドポイントを削除する

    次のいずれかの方法でモデルのデプロイを解除し、エンドポイントを削除します。

    コンソール

    1. Google Cloud コンソールで、[オンライン予測]、[エンドポイント] の順にクリックします。

      [エンドポイント] ページに移動

    2. [リージョン] プルダウン リストで、エンドポイントをデプロイしたリージョンを選択します。

    3. エンドポイント名をクリックして詳細ページを開きます。例: gemma2-2b-it-mg-one-click-deploy

    4. Gemma 2 (Version 1) モデルの行で、 [アクション] をクリックして、次に [エンドポイントからモデルのデプロイを解除] をクリックします。

    5. [エンドポイントからモデルのデプロイを解除] ダイアログで [デプロイ解除] をクリックします。

    6. [戻る] ボタンをクリックして [エンドポイント] ページに戻ります。

      [エンドポイント] ページに移動

    7. gemma2-2b-it-mg-one-click-deploy 行の末尾にある [アクション] をクリックし、[エンドポイントを削除] を選択します。

    8. 確認プロンプトで [確認] をクリックします。

    gcloud

    Google Cloud CLI を使用してモデルのデプロイを解除し、エンドポイントを削除する手順は次のとおりです。

    これらのコマンドでは、次のように置き換えます。

    • PROJECT_ID は、プロジェクト名に置き換えます。
    • LOCATION_ID は、モデルとエンドポイントをデプロイしたリージョンに置き換えます。
    • ENDPOINT_ID は、エンドポイント ID に置き換えます。
    • DEPLOYED_MODEL_NAME はモデルの表示名に置き換えます。
    • DEPLOYED_MODEL_ID はモデル ID に置き換えます。
    1. gcloud ai endpoints list コマンドを実行してエンドポイント ID を取得します。このコマンドを使用すると、プロジェクト内のすべてのエンドポイントのエンドポイント ID が一覧表示されます。このチュートリアルで使用するエンドポイントの ID をメモします。

      gcloud ai endpoints list \
          --project=PROJECT_ID \
          --region=LOCATION_ID
      

      出力は次のようになります。出力では、ID は ENDPOINT_ID と呼ばれます。

      Using endpoint [https://us-central1-aiplatform.googleapis.com/]
      ENDPOINT_ID: 1234567891234567891
      DISPLAY_NAME: gemma2-2b-it-mg-one-click-deploy
      
    2. gcloud ai models describe コマンドを実行してモデル ID を取得します。このチュートリアルでデプロイしたモデルの ID をメモします。

      gcloud ai models describe DEPLOYED_MODEL_NAME \
          --project=PROJECT_ID \
          --region=LOCATION_ID
      

      省略した出力は次のようになります。出力では、ID は deployedModelId と呼ばれます。

      Using endpoint [https://us-central1-aiplatform.googleapis.com/]
      artifactUri: [URI removed]
      baseModelSource:
        modelGardenSource:
          publicModelName: publishers/google/models/gemma2
      ...
      deployedModels:
      - deployedModelId: '1234567891234567891'
        endpoint: projects/12345678912/locations/us-central1/endpoints/12345678912345
      displayName: gemma2-2b-it-12345678912345
      etag: [ETag removed]
      modelSourceInfo:
        sourceType: MODEL_GARDEN
      name: projects/123456789123/locations/us-central1/models/gemma2-2b-it-12345678912345
      ...
      
    3. エンドポイントからモデルのデプロイを解除します。前のコマンドからエンドポイント ID とモデル ID が必要です。

      gcloud ai endpoints undeploy-model ENDPOINT_ID \
          --project=PROJECT_ID \
          --region=LOCATION_ID \
          --deployed-model-id=DEPLOYED_MODEL_ID
      

      このコマンドは出力を生成しません。

    4. gcloud ai endpoints delete コマンドを実行して、エンドポイントを削除します。

      gcloud ai endpoints delete ENDPOINT_ID \
          --project=PROJECT_ID \
          --region=LOCATION_ID
      

      プロンプトが表示されたら、「y」と入力して確定します。このコマンドは出力を生成しません。

    モデルを削除する

    コンソール

    1. Google Cloud コンソールの Vertex AI セクションから [Model Registry] ページに移動します。

      [Model Registry] ページに移動

    2. [リージョン] プルダウン リストで、モデルをデプロイしたリージョンを選択します。

    3. gemma2-2b-it-1234567891234 行の末尾にある [アクション] をクリックします。

    4. [モデルを削除] を選択します。

      モデルを削除すると、関連するすべてのモデル バージョンと評価が Google Cloud プロジェクトから削除されます。

    5. 確認プロンプトで [削除] をクリックします。

    gcloud

    Google Cloud CLI を使用してモデルを削除するには、モデルの表示名とリージョンを gcloud ai models delete コマンドに指定します。

    gcloud ai models delete DEPLOYED_MODEL_NAME \
        --project=PROJECT_ID \
        --region=LOCATION_ID
    

    DEPLOYED_MODEL_NAME は、モデルの表示名に置き換えます。PROJECT_ID は、プロジェクト名に置き換えます。LOCATION_ID は、モデルをデプロイしたリージョンに置き換えます。

    次のステップ