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

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

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

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
}