使用 Model Garden 和 Vertex AI GPU 支援的端點,部署並推論 Gemma

在本教學課程中,您會使用 Model Garden 將Gemma 1B 開放式模型部署至採用 GPU 的 Vertex AI 端點。您必須先將模型部署至端點,才能使用模型進行線上預測。部署過程中,系統會將實體資源與模型建立關聯,讓模型以低延遲的方式提供線上預測結果。

部署 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

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 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,以及可自行部署的模型。

    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 替換為上一個清單指令中的模型 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:先前清單指令中的模型 ID。如果是 Hugging Face 模型,請使用 Hugging Face 模型網址格式,例如 stabilityai/stable-diffusion-xl-base-1.0
    • 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,可用於檢查部署狀態。

    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 方法和網址:

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。ID 採用下列格式:publishers/PUBLISHER_NAME/models/ MODEL_NAME@MODEL_VERSION

HTTP 方法和網址:

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 方法和網址:

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。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 方法和網址:

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. 按一下「Deploy」(部署),開啟「Deploy model」(部署模型)窗格。

  4. 在「Deploy model」(部署模型) 窗格中,指定部署作業的詳細資料。

    1. 使用或修改產生的模型和端點名稱。
    2. 選取要建立模型端點的位置。
    3. 為部署項目的每個節點選取要使用的機器類型。
    4. 如要使用 Compute Engine 預留項目,請在「部署設定」部分下方選取「進階」

      在「預訂類型」欄位中,選取預訂類型。預訂的機型必須符合您指定的規格。

      • 自動使用建立的預留項目:Vertex AI 會自動選取具有相符屬性的允許預留項目。如果自動選取的預留項目沒有容量,Vertex AI 會使用一般 Google Cloud資源集區。
      • 選取特定預留項目: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 控制台的「Welcome」(歡迎使用) 頁面。

      前往「歡迎」

    2. 在頁面頂端的專案挑選器中選取專案。

      專案名稱、專案編號和專案 ID 會顯示在「歡迎」標題下方。

  • ENDPOINT_REGION:這是部署端點的區域。

  • ENDPOINT_ID:如要找出端點 ID,請在控制台中查看,或執行 gcloud ai endpoints list 指令。您需要「Deploy model」(部署模型) 窗格中的端點名稱和區域。

    控制台

    如要查看端點詳細資料,請依序點選「線上預測」>「端點」,然後選取您的區域。請記下「ID」欄中顯示的號碼。

    前往 Endpoints

    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

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 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

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 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

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 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
}