Men-deploy dan melakukan inferensi Gemma menggunakan endpoint yang didukung GPU Model Garden dan Vertex AI


Dalam tutorial ini, Anda akan menggunakan Model Garden untuk men-deploy model terbuka Gemma 1B ke endpoint Vertex AI yang didukung GPU. Anda harus men-deploy model ke endpoint sebelum model tersebut dapat digunakan untuk menyajikan prediksi online. Men-deploy model akan mengaitkan resource fisik dengan model tersebut, sehingga dapat menyajikan prediksi online dengan latensi rendah.

Setelah men-deploy model Gemma 1B, Anda akan melakukan inferensi model terlatih menggunakan PredictionServiceClient untuk mendapatkan prediksi online. Prediksi online adalah permintaan sinkron yang dibuat ke model yang di-deploy ke endpoint.

Tujuan

Tutorial ini menunjukkan cara melakukan tugas-tugas berikut:

  • Men-deploy model terbuka Gemma 1B ke endpoint yang didukung GPU dengan menggunakan Model Garden
  • Gunakan PredictionServiceClient untuk mendapatkan prediksi online

Biaya

Dalam dokumen ini, Anda akan menggunakan komponen Google Cloudyang dapat ditagih berikut:

Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda, gunakan kalkulator harga.

Pengguna Google Cloud baru mungkin memenuhi syarat untuk mendapatkan uji coba gratis.

Setelah menyelesaikan tugas yang dijelaskan dalam dokumen ini, Anda dapat menghindari penagihan berkelanjutan dengan menghapus resource yang Anda buat. Untuk mengetahui informasi selengkapnya, lihat Pembersihan.

Sebelum memulai

Tutorial ini mengharuskan Anda untuk:

  • Menyiapkan Google Cloud project dan mengaktifkan Vertex AI API
  • Di komputer lokal Anda:
    • Menginstal, melakukan inisialisasi, dan mengautentikasi dengan Google Cloud CLI
    • Instal SDK untuk bahasa Anda

Menyiapkan project Google Cloud

Siapkan Google Cloud project Anda dan aktifkan 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. Menyiapkan Google Cloud CLI

    Di komputer lokal Anda, siapkan Google Cloud CLI.

    1. Instal dan lakukan inisialisasiGoogle Cloud CLI.

    2. Jika sebelumnya Anda telah menginstal gcloud CLI, pastikan komponen gcloud Anda diupdate dengan menjalankan perintah ini.

      gcloud components update
    3. Untuk melakukan autentikasi dengan gcloud CLI, buat file Kredensial Default Aplikasi (ADC) lokal dengan menjalankan perintah ini. Alur web yang diluncurkan oleh perintah digunakan untuk memberikan kredensial pengguna Anda.

      gcloud auth application-default login

      Untuk mengetahui informasi selengkapnya, lihat konfigurasi autentikasi gcloud CLI dan konfigurasi ADC.

    Menyiapkan SDK untuk bahasa pemrograman Anda

    Untuk menyiapkan lingkungan yang digunakan dalam tutorial ini, Anda menginstal Vertex AI SDK untuk bahasa Anda dan library Protocol Buffers. Contoh kode menggunakan fungsi dari library Protocol Buffers untuk mengonversi kamus input ke format JSON yang diharapkan oleh API.

    Di komputer lokal Anda, klik salah satu tab berikut untuk menginstal SDK untuk bahasa pemrograman Anda.

    Python

    Di komputer lokal Anda, klik salah satu tab berikut untuk menginstal SDK untuk bahasa pemrograman Anda.

    • Instal dan update Vertex AI SDK untuk Python dengan menjalankan perintah ini.

      pip3 install --upgrade "google-cloud-aiplatform>=1.64"
    • Instal library Protocol Buffers untuk Python dengan menjalankan perintah ini.

      pip3 install --upgrade "protobuf>=5.28"

    Node.js

    Instal atau update aiplatform SDK untuk Node.js dengan menjalankan perintah berikut.

    npm install @google-cloud/aiplatform

    Java

    Untuk menambahkan google-cloud-aiplatform sebagai dependensi, tambahkan kode yang sesuai untuk lingkungan Anda.

    Maven dengan BOM

    Tambahkan HTML berikut ke pom.xml Anda:

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

    Maven tanpa BOM

    Tambahkan kode berikut ke pom.xml Anda:

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

    Gradle tanpa BOM

    Tambahkan kode berikut ke build.gradle Anda:

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

    Go

    Instal paket Go ini dengan menjalankan perintah berikut.

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

    Men-deploy Gemma menggunakan Model Garden

    Anda dapat men-deploy Gemma 1B menggunakan kartu modelnya di konsol Google Cloud atau secara terprogram.

    Untuk mengetahui informasi selengkapnya tentang cara menyiapkan Google Gen AI SDK atau Google Cloud CLI, lihat ringkasan Google Gen AI SDK atau Menginstal Google Cloud CLI.

    Python

    Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python.

    1. Buat daftar model yang dapat Anda deploy dan catat ID model yang akan di-deploy. Anda dapat mencantumkan model Hugging Face yang didukung di Model Garden dan bahkan memfilternya berdasarkan nama model. Output tidak menyertakan model yang di-tuning.

      
      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. Lihat spesifikasi deployment untuk model menggunakan ID model dari langkah sebelumnya. Anda dapat melihat jenis mesin, jenis akselerator, dan URI image container yang telah diverifikasi Model Garden untuk model tertentu.

      
      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. Men-deploy model ke endpoint. Model Garden menggunakan konfigurasi deployment default kecuali jika Anda menentukan argumen dan nilai tambahan.

      
      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

    Sebelum memulai, tentukan project kuota untuk menjalankan perintah berikut. Perintah yang Anda jalankan akan dihitung dalam kuota untuk project tersebut. Untuk mengetahui informasi selengkapnya, lihat Menetapkan project kuota.

    1. Buat daftar model yang dapat Anda deploy dengan menjalankan perintah gcloud ai model-garden models list. Perintah ini mencantumkan semua ID model dan ID model yang dapat Anda deploy sendiri.

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

      Di output, temukan ID model yang akan di-deploy. Contoh berikut menunjukkan output yang disingkat.

      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
      

      Output tidak menyertakan model yang di-tune atau model Hugging Face. Untuk melihat model Hugging Face yang didukung, tambahkan tanda --can-deploy-hugging-face-models.

    2. Untuk melihat spesifikasi deployment model, jalankan perintah gcloud ai model-garden models list-deployment-config. Anda dapat melihat jenis mesin, jenis akselerator, dan URI image container yang didukung Model Garden untuk model tertentu.

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

      Ganti MODEL_ID dengan ID model dari perintah daftar sebelumnya, seperti google/gemma@gemma-2b atau stabilityai/stable-diffusion-xl-base-1.0.

    3. Deploy model ke endpoint dengan menjalankan perintah gcloud ai model-garden models deploy. Model Garden membuat nama tampilan untuk endpoint Anda dan menggunakan konfigurasi deployment default, kecuali jika Anda menentukan argumen dan nilai tambahan.

      Untuk menjalankan perintah secara asinkron, sertakan tanda --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]
      

      Ganti placeholder berikut:

      • MODEL_ID: ID model dari perintah daftar sebelumnya. Untuk model Hugging Face, gunakan format URL model Hugging Face, seperti stabilityai/stable-diffusion-xl-base-1.0.
      • MACHINE_TYPE: Menentukan kumpulan resource yang akan di-deploy untuk model Anda, seperti g2-standard-4.
      • ACCELERATOR_TYPE: Menentukan akselerator yang akan ditambahkan ke deployment Anda untuk membantu meningkatkan performa saat bekerja dengan beban kerja berat, seperti NVIDIA_L4.
      • ENDPOINT_NAME: Nama untuk endpoint Vertex AI yang di-deploy.
      • HF_ACCESS_TOKEN: Untuk model Hugging Face, jika model dibatasi, berikan token akses.
      • RESERVATION_RESOURCE_NAME: Untuk menggunakan pemesanan Compute Engine tertentu, tentukan nama pemesanan Anda. Jika menentukan pemesanan tertentu, Anda tidak dapat menentukan any-reservation.

      Output mencakup konfigurasi deployment yang digunakan Model Garden, ID endpoint, dan ID operasi deployment, yang dapat Anda gunakan untuk memeriksa status deployment.

      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. Untuk melihat detail tentang deployment Anda, jalankan perintah gcloud ai endpoints list --list-model-garden-endpoints-only:

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

      Ganti LOCATION_ID dengan region tempat Anda men-deploy model.

      Output mencakup semua endpoint yang dibuat dari Model Garden dan mencakup informasi seperti ID endpoint, nama endpoint, dan apakah endpoint dikaitkan dengan model yang di-deploy. Untuk menemukan deployment Anda, cari nama endpoint yang ditampilkan dari perintah sebelumnya.

    REST

    Mencantumkan semua model yang dapat di-deploy, lalu mendapatkan ID model yang akan di-deploy. Kemudian, Anda dapat men-deploy model dengan konfigurasi dan endpoint default-nya. Atau, Anda dapat memilih untuk menyesuaikan deployment, seperti menyetel jenis mesin tertentu atau menggunakan endpoint khusus.

    Mencantumkan model yang dapat Anda deploy

    Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

    • PROJECT_ID: ID project Google Cloud Anda.
    • QUERY_PARAMETERS: Untuk mencantumkan model Model Garden, tambahkan parameter kueri berikut listAllVersions=True&filter=is_deployable(true). Untuk mencantumkan model Hugging Face, tetapkan filter ke alt=json&is_hf_wildcard(true)+AND+labels.VERIFIED_DEPLOYMENT_CONFIG%3DVERIFIED_DEPLOYMENT_SUCCEED&listAllVersions=True.

    Metode HTTP dan URL:

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

    Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

    curl

    Jalankan perintah berikut:

    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

    Jalankan perintah berikut:

    $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

    Anda akan menerima respons JSON yang mirip dengan yang berikut ini.

    {
      "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"
              }
            },
            ...
    

    Men-deploy model

    Men-deploy model dari Model Garden atau model dari Hugging Face. Anda juga dapat menyesuaikan deployment dengan menentukan kolom JSON tambahan.

    Men-deploy model dengan konfigurasi defaultnya.

    Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

    • LOCATION: Region tempat model di-deploy.
    • PROJECT_ID: ID project Google Cloud Anda.
    • MODEL_ID: ID model yang akan di-deploy, yang bisa Anda dapatkan dari mencantumkan semua model yang dapat di-deploy. ID menggunakan format berikut: publishers/PUBLISHER_NAME/models/ MODEL_NAME@MODEL_VERSION.

    Metode HTTP dan URL:

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

    Isi JSON permintaan:

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

    Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

    curl

    Simpan isi permintaan dalam file bernama request.json. Jalankan perintah berikut di terminal untuk membuat atau menimpa file ini di direktori saat ini:

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

    Kemudian, jalankan perintah berikut untuk mengirim permintaan REST Anda:

    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

    Simpan isi permintaan dalam file bernama request.json. Jalankan perintah berikut di terminal untuk membuat atau menimpa file ini di direktori saat ini:

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

    Kemudian jalankan perintah berikut untuk mengirim permintaan REST Anda:

    $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

    Anda akan menerima respons JSON yang mirip dengan yang berikut ini.

    {
      "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"
      }
    }
    

    Men-deploy model Hugging Face

    Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

    • LOCATION: Region tempat model di-deploy.
    • PROJECT_ID: ID project Google Cloud Anda.
    • MODEL_ID: ID model Hugging Face yang akan di-deploy, yang bisa Anda dapatkan dari mencantumkan semua model yang dapat di-deploy. ID menggunakan format berikut: PUBLISHER_NAME/MODEL_NAME.
    • ACCESS_TOKEN: Jika model dibatasi, berikan token akses.

    Metode HTTP dan URL:

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

    Isi JSON permintaan:

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

    Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

    curl

    Simpan isi permintaan dalam file bernama request.json. Jalankan perintah berikut di terminal untuk membuat atau menimpa file ini di direktori saat ini:

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

    Kemudian, jalankan perintah berikut untuk mengirim permintaan REST Anda:

    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

    Simpan isi permintaan dalam file bernama request.json. Jalankan perintah berikut di terminal untuk membuat atau menimpa file ini di direktori saat ini:

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

    Kemudian jalankan perintah berikut untuk mengirim permintaan REST Anda:

    $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

    Anda akan menerima respons JSON yang mirip dengan yang berikut ini.

    {
      "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"
      }
    }
    

    Men-deploy model dengan penyesuaian

    Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

    • LOCATION: Region tempat model di-deploy.
    • PROJECT_ID: ID project Google Cloud Anda.
    • MODEL_ID: ID model yang akan di-deploy, yang bisa Anda dapatkan dari mencantumkan semua model yang dapat di-deploy. ID menggunakan format berikut: publishers/PUBLISHER_NAME/models/ MODEL_NAME@MODEL_VERSION, seperti google/gemma@gemma-2b atau stabilityai/stable-diffusion-xl-base-1.0.
    • MACHINE_TYPE: Menentukan kumpulan resource yang akan di-deploy untuk model Anda, seperti g2-standard-4.
    • ACCELERATOR_TYPE: Menentukan akselerator yang akan ditambahkan ke deployment Anda untuk membantu meningkatkan performa saat menangani beban kerja berat, seperti NVIDIA_L4
    • ACCELERATOR_COUNT: Jumlah akselerator yang akan digunakan dalam deployment Anda.
    • reservation_affinity_type: Untuk menggunakan reservasi Compute Engine yang ada untuk deployment Anda, tentukan reservasi apa pun atau reservasi tertentu. Jika Anda menentukan nilai ini, jangan tentukan spot.
    • spot: Apakah akan menggunakan VM spot untuk deployment Anda.
    • IMAGE_URI: Lokasi image container yang akan digunakan, seperti us-docker.pkg.dev/vertex-ai/vertex-vision-model-garden-dockers/pytorch-vllm-serve:20241016_0916_RC00_maas
    • CONTAINER_ARGS: Argumen yang akan diteruskan ke container selama deployment.
    • CONTAINER_PORT: Nomor port untuk container Anda.
    • fast_tryout_enabled: Saat menguji model, Anda dapat memilih untuk menggunakan deployment yang lebih cepat. Opsi ini hanya tersedia untuk model yang sering digunakan dengan jenis mesin tertentu. Jika diaktifkan, Anda tidak dapat menentukan model atau konfigurasi deployment.

    Metode HTTP dan URL:

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

    Isi JSON permintaan:

    {
      "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
      },
    }
    

    Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

    curl

    Simpan isi permintaan dalam file bernama request.json. Jalankan perintah berikut di terminal untuk membuat atau menimpa file ini di direktori saat ini:

    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

    Kemudian, jalankan perintah berikut untuk mengirim permintaan REST Anda:

    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

    Simpan isi permintaan dalam file bernama request.json. Jalankan perintah berikut di terminal untuk membuat atau menimpa file ini di direktori saat ini:

    @'
    {
      "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

    Kemudian jalankan perintah berikut untuk mengirim permintaan REST Anda:

    $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

    Anda akan menerima respons JSON yang mirip dengan yang berikut ini.

    {
      "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"
      }
    }
    

    Konsol

    1. Di konsol Google Cloud , buka halaman Model Garden.

      Buka Model Garden

    2. Temukan model yang didukung yang ingin Anda deploy, lalu klik kartu modelnya.

    3. Klik Deploy untuk membuka panel Deploy model.

    4. Di panel Deploy model, tentukan detail untuk deployment Anda.

      1. Gunakan atau ubah nama model dan endpoint yang dihasilkan.
      2. Pilih lokasi untuk membuat endpoint model Anda.
      3. Pilih jenis mesin yang akan digunakan untuk setiap node deployment Anda.
      4. Untuk menggunakan pemesanan Compute Engine, di bagian Setelan deployment, pilih Lanjutan.

        Untuk kolom Jenis reservasi, pilih jenis reservasi. Reservasi harus sesuai dengan spesifikasi mesin yang Anda tentukan.

        • Gunakan reservasi yang dibuat secara otomatis: Vertex AI secara otomatis memilih reservasi yang diizinkan dengan properti yang cocok. Jika tidak ada kapasitas dalam reservasi yang dipilih secara otomatis, Vertex AI akan menggunakan kumpulan resource umum Google Cloud.
        • Pilih reservasi tertentu: Vertex AI menggunakan reservasi tertentu. Jika tidak ada kapasitas untuk reservasi yang Anda pilih, akan terjadi error.
        • Jangan gunakan (default): Vertex AI menggunakan kumpulan resource Google Cloud umum. Nilai ini memiliki efek yang sama dengan tidak menentukan reservasi.
    5. Klik Deploy.

    Terraform

    Untuk mempelajari cara menerapkan atau menghapus konfigurasi Terraform, lihat Perintah dasar Terraform. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi penyedia Terraform.

    Men-deploy model

    Contoh berikut men-deploy model gemma-3-1b-it ke endpoint Vertex AI baru di us-central1 menggunakan konfigurasi default.

    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
      }
    }
    

    Untuk men-deploy model dengan penyesuaian, lihat Endpoint Vertex AI dengan Deployment Model Garden untuk mengetahui detailnya.

    Terapkan Konfigurasi

    terraform init
    terraform plan
    terraform apply
    

    Setelah Anda menerapkan konfigurasi, Terraform akan menyediakan endpoint Vertex AI baru dan men-deploy model terbuka yang ditentukan.

    Pembersihan

    Untuk menghapus endpoint dan deployment model, jalankan perintah berikut:

    terraform destroy
    

    Menyimpulkan Gemma 1B dengan PredictionServiceClient

    Setelah men-deploy Gemma 1B, Anda menggunakan PredictionServiceClient untuk mendapatkan prediksi online untuk perintah: "Mengapa langit berwarna biru?"

    Parameter kode

    Contoh kode PredictionServiceClient mengharuskan Anda memperbarui hal berikut.

    • PROJECT_ID: Untuk menemukan project ID Anda, ikuti langkah-langkah berikut.

      1. Buka halaman Welcome di konsol Google Cloud .

        Buka Selamat Datang

      2. Dari pemilih project di bagian atas halaman, pilih project Anda.

        Nama project, nomor project, dan project ID muncul setelah judul Selamat datang.

    • ENDPOINT_REGION: Ini adalah region tempat Anda men-deploy endpoint.

    • ENDPOINT_ID: Untuk menemukan ID endpoint, lihat di konsol atau jalankan perintah gcloud ai endpoints list. Anda memerlukan nama dan region endpoint dari panel Deploy model.

      Konsol

      Anda dapat melihat detail endpoint dengan mengklik Online prediction > Endpoints dan memilih region Anda. Perhatikan angka yang muncul di kolom ID.

      Buka Endpoint

      gcloud

      Anda dapat melihat detail endpoint dengan menjalankan perintah gcloud ai endpoints list.

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

      Outputnya akan terlihat seperti ini.

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

    Kode contoh

    Dalam kode contoh untuk bahasa Anda, perbarui PROJECT_ID, ENDPOINT_REGION, dan ENDPOINT_ID. Kemudian jalankan kode Anda.

    Python

    Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python.

    """
    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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Node.js Vertex AI.

    Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

    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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Java Vertex AI.

    Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

    
    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

    Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Go Vertex AI.

    Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

    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
    }
    

    Pembersihan

    Agar tidak perlu membayar biaya pada akun Google Cloud Anda untuk resource yang digunakan dalam tutorial ini, hapus project yang berisi resource tersebut, atau simpan project dan hapus setiap resource.

    Menghapus project

    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.

    Menghapus resource satu per satu

    Jika Anda mempertahankan project, hapus resource yang digunakan dalam tutorial ini:

    • Membatalkan deployment model dan menghapus endpoint
    • Menghapus model dari Model Registry

    Membatalkan deployment model dan menghapus endpoint

    Gunakan salah satu metode berikut untuk membatalkan deployment model dan menghapus endpoint.

    Konsol

    1. Di Google Cloud konsol, klik Prediksi online, lalu klik Endpoint.

      Buka halaman Endpoint

    2. Di menu drop-down Region, pilih region tempat Anda men-deploy endpoint.

    3. Klik nama endpoint untuk membuka halaman detail. Contoh: gemma2-2b-it-mg-one-click-deploy

    4. Di baris untuk model Gemma 2 (Version 1), klik Tindakan, lalu klik Batalkan deployment model dari endpoint.

    5. Pada dialog Batalkan deployment model dari endpoint, klik Batalkan deployment.

    6. Klik tombol Back untuk kembali ke halaman Endpoints.

      Buka halaman Endpoint

    7. Di akhir baris gemma2-2b-it-mg-one-click-deploy, klik Tindakan, lalu pilih Hapus endpoint.

    8. Di perintah konfirmasi, klik Konfirmasi.

    gcloud

    Untuk membatalkan deployment model dan menghapus endpoint menggunakan Google Cloud CLI, ikuti langkah-langkah berikut.

    Dalam perintah ini, ganti:

    • PROJECT_ID dengan nama project Anda
    • LOCATION_ID dengan region tempat Anda men-deploy model dan endpoint
    • ENDPOINT_ID dengan ID endpoint
    • DEPLOYED_MODEL_NAME dengan nama tampilan model
    • DEPLOYED_MODEL_ID dengan ID model
    1. Dapatkan ID endpoint dengan menjalankan perintah gcloud ai endpoints list. Perintah ini mencantumkan ID endpoint untuk semua endpoint di project Anda. Catat ID endpoint yang digunakan dalam tutorial ini.

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

      Outputnya akan terlihat seperti ini. Dalam output, ID disebut ENDPOINT_ID.

      Using endpoint [https://us-central1-aiplatform.googleapis.com/]
      ENDPOINT_ID: 1234567891234567891
      DISPLAY_NAME: gemma2-2b-it-mg-one-click-deploy
      
    2. Dapatkan ID model dengan menjalankan perintah gcloud ai models describe. Catat ID model yang Anda deploy dalam tutorial ini.

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

      Output yang disingkat akan terlihat seperti ini. Dalam output, ID disebut 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. Batalkan deployment model dari endpoint. Anda akan memerlukan ID endpoint dan ID model dari perintah sebelumnya.

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

      Perintah ini tidak menghasilkan output.

    4. Jalankan perintah gcloud ai endpoints delete untuk menghapus endpoint.

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

      Jika diminta, ketik y untuk mengonfirmasi. Perintah ini tidak menghasilkan output.

    Menghapus model

    Konsol

    1. Buka halaman Model Registry dari bagian Vertex AI di konsol Google Cloud .

      Buka halaman Model Registry

    2. Di menu drop-down Region, pilih region tempat Anda men-deploy model.

    3. Di akhir baris gemma2-2b-it-1234567891234, klik Tindakan.

    4. Pilih Hapus model.

      Saat Anda menghapus model, semua versi dan evaluasi model terkait akan dihapus dari Google Cloud project Anda.

    5. Pada perintah konfirmasi, klik Hapus.

    gcloud

    Untuk menghapus model menggunakan Google Cloud CLI, berikan nama tampilan dan region model ke perintah gcloud ai models delete.

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

    Ganti DEPLOYED_MODEL_NAME dengan nama tampilan model. Ganti PROJECT_ID dengan nama project Anda. Ganti LOCATION_ID dengan region tempat Anda men-deploy model.

    Langkah berikutnya