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

Dalam tutorial ini, Anda akan menggunakan Model Garden untuk men-deploy model terbuka Gemma 2B ke endpoint Vertex AI yang didukung TPU. 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 2B, Anda akan melakukan inferensi pada model terlatih menggunakan PredictionServiceClient untuk mendapatkan prediksi online. Prediksi online adalah permintaan sinkron yang dibuat ke model yang di-deploy ke endpoint.

Men-deploy Gemma menggunakan Model Garden

Anda men-deploy model Gemma 2B ke jenis mesin Compute Engine ct5lp-hightpu-1t yang dioptimalkan untuk pelatihan skala kecil hingga sedang. Mesin ini memiliki satu akselerator TPU v5e. Untuk mengetahui informasi selengkapnya tentang melatih model menggunakan TPU, lihat Pelatihan Cloud TPU v5e.

Dalam tutorial ini, Anda akan men-deploy model terbuka Gemma 2B yang disesuaikan dengan instruksi menggunakan kartu model di Model Garden. Versi model tertentu adalah gemma2-2b-it-it adalah singkatan dari instruction-tuned.

Model Gemma 2B memiliki ukuran parameter yang lebih kecil, yang berarti persyaratan resource yang lebih rendah dan fleksibilitas deployment yang lebih tinggi.

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

    Buka Model Garden

  2. Klik kartu model Gemma 2.

    Buka Gemma 2

  3. Klik Deploy untuk membuka panel Deploy model.

  4. Di panel Deploy model, tentukan detail ini.

    1. Untuk Deployment environment, klik Vertex AI.

    2. Di bagian Deploy model:

      1. Untuk Resource ID, pilih gemma-2b-it.

      2. Untuk Model name dan Endpoint name, terima nilai default. Contoh:

        • Nama model: gemma2-2b-it-1234567891234
        • Nama endpoint: gemma2-2b-it-mg-one-click-deploy

        Catat nama endpoint. Anda akan memerlukannya untuk menemukan ID endpoint yang digunakan dalam contoh kode.

    3. Di bagian Deployment settings:

      1. Terima opsi default untuk setelan Basic.

      2. Untuk Region, terima nilai default atau pilih wilayah dari daftar. Catat regionnya. Anda akan memerlukannya untuk contoh kode.

      3. Untuk Machine spec, pilih instance yang didukung TPU: ct5lp-hightpu-1t (1 TPU_V5_LITEPOD; ct5lp-hightpu-1t).

  5. Klik Deploy. Saat deployment selesai, Anda akan menerima email yang berisi detail tentang endpoint baru Anda. Anda juga dapat melihat detail endpoint dengan mengklik Prediksi online > Endpoint dan memilih region Anda.

    Buka Endpoint

Menyimpulkan Gemma 2B dengan PredictionServiceClient

Setelah men-deploy Gemma 2B, 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 TPU 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 TPUs
# Example format: [{'prompt': 'Why is the sky blue?', 'temperature': 0.9}]
input = {"prompt": prompt}
input.update(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.

// 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';

// Prompt used in the prediction
const prompt = 'Why is the sky blue?';

// Encapsulate the prompt in a correct format for TPUs
// Example format: [{prompt: 'Why is the sky blue?', temperature: 0.9}]
const input = {
  prompt,
  // Parameters for default configuration
  maxOutputTokens: 1024,
  temperature: 0.9,
  topP: 1.0,
  topK: 1,
};

// 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);

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 Gemma2PredictTpu {
  private final PredictionServiceClient predictionServiceClient;

  // Constructor to inject the PredictionServiceClient
  public Gemma2PredictTpu(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-west1";
    String endpointId = "YOUR_ENDPOINT_ID";

    PredictionServiceSettings predictionServiceSettings =
        PredictionServiceSettings.newBuilder()
            .setEndpoint(String.format("%s-aiplatform.googleapis.com:443", endpointRegion))
            .build();
    PredictionServiceClient predictionServiceClient =
        PredictionServiceClient.create(predictionServiceSettings);
    Gemma2PredictTpu creator = new Gemma2PredictTpu(predictionServiceClient);

    creator.gemma2PredictTpu(projectId, endpointRegion, endpointId);
  }

  // Demonstrates how to run inference on a Gemma2 model
  // deployed to a Vertex AI endpoint with TPU accelerators.
  public String gemma2PredictTpu(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 = "{ \"prompt\": \"Why is the sky blue?\"}";
    Value.Builder instanceValue = Value.newBuilder();
    JsonFormat.parser().merge(instance, instanceValue);
    // Encapsulate the prompt in a correct format for TPUs
    // Example format: [{'prompt': 'Why is the sky blue?', 'temperature': 0.9}]
    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"
)

// predictTPU demonstrates how to run interference on a Gemma2 model deployed to a Vertex AI endpoint with TPU accelerators.
func predictTPU(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.
	// Example format: [{'prompt': 'Why is the sky blue?', 'temperature': 0.9}]
	promptValue, err := structpb.NewValue(map[string]interface{}{
		"prompt":     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
}