使用 Gemma 開放式模型和 ML.GENERATE_TEXT 函式生成文字

本教學課程將說明如何建立遠端模型,以Gemma 模型為基礎,然後如何搭配使用該模型和 ML.GENERATE_TEXT 函式,從 bigquery-public-data.imdb.reviews 公開資料表中擷取關鍵字,並對電影評論執行情緒分析。

所需權限

  • 如要建立資料集,您必須具備 bigquery.datasets.create 身分與存取權管理 (IAM) 權限。
  • 如要建立連線資源,您必須具備下列 IAM 權限:

    • bigquery.connections.create
    • bigquery.connections.get
  • 如要將權限授予連線的服務帳戶,您必須具備下列權限:

    • resourcemanager.projects.setIamPolicy
  • 您必須具備下列權限,才能建立模型:

    • bigquery.jobs.create
    • bigquery.models.create
    • bigquery.models.getData
    • bigquery.models.updateData
    • bigquery.connections.delegate
  • 如要執行推論,您需要具備下列權限:

    • bigquery.models.getData
    • bigquery.jobs.create

費用

在本文件中,您會使用 Google Cloud的下列計費元件:

  • BigQuery ML: You incur costs for the data that you process in BigQuery.
  • Vertex AI: You incur costs for calls to the Vertex AI model that's represented by the remote model.

您可以使用 Pricing Calculator 根據預測用量產生預估費用。 新 Google Cloud 使用者可能符合申請免費試用的資格。

如要進一步瞭解 BigQuery 定價,請參閱 BigQuery 說明文件中的「BigQuery 定價」一節。

您部署至 Vertex AI 的開放式模型會依機器小時計費。也就是說,只要端點完全設定完成,系統就會開始計費,並持續計費,直到您取消部署為止。如要進一步瞭解 Vertex AI 定價,請參閱 Vertex AI 定價頁面。

事前準備

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

    Go to project selector

  2. Make sure that billing is enabled for your Google Cloud project.

  3. Enable the BigQuery, BigQuery Connection, and Vertex AI APIs.

    Enable the APIs

在 Vertex AI 上部署 Gemma 模型

按照「部署 Model Garden 模型」一文中的指示,將 gemma-2-27b-it 模型部署至 Vertex AI。在部署期間,您必須選取「公開 (共用端點)」做為部署工作流程中「端點存取權」欄位的值。

建立資料集

建立 BigQuery 資料集來儲存機器學習模型。

控制台

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往「BigQuery」頁面

  2. 在「Explorer」窗格中,按一下專案名稱。

  3. 依序點選 「View actions」(查看動作) >「Create dataset」(建立資料集)

    「建立資料集」選單選項。

  4. 在「Create dataset」頁面上執行下列操作:

    • 在「Dataset ID」(資料集 ID) 中輸入 bqml_tutorial

    • 在「位置類型」中選取「多區域」,然後選取「美國 (多個美國區域)」

    • 保留其餘預設設定,然後點選「Create dataset」(建立資料集)

bq

如要建立新的資料集,請使用 bq mk 指令搭配 --location 旗標。如需可能參數的完整清單,請參閱 bq mk --dataset 指令參考資料。

  1. 建立名為 bqml_tutorial 的資料集,並將資料位置設為 US,說明為 BigQuery ML tutorial dataset

    bq --location=US mk -d \
     --description "BigQuery ML tutorial dataset." \
     bqml_tutorial

    這個指令採用 -d 捷徑,而不是使用 --dataset 旗標。如果您省略 -d--dataset,該指令預設會建立資料集。

  2. 確認資料集已建立:

    bq ls

API

請呼叫 datasets.insert 方法,搭配已定義的資料集資源

{
  "datasetReference": {
     "datasetId": "bqml_tutorial"
  }
}

BigQuery DataFrames

在嘗試這個範例之前,請先參閱 BigQuery 快速入門:使用 BigQuery DataFrames,按照 BigQuery DataFrames 設定說明進行操作。詳情請參閱 BigQuery DataFrames 參考資料說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定 ADC」。

import google.cloud.bigquery

bqclient = google.cloud.bigquery.Client()
bqclient.create_dataset("bqml_tutorial", exists_ok=True)

建立連線

建立 Cloud 資源連線,並取得連線的服務帳戶。請在先前步驟中建立的資料集位置中建立連線。

如果您已設定具備適當權限的預設連線,可以略過這個步驟。

為遠端模型建立Cloud 資源連線,並取得連線的服務帳戶。請在與您在上一個步驟中建立的資料集相同的位置建立連線。

選取下列選項之一:

主控台

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在「Explorer」窗格中,按一下 「新增資料」

    「新增資料」UI 元素。

    「Add data」對話方塊隨即開啟。

  3. 在「Filter By」窗格中的「Data Source Type」部分,選取「Business Applications」

    或者,您也可以在「Search for data sources」欄位中輸入 Vertex AI

  4. 在「精選資料來源」部分,按一下「Vertex AI」

  5. 按一下「Vertex AI 模型:BigQuery 聯盟」解決方案資訊卡。

  6. 在「連線類型」清單中,選取「Vertex AI 遠端模型、遠端函式和 BigLake (Cloud 資源)」

  7. 在「連線 ID」欄位中,輸入連線的名稱。

  8. 點選「建立連線」

  9. 按一下「前往連線」

  10. 在「連線資訊」窗格中,複製服務帳戶 ID,以便在後續步驟中使用。

bq

  1. 在指令列環境中建立連線:

    bq mk --connection --location=REGION --project_id=PROJECT_ID \
        --connection_type=CLOUD_RESOURCE CONNECTION_ID

    --project_id 參數會覆寫預設專案。

    更改下列內容:

    • REGION:您的連線區域
    • PROJECT_ID:您的 Google Cloud 專案 ID
    • CONNECTION_ID:連線 ID

    建立連線資源時,BigQuery 會建立專屬的系統服務帳戶,並將該帳戶與連線建立關聯。

    疑難排解:如果您收到下列連線錯誤,請更新 Google Cloud SDK

    Flags parsing error: flag --connection_type=CLOUD_RESOURCE: value should be one of...
    
  2. 擷取並複製服務帳戶 ID,以便在後續步驟中使用:

    bq show --connection PROJECT_ID.REGION.CONNECTION_ID

    輸出結果會與下列內容相似:

    name                          properties
    1234.REGION.CONNECTION_ID     {"serviceAccountId": "connection-1234-9u56h9@gcp-sa-bigquery-condel.iam.gserviceaccount.com"}
    

Terraform

使用 google_bigquery_connection 資源。

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

以下範例會在 US 地區中建立名為 my_cloud_resource_connection 的 Cloud 資源連線:


# This queries the provider for project information.
data "google_project" "default" {}

# This creates a cloud resource connection in the US region named my_cloud_resource_connection.
# Note: The cloud resource nested object has only one output field - serviceAccountId.
resource "google_bigquery_connection" "default" {
  connection_id = "my_cloud_resource_connection"
  project       = data.google_project.default.project_id
  location      = "US"
  cloud_resource {}
}

如要在 Google Cloud 專案中套用 Terraform 設定,請完成下列各節中的步驟。

準備 Cloud Shell

  1. 啟動 Cloud Shell
  2. 設定要套用 Terraform 設定的預設 Google Cloud 專案。

    您只需為每個專案執行這個指令一次,而且可以在任何目錄中執行。

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    如果您在 Terraform 設定檔中設定明確的值,系統就會覆寫環境變數。

準備目錄

每個 Terraform 設定檔都必須有自己的目錄 (也稱為根模組)。

  1. Cloud Shell 中建立目錄,並在該目錄中建立新檔案。檔案名稱必須包含 .tf 副檔名,例如 main.tf。在本教學課程中,檔案稱為 main.tf
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. 如果您正在參考教學課程,可以複製各個章節或步驟中的程式碼範例。

    將範例程式碼複製到新建立的 main.tf 中。

    您可以視需要從 GitHub 複製程式碼。如果 Terraform 程式碼片段是端對端解決方案的一部分,建議您採用這種做法。

  3. 查看並修改要套用至環境的範例參數。
  4. 儲存變更。
  5. 初始化 Terraform。這項操作只需對每個目錄執行一次。
    terraform init

    如要使用最新版的 Google 供應器,您可以選擇加入 -upgrade 選項:

    terraform init -upgrade

套用變更

  1. 檢查設定,確認 Terraform 要建立或更新的資源符合您的預期:
    terraform plan

    視需要修正設定。

  2. 執行下列指令,並在提示中輸入 yes,即可套用 Terraform 設定:
    terraform apply

    等待 Terraform 顯示「Apply complete!」(套用完成) 訊息。

  3. 開啟 Google Cloud 專案即可查看結果。在 Google Cloud 控制台中,前往 UI 中的資源,確認 Terraform 已建立或更新這些資源。

將權限授予連線的服務帳戶

為連線的服務帳戶授予 Vertex AI 使用者角色。您必須在開始前一節中建立或選取的專案中授予此角色。在其他專案中授予角色會導致 bqcx-1234567890-xxxx@gcp-sa-bigquery-condel.iam.gserviceaccount.com does not have the permission to access resource 錯誤。

如要授予角色,請按照下列步驟操作:

  1. 前往「IAM & Admin」(IAM 與管理) 頁面。

    前往「IAM & Admin」(IAM 與管理)

  2. 按一下 「授予存取權」

  3. 在「新增主體」欄位,輸入先前複製的服務帳戶 ID。

  4. 在「請選擇角色」欄位中,依序選擇「Vertex AI」和「Vertex AI 使用者角色」

  5. 按一下 [儲存]

建立遠端模型

建立代表已代管 Vertex AI 模型的遠端模型:

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往 BigQuery

  2. 在查詢編輯器中執行下列陳述式:

CREATE OR REPLACE MODEL `bqml_tutorial.gemma_model`
  REMOTE WITH CONNECTION `LOCATION.CONNECTION_ID`
  OPTIONS (ENDPOINT = 'https://ENDPOINT_REGION-aiplatform.googleapis.com/v1/projects/ENDPOINT_PROJECT_ID/locations/ENDPOINT_REGION/endpoints/ENDPOINT_ID');

更改下列內容:

  • LOCATION:連線位置。
  • CONNECTION_ID:BigQuery 連線的 ID。

    在 Google Cloud 控制台查看連線詳細資料時,這是連線 ID 中顯示的完整限定連線 ID 最後一節的值,例如 projects/myproject/locations/connection_location/connections/myconnection

  • ENDPOINT_REGION:開放式模型的部署區域。
  • ENDPOINT_PROJECT_ID:部署開放式模型的專案。
  • ENDPOINT_ID:開放式模型使用的 HTTPS 端點 ID。如要取得端點 ID,請在「線上預測」頁面上找出已開放的模型,然後複製「ID」欄位中的值。

以下範例顯示有效 HTTP 端點的格式:

https://us-central1-aiplatform.googleapis.com/v1/projects/myproject/locations/us-central1/endpoints/1234

查詢需要幾秒鐘的時間才能完成,完成後,gemma_model 模型就會顯示在「Explorer」窗格中的 bqml_tutorial 資料集中。由於查詢是使用 CREATE MODEL 陳述式建立模型,因此沒有查詢結果。

執行關鍵字擷取

使用遠端模型和 ML.GENERATE_TEXT 函式,對 IMDB 電影評論執行關鍵字擷取作業:

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往 BigQuery

  2. 在查詢編輯器中輸入以下陳述式,針對五則電影評論執行關鍵字擷取作業:

    SELECT
      *
    FROM
      ML.GENERATE_TEXT(
        MODEL `bqml_tutorial.gemma_model`,
        (
          SELECT
            CONCAT('Extract the key words from the movie review below: ', review) AS prompt,
            *
          FROM
            `bigquery-public-data.imdb.reviews`
          LIMIT 10
        ),
        STRUCT(
          0.2 AS temperature,
          100 AS max_output_tokens,
          TRUE AS flatten_json_output));

    輸出結果會與下列內容相似,為了方便閱讀,我們省略了未產生的資料欄:

    +----------------------------------------------+-------------------------+-----------------------------+-----+
    | generated_text                               | ml_generate_text_status | prompt                      | ... |
    +----------------------------------------------+-------------------------------------------------------+-----+
    | Here are some key words from the             |                         | Extract the key words from  |     |
    | movie review: * **Romance:**                 |                         | the movie review below:     |     |
    | "romantic tryst," "elope" * **Comedy:**      |                         | Linda Arvidson (as Jennie)  |     |
    | "Contrived Comedy" * **Burglary:**           |                         | and Harry Solter (as Frank) |     |
    | "burglar," "rob," "booty" * **Chase:**       |                         | are enjoying a romantic     |     |
    | "chases," "escape" * **Director:** "D.W.     |                         | tryst, when in walks her    |     |
    | Griffith" * **Actors:** "Linda Arvidson,"... |                         | father Charles Inslee;...   |     |
    +----------------------------------------------+-------------------------+-----------------------------+-----+
    | Here are some key words from the             |                         | Extract the key words from  |     |
    | movie review: * **Elderbush Gilch:** The     |                         | the movie review below:     |     |
    | name of the movie being reviewed. *          |                         | This is the second addition |     |
    | **Disappointment:** The reviewer's           |                         | to Frank Baum's personally  |     |
    | overall feeling about the film. *            |                         | produced trilogy of Oz      |     |
    | **Dim-witted:** Describes the story          |                         | films. It's essentially the |     |
    | line negatively. * **Moronic, sadistic,...   |                         | same childishness as the... |     |
    +----------------------------------------------+-------------------------+-----------------------------+-----+
    

    結果包含下列資料欄:

    • generated_text:系統產生的文字。
    • ml_generate_text_status:對應資料列的 API 回應狀態。如果作業成功,這個值會為空白。
    • prompt:用於情緒分析的提示。
    • bigquery-public-data.imdb.reviews 資料表的所有欄。

執行情緒分析

使用遠端模型和 ML.GENERATE_TEXT 函式,對 IMDB 電影評論執行情緒分析:

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往 BigQuery

  2. 在查詢編輯器中執行下列陳述式,對五則電影評論執行情緒分析:

    SELECT
      *
    FROM
      ML.GENERATE_TEXT(
        MODEL `bqml_tutorial.gemma_model`,
        (
          SELECT
            CONCAT('Analyze the sentiment of the following movie review and classify it as either POSITIVE or NEGATIVE. \nMovie Review: ', review) AS prompt,
            *
          FROM
            `bigquery-public-data.imdb.reviews`
          LIMIT 10
        ),
        STRUCT(
          0.2 AS temperature,
          128 AS max_output_tokens,
          TRUE AS flatten_json_output));

    輸出結果會與下列內容類似,為了方便閱讀,我們省略了未產生的資料欄:

    +----------------------------------------------+-------------------------+-----------------------------+-----+
    | generated_text                               | ml_generate_text_status | prompt                      | ... |
    +----------------------------------------------+-------------------------------------------------------+-----+
    | Sentiment: NEGATIVE Justification:   |                         | Analyze the sentiment of    |     |
    | * Negative Language: The reviewer uses   |                         | movie review and classify   |     |
    | phrases like "don't quite make it," "come to |                         | it as either POSITIVE or    |     |
    | mind," "quite disappointing," and "not many  |                         | NEGATIVE. Movie Review:     |     |
    | laughs." * Specific Criticisms: The      |                         | Although Charlie Chaplin    |     |
    | reviewer points out specific flaws in the    |                         | made some great short       |     |
    | plot and humor, stating that the manager...  |                         | comedies in the late...     |     |
    +----------------------------------------------+-------------------------+-----------------------------+-----+
    | Sentiment: NEGATIVE Reasoning:       |                         | Analyze the sentiment of    |     |
    | * Negative Language: The reviewer uses   |                         | movie review and classify   |     |
    | phrases like "poor writing," "static camera- |                         | it as either POSITIVE or    |     |
    | work," "chews the scenery," "all surface and |                         | NEGATIVE. Movie Review:     |     |
    | no depth," "sterile spectacles," which all   |                         | Opulent sets and sumptuous  |     |
    | carry negative connotations. * Comparison  |                         | costumes well photographed  |     |
    | to a More Successful Film:...              |                         | by Theodor Sparkuhl, and... |     |
    +----------------------------------------------+-------------------------+-----------------------------+-----+
    

    結果包含與執行關鍵字擷取所述相同的資料欄。

取消部署模型

如果您選擇不按照建議刪除專案,請務必在 Vertex AI 中取消部署 Gemma 模型,以免繼續收取相關費用。

清除所用資源

  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.