本教學課程將示範如何使用 BigQuery、Cloud Run 和 Gemma LLM,從大型資料集擷取洞察資訊。在本教學課程中,您會將範例應用程式部署至 Google Kubernetes Engine (GKE)。這個範例應用程式會運用 BigQuery 儲存及處理資料、使用 Cloud Run 處理要求,並透過 Gemma LLM 分析資料,以及根據收到的提示生成預測結果。
本教學課程的適用對象為雲端平台管理員和架構師、資料和 AI 專家、機器學習工程師,以及機器學習運作 (DevOps) 專業人員。閱讀本頁面之前,請務必先熟悉 Kubernetes 和 Jupyter 等筆記本環境。
完成「Serve Gemma open models using GPUs on GKE with Hugging Face TGI」(透過 Hugging Face TGI 使用 GKE 中的 GPU 提供 Gemma 開放式模型服務) 教學課程,是本教學課程的先決條件。TGI 架構可簡化模型服務程序。
選用 GKE 和 BigQuery 的理由
BigQuery 是一項平台即服務 (PaaS),提供全代管無伺服器資料倉儲,可對 PB 級資料進行可擴充的分析。BigQuery 可讓您專注於分析資料,找出有意義的洞察資訊,同時使用熟悉的 SQL 和內建機器學習。
在 GKE 上搭配 TGI 使用 GPU,即可部署 Gemma 語言模型,以自然語言分析及摘要使用者互動內容。隨後,只要將 BigQuery 與 GKE 整合,就能使用 BigQuery 有效率地處理大量資料集 (例如 Google Analytics),並運用模型的自然語言理解功能產生有意義的洞察資料。
舉例來說,如果您是電子商務公司的資料科學家、分析師或業務決策者,可能想瞭解網站或應用程式的使用者行為。這類洞察資料有助於最佳化及個人化使用者歷程,並做出明智的業務決策來提高銷售量。
在這種情況下,您可以從 BigQuery 取得原始 Google Analytics 資料,提供給 Gemma 模型,然後以自然語言取得網頁造訪摘要和洞察資料。Gemma 模型在 GKE 的 GPU 加速可擴充基礎架構上執行,可快速處理使用者歷程資料,找出模式和趨勢。您可以取得洞察資料,找出熱門的產品組合、找出結帳程序中常見的流失點,以及找出能將流量帶往特定到達網頁的成功行銷活動。
優點
這項解決方案提供精簡的工作流程,具備下列優點:
- BigQuery 整合:使用 BigQuery 儲存及處理大型資料集 (例如本教學課程中的 Google Analytics 資料)。這樣您就能查詢及彙整模型分析所需的資料。
- GPU 加速:在支援 GPU 的 GKE 叢集上執行 Gemma 模型,加快推論程序,預測速度遠勝 CPU 型處理器。
- 降低成本和時間:使用預先訓練的開放原始碼 Gemma 語言模型,節省時間和資源,不必從頭建構自訂模型。
目標
在本教學課程中,您將瞭解以下內容:
- 部署模型並公開:建立服務 YAML 檔案,定義內部負載平衡器,以便存取 Gemma 模型。
- 建立 BigQuery 遠端函式:執行 Python 程式碼,定義可接收 Google Analytics 資料的遠端函式、為模型建構提示、使用負載平衡器將要求傳送至模型端點,並傳回模型的回應。
- 設定虛擬私有雲 (VPC) 網路:設定 VPC 網路和 VPC 連接器,以便在 BigQuery 和 GKE 叢集之間啟用安全通訊。遠端函式必須存取模型端點,才能正常運作。
- 分析資料:使用 BigQuery DataFrames 分析資料,或使用
bq
指令列工具直接以 SQL 分析資料。在 Colab Enterprise 筆記本中執行提供的程式碼片段,即可:- 使用 SQL 查詢 BigQuery 中的 Google Analytics 資料。
- 將遠端函式套用至資料,從 Gemma 模型產生洞察。
- 顯示結果。
架構
下圖顯示相關元件和互動方式:
- 使用 Colab Enterprise 筆記本執行 Python 程式碼。 使用 Python 時,您可以透過 bigframes 程式庫簡化 SQL 互動。
- BigQuery 是大數據處理引擎,可讓您使用 SQL 處理資料。
- 遠端函式會叫用 Cloud Run 函式。資料會自動傳送至遠端函式,經過準備後再傳送至 GKE 進行推論。
- 結果會傳回 BigQuery,並顯示在表格中。
費用
在本文件中,您會使用 Google Cloud的下列計費元件:
- Compute Engine instances used by GKE
- GPU resources used by GKE
- BigQuery
- Cloud Load Balancing
- Cloud Run functions
如要根據預測用量估算費用,請使用 Pricing Calculator。
完成本文所述工作後,您可以刪除已建立的資源,避免繼續計費。詳情請參閱清除所用資源一節。
事前準備
請務必完成下列必要條件:
選取或建立專案
您可以使用現有專案,或為本教學課程建立新專案。
- 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.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Artifact Registry, Compute Engine, GKE, IAM Service Account Credentials, Cloud Functions, Cloud Build, Cloud Run Admin, Cloud Logging, Serverless VPC Access, BigQuery, Dataform, Vertex AI APIs.
-
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.
-
Make sure that you have the following role or roles on the project: roles/aiplatform.colabEnterpriseAdmin, roles/run.invoker, roles/container.admin, roles/iam.serviceAccountAdmin, roles/logging.logWriter
Check for the roles
-
In the Google Cloud console, go to the IAM page.
Go to IAM - Select the project.
-
In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.
- For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.
Grant the roles
-
In the Google Cloud console, go to the IAM page.
前往 IAM - 選取專案。
- 按一下「授予存取權」 。
-
在「New principals」(新增主體) 欄位中,輸入您的使用者 ID。 這通常是 Google 帳戶的電子郵件地址。
- 在「Select a role」(選取角色) 清單中,選取角色。
- 如要授予其他角色,請按一下 「新增其他角色」,然後新增每個其他角色。
- 按一下 [Save]。
- 將
PROJECT_ID
替換為您的專案 ID。 - 將
PROJECT_NUMBER
替換為專案編號,為專案建構 Compute Engine 預設服務帳戶網域。例如:123456789012-compute@developer.gserviceaccount.com
。 - 將
ROLE
替換為各個角色。 建立下列
tgi-2b-lb-service.yaml
資訊清單:apiVersion: v1 kind: Service metadata: name: llm-lb-service annotations: networking.gke.io/load-balancer-type: "Internal" spec: selector: app: gemma-server type: LoadBalancer ports: - protocol: TCP port: 8000 targetPort: 8000
開啟新的 Cloud Shell 終端機,然後執行下列指令來套用資訊清單:
kubectl apply -f tgi-2b-lb-service.yaml
取得負載平衡器 IP 位址。您可能需要等待 1 到 2 分鐘,才能擷取這個 IP 位址:
kubectl get service llm-lb-service --output yaml | grep ip:
前往 Google Cloud 控制台的「Colab Enterprise Notebooks」頁面:
在「Region」(區域) 選單中選取「
us-central1
」。您在本教學課程中建立的所有服務,都位於這個區域。按一下「檔案」旁的「建立筆記本」。
- 按一下「+ 程式碼」,插入新的程式碼儲存格。
在新的程式碼儲存格中複製下列程式碼:
# Install the necessary packages on the notebook runtime %pip install --upgrade bigframes --quiet import bigframes.pandas as bpd import os import ast import requests # Replace the following variables # Use the format ip:port # For example, "10.128.05:8000" lb_url = "LOADBALANCER_IP_ADDRESS:8000" # Set BigQuery DataFrames options bpd.options.bigquery.project = "PROJECT_ID" bpd.options.bigquery.location = "US" # Update the VPC connector name with the one you created vpc_connector_name = "VPC_CONNECTOR_NAME" # Create a remote function using bigframes # https://cloud.google.com/bigquery/docs/remote-functions#bigquery-dataframes @bpd.remote_function( dataset="ga_demo", name="ga_explain_example", bigquery_connection="bigframes-rf-conn", reuse=True, packages=["requests"], cloud_function_vpc_connector=VPC_CONNECTOR_NAME, cloud_function_service_account="default", ) def process_incoming(data: str) -> str: ga_data = ast.literal_eval(data) USER_PROMPT = """ 'The following are the results from Google Analytics. They are reverse ranked. reverse_event_number 1 is the last page visited. reverse_event_number 2 is the second last page visited. You are given the following data. {} Can you summarize what was the most popular page people landed on and what page they came from? """.format(ga_data) url = 'http://{}/generate'.format(lb_url) myobj = { "inputs": USER_PROMPT, "temperature": 0.90, "top_p": 0.95, "max_tokens": 2048 } x = requests.post(url, json=myobj) result = x.text return (result) function_name = process_incoming.bigframes_remote_function print (f"The function name is: {function_name}")
更改下列內容:
LOADBALANCER_IP_ADDRESS
:您先前建立的內部負載平衡器的 IP 位址和通訊埠,例如10.128.05:8000
。PROJECT_ID
:您的專案 ID。VPC_CONNECTOR_NAME
:您先前建立的無伺服器虛擬私有雲存取連接器名稱。
在本教學課程中,BigQuery 資料集的位置設為
US
,預設為us-central1
地區。按一下「執行儲存格」圖示
。- 使用 BigQuery DataFrames
- 使用
bq
指令列工具,直接在 SQL 中執行查詢。 - 按一下「+ 程式碼」,插入新的程式碼儲存格。
- 將下列程式碼複製到新的程式碼儲存格中,然後按一下「執行儲存格」 。
- 按一下「+ 程式碼」,插入新的程式碼儲存格。
在新的程式碼儲存格中複製下列程式碼,並將
PROJECT_ID
替換為您的專案 ID。# Update with your PROJECT_ID function_name = 'PROJECT_ID.ga_demo.ga_explain_example' new_sql = """'with \ data_table as ( \ SELECT \ distinct \ user_pseudo_id, \ events.value.string_value, \ event_timestamp, \ rank() over (partition by user_pseudo_id order by event_timestamp desc) as reverse_event_number \ FROM \ `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131` as events20210131, \ unnest (events20210131.event_params) as events \ where events.key = "page_location" \ qualify reverse_event_number < 3 \ ) \ select \ *, `{}`(TO_JSON_STRING (data_table)) as result \ from data_table \ limit 10;' \ """.format(function_name) # Run query using bq cli directly in a notebook cell !bq query --use_legacy_sql=false \ {new_sql}
按一下「執行儲存格」圖示
。- 刪除 Colab Enterprise 筆記本。
- 刪除 Colab Enterprise 執行階段。
- 刪除 BigQuery 函式。
請確認服務帳戶具備「
bigquery.routines.delete
」權限。 詳情請參閱 BigQuery 權限。 - 刪除 BigQuery 外部連結。
- 刪除 Cloud Run 函式。
- 刪除 GKE 叢集。
- 刪除虛擬私有雲連接器。
- 試用實作程式碼研究室,瞭解結構化和非結構化資料分析的使用情境。
- 請參閱「在 GKE 上執行批次工作負載的最佳做法」。
- 進一步瞭解 BigQuery 中的 AI/ML 應用實例。
- 進一步瞭解 GKE 中的 AI/機器學習應用實例。
將角色授予 Compute Engine 預設服務帳戶。針對下列每個 IAM 角色執行一次下列指令:
roles/logging.logWriter, roles/artifactregistry.writer, roles/storage.objectViewer
gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com" --role=ROLE
提供 Gemma 模型
前往「使用 Hugging Face TGI 在 GKE 上透過 GPU 提供 Gemma 開放式模型」教學課程,按照「事前準備」到「使用 curl 與模型互動」的說明操作,確保 Gemma 模型部署成功,且您可以與模型互動。
在本教學課程中,請部署 Gemma 2B-it 模型。
設定虛擬私有雲網路
在
us-central1
區域中建立或使用 VPC 網路,讓遠端函式可以連線至 GKE 叢集。在本教學課程中,請使用Default
VPC。為確保 BigQuery 資料集、遠端函式和基礎 Cloud Run 函式部署在相容的位置,VPC 網路必須與 BigQuery 遠端函式位於相同區域。在本教學課程中,您建立遠端函式時設定 BigQuery DataFrame 選項,並指定
US
做為資料集的位置,預設為 Cloud Run 函式的us-central1
區域。因此,請在us-central1
地區建立或使用虛擬私有雲。建立負載平衡器
請按照下列操作說明,在 GKE 叢集中建立內部負載平衡器:
您將使用這個 IP 位址,與負載平衡器後方執行的
gemma-server
應用程式通訊。建立連接器
您可以使用無伺服器虛擬私有雲存取連接器,透過虛擬私有雲網路傳送及接收要求,不必使用公開網際網路。詳情請參閱無伺服器虛擬私有雲存取。
在本教學課程中,您將建立具有新專屬子網路的連接器,避免與虛擬私有雲中的現有資源發生 IP 位址衝突。如需操作說明,請參閱「建立連接器」一節,並按照「建立連接器和新的子網路」一節的
gcloud
操作說明操作。如要使用現有子網路,請按照「使用現有子網路建立連接器」一節的說明操作。
會強制執行這項規定。詳情請參閱「連接器子網路需求」。
建立筆記本
在本教學課程中,您將使用 Colab Enterprise 筆記本執行所有程式碼,定義 BigQuery 遠端函式並執行分析。
如要透過 Google Cloud 控制台建立 Colab Enterprise 筆記本,請按照下列步驟操作:
新的筆記本就會出現在「My notebooks」(我的筆記本) 分頁中。
如要在新筆記本中執行程式碼,請在筆記本中為每個指令或程式碼片段插入新的程式碼儲存格。
建立 BigQuery 遠端函式
您可以使用
bigframes
程式庫定義 BigQuery 遠端函式。在本節中,請使用bigframes
建立名為process_incoming
的遠端函式。這項遠端函式會將 Google Analytics 資料做為輸入內容、建構提示,並傳送至 Gemma 模型進行分析。在您建立的 Colab Enterprise 筆記本中:
輸出內容會顯示函式名稱,如下所示:
The function name is: PROJECT_ID.ga_demo.ga_explain_example
分析使用者行為
在本節中,您將使用
process_incoming
遠端函式,透過下列任一方式分析網站上的使用者行為:使用 BigQuery DataFrames
如要使用您建立的 Colab Enterprise 筆記本,透過 BigQuery DataFrames 執行遠端函式,請按照下列步驟操作:
# Generate a list of all matchups and their histories as a JSON grouping_sql = """ with data_table as ( SELECT distinct user_pseudo_id, events.value.string_value, event_timestamp, rank() over (partition by user_pseudo_id order by event_timestamp desc) as reverse_event_number FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131` as events20210131, unnest (events20210131.event_params) as events where events.key = 'page_location' qualify reverse_event_number < 3 ) select *,TO_JSON_STRING (data_table) as ga_history from data_table limit 10; """ ga_df = bpd.read_gbq(grouping_sql) post_processed = ga_df.assign(results=ga_df['ga_history'].apply(process_incoming),axis=1) post_processed.head(10)
以下輸出內容顯示查詢的範例結果:
user_pseudo_id string_value event_timestamp reverse_event_number ga_history 結果 軸 0 2342103247.0307162928 https://shop.googlemerchandisestore.com/Google... 1612096237169825 2 {"user_pseudo_id":"2342103247.0307162928","str... {"generated_text":"\n 'The following are... 1 48976087.6959390698 https://www.googlemerchandisestore.com/ 1612056537823270 2 {"user_pseudo_id":"48976087.6959390698","strin... {"generated_text":"\n \n ```python\n imp... 使用
bq
指令列工具或者,您也可以使用
bq
指令列工具,直接使用 SQL 執行分析。如要在您建立的 Colab Enterprise 筆記本中,使用
bq
指令列工具執行遠端函式,請按照下列步驟操作:以下輸出內容顯示查詢的範例結果:
user_pseudo_id string_value event_timestamp reverse_event_number result 86037838.0267811614 https://shop.googlemerchandisestore.com/Google+Redesign/Apparel/Google+Dino+Game+Tee 1612128627715585 1 {"generated_text":"Answer:\n The most popular page was https://shop.googlemerchandisestore.com/Google+Redesign/Apparel/Google+Dino+Game+Tee\n The next most popular page was the page they came from.\n\n Explanation:\n\nThe provided data shows that the current user visited Google's merchandise store specifically for the product "Google Dino Game Tee." \n \n重要考量:\n\n* 資料解讀:您無法明確指出「} 4024190.3037653934 https://shop.googlemerchandisestore.com/Google+Redesign/Apparel/Google+Black+Cloud+Zip+Hoodie 1612085948486438 1 {"generated_text":"\n ```python\n import pandas as pd\n\n data = {'user_pseudo_id': ['4024190.3037653934', '4024190.3037653934', '4024190.3037653934'],\n 'string_value': ['https://shop.googlemerchandisestore.com"} 清除所用資源
如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。
如要避免系統向您的 Google Cloud 帳戶收取本教學課程所用資源的費用,請刪除個別資源。
後續步驟
-
啟用 API
設定 Cloud Shell
在本教學課程中,您將使用 Cloud Shell 執行 gcloud
和 kubectl
指令。Cloud Shell 是殼層環境,用於管理 Google Cloud上託管的資源。這個環境已預先安裝 Google Cloud CLI 和 kubectl 指令列工具。
此時 Cloud Shell 工作階段會在控制台底部的頁框中開啟,
在本教學課程中執行指令前,請務必將預設專案設為要部署範例應用程式的專案 ID。如果尚未設定,請在 Cloud Shell 中執行下列指令:
gcloud config set project PROJECT_ID
將 PROJECT_ID
替換為專案 ID。
授予 IAM 角色
請確認您的使用者帳戶和專案中的 Compute Engine 預設服務帳戶,都具備本教學課程所需的身分與存取權管理 (IAM) 角色。