建立管道

Agent Platform Pipelines 可讓您以無伺服器的方式,自動化調度管理機器學習 (ML) 工作流程。您必須先將工作流程定義為 pipeline,Agent Platform Pipelines 才能自動化調度管理機器學習工作流程。機器學習管道是可攜式且可擴充的機器學習工作流程,以容器和 Google Cloud 服務為基礎。

本指南說明如何開始建構機器學習管道。

我該使用哪一個管道 SDK?

Agent Platform Pipelines 可執行使用下列任一 SDK 建構的管道:

  • Kubeflow Pipelines SDK 2.0 以上版本

  • TensorFlow Extended 0.30.0 以上版本

如果您在機器學習工作流程中使用 TensorFlow 處理 TB 規模的結構化資料或文字資料,建議您使用 TFX 建構管道。

如為其他用途,建議您使用 Kubeflow Pipelines SDK 建構管道。使用 Kubeflow Pipelines SDK 建構 pipeline 時,您可以建構自訂元件或重複使用預先建構的元件 (例如 Google Cloud Pipeline 元件),藉此實作工作流程。Google Cloud Pipeline 元件可讓您在管道中更輕鬆地使用 Gemini Enterprise Agent Platform 服務,例如 AutoML。

本指南說明如何使用 Kubeflow Pipelines SDK 建構管道。

事前準備

建構及執行管道前,請按照下列操作說明設定 Google Cloud 專案和開發環境。

  1. 如要準備好 Google Cloud 專案來執行機器學習管道,請按照指南中的操作說明設定Google Cloud 專案。

  2. 安裝 Kubeflow Pipelines SDK 2 以上版本。

    pip install --upgrade "kfp>=2,<3"
    
  1. 如要在管道中使用 Gemini Enterprise Agent Platform Python 用戶端,請安裝 Gemini Enterprise Agent Platform 用戶端程式庫 1.7 以上版本。

  2. 如要在管道中使用 Gemini Enterprise Agent Platform 服務,請安裝Google Cloud SDK。

開始建構管道

如要在 Agent Platform Pipelines 自動化調度管理機器學習工作流程,您必須先將工作流程描述為管道。下列範例說明如何搭配使用 Google Cloud Pipeline 元件和 Gemini Enterprise Agent Platform,建立資料集、使用 AutoML 訓練模型,以及部署訓練後的模型來進行預測。

執行下列程式碼範例前,請務必先設定驗證機制。

如何設定驗證

如要設定驗證機制,您必須建立服務帳戶金鑰,並為服務帳戶金鑰的路徑設定環境變數。

  1. 建立服務帳戶:

    1. 前往 Google Cloud 控制台的「Create service account」(建立服務帳戶) 頁面。

      前往「Create service account」(建立服務帳戶) 頁面

    2. 在 [Service account name] (服務帳戶名稱) 欄位中輸入一個名稱。
    3. (選用) 在「Service account description」(服務帳戶說明) 欄位中輸入說明。
    4. 點選「建立」。
    5. 按一下「請選擇角色」欄位。在「所有角色」下方,依序選取「Gemini Enterprise Agent Platform」 >「Agent Platform 使用者」。
    6. 按一下「Done」(完成),建立服務帳戶。

      請勿關閉瀏覽器視窗,後續步驟會用到。

  2. 建立用於驗證的服務帳戶金鑰:

    1. 在 Google Cloud 控制台中,點按您建立的服務帳戶電子郵件地址。
    2. 點按「Keys」(金鑰)。
    3. 依序點選「新增金鑰」和「建立新的金鑰」。
    4. 點選「建立」。系統會將 JSON 金鑰檔案下載至您的電腦。
    5. 按一下 [關閉]。
  3. 將您用來執行管道的服務帳戶存取權,授予新的服務帳戶。
    1. 按一下 即可返回服務帳戶清單。
    2. 按一下用來執行管道的服務帳戶名稱。「Service account details」(服務帳戶詳細資料) 頁面隨即顯示。

      如果您按照指南中的操作說明,為 Gemini Enterprise Agent Platform Pipelines 設定專案,這個服務帳戶就是您在「設定具備精細權限的服務帳戶」一節中建立的服務帳戶。否則,Gemini Enterprise Agent Platform 會使用 Compute Engine 預設服務帳戶執行管道。Compute Engine 預設服務帳戶的名稱如下:PROJECT_NUMBER-compute@developer.gserviceaccount.com

    3. 按一下「Permissions」(權限) 分頁標籤。
    4. 按一下「Grant access」(授予存取權)。「Add principals」(新增主體) 面板隨即顯示。
    5. 在「New principals」(新增主體) 方塊中,輸入您在先前步驟中建立的服務帳戶電子郵件地址。
    6. 在「Role」(角色) 下拉式選單中,依序選取「Service accounts」(服務帳戶) >「Service account user」(服務帳戶使用者)。
    7. 按一下「儲存」
  4. 將環境變數 GOOGLE_APPLICATION_CREDENTIALS 設為包含服務帳戶金鑰的 JSON 檔案路徑。這項變數僅適用於您目前的殼層工作階段,因此如果您開啟了新的工作階段,就必須重新設定變數。

    範例:Linux 或 macOS

    將 [PATH] 替換為包含服務帳戶金鑰的 JSON 檔案路徑。

    export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

    例如:

    export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

    範例:Windows

    將 [PATH] 替換為包含服務帳戶金鑰的 JSON 檔案路徑,並將 [FILE_NAME] 替換為檔案名稱。

    使用 PowerShell:

    $env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

    例如:

    $env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

    使用命令提示字元:

    set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

使用 Kubeflow Pipelines DSL 套件定義工作流程

kfp.dsl 套件包含特定領域語言 (DSL),可用於定義管道和元件,以及與其互動。

Kubeflow pipeline 元件是建立 pipeline 步驟的工廠函式。每個元件都會說明元件的輸入、輸出和實作。舉例來說,在下列程式碼範例中,ds_op 是元件。

元件可用於建立管道步驟。管道執行時,只要所需資料可用,就會執行步驟。舉例來說,訓練元件可以將 CSV 檔案做為輸入內容,並用於訓練模型。

import kfp
from google.cloud import aiplatform
from google_cloud_pipeline_components.v1.dataset import ImageDatasetCreateOp
from google_cloud_pipeline_components.v1.automl.training_job import AutoMLImageTrainingJobRunOp
from google_cloud_pipeline_components.v1.endpoint import EndpointCreateOp, ModelDeployOp

project_id = PROJECT_ID
pipeline_root_path = PIPELINE_ROOT

# Define the workflow of the pipeline.
@kfp.dsl.pipeline(
    name="automl-image-training-v2",
    pipeline_root=pipeline_root_path)
def pipeline(project_id: str):
    # The first step of your workflow is a dataset generator.
    # This step takes a Google Cloud Pipeline Component, providing the necessary
    # input arguments, and uses the Python variable `ds_op` to define its
    # output. Note that here the `ds_op` only stores the definition of the
    # output but not the actual returned object from the execution. The value
    # of the object is not accessible at the dsl.pipeline level, and can only be
    # retrieved by providing it as the input to a downstream component.
    ds_op = ImageDatasetCreateOp(
        project=project_id,
        display_name="flowers",
        gcs_source="gs://cloud-samples-data/vision/automl_classification/flowers/all_data_v2.csv",
        import_schema_uri=aiplatform.schema.dataset.ioformat.image.single_label_classification,
    )

    # The second step is a model training component. It takes the dataset
    # outputted from the first step, supplies it as an input argument to the
    # component (see `dataset=ds_op.outputs["dataset"]`), and will put its
    # outputs into `training_job_run_op`.
    training_job_run_op = AutoMLImageTrainingJobRunOp(
        project=project_id,
        display_name="train-iris-automl-mbsdk-1",
        prediction_type="classification",
        model_type="CLOUD",
        dataset=ds_op.outputs["dataset"],
        model_display_name="iris-classification-model-mbsdk",
        training_fraction_split=0.6,
        validation_fraction_split=0.2,
        test_fraction_split=0.2,
        budget_milli_node_hours=8000,
    )

    # The third and fourth step are for deploying the model.
    create_endpoint_op = EndpointCreateOp(
        project=project_id,
        display_name = "create-endpoint",
    )

    model_deploy_op = ModelDeployOp(
        model=training_job_run_op.outputs["model"],
        endpoint=create_endpoint_op.outputs['endpoint'],
        automatic_resources_min_replica_count=1,
        automatic_resources_max_replica_count=1,
    )

更改下列內容:

  • PROJECT_ID:執行這個管道的 Google Cloud 專案。
  • PIPELINE_ROOT_PATH:指定 pipelines 服務帳戶可存取的 Cloud Storage URI。管道執行的構件會儲存在管道根目錄中。Cloud Storage URI 必須開頭為 gs://。

    管道根目錄可設為管道函式上 @kfp.dsl.pipeline 註解的引數,也可以在呼叫 create_run_from_job_spec 建立管道執行作業時設定。

將 pipeline 編譯成 YAML 檔案

定義 pipeline 的工作流程後,即可繼續將 pipeline 編譯為 YAML 格式。YAML 檔案包含在 Agent Platform Pipelines 執行管道所需的所有資訊。

from kfp import compiler

compiler.Compiler().compile(
    pipeline_func=pipeline,
    package_path='image_classif_pipeline.yaml'
)

提交管道執行作業

將管道的工作流程編譯成 YAML 格式後,您可以使用 Gemini Enterprise Agent Platform Python 用戶端提交及執行管道。

import google.cloud.aiplatform as aip

# Before initializing, make sure to set the GOOGLE_APPLICATION_CREDENTIALS
# environment variable to the path of your service account.
aip.init(
    project=project_id,
    location=PROJECT_REGION,
)

# Prepare the pipeline job
job = aip.PipelineJob(
    display_name="automl-image-training-v2",
    template_path="image_classif_pipeline.yaml",
    pipeline_root=pipeline_root_path,
    parameter_values={
        'project_id': project_id
    }
)

job.submit()

更改下列內容:

  • PROJECT_REGION:這個管道執行的區域。

在上述範例中:

  1. Kubeflow 管道是以 Python 函式定義。這個函式會加上 @kfp.dsl.pipeline 裝飾器,指定 pipeline 的名稱和根路徑。管道根路徑是儲存管道構件的位置。
  2. 管道的工作流程步驟是使用 Google Cloud Pipeline Components 建立。將某個元件的輸出內容做為另一個元件的輸入內容,即可將管道的工作流程定義為圖表。例如:training_job_run_op 依附於 ds_op 的 dataset 輸出。
  3. 使用 kfp.compiler.Compiler 編譯管道。
  4. 您可以使用 Gemini Enterprise Agent Platform Python 用戶端,在 Agent Platform Pipelines 建立管道執行作業。執行 pipeline 時,您可以覆寫 pipeline 名稱和 pipeline 根路徑。您可以使用管道名稱將管道執行作業分組。覆寫管道名稱有助於區分正式版和實驗版管道執行作業。

如要進一步瞭解如何建構管道,請參閱建構 Kubeflow 管道一節,並按照範例和教學課程操作。

在本機測試管道 (選用)

定義管道和元件後,您可以在本機編寫環境中執行程式碼,測試元件程式碼。在本機執行管道或元件,即可在遠端環境 (例如 Agent Platform Pipelines) 建立管道執行作業之前,找出並偵錯潛在問題。如要進一步瞭解如何在本機執行管道和元件,請參閱 KFP 說明文件中的「本機執行」一節。

本頁面說明如何定義及執行由兩項工作組成的管道。

設定本機環境

  1. 選用:安裝 Docker。

  2. 使用下列程式碼範例定義入門管道:

    from kfp import dsl
    
    # Define a component to add two numbers.
    @dsl.component
    def add(a: int, b: int) -> int:
        return a + b
    
    # Define a simple pipeline using the component.
    @dsl.pipeline
    def addition_pipeline(x: int, y: int, z: int) -> int:
        task1 = add(a=x, b=y)
        task2 = add(a=task1.output, b=z)
        return task2.output
    

叫用本機執行作業

使用 local.init() 函式初始化本機工作階段。使用 local.init() 時,KFP SDK 會在本機執行您呼叫的管道和元件。

使用 local.init() 時,必須指定執行器類型。執行器類型會指出 KFP 應如何執行每項工作。

請參考下列範例,指定 DockerRunner 執行器類型,在容器中執行各項任務。如要進一步瞭解 KFP 支援的本機執行工具,請參閱 KFP 說明文件中的「本機執行工具」一節。

from kfp import local

local.init(runner=local.DockerRunner())

pipeline_task = addition_pipeline(x=1, y=2, z=3)

使用下列程式碼,查看在本機執行的管道工作輸出內容:

print(f'Result: {pipeline_task.output}')

建構 Kubeflow 管道

請按照下列程序建構管道。

  1. 將管道設計為一系列元件。為了促進重複使用,每個元件都應有單一責任。設計管道時,請盡可能重複使用經過驗證的元件,例如 Google Cloud Pipeline 元件。

    進一步瞭解如何設計管道。

  2. 使用 Kubeflow Pipelines SDK 建構實作機器學習工作流程所需的任何自訂元件。元件是一組獨立的程式碼,用於執行機器學習工作流程中的步驟。請使用下列選項建立管道元件。

  3. 以 Python 函式建構管道。

    進一步瞭解如何將 pipeline 定義為 Python 函式。

  4. 使用 Kubeflow Pipelines SDK 編譯器編譯管道。

    from kfp import compiler
    
    compiler.Compiler().compile(
        pipeline_func=PIPELINE_FUNCTION,
        package_path=PIPELINE_PACKAGE_PATH)
    

    更改下列內容:

    • PIPELINE_FUNCTION:管道函式的名稱。
    • PIPELINE_PACKAGE_PATH:儲存已編譯 pipeline 的路徑。
  5. 使用 Google Cloud 控制台或 Python 執行管道。

存取管道中的 Google Cloud 資源

如果在執行管道時未指定服務帳戶,Agent Platform Pipelines 會使用 Compute Engine 預設服務帳戶執行管道。Agent Platform Pipelines 也會使用 pipeline 執行的服務帳戶,授權 pipeline 存取Google Cloud 資源。Compute Engine 預設服務帳戶預設具備專案編輯者角色。這可能會授予管道過多 Google Cloud 專案中 Google Cloud 資源的存取權。

建議您建立服務帳戶來執行管道,然後將執行管道所需的 Google Cloud 資源精細權限授予這個帳戶。

進一步瞭解如何使用 Identity and Access Management 建立服務帳戶,以及管理授予服務帳戶的存取權。

讓管道保持最新狀態

您用來建構及執行 pipeline 的 SDK 用戶端和容器映像檔會定期更新至新版本,以修補安全漏洞並新增功能。為確保管道保持最新版本,建議您採取下列做法:

後續步驟