可建立訓練管線

訓練管線可讓您執行自訂機器學習 (ML) 訓練,並根據訓練輸出內容自動建立 Model 資源。

如果您的工作只涉及執行訓練工作,以及自動建立模型資源,而不必自動化調度管理完整工作流程,則使用本文所述的獨立訓練管道可能就足夠。不過,如果您的目標是建構穩健、自動化且可重複執行的端對端機器學習生命週期,且涉及多個步驟 (例如資料處理、訓練、評估、部署或監控),建議使用 Gemini Enterprise Agent Platform Pipelines,因為這項服務專為工作流程自動調度管理而設計。

建立管道前

在 Agent Platform 建立訓練管道前,您必須先建立 Python 訓練應用程式或自訂容器,定義要在 Agent Platform 執行的訓練程式碼和依附元件。如果您使用 PyTorch、TensorFlow、scikit-learn 或 XGBoost 建立 Python 訓練應用程式,可以使用預先建構的容器執行程式碼。如果不確定要選擇哪一個選項,請參閱訓練程式碼規定,瞭解詳情。

訓練管道選項

訓練管道會封裝訓練工作,並提供額外步驟。本指南說明兩種不同的訓練管道:

  • 啟動 CustomJob,並將產生的模型上傳至 Agent Platform
  • 啟動超參數調整工作,並將產生的模型上傳至 Agent Platform

此外,您也可以在訓練管道中使用代管資料集。進一步瞭解如何設定訓練管道,以使用代管資料集。

CustomJob 包含的內容

建立自訂工作時,您需要指定 Agent Platform 執行訓練程式碼所需的設定,包括:

您可以在 worker 集區中指定下列設定:

如要在 Vertex AI Training 管道外建立獨立自訂工作,請參閱自訂工作指南。

設定管道以使用代管資料集

在訓練管道中,您可以設定無伺服器訓練工作或超參數調整工作,以使用代管資料集。代管資料集可讓您透過訓練應用程式和模型管理資料集。

如要在訓練管道中使用代管資料集,請按照下列步驟操作:

  1. 建立資料集。
  2. 更新訓練應用程式,以便使用代管資料集。詳情請參閱「Agent Platform 如何將資料集傳遞至訓練應用程式」。
  3. 建立訓練管道時,請指定代管資料集。舉例來說,如果您使用 REST API 建立訓練管道,請在 inputDataConfig 區段中指定資料集設定。

    您必須在建立資料集的相同區域中建立訓練管道。

詳情請參閱 TrainingPipeline 的 API 參考資料。

設定分散式訓練

在訓練管道中,您可以指定多個 worker 集區,為分散式訓練設定無伺服器訓練工作或超參數調整工作。

本頁所有範例都顯示具有一個 worker 集區的單一副本訓練工作。如要修改這些項目以進行分散式訓練,請按照下列步驟操作:

  • 使用第一個 worker 集區設定主要副本,並將副本數量設為 1。
  • 如果機器學習架構支援這些額外的分散式訓練叢集工作,請新增更多 worker 集區,設定 worker 副本、參數伺服器副本或評估器副本。

進一步瞭解如何使用分散式訓練。

CustomJob 和模型上傳

這個訓練管道封裝了自訂工作,並新增便利步驟,讓您在訓練後更輕鬆地將模型部署至 Agent Platform。這個訓練管道會執行兩項主要作業:

  1. 訓練管道會建立 CustomJob 資源。自訂工作會使用您指定的運算資源執行訓練應用程式。

  2. 自訂工作完成後,訓練管道會在您為 Cloud Storage bucket 指定的輸出目錄中,找出訓練應用程式建立的模型構件。並使用這些構件建立模型資源,為模型部署做好準備。

設定模型構件位置的方法有兩種:

如果同時指定 baseOutputDirectory 和 modelToUpload.artifactUri,Agent Platform 會使用 modelToUpload.artifactUri。

如要建立這類訓練管道,請按照下列步驟操作:

控制台

  1. 前往 Google Cloud 控制台「Agent Platform」部分的「Training pipelines」(訓練管道) 頁面。

    前往「Training pipelines」(訓練管道)

  2. 按一下 「Create」(建立),開啟「Train new model」(訓練新模型) 窗格。

  3. 在「Training method」(訓練方法) 步驟中,指定下列設定:

    1. 如要使用代管資料集進行訓練,請指定「Dataset」(資料集) 和「Annotation set」(註解集)。

      否則,請在「Dataset」(資料集) 下拉式選單中,選取「No managed dataset」(沒有代管資料集)。

    2. 選取「Custom training (advanced)」(自訂訓練 (進階))。

    按一下「繼續」。

  4. 在「Model details」(模型詳細資料) 步驟中,選擇「Train new model」(訓練新模型) 或「Train new version」(訓練新版本)。如果選取訓練新模型,請為模型輸入自選名稱 MODEL_NAME。按一下「繼續」。

  5. 在「訓練容器」步驟中,指定下列設定:

    1. 選取要使用預先建構的容器還是自訂容器進行訓練。

    2. 根據您的選擇,執行下列其中一項操作:

      • 如要使用預先建構的容器進行訓練,請向 Agent Platform 提供必要資訊,以便使用您上傳至 Cloud Storage 的訓練套件:

        1. 使用「Model framework」(模型架構) 和「Model framework version」(模型架構版本) 下拉式選單,指定要使用的預先建構容器。

        2. 在「Package location」(套件位置) 欄位中,指定您建立並上傳的 Python 訓練應用程式 Cloud Storage URI。這個檔案的結尾通常是 .tar.gz。

        3. 在「Python module」(Python 模組) 欄位中,輸入訓練應用程式進入點的模組名稱。

      • 如要使用自訂容器進行訓練,請在「Container image」(容器映像檔) 欄位中,指定容器映像檔的 Artifact Registry 或 Docker Hub URI。

    3. 在「Model output directory」(模型輸出目錄) 欄位中,指定您有權存取的值區中目錄的 Cloud Storage URI。目錄不一定要存在。

      這個值會傳遞至 Agent Platform 的 baseOutputDirectory API 欄位,該欄位會設定訓練應用程式執行時可存取的數個環境變數。

      訓練結束時,Agent Platform 會在這個 URI 的子目錄中尋找模型構件,以便建立 Model。(這個子目錄可做為 AIP_MODEL_DIR 環境變數,供訓練程式碼使用)。

      如果不使用超參數調整,Agent Platform 會預期在 BASE_OUTPUT_DIRECTORY/model/ 中找到模型構件。

    4. 選用:在「Arguments」(引數) 欄位中,您可以指定 Agent Platform 開始執行訓練程式碼時要使用的引數。所有引數的長度總和上限為 100,000 個字元。這些引數的行為會因使用的容器類型而異:

      • 如果您使用預先建構的容器,Agent Platform 會將引數做為指令列旗標傳遞至 Python 模組。

      • 如果您使用自訂容器,Agent Platform 會以引數覆寫容器的 CMD 指令。

    按一下「繼續」。

  6. 在「Hyperparameter tuning」(超參數調整) 步驟中,確認未勾選「Enable hyperparameter tuning」(啟用超參數調整) 核取方塊。按一下「Continue」(繼續)。

  7. 在「Compute and pricing」(運算和定價) 步驟中,指定下列設定:

    1. 在「Region」(區域) 下拉式選單中,選取「支援自訂訓練的區域」。

    2. 在「Worker pool 0」(工作站集區 0) 區段中,指定要用於訓練的運算資源。

      如果指定加速器,請確認所選區域提供您選擇的加速器類型。

      如要執行分散式訓練,請按一下「Add more worker pools」(新增更多 worker 集區),並為每個額外的 worker 集區指定一組額外的運算資源。

    按一下「繼續」。

  8. 在「Prediction container」(預測容器) 步驟中,指定下列設定:

    1. 選取要使用預先建構的容器還是自訂容器,透過訓練後的模型提供預測結果。

    2. 根據您的選擇,執行下列其中一項操作:

      • 如要使用預先建構的容器提供預測,請使用「Model framework」(模型架構)、「Model framework version」(模型架構版本)和「Accelerator type」(加速器類型)欄位,選擇要用於預測的預先建構預測容器。

        將「Model framework」(模型架構) 和「Model framework version」(模型架構版本) 與您用於訓練的機器學習架構進行比對。只有在您日後想使用 GPU 進行線上或批次預測時,才需要指定加速器類型。

      • 如要使用自訂容器提供預測,請按照下列步驟操作:

        1. 在「Container image」(容器映像檔) 欄位中,指定容器映像檔的 Artifact Registry URI。

        2. 您可以視需要指定指令,覆寫容器的 ENTRYPOINT 指令。

    3. 「Model directory」(模型目錄) 欄位包含您先前在「Training container」(訓練容器) 步驟的「Model output directory」(模型輸出目錄) 欄位中設定的值。變更任一欄位都會產生相同效果。如要進一步瞭解這個欄位,請參閱前述操作說明。

    4. 將「Predict schemata」(預測結構定義) 區段中的欄位留空。

  9. 點選「Start training」(開始訓練),啟動無伺服器訓練管道。

REST

使用下列程式碼範例,透過 trainingPipeline 資源的 create 方法建立訓練管道。

注意:如要將這個管道設為建立新的模型版本,可以選擇在 trainingPipeline 欄位中新增 PARENT_MODEL。

詳情請參閱「使用 Gemini Enterprise Agent Platform Model Registry 建立模型版本」。

使用任何要求資料之前,請先修改下列項目的值:

  • LOCATION_ID:執行訓練程式碼及儲存 Model 的區域。
  • PROJECT_ID:專案 ID。
  • TRAINING_PIPELINE_NAME:必填,trainingPipeline 的顯示名稱。
  • 如果訓練應用程式使用 Agent Platform 資料集,請指定下列項目:
    • DATASET_ID:資料集 ID。
    • ANNOTATIONS_FILTER:依據您指定的註解篩選資料集。
    • ANNOTATION_SCHEMA_URI:依指定的註解結構定義 URI 篩選資料集。
    • 請使用下列其中一個選項,指定如何將資料項目分割為訓練集、驗證集和測試集。
      • 如要根據定義各組大小的分數分割資料集,請指定下列項目:
        • TRAINING_FRACTION:用於訓練模型的資料集比例。
        • VALIDATION_FRACTION::用於驗證 模型的資料集比例。
        • TEST_FRACTION:用於評估模型的資料集比例。
      • 如要根據篩選條件分割資料集,請指定下列項目:
        • TRAINING_FILTER:篩選資料集,找出要用於訓練模型的資料項目。
        • VALIDATION_FILTER:篩選資料集,找出用於驗證模型的資料項目。
        • TEST_FILTER:篩選資料集,找出用於評估模型的資料項目。
      • 如要使用預先定義的分割,請指定下列項目:
        • PREDEFINED_SPLIT_KEY:用於分割資料集的資料欄名稱。這個資料欄可接受的值包括「training」、「validation」和「test」。
      • 如要根據資料項目的時間戳記分割資料集,請指定下列項目:
        • TIMESTAMP_TRAINING_FRACTION:用於訓練模型的資料集比例。
        • TIMESTAMP_VALIDATION_FRACTION:用於驗證模型的資料集比例。
        • TIMESTAMP_TEST_FRACTION:用於評估模型的資料集比例。
        • TIMESTAMP_SPLIT_KEY:用於分割 資料集的時間戳記資料欄名稱。
    • OUTPUT_URI_PREFIX:Agent Platform 將訓練資料集分割為訓練集、驗證集和測試集後,會將資料集匯出至這個 Cloud Storage 位置。
  • 定義自訂訓練工作:
    • MACHINE_TYPE:機器類型。請參閱可用於訓練的機器類型。
    • ACCELERATOR_TYPE:(選用) 要附加至各項試驗的加速器類型。
    • ACCELERATOR_COUNT:(選用) 要附加至各項試驗的加速器數量。
    • REPLICA_COUNT:每次試驗要使用的工作站副本數量。
    • 如果訓練應用程式是在自訂容器中執行,請指定下列項目:
      • CUSTOM_CONTAINER_IMAGE_URI:Artifact Registry 或 Docker Hub 中容器映像檔的 URI,要在每個 worker 副本上執行。
      • CUSTOM_CONTAINER_COMMAND:(選用) 容器啟動時要叫用的指令。這個指令會覆寫容器的預設進入點。
      • CUSTOM_CONTAINER_ARGS:(選用) 啟動容器時要傳遞的引數。所有引數的長度總和上限為 100,000 個字元。
    • 如果訓練應用程式是在預先建構容器中執行的 Python 套件,請指定下列項目:
      • PYTHON_PACKAGE_EXECUTOR_IMAGE_URI:執行所提供 Python 套件的容器映像檔 URI。請參閱可用於訓練的預先建構容器。
      • PYTHON_PACKAGE_URIS:Python 套件檔案的 Cloud Storage 位置,這些檔案是訓練程式及其依附套件。套件 URI 數量上限為 100 個。
      • PYTHON_MODULE:安裝套件後要執行的 Python 模組名稱。
      • PYTHON_PACKAGE_ARGS:(選用) 要傳遞至 Python 模組的指令列引數。所有引數的長度總和上限為 100,000 個字元。
    • TIMEOUT:(選用) 工作的執行時間上限。
  • MODEL_NAME:TrainingPipeline 上傳 (建立) 的模型顯示名稱。
  • MODEL_DESCRIPTION:模型說明。
  • IMAGE_URI:用於執行預測作業的容器映像檔 URI。例如:us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-1:latest。使用預先建構的容器或自訂容器。
  • modelToUpload.labels:用於整理模型的任何鍵/值組合。舉例來說:
    • "env": "prod"
    • "tier": "backend"
  • 為要套用至這個訓練管道的任何標籤指定 LABEL_NAME 和 LABEL_VALUE。

HTTP 方法和網址:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/trainingPipelines

JSON 要求內文:

{
  "displayName": "TRAINING_PIPELINE_NAME",
  "inputDataConfig": {
    "datasetId": DATASET_ID,
    "annotationsFilter": ANNOTATIONS_FILTER,
    "annotationSchemaUri": ANNOTATION_SCHEMA_URI,

    // Union field split can be only one of the following:
    "fractionSplit": {
      "trainingFraction": TRAINING_FRACTION,
      "validationFraction": VALIDATION_FRACTION,
      "testFraction": TEST_FRACTION
    },
    "filterSplit": {
      "trainingFilter": TRAINING_FILTER,
      "validationFilter": VALIDATION_FILTER,
      "testFilter": TEST_FILTER
    },
    "predefinedSplit": {
      "key": PREDEFINED_SPLIT_KEY
    },
    "timestampSplit": {
      "trainingFraction": TIMESTAMP_TRAINING_FRACTION,
      "validationFraction": TIMESTAMP_VALIDATION_FRACTION,
      "testFraction": TIMESTAMP_TEST_FRACTION,
      "key": TIMESTAMP_SPLIT_KEY
    }
    // End of list of possible types for union field split.
    "gcsDestination": {
      "outputUriPrefix": OUTPUT_URI_PREFIX
    }
  },
  "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/custom_task_1.0.0.yaml",
  "trainingTaskInputs": {
    "workerPoolSpecs": [
        {
          "machineSpec": {
            "machineType": MACHINE_TYPE,
            "acceleratorType": ACCELERATOR_TYPE,
            "acceleratorCount": ACCELERATOR_COUNT
          },
          "replicaCount": REPLICA_COUNT,

          // Union field task can be only one of the following:
          "containerSpec": {
            "imageUri": CUSTOM_CONTAINER_IMAGE_URI,
            "command": [
              CUSTOM_CONTAINER_COMMAND
            ],
            "args": [
              CUSTOM_CONTAINER_ARGS
            ]
          },
          "pythonPackageSpec": {
            "executorImageUri": PYTHON_PACKAGE_EXECUTOR_IMAGE_URI,
            "packageUris": [
              PYTHON_PACKAGE_URIS
            ],
            "pythonModule": PYTHON_MODULE,
            "args": [
              PYTHON_PACKAGE_ARGS
            ]
          }
          // End of list of possible types for union field task.
        }
      ],
      "scheduling": {
        "TIMEOUT": TIMEOUT
      }
    }
  },
  "modelToUpload": {
    "displayName": "MODEL_NAME",
    "predictSchemata": {},
    "containerSpec": {
      "imageUri": "IMAGE_URI"
    }
  },
  "labels": {
    LABEL_NAME_1": LABEL_VALUE_1,
    LABEL_NAME_2": LABEL_VALUE_2
  }
}

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/trainingPipelines"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$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_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/trainingPipelines" | Select-Object -Expand Content

回覆內容包含規格和 TRAININGPIPELINE_ID 的相關資訊。

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 Agent Platform 快速入門導覽課程」中的 Java 設定說明操作。詳情請參閱 Agent Platform Java API 參考文件。

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

import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.Model;
import com.google.cloud.aiplatform.v1.ModelContainerSpec;
import com.google.cloud.aiplatform.v1.PipelineServiceClient;
import com.google.cloud.aiplatform.v1.PipelineServiceSettings;
import com.google.cloud.aiplatform.v1.TrainingPipeline;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;

public class CreateTrainingPipelineCustomJobSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String displayName = "DISPLAY_NAME";
    String modelDisplayName = "MODEL_DISPLAY_NAME";
    String containerImageUri = "CONTAINER_IMAGE_URI";
    String baseOutputDirectoryPrefix = "BASE_OUTPUT_DIRECTORY_PREFIX";
    createTrainingPipelineCustomJobSample(
        project, displayName, modelDisplayName, containerImageUri, baseOutputDirectoryPrefix);
  }

  static void createTrainingPipelineCustomJobSample(
      String project,
      String displayName,
      String modelDisplayName,
      String containerImageUri,
      String baseOutputDirectoryPrefix)
      throws IOException {
    PipelineServiceSettings settings =
        PipelineServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();
    String location = "us-central1";

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PipelineServiceClient client = PipelineServiceClient.create(settings)) {
      JsonObject jsonMachineSpec = new JsonObject();
      jsonMachineSpec.addProperty("machineType", "n1-standard-4");

      // A working docker image can be found at
      // gs://cloud-samples-data/ai-platform/mnist_tfrecord/custom_job
      // This sample image accepts a set of arguments including model_dir.
      JsonObject jsonContainerSpec = new JsonObject();
      jsonContainerSpec.addProperty("imageUri", containerImageUri);
      JsonArray jsonArgs = new JsonArray();
      jsonArgs.add("--model_dir=$(AIP_MODEL_DIR)");
      jsonContainerSpec.add("args", jsonArgs);

      JsonObject jsonJsonWorkerPoolSpec0 = new JsonObject();
      jsonJsonWorkerPoolSpec0.addProperty("replicaCount", 1);
      jsonJsonWorkerPoolSpec0.add("machineSpec", jsonMachineSpec);
      jsonJsonWorkerPoolSpec0.add("containerSpec", jsonContainerSpec);

      JsonArray jsonWorkerPoolSpecs = new JsonArray();
      jsonWorkerPoolSpecs.add(jsonJsonWorkerPoolSpec0);

      JsonObject jsonBaseOutputDirectory = new JsonObject();
      // The GCS location for outputs must be accessible by the project's AI Platform
      // service account.
      jsonBaseOutputDirectory.addProperty("output_uri_prefix", baseOutputDirectoryPrefix);

      JsonObject jsonTrainingTaskInputs = new JsonObject();
      jsonTrainingTaskInputs.add("workerPoolSpecs", jsonWorkerPoolSpecs);
      jsonTrainingTaskInputs.add("baseOutputDirectory", jsonBaseOutputDirectory);

      Value.Builder trainingTaskInputsBuilder = Value.newBuilder();
      JsonFormat.parser().merge(jsonTrainingTaskInputs.toString(), trainingTaskInputsBuilder);
      Value trainingTaskInputs = trainingTaskInputsBuilder.build();
      String trainingTaskDefinition =
          "gs://google-cloud-aiplatform/schema/trainingjob/definition/custom_task_1.0.0.yaml";
      String imageUri = "gcr.io/cloud-aiplatform/prediction/tf-cpu.1-15:latest";
      ModelContainerSpec containerSpec =
          ModelContainerSpec.newBuilder().setImageUri(imageUri).build();
      Model modelToUpload =
          Model.newBuilder()
              .setDisplayName(modelDisplayName)
              .setContainerSpec(containerSpec)
              .build();
      TrainingPipeline trainingPipeline =
          TrainingPipeline.newBuilder()
              .setDisplayName(displayName)
              .setTrainingTaskDefinition(trainingTaskDefinition)
              .setTrainingTaskInputs(trainingTaskInputs)
              .setModelToUpload(modelToUpload)
              .build();
      LocationName parent = LocationName.of(project, location);
      TrainingPipeline response = client.createTrainingPipeline(parent, trainingPipeline);
      System.out.format("response: %s\n", response);
      System.out.format("Name: %s\n", response.getName());
    }
  }
}

Python

如要瞭解如何安裝或更新 Vertex AI SDK for Python,請參閱「安裝 Vertex AI SDK for Python」。詳情請參閱 Python API 參考文件。

下列範例說明如何使用 Agent Platform SDK for Python 建立無伺服器訓練管道。選擇要使用自訂容器或預先建構的容器進行訓練:

預先建構的容器

使用 Agent Platform SDK for Python 建立訓練管道,在預先建構的容器中執行 Python 程式碼時,您可以透過下列任一方式提供訓練程式碼:

  • 指定 Cloud Storage 中 Python 來源發行套件的 URI。

    (不使用 Agent Platform SDK for Python 建立訓練管道時,也可以使用這個選項)。

  • 指定本機電腦上的 Python 指令碼路徑。建立訓練管道前,Agent Platform SDK for Python 會將指令碼封裝為來源發行版本,並上傳至您選擇的 Cloud Storage bucket。

    (只有使用 Agent Platform SDK for Python 時,才能選取這個選項)。

如要查看各選項的程式碼範例,請選取對應的分頁標籤:

套件

以下範例使用 CustomPythonPackageTrainingJob 類別。

def create_training_pipeline_custom_package_job_sample(
    project: str,
    location: str,
    staging_bucket: str,
    display_name: str,
    python_package_gcs_uri: str,
    python_module_name: str,
    container_uri: str,
    model_serving_container_image_uri: str,
    dataset_id: Optional[str] = None,
    model_display_name: Optional[str] = None,
    args: Optional[List[Union[str, float, int]]] = None,
    replica_count: int = 1,
    machine_type: str = "n1-standard-4",
    accelerator_type: str = "ACCELERATOR_TYPE_UNSPECIFIED",
    accelerator_count: int = 0,
    training_fraction_split: float = 0.8,
    validation_fraction_split: float = 0.1,
    test_fraction_split: float = 0.1,
    sync: bool = True,
    tensorboard_resource_name: Optional[str] = None,
    service_account: Optional[str] = None,
):
    aiplatform.init(project=project, location=location, staging_bucket=staging_bucket)

    job = aiplatform.CustomPythonPackageTrainingJob(
        display_name=display_name,
        python_package_gcs_uri=python_package_gcs_uri,
        python_module_name=python_module_name,
        container_uri=container_uri,
        model_serving_container_image_uri=model_serving_container_image_uri,
    )

    # This example uses an ImageDataset, but you can use another type
    dataset = aiplatform.ImageDataset(dataset_id) if dataset_id else None

    model = job.run(
        dataset=dataset,
        model_display_name=model_display_name,
        args=args,
        replica_count=replica_count,
        machine_type=machine_type,
        accelerator_type=accelerator_type,
        accelerator_count=accelerator_count,
        training_fraction_split=training_fraction_split,
        validation_fraction_split=validation_fraction_split,
        test_fraction_split=test_fraction_split,
        sync=sync,
        tensorboard=tensorboard_resource_name,
        service_account=service_account,
    )

    model.wait()

    print(model.display_name)
    print(model.resource_name)
    print(model.uri)
    return model

指令碼

下列範例使用 CustomTrainingJob 類別。

def create_training_pipeline_custom_job_sample(
    project: str,
    location: str,
    staging_bucket: str,
    display_name: str,
    script_path: str,
    container_uri: str,
    model_serving_container_image_uri: str,
    dataset_id: Optional[str] = None,
    model_display_name: Optional[str] = None,
    args: Optional[List[Union[str, float, int]]] = None,
    replica_count: int = 0,
    machine_type: str = "n1-standard-4",
    accelerator_type: str = "ACCELERATOR_TYPE_UNSPECIFIED",
    accelerator_count: int = 0,
    training_fraction_split: float = 0.8,
    validation_fraction_split: float = 0.1,
    test_fraction_split: float = 0.1,
    sync: bool = True,
    tensorboard_resource_name: Optional[str] = None,
    service_account: Optional[str] = None,
):
    aiplatform.init(project=project, location=location, staging_bucket=staging_bucket)

    job = aiplatform.CustomTrainingJob(
        display_name=display_name,
        script_path=script_path,
        container_uri=container_uri,
        model_serving_container_image_uri=model_serving_container_image_uri,
    )

    # This example uses an ImageDataset, but you can use another type
    dataset = aiplatform.ImageDataset(dataset_id) if dataset_id else None

    model = job.run(
        dataset=dataset,
        model_display_name=model_display_name,
        args=args,
        replica_count=replica_count,
        machine_type=machine_type,
        accelerator_type=accelerator_type,
        accelerator_count=accelerator_count,
        training_fraction_split=training_fraction_split,
        validation_fraction_split=validation_fraction_split,
        test_fraction_split=test_fraction_split,
        sync=sync,
        tensorboard=tensorboard_resource_name,
        service_account=service_account,
    )

    model.wait()

    print(model.display_name)
    print(model.resource_name)
    print(model.uri)
    return model

自訂容器

下列範例使用 CustomContainerTrainingJob 類別。

def create_training_pipeline_custom_container_job_sample(
    project: str,
    location: str,
    staging_bucket: str,
    display_name: str,
    container_uri: str,
    model_serving_container_image_uri: str,
    dataset_id: Optional[str] = None,
    model_display_name: Optional[str] = None,
    args: Optional[List[Union[str, float, int]]] = None,
    replica_count: int = 1,
    machine_type: str = "n1-standard-4",
    accelerator_type: str = "ACCELERATOR_TYPE_UNSPECIFIED",
    accelerator_count: int = 0,
    training_fraction_split: float = 0.8,
    validation_fraction_split: float = 0.1,
    test_fraction_split: float = 0.1,
    sync: bool = True,
    tensorboard_resource_name: Optional[str] = None,
    service_account: Optional[str] = None,
):
    aiplatform.init(project=project, location=location, staging_bucket=staging_bucket)

    job = aiplatform.CustomContainerTrainingJob(
        display_name=display_name,
        container_uri=container_uri,
        model_serving_container_image_uri=model_serving_container_image_uri,
    )

    # This example uses an ImageDataset, but you can use another type
    dataset = aiplatform.ImageDataset(dataset_id) if dataset_id else None

    model = job.run(
        dataset=dataset,
        model_display_name=model_display_name,
        args=args,
        replica_count=replica_count,
        machine_type=machine_type,
        accelerator_type=accelerator_type,
        accelerator_count=accelerator_count,
        training_fraction_split=training_fraction_split,
        validation_fraction_split=validation_fraction_split,
        test_fraction_split=test_fraction_split,
        sync=sync,
        tensorboard=tensorboard_resource_name,
        service_account=service_account,
    )

    model.wait()

    print(model.display_name)
    print(model.resource_name)
    print(model.uri)
    return model

超參數調整工作和模型上傳

這個訓練管道封裝了超參數調整工作,並新增便利步驟,讓您在訓練後更輕鬆地將模型部署至 Agent Platform。這個訓練管道主要執行兩項工作:

  1. 訓練管道會建立超參數調整工作資源。超參數調整工作會建立多項試驗。在每次試驗中,自訂工作會使用您指定的運算資源和超參數,執行訓練應用程式。

  2. 超參數調整工作完成後,訓練管道會在您為 Cloud Storage bucket 指定的輸出目錄 (baseOutputDirectory) 中,找出最佳試驗的模型構件。訓練管道會使用這些構件建立模型資源,為模型部署做好準備。

在這個訓練管道中,您必須指定 baseOutputDirectory,讓 Agent Platform 搜尋最佳試驗的模型構件。

超參數調整工作有其他設定需要調整。進一步瞭解 HyperparameterTuningJob 的設定。

REST

使用下列程式碼範例,透過 trainingPipeline 資源的 create 方法建立訓練管道。

使用任何要求資料之前,請先修改下列項目的值:

  • LOCATION_ID:專案的區域。
  • PROJECT_ID:專案 ID。
  • TRAINING_PIPELINE_NAME:必填,trainingPipeline 的顯示名稱。
  • 如果訓練應用程式使用 Agent Platform 資料集,請指定下列項目:
    • DATASET_ID:資料集 ID。
    • ANNOTATIONS_FILTER:依據您指定的註解篩選資料集。
    • ANNOTATION_SCHEMA_URI:依指定的註解結構定義 URI 篩選資料集。
    • 請使用下列其中一個選項,指定如何將資料項目分割為訓練集、驗證集和測試集。
      • 如要根據定義各組大小的分數分割資料集,請指定下列項目:
        • TRAINING_FRACTION:用於訓練模型的資料集比例。
        • VALIDATION_FRACTION::用於驗證 模型的資料集比例。
        • TEST_FRACTION:用於評估模型的資料集比例。
      • 如要根據篩選條件分割資料集,請指定下列項目:
        • TRAINING_FILTER:篩選資料集,找出要用於訓練模型的資料項目。
        • VALIDATION_FILTER:篩選資料集,找出用於驗證模型的資料項目。
        • TEST_FILTER:篩選資料集,找出用於評估模型的資料項目。
      • 如要使用預先定義的分割,請指定下列項目:
        • PREDEFINED_SPLIT_KEY:用於分割資料集的資料欄名稱。這個資料欄可接受的值包括「training」、「validation」和「test」。
      • 如要根據資料項目的時間戳記分割資料集,請指定下列項目:
        • TIMESTAMP_TRAINING_FRACTION:用於訓練模型的資料集比例。
        • TIMESTAMP_VALIDATION_FRACTION:用於驗證模型的資料集比例。
        • TIMESTAMP_TEST_FRACTION:用於評估模型的資料集比例。
        • TIMESTAMP_SPLIT_KEY:用於分割 資料集的時間戳記資料欄名稱。
    • OUTPUT_URI_PREFIX:Agent Platform 將訓練資料集分割為訓練集、驗證集和測試集後,匯出訓練資料集的 Cloud Storage 位置。
  • 指定超參數調整工作:
    • 指定指標:
      • METRIC_ID:這項指標的名稱。
      • METRIC_GOAL:這項指標的目標。可以是 MAXIMIZE 或 MINIMIZE。
    • 指定超參數:
      • PARAMETER_ID:這個超參數的名稱。
      • PARAMETER_SCALE:(選用) 參數的縮放方式。如果是 CATEGORICAL 參數,請保留未設定狀態。可以是 UNIT_LINEAR_SCALE、UNIT_LOG_SCALE、UNIT_REVERSE_LOG_SCALE 或 SCALE_TYPE_UNSPECIFIED
      • 如果這個超參數的類型為 DOUBLE,請指定這個超參數的最小值 (DOUBLE_MIN_VALUE) 和最大值 (DOUBLE_MAX_VALUE)。
      • 如果這個超參數的類型為 INTEGER,請指定這個超參數的最小值 (INTEGER_MIN_VALUE) 和最大值 (INTEGER_MAX_VALUE)。
      • 如果這個超參數的類型為 CATEGORICAL,請將可接受的值 (CATEGORICAL_VALUES) 指定為字串陣列。
      • 如果這個超參數的類型為 DISCRETE,請將可接受的值 (DISCRETE_VALUES) 指定為數字陣列。
    • ALGORITHM:(選用) 這項超參數調整工作要使用的搜尋演算法。可以是 ALGORITHM_UNSPECIFIED、GRID_SEARCH 或 RANDOM_SEARCH。
    • MAX_TRIAL_COUNT::這項工作要執行的試驗數量上限。
    • PARALLEL_TRIAL_COUNT:可同時執行的試驗數量上限。
    • MAX_FAILED_TRIAL_COUNT:超參數調整工作失敗前,可失敗的工作數量。
    • 定義試用自訂訓練工作:
      • MACHINE_TYPE:機器類型。請參閱可用於訓練的機器類型。
      • ACCELERATOR_TYPE:(選用) 要附加至各項試驗的加速器類型。
      • ACCELERATOR_COUNT:(選用) 要附加至各項試驗的加速器數量。
      • REPLICA_COUNT:每次試驗要使用的工作站副本數量。
      • 如果訓練應用程式是在自訂容器中執行,請指定下列項目:
        • CUSTOM_CONTAINER_IMAGE_URI:Artifact Registry 或 Docker Hub 中容器映像檔的 URI,要在每個 worker 副本上執行。
        • CUSTOM_CONTAINER_COMMAND:(選用) 容器啟動時要叫用的指令。這個指令會覆寫容器的預設進入點。
        • CUSTOM_CONTAINER_ARGS:(選用) 啟動容器時要傳遞的引數。
      • 如果訓練應用程式是在預先建構容器中執行的 Python 套件,請指定下列項目:
        • PYTHON_PACKAGE_EXECUTOR_IMAGE_URI:執行所提供 Python 套件的容器映像檔 URI。請參閱可用於訓練的預先建構容器。
        • PYTHON_PACKAGE_URIS:Python 套件檔案的 Cloud Storage 位置,這些檔案是訓練程式及其依附套件。套件 URI 數量上限為 100 個。
        • PYTHON_MODULE:安裝套件後要執行的 Python 模組名稱。
        • PYTHON_PACKAGE_ARGS:(選用) 要傳遞至 Python 模組的指令列引數。
    • 瞭解工作排程選項。
    • TIMEOUT:(選用) 每項試驗的執行時間上限。
    • 針對要套用至這項超參數調整工作的任何標籤,指定 LABEL_NAME 和 LABEL_VALUE。
  • MODEL_NAME:TrainingPipeline 上傳 (建立) 的模型顯示名稱。
  • MODEL_DESCRIPTION:選用。模型的說明。
  • PREDICTION_IMAGE_URI:必填,請指定下列其中一個選項:
  • modelToUpload.labels:選用。任何一組用於整理模型的鍵/值組合。舉例來說:
    • "env": "prod"
    • "tier": "backend"
  • 針對要套用至這個訓練管道的任何標籤,指定 LABEL_NAME 和 LABEL_VALUE。

HTTP 方法和網址:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/trainingPipelines

JSON 要求內文:

{
  "displayName": "TRAINING_PIPELINE_NAME",
  "inputDataConfig": {
    "datasetId": DATASET_ID,
    "annotationsFilter": ANNOTATIONS_FILTER,
    "annotationSchemaUri": ANNOTATION_SCHEMA_URI,

    // Union field split can be only one of the following:
    "fractionSplit": {
      "trainingFraction": TRAINING_FRACTION,
      "validationFraction": VALIDATION_FRACTION,
      "testFraction": TEST_FRACTION
    },
    "filterSplit": {
      "trainingFilter": TRAINING_FILTER,
      "validationFilter": VALIDATION_FILTER,
      "testFilter": TEST_FILTER
    },
    "predefinedSplit": {
      "key": PREDEFINED_SPLIT_KEY
    },
    "timestampSplit": {
      "trainingFraction": TIMESTAMP_TRAINING_FRACTION,
      "validationFraction": TIMESTAMP_VALIDATION_FRACTION,
      "testFraction": TIMESTAMP_TEST_FRACTION,
      "key": TIMESTAMP_SPLIT_KEY
    }
    // End of list of possible types for union field split.
    "gcsDestination": {
      "outputUriPrefix": OUTPUT_URI_PREFIX
    }
  },
  "trainingTaskDefinition": "gs://google-cloud-aiplatform/schema/trainingjob/definition/hyperparameter_tuning_task_1.0.0.yaml",
  "trainingTaskInputs": {
    "studySpec": {
    "metrics": [
      {
        "metricId": METRIC_ID,
        "goal": METRIC_GOAL
      }
    ],
    "parameters": [
      {
        "parameterId": PARAMETER_ID,
        "scaleType": PARAMETER_SCALE,

        // Union field parameter_value_spec can be only one of the following:
        "doubleValueSpec": {
            "minValue": DOUBLE_MIN_VALUE,
            "maxValue": DOUBLE_MAX_VALUE
        },
        "integerValueSpec": {
            "minValue": INTEGER_MIN_VALUE,
            "maxValue": INTEGER_MAX_VALUE
        },
        "categoricalValueSpec": {
            "values": [
              CATEGORICAL_VALUES
            ]
        },
        "discreteValueSpec": {
            "values": [
              DISCRETE_VALUES
            ]
        }
        // End of list of possible types for union field parameter_value_spec.
      }
    ],
    "ALGORITHM": ALGORITHM
  },
  "maxTrialCount": MAX_TRIAL_COUNT,
  "parallelTrialCount": PARALLEL_TRIAL_COUNT,
  "maxFailedTrialCount": MAX_FAILED_TRIAL_COUNT,
  "trialJobSpec": {
      "workerPoolSpecs": [
        {
          "machineSpec": {
            "machineType": MACHINE_TYPE,
            "acceleratorType": ACCELERATOR_TYPE,
            "acceleratorCount": ACCELERATOR_COUNT
          },
          "replicaCount": REPLICA_COUNT,

          // Union field task can be only one of the following:
          "containerSpec": {
            "imageUri": CUSTOM_CONTAINER_IMAGE_URI,
            "command": [
              CUSTOM_CONTAINER_COMMAND
            ],
            "args": [
              CUSTOM_CONTAINER_ARGS
            ]
          },
          "pythonPackageSpec": {
            "executorImageUri": PYTHON_PACKAGE_EXECUTOR_IMAGE_URI,
            "packageUris": [
              PYTHON_PACKAGE_URIS
            ],
            "pythonModule": PYTHON_MODULE,
            "args": [
              PYTHON_PACKAGE_ARGS
            ]
          }
          // End of list of possible types for union field task.
        }
      ],
      "scheduling": {
        "TIMEOUT": TIMEOUT
      }
    },
    "labels": {
      LABEL_NAME_1": LABEL_VALUE_1,
      LABEL_NAME_2": LABEL_VALUE_2
    }
  },
  "modelToUpload": {
    "displayName": "MODEL_NAME",
    "description": "MODEL_DESCRIPTION",
    "predictSchemata": {},
    "containerSpec": {
      "imageUri": "PREDICTION_IMAGE_URI"
    }
  },
  "labels": {
    LABEL_NAME_1": LABEL_VALUE_1,
    LABEL_NAME_2": LABEL_VALUE_2
  }
}

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/trainingPipelines"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$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_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/trainingPipelines" | Select-Object -Expand Content

回覆內容包含規格和 TRAININGPIPELINE_ID 的相關資訊。

監控訓練

如要查看訓練記錄,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台「Agent Platform」部分的「Training」頁面。

    前往「訓練」頁面

  2. 點選工作名稱,前往自訂工作頁面。

  3. 按一下「查看記錄」。

您也可以在訓練管道執行期間,使用互動式殼層檢查訓練容器。

查看訓練完成的模型

無伺服器訓練管道完成後,您可以在 Google Cloud 控制台的「Agent Platform」部分,前往「Models」(模型) 頁面查看訓練好的模型。

前往「Models」(模型) 頁面

後續步驟