可建立訓練管線

訓練管線可讓您執行自訂機器學習 (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 執行訓練程式碼所需的設定,包括:

在工作站集區中,您可以指定下列設定:

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

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

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

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

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

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

如要瞭解詳情,請參閱 TrainingPipeline 的 API 參考資料。

設定分散式訓練

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

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

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

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

CustomJob 和模型上傳

這項訓練管道封裝了自訂工作,並新增便利步驟,方便您在訓練後將模型部署至 Agent Platform。這個訓練管道主要有兩項功能:

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

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

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

如果您同時指定 baseOutputDirectorymodelToUpload.artifactUri,Agent Platform 會使用 modelToUpload.artifactUri

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

控制台

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

    前往訓練管線

  2. 按一下「建立」,開啟「訓練新模型」窗格。

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

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

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

    2. 選取「自訂訓練 (進階)」

    按一下「繼續」

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

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

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

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

      • 如要使用預先建構的訓練專用容器,請提供 Agent Platform 相關資訊,以便使用您上傳到 Cloud Storage 的訓練套件:

        1. 使用「模型架構」和「模型架構版本」下拉式清單,指定要使用的預先建構容器

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

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

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

    3. 在「模型輸出目錄」欄位中,指定您有權存取的值區中目錄的 Cloud Storage URI。該目錄尚不需要存在。

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

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

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

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

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

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

    按一下「繼續」

  6. 在「超參數調整」步驟中,請確認未勾選「啟用超參數調整」核取方塊。按一下「繼續」

  7. 在「運算和價格」步驟中,指定下列設定:

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

    2. 在「工作站集區 0」部分,指定用於訓練的運算資源

      如果您指定加速器,請確認所選加速器類型可在所選區域使用

      如要執行分散式訓練,請按一下「新增更多工作站集區」,然後為每個要新增的工作站集區指定一組額外的運算資源。

    按一下「繼續」

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

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

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

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

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

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

REST

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

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

詳情請參閱「透過 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,將在每個工作站副本上執行。
      • 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:上傳 (建立) 的模型顯示名稱。
  • MODEL_DESCRIPTION:模型的說明。
  • IMAGE_URI:用於執行預測的容器映像檔 URI。例如:us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-1:latest。使用預先建構的容器自訂容器
  • modelToUpload.labels:任何一組鍵/值組合,可用於整理模型。舉例來說:
    • "env": "prod"
    • "tier": "backend"
  • 為要套用至這項訓練管道的任何標籤,指定 LABEL_NAMELABEL_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。這個訓練 pipeline 主要會執行兩項操作:

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

  2. 超參數調整工作完成後,訓練管道會在您為 Cloud Storage 值區指定的輸出目錄 (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:這項指標的目標。可以是 MAXIMIZEMINIMIZE
    • 指定超參數:
      • PARAMETER_ID:這個超參數的名稱。
      • PARAMETER_SCALE:(選用)。參數的縮放方式。CATEGORICAL 參數請保留未設定狀態。可以是 UNIT_LINEAR_SCALEUNIT_LOG_SCALEUNIT_REVERSE_LOG_SCALESCALE_TYPE_UNSPECIFIED
      • 如果這個超參數的類型為 DOUBLE,請為這個超參數指定最小值 (DOUBLE_MIN_VALUE) 和最大值 (DOUBLE_MAX_VALUE)。
      • 如果這個超參數的類型為 INTEGER,請為這個超參數指定最小值 (INTEGER_MIN_VALUE) 和最大值 (INTEGER_MAX_VALUE)。
      • 如果這個超參數的類型為 CATEGORICAL,請將可接受的值 (CATEGORICAL_VALUES) 指定為字串陣列。
      • 如果這個超參數的類型為 DISCRETE,請將可接受的值 (DISCRETE_VALUES) 指定為數字陣列。
    • ALGORITHM:(選用)。要在這項超參數調整工作中使用的搜尋演算法。可以是 ALGORITHM_UNSPECIFIEDGRID_SEARCHRANDOM_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,將在每個工作站副本上執行。
        • 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_NAMELABEL_VALUE
  • MODEL_NAME:上傳 (建立) 的模型顯示名稱。
  • MODEL_DESCRIPTION:選用。模型的說明。
  • PREDICTION_IMAGE_URI:必填,選取下列其中一個選項:
  • modelToUpload.labels:選用。任何一組鍵/值組合,可用於整理模型。舉例來說:
    • "env": "prod"
    • "tier": "backend"
  • 為要套用至這項訓練管道的任何標籤指定 LABEL_NAMELABEL_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 部分,於「模型」頁面中找到訓練好的模型。

前往「模型」頁面

後續步驟