커스텀 학습용 컨테이너 설정 구성

커스텀 학습을 수행할 때 Vertex AI에서 실행할 머신러닝(ML) 코드를 지정해야 합니다. 이렇게 하려면 커스텀 컨테이너 또는 사전 빌드된 컨테이너에서 실행되는 Python 학습 애플리케이션의 학습 컨테이너 설정을 구성합니다.

커스텀 컨테이너 또는 사전 빌드된 컨테이너를 사용할지 결정하려면 학습 코드 요구사항을 참조하세요.

이 문서에서는 위의 사례 중 하나에서 지정해야 하는 Vertex AI API의 필드를 설명합니다.

컨테이너 설정을 지정하는 위치

WorkerPoolSpec 내에 구성 세부정보를 지정합니다. 커스텀 학습을 수행하는 방법에 따라 이 WorkerPoolSpec을 다음 API 필드 중 하나에 넣습니다.

분산 학습을 수행하는 경우 각 작업자 풀에 서로 다른 설정을 사용할 수 있습니다.

컨테이너 설정 구성

사전 빌드된 컨테이너 또는 커스텀 컨테이너를 사용하는지 여부에 따라 WorkerPoolSpec에 다른 필드를 지정해야 합니다. 시나리오를 위한 탭을 선택합니다.

사전 빌드된 컨테이너

  1. 학습에 사용할 ML 프레임워크를 지원하는 사전 빌드된 컨테이너를 선택합니다. pythonPackageSpec.executorImageUri 필드에 컨테이너 이미지 URI 중 하나를 지정합니다.

  2. pythonPackageSpec.packageUris 필드Python 학습 애플리케이션의 Cloud Storage URI를 지정합니다.

  3. pythonPackageSpec.pythonModule 필드에서 학습 애플리케이션의 진입점 모듈을 지정합니다.

  4. 원하는 경우 pythonPackageSpec.args 필드에서 학습 애플리케이션의 진입점 모듈에 전달할 명령줄 인수 목록을 지정합니다.

다음 예시에서는 CustomJob을 만들 때 이러한 컨테이너 설정을 지정하는 위치를 보여줍니다.

콘솔

Google Cloud 콘솔에서는 CustomJob을 직접 만들 수 없습니다. 하지만 CustomJob을 만드는 TrainingPipeline을 만들 수 있습니다. Google Cloud 콘솔에서 TrainingPipeline을 만들 때 학습 컨테이너 단계의 특정 필드에 사전 빌드된 컨테이너 설정을 지정할 수 있습니다.

  • pythonPackageSpec.executorImageUri: 모델 프레임워크모델 프레임워크 버전 드롭다운 목록을 사용합니다.

  • pythonPackageSpec.packageUris: 패키지 위치 필드를 사용합니다.

  • pythonPackageSpec.pythonModule: Python 모듈 필드를 사용합니다.

  • pythonPackageSpec.args: 인수 필드를 사용합니다.

gcloud

gcloud ai custom-jobs create \
  --region=LOCATION \
  --display-name=JOB_NAME \
  --python-package-uris=PYTHON_PACKAGE_URIS \
  --worker-pool-spec=machine-type=MACHINE_TYPE,replica-count=REPLICA_COUNT,executor-image-uri=PYTHON_PACKAGE_EXECUTOR_IMAGE_URI,python-module=PYTHON_MODULE

자세한 내용은 CustomJob 만들기 가이드를 참조하세요.

커스텀 컨테이너

  1. containerSpec.imageUri 필드커스텀 컨테이너의 Artifact Registry 또는 Docker Hub URI를 지정합니다.

  2. 원하는 경우 컨테이너의 ENTRYPOINT 또는 CMD 안내를 재정의하려면 containerSpec.command 또는 containerSpec.args 필드를 지정합니다. 이러한 필드는 컨테이너가 다음 규칙에 따라 실행되는 방식에 영향을 줍니다.

    • 둘 다 지정하지 않은 경우: 컨테이너가 ENTRYPOINT 안내와 CMD 안내(있는 경우)에 따라 실행됩니다. CMDENTRYPOINT의 상호작용 방식에 대한 Docker 문서를 참조하세요.

    • containerSpec.command만 지정하는 경우: 컨테이너가 ENTRYPOINT 안내 대신 containerSpec.command 값으로 실행됩니다. 컨테이너에 CMD 명령어가 있는 경우 무시됩니다.

    • containerSpec.args만 지정하는 경우: CMD 안내 대신 containerSpec.args 값으로 ENTRYPOINT 안내에 따라 컨테이너가 실행됩니다.

    • 두 필드 모두 지정하는 경우: 컨테이너가 ENTRYPOINT 안내 대신 containerSpec.command로, CMD 안내 대신 containerSpec.args로 실행됩니다.

다음 예시에서는 CustomJob을 만들 때 이러한 컨테이너 설정 중 일부를 지정할 수 있는 위치를 보여줍니다.

콘솔

Google Cloud 콘솔에서는 CustomJob을 직접 만들 수 없습니다. 하지만 CustomJob을 만드는 TrainingPipeline을 만들 수 있습니다. Google Cloud Console에서 TrainingPipeline을 만들 때 학습 컨테이너 단계의 특정 필드에 커스텀 컨테이너 설정을 지정할 수 있습니다.

  • containerSpec.imageUri: 컨테이너 이미지 필드를 사용합니다.

  • containerSpec.command: Google Cloud Console에서 이 API 필드를 구성할 수 없습니다.

  • containerSpec.args: 인수 필드를 사용합니다.

gcloud

gcloud ai custom-jobs create \
  --region=LOCATION \
  --display-name=JOB_NAME \
  --worker-pool-spec=machine-type=MACHINE_TYPE,replica-count=REPLICA_COUNT,container-image-uri=CUSTOM_CONTAINER_IMAGE_URI

Java

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Vertex AI Java API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.aiplatform.v1.AcceleratorType;
import com.google.cloud.aiplatform.v1.ContainerSpec;
import com.google.cloud.aiplatform.v1.CustomJob;
import com.google.cloud.aiplatform.v1.CustomJobSpec;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.MachineSpec;
import com.google.cloud.aiplatform.v1.WorkerPoolSpec;
import java.io.IOException;

// Create a custom job to run machine learning training code in Vertex AI
public class CreateCustomJobSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String displayName = "DISPLAY_NAME";

    // Vertex AI runs your training application in a Docker container image. A Docker container
    // image is a self-contained software package that includes code and all dependencies. Learn
    // more about preparing your training application at
    // http://cloud.go888ogle.com.fqhub.com/vertex-ai/docs/training/overview#prepare_your_training_application
    String containerImageUri = "CONTAINER_IMAGE_URI";
    createCustomJobSample(project, displayName, containerImageUri);
  }

  static void createCustomJobSample(String project, String displayName, String containerImageUri)
      throws IOException {
    JobServiceSettings settings =
        JobServiceSettings.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.
    try (JobServiceClient client = JobServiceClient.create(settings)) {
      MachineSpec machineSpec =
          MachineSpec.newBuilder()
              .setMachineType("n1-standard-4")
              .setAcceleratorType(AcceleratorType.NVIDIA_TESLA_K80)
              .setAcceleratorCount(1)
              .build();

      ContainerSpec containerSpec =
          ContainerSpec.newBuilder().setImageUri(containerImageUri).build();

      WorkerPoolSpec workerPoolSpec =
          WorkerPoolSpec.newBuilder()
              .setMachineSpec(machineSpec)
              .setReplicaCount(1)
              .setContainerSpec(containerSpec)
              .build();

      CustomJobSpec customJobSpecJobSpec =
          CustomJobSpec.newBuilder().addWorkerPoolSpecs(workerPoolSpec).build();

      CustomJob customJob =
          CustomJob.newBuilder()
              .setDisplayName(displayName)
              .setJobSpec(customJobSpecJobSpec)
              .build();
      LocationName parent = LocationName.of(project, location);
      CustomJob response = client.createCustomJob(parent, customJob);
      System.out.format("response: %s\n", response);
      System.out.format("Name: %s\n", response.getName());
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Vertex AI Node.js API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */

// const customJobDisplayName = 'YOUR_CUSTOM_JOB_DISPLAY_NAME';
// const containerImageUri = 'YOUR_CONTAINER_IMAGE_URI';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Job Service Client library
const {JobServiceClient} = require('@google-cloud/aiplatform');

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

// Instantiates a client
const jobServiceClient = new JobServiceClient(clientOptions);

async function createCustomJob() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  const customJob = {
    displayName: customJobDisplayName,
    jobSpec: {
      workerPoolSpecs: [
        {
          machineSpec: {
            machineType: 'n1-standard-4',
            acceleratorType: 'NVIDIA_TESLA_K80',
            acceleratorCount: 1,
          },
          replicaCount: 1,
          containerSpec: {
            imageUri: containerImageUri,
            command: [],
            args: [],
          },
        },
      ],
    },
  };
  const request = {parent, customJob};

  // Create custom job request
  const [response] = await jobServiceClient.createCustomJob(request);

  console.log('Create custom job response:\n', JSON.stringify(response));
}
createCustomJob();

Python

Python용 Vertex AI SDK를 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참고 문서를 확인하세요.

from google.cloud import aiplatform

def create_custom_job_sample(
    project: str,
    display_name: str,
    container_image_uri: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
):
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.JobServiceClient(client_options=client_options)
    custom_job = {
        "display_name": display_name,
        "job_spec": {
            "worker_pool_specs": [
                {
                    "machine_spec": {
                        "machine_type": "n1-standard-4",
                        "accelerator_type": aiplatform.gapic.AcceleratorType.NVIDIA_TESLA_K80,
                        "accelerator_count": 1,
                    },
                    "replica_count": 1,
                    "container_spec": {
                        "image_uri": container_image_uri,
                        "command": [],
                        "args": [],
                    },
                }
            ]
        },
    }
    parent = f"projects/{project}/locations/{location}"
    response = client.create_custom_job(parent=parent, custom_job=custom_job)
    print("response:", response)

자세한 내용은 CustomJob 만들기 가이드를 참조하세요.

다음 단계