GPU를 사용하는 작업 만들기 및 실행

이 문서에서는 그래픽 처리 장치(GPU)를 사용하는 작업을 만들고 실행하는 방법을 설명합니다. GPU의 기능 및 제한사항에 대해 자세히 알아보려면 Compute Engine 문서의 GPU 정보를 참고하세요.

Batch 작업을 만들 때 원하는 경우 GPU를 사용하여 특정 워크로드를 가속화할 수 있습니다. GPU를 사용하는 작업의 일반적인 사용 사례에는 집중적인 데이터 처리 및 머신러닝 (ML)과 같은 인공지능 (AI) 워크로드가 있습니다.

시작하기 전에

  1. Batch를 사용한 적이 없으면 Batch 시작하기를 검토하고 프로젝트 및 사용자 기본 요건을 완료하여 Batch를 사용 설정하세요.
  2. 작업을 만드는 데 필요한 권한을 얻으려면 관리자에게 다음 IAM 역할을 부여해 달라고 요청하세요.

    역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

    커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

GPU를 사용하는 작업 만들기

GPU를 사용하는 작업을 만들려면 다음을 수행합니다.

  1. GPU를 사용하는 작업의 요구사항 계획
  2. 식별한 요구사항 및 방법으로 작업 만들기. 권장 옵션을 사용하여 작업을 만드는 방법의 예시는 이 문서의 GPU를 사용하는 작업 예시 만들기를 참고하세요.

GPU를 사용하는 작업의 요구사항 계획

GPU를 사용하는 작업을 만들기 전에 다음 섹션에 설명된 대로 작업의 요구사항을 계획하세요.

  1. GPU 머신 유형 및 소비 옵션 선택
  2. GPU 드라이버 설치
  3. 호환되는 VM 리소스 정의

1단계: GPU 머신 유형 및 소비 옵션 선택

작업 요구사항은 선호하는 GPU 머신 유형 및 소비 옵션에 따라 다르며 각 옵션이 상호 종속적일 수 있습니다.

작업의 GPU 머신 유형과 소비 옵션을 선택하려면 다음 단계를 완료하세요.

  1. 우선순위를 식별하고 선택합니다.

    • 성능과 기본 가격을 우선시하려면 이 문서의 GPU 머신 유형 선택 섹션을 참고하세요.
    • 리소스 가용성 또는 할인을 우선시하려면 이 문서의 사용 옵션 선택 섹션을 참고하세요.
  2. 첫 번째 선택과 호환되는 항목을 기준으로 나머지 항목을 선택합니다.

    1. 첫 번째 선택과 호환되는 옵션을 확인하려면 Compute Engine 문서의 머신 유형별 소비 옵션 가용성을 참고하세요.

    2. 소비 옵션 선택 또는 GPU 머신 유형 선택은 각각 나머지 섹션을 참고하세요.

GPU 머신 유형 선택

작업의 GPU 머신 유형을 선택하고 작업 요구사항을 파악하려면 다음 단계를 완료하세요.

  1. GPU 머신 유형 선택: 사용 가능한 GPU 머신 유형(GPU 유형, GPU 수, 머신 유형(vCPU 및 메모리)의 유효한 조합) 및 권장 사용 사례를 검토하려면 Compute Engine 문서의 GPU 머신 유형가속기 최적화 머신 계열을 참고하세요.

  2. GPU 머신 유형의 작업 요구사항 이해: GPU 머신 유형을 지정하는 작업에 필요한 필드는 다음 표의 카테고리에 따라 다릅니다.

    GPU 머신 유형 및 작업 요구사항

    가속기 최적화 VM용 GPU: 가속기 최적화 머신 계열의 머신 유형을 사용하는 VM에는 이러한 GPU의 특정 유형과 개수가 자동으로 연결됩니다.

    가속기 최적화 VM에 GPU를 사용하려면 머신 유형을 지정하는 것이 좋습니다. 각 가속기 최적화 머신 유형은 특정 유형과 수의 GPU만 지원하므로 가속기 최적화 머신 유형 외에 이러한 값을 지정하든 지정하지 않든 기능적으로 동일합니다.

    특히 Batch는 가속기 최적화 VM의 GPU 유형과 수만 지정하는 것도 지원하지만 결과 vCPU 및 메모리 옵션은 매우 제한적인 경우가 많습니다. 따라서 사용 가능한 vCPU 및 메모리 옵션이 작업의 태스크 요구사항과 호환되는지 확인하는 것이 좋습니다.

    N1 VM용 GPU: 이러한 GPU는 각 VM에 연결할 유형과 개수를 지정해야 하며 N1 머신 시리즈의 머신 유형이 있는 VM에 연결해야 합니다.

    N1 VM에 GPU를 사용하려면 GPU 유형과 GPU 수를 최소한 지정하는 것이 좋습니다. 값 조합이 유효한 N1 머신 유형의 GPU 옵션 중 하나와 일치하는지 확인합니다. 특정 유형 및 수의 GPU를 사용하는 N1 VM의 vCPU 및 메모리 옵션은 매우 유연합니다. Google Cloud 콘솔을 사용하여 작업을 만들지 않는 경우 Batch에서 작업의 태스크 요구사항을 충족하는 머신 유형을 자동으로 선택하도록 할 수 있습니다.

소비 옵션 선택

이 섹션에서는 작업의 소비 옵션을 선택하는 방법과 각 옵션의 작업 요구사항을 요약합니다.

Batch에서 사용할 수 있는 소비 옵션과 요구사항은 다음 표에 설명되어 있습니다. 이 표에는 사용 사례를 기준으로 대략 가장 높은 리소스 가용성부터 가장 낮은 리소스 가용성까지 나열되어 있습니다.

요약하자면 대부분의 사용자는 다음과 같이 작업의 소비 옵션을 선택하는 것이 좋습니다.

  • 다른 조건 중 하나가 참이 아닌 경우 Flex-start VM(미리보기)(요구사항을 충족하는 경우 권장) 또는 주문형을 사용합니다.
  • 작업에 리소스 가용성에 대한 매우 높은 보장이 필요하거나 삭제할 수 없는 사용되지 않는 예약이 있는 경우 캘린더 모드 예약(미리보기)(요구사항을 충족하는 경우 권장) 또는 예약을 사용하세요.
  • (선택사항) 워크로드가 내결함성이 매우 높은 경우 스팟 VM을 사용하여 비용을 줄일 수 있습니다.
소비 옵션 및 작업 요구사항

예약

  • 사용 사례: 리소스 가용성을 매우 높은 수준으로 보장하고 캘린더 모드 예약을 사용할 수 없거나 사용되지 않을 수 있는 기존 예약이 이미 있는 경우 작업에 예약을 사용하는 것이 좋습니다.

  • 세부정보: 예약이 생성되면 예약이 삭제될 때까지 지정된 VM의 비용이 VM을 실행하는 것과 동일한 가격으로 발생합니다. 예약을 사용하는 VM에는 별도의 비용이 발생하지 않지만 예약에는 사용 여부와 관계없이 비용이 발생합니다.

    Compute Engine 문서에서 예약에 대해 자세히 알아보세요.

Batch는 사용되지 않은 예약 VM을 사용할 수 있는 작업에 예약을 사용합니다. 예약을 사용하는 작업 요구사항에 대한 자세한 내용은 VM 예약을 사용하여 리소스 가용성 확보 페이지를 참고하세요.

캘린더 모드 예약 (프리뷰)

  • 사용 사례: 캘린더 모드 예약을 지원하는 GPU 머신 유형을 사용하고 리소스 가용성을 최소 1일에서 최대 90일 동안 매우 높은 수준으로 보장해야 하는 경우 작업에 캘린더 모드 예약을 사용하는 것이 좋습니다.

  • 세부정보: 작업을 만들기 전에 사용할 수 있는 캘린더 모드 예약을 요청하거나 식별해야 합니다. Compute Engine이 캘린더 모드에서 미래용 예약 요청을 처리하면 자동 생성된 캘린더 모드 예약에 지정된 VM을 전체 예약 기간 동안 동적 워크로드 스케줄러 가격 책정으로 실행하는 것과 동일한 비용이 발생합니다. 동적 워크로드 스케줄러 가격 책정은 주문형 가격에서 최대 53% 할인된 가격을 제공합니다. 사용할 수 있는 자동 생성된 캘린더 모드 예약을 확인한 후 캘린더 모드 예약을 사용하는 작업을 만드는 것은 예약을 사용하는 작업을 만드는 것과 매우 유사합니다.

    Compute Engine 문서에서 캘린더 모드 예약에 대해 자세히 알아보세요.

Batch는 다음을 모두 충족하는 작업에 캘린더 모드 예약을 사용합니다.

Flex-start VM (미리보기)

  • 사용 사례: 할인된 가격과 최대 7일의 실행 기간을 대가로 최선을 다한 가용성을 감당할 수 있는 작업인 경우 Flex-start VM을 사용하는 것이 좋습니다.

    주문형 VM 및 스팟 VM과 비교할 때 Flex-start VM을 사용하면 여러 GPU 리소스에 동시에 더 쉽게 액세스할 수 있습니다. 예를 들어 Flex-start VM은 리소스 사용 불가능으로 인해 발생하는 지연이나 문제를 완화하여 작업 예약에 도움이 될 수 있습니다.

  • 세부정보: Flex-start VM을 사용하는 작업을 생성하라는 요청이 수락되면 VM에 동적 워크로드 스케줄러 가격 책정이 적용되어 주문형 가격에서 최대 53% 할인된 가격으로 청구됩니다.

    Compute Engine 문서에서 flex-start VM에 대해 자세히 알아보세요.

Batch는 다음을 모두 충족하는 작업에 Flex-start VM을 사용합니다.

주문형

  • 사용 사례: 기본적으로 대부분의 다른 작업에는 주문형을 사용하는 것이 좋습니다.1

  • 세부정보: 온디맨드는 일반적으로 Compute Engine VM에 액세스하는 기본 방법입니다. 온디맨드를 사용하면 요청 시 리소스 (사용 가능한 경우)에 액세스할 수 있습니다. 작업이 완료되거나 실행 시간 제한에 도달할 때까지 리소스가 삭제됩니다.

일괄은 기본적으로 대부분의 다른 작업에 주문형을 사용합니다. 작업이 온디맨드를 사용하도록 하려면 다음을 모두 실행하세요.1

  • provisioningModel 필드를 STANDARD로 설정합니다.
  • 예약 차단 작업이 호환되는 예약을 사용하여 자동으로 사용하지 못하도록 하려면 reservation 필드를 NO_RESERVATION로 설정합니다. 자세한 내용은 예약된 VM을 사용할 수 없는 작업 만들기 및 실행을 참고하세요.

1예외: A3 머신 시리즈를 사용하는 작업의 경우 기본 동작이 고유하므로 온디맨드를 사용하지 않고 provisioningModel 필드를 정의되지 않은 상태로 두지 않는 것이 좋습니다. 대신 유연한 시작 VM의 작업 요구사항을 사용하세요. 리소스 가용성이 낮기 때문에 A3 머신 시리즈에는 주문형을 사용하지 않는 것이 좋습니다. 따라서 작업에서 A3 머신 시리즈를 사용하고, 예약을 차단하고, provisioningModel 필드가 정의되지 않았거나 STANDARD로 설정된 경우 기본 소비 옵션은 고유합니다. 동작은 실행 시간을 7일로 제한하는 Flex-start VM과 유사하지만 이러한 작업에는 동적 워크로드 스케줄러 가격 책정의 할인이 적용되지 않으므로 권장되지 않습니다. A3 VM을 사용하는 작업에서 7일의 실행 시간 제한을 허용할 수 있는 경우 주문형 대신 Flex-start VM을 사용하는 것이 좋습니다. 그렇지 않으면 provisioningModelSTANDARD로 설정하고 reservation 필드를 NO_RESERVATION로 설정하지 않고 작업이 예약을 사용할 수 없는지 수동으로 확인하지 않는 한 A3 VM이 있는 작업이 주문형을 사용하도록 할 수 없습니다.

스팟 VM

  • 사용 사례: 스팟 VM을 사용하여 내결함성 워크로드의 비용을 줄이는 것이 좋습니다.

  • 세부정보: 스팟 VM을 사용하는 작업을 생성하라는 요청이 수락되면 VM에 스팟 VM 가격이 청구됩니다. 이 가격은 자주 변경될 수 있으며 주문형 가격의 최대 91%까지 가장 큰 할인을 제공할 수 있습니다. 하지만 스팟 VM은 항상 사용할 수 있는 것이 아니며 언제든지 선점될 수 있습니다.

    Compute Engine 문서에서 스팟 VM에 대해 자세히 알아보세요.

Batch는 다음을 모두 충족하는 작업에 스팟 VM을 사용합니다.

  • provisioningModel 필드를 SPOT로 설정합니다.
  • (선택사항) 예약 차단 예약과 함께 스팟 VM을 사용할 수 없습니다. 특히 작업은 reservation 필드를 NO_RESERVATION로 선택적으로 설정할 수 있습니다. 자세한 내용은 예약된 VM을 사용할 수 없는 작업 만들기 및 실행을 참고하세요.

2단계: GPU 드라이버 설치

작업에 GPU를 사용하려면 GPU 드라이버를 설치해야 합니다. GPU 드라이버를 설치하려면 다음 방법 중 하나를 선택합니다.

  • GPU 드라이버 자동 설치 (가능한 경우 권장됨): 예시에 표시된 것처럼 Batch가 타사 위치에서 필요한 GPU 드라이버를 가져와 사용자를 대신하여 설치하도록 하려면 작업에 대한 installGpuDrivers 필드를 true로 설정합니다. 이 방법은 작업에서 드라이버를 수동으로 설치할 필요가 없는 경우에 권장됩니다.

    선택적으로 Batch에서 설치하는 GPU 드라이버 버전을 지정해야 하는 경우 driverVersion 필드도 설정합니다.

  • GPU 드라이버 수동 설치: 이 방법은 다음 중 하나라도 해당하는 경우에 필요합니다.

    • 작업이 스크립트와 컨테이너 실행 가능 항목을 모두 사용하며 인터넷 액세스 권한이 없는 경우. 작업에 있는 액세스 권한에 대한 자세한 내용은 Batch 네트워킹 개요를 참조하세요.
    • 작업이 커스텀 VM 이미지를 사용하는 경우. VM OS 이미지 및 사용할 수 있는 VM OS 이미지에 관한 자세한 내용은 VM OS 환경 개요를 참고하세요.

    필요한 GPU 드라이버를 수동으로 설치하려면 다음 방법을 사용하는 것이 좋습니다.

    1. GPU 드라이버가 포함된 맞춤 VM 이미지를 만듭니다.

      1. GPU 드라이버를 설치하려면 사용하려는 OS에 따라 설치 스크립트를 실행하세요.

      2. 작업에 컨테이너 실행 가능 항목이 있고 Container-Optimized OS를 사용하지 않는 경우 NVIDIA Container Toolkit도 설치해야 합니다.

    2. GPU를 사용하는 작업을 만들고 제출할 때는 GPU 드라이버가 포함된 커스텀 VM 이미지를 지정하고 작업의 installGpuDrivers 필드false (기본값)로 설정합니다.

3단계: 호환되는 VM 리소스 정의

작업의 VM 리소스를 정의하는 요구사항과 옵션에 대해 알아보려면 작업 리소스를 참고하세요.

요약하자면 GPU를 사용하는 작업의 VM 리소스를 정의할 때는 다음을 모두 수행해야 합니다.

  • 작업의 VM이 있는 위치에서 GPU 머신 유형을 사용할 수 있는지 확인.

    GPU 머신 유형을 사용할 수 있는 위치를 알아보려면 Compute Engine 문서의 가속기 가용성을 참고하세요.

  • 작업의 머신 유형을 지정하는 경우 머신 유형에 작업의 태스크 요구사항에 충분한 vCPU 및 메모리가 있는지 확인. Google Cloud 콘솔을 사용하여 작업을 만들 때는 항상 작업의 머신 유형을 지정해야 하며, 가속기 최적화 VM에 GPU를 사용하는 작업을 만들 때는 머신 유형을 지정하는 것이 좋습니다.

  • 유효한 메서드를 사용하여 작업의 VM 리소스 정의

    • instances[].policy 필드를 사용하여 VM 리소스를 직접 정의합니다(가능한 경우 권장). 이 메서드는 에 나와 있습니다.
    • instances[].instanceTemplate 필드를 사용하여 템플릿을 통해 VM 리소스를 정의합니다. 이 방법은 맞춤 이미지를 통해 GPU 드라이버를 수동으로 설치하는 데 필요합니다. 자세한 내용은 VM 인스턴스 템플릿을 사용하여 작업 리소스 정의를 참고하세요.

GPU를 사용하는 예시 작업 만들기

다음 섹션에서는 각 소비 옵션에 대한 예시 작업을 만드는 방법을 설명합니다. 특히 예시 작업은 권장 옵션을 사용합니다. 모두 GPU 드라이버를 자동으로 설치하고 모두 VM 리소스를 직접 정의합니다.

소비 옵션 작업 지침 예시
예약 또는 캘린더 모드 예약 (미리보기)

VM 예약을 사용하여 리소스 가용성 확보

Flex-start VM (미리보기)

GPU 및 Flex-start VM 사용

주문형 또는 스팟 VM

GPU 머신 유형에 따라 다음 옵션 중 하나를 선택합니다.

GPU 및 Flex-start VM 사용

gcloud CLI 또는 Batch API를 사용하여 동적 워크로드 스케줄러를 통해 A3 VM에 GPU를 사용하는 작업을 만들 수 있습니다.

gcloud

  1. GPU 드라이버를 설치하고, 유연한 시작 VM을 지원하고, 예약을 차단하고, GPU 머신 유형을 지원하는 위치에서 실행되는 GPU 머신 유형을 지정하는 JSON 파일을 만듭니다.

    예를 들어 액셀러레이터 최적화 VM에 플렉스 시작 VM과 GPU를 사용하는 기본 스크립트 작업을 만들려면 다음 콘텐츠가 포함된 JSON 파일을 만듭니다.

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello world from task ${BATCH_TASK_INDEX}."
                            }
                        }
                    ]
                },
                "taskCount": 3,
                "parallelism": 1
            }
        ],
        "allocationPolicy": {
            "instances": [
                {
                    "installGpuDrivers": INSTALL_GPU_DRIVERS,
                    "policy": {
                        "provisioningModel":"FLEX_START",
                        "machineType": "MACHINE_TYPE",
                        "reservation": "NO_RESERVATION"
                    }
                }
            ],
            "location": {
                "allowedLocations": [
                    "ALLOWED_LOCATIONS"
                ]
            }
        },
        "logsPolicy": {
            "destination": "CLOUD_LOGGING"
        }
    }
    

    다음을 바꿉니다.

    • INSTALL_GPU_DRIVERS: true로 설정되면 Batch가 타사 위치에서 policy 필드에 지정한 GPU 유형에 필요한 드라이버를 가져오고 Batch가 이를 자동으로 설치합니다. 이 필드를 false(기본값)로 설정하면 이 작업에 GPU를 사용하도록 GPU 드라이버를 수동으로 설치해야 합니다.

    • MACHINE_TYPE: Flex-start VM을 지원하는 GPU 머신 유형입니다. 자세한 내용은 Compute Engine 문서의 머신 유형별 소비 옵션 가용성을 참고하세요.

    • ALLOWED_LOCATIONS: 선택적으로 allowedLocations[] 필드를 사용하여 작업의 VM이 실행될 수 있는 리전 또는 리전의 특정 영역을 지정할 수 있습니다(예: regions/us-central1us-central1 리전의 모든 영역을 허용함). 이 작업에 사용하려는 GPU 머신 유형을 제공하는 위치를 지정해야 합니다. 그렇지 않고 이 필드를 생략하는 경우 작업 위치에 GPU 머신 유형이 제공되는지 확인합니다.

  2. 작업을 만들고 실행하려면 gcloud alpha batch jobs submit 명령어를 사용합니다.

    gcloud batch jobs submit JOB_NAME \
        --location LOCATION \
        --config JSON_CONFIGURATION_FILE
    

    다음을 바꿉니다.

    • JOB_NAME: 작업의 이름

    • LOCATION: 작업의 위치

    • JSON_CONFIGURATION_FILE: 작업의 구성 세부정보가 포함된 JSON 파일의 경로

API

GPU 드라이버를 설치하고, 유연한 시작 VM을 지원하고, 예약을 차단하고, GPU 머신 유형을 지원하는 위치에서 실행되는 GPU 머신 유형을 지정하는 v1alpha jobs.create 메서드POST 요청을 보냅니다.

예를 들어 가속기 최적화 VM에 Flex-start VM과 GPU를 사용하는 기본 스크립트 작업을 만들려면 다음 요청을 수행합니다.

POST https://batch.googleapis.com/v1alpha/projects/PROJECT_ID/locations/LOCATION/jobs?job_id=JOB_NAME

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            "text": "echo Hello world from task ${BATCH_TASK_INDEX}."
                        }
                    }
                ]
            },
            "taskCount": 3,
            "parallelism": 1
        }
    ],
    "allocationPolicy": {
        "instances": [
            {
                "installGpuDrivers": INSTALL_GPU_DRIVERS,
                "policy": {
                    "provisioningModel":"FLEX_START",
                    "machineType": "MACHINE_TYPE",
                    "reservation": "NO_RESERVATION"
                }
            }
        ],
        "location": {
            "allowedLocations": [
                "ALLOWED_LOCATIONS"
            ]
        }
    },
    "logsPolicy": {
        "destination": "CLOUD_LOGGING"
    }
}

다음을 바꿉니다.

  • PROJECT_ID: 프로젝트의 프로젝트 ID

  • LOCATION: 작업의 위치

  • JOB_NAME: 작업의 이름

  • INSTALL_GPU_DRIVERS: true로 설정되면 Batch가 타사 위치에서 policy 필드에 지정한 GPU 유형에 필요한 드라이버를 가져오고 Batch가 이를 자동으로 설치합니다. 이 필드를 false(기본값)로 설정하면 이 작업에 GPU를 사용하도록 GPU 드라이버를 수동으로 설치해야 합니다.

  • MACHINE_TYPE: Flex-start VM을 지원하는 GPU 머신 유형입니다. 자세한 내용은 Compute Engine 문서의 머신 유형별 소비 옵션 가용성을 참고하세요.

  • ALLOWED_LOCATIONS: 선택적으로 allowedLocations[] 필드를 사용하여 작업의 VM이 실행될 수 있는 리전 또는 리전의 특정 영역을 지정할 수 있습니다(예: regions/us-central1us-central1 리전의 모든 영역을 허용함). 이 작업에 사용하려는 GPU 머신 유형을 제공하는 위치를 지정해야 합니다. 그렇지 않고 이 필드를 생략하는 경우 작업 위치에 GPU 머신 유형이 제공되는지 확인합니다.

가속기 최적화 VM에 GPU 사용하기

Google Cloud 콘솔, gcloud CLI, Batch API, Java, Node.js 또는 Python을 사용하여 가속기 최적화 VM에 GPU를 사용하는 작업을 만들 수 있습니다.

콘솔

Google Cloud 콘솔을 사용하여 GPU를 사용하는 작업을 만들려면 다음을 수행합니다.

  1. Google Cloud 콘솔에서 작업 목록 페이지로 이동합니다.

    작업 목록으로 이동

  2. 만들기를 클릭합니다. 일괄 작업 만들기 페이지가 열립니다. 왼쪽 창에서 작업 세부정보 페이지가 선택됩니다.

  3. 작업 세부정보 페이지를 구성합니다.

    1. 선택사항: 작업 이름 필드에서 작업 이름을 맞춤설정합니다.

      예를 들어 example-gpu-job를 입력합니다.

    2. 태스크 세부정보 섹션을 구성합니다.

      1. 새 실행 가능 항목 창에서 이 작업을 실행할 스크립트 또는 컨테이너를 하나 이상 추가합니다.

        예를 들어 기본 스크립트 작업을 만들려면 다음을 실행합니다.

        1. 스크립트 체크박스를 선택합니다. 필드가 표시됩니다.

        2. 필드에 다음 스크립트를 입력합니다.

          echo Hello world from task ${BATCH_TASK_INDEX}.
          
        3. 완료를 클릭합니다.

      2. 태스크 수 필드에 이 작업의 태스크 수를 입력합니다.

        예를 들어 3를 입력합니다.

      3. 선택사항: 동시 실행 필드에 동시에 실행할 작업 수를 입력합니다.

        예를 들어 1(기본값)을 입력합니다.

  4. 리소스 사양 페이지를 구성합니다.

    1. 왼쪽 창에서 리소스 사양을 클릭합니다. 리소스 사양 페이지가 열립니다.

    2. VM 프로비저닝 모델 섹션에서 이 작업의 VM에 대한 사용 옵션에 대해 다음 옵션 중 하나를 선택합니다.

      • 작업이 선점을 감내할 수 있고 할인된 가격으로 스팟 VM을 사용하려면 Spot을 선택합니다.

      • 그렇지 않고 주문형 VM을 사용하려면 표준 (기본값)을 선택합니다.

    3. 이 작업의 위치를 선택합니다.

      1. 리전 필드에서 리전을 선택합니다.

      2. 영역 필드에서 다음 중 하나를 수행합니다.

        • 이 작업을 특정 영역에서만 실행하도록 제한하려면 영역을 선택합니다.

        • 그렇지 않으면 모두 (기본값)를 선택합니다.

    4. 이 작업의 VM에 대한 GPU 머신 유형을 선택합니다.

      1. 머신 계열 옵션에서 GPU를 클릭합니다.

      2. GPU 유형 필드에서 GPU 유형을 선택합니다. 그런 다음 GPU 수 필드에서 각 VM의 GPU 수를 선택합니다.

        가속기 최적화 VM용 GPU 유형 중 하나를 선택한 경우 머신 유형 필드에서는 선택한 GPU 유형과 수에 따라 머신 유형에 대한 옵션 하나만 허용합니다.

      3. GPU 드라이버를 자동으로 설치하려면 GPU 드라이버 설치 (기본값)를 선택합니다.

    5. 각 작업에 필요한 VM 리소스 양을 구성합니다.

      1. 코어 필드에 태스크당 vCPU 양을 입력합니다.

        예를 들어 1(기본값)을 입력합니다.

      2. 메모리 필드에 태스크당 RAM 용량을 GB 단위로 입력합니다.

        예를 들어 0.5(기본값)을 입력합니다.

    6. 완료를 클릭합니다.

  5. 선택사항: 이 작업의 다른 필드를 구성합니다.

  6. 선택사항: 작업 구성을 검토하려면 왼쪽 창에서 미리보기를 클릭합니다.

  7. 만들기를 클릭합니다.

    작업 세부정보 페이지에 자신이 만든 작업이 표시됩니다.

gcloud

  1. GPU 드라이버를 설치하고, 가속기 최적화 머신 계열의 머신 유형을 지정하고, GPU 머신 유형이 있는 위치에서 실행되는 JSON 파일을 만듭니다.

    예를 들어 가속기 최적화 VM에 GPU를 사용하는 기본 스크립트 작업을 만들려면 다음 콘텐츠가 포함된 JSON 파일을 만듭니다.

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello world from task ${BATCH_TASK_INDEX}."
                            }
                        }
                    ]
                },
                "taskCount": 3,
                "parallelism": 1
            }
        ],
        "allocationPolicy": {
            "instances": [
                {
                    "installGpuDrivers": INSTALL_GPU_DRIVERS,
                    "policy": {
                        "provisioningModel": "PROVISIONING_MODEL",
                        "machineType": "MACHINE_TYPE",
                        "reservation": "NO_RESERVATION"
                    }
                }
            ],
            "location": {
                "allowedLocations": [
                    "ALLOWED_LOCATIONS"
                ]
            }
        },
        "logsPolicy": {
            "destination": "CLOUD_LOGGING"
        }
    }
    

    다음을 바꿉니다.

    • INSTALL_GPU_DRIVERS: true로 설정되면 Batch가 타사 위치에서 policy 필드에 지정한 GPU 유형에 필요한 드라이버를 가져오고 Batch가 이를 자동으로 설치합니다. 이 필드를 false(기본값)로 설정하면 이 작업에 GPU를 사용하도록 GPU 드라이버를 수동으로 설치해야 합니다.

    • PROVISIONING_MODEL: 소비 옵션의 프로비저닝 모델입니다. 주문형의 경우 STANDARD, 스팟 VM의 경우 SPOT입니다.

    • MACHINE_TYPE: 가속기 최적화 머신 계열의 머신 유형

    • ALLOWED_LOCATIONS: 선택적으로 allowedLocations[] 필드를 사용하여 작업의 VM이 실행될 수 있는 리전 또는 리전의 특정 영역을 지정할 수 있습니다(예: regions/us-central1us-central1 리전의 모든 영역을 허용함). 이 작업에 사용하려는 GPU 머신 유형을 제공하는 위치를 지정해야 합니다. 그렇지 않고 이 필드를 생략하는 경우 작업 위치에 GPU 머신 유형이 제공되는지 확인합니다.

  2. 작업을 만들고 실행하려면 gcloud batch jobs submit 명령어를 사용합니다.

    gcloud batch jobs submit JOB_NAME \
        --location LOCATION \
        --config JSON_CONFIGURATION_FILE
    

    다음을 바꿉니다.

    • JOB_NAME: 작업의 이름

    • LOCATION: 작업의 위치

    • JSON_CONFIGURATION_FILE: 작업의 구성 세부정보가 포함된 JSON 파일의 경로

API

GPU 드라이버를 설치하고, 가속기 최적화 머신 계열의 머신 유형을 지정하고, GPU 머신 유형이 있는 위치에서 실행되는 jobs.create 메서드POST 요청을 보냅니다.

예를 들어 가속기 최적화 VM에 GPU를 사용하는 기본 스크립트 작업을 만들려면 다음 요청을 수행합니다.

POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs?job_id=JOB_NAME

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            "text": "echo Hello world from task ${BATCH_TASK_INDEX}."
                        }
                    }
                ]
            },
            "taskCount": 3,
            "parallelism": 1
        }
    ],
    "allocationPolicy": {
        "instances": [
            {
                "installGpuDrivers": INSTALL_GPU_DRIVERS,
                "policy": {
                    "provisioningModel": "PROVISIONING_MODEL",
                    "machineType": "MACHINE_TYPE",
                    "reservation": "NO_RESERVATION"
                }
            }
        ],
        "location": {
            "allowedLocations": [
                "ALLOWED_LOCATIONS"
            ]
        }
    },
    "logsPolicy": {
        "destination": "CLOUD_LOGGING"
    }
}

다음을 바꿉니다.

  • PROJECT_ID: 프로젝트의 프로젝트 ID

  • LOCATION: 작업의 위치

  • JOB_NAME: 작업의 이름

  • INSTALL_GPU_DRIVERS: true로 설정되면 Batch가 타사 위치에서 policy 필드에 지정한 GPU 유형에 필요한 드라이버를 가져오고 Batch가 이를 자동으로 설치합니다. 이 필드를 false(기본값)로 설정하면 이 작업에 GPU를 사용하도록 GPU 드라이버를 수동으로 설치해야 합니다.

  • PROVISIONING_MODEL: 소비 옵션의 프로비저닝 모델입니다. 주문형의 경우 STANDARD, 스팟 VM의 경우 SPOT입니다.

  • MACHINE_TYPE: 가속기 최적화 머신 계열의 머신 유형

  • ALLOWED_LOCATIONS: 선택적으로 allowedLocations[] 필드를 사용하여 작업의 VM이 실행될 수 있는 리전 또는 리전의 특정 영역을 지정할 수 있습니다(예: regions/us-central1us-central1 리전의 모든 영역을 허용함). 이 작업에 사용하려는 GPU 머신 유형을 제공하는 위치를 지정해야 합니다. 그렇지 않고 이 필드를 생략하는 경우 작업 위치에 GPU 머신 유형이 제공되는지 확인합니다.

자바


import com.google.cloud.batch.v1.AllocationPolicy;
import com.google.cloud.batch.v1.AllocationPolicy.Accelerator;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicyOrTemplate;
import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.Runnable.Script;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateGpuJob {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the region you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "europe-central2";
    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "JOB_NAME";
    // Optional. When set to true, Batch fetches the drivers required for the GPU type
    // that you specify in the policy field from a third-party location,
    // and Batch installs them on your behalf. If you set this field to false (default),
    // you need to install GPU drivers manually to use any GPUs for this job.
    boolean installGpuDrivers = false;
    // Accelerator-optimized machine types are available to Batch jobs. See the list
    // of available types on: https://cloud.google.com/compute/docs/accelerator-optimized-machines
    String machineType = "g2-standard-4";

    createGpuJob(projectId, region, jobName, installGpuDrivers, machineType);
  }

  // Create a job that uses GPUs
  public static Job createGpuJob(String projectId, String region, String jobName,
                                  boolean installGpuDrivers, String machineType)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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 (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {
      // Define what will be done as part of the job.
      Runnable runnable =
          Runnable.newBuilder()
              .setScript(
                  Script.newBuilder()
                      .setText(
                          "echo Hello world! This is task ${BATCH_TASK_INDEX}. "
                                  + "This job has a total of ${BATCH_TASK_COUNT} tasks.")
                      // You can also run a script from a file. Just remember, that needs to be a
                      // script that's already on the VM that will be running the job.
                      // Using setText() and setPath() is mutually exclusive.
                      // .setPath("/tmp/test.sh")
                      .build())
              .build();

      TaskSpec task = TaskSpec.newBuilder()
                  // Jobs can be divided into tasks. In this case, we have only one task.
                  .addRunnables(runnable)
                  .setMaxRetryCount(2)
                  .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
                  .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder()
          .setTaskCount(3)
          .setParallelism(1)
          .setTaskSpec(task)
          .build();

      // Policies are used to define on what kind of virtual machines the tasks will run.
      // Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
      InstancePolicy instancePolicy =
          InstancePolicy.newBuilder().setMachineType(machineType).build();  

      // Policies are used to define on what kind of virtual machines the tasks will run on.
      AllocationPolicy allocationPolicy =
          AllocationPolicy.newBuilder()
              .addInstances(
                  InstancePolicyOrTemplate.newBuilder()
                      .setInstallGpuDrivers(installGpuDrivers)
                      .setPolicy(instancePolicy)
                      .build())
              .build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              .setAllocationPolicy(allocationPolicy)
              .putLabels("env", "testing")
              .putLabels("type", "script")
              // We use Cloud Logging as it's an out of the box available option.
              .setLogsPolicy(
                  LogsPolicy.newBuilder().setDestination(LogsPolicy.Destination.CLOUD_LOGGING))
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.getName());

      return result;
    }
  }
}

Node.js

// Imports the Batch library
const batchLib = require('@google-cloud/batch');
const batch = batchLib.protos.google.cloud.batch.v1;

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

/**
 * TODO(developer): Update these variables before running the sample.
 */
// Project ID or project number of the Google Cloud project you want to use.
const projectId = await batchClient.getProjectId();
// Name of the region you want to use to run the job. Regions that are
// available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
const region = 'europe-central2';
// The name of the job that will be created.
// It needs to be unique for each project and region pair.
const jobName = 'batch-gpu-job';
// The GPU type. You can view a list of the available GPU types
// by using the `gcloud compute accelerator-types list` command.
const gpuType = 'nvidia-l4';
// The number of GPUs of the specified type.
const gpuCount = 1;
// Optional. When set to true, Batch fetches the drivers required for the GPU type
// that you specify in the policy field from a third-party location,
// and Batch installs them on your behalf. If you set this field to false (default),
// you need to install GPU drivers manually to use any GPUs for this job.
const installGpuDrivers = false;
// Accelerator-optimized machine types are available to Batch jobs. See the list
// of available types on: https://cloud.google.com/compute/docs/accelerator-optimized-machines
const machineType = 'g2-standard-4';

// Define what will be done as part of the job.
const runnable = new batch.Runnable({
  script: new batch.Runnable.Script({
    commands: ['-c', 'echo Hello world! This is task ${BATCH_TASK_INDEX}.'],
  }),
});

const task = new batch.TaskSpec({
  runnables: [runnable],
  maxRetryCount: 2,
  maxRunDuration: {seconds: 3600},
});

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup({
  taskCount: 3,
  taskSpec: task,
});

// Policies are used to define on what kind of virtual machines the tasks will run on.
// In this case, we tell the system to use "g2-standard-4" machine type.
// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
const instancePolicy = new batch.AllocationPolicy.InstancePolicy({
  machineType,
  // Accelerator describes Compute Engine accelerators to be attached to the VM
  accelerators: [
    new batch.AllocationPolicy.Accelerator({
      type: gpuType,
      count: gpuCount,
      installGpuDrivers,
    }),
  ],
});

const allocationPolicy = new batch.AllocationPolicy.InstancePolicyOrTemplate({
  instances: [{installGpuDrivers, policy: instancePolicy}],
});

const job = new batch.Job({
  name: jobName,
  taskGroups: [group],
  labels: {env: 'testing', type: 'script'},
  allocationPolicy,
  // We use Cloud Logging as it's an option available out of the box
  logsPolicy: new batch.LogsPolicy({
    destination: batch.LogsPolicy.Destination.CLOUD_LOGGING,
  }),
});
// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateBatchGPUJob() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

  // Run request
  const [response] = await batchClient.createJob(request);
  console.log(JSON.stringify(response));
}

await callCreateBatchGPUJob();

Python

from google.cloud import batch_v1


def create_gpu_job(project_id: str, region: str, job_name: str) -> batch_v1.Job:
    """
    This method shows how to create a sample Batch Job that will run
    a simple command on Cloud Compute instances on GPU machines.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
        job_name: the name of the job that will be created.
            It needs to be unique for each project and region pair.

    Returns:
        A job object representing the job created.
    """
    client = batch_v1.BatchServiceClient()

    # Define what will be done as part of the job.
    task = batch_v1.TaskSpec()
    runnable = batch_v1.Runnable()
    runnable.script = batch_v1.Runnable.Script()
    runnable.script.text = "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
    # You can also run a script from a file. Just remember, that needs to be a script that's
    # already on the VM that will be running the job. Using runnable.script.text and runnable.script.path is mutually
    # exclusive.
    # runnable.script.path = '/tmp/test.sh'
    task.runnables = [runnable]

    # We can specify what resources are requested by each task.
    resources = batch_v1.ComputeResource()
    resources.cpu_milli = 2000  # in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
    resources.memory_mib = 16  # in MiB
    task.compute_resource = resources

    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    # Tasks are grouped inside a job using TaskGroups.
    # Currently, it's possible to have only one task group.
    group = batch_v1.TaskGroup()
    group.task_count = 4
    group.task_spec = task

    # Policies are used to define on what kind of virtual machines the tasks will run on.
    # In this case, we tell the system to use "g2-standard-4" machine type.
    # Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "g2-standard-4"

    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy
    instances.install_gpu_drivers = True
    allocation_policy = batch_v1.AllocationPolicy()
    allocation_policy.instances = [instances]

    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy
    job.labels = {"env": "testing", "type": "container"}
    # We use Cloud Logging as it's an out of the box available option
    job.logs_policy = batch_v1.LogsPolicy()
    job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING

    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

N1 VM에 GPU 사용하기

Google Cloud 콘솔, gcloud CLI, Batch API, Java, Node.js 또는 Python을 사용하여 N1 VM용 GPU를 사용하는 작업을 만들 수 있습니다.

콘솔

Google Cloud 콘솔을 사용하여 GPU를 사용하는 작업을 만들려면 다음을 수행합니다.

  1. Google Cloud 콘솔에서 작업 목록 페이지로 이동합니다.

    작업 목록으로 이동

  2. 만들기를 클릭합니다. 일괄 작업 만들기 페이지가 열립니다. 왼쪽 창에서 작업 세부정보 페이지가 선택됩니다.

  3. 작업 세부정보 페이지를 구성합니다.

    1. 선택사항: 작업 이름 필드에서 작업 이름을 맞춤설정합니다.

      예를 들어 example-gpu-job를 입력합니다.

    2. 태스크 세부정보 섹션을 구성합니다.

      1. 새 실행 가능 항목 창에서 이 작업을 실행할 스크립트 또는 컨테이너를 하나 이상 추가합니다.

        예를 들어 기본 스크립트 작업을 만들려면 다음을 실행합니다.

        1. 스크립트 체크박스를 선택합니다. 필드가 표시됩니다.

        2. 필드에 다음 스크립트를 입력합니다.

          echo Hello world from task ${BATCH_TASK_INDEX}.
          
        3. 완료를 클릭합니다.

      2. 태스크 수 필드에 이 작업의 태스크 수를 입력합니다.

        예를 들어 3를 입력합니다.

      3. 선택사항: 동시 실행 필드에 동시에 실행할 작업 수를 입력합니다.

        예를 들어 1(기본값)을 입력합니다.

  4. 리소스 사양 페이지를 구성합니다.

    1. 왼쪽 창에서 리소스 사양을 클릭합니다. 리소스 사양 페이지가 열립니다.

    2. VM 프로비저닝 모델 섹션에서 이 작업의 VM에 대한 사용 옵션에 대해 다음 옵션 중 하나를 선택합니다.

      • 작업이 선점을 감내할 수 있고 할인된 가격으로 스팟 VM을 사용하려면 Spot을 선택합니다.

      • 그렇지 않고 주문형 VM을 사용하려면 표준 (기본값)을 선택합니다.

    3. 이 작업의 위치를 선택합니다.

      1. 리전 필드에서 리전을 선택합니다.

      2. 영역 필드에서 다음 중 하나를 수행합니다.

        • 이 작업을 특정 영역에서만 실행하도록 제한하려면 영역을 선택합니다.

        • 그렇지 않으면 모두 (기본값)를 선택합니다.

    4. 이 작업의 VM에 대한 GPU 머신 유형을 선택합니다.

      1. 머신 계열 옵션에서 GPU를 클릭합니다.

      2. GPU 유형 필드에서 GPU 유형을 선택합니다.

        N1 VM용 GPU 유형 중 하나를 선택한 경우 시리즈 필드가 N1로 설정됩니다.

      3. GPU 수 필드에서 각 VM의 GPU 수를 선택합니다.

      4. 머신 유형 필드에서 머신 유형을 선택합니다.

      5. GPU 드라이버를 자동으로 설치하려면 GPU 드라이버 설치 (기본값)를 선택합니다.

    5. 각 작업에 필요한 VM 리소스 양을 구성합니다.

      1. 코어 필드에 태스크당 vCPU 양을 입력합니다.

        예를 들어 1(기본값)을 입력합니다.

      2. 메모리 필드에 태스크당 RAM 용량을 GB 단위로 입력합니다.

        예를 들어 0.5(기본값)을 입력합니다.

    6. 완료를 클릭합니다.

  5. 선택사항: 이 작업의 다른 필드를 구성합니다.

  6. 선택사항: 작업 구성을 검토하려면 왼쪽 창에서 미리보기를 클릭합니다.

  7. 만들기를 클릭합니다.

    작업 세부정보 페이지에 자신이 만든 작업이 표시됩니다.

gcloud

  1. GPU 드라이버를 설치하고, accelerators[] 필드의 typecount 하위 필드를 정의하고, GPU 머신 유형이 있는 위치에서 실행되는 JSON 파일을 만듭니다.

    예를 들어 N1 VM에 GPU를 사용하고 Batch에서 정확한 N1 머신 유형을 선택하도록 하는 기본 스크립트 작업을 만들려면 다음 콘텐츠로 JSON 파일을 만듭니다.

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello world from task ${BATCH_TASK_INDEX}."
                            }
                        }
                    ]
                },
                "taskCount": 3,
                "parallelism": 1
            }
        ],
        "allocationPolicy": {
            "instances": [
                {
                    "installGpuDrivers": INSTALL_GPU_DRIVERS,
                    "policy": {
                        "provisioningModel": "PROVISIONING_MODEL",
                        "reservation": "NO_RESERVATION",
                        "accelerators": [
                            {
                                "type": "GPU_TYPE",
                                "count": GPU_COUNT
                            }
                        ]
                    }
                }
            ],
            "location": {
                "allowedLocations": [
                    "ALLOWED_LOCATIONS"
                ]
            }
        },
        "logsPolicy": {
            "destination": "CLOUD_LOGGING"
        }
    }
    

    다음을 바꿉니다.

    • INSTALL_GPU_DRIVERS: true로 설정되면 Batch가 타사 위치에서 policy 필드에 지정한 GPU 유형에 필요한 드라이버를 가져오고 Batch가 이를 자동으로 설치합니다. 이 필드를 false(기본값)로 설정하면 이 작업에 GPU를 사용하도록 GPU 드라이버를 수동으로 설치해야 합니다.

    • PROVISIONING_MODEL: 소비 옵션의 프로비저닝 모델입니다. 주문형의 경우 STANDARD, 스팟 VM의 경우 SPOT입니다.

    • GPU_TYPE: GPU 유형입니다. gcloud compute accelerator-types list 명령어를 사용하여 사용 가능한 GPU 유형 목록을 볼 수 있습니다. N1 VM의 GPU에만 이 필드를 사용하세요.

    • GPU_COUNT: 지정된 유형의 GPU 수 유효한 옵션에 대한 자세한 내용은 N1 머신 시리즈의 GPU 머신 유형을 참고하세요. N1 VM의 GPU에만 이 필드를 사용하세요.

    • ALLOWED_LOCATIONS: 선택적으로 allowedLocations[] 필드를 사용하여 작업의 VM이 실행될 수 있는 리전 또는 리전의 특정 영역을 지정할 수 있습니다(예: regions/us-central1us-central1 리전의 모든 영역을 허용함). 이 작업에 사용하려는 GPU 머신 유형을 제공하는 위치를 지정해야 합니다. 그렇지 않고 이 필드를 생략하는 경우 작업 위치에 GPU 머신 유형이 제공되는지 확인합니다.

  2. 작업을 만들고 실행하려면 gcloud batch jobs submit 명령어를 사용합니다.

    gcloud batch jobs submit JOB_NAME \
        --location LOCATION \
        --config JSON_CONFIGURATION_FILE
    

    다음을 바꿉니다.

    • JOB_NAME: 작업의 이름

    • LOCATION: 작업의 위치

    • JSON_CONFIGURATION_FILE: 작업의 구성 세부정보가 포함된 JSON 파일의 경로

API

GPU 드라이버를 설치하고, accelerators[] 필드의 typecount 하위 필드를 정의하고, GPU 머신 유형이 있는 위치를 사용하는 jobs.create 메서드POST 요청을 보냅니다.

예를 들어 N1 VM에 GPU를 사용하고 Batch에서 정확한 N1 머신 유형을 선택하도록 하는 기본 스크립트 작업을 만들려면 다음 요청을 수행합니다.

POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs?job_id=JOB_NAME

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            "text": "echo Hello world from task ${BATCH_TASK_INDEX}."
                        }
                    }
                ]
            },
            "taskCount": 3,
            "parallelism": 1
        }
    ],
    "allocationPolicy": {
        "instances": [
            {
                "installGpuDrivers": INSTALL_GPU_DRIVERS,
                "policy": {
                    "provisioningModel": "PROVISIONING_MODEL",
                    "reservation": "NO_RESERVATION",
                    "accelerators": [
                        {
                            "type": "GPU_TYPE",
                            "count": GPU_COUNT
                        }
                    ]
                }
            }
        ],
        "location": {
            "allowedLocations": [
                "ALLOWED_LOCATIONS"
            ]
        }
    },
    "logsPolicy": {
        "destination": "CLOUD_LOGGING"
    }
}

다음을 바꿉니다.

  • PROJECT_ID: 프로젝트의 프로젝트 ID

  • LOCATION: 작업의 위치

  • JOB_NAME: 작업의 이름

  • INSTALL_GPU_DRIVERS: true로 설정되면 Batch가 타사 위치에서 policy 필드에 지정한 GPU 유형에 필요한 드라이버를 가져오고 Batch가 이를 자동으로 설치합니다. 이 필드를 false(기본값)로 설정하면 이 작업에 GPU를 사용하도록 GPU 드라이버를 수동으로 설치해야 합니다.

  • PROVISIONING_MODEL: 소비 옵션의 프로비저닝 모델입니다. 주문형의 경우 STANDARD, 스팟 VM의 경우 SPOT입니다.

  • GPU_TYPE: GPU 유형입니다. gcloud compute accelerator-types list 명령어를 사용하여 사용 가능한 GPU 유형 목록을 볼 수 있습니다. N1 VM의 GPU에만 이 필드를 사용하세요.

  • GPU_COUNT: 지정된 유형의 GPU 수 유효한 옵션에 대한 자세한 내용은 N1 머신 시리즈의 GPU 머신 유형을 참고하세요. N1 VM의 GPU에만 이 필드를 사용하세요.

  • ALLOWED_LOCATIONS: 선택적으로 allowedLocations[] 필드를 사용하여 작업의 VM이 실행될 수 있는 리전 또는 리전의 특정 영역을 지정할 수 있습니다(예: regions/us-central1us-central1 리전의 모든 영역을 허용함). 이 작업에 사용하려는 GPU 머신 유형을 제공하는 위치를 지정해야 합니다. 그렇지 않고 이 필드를 생략하는 경우 작업 위치에 GPU 머신 유형이 제공되는지 확인합니다.

자바


import com.google.cloud.batch.v1.AllocationPolicy;
import com.google.cloud.batch.v1.AllocationPolicy.Accelerator;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicyOrTemplate;
import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.Runnable.Script;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateGpuJobN1 {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the region you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "europe-central2";
    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "JOB_NAME";
    // Optional. When set to true, Batch fetches the drivers required for the GPU type
    // that you specify in the policy field from a third-party location,
    // and Batch installs them on your behalf. If you set this field to false (default),
    // you need to install GPU drivers manually to use any GPUs for this job.
    boolean installGpuDrivers = false;
    // The GPU type. You can view a list of the available GPU types
    // by using the `gcloud compute accelerator-types list` command.
    String gpuType = "nvidia-tesla-t4";
    // The number of GPUs of the specified type.
    int gpuCount = 2;

    createGpuJob(projectId, region, jobName, installGpuDrivers, gpuType, gpuCount);
  }

  // Create a job that uses GPUs
  public static Job createGpuJob(String projectId, String region, String jobName,
                                  boolean installGpuDrivers, String gpuType, int gpuCount)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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 (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {
      // Define what will be done as part of the job.
      Runnable runnable =
          Runnable.newBuilder()
              .setScript(
                  Script.newBuilder()
                      .setText(
                          "echo Hello world! This is task ${BATCH_TASK_INDEX}. "
                                  + "This job has a total of ${BATCH_TASK_COUNT} tasks.")
                      // You can also run a script from a file. Just remember, that needs to be a
                      // script that's already on the VM that will be running the job.
                      // Using setText() and setPath() is mutually exclusive.
                      // .setPath("/tmp/test.sh")
                      .build())
              .build();

      TaskSpec task = TaskSpec.newBuilder()
                  // Jobs can be divided into tasks. In this case, we have only one task.
                  .addRunnables(runnable)
                  .setMaxRetryCount(2)
                  .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
                  .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder()
          .setTaskCount(3)
          .setParallelism(1)
          .setTaskSpec(task)
          .build();

      // Accelerator describes Compute Engine accelerators to be attached to the VM.
      Accelerator accelerator = Accelerator.newBuilder()
          .setType(gpuType)
          .setCount(gpuCount)
          .build();

      // Policies are used to define on what kind of virtual machines the tasks will run on.
      AllocationPolicy allocationPolicy =
          AllocationPolicy.newBuilder()
              .addInstances(
                  InstancePolicyOrTemplate.newBuilder()
                      .setInstallGpuDrivers(installGpuDrivers)
                      .setPolicy(InstancePolicy.newBuilder().addAccelerators(accelerator))
                      .build())
              .build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              .setAllocationPolicy(allocationPolicy)
              .putLabels("env", "testing")
              .putLabels("type", "script")
              // We use Cloud Logging as it's an out of the box available option.
              .setLogsPolicy(
                  LogsPolicy.newBuilder().setDestination(LogsPolicy.Destination.CLOUD_LOGGING))
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.getName());

      return result;
    }
  }
}

Node.js

// Imports the Batch library
const batchLib = require('@google-cloud/batch');
const batch = batchLib.protos.google.cloud.batch.v1;

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

/**
 * TODO(developer): Update these variables before running the sample.
 */
// Project ID or project number of the Google Cloud project you want to use.
const projectId = await batchClient.getProjectId();
// Name of the region you want to use to run the job. Regions that are
// available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
const region = 'europe-central2';
// The name of the job that will be created.
// It needs to be unique for each project and region pair.
const jobName = 'batch-gpu-job-n1';
// The GPU type. You can view a list of the available GPU types
// by using the `gcloud compute accelerator-types list` command.
const gpuType = 'nvidia-tesla-t4';
// The number of GPUs of the specified type.
const gpuCount = 1;
// Optional. When set to true, Batch fetches the drivers required for the GPU type
// that you specify in the policy field from a third-party location,
// and Batch installs them on your behalf. If you set this field to false (default),
// you need to install GPU drivers manually to use any GPUs for this job.
const installGpuDrivers = false;
// Accelerator-optimized machine types are available to Batch jobs. See the list
// of available types on: https://cloud.google.com/compute/docs/accelerator-optimized-machines
const machineType = 'n1-standard-16';

// Define what will be done as part of the job.
const runnable = new batch.Runnable({
  script: new batch.Runnable.Script({
    commands: ['-c', 'echo Hello world! This is task ${BATCH_TASK_INDEX}.'],
  }),
});

const task = new batch.TaskSpec({
  runnables: [runnable],
  maxRetryCount: 2,
  maxRunDuration: {seconds: 3600},
});

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup({
  taskCount: 3,
  taskSpec: task,
});

// Policies are used to define on what kind of virtual machines the tasks will run on.
// In this case, we tell the system to use "g2-standard-4" machine type.
// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
const instancePolicy = new batch.AllocationPolicy.InstancePolicy({
  machineType,
  // Accelerator describes Compute Engine accelerators to be attached to the VM
  accelerators: [
    new batch.AllocationPolicy.Accelerator({
      type: gpuType,
      count: gpuCount,
      installGpuDrivers,
    }),
  ],
});

const allocationPolicy = new batch.AllocationPolicy.InstancePolicyOrTemplate({
  instances: [{installGpuDrivers, policy: instancePolicy}],
});

const job = new batch.Job({
  name: jobName,
  taskGroups: [group],
  labels: {env: 'testing', type: 'script'},
  allocationPolicy,
  // We use Cloud Logging as it's an option available out of the box
  logsPolicy: new batch.LogsPolicy({
    destination: batch.LogsPolicy.Destination.CLOUD_LOGGING,
  }),
});
// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateBatchGPUJobN1() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

  // Run request
  const [response] = await batchClient.createJob(request);
  console.log(JSON.stringify(response));
}

await callCreateBatchGPUJobN1();

Python

from google.cloud import batch_v1


def create_gpu_job(
    project_id: str, region: str, zone: str, job_name: str
) -> batch_v1.Job:
    """
    This method shows how to create a sample Batch Job that will run
    a simple command on Cloud Compute instances on GPU machines.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
        zone: name of the zone you want to use to run the job. Important in regard to GPUs availability.
            GPUs availability can be found here: https://cloud.google.com/compute/docs/gpus/gpu-regions-zones
        job_name: the name of the job that will be created.
            It needs to be unique for each project and region pair.

    Returns:
        A job object representing the job created.
    """
    client = batch_v1.BatchServiceClient()

    # Define what will be done as part of the job.
    task = batch_v1.TaskSpec()
    runnable = batch_v1.Runnable()
    runnable.script = batch_v1.Runnable.Script()
    runnable.script.text = "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
    # You can also run a script from a file. Just remember, that needs to be a script that's
    # already on the VM that will be running the job. Using runnable.script.text and runnable.script.path is mutually
    # exclusive.
    # runnable.script.path = '/tmp/test.sh'
    task.runnables = [runnable]

    # We can specify what resources are requested by each task.
    resources = batch_v1.ComputeResource()
    resources.cpu_milli = 2000  # in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
    resources.memory_mib = 16  # in MiB
    task.compute_resource = resources

    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    # Tasks are grouped inside a job using TaskGroups.
    # Currently, it's possible to have only one task group.
    group = batch_v1.TaskGroup()
    group.task_count = 4
    group.task_spec = task

    # Policies are used to define on what kind of virtual machines the tasks will run on.
    # Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "n1-standard-16"

    accelerator = batch_v1.AllocationPolicy.Accelerator()
    # Note: not every accelerator is compatible with instance type
    # Read more here: https://cloud.google.com/compute/docs/gpus#t4-gpus
    accelerator.type_ = "nvidia-tesla-t4"
    accelerator.count = 1

    policy.accelerators = [accelerator]
    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy
    instances.install_gpu_drivers = True
    allocation_policy = batch_v1.AllocationPolicy()
    allocation_policy.instances = [instances]

    location = batch_v1.AllocationPolicy.LocationPolicy()
    location.allowed_locations = ["zones/us-central1-b"]
    allocation_policy.location = location

    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy
    job.labels = {"env": "testing", "type": "container"}
    # We use Cloud Logging as it's an out of the box available option
    job.logs_policy = batch_v1.LogsPolicy()
    job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING

    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

다음 단계