建立及執行使用 GPU 的工作

本文說明如何建立及執行使用圖形處理器 (GPU) 的工作。如要進一步瞭解 GPU 的功能和限制,請參閱 Compute Engine 說明文件中的「關於 GPU」。

建立批次工作時,您可以選擇使用 GPU 加速特定工作負載。使用 GPU 的工作常見用途包括密集資料處理和人工智慧工作負載 (AI),例如機器學習 (ML)。或者,您也可以改用 TPU 加快 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. 找出並選取優先順序:

  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。

    如要將 GPU 用於加速器最佳化 VM,建議您指定機器類型。每個加速器最佳化機型僅支援特定類型和數量的 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 的可用消耗選項和工作需求。下表根據用途列出消耗選項,大致依取得難度由高到低排序。請確認所選使用模式符合您對定價、執行時間和機型支援的需求。如要進一步瞭解如何選擇使用模式,請參閱「提高資源取得能力」、Compute Engine 佈建模式說明文件,以及 AI Hypercomputer 使用模式說明文件。

用量方案和工作需求

預訂

  • 用途:如果您希望資源可用性有極高保障,且無法使用日曆模式預留項目,或您已有未使用的預留項目,建議您為工作預留項目。

  • 詳細資料:建立預留項目後,系統會按照與執行 VM 相同的價格,收取指定 VM 的費用,直到您刪除預留項目為止。使用預留項目的 VM 不會產生額外費用,但無論是否使用,預留項目都會產生費用。

    如要進一步瞭解預留項目,請參閱 Compute Engine 說明文件。

Batch 會使用預留項目,執行可耗用未使用預留 VM 的工作。如要進一步瞭解使用預留項目的工作需求,請參閱「使用 VM 預留項目確保資源可用性」頁面。

日曆模式預留項目

  • 用途:如果您想使用支援日曆模式預留項目的 GPU 機型,且需要高度確保資源可用性至少 1 天,最多 90 天,建議您為工作使用日曆模式預留項目。

  • 詳細資料:建立工作前,您必須要求或找出可使用的日曆模式預留項目。如果 Compute Engine 以日曆模式履行未來預留項目要求,自動建立的日曆模式預留項目費用,與在整個預留期間以 Dynamic Workload Scheduler 定價執行指定 VM 的費用相同,可享隨選價格最高 53% 的折扣。找出可用的自動建立日曆模式預留項目後,建立使用日曆模式預留項目的工作,與建立使用預留項目的工作非常相似。

    如要進一步瞭解日曆模式預留項目,請參閱 Compute Engine 說明文件。

如果工作符合下列所有條件,Batch 會使用日曆模式預留項目:

彈性啟動型 VM

  • 用途:如果您的工作可以接受盡力取得資源,以換取折扣價格和最多 7 天的執行時間,建議使用彈性啟動型 VM。

    相較於隨選和 Spot VM,彈性啟動型 VM 可讓您更輕鬆地同時存取多項 GPU 資源。舉例來說,彈性啟動型 VM 可減少資源無法使用造成的延遲或問題,有助於排定工作。

  • 詳細資料:如果建立使用彈性啟動型 VM 的工作要求獲得滿足,VM 會依 Dynamic Workload Scheduler 定價計費,最多可享 53% 的隨選價格折扣。

    如要進一步瞭解彈性啟動型 VM,請參閱 Compute Engine 說明文件。

如果工作符合下列所有條件,Batch 會使用彈性啟動型 VM:

以量計價

  • 用途:隨選模式快速且容易試用,因此是大多數工作的預設消耗選項1。不過,如果有其他消耗選項更符合您的優先順序,或您反覆遇到資源取得問題,則不建議使用隨選模式。

  • 詳細資料:隨選通常是存取 Compute Engine VM 的預設方式。隨選模式可讓您在提出要求時存取資源 (如有)。在工作完成或達到執行時間限制之前,系統不會刪除資源。

根據預設,Batch 會使用隨選資源執行大部分工作。如要確保工作使用隨選資源,請完成下列所有操作:1

  • 將 provisioningModel 欄位設為 STANDARD。
  • 避免使用預留項目。如要防止工作自動使用相容的預留項目,請將 reservation 欄位設為 NO_RESERVATION。詳情請參閱「建立及執行無法使用預留 VM 的工作」。

1例外狀況:對於使用 A3 機器系列的工作,預設行為是唯一的,建議您不要使用隨選,也不要將 provisioningModel 欄位留空,而是使用彈性啟動型 VM 的工作需求。由於資源可用性偏低,不建議 A3 機器系列使用隨選模式。因此,如果工作使用 A3 機器系列、封鎖預留項目,且 provisioningModel 欄位未定義或設為 STANDARD,則預設消耗選項是唯一的:行為類似於彈性啟動型 VM,會將執行時間限制為 7 天;不過,我們不建議這麼做,因為這些工作不會享有 Dynamic Workload Scheduler 定價的折扣。如果 A3 VM 工作可容許 7 天的執行時間限制,建議使用彈性啟動型 VM,而非隨選 VM。否則,除非您將 provisioningModel 設為 STANDARD,並手動確認工作無法使用預留項目,且未將 reservation 欄位設為 NO_RESERVATION,否則無法確保使用 A3 VM 的工作會使用隨選資源。

Spot VM

  • 用途:建議您使用 Spot VM 降低容錯工作負載的成本。

  • 詳細資料:如果建立使用 Spot VM 的工作要求獲得滿足,VM 會按照 Spot VM 定價收費,這類價格可能經常變動,且可能提供最大折扣,最多可享隨選價格 91% 的折扣。不過,Spot VM 不一定隨時可用,且可能隨時遭到先占。

    進一步瞭解 Spot VM 和使用 Spot VM 的工作建議。

Batch 會將 Spot VM 用於符合下列所有條件的工作:

  • 將 provisioningModel 欄位設為 SPOT。
  • (選用) 防止預留項目用量。Spot VM 無法與預留項目搭配使用。具體來說,工作可以選擇將 reservation 欄位設為 NO_RESERVATION。詳情請參閱「建立及執行無法使用預留 VM 的工作」。

步驟 2:安裝 GPU 驅動程式

如要在工作中使用 GPU,必須安裝 GPU 驅動程式。如要安裝 GPU 驅動程式,請選取下列其中一種方法:

步驟 3:定義相容的 VM 資源

如要瞭解定義工作 VM 資源的需求條件和選項,請參閱「工作資源」。

總之,為使用 GPU 的工作定義 VM 資源時,您必須完成下列所有操作:

  • 確認工作 VM 的位置提供 GPU 機型。

    如要瞭解哪些位置提供 GPU 機型,請參閱 Compute Engine 說明文件中的「GPU 位置」。

  • 如果指定工作的機型,請確保該機型有足夠的 vCPU 和記憶體,可滿足工作的任務需求。使用 Google Cloud 控制台建立工作時,必須指定工作的機器類型。如果建立的工作會使用 GPU 執行加速器最佳化 VM,也建議指定機器類型。

  • 請務必使用有效方法定義工作的 VM 資源:

    • 直接使用 instances[].policy 欄位定義 VM 資源 (建議盡可能採用此做法)。範例中會說明這個方法。
    • 使用 instances[].instanceTemplate 欄位,透過範本定義 VM 資源。如要透過自訂映像檔手動安裝 GPU 驅動程式,就必須使用這個方法。詳情請參閱「使用 VM 執行個體範本定義工作資源」。

建立使用 GPU 的工作

以下各節說明如何為各個消耗選項建立範例工作。具體來說,範例工作會使用建議選項:全部自動安裝 GPU 驅動程式,並直接定義 VM 資源。

計費方案 工作操作說明範例
預留項目或日曆模式預留項目

使用 VM 預留項目確保資源可用性

彈性啟動型 VM

使用 GPU 和彈性啟動型 VM

隨選或 Spot VM

根據 GPU 機型,選取下列其中一個選項:

使用 GPU 和彈性啟動型 VM

您可以使用 gcloud CLI 或 Batch API,透過 Dynamic Workload Scheduler 建立使用 A3 VM GPU 的工作。

gcloud

  1. 建立 JSON 檔案,用於安裝 GPU 驅動程式、指定支援彈性啟動型 VM 的 GPU 機型、封鎖預留項目,以及在支援 GPU 機型的位置執行。

    舉例來說,如要建立基本指令碼工作,並使用彈性啟動型 VM 和 GPU 執行加速器最佳化 VM,請建立包含下列內容的 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:是否自動安裝 GPU 驅動程式。如果設為 true,Batch 會從第三方位置擷取您在 policy 欄位中指定的 GPU 類型所需驅動程式,並代為安裝。如果將這個欄位設為 false (預設),則須手動安裝 GPU 驅動程式,才能在這項工作使用任何 GPU。

    • MACHINE_TYPE:支援彈性啟動型 VM 的 GPU 機器類型。詳情請參閱 Compute Engine 說明文件中的「依機型查看用量選項可用性」。

    • ALLOWED_LOCATIONS:工作允許的位置。請確保工作 Compute Engine 資源的位置提供您要用於這項工作的 GPU 機型,方法是使用下列其中一個選項:

      • 根據預設,如果省略 allowedLocations[] 欄位,工作會在工作位置 (LOCATION) 區域中建立的 Compute Engine 資源上執行。
      • 您也可以選擇加入 allowedLocations[] 欄位,這樣工作就只能在指定位置建立的 Compute Engine 資源上執行。

  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

向 jobs.create 方法發出 POST 要求,安裝 GPU 驅動程式、指定支援彈性啟動型 VM 的 GPU 機型、封鎖預留項目,並在支援該 GPU 機型的位置執行。

舉例來說,如要建立基本指令碼工作,並使用彈性啟動 VM 和加速器最佳化 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":"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:是否自動安裝 GPU 驅動程式。如果設為 true,Batch 會從第三方位置擷取您在 policy 欄位中指定的 GPU 類型所需驅動程式,並代為安裝。如果將這個欄位設為 false (預設),則須手動安裝 GPU 驅動程式,才能在這項工作使用任何 GPU。

  • MACHINE_TYPE:支援彈性啟動型 VM 的 GPU 機器類型。詳情請參閱 Compute Engine 說明文件中的「依機型查看用量選項可用性」。

  • ALLOWED_LOCATIONS:工作允許的位置。請確保工作 Compute Engine 資源的位置提供您要用於這項工作的 GPU 機型,方法是使用下列其中一個選項:

    • 根據預設,如果省略 allowedLocations[] 欄位,工作會在工作位置 (LOCATION) 區域中建立的 Compute Engine 資源上執行。
    • 您也可以選擇加入 allowedLocations[] 欄位,這樣工作就只能在指定位置建立的 Compute Engine 資源上執行。

使用 GPU 建立加速器最佳化 VM

您可以使用Google Cloud 控制台、gcloud CLI、Batch API、Java、Node.js 或 Python,建立使用 GPU 的加速器最佳化 VM 工作。

控制台

如要使用 Google Cloud 控制台建立使用 GPU 的工作,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台的「Job list」(工作清單) 頁面。

    前往工作清單

  2. 按一下「 建立」。「Create batch job」(建立批次工作) 頁面隨即開啟。左側窗格會選取「Job details」(工作詳細資料) 頁面。

  3. 設定「Job details」(工作詳細資料) 頁面:

    1. 選用:在「Job name」(工作名稱) 欄位中自訂工作名稱。

      例如,輸入 example-gpu-job。

    2. 設定「Task details」(工作詳細資料) 部分:

      1. 在「New runnable」(新增可執行檔) 視窗中,新增至少一個指令碼或容器,以便執行這項工作。

        舉例來說,如要建立基本指令碼工作,請按照下列步驟操作:

        1. 勾選「Script」核取方塊。系統會隨即顯示欄位。

        2. 在欄位中輸入下列指令碼:

          echo Hello world from task ${BATCH_TASK_INDEX}.
          
        3. 按一下「完成」。

      2. 在「Task count」(工作數量) 欄位中,輸入這項工作的任務數量。

        例如,輸入 3。

      3. 選用:在「Parallelism」(平行處理) 欄位中,輸入要同時執行的工作數量。

        例如,輸入 1 (預設)。

  4. 設定「Resource specifications」(資源規格) 頁面:

    1. 在左側窗格中,按一下「Resource specifications」(資源規格)。「Resource specifications」(資源規格) 頁面隨即開啟。

    2. 在「VM provisioning model」(VM 佈建模型) 部分,為這項工作的 VM 選取下列其中一個消耗選項:

      • 如果工作可以承受先占,且您想以折扣價使用 Spot VM,請選取「Spot」。

      • 如要使用隨選 VM,請選取「Standard」(標準) (預設)。

    3. 選取這項工作的位置。

      1. 在「Region」(區域) 欄位中選取區域。

      2. 在「Zone」(可用區) 欄位中,執行下列任一操作:

        • 如要限制這項工作只能在特定可用區執行,請選取可用區。

        • 否則,請選取「any」(預設)。

    4. 在「Machine type configuration」(機器類型設定) 區段中,選取這項工作 VM 的 GPU 機器類型:

      1. 如要指定一種機型,請選取「Fixed machine type」(固定機型) (預設)。

      2. 在機器家族選項中,按一下「GPU」。

      3. 在「GPU type」(GPU 類型) 欄位中,選取 GPU 類型。接著,在「Number of GPUs」(GPU 數量) 欄位中,選取每個 VM 的 GPU 數量。

        如果您選取加速器最佳化 VM 的其中一種 GPU 類型,則「Machine type」(機器類型) 欄位只會根據您選取的 GPU 類型和數量,提供一種機器類型選項。

      4. 如要自動安裝 GPU 驅動程式,請選取「GPU driver installation」(GPU 驅動程式安裝) (預設)。

    5. 在「Task resources」(工作資源) 區段中,設定每項工作所需的 VM 資源量:

      1. 在「Cores」(核心) 欄位中,輸入每項工作的 vCPUs 數量。

        例如,輸入 1 (預設)。

      2. 在「Memory」(記憶體) 欄位中,輸入每項工作的 RAM 容量 (以 GB 為單位)。

        例如,輸入 0.5 (預設)。

    6. 按一下「完成」。

  5. 選用:設定這項工作的其他欄位。

  6. 選用:如要查看工作設定,請按一下左側窗格中的「Preview」(預覽)。

  7. 點選「建立」。

    「Job details」(工作詳細資料) 頁面會顯示您建立的工作。

gcloud

  1. 建立 JSON 檔案,安裝 GPU 驅動程式、指定加速器最佳化機器家族的機型,並在具有 GPU 機型的位置執行。

    舉例來說,如要建立基本指令碼工作,並使用 GPU 執行加速器最佳化 VM,請建立包含下列內容的 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:是否自動安裝 GPU 驅動程式。如果設為 true,Batch 會從第三方位置擷取您在 policy 欄位中指定的 GPU 類型所需驅動程式,並代為安裝。如果將這個欄位設為 false (預設),則須手動安裝 GPU 驅動程式,才能在這項工作使用任何 GPU。

    • PROVISIONING_MODEL:用量選項的佈建模式:STANDARD 代表隨選,SPOT 代表 Spot VM。

    • MACHINE_TYPE:加速器最佳化機器系列中的機型。

    • ALLOWED_LOCATIONS:工作允許的位置。請確保工作 Compute Engine 資源的位置提供您要用於這項工作的 GPU 機型,方法是使用下列其中一個選項:

      • 根據預設,如果省略 allowedLocations[] 欄位,工作會在工作位置 (LOCATION) 區域中建立的 Compute Engine 資源上執行。
      • 您也可以選擇加入 allowedLocations[] 欄位,這樣工作就只能在指定位置建立的 Compute Engine 資源上執行。

  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

向 jobs.create 方法發出 POST 要求,安裝 GPU 驅動程式、指定加速器最佳化機器家族的機型,並在具有 GPU 機型的位置執行。

舉例來說,如要建立基本指令碼工作,並使用 GPU 執行加速器最佳化 VM,請提出下列要求:

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:是否自動安裝 GPU 驅動程式。如果設為 true,Batch 會從第三方位置擷取您在 policy 欄位中指定的 GPU 類型所需驅動程式,並代為安裝。如果將這個欄位設為 false (預設),則須手動安裝 GPU 驅動程式,才能在這項工作使用任何 GPU。

  • PROVISIONING_MODEL:用量選項的佈建模式:STANDARD 代表隨選,SPOT 代表 Spot VM。

  • MACHINE_TYPE:加速器最佳化機器系列中的機型。

  • ALLOWED_LOCATIONS:工作允許的位置。請確保工作 Compute Engine 資源的位置提供您要用於這項工作的 GPU 機型,方法是使用下列其中一個選項:

    • 根據預設,如果省略 allowedLocations[] 欄位,工作會在工作位置 (LOCATION) 區域中建立的 Compute Engine 資源上執行。
    • 您也可以選擇加入 allowedLocations[] 欄位,這樣工作就只能在指定位置建立的 Compute Engine 資源上執行。

Java


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 控制台的「Job list」(工作清單) 頁面。

    前往工作清單

  2. 按一下「 建立」。「Create batch job」(建立批次工作) 頁面隨即開啟。左側窗格會選取「Job details」(工作詳細資料) 頁面。

  3. 設定「Job details」(工作詳細資料) 頁面:

    1. 選用:在「Job name」(工作名稱) 欄位中自訂工作名稱。

      例如,輸入 example-gpu-job。

    2. 設定「Task details」(工作詳細資料) 部分:

      1. 在「New runnable」(新增可執行檔) 視窗中,新增至少一個指令碼或容器,以便執行這項工作。

        舉例來說,如要建立基本指令碼工作,請按照下列步驟操作:

        1. 勾選「Script」核取方塊。系統會隨即顯示欄位。

        2. 在欄位中輸入下列指令碼:

          echo Hello world from task ${BATCH_TASK_INDEX}.
          
        3. 按一下「完成」。

      2. 在「Task count」(工作數量) 欄位中,輸入這項工作的任務數量。

        例如,輸入 3。

      3. 選用:在「Parallelism」(平行處理) 欄位中,輸入要同時執行的工作數量。

        例如,輸入 1 (預設)。

  4. 設定「Resource specifications」(資源規格) 頁面:

    1. 在左側窗格中,按一下「Resource specifications」(資源規格)。「Resource specifications」(資源規格) 頁面隨即開啟。

    2. 在「VM provisioning model」(VM 佈建模型) 部分,為這項工作的 VM 選取下列其中一個消耗選項:

      • 如果工作可以承受先占,且您想以折扣價使用 Spot VM,請選取「Spot」。

      • 如要使用隨選 VM,請選取「Standard」(標準) (預設)。

    3. 選取這項工作的位置。

      1. 在「Region」(區域) 欄位中選取區域。

      2. 在「Zone」(可用區) 欄位中,執行下列任一操作:

        • 如要限制這項工作只能在特定可用區執行,請選取可用區。

        • 否則,請選取「any」(預設)。

    4. 在「Machine type configuration」(機器類型設定) 區段中,選取這項工作 VM 的 GPU 機器類型:

      1. 如要指定一種機型,請選取「Fixed machine type」(固定機型) (預設)。

      2. 在機器家族選項中,按一下「GPU」。

      3. 在「GPU type」(GPU 類型) 欄位中,選取 GPU 類型。

        如果您選取 N1 VM 的其中一種 GPU 類型,「Series」(系列) 欄位會設為「N1」。

      4. 在「Number of GPUs」(GPU 數量) 欄位中,選取每個 VM 的 GPU 數量。

      5. 在「Machine type」(機器類型) 欄位中,選取機器類型。

      6. 如要自動安裝 GPU 驅動程式,請選取「GPU driver installation」(GPU 驅動程式安裝) (預設)。

    5. 在「Task resources」(工作資源) 區段中,設定每項工作所需的 VM 資源量:

      1. 在「Cores」(核心) 欄位中,輸入每項工作的 vCPUs 數量。

        例如,輸入 1 (預設)。

      2. 在「Memory」(記憶體) 欄位中,輸入每項工作的 RAM 容量 (以 GB 為單位)。

        例如,輸入 0.5 (預設)。

    6. 按一下「完成」。

  5. 選用:設定這項工作的其他欄位。

  6. 選用:如要查看工作設定,請按一下左側窗格中的「Preview」(預覽)。

  7. 點選「建立」。

    「Job details」(工作詳細資料) 頁面會顯示您建立的工作。

gcloud

  1. 建立 JSON 檔案,用於安裝 GPU 驅動程式、定義 accelerators[] 欄位的 type 和 count 子欄位,並在具有 GPU 機型的位置執行。

    舉例來說,如要建立基本指令碼工作,使用 GPU 執行 N1 VM,並讓 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:是否自動安裝 GPU 驅動程式。如果設為 true,Batch 會從第三方位置擷取您在 policy 欄位中指定的 GPU 類型所需驅動程式,並代為安裝。如果將這個欄位設為 false (預設),則須手動安裝 GPU 驅動程式,才能在這項工作使用任何 GPU。

    • PROVISIONING_MODEL:用量選項的佈建模式:STANDARD 代表隨選,SPOT 代表 Spot VM。

    • GPU_TYPE:GPU 類型。您可以使用 gcloud compute accelerator-types list 指令查看可用的 GPU 類型清單。這個欄位僅適用於 N1 VM 的 GPU。

    • GPU_COUNT:指定類型的 GPU 數量。如要進一步瞭解有效選項,請參閱「N1 機器系列的 GPU 機型」。這個欄位僅適用於 N1 VM 的 GPU。

    • ALLOWED_LOCATIONS:工作允許的位置。請確保工作 Compute Engine 資源的位置提供您要用於這項工作的 GPU 機型,方法是使用下列其中一個選項:

      • 根據預設,如果省略 allowedLocations[] 欄位,工作會在工作位置 (LOCATION) 區域中建立的 Compute Engine 資源上執行。
      • 您也可以選擇加入 allowedLocations[] 欄位,這樣工作就只能在指定位置建立的 Compute Engine 資源上執行。

  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

向 jobs.create 方法發出 POST 要求,安裝 GPU 驅動程式、定義 accelerators[] 欄位的 type 和 count 子欄位,並使用具有 GPU 機型的位置。

舉例來說,如要建立基本指令碼工作,使用 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:是否自動安裝 GPU 驅動程式。如果設為 true,Batch 會從第三方位置擷取您在 policy 欄位中指定的 GPU 類型所需驅動程式,並代為安裝。如果將這個欄位設為 false (預設),則須手動安裝 GPU 驅動程式,才能在這項工作使用任何 GPU。

  • PROVISIONING_MODEL:用量選項的佈建模式:STANDARD 代表隨選,SPOT 代表 Spot VM。

  • GPU_TYPE:GPU 類型。您可以使用 gcloud compute accelerator-types list 指令查看可用的 GPU 類型清單。這個欄位僅適用於 N1 VM 的 GPU。

  • GPU_COUNT:指定類型的 GPU 數量。如要進一步瞭解有效選項,請參閱「N1 機器系列的 GPU 機型」。這個欄位僅適用於 N1 VM 的 GPU。

  • ALLOWED_LOCATIONS:工作允許的位置。請確保工作 Compute Engine 資源的位置提供您要用於這項工作的 GPU 機型,方法是使用下列其中一個選項:

    • 根據預設,如果省略 allowedLocations[] 欄位,工作會在工作位置 (LOCATION) 區域中建立的 Compute Engine 資源上執行。
    • 您也可以選擇加入 allowedLocations[] 欄位,這樣工作就只能在指定位置建立的 Compute Engine 資源上執行。

Java


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)

後續步驟