创建和运行使用 GPU 的作业

本文档介绍了如何创建和运行使用图形处理单元 (GPU) 的作业。如需详细了解 GPU 的功能和限制,请参阅 Compute Engine 文档中的 GPU 简介

创建 Batch 作业时,您可以选择使用 GPU 来加速特定的工作负载。使用 GPU 的作业的常见应用场景包括密集型数据处理和人工智能 (AI) 工作负载(例如机器学习 (ML))。

准备工作

  1. 如果您之前未使用过 Batch,请查看开始使用 Batch,并完成项目和用户的前提条件以启用 Batch。
  2. 如需获得创建作业所需的权限,请让您的管理员为您授予以下 IAM 角色:

    如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

    您也可以通过自定义角色或其他预定义角色来获取所需的权限。

创建使用 GPU 的作业

如需创建使用 GPU 的作业,请执行以下操作:

  1. 规划使用 GPU 的作业的要求
  2. 根据您确定的要求和方法创建作业。 如需查看如何使用建议的选项创建作业的示例,请参阅本文档中的创建使用 GPU 的示例作业

规划使用 GPU 的作业的要求

在创建使用 GPU 的作业之前,请按以下部分所述规划作业的要求:

  1. 选择 GPU 机器类型和消耗选项
  2. 安装 GPU 驱动程序
  3. 定义兼容的虚拟机资源

第 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 机器类型及其作业要求

    加速器优化型虚拟机的 GPU:如果虚拟机的机器类型属于加速器优化型机器系列,则会自动挂接特定类型和数量的此类 GPU。

    如需将 GPU 用于加速器优化虚拟机,我们建议您指定机器类型。每种加速器优化机器类型仅支持特定类型和数量的 GPU,因此无论您是否指定这些值,其功能都与加速器优化机器类型相同。

    具体而言,Batch 还支持仅为经过加速器优化的虚拟机指定 GPU 的类型和数量,但由此产生的 vCPU 和内存选项通常非常有限。因此,我们建议您验证可用的 vCPU 和内存选项是否与作业的任务要求兼容。

    N1 虚拟机的 GPU:这些 GPU 需要您指定要挂接到每个虚拟机的类型和数量,并且必须挂接到机器类型属于 N1 机器系列的虚拟机。

    如需为 N1 虚拟机使用 GPU,建议您至少指定 GPU 的类型和数量。确保值组合与 N1 机器类型的有效 GPU 选项之一相匹配。对于使用任何特定类型和数量 GPU 的 N1 虚拟机,vCPU 和内存选项非常灵活。除非您使用 Google Cloud 控制台创建作业,否则您可以让 Batch 自动选择满足作业任务要求的机器类型。

选择使用选项

本部分总结了如何为作业选择消费选项,以及每种选项的作业要求。

下表介绍了 Batch 的可用消耗选项及其要求,并根据这些选项的用例(从大致最高到最低的资源可用性)列出了这些选项。

总而言之,我们建议大多数用户为作业选择以下消费选项:

  • 除非满足其他条件之一,否则请使用灵活启动虚拟机(预览版)(如果满足您的要求,则首选此选项)或按需付费虚拟机。
  • 如果您的作业需要极高的资源可用性保证,或者您有任何无法删除的未使用预留,请使用日历模式预留(预览版)(如果满足您的要求,则首选此模式)或预留。
  • (可选)如果您的工作负载具有很强的容错能力,那么您或许可以尝试使用 Spot 虚拟机来降低费用。
使用选项及其作业要求

预留

  • 使用场景:如果您希望资源可用性得到非常高的保障,但无法使用日历模式预留,或者您已有可能会未使用的现有预留,我们建议您为作业使用预留。

  • 详细信息:创建预留后,系统会按照与运行虚拟机相同的价格收取指定虚拟机的费用,直到您删除预留为止。使用预留的虚拟机不会产生单独的费用,但无论是否使用预留,都会产生费用。

    如需详细了解预留,请参阅 Compute Engine 文档。

Batch 使用预留来运行可使用未使用的预留虚拟机的作业。如需详细了解使用预留的作业要求,请参阅使用虚拟机预留确保资源可用性页面。

日历模式下的预留(预览版

  • 使用情形:如果您想使用支持日历模式预留的 GPU 机器类型,并且需要至少 1 天(最多 90 天)的资源可用性保证,我们建议您为作业使用日历模式预留。

  • 详情:在创建作业之前,您必须请求或确定可使用的日历模式预留。如果 Compute Engine 满足了日历模式下的未来预留请求,则自动创建的日历模式预留的费用与在整个预留期内以动态工作负载调度器价格运行指定虚拟机的费用相同,该价格可提供最高 53% 的按需价格折扣。在确定可使用的自动创建的日历模式预留后,创建使用日历模式预留的作业与创建使用预留的作业非常相似。

    如需详细了解 Compute Engine 文档中的日历模式预留,请参阅相关内容。

Batch 会为满足以下所有条件的作业使用日历模式预留

灵活启动虚拟机(预览版

  • 使用情形:如果您的作业可以承受尽力而为的可用性,以换取折扣价格和最多 7 天的运行时间,我们建议您使用灵活启动虚拟机。

    与按需虚拟机和 Spot 虚拟机相比,灵活启动虚拟机可让您更轻松地同时访问许多 GPU 资源。例如,灵活启动虚拟机有助于进行作业调度,方法是缓解因资源不可用而导致的延迟或问题。

  • 详情:如果创建使用灵活启动虚拟机的作业的请求得到满足,则虚拟机会按照动态工作负载调度器价格计费,该价格可提供最高 53% 的按需价格折扣。

    如需详细了解 Compute Engine 文档中的灵活启动虚拟机,请参阅相关内容。

对于满足以下所有条件的作业,Batch 会使用灵活启动虚拟机

按需

  • 应用场景:我们建议默认情况下为大多数其他作业使用按需执行。1

  • 详情:按需通常是访问 Compute Engine 虚拟机的默认方式。按需可让您在需要时访问资源(如果可用)。系统会删除资源,直到作业完成或达到运行时限为止。

默认情况下,批处理作业对大多数其他作业使用按需模式。如果您想确保作业使用按需实例,请执行以下所有操作1

1例外情况:对于使用 A3 系列机器的作业,默认行为是唯一的,我们建议您不要使用按需虚拟机,也不要将 provisioningModel 字段保留为未定义;而应使用 Flex-start 虚拟机的作业要求 由于资源可用性较低,不建议 A3 机器系列使用按需实例。因此,如果作业使用 A3 机器系列、阻止预留,并且 provisioningModel 字段未定义或设置为 STANDARD,则默认使用选项是唯一的:其行为类似于灵活启动虚拟机,将运行时间限制为 7 天;不过,不建议使用此选项,因为这些作业不会获得动态工作负载调度器价格的折扣。 如果使用 A3 虚拟机的作业可以容忍 7 天的运行时间限制,我们建议您使用灵活启动虚拟机,而不是按需虚拟机。 否则,您无法确保使用 A3 虚拟机的作业使用按需付费,除非您将 provisioningModel 设置为 STANDARD 并手动验证作业无法使用预留,而无需将 reservation 字段设置为 NO_RESERVATION

Spot 虚拟机

  • 使用情形:建议尝试使用 Spot 虚拟机来降低容错型工作负载的费用。

  • 详细信息:如果创建使用 Spot 虚拟机的作业的请求得到满足,则虚拟机将按 Spot 虚拟机价格收费,该价格可能会经常变动,并且可能提供最大折扣,最高可优惠按需价格的 91%。不过,Spot 虚拟机可能并非始终可用,并且随时可能被抢占。

    如需详细了解 Spot 虚拟机,请参阅 Compute Engine 文档。

Batch 会针对满足以下所有条件的作业使用 Spot 虚拟机

  • provisioningModel 字段设置为 SPOT
  • (可选)屏蔽预订。您无法将 Spot 虚拟机与预留搭配使用。具体来说,作业可以选择性地将 reservation 字段设置为 NO_RESERVATION。如需了解详情,请参阅创建和运行无法使用预留虚拟机的作业

第 2 步:安装 GPU 驱动程序

如需将 GPU 用于作业,您必须安装 GPU 驱动程序。如需安装 GPU 驱动程序,请选择以下方法之一:

第 3 步:定义兼容的虚拟机资源

如需了解定义作业的虚拟机资源的要求和选项,请参阅作业资源

总而言之,在为使用 GPU 的作业定义虚拟机资源时,您必须执行以下所有操作:

  • 确保 GPU 机器类型在作业虚拟机的所在位置可用。

    如需了解 GPU 机器类型的可用区域,请参阅 Compute Engine 文档中的加速器可用性

  • 如果您指定作业的机器类型,请确保该机器类型具有足够的 vCPU 和内存来满足作业的任务要求。无论何时使用 Google Cloud 控制台创建作业,都必须指定作业的机器类型;无论何时创建使用 GPU 的作业,都建议指定作业的机器类型,以便使用经过加速器优化的虚拟机。

  • 请确保您使用有效方法为作业定义虚拟机资源:

    • 使用 instances[].policy 字段直接定义虚拟机资源(建议尽可能使用)。 此方法在示例中进行了演示。
    • 使用 instances[].instanceTemplate 字段通过模板定义虚拟机资源。 此方法是必需的,用于通过自定义映像手动安装 GPU 驱动程序。如需了解详情,请参阅使用虚拟机实例模板定义作业资源

创建使用 GPU 的作业示例

以下部分介绍了如何为每种消费选项创建示例作业。具体而言,示例作业使用建议的选项:全部自动安装 GPU 驱动程序,全部直接定义虚拟机资源。

使用选项 作业指令示例
预留日历模式下的预留(预览版

使用虚拟机预留确保资源可用性

灵活启动虚拟机(预览版

使用 GPU 和灵活启动虚拟机

按需虚拟机Spot 虚拟机

根据您的 GPU 机器类型,选择以下选项之一:

使用 GPU 和灵活启动虚拟机

您可以使用 gcloud CLI 或 Batch API 通过动态工作负载调度器创建使用 GPU 的 A3 虚拟机作业。

gcloud

  1. 创建一个 JSON 文件,用于安装 GPU 驱动程序、指定支持灵活启动虚拟机的 GPU 机器类型、阻止预留,并在支持该 GPU 机器类型的位置运行。

    例如,如需创建使用 Flex-start 虚拟机和 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 类型所需的驱动程序,并代表您安装这些驱动程序。如果您将此字段设置为 false(默认值),则需要手动安装 GPU 驱动程序才能使用任何 GPU 来运行此作业。

    • MACHINE_TYPE:支持灵活启动虚拟机的 GPU 机器类型。如需了解详情,请参阅 Compute Engine 文档中的按机器类型列出的消费选项可用性

    • ALLOWED_LOCATIONS:您可以选择使用 allowedLocations[] 字段来指定作业的虚拟机允许运行的区域或区域中的特定可用区,例如,regions/us-central1 允许在 us-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

v1alpha jobs.create 方法发出 POST 请求,该请求会安装 GPU 驱动程序、指定支持灵活启动虚拟机的 GPU 机器类型、阻止预留,并在支持 GPU 机器类型的位置运行。

例如,如需创建使用灵活启动虚拟机和 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 类型所需的驱动程序,并代表您安装这些驱动程序。如果您将此字段设置为 false(默认值),则需要手动安装 GPU 驱动程序才能将任何 GPU 用于此作业。

  • MACHINE_TYPE:支持灵活启动虚拟机的 GPU 机器类型。如需了解详情,请参阅 Compute Engine 文档中的按机器类型列出的消费选项可用性

  • ALLOWED_LOCATIONS:您可以选择使用 allowedLocations[] 字段来指定作业的虚拟机允许运行的区域或区域中的特定可用区,例如,regions/us-central1 允许在 us-central1 区域中的所有可用区运行。 请务必指定提供您希望用于此作业的 GPU 机器类型的位置。否则,如果您省略此字段,请确保作业的位置提供 GPU 机器类型。

为加速器优化型虚拟机使用 GPU

您可以使用Google Cloud 控制台、gcloud CLI、Batch API、Java、Node.js 或 Python 创建使用 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. 虚拟机预配模型部分中,为相应作业的虚拟机选择以下使用选项之一:

      • 如果您的作业可以承受抢占,并且您想要使用折扣价的 Spot 虚拟机,请选择 Spot

      • 否则,如需使用按需付费型虚拟机,请选择标准(默认)。

    3. 为此作业选择位置

      1. 区域字段中,选择一个区域。

      2. 可用区字段中,执行以下操作之一:

        • 如果您希望将此作业限制为仅在特定可用区中运行,请选择一个可用区。

        • 否则,请选择任意(默认)。

    4. 为相应作业的虚拟机选择 GPU 机器类型:

      1. 在机器系列选项中,点击 GPU

      2. GPU 类型字段中,选择 GPU 类型。然后,在 GPU 数量字段中,选择每个虚拟机的 GPU 数量。

        如果您选择的是加速器优化型虚拟机的 GPU 类型,则机器类型字段仅允许根据您选择的 GPU 类型和数量选择一种机器类型。

      3. 如需自动安装 GPU 驱动程序,请选择 GPU 驱动程序安装(默认)。

    5. 配置每项任务所需的虚拟机资源量:

      1. 核心数字段中,输入每个任务的 vCPUs 数量。

        例如,输入 1(默认值)。

      2. 内存字段中,输入每个任务的 RAM 量(以 GB 为单位)。

        例如,输入 0.5(默认值)。

    6. 点击完成

  5. 可选:配置此作业的其他字段

  6. 可选:如需查看作业配置,请在左侧窗格中点击预览

  7. 点击创建

    作业详情页面会显示您创建的作业。

gcloud

  1. 创建一个 JSON 文件,用于安装 GPU 驱动程序、指定加速器优化机器系列中的机器类型,并在具有 GPU 机器类型的位置运行。

    例如,如需创建使用 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 类型所需的驱动程序,并代表您将其安装。如果您将此字段设置为 false(默认值),则需要手动安装 GPU 驱动程序才能将任何 GPU 用于此作业。

    • PROVISIONING_MODEL消费选项的预配模型:STANDARD 表示按需,SPOT 表示 Spot 虚拟机。

    • MACHINE_TYPE加速器优化机器系列中的机器类型。

    • ALLOWED_LOCATIONS:您可以选择使用 allowedLocations[] 字段来指定作业的虚拟机允许运行的区域或区域中的特定可用区,例如,regions/us-central1 允许在 us-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

jobs.create 方法发出 POST 请求,该请求会安装 GPU 驱动程序、指定加速器优化机器系列中的机器类型,并在具有 GPU 机器类型的位置运行。

例如,如需创建使用 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 类型所需的驱动程序,并代表您安装这些驱动程序。如果您将此字段设置为 false(默认值),则需要手动安装 GPU 驱动程序才能将任何 GPU 用于此作业。

  • PROVISIONING_MODEL消费选项的预配模型:STANDARD 表示按需,SPOT 表示 Spot 虚拟机。

  • MACHINE_TYPE加速器优化机器系列中的机器类型。

  • ALLOWED_LOCATIONS:您可以选择使用 allowedLocations[] 字段来指定作业的虚拟机允许运行的区域或区域中的特定可用区,例如,regions/us-central1 允许在 us-central1 区域中的所有可用区运行。 请务必指定提供您希望用于此作业的 GPU 机器类型的位置。否则,如果您省略此字段,请确保作业的位置提供 GPU 机器类型。

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 虚拟机使用 GPU

您可以使用 Google Cloud 控制台、gcloud CLI、Batch API、Java、Node.js 或 Python 创建使用 GPU 的 N1 虚拟机作业。

控制台

如需使用 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. 虚拟机预配模型部分中,为相应作业的虚拟机选择以下使用选项之一:

      • 如果您的作业可以承受抢占,并且您想要使用折扣价的 Spot 虚拟机,请选择 Spot

      • 否则,如需使用按需付费型虚拟机,请选择标准(默认)。

    3. 为此作业选择位置

      1. 区域字段中,选择一个区域。

      2. 可用区字段中,执行以下操作之一:

        • 如果您希望将此作业限制为仅在特定可用区中运行,请选择一个可用区。

        • 否则,请选择任意(默认)。

    4. 为相应作业的虚拟机选择 GPU 机器类型:

      1. 在机器系列选项中,点击 GPU

      2. GPU 类型字段中,选择 GPU 类型。

        如果您选择了 N1 虚拟机的 GPU 类型之一,则系列字段会设置为 N1

      3. GPU 数量字段中,为每个虚拟机选择 GPU 数量。

      4. 机器类型字段中,选择机器类型。

      5. 如需自动安装 GPU 驱动程序,请选择 GPU 驱动程序安装(默认)。

    5. 配置每项任务所需的虚拟机资源量:

      1. 核心数字段中,输入每个任务的 vCPUs 数量。

        例如,输入 1(默认值)。

      2. 内存字段中,输入每个任务的 RAM 量(以 GB 为单位)。

        例如,输入 0.5(默认值)。

    6. 点击完成

  5. 可选:配置此作业的其他字段

  6. 可选:如需查看作业配置,请在左侧窗格中点击预览

  7. 点击创建

    作业详情页面会显示您创建的作业。

gcloud

  1. 创建一个 JSON 文件,该文件用于安装 GPU 驱动程序、定义 accelerators[] 字段的 typecount 子字段,并在具有 GPU 机器类型的位置运行。

    例如,如需创建使用 GPU 的 N1 虚拟机的基本脚本作业,并让 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 类型所需的驱动程序,并代表您将其安装。如果您将此字段设置为 false(默认值),则需要手动安装 GPU 驱动程序才能使用任何 GPU 来运行此作业。

    • PROVISIONING_MODEL消费选项的预配模型:STANDARD 表示按需,SPOT 表示 Spot 虚拟机。

    • GPU_TYPEGPU 类型。您可以使用 gcloud compute accelerator-types list 命令查看可用 GPU 类型的列表。仅将此字段用于 N1 虚拟机的 GPU。

    • GPU_COUNT:指定类型的 GPU 数量。如需详细了解有效选项,请参阅 N1 机器系列的 GPU 机器类型。仅将此字段用于 N1 虚拟机的 GPU。

    • ALLOWED_LOCATIONS:您可以选择使用 allowedLocations[] 字段来指定作业的虚拟机允许运行的区域或区域中的特定可用区,例如,regions/us-central1 允许在 us-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

jobs.create 方法发出 POST 请求,该请求会安装 GPU 驱动程序,定义 accelerators[] 字段的 typecount 子字段,并使用具有 GPU 机器类型的位置。

例如,如需创建使用 GPU 的 N1 虚拟机并让 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 类型所需的驱动程序,并代表您安装这些驱动程序。如果您将此字段设置为 false(默认值),则需要手动安装 GPU 驱动程序才能使用任何 GPU 来运行此作业。

  • PROVISIONING_MODEL消费选项的预配模型:STANDARD 表示按需,SPOT 表示 Spot 虚拟机。

  • GPU_TYPEGPU 类型。您可以使用 gcloud compute accelerator-types list 命令查看可用 GPU 类型的列表。仅将此字段用于 N1 虚拟机的 GPU。

  • GPU_COUNT:指定类型的 GPU 数量。如需详细了解有效选项,请参阅 N1 机器系列的 GPU 机器类型。 仅将此字段用于 N1 虚拟机的 GPU。

  • ALLOWED_LOCATIONS:您可以选择使用 allowedLocations[] 字段来指定作业的虚拟机允许运行的区域或区域中的特定可用区,例如,regions/us-central1 允许在 us-central1 区域中的所有可用区运行。 请务必指定提供您希望用于此作业的 GPU 机器类型的位置。否则,如果您省略此字段,请确保作业的位置提供 GPU 机器类型。

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)

后续步骤