创建和运行使用 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. 定义兼容的虚拟机资源

第 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 的可用消耗选项及其作业要求。下表根据用例列出了消耗选项:从大致最高到最低的可获取性。确保您选择的使用选项也符合您对价格、运行时和机器类型支持的要求。如需详细了解如何选择使用选项,另请参阅提高资源可获取性、Compute Engine 预配模型文档和 AI Hypercomputer 使用选项文档。

使用选项及其作业要求

预留

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

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

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

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

日历模式预留

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

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

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

Batch 会将日历模式预留用于执行以下所有操作的作业:

灵活启动型虚拟机

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

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

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

    如需详细了解灵活启动型虚拟机,请参阅 Compute Engine 文档。

对于执行以下所有操作的作业,Batch 会使用灵活启动型虚拟机:

按需

  • 应用场景:按需模式快速且易于尝试使用,因此它是大多数作业的默认消耗选项。1但是,如果其他消耗选项更符合您的优先事项,或者您反复遇到资源可获取性问题,我们不建议您使用按需模式。

  • 详细信息:按需通常是访问 Compute Engine 虚拟机的默认方式。按需预留可让您在请求时访问资源(如果可用)。在作业完成或达到运行时长限制之前,系统不会删除这些资源。

默认情况下,Batch 会对大多数作业使用按需模式。如果您想确保作业使用按需价格,请执行以下所有操作:1

  • 将 provisioningModel 字段设置为 STANDARD。
  • 阻止使用预留。如需防止作业自动使用兼容的预留,请将 reservation 字段设置为 NO_RESERVATION。如需了解详情,请参阅创建和运行无法使用预留虚拟机的作业。

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

Spot 虚拟机

  • 用例:我们建议您使用 Spot 虚拟机来降低容错型工作负载的费用。

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

    详细了解 Spot 虚拟机和针对使用 Spot 虚拟机的作业的建议。

Batch 会将 Spot 虚拟机用于执行以下所有操作的作业:

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

第 2 步:安装 GPU 驱动程序

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

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

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

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

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

    如需了解哪些位置提供 GPU 机器类型,请参阅 Compute Engine 文档中的 GPU 位置。

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

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

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

创建使用 GPU 的作业

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

使用选项 作业说明示例
预留或日历模式预留

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

灵活启动型虚拟机

使用 GPU 和灵活启动型虚拟机

按需虚拟机或 Spot 虚拟机

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

使用 GPU 和灵活启动型虚拟机

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

gcloud

  1. 创建一个 JSON 文件,用于安装 GPU 驱动程序、指定支持灵活启动型虚拟机的 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":"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:支持灵活启动型虚拟机的 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 驱动程序、指定支持灵活启动型虚拟机的 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":"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:支持灵活启动型虚拟机的 GPU 机器类型。如需了解详情,请参阅 Compute Engine 文档中的按机器类型划分的使用选项可用性。

  • ALLOWED_LOCATIONS:作业的允许位置。请使用以下任一选项,确保作业的 Compute Engine 资源所在的位置提供您希望用于此作业的 GPU 机器类型:

    • 默认情况下,如果您省略 allowedLocations[] 字段,则作业会在作业位置 (LOCATION) 区域中创建的 Compute Engine 资源上运行。
    • (可选)如果您添加 allowedLocations[] 字段,则作业只能在指定位置创建的 Compute Engine 资源上运行。

为加速器优化型虚拟机使用 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:是否自动安装 GPU 驱动程序。如果设置为 true,Batch 会从第三方位置提取您在 policy 字段中指定的 GPU 类型所需的驱动程序,并代表您安装这些驱动程序。如果您将此字段设置为 false(默认),则需要手动安装 GPU 驱动程序,才能为此作业使用任何 GPU。

    • PROVISIONING_MODEL:用量选项的预配模型:STANDARD(按需)或 SPOT(Spot 虚拟机)。

    • 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 的基本脚本作业,请发出以下请求:

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 虚拟机)。

  • 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)

将 GPU 用于 N1 虚拟机

您可以使用 Google Cloud 控制台、gcloud CLI、Batch API、Java、Node.js 或 Python 创建为 N1 虚拟机使用 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. 在可用区字段中,执行以下操作之一:

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

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

    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[] 字段的 type 和 count 子字段,并在具有 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:是否自动安装 GPU 驱动程序。如果设置为 true,Batch 会从第三方位置提取您在 policy 字段中指定的 GPU 类型所需的驱动程序,并代表您安装这些驱动程序。如果您将此字段设置为 false(默认),则需要手动安装 GPU 驱动程序,才能为此作业使用任何 GPU。

    • PROVISIONING_MODEL:用量选项的预配模型:STANDARD(按需)或 SPOT(Spot 虚拟机)。

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

    • GPU_COUNT:指定类型的 GPU 数量。如需详细了解有效选项,请参阅 N1 机器系列的 GPU 机器类型。此字段仅适用于 N1 虚拟机的 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 虚拟机的 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 虚拟机)。

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

  • GPU_COUNT:指定类型的 GPU 数量。如需详细了解有效选项,请参阅 N1 机器系列的 GPU 机器类型。此字段仅适用于 N1 虚拟机的 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)

后续步骤