Membuat dan menjalankan tugas yang menggunakan GPU

Dokumen ini menjelaskan cara membuat dan menjalankan tugas yang menggunakan unit pemrosesan grafis (GPU). Untuk mempelajari lebih lanjut fitur dan batasan GPU, lihat Tentang GPU dalam dokumentasi Compute Engine.

Saat membuat tugas Batch, Anda dapat menggunakan GPU secara opsional untuk mempercepat workload tertentu. Kasus penggunaan umum untuk tugas yang menggunakan GPU mencakup pemrosesan data intensif dan workload kecerdasan buatan (AI) seperti machine learning (ML).

Sebelum memulai

  1. Jika belum pernah menggunakan Batch, baca Mulai menggunakan Batch dan aktifkan Batch dengan menyelesaikan prasyarat untuk project dan pengguna.
  2. Untuk mendapatkan izin yang Anda perlukan untuk membuat tugas, minta administrator Anda untuk memberi Anda peran IAM berikut:

    Untuk mengetahui informasi selengkapnya tentang cara memberikan peran, lihat Mengelola akses ke project, folder, dan organisasi.

    Anda mungkin juga bisa mendapatkan izin yang diperlukan melalui peran khusus atau peran bawaan lainnya.

Membuat tugas yang menggunakan GPU

Untuk membuat tugas yang menggunakan GPU, lakukan hal berikut:

  1. Rencanakan persyaratan untuk tugas yang menggunakan GPU.
  2. Buat tugas dengan persyaratan dan metode yang telah Anda identifikasi. Untuk contoh cara membuat tugas menggunakan opsi yang direkomendasikan, lihat Membuat contoh tugas yang menggunakan GPU dalam dokumen ini.

Merencanakan persyaratan untuk tugas yang menggunakan GPU

Sebelum membuat tugas yang menggunakan GPU, rencanakan persyaratan tugas seperti yang dijelaskan di bagian berikut:

  1. Pilih jenis mesin GPU dan metode penyediaan
  2. Instal driver GPU.
  3. Tentukan resource VM yang kompatibel

Langkah 1: Pilih jenis mesin GPU dan metode penyediaan

Persyaratan tugas bervariasi berdasarkan jenis mesin GPU dan metode penyediaan yang Anda pilih, dan opsi untuk setiap persyaratan mungkin saling bergantung. Berdasarkan persyaratan dan prioritas Anda, Anda dapat memilih jenis mesin GPU terlebih dahulu atau memilih metode penyediaan terlebih dahulu. Secara umum, jenis mesin GPU terutama memengaruhi performa dan harga dasar, dan metode penyediaan terutama memengaruhi ketersediaan resource dan biaya atau diskon tambahan.

Pilih jenis mesin GPU

Jenis mesin GPU yang tersedia (kombinasi valid dari jenis GPU, jumlah GPU, dan jenis mesin (vCPU dan memori)) serta kasus penggunaannya tercantum di halaman Jenis mesin GPU dalam dokumentasi Compute Engine.

Kolom yang diperlukan agar tugas dapat menentukan jenis mesin GPU bervariasi berdasarkan kategori dalam tabel berikut:

Jenis mesin GPU dan persyaratan tugasnya

GPU untuk VM yang dioptimalkan akselerator: VM dengan jenis mesin dari kelompok mesin yang dioptimalkan akselerator memiliki jenis dan jumlah GPU ini yang terpasang secara otomatis.

Untuk menggunakan GPU untuk VM yang dioptimalkan akselerator, sebaiknya tentukan jenis mesin. Setiap jenis mesin yang dioptimalkan akselerator hanya mendukung jenis dan jumlah GPU tertentu, sehingga secara fungsional setara, baik Anda menentukan nilai tersebut maupun tidak, selain jenis mesin yang dioptimalkan akselerator.

Secara khusus, Batch juga mendukung penentuan hanya jenis dan jumlah GPU untuk VM yang dioptimalkan akselerator, tetapi opsi vCPU dan memori yang dihasilkan sering kali sangat terbatas. Oleh karena itu, sebaiknya Anda memverifikasi bahwa opsi memori dan vCPU yang tersedia kompatibel dengan persyaratan tugas pekerjaan.

GPU untuk VM N1: GPU ini mengharuskan Anda menentukan jenis dan jumlah yang akan dipasang ke setiap VM dan harus dipasang ke VM dengan jenis mesin dari seri mesin N1.

Untuk menggunakan GPU bagi VM N1, sebaiknya tentukan setidaknya jenis GPU dan jumlah GPU. Pastikan kombinasi nilai cocok dengan salah satu opsi GPU yang valid untuk jenis mesin N1. Opsi vCPU dan memori untuk VM N1 yang menggunakan jenis dan jumlah GPU tertentu cukup fleksibel. Kecuali jika Anda membuat tugas menggunakan konsol Google Cloud , Anda dapat membiarkan Batch memilih jenis mesin secara otomatis yang memenuhi persyaratan tugas.

Pilih metode penyediaan

Batch menggunakan metode yang berbeda untuk menyediakan resource VM bagi tugas yang menggunakan GPU berdasarkan jenis resource yang diminta tugas Anda. Metode penyediaan yang tersedia dan persyaratannya dijelaskan dalam tabel berikut, yang mencantumkannya berdasarkan kasus penggunaannya: dari ketersediaan resource tertinggi hingga terendah.

Singkatnya, sebaiknya sebagian besar pengguna melakukan hal berikut:

  • Jika Anda ingin menggunakan jenis mesin GPU A3 tanpa reservasi, gunakan Dynamic Workload Scheduler for Batch (Pratinjau).

  • Untuk semua jenis mesin GPU lainnya, gunakan metode penyediaan default. Metode penyediaan default biasanya adalah on-demand; pengecualiannya adalah jika project Anda memiliki reservasi yang tidak digunakan yang dapat digunakan tugas secara otomatis.

Metode penyediaan dan persyaratan tugasnya

Pemesanan

  • Kasus penggunaan: Sebaiknya gunakan reservasi untuk tugas jika Anda menginginkan tingkat jaminan yang sangat tinggi atas ketersediaan resource atau jika Anda sudah memiliki reservasi yang mungkin tidak digunakan.

  • Detail: Pemesanan menimbulkan biaya VM yang ditentukan dengan harga yang sama seperti menjalankan VM hingga Anda menghapus pemesanan. VM yang menggunakan reservasi tidak dikenai biaya terpisah, tetapi reservasi dikenai biaya terlepas dari penggunaan.

Batch menggunakan reservasi untuk tugas yang dapat menggunakan reservasi yang tidak digunakan. Untuk mengetahui informasi selengkapnya tentang pemesanan dan persyaratannya, lihat halaman Memastikan ketersediaan resource menggunakan reservasi VM.

Dynamic Workload Scheduler untuk Batch (Pratinjau)

  • Kasus penggunaan: Sebaiknya gunakan Dynamic Workload Scheduler jika Anda ingin menggunakan GPU untuk VM dengan jenis mesin dari seri mesin A3 tanpa menggunakan reservasi.

  • Detail: Dynamic Workload Scheduler dapat mempermudah Anda mengakses banyak resource secara bersamaan yang mempercepat workload AI dan ML. Misalnya, Dynamic Workload Scheduler dapat membantu penjadwalan tugas dengan mengurangi penundaan atau masalah yang disebabkan oleh ketersediaan resource.

Batch menggunakan Dynamic Workload Scheduler untuk tugas yang melakukan semua hal berikut:

  • Tentukan jenis mesin GPU A3.
  • Blokir reservasi. Secara khusus, tugas harus menetapkan kolom reservation ke NO_RESERVATION. Untuk mengetahui informasi selengkapnya, lihat Membuat dan menjalankan tugas yang tidak dapat menggunakan VM yang dipesan.
  • Jangan gunakan Spot VM. Secara khusus, tugas dapat menghapus kolom provisioningModel atau menetapkan kolom provisioningModel ke STANDARD.

Sesuai permintaan

  • Kasus penggunaan: Sebaiknya gunakan on-demand untuk semua tugas lainnya.

  • Detail: Sesuai permintaan biasanya merupakan cara default untuk mengakses VM Compute Engine. On-demand memungkinkan Anda meminta dan (jika tersedia) langsung mengakses resource satu VM dalam satu waktu.

Batch menggunakan on-demand untuk semua tugas lainnya.

Spot VM

  • Kasus penggunaan: Sebaiknya coba gunakan Spot VM untuk mengurangi biaya workload fault-tolerant.

  • Detail: Spot VM memberikan diskon yang signifikan, tetapi mungkin tidak selalu tersedia dan dapat di-preempt kapan saja. Untuk informasi selengkapnya, lihat Spot VM dalam dokumentasi Compute Engine.

Batch menggunakan Spot VM untuk tugas yang menetapkan kolom provisioningModel ke SPOT.

Langkah 2: Instal driver GPU

Untuk menggunakan GPU dalam tugas, Anda harus menginstal driver GPU. Untuk menginstal driver GPU, pilih salah satu metode berikut:

  • Instal driver GPU secara otomatis (direkomendasikan jika memungkinkan): Seperti yang ditunjukkan dalam contoh, agar Batch mengambil driver GPU yang diperlukan dari lokasi pihak ketiga dan menginstalnya atas nama Anda, tetapkan kolom installGpuDrivers untuk tugas ke true. Metode ini direkomendasikan jika tugas Anda tidak mengharuskan Anda menginstal driver secara manual.

    Secara opsional, jika Anda perlu menentukan versi driver GPU yang diinstal Batch, tetapkan juga kolom driverVersion.

  • Instal driver GPU secara manual: Metode ini diperlukan jika salah satu kondisi berikut terpenuhi:

    • Tugas menggunakan script dan container yang dapat dijalankan, serta tidak memiliki akses internet. Untuk mengetahui informasi selengkapnya tentang akses yang dimiliki tugas, lihat Ringkasan jaringan batch.
    • Tugas menggunakan image VM kustom. Untuk mempelajari lebih lanjut image OS VM dan image OS VM yang dapat Anda gunakan, lihat Ringkasan lingkungan OS VM.

    Untuk menginstal driver GPU yang diperlukan secara manual, metode berikut direkomendasikan:

    1. Buat image VM kustom yang menyertakan driver GPU.

      1. Untuk menginstal driver GPU, jalankan skrip penginstalan berdasarkan OS yang ingin Anda gunakan:

      2. Jika tugas Anda memiliki runnable container dan tidak menggunakan Container-Optimized OS, Anda juga harus menginstal NVIDIA Container Toolkit

    2. Saat Anda membuat dan mengirimkan tugas yang menggunakan GPU, tentukan image VM kustom yang menyertakan driver GPU, dan tetapkan kolom installGpuDrivers untuk tugas ke false (default).

Langkah 3: Tentukan resource VM yang kompatibel

Untuk mempelajari persyaratan dan opsi dalam menentukan resource VM untuk tugas, lihat Resource tugas.

Singkatnya, Anda harus melakukan semua hal berikut saat menentukan resource VM untuk tugas yang menggunakan GPU:

  • Pastikan jenis mesin GPU tersedia di lokasi VM tugas Anda.

    Untuk mempelajari tempat jenis mesin GPU tersedia, lihat Ketersediaan GPU menurut region dan zona dalam dokumentasi Compute Engine.

  • Jika Anda menentukan jenis mesin tugas, pastikan jenis mesin tersebut memiliki vCPU dan memori yang cukup untuk persyaratan tugas. Jenis mesin tugas harus ditentukan setiap kali Anda membuat tugas menggunakan konsol Google Cloud dan direkomendasikan setiap kali Anda membuat tugas yang menggunakan GPU untuk VM yang dioptimalkan untuk akselerator.

  • Pastikan Anda menentukan resource VM untuk tugas menggunakan metode yang valid:

    • Tentukan resource VM secara langsung menggunakan kolom instances[].policy (direkomendasikan jika memungkinkan). Metode ini ditunjukkan dalam contoh.
    • Tentukan resource VM melalui template menggunakan kolom instances[].instanceTemplate. Metode ini diperlukan untuk menginstal driver GPU secara manual melalui image kustom. Untuk mengetahui informasi selengkapnya, lihat Menentukan resource tugas menggunakan template instance VM.

Buat contoh tugas yang menggunakan GPU

Bagian berikut menjelaskan cara membuat contoh tugas untuk setiap jenis mesin GPU menggunakan opsi yang direkomendasikan. Secara khusus, semua contoh tugas menginstal driver GPU secara otomatis, semuanya menentukan resource VM secara langsung, dan menentukan metode penyediaan atau menggunakan metode penyediaan default.

Menggunakan GPU untuk VM A3 melalui Dynamic Workload Scheduler for Batch (Pratinjau)

Anda dapat membuat tugas yang menggunakan GPU untuk VM A3 melalui Dynamic Workload Scheduler menggunakan gcloud CLI atau Batch API.

gcloud

  1. Buat file JSON yang menginstal driver GPU, menentukan jenis mesin dari seri mesin A3, memblokir reservasi, dan berjalan di lokasi yang memiliki jenis mesin GPU.

    Misalnya, untuk membuat tugas skrip dasar yang menggunakan GPU untuk VM A3 melalui Dynamic Workload Scheduler, buat file JSON dengan konten berikut:

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

    Ganti kode berikut:

    • INSTALL_GPU_DRIVERS: Jika disetel ke true, Batch akan mengambil driver yang diperlukan untuk jenis GPU yang Anda tentukan di kolom policy dari lokasi pihak ketiga, dan Batch akan menginstalnya untuk Anda. Jika Anda menyetel kolom ini ke false (default), Anda harus menginstal driver GPU secara manual untuk menggunakan GPU apa pun untuk tugas ini.

    • MACHINE_TYPE: jenis mesin dari seri mesin A3.

    • ALLOWED_LOCATIONS: Anda dapat secara opsional menggunakan kolom allowedLocations[] untuk menentukan region atau zona tertentu dalam region tempat VM untuk tugas Anda diizinkan berjalan—misalnya, regions/us-central1 mengizinkan semua zona di region us-central1. Pastikan Anda menentukan lokasi yang menawarkan jenis mesin GPU yang Anda inginkan untuk tugas ini. Jika tidak, jika Anda menghapus kolom ini, pastikan lokasi tugas menawarkan jenis mesin GPU.

  2. Untuk membuat dan menjalankan tugas, gunakan perintah gcloud batch jobs submit:

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

    Ganti kode berikut:

    • JOB_NAME: nama tugas.

    • LOCATION: lokasi tugas.

    • JSON_CONFIGURATION_FILE: jalur untuk file JSON dengan detail konfigurasi tugas.

API

Buat permintaan POST ke metode jobs.create yang menginstal driver GPU, menentukan jenis mesin dari seri mesin A3, memblokir reservasi, dan berjalan di lokasi yang memiliki jenis mesin GPU.

Misalnya, untuk membuat tugas skrip dasar yang menggunakan GPU untuk VM A3 melalui Dynamic Workload Scheduler, buat permintaan berikut:

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": {
                    "machineType": "MACHINE_TYPE",
                    "reservation": "NO_RESERVATION"
                }
            }
        ],
        "location": {
            "allowedLocations": [
                "ALLOWED_LOCATIONS"
            ]
        }
    },
    "logsPolicy": {
        "destination": "CLOUD_LOGGING"
    }
}

Ganti kode berikut:

  • PROJECT_ID: Project ID project Anda.

  • LOCATION: lokasi tugas.

  • JOB_NAME: nama tugas.

  • INSTALL_GPU_DRIVERS: Jika disetel ke true, Batch akan mengambil driver yang diperlukan untuk jenis GPU yang Anda tentukan di kolom policy dari lokasi pihak ketiga, dan Batch akan menginstalnya untuk Anda. Jika Anda menyetel kolom ini ke false (default), Anda harus menginstal driver GPU secara manual untuk menggunakan GPU apa pun untuk tugas ini.

  • MACHINE_TYPE: jenis mesin dari seri mesin A3.

  • ALLOWED_LOCATIONS: Anda dapat secara opsional menggunakan kolom allowedLocations[] untuk menentukan region atau zona tertentu dalam region tempat VM untuk tugas Anda diizinkan berjalan—misalnya, regions/us-central1 mengizinkan semua zona di region us-central1. Pastikan Anda menentukan lokasi yang menawarkan jenis mesin GPU yang Anda inginkan untuk tugas ini. Jika tidak, jika Anda menghapus kolom ini, pastikan lokasi tugas menawarkan jenis mesin GPU.

Menggunakan GPU untuk VM yang dioptimalkan akselerator

Anda dapat membuat tugas yang menggunakan GPU untuk VM yang dioptimalkan akselerator menggunakan Google Cloud konsol, gcloud CLI, Batch API, Java, Node.js, atau Python.

Konsol

Untuk membuat tugas yang menggunakan GPU menggunakan konsol Google Cloud , lakukan hal berikut:

  1. Di konsol Google Cloud , buka halaman Job list.

    Buka Daftar tugas

  2. Klik Create. Halaman Create batch job akan terbuka. Di panel kiri, halaman Job details dipilih.

  3. Konfigurasi halaman Detail pekerjaan:

    1. Opsional: Di kolom Nama tugas, sesuaikan nama tugas.

      Misalnya, masukkan example-gpu-job.

    2. Konfigurasi bagian Detail tugas:

      1. Di jendela Dapat dijalankan baru, tambahkan setidaknya satu skrip atau penampung agar tugas ini dapat dijalankan.

        Misalnya, untuk membuat tugas skrip dasar, lakukan hal berikut:

        1. Centang kotak Script. Kolom akan muncul.

        2. Di kolom, masukkan skrip berikut:

          echo Hello world from task ${BATCH_TASK_INDEX}.
          
        3. Klik Selesai.

      2. Di kolom Jumlah tugas, masukkan jumlah tugas untuk tugas ini.

        Misalnya, masukkan 3.

      3. Opsional: Di kolom Paralelisme, masukkan jumlah tugas yang akan dijalankan secara bersamaan.

        Misalnya, masukkan 1 (default).

  4. Konfigurasi halaman Spesifikasi resource:

    1. Di panel kiri, klik Spesifikasi resource. Halaman Spesifikasi resource akan terbuka.

    2. Opsional: Di bagian VM provisioning model, pilih salah satu opsi berikut untuk provisioning model bagi VM tugas ini:

      • Jika tugas Anda dapat menahan preemption dan Anda menginginkan VM yang didiskon, pilih Spot.

      • Jika tidak, pilih Standar (default).

    3. Pilih lokasi untuk tugas ini.

      1. Di kolom Region, pilih region.

      2. Di kolom Zone, lakukan salah satu hal berikut:

        • Jika Anda ingin membatasi tugas ini agar hanya berjalan di zona tertentu, pilih zona.

        • Jika tidak, pilih apa saja (default).

    4. Pilih jenis mesin GPU untuk VM tugas ini:

      1. Di opsi kelompok mesin, klik GPU.

      2. Di kolom GPU type, pilih jenis GPU. Kemudian, di kolom Number of GPUs, pilih jumlah GPU untuk setiap VM.

        Jika Anda memilih salah satu jenis GPU untuk VM yang dioptimalkan akselerator, kolom Jenis mesin hanya mengizinkan satu opsi untuk jenis mesin berdasarkan jenis dan jumlah GPU yang Anda pilih.

      3. Untuk menginstal driver GPU secara otomatis, pilih GPU driver installation (default).

    5. Konfigurasi jumlah resource VM yang diperlukan untuk setiap tugas:

      1. Di kolom Cores, masukkan jumlah vCPUs per tugas.

        Misalnya, masukkan 1 (default).

      2. Di kolom Memory, masukkan jumlah RAM dalam GB per tugas.

        Misalnya, masukkan 0.5 (default).

    6. Klik Selesai.

  5. Opsional: Konfigurasi kolom lain untuk tugas ini.

  6. Opsional: Untuk meninjau konfigurasi tugas, di panel kiri, klik Pratinjau.

  7. Klik Buat.

    Halaman Job details menampilkan tugas yang Anda buat.

gcloud

  1. Buat file JSON yang menginstal driver GPU, menentukan jenis mesin dari kelompok mesin yang dioptimalkan akselerator, dan berjalan di lokasi yang memiliki jenis mesin GPU.

    Misalnya, untuk membuat tugas skrip dasar yang menggunakan GPU untuk VM yang dioptimalkan untuk akselerator, buat file JSON dengan konten berikut:

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

    Ganti kode berikut:

    • INSTALL_GPU_DRIVERS: Jika disetel ke true, Batch akan mengambil driver yang diperlukan untuk jenis GPU yang Anda tentukan di kolom policy dari lokasi pihak ketiga, dan Batch akan menginstalnya untuk Anda. Jika Anda menyetel kolom ini ke false (default), Anda harus menginstal driver GPU secara manual untuk menggunakan GPU apa pun untuk tugas ini.

    • MACHINE_TYPE: jenis mesin dari kelompok mesin yang dioptimalkan akselerator.

    • ALLOWED_LOCATIONS: Anda dapat secara opsional menggunakan kolom allowedLocations[] untuk menentukan region atau zona tertentu dalam region tempat VM untuk tugas Anda diizinkan berjalan—misalnya, regions/us-central1 mengizinkan semua zona di region us-central1. Pastikan Anda menentukan lokasi yang menawarkan jenis mesin GPU yang Anda inginkan untuk tugas ini. Jika tidak, jika Anda menghapus kolom ini, pastikan lokasi tugas menawarkan jenis mesin GPU.

  2. Untuk membuat dan menjalankan tugas, gunakan perintah gcloud batch jobs submit:

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

    Ganti kode berikut:

    • JOB_NAME: nama tugas.

    • LOCATION: lokasi tugas.

    • JSON_CONFIGURATION_FILE: jalur untuk file JSON dengan detail konfigurasi tugas.

API

Buat permintaan POST ke metode jobs.create yang menginstal driver GPU, menentukan jenis mesin dari kelompok mesin yang dioptimalkan akselerator, dan berjalan di lokasi yang memiliki jenis mesin GPU.

Misalnya, untuk membuat tugas skrip dasar yang menggunakan GPU untuk VM yang dioptimalkan untuk akselerator, buat permintaan berikut:

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": {
                    "machineType": "MACHINE_TYPE"
                }
            }
        ],
        "location": {
            "allowedLocations": [
                "ALLOWED_LOCATIONS"
            ]
        }
    },
    "logsPolicy": {
        "destination": "CLOUD_LOGGING"
    }
}

Ganti kode berikut:

  • PROJECT_ID: Project ID project Anda.

  • LOCATION: lokasi tugas.

  • JOB_NAME: nama tugas.

  • INSTALL_GPU_DRIVERS: Jika disetel ke true, Batch akan mengambil driver yang diperlukan untuk jenis GPU yang Anda tentukan di kolom policy dari lokasi pihak ketiga, dan Batch akan menginstalnya untuk Anda. Jika Anda menyetel kolom ini ke false (default), Anda harus menginstal driver GPU secara manual untuk menggunakan GPU apa pun untuk tugas ini.

  • MACHINE_TYPE: jenis mesin dari kelompok mesin yang dioptimalkan akselerator.

  • ALLOWED_LOCATIONS: Anda dapat secara opsional menggunakan kolom allowedLocations[] untuk menentukan region atau zona tertentu dalam region tempat VM untuk tugas Anda diizinkan berjalan—misalnya, regions/us-central1 mengizinkan semua zona di region us-central1. Pastikan Anda menentukan lokasi yang menawarkan jenis mesin GPU yang Anda inginkan untuk tugas ini. Jika tidak, jika Anda menghapus kolom ini, pastikan lokasi tugas menawarkan jenis mesin 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)

Menggunakan GPU untuk VM N1

Anda dapat membuat tugas yang menggunakan GPU untuk VM N1 menggunakan Google Cloud konsol, gcloud CLI, Batch API, Java, Node.js, atau Python.

Konsol

Untuk membuat tugas yang menggunakan GPU menggunakan konsol Google Cloud , lakukan hal berikut:

  1. Di konsol Google Cloud , buka halaman Job list.

    Buka Daftar tugas

  2. Klik Create. Halaman Create batch job akan terbuka. Di panel kiri, halaman Job details dipilih.

  3. Konfigurasi halaman Detail pekerjaan:

    1. Opsional: Di kolom Nama tugas, sesuaikan nama tugas.

      Misalnya, masukkan example-gpu-job.

    2. Konfigurasi bagian Detail tugas:

      1. Di jendela Dapat dijalankan baru, tambahkan setidaknya satu skrip atau penampung agar tugas ini dapat dijalankan.

        Misalnya, untuk membuat tugas skrip dasar, lakukan hal berikut:

        1. Centang kotak Script. Kolom akan muncul.

        2. Di kolom, masukkan skrip berikut:

          echo Hello world from task ${BATCH_TASK_INDEX}.
          
        3. Klik Selesai.

      2. Di kolom Jumlah tugas, masukkan jumlah tugas untuk tugas ini.

        Misalnya, masukkan 3.

      3. Opsional: Di kolom Paralelisme, masukkan jumlah tugas yang akan dijalankan secara bersamaan.

        Misalnya, masukkan 1 (default).

  4. Konfigurasi halaman Spesifikasi resource:

    1. Di panel kiri, klik Spesifikasi resource. Halaman Spesifikasi resource akan terbuka.

    2. Opsional: Di bagian VM provisioning model, pilih salah satu opsi berikut untuk provisioning model bagi VM tugas ini:

      • Jika tugas Anda dapat menahan preemption dan Anda menginginkan VM yang didiskon, pilih Spot.

      • Jika tidak, pilih Standar (default).

    3. Pilih lokasi untuk tugas ini.

      1. Di kolom Region, pilih region.

      2. Di kolom Zone, lakukan salah satu hal berikut:

        • Jika Anda ingin membatasi tugas ini agar hanya berjalan di zona tertentu, pilih zona.

        • Jika tidak, pilih apa saja (default).

    4. Pilih jenis mesin GPU untuk VM tugas ini:

      1. Di opsi kelompok mesin, klik GPU.

      2. Di kolom GPU type, pilih jenis GPU.

        Jika Anda memilih salah satu jenis GPU untuk VM N1, kolom Seri akan disetel ke N1.

      3. Di kolom Number of GPUs, pilih jumlah GPU untuk setiap VM.

      4. Di kolom Machine type, pilih jenis mesin.

      5. Untuk menginstal driver GPU secara otomatis, pilih GPU driver installation (default).

    5. Konfigurasi jumlah resource VM yang diperlukan untuk setiap tugas:

      1. Di kolom Cores, masukkan jumlah vCPUs per tugas.

        Misalnya, masukkan 1 (default).

      2. Di kolom Memory, masukkan jumlah RAM dalam GB per tugas.

        Misalnya, masukkan 0.5 (default).

    6. Klik Selesai.

  5. Opsional: Konfigurasi kolom lain untuk tugas ini.

  6. Opsional: Untuk meninjau konfigurasi tugas, di panel kiri, klik Pratinjau.

  7. Klik Buat.

    Halaman Job details menampilkan tugas yang Anda buat.

gcloud

  1. Buat file JSON yang menginstal driver GPU, menentukan sub-bidang type dan count dari bidang accelerators[], dan berjalan di lokasi yang memiliki jenis mesin GPU.

    Misalnya, untuk membuat tugas skrip dasar yang menggunakan GPU untuk VM N1 dan memungkinkan Batch memilih jenis mesin N1 yang tepat, buat file JSON dengan konten berikut:

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

    Ganti kode berikut:

    • INSTALL_GPU_DRIVERS: Jika disetel ke true, Batch akan mengambil driver yang diperlukan untuk jenis GPU yang Anda tentukan di kolom policy dari lokasi pihak ketiga, dan Batch akan menginstalnya untuk Anda. Jika Anda menyetel kolom ini ke false (default), Anda harus menginstal driver GPU secara manual untuk menggunakan GPU apa pun untuk tugas ini.

    • GPU_TYPE: jenis GPU. Anda dapat melihat daftar jenis GPU yang tersedia menggunakan perintah gcloud compute accelerator-types list. Gunakan kolom ini hanya untuk GPU untuk VM N1.

    • GPU_COUNT: jumlah GPU dari jenis yang ditentukan. Untuk mengetahui informasi selengkapnya tentang opsi yang valid, lihat Jenis mesin GPU untuk seri mesin N1. Gunakan kolom ini hanya untuk GPU untuk VM N1.

    • ALLOWED_LOCATIONS: Anda dapat secara opsional menggunakan kolom allowedLocations[] untuk menentukan region atau zona tertentu dalam region tempat VM untuk tugas Anda diizinkan berjalan—misalnya, regions/us-central1 mengizinkan semua zona di region us-central1. Pastikan Anda menentukan lokasi yang menawarkan jenis mesin GPU yang Anda inginkan untuk tugas ini. Jika tidak, jika Anda menghapus kolom ini, pastikan lokasi tugas menawarkan jenis mesin GPU.

  2. Untuk membuat dan menjalankan tugas, gunakan perintah gcloud batch jobs submit:

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

    Ganti kode berikut:

    • JOB_NAME: nama tugas.

    • LOCATION: lokasi tugas.

    • JSON_CONFIGURATION_FILE: jalur untuk file JSON dengan detail konfigurasi tugas.

API

Buat permintaan POST ke metode jobs.create yang menginstal driver GPU, menentukan subkolom type dan count dari kolom accelerators[], dan menggunakan lokasi yang memiliki jenis mesin GPU.

Misalnya, untuk membuat tugas skrip dasar yang menggunakan GPU untuk VM N1 dan memungkinkan Batch memilih jenis mesin N1 yang tepat, buat permintaan berikut:

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": {
                    "accelerators": [
                        {
                            "type": "GPU_TYPE",
                            "count": GPU_COUNT
                        }
                    ]
                }
            }
        ],
        "location": {
            "allowedLocations": [
                "ALLOWED_LOCATIONS"
            ]
        }
    },
    "logsPolicy": {
        "destination": "CLOUD_LOGGING"
    }
}

Ganti kode berikut:

  • PROJECT_ID: Project ID project Anda.

  • LOCATION: lokasi tugas.

  • JOB_NAME: nama tugas.

  • INSTALL_GPU_DRIVERS: Jika disetel ke true, Batch akan mengambil driver yang diperlukan untuk jenis GPU yang Anda tentukan di kolom policy dari lokasi pihak ketiga, dan Batch akan menginstalnya untuk Anda. Jika Anda menyetel kolom ini ke false (default), Anda harus menginstal driver GPU secara manual untuk menggunakan GPU apa pun untuk tugas ini.

  • GPU_TYPE: jenis GPU. Anda dapat melihat daftar jenis GPU yang tersedia menggunakan perintah gcloud compute accelerator-types list. Gunakan kolom ini hanya untuk GPU untuk VM N1.

  • GPU_COUNT: jumlah GPU dari jenis yang ditentukan. Untuk mengetahui informasi selengkapnya tentang opsi yang valid, lihat Jenis mesin GPU untuk seri mesin N1. Gunakan kolom ini hanya untuk GPU untuk VM N1.

  • ALLOWED_LOCATIONS: Anda dapat secara opsional menggunakan kolom allowedLocations[] untuk menentukan region atau zona tertentu dalam region tempat VM untuk tugas Anda diizinkan berjalan—misalnya, regions/us-central1 mengizinkan semua zona di region us-central1. Pastikan Anda menentukan lokasi yang menawarkan jenis mesin GPU yang Anda inginkan untuk tugas ini. Jika tidak, jika Anda menghapus kolom ini, pastikan lokasi tugas menawarkan jenis mesin 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)

Langkah berikutnya