管理排入佇列的資源

排入佇列的資源可讓您按照佇列順序要求 Cloud TPU 資源。 如果要求排入佇列的資源,該項要求就會列入 Cloud TPU 服務保有的佇列。當要求的資源可用時,系統會將其指派給您的 Google Cloud 專案,供您立即專屬使用。除非您刪除或遭到搶占,否則該 VM 會繼續指派給專案。只有 TPU Spot VM 和先占 TPU 符合搶占資格。

您可以在已加入佇列的資源要求中,指定選用的開始和結束時間。開始時間指定填入請求的最早時間。如果要求未在指定時間前完成,就會過期。要求過期後仍會保留在佇列中。

已加入佇列的資源要求可能處於下列其中一種狀態:

WAITING_FOR_RESOURCES
要求已通過初步驗證,並加入佇列。 如果沒有足夠的可用資源,系統就會維持這個狀態,直到資源充足或配置間隔結束為止,才會開始佈建要求。需求量高時,並非所有要求都能立即佈建。如要更可靠地取得 TPU,請考慮購買預訂。
PROVISIONING
系統已從佇列中選取要求,並正在分配資源。
ACTIVE
要求已分配。排入佇列的資源要求處於 ACTIVE 狀態時,您可以按照「管理 TPU」一文所述管理 TPU VM。
FAILED
要求無法完成,可能是因為要求有問題,或是所要求的資源在分配間隔內無法使用。除非明確刪除,否則要求會一直保留在佇列中。
SUSPENDING
系統正在刪除與要求相關聯的資源。
SUSPENDED
要求中指定的資源已刪除。要求處於 SUSPENDED 狀態時,就不再符合進一步分配的資格。

必要條件

執行本指南中的指令前,請先安裝 Google Cloud CLI、建立 Google Cloud 專案,並啟用 Cloud TPU API。如需操作說明,請參閱設定 Cloud TPU 環境

如果您使用 Cloud 用戶端程式庫,請按照所用語言的設定說明操作:

要求隨選排入佇列的資源

隨選資源不會遭到搶占,但隨選配額無法保證有足夠的可用 Cloud TPU 資源來滿足您的要求。如要進一步瞭解隨選資源,請參閱「配額類型」。

gcloud

gcloud compute tpus queued-resources create your-queued-resource-id \
    --node-id your-node-id \
    --project your-project-id \
    --zone us-central1-a \
    --accelerator-type v5litepod-8 \
    --runtime-version v2-alpha-tpuv5-lite

指令參數說明

queued-resource-id
使用者指派的佇列資源要求 ID。
node-id
系統分配佇列資源要求時建立的 TPU 使用者指派 ID。
project
您的 Google Cloud 專案。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本

curl

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d "{
    'tpu': {
    'node_spec': {
        'parent': 'projects/your-project-number/locations/us-central1-a',
        'node_id': 'your-node-id',
        'node': {
        'accelerator_type': 'v5litepod-8',
        'runtime_version': 'v2-alpha-tpuv5-lite',
        }
    }
    }
}" \
https://tpu.googleapis.com/v2alpha1/projects/your-project-id/locations/us-central1-a/queuedResources?queued_resource_id=your-queued-resource-id

指令參數說明

queued-resource-id
使用者指派的佇列資源要求 ID。
node-id
系統分配佇列資源要求時建立的 TPU 使用者指派 ID。
project
您的 Google Cloud 專案。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本

控制台

  1. 前往 Google Cloud 控制台的「TPUs」頁面:

    前往 TPU

  2. 按一下「建立 TPU」

  3. 在「Name」(名稱) 欄位中,輸入 TPU 的名稱。

  4. 在「Zone」(可用區) 方塊中,選取要建立 TPU 的可用區。

  5. 在「TPU type」(TPU 類型) 方塊中,選取加速器類型。加速器類型會指定要建立的 Cloud TPU 版本和大小。如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱「TPU 版本」。

  6. 在「TPU 軟體版本」方塊中,選取軟體版本。建立 Cloud TPU VM 時,TPU 軟體版本會指定要安裝的 TPU 執行階段版本。詳情請參閱「TPU 軟體版本」。

  7. 按一下「啟用佇列」切換鈕。

  8. 在「Queued resource name」(已加入佇列的資源名稱) 欄位中,輸入已加入佇列的資源要求名稱。

  9. 按一下「建立」,建立已加入佇列的資源要求。

Java

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import com.google.cloud.tpu.v2alpha1.CreateQueuedResourceRequest;
import com.google.cloud.tpu.v2alpha1.Node;
import com.google.cloud.tpu.v2alpha1.QueuedResource;
import com.google.cloud.tpu.v2alpha1.TpuClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateQueuedResource {
  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 create a node.
    String projectId = "YOUR_PROJECT_ID";
    // The zone in which to create the TPU.
    // For more information about supported TPU types for specific zones,
    // see https://cloud.google.com/tpu/docs/regions-zones
    String zone = "us-central1-a";
    // The name for your TPU.
    String nodeName = "YOUR_NODE_ID";
    // The accelerator type that specifies the version and size of the Cloud TPU you want to create.
    // For more information about supported accelerator types for each TPU version,
    // see https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#versions.
    String tpuType = "v5litepod-4";
    // Software version that specifies the version of the TPU runtime to install.
    // For more information see https://cloud.google.com/tpu/docs/runtimes
    String tpuSoftwareVersion = "v2-tpuv5-litepod";
    // The name for your Queued Resource.
    String queuedResourceId = "QUEUED_RESOURCE_ID";

    createQueuedResource(
        projectId, zone, queuedResourceId, nodeName, tpuType, tpuSoftwareVersion);
  }

  // Creates a Queued Resource
  public static QueuedResource createQueuedResource(String projectId, String zone,
      String queuedResourceId, String nodeName, String tpuType, String tpuSoftwareVersion)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    String resource = String.format("projects/%s/locations/%s/queuedResources/%s",
            projectId, zone, queuedResourceId);
    // 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 (TpuClient tpuClient = TpuClient.create()) {
      String parent = String.format("projects/%s/locations/%s", projectId, zone);
      Node node =
          Node.newBuilder()
              .setName(nodeName)
              .setAcceleratorType(tpuType)
              .setRuntimeVersion(tpuSoftwareVersion)
              .setQueuedResource(resource)
              .build();

      QueuedResource queuedResource =
          QueuedResource.newBuilder()
              .setName(queuedResourceId)
              .setTpu(
                  QueuedResource.Tpu.newBuilder()
                      .addNodeSpec(
                          QueuedResource.Tpu.NodeSpec.newBuilder()
                              .setParent(parent)
                              .setNode(node)
                              .setNodeId(nodeName)
                              .build())
                      .build())
              .build();

      CreateQueuedResourceRequest request =
          CreateQueuedResourceRequest.newBuilder()
              .setParent(parent)
              .setQueuedResourceId(queuedResourceId)
              .setQueuedResource(queuedResource)
              .build();

      return tpuClient.createQueuedResourceAsync(request).get(1, TimeUnit.MINUTES);
    }
  }
}

Python

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import tpu_v2alpha1

# TODO(developer): Update and un-comment below lines
# project_id = "your-project-id"
# zone = "us-central1-a"
# tpu_name = "tpu-name"
# tpu_type = "v5litepod-4"
# runtime_version = "v2-tpuv5-litepod"
# queued_resource_name = "resource-name"

node = tpu_v2alpha1.Node()
node.accelerator_type = tpu_type
# To see available runtime version use command:
# gcloud compute tpus versions list --zone={ZONE}
node.runtime_version = runtime_version

node_spec = tpu_v2alpha1.QueuedResource.Tpu.NodeSpec()
node_spec.parent = f"projects/{project_id}/locations/{zone}"
node_spec.node_id = tpu_name
node_spec.node = node

resource = tpu_v2alpha1.QueuedResource()
resource.tpu = tpu_v2alpha1.QueuedResource.Tpu(node_spec=[node_spec])

request = tpu_v2alpha1.CreateQueuedResourceRequest(
    parent=f"projects/{project_id}/locations/{zone}",
    queued_resource_id=queued_resource_name,
    queued_resource=resource,
)

client = tpu_v2alpha1.TpuClient()
operation = client.create_queued_resource(request=request)

response = operation.result()
print(response.name)
print(response.state)
# Example response:
# projects/[project_id]/locations/[zone]/queuedResources/resource-name
# State.WAITING_FOR_RESOURCES

使用預約要求排入佇列的資源

您可以使用預留項目要求佇列資源。如要購買預訂,請與 Google Cloud 帳戶團隊聯絡。

gcloud

gcloud compute tpus queued-resources create your-queued-resource-id \
    --node-id your-node-id \
    --project your-project-id \
    --zone us-central1-a \
    --accelerator-type v5litepod-8 \
    --runtime-version v2-alpha-tpuv5-lite \
    --reserved

指令參數說明

queued-resource-id
使用者指派的佇列資源要求 ID。
node-id
系統分配佇列資源要求時建立的 TPU 使用者指派 ID。
project
您的 Google Cloud 專案。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
reserved
在要求排入佇列的資源時,請使用這個標記,將資源納入 Cloud TPU 預訂項目。

curl

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d "{
    'tpu': {
    'node_spec': {
        'parent': 'projects/your-project-number/locations/us-central1-a',
        'node_id': 'your-node-id',
        'node': {
        'accelerator_type': 'v5litepod-8',
        'runtime_version': 'v2-alpha-tpuv5-lite',
        }
    }
    },
    'guaranteed': {
    'reserved': true,
    }
}" \
https://tpu.googleapis.com/v2alpha1/projects/your-project-id/locations/us-central1-a/queuedResources?queued_resource_id=your-queued-resource-id

指令參數說明

queued-resource-id
使用者指派的佇列資源要求 ID。
node-id
系統分配佇列資源要求時建立的 TPU 使用者指派 ID。
project
您的 Google Cloud 專案。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
reserved
在要求排入佇列的資源時,請使用這個標記,將資源納入 Cloud TPU 預訂項目。

控制台

  1. 前往 Google Cloud 控制台的「TPUs」頁面:

    前往 TPU

  2. 按一下「建立 TPU」

  3. 在「Name」(名稱) 欄位中,輸入 TPU 的名稱。

  4. 在「Zone」(可用區) 方塊中,選取要建立 TPU 的可用區。

  5. 在「TPU type」(TPU 類型) 方塊中,選取加速器類型。加速器類型會指定要建立的 Cloud TPU 版本和大小。如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱「TPU 版本」。

  6. 在「TPU 軟體版本」方塊中,選取軟體版本。建立 Cloud TPU VM 時,TPU 軟體版本會指定要安裝的 TPU 執行階段版本。詳情請參閱「TPU 軟體版本」。

  7. 按一下「啟用佇列」切換鈕。

  8. 在「Queued resource name」(已加入佇列的資源名稱) 欄位中,輸入已加入佇列的資源要求名稱。

  9. 展開「管理」部分。

  10. 勾選「使用現有的預留項目」核取方塊。

  11. 按一下「建立」,建立已加入佇列的資源要求。

要求 TPU Spot VM 佇列資源

Spot VM 是可隨時先占並指派給其他工作負載的資源。Spot VM 資源的費用較低,與非 Spot VM 要求相比,您可能更快就能存取資源。如要進一步瞭解 TPU Spot VM,請參閱「管理 TPU Spot VM」。

gcloud

gcloud compute tpus queued-resources create your-queued-resource-id \
    --node-id your-node-id \
    --project your-project-id \
    --zone us-central1-a \
    --accelerator-type v5litepod-8 \
    --runtime-version v2-alpha-tpuv5-lite \
    --spot

指令參數說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 ID。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
spot
布林值旗標,用於指定排隊資源是否為 Spot VM。

curl

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d "{
    'tpu': {
    'node_spec': {
        'parent': 'projects/your-project-number/locations/us-central1-a',
        'node_id': 'your-node-id',
        'node': {
        'accelerator_type': 'v5litepod-8',
        'runtime_version': 'v2-alpha-tpuv5-lite'
        }
    }
    },
    'spot': {}
}" \
https://tpu.googleapis.com/v2alpha1/projects/your-project-id/locations/us-central1-a/queuedResources?queued_resource_id=your-queued-resource-id

指令參數說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 ID。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
spot
布林值旗標,用於指定排隊資源是否為 Spot VM。

控制台

  1. 前往 Google Cloud 控制台的「TPUs」頁面:

    前往 TPU

  2. 按一下「建立 TPU」

  3. 在「Name」(名稱) 欄位中,輸入 TPU 的名稱。

  4. 在「Zone」(可用區) 方塊中,選取要建立 TPU 的可用區。

  5. 在「TPU type」(TPU 類型) 方塊中,選取加速器類型。加速器類型會指定要建立的 Cloud TPU 版本和大小。如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱「TPU 版本」。

  6. 在「TPU 軟體版本」方塊中,選取軟體版本。建立 Cloud TPU VM 時,TPU 軟體版本會指定要安裝的 TPU 執行階段版本。詳情請參閱「TPU 軟體版本」。

  7. 按一下「啟用佇列」切換鈕。

  8. 在「Queued resource name」(已加入佇列的資源名稱) 欄位中,輸入已加入佇列的資源要求名稱。

  9. 展開「管理」部分。

  10. 勾選「將此設為 TPU Spot VM」核取方塊。

  11. 點選「建立」

Java

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import com.google.cloud.tpu.v2alpha1.CreateQueuedResourceRequest;
import com.google.cloud.tpu.v2alpha1.Node;
import com.google.cloud.tpu.v2alpha1.QueuedResource;
import com.google.cloud.tpu.v2alpha1.SchedulingConfig;
import com.google.cloud.tpu.v2alpha1.TpuClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class CreateSpotQueuedResource {
  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to create a node.
    String projectId = "YOUR_PROJECT_ID";
    // The zone in which to create the TPU.
    // For more information about supported TPU types for specific zones,
    // see https://cloud.google.com/tpu/docs/regions-zones
    String zone = "us-central1-a";
    // The name for your TPU.
    String nodeName = "YOUR_TPU_NAME";
    // The accelerator type that specifies the version and size of the Cloud TPU you want to create.
    // For more information about supported accelerator types for each TPU version,
    // see https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#versions.
    String tpuType = "v5litepod-4";
    // Software version that specifies the version of the TPU runtime to install.
    // For more information see https://cloud.google.com/tpu/docs/runtimes
    String tpuSoftwareVersion = "v2-tpuv5-litepod";
    // The name for your Queued Resource.
    String queuedResourceId = "QUEUED_RESOURCE_ID";

    createQueuedResource(
        projectId, zone, queuedResourceId, nodeName, tpuType, tpuSoftwareVersion);
  }

  // Creates a Queued Resource with --preemptible flag.
  public static QueuedResource createQueuedResource(
      String projectId, String zone, String queuedResourceId,
      String nodeName, String tpuType, String tpuSoftwareVersion)
      throws IOException, ExecutionException, InterruptedException {
    // 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 (TpuClient tpuClient = TpuClient.create()) {
      String parent = String.format("projects/%s/locations/%s", projectId, zone);
      String resourceName = String.format("projects/%s/locations/%s/queuedResources/%s",
              projectId, zone, queuedResourceId);
      SchedulingConfig schedulingConfig = SchedulingConfig.newBuilder()
          .setPreemptible(true)
          .build();

      Node node =
          Node.newBuilder()
              .setName(nodeName)
              .setAcceleratorType(tpuType)
              .setRuntimeVersion(tpuSoftwareVersion)
              .setSchedulingConfig(schedulingConfig)
              .setQueuedResource(resourceName)
              .build();

      QueuedResource queuedResource =
          QueuedResource.newBuilder()
              .setName(queuedResourceId)
              .setTpu(
                  QueuedResource.Tpu.newBuilder()
                      .addNodeSpec(
                          QueuedResource.Tpu.NodeSpec.newBuilder()
                              .setParent(parent)
                              .setNode(node)
                              .setNodeId(nodeName)
                              .build())
                      .build())
              .build();

      CreateQueuedResourceRequest request =
          CreateQueuedResourceRequest.newBuilder()
              .setParent(parent)
              .setQueuedResourceId(queuedResourceId)
              .setQueuedResource(queuedResource)
              .build();

      return tpuClient.createQueuedResourceAsync(request).get();
    }
  }
}

Python

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import tpu_v2alpha1

# TODO(developer): Update and un-comment below lines
# project_id = "your-project-id"
# zone = "us-central1-a"
# tpu_name = "tpu-name"
# tpu_type = "v5litepod-4"
# runtime_version = "v2-tpuv5-litepod"
# queued_resource_name = "resource-name"

node = tpu_v2alpha1.Node()
node.accelerator_type = tpu_type
# To see available runtime version use command:
# gcloud compute tpus versions list --zone={ZONE}
node.runtime_version = runtime_version

node_spec = tpu_v2alpha1.QueuedResource.Tpu.NodeSpec()
node_spec.parent = f"projects/{project_id}/locations/{zone}"
node_spec.node_id = tpu_name
node_spec.node = node

resource = tpu_v2alpha1.QueuedResource()
resource.tpu = tpu_v2alpha1.QueuedResource.Tpu(node_spec=[node_spec])
# Create a spot resource
resource.spot = tpu_v2alpha1.QueuedResource.Spot()

request = tpu_v2alpha1.CreateQueuedResourceRequest(
    parent=f"projects/{project_id}/locations/{zone}",
    queued_resource_id=queued_resource_name,
    queued_resource=resource,
)

client = tpu_v2alpha1.TpuClient()
operation = client.create_queued_resource(request=request)
response = operation.result()

print(response.name)
print(response.state)
# Example response:
# projects/[project_id]/locations/[zone]/queuedResources/resource-name
# State.WAITING_FOR_RESOURCES

要求在指定時間之前或之後分配佇列資源

您可以在已加入佇列的資源要求中,指定選填的開始時間結束時間。開始時間或開始時間長度會指定填寫要求的最早時間。結束時間或結束時間長度會指定要求保持有效的時間長度。 如果要求未在指定結束時間或指定時間長度內填寫完畢,要求就會過期。要求過期後,仍會保留在佇列中,但不再符合分配資格。

您也可以指定開始時間/時間長度和結束時間/時間長度,藉此指定分配間隔

如需支援的時間戳記和時間長度格式清單,請參閱「日期時間」。

要求在指定時間後完成排入佇列的資源

在已加入佇列的資源要求中,您可以指定資源應在何時或經過多久後分配。

gcloud

下列指令要求在 2022 年 12 月 14 日上午 9 點後分配 v5p-4096 TPU。

gcloud compute tpus queued-resources create your-queued-resource-id \
    --node-id your-node-id \
    --project your-project-id \
    --zone us-east5-a \
    --accelerator-type v5p-4096 \
    --runtime-version v2-alpha-tpuv5 \
    --valid-after-time 2022-12-14T09:00:00Z

指令參數說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 Google Cloud 。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
valid-after-time
資源應配置的時間。如要進一步瞭解時間格式,請參閱 Google Cloud CLI 主題 datetime

curl

下列指令要求在 2022 年 12 月 14 日上午 9 點後分配 v5p-4096 TPU。

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d "{
    'tpu': {
    'node_spec': {
        'parent': 'projects/your-project-number/locations/us-east5-a',
        'node_id': 'your-node-id',
        'node': {
        'accelerator_type': 'v5p-4096',
        'runtime_version': 'v2-alpha-tpuv5',
        }
    }
    },
    'queueing_policy': {
    'valid_after_time': {
        'seconds': 2022-12-14T09:00:00Z
    }
    }
}" \
https://tpu.googleapis.com/v2alpha1/projects/your-project-id/locations/us-east5-a/queuedResources?queued_resource_id=your-queued-resource-id

指令參數說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 Google Cloud 。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
valid-after-time
資源應配置的時間。如要進一步瞭解時間格式,請參閱 Google Cloud CLI 主題 datetime

控制台

  1. 前往 Google Cloud 控制台的「TPUs」頁面:

    前往 TPU

  2. 按一下「建立 TPU」

  3. 在「Name」(名稱) 欄位中,輸入 TPU 的名稱。

  4. 在「Zone」(可用區) 方塊中,選取要建立 TPU 的可用區。

  5. 在「TPU type」(TPU 類型) 方塊中,選取加速器類型。加速器類型會指定要建立的 Cloud TPU 版本和大小。如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱「TPU 版本」。

  6. 在「TPU 軟體版本」方塊中,選取軟體版本。建立 Cloud TPU VM 時,TPU 軟體版本會指定要安裝的 TPU 執行階段版本。詳情請參閱 TPU 軟體版本

  7. 按一下「啟用佇列」切換鈕。

  8. 在「Queued resource name」(已加入佇列的資源名稱) 欄位中,輸入已加入佇列的資源要求名稱。

  9. 在「Start request on」(要求開始時間) 欄位中,輸入應分配資源的時間。

  10. 按一下「建立」,建立已加入佇列的資源要求。

以下範例要求在六小時後分配 v5p-32。

gcloud

    gcloud compute tpus queued-resources create your-queued-resource-id \
        --node-id your-node-id \
        --project your-project-id \
        --zone us-east5-a \
        --accelerator-type v5p-32 \
        --runtime-version v2-alpha-tpuv5 \
        --valid-after-duration 6h

指令參數說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 Google Cloud 。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
valid-after-duration
TPU 不得佈建的時長。如要進一步瞭解時間長度格式,請參閱 Google Cloud CLI 主題 datetime

curl

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d "{
    'tpu': {
    'node_spec': {
        'parent': 'projects/your-project-number/locations/us-east5-a',
        'node_id': 'your-node-id',
        'node': {
        'accelerator_type': 'v5p-32',
        'runtime_version': 'v2-alpha-tpuv5',
        }
    }
    },
'queueing_policy': {
    'valid_after_duration': {
        'seconds': 21600
    }
}" \
https://tpu.googleapis.com/v2alpha1/projects/your-project-id/locations/us-east5-a/queuedResources?queued_resource_id=your-queued-resource-id

指令參數說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 Google Cloud 。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
valid-after-duration
TPU 不得佈建的時長。如要進一步瞭解時間長度格式,請參閱 Google Cloud CLI 主題 datetime

Java

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import com.google.cloud.tpu.v2alpha1.CreateQueuedResourceRequest;
import com.google.cloud.tpu.v2alpha1.Node;
import com.google.cloud.tpu.v2alpha1.QueuedResource;
import com.google.cloud.tpu.v2alpha1.TpuClient;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class CreateTimeBoundQueuedResource {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to create a node.
    String projectId = "YOUR_PROJECT_ID";
    // The zone in which to create the TPU.
    // For more information about supported TPU types for specific zones,
    // see https://cloud.google.com/tpu/docs/regions-zones
    String zone = "us-central2-b";
    // The name of your node.
    String nodeId = "YOUR_NODE_ID";
    // The accelerator type that specifies the version and size of the Cloud TPU you want to create.
    // For more information about supported accelerator types for each TPU version,
    // see https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#versions.
    String acceleratorType = "v2-8";
    // Software version that specifies the version of the TPU runtime to install.
    // For more information see https://cloud.google.com/tpu/docs/runtimes
    String runtimeVersion = "v2-tpuv5-litepod";
    // The name of your Queued Resource.
    String queuedResourceId = "YOUR_QUEUED_RESOURCE_ID";

    createTimeBoundQueuedResource(projectId, nodeId,
        queuedResourceId, zone, acceleratorType, runtimeVersion);
  }

  // Creates a Queued Resource with time bound configuration.
  public static QueuedResource createTimeBoundQueuedResource(
      String projectId, String nodeId, String queuedResourceId,
      String zone, String acceleratorType, String runtimeVersion)
          throws IOException, ExecutionException, InterruptedException {
    // 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 (TpuClient tpuClient = TpuClient.create()) {
      String parent = String.format("projects/%s/locations/%s", projectId, zone);
      // Create a Duration object representing 6 hours.
      Duration validAfterDuration = Duration.newBuilder().setSeconds(6 * 3600).build();
      // You could also use timestamps like this:
      // Timestamp validAfterTime = Timestamps.parse("2024-10-14T09:00:00Z");

      Node node =
          Node.newBuilder()
              .setName(nodeId)
              .setAcceleratorType(acceleratorType)
              .setRuntimeVersion(runtimeVersion)
              .setQueuedResource(
                  String.format(
                      "projects/%s/locations/%s/queuedResources/%s",
                      projectId, zone, queuedResourceId))
              .build();

      QueuedResource queuedResource =
          QueuedResource.newBuilder()
              .setName(queuedResourceId)
              .setTpu(
                  QueuedResource.Tpu.newBuilder()
                      .addNodeSpec(
                          QueuedResource.Tpu.NodeSpec.newBuilder()
                              .setParent(parent)
                              .setNode(node)
                              .setNodeId(nodeId)
                              .build())
                      .build())
              .setQueueingPolicy(
                  QueuedResource.QueueingPolicy.newBuilder()
                      .setValidAfterDuration(validAfterDuration)
                      // .setValidAfterTime(validAfterTime)
                      .build())
              .build();

      CreateQueuedResourceRequest request =
          CreateQueuedResourceRequest.newBuilder()
              .setParent(parent)
              .setQueuedResource(queuedResource)
              .setQueuedResourceId(queuedResourceId)
              .build();

      return tpuClient.createQueuedResourceAsync(request).get();
    }
  }
}

要求在指定時間後過期的排入佇列資源

在佇列資源要求中,您可以指定佇列資源要求保持有效的時間長度。如果要求未在指定時間或時間長度內完成,要求就會失效。

gcloud

下列指令會要求 v5p-4096 TPU。如果我們在 2022 年 12 月 14 日上午 9 點前未收到要求,要求就會失效。

gcloud compute tpus queued-resources create your-queued-resource-id \
    --node-id your-node-id \
    --project your-project-id \
    --zone us-east5-a \
    --accelerator-type v5p-4096 \
    --runtime-version v2-alpha-tpuv5 \
    --valid-until-time 2022-12-14T09:00:00Z

指令參數說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 ID。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
valid-until-time
要求取消的時間。如要進一步瞭解時間長度格式,請參閱 Google Cloud CLI 主題日期時間

curl

下列指令會要求 v5p-4096 TPU。如果我們在 2022 年 12 月 14 日上午 9 點前未收到要求,要求就會失效。

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d "{
    'tpu': {
    'node_spec': {
        'parent': 'projects/your-project-number/locations/us-east5-a',
        'node_id': 'your-node-id',
        'node': {
        'accelerator_type': 'v5p-4096',
        'runtime_version': 'v2-alpha-tpuv5',
        }
    }
    },
    'queueing_policy': {
    'valid_until_time': {
        'seconds': 1655197200
    }
    }
}" \
https://tpu.googleapis.com/v2alpha1/projects/your-project-id/locations/us-east5-a/queuedResources?queued_resource_id=your-queued-resource-id

指令參數說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 ID。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
valid-until-time
要求取消的時間。如要進一步瞭解時間長度格式,請參閱 Google Cloud CLI 主題日期時間

控制台

  1. 前往 Google Cloud 控制台的「TPUs」頁面:

    前往 TPU

  2. 按一下「建立 TPU」

  3. 在「Name」(名稱) 欄位中,輸入 TPU 的名稱。

  4. 在「Zone」(可用區) 方塊中,選取要建立 TPU 的可用區。

  5. 在「TPU type」(TPU 類型) 方塊中,選取加速器類型。加速器類型會指定要建立的 Cloud TPU 版本和大小。如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱「TPU 版本」。

  6. 在「TPU 軟體版本」方塊中,選取軟體版本。建立 Cloud TPU VM 時,TPU 軟體版本會指定要安裝的 TPU 執行階段版本。詳情請參閱「TPU 軟體版本」。

  7. 按一下「啟用佇列」切換鈕。

  8. 在「Queued resource name」(已加入佇列的資源名稱) 欄位中,輸入已加入佇列的資源要求名稱。

  9. 在「Cancel request on」(取消要求時間) 欄位中,輸入排隊資源要求未填入時的到期時間。

  10. 按一下「建立」,建立已加入佇列的資源要求。

以下範例要求 v5p-32。如果要求未在六小時內填寫完畢,就會失效。

gcloud

    gcloud compute tpus queued-resources create your-queued-resource-id \
    --node-id your-node-id \
    --project your-project-id \
    --zone us-east5-a \
    --accelerator-type v5p-32 \
    --runtime-version v2-alpha-tpuv5 \
    --valid-until-duration 6h

指令參數說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 Google Cloud 。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
valid-until-duration
要求的有效期間。如要進一步瞭解時間長度格式,請參閱 Google Cloud CLI 主題 datetime

curl

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d "{
    'tpu': {
    'node_spec': {
        'parent': 'projects/your-project-number/locations/us-east5-a',
        'node_id': 'your-node-id',
        'node': {
        'accelerator_type': 'v5p-32',
        'runtime_version': 'v2-alpha-tpuv5',
        }
    }
    },
'queueing_policy': {
    'valid_until_duration': {
        'seconds': 21600
    }
}" \
https://tpu.googleapis.com/v2alpha1/projects/your-project-id/locations/us-east5-a/queuedResources?queued_resource_id=your-queued-resource-id

指令參數說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 Google Cloud 。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
valid-until-duration
要求的有效期間。如要進一步瞭解時間長度格式,請參閱 Google Cloud CLI 主題 datetime

Python

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import tpu_v2alpha1

# TODO(developer): Update and un-comment below lines
# project_id = "your-project-id"
# zone = "us-central1-a"
# tpu_name = "tpu-name"
# tpu_type = "v5litepod-4"
# runtime_version = "v2-tpuv5-litepod"
# queued_resource_name = "resource-name"

node = tpu_v2alpha1.Node()
node.accelerator_type = tpu_type
# To see available runtime version use command:
# gcloud compute tpus versions list --zone={ZONE}
node.runtime_version = runtime_version

node_spec = tpu_v2alpha1.QueuedResource.Tpu.NodeSpec()
node_spec.parent = f"projects/{project_id}/locations/{zone}"
node_spec.node_id = tpu_name
node_spec.node = node

resource = tpu_v2alpha1.QueuedResource()
resource.tpu = tpu_v2alpha1.QueuedResource.Tpu(node_spec=[node_spec])

# Use one of the following queueing policies
resource.queueing_policy = tpu_v2alpha1.QueuedResource.QueueingPolicy(
    # valid_after_duration = "6000s", # Duration after which a resource should be allocated
    valid_until_duration="90s",  # Specify how long a queued resource request remains valid
    # valid_after_time="2024-10-31T09:00:00Z", # Specify a time after which a resource should be allocated
    # valid_until_time="2024-10-29T16:00:00Z",  # Specify a time before which the resource should be allocated
)

request = tpu_v2alpha1.CreateQueuedResourceRequest(
    parent=f"projects/{project_id}/locations/{zone}",
    queued_resource_id=queued_resource_name,
    queued_resource=resource,
)

client = tpu_v2alpha1.TpuClient()
operation = client.create_queued_resource(request=request)

response = operation.result()
print(resource.queueing_policy)
print(response.queueing_policy.valid_until_time)
# Example response:
# valid_until_duration {
#   seconds: 90
# }
# 2024-10-29 14:22:53.562090+00:00

要求在指定間隔內分配佇列資源

您可以同時指定開始時間/時間長度和結束時間/時間長度,藉此指定分配間隔。

gcloud

下列指令要求在目前時間的 5 小時 30 分後建立 v5p-32,最晚要在 2022 年 12 月 14 日上午 9 點前建立。

gcloud compute tpus queued-resources create your-queued-resource-id \
    --node-id your-node-id \
    --project your-project-id \
    --zone us-east5-a \
    --accelerator-type v5p-32 \
    --runtime-version v2-alpha-tpuv5 \
    --valid-after-duration 5h30m \
    --valid-until-time 2022-12-14T09:00:00Z

指令旗標說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 ID。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
valid-until-time
要求取消的時間。如要進一步瞭解時間長度格式,請參閱 Google Cloud CLI 主題日期時間
valid-after-duration
TPU 不得佈建的時長。如要進一步瞭解時間長度格式,請參閱 Google Cloud CLI 主題日期時間

curl

下列指令要求在目前時間的 5 小時 30 分後建立 v5p-32,最晚要在 2022 年 12 月 14 日上午 9 點前建立。

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d "{
    'tpu': {
    'node_spec': {
        'parent': 'projects/your-project-number/locations/us-east5-a',
        'node_id': 'your-node-id',
        'node': {
        'accelerator_type': 'v5p-32',
        'runtime_version': 'v2-alpha-tpuv5',
        }
    }
    },
'queueing_policy': {
    'validInterval': {
        'startTime': '2022-12-10T14:30:00Z',
        'endTime': '2022-12-14T09:00:00Z'
    }
    },
}" \
https://tpu.googleapis.com/v2alpha1/projects/your-project-id/locations/us-east5-a/queuedResources?queued_resource_id=your-queued-resource-id

指令旗標說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 ID。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
valid-until-timw
要求取消的時間。如要進一步瞭解時間長度格式,請參閱 Google Cloud CLI 主題日期時間
valid-until-duration
要求的有效期間。如要進一步瞭解時間長度格式,請參閱 Google Cloud CLI 主題日期時間

控制台

  1. 前往 Google Cloud 控制台的「TPUs」頁面:

    前往 TPU

  2. 按一下「建立 TPU」

  3. 在「Name」(名稱) 欄位中,輸入 TPU 的名稱。

  4. 在「Zone」(可用區) 方塊中,選取要建立 TPU 的可用區。

  5. 在「TPU type」(TPU 類型) 方塊中,選取加速器類型。加速器類型會指定要建立的 Cloud TPU 版本和大小。如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱「TPU 版本」。

  6. 在「TPU 軟體版本」方塊中,選取軟體版本。建立 Cloud TPU VM 時,TPU 軟體版本會指定要安裝的 TPU 執行階段版本。詳情請參閱「TPU 軟體版本」。

  7. 按一下「啟用佇列」切換鈕。

  8. 在「Queued resource name」(已加入佇列的資源名稱) 欄位中,輸入已加入佇列的資源要求名稱。

  9. 在「Start request on」(要求開始時間) 欄位中,輸入應分配資源的時間。

  10. 在「Cancel request on」(取消要求時間) 欄位中,輸入排隊資源要求未填入時的到期時間。

  11. 按一下「建立」,建立已加入佇列的資源要求。

使用開機指令碼要求排入佇列的資源

您可以指定要在佇列資源佈建完成後執行的指令碼。

gcloud

使用 gcloud 指令時,您可以分別使用 --metadata--metadata-from-file 旗標,指定指令碼指令或包含指令碼程式碼的檔案。以下範例會建立已加入佇列的資源要求,以執行 startup-script.sh 指令碼。

gcloud compute tpus queued-resources create your-queued-resource-id \
    --node-id your-node-id \
    --project your-project-id \
    --zone us-central1-a \
    --accelerator-type v5litepod-8 \
    --runtime-version v2-alpha-tpuv5-lite \
    --metadata-from-file='startup-script=startup-script.sh'

指令旗標說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 ID。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
validInterval
:要求有效時間,過期後要求會遭到取消。如要進一步瞭解時間長度格式,請參閱 Google Cloud CLI 主題日期時間
metadata-from-file
指定包含中繼資料的檔案。如果未指定中繼資料檔案的完整路徑,指令會假設該檔案位於目前目錄。在本範例中,檔案包含啟動指令碼,會在佈建佇列資源時執行。
metadata
指定要求的相關中繼資料。在本範例中,中繼資料是排隊資源佈建時執行的開機指令碼指令。

curl

使用 curl 時,您必須在 JSON 內容中加入指令碼程式碼。下列範例包含 JSON 主體中的內嵌指令碼。

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d "{
    tpu: {
        node_spec: {
        parent: 'projects/your-project-number/locations/us-central1-a',
        node_id: 'your-node-id',
        node: {
            accelerator_type: 'v5e-8',
            runtime_version: 'v2-alpha-tpuv5-lite',
            metadata: {
                "startup-script": "#! /bin/bash\npwd > /tmp/out.txt\nwhoami >> /tmp/out.txt"
            }
        }
        }
    },
'queueing_policy': {
    'validInterval': {
        'startTime': '2022-12-10T14:30:00Z',
        'endTime': '2022-12-14T09:00:00Z'
    }
    },
}" \
https://tpu.googleapis.com/v2alpha1/projects/your-project-id/locations/us-central1-a/queuedResources?queued_resource_id=your-queued-resource-id

指令旗標說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
node-id
為回應要求而建立的 TPU 使用者定義 ID。
project
已分配佇列資源的專案 ID。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
validInterval
:要求有效時間,過期後要求會遭到取消。如要進一步瞭解時間長度格式,請參閱 Google Cloud CLI 主題日期時間
metadata-from-file
指定包含中繼資料的檔案。如果未指定中繼資料檔案的完整路徑,指令會假設該檔案位於目前目錄。在本範例中,檔案包含啟動指令碼,會在佈建佇列資源時執行。
metadata
指定要求的相關中繼資料。在本範例中,中繼資料是排隊資源佈建時執行的開機指令碼指令。

Java

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import com.google.cloud.tpu.v2alpha1.CreateQueuedResourceRequest;
import com.google.cloud.tpu.v2alpha1.Node;
import com.google.cloud.tpu.v2alpha1.QueuedResource;
import com.google.cloud.tpu.v2alpha1.TpuClient;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class CreateQueuedResourceWithStartupScript {
  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to create a node.
    String projectId = "YOUR_PROJECT_ID";
    // The zone in which to create the TPU.
    // For more information about supported TPU types for specific zones,
    // see https://cloud.google.com/tpu/docs/regions-zones
    String zone = "us-central1-a";
    // The name for your TPU.
    String nodeName = "YOUR_TPU_NAME";
    // The accelerator type that specifies the version and size of the Cloud TPU you want to create.
    // For more information about supported accelerator types for each TPU version,
    // see https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#versions.
    String tpuType = "v5litepod-4";
    // Software version that specifies the version of the TPU runtime to install.
    // For more information see https://cloud.google.com/tpu/docs/runtimes
    String tpuSoftwareVersion = "v2-tpuv5-litepod";
    // The name for your Queued Resource.
    String queuedResourceId = "QUEUED_RESOURCE_ID";

    createQueuedResource(projectId, zone, queuedResourceId, nodeName,
        tpuType, tpuSoftwareVersion);
  }

  // Creates a Queued Resource with startup script.
  public static QueuedResource createQueuedResource(
      String projectId, String zone, String queuedResourceId,
      String nodeName, String tpuType, String tpuSoftwareVersion)
      throws IOException, ExecutionException, InterruptedException {
    String parent = String.format("projects/%s/locations/%s", projectId, zone);
    String startupScriptContent = "#!/bin/bash\necho \"Hello from the startup script!\"";
    // Add startup script to metadata
    Map<String, String> metadata = new HashMap<>();
    metadata.put("startup-script", startupScriptContent);
    String queuedResourceForTpu =  String.format("projects/%s/locations/%s/queuedResources/%s",
            projectId, zone, queuedResourceId);
    // 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 (TpuClient tpuClient = TpuClient.create()) {
      Node node =
          Node.newBuilder()
              .setName(nodeName)
              .setAcceleratorType(tpuType)
              .setRuntimeVersion(tpuSoftwareVersion)
              .setQueuedResource(queuedResourceForTpu)
              .putAllMetadata(metadata)
              .build();

      QueuedResource queuedResource =
          QueuedResource.newBuilder()
              .setName(queuedResourceId)
              .setTpu(
                  QueuedResource.Tpu.newBuilder()
                      .addNodeSpec(
                          QueuedResource.Tpu.NodeSpec.newBuilder()
                              .setParent(parent)
                              .setNode(node)
                              .setNodeId(nodeName)
                              .build())
                      .build())
              .build();

      CreateQueuedResourceRequest request =
          CreateQueuedResourceRequest.newBuilder()
              .setParent(parent)
              .setQueuedResourceId(queuedResourceId)
              .setQueuedResource(queuedResource)
              .build();
      // You can wait until TPU Node is READY,
      // and check its status using getTpuVm() from "tpu_vm_get" sample.

      return tpuClient.createQueuedResourceAsync(request).get();
    }
  }
}

Python

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import tpu_v2alpha1

# TODO(developer): Update and un-comment below lines
# project_id = "your-project-id"
# zone = "us-central1-a"
# tpu_name = "tpu-name"
# tpu_type = "v5litepod-4"
# runtime_version = "v2-tpuv5-litepod"
# queued_resource_name = "resource-name"

node = tpu_v2alpha1.Node()
node.accelerator_type = tpu_type
# To see available runtime version use command:
# gcloud compute tpus versions list --zone={ZONE}
node.runtime_version = runtime_version
# This startup script updates numpy to the latest version and logs the output to a file.
script = {
    "startup-script": """#!/bin/bash
echo "Hello World" > /var/log/hello.log
sudo pip3 install --upgrade numpy >> /var/log/hello.log 2>&1
"""
}
node.metadata = script
# Enabling external IPs for internet access from the TPU node for updating numpy
node.network_config = tpu_v2alpha1.NetworkConfig(
    enable_external_ips=True,
)

node_spec = tpu_v2alpha1.QueuedResource.Tpu.NodeSpec()
node_spec.parent = f"projects/{project_id}/locations/{zone}"
node_spec.node_id = tpu_name
node_spec.node = node

resource = tpu_v2alpha1.QueuedResource()
resource.tpu = tpu_v2alpha1.QueuedResource.Tpu(node_spec=[node_spec])

request = tpu_v2alpha1.CreateQueuedResourceRequest(
    parent=f"projects/{project_id}/locations/{zone}",
    queued_resource_id=queued_resource_name,
    queued_resource=resource,
)

client = tpu_v2alpha1.TpuClient()
operation = client.create_queued_resource(request=request)

response = operation.result()
print(response.name)
print(response.tpu.node_spec[0].node.metadata)
# Example response:
# projects/[project_id]/locations/[zone]/queuedResources/resource-name
# {'startup-script': '#!/bin/bash\n    echo "Hello World" > /var/log/hello.log\n
# sudo pip3 install --upgrade numpy >> /var/log/hello.log 2>&1\n    '}

使用指定的網路和子網路要求排入佇列的資源

在排入佇列的資源要求中,您可以指定要將 TPU 連線至哪個網路和子網路。

gcloud

gcloud compute tpus queued-resources create your-queued-resource-id \
    --node-id your-node-id \
    --project your-project-id \
    --zone us-central1-a \
    --accelerator-type v5e-8 \
    --runtime-version v2-alpha-tpuv5-lite \
    --network network-name \
    --subnetwork subnetwork-name

指令參數說明

queued-resource-id
使用者指派的佇列資源要求 ID。
node-id
系統分配佇列資源要求時建立的 TPU 使用者指派 ID。
project
您的 Google Cloud 專案。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
reserved
在要求排入佇列的資源時,請使用這個標記,將資源納入 Cloud TPU 預訂項目。
network
排入佇列的資源所屬的網路。
subnetwork
排入佇列的資源所屬的子網路。

curl

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d "{
    'tpu': {
    'node_spec': {
        'parent': 'projects/your-project-number/locations/us-central1-a',
        'node_id': 'your-node-id',
        'node': {
        'accelerator_type': 'v5e-8',
        'runtime_version': 'v2-alpha-tpuv5-lite',
        'network_config': {
            'network': 'network-name',
            'subnetwork': 'subnetwork-name',
            'enable_external_ips': true
        }
    }
    },
    'guaranteed': {
    'reserved': true,
    }
}" \
https://tpu.googleapis.com/v2alpha1/projects/your-project-id/locations/us-central1-a/queuedResources?queued_resource_id=your-queued-resource-id

指令參數說明

queued-resource-id
使用者指派的佇列資源要求 ID。
node-id
系統分配佇列資源要求時建立的 TPU 使用者指派 ID。
project
您的 Google Cloud 專案。
zone
您要建立 Cloud TPU 的區域
accelerator-type
加速器類型會指定您要建立的 Cloud TPU 版本和大小。 如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱 TPU 版本
runtime-version
Cloud TPU 軟體版本
reserved
在要求排入佇列的資源時,請使用這個標記,將資源納入 Cloud TPU 預訂項目。
network
排入佇列的資源所屬的網路。
subnetwork
排入佇列的資源所屬的子網路。

控制台

  1. 前往 Google Cloud 控制台的「TPUs」頁面:

    前往 TPU

  2. 按一下「建立 TPU」

  3. 在「Name」(名稱) 欄位中,輸入 TPU 的名稱。

  4. 在「Zone」(可用區) 方塊中,選取要建立 TPU 的可用區。

  5. 在「TPU type」(TPU 類型) 方塊中,選取加速器類型。加速器類型會指定要建立的 Cloud TPU 版本和大小。如要進一步瞭解各個 TPU 版本支援的加速器類型,請參閱「TPU 版本」。

  6. 在「TPU 軟體版本」方塊中,選取軟體版本。建立 Cloud TPU VM 時,TPU 軟體版本會指定要安裝的 TPU 執行階段版本。詳情請參閱「TPU 軟體版本」。

  7. 按一下「啟用佇列」切換鈕。

  8. 在「Queued resource name」(已加入佇列的資源名稱) 欄位中,輸入已加入佇列的資源要求名稱。

  9. 展開「網路」部分。

  10. 在「Network」(網路) 和「Subnetwork」(子網路) 欄位中,選取要使用的網路和子網路。

  11. 按一下「建立」,建立已加入佇列的資源要求。

Java

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import com.google.api.gax.retrying.RetrySettings;
import com.google.cloud.tpu.v2alpha1.CreateQueuedResourceRequest;
import com.google.cloud.tpu.v2alpha1.NetworkConfig;
import com.google.cloud.tpu.v2alpha1.Node;
import com.google.cloud.tpu.v2alpha1.QueuedResource;
import com.google.cloud.tpu.v2alpha1.TpuClient;
import com.google.cloud.tpu.v2alpha1.TpuSettings;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import org.threeten.bp.Duration;

public class CreateQueuedResourceWithNetwork {
  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to create a node.
    String projectId = "YOUR_PROJECT_ID";
    // The zone in which to create the TPU.
    // For more information about supported TPU types for specific zones,
    // see https://cloud.google.com/tpu/docs/regions-zones
    String zone = "europe-west4-a";
    // The name for your TPU.
    String nodeName = "YOUR_TPU_NAME";
    // The accelerator type that specifies the version and size of the Cloud TPU you want to create.
    // For more information about supported accelerator types for each TPU version,
    // see https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#versions.
    String tpuType = "v5litepod-4";
    // Software version that specifies the version of the TPU runtime to install.
    // For more information see https://cloud.google.com/tpu/docs/runtimes
    String tpuSoftwareVersion = "v2-tpuv5-litepod";
    // The name for your Queued Resource.
    String queuedResourceId = "QUEUED_RESOURCE_ID";
    // The name of the network you want the node to connect to.
    // The network should be assigned to your project.
    String networkName = "YOUR_COMPUTE_TPU_NETWORK";

    createQueuedResourceWithNetwork(projectId, zone, queuedResourceId, nodeName,
        tpuType, tpuSoftwareVersion, networkName);
  }

  // Creates a Queued Resource with network configuration.
  public static QueuedResource createQueuedResourceWithNetwork(
      String projectId, String zone, String queuedResourceId, String nodeName,
      String tpuType, String tpuSoftwareVersion, String networkName)
      throws IOException, ExecutionException, InterruptedException {
    // With these settings the client library handles the Operation's polling mechanism
    // and prevent CancellationException error
    TpuSettings.Builder clientSettings =
        TpuSettings.newBuilder();
    clientSettings
        .createQueuedResourceSettings()
        .setRetrySettings(
            RetrySettings.newBuilder()
                .setInitialRetryDelay(Duration.ofMillis(5000L))
                .setRetryDelayMultiplier(2.0)
                .setInitialRpcTimeout(Duration.ZERO)
                .setRpcTimeoutMultiplier(1.0)
                .setMaxRetryDelay(Duration.ofMillis(45000L))
                .setTotalTimeout(Duration.ofHours(24L))
                .build());
    // 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 (TpuClient tpuClient = TpuClient.create(clientSettings.build())) {
      String parent = String.format("projects/%s/locations/%s", projectId, zone);
      String region = zone.substring(0, zone.length() - 2);

      // Specify the network and subnetwork that you want to connect your TPU to.
      NetworkConfig networkConfig =
          NetworkConfig.newBuilder()
              .setEnableExternalIps(true)
              .setNetwork(String.format("projects/%s/global/networks/%s", projectId, networkName))
              .setSubnetwork(
                  String.format(
                      "projects/%s/regions/%s/subnetworks/%s", projectId, region, networkName))
              .build();

      // Create a node
      Node node =
          Node.newBuilder()
              .setName(nodeName)
              .setAcceleratorType(tpuType)
              .setRuntimeVersion(tpuSoftwareVersion)
              .setNetworkConfig(networkConfig)
              .setQueuedResource(
                  String.format(
                      "projects/%s/locations/%s/queuedResources/%s",
                      projectId, zone, queuedResourceId))
              .build();

      // Create queued resource
      QueuedResource queuedResource =
          QueuedResource.newBuilder()
              .setName(queuedResourceId)
              .setTpu(
                  QueuedResource.Tpu.newBuilder()
                      .addNodeSpec(
                          QueuedResource.Tpu.NodeSpec.newBuilder()
                              .setParent(parent)
                              .setNode(node)
                              .setNodeId(nodeName)
                              .build())
                      .build())
              .build();

      CreateQueuedResourceRequest request =
          CreateQueuedResourceRequest.newBuilder()
              .setParent(parent)
              .setQueuedResource(queuedResource)
              .setQueuedResourceId(queuedResourceId)
              .build();

      // You can wait until TPU Node is READY,
      // and check its status using getTpuVm() from "tpu_vm_get" sample.

      return tpuClient.createQueuedResourceAsync(request).get();
    }
  }
}

Python

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import tpu_v2alpha1

# TODO(developer): Update and un-comment below lines
# project_id = "your-project-id"
# zone = "us-central1-a"
# tpu_name = "tpu-name"
# tpu_type = "v5litepod-4"
# runtime_version = "v2-tpuv5-litepod"
# queued_resource_name = "resource-name"
# network = "default"

node = tpu_v2alpha1.Node()
node.accelerator_type = tpu_type
node.runtime_version = runtime_version
# Setting network configuration
node.network_config = tpu_v2alpha1.NetworkConfig(
    network=network,  # Update if you want to use a specific network
    subnetwork="default",  # Update if you want to use a specific subnetwork
    enable_external_ips=True,
    can_ip_forward=True,
)

node_spec = tpu_v2alpha1.QueuedResource.Tpu.NodeSpec()
node_spec.parent = f"projects/{project_id}/locations/{zone}"
node_spec.node_id = tpu_name
node_spec.node = node

resource = tpu_v2alpha1.QueuedResource()
resource.tpu = tpu_v2alpha1.QueuedResource.Tpu(node_spec=[node_spec])

request = tpu_v2alpha1.CreateQueuedResourceRequest(
    parent=f"projects/{project_id}/locations/{zone}",
    queued_resource_id=queued_resource_name,
    queued_resource=resource,
)

client = tpu_v2alpha1.TpuClient()
operation = client.create_queued_resource(request=request)

response = operation.result()
print(response.name)
print(response.tpu.node_spec[0].node.network_config)
print(resource.tpu.node_spec[0].node.network_config.network == "default")
# Example response:
# network: "default"
# subnetwork: "default"
# enable_external_ips: true
# can_ip_forward: true

刪除排入佇列的資源要求

您可以刪除排入佇列的資源要求,以及與要求相關聯的 TPU,方法如下:

gcloud

--force 旗標傳遞至 queued-resource delete 指令:

gcloud compute tpus queued-resources delete your-queued-resource-id \
    --project your-project-id \
    --zone us-central1-a \
    --force \
    --async

指令旗標說明

your-queued-resource-id
使用者指派的佇列資源要求 ID。
project
已分配佇列資源的專案 Google Cloud 。
zone
要刪除的 Cloud TPU 區域
force
刪除 TPU VM 和排入佇列的資源要求。

curl

curl 要求中使用查詢參數 force=true

curl -X DELETE -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://tpu.googleapis.com/v2/projects/your-project-id/locations/us-central1-a/queuedResources/your-queued-resource-id?force=true

指令旗標說明

your-queued-resource-id
使用者指派的佇列資源要求 ID。
project
已分配佇列資源的專案 Google Cloud 。
zone
要刪除的 Cloud TPU 區域
force
刪除 TPU VM 和排入佇列的資源要求。

控制台

  1. 前往 Google Cloud 控制台的「TPUs」頁面:

    前往 TPU

  2. 按一下「已加入佇列的資源」分頁標籤。

  3. 選取佇列中的資源要求旁邊的核取方塊。

  4. 按一下「刪除」圖示

Java

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import com.google.api.gax.retrying.RetrySettings;
import com.google.cloud.tpu.v2alpha1.DeleteQueuedResourceRequest;
import com.google.cloud.tpu.v2alpha1.TpuClient;
import com.google.cloud.tpu.v2alpha1.TpuSettings;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import org.threeten.bp.Duration;

public class DeleteForceQueuedResource {
  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project.
    String projectId = "YOUR_PROJECT_ID";
    // The zone in which the TPU was created.
    String zone = "us-central1-f";
    // The name for your Queued Resource.
    String queuedResourceId = "QUEUED_RESOURCE_ID";

    deleteForceQueuedResource(projectId, zone, queuedResourceId);
  }

  // Deletes a Queued Resource asynchronously with --force flag.
  public static void deleteForceQueuedResource(
      String projectId, String zone, String queuedResourceId)
          throws ExecutionException, InterruptedException, IOException {
    String name = String.format("projects/%s/locations/%s/queuedResources/%s",
        projectId, zone, queuedResourceId);
    // With these settings the client library handles the Operation's polling mechanism
    // and prevent CancellationException error
    TpuSettings.Builder clientSettings =
        TpuSettings.newBuilder();
    clientSettings
        .deleteQueuedResourceSettings()
        .setRetrySettings(
            RetrySettings.newBuilder()
                .setInitialRetryDelay(Duration.ofMillis(5000L))
                .setRetryDelayMultiplier(2.0)
                .setInitialRpcTimeout(Duration.ZERO)
                .setRpcTimeoutMultiplier(1.0)
                .setMaxRetryDelay(Duration.ofMillis(45000L))
                .setTotalTimeout(Duration.ofHours(24L))
                .build());

    // 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 (TpuClient tpuClient = TpuClient.create(clientSettings.build())) {
      DeleteQueuedResourceRequest request =
          DeleteQueuedResourceRequest.newBuilder().setName(name).setForce(true).build();
      // Waiting for updates in the library. Until then, the operation will complete successfully,
      // but the user will receive an error message with UnknownException and IllegalStateException.
      tpuClient.deleteQueuedResourceAsync(request).get();

      System.out.printf("Deleted Queued Resource: %s\n", name);
    }
  }
}

Python

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import tpu_v2alpha1

# TODO(developer): Update and un-comment below lines
# project_id = "your-project-id"
# zone = "us-central1-b"
# queued_resource_name = "resource-name"

client = tpu_v2alpha1.TpuClient()
request = tpu_v2alpha1.DeleteQueuedResourceRequest(
    name=f"projects/{project_id}/locations/{zone}/queuedResources/{queued_resource_name}",
    force=True,  # Set force=True to delete the resource with tpu nodes.
)

try:
    op = client.delete_queued_resource(request=request)
    op.result()
    print(f"Queued resource '{queued_resource_name}' successfully deleted.")
except TypeError as e:
    print(f"Error deleting resource: {e}")
    print(f"Queued resource '{queued_resource_name}' successfully deleted.")

如果直接刪除 TPU,也必須刪除排入佇列的資源,如下列範例所示。刪除 TPU 時,排入佇列的資源要求會轉換為 SUSPENDED 狀態,之後即可刪除排入佇列的資源要求。

gcloud

刪除 TPU:

$ gcloud compute tpus tpu-vm delete your-node-id \
    --project=your-project-id \
    --zone=us-central1-a \
    --quiet

指令旗標說明

project
已分配佇列資源的專案 Google Cloud 。
zone
要刪除的 Cloud TPU 區域
your-node-id
要刪除的 TPU 名稱。

刪除 TPU 時,相關聯的佇列資源會進入 SUSPENDING 狀態,然後進入 SUSPENDED 狀態。如果佇列中的資源處於 SUSPENDED 狀態,您可以刪除該資源:

gcloud compute tpus queued-resources delete your-queued-resource-id \
    --project your-project-id \
    --zone us-central1-a

指令旗標說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
project
已分配佇列資源的專案 Google Cloud 。
zone
要刪除的 Cloud TPU 區域

curl

刪除 TPU:

curl -X DELETE -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://tpu.googleapis.com/v2/projects/your-project/locations/us-central1-a/nodes?node_id=your-node-id

指令旗標說明

project
已分配佇列資源的專案 Google Cloud 。
zone
要刪除的 Cloud TPU 區域
your-node-id
要刪除的 TPU 名稱。

刪除 TPU 時,相關聯的佇列資源會進入 SUSPENDING 狀態,然後進入 SUSPENDED 狀態。如果佇列中的資源處於 SUSPENDED 狀態,您可以刪除該資源:

curl -X DELETE -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://tpu.googleapis.com/v2/projects/your-project-id/locations/us-central1-a/queuedResources/your-queued-resource-id

指令旗標說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
project
已分配佇列資源的專案 Google Cloud 。
zone
要刪除的 Cloud TPU 區域

控制台

刪除 TPU:

  1. 前往 Google Cloud 控制台的「TPUs」頁面:

    前往 TPU

  2. 勾選 TPU 旁的核取方塊。

  3. 按一下「刪除」圖示

刪除 TPU 時,相關聯的佇列資源會進入「正在暫停」狀態,然後進入「已暫停」狀態。如果排入佇列的資源處於「已暫停」狀態,您可以刪除該資源:

  1. 按一下「已加入佇列的資源」分頁標籤。
  2. 選取佇列中的資源要求旁邊的核取方塊。
  3. 按一下「刪除」圖示

Java

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.cloud.tpu.v2.DeleteNodeRequest;
import com.google.cloud.tpu.v2.NodeName;
import com.google.cloud.tpu.v2.TpuClient;
import com.google.cloud.tpu.v2.TpuSettings;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import org.threeten.bp.Duration;

public class DeleteTpuVm {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to create a node.
    String projectId = "YOUR_PROJECT_ID";
    // The zone in which to create the TPU.
    // For more information about supported TPU types for specific zones,
    // see https://cloud.google.com/tpu/docs/regions-zones
    String zone = "europe-west4-a";
    // The name for your TPU.
    String nodeName = "YOUR_TPU_NAME";

    deleteTpuVm(projectId, zone, nodeName);
  }

  // Deletes a TPU VM with the specified name in the given project and zone.
  public static void deleteTpuVm(String projectId, String zone, String nodeName)
      throws IOException, ExecutionException, InterruptedException {
    // With these settings the client library handles the Operation's polling mechanism
    // and prevent CancellationException error
    TpuSettings.Builder clientSettings =
        TpuSettings.newBuilder();
    clientSettings
        .deleteNodeOperationSettings()
        .setPollingAlgorithm(
            OperationTimedPollAlgorithm.create(
                RetrySettings.newBuilder()
                    .setInitialRetryDelay(Duration.ofMillis(5000L))
                    .setRetryDelayMultiplier(1.5)
                    .setMaxRetryDelay(Duration.ofMillis(45000L))
                    .setInitialRpcTimeout(Duration.ZERO)
                    .setRpcTimeoutMultiplier(1.0)
                    .setMaxRpcTimeout(Duration.ZERO)
                    .setTotalTimeout(Duration.ofHours(24L))
                    .build()));

    // 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 (TpuClient tpuClient = TpuClient.create(clientSettings.build())) {
      String name = NodeName.of(projectId, zone, nodeName).toString();

      DeleteNodeRequest request = DeleteNodeRequest.newBuilder().setName(name).build();

      tpuClient.deleteNodeAsync(request).get();
      System.out.println("TPU VM deleted");
    }
  }
}

刪除 TPU 時,相關聯的佇列資源會進入 SUSPENDING 狀態,然後進入 SUSPENDED 狀態。排入佇列的資源處於 SUSPENDED 狀態時,您可以刪除該資源:

import com.google.cloud.tpu.v2alpha1.DeleteQueuedResourceRequest;
import com.google.cloud.tpu.v2alpha1.TpuClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class DeleteQueuedResource {
  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project.
    String projectId = "YOUR_PROJECT_ID";
    // The zone in which the TPU was created.
    String zone = "us-central1-f";
    // The name for your Queued Resource.
    String queuedResourceId = "QUEUED_RESOURCE_ID";

    deleteQueuedResource(projectId, zone, queuedResourceId);
  }

  // Deletes a Queued Resource asynchronously.
  public static void deleteQueuedResource(String projectId, String zone, String queuedResourceId)
      throws ExecutionException, InterruptedException, IOException {
    String name = String.format("projects/%s/locations/%s/queuedResources/%s",
        projectId, zone, queuedResourceId);
    // 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 (TpuClient tpuClient = TpuClient.create()) {
      // Before deleting the queued resource it is required to delete the TPU VM.
      // For more information about deleting TPU
      // see https://cloud.google.com/tpu/docs/managing-tpus-tpu-vm

      DeleteQueuedResourceRequest request =
              DeleteQueuedResourceRequest.newBuilder().setName(name).build();

      tpuClient.deleteQueuedResourceAsync(request).get();
    }
  }
}

Python

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import tpu_v2

# TODO(developer): Update and un-comment below lines
# project_id = "your-project-id"
# zone = "us-central1-b"
# tpu_name = "tpu-name"

client = tpu_v2.TpuClient()
try:
    client.delete_node(
        name=f"projects/{project_id}/locations/{zone}/nodes/{tpu_name}"
    )
    print("The TPU node was deleted.")
except Exception as e:
    print(e)

刪除 TPU 時,相關聯的佇列資源會進入 SUSPENDING 狀態,然後進入 SUSPENDED 狀態。排入佇列的資源處於 SUSPENDED 狀態時,您可以刪除該資源:

from google.cloud import tpu_v2alpha1

# TODO(developer): Update and un-comment below lines
# project_id = "your-project-id"
# zone = "us-central1-b"
# queued_resource_name = "resource-name"

client = tpu_v2alpha1.TpuClient()
name = (
    f"projects/{project_id}/locations/{zone}/queuedResources/{queued_resource_name}"
)

try:
    op = client.delete_queued_resource(name=name)
    op.result()
    print(f"Queued resource '{queued_resource_name}' successfully deleted.")
except TypeError as e:
    print(f"Error deleting resource: {e}")
    print(f"Queued resource '{queued_resource_name}' successfully deleted.")

擷取佇列中資源要求的狀態和診斷資訊

擷取佇列中資源要求的狀態和診斷資訊:

gcloud

gcloud compute tpus queued-resources describe queued-resource-request-id \
    --project your-project-id \
    --zone us-central1-a

指令旗標說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
project
已分配佇列資源的專案 ID。
zone
您要建立 Cloud TPU 的區域

curl

curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://tpu.googleapis.com/v2/projects/your-project-id/locations/us-central1-a/queuedResources/your-queued-resource-id

指令旗標說明

queued-resource-request-id
使用者指派的佇列資源要求 ID。
project
已分配佇列資源的專案 ID。
zone
您要建立 Cloud TPU 的區域

控制台

  1. 前往 Google Cloud 控制台的「TPUs」頁面:

    前往 TPU

  2. 按一下「已加入佇列的資源」分頁標籤。

  3. 按一下已加入佇列的資源要求名稱。

佈建 TPU 後,您也可以前往「TPU」頁面,找出 TPU 並點選相應的佇列資源要求名稱,查看佇列資源要求的詳細資料。

Java

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import com.google.cloud.tpu.v2alpha1.GetQueuedResourceRequest;
import com.google.cloud.tpu.v2alpha1.QueuedResource;
import com.google.cloud.tpu.v2alpha1.TpuClient;
import java.io.IOException;

public class GetQueuedResource {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project.
    String projectId = "YOUR_PROJECT_ID";
    // The zone in which the TPU was created.
    String zone = "us-central1-f";
    // The name for your Queued Resource.
    String queuedResourceId = "QUEUED_RESOURCE_ID";

    getQueuedResource(projectId, zone, queuedResourceId);
  }

  // Get a Queued Resource.
  public static QueuedResource getQueuedResource(
      String projectId, String zone, String queuedResourceId) throws IOException {
    String name = String.format("projects/%s/locations/%s/queuedResources/%s",
        projectId, zone, queuedResourceId);
    // 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 (TpuClient tpuClient = TpuClient.create()) {
      GetQueuedResourceRequest request =
          GetQueuedResourceRequest.newBuilder().setName(name).build();

      return tpuClient.getQueuedResource(request);
    }
  }
}

Python

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import tpu_v2alpha1

# TODO(developer): Update and un-comment below lines
# project_id = "your-project-id"
# zone = "us-central1-b"
# queued_resource_name = "resource-name"

client = tpu_v2alpha1.TpuClient()
name = (
    f"projects/{project_id}/locations/{zone}/queuedResources/{queued_resource_name}"
)
resource = client.get_queued_resource(name=name)
print("Resource name:", resource.name)
print(resource.state)
# Example response:
# Resource name: projects/{project_id}/locations/{zone}/queuedResources/resource-name
# State.ACTIVE

如果要求失敗,輸出內容會包含錯誤資訊。如果要求正在等待資源,輸出內容會類似如下:

gcloud

    name: projects/your-project-id/locations/us-central1-a/queuedResources/your-queued-resource-id
    state:
    state: WAITING_FOR_RESOURCES
    tpu:
    nodeSpec:
    - node:
        acceleratorType: v4-8
        bootDisk: {}
        networkConfig:
            enableExternalIps: true
        queuedResource: projects/your-project-number/locations/us-central1-a/queuedResources/your-queued-resource-id
        runtimeVersion: v2-alpha-tpuv5-lite
        schedulingConfig: {}
        serviceAccount: {}
        shieldedInstanceConfig: {}
        useTpuVm: true
        nodeId: your-node-id
        parent: projects/your-project-number/locations/us-central1-a

控制台

「排入佇列的資源狀態」欄位會顯示「正在等待資源」

列出專案中已加入佇列的資源要求

列出專案中排入佇列的資源要求:

gcloud

gcloud compute tpus queued-resources list --project your-project-id \
    --zone us-central1-a

指令旗標說明

project
已分配佇列資源的專案 Google Cloud 。
zone
您要建立 Cloud TPU 的區域

curl

curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://tpu.googleapis.com/v2/projects/your-project-id/locations/your-zone/queuedResources

指令旗標說明

project
已分配佇列資源的專案 Google Cloud 。
zone
您要建立 Cloud TPU 的區域

控制台

  1. 前往 Google Cloud 控制台的「TPUs」頁面:

    前往 TPU

  2. 按一下「已加入佇列的資源」分頁標籤。

Java

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import com.google.cloud.tpu.v2alpha1.ListQueuedResourcesRequest;
import com.google.cloud.tpu.v2alpha1.QueuedResource;
import com.google.cloud.tpu.v2alpha1.TpuClient;
import com.google.cloud.tpu.v2alpha1.TpuClient.ListQueuedResourcesPage;
import java.io.IOException;

public class ListQueuedResources {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project.
    String projectId = "YOUR_PROJECT_ID";
    // The zone in which the TPU was created.
    String zone = "us-central1-a";

    listQueuedResources(projectId, zone);
  }

  // List Queued Resources.
  public static ListQueuedResourcesPage listQueuedResources(
      String projectId, String zone) throws IOException {
    String parent = String.format("projects/%s/locations/%s", projectId, zone);
    // 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 (TpuClient tpuClient = TpuClient.create()) {
      ListQueuedResourcesRequest request =
          ListQueuedResourcesRequest.newBuilder().setParent(parent).build();
      ListQueuedResourcesPage response =  tpuClient.listQueuedResources(request).getPage();

      for (QueuedResource queuedResource : response.iterateAll()) {
        System.out.println(queuedResource.getName());
      }
      return response;
    }
  }
}

Python

如要驗證 Cloud TPU,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import tpu_v2alpha1

# TODO(developer): Update and un-comment below lines
# project_id = "your-project-id"
# zone = "us-central1-b"

client = tpu_v2alpha1.TpuClient()
parent = f"projects/{project_id}/locations/{zone}"
resources = client.list_queued_resources(parent=parent)
for resource in resources:
    print("Resource name:", resource.name)
    print("TPU id:", resource.tpu.node_spec[0].node_id)
# Example response:
# Resource name: projects/{project_id}/locations/{zone}/queuedResources/resource-name
# TPU id: tpu-name