Cloud TPU VM 만들기

Create Node API, 큐에 추가된 리소스 API 또는 Google Kubernetes Engine (GKE)을 사용하여 TPU VM을 만듭니다.

Google Cloud CLI를 사용하여 gcloud compute tpus tpu-vm create 명령어를 실행할 때와Google Cloud 콘솔을 사용하여 TPU VM을 만들 때 Create Node API를 호출합니다. Create Node API를 사용하면 시스템에서 요청을 즉시 처리합니다. 요청을 처리할 수 있는 용량이 부족하면 요청이 실패합니다.

큐에 추가된 리소스 API를 사용하여 TPU VM을 만드는 것이 좋습니다. 큐에 추가된 리소스 API를 사용하여 TPU VM을 만들면 Cloud TPU 서비스에서 유지보수하는 큐에 큐에 추가된 리소스 요청이 추가됩니다. 요청된 리소스를 사용할 수 있게 되면 서비스에서 즉시 독점적으로 사용할 수 있도록 Google Cloud 프로젝트에 할당합니다. 자세한 내용은 큐에 추가된 리소스 관리를 참조하세요.

Google Kubernetes Engine (GKE)을 사용하여 TPU 리소스를 관리하려면 먼저 GKE 클러스터를 만드세요. 그런 다음 TPU 슬라이스가 포함된 노드 풀을 클러스터에 추가합니다. 자세한 내용은 GKE의 TPU 정보를 참조하세요.

기본 요건

다음 기본 요건을 완료합니다.

  1. TPU용 Google Cloud 프로젝트 설정에 설명된 대로 TPU용 Google Cloud 프로젝트를 만듭니다.

  2. Cloud TPU 리소스 계획에 설명된 대로 TPU 요구사항을 확인합니다.

  3. Cloud 클라이언트 라이브러리 중 하나를 사용하는 경우 사용 중인 언어에 대한 설정 안내를 따릅니다.

  4. 칩 8개가 있는 v5e TPU를 만들기 위한 환경 변수를 설정합니다. 다음 예시에서는 칩이 8개인 v5e TPU를 사용합니다. 다른 가속기 유형과 버전을 지정할 수 있습니다. 자세한 내용은 TPU 버전을 참고하세요.

      export TPU_NAME=your-tpu-name
      export PROJECT_ID=your-project
      export ZONE=us-central1-a
      export ACCELERATOR_TYPE=v5litepod-8
      export VERSION=v2-alpha-tpuv5-lite
    

Create Node API를 사용하여 Cloud TPU 만들기

gcloud, Google Cloud 콘솔 또는 Cloud TPU API를 사용하여 Cloud TPU를 만듭니다.

Cloud TPU를 만들 때 TPU 소프트웨어 버전 (런타임 버전이라고도 함)을 지정합니다. 사용할 소프트웨어 버전을 확인하려면 TPU 소프트웨어 버전을 참고하세요.

또한 사용 중인 TPU 구성의 TensorCore 또는 TPU 칩 수를 지정합니다. 자세한 내용은 시스템 아키텍처에서 사용 중인 TPU 버전 섹션을 참고하세요.

gcloud

gcloud compute tpus tpu-vm create 명령어를 사용하여 Create Node API를 통해 TPU를 만듭니다. 외부 및 내부 IP 주소를 참고하여 특정 내부 또는 외부 IP 주소를 구성하세요.

다음 명령어는 TPU 칩이 8개인 v5e TPU VM을 만듭니다.

gcloud compute tpus tpu-vm create $TPU_NAME \
  --project=$PROJECT_ID
  --zone=$ZONE \
  --accelerator-type=$ACCELERATOR_TYPE \
  --version=$VERSION

명령어 플래그 설명

zone
Cloud TPU를 만드는 영역입니다.
accelerator-type
가속기 유형은 만들려는 Cloud TPU의 버전과 크기를 지정합니다. 각 TPU 버전에서 지원되는 액셀러레이터 유형에 대한 자세한 내용은 TPU 버전을 참고하세요.
version
TPU 소프트웨어 버전입니다.

콘솔

다음 안내에서는 TPU 칩이 8개인 v5e TPU VM을 만듭니다.

  1. Google Cloud 콘솔에서 TPU 페이지로 이동합니다.

    TPU로 이동

  2. TPU 만들기를 클릭합니다.

  3. 이름 필드에 TPU 이름을 입력합니다.

  4. 영역 필드에서 TPU를 만들 영역을 선택합니다.

  5. TPU 유형 필드에서 가속기 유형을 선택합니다. 액셀러레이터 유형은 만들려는 Cloud TPU의 버전과 크기를 지정합니다. TPU 버전마다 지원되는 액셀러레이터 유형에 대한 자세한 내용은 TPU 버전을 참조하세요.

  6. TPU 소프트웨어 버전 필드에서 소프트웨어 버전을 선택합니다. Cloud TPU VM을 만들 때 TPU 소프트웨어 버전은 설치할 TPU 런타임 버전을 지정합니다. 자세한 내용은 TPU 소프트웨어 버전을 참조하세요.

  7. 만들기를 클릭하여 리소스를 만듭니다.

curl

다음 명령어는 curl을 사용하여 TPU 칩이 8개인 v5e TPU VM을 만듭니다.

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json" -d "{accelerator_type: $ACCELERATOR_TYPE, \
runtime_version:'$VERSION', \
network_config: {enable_external_ips: true}, \
shielded_instance_config: { enable_secure_boot: true }}" \
https://tpu.googleapis.com/v2/projects/$PROJECT_ID/locations/$ZONE/nodes?node_id=$TPU_NAME

필수 입력란

runtime_version
사용하는 Cloud TPU 런타임 버전입니다.
project-id
등록된 Google Cloud 프로젝트의 이름입니다.
zone
Cloud TPU를 만드는 영역입니다.
node_name
만들려는 TPU VM의 이름입니다.

자바

이 코드 예시에서는 Java의 Cloud TPU API를 사용하여 TPU 칩이 8개인 v5e TPU VM을 만듭니다.

Cloud TPU에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.cloud.tpu.v2.CreateNodeRequest;
import com.google.cloud.tpu.v2.Node;
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 CreateTpuVm {

  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 = "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 tpuSoftwareVersion = "v2-tpuv5-litepod";

    createTpuVm(projectId, zone, nodeName, tpuType, tpuSoftwareVersion);
  }

  // Creates a TPU VM with the specified name, zone, accelerator type, and version.
  public static Node createTpuVm(
      String projectId, String zone, String nodeName, String tpuType, String tpuSoftwareVersion)
      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
        .createNodeOperationSettings()
        .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 parent = String.format("projects/%s/locations/%s", projectId, zone);

      Node tpuVm = Node.newBuilder()
              .setName(nodeName)
              .setAcceleratorType(tpuType)
              .setRuntimeVersion(tpuSoftwareVersion)
              .build();

      CreateNodeRequest request = CreateNodeRequest.newBuilder()
              .setParent(parent)
              .setNodeId(nodeName)
              .setNode(tpuVm)
              .build();

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

Node.js

이 코드 예시에서는 Node.js의 Cloud TPU API를 사용하여 TPU 칩이 8개인 v5e TPU VM을 만듭니다.

Cloud TPU에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Import the TPUClient
// TODO(developer): Uncomment below line before running the sample.
// const {TpuClient} = require('@google-cloud/tpu').v2;
const {Node, NetworkConfig} =
  require('@google-cloud/tpu').protos.google.cloud.tpu.v2;

// Instantiate a tpuClient
// TODO(developer): Uncomment below line before running the sample.
// tpuClient = new TpuClient();

// TODO(developer): Update below line before running the sample.
// Project ID or project number of the Google Cloud project you want to create a node.
const projectId = await tpuClient.getProjectId();

// The name of the network you want the TPU node to connect to. The network should be assigned to your project.
const networkName = 'compute-tpu-network';

// The region of the network, that you want the TPU node to connect to.
const region = 'europe-west4';

// The name for your TPU.
const nodeName = 'node-name-1';

// 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
const zone = 'europe-west4-a';

// 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.
const 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
const tpuSoftwareVersion = 'v2-tpuv5-litepod';

async function callCreateTpuVM() {
  // Create a node
  const node = new Node({
    name: nodeName,
    zone,
    acceleratorType: tpuType,
    runtimeVersion: tpuSoftwareVersion,
    // Define network
    networkConfig: new NetworkConfig({
      enableExternalIps: true,
      network: `projects/${projectId}/global/networks/${networkName}`,
      subnetwork: `projects/${projectId}/regions/${region}/subnetworks/${networkName}`,
    }),
  });

  const parent = `projects/${projectId}/locations/${zone}`;
  const request = {parent, node, nodeId: nodeName};

  const [operation] = await tpuClient.createNode(request);

  // Wait for the create operation to complete.
  const [response] = await operation.promise();

  console.log(`TPU VM: ${nodeName} created.`);
  return response;
}
return await callCreateTpuVM();

Python

이 코드 예시에서는 Python의 Cloud TPU API를 사용하여 TPU 칩이 8개인 v5e TPU VM을 만듭니다.

Cloud TPU에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import tpu_v2

# 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"

# Create a TPU node
node = tpu_v2.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

request = tpu_v2.CreateNodeRequest(
    parent=f"projects/{project_id}/locations/{zone}",
    node_id=tpu_name,
    node=node,
)

# Create a TPU client
client = tpu_v2.TpuClient()
operation = client.create_node(request=request)
print("Waiting for operation to complete...")

response = operation.result()
print(response)
# Example response:
# name: "projects/[project_id]/locations/[zone]/nodes/my-tpu"
# accelerator_type: "v5litepod-4"
# state: READY
# ...

시작 스크립트 실행

TPU VM을 만들 때 --metadata startup-script 플래그를 지정하여 TPU VM에서 시작 스크립트를 실행합니다.

gcloud

이 명령어는 TPU VM을 만들고 시작 스크립트를 지정합니다.

gcloud compute tpus tpu-vm create $TPU_NAME \
  --zone=$ZONE \
  --accelerator-type=$ACCELERATOR_TYPE \
  --version=$VERSION \
  --metadata startup-script='#! /bin/bash
     pip3 install numpy
     EOF'

자바

이 코드 예시에서는 TPU VM을 만들고 Java에서 시작 스크립트를 지정합니다.

Cloud TPU에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.cloud.tpu.v2.CreateNodeRequest;
import com.google.cloud.tpu.v2.Node;
import com.google.cloud.tpu.v2.TpuClient;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class CreateTpuVmWithStartupScript {
  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 acceleratorType = "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";

    createTpuVmWithStartupScript(projectId, zone, nodeName, acceleratorType, tpuSoftwareVersion);
  }

  // Create a TPU VM with a startup script.
  public static Node createTpuVmWithStartupScript(String projectId, String zone,
      String nodeName, String acceleratorType, 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 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);

      Node tpuVm =
          Node.newBuilder()
             .setName(nodeName)
             .setAcceleratorType(acceleratorType)
             .setRuntimeVersion(tpuSoftwareVersion)
             .putAllMetadata(metadata)
             .build();

      CreateNodeRequest request =
          CreateNodeRequest.newBuilder()
             .setParent(parent)
             .setNodeId(nodeName)
             .setNode(tpuVm)
             .build();

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

Node.js

이 코드 예시에서는 TPU VM을 만들고 Node.js에서 시작 스크립트를 지정합니다.

Cloud TPU에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Import the TPUClient
// TODO(developer): Uncomment below line before running the sample.
// const {TpuClient} = require('@google-cloud/tpu').v2;

const {Node, NetworkConfig} =
  require('@google-cloud/tpu').protos.google.cloud.tpu.v2;

// Instantiate a tpuClient
// TODO(developer): Uncomment below line before running the sample.
// tpuClient = new TpuClient();

// TODO(developer): Update these variables before running the sample.
// Project ID or project number of the Google Cloud project you want to create a node.
const projectId = await tpuClient.getProjectId();

// The name of the network you want the TPU node to connect to. The network should be assigned to your project.
const networkName = 'compute-tpu-network';

// The region of the network, that you want the TPU node to connect to.
const region = 'europe-west4';

// The name for your TPU.
const nodeName = 'node-name-1';

// 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
const zone = 'europe-west4-a';

// 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.
const 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
const tpuSoftwareVersion = 'v2-tpuv5-litepod';

async function callCreateTpuVMStartupScript() {
  // Create a node
  const node = new Node({
    name: nodeName,
    zone,
    acceleratorType: tpuType,
    runtimeVersion: tpuSoftwareVersion,
    // Define network
    networkConfig: new NetworkConfig({
      enableExternalIps: true,
      network: `projects/${projectId}/global/networks/${networkName}`,
      subnetwork: `projects/${projectId}/regions/${region}/subnetworks/${networkName}`,
    }),
    metadata: {
      // The script updates numpy to the latest version and logs the output to a file.
      'startup-script': `#!/bin/bash
        echo "Hello World" > /var/log/hello.log
        sudo pip3 install --upgrade numpy >> /var/log/hello.log 2>&1`,
    },
  });

  const parent = `projects/${projectId}/locations/${zone}`;
  const request = {parent, node, nodeId: nodeName};

  const [operation] = await tpuClient.createNode(request);

  // Wait for the create operation to complete.
  const [response] = await operation.promise();

  console.log(JSON.stringify(response));
  return response;
}
return await callCreateTpuVMStartupScript();

Python

이 코드 예시에서는 TPU VM을 만들고 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-a"
# tpu_name = "tpu-name"
# tpu_type = "v5litepod-4"
# runtime_version = "v2-tpuv5-litepod"

node = tpu_v2.Node()
node.accelerator_type = tpu_type
node.runtime_version = runtime_version

# This startup script updates numpy to the latest version and logs the output to a file.
metadata = {
    "startup-script": """#!/bin/bash
echo "Hello World" > /var/log/hello.log
sudo pip3 install --upgrade numpy >> /var/log/hello.log 2>&1
"""
}

# Adding metadata with startup script to the TPU node.
node.metadata = metadata
# Enabling external IPs for internet access from the TPU node.
node.network_config = tpu_v2.NetworkConfig(enable_external_ips=True)

request = tpu_v2.CreateNodeRequest(
    parent=f"projects/{project_id}/locations/{zone}",
    node_id=tpu_name,
    node=node,
)

client = tpu_v2.TpuClient()
operation = client.create_node(request=request)
print("Waiting for operation to complete...")

response = operation.result()
print(response.metadata)
# Example response:
# {'startup-script': '#!/bin/bash\n    echo "Hello World" > /var/log/hello.log\n
# ...

다음 단계