Administra recursos de TPU

En esta página, se describe cómo crear, enumerar, detener, iniciar, borrar y conectarse a las TPU de Cloud con la API de Create Node. Se llama a la API de Create Node cuando ejecutas el comando gcloud compute tpus tpu-vm create con Google Cloud CLI y cuando creas una TPU con la consola de Google Cloud. Cuando usas la API de Create Node, tu solicitud se procesa de inmediato. Si no hay suficiente capacidad para completar la solicitud, esta fallará.

La práctica recomendada es crear TPU con recursos en cola en lugar de la API de Create Node. Cuando se solicitan recursos en cola, la solicitud se agrega a una cola que mantiene el servicio de Cloud TPU. Cuando el recurso solicitado esté disponible, se asignará a tu Google Cloud proyecto para que lo uses de forma exclusiva de inmediato. Para obtener más información, consulta Administra recursos en cola.

Cuando usas Multislice, debes usar recursos en cola. Para obtener más información, consulta Introducción a Multislice.

Si quieres usar Google Kubernetes Engine (GKE) para administrar recursos de TPU, primero debes crear un clúster de GKE. Luego, agregas grupos de nodos que contienen porciones de TPU a tu clúster. Para obtener más información, consulta Acerca de las TPU en GKE.

Requisitos previos

Antes de ejecutar estos procedimientos, debes instalar Google Cloud CLI, crear un proyecto de Google Cloud y habilitar la API de Cloud TPU. Para obtener instrucciones, consulta Configura el entorno de Cloud TPU.

Si usas Google Cloud CLI, puedes ejecutar comandos con Cloud Shell, una VM de Compute Engine o tu máquina local. Cloud Shell te permite interactuar con Cloud TPU sin tener que instalar ningún software. Cloud Shell se desconecta después de un período de inactividad. Si ejecutas comandos de larga duración, te recomendamos que instales Google Cloud CLI en tu máquina local. Para obtener más información sobre Google Cloud CLI, consulta la referencia de gcloud.

Crea una Cloud TPU con la API de Create Node

Puedes crear una Cloud TPU con gcloud, la consola de Google Cloud o la API de Cloud TPU.

Cuando creas una Cloud TPU, debes especificar la imagen de la VM de TPU (también llamada versión de software de TPU). Para determinar qué imagen de VM debes usar, consulta Imágenes de VM de TPU.

También debes especificar la configuración de TPU en términos de TensorCores o chips TPU. Para obtener más información, consulta la sección de la versión de TPU que usas en Arquitectura del sistema.

gcloud

Para crear una TPU con la API de Create Node, usa el comando gcloud compute tpus tpu-vm create. Para configurar direcciones IP internas o externas específicas, consulta las instrucciones en Direcciones IP internas y externas.

El siguiente comando usa una configuración de TPU v4-8:

$ gcloud compute tpus tpu-vm create tpu-name \
  --zone=us-central2-b \
  --accelerator-type=v4-8 \
  --version=tpu-software-version

Descripciones de las marcas de comandos

zone
Es la zona en la que deseas crear la Cloud TPU.
accelerator-type
El tipo de acelerador especifica la versión y el tamaño de la Cloud TPU que deseas crear. Para obtener más información sobre los tipos de aceleradores compatibles con cada versión de TPU, consulta Versiones de TPU.
version
La versión del software de la TPU.
shielded-secure-boot (opcional)
Especifica que las instancias de TPU se crean con el inicio seguro habilitado. Esto las convierte implícitamente en instancias de VM protegidas. Consulta ¿Qué es una VM protegida? para obtener más detalles.

El siguiente comando crea una TPU con una topología específica:

$ gcloud compute tpus tpu-vm create tpu-name \
  --zone=us-central2-b \
  --type=v4 \
  --topology=2x2x1 \
  --version=tpu-software-version

Marcas obligatorias

tpu-name
Es el nombre de la VM de TPU que estás creando.
zone
Es la zona en la que estás creando la Cloud TPU.
type
La versión de TPU que deseas usar. Para obtener más información, consulta Versiones de TPU.
topology
La disposición física de los chips TPU, que especifica la cantidad de chips en cada dimensión. Para obtener más información sobre las topologías compatibles para cada versión de TPU, consulta Versiones de TPU.
version
La versión del software de TPU que quieres usar. Para obtener más información, consulta Versiones de software de TPU.

Console

  1. En la consola de Google Cloud, ve a la página TPUs:

    Ve a TPUs

  2. Haz clic en Crear TPU.

  3. En el campo Nombre, ingresa un nombre para tu TPU.

  4. En el cuadro Zona, selecciona la zona en la que deseas crear la TPU.

  5. En el cuadro Tipo de TPU, selecciona un tipo de acelerador. El tipo de acelerador especifica la versión y el tamaño de la Cloud TPU que deseas crear. Para obtener más información sobre los tipos de aceleradores compatibles con cada versión de TPU, consulta Versiones de TPU.

  6. En el cuadro Versión de software de TPU, selecciona una versión de software. Cuando creas una VM de Cloud TPU, la versión del software de TPU especifica la versión del entorno de ejecución de TPU que se instalará. Para obtener más información, consulta Imágenes de VM de TPU.

  7. Haz clic en Crear para crear tus recursos.

curl

El siguiente comando usa curl para crear una TPU.

$ curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json" -d "{accelerator_type: 'v4-8', \
runtime_version:'tpu-vm-tf-2.18.0-pjrt', \
network_config: {enable_external_ips: true}, \
shielded_instance_config: { enable_secure_boot: true }}" \
https://tpu.googleapis.com/v2/projects/project-id/locations/us-central2-b/nodes?node_id=node_name

Campos obligatorios

runtime_version
La versión del entorno de ejecución de Cloud TPU que deseas usar.
project
El nombre de tu proyecto Google Cloud inscrito.
zone
Es la zona en la que creas la Cloud TPU.
node_name
Es el nombre de la VM de TPU que creas.

Java

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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 = "tpu-vm-tf-2.14.1";

    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

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// 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 = '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
const tpuSoftwareVersion = 'tpu-vm-tf-2.14.1';

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

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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"
# tpu_type = "v2-8"
# runtime_version = "tpu-vm-tf-2.17.0-pjrt"

# 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: "v2-8"
# state: READY
# ...

Ejecuta una secuencia de comandos de inicio

gcloud

Para ejecutar una secuencia de comandos de inicio en cada VM de TPU, especifica la marca --metadata startup-script cuando crees la VM de TPU. Con el siguiente comando, se crea una VM de TPU con una secuencia de comandos de inicio.

$ gcloud compute tpus tpu-vm create tpu-name \
  --zone=us-central2-b \
  --accelerator-type=tpu-type \
  --version=tpu-vm-tf-2.18.0-pjrt \
  --metadata startup-script='#! /bin/bash
     pip3 install numpy
     EOF'

Java

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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-f";
    // 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 = "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 = "tpu-vm-tf-2.14.1";

    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

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// 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 = '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
const tpuSoftwareVersion = 'tpu-vm-tf-2.17.0-pod-pjrt';

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

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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"
# tpu_type = "v2-8"
# runtime_version = "tpu-vm-tf-2.17.0-pjrt"

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

Cómo conectarse a una Cloud TPU

gcloud

Conéctate a tu Cloud TPU con SSH:

$ gcloud compute tpus tpu-vm ssh tpu-name --zone=zone

Cuando solicitas una porción más grande que un solo host, Cloud TPU crea una VM de TPU para cada host. La cantidad de chips TPU por host depende de la versión de TPU.

Para instalar objetos binarios o ejecutar código, conéctate a cada VM de TPU con tpu-vm ssh command.

$ gcloud compute tpus tpu-vm ssh tpu-name

Para conectarte a una VM de TPU específica con SSH, usa la marca --worker que sigue un índice basado en 0:

$ gcloud compute tpus tpu-vm ssh tpu-name --worker=1

Para ejecutar un comando en todas las VMs de TPU con un solo comando, usa las marcas --worker=all y --command:

$ gcloud compute tpus tpu-vm ssh tpu-name \
  --project=your_project_ID \
  --zone=zone \
  --worker=all \
  --command='pip install "jax[tpu]==0.4.20" -f https://storage.googleapis.com/jax-releases/libtpu_releases.html'

En el caso de Multislice, puedes ejecutar un comando en una sola VM con el nombre de la TPU enumerada, con cada prefijo de porción y el número agregado. Para ejecutar un comando en todas las VMs de TPU en todas las porciones, usa las marcas --node=all, --worker=all y --command, con una marca opcional --batch-size.

$ gcloud compute tpus queued-resources ssh ${QUEUED_RESOURCE_ID} \
  --project=project_ID \
  --zone=zone \
  --node=all \
  --worker=all \
  --command='pip install "jax[tpu]==0.4.20" -f https://storage.googleapis.com/jax-releases/libtpu_releases.html' \
  --batch-size=4

Console

Para conectarte a tus TPU en la consola de Google Cloud, usa SSH en el navegador:

  1. En la consola de Google Cloud, ve a la página TPUs:

    Ve a TPUs

  2. En la lista de VMs de TPU, haz clic en SSH en la fila de la VM de TPU a la que deseas conectarte.

Cómo enumerar tus recursos de Cloud TPU

Puedes enumerar todas tus Cloud TPU en una zona especificada.

gcloud

$ gcloud compute tpus tpu-vm list --zone=zone

Console

En la consola de Google Cloud, ve a la página TPUs:

Ve a TPUs

Java

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import com.google.cloud.tpu.v2.ListNodesRequest;
import com.google.cloud.tpu.v2.TpuClient;
import java.io.IOException;

public class ListTpuVms {

  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 you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // The zone where the TPUs are located.
    // For more information about supported TPU types for specific zones,
    // see https://cloud.google.com/tpu/docs/regions-zones
    String zone = "us-central1-f";

    listTpuVms(projectId, zone);
  }

  // Lists TPU VMs in the specified zone.
  public static TpuClient.ListNodesPage listTpuVms(String projectId, String zone)
      throws IOException {
    // 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);

      ListNodesRequest request = ListNodesRequest.newBuilder().setParent(parent).build();

      return tpuClient.listNodes(request).getPage();
    }
  }
}

Node.js

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// Import the TPUClient
// TODO(developer): Uncomment below line before running the sample.
// const {TpuClient} = require('@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 retrive a list of TPU nodes.
const projectId = await tpuClient.getProjectId();

// The zone from which the TPUs are retrived.
const zone = 'europe-west4-a';

async function callTpuVMList() {
  const request = {
    parent: `projects/${projectId}/locations/${zone}`,
  };

  const [response] = await tpuClient.listNodes(request);

  return response;
}

return await callTpuVMList();

Python

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

from google.cloud import tpu_v2

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

client = tpu_v2.TpuClient()

nodes = client.list_nodes(parent=f"projects/{project_id}/locations/{zone}")
for node in nodes:
    print(node.name)
    print(node.state)
    print(node.accelerator_type)
# Example response:
# projects/[project_id]/locations/[zone]/nodes/node-name
# State.READY
# v2-8

Recupera información sobre tu Cloud TPU

Puedes recuperar información sobre una Cloud TPU especificada.

gcloud

$ gcloud compute tpus tpu-vm describe tpu-name \
  --zone=zone

Console

  1. En la consola de Google Cloud, ve a la página TPUs:

    Ve a TPUs

  2. Haz clic en el nombre de tu Cloud TPU. En la consola, se muestra la página de detalles de Cloud TPU.

Java

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import com.google.cloud.tpu.v2.GetNodeRequest;
import com.google.cloud.tpu.v2.Node;
import com.google.cloud.tpu.v2.NodeName;
import com.google.cloud.tpu.v2.TpuClient;
import java.io.IOException;

public class GetTpuVm {

  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 you want to use.
    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";

    getTpuVm(projectId, zone, nodeName);
  }

  // Describes a TPU VM with the specified name in the given project and zone.
  public static Node getTpuVm(String projectId, String zone, String nodeName)
      throws IOException {
    // 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 name = NodeName.of(projectId, zone, nodeName).toString();

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

      return tpuClient.getNode(request);
    }
  }
}

Node.js

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// Import the TPUClient
// TODO(developer): Uncomment below line before running the sample.
// const {TpuClient} = require('@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 retrive a node.
const projectId = await tpuClient.getProjectId();

// The name of TPU to retrive.
const nodeName = 'node-name-1';

// The zone, where the TPU is created.
const zone = 'europe-west4-a';

async function callGetTpuVM() {
  const request = {
    name: `projects/${projectId}/locations/${zone}/nodes/${nodeName}`,
  };

  const [response] = await tpuClient.getNode(request);

  console.log(`Node: ${nodeName} retrived.`);
  return response;
}

return await callGetTpuVM();

Python

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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()
node = client.get_node(
    name=f"projects/{project_id}/locations/{zone}/nodes/{tpu_name}"
)

print(node)
# Example response:
# name: "projects/[project_id]/locations/[zone]/nodes/tpu-name"
# state: "READY"
# runtime_version: ...

Detén tus recursos de Cloud TPU

Puedes detener una sola Cloud TPU para dejar de generar cargos sin perder la configuración ni el software de tu VM.

gcloud

$ gcloud compute tpus tpu-vm stop tpu-name \
  --zone=zone

Console

  1. En la consola de Google Cloud, ve a la página TPUs:

    Ve a TPUs

  2. Selecciona la casilla de verificación junto a tu Cloud TPU.

  3. Haz clic en Detener.

Java

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import com.google.cloud.tpu.v2.Node;
import com.google.cloud.tpu.v2.NodeName;
import com.google.cloud.tpu.v2.StopNodeRequest;
import com.google.cloud.tpu.v2.TpuClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class StopTpuVm {

  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 use.
    String projectId = "YOUR_PROJECT_ID";
    // The zone where the TPU is located.
    // For more information about supported TPU types for specific zones,
    // see https://cloud.google.com/tpu/docs/regions-zones
    String zone = "us-central1-f";
    // The name for your TPU.
    String nodeName = "YOUR_TPU_NAME";

    stopTpuVm(projectId, zone, nodeName);
  }

  // Stops a TPU VM with the specified name in the given project and zone.
  public static Node stopTpuVm(String projectId, String zone, String nodeName)
      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 name = NodeName.of(projectId, zone, nodeName).toString();

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

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

Node.js

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// Import the TPUClient
// TODO(developer): Uncomment below line before running the sample.
// const {TpuClient} = require('@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 stop a node.
const projectId = await tpuClient.getProjectId();

// The name of TPU to stop.
const nodeName = 'node-name-1';

// The zone, where the TPU is created.
const zone = 'europe-west4-a';

async function callStopTpuVM() {
  const request = {
    name: `projects/${projectId}/locations/${zone}/nodes/${nodeName}`,
  };

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

  console.log(`Node: ${nodeName} stopped.`);
  return response;
}

return await callStopTpuVM();

Python

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

request = tpu_v2.StopNodeRequest(
    name=f"projects/{project_id}/locations/{zone}/nodes/{tpu_name}",
)
try:
    operation = client.stop_node(request=request)
    print("Waiting for stop operation to complete...")
    response = operation.result()
    print(f"This TPU {tpu_name} has been stopped")
    print(response.state)
    # Example response:
    # State.STOPPED

    return response
except Exception as e:
    print(e)

Inicia tus recursos de Cloud TPU

Puedes iniciar una Cloud TPU cuando está detenida.

gcloud

$ gcloud compute tpus tpu-vm start tpu-name \
  --zone=zone

Console

  1. En la consola de Google Cloud, ve a la página TPUs:

    Ve a TPUs

  2. Selecciona la casilla de verificación junto a tu Cloud TPU.

  3. Haz clic en Iniciar.

Java

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import com.google.cloud.tpu.v2.Node;
import com.google.cloud.tpu.v2.NodeName;
import com.google.cloud.tpu.v2.StartNodeRequest;
import com.google.cloud.tpu.v2.TpuClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class StartTpuVm {

  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 use.
    String projectId = "YOUR_PROJECT_ID";
    // The zone where the TPU is located.
    // For more information about supported TPU types for specific zones,
    // see https://cloud.google.com/tpu/docs/regions-zones
    String zone = "us-central1-f";
    // The name for your TPU.
    String nodeName = "YOUR_TPU_NAME";

    startTpuVm(projectId, zone, nodeName);
  }

  // Starts a TPU VM with the specified name in the given project and zone.
  public static Node startTpuVm(String projectId, String zone, String nodeName)
      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 name = NodeName.of(projectId, zone, nodeName).toString();

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

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

Node.js

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// Import the TPUClient
// TODO(developer): Uncomment below line before running the sample.
// const {TpuClient} = require('@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 start a node.
const projectId = await tpuClient.getProjectId();

// The name of TPU to start.
const nodeName = 'node-name-1';

// The zone, where the TPU is created.
const zone = 'europe-west4-a';

async function callStartTpuVM() {
  const request = {
    name: `projects/${projectId}/locations/${zone}/nodes/${nodeName}`,
  };

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

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

  console.log(`Node: ${nodeName} started.`);
  return response;
}

return await callStartTpuVM();

Python

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

request = tpu_v2.StartNodeRequest(
    name=f"projects/{project_id}/locations/{zone}/nodes/{tpu_name}",
)
try:
    operation = client.start_node(request=request)
    print("Waiting for start operation to complete...")
    response = operation.result()
    print(f"TPU {tpu_name} has been started")
    print(response.state)
    # Example response:
    # State.READY

    return response
except Exception as e:
    print(e)

Cómo borrar una Cloud TPU

Borra las porciones de tu VM de TPU al final de la sesión.

gcloud

$ gcloud compute tpus tpu-vm delete tpu-name \
  --project=project-id \
  --zone=zone \
  --quiet

Descripciones de las marcas de comandos

zone
Es la zona en la que deseas borrar la Cloud TPU.

Console

  1. En la consola de Google Cloud, ve a la página TPUs:

    Ve a TPUs

  2. Selecciona la casilla de verificación junto a tu Cloud TPU.

  3. Haz clic en Borrar.

Java

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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");
    }
  }
}

Node.js

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// Import the TPUClient
// TODO(developer): Uncomment below line before running the sample.
// const {TpuClient} = require('@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 delete a node.
const projectId = await tpuClient.getProjectId();

// The name of TPU to delete.
const nodeName = 'node-name-1';

// The zone, where the TPU is created.
const zone = 'europe-west4-a';

async function callDeleteTpuVM() {
  const request = {
    name: `projects/${projectId}/locations/${zone}/nodes/${nodeName}`,
  };

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

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

  console.log(`Node: ${nodeName} deleted.`);
  return response;
}

return await callDeleteTpuVM();

Python

Para autenticarte en Cloud TPU, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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)