ניהול משאבי TPU

בדף הזה מוסבר איך להציג רשימה של מכונות וירטואליות של TPU, לעצור, להפעיל ולמחוק אותן, ואיך להתחבר אליהן.

דרישות מוקדמות

לפני שמריצים את התהליכים האלה, צריך לבצע את השלבים הבאים:

  1. יוצרים Google Cloud פרויקט עבור ה-TPU כמו שמתואר במאמר בנושא הגדרת Google Cloud פרויקט ל-TPU.

  2. קובעים את הדרישות שלכם ל-TPU כמו שמתואר במאמר תכנון משאבי Cloud TPU.

  3. יוצרים TPU VM כמו שמתואר במאמר יצירת TPU VM.

  4. אם אתם משתמשים באחת מספריות הלקוח של הענן, אתם צריכים לפעול לפי הוראות ההגדרה של השפה שבה אתם משתמשים:

  5. מגדירים משתני סביבה.

      export TPU_NAME=your-tpu-name
      export ZONE=your-zone
    

התחברות ל-Cloud TPU

אפשר להתחבר ל-Cloud TPU באמצעות SSH.

אם אתם לא מצליחים להתחבר למכונה וירטואלית של TPU באמצעות SSH, יכול להיות שלמכונה הווירטואלית של TPU אין כתובת IP חיצונית. כדי לגשת למכונת TPU וירטואלית ללא כתובת IP חיצונית, פועלים לפי ההוראות במאמר התחברות למכונת TPU וירטואלית ללא כתובת IP ציבורית.

gcloud

מתחברים ל-Cloud TPU באמצעות SSH:

$ gcloud compute tpus tpu-vm ssh $TPU_NAME --zone=$ZONE

כשמבקשים פרוסת TPU גדולה יותר ממארח יחיד, Cloud TPU יוצר מכונת TPU וירטואלית לכל מארח. מספר שבבי ה-TPU בכל מארח תלוי בגרסת ה-TPU.

כדי להתקין קבצים בינאריים או להריץ קוד, מתחברים לכל TPU VM באמצעות tpu-vm ssh הפקודה.

$ gcloud compute tpus tpu-vm ssh $TPU_NAME --zone=$ZONE

כדי להתחבר למכונת TPU ספציפית באמצעות SSH, משתמשים בדגל --worker עם אינדקס מבוסס-0:

$ gcloud compute tpus tpu-vm ssh $TPU_NAME --zone=$ZONE --worker=1

כדי להריץ פקודה בכל מכונות ה-VM של TPU, משתמשים בדגלים --worker=all ו---command:

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

ב-Multislice, אפשר להריץ פקודה במכונה וירטואלית אחת באמצעות השם הממוספר של ה-TPU, עם קידומת של כל פרוסה והמספר שנוסף אליה. כדי להריץ פקודה בכל מכונות ה-TPU הווירטואליות בכל הפרוסות, משתמשים בדגלים --node=all, --worker=all ו---command, עם הדגל האופציונלי --batch-size.

$ gcloud compute tpus queued-resources ssh your-queued-resource-id \
  --zone=$ZONE \
  --node=all \
  --worker=all \
  --command='pip install jax[tpu] -f https://storage.googleapis.com/jax-releases/libtpu_releases.html' \
  --batch-size=4

כשמתחברים למכונות וירטואליות באמצעות Google Cloud CLI, מערכת Compute Engine יוצרת מפתח SSH קבוע.

המסוף

כדי להתחבר ל-TPU במסוף Google Cloud , משתמשים ב-SSH בדפדפן:

  1. נכנסים לדף TPUs במסוף Google Cloud .

    כניסה לדף TPUs

  2. ברשימת מכונות ה-TPU הווירטואליות, לוחצים על SSH בשורה של מכונת ה-TPU הווירטואלית שרוצים להתחבר אליה.

    כשמתחברים למכונות וירטואליות של TPU באמצעות Google Cloud המסוף, מערכת Compute Engine יוצרת מפתח SSH זמני.

הצגת רשימה של משאבי Cloud TPU

אפשר להציג רשימה של כל משאבי Cloud TPU באזור מסוים.

gcloud

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

המסוף

נכנסים לדף TPUs במסוף Google Cloud .

כניסה לדף TPUs

Java

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

אחזור מידע על Cloud TPU

אפשר לאחזר מידע על Cloud TPU ספציפי.

gcloud

$ gcloud compute tpus tpu-vm describe $TPU_NAME \
  --zone=$ZONE

המסוף

  1. נכנסים לדף TPUs במסוף Google Cloud .

    כניסה לדף TPUs

  2. לוחצים על השם של Cloud TPU. בדף הפרטים של Cloud TPU שמוצג במסוף:

Java

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

הפסקת משאבי Cloud TPU

אפשר להפסיק שימוש ב-Cloud TPU יחיד כדי להימנע מחיובים, בלי לאבד את הגדרות המכונה הווירטואלית והתוכנה שלו.

ה-API של queued resources לא תומך בהפסקת פרוסות TPU או יחידות TPU. כדי להפסיק את החיובים על יחידות TPU שהוקצו דרך ה-API של משאבים בתור, צריך למחוק את ה-TPU.

gcloud

$ gcloud compute tpus tpu-vm stop $TPU_NAME \
  --zone=$ZONE

המסוף

  1. נכנסים לדף TPUs במסוף Google Cloud .

    כניסה לדף TPUs

  2. מסמנים את התיבה לצד Cloud TPU.

  3. לוחצים על הפסקה.

Java

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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"

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

except Exception as e:
    print(e)
    raise e

הפעלת משאבי Cloud TPU

אפשר להפעיל Cloud TPU שהופסק.

ה-API של queued resources לא תומך בהפעלת TPU Pods או TPUs.

gcloud

$ gcloud compute tpus tpu-vm start $TPU_NAME \
  --zone=$ZONE

המסוף

  1. נכנסים לדף TPUs במסוף Google Cloud .

    כניסה לדף TPUs

  2. מסמנים את התיבה לצד Cloud TPU.

  3. לוחצים על התחלה.

Java

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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"

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

except Exception as e:
    print(e)
    raise e

מחיקה של Cloud TPU

מוחקים את חלקי ה-VM של TPU אחרי הסשן.

gcloud

$ gcloud compute tpus tpu-vm delete $TPU_NAME \
  --zone=$ZONE \
  --quiet

תיאורים של דגלי פקודות

  • zone: האזור שבו אתם מתכננים למחוק את Cloud TPU.
  • quiet: משבית את כל ההנחיות האינטראקטיביות כשמריצים פקודות ב-CLI של gcloud.

המסוף

  1. נכנסים לדף TPUs במסוף Google Cloud .

    כניסה לדף TPUs

  2. מסמנים את התיבה לצד Cloud TPU.

  3. לוחצים על מחיקה.

Java

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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

כדי לבצע אימות ב-Cloud TPU, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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)

המאמרים הבאים