יצירת מכונות וירטואליות של Cloud TPU

כדי ליצור TPU VM, משתמשים ב-Create Node API, ב-queued resources API או ב-Google Kubernetes Engine ‏ (GKE).

אתם קוראים ל-Create Node API כשאתם מריצים את הפקודה gcloud compute tpus tpu-vm create באמצעות Google Cloud CLI, וכשאתם יוצרים TPU VM באמצעות מסוףGoogle Cloud . כשמשתמשים ב-Create Node API, המערכת מעבדת את הבקשה באופן מיידי. אם אין מספיק קיבולת כדי למלא את הבקשה, הבקשה נכשלת.

מומלץ ליצור TPU VM באמצעות ה-API של המשאבים בתור. כשיוצרים TPU VM באמצעות ה-API של המשאב בתור, שירות Cloud TPU מוסיף את הקצאת המשאבים שלכם לתור שהשירות מנהל. כשהמשאב המבוקש יהיה זמין, השירות יקצה אותו לפרויקט ב- Google Cloud לשימוש מיידי ובלעדי. מידע נוסף מופיע במאמר ניהול משאבים בתור.

כדי להשתמש ב-Google Kubernetes Engine ‏ (GKE) לניהול משאבי TPU, קודם צריך ליצור אשכול GKE. לאחר מכן, מוסיפים לאשכול מאגרי צמתים שמכילים פרוסות TPU. מידע נוסף זמין במאמר מידע על יחידות TPU ב-GKE.

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

מבצעים את הפעולות הבאות:

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

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

  3. אם אתם משתמשים באחת מספריות הלקוח ב-Cloud, פעלו לפי הוראות ההגדרה של השפה שבה אתם משתמשים:

  4. מגדירים משתני סביבה ליצירת TPU v5e עם שמונה צ'יפים. בדוגמאות הבאות נעשה שימוש ב-TPU v5e עם שמונה צ'יפים. אפשר לציין סוג וגרסה אחרים של מאיץ. מידע נוסף זמין במאמר גרסאות 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
    

יצירת Cloud TPU באמצעות Create Node API

אפשר ליצור Cloud TPU באמצעות gcloud, מסוף Google Cloud או Cloud TPU API.

כשיוצרים Cloud TPU, צריך לציין את גרסת התוכנה של ה-TPU (שנקראת גם גרסת זמן הריצה). כדי לקבוע באיזו גרסת תוכנה להשתמש, קראו את המאמר גרסאות תוכנה של TPU.

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

gcloud

משתמשים בפקודה gcloud compute tpus tpu-vm create כדי ליצור TPU באמצעות Create Node API. כדי להגדיר כתובות IP פנימיות או חיצוניות ספציפיות, קראו את המאמר כתובות IP חיצוניות ופנימיות.

הפקודה הבאה יוצרת מכונת TPU VM בגרסה v5e עם 8 שבבי TPU:

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

תיאורי דגלי הפקודות

zone
‫
התחום (zone) שבו יוצרים את ה-Cloud TPU.
accelerator-type
‫
סוג המאיץ מציין את הגרסה והגודל של ה-Cloud TPU שאתם יוצרים. למידע נוסף על סוגי המאיצים שנתמכים בכל גרסת TPU, ראו גרסאות TPU.
version
גרסת התוכנה של ה-TPU.

המסוף

ההוראות הבאות יוצרות TPU VM מסוג v5e עם 8 שבבי TPU:

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

    כניסה לדף TPUs

  2. לוחצים על Create TPU.

  3. בשדה Name, נותנים שם ל-TPU.

  4. בשדה Zone, בוחרים את האזור שבו יוצרים את ה-TPU.

  5. בשדה TPU type, בוחרים סוג מאיץ. סוג המאיץ מציין את הגרסה והגודל של ה-Cloud TPU שאתם יוצרים. למידע נוסף על סוגי המאיצים שנתמכים בכל גרסת TPU, ראו גרסאות TPU.

  6. בשדה TPU software version, בוחרים גרסת תוכנה. כשיוצרים מכונה וירטואלית של Cloud TPU, גרסת התוכנה של ה-TPU מציינת את גרסת סביבת זמן הריצה של ה-TPU שצריך להתקין. מידע נוסף זמין במאמר גרסאות תוכנה של TPU.

  7. לוחצים על Create כדי ליצור את המשאבים.

curl

הפקודה הבאה משתמשת ב-curl כדי ליצור מכונת TPU VM מסוג v5e עם 8 שבבי TPU.

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

דוגמת הקוד הבאה יוצרת מכונת TPU VM v5e עם 8 שבבי TPU באמצעות Cloud TPU API ב-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.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

דוגמת הקוד הזו יוצרת מכונת TPU VM בגרסה v5e עם 8 שבבי TPU באמצעות Cloud TPU API ב-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;
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

דוגמת הקוד הזו יוצרת מכונת TPU VM v5e עם 8 שבבי TPU באמצעות Cloud TPU API ב-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"
# 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'

Java

בדוגמת הקוד הבאה נוצרת TPU VM ומוגדר סקריפט לטעינה בזמן ההפעלה ב-Java.

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

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, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// 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, אתם צריכים להגדיר את 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"
# 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
# ...

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