在 Google Colab 中,是否有一种编程方法可以检查我连接到哪个运行时,例如 gpu 或 tpu 环境?

问题描述

在 Google Colab 中,是否有一种编程方法可以检查我连接到哪个运行时,例如 gpu 或 tpu 环境?

例如,我可以使用以下代码检查它是否在 tpu 运行时下。但是什么是“gpu”运行时?

导入操作系统

tpu_good_to_go = "COLAB_TPU_ADDR" in os.environ

解决方法

如果您的用例不使用 os 包,则以下响应提供详细信息。

colab 中的默认模式,您可以在其中看到通用 CPU(例如 /device:CPU:0)用作 Colab 中以下命令提供的信息。

          //1st part
          const searchBar = document.querySelector(".users .search input");
         searchBtn = document.querySelector(".users .search button");

         searchBtn.onclick = () => {
            searchBar.classList.toggle("active");
            searchBar.focus();
             searchBtn.classList.toggle("active");
          };    


         //2nd part
         setInterval(() => {
           console.log("habib");
            // let's start Ajax
              let xhr = new XMLHttpRequest(); //creating xml object
              xhr.open("GET","php/users.php",true);
              xhr.onload = () => {
                 if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status === 200) {
                        let data = xhr.response;
                         console.log(data);
                     }
                   }
              };
              // we have to send through ajax to php
             xhr.send();
       },500);

输出:

from tensorflow.python.client import device_lib
device_lib.list_local_devices()

您将运行时更改为 GPU 模式,在 Colab 中通过以下命令查看使用 TF 的 GPU 详细信息。

[name: "/device:CPU:0"
 device_type: "CPU"
 memory_limit: 268435456
 locality {
 }
 incarnation: 14923719279742952081]

输出:

from tensorflow.python.client import device_lib
device_lib.list_local_devices()
,

这样的事情应该可以工作:

import os

if(int(os.environ["COLAB_GPU"]) > 0):
  print("a GPU is connected.")
elif("COLAB_TPU_ADDR" in os.environ and os.environ["COLAB_TPU_ADDR"]):
  print("A TPU is connected.")
else:
  print("No accelerator is connected.")

您还可以像这样使用 tf.distribute.Strategy 组织您的代码以在 GPU/TPU 上运行:

# Detect hardware,return appropriate distribution strategy
try:
    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection
except ValueError:
    tpu = None

if tpu:
    tf.config.experimental_connect_to_cluster(tpu)
    tf.tpu.experimental.initialize_tpu_system(tpu)
    strategy = tf.distribute.experimental.TPUStrategy(tpu)
else:
    strategy = tf.distribute.MirroredStrategy() # works on GPU and multi-GPU

print("REPLICAS: ",strategy.num_replicas_in_sync)