如何检查TPU在Google Colab中是否可用?

时间:2020-07-03 08:38:01

标签: google-colaboratory tensorflow2.0 tpu

我正在尝试根据TPU的可用性选择一种分发策略。

我的代码如下:

import tensorflow as tf
if tf.config.list_physical_devices('tpu'):
  resolver = tf.distribute.cluster_resolver.TPUClusterResolver()
  tf.config.experimental_connect_to_cluster(resolver)
  tf.tpu.experimental.initialize_tpu_system(resolver)
  print("All devices: ", tf.config.list_logical_devices('TPU'))
  strategy = tf.distribute.experimental.TPUStrategy(resolver)
else:  # use default strategy
  strategy = tf.distribute.get_strategy() 

但这不起作用。

如何识别TPU?

1 个答案:

答案 0 :(得分:2)

以下代码有效:

import tensorflow as tf
try:
  resolver = tf.distribute.cluster_resolver.TPUClusterResolver()
  tf.config.experimental_connect_to_cluster(resolver)
  tf.tpu.experimental.initialize_tpu_system(resolver)
  print("All devices: ", tf.config.list_logical_devices('TPU'))
  strategy = tf.distribute.experimental.TPUStrategy(resolver)
except ValueError:
  strategy = tf.distribute.get_strategy()