ものづくりのブログ

うちのネコを題材にしたものづくりができたらいいなと思っていろいろ奮闘してます。

TPU が使ってみたくて Google Colaboratory を使ってみる

Google ColaboratoryでTPUというものが使えるらしいので、使ってみました。

TPUとは

テンソル・プロセッシング・ユニット(Tensor processing unit、TPU)はGoogleが開発した機械学習に特化した特定用途向け集積回路(ASIC)です。
ja.wikipedia.org

Google Colaboratory とは

Google Colaboratory は教育や研究機関へ機械学習の普及を目的とした Google の研究プロジェクトの一つでです。Google アカウントがあれば無料で利用することができます。

使い方

Google Colaboratory を始めるには、以下のサイトにアクセスして、Google アカウントでログインするだけです。
colab.research.google.com

ログインすると以下のような画面が表示されます。

Google Colab で TPU を使ってみる

ノートブックのメニューバーから「編集」>「ノートブックの設定」をクリックします。

次に TPU を選択します。

TPU が設定できたかどうか確認するには以下のコードを実行します。

TPU でスクリプトを実行
import tensorflow as tf
try:
  tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection
  print('Running on TPU ', tpu.cluster_spec().as_dict()['worker'])
except ValueError:
  raise BaseException('ERROR: Not connected to a TPU runtime; please see the previous cell in this notebook for instructions!')

tf.config.experimental_connect_to_cluster(tpu)
tf.tpu.experimental.initialize_tpu_system(tpu)
tpu_strategy = tf.distribute.TPUStrategy(tpu) 

TPU が使われている場合以下のような表示になります。

GPU でスクリプトを実行

ちなみに GPU の場合は以下のような表示になります。

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