我曾经tf.contrib.tpu.keras_to_tpu_model
让我的代码能够在 TPU 上运行,但是完成一个 epoch 需要 170 小时,而 CPU 需要相同的时间,GPU 每个 epoch 只需要 40 小时。我试图调整批量大小,但没有任何改变。我已经测试过输入函数在 GPU 上运行时可能会占用 20% 的运行时间,所以我认为这可能不是主要原因。
这是我的代码:https ://github.com/WangHexie/DHNE/blob/master/src/hypergraph_embedding.py
在 colab 上运行:
- TPU:https ://colab.research.google.com/gist/WangHexie/30c385509f9cd93be747f04c39f039a4/tpu-error.ipynb
- GPU:<a href="https://colab.research.google.com/gist/WangHexie/5bfac53bf92ef0ad527f15ddbf8705e1/-gpu-ipynb.ipynb" rel="nofollow noreferrer">https://colab.research.google.com /gist/WangHexie/5bfac53bf92ef0ad527f15ddbf8705e1/-gpu-ipynb.ipynb
该模型:
def build_model(self):
self.inputs = [Input(shape=(self.options.dim_feature[i], ), name='input_{}'.format(i), dtype='float') for i in range(3)]
self.encodeds = [Dense(self.options.embedding_size[i], activation='tanh', name='encode_{}'.format(i))(self.inputs[i]) for i in range(3)]
self.decodeds = [Dense(self.options.dim_feature[i], activation='sigmoid', name='decode_{}'.format(i),
activity_regularizer = regularizers.l2(0.0))(self.encodeds[i]) for i in range(3)]
self.merged = concatenate(self.encodeds, axis=1)
self.hidden_layer = Dense(self.options.hidden_size, activation='tanh', name='full_connected_layer')(self.merged)
self.ouput_layer = Dense(1, activation='sigmoid', name='classify_layer')(self.hidden_layer)
self.model = Model(inputs=self.inputs, outputs=self.decodeds+[self.ouput_layer])
self.model.compile(optimizer=tf.train.AdamOptimizer(learning_rate=self.options.learning_rate),
loss=[self.sparse_autoencoder_error]*3+['binary_crossentropy'],
loss_weights=[self.options.alpha]*3+[1.0],
metrics=dict([('decode_{}'.format(i), 'mse') for i in range(3)]+[('classify_layer', 'accuracy')]))
self.model = tf.contrib.tpu.keras_to_tpu_model(
self.model,
strategy=tf.contrib.tpu.TPUDistributionStrategy(
tf.contrib.cluster_resolver.TPUClusterResolver(
tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
)
)
self.model.summary()