python - 使用分布式策略在 Colab TPU 上训练模型

标签 python tensorflow tensorflow2.0 distributed-computing tpu

我正在尝试使用 TPU 在 Colab 上训练和运行图像分类模型。没有 torch 。

我知道 TPU 仅适用于 GCS 存储桶中的文件,因此我从存储桶中加载数据集,并且还评论了检查点和日志记录功能,以免出现此类错误。我只是想看看它在 TPU 上训练时没有错误。

在 CPU 和 GPU 上,代码可以工作,但是当我在创建模型之前使用 withstrategy.scope(): 时,就会出现问题。 这是在训练模型时给我带来问题的函数:

def train_step(self, images, labels):
    with tf.GradientTape() as tape:
        predictionProbs = self(images, training=True)
        loss = self.loss_fn(labels, predictionProbs)

    grads = tape.gradient(loss, self.trainable_weights)

    predictionLabels = tf.squeeze(tf.cast(predictionProbs > PROB_THRESHOLD_POSITIVE, tf.float32), axis=1)
    acc = tf.reduce_mean(tf.cast(predictionLabels == labels, tf.float32))

    self.optimizer.apply_gradients(zip(grads, self.trainable_weights)) # here is the problem

    return loss, acc

这是我遇到的错误:

RuntimeError: `apply_gradients() cannot be called in cross-replica context. Use `tf.distribute.Strategy.run` to enter replica context.

我看过https://www.tensorflow.org/api_docs/python/tf/distribute/Strategy我认为这是解决方案,但我以前从未这样做过,而且我不知道从哪里开始。

有人可以就这个问题给我建议吗?

最佳答案

您必须使用strategy.run()调用此过程:

strategy.run(train_step, args=(images, labels))

关于python - 使用分布式策略在 Colab TPU 上训练模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65251058/

相关文章:

python - 如何使用 Python 删除部分 XML 数据并将其写入新文件

java - Java 和 Python 中的数据结构及其实现 : Lists, 数组、元组

python - 无法正确保留多对多关系

linux - 无法安装 Go Tensorflow

python-3.x - Tensorflow 2.1 全内存和 tf.function 调用两次

python-3.x - python 3 : How to evaluate the Adam Gradient in Tensor Flow 2. 0?我想替换我的实现

python - 如何将字符串分解为列表?

python - 在TensorFlow中评估CIFAR-10时如何获得类别概率?

python - 如何使用 Google Colab 安装 vizdoom?

python - tensorflow 2.0 中是否有 cudnnLSTM 或 cudNNGRU 替代方案