在Google Colab中使用相同的TPU模型进行训练和推理(预测)

时间:2019-01-27 07:47:26

标签: keras google-colaboratory google-cloud-tpu tpu google-notebook

我有这样的代码:

def getModel():
    model = Sequential()
    model.Add(...)
    .....
    model = tf.contrib.tpu.keras_to_tpu_model(model,
            strategy=tf.contrib.tpu.TPUDistributionStrategy(
            tf.contrib.cluster_resolver.TPUClusterResolver(tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
        ))
    model.compile(loss='mse',
                  optimizer=tf.train.AdamOptimizer(learning_rate=1e-3, ))
    return model

tpu_model = getModel()
## Main loop
    ....
    tpu_model.predict(states)
    tpu_model.fit(...)

请注意,我使用相同的tpu_model进行批量预测和培训。

tpu_model.predict()似乎工作正常,但是在运行tpu_model.fit(...)时会引发以下错误:

WARNING:tensorflow:tpu_model (from tensorflow.contrib.tpu.python.tpu.keras_support) is experimental and may change or be removed at any time, and without warning.
INFO:tensorflow:New input shapes; (re-)compiling: mode=infer (# of cores 8), [TensorSpec(shape=(4, 7), dtype=tf.float32, name='dense_6_input_10')]
INFO:tensorflow:Overriding default placeholder.
INFO:tensorflow:Remapping placeholder for dense_6_input
INFO:tensorflow:Started compiling
INFO:tensorflow:Finished compiling. Time elapsed: 1.464857578277588 secs
INFO:tensorflow:Setting weights on TPU model.
...
...
...
RuntimeError                              Traceback (most recent call last)
--> 101         history = tpu_model.fit(states, target_f, epochs=1, verbose=0)
    102         # Keeping track of loss
    103         loss = history.history['loss'][0]

/usr/local/lib/python3.6/dist-packages/tensorflow/contrib/tpu/python/tpu/keras_support.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
   1505                                   validation_split, validation_data, shuffle,
   1506                                   class_weight, sample_weight, initial_epoch,
-> 1507                                   steps_per_epoch, validation_steps, **kwargs)
   1508       finally:
   1509         self._numpy_to_infeed_manager_list = []

/usr/local/lib/python3.6/dist-packages/tensorflow/contrib/tpu/python/tpu/keras_support.py in _pipeline_fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
   1578         steps_name='steps_per_epoch',
   1579         steps=steps_per_epoch,
-> 1580         validation_split=validation_split)
   1581 
   1582     # Prepare validation data

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, steps, validation_split)
    990         x, y, sample_weight = next_element
    991     x, y, sample_weights = self._standardize_weights(x, y, sample_weight,
--> 992                                                      class_weight, batch_size)
    993     return x, y, sample_weights
    994 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in _standardize_weights(self, x, y, sample_weight, class_weight, batch_size)
   1036     if y is not None:
   1037       if not self.optimizer:
-> 1038         raise RuntimeError('You must compile a model before '
   1039                            'training/testing. '
   1040                            'Use `model.compile(optimizer, loss)`.')

RuntimeError: You must compile a model before training/testing. Use `model.compile(optimizer, loss)`.

从日志中可以看到,在TPU上似乎有两种模式可以运行:
1. mode=infer
2. mode=training

似乎两者不能同时完成。有什么办法解决吗?

我无法使用生成器,因为我正在进行强化学习,其中批次基于实时添加到列表中的实时样本进行动态采样,从中对批次进行采样,预测(并更改某些值)和进行训练。

2 个答案:

答案 0 :(得分:0)

我认为您可以执行以下操作:

  • 选择tensorflow keras Adam,并在get_update()中添加一些代码:
    如果self.iterations = 0:
    lr = 0
    其他:
    lr = self.lr
  • 使用这个自建的Adam,使用shape =(批量大小,您的其他形状)构建小的火车数据'data_for_graph_build'
  • 执行 tpu_model.fit(data_for_graph_build,epoch = 1,batch_size = batchsize)
  • 最后完成 tpu_model.predict(states) tpu_model.fit(...)

这似乎很棘手。我希望它能起作用。但可能会导致差异,因为优化器权重基于 data_for_graph_build

构建

答案 1 :(得分:-1)

通常,您会在致电fit之前先致电predict,因为fit会训练模型,而predict使用训练后的模型进行预测。看看这些Cloud TPU Tutorials并看看this guide以了解Keras API。