tensorflow - Keras:TPU 模型的所有操作都必须具有恒定的形状

标签 tensorflow keras google-colaboratory tpu google-cloud-tpu

我正在使用预训练的 keras 模型,我想在 Google Colaboratory 的 TPU 上运行它,但出现以下错误:

ValueError: Layer has a variable shape in a non-batch dimension. TPU models must have constant shapes for all operations.

You may have to specify 'input_length' for RNN/TimeDistributed layers.

Layer: Input shape: [(None, 128, 768), (None, 1)] Output shape: (None, None, 768)



我正在与 keras-xlnet 一起工作.据我了解,按照 here 的说明编译模型时,TPU 需要具有固定的批量大小。和 here .

模型从检查点加载:
from keras_xlnet import Tokenizer, load_trained_model_from_checkpoint, 
      ATTENTION_TYPE_BI

checkpoint_path = 'xlnet_cased_L-12_H-768_A-12'

tokenizer = Tokenizer(os.path.join(checkpoint_path, 'spiece.model'))
model = load_trained_model_from_checkpoint(
    config_path=os.path.join(checkpoint_path, 'xlnet_config.json'),
    checkpoint_path=os.path.join(checkpoint_path, 'xlnet_model.ckpt'),
    batch_size=BATCH_SIZE,
    memory_len=512,
    target_len=SEQ_LEN,
    in_train_phase=False,
    attention_type=ATTENTION_TYPE_BI,
    )
 model.summary()

然后编译模型(经过一些更改后):
from keras_bert import AdamWarmup, calc_train_steps

decay_steps, warmup_steps = calc_train_steps(
    y_train.shape[0],
    batch_size=BATCH_SIZE,
    epochs=EPOCHS,
    )


model.compile(
    AdamWarmup(decay_steps=decay_steps, warmup_steps=warmup_steps, lr=LR),
    loss='binary_crossentropy',
    )

然后,模型加载到TPU,出现错误:
tpu_address = 'grpc://' + os.environ['COLAB_TPU_ADDR']
    strategy = tf.contrib.tpu.TPUDistributionStrategy(
    tf.contrib.cluster_resolver.TPUClusterResolver(tpu=tpu_address)
    )

with tf.keras.utils.custom_object_scope(get_custom_objects()):
    tpu_model = tf.contrib.tpu.keras_to_tpu_model(model, strategy=strategy)

有没有办法可以在编译时修复我的批处理大小以消除上述错误?还是问题完全不同?

最佳答案

我同意这些评论 - 要使其正常工作,您需要将各种可变输出形状(例如无、无、768)调整为固定大小(第一个批次尺寸除外)。也许你可以用简单的填充来做到这一点。如果您可以遍历保存的模型层并将权重加载到您使用填充尺寸编写的新模型中,它甚至可以工作。我会说这比考虑 TPU 就绪版本已经可用更麻烦。

对于这个模型,我建议远离 Keras。官方的 TensorFlow XLNet 实现应该无需修改即可与 TPU 一起使用。它还带有预先训练好的检查点。 https://github.com/zihangdai/xlnet

它使用标准的 TPUEstimator 类将模型函数发送给 TPU 工作线程,因此您无需处理 tf.contrib.tpu.keras_to_tpu_model .

存储库中给出的示例可以在 colab 中运行,其中 $TPU_NAME$COLAB_TPU_ADDR并将预训练的检查点和 imdb 数据上传到 colab 可以访问的存储桶。

python run_classifier.py \
  --use_tpu=True \
  --tpu=${TPU_NAME} \
  --do_train=True \
  --do_eval=True \
  --eval_all_ckpt=True \
  --task_name=imdb \
  --data_dir=${IMDB_DIR} \
  --output_dir=${GS_ROOT}/proc_data/imdb \
  --model_dir=${GS_ROOT}/exp/imdb \
  --uncased=False \
  --spiece_model_file=${LARGE_DIR}/spiece.model \
  --model_config_path=${GS_ROOT}/${LARGE_DIR}/model_config.json \
  --init_checkpoint=${GS_ROOT}/${LARGE_DIR}/xlnet_model.ckpt \
  --max_seq_length=512 \
  --train_batch_size=32 \
  --eval_batch_size=8 \
  --num_hosts=1 \
  --num_core_per_host=8 \
  --learning_rate=2e-5 \
  --train_steps=4000 \
  --warmup_steps=500 \
  --save_steps=500 \
  --iterations=500

关于tensorflow - Keras:TPU 模型的所有操作都必须具有恒定的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58615546/

相关文章:

python - 当我尝试在 keras 模型中嵌入序列数据时,如何解决 'could not convert string to float:' 错误

google-colaboratory - 无法读取 google colaboratory 中的文件

python - 从另一个驱动器帐户将数据集导入google colab

python - 属性错误: 'Model' object has no attribute '_name' during input layer concatenation

tensorflow - 尝试使用 Keras 功能 API 构建 CNN 模型时图断开连接

validation - 训练准确性提高但验证准确性保持不变

python - 当调用像 Activation ('relu' )(X) 这样的类时,它实际上是如何工作的?

python - Talos 多 GPU 功能

c++ - 为 tensorflow c++ api session 选择特定的 gpu

google-colaboratory - 从谷歌colab研究中的多个工作表中提取数据