【问题标题】:List index out of range when saving finetuned Tensorflow model保存微调的 Tensorflow 模型时列表索引超出范围
【发布时间】:2021-06-07 20:20:28
【问题描述】:

我正在尝试使用 Tensorflow 从 Huggingface 微调预训练的 BERT 模型。一切运行顺利,模型构建和训练没有错误。但是当我尝试保存模型时,它会因错误“IndexError:list index out of range”而停止。我正在使用带有 TPU 的 Google Colab。

任何帮助将不胜感激!

代码:

import tensorflow as tf
from tensorflow.keras import activations, optimizers, losses
from transformers import TFBertModel

def create_model(max_sequence, model_name, num_labels):
    bert_model = TFBertModel.from_pretrained(model_name)
    input_ids = tf.keras.layers.Input(shape=(max_sequence,), dtype=tf.int32, name='input_ids')
    attention_mask = tf.keras.layers.Input((max_sequence,), dtype=tf.int32, name='attention_mask')
    output = bert_model([input_ids, attention_mask])[0]
    output = output[:, 0, :]
    output = tf.keras.layers.Dense(num_labels, activation='sigmoid')(output)
    model = tf.keras.models.Model(inputs=[input_ids, attention_mask], outputs=output)
    return model

with strategy.scope():
  model = create_model(20, 'bert-base-uncased', 1)
  opt = optimizers.Adam(learning_rate=3e-5)
  loss = 'binary_crossentropy'
  model.compile(optimizer=opt, loss=loss, metrics=['accuracy'])

model.fit(tfdataset_train, batch_size=32, epochs=2)
SAVE_PATH = 'path/to/save/location'
model.save(SAVE_PATH)

错误:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-22-255116b49022> in <module>()
      1 SAVE_PATH = 'path/to/save/location'
----> 2 model.save(SAVE_PATH,save_format='tf')

50 frames
/usr/local/lib/python3.7/dist-packages/transformers/modeling_tf_utils.py in input_processing(func, config, input_ids, **kwargs)
    372                     output[tensor_name] = input
    373                 else:
--> 374                     output[parameter_names[i]] = input
    375             elif isinstance(input, allowed_types) or input is None:
    376                 output[parameter_names[i]] = input

IndexError: list index out of range

用形状绘制的模型: Tensorflow Model

【问题讨论】:

  • 这解决了问题,但模型训练不正确。

标签: python tensorflow google-colaboratory bert-language-model huggingface-transformers


【解决方案1】:

解决办法是改变:

output = bert_model([input_ids, attention_mask])[0]

output = bert_model.bert([input_ids, attention_mask])[0]

参考:https://github.com/huggingface/transformers/issues/3627

我赞成您发布的解决方案,但后来我在训练时发现模型存在问题。它不能很好地收敛。

【讨论】:

    【解决方案2】:

    我在尝试保存使用所有三个输入张量(input_ids、token_type_ids 和 attention_mask)的微调 BERT 模型(使用 huggingface 和 tensorflow)时遇到了同样的错误。

    对我有用的解决方案是对user_007的答案稍作修改,如下:

    output = bert_model.bert(
        input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask
    )[0]
    

    【讨论】:

      【解决方案3】:

      问题解决了!

      移除两个输入层之一(即 attention_mask)解决了这个问题。

      工作代码->

      import tensorflow as tf
      from tensorflow.keras import activations, optimizers, losses
      from transformers import TFBertModel
      
      def create_model(max_sequence, model_name, num_labels):
          bert_model = TFBertModel.from_pretrained(model_name)
          input_ids = tf.keras.layers.Input(shape=(max_sequence,), dtype=tf.int32, name='input_ids')
          #attention_mask = tf.keras.layers.Input((max_sequence,), dtype=tf.int32, name='attention_mask')
          #output = bert_model([input_ids, attention_mask])[0]
          output = bert_model([input_ids])[0]
          output = output[:, 0, :]
          output = tf.keras.layers.Dense(num_labels, activation='sigmoid')(output)
          #model = tf.keras.models.Model(inputs=[input_ids, attention_mask], outputs=output)
          model = tf.keras.models.Model(inputs=[input_ids], outputs=output)
          return model
      
      with strategy.scope():
        model = create_model(20, 'bert-base-uncased', 1)
        opt = optimizers.Adam(learning_rate=3e-5)
        loss = 'binary_crossentropy'
        model.compile(optimizer=opt, loss=loss, metrics=['accuracy'])
      
      model.fit(tfdataset_train, batch_size=32, epochs=2)
      SAVE_PATH = 'path/to/save/location'
      model.save(SAVE_PATH)
      

      【讨论】:

      • 谢谢!只是为了强调一些事情:这个错误出现在我使用 Tf==2.3 和 transformers==4.3
      • 这可能会解决问题,但其他两个答案允许您保存模型并将有用的信息传递给模型。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多