微调BERT模型保存时出现List index out of range报错问题
报错原因
这个IndexError出现在模型保存阶段的计算图追踪过程中,核心原因是直接将输入张量组成的列表作为位置参数传入TFBertMainLayer时,TensorFlow序列化时无法正确解析BERT层的输入结构,触发索引越界。
解决方法
按如下步骤修改即可正常保存:
- 修改BERT层调用逻辑:不要直接访问
bert_model.bert内部层,同时将列表输入改为关键字参数传递,避免位置参数解析错误。将原有代码行
x = bert_model.bert([input_ids, attention_masks])
替换为:
x = bert_model(input_ids=input_ids, attention_mask=attention_masks)
原有x = x.pooler_output的逻辑无需改动。
- 若修改后仍存在保存异常,可选择保存为HDF5格式而非默认的SavedModel格式,加载时先初始化模型结构再加载权重:
# 保存模型 model.save("bert_multi_label.h5", save_format="h5") # 加载模型 loaded_model = create_model() loaded_model.load_weights("bert_multi_label.h5")
修改后的完整模型代码
def create_model(max_length = 256): bert_model = TFBertModel.from_pretrained('bert-base-uncased') for layer in bert_model.layers: layer.trainable = False input_ids = tf.keras.Input(shape = (max_length, ), dtype = tf.int32, name = 'input_ids') attention_masks = tf.keras.Input(shape = (max_length, ), dtype = tf.int32, name = 'attention_masks') # 修改后的BERT层调用 x = bert_model(input_ids=input_ids, attention_mask=attention_masks) x = x.pooler_output x = tf.keras.layers.Dropout(0.2)(x) x = tf.keras.layers.Dense(256, activation = 'relu')(x) x = tf.keras.layers.Dropout(0.2)(x) x = tf.keras.layers.Dense(33)(x) out = tf.keras.layers.Activation('sigmoid')(x) model = tf.keras.Model(inputs = [input_ids, attention_masks], outputs = out) model.compile(optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5), loss = tf.keras.losses.BinaryCrossentropy(), metrics = tf.metrics.BinaryAccuracy()) return model
内容的提问来源于stack exchange,提问作者Pratik Sanghavi
相关产品推荐
相关产品推荐

