向 Huggingface 变形金刚添加附加层

Add additional layers to the Huggingface transformers

我想在预训练 TFDistilBertModelTFXLNetModelTFRobertaModel Huggingface 模型后添加额外的 Dense 层。我已经看到如何使用 TFBertModel 来做到这一点,例如in this notebook:

output = bert_model([input_ids,attention_masks])
output = output[1]
output = tf.keras.layers.Dense(32,activation='relu')(output)

所以,这里我需要使用 BERT 输出元组的第二项(即索引为 1 的项)。根据 docs TFBertModel 在这个元组索引处有 pooler_output。但是其他三个型号没有pooler_output.

那么,如何向其他三个模型输出添加额外的层?

看起来 pooler_outputRobertaBert 特定的输出。

但是我们可以对所有模型使用一些 hidden_states(所以,不仅是最后的隐藏状态),而不是使用 pooler_output,我们想使用它们,因为 papers report hidden_stateslast_hidden_state.

更准确
# Import the needed model(Bert, Roberta or DistilBert) with output_hidden_states=True
transformer_model = TFBertForSequenceClassification.from_pretrained('bert-large-cased', output_hidden_states=True)

input_ids = tf.keras.Input(shape=(128, ),dtype='int32')
attention_mask = tf.keras.Input(shape=(128, ), dtype='int32')

transformer = transformer_model([input_ids, attention_mask])    
hidden_states = transformer[1] # get output_hidden_states

hidden_states_size = 4 # count of the last states 
hiddes_states_ind = list(range(-hidden_states_size, 0, 1))

selected_hiddes_states = tf.keras.layers.concatenate(tuple([hidden_states[i] for i in hiddes_states_ind]))

# Now we can use selected_hiddes_states as we want
output = tf.keras.layers.Dense(128, activation='relu')(selected_hiddes_states)
output = tf.keras.layers.Dense(1, activation='sigmoid')(output)
model = tf.keras.models.Model(inputs = [input_ids, attention_mask], outputs = output)
model.compile(tf.keras.optimizers.Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])