Add additional layers to the Huggingface transformers

Viewed 6151

I want to add additional Dense layer after pretrained TFDistilBertModel, TFXLNetModel and TFRobertaModel Huggingface models. I have already seen how I can do this with the TFBertModel, e.g. in this notebook:

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

So, here I need to use the second item(i.e. item with index 1) of the BERT output tuple. According to the docs TFBertModel has pooler_output at this tuple index. But the other three models don't have pooler_output.

So, how can I add additional layers to the other three model outputs?

1 Answers

It looks like pooler_output is a Roberta and Bert specific output.

But instead of using pooler_output we can use a few hidden_states(so, not only last hidden state) with all models, we want to use them because papers report that hidden_states can give more accuracy than just one last_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'])
Related