forked from kpot/keras-transformer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
233 lines (214 loc) · 10.1 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
from keras import regularizers
from keras.models import Model
# noinspection PyPep8Naming
from keras import backend as K
from keras.layers import Input, Softmax, Embedding, Add, Lambda, Dense
from keras_transformer.extras import ReusableEmbedding, TiedOutputEmbedding
from keras_transformer.position import TransformerCoordinateEmbedding
from keras_transformer.transformer import TransformerACT, TransformerBlock
def universal_transformer_gpt_model(
max_seq_length: int, vocabulary_size: int,
word_embedding_size: int, transformer_depth: int,
num_heads: int, transformer_dropout: float = 0.1,
embedding_dropout: float = 0.6,
l2_reg_penalty: float = 1e-6,
confidence_penalty_weight: float = 0.1):
"""
A model which is similar to the one described by OpenAI in paper
"Improving Language Understanding by Generative Pre-Training", except
that it relies L2 regularization of the word embedding matrix
(instead of the dropout), and uses Universal Transformer architecture.
"""
word_ids = Input(shape=(max_seq_length,), dtype='int32', name='word_ids')
l2_regularizer = (regularizers.l2(l2_reg_penalty) if l2_reg_penalty
else None)
embedding_layer = ReusableEmbedding(
vocabulary_size, word_embedding_size,
input_length=max_seq_length,
name='bpe_embeddings',
# Regularization is based on paper "A Comparative Study on
# Regularization Strategies for Embedding-based Neural Networks"
# https://arxiv.org/pdf/1508.03721.pdf
embeddings_regularizer=l2_regularizer)
output_layer = TiedOutputEmbedding(
projection_regularizer=l2_regularizer,
projection_dropout=embedding_dropout,
name='word_prediction_logits')
coordinate_embedding_layer = TransformerCoordinateEmbedding(
transformer_depth,
name='coordinate_embedding')
transformer_act_layer = TransformerACT(name='adaptive_computation_time')
transformer_block = TransformerBlock(
name='transformer', num_heads=num_heads,
residual_dropout=transformer_dropout,
attention_dropout=transformer_dropout,
use_masking=True, vanilla_wiring=False)
output_softmax_layer = Softmax(name='word_predictions')
next_step_input, embedding_matrix = embedding_layer(word_ids)
act_output = next_step_input
for i in range(transformer_depth):
next_step_input = coordinate_embedding_layer(next_step_input, step=i)
next_step_input = transformer_block(next_step_input)
next_step_input, act_output = transformer_act_layer(next_step_input)
transformer_act_layer.finalize()
next_step_input = act_output
word_predictions = output_softmax_layer(
output_layer([next_step_input, embedding_matrix]))
model = Model(inputs=[word_ids], outputs=[word_predictions])
# Penalty for confidence of the output distribution, as described in
# "Regularizing Neural Networks by Penalizing Confident
# Output Distributions" (https://arxiv.org/abs/1701.06548)
confidence_penalty = K.mean(
confidence_penalty_weight *
K.sum(word_predictions * K.log(word_predictions), axis=-1))
model.add_loss(confidence_penalty)
return model
def vanilla_transformer_gpt_model(
max_seq_length: int, vocabulary_size: int,
word_embedding_size: int, transformer_depth: int,
num_heads: int, transformer_dropout: float = 0.1,
embedding_dropout: float = 0.6,
l2_reg_penalty: float = 1e-6,
confidence_penalty_weight: float = 0.1):
"""
A model which is almost identical to the one described by OpenAI in paper
"Improving Language Understanding by Generative Pre-Training", except
that it uses L2 regularization of the word embedding matrix,
instead of the dropout.
"""
word_ids = Input(shape=(max_seq_length,), dtype='int32', name='word_ids')
l2_regularizer = (regularizers.l2(l2_reg_penalty) if l2_reg_penalty
else None)
embedding_layer = ReusableEmbedding(
vocabulary_size, word_embedding_size,
input_length=max_seq_length,
name='bpe_embeddings',
# Regularization is based on paper "A Comparative Study on
# Regularization Strategies for Embedding-based Neural Networks"
# https://arxiv.org/pdf/1508.03721.pdf
embeddings_regularizer=l2_regularizer)
output_layer = TiedOutputEmbedding(
projection_regularizer=l2_regularizer,
projection_dropout=embedding_dropout,
name='word_prediction_logits')
coordinate_embedding_layer = TransformerCoordinateEmbedding(
1,
name='coordinate_embedding')
output_softmax_layer = Softmax(name='word_predictions')
next_step_input, embedding_matrix = embedding_layer(word_ids)
next_step_input = coordinate_embedding_layer(next_step_input, step=0)
for i in range(transformer_depth):
next_step_input = (
TransformerBlock(
name='transformer' + str(i), num_heads=num_heads,
residual_dropout=transformer_dropout,
attention_dropout=transformer_dropout,
use_masking=True,
vanilla_wiring=True)
(next_step_input))
word_predictions = output_softmax_layer(
output_layer([next_step_input, embedding_matrix]))
model = Model(inputs=[word_ids], outputs=[word_predictions])
# Penalty for confidence of the output distribution, as described in
# "Regularizing Neural Networks by Penalizing Confident
# Output Distributions" (https://arxiv.org/abs/1701.06548)
confidence_penalty = K.mean(
confidence_penalty_weight *
K.sum(word_predictions * K.log(word_predictions), axis=-1))
model.add_loss(confidence_penalty)
return model
def transformer_bert_model(
max_seq_length: int, vocabulary_size: int,
word_embedding_size: int,
use_universal_transformer: bool,
transformer_depth: int,
num_heads: int,
transformer_dropout: float = 0.1,
embedding_dropout: float = 0.6,
l2_reg_penalty: float = 1e-4):
"""
Builds a BERT-based model (Bidirectional Encoder Representations
from Transformers) following paper "BERT: Pre-training of Deep
Bidirectional Transformers for Language Understanding"
(https://arxiv.org/abs/1810.04805)
Depending on the value passed with `use_universal_transformer` argument,
this function applies either an Adaptive Universal Transformer (2018)
or a vanilla Transformer (2017) to do the job (the original paper uses
vanilla Transformer).
"""
word_ids = Input(shape=(max_seq_length,), dtype='int32', name='word_ids')
segment_ids = Input(
shape=(max_seq_length,), dtype='int32', name='segment_ids')
l2_regularizer = (regularizers.l2(l2_reg_penalty) if l2_reg_penalty
else None)
embedding_layer = ReusableEmbedding(
vocabulary_size, word_embedding_size,
input_length=max_seq_length,
name='bpe_embeddings',
# Regularization is based on paper "A Comparative Study on
# Regularization Strategies for Embedding-based Neural Networks"
# https://arxiv.org/pdf/1508.03721.pdf
embeddings_regularizer=l2_regularizer)
segment_embedding_layer = Embedding(
2, # "Segment A" and "Segment B" embeddings
word_embedding_size, name='segment_embeddings')
add_segment_layer = Add(name='add_segment')
output_layer = TiedOutputEmbedding(
projection_regularizer=l2_regularizer,
projection_dropout=embedding_dropout,
name='word_prediction_logits')
output_softmax_layer = Softmax(name='word_predictions')
coordinate_embedding_layer = TransformerCoordinateEmbedding(
transformer_depth if use_universal_transformer else 1,
name='coordinate_embedding')
next_step_input, embedding_matrix = embedding_layer(word_ids)
segment_embeddings = segment_embedding_layer(segment_ids)
if use_universal_transformer:
# Building a Universal Transformer (2018)
act_layer = TransformerACT(
name='adaptive_computation_time')
transformer_block = TransformerBlock(
name='transformer', num_heads=num_heads,
residual_dropout=transformer_dropout,
attention_dropout=transformer_dropout,
# Allow bi-directional attention
use_masking=False)
act_output = next_step_input
for i in range(transformer_depth):
next_step_input = coordinate_embedding_layer(
next_step_input, step=i)
next_step_input = add_segment_layer(
[next_step_input, segment_embeddings])
next_step_input = transformer_block(next_step_input)
next_step_input, act_output = act_layer(next_step_input)
act_layer.finalize()
next_step_input = act_output
else:
# Building a Vanilla Transformer (described in
# "Attention is all you need", 2017)
next_step_input = coordinate_embedding_layer(next_step_input, step=0)
next_step_input = add_segment_layer(
[next_step_input, segment_embeddings])
for i in range(transformer_depth):
next_step_input = (
TransformerBlock(
name='transformer' + str(i), num_heads=num_heads,
residual_dropout=transformer_dropout,
attention_dropout=transformer_dropout,
use_masking=False, # Allow bi-directional attention
vanilla_wiring=True)
(next_step_input))
word_predictions = output_softmax_layer(
output_layer([next_step_input, embedding_matrix]))
cls_node_slice = (
# selecting the first output position in each sequence
# (responsible for classification)
Lambda(lambda x: x[:, 0], name='cls_node_slicer')
(next_step_input))
class_prediction = (
Dense(1, name='class_prediction', activation='sigmoid')
(cls_node_slice))
model = Model(
inputs=[word_ids, segment_ids],
outputs=[word_predictions, class_prediction])
return model