-
Notifications
You must be signed in to change notification settings - Fork 3
/
modules.py
2161 lines (1883 loc) · 101 KB
/
modules.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from math import ceil
import tensorflow as tf
def layer_normalization(layer, epsilon=1e-8):
"""
Implements layer normalization.
:param layer: has 2-dimensional, the first dimension is the batch_size
:param epsilon: a small number to avoid numerical issues, such as zero division.
:return: normalized tensor, of the same shape as the input
"""
with tf.variable_scope("layer_norm"):
params_shape = layer.get_shape()[-1:]
mean, variance = tf.nn.moments(layer, [-1], keep_dims=True)
beta = tf.get_variable(
name="beta", shape=params_shape, initializer=tf.zeros_initializer(), trainable=True)
gamma = tf.get_variable(
name="gamma", shape=params_shape, initializer=tf.ones_initializer(), trainable=True)
normalized = (layer - mean) / ((variance + epsilon) ** 0.5)
outputs = gamma * normalized + beta
return outputs
def division_masking(inputs, axis, multiplies):
"""
Masking used when dividing one element by the sum on a certain axis.
Division by 0 is not possible -- all values will be -infinity, instead.
:param inputs: the input needed to be divided
:param axis: axis on which to perform the reduced sum
:param multiplies: the shape to be used when tiling the division masks.
:return: the correct normalized inputs (with -infinity for divisions by 0).
"""
division_masks = tf.sign(tf.reduce_sum(inputs, axis=axis, keep_dims=True))
division_masks = tf.tile(division_masks, multiples=multiplies)
divided_inputs = tf.where(
tf.equal(division_masks, 0),
tf.zeros_like(inputs),
# tf.ones_like(inputs) * (-2 ** 32 + 1.0),
tf.div(inputs, tf.reduce_sum(inputs, axis=axis, keep_dims=True)))
return divided_inputs
def label_smoothing(labels, epsilon=0.1):
"""
Implements label smoothing. This prevents the model from becoming
over-confident about its predictions and thus, less prone to overfitting.
Label smoothing regularizes the model and makes it more adaptable.
:param labels: 3D tensor with the last dimension as the number of labels
:param epsilon: smoothing rate
:return: smoothed labels
"""
num_labels = labels.get_shape().as_list()[-1]
return ((1 - epsilon) * labels) + (epsilon / num_labels)
def mask(inputs, queries=None, keys=None, mask_type=None):
"""
Generates masks and apply them to 3D inputs.
inputs: 3D tensor. [B, M, M]
queries: 3D tensor. [B, M, E]
keys: 3D tensor. [B, M, E]
"""
padding_num = -2 ** 32 + 1
if "key" in mask_type:
masks = tf.sign(tf.reduce_sum(tf.abs(keys), axis=-1)) # [B, M]
masks = tf.expand_dims(masks, axis=1) # [B, 1, M]
masks = tf.tile(masks, [1, tf.shape(queries)[1], 1]) # [B, M, M]
paddings = tf.ones_like(inputs) * padding_num
outputs = tf.where(tf.equal(masks, 0), paddings, inputs) # [B, M, M]
elif "query" in mask_type:
masks = tf.sign(tf.reduce_sum(tf.abs(queries), axis=-1)) # [B, M]
masks = tf.expand_dims(masks, axis=-1) # [B, M, 1]
masks = tf.tile(masks, [1, 1, tf.shape(keys)[1]]) # [B, M, M]
outputs = inputs * masks
else:
raise ValueError("Unknown mask type: %s. You need to choose "
"between \"keys\" and \"query\"." % mask_type)
return outputs
def mask_2(inputs, queries=None, keys=None, mask_type=None):
"""
Generates masks and apply them to 4D inputs.
inputs: 3D tensor. [H, B, M, M]
queries: 3D tensor. [H, B, M, E]
keys: 3D tensor. [H, B, M, E]
"""
padding_num = -2 ** 32 + 1
if "key" in mask_type:
masks = tf.sign(tf.reduce_sum(tf.abs(keys), axis=-1)) # [H, B, M]
masks = tf.expand_dims(masks, axis=2) # [H, B, 1, M]
masks = tf.tile(masks, [1, 1, tf.shape(queries)[2], 1]) # [H, B, M, M]
paddings = tf.ones_like(inputs) * padding_num
outputs = tf.where(tf.equal(masks, 0), paddings, inputs) # [H, B, M, M]
elif "query" in mask_type:
masks = tf.sign(tf.reduce_sum(tf.abs(queries), axis=-1)) # [H, B, M]
masks = tf.expand_dims(masks, axis=-1) # [H, B, M, 1]
masks = tf.tile(masks, [1, 1, 1, tf.shape(keys)[2]]) # [H, B, M, M]
outputs = inputs * masks
else:
raise ValueError("Unknown mask type: %s. You need to choose "
"between \"keys\" and \"query\"." % mask_type)
return outputs
def cosine_distance_loss(inputs, take_abs=False):
"""
Computes the cosine pairwise distance loss between the input heads.
:param inputs: expects tensor with its last two dimensions [*, H, E],
where H = num heads and E = arbitrary vector dimension.
:param take_abs: take the absolute value of the cosine similarity; this
has the effect of switching from [-1, 1] to [0, 1], with the minimum at 0,
i.e. when the vectors are orthogonal, which is what we want.
However, this might not be differentiable at 0.
:return: loss of the cosine distance between any 2 pairs of head vectors.
"""
with tf.variable_scope("cosine_distance_loss"):
# Calculate the cosine similarity and cosine distance.
# The goal is to maximize the cosine distance.
normalized_inputs = tf.nn.l2_normalize(inputs, axis=-1)
permutation = list(range(len(inputs.get_shape().as_list())))
permutation[-1], permutation[-2] = permutation[-2], permutation[-1]
cos_similarity = tf.matmul(
normalized_inputs, tf.transpose(normalized_inputs, permutation))
# Mask the lower diagonal matrix.
ones = tf.ones_like(cos_similarity)
mask_upper = tf.matrix_band_part(ones, 0, -1) # upper triangular part
mask_diagonal = tf.matrix_band_part(ones, 0, 0) # diagonal
mask_matrix = tf.cast(mask_upper - mask_diagonal, dtype=tf.bool)
upper_triangular_flat = tf.boolean_mask(cos_similarity, mask_matrix)
if take_abs:
return tf.reduce_mean(tf.math.abs(upper_triangular_flat))
else:
return tf.reduce_mean(upper_triangular_flat)
def single_head_attention_binary_labels(
inputs,
initializer,
attention_size,
sentence_lengths,
hidden_units):
"""
Computes single-head attention (just normal, vanilla, soft attention).
:param inputs: 3D floats of shape [B, M, E]
:param initializer: type of initializer (best if Glorot or Xavier)
:param attention_size: number of units to use for the attention evidence
:param sentence_lengths: 2D ints of shape [B, M]
:param hidden_units: number of units to use for the processed sent tensor
:return sentence_scores: result of the attention * input; floats of shape [B]
:return sentence_predictions: predicted labels for each sentence in the batch; ints of shape [B]
:return token_scores: result of the un-normalized attention weights; floats of shape [B, M]
:return token_predictions: predicted labels for each token in each sentence; ints of shape [B, M]
"""
with tf.variable_scope("single_head_attention_binary_labels"):
attention_evidence = tf.layers.dense(
inputs=inputs, units=attention_size,
activation=tf.tanh, kernel_initializer=initializer) # [B, M, attention_size]
attention_weights = tf.layers.dense(
inputs=attention_evidence, units=1,
kernel_initializer=initializer) # [B, M, 1]
attention_weights = tf.squeeze(attention_weights, axis=-1) # [B, M]
attention_weights = tf.sigmoid(attention_weights)
token_scores = attention_weights
token_predictions = tf.where(
tf.greater_equal(token_scores, 0.5),
tf.ones_like(token_scores),
tf.zeros_like(token_scores))
token_predictions = tf.cast(tf.where(
tf.sequence_mask(sentence_lengths),
token_predictions,
tf.zeros_like(token_predictions) - 1e6), tf.int32)
attention_weights = tf.where(
tf.sequence_mask(sentence_lengths),
attention_weights, tf.zeros_like(attention_weights))
attention_weights = attention_weights / tf.reduce_sum(
attention_weights, axis=1, keep_dims=True) # [B, M]
product = inputs * tf.expand_dims(attention_weights, axis=-1) # [B, M, E]
processed_tensor = tf.reduce_sum(product, axis=1) # [B, E]
if hidden_units > 0:
processed_tensor = tf.layers.dense(
inputs=processed_tensor, units=hidden_units,
activation=tf.tanh, kernel_initializer=initializer) # [B, hidden_units]
sentence_scores = tf.layers.dense(
inputs=processed_tensor, units=1,
activation=tf.sigmoid, kernel_initializer=initializer,
name="output_sent_single_head_ff") # [B, 1]
sentence_scores = tf.reshape(
sentence_scores, shape=[tf.shape(processed_tensor)[0]]) # [B]
sentence_predictions = tf.where(
tf.greater_equal(sentence_scores, 0.5),
tf.ones_like(sentence_scores, dtype=tf.int32),
tf.zeros_like(sentence_scores, dtype=tf.int32)) # [B]
return sentence_scores, sentence_predictions, token_scores, token_predictions
def baseline_lstm_last_contexts(
last_token_contexts,
last_context,
initializer,
scoring_activation,
sentence_lengths,
hidden_units,
num_sentence_labels,
num_token_labels):
"""
Computes token and sentence scores/predictions solely from the last LSTM contexts.
vectors that the Bi-LSTM has produced. Works for flexible no. of labels.
:param last_token_contexts: the (concatenated) Bi-LSTM outputs per-token.
:param last_context: the (concatenated) Bi-LSTM final state.
:param initializer: type of initializer (best if Glorot or Xavier)
:param scoring_activation: used in computing the sentence scores from the token scores (per-head)
:param sentence_lengths: 2D ints of shape [B, M]
:param hidden_units: number of units to use for the processed sentence tensor
:param num_sentence_labels: number of unique sentence labels
:param num_token_labels: number of unique token labels
:return sentence_scores: 2D floats of shape [B, num_sentence_labels]
:return sentence_predictions: predicted labels for each sentence in the batch; ints of shape [B]
:return token_scores: 3D floats of shape [B, M, num_token_labels]
:return token_predictions: predicted labels for each token in each sentence; ints of shape [B, M]
:return: attention weights will be a tensor of zeros of shape [B, M, num_token_labels].
"""
with tf.variable_scope("baseline_lstm_last_contexts"):
if hidden_units > 0:
processed_tensor = tf.layers.dense(
last_context, units=hidden_units,
activation=tf.tanh, kernel_initializer=initializer)
token_scores = tf.layers.dense(
last_token_contexts, units=hidden_units,
activation=tf.tanh, kernel_initializer=initializer)
else:
processed_tensor = last_context
token_scores = last_token_contexts
sentence_scores = tf.layers.dense(
processed_tensor, units=num_sentence_labels,
activation=scoring_activation, kernel_initializer=initializer,
name="sentence_scores_lstm_ff") # [B, num_sentence_labels]
sentence_probabilities = tf.nn.softmax(sentence_scores, axis=-1)
sentence_predictions = tf.argmax(sentence_probabilities, axis=-1) # [B]
token_scores = tf.layers.dense(
token_scores, units=num_token_labels,
activation=scoring_activation, kernel_initializer=initializer,
name="token_scores_lstm_ff") # [B, M, num_token_labels]
masked_sentence_lengths = tf.tile(
input=tf.expand_dims(
tf.sequence_mask(sentence_lengths), axis=-1),
multiples=[1, 1, num_token_labels])
token_scores = tf.where(
masked_sentence_lengths,
token_scores,
tf.zeros_like(token_scores)) # [B, M, num_token_labels]
token_probabilities = tf.nn.softmax(token_scores, axis=-1)
token_predictions = tf.argmax(token_probabilities, axis=-1)
attention_weights = tf.zeros_like(token_scores)
return sentence_scores, sentence_predictions, token_scores, token_predictions, \
token_probabilities, sentence_probabilities, attention_weights
def single_head_attention_multiple_labels(
inputs,
initializer,
attention_activation,
attention_size,
sentence_lengths,
hidden_units,
num_sentence_labels,
num_token_labels):
"""
Computes single-head attention, but adapt it (naively) to make it work for multiple labels.
:param inputs: 3D floats of shape [B, M, E]
:param initializer: type of initializer (best if Glorot or Xavier)
:param attention_activation: type of attention activation (soft, sharp, linear, etc)
:param attention_size: number of units to use for the attention evidence
:param sentence_lengths: 2D ints of shape [B, M]
:param hidden_units: number of units to use for the processed sent tensor
:param num_sentence_labels: number of unique sentence labels
:param num_token_labels: number of unique token labels
:return sentence_scores: 2D floats of shape [B, num_sentence_labels]
:return sentence_predictions: predicted labels for each sentence in the batch; ints of shape [B]
:return token_scores: 3D floats of shape [B, M, num_token_labels]
:return token_predictions: predicted labels for each token in each sentence; ints of shape [B, M]
"""
with tf.variable_scope("SHA_multiple_labels"):
attention_evidence = tf.layers.dense(
inputs=inputs, units=attention_size,
activation=tf.tanh, kernel_initializer=initializer) # [B, M, attention_size]
attention_evidence = tf.layers.dense(
inputs=attention_evidence, units=1,
kernel_initializer=initializer) # [B, M, 1]
attention_evidence = tf.squeeze(attention_evidence, axis=-1) # [B, M]
# Apply a non-linear layer to obtain (un-normalized) attention weights.
if attention_activation == "soft":
attention_weights = tf.nn.sigmoid(attention_evidence)
elif attention_activation == "sharp":
attention_weights = tf.math.exp(attention_evidence)
elif attention_activation == "linear":
attention_weights = attention_evidence
elif attention_activation == "softmax":
attention_weights = tf.nn.softmax(attention_evidence)
else:
raise ValueError("Unknown/unsupported activation for attention activation: %s."
% attention_activation)
# Mask attention weights.
attention_weights = tf.where(
tf.sequence_mask(sentence_lengths),
attention_weights, tf.zeros_like(attention_weights))
attention_weights_unnormalized = attention_weights
# Normalize attention weights.
if attention_activation != "softmax":
attention_weights = attention_weights / tf.reduce_sum(
attention_weights, axis=-1, keep_dims=True) # [B, M]
token_scores = tf.layers.dense(
inputs=tf.expand_dims(attention_weights_unnormalized, -1),
units=num_token_labels,
kernel_initializer=initializer,
name="output_single_head_token_scores_ff") # [B, M, num_token_labels]
token_probabilities = tf.nn.softmax(token_scores)
token_predictions = tf.argmax(token_probabilities,
axis=2, output_type=tf.int32) # [B, M]
product = inputs * tf.expand_dims(attention_weights, axis=-1) # [B, M, E]
processed_tensor = tf.reduce_sum(product, axis=1) # [B, E]
if hidden_units > 0:
processed_tensor = tf.layers.dense(
inputs=processed_tensor, units=hidden_units,
activation=tf.tanh, kernel_initializer=initializer) # [B, hidden_units]
sentence_scores = tf.layers.dense(
inputs=processed_tensor, units=num_sentence_labels,
kernel_initializer=initializer,
name="output_multi_sent_specified_scores_ff") # [B, num_unique_sent_labels]
sentence_probabilities = tf.nn.softmax(sentence_scores, axis=-1)
sentence_predictions = tf.argmax(sentence_probabilities, axis=-1) # [B]
return sentence_scores, sentence_predictions, token_scores, token_predictions, \
token_probabilities, sentence_probabilities, attention_weights
def multi_head_attention_with_scores_from_shared_heads(
inputs,
initializer,
attention_activation,
hidden_units,
num_sentence_labels,
num_heads,
is_training,
dropout,
sentence_lengths,
use_residual_connection,
token_scoring_method):
"""
Computes multi-head attention (mainly inspired by the transformer architecture).
This method does not take into account any masking at any level.
All the masking will be performed before computing a primary/secondary loss.
:param inputs: 3D floats of shape [B, M, E]
:param initializer: type of initializer (best if Glorot or Xavier)
:param attention_activation: type of attention activation (linear, softmax or sigmoid)
:param hidden_units: number of units to use for the processed sent tensor
:param num_sentence_labels: number of unique sentence labels
:param num_heads: number of unique token labels
:param is_training: if set to True, the current phase is a training one (rather than testing)
:param dropout: the keep_probs value for the dropout
:param sentence_lengths: the true sentence lengths, used for masking
:param use_residual_connection: if set to True, a residual connection is added to the inputs
:param token_scoring_method: can be either max, sum or avg
:return sentence_scores: 2D floats of shape [B, num_sentence_labels]
:return sentence_predictions: predicted labels for each sentence in the batch; ints of shape [B]
:return token_scores: 3D floats of shape [B, M, num_heads]
:return token_predictions: predicted labels for each token in each sentence; ints of shape [B, M]
:return token_probabilities: the token scores normalized across the axis
"""
with tf.variable_scope("MHA_sentence_scores_from_shared_heads"):
num_units = inputs.get_shape().as_list()[-1]
if num_units % num_heads != 0:
num_units = ceil(num_units / num_heads) * num_heads
inputs = tf.layers.dense(inputs, num_units) # [B, M, num_units]
# Project to get the queries, keys, and values.
queries = tf.layers.dense(
inputs, num_units, activation=tf.tanh,
kernel_initializer=initializer) # [B, M, num_units]
keys = tf.layers.dense(
inputs, num_units, activation=tf.tanh,
kernel_initializer=initializer) # [B, M, num_units]
values = tf.layers.dense(
inputs, num_units, activation=tf.tanh,
kernel_initializer=initializer) # [B, M, num_units]
# Mask out the keys, queries and values: replace with 0 all the token
# positions between the true and the maximum sentence length.
multiplication_mask = tf.tile(
input=tf.expand_dims(tf.sequence_mask(sentence_lengths), axis=-1),
multiples=[1, 1, num_units]) # [B, M, num_units]
queries = tf.where(multiplication_mask, queries, tf.zeros_like(queries))
keys = tf.where(multiplication_mask, keys, tf.zeros_like(keys))
values = tf.where(multiplication_mask, values, tf.zeros_like(values))
# Split and concat as many projections as the number of heads.
queries = tf.concat(
tf.split(queries, num_heads, axis=2),
axis=0) # [B*num_heads, M, num_units/num_heads]
keys = tf.concat(
tf.split(keys, num_heads, axis=2),
axis=0) # [B*num_heads, M, num_units/num_heads]
values = tf.concat(
tf.split(values, num_heads, axis=2),
axis=0) # [B*num_heads, M, num_units/num_heads]
# Transpose multiplication and scale
attention_evidence = tf.matmul(
queries, tf.transpose(keys, [0, 2, 1])) # [B*num_heads, M, M]
attention_evidence = tf.math.divide(
attention_evidence, tf.constant(num_units ** 0.5))
# Mask columns (with values of -infinity), based on rows that have 0 sum.
attention_evidence_masked = mask(
attention_evidence, queries, keys, mask_type="key")
# Apply a non-linear layer to obtain (un-normalized) attention weights.
if attention_activation == "soft":
attention_weights = tf.nn.sigmoid(attention_evidence_masked)
elif attention_activation == "sharp":
attention_weights = tf.math.exp(attention_evidence_masked)
elif attention_activation == "linear":
attention_weights = attention_evidence_masked
elif attention_activation == "softmax":
attention_weights = tf.nn.softmax(attention_evidence_masked)
else:
raise ValueError("Unknown/unsupported attention activation: %s."
% attention_activation)
attention_weights_unnormalized = attention_weights
# Normalize attention weights.
if attention_activation != "softmax":
attention_weights /= tf.reduce_sum(
attention_weights, axis=-1, keep_dims=True)
# Mask rows (with values of 0), based on columns that have 0 sum.
attention_weights = mask(
attention_weights, queries, keys, mask_type="query")
attention_weights_unnormalized = mask(
attention_weights_unnormalized, queries, keys, mask_type="query")
# Apply a dropout layer on the attention weights.
if dropout > 0.0:
dropout_attention = (dropout * tf.cast(is_training, tf.float32)
+ (1.0 - tf.cast(is_training, tf.float32)))
attention_weights = tf.nn.dropout(
attention_weights, dropout_attention,
name="dropout_attention_weights") # [B*num_heads, M, M]
# [B*num_heads, M, num_units/num_heads]
product = tf.matmul(attention_weights, values)
product = tf.concat(
tf.split(product, num_heads), axis=2) # [B, M, num_units]
# Add a residual connection, followed by layer normalization.
if use_residual_connection:
product += inputs
product = layer_normalization(product) # [B, M, num_units]
processed_tensor = tf.reduce_sum(product, axis=1) # [B, num_units]
if hidden_units > 0:
processed_tensor = tf.layers.dense(
inputs=processed_tensor, units=hidden_units,
activation=tf.tanh, kernel_initializer=initializer) # [B, hidden_units]
sentence_scores = tf.layers.dense(
inputs=processed_tensor, units=num_sentence_labels,
kernel_initializer=initializer,
name="output_sent_specified_scores_ff") # [B, num_unique_sent_labels]
sentence_probabilities = tf.nn.softmax(sentence_scores)
sentence_predictions = tf.argmax(sentence_probabilities, axis=1) # [B]
# Obtain token scores from the attention weights.
# The token scores will have shape [B*num_heads, M, 1].
if token_scoring_method == "sum":
token_scores = tf.expand_dims(tf.reduce_sum(
attention_weights_unnormalized, axis=1), axis=2)
elif token_scoring_method == "max":
token_scores = tf.expand_dims(tf.reduce_max(
attention_weights_unnormalized, axis=1), axis=2)
elif token_scoring_method == "avg":
token_scores = tf.expand_dims(tf.reduce_mean(
attention_weights_unnormalized, axis=1), axis=2)
elif token_scoring_method == "logsumexp":
token_scores = tf.expand_dims(tf.reduce_logsumexp(
attention_weights_unnormalized, axis=1), axis=2)
else:
raise ValueError("Unknown/unsupported token scoring method: %s"
% token_scoring_method)
token_scores = tf.concat(
tf.split(token_scores, num_heads), axis=2) # [B, M, num_heads]
token_probabilities = tf.nn.softmax(token_scores)
token_predictions = tf.argmax(
token_probabilities, axis=2, output_type=tf.int32) # [B, M]
attention_weights = tf.concat(
tf.split(tf.expand_dims(attention_weights, axis=-1), num_heads),
axis=-1) # [B, M, M, num_heads]
return sentence_scores, sentence_predictions, \
token_scores, token_predictions, \
token_probabilities, sentence_probabilities, attention_weights
def multi_head_attention_with_scores_from_separate_heads(
inputs,
initializer,
attention_activation,
num_sentence_labels,
num_heads,
is_training,
dropout,
sentence_lengths,
normalize_sentence,
token_scoring_method,
scoring_activation=None,
separate_heads=True):
"""
Computes multi-head attention (mainly inspired by the transformer architecture).
This version of the implementation applies masking at several levels:
* first, the keys, queries and values so that the matrix multiplications
are performed only between meaningful positions
* second, the attention evidence values of 0 should be replaced with -infinity
so that when applying a non-linear layer, the resulted value is very close to 0.
* third, when obtaining the token probabilities (by normalizing across the scores),
division masking is performed (a value of 0 should be attributed to all 0 sums).
The masking performed before computing a primary/secondary loss is preserved.
:param inputs: 3D floats of shape [B, M, E]
:param initializer: type of initializer (best if Glorot or Xavier)
:param attention_activation: type of attention activation (linear, softmax or sigmoid)
:param num_sentence_labels: number of unique sentence labels
:param num_heads: number of unique token labels
:param is_training: if set to True, the current phase is a training one (rather than testing)
:param dropout: the keep_probs value for the dropout
:param sentence_lengths: the true sentence lengths, used for masking
:param normalize_sentence: if set to True, the last weighted sentence layer is normalized
:param token_scoring_method: can be either max, sum or avg
:param scoring_activation: used in computing the sentence scores from the token scores (per-head)
:param separate_heads: boolean value; when set to False, all heads
are used to obtain the sentence scores; when set to True, the default and non-default heads
from the token scores are used to obtain the sentence scores.
:return sentence_scores: 2D floats of shape [B, num_sentence_labels]
:return sentence_predictions: predicted labels for each sentence in the batch; ints of shape [B]
:return token_scores: 3D floats of shape [B, M, num_heads]
:return token_predictions: predicted labels for each token in each sentence; ints of shape [B, M]
"""
with tf.variable_scope("MHA_sentence_scores_from_separate_heads"):
num_units = inputs.get_shape().as_list()[-1]
if num_units % num_heads != 0:
num_units = ceil(num_units / num_heads) * num_heads
inputs = tf.layers.dense(inputs, num_units) # [B, M, num_units]
# Project to get the queries, keys, and values.
queries = tf.layers.dense(
inputs, num_units, activation=tf.tanh,
kernel_initializer=initializer) # [B, M, num_units]
keys = tf.layers.dense(
inputs, num_units, activation=tf.tanh,
kernel_initializer=initializer) # [B, M, num_units]
values = tf.layers.dense(
inputs, num_units, activation=tf.tanh,
kernel_initializer=initializer) # [B, M, num_units]
# Mask out the keys, queries and values: replace with 0 all the token
# positions between the true and the maximum sentence length.
multiplication_mask = tf.tile(
input=tf.expand_dims(tf.sequence_mask(sentence_lengths), axis=-1),
multiples=[1, 1, num_units]) # [B, M, num_units]
queries = tf.where(multiplication_mask, queries, tf.zeros_like(queries))
keys = tf.where(multiplication_mask, keys, tf.zeros_like(keys))
values = tf.where(multiplication_mask, values, tf.zeros_like(values))
# Split and concat as many projections as the number of heads.
queries = tf.concat(
tf.split(queries, num_heads, axis=2),
axis=0) # [B*num_heads, M, num_units/num_heads]
keys = tf.concat(
tf.split(keys, num_heads, axis=2),
axis=0) # [B*num_heads, M, num_units/num_heads]
# Transpose multiplication and scale
attention_evidence = tf.matmul(
queries, tf.transpose(keys, [0, 2, 1])) # [B*num_heads, M, M]
attention_evidence = tf.math.divide(
attention_evidence, tf.constant(num_units ** 0.5))
# Mask columns (with values of -infinity), based on rows that have 0 sum.
attention_evidence_masked = mask(
attention_evidence, queries, keys, mask_type="key")
# Apply a non-linear layer to obtain (un-normalized) attention weights.
if attention_activation == "soft":
attention_weights = tf.nn.sigmoid(attention_evidence_masked)
elif attention_activation == "sharp":
attention_weights = tf.math.exp(attention_evidence_masked)
elif attention_activation == "linear":
attention_weights = attention_evidence_masked
elif attention_activation == "softmax":
attention_weights = tf.nn.softmax(attention_evidence_masked)
else:
raise ValueError("Unknown/unsupported attention activation: %s."
% attention_activation)
# Normalize attention weights.
if attention_activation != "softmax":
attention_weights /= tf.reduce_sum(
attention_weights, axis=-1, keep_dims=True)
# Mask rows (with values of 0), based on columns that have 0 sum.
attention_weights = mask(
attention_weights, queries, keys, mask_type="query")
# Apply a dropout layer on the attention weights.
if dropout > 0.0:
dropout_attention = (dropout * tf.cast(is_training, tf.float32)
+ (1.0 - tf.cast(is_training, tf.float32)))
attention_weights = tf.nn.dropout(
attention_weights, dropout_attention,
name="dropout_attention_weights") # [B*num_heads, M, M]
# Obtain the token scores from the attention weights.
# The token_scores below will have shape [B*num_heads, 1, M].
if token_scoring_method == "sum":
token_scores = tf.reduce_sum(
attention_weights, axis=1, keep_dims=True)
elif token_scoring_method == "max":
token_scores = tf.reduce_max(
attention_weights, axis=1, keep_dims=True)
elif token_scoring_method == "avg":
token_scores = tf.reduce_mean(
attention_weights, axis=1, keep_dims=True)
elif token_scoring_method == "logsumexp":
token_scores = tf.reduce_logsumexp(
attention_weights, axis=1, keep_dims=True)
else:
raise ValueError("Unknown/unsupported token scoring method: %s"
% token_scoring_method)
token_scores = tf.concat(
tf.split(token_scores, num_heads),
axis=1) # [B, num_heads, M]
token_scores_normalized = division_masking(
inputs=token_scores, axis=-1,
multiplies=[1, 1, tf.shape(token_scores)[-1]]) # [B, num_heads, M]
token_probabilities = tf.nn.softmax(token_scores, axis=1)
token_predictions = tf.argmax(
token_probabilities, axis=1, output_type=tf.int32) # [B, M]
# Obtain a weighted sum between the inputs and the attention weights.
# [B, num_heads, num_units]
weighted_sum_representation = tf.matmul(token_scores_normalized, values)
if normalize_sentence:
weighted_sum_representation = layer_normalization(weighted_sum_representation)
if separate_heads:
# Get the sentence representations corresponding to the default head.
default_head = tf.gather(
weighted_sum_representation,
indices=[0], axis=1) # [B, 1, num_units]
# Get the sentence representations corresponding to the default head.
non_default_heads = tf.gather(
weighted_sum_representation,
indices=list(range(1, num_heads)), axis=1) # [B, num_heads-1, num_units]
# Project onto one unit, corresponding to
# the default sentence label score.
sentence_default_scores = tf.layers.dense(
default_head, units=1,
activation=scoring_activation, kernel_initializer=initializer,
name="sentence_default_scores_ff") # [B, 1, 1]
sentence_default_scores = tf.squeeze(
sentence_default_scores, axis=-1) # [B, 1]
# Project onto (num_sentence_labels-1) units, corresponding to
# the non-default sentence label scores.
sentence_non_default_scores = tf.layers.dense(
non_default_heads, units=num_sentence_labels-1,
activation=scoring_activation, kernel_initializer=initializer,
name="sentence_non_default_scores_ff") # [B, num_heads-1, num_sentence_labels-1]
sentence_non_default_scores = tf.reduce_mean(
sentence_non_default_scores, axis=1) # [B, num_sent_labels-1]
sentence_scores = tf.concat(
[sentence_default_scores, sentence_non_default_scores],
axis=-1, name="sentence_scores_concatenation") # [B, num_sent_labels]
else:
processed_tensor = tf.layers.dense(
inputs=weighted_sum_representation, units=num_sentence_labels,
activation=scoring_activation, kernel_initializer=initializer,
name="sentence_scores_ff") # [B, num_heads, num_unique_sent_labels]
sentence_scores = tf.reduce_sum(
processed_tensor, axis=1) # [B, num_sent_labels]
sentence_probabilities = tf.nn.softmax(sentence_scores)
sentence_predictions = tf.argmax(sentence_probabilities, axis=1) # [B]
# Get token scores and probabilities of shape # [B, M, num_heads].
token_scores = tf.transpose(token_scores, [0, 2, 1])
token_probabilities = tf.transpose(token_probabilities, [0, 2, 1])
attention_weights = tf.concat(
tf.split(tf.expand_dims(attention_weights, axis=-1), num_heads),
axis=-1) # [B, M, M, num_heads]
return sentence_scores, sentence_predictions, \
token_scores, token_predictions, \
token_probabilities, sentence_probabilities, attention_weights
def compute_scores_from_additive_attention(
inputs,
initializer,
attention_activation,
sentence_lengths,
attention_size=50,
hidden_units=50):
"""
Computes token and sentence scores from a single-head additive attention mechanism.
:param inputs: 3D floats of shape [B, M, E]
:param initializer: type of initializer (best if Glorot or Xavier)
:param attention_activation: type of attention activation (linear, softmax or sigmoid)
:param sentence_lengths: 2D ints of shape [B, M]
:param attention_size: number of units to use for the attention evidence
:param hidden_units: number of units to use for the processed sent tensor
:return sentence_scores: result of the attention * input; floats of shape [B]
:return token_scores: result of the un-normalized attention weights; floats of shape [B, M]
:return attention_weights: 2D floats of shape [B, M] of normalized token_scores
"""
with tf.variable_scope("compute_classic_single_head_attention"):
attention_evidence = tf.layers.dense(
inputs=inputs, units=attention_size,
activation=tf.tanh, kernel_initializer=initializer) # [B, M, attention_size]
attention_weights = tf.layers.dense(
inputs=attention_evidence, units=1,
kernel_initializer=initializer) # [B, M, 1]
attention_weights = tf.squeeze(attention_weights, axis=-1) # [B, M]
# Obtain the un-normalized attention weights.
if attention_activation == "soft":
attention_weights = tf.nn.sigmoid(attention_weights)
elif attention_activation == "sharp":
attention_weights = tf.exp(attention_weights)
elif attention_activation == "linear":
attention_weights = attention_weights
else:
raise ValueError("Unknown/unsupported attention activation: %s"
% attention_activation)
attention_weights = tf.where(
tf.sequence_mask(sentence_lengths),
attention_weights, tf.zeros_like(attention_weights))
token_scores = attention_weights # [B, M]
# Obtain the normalized attention weights (they will also be sentence weights).
attention_weights = attention_weights / tf.reduce_sum(
attention_weights, axis=1, keep_dims=True) # [B, M]
product = inputs * tf.expand_dims(attention_weights, axis=-1) # [B, M, num_units]
processed_tensor = tf.reduce_sum(product, axis=1) # [B, E]
if hidden_units > 0:
processed_tensor = tf.layers.dense(
inputs=processed_tensor, units=hidden_units,
activation=tf.tanh, kernel_initializer=initializer) # [B, hidden_units]
sentence_scores = tf.layers.dense(
inputs=processed_tensor, units=1,
activation=tf.sigmoid, kernel_initializer=initializer,
name="output_sent_single_head_ff") # [B, 1]
sentence_scores = tf.squeeze(sentence_scores, axis=-1)
return sentence_scores, token_scores, attention_weights
def compute_scores_from_scaled_dot_product_attention(
inputs,
initializer,
attention_activation,
sentence_lengths,
token_scoring_method):
"""
Computes token and sentence scores from a single-head scaled dot product attention mechanism.
:param inputs: 3D floats of shape [B, M, E]
:param initializer: type of initializer (best with Glorot or Xavier)
:param attention_activation: type of attention activation: sharp (exp) or soft (sigmoid)
:param sentence_lengths: 2D ints of shape [B, M]
:param token_scoring_method: can be either max, sum or avg
:return sentence_scores: 2D floats of shape [B, num_sentence_labels]
:return token_scores: 2D floats of shape [B, M]
:return token_probabilities: 2D floats of shape [B, M] of normalized token_scores
"""
with tf.variable_scope("compute_transformer_single_head_attention"):
num_units = inputs.get_shape().as_list()[-1]
# Project to get the queries, keys, and values, all of them of shape [B, M, num_units].
queries = tf.layers.dense(
inputs, num_units, activation=tf.tanh,
kernel_initializer=initializer)
keys = tf.layers.dense(
inputs, num_units, activation=tf.tanh,
kernel_initializer=initializer)
# Mask out the keys, queries and values: replace with 0 all the token
# positions between the true and the maximum sentence length.
multiplication_mask = tf.tile(
input=tf.expand_dims(tf.sequence_mask(sentence_lengths), axis=-1),
multiples=[1, 1, num_units]) # [B, M, num_units]
queries = tf.where(multiplication_mask, queries, tf.zeros_like(queries))
keys = tf.where(multiplication_mask, keys, tf.zeros_like(keys))
# Scaled dot-product attention.
attention_evidence = tf.matmul(
queries, tf.transpose(keys, [0, 2, 1])) # [B, M, M]
attention_evidence = tf.math.divide(
attention_evidence, tf.constant(num_units ** 0.5))
# Mask columns (with values of -infinity), based on rows that have 0 sum.
attention_evidence_masked = mask(
attention_evidence, queries, keys, mask_type="key")
# Obtain the un-normalized attention weights.
if attention_activation == "soft":
attention_weights = tf.nn.sigmoid(attention_evidence_masked)
elif attention_activation == "sharp":
attention_weights = tf.exp(attention_evidence_masked)
else:
raise ValueError("Unknown/unsupported activation for attention: %s"
% attention_activation)
attention_weights_unnormalized = attention_weights
# Normalize attention weights.
attention_weights /= tf.reduce_sum(
attention_weights, axis=-1, keep_dims=True) # [B, M, M]
# Mask rows (with values of 0), based on columns that have 0 sum.
attention_weights = mask(
attention_weights, queries, keys, mask_type="query")
attention_weights_unnormalized = mask(
attention_weights_unnormalized, queries, keys, mask_type="query")
# Obtain the token scores from the attention weights.
# The token_scores below will have shape [B, M].
if token_scoring_method == "sum":
token_scores = tf.reduce_sum(
attention_weights_unnormalized, axis=1)
elif token_scoring_method == "max":
token_scores = tf.reduce_max(
attention_weights_unnormalized, axis=1)
elif token_scoring_method == "avg":
token_scores = tf.reduce_mean(
attention_weights_unnormalized, axis=1)
elif token_scoring_method == "logsumexp":
token_scores = tf.reduce_logsumexp(
attention_weights_unnormalized, axis=1)
else:
raise ValueError("Unknown/unsupported token scoring method: %s"
% token_scoring_method)
token_scores_normalized = division_masking(
inputs=token_scores, axis=-1,
multiplies=[1, tf.shape(token_scores)[1]]) # [B, M]
# Sentence scores as a weighted sum between the inputs and the attention weights.
# weighted_sum_representation = tf.matmul(attention_weights, inputs)
weighted_sum_representation = inputs * tf.expand_dims(
token_scores_normalized, axis=-1) # [B, M, num_units]
processed_tensor = tf.reduce_sum(
weighted_sum_representation, axis=1) # [B, num_units]
sentence_scores = tf.layers.dense(
inputs=processed_tensor, units=1,
activation=tf.sigmoid, kernel_initializer=initializer,
name="sentence_scores_from_scaled_dot_product_ff") # [B, 1]
sentence_scores = tf.squeeze(sentence_scores, axis=-1) # [B]
return sentence_scores, token_scores, attention_weights
def single_head_attention_multiple_transformations(
inputs,
initializer,
attention_activation,
num_sentence_labels,
num_heads,
sentence_lengths,
token_scoring_method,
scoring_activation=None,
how_to_compute_attention="dot",
separate_heads=True):
"""
Computes token and sentence scores using a single-head attention mechanism,
which can either be additive (mainly inspired by the single-head binary-label
method above, as in Rei and Sogaard paper https://arxiv.org/pdf/1811.05949.pdf)
or a scaled-dot product version (inspired by the transformer, but with just one head).
Then, use these scores to obtain predictions at both granularities.
:param inputs: 3D floats of shape [B, M, E]
:param initializer: type of initializer (best if Glorot or Xavier)
:param attention_activation
:param num_sentence_labels: number of unique sentence labels
:param num_heads: number of unique token labels
:param sentence_lengths: the true sentence lengths, used for masking
:param token_scoring_method
:param scoring_activation: activation used for scoring, default is None.
:param how_to_compute_attention: compute attention in the classic way (Marek) or as in transformer
:param separate_heads: boolean value; when set to False, all heads
are used to obtain the sentence scores; when set to True, the default and non-default heads
from the token scores are used to obtain the sentence scores.
:return sentence_scores: 2D floats of shape [B, num_sentence_labels]
:return sentence_predictions: predicted labels for each sentence in the batch; ints of shape [B]
:return token_scores: 3D floats of shape [B, M, num_heads]
:return token_predictions: predicted labels for each token in each sentence; ints of shape [B, M]
"""
with tf.variable_scope("transformer_single_heads_multi_attention"):
token_scores_per_head = []
sentence_scores_per_head = []
attention_weights_per_head = []
for i in range(num_heads):
with tf.variable_scope("num_head_{}".format(i), reuse=tf.AUTO_REUSE):
if how_to_compute_attention == "additive":
sentence_scores_head_i, token_scores_head_i, attention_weights_head_i = \
compute_scores_from_additive_attention(
inputs=inputs, initializer=initializer,
attention_activation=attention_activation,
sentence_lengths=sentence_lengths)
elif how_to_compute_attention == "dot":
sentence_scores_head_i, token_scores_head_i, attention_weights_head_i = \
compute_scores_from_scaled_dot_product_attention(
inputs=inputs, initializer=initializer,
attention_activation=attention_activation,
sentence_lengths=sentence_lengths,
token_scoring_method=token_scoring_method)
else:
raise ValueError("Unknown/unsupported way of computing the attention: %s"
% how_to_compute_attention)
sentence_scores_per_head.append(sentence_scores_head_i)
token_scores_per_head.append(token_scores_head_i)
attention_weights_per_head.append(attention_weights_head_i)
sentence_scores = tf.stack(sentence_scores_per_head, axis=-1) # [B, num_heads]
if separate_heads:
sentence_default_score = tf.layers.dense(
inputs=tf.expand_dims(sentence_scores[:, 0], axis=-1), units=1,
activation=scoring_activation, kernel_initializer=initializer,
name="ff_non_default_sentence_scores")
sentence_non_default_scores = tf.layers.dense(
inputs=sentence_scores[:, 1:], units=num_sentence_labels-1,
activation=scoring_activation, kernel_initializer=initializer,
name="ff_default_sentence_scores")
sentence_scores = tf.concat(
[sentence_default_score, sentence_non_default_scores],
axis=-1, name="sentence_scores_concatenation")
else:
sentence_scores = tf.layers.dense(
inputs=sentence_scores, units=num_sentence_labels,
activation=scoring_activation, kernel_initializer=initializer,
name="ff_sentence_scores") # [B, num_sentence_labels]
sentence_probabilities = tf.nn.softmax(sentence_scores)
sentence_predictions = tf.argmax(sentence_probabilities, axis=1) # [B]
token_scores = tf.stack(token_scores_per_head, axis=-1) # [B, M, num_heads]
token_probabilities = tf.nn.softmax(token_scores, axis=-1) # [B, M, num_heads]
token_predictions = tf.argmax(token_probabilities, axis=-1) # [B, M]
# Will be of shape [B, M, H] if an additive attention was used, or
# of shape [B, M, M, H] if a scaled-dot product attention was used.
attention_weights = tf.stack(attention_weights_per_head, axis=-1)
return sentence_scores, sentence_predictions, token_scores, token_predictions, \
token_probabilities, sentence_probabilities, attention_weights
def variant_1(
inputs,
initializer,
attention_activation,
num_sentence_labels,
num_heads,