-
Notifications
You must be signed in to change notification settings - Fork 98
/
attention.py
211 lines (190 loc) · 8.55 KB
/
attention.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
from keras.layers import Layer
import keras.backend as K
class Attention(Layer):
def __init__(self, method=None, **kwargs):
self.supports_masking = True
if method != 'lba' and method !='ga' and method != 'cba' and method is not None:
raise ValueError('attention method is not supported')
self.method = method
super(Attention, self).__init__(**kwargs)
def build(self, input_shape):
if isinstance(input_shape, list):
self.att_size = input_shape[0][-1]
self.query_dim = input_shape[1][-1]
if self.method == 'ga' or self.method == 'cba':
self.Wq = self.add_weight(name='kernal_query_features', shape=(self.query_dim, self.att_size), initializer='glorot_normal', trainable=True)
else:
self.att_size = input_shape[-1]
if self.method == 'cba':
self.Wh = self.add_weight(name='kernal_hidden_features', shape=(self.att_size,self.att_size), initializer='glorot_normal', trainable=True)
if self.method == 'lba' or self.method == 'cba':
self.v = self.add_weight(name='query_vector', shape=(self.att_size, 1), initializer='zeros', trainable=True)
super(Attention, self).build(input_shape)
def call(self, inputs, mask=None):
'''
:param inputs: a list of tensor of length not larger than 2, or a memory tensor of size BxTXD1.
If a list, the first entry is memory, and the second one is query tensor of size BxD2 if any
:param mask: the masking entry will be directly discarded
:return: a tensor of size BxD1, weighted summing along the sequence dimension
'''
if isinstance(inputs, list) and len(inputs) == 2:
memory, query = inputs
if self.method is None:
return memory[:,-1,:]
elif self.method == 'cba':
hidden = K.dot(memory, self.Wh) + K.expand_dims(K.dot(query, self.Wq), 1)
hidden = K.tanh(hidden)
s = K.squeeze(K.dot(hidden, self.v), -1)
elif self.method == 'ga':
s = K.sum(K.expand_dims(K.dot(query, self.Wq), 1) * memory, axis=-1)
else:
s = K.squeeze(K.dot(memory, self.v), -1)
if mask is not None:
mask = mask[0]
else:
if isinstance(inputs, list):
if len(inputs) != 1:
raise ValueError('inputs length should not be larger than 2')
memory = inputs[0]
else:
memory = inputs
if self.method is None:
return memory[:,-1,:]
elif self.method == 'cba':
hidden = K.dot(memory, self.Wh)
hidden = K.tanh(hidden)
s = K.squeeze(K.dot(hidden, self.v), -1)
elif self.method == 'ga':
raise ValueError('general attention needs the second input')
else:
s = K.squeeze(K.dot(memory, self.v), -1)
s = K.softmax(s)
if mask is not None:
s *= K.cast(mask, dtype='float32')
sum_by_time = K.sum(s, axis=-1, keepdims=True)
s = s / (sum_by_time + K.epsilon())
return K.sum(memory * K.expand_dims(s), axis=1)
def compute_mask(self, inputs, mask=None):
return None
def compute_output_shape(self, input_shape):
if isinstance(input_shape, list):
att_size = input_shape[0][-1]
batch = input_shape[0][0]
else:
att_size = input_shape[-1]
batch = input_shape[0]
return (batch, att_size)
class SimpleAttention(Layer):
def __init__(self, method=None, **kwargs):
self.supports_masking = True
if method != 'lba' and method !='ga' and method != 'cba' and method is not None:
raise ValueError('attention method is not supported')
self.method = method
super(SimpleAttention, self).__init__(**kwargs)
def build(self, input_shape):
if isinstance(input_shape, list):
self.att_size = input_shape[0][-1]
self.query_dim = input_shape[1][-1] + self.att_size
else:
self.att_size = input_shape[-1]
self.query_dim = self.att_size
if self.method == 'cba' or self.method == 'ga':
self.Wq = self.add_weight(name='kernal_query_features', shape=(self.query_dim, self.att_size),
initializer='glorot_normal', trainable=True)
if self.method == 'cba':
self.Wh = self.add_weight(name='kernal_hidden_features', shape=(self.att_size, self.att_size), initializer='glorot_normal', trainable=True)
if self.method == 'lba' or self.method == 'cba':
self.v = self.add_weight(name='query_vector', shape=(self.att_size, 1), initializer='zeros', trainable=True)
super(SimpleAttention, self).build(input_shape)
def call(self, inputs, mask=None):
'''
:param inputs: a list of tensor of length not larger than 2, or a memory tensor of size BxTXD1.
If a list, the first entry is memory, and the second one is query tensor of size BxD2 if any
:param mask: the masking entry will be directly discarded
:return: a tensor of size BxD1, weighted summing along the sequence dimension
'''
query = None
if isinstance(inputs, list):
memory = inputs[0]
if len(inputs) > 1:
query = inputs[1]
elif len(inputs) > 2:
raise ValueError('inputs length should not be larger than 2')
if isinstance(mask, list):
mask = mask[0]
else:
memory = inputs
input_shape = K.int_shape(memory)
if len(input_shape) >3:
input_length = input_shape[1]
memory = K.reshape(memory, (-1,) + input_shape[2:])
if mask is not None:
mask = K.reshape(mask, (-1,) + input_shape[2:-1])
if query is not None:
raise ValueError('query can be not supported')
last = memory[:,-1,:]
memory = memory[:,:-1,:]
if query is None:
query = last
else:
query = K.concatenate([query, last], axis=-1)
if self.method is None:
if len(input_shape) > 3:
output_shape = K.int_shape(last)
return K.reshape(last, (-1, input_shape[1], output_shape[-1]))
else:
return last
elif self.method == 'cba':
hidden = K.dot(memory, self.Wh) + K.expand_dims(K.dot(query, self.Wq), 1)
hidden = K.tanh(hidden)
s = K.squeeze(K.dot(hidden, self.v), -1)
elif self.method == 'ga':
s = K.sum(K.expand_dims(K.dot(query, self.Wq), 1) * memory, axis=-1)
else:
s = K.squeeze(K.dot(memory, self.v), -1)
s = K.softmax(s)
if mask is not None:
mask = mask[:,:-1]
s *= K.cast(mask, dtype='float32')
sum_by_time = K.sum(s, axis=-1, keepdims=True)
s = s / (sum_by_time + K.epsilon())
#return [K.concatenate([K.sum(memory * K.expand_dims(s), axis=1), last], axis=-1), s]
result = K.concatenate([K.sum(memory * K.expand_dims(s), axis=1), last], axis=-1)
if len(input_shape)>3:
output_shape = K.int_shape(result)
return K.reshape(result, (-1, input_shape[1], output_shape[-1]))
else:
return result
def compute_mask(self, inputs, mask=None):
if isinstance(inputs, list):
memory = inputs[0]
else:
memory = inputs
if len(K.int_shape(memory)) > 3 and mask is not None:
return K.all(mask, axis=-1)
else:
return None
def compute_output_shape(self, input_shape):
if isinstance(input_shape, list):
att_size = input_shape[0][-1]
seq_len = input_shape[0][1]
batch = input_shape[0][0]
else:
att_size = input_shape[-1]
seq_len = input_shape[1]
batch = input_shape[0]
#shape2 = (batch, seq_len, 1)
if len(input_shape)>3:
if self.method is not None:
shape1 = (batch, seq_len, att_size*2)
else:
shape1 = (batch, seq_len, att_size)
#return [shape1, shape2]
return shape1
else:
if self.method is not None:
shape1 = (batch, att_size*2)
else:
shape1 = (batch, att_size)
#return [shape1, shape2]
return shape1