-
Notifications
You must be signed in to change notification settings - Fork 12
/
layers.py
312 lines (253 loc) · 8.86 KB
/
layers.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
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange, repeat
import numpy as np
import math
from math import sqrt
from utils.sparse_max import Sparsemax
from utils.entmax import Entmax15
from utils.general_entmax import EntmaxAlpha
class FullAttention(nn.Module):
'''
The Attention operation
'''
def __init__(self, scale=None, attention_dropout=0.0):
super(FullAttention, self).__init__()
self.scale = scale
self.dropout = nn.Dropout(attention_dropout)
def forward(self, queries, keys, values, mask=None):
B, L, H, E = queries.shape
_, S, _, D = values.shape
scale = self.scale or 1. / sqrt(E)
scores = torch.einsum("blhe,bshe->bhls", queries, keys)
if mask is not None:
mask = mask.unsqueeze(1).unsqueeze(1).repeat(1, H, scores.size(-2), 1)
scores = scores.masked_fill_(mask, float('-inf'))
A = self.dropout(torch.softmax(scale * scores, dim=-1))
V = torch.einsum("bhls,bshd->blhd", A, values)
return V.contiguous()
class AttentionLayer(nn.Module):
'''
The Multi-head Self-Attention (MSA) Layer
'''
def __init__(
self,
d_model,
n_heads,
d_keys=None,
d_values=None,
mix=True,
dropout=0.1,
scale=None):
super(AttentionLayer, self).__init__()
d_keys = d_keys or (d_model // n_heads)
d_values = d_values or (d_model // n_heads)
self.d_model = d_model
self.inner_attention = FullAttention(
scale=scale, attention_dropout=dropout)
self.query_projection = nn.Linear(d_model, d_keys * n_heads)
self.key_projection = nn.Linear(d_model, d_keys * n_heads)
self.value_projection = nn.Linear(d_model, d_values * n_heads)
self.out_projection = nn.Linear(d_values * n_heads, d_model)
self.n_heads = n_heads
self.mix = mix
def forward(self, inputs):
queries = inputs
keys = inputs
values = inputs
B, L, _ = queries.shape
_, S, _ = keys.shape
H = self.n_heads
queries = self.query_projection(queries).view(B, L, H, -1)
keys = self.key_projection(keys).view(B, S, H, -1)
values = self.value_projection(values).view(B, S, H, -1)
out = self.inner_attention(
queries,
keys,
values,
)
out = out.view(B, L, -1)
out = out.mean(1)
return self.out_projection(out)
class HopfieldCore(nn.Module):
'''
The Hopfield operation
'''
def __init__(self, scale=None, attention_dropout=0.0, mode='sparsemax', norm=False):
super(HopfieldCore, self).__init__()
self.scale = scale
self.norm = norm
self.dropout = nn.Dropout(attention_dropout)
if mode == 'sparsemax':
self.softmax = Sparsemax(dim=-1)
elif mode == 'entmax':
self.softmax = Entmax15(dim=-1)
elif mode == 'gsh':
self.softmax = EntmaxAlpha(dim=-1)
else:
self.softmax = nn.Softmax(dim=-1)
def forward(self, queries, keys, values, mask=None):
B, L, H, E = queries.shape
_, S, _, D = values.shape
scale = self.scale or 1. / sqrt(E)
scores = torch.einsum("blhe,bshe->bhls", queries, keys)
if self.norm and H == 1:
scores = F.normalize(scores)
if mask is not None:
mask = mask.unsqueeze(1).unsqueeze(1).repeat(1, H, scores.size(-2), 1)
scores = scores.masked_fill_(mask, float('-inf'))
A = self.dropout(torch.softmax(scale * scores, dim=-1))
V = torch.einsum("bhls,bshd->blhd", A, values)
return V.contiguous()
class Hopfield(nn.Module):
'''
The Multi-head Self-Attention (MSA) Layer
'''
def __init__(
self,
d_model,
n_heads,
d_keys=None,
d_values=None,
mix=True,
update_steps=1,
dropout=0.1,
mode='softmax',
scale=None):
super(Hopfield, self).__init__()
d_keys = d_keys or (d_model // n_heads)
d_values = d_values or (d_model // n_heads)
self.d_model = d_model
self.inner_attention = HopfieldCore(
scale=scale, attention_dropout=dropout, mode=mode)
self.query_projection = nn.Linear(d_model, d_keys * n_heads)
self.key_projection = nn.Linear(d_model, d_keys * n_heads)
self.value_projection = nn.Linear(
d_values * n_heads, d_values * n_heads)
self.out_projection = nn.Linear(d_values * n_heads, d_model)
self.n_heads = n_heads
self.mix = mix
self.update_steps = update_steps
def forward(self, R, Y, mask=None):
B, L, _ = R.shape
_, S, _ = Y.shape
H = self.n_heads
queries = self.query_projection(R).view(B, L, H, -1)
keys = self.key_projection(Y)
values = self.value_projection(keys).view(B, S, H, -1)
keys = keys.view(B, S, H, -1)
for i in range(self.update_steps):
queries = self.inner_attention(
queries,
keys,
values,
mask
)
out = queries
out = out.view(B, L, -1)
return self.out_projection(out)
class HopfieldPooling(nn.Module):
'''
The Multi-head Self-Attention (MSA) Layer
'''
def __init__(
self,
d_model,
n_heads,
d_keys=None,
d_values=None,
mix=True,
num_pattern=1,
update_steps=1,
dropout=0.1,
mode='softmax',
scale=None):
super(HopfieldPooling, self).__init__()
d_keys = d_keys or (d_model // n_heads)
d_values = d_values or (d_model // n_heads)
self.d_model = d_model
self.inner_attention = HopfieldCore(
scale=scale, attention_dropout=dropout, mode=mode)
self.query_projection = nn.Linear(d_model, d_keys * n_heads)
self.key_projection = nn.Linear(d_model, d_keys * n_heads)
self.value_projection = nn.Linear(
d_values * n_heads, d_values * n_heads)
self.out_projection = nn.Linear(d_values * n_heads, d_model)
self.n_heads = n_heads
self.mix = mix
self.update_steps = update_steps
pooling_weight_size = d_model
self.query = nn.Parameter(
torch.randn(
size=(
*
(
(1,
num_pattern)),
d_model if pooling_weight_size is None else pooling_weight_size), dtype=torch.float32),
requires_grad=True)
def forward(self, Y, mask=None):
# queries : state pattern
# keys : store pattern
# values : should just be keys
B, L, _ = self.query.shape
B, S, _ = Y.shape
H = self.n_heads
q = self.query.repeat((*((B, 1)), 1))
queries = self.query_projection(q).view(B, L, H, -1)
keys = self.key_projection(Y)
values = self.value_projection(keys).view(B, S, H, -1)
keys = keys.view(B, S, H, -1)
for _ in range(self.update_steps):
queries = self.inner_attention(
queries,
keys,
values,
mask
)
out = queries
out = out.view(B, L, -1)
return self.out_projection(out)
class HopfieldLayer(nn.Module):
def __init__(
self,
d_model,
n_heads,
d_keys=None,
d_values=None,
mix=False,
update_steps=1,
dropout=0.0,
mode='softmax',
scale=None):
super(HopfieldLayer, self).__init__()
d_keys = d_keys or (d_model // n_heads)
d_values = d_values or (d_model // n_heads)
self.d_model = d_model
self.ln = nn.LayerNorm(d_model, elementwise_affine=False)
if mode in ["sparsemax", "softmax", "entmax", "gsh"]:
self.inner_attention = HopfieldCore(
scale=scale, attention_dropout=dropout, mode=mode, norm=True)
self.n_heads = n_heads
self.mix = mix
self.update_steps = update_steps
def forward(self, R, Y):
# R : query pattern
# Y : memory pattern
B, L, _ = R.shape
B, S, _ = Y.shape
H = self.n_heads
# R, Y = self.ln(R), self.ln(Y)
queries = R.view(B, L, H, -1)
keys = Y.view(B, S, H, -1)
values = Y.view(B, S, H, -1)
for _ in range(self.update_steps):
queries = self.inner_attention(
queries,
keys,
values,
)
out = queries
out = out.view(B, L, -1)
return out