-
Notifications
You must be signed in to change notification settings - Fork 4
/
embedding.py
254 lines (185 loc) · 8.37 KB
/
embedding.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
from utils import *
class embed(nn.Module):
def __init__(self, ls, cti, wti, batch_first = False, hre = False):
super().__init__()
self.dim = sum(ls.values())
self.batch_first = batch_first
# architecture
self.char_embed = None
self.word_embed = None
self.sent_embed = None
for model, dim in ls.items():
assert model in ("lookup", "cnn", "rnn", "sae")
if model in ("cnn", "rnn"):
self.char_embed = getattr(self, model)(len(cti), dim)
if model in ("lookup", "sae"):
self.word_embed = getattr(self, model)(len(wti), dim)
if hre:
self.sent_embed = self.rnn(self.dim, self.dim, hre = True)
self = self.cuda() if CUDA else self
def forward(self, b, xc, xw):
hc, hw = None, None
if self.char_embed:
hc = self.char_embed(xc) # [Ls, B * Ld, Lw] -> [Ls, B * Ld, Hc]
if self.word_embed:
hw = self.word_embed(xw) # [Ls, B * Ld] -> [Ls, B * Ld, Hw]
h = torch.cat([h for h in [hc, hw] if type(h) == torch.Tensor], 2)
if self.sent_embed:
if self.batch_first:
h.transpose_(0, 1)
h = self.sent_embed(h) # [Lw, B * Ld, H] -> [1, B * Ld, H]
h = h.view(b, -1, h.size(2)) # [B, Ld, H]
if not self.batch_first:
h.transpose_(0, 1)
return h
class lookup(nn.Module):
def __init__(self, vocab_size, embed_size):
super().__init__()
self.embed = nn.Embedding(vocab_size, embed_size, padding_idx = PAD_IDX)
def forward(self, x):
return self.embed(x) # [Ls, B * Ld, H]
class cnn(nn.Module):
def __init__(self, vocab_size, embed_size):
super().__init__()
dim = 50
num_featmaps = 50 # feature maps generated by each kernel
kernel_sizes = [3]
# architecture
self.embed = nn.Embedding(vocab_size, dim, padding_idx = PAD_IDX)
self.conv = nn.ModuleList([nn.Conv2d(
in_channels = 1, # Ci
out_channels = num_featmaps, # Co
kernel_size = (i, dim) # height, width
) for i in kernel_sizes]) # num_kernels (K)
self.dropout = nn.Dropout(DROPOUT)
self.fc = nn.Linear(len(kernel_sizes) * num_featmaps, embed_size)
def forward(self, x):
b = x.size(1) # B' = B * Ld
x = x.reshape(-1, x.size(2)) # [B' * Ls, Lw]
x = self.embed(x).unsqueeze(1) # [B' * Ls, Ci = 1, Lw, dim]
h = [conv(x) for conv in self.conv] # [B' * Ls, Co, Lw, 1] * K
h = [F.relu(k).squeeze(3) for k in h] # [B' * Ls, Co, Lw] * K
h = [F.max_pool1d(k, k.size(2)).squeeze(2) for k in h] # [B' * Ls, Co] * K
h = torch.cat(h, 1) # [B' * Ls, Co * K]
h = self.dropout(h)
h = self.fc(h) # fully connected layer [B' * Ls, H]
h = h.view(-1, b, h.size(1)) # [Ls, B', H]
return h
class rnn(nn.Module):
def __init__(self, vocab_size, embed_size, hre = False):
super().__init__()
self.dim = embed_size
self.rnn_type = "GRU" # LSTM, GRU
self.num_dirs = 2 # unidirectional: 1, bidirectional: 2
self.num_layers = 2
self.hre = hre
# architecture
self.embed = nn.Embedding(vocab_size, embed_size, padding_idx = PAD_IDX)
self.rnn = getattr(nn, self.rnn_type)(
input_size = self.dim,
hidden_size = self.dim // self.num_dirs,
num_layers = self.num_layers,
bias = True,
dropout = DROPOUT,
bidirectional = (self.num_dirs == 2)
)
def init_state(self, b): # initialize RNN states
n = self.num_layers * self.num_dirs
h = self.dim // self.num_dirs
hs = zeros(n, b, h) # hidden state
if self.rnn_type == "GRU":
return hs
cs = zeros(n, b, h) # LSTM cell state
return (hs, cs)
def forward(self, x):
b = x.size(1) # B' = B * Ld
s = self.init_state(b * (1 if self.hre else x.size(0)))
if not self.hre: # [Ls, B', Lw] -> [Lw, B' * Ls, H]
x = x.reshape(-1, x.size(2)).transpose(0, 1)
x = self.embed(x)
h, s = self.rnn(x, s)
h = s if self.rnn_type == "GRU" else s[-1]
h = torch.cat([x for x in h[-self.num_dirs:]], 1) # final hidden state
h = h.view(-1, b, h.size(1)) # [Ls, B', H]
return h
class sae(nn.Module): # self-attentive encoder
def __init__(self, vocab_size, embed_size = 512):
super().__init__()
dim = embed_size
num_layers = 1
# architecture
self.embed = nn.Embedding(vocab_size, dim, padding_idx = PAD_IDX)
self.pe = self.pos_encoding(dim)
self.layers = nn.ModuleList([self.layer(dim) for _ in range(num_layers)])
def forward(self, x):
mask = x.eq(PAD_IDX).view(x.size(0), 1, 1, -1)
x = self.embed(x)
h = x + self.pe[:x.size(1)]
for layer in self.layers:
h = layer(h, mask)
return h
def pos_encoding(self, dim, maxlen = 1000): # positional encoding
pe = Tensor(maxlen, dim)
pos = torch.arange(0, maxlen, 1.).unsqueeze(1)
k = torch.exp(-np.log(10000) * torch.arange(0, dim, 2.) / dim)
pe[:, 0::2] = torch.sin(pos * k)
pe[:, 1::2] = torch.cos(pos * k)
return pe
class layer(nn.Module): # encoder layer
def __init__(self, dim):
super().__init__()
# architecture
self.attn = embed.sae.mh_attn(dim)
self.ffn = embed.sae.ffn(dim)
def forward(self, x, mask):
z = self.attn(x, x, x, mask)
z = self.ffn(z)
return z
class mh_attn(nn.Module): # multi-head attention
def __init__(self, dim):
super().__init__()
self.D = dim # dimension of model
self.H = 8 # number of heads
self.Dk = self.D // self.H # dimension of key
self.Dv = self.D // self.H # dimension of value
# architecture
self.Wq = nn.Linear(self.D, self.H * self.Dk) # query
self.Wk = nn.Linear(self.D, self.H * self.Dk) # key
self.Wv = nn.Linear(self.D, self.H * self.Dv) # value
self.Wo = nn.Linear(self.H * self.Dv, self.D)
self.dropout = nn.Dropout(DROPOUT)
self.norm = nn.LayerNorm(self.D)
def sdp_attn(self, q, k, v, mask): # scaled dot-product attention
c = np.sqrt(self.Dk)
a = torch.matmul(q, k.transpose(2, 3)) / c
a = a.masked_fill(mask, -10000)
a = F.softmax(a, 2)
a = torch.matmul(a, v)
return a # attention weights
def forward(self, q, k, v, mask):
b = q.size(0)
x = q
q = self.Wq(q).view(b, -1, self.H, self.Dk).transpose(1, 2)
k = self.Wk(k).view(b, -1, self.H, self.Dk).transpose(1, 2)
v = self.Wv(v).view(b, -1, self.H, self.Dv).transpose(1, 2)
z = self.sdp_attn(q, k, v, mask)
z = z.transpose(1, 2).contiguous().view(b, -1, self.H * self.Dv)
z = self.Wo(z)
z = self.norm(x + self.dropout(z)) # residual connection and dropout
return z
class ffn(nn.Module): # position-wise feed-forward networks
def __init__(self, dim):
super().__init__()
dim_ffn = 2048
# architecture
self.layers = nn.Sequential(
nn.Linear(dim, dim_ffn),
nn.ReLU(),
nn.Dropout(DROPOUT),
nn.Linear(dim_ffn, dim)
)
self.norm = nn.LayerNorm(dim)
def forward(self, x):
z = x + self.layers(x) # residual connection
z = self.norm(z) # layer normalization
return z