-
Notifications
You must be signed in to change notification settings - Fork 5
/
transformer.py
218 lines (161 loc) · 7.34 KB
/
transformer.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
'''
Copied from SLATE (https://github.com/singhgautam/slate/blob/master/transformer.py) and slightly modified
'''
from utils_spot import *
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads, dropout=0., gain=1.):
super().__init__()
assert d_model % num_heads == 0, "d_model must be divisible by num_heads"
self.d_model = d_model
self.num_heads = num_heads
self.attn_dropout = nn.Dropout(dropout)
self.output_dropout = nn.Dropout(dropout)
self.proj_q = linear(d_model, d_model, bias=False)
self.proj_k = linear(d_model, d_model, bias=False)
self.proj_v = linear(d_model, d_model, bias=False)
self.proj_o = linear(d_model, d_model, bias=False, gain=gain)
def forward(self, q, k, v, attn_mask=None):
"""
q: batch_size x target_len x d_model
k: batch_size x source_len x d_model
v: batch_size x source_len x d_model
attn_mask: target_len x source_len
return: batch_size x target_len x d_model
"""
B, T, _ = q.shape
_, S, _ = k.shape
q = self.proj_q(q).view(B, T, self.num_heads, -1).transpose(1, 2)
k = self.proj_k(k).view(B, S, self.num_heads, -1).transpose(1, 2)
v = self.proj_v(v).view(B, S, self.num_heads, -1).transpose(1, 2)
q = q * (q.shape[-1] ** (-0.5))
attn = torch.matmul(q, k.transpose(-1, -2))
if attn_mask is not None:
attn = attn.masked_fill(attn_mask, float('-inf'))
attn = F.softmax(attn, dim=-1)
attn = self.attn_dropout(attn)
output = torch.matmul(attn, v).transpose(1, 2).reshape(B, T, -1)
output = self.proj_o(output)
output = self.output_dropout(output)
return output
class PositionalEncoding(nn.Module):
def __init__(self, max_len, d_model, dropout=0.1):
super().__init__()
self.dropout = nn.Dropout(dropout)
self.pe = nn.Parameter(torch.zeros(1, max_len, d_model), requires_grad=True)
nn.init.trunc_normal_(self.pe)
def forward(self, input):
"""
input: batch_size x seq_len x d_model
return: batch_size x seq_len x d_model
"""
T = input.shape[1]
return self.dropout(input + self.pe[:, :T])
class TransformerEncoderBlock(nn.Module):
def __init__(self, d_model, num_heads, dropout=0., gain=1., is_first=False):
super().__init__()
self.is_first = is_first
self.attn_layer_norm = nn.LayerNorm(d_model)
self.attn = MultiHeadAttention(d_model, num_heads, dropout, gain)
self.ffn_layer_norm = nn.LayerNorm(d_model)
self.ffn = nn.Sequential(
linear(d_model, 4 * d_model, weight_init='kaiming'),
nn.ReLU(),
linear(4 * d_model, d_model, gain=gain),
nn.Dropout(dropout))
def forward(self, input):
"""
input: batch_size x source_len x d_model
return: batch_size x source_len x d_model
"""
if self.is_first:
input = self.attn_layer_norm(input)
x = self.attn(input, input, input)
input = input + x
else:
x = self.attn_layer_norm(input)
x = self.attn(x, x, x)
input = input + x
x = self.ffn_layer_norm(input)
x = self.ffn(x)
return input + x
class TransformerEncoder(nn.Module):
def __init__(self, num_blocks, d_model, num_heads, dropout=0.):
super().__init__()
if num_blocks > 0:
gain = (2 * num_blocks) ** (-0.5)
self.blocks = nn.ModuleList(
[TransformerEncoderBlock(d_model, num_heads, dropout, gain, is_first=True)] +
[TransformerEncoderBlock(d_model, num_heads, dropout, gain, is_first=False)
for _ in range(num_blocks - 1)])
else:
self.blocks = nn.ModuleList()
self.layer_norm = nn.LayerNorm(d_model)
def forward(self, input):
"""
input: batch_size x source_len x d_model
return: batch_size x source_len x d_model
"""
for block in self.blocks:
input = block(input)
return self.layer_norm(input)
class TransformerDecoderBlock(nn.Module):
def __init__(self, max_len, d_model, num_heads, dropout=0., gain=1., is_first=False, num_cross_heads=None):
super().__init__()
self.is_first = is_first
self.self_attn_layer_norm = nn.LayerNorm(d_model)
self.self_attn = MultiHeadAttention(d_model, num_heads, dropout, gain)
mask = torch.triu(torch.ones((max_len, max_len), dtype=torch.bool), diagonal=1)
self.self_attn_mask = nn.Parameter(mask, requires_grad=False)
self.encoder_decoder_attn_layer_norm = nn.LayerNorm(d_model)
if num_cross_heads is None:
num_cross_heads = num_heads
self.encoder_decoder_attn = MultiHeadAttention(d_model, num_cross_heads, dropout, gain)
self.ffn_layer_norm = nn.LayerNorm(d_model)
self.ffn = nn.Sequential(
linear(d_model, 4 * d_model, weight_init='kaiming'),
nn.ReLU(),
linear(4 * d_model, d_model, gain=gain),
nn.Dropout(dropout))
def forward(self, input, encoder_output, causal_mask=True):
"""
input: batch_size x target_len x d_model
encoder_output: batch_size x source_len x d_model
return: batch_size x target_len x d_model
"""
T = input.shape[1]
self_attn_mask = self.self_attn_mask[:T, :T] if causal_mask else None
if self.is_first:
input = self.self_attn_layer_norm(input)
x = self.self_attn(input, input, input, self_attn_mask)
input = input + x
else:
x = self.self_attn_layer_norm(input)
x = self.self_attn(x, x, x, self_attn_mask)
input = input + x
x = self.encoder_decoder_attn_layer_norm(input)
x = self.encoder_decoder_attn(x, encoder_output, encoder_output)
input = input + x
x = self.ffn_layer_norm(input)
x = self.ffn(x)
return input + x
class TransformerDecoder(nn.Module):
def __init__(self, num_blocks, max_len, d_model, num_heads, dropout=0., num_cross_heads=None):
super().__init__()
if num_blocks > 0:
gain = (3 * num_blocks) ** (-0.5)
self.blocks = nn.ModuleList(
[TransformerDecoderBlock(max_len, d_model, num_heads, dropout, gain, is_first=True)] +
[TransformerDecoderBlock(max_len, d_model, num_heads, dropout, gain, is_first=False, num_cross_heads=num_cross_heads)
for _ in range(num_blocks - 1)])
else:
self.blocks = nn.ModuleList()
self.layer_norm = nn.LayerNorm(d_model)
def forward(self, input, encoder_output, causal_mask=True):
"""
input: batch_size x target_len x d_model
encoder_output: batch_size x source_len x d_model
return: batch_size x target_len x d_model
"""
for block in self.blocks:
input = block(input, encoder_output, causal_mask)
return self.layer_norm(input)