-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtransformer.py
431 lines (360 loc) · 14.6 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
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
"""Transformer with multi head attention."""
import torch
from torch import nn
from torch import Tensor
import torch.nn.functional as f
def scaled_dot_product_attention(query: Tensor, key: Tensor, value: Tensor) -> Tensor:
"""
Compute scaled dot-product attention between the query, key, and value tensors.
Args:
query (Tensor): The query tensor of shape (batch_size, num_query, query_dim).
key (Tensor): The key tensor of shape (batch_size, num_key, key_dim).
value (Tensor): The value tensor of shape (batch_size, num_value, value_dim).
Returns:
Tensor: The attention tensor of shape (batch_size, num_query, value_dim).
"""
temp = query.bmm(key.transpose(1, 2))
scale = query.size(-1) ** 0.5
softmax = f.softmax(temp / scale, dim=-1)
return softmax.bmm(value)
class AttentionHead(nn.Module):
"""Create a single attention head."""
def __init__(self, dim_in: int, dim_q: int, dim_k: int):
"""
A single attention head that computes attention scores between the query, key,
and value tensors.
Args:
dim_in (int): The input dimension of the query, key, and value tensors.
dim_q (int): The output dimension of the query tensor.
dim_k (int): The output dimension of the key and value tensors.
"""
super().__init__()
self.q = nn.Linear(dim_in, dim_q)
self.k = nn.Linear(dim_in, dim_k)
self.v = nn.Linear(dim_in, dim_k)
def forward(self, query: Tensor, key: Tensor, value: Tensor) -> Tensor:
"""
Compute attention scores between the query, key, and value tensors.
Args:
query (Tensor): The query tensor of shape (batch_size, num_query, query_dim)
key (Tensor): The key tensor of shape (batch_size, num_key, key_dim)
value (Tensor): The value tensor of shape (batch_size, num_value, value_dim)
Returns:
Tensor: The attention tensor of shape (batch_size, num_query, value_dim)
"""
return scaled_dot_product_attention(self.q(query), self.k(key), self.v(value))
class MultiHeadAttention(nn.Module):
"""Create multiple attention heads."""
def __init__(self, num_heads: int, dim_in: int, dim_q: int, dim_k: int):
"""
Initializes a Multi-Head Attention module.
Args:
- num_heads (int): The number of attention heads to use.
- dim_in (int): The dimensionality of the input tensor.
- dim_q (int): The dimensionality of the query tensor.
- dim_k (int): The dimensionality of the key tensor.
"""
super().__init__()
self.heads = nn.ModuleList(
[AttentionHead(dim_in, dim_q, dim_k) for _ in range(num_heads)]
)
self.linear = nn.Linear(num_heads * dim_k, dim_in)
def forward(self, query: Tensor, key: Tensor, value: Tensor) -> Tensor:
"""
Computes the forward pass of the Multi-Head Attention module.
Args:
- query (Tensor): The query tensor of shape (batch_size, seq_len_q, dim_q).
- key (Tensor): The key tensor of shape (batch_size, seq_len_k, dim_k).
- value (Tensor): The value tensor of shape (batch_size, seq_len_v, dim_v).
Returns:
- output (Tensor): The output tensor of shape (batch_size, seq_len_q, dim_in).
"""
return self.linear(
torch.cat([h(query, key, value) for h in self.heads], dim=-1)
)
def position_encoding(
seq_len: int,
dim_model: int,
device: torch.device = torch.device("cpu"),
) -> Tensor:
"""
Generate the positional encoding for a given sequence length and dimensionality.
Args:
seq_len (int): The length of the input sequence.
dim_model (int): The dimensionality of the input sequence.
device (torch.device, optional): The device on which to create the tensor.
Returns:
Tensor: The positional encoding tensor of shape (1, seq_len, dim_model).
"""
pos = torch.arange(seq_len, dtype=torch.float, device=device).reshape(1, -1, 1)
dim = torch.arange(dim_model, dtype=torch.float, device=device).reshape(1, 1, -1)
phase = pos / (1e4 ** (dim / dim_model))
return torch.where(dim.long() % 2 == 0, torch.sin(phase), torch.cos(phase))
def feed_forward(
dim_input: int = 512, dim_feedforward: int = 2048, activation: nn.Module = nn.ReLU()
) -> nn.Module:
"""
Create a feedforward network module with two linear layers and an activation function.
Args:
dim_input (int, optional): The dimensionality of the input tensor
dim_feedforward (int, optional): The dimensionality of the hidden layer
activation (nn.Module, optional): The activation function to use
Returns:
nn.Module: The feedforward network module
"""
return nn.Sequential(
nn.Linear(dim_input, dim_feedforward),
activation,
nn.Linear(dim_feedforward, dim_input),
)
class Residual(nn.Module):
def __init__(self, sublayer: nn.Module, dimension: int, dropout: float = 0.1):
"""
Apply residual connections to a sublayer module.
Args:
sublayer (nn.Module): The sublayer module to apply the residual connection to
dimension (int): The dimensionality of the sublayer input/output tensors
dropout (float, optional): The dropout probability to apply
"""
super().__init__()
self.sublayer = sublayer
self.norm = nn.LayerNorm(dimension)
self.dropout = nn.Dropout(dropout)
def forward(self, *tensors: Tensor) -> Tensor:
"""
Compute a forward pass through the residual module.
Args:
tensors (Tuple[Tensor]): The input tensor(s) to the sublayer.
Returns:
Tensor: The output tensor of the residual module.
"""
# Assume that the "query" tensor is given first, so we can compute the
# residual. This matches the signature of 'MultiHeadAttention'.
return self.norm(tensors[0] + self.dropout(self.sublayer(*tensors)))
class TransformerEncoderLayer(nn.Module):
"""Create encoder layer of transformer."""
def __init__(
self,
dim_model: int = 512,
num_heads: int = 6,
dim_feedforward: int = 2048,
dropout: float = 0.1,
activation: nn.Module = nn.ReLU(),
):
"""
Initialize a encoder layer.
Args:
- dim_model (int): The dimensionality of the input sequence.
- num_heads (int): The number of attention heads to use.
- dim_feedforward (int, optional): The dimensionality of the hidden layer.
- dropout (float, optional): The dropout probability to apply.
- activation (nn.Module, optional): The activation function to use.
"""
super().__init__()
dim_q = dim_k = max(dim_model // num_heads, 1)
self.attention = Residual(
MultiHeadAttention(num_heads, dim_model, dim_q, dim_k),
dimension=dim_model,
dropout=dropout,
)
self.feed_forward = Residual(
feed_forward(dim_model, dim_feedforward, activation),
dimension=dim_model,
dropout=dropout,
)
def forward(self, src: Tensor) -> Tensor:
"""
Compute a forward pass through the encoder layer.
Args:
src (Tensor): The input tensor(s) to the sublayer.
Returns:
Tensor: The output tensor of the encoder layer.
"""
src = self.attention(src, src, src)
return self.feed_forward(src)
class TransformerEncoder(nn.Module):
"""Create encoder part of transformer."""
def __init__(
self,
num_layers: int = 6,
dim_model: int = 512,
num_heads: int = 8,
dim_feedforward: int = 2048,
dropout: float = 0.1,
activation: nn.Module = nn.ReLU(),
):
"""
Initialize the encoder part of transformer.
Args:
- num_layers (int): The number of encoder layers to create.
- dim_model (int): The dimensionality of the input sequence.
- num_heads (int): The number of attention heads to use.
- dim_feedforward (int, optional): The dimensionality of the hidden layer.
- dropout (float, optional): The dropout probability to apply.
- activation (nn.Module, optional): The activation function to use.
"""
super().__init__()
self.layers = nn.ModuleList(
[
TransformerEncoderLayer(
dim_model, num_heads, dim_feedforward, dropout, activation
)
for _ in range(num_layers)
]
)
def forward(self, src: Tensor) -> Tensor:
"""
Compute a forward pass through the encoder module.
Args:
src (Tensor): The input tensor(s) to the sublayer.
Returns:
Tensor: The output tensor of the encoder module.
"""
seq_len, dimension = src.size(1), src.size(2)
src += position_encoding(seq_len, dimension)
for layer in self.layers:
src = layer(src)
return src
class TransformerDecoderLayer(nn.Module):
"""Create decoder layer of transformer."""
def __init__(
self,
dim_model: int = 512,
num_heads: int = 6,
dim_feedforward: int = 2048,
dropout: float = 0.1,
activation: nn.Module = nn.ReLU(),
):
"""
Initialize a decoder layer.
Args:
- dim_model (int): The dimensionality of the input sequence.
- num_heads (int): The number of attention heads to use.
- dim_feedforward (int, optional): The dimensionality of the hidden layer.
- dropout (float, optional): The dropout probability to apply.
- activation (nn.Module, optional): The activation function to use.
"""
super().__init__()
dim_q = dim_k = max(dim_model // num_heads, 1)
self.attention_1 = Residual(
MultiHeadAttention(num_heads, dim_model, dim_q, dim_k),
dimension=dim_model,
dropout=dropout,
)
self.attention_2 = Residual(
MultiHeadAttention(num_heads, dim_model, dim_q, dim_k),
dimension=dim_model,
dropout=dropout,
)
self.feed_forward = Residual(
feed_forward(dim_model, dim_feedforward, activation),
dimension=dim_model,
dropout=dropout,
)
def forward(self, tgt: Tensor, memory: Tensor) -> Tensor:
"""
Compute a forward pass through the decoder layer.
Args:
tgt (Tensor): The input tensor(s) to the decoder.
memory (Tensor): The input tensor(s) from the sublayer.
Returns:
Tensor: The output tensor of the decoder layer.
"""
tgt = self.attention_1(tgt, tgt, tgt)
tgt = self.attention_2(tgt, memory, memory)
return self.feed_forward(tgt)
class TransformerDecoder(nn.Module):
"""Create decoder part of transformer."""
def __init__(
self,
num_layers: int = 6,
dim_model: int = 512,
num_heads: int = 8,
dim_feedforward: int = 2048,
dropout: float = 0.1,
activation: nn.Module = nn.ReLU(),
):
"""
Initialize the decoder part of transformer.
Args:
- num_layers (int): The number of encoder layers to create.
- dim_model (int): The dimensionality of the input sequence.
- num_heads (int): The number of attention heads to use.
- dim_feedforward (int, optional): The dimensionality of the hidden layer.
- dropout (float, optional): The dropout probability to apply.
- activation (nn.Module, optional): The activation function to use.
"""
super().__init__()
self.layers = nn.ModuleList(
[
TransformerDecoderLayer(
dim_model, num_heads, dim_feedforward, dropout, activation
)
for _ in range(num_layers)
]
)
self.linear = nn.Linear(dim_model, dim_model)
def forward(self, tgt: Tensor, memory: Tensor) -> Tensor:
"""
Compute a forward pass through the decoder.
Args:
tgt (Tensor): The input tensor(s) to the decoder.
memory (Tensor): The input tensor(s) from the sublayer.
Returns:
Tensor: The output tensor of the decoder.
"""
seq_len, dimension = tgt.size(1), tgt.size(2)
tgt += position_encoding(seq_len, dimension)
for layer in self.layers:
tgt = layer(tgt, memory)
return self.linear(tgt)
class Transformer(nn.Module):
"""Build transformer with encoder and decoder."""
def __init__(
self,
num_encoder_layers: int = 6,
num_decoder_layers: int = 6,
dim_model: int = 512,
num_heads: int = 6,
dim_feedforward: int = 2048,
dropout: float = 0.1,
activation: nn.Module = nn.ReLU(),
):
"""
Initialize the transformer.
Args:
- num_encoder_layers (int): The number of encoder layers to create.
- num_decoder_layers (int): The number of decoder layers to create.
- dim_model (int): The dimensionality of the input sequence.
- num_heads (int): The number of attention heads to use.
- dim_feedforward (int, optional): The dimensionality of the hidden layer.
- dropout (float, optional): The dropout probability to apply.
- activation (nn.Module, optional): The activation function to use.
"""
super().__init__()
self.encoder = TransformerEncoder(
num_layers=num_encoder_layers,
dim_model=dim_model,
num_heads=num_heads,
dim_feedforward=dim_feedforward,
dropout=dropout,
activation=activation,
)
self.decoder = TransformerDecoder(
num_layers=num_decoder_layers,
dim_model=dim_model,
num_heads=num_heads,
dim_feedforward=dim_feedforward,
dropout=dropout,
activation=activation,
)
def forward(self, src: Tensor, tgt: Tensor) -> Tensor:
"""
Compute a forward pass through the transformer.
Args:
src (Tensor): The input tensor(s) to the encoder.
tgt (Tensor): The input tensor(s) to the decoder.
Returns:
Tensor: The output tensor of the decoder.
"""
return self.decoder(tgt, self.encoder(src))