-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
114 lines (87 loc) · 3.14 KB
/
main.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
import torch
from util import MultiHead, FullyConnectedOutput, PositionEmbedding
from mask import mask_pad, mask_tril
class EncoderLayer(torch.nn.Module):
def __init__(self):
super().__init__()
# 多头注意力层
self.mh = MultiHead()
# 全连接层
self.fc = FullyConnectedOutput()
def forward(self, x, mask):
# 计算自注意力,维度不变
# [b, 40, 32] -> [b, 40, 32]
score = self.mh(x, x, x, mask)
# 全连接输出,维度不变
# [b, 40, 32] -> [b, 40, 32]
out = self.fc(score)
return out
class Encoder(torch.nn.Module):
def __init__(self):
super().__init__()
self.layer_1 = EncoderLayer()
self.layer_2 = EncoderLayer()
self.layer_3 = EncoderLayer()
def forward(self, x, mask):
x = self.layer_1(x, mask)
x = self.layer_2(x, mask)
x = self.layer_3(x, mask)
return x
class DecoderLayer(torch.nn.Module):
def __init__(self):
super().__init__()
# mask的那部分
self.mh1 = MultiHead()
# 从encoder那边来的部分
self.mh2 = MultiHead()
# 全连接层
self.fc = FullyConnectedOutput()
def forward(self, x, y, mask_pad_x, mask_tril_y):
# 先计算y的自注意力,维度不变
# [b, 40, 32] -> [b, 40, 32]
# mask_tril_y为了预测下一个词
y = self.mh1(y, y, y, mask_tril_y)
# 结合x和y的注意力计算,维度不变
# [b, 40, 32],[b, 40, 32] -> [b, 40, 32]
y = self.mh2(y, x, x, mask_pad_x)
# 全连接输出,维度不变
# [b, 40, 32] -> [b, 40, 32]
y = self.fc(y)
return y
class Decoder(torch.nn.Module):
def __init__(self):
super().__init__()
self.layer_1 = DecoderLayer()
self.layer_2 = DecoderLayer()
self.layer_3 = DecoderLayer()
def forward(self, x, y, mask_pad_x, mask_tril_y):
y = self.layer_1(x, y, mask_pad_x, mask_tril_y)
y = self.layer_2(x, y, mask_pad_x, mask_tril_y)
y = self.layer_3(x, y, mask_pad_x, mask_tril_y)
return y
class Transformer(torch.nn.Module):
def __init__(self):
super().__init__()
self.embed_x = PositionEmbedding()
self.embed_y = PositionEmbedding()
self.encoder = Encoder()
self.decoder = Decoder()
self.fc_out = torch.nn.Linear(32, 39)
def forward(self, x, y):
# [b, 1, 40, 40]
mask_pad_x = mask_pad(x)
mask_tril_y = mask_tril(y)
# 编码,添加位置信息
# x = [b, 40] -> [b, 40, 32]
# y = [b, 40] -> [b, 40, 32]
x, y = self.embed_x(x), self.embed_y(y)
# 编码层计算
# [b, 40, 32] -> [b, 40, 32]
x = self.encoder(x, mask_pad_x)
# 解码层计算
# [b, 40, 32],[b, 40, 32] -> [b, 40, 32]
y = self.decoder(x, y, mask_pad_x, mask_tril_y)
# 全连接输出,维度不变
# [b, 40, 32] -> [b, 40, 39]
y = self.fc_out(y)
return y