oucgc1996 commited on
Commit
a464b00
·
verified ·
1 Parent(s): ed2a20e

Delete bertmodel.py

Browse files
Files changed (1) hide show
  1. bertmodel.py +0 -199
bertmodel.py DELETED
@@ -1,199 +0,0 @@
1
- import torch.nn as nn
2
- import copy, math
3
- import torch
4
- import numpy as np
5
- import torch.nn.functional as F
6
-
7
- class Bert(nn.Module):
8
-
9
- def __init__(self, encoder, src_embed):
10
- super(Bert, self).__init__()
11
-
12
- self.encoder = encoder
13
- self.src_embed = src_embed
14
-
15
- def forward(self, src, src_mask):
16
-
17
- return self.encoder(self.src_embed(src), src_mask)
18
-
19
-
20
- class Encoder(nn.Module):
21
- "Encoder是N个EncoderLayer的堆积而成"
22
- def __init__(self, layer, N):
23
- super(Encoder, self).__init__()
24
- #layer是一个SubLayer,我们clone N个
25
- self.layers = clones(layer, N)
26
- #再加一个LayerNorm层
27
- self.norm = LayerNorm(layer.size)
28
-
29
- def forward(self, x, mask):
30
- "把输入(x,mask)被逐层处理"
31
- for layer in self.layers:
32
- x = layer(x, mask)
33
- return self.norm(x) #N个EncoderLayer处理完成之后还需要一个LayerNorm
34
-
35
- class LayerNorm(nn.Module):
36
- "构建一个layernorm模型"
37
- def __init__(self, features, eps=1e-6):
38
- super(LayerNorm, self).__init__()
39
- self.a_2 = nn.Parameter(torch.ones(features))
40
- self.b_2 = nn.Parameter(torch.zeros(features))
41
- self.eps = eps
42
-
43
- def forward(self, x):
44
- mean = x.mean(-1, keepdim=True)
45
- std = x.std(-1, keepdim=True)
46
- return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
47
-
48
- class SublayerConnection(nn.Module):
49
- """
50
- LayerNorm + sublayer(Self-Attenion/Dense) + dropout + 残差连接
51
- 为了简单,把LayerNorm放到了前面,这和原始论文稍有不同,原始论文LayerNorm在最后
52
- """
53
- def __init__(self, size, dropout):
54
- super(SublayerConnection, self).__init__()
55
- self.norm = LayerNorm(size)
56
- self.dropout = nn.Dropout(dropout)
57
-
58
- def forward(self, x, sublayer):
59
- #将残差连接应用于具有相同大小的任何子层
60
- return x + self.dropout(sublayer(self.norm(x)))
61
-
62
- class EncoderLayer(nn.Module):
63
- "Encoder由self-attn and feed forward构成"
64
- def __init__(self, size, self_attn, feed_forward, dropout):
65
- super(EncoderLayer, self).__init__()
66
- self.self_attn = self_attn
67
- self.feed_forward = feed_forward
68
- self.sublayer = clones(SublayerConnection(size, dropout), 2)
69
- self.size = size
70
-
71
- def forward(self, x, mask):
72
- "如上图所示"
73
- x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
74
- return self.sublayer[1](x, self.feed_forward)
75
-
76
- class PositionwiseFeedForward(nn.Module):
77
- "Implements FFN equation."
78
- def __init__(self, d_model, d_ff, dropout=0.1):
79
- super(PositionwiseFeedForward, self).__init__()
80
- self.w_1 = nn.Linear(d_model, d_ff)
81
- self.w_2 = nn.Linear(d_ff, d_model)
82
- self.dropout = nn.Dropout(dropout)
83
-
84
- def forward(self, x):
85
- return self.w_2(self.dropout(F.relu(self.w_1(x))))
86
-
87
- def make_bert(src_vocab, N=6, d_model=512, d_ff=2048, h=8, dropout=0.1):
88
- "构建模型"
89
- c = copy.deepcopy
90
- attn = MultiHeadedAttention(h, d_model)
91
- ff = PositionwiseFeedForward(d_model, d_ff, dropout)
92
- position = PositionalEncoding(d_model, dropout)
93
- model = Bert(
94
- Encoder(EncoderLayer(d_model, c(attn), c(ff), dropout), N),
95
-
96
- nn.Sequential(Embeddings(d_model, src_vocab), c(position)),
97
- )
98
-
99
- # 随机初始化参数,这非常重要用Glorot/fan_avg.
100
- for p in model.parameters():
101
- if p.dim() > 1:
102
- nn.init.xavier_uniform_(p)
103
- return model
104
-
105
- def make_bert_without_emb(d_model=128, N=2, d_ff=512, h=8, dropout=0.1):
106
- c = copy.deepcopy
107
- attn = MultiHeadedAttention(h, d_model)
108
- ff = PositionwiseFeedForward(d_model, d_ff, dropout)
109
- trainable_encoder = Encoder(EncoderLayer(d_model, c(attn), c(ff), dropout), N)
110
-
111
- return trainable_encoder
112
-
113
-
114
-
115
- def clones(module, N):
116
- "克隆N个完全相同的SubLayer,使用了copy.deepcopy"
117
- return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
118
-
119
- def subsequent_mask(size):
120
- "Mask out subsequent positions."
121
- attn_shape = (1, size, size)
122
- subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')
123
- return torch.from_numpy(subsequent_mask) == 0
124
-
125
- def attention(query, key, value, mask=None, dropout=None):
126
- "计算 'Scaled Dot Product Attention'"
127
- d_k = query.size(-1)
128
- scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
129
- if mask is not None:
130
- mask = mask.unsqueeze(-2)
131
- scores = scores.masked_fill(mask == 0, -1e9)
132
- p_attn = F.softmax(scores, dim = -1)
133
- if dropout is not None:
134
- p_attn = dropout(p_attn)
135
- return torch.matmul(p_attn, value), p_attn
136
-
137
- class MultiHeadedAttention(nn.Module):
138
- def __init__(self, h, d_model, dropout=0.1):
139
- "传入head个数及model的维度."
140
- super(MultiHeadedAttention, self).__init__()
141
- assert d_model % h == 0
142
- # 这里假设d_v=d_k
143
- self.d_k = d_model // h
144
- self.h = h
145
- self.linears = clones(nn.Linear(d_model, d_model), 4)
146
- self.attn = None
147
- self.dropout = nn.Dropout(p=dropout)
148
-
149
- def forward(self, query, key, value, mask=None):
150
- "Implements Figure 2"
151
- if mask is not None:
152
- # 相同的mask适应所有的head.
153
- mask = mask.unsqueeze(1)
154
- nbatches = query.size(0)
155
-
156
- # 1) 首先使用线性变换,然后把d_model分配给h个Head,每个head为d_k=d_model/h
157
- query, key, value = \
158
- [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)
159
- for l, x in zip(self.linears, (query, key, value))]
160
-
161
- # 2) 使用attention函数计算scaled-Dot-product-attention
162
- x, self.attn = attention(query, key, value, mask=mask,
163
- dropout=self.dropout)
164
-
165
- # 3) 实现Multi-head attention,用view函数把8个head的64维向量拼接成一个512的向量。
166
- #然后再使用一个线性变换(512,521),shape不变.
167
- x = x.transpose(1, 2).contiguous() \
168
- .view(nbatches, -1, self.h * self.d_k)
169
- return self.linears[-1](x)
170
-
171
- class Embeddings(nn.Module):
172
- def __init__(self, d_model, vocab):
173
- super(Embeddings, self).__init__()
174
- self.lut = nn.Embedding(vocab, d_model)
175
- self.d_model = d_model
176
-
177
- def forward(self, x):
178
- return self.lut(x) * math.sqrt(self.d_model)
179
-
180
- class PositionalEncoding(nn.Module):
181
- "实现PE函数"
182
- def __init__(self, d_model, dropout, max_len=5000):
183
- super(PositionalEncoding, self).__init__()
184
- self.dropout = nn.Dropout(p=dropout)
185
-
186
- # Compute the positional encodings once in log space.
187
- pe = torch.zeros(max_len, d_model)
188
- position = torch.arange(0, max_len).unsqueeze(1)
189
- div_term = torch.exp(torch.arange(0, d_model, 2) *
190
- -(math.log(10000.0) / d_model))
191
- pe[:, 0::2] = torch.sin(position * div_term)
192
- pe[:, 1::2] = torch.cos(position * div_term)
193
- pe = pe.unsqueeze(0)
194
- self.register_buffer('pe', pe)
195
-
196
- def forward(self, x):
197
- x = x + self.pe[:, :x.size(1)].clone().detach()
198
- return self.dropout(x)
199
-